code
stringlengths 1
199k
|
|---|
import logging
import traceback
from gi.repository import GObject
from gi.repository import Gtk
from gi.repository import Gdk
import libvirt
import virtManager.uihelpers as uihelpers
from virtManager.storagebrowse import vmmStorageBrowser
from virtManager.baseclass import vmmGObjectUI
from virtManager.addhardware import vmmAddHardware
from virtManager.choosecd import vmmChooseCD
from virtManager.console import vmmConsolePages
from virtManager.serialcon import vmmSerialConsole
from virtManager.graphwidgets import Sparkline
from virtManager import util as util
import virtinst
EDIT_TOTAL = 37
(EDIT_NAME,
EDIT_ACPI,
EDIT_APIC,
EDIT_CLOCK,
EDIT_MACHTYPE,
EDIT_SECURITY,
EDIT_DESC,
EDIT_VCPUS,
EDIT_CPUSET,
EDIT_CPU,
EDIT_TOPOLOGY,
EDIT_MEM,
EDIT_AUTOSTART,
EDIT_BOOTORDER,
EDIT_BOOTMENU,
EDIT_KERNEL,
EDIT_INIT,
EDIT_DISK_RO,
EDIT_DISK_SHARE,
EDIT_DISK_CACHE,
EDIT_DISK_IO,
EDIT_DISK_BUS,
EDIT_DISK_SERIAL,
EDIT_DISK_FORMAT,
EDIT_DISK_IOTUNE,
EDIT_SOUND_MODEL,
EDIT_SMARTCARD_MODE,
EDIT_NET_MODEL,
EDIT_NET_VPORT,
EDIT_NET_SOURCE,
EDIT_GFX_PASSWD,
EDIT_GFX_TYPE,
EDIT_GFX_KEYMAP,
EDIT_VIDEO_MODEL,
EDIT_WATCHDOG_MODEL,
EDIT_WATCHDOG_ACTION,
EDIT_CONTROLLER_MODEL
) = range(EDIT_TOTAL)
HW_LIST_COL_LABEL = 0
HW_LIST_COL_ICON_NAME = 1
HW_LIST_COL_ICON_SIZE = 2
HW_LIST_COL_TYPE = 3
HW_LIST_COL_DEVICE = 4
HW_LIST_TYPE_GENERAL = 0
HW_LIST_TYPE_STATS = 1
HW_LIST_TYPE_CPU = 2
HW_LIST_TYPE_MEMORY = 3
HW_LIST_TYPE_BOOT = 4
HW_LIST_TYPE_DISK = 5
HW_LIST_TYPE_NIC = 6
HW_LIST_TYPE_INPUT = 7
HW_LIST_TYPE_GRAPHICS = 8
HW_LIST_TYPE_SOUND = 9
HW_LIST_TYPE_CHAR = 10
HW_LIST_TYPE_HOSTDEV = 11
HW_LIST_TYPE_VIDEO = 12
HW_LIST_TYPE_WATCHDOG = 13
HW_LIST_TYPE_CONTROLLER = 14
HW_LIST_TYPE_FILESYSTEM = 15
HW_LIST_TYPE_SMARTCARD = 16
HW_LIST_TYPE_REDIRDEV = 17
remove_pages = [HW_LIST_TYPE_NIC, HW_LIST_TYPE_INPUT,
HW_LIST_TYPE_GRAPHICS, HW_LIST_TYPE_SOUND, HW_LIST_TYPE_CHAR,
HW_LIST_TYPE_HOSTDEV, HW_LIST_TYPE_DISK, HW_LIST_TYPE_VIDEO,
HW_LIST_TYPE_WATCHDOG, HW_LIST_TYPE_CONTROLLER,
HW_LIST_TYPE_FILESYSTEM, HW_LIST_TYPE_SMARTCARD,
HW_LIST_TYPE_REDIRDEV]
BOOT_DEV_TYPE = 0
BOOT_LABEL = 1
BOOT_ICON = 2
BOOT_ACTIVE = 3
PAGE_CONSOLE = 0
PAGE_DETAILS = 1
PAGE_DYNAMIC_OFFSET = 2
def prettyify_disk_bus(bus):
if bus in ["ide", "sata", "scsi", "usb"]:
return bus.upper()
if bus in ["xen"]:
return bus.capitalize()
if bus == "virtio":
return "VirtIO"
if bus == "spapr-vscsi":
return "vSCSI"
return bus
def prettyify_disk(devtype, bus, idx):
busstr = prettyify_disk_bus(bus) or ""
if devtype == "floppy":
devstr = "Floppy"
busstr = ""
elif devtype == "cdrom":
devstr = "CDROM"
else:
devstr = devtype.capitalize()
if busstr:
ret = "%s %s" % (busstr, devstr)
else:
ret = devstr
return "%s %s" % (ret, idx)
def safeint(val, fmt="%.3d"):
try:
int(val)
except:
return str(val)
return fmt % int(val)
def prettyify_bytes(val):
if val > (1024 * 1024 * 1024):
return "%2.2f GB" % (val / (1024.0 * 1024.0 * 1024.0))
else:
return "%2.2f MB" % (val / (1024.0 * 1024.0))
def build_redir_label(redirdev):
# String shown in the devices details section
addrlabel = ""
# String shown in the VMs hardware list
hwlabel = ""
if redirdev.type == 'spicevmc':
addrlabel = None
elif redirdev.type == 'tcp':
addrlabel += _("%s:%s") % (redirdev.host, redirdev.service)
else:
raise RuntimeError("unhandled redirection kind: %s" % redirdev.type)
hwlabel = _("Redirected %s") % redirdev.bus.upper()
return addrlabel, hwlabel
def build_hostdev_label(hostdev):
# String shown in the devices details section
srclabel = ""
# String shown in the VMs hardware list
hwlabel = ""
typ = hostdev.type
vendor = hostdev.vendor
product = hostdev.product
addrbus = hostdev.bus
addrdev = hostdev.device
addrslt = hostdev.slot
addrfun = hostdev.function
addrdom = hostdev.domain
def dehex(val):
if val.startswith("0x"):
val = val[2:]
return val
hwlabel = typ.upper()
srclabel = typ.upper()
if vendor and product:
# USB by vendor + product
devstr = " %s:%s" % (dehex(vendor), dehex(product))
srclabel += devstr
hwlabel += devstr
elif addrbus and addrdev:
# USB by bus + dev
srclabel += (" Bus %s Device %s" %
(safeint(addrbus), safeint(addrdev)))
hwlabel += " %s:%s" % (safeint(addrbus), safeint(addrdev))
elif addrbus and addrslt and addrfun and addrdom:
# PCI by bus:slot:function
devstr = (" %s:%s:%s.%s" %
(dehex(addrdom), dehex(addrbus),
dehex(addrslt), dehex(addrfun)))
srclabel += devstr
hwlabel += devstr
return srclabel, hwlabel
def lookup_nodedev(vmmconn, hostdev):
def intify(val, do_hex=False):
try:
if do_hex:
return int(val or '0x00', 16)
else:
return int(val)
except:
return -1
def attrVal(node, attr):
if not hasattr(node, attr):
return None
return getattr(node, attr)
devtype = hostdev.type
found_dev = None
vendor_id = product_id = bus = device = \
domain = slot = func = None
# For USB we want a device, not a bus
if devtype == 'usb':
devtype = 'usb_device'
vendor_id = hostdev.vendor or -1
product_id = hostdev.product or -1
bus = intify(hostdev.bus)
device = intify(hostdev.device)
elif devtype == 'pci':
domain = intify(hostdev.domain, True)
bus = intify(hostdev.bus, True)
slot = intify(hostdev.slot, True)
func = intify(hostdev.function, True)
devs = vmmconn.get_nodedevs(devtype, None)
for dev in devs:
# Try to match with product_id|vendor_id|bus|device
if (attrVal(dev, "product_id") == product_id and
attrVal(dev, "vendor_id") == vendor_id and
attrVal(dev, "bus") == bus and
attrVal(dev, "device") == device):
found_dev = dev
break
else:
# Try to get info from bus/addr
dev_id = intify(attrVal(dev, "device"))
bus_id = intify(attrVal(dev, "bus"))
dom_id = intify(attrVal(dev, "domain"))
func_id = intify(attrVal(dev, "function"))
slot_id = intify(attrVal(dev, "slot"))
if ((dev_id == device and bus_id == bus) or
(dom_id == domain and func_id == func and
bus_id == bus and slot_id == slot)):
found_dev = dev
break
return found_dev
class vmmDetails(vmmGObjectUI):
__gsignals__ = {
"action-save-domain": (GObject.SignalFlags.RUN_FIRST, None, [str, str]),
"action-destroy-domain": (GObject.SignalFlags.RUN_FIRST, None, [str, str]),
"action-suspend-domain": (GObject.SignalFlags.RUN_FIRST, None, [str, str]),
"action-resume-domain": (GObject.SignalFlags.RUN_FIRST, None, [str, str]),
"action-run-domain": (GObject.SignalFlags.RUN_FIRST, None, [str, str]),
"action-shutdown-domain": (GObject.SignalFlags.RUN_FIRST, None, [str, str]),
"action-reset-domain": (GObject.SignalFlags.RUN_FIRST, None, [str, str]),
"action-reboot-domain": (GObject.SignalFlags.RUN_FIRST, None, [str, str]),
"action-exit-app": (GObject.SignalFlags.RUN_FIRST, None, []),
"action-view-manager": (GObject.SignalFlags.RUN_FIRST, None, []),
"action-migrate-domain": (GObject.SignalFlags.RUN_FIRST, None, [str, str]),
"action-clone-domain": (GObject.SignalFlags.RUN_FIRST, None, [str, str]),
"details-closed": (GObject.SignalFlags.RUN_FIRST, None, []),
"details-opened": (GObject.SignalFlags.RUN_FIRST, None, []),
"customize-finished": (GObject.SignalFlags.RUN_FIRST, None, []),
}
def __init__(self, vm, parent=None):
vmmGObjectUI.__init__(self, "vmm-details.ui", "vmm-details")
self.vm = vm
self.conn = self.vm.conn
self.is_customize_dialog = False
if parent:
# Details window is being abused as a 'configure before install'
# dialog, set things as appropriate
self.is_customize_dialog = True
self.topwin.set_type_hint(Gdk.WindowTypeHint.DIALOG)
self.topwin.set_transient_for(parent)
self.widget("toolbar-box").show()
self.widget("customize-toolbar").show()
self.widget("details-toolbar").hide()
self.widget("details-menubar").hide()
pages = self.widget("details-pages")
pages.set_current_page(PAGE_DETAILS)
self.active_edits = []
self.serial_tabs = []
self.last_console_page = PAGE_CONSOLE
self.addhw = None
self.media_choosers = {"cdrom": None, "floppy": None}
self.storage_browser = None
self.ignorePause = False
self.ignoreDetails = False
self._cpu_copy_host = False
self.console = vmmConsolePages(self.vm, self.builder, self.topwin)
# Set default window size
w, h = self.vm.get_details_window_size()
self.topwin.set_default_size(w or 800, h or 600)
self.oldhwkey = None
self.addhwmenu = None
self.keycombo_menu = None
self.init_menus()
self.init_details()
self.cpu_usage_graph = None
self.memory_usage_graph = None
self.disk_io_graph = None
self.network_traffic_graph = None
self.init_graphs()
self.builder.connect_signals({
"on_close_details_clicked": self.close,
"on_details_menu_close_activate": self.close,
"on_vmm_details_delete_event": self.close,
"on_vmm_details_configure_event": self.window_resized,
"on_details_menu_quit_activate": self.exit_app,
"on_control_vm_details_toggled": self.details_console_changed,
"on_control_vm_console_toggled": self.details_console_changed,
"on_control_run_clicked": self.control_vm_run,
"on_control_shutdown_clicked": self.control_vm_shutdown,
"on_control_pause_toggled": self.control_vm_pause,
"on_control_fullscreen_toggled": self.control_fullscreen,
"on_details_customize_finish_clicked": self.customize_finish,
"on_details_cancel_customize_clicked": self.close,
"on_details_menu_run_activate": self.control_vm_run,
"on_details_menu_poweroff_activate": self.control_vm_shutdown,
"on_details_menu_reboot_activate": self.control_vm_reboot,
"on_details_menu_save_activate": self.control_vm_save,
"on_details_menu_reset_activate": self.control_vm_reset,
"on_details_menu_destroy_activate": self.control_vm_destroy,
"on_details_menu_pause_activate": self.control_vm_pause,
"on_details_menu_clone_activate": self.control_vm_clone,
"on_details_menu_migrate_activate": self.control_vm_migrate,
"on_details_menu_screenshot_activate": self.control_vm_screenshot,
"on_details_menu_view_toolbar_activate": self.toggle_toolbar,
"on_details_menu_view_manager_activate": self.view_manager,
"on_details_menu_view_details_toggled": self.details_console_changed,
"on_details_menu_view_console_toggled": self.details_console_changed,
"on_details_pages_switch_page": self.switch_page,
"on_overview_name_changed": lambda *x: self.enable_apply(x, EDIT_NAME),
"on_overview_acpi_changed": self.config_acpi_changed,
"on_overview_apic_changed": self.config_apic_changed,
"on_overview_clock_changed": lambda *x: self.enable_apply(x, EDIT_CLOCK),
"on_machine_type_changed": lambda *x: self.enable_apply(x, EDIT_MACHTYPE),
"on_security_label_changed": lambda *x: self.enable_apply(x, EDIT_SECURITY),
"on_security_relabel_changed": lambda *x: self.enable_apply(x, EDIT_SECURITY),
"on_security_type_changed": self.security_type_changed,
"on_config_vcpus_changed": self.config_vcpus_changed,
"on_config_maxvcpus_changed": self.config_maxvcpus_changed,
"on_config_vcpupin_changed": lambda *x: self.enable_apply(x, EDIT_CPUSET),
"on_config_vcpupin_generate_clicked": self.config_vcpupin_generate,
"on_cpu_model_changed": lambda *x: self.enable_apply(x, EDIT_CPU),
"on_cpu_cores_changed": lambda *x: self.enable_apply(x, EDIT_TOPOLOGY),
"on_cpu_sockets_changed": lambda *x: self.enable_apply(x, EDIT_TOPOLOGY),
"on_cpu_threads_changed": lambda *x: self.enable_apply(x, EDIT_TOPOLOGY),
"on_cpu_copy_host_clicked": self.config_cpu_copy_host,
"on_cpu_topology_enable_toggled": self.config_cpu_topology_enable,
"on_config_memory_changed": self.config_memory_changed,
"on_config_maxmem_changed": self.config_maxmem_changed,
"on_config_boot_moveup_clicked" : lambda *x: self.config_boot_move(x, True),
"on_config_boot_movedown_clicked" : lambda *x: self.config_boot_move(x, False),
"on_config_autostart_changed": lambda *x: self.enable_apply(x, x, EDIT_AUTOSTART),
"on_boot_menu_changed": lambda *x: self.enable_apply(x, EDIT_BOOTMENU),
"on_boot_kernel_changed": lambda *x: self.enable_apply(x, EDIT_KERNEL),
"on_boot_kernel_initrd_changed": lambda *x: self.enable_apply(x, EDIT_KERNEL),
"on_boot_kernel_args_changed": lambda *x: self.enable_apply(x, EDIT_KERNEL),
"on_boot_kernel_browse_clicked": self.browse_kernel,
"on_boot_kernel_initrd_browse_clicked": self.browse_initrd,
"on_boot_init_path_changed": lambda *x: self.enable_apply(x, EDIT_INIT),
"on_disk_readonly_changed": lambda *x: self.enable_apply(x, EDIT_DISK_RO),
"on_disk_shareable_changed": lambda *x: self.enable_apply(x, EDIT_DISK_SHARE),
"on_disk_cache_combo_changed": lambda *x: self.enable_apply(x, EDIT_DISK_CACHE),
"on_disk_io_combo_changed": lambda *x: self.enable_apply(x, EDIT_DISK_IO),
"on_disk_bus_combo_changed": lambda *x: self.enable_apply(x, EDIT_DISK_BUS),
"on_disk_format_changed": lambda *x: self.enable_apply(x, EDIT_DISK_FORMAT),
"on_disk_serial_changed": lambda *x: self.enable_apply(x, EDIT_DISK_SERIAL),
"on_disk_iotune_changed": self.iotune_changed,
"on_network_source_combo_changed": lambda *x: self.enable_apply(x, EDIT_NET_SOURCE),
"on_network_bridge_changed": lambda *x: self.enable_apply(x, EDIT_NET_SOURCE),
"on_network-source-mode-combo_changed": lambda *x: self.enable_apply(x, EDIT_NET_SOURCE),
"on_network_model_combo_changed": lambda *x: self.enable_apply(x, EDIT_NET_MODEL),
"on_vport_type_changed": lambda *x: self.enable_apply(x, EDIT_NET_VPORT),
"on_vport_managerid_changed": lambda *x: self.enable_apply(x,
EDIT_NET_VPORT),
"on_vport_typeid_changed": lambda *x: self.enable_apply(x,
EDIT_NET_VPORT),
"on_vport_typeidversion_changed": lambda *x: self.enable_apply(x,
EDIT_NET_VPORT),
"on_vport_instanceid_changed": lambda *x: self.enable_apply(x,
EDIT_NET_VPORT),
"on_gfx_type_combo_changed": lambda *x: self.enable_apply(x, EDIT_GFX_TYPE),
"on_vnc_keymap_combo_changed": lambda *x: self.enable_apply(x,
EDIT_GFX_KEYMAP),
"on_vnc_password_changed": lambda *x: self.enable_apply(x, EDIT_GFX_PASSWD),
"on_sound_model_combo_changed": lambda *x: self.enable_apply(x,
EDIT_SOUND_MODEL),
"on_video_model_combo_changed": lambda *x: self.enable_apply(x,
EDIT_VIDEO_MODEL),
"on_watchdog_model_combo_changed": lambda *x: self.enable_apply(x,
EDIT_WATCHDOG_MODEL),
"on_watchdog_action_combo_changed": lambda *x: self.enable_apply(x,
EDIT_WATCHDOG_ACTION),
"on_smartcard_mode_combo_changed": lambda *x: self.enable_apply(x,
EDIT_SMARTCARD_MODE),
"on_config_apply_clicked": self.config_apply,
"on_config_cancel_clicked": self.config_cancel,
"on_config_cdrom_connect_clicked": self.toggle_storage_media,
"on_config_remove_clicked": self.remove_xml_dev,
"on_add_hardware_button_clicked": self.add_hardware,
"on_hw_list_button_press_event": self.popup_addhw_menu,
# Listeners stored in vmmConsolePages
"on_details_menu_view_fullscreen_activate": self.console.toggle_fullscreen,
"on_details_menu_view_size_to_vm_activate": self.console.size_to_vm,
"on_details_menu_view_scale_always_toggled": self.console.set_scale_type,
"on_details_menu_view_scale_fullscreen_toggled": self.console.set_scale_type,
"on_details_menu_view_scale_never_toggled": self.console.set_scale_type,
"on_console_pages_switch_page": self.console.page_changed,
"on_console_auth_password_activate": self.console.auth_login,
"on_console_auth_login_clicked": self.console.auth_login,
"on_controller_model_combo_changed": lambda *x: self.enable_apply(x,
EDIT_CONTROLLER_MODEL),
})
# Deliberately keep all this after signal connection
self.vm.connect("status-changed", self.refresh_vm_state)
self.vm.connect("config-changed", self.refresh_vm_state)
self.vm.connect("resources-sampled", self.refresh_resources)
self.widget("hw-list").get_selection().connect("changed",
self.hw_changed)
self.widget("config-boot-list").get_selection().connect(
"changed",
self.config_bootdev_selected)
finish_img = Gtk.Image.new_from_stock(Gtk.STOCK_ADD,
Gtk.IconSize.BUTTON)
self.widget("add-hardware-button").set_image(finish_img)
self.populate_hw_list()
self.repopulate_boot_list()
self.hw_selected()
self.refresh_vm_state()
def _cleanup(self):
self.oldhwkey = None
if self.addhw:
self.addhw.cleanup()
self.addhw = None
if self.storage_browser:
self.storage_browser.cleanup()
self.storage_browser = None
for key in self.media_choosers:
if self.media_choosers[key]:
self.media_choosers[key].cleanup()
self.media_choosers = {}
for serial in self.serial_tabs:
self._close_serial_tab(serial)
self.console.cleanup()
self.console = None
self.vm = None
self.conn = None
self.addhwmenu = None
def show(self):
logging.debug("Showing VM details: %s", self.vm)
vis = self.is_visible()
self.topwin.present()
if vis:
return
self.emit("details-opened")
self.refresh_vm_state()
def customize_finish(self, src):
ignore = src
if self.has_unapplied_changes(self.get_hw_row()):
return
return self._close(customize_finish=True)
def close(self, ignore1=None, ignore2=None):
logging.debug("Closing VM details: %s", self.vm)
return self._close()
def _close(self, customize_finish=False):
fs = self.widget("details-menu-view-fullscreen")
if fs.get_active():
fs.set_active(False)
if not self.is_visible():
return
self.topwin.hide()
if (self.console.viewer and
self.console.viewer.display and
self.console.viewer.display.get_visible()):
try:
self.console.close_viewer()
except:
logging.error("Failure when disconnecting from desktop server")
if customize_finish:
self.emit("customize-finished")
else:
self.emit("details-closed")
return 1
def is_visible(self):
return bool(self.topwin.get_visible())
##########################
# Initialization helpers #
##########################
def init_menus(self):
# Shutdown button menu
uihelpers.build_shutdown_button_menu(self.widget("control-shutdown"),
self.control_vm_shutdown,
self.control_vm_reboot,
self.control_vm_reset,
self.control_vm_destroy,
self.control_vm_save)
for name in ["details-menu-shutdown",
"details-menu-reboot",
"details-menu-reset",
"details-menu-poweroff",
"details-menu-destroy"]:
image = Gtk.Image.new_from_icon_name("system-shutdown",
Gtk.IconSize.MENU)
self.widget(name).set_image(image)
# Add HW popup menu
self.addhwmenu = Gtk.Menu()
addHW = Gtk.ImageMenuItem(_("_Add Hardware"))
addHW.set_use_underline(True)
addHWImg = Gtk.Image()
addHWImg.set_from_stock(Gtk.STOCK_ADD, Gtk.IconSize.MENU)
addHW.set_image(addHWImg)
addHW.show()
addHW.connect("activate", self.add_hardware)
rmHW = Gtk.ImageMenuItem(_("_Remove Hardware"))
rmHW.set_use_underline(True)
rmHWImg = Gtk.Image()
rmHWImg.set_from_stock(Gtk.STOCK_REMOVE, Gtk.IconSize.MENU)
rmHW.set_image(rmHWImg)
rmHW.show()
rmHW.connect("activate", self.remove_xml_dev)
self.addhwmenu.add(addHW)
self.addhwmenu.add(rmHW)
# Serial list menu
smenu = Gtk.Menu()
smenu.connect("show", self.populate_serial_menu)
self.widget("details-menu-view-serial-list").set_submenu(smenu)
# Don't allowing changing network/disks for Dom0
dom0 = self.vm.is_management_domain()
self.widget("add-hardware-button").set_sensitive(not dom0)
self.widget("hw-panel").set_show_tabs(False)
self.widget("details-pages").set_show_tabs(False)
self.widget("console-pages").set_show_tabs(False)
self.widget("details-menu-view-toolbar").set_active(
self.config.get_details_show_toolbar())
# Keycombo menu (ctrl+alt+del etc.)
self.keycombo_menu = uihelpers.build_keycombo_menu(
self.console.send_key)
self.widget("details-menu-send-key").set_submenu(self.keycombo_menu)
def init_graphs(self):
graph_table = self.widget("graph-table")
self.cpu_usage_graph = Sparkline()
self.cpu_usage_graph.set_property("reversed", True)
graph_table.attach(self.cpu_usage_graph, 1, 2, 0, 1)
self.memory_usage_graph = Sparkline()
self.memory_usage_graph.set_property("reversed", True)
graph_table.attach(self.memory_usage_graph, 1, 2, 1, 2)
self.disk_io_graph = Sparkline()
self.disk_io_graph.set_property("reversed", True)
self.disk_io_graph.set_property("filled", False)
self.disk_io_graph.set_property("num_sets", 2)
self.disk_io_graph.set_property("rgb", [x / 255.0 for x in
[0x82, 0x00, 0x3B, 0x29, 0x5C, 0x45]])
graph_table.attach(self.disk_io_graph, 1, 2, 2, 3)
self.network_traffic_graph = Sparkline()
self.network_traffic_graph.set_property("reversed", True)
self.network_traffic_graph.set_property("filled", False)
self.network_traffic_graph.set_property("num_sets", 2)
self.network_traffic_graph.set_property("rgb", [x / 255.0 for x in
[0x82, 0x00, 0x3B,
0x29, 0x5C, 0x45]])
graph_table.attach(self.network_traffic_graph, 1, 2, 3, 4)
graph_table.show_all()
def init_details(self):
# Hardware list
# [ label, icon name, icon size, hw type, hw data/class]
hw_list_model = Gtk.ListStore(str, str, int, int, object)
self.widget("hw-list").set_model(hw_list_model)
hwCol = Gtk.TreeViewColumn("Hardware")
hwCol.set_spacing(6)
hwCol.set_min_width(165)
hw_txt = Gtk.CellRendererText()
hw_img = Gtk.CellRendererPixbuf()
hwCol.pack_start(hw_img, False)
hwCol.pack_start(hw_txt, True)
hwCol.add_attribute(hw_txt, 'text', HW_LIST_COL_LABEL)
hwCol.add_attribute(hw_img, 'stock-size', HW_LIST_COL_ICON_SIZE)
hwCol.add_attribute(hw_img, 'icon-name', HW_LIST_COL_ICON_NAME)
self.widget("hw-list").append_column(hwCol)
# Description text view
desc = self.widget("overview-description")
buf = Gtk.TextBuffer()
buf.connect("changed", self.enable_apply, EDIT_DESC)
desc.set_buffer(buf)
# List of applications.
apps_list = self.widget("inspection-apps")
apps_model = Gtk.ListStore(str, str, str)
apps_list.set_model(apps_model)
name_col = Gtk.TreeViewColumn(_("Name"))
version_col = Gtk.TreeViewColumn(_("Version"))
summary_col = Gtk.TreeViewColumn()
apps_list.append_column(name_col)
apps_list.append_column(version_col)
apps_list.append_column(summary_col)
name_text = Gtk.CellRendererText()
name_col.pack_start(name_text, True)
name_col.add_attribute(name_text, 'text', 0)
name_col.set_sort_column_id(0)
version_text = Gtk.CellRendererText()
version_col.pack_start(version_text, True)
version_col.add_attribute(version_text, 'text', 1)
version_col.set_sort_column_id(1)
summary_text = Gtk.CellRendererText()
summary_col.pack_start(summary_text, True)
summary_col.add_attribute(summary_text, 'text', 2)
summary_col.set_sort_column_id(2)
# Clock combo
clock_combo = self.widget("overview-clock-combo")
clock_model = Gtk.ListStore(str)
clock_combo.set_model(clock_model)
text = Gtk.CellRendererText()
clock_combo.pack_start(text, True)
clock_combo.add_attribute(text, 'text', 0)
clock_model.set_sort_column_id(0, Gtk.SortType.ASCENDING)
for offset in ["localtime", "utc"]:
clock_model.append([offset])
arch = self.vm.get_arch()
caps = self.vm.conn.get_capabilities()
machines = []
if len(caps.guests) > 0:
for guest in caps.guests:
if len(guest.domains) > 0:
for domain in guest.domains:
machines = list(set(machines + domain.machines))
if arch in ["i686", "x86_64"]:
self.widget("label81").hide()
self.widget("hbox30").hide()
else:
machtype_combo = self.widget("machine-type-combo")
machtype_model = Gtk.ListStore(str)
machtype_combo.set_model(machtype_model)
text = Gtk.CellRendererText()
machtype_combo.pack_start(text, True)
machtype_combo.add_attribute(text, 'text', 0)
machtype_model.set_sort_column_id(0, Gtk.SortType.ASCENDING)
if len(machines) > 0:
for machine in machines:
machtype_model.append([machine])
# Security info tooltips
self.widget("security-static-info").set_tooltip_text(
_("Static SELinux security type tells libvirt to always start the guest process with the specified label. Unless 'relabel' is set, the administrator is responsible for making sure the images are labeled correctly on disk."))
self.widget("security-dynamic-info").set_tooltip_text(
_("The dynamic SELinux security type tells libvirt to automatically pick a unique label for the guest process and guest image, ensuring total isolation of the guest. (Default)"))
# VCPU Pinning list
generate_cpuset = self.widget("config-vcpupin-generate")
generate_warn = self.widget("config-vcpupin-generate-err")
if not self.conn.get_capabilities().host.topology:
generate_cpuset.set_sensitive(False)
generate_warn.show()
generate_warn.set_tooltip_text(_("Libvirt did not detect NUMA capabilities."))
# [ VCPU #, Currently running on Phys CPU #, CPU Pinning list ]
vcpu_list = self.widget("config-vcpu-list")
vcpu_model = Gtk.ListStore(str, str, str)
vcpu_list.set_model(vcpu_model)
vcpuCol = Gtk.TreeViewColumn(_("VCPU"))
physCol = Gtk.TreeViewColumn(_("On CPU"))
pinCol = Gtk.TreeViewColumn(_("Pinning"))
vcpu_list.append_column(vcpuCol)
vcpu_list.append_column(physCol)
vcpu_list.append_column(pinCol)
vcpu_text = Gtk.CellRendererText()
vcpuCol.pack_start(vcpu_text, True)
vcpuCol.add_attribute(vcpu_text, 'text', 0)
vcpuCol.set_sort_column_id(0)
phys_text = Gtk.CellRendererText()
physCol.pack_start(phys_text, True)
physCol.add_attribute(phys_text, 'text', 1)
physCol.set_sort_column_id(1)
pin_text = Gtk.CellRendererText()
pin_text.set_property("editable", True)
pin_text.connect("edited", self.config_vcpu_pin)
pinCol.pack_start(pin_text, True)
pinCol.add_attribute(pin_text, 'text', 2)
# Boot device list
boot_list = self.widget("config-boot-list")
# model = [ XML boot type, display name, icon name, enabled ]
boot_list_model = Gtk.ListStore(str, str, str, bool)
boot_list.set_model(boot_list_model)
chkCol = Gtk.TreeViewColumn()
txtCol = Gtk.TreeViewColumn()
boot_list.append_column(chkCol)
boot_list.append_column(txtCol)
chk = Gtk.CellRendererToggle()
chk.connect("toggled", self.config_boot_toggled)
chkCol.pack_start(chk, False)
chkCol.add_attribute(chk, 'active', BOOT_ACTIVE)
icon = Gtk.CellRendererPixbuf()
txtCol.pack_start(icon, False)
txtCol.add_attribute(icon, 'icon-name', BOOT_ICON)
text = Gtk.CellRendererText()
txtCol.pack_start(text, True)
txtCol.add_attribute(text, 'text', BOOT_LABEL)
txtCol.add_attribute(text, 'sensitive', BOOT_ACTIVE)
no_default = not self.is_customize_dialog
# CPU features
caps = self.vm.conn.get_capabilities()
cpu_values = None
cpu_names = []
all_features = []
try:
cpu_values = caps.get_cpu_values(self.vm.get_arch())
cpu_names = sorted([c.model for c in cpu_values.cpus],
key=str.lower)
all_features = cpu_values.features
except:
logging.exception("Error populating CPU model list")
# [ feature name, mode]
feat_list = self.widget("cpu-features")
feat_model = Gtk.ListStore(str, str)
feat_list.set_model(feat_model)
nameCol = Gtk.TreeViewColumn()
polCol = Gtk.TreeViewColumn()
polCol.set_min_width(80)
feat_list.append_column(nameCol)
feat_list.append_column(polCol)
# Feature name col
name_text = Gtk.CellRendererText()
nameCol.pack_start(name_text, True)
nameCol.add_attribute(name_text, 'text', 0)
nameCol.set_sort_column_id(0)
# Feature policy col
feat_combo = Gtk.CellRendererCombo()
m = Gtk.ListStore(str)
for p in virtinst.CPUFeature.POLICIES:
m.append([p])
m.append(["default"])
feat_combo.set_property("model", m)
feat_combo.set_property("text-column", 0)
feat_combo.set_property("editable", True)
polCol.pack_start(feat_combo, False)
polCol.add_attribute(feat_combo, 'text', 1)
polCol.set_sort_column_id(1)
def feature_changed(src, index, treeiter, model):
model[index][1] = src.get_property("model")[treeiter][0]
self.enable_apply(EDIT_CPU)
feat_combo.connect("changed", feature_changed, feat_model)
for name in all_features:
feat_model.append([name, "default"])
# CPU model combo
cpu_model = self.widget("cpu-model")
model = Gtk.ListStore(str, object)
cpu_model.set_model(model)
cpu_model.set_entry_text_column(0)
model.set_sort_column_id(0, Gtk.SortType.ASCENDING)
for name in cpu_names:
model.append([name, cpu_values.get_cpu(name)])
# Disk cache combo
disk_cache = self.widget("disk-cache-combo")
uihelpers.build_cache_combo(self.vm, disk_cache)
# Disk io combo
disk_io = self.widget("disk-io-combo")
uihelpers.build_io_combo(self.vm, disk_io)
# Disk format combo
format_list = self.widget("disk-format")
uihelpers.build_storage_format_combo(self.vm, format_list)
# Disk bus combo
disk_bus = self.widget("disk-bus-combo")
uihelpers.build_disk_bus_combo(self.vm, disk_bus)
# Disk iotune expander
if not (self.conn.is_qemu() or self.conn.is_test_conn()):
self.widget("iotune-expander").set_property("visible", False)
# Network source
net_source = self.widget("network-source-combo")
net_bridge = self.widget("network-bridge-box")
source_mode_box = self.widget("network-source-mode-box")
source_mode_label = self.widget("network-source-mode")
vport_expander = self.widget("vport-expander")
uihelpers.init_network_list(net_source, net_bridge, source_mode_box,
source_mode_label, vport_expander)
# source mode
source_mode = self.widget("network-source-mode-combo")
uihelpers.build_source_mode_combo(self.vm, source_mode)
# Network model
net_model = self.widget("network-model-combo")
uihelpers.build_netmodel_combo(self.vm, net_model)
# Graphics type
gfx_type = self.widget("gfx-type-combo")
model = Gtk.ListStore(str, str)
gfx_type.set_model(model)
text = Gtk.CellRendererText()
gfx_type.pack_start(text, True)
gfx_type.add_attribute(text, 'text', 1)
model.append([virtinst.VirtualGraphics.TYPE_VNC,
"VNC"])
model.append([virtinst.VirtualGraphics.TYPE_SPICE,
"Spice"])
gfx_type.set_active(-1)
# Graphics keymap
gfx_keymap = self.widget("gfx-keymap-combo")
uihelpers.build_vnc_keymap_combo(self.vm, gfx_keymap,
no_default=no_default)
# Sound model
sound_dev = self.widget("sound-model-combo")
uihelpers.build_sound_combo(self.vm, sound_dev, no_default=no_default)
# Video model combo
video_dev = self.widget("video-model-combo")
uihelpers.build_video_combo(self.vm, video_dev, no_default=no_default)
# Watchdog model combo
combo = self.widget("watchdog-model-combo")
uihelpers.build_watchdogmodel_combo(self.vm, combo,
no_default=no_default)
# Watchdog action combo
combo = self.widget("watchdog-action-combo")
uihelpers.build_watchdogaction_combo(self.vm, combo,
no_default=no_default)
# Smartcard mode
sc_mode = self.widget("smartcard-mode-combo")
uihelpers.build_smartcard_mode_combo(self.vm, sc_mode)
# Redirection type
combo = self.widget("redir-type-combo")
uihelpers.build_redir_type_combo(self.vm, combo)
# Controller model
combo = self.widget("controller-model-combo")
model = Gtk.ListStore(str, str)
combo.set_model(model)
text = Gtk.CellRendererText()
combo.pack_start(text, True)
combo.add_attribute(text, 'text', 1)
combo.set_active(-1)
# Helper function to handle the combo/label pattern used for
# video model, sound model, network model, etc.
def set_combo_label(self, prefix, value, model_idx=0, label="",
comparefunc=None):
label = label or value
model_label = self.widget(prefix + "-label")
model_combo = self.widget(prefix + "-combo")
idx = -1
if comparefunc:
model_in_list, idx = comparefunc(model_combo.get_model(), value)
else:
model_list = [x[model_idx] for x in model_combo.get_model()]
model_in_list = (value in model_list)
if model_in_list:
idx = model_list.index(value)
model_label.set_property("visible", not model_in_list)
model_combo.set_property("visible", model_in_list)
model_label.set_text(label or "")
if model_in_list:
model_combo.set_active(idx)
else:
model_combo.set_active(-1)
# Helper for accessing value of combo/label pattern
def get_combo_value(self, widgetname, model_idx=0):
combo = self.widget(widgetname)
if combo.get_active() < 0:
return None
return combo.get_model()[combo.get_active()][model_idx]
def get_combo_label_value(self, prefix, model_idx=0):
comboname = prefix + "-combo"
label = self.widget(prefix + "-label")
value = None
if label.get_property("visible"):
value = label.get_text()
else:
value = self.get_combo_value(comboname, model_idx)
return value
##########################
# Window state listeners #
##########################
def window_resized(self, ignore, event):
# Sometimes dimensions change when window isn't visible
if not self.is_visible():
return
self.vm.set_details_window_size(event.width, event.height)
def popup_addhw_menu(self, widget, event):
ignore = widget
if event.button != 3:
return
self.addhwmenu.popup(None, None, None, None, 0, event.time)
def build_serial_list(self):
ret = []
def add_row(text, err, sensitive, do_radio, cb, serialidx):
ret.append([text, err, sensitive, do_radio, cb, serialidx])
devs = self.vm.get_serial_devs()
if len(devs) == 0:
add_row(_("No text console available"),
None, False, False, None, None)
def build_desc(dev):
if dev.virtual_device_type == "console":
return "Text Console %d" % (dev.vmmindex + 1)
return "Serial %d" % (dev.vmmindex + 1)
for dev in devs:
desc = build_desc(dev)
idx = dev.vmmindex
err = vmmSerialConsole.can_connect(self.vm, dev)
sensitive = not bool(err)
def cb(src):
return self.control_serial_tab(src, desc, idx)
add_row(desc, err, sensitive, True, cb, idx)
return ret
def current_serial_dev(self):
showing_serial = (self.last_console_page >= PAGE_DYNAMIC_OFFSET)
if not showing_serial:
return
serial_idx = self.last_console_page - PAGE_DYNAMIC_OFFSET
if len(self.serial_tabs) < serial_idx:
return
return self.serial_tabs[serial_idx]
def populate_serial_menu(self, src):
for ent in src:
src.remove(ent)
serial_page_dev = self.current_serial_dev()
showing_graphics = (self.last_console_page == PAGE_CONSOLE)
# Populate serial devices
group = None
itemlist = self.build_serial_list()
for msg, err, sensitive, do_radio, cb, ignore in itemlist:
if do_radio:
item = Gtk.RadioMenuItem(group)
item.set_label(msg)
if group is None:
group = item
else:
item = Gtk.MenuItem(msg)
item.set_sensitive(sensitive)
if err and not sensitive:
item.set_tooltip_text(err)
if cb:
item.connect("toggled", cb)
# Tab is already open, make sure marked as such
if (sensitive and
serial_page_dev and
serial_page_dev.name == msg):
item.set_active(True)
src.add(item)
src.add(Gtk.SeparatorMenuItem())
# Populate graphical devices
devs = self.vm.get_graphics_devices()
if len(devs) == 0:
item = Gtk.MenuItem(_("No graphical console available"))
item.set_sensitive(False)
src.add(item)
else:
dev = devs[0]
item = Gtk.RadioMenuItem(group)
item.set_label(_("Graphical Console %s") %
dev.pretty_type_simple(dev.type))
if group is None:
group = item
if showing_graphics:
item.set_active(True)
item.connect("toggled", self.control_serial_tab,
dev.virtual_device_type, dev.type)
src.add(item)
src.show_all()
def control_fullscreen(self, src):
menu = self.widget("details-menu-view-fullscreen")
if src.get_active() != menu.get_active():
menu.set_active(src.get_active())
def toggle_toolbar(self, src):
if self.is_customize_dialog:
return
active = src.get_active()
self.config.set_details_show_toolbar(active)
if (active and not
self.widget("details-menu-view-fullscreen").get_active()):
self.widget("toolbar-box").show()
else:
self.widget("toolbar-box").hide()
def get_selected_row(self, widget):
selection = widget.get_selection()
model, treepath = selection.get_selected()
if treepath is None:
return None
return model[treepath]
def get_boot_selection(self):
return self.get_selected_row(self.widget("config-boot-list"))
def set_hw_selection(self, page, disable_apply=True):
if disable_apply:
self.disable_apply()
hwlist = self.widget("hw-list")
selection = hwlist.get_selection()
selection.select_path(str(page))
def get_hw_row(self):
return self.get_selected_row(self.widget("hw-list"))
def get_hw_selection(self, field):
row = self.get_hw_row()
if not row:
return None
return row[field]
def force_get_hw_pagetype(self, page=None):
if page:
return page
page = self.get_hw_selection(HW_LIST_COL_TYPE)
if page is None:
page = HW_LIST_TYPE_GENERAL
self.set_hw_selection(0)
return page
def has_unapplied_changes(self, row):
if not row:
return False
if not self.widget("config-apply").get_sensitive():
return False
if not util.chkbox_helper(self,
self.config.get_confirm_unapplied,
self.config.set_confirm_unapplied,
text1=(_("There are unapplied changes. Would you like to apply "
"them now?")),
chktext=_("Don't warn me again."),
alwaysrecord=True,
default=False):
return False
return not self.config_apply(row=row)
def hw_changed(self, ignore):
newrow = self.get_hw_row()
model = self.widget("hw-list").get_model()
if newrow[HW_LIST_COL_DEVICE] == self.oldhwkey:
return
oldhwrow = None
for row in model:
if row[HW_LIST_COL_DEVICE] == self.oldhwkey:
oldhwrow = row
break
if self.has_unapplied_changes(oldhwrow):
# Unapplied changes, and syncing them failed
pageidx = 0
for idx in range(len(model)):
if model[idx][HW_LIST_COL_DEVICE] == self.oldhwkey:
pageidx = idx
break
self.set_hw_selection(pageidx, disable_apply=False)
else:
self.oldhwkey = newrow[HW_LIST_COL_DEVICE]
self.hw_selected()
def hw_selected(self, page=None):
pagetype = self.force_get_hw_pagetype(page)
self.widget("config-remove").set_sensitive(True)
self.widget("hw-panel").set_sensitive(True)
self.widget("hw-panel").show()
try:
if pagetype == HW_LIST_TYPE_GENERAL:
self.refresh_overview_page()
elif pagetype == HW_LIST_TYPE_STATS:
self.refresh_stats_page()
elif pagetype == HW_LIST_TYPE_CPU:
self.refresh_config_cpu()
elif pagetype == HW_LIST_TYPE_MEMORY:
self.refresh_config_memory()
elif pagetype == HW_LIST_TYPE_BOOT:
self.refresh_boot_page()
elif pagetype == HW_LIST_TYPE_DISK:
self.refresh_disk_page()
elif pagetype == HW_LIST_TYPE_NIC:
self.refresh_network_page()
elif pagetype == HW_LIST_TYPE_INPUT:
self.refresh_input_page()
elif pagetype == HW_LIST_TYPE_GRAPHICS:
self.refresh_graphics_page()
elif pagetype == HW_LIST_TYPE_SOUND:
self.refresh_sound_page()
elif pagetype == HW_LIST_TYPE_CHAR:
self.refresh_char_page()
elif pagetype == HW_LIST_TYPE_HOSTDEV:
self.refresh_hostdev_page()
elif pagetype == HW_LIST_TYPE_VIDEO:
self.refresh_video_page()
elif pagetype == HW_LIST_TYPE_WATCHDOG:
self.refresh_watchdog_page()
elif pagetype == HW_LIST_TYPE_CONTROLLER:
self.refresh_controller_page()
elif pagetype == HW_LIST_TYPE_FILESYSTEM:
self.refresh_filesystem_page()
elif pagetype == HW_LIST_TYPE_SMARTCARD:
self.refresh_smartcard_page()
elif pagetype == HW_LIST_TYPE_REDIRDEV:
self.refresh_redir_page()
else:
pagetype = -1
except Exception, e:
self.err.show_err(_("Error refreshing hardware page: %s") % str(e))
return
rem = pagetype in remove_pages
self.disable_apply()
self.widget("config-remove").set_property("visible", rem)
self.widget("hw-panel").set_current_page(pagetype)
def details_console_changed(self, src):
if self.ignoreDetails:
return
if not src.get_active():
return
is_details = False
if (src == self.widget("control-vm-details") or
src == self.widget("details-menu-view-details")):
is_details = True
pages = self.widget("details-pages")
if pages.get_current_page() == PAGE_DETAILS:
if self.has_unapplied_changes(self.get_hw_row()):
self.sync_details_console_view(True)
return
self.disable_apply()
if is_details:
pages.set_current_page(PAGE_DETAILS)
else:
pages.set_current_page(self.last_console_page)
def sync_details_console_view(self, is_details):
details = self.widget("control-vm-details")
details_menu = self.widget("details-menu-view-details")
console = self.widget("control-vm-console")
console_menu = self.widget("details-menu-view-console")
try:
self.ignoreDetails = True
details.set_active(is_details)
details_menu.set_active(is_details)
console.set_active(not is_details)
console_menu.set_active(not is_details)
finally:
self.ignoreDetails = False
def switch_page(self, ignore1=None, ignore2=None, newpage=None):
self.page_refresh(newpage)
self.sync_details_console_view(newpage == PAGE_DETAILS)
self.console.set_allow_fullscreen()
if newpage == PAGE_CONSOLE or newpage >= PAGE_DYNAMIC_OFFSET:
self.last_console_page = newpage
def change_run_text(self, can_restore):
if can_restore:
text = _("_Restore")
else:
text = _("_Run")
strip_text = text.replace("_", "")
self.widget("details-menu-run").get_child().set_label(text)
self.widget("control-run").set_label(strip_text)
def refresh_vm_state(self, ignore1=None, ignore2=None, ignore3=None):
vm = self.vm
status = self.vm.status()
self.toggle_toolbar(self.widget("details-menu-view-toolbar"))
active = vm.is_active()
destroy = vm.is_destroyable()
run = vm.is_runable()
stop = vm.is_stoppable()
paused = vm.is_paused()
ro = vm.is_read_only()
if vm.managedsave_supported:
self.change_run_text(vm.hasSavedImage())
self.widget("details-menu-destroy").set_sensitive(destroy)
self.widget("control-run").set_sensitive(run)
self.widget("details-menu-run").set_sensitive(run)
self.widget("details-menu-migrate").set_sensitive(stop)
self.widget("control-shutdown").set_sensitive(stop)
self.widget("details-menu-shutdown").set_sensitive(stop)
self.widget("details-menu-save").set_sensitive(stop)
self.widget("control-pause").set_sensitive(stop)
self.widget("details-menu-pause").set_sensitive(stop)
self.set_pause_state(paused)
self.widget("overview-name").set_editable(not active)
self.widget("config-vcpus").set_sensitive(not ro)
self.widget("config-vcpupin").set_sensitive(not ro)
self.widget("config-memory").set_sensitive(not ro)
self.widget("config-maxmem").set_sensitive(not ro)
# Disable send key menu entries for offline VM
self.console.send_key_button.set_sensitive(not (run or paused))
send_key = self.widget("details-menu-send-key")
for c in send_key.get_submenu().get_children():
c.set_sensitive(not (run or paused))
self.console.update_widget_states(vm, status)
if not run:
self.activate_default_console_page()
self.widget("overview-status-text").set_text(
self.vm.run_status())
self.widget("overview-status-icon").set_from_icon_name(
self.vm.run_status_icon_name(), Gtk.IconSize.MENU)
details = self.widget("details-pages")
self.page_refresh(details.get_current_page())
# This is safe to refresh, and is dependent on domain state
self._refresh_runtime_pinning()
#############################
# External action listeners #
#############################
def view_manager(self, src_ignore):
self.emit("action-view-manager")
def exit_app(self, src_ignore):
self.emit("action-exit-app")
def activate_default_console_page(self):
if self.vm.get_graphics_devices() or not self.vm.get_serial_devs():
return
# Only show serial page if we are already on console view
pages = self.widget("details-pages")
if pages.get_current_page() != PAGE_CONSOLE:
return
# Show serial console
devs = self.build_serial_list()
for name, ignore, sensitive, ignore, cb, serialidx in devs:
if not sensitive or not cb:
continue
self._show_serial_tab(name, serialidx)
break
def activate_default_page(self):
pages = self.widget("details-pages")
pages.set_current_page(PAGE_CONSOLE)
self.activate_default_console_page()
def activate_console_page(self):
pages = self.widget("details-pages")
pages.set_current_page(PAGE_CONSOLE)
def activate_performance_page(self):
self.widget("details-pages").set_current_page(PAGE_DETAILS)
self.set_hw_selection(HW_LIST_TYPE_STATS)
def activate_config_page(self):
self.widget("details-pages").set_current_page(PAGE_DETAILS)
def add_hardware(self, src_ignore):
try:
if self.addhw is None:
self.addhw = vmmAddHardware(self.vm)
self.addhw.show(self.topwin)
except Exception, e:
self.err.show_err((_("Error launching hardware dialog: %s") %
str(e)))
def remove_xml_dev(self, src_ignore):
info = self.get_hw_selection(HW_LIST_COL_DEVICE)
if not info:
return
devtype = info.virtual_device_type
self.remove_device(devtype, info)
def set_pause_state(self, paused):
# Set pause widget states
try:
self.ignorePause = True
self.widget("control-pause").set_active(paused)
self.widget("details-menu-pause").set_active(paused)
finally:
self.ignorePause = False
def control_vm_pause(self, src):
if self.ignorePause:
return
# Let state handler listener change things if necc.
self.set_pause_state(not src.get_active())
if not self.vm.is_paused():
self.emit("action-suspend-domain",
self.vm.conn.get_uri(),
self.vm.get_uuid())
else:
self.emit("action-resume-domain",
self.vm.conn.get_uri(),
self.vm.get_uuid())
def control_vm_run(self, src_ignore):
self.emit("action-run-domain",
self.vm.conn.get_uri(), self.vm.get_uuid())
def control_vm_shutdown(self, src_ignore):
self.emit("action-shutdown-domain",
self.vm.conn.get_uri(), self.vm.get_uuid())
def control_vm_reboot(self, src_ignore):
self.emit("action-reboot-domain",
self.vm.conn.get_uri(), self.vm.get_uuid())
def control_vm_save(self, src_ignore):
self.emit("action-save-domain",
self.vm.conn.get_uri(), self.vm.get_uuid())
def control_vm_reset(self, src_ignore):
self.emit("action-reset-domain",
self.vm.conn.get_uri(), self.vm.get_uuid())
def control_vm_destroy(self, src_ignore):
self.emit("action-destroy-domain",
self.vm.conn.get_uri(), self.vm.get_uuid())
def control_vm_clone(self, src_ignore):
self.emit("action-clone-domain",
self.vm.conn.get_uri(), self.vm.get_uuid())
def control_vm_migrate(self, src_ignore):
self.emit("action-migrate-domain",
self.vm.conn.get_uri(), self.vm.get_uuid())
def control_vm_screenshot(self, src_ignore):
image = self.console.viewer.get_pixbuf()
# If someone feels kind they could extend this code to allow
# user to choose what image format they'd like to save in....
path = util.browse_local(
self.topwin,
_("Save Virtual Machine Screenshot"),
self.vm.conn,
_type=("png", "PNG files"),
dialog_type=Gtk.FileChooserAction.SAVE,
browse_reason=self.config.CONFIG_DIR_SCREENSHOT)
if not path:
return
filename = path
if not filename.endswith(".png"):
filename += ".png"
# Save along with a little metadata about us & the domain
image.save(filename, 'png',
{'tEXt::Hypervisor URI': self.vm.conn.get_uri(),
'tEXt::Domain Name': self.vm.get_name(),
'tEXt::Domain UUID': self.vm.get_uuid(),
'tEXt::Generator App': self.config.get_appname(),
'tEXt::Generator Version': self.config.get_appversion()})
msg = Gtk.MessageDialog(self.topwin,
Gtk.DialogFlags.MODAL,
Gtk.MessageType.INFO,
Gtk.ButtonsType.OK,
(_("The screenshot has been saved to:\n%s") %
filename))
msg.set_title(_("Screenshot saved"))
msg.run()
msg.destroy()
#########################
# Serial Console pieces #
#########################
def control_serial_tab(self, src_ignore, name, target_port):
pages = self.widget("details-pages")
is_graphics = (name == "graphics")
is_serial = not is_graphics
if is_graphics:
pages.set_current_page(PAGE_CONSOLE)
elif is_serial:
self._show_serial_tab(name, target_port)
def _show_serial_tab(self, name, target_port):
serial = None
for s in self.serial_tabs:
if s.name == name:
serial = s
break
if not serial:
serial = vmmSerialConsole(self.vm, target_port, name)
title = Gtk.Label(label=name)
self.widget("details-pages").append_page(serial.box, title)
self.serial_tabs.append(serial)
serial.open_console()
page_idx = self.serial_tabs.index(serial) + PAGE_DYNAMIC_OFFSET
self.widget("details-pages").set_current_page(page_idx)
def _close_serial_tab(self, serial):
if not serial in self.serial_tabs:
return
page_idx = self.serial_tabs.index(serial) + PAGE_DYNAMIC_OFFSET
self.widget("details-pages").remove_page(page_idx)
serial.cleanup()
self.serial_tabs.remove(serial)
############################
# Details/Hardware getters #
############################
def get_config_boot_devs(self):
boot_model = self.widget("config-boot-list").get_model()
devs = []
for row in boot_model:
if row[BOOT_ACTIVE]:
devs.append(row[BOOT_DEV_TYPE])
return devs
def get_config_cpu_model(self):
cpu_list = self.widget("cpu-model")
model = cpu_list.get_child().get_text()
for row in cpu_list.get_model():
if model == row[0]:
return model, row[1].vendor
return model, None
def get_config_cpu_features(self):
feature_list = self.widget("cpu-features")
ret = []
for row in feature_list.get_model():
if row[1] in ["off", "model"]:
continue
ret.append(row)
return ret
##############################
# Details/Hardware listeners #
##############################
def _browse_file(self, callback, is_media=False):
if is_media:
reason = self.config.CONFIG_DIR_ISO_MEDIA
else:
reason = self.config.CONFIG_DIR_IMAGE
if self.storage_browser is None:
self.storage_browser = vmmStorageBrowser(self.conn)
self.storage_browser.set_finish_cb(callback)
self.storage_browser.set_browse_reason(reason)
self.storage_browser.show(self.topwin, self.conn)
def browse_kernel(self, src_ignore):
def cb(ignore, path):
self.widget("boot-kernel").set_text(path)
self._browse_file(cb)
def browse_initrd(self, src_ignore):
def cb(ignore, path):
self.widget("boot-kernel-initrd").set_text(path)
self._browse_file(cb)
def disable_apply(self):
self.active_edits = []
self.widget("config-apply").set_sensitive(False)
self.widget("config-cancel").set_sensitive(False)
def enable_apply(self, *arglist):
edittype = arglist[-1]
self.widget("config-apply").set_sensitive(True)
self.widget("config-cancel").set_sensitive(True)
if edittype not in self.active_edits:
self.active_edits.append(edittype)
# Overview -> Machine settings
def config_acpi_changed(self, ignore):
widget = self.widget("overview-acpi")
incon = widget.get_inconsistent()
widget.set_inconsistent(False)
if incon:
widget.set_active(True)
self.enable_apply(EDIT_ACPI)
def config_apic_changed(self, ignore):
widget = self.widget("overview-apic")
incon = widget.get_inconsistent()
widget.set_inconsistent(False)
if incon:
widget.set_active(True)
self.enable_apply(EDIT_APIC)
# Overview -> Security
def security_type_changed(self, button):
self.enable_apply(EDIT_SECURITY)
self.widget("security-label").set_sensitive(not button.get_active())
self.widget("security-relabel").set_sensitive(not button.get_active())
# Memory
def config_get_maxmem(self):
return uihelpers.spin_get_helper(self.widget("config-maxmem"))
def config_get_memory(self):
return uihelpers.spin_get_helper(self.widget("config-memory"))
def config_maxmem_changed(self, src_ignore):
self.enable_apply(EDIT_MEM)
def config_memory_changed(self, src_ignore):
self.enable_apply(EDIT_MEM)
maxadj = self.widget("config-maxmem")
mem = self.config_get_memory()
if maxadj.get_value() < mem:
maxadj.set_value(mem)
ignore, upper = maxadj.get_range()
maxadj.set_range(mem, upper)
def generate_cpuset(self):
mem = int(self.vm.get_memory()) / 1024 / 1024
return virtinst.Guest.generate_cpuset(self.conn.vmm, mem)
# VCPUS
def config_get_vcpus(self):
return uihelpers.spin_get_helper(self.widget("config-vcpus"))
def config_get_maxvcpus(self):
return uihelpers.spin_get_helper(self.widget("config-maxvcpus"))
def config_vcpupin_generate(self, ignore):
try:
pinstr = self.generate_cpuset()
except Exception, e:
return self.err.val_err(
_("Error generating CPU configuration"), e)
self.widget("config-vcpupin").set_text("")
self.widget("config-vcpupin").set_text(pinstr)
def config_vcpus_changed(self, ignore):
self.enable_apply(EDIT_VCPUS)
conn = self.vm.conn
host_active_count = conn.host_active_processor_count()
cur = self.config_get_vcpus()
# Warn about overcommit
warn = bool(cur > host_active_count)
self.widget("config-vcpus-warn-box").set_property("visible", warn)
maxadj = self.widget("config-maxvcpus")
maxval = self.config_get_maxvcpus()
if maxval < cur:
maxadj.set_value(cur)
ignore, upper = maxadj.get_range()
maxadj.set_range(cur, upper)
def config_maxvcpus_changed(self, ignore):
self.enable_apply(EDIT_VCPUS)
def config_cpu_copy_host(self, src_ignore):
# Update UI with output copied from host
try:
CPU = virtinst.CPU(self.vm.conn.vmm)
CPU.copy_host_cpu()
self._refresh_cpu_config(CPU)
self._cpu_copy_host = True
except Exception, e:
self.err.show_err(_("Error copying host CPU: %s") % str(e))
return
def config_cpu_topology_enable(self, src):
do_enable = src.get_active()
self.widget("cpu-topology-table").set_sensitive(do_enable)
self.enable_apply(EDIT_TOPOLOGY)
# Boot device / Autostart
def config_bootdev_selected(self, ignore):
boot_row = self.get_boot_selection()
boot_selection = boot_row and boot_row[BOOT_DEV_TYPE]
boot_devs = self.get_config_boot_devs()
up_widget = self.widget("config-boot-moveup")
down_widget = self.widget("config-boot-movedown")
down_widget.set_sensitive(bool(boot_devs and
boot_selection and
boot_selection in boot_devs and
boot_selection != boot_devs[-1]))
up_widget.set_sensitive(bool(boot_devs and boot_selection and
boot_selection in boot_devs and
boot_selection != boot_devs[0]))
def config_boot_toggled(self, ignore, index):
boot_model = self.widget("config-boot-list").get_model()
boot_row = boot_model[index]
is_active = boot_row[BOOT_ACTIVE]
boot_row[BOOT_ACTIVE] = not is_active
self.repopulate_boot_list(self.get_config_boot_devs(),
boot_row[BOOT_DEV_TYPE])
self.enable_apply(EDIT_BOOTORDER)
def config_boot_move(self, src, move_up):
ignore = src
boot_row = self.get_boot_selection()
if not boot_row:
return
boot_selection = boot_row[BOOT_DEV_TYPE]
boot_devs = self.get_config_boot_devs()
boot_idx = boot_devs.index(boot_selection)
if move_up:
new_idx = boot_idx - 1
else:
new_idx = boot_idx + 1
if new_idx < 0 or new_idx >= len(boot_devs):
# Somehow we got out of bounds
return
swap_dev = boot_devs[new_idx]
boot_devs[new_idx] = boot_selection
boot_devs[boot_idx] = swap_dev
self.repopulate_boot_list(boot_devs, boot_selection)
self.enable_apply(EDIT_BOOTORDER)
# IO Tuning
def iotune_changed(self, ignore):
iotune_rbs = int(self.get_text("disk-iotune-rbs") or 0)
iotune_ris = int(self.get_text("disk-iotune-ris") or 0)
iotune_tbs = int(self.get_text("disk-iotune-tbs") or 0)
iotune_tis = int(self.get_text("disk-iotune-tis") or 0)
iotune_wbs = int(self.get_text("disk-iotune-wbs") or 0)
iotune_wis = int(self.get_text("disk-iotune-wis") or 0)
# libvirt doesn't support having read/write settings along side total
# settings, so disable the widgets accordingly.
have_rw_bytes = (iotune_rbs > 0 or
iotune_wbs > 0)
have_t_bytes = (not have_rw_bytes and iotune_tbs > 0)
self.widget("disk-iotune-rbs").set_sensitive(have_rw_bytes or not
have_t_bytes)
self.widget("disk-iotune-wbs").set_sensitive(have_rw_bytes or not
have_t_bytes)
self.widget("disk-iotune-tbs").set_sensitive(have_t_bytes or not
have_rw_bytes)
if have_rw_bytes:
self.widget("disk-iotune-tbs").set_value(0)
elif have_t_bytes:
self.widget("disk-iotune-rbs").set_value(0)
self.widget("disk-iotune-wbs").set_value(0)
have_rw_iops = (iotune_ris > 0 or iotune_wis > 0)
have_t_iops = (not have_rw_iops and iotune_tis > 0)
self.widget("disk-iotune-ris").set_sensitive(have_rw_iops or not
have_t_iops)
self.widget("disk-iotune-wis").set_sensitive(have_rw_iops or not
have_t_iops)
self.widget("disk-iotune-tis").set_sensitive(have_t_iops or not
have_rw_iops)
if have_rw_iops:
self.widget("disk-iotune-tis").set_value(0)
elif have_t_iops:
self.widget("disk-iotune-ris").set_value(0)
self.widget("disk-iotune-wis").set_value(0)
self.enable_apply(EDIT_DISK_IOTUNE)
# CDROM Eject/Connect
def toggle_storage_media(self, src_ignore):
disk = self.get_hw_selection(HW_LIST_COL_DEVICE)
if not disk:
return
dev_id_info = disk
curpath = disk.path
devtype = disk.device
try:
if curpath:
# Disconnect cdrom
self.change_storage_media(dev_id_info, None)
return
except Exception, e:
self.err.show_err((_("Error disconnecting media: %s") % e))
return
try:
def change_cdrom_wrapper(src_ignore, dev_id_info, newpath):
return self.change_storage_media(dev_id_info, newpath)
# Launch 'Choose CD' dialog
if self.media_choosers[devtype] is None:
ret = vmmChooseCD(self.vm, dev_id_info)
ret.connect("cdrom-chosen", change_cdrom_wrapper)
self.media_choosers[devtype] = ret
dialog = self.media_choosers[devtype]
dialog.dev_id_info = dev_id_info
dialog.show(self.topwin)
except Exception, e:
self.err.show_err((_("Error launching media dialog: %s") % e))
return
##################################################
# Details/Hardware config changes (apply button) #
##################################################
def config_cancel(self, ignore=None):
# Remove current changes and deactive 'apply' button
self.hw_selected()
def config_apply(self, ignore=None, row=None):
pagetype = None
devobj = None
if not row:
row = self.get_hw_row()
if row:
pagetype = row[HW_LIST_COL_TYPE]
devobj = row[HW_LIST_COL_DEVICE]
key = devobj
ret = False
try:
if pagetype is HW_LIST_TYPE_GENERAL:
ret = self.config_overview_apply()
elif pagetype is HW_LIST_TYPE_CPU:
ret = self.config_vcpus_apply()
elif pagetype is HW_LIST_TYPE_MEMORY:
ret = self.config_memory_apply()
elif pagetype is HW_LIST_TYPE_BOOT:
ret = self.config_boot_options_apply()
elif pagetype is HW_LIST_TYPE_DISK:
ret = self.config_disk_apply(key)
elif pagetype is HW_LIST_TYPE_NIC:
ret = self.config_network_apply(key)
elif pagetype is HW_LIST_TYPE_GRAPHICS:
ret = self.config_graphics_apply(key)
elif pagetype is HW_LIST_TYPE_SOUND:
ret = self.config_sound_apply(key)
elif pagetype is HW_LIST_TYPE_VIDEO:
ret = self.config_video_apply(key)
elif pagetype is HW_LIST_TYPE_WATCHDOG:
ret = self.config_watchdog_apply(key)
elif pagetype is HW_LIST_TYPE_SMARTCARD:
ret = self.config_smartcard_apply(key)
elif pagetype is HW_LIST_TYPE_CONTROLLER:
ret = self.config_controller_apply(key)
else:
ret = False
except Exception, e:
return self.err.show_err(_("Error apply changes: %s") % e)
if ret is not False:
self.disable_apply()
return True
def get_text(self, widgetname, strip=True):
ret = self.widget(widgetname).get_text()
if strip:
ret = ret.strip()
return ret
def editted(self, pagetype):
if pagetype not in range(EDIT_TOTAL):
raise RuntimeError("crap! %s" % pagetype)
return pagetype in self.active_edits
def make_apply_data(self):
definefuncs = []
defineargs = []
hotplugfuncs = []
hotplugargs = []
def add_define(func, *args):
definefuncs.append(func)
defineargs.append(args)
def add_hotplug(func, *args):
hotplugfuncs.append(func)
hotplugargs.append(args)
return (definefuncs, defineargs, add_define,
hotplugfuncs, hotplugargs, add_hotplug)
# Overview section
def config_overview_apply(self):
df, da, add_define, hf, ha, add_hotplug = self.make_apply_data()
ignore = add_hotplug
if self.editted(EDIT_NAME):
name = self.widget("overview-name").get_text()
add_define(self.vm.define_name, name)
if self.editted(EDIT_ACPI):
enable_acpi = self.widget("overview-acpi").get_active()
if self.widget("overview-acpi").get_inconsistent():
enable_acpi = None
add_define(self.vm.define_acpi, enable_acpi)
if self.editted(EDIT_APIC):
enable_apic = self.widget("overview-apic").get_active()
if self.widget("overview-apic").get_inconsistent():
enable_apic = None
add_define(self.vm.define_apic, enable_apic)
if self.editted(EDIT_CLOCK):
clock = self.get_combo_label_value("overview-clock")
add_define(self.vm.define_clock, clock)
if self.editted(EDIT_MACHTYPE):
machtype = self.get_combo_label_value("machine-type")
add_define(self.vm.define_machtype, machtype)
if self.editted(EDIT_SECURITY):
semodel = None
setype = "static"
selabel = self.get_text("security-label")
relabel = self.widget("security-relabel").get_active()
if self.widget("security-dynamic").get_active():
setype = "dynamic"
relabel = True
if self.widget("security-type-box").get_sensitive():
semodel = self.get_text("security-model")
add_define(self.vm.define_seclabel, semodel, setype, selabel, relabel)
if self.editted(EDIT_DESC):
desc_widget = self.widget("overview-description")
desc = desc_widget.get_buffer().get_property("text") or ""
add_define(self.vm.define_description, desc)
add_hotplug(self.vm.hotplug_description, desc)
return self._change_config_helper(df, da, hf, ha)
# CPUs
def config_vcpus_apply(self):
df, da, add_define, hf, ha, add_hotplug = self.make_apply_data()
if self.editted(EDIT_VCPUS):
vcpus = self.config_get_vcpus()
maxv = self.config_get_maxvcpus()
add_define(self.vm.define_vcpus, vcpus, maxv)
add_hotplug(self.vm.hotplug_vcpus, vcpus)
if self.editted(EDIT_CPUSET):
cpuset = self.get_text("config-vcpupin")
print cpuset
add_define(self.vm.define_cpuset, cpuset)
add_hotplug(self.config_vcpu_pin_cpuset, cpuset)
if self.editted(EDIT_CPU):
model, vendor = self.get_config_cpu_model()
features = self.get_config_cpu_features()
add_define(self.vm.define_cpu,
model, vendor, self._cpu_copy_host, features)
if self.editted(EDIT_TOPOLOGY):
do_top = self.widget("cpu-topology-enable").get_active()
sockets = self.widget("cpu-sockets").get_value()
cores = self.widget("cpu-cores").get_value()
threads = self.widget("cpu-threads").get_value()
if not do_top:
sockets = None
cores = None
threads = None
add_define(self.vm.define_cpu_topology, sockets, cores, threads)
ret = self._change_config_helper(df, da, hf, ha)
if ret:
self._cpu_copy_host = False
return ret
def config_vcpu_pin(self, src_ignore, path, new_text):
vcpu_list = self.widget("config-vcpu-list")
vcpu_model = vcpu_list.get_model()
row = vcpu_model[path]
conn = self.vm.conn
try:
new_text = new_text.strip()
vcpu_num = int(row[0])
pinlist = virtinst.Guest.cpuset_str_to_tuple(conn.vmm, new_text)
except Exception, e:
self.err.val_err(_("Error building pin list"), e)
return
try:
self.vm.pin_vcpu(vcpu_num, pinlist)
except Exception, e:
self.err.show_err(_("Error pinning vcpus"), e)
return
self._refresh_runtime_pinning()
def config_vcpu_pin_cpuset(self, cpuset):
conn = self.vm.conn
vcpu_list = self.widget("config-vcpu-list")
vcpu_model = vcpu_list.get_model()
if self.vm.vcpu_pinning() == cpuset:
return
pinlist = virtinst.Guest.cpuset_str_to_tuple(conn.vmm, cpuset)
for row in vcpu_model:
vcpu_num = row[0]
self.vm.pin_vcpu(int(vcpu_num), pinlist)
# Memory
def config_memory_apply(self):
df, da, add_define, hf, ha, add_hotplug = self.make_apply_data()
if self.editted(EDIT_MEM):
curmem = None
maxmem = self.config_get_maxmem()
if self.widget("config-memory").get_sensitive():
curmem = self.config_get_memory()
if curmem:
curmem = int(curmem) * 1024
if maxmem:
maxmem = int(maxmem) * 1024
add_define(self.vm.define_both_mem, curmem, maxmem)
add_hotplug(self.vm.hotplug_both_mem, curmem, maxmem)
return self._change_config_helper(df, da, hf, ha)
# Boot device / Autostart
def config_boot_options_apply(self):
df, da, add_define, hf, ha, add_hotplug = self.make_apply_data()
ignore = add_hotplug
if self.editted(EDIT_AUTOSTART):
auto = self.widget("config-autostart")
try:
self.vm.set_autostart(auto.get_active())
except Exception, e:
self.err.show_err(
(_("Error changing autostart value: %s") % str(e)))
return False
if self.editted(EDIT_BOOTORDER):
bootdevs = self.get_config_boot_devs()
add_define(self.vm.set_boot_device, bootdevs)
if self.editted(EDIT_BOOTMENU):
bootmenu = self.widget("boot-menu").get_active()
add_define(self.vm.set_boot_menu, bootmenu)
if self.editted(EDIT_KERNEL):
kernel = self.get_text("boot-kernel")
initrd = self.get_text("boot-kernel-initrd")
args = self.get_text("boot-kernel-args")
if initrd and not kernel:
return self.err.val_err(
_("Cannot set initrd without specifying a kernel path"))
if args and not kernel:
return self.err.val_err(
_("Cannot set kernel arguments without specifying a kernel path"))
add_define(self.vm.set_boot_kernel, kernel, initrd, args)
if self.editted(EDIT_INIT):
init = self.get_text("boot-init-path")
if not init:
return self.err.val_err(_("An init path must be specified"))
add_define(self.vm.set_boot_init, init)
return self._change_config_helper(df, da, hf, ha)
# CDROM
def change_storage_media(self, dev_id_info, newpath):
return self._change_config_helper(self.vm.define_storage_media,
(dev_id_info, newpath),
self.vm.hotplug_storage_media,
(dev_id_info, newpath))
# Disk options
def config_disk_apply(self, dev_id_info):
df, da, add_define, hf, ha, add_hotplug = self.make_apply_data()
ignore = add_hotplug
if self.editted(EDIT_DISK_RO):
do_readonly = self.widget("disk-readonly").get_active()
add_define(self.vm.define_disk_readonly, dev_id_info, do_readonly)
if self.editted(EDIT_DISK_SHARE):
do_shareable = self.widget("disk-shareable").get_active()
add_define(self.vm.define_disk_shareable,
dev_id_info, do_shareable)
if self.editted(EDIT_DISK_CACHE):
cache = self.get_combo_label_value("disk-cache")
add_define(self.vm.define_disk_cache, dev_id_info, cache)
if self.editted(EDIT_DISK_IO):
io = self.get_combo_label_value("disk-io")
add_define(self.vm.define_disk_io, dev_id_info, io)
if self.editted(EDIT_DISK_FORMAT):
fmt = self.widget("disk-format").get_child().get_text().strip()
add_define(self.vm.define_disk_driver_type, dev_id_info, fmt)
if self.editted(EDIT_DISK_SERIAL):
serial = self.get_text("disk-serial")
add_define(self.vm.define_disk_serial, dev_id_info, serial)
if self.editted(EDIT_DISK_IOTUNE):
iotune_rbs = int(self.widget("disk-iotune-rbs").get_value() * 1024)
iotune_ris = int(self.widget("disk-iotune-ris").get_value())
iotune_tbs = int(self.widget("disk-iotune-tbs").get_value() * 1024)
iotune_tis = int(self.widget("disk-iotune-tis").get_value())
iotune_wbs = int(self.widget("disk-iotune-wbs").get_value() * 1024)
iotune_wis = int(self.widget("disk-iotune-wis").get_value())
add_define(self.vm.define_disk_iotune_rbs, dev_id_info, iotune_rbs)
add_define(self.vm.define_disk_iotune_ris, dev_id_info, iotune_ris)
add_define(self.vm.define_disk_iotune_tbs, dev_id_info, iotune_tbs)
add_define(self.vm.define_disk_iotune_tis, dev_id_info, iotune_tis)
add_define(self.vm.define_disk_iotune_wbs, dev_id_info, iotune_wbs)
add_define(self.vm.define_disk_iotune_wis, dev_id_info, iotune_wis)
# Do this last since it can change uniqueness info of the dev
if self.editted(EDIT_DISK_BUS):
bus = self.get_combo_label_value("disk-bus")
addr = None
if bus == "spapr-vscsi":
bus = "scsi"
addr = "spapr-vio"
add_define(self.vm.define_disk_bus, dev_id_info, bus, addr)
return self._change_config_helper(df, da, hf, ha)
# Audio options
def config_sound_apply(self, dev_id_info):
df, da, add_define, hf, ha, add_hotplug = self.make_apply_data()
ignore = add_hotplug
if self.editted(EDIT_SOUND_MODEL):
model = self.get_combo_label_value("sound-model")
if model:
add_define(self.vm.define_sound_model, dev_id_info, model)
return self._change_config_helper(df, da, hf, ha)
# Smartcard options
def config_smartcard_apply(self, dev_id_info):
df, da, add_define, hf, ha, add_hotplug = self.make_apply_data()
ignore = add_hotplug
if self.editted(EDIT_SMARTCARD_MODE):
model = self.get_combo_label_value("smartcard-mode")
if model:
add_define(self.vm.define_smartcard_mode, dev_id_info, model)
return self._change_config_helper(df, da, hf, ha)
# Network options
def config_network_apply(self, dev_id_info):
df, da, add_define, hf, ha, add_hotplug = self.make_apply_data()
ignore = add_hotplug
if self.editted(EDIT_NET_MODEL):
model = self.get_combo_label_value("network-model")
addr = None
if model == "spapr-vlan":
addr = "spapr-vio"
add_define(self.vm.define_network_model, dev_id_info, model, addr)
if self.editted(EDIT_NET_SOURCE):
mode = None
net_list = self.widget("network-source-combo")
net_bridge = self.widget("network-bridge")
nettype, source = uihelpers.get_network_selection(net_list,
net_bridge)
if nettype == "direct":
mode = self.get_combo_label_value("network-source-mode")
add_define(self.vm.define_network_source, dev_id_info,
nettype, source, mode)
if self.editted(EDIT_NET_VPORT):
vport_type = self.get_text("vport-type")
vport_managerid = self.get_text("vport-managerid")
vport_typeid = self.get_text("vport-typeid")
vport_idver = self.get_text("vport-typeidversion")
vport_instid = self.get_text("vport-instanceid")
add_define(self.vm.define_virtualport, dev_id_info,
vport_type, vport_managerid, vport_typeid,
vport_idver, vport_instid)
return self._change_config_helper(df, da, hf, ha)
# Graphics options
def _do_change_spicevmc(self, gdev, newgtype):
has_multi_spice = (len([d for d in self.vm.get_graphics_devices() if
d.type == d.TYPE_SPICE]) > 1)
has_spicevmc = bool([d for d in self.vm.get_char_devices() if
(d.dev_type == d.DEV_CHANNEL and
d.char_type == d.CHAR_SPICEVMC)])
fromspice = (gdev.type == "spice")
tospice = (newgtype == "spice")
if fromspice and tospice:
return False
if not fromspice and not tospice:
return False
if tospice and has_spicevmc:
return False
if fromspice and not has_spicevmc:
return False
if fromspice and has_multi_spice:
# Don't offer to remove if there are other spice displays
return False
msg = (_("You are switching graphics type to %(gtype)s, "
"would you like to %(action)s Spice agent channels?") %
{"gtype": newgtype,
"action": fromspice and "remove" or "add"})
return self.err.yes_no(msg)
def config_graphics_apply(self, dev_id_info):
df, da, add_define, hf, ha, add_hotplug = self.make_apply_data()
if self.editted(EDIT_GFX_PASSWD):
passwd = self.get_text("gfx-password", strip=False) or None
add_define(self.vm.define_graphics_password, dev_id_info, passwd)
add_hotplug(self.vm.hotplug_graphics_password, dev_id_info,
passwd)
if self.editted(EDIT_GFX_KEYMAP):
keymap = self.get_combo_label_value("gfx-keymap")
add_define(self.vm.define_graphics_keymap, dev_id_info, keymap)
# Do this last since it can change graphics unique ID
if self.editted(EDIT_GFX_TYPE):
gtype = self.get_combo_label_value("gfx-type")
change_spicevmc = self._do_change_spicevmc(dev_id_info, gtype)
add_define(self.vm.define_graphics_type, dev_id_info,
gtype, change_spicevmc)
return self._change_config_helper(df, da, hf, ha)
# Video options
def config_video_apply(self, dev_id_info):
df, da, add_define, hf, ha, add_hotplug = self.make_apply_data()
ignore = add_hotplug
if self.editted(EDIT_VIDEO_MODEL):
model = self.get_combo_label_value("video-model")
if model:
add_define(self.vm.define_video_model, dev_id_info, model)
return self._change_config_helper(df, da, hf, ha)
# Controller options
def config_controller_apply(self, dev_id_info):
df, da, add_define, hf, ha, add_hotplug = self.make_apply_data()
ignore = add_hotplug
if self.editted(EDIT_CONTROLLER_MODEL):
model = self.get_combo_label_value("controller-model")
if model:
add_define(self.vm.define_controller_model, dev_id_info, model)
return self._change_config_helper(df, da, hf, ha)
# Watchdog options
def config_watchdog_apply(self, dev_id_info):
df, da, add_define, hf, ha, add_hotplug = self.make_apply_data()
ignore = add_hotplug
if self.editted(EDIT_WATCHDOG_MODEL):
model = self.get_combo_label_value("watchdog-model")
add_define(self.vm.define_watchdog_model, dev_id_info, model)
if self.editted(EDIT_WATCHDOG_ACTION):
action = self.get_combo_label_value("watchdog-action")
add_define(self.vm.define_watchdog_action, dev_id_info, action)
return self._change_config_helper(df, da, hf, ha)
# Device removal
def remove_device(self, dev_type, dev_id_info):
logging.debug("Removing device: %s %s", dev_type, dev_id_info)
if not util.chkbox_helper(self, self.config.get_confirm_removedev,
self.config.set_confirm_removedev,
text1=(_("Are you sure you want to remove this device?"))):
return
# Define the change
try:
self.vm.remove_device(dev_id_info)
except Exception, e:
self.err.show_err(_("Error Removing Device: %s" % str(e)))
return
# Try to hot remove
detach_err = False
try:
if self.vm.is_active():
self.vm.detach_device(dev_id_info)
except Exception, e:
logging.debug("Device could not be hotUNplugged: %s", str(e))
detach_err = (str(e), "".join(traceback.format_exc()))
if not detach_err:
self.disable_apply()
return
self.err.show_err(
_("Device could not be removed from the running machine"),
details=(detach_err[0] + "\n\n" + detach_err[1]),
text2=_("This change will take effect after the next guest "
"shutdown."),
buttons=Gtk.ButtonsType.OK,
dialog_type=Gtk.MessageType.INFO)
# Generic config change helpers
def _change_config_helper(self,
define_funcs, define_funcs_args,
hotplug_funcs=None, hotplug_funcs_args=None):
"""
Requires at least a 'define' function and arglist to be specified
(a function where we change the inactive guest config).
Arguments can be a single arg or a list or appropriate arg type (e.g.
a list of functions for define_funcs)
"""
def listify(val):
if not val:
return []
if type(val) is not list:
return [val]
return val
define_funcs = listify(define_funcs)
define_funcs_args = listify(define_funcs_args)
hotplug_funcs = listify(hotplug_funcs)
hotplug_funcs_args = listify(hotplug_funcs_args)
hotplug_err = []
active = self.vm.is_active()
# Hotplug change
func = None
if active and hotplug_funcs:
for idx in range(len(hotplug_funcs)):
func = hotplug_funcs[idx]
args = hotplug_funcs_args[idx]
try:
func(*args)
except Exception, e:
logging.debug("Hotplug failed: func=%s: %s",
func, str(e))
hotplug_err.append((str(e),
"".join(traceback.format_exc())))
# Persistent config change
try:
for idx in range(len(define_funcs)):
func = define_funcs[idx]
args = define_funcs_args[idx]
func(*args)
if define_funcs:
self.vm.redefine_cached()
except Exception, e:
self.err.show_err((_("Error changing VM configuration: %s") %
str(e)))
# If we fail, make sure we flush the cache
self.vm.refresh_xml()
return False
if (hotplug_err or
(active and not len(hotplug_funcs) == len(define_funcs))):
if len(define_funcs) > 1:
msg = _("Some changes may require a guest shutdown "
"to take effect.")
else:
msg = _("These changes will take effect after "
"the next guest shutdown.")
dtype = hotplug_err and Gtk.MessageType.WARNING or Gtk.MessageType.INFO
hotplug_msg = ""
for err1, tb in hotplug_err:
hotplug_msg += (err1 + "\n\n" + tb + "\n")
self.err.show_err(msg,
details=hotplug_msg,
buttons=Gtk.ButtonsType.OK,
dialog_type=dtype)
return True
########################
# Details page refresh #
########################
def refresh_resources(self, ignore):
details = self.widget("details-pages")
page = details.get_current_page()
# If the dialog is visible, we want to make sure the XML is always
# up to date
if self.is_visible():
self.vm.refresh_xml()
# Stats page needs to be refreshed every tick
if (page == PAGE_DETAILS and
self.get_hw_selection(HW_LIST_COL_TYPE) == HW_LIST_TYPE_STATS):
self.refresh_stats_page()
def page_refresh(self, page):
if page != PAGE_DETAILS:
return
# This function should only be called when the VM xml actually
# changes (not everytime it is refreshed). This saves us from blindly
# parsing the xml every tick
# Add / remove new devices
self.repopulate_hw_list()
pagetype = self.get_hw_selection(HW_LIST_COL_TYPE)
if pagetype is None:
return
if self.widget("config-apply").get_sensitive():
# Apply button sensitive means user is making changes, don't
# erase them
return
self.hw_selected(page=pagetype)
def refresh_overview_page(self):
# Basic details
self.widget("overview-name").set_text(self.vm.get_name())
self.widget("overview-uuid").set_text(self.vm.get_uuid())
desc = self.vm.get_description() or ""
desc_widget = self.widget("overview-description")
desc_widget.get_buffer().set_text(desc)
# Hypervisor Details
self.widget("overview-hv").set_text(self.vm.get_pretty_hv_type())
arch = self.vm.get_arch() or _("Unknown")
emu = self.vm.get_emulator() or _("None")
self.widget("overview-arch").set_text(arch)
self.widget("overview-emulator").set_text(emu)
# Operating System (ie. inspection data)
hostname = self.vm.inspection.hostname
if not hostname:
hostname = _("unknown")
self.widget("inspection-hostname").set_text(hostname)
product_name = self.vm.inspection.product_name
if not product_name:
product_name = _("unknown")
self.widget("inspection-product-name").set_text(product_name)
# Applications (also inspection data)
apps = self.vm.inspection.applications or []
apps_list = self.widget("inspection-apps")
apps_model = apps_list.get_model()
apps_model.clear()
for app in apps:
name = ""
if app["app_name"]:
name = app["app_name"]
if app["app_display_name"]:
name = app["app_display_name"]
version = ""
if app["app_version"]:
version = app["app_version"]
if app["app_release"]:
version += "-" + app["app_release"]
summary = ""
if app["app_summary"]:
summary = app["app_summary"]
apps_model.append([name, version, summary])
# Machine settings
acpi = self.vm.get_acpi()
apic = self.vm.get_apic()
clock = self.vm.get_clock()
machtype = self.vm.get_machtype()
# Hack in a way to represent 'default' acpi/apic for customize dialog
self.widget("overview-acpi").set_active(bool(acpi))
self.widget("overview-acpi").set_inconsistent(
acpi is None and self.is_customize_dialog)
self.widget("overview-apic").set_active(bool(apic))
self.widget("overview-apic").set_inconsistent(
apic is None and self.is_customize_dialog)
if not clock:
clock = _("Same as host")
self.set_combo_label("overview-clock", clock)
if not arch in ["i686", "x86_64"]:
if machtype is not None:
self.set_combo_label("machine-type", machtype)
# Security details
semodel, sectype, vmlabel, relabel = self.vm.get_seclabel()
caps = self.vm.conn.get_capabilities()
if caps.host.secmodel and caps.host.secmodel.model:
semodel = caps.host.secmodel.model
self.widget("security-model").set_text(semodel or _("None"))
if not semodel or semodel == "apparmor":
self.widget("security-type-box").hide()
self.widget("security-type-label").hide()
else:
self.widget("security-type-box").set_sensitive(bool(semodel))
if sectype == "static":
self.widget("security-static").set_active(True)
self.widget("security-relabel").set_sensitive(True)
# As "no" is default for relabel with 'static' label and
# 'dynamic' must have relabel='yes', this will work properly
# for both False (relabel='no') and None (relabel not
# specified)
self.widget("security-relabel").set_active(relabel)
else:
self.widget("security-dynamic").set_active(True)
# Dynamic label type must use resource labeling
self.widget("security-relabel").set_active(True)
self.widget("security-relabel").set_sensitive(False)
self.widget("security-label").set_text(vmlabel)
def refresh_stats_page(self):
def _dsk_rx_tx_text(rx, tx, unit):
return ('<span color="#82003B">%(rx)d %(unit)s read</span>\n'
'<span color="#295C45">%(tx)d %(unit)s write</span>' %
{"rx": rx, "tx": tx, "unit": unit})
def _net_rx_tx_text(rx, tx, unit):
return ('<span color="#82003B">%(rx)d %(unit)s in</span>\n'
'<span color="#295C45">%(tx)d %(unit)s out</span>' %
{"rx": rx, "tx": tx, "unit": unit})
cpu_txt = _("Disabled")
mem_txt = _("Disabled")
dsk_txt = _("Disabled")
net_txt = _("Disabled")
cpu_txt = "%d %%" % self.vm.guest_cpu_time_percentage()
cur_vm_memory = self.vm.stats_memory()
vm_memory = self.vm.maximum_memory()
mem_txt = "%s of %s" % (util.pretty_mem(cur_vm_memory),
util.pretty_mem(vm_memory))
if self.config.get_stats_enable_disk_poll():
dsk_txt = _dsk_rx_tx_text(self.vm.disk_read_rate(),
self.vm.disk_write_rate(), "KB/s")
if self.config.get_stats_enable_net_poll():
net_txt = _net_rx_tx_text(self.vm.network_rx_rate(),
self.vm.network_tx_rate(), "KB/s")
self.widget("overview-cpu-usage-text").set_text(cpu_txt)
self.widget("overview-memory-usage-text").set_text(mem_txt)
self.widget("overview-network-traffic-text").set_markup(net_txt)
self.widget("overview-disk-usage-text").set_markup(dsk_txt)
self.cpu_usage_graph.set_property("data_array",
self.vm.guest_cpu_time_vector())
self.memory_usage_graph.set_property("data_array",
self.vm.stats_memory_vector())
self.disk_io_graph.set_property("data_array",
self.vm.disk_io_vector())
self.network_traffic_graph.set_property("data_array",
self.vm.network_traffic_vector())
def _refresh_cpu_count(self):
conn = self.vm.conn
host_active_count = conn.host_active_processor_count()
maxvcpus = self.vm.vcpu_max_count()
curvcpus = self.vm.vcpu_count()
curadj = self.widget("config-vcpus")
maxadj = self.widget("config-maxvcpus")
curadj.set_value(int(curvcpus))
maxadj.set_value(int(maxvcpus))
self.widget("state-host-cpus").set_text(str(host_active_count))
# Warn about overcommit
warn = bool(self.config_get_vcpus() > host_active_count)
self.widget("config-vcpus-warn-box").set_property("visible", warn)
def _refresh_cpu_pinning(self):
# Populate VCPU pinning
vcpupin = self.vm.vcpu_pinning()
self.widget("config-vcpupin").set_text(vcpupin)
def _refresh_runtime_pinning(self):
conn = self.vm.conn
host_active_count = conn.host_active_processor_count()
vcpu_list = self.widget("config-vcpu-list")
vcpu_model = vcpu_list.get_model()
vcpu_model.clear()
reason = ""
if not self.vm.is_active():
reason = _("VCPU info only available for running domain.")
else:
try:
vcpu_info, vcpu_pinning = self.vm.vcpu_info()
except Exception, e:
reason = _("Error getting VCPU info: %s") % str(e)
if not self.vm.getvcpus_supported:
reason = _("Virtual machine does not support runtime "
"VPCU info.")
vcpu_list.set_sensitive(not bool(reason))
vcpu_list.set_tooltip_text(reason or "")
if reason:
return
def build_cpuset_str(pin_info):
pinstr = ""
for i in range(host_active_count):
if i < len(pin_info) and pin_info[i]:
pinstr += (",%s" % str(i))
return pinstr.strip(",")
for idx in range(len(vcpu_info)):
vcpu = str(vcpu_info[idx][0])
vcpucur = str(vcpu_info[idx][3])
vcpupin = build_cpuset_str(vcpu_pinning[idx])
vcpu_model.append([vcpu, vcpucur, vcpupin])
def _refresh_cpu_config(self, cpu):
feature_ui = self.widget("cpu-features")
model = cpu.model or ""
caps = self.vm.conn.get_capabilities()
capscpu = None
try:
arch = self.vm.get_arch()
if arch:
cpu_values = caps.get_cpu_values(arch)
for c in cpu_values.cpus:
if model and c.model == model:
capscpu = c
break
except:
pass
show_top = bool(cpu.sockets or cpu.cores or cpu.threads)
sockets = cpu.sockets or 1
cores = cpu.cores or 1
threads = cpu.threads or 1
self.widget("cpu-topology-enable").set_active(show_top)
self.widget("cpu-model").get_child().set_text(model)
self.widget("cpu-sockets").set_value(sockets)
self.widget("cpu-cores").set_value(cores)
self.widget("cpu-threads").set_value(threads)
def get_feature_policy(name):
for f in cpu.features:
if f.name == name:
return f.policy
if capscpu:
for f in capscpu.features:
if f == name:
return "model"
return "off"
for row in feature_ui.get_model():
row[1] = get_feature_policy(row[0])
def refresh_config_cpu(self):
self._cpu_copy_host = False
cpu = self.vm.get_cpu_config()
self._refresh_cpu_count()
self._refresh_cpu_pinning()
self._refresh_runtime_pinning()
self._refresh_cpu_config(cpu)
def refresh_config_memory(self):
host_mem_widget = self.widget("state-host-memory")
host_mem = self.vm.conn.host_memory_size() / 1024
vm_cur_mem = self.vm.get_memory() / 1024.0
vm_max_mem = self.vm.maximum_memory() / 1024.0
host_mem_widget.set_text("%d MB" % (int(round(host_mem))))
curmem = self.widget("config-memory")
maxmem = self.widget("config-maxmem")
curmem.set_value(int(round(vm_cur_mem)))
maxmem.set_value(int(round(vm_max_mem)))
if not self.widget("config-memory").get_sensitive():
ignore, upper = maxmem.get_range()
maxmem.set_range(curmem.get_value(), upper)
def refresh_disk_page(self):
disk = self.get_hw_selection(HW_LIST_COL_DEVICE)
if not disk:
return
path = disk.path
devtype = disk.device
ro = disk.read_only
share = disk.shareable
bus = disk.bus
addr = disk.address.type
idx = disk.disk_bus_index
cache = disk.driver_cache
io = disk.driver_io
driver_type = disk.driver_type or ""
serial = disk.serial
iotune_rbs = (disk.iotune_rbs or 0) / 1024
iotune_ris = (disk.iotune_ris or 0)
iotune_tbs = (disk.iotune_tbs or 0) / 1024
iotune_tis = (disk.iotune_tis or 0)
iotune_wbs = (disk.iotune_wbs or 0) / 1024
iotune_wis = (disk.iotune_wis or 0)
show_format = (not self.is_customize_dialog or
disk.path_exists(disk.conn, disk.path))
size = _("Unknown")
if not path:
size = "-"
else:
vol = self.conn.get_vol_by_path(path)
if vol:
size = vol.get_pretty_capacity()
elif not self.conn.is_remote():
ignore, val = virtinst.VirtualDisk.stat_local_path(path)
if val != 0:
size = prettyify_bytes(val)
is_cdrom = (devtype == virtinst.VirtualDisk.DEVICE_CDROM)
is_floppy = (devtype == virtinst.VirtualDisk.DEVICE_FLOPPY)
if addr == "spapr-vio":
bus = "spapr-vscsi"
pretty_name = prettyify_disk(devtype, bus, idx)
self.widget("disk-source-path").set_text(path or "-")
self.widget("disk-target-type").set_text(pretty_name)
self.widget("disk-readonly").set_active(ro)
self.widget("disk-readonly").set_sensitive(not is_cdrom)
self.widget("disk-shareable").set_active(share)
self.widget("disk-size").set_text(size)
self.set_combo_label("disk-cache", cache)
self.set_combo_label("disk-io", io)
self.widget("disk-format").set_sensitive(show_format)
self.widget("disk-format").get_child().set_text(driver_type)
no_default = not self.is_customize_dialog
self.populate_disk_bus_combo(devtype, no_default)
self.set_combo_label("disk-bus", bus)
self.widget("disk-serial").set_text(serial or "")
self.widget("disk-iotune-rbs").set_value(iotune_rbs)
self.widget("disk-iotune-ris").set_value(iotune_ris)
self.widget("disk-iotune-tbs").set_value(iotune_tbs)
self.widget("disk-iotune-tis").set_value(iotune_tis)
self.widget("disk-iotune-wbs").set_value(iotune_wbs)
self.widget("disk-iotune-wis").set_value(iotune_wis)
button = self.widget("config-cdrom-connect")
if is_cdrom or is_floppy:
if not path:
# source device not connected
button.set_label(Gtk.STOCK_CONNECT)
else:
button.set_label(Gtk.STOCK_DISCONNECT)
button.show()
else:
button.hide()
def refresh_network_page(self):
net = self.get_hw_selection(HW_LIST_COL_DEVICE)
if not net:
return
nettype = net.type
source = net.get_source()
source_mode = net.source_mode
model = net.model
netobj = None
if nettype == virtinst.VirtualNetworkInterface.TYPE_VIRTUAL:
name_dict = {}
for uuid in self.conn.list_net_uuids():
vnet = self.conn.get_net(uuid)
name = vnet.get_name()
name_dict[name] = vnet
if source and source in name_dict:
netobj = name_dict[source]
desc = uihelpers.pretty_network_desc(nettype, source, netobj)
self.widget("network-mac-address").set_text(net.macaddr)
uihelpers.populate_network_list(
self.widget("network-source-combo"),
self.conn)
self.widget("network-source-combo").set_active(-1)
self.widget("network-bridge").set_text("")
def compare_network(model, info):
for idx in range(len(model)):
row = model[idx]
if row[0] == info[0] and row[1] == info[1]:
return True, idx
if info[0] == virtinst.VirtualNetworkInterface.TYPE_BRIDGE:
idx = (len(model) - 1)
self.widget("network-bridge").set_text(str(info[1]))
return True, idx
return False, 0
self.set_combo_label("network-source",
(nettype, source), label=desc,
comparefunc=compare_network)
# source mode
uihelpers.populate_source_mode_combo(self.vm,
self.widget("network-source-mode-combo"))
self.set_combo_label("network-source-mode", source_mode)
# Virtualport config
show_vport = (nettype == "direct")
vport = net.virtualport
self.widget("vport-expander").set_property("visible", show_vport)
self.widget("vport-type").set_text(vport.type or "")
self.widget("vport-managerid").set_text(vport.managerid or "")
self.widget("vport-typeid").set_text(vport.typeid or "")
self.widget("vport-typeidversion").set_text(vport.typeidversion or "")
self.widget("vport-instanceid").set_text(vport.instanceid or "")
uihelpers.populate_netmodel_combo(self.vm,
self.widget("network-model-combo"))
self.set_combo_label("network-model", model)
def refresh_input_page(self):
inp = self.get_hw_selection(HW_LIST_COL_DEVICE)
if not inp:
return
ident = "%s:%s" % (inp.type, inp.bus)
if ident == "tablet:usb":
dev = _("EvTouch USB Graphics Tablet")
elif ident == "mouse:usb":
dev = _("Generic USB Mouse")
elif ident == "mouse:xen":
dev = _("Xen Mouse")
elif ident == "mouse:ps2":
dev = _("PS/2 Mouse")
else:
dev = inp.bus + " " + inp.type
if inp.type == "tablet":
mode = _("Absolute Movement")
else:
mode = _("Relative Movement")
self.widget("input-dev-type").set_text(dev)
self.widget("input-dev-mode").set_text(mode)
# Can't remove primary Xen or PS/2 mice
if inp.type == "mouse" and inp.bus in ("xen", "ps2"):
self.widget("config-remove").set_sensitive(False)
else:
self.widget("config-remove").set_sensitive(True)
def refresh_graphics_page(self):
gfx = self.get_hw_selection(HW_LIST_COL_DEVICE)
if not gfx:
return
title = self.widget("graphics-title")
table = self.widget("graphics-table")
table.foreach(lambda w, ignore: w.hide(), ())
def set_title(text):
title.set_markup("<b>%s</b>" % text)
def show_row(widget_name, suffix=""):
base = "gfx-%s" % widget_name
self.widget(base + "-title").show()
self.widget(base + suffix).show()
def show_text(widget_name, text):
show_row(widget_name)
self.widget("gfx-" + widget_name).set_text(text)
def port_to_string(port):
if port is None:
return "-"
return (port == -1 and _("Automatically allocated") or str(port))
gtype = gfx.type
is_vnc = (gtype == "vnc")
is_sdl = (gtype == "sdl")
is_spice = (gtype == "spice")
is_other = not (True in [is_vnc, is_sdl, is_spice])
set_title(_("%(graphicstype)s Server") %
{"graphicstype" : gfx.pretty_type_simple(gtype)})
settype = ""
if is_vnc or is_spice:
port = port_to_string(gfx.port)
address = (gfx.listen or "127.0.0.1")
keymap = (gfx.keymap or None)
passwd = gfx.passwd or ""
show_text("password", passwd)
show_text("port", port)
show_text("address", address)
show_row("keymap", "-box")
self.set_combo_label("gfx-keymap", keymap)
settype = gtype
if is_spice:
tlsport = port_to_string(gfx.tlsPort)
show_text("tlsport", tlsport)
if is_sdl:
set_title(_("Local SDL Window"))
display = gfx.display or _("Unknown")
xauth = gfx.xauth or _("Unknown")
show_text("display", display)
show_text("xauth", xauth)
if is_other:
settype = gfx.pretty_type_simple(gtype)
if settype:
show_row("type", "-box")
self.set_combo_label("gfx-type", gtype, label=settype)
def refresh_sound_page(self):
sound = self.get_hw_selection(HW_LIST_COL_DEVICE)
if not sound:
return
self.set_combo_label("sound-model", sound.model)
def refresh_smartcard_page(self):
sc = self.get_hw_selection(HW_LIST_COL_DEVICE)
if not sc:
return
self.set_combo_label("smartcard-mode", sc.mode)
def refresh_redir_page(self):
rd = self.get_hw_selection(HW_LIST_COL_DEVICE)
if not rd:
return
address = build_redir_label(rd)[0] or "-"
devlabel = "<b>Redirected %s Device</b>" % rd.bus.upper()
self.widget("redir-title").set_markup(devlabel)
self.widget("redir-address").set_text(address)
self.widget("redir-type-label").set_text(rd.type)
self.widget("redir-type-combo").hide()
def refresh_char_page(self):
chardev = self.get_hw_selection(HW_LIST_COL_DEVICE)
if not chardev:
return
show_target_type = not (chardev.dev_type in
[chardev.DEV_SERIAL, chardev.DEV_PARALLEL])
def show_ui(param, val=None):
widgetname = "char-" + param.replace("_", "-")
labelname = widgetname + "-label"
doshow = chardev.supports_property(param, ro=True)
# Exception: don't show target type for serial/parallel
if (param == "target_type" and not show_target_type):
doshow = False
if not val and doshow:
val = getattr(chardev, param)
self.widget(widgetname).set_property("visible", doshow)
self.widget(labelname).set_property("visible", doshow)
self.widget(widgetname).set_text(val or "-")
def build_host_str(base):
if (not chardev.supports_property(base + "_host") or
not chardev.supports_property(base + "_port")):
return ""
host = getattr(chardev, base + "_host") or ""
port = getattr(chardev, base + "_port") or ""
ret = str(host)
if port:
ret += ":%s" % str(port)
return ret
char_type = chardev.virtual_device_type.capitalize()
target_port = chardev.target_port
dev_type = chardev.char_type or "pty"
primary = hasattr(chardev, "virtmanager_console_dup")
typelabel = ""
if char_type == "serial":
typelabel = _("Serial Device")
elif char_type == "parallel":
typelabel = _("Parallel Device")
elif char_type == "console":
typelabel = _("Console Device")
elif char_type == "channel":
typelabel = _("Channel Device")
else:
typelabel = _("%s Device") % char_type.capitalize()
if target_port is not None and not show_target_type:
typelabel += " %s" % (int(target_port) + 1)
if primary:
typelabel += " (%s)" % _("Primary Console")
typelabel = "<b>%s</b>" % typelabel
self.widget("char-type").set_markup(typelabel)
self.widget("char-dev-type").set_text(dev_type)
# Device type specific properties, only show if apply to the cur dev
show_ui("source_host", build_host_str("source"))
show_ui("bind_host", build_host_str("bind"))
show_ui("source_path")
show_ui("target_type")
show_ui("target_name")
def refresh_hostdev_page(self):
hostdev = self.get_hw_selection(HW_LIST_COL_DEVICE)
if not hostdev:
return
devtype = hostdev.type
pretty_name = None
nodedev = lookup_nodedev(self.vm.conn, hostdev)
if nodedev:
pretty_name = nodedev.pretty_name()
if not pretty_name:
pretty_name = build_hostdev_label(hostdev)[0] or "-"
devlabel = "<b>Physical %s Device</b>" % devtype.upper()
self.widget("hostdev-title").set_markup(devlabel)
self.widget("hostdev-source").set_text(pretty_name)
def refresh_video_page(self):
vid = self.get_hw_selection(HW_LIST_COL_DEVICE)
if not vid:
return
no_default = not self.is_customize_dialog
uihelpers.populate_video_combo(self.vm,
self.widget("video-model-combo"),
no_default=no_default)
model = vid.model_type
ram = vid.vram
heads = vid.heads
try:
ramlabel = ram and "%d MB" % (int(ram) / 1024) or "-"
except:
ramlabel = "-"
self.widget("video-ram").set_text(ramlabel)
self.widget("video-heads").set_text(heads and heads or "-")
self.set_combo_label("video-model", model,
label=vid.pretty_model(model))
def refresh_watchdog_page(self):
watch = self.get_hw_selection(HW_LIST_COL_DEVICE)
if not watch:
return
model = watch.model
action = watch.action
self.set_combo_label("watchdog-model", model)
self.set_combo_label("watchdog-action", action)
def refresh_controller_page(self):
dev = self.get_hw_selection(HW_LIST_COL_DEVICE)
if not dev:
return
type_label = virtinst.VirtualController.pretty_type(dev.type)
model_label = dev.model
if not model_label:
model_label = _("Default")
self.widget("controller-type").set_text(type_label)
combo = self.widget("controller-model-combo")
model = combo.get_model()
model.clear()
if dev.type == virtinst.VirtualController.CONTROLLER_TYPE_USB:
model.append(["Default", "Default"])
model.append(["ich9-ehci1", "USB 2"])
self.widget("config-remove").set_sensitive(False)
else:
self.widget("config-remove").set_sensitive(True)
self.set_combo_label("controller-model", model_label)
def refresh_filesystem_page(self):
dev = self.get_hw_selection(HW_LIST_COL_DEVICE)
if not dev:
return
self.widget("fs-type").set_text(dev.type)
# mode can be irrelevant depending on the fs driver type
# selected.
if dev.mode:
self.show_pair("fs-mode", True)
self.widget("fs-mode").set_text(dev.mode)
else:
self.show_pair("fs-mode", False)
self.widget("fs-driver").set_text(dev.driver or _("Default"))
self.widget("fs-wrpolicy").set_text(dev.wrpolicy or _("Default"))
self.widget("fs-source").set_text(dev.source)
self.widget("fs-target").set_text(dev.target)
if dev.readonly:
self.widget("fs-readonly").set_text("Yes")
else:
self.widget("fs-readonly").set_text("No")
def refresh_boot_page(self):
# Refresh autostart
try:
# Older libvirt versions return None if not supported
autoval = self.vm.get_autostart()
except libvirt.libvirtError:
autoval = None
# Autostart
autostart_chk = self.widget("config-autostart")
enable_autostart = (autoval is not None)
autostart_chk.set_sensitive(enable_autostart)
autostart_chk.set_active(enable_autostart and autoval or False)
show_kernel = not self.vm.is_container()
show_init = self.vm.is_container()
show_boot = (not self.vm.is_container() and not self.vm.is_xenpv())
self.widget("boot-order-align").set_property("visible", show_boot)
self.widget("boot-kernel-align").set_property("visible", show_kernel)
self.widget("boot-init-align").set_property("visible", show_init)
# Kernel/initrd boot
kernel, initrd, args = self.vm.get_boot_kernel_info()
expand = bool(kernel or initrd or args)
self.widget("boot-kernel").set_text(kernel or "")
self.widget("boot-kernel-initrd").set_text(initrd or "")
self.widget("boot-kernel-args").set_text(args or "")
if expand:
self.widget("boot-kernel-expander").set_expanded(True)
# <init> populate
init = self.vm.get_init()
self.widget("boot-init-path").set_text(init or "")
# Boot menu populate
menu = self.vm.get_boot_menu() or False
self.widget("boot-menu").set_active(menu)
self.repopulate_boot_list()
############################
# Hardware list population #
############################
def populate_disk_bus_combo(self, devtype, no_default):
buslist = self.widget("disk-bus-combo")
busmodel = buslist.get_model()
busmodel.clear()
buses = []
if devtype == virtinst.VirtualDisk.DEVICE_FLOPPY:
buses.append(["fdc", "Floppy"])
elif devtype == virtinst.VirtualDisk.DEVICE_CDROM:
buses.append(["ide", "IDE"])
if self.vm.rhel6_defaults():
buses.append(["scsi", "SCSI"])
else:
if self.vm.is_hvm():
buses.append(["ide", "IDE"])
if self.vm.rhel6_defaults():
buses.append(["scsi", "SCSI"])
buses.append(["usb", "USB"])
if self.vm.get_hv_type() in ["kvm", "test"]:
buses.append(["sata", "SATA"])
buses.append(["virtio", "Virtio"])
if (self.vm.get_hv_type() == "kvm" and
self.vm.get_machtype() == "pseries"):
buses.append(["spapr-vscsi", "sPAPR-vSCSI"])
if self.vm.conn.is_xen() or self.vm.get_hv_type() == "test":
buses.append(["xen", "Xen"])
for row in buses:
busmodel.append(row)
if not no_default:
busmodel.append([None, "default"])
def populate_hw_list(self):
hw_list_model = self.widget("hw-list").get_model()
hw_list_model.clear()
def add_hw_list_option(title, page_id, icon_name):
hw_list_model.append([title, icon_name,
Gtk.IconSize.LARGE_TOOLBAR,
page_id, title])
add_hw_list_option("Overview", HW_LIST_TYPE_GENERAL, "computer")
if not self.is_customize_dialog:
add_hw_list_option("Performance", HW_LIST_TYPE_STATS,
"utilities-system-monitor")
add_hw_list_option("Processor", HW_LIST_TYPE_CPU, "device_cpu")
add_hw_list_option("Memory", HW_LIST_TYPE_MEMORY, "device_mem")
add_hw_list_option("Boot Options", HW_LIST_TYPE_BOOT, "system-run")
self.repopulate_hw_list()
def repopulate_hw_list(self):
hw_list = self.widget("hw-list")
hw_list_model = hw_list.get_model()
currentDevices = []
def dev_cmp(origdev, newdev):
if isinstance(origdev, str):
return False
if origdev == newdev:
return True
if not origdev.get_xml_node_path():
return False
return origdev.get_xml_node_path() == newdev.get_xml_node_path()
def add_hw_list_option(idx, name, page_id, info, icon_name):
hw_list_model.insert(idx, [name, icon_name,
Gtk.IconSize.LARGE_TOOLBAR,
page_id, info])
def update_hwlist(hwtype, info, name, icon_name):
"""
See if passed hw is already in list, and if so, update info.
If not in list, add it!
"""
currentDevices.append(info)
insertAt = 0
for row in hw_list_model:
rowdev = row[HW_LIST_COL_DEVICE]
if dev_cmp(rowdev, info):
# Update existing HW info
row[HW_LIST_COL_DEVICE] = info
row[HW_LIST_COL_LABEL] = name
row[HW_LIST_COL_ICON_NAME] = icon_name
return
if row[HW_LIST_COL_TYPE] <= hwtype:
insertAt += 1
# Add the new HW row
add_hw_list_option(insertAt, name, hwtype, info, icon_name)
# Populate list of disks
for disk in self.vm.get_disk_devices():
devtype = disk.device
bus = disk.bus
idx = disk.disk_bus_index
icon = "drive-harddisk"
if devtype == "cdrom":
icon = "media-optical"
elif devtype == "floppy":
icon = "media-floppy"
if disk.address.type == "spapr-vio":
bus = "spapr-vscsi"
label = prettyify_disk(devtype, bus, idx)
update_hwlist(HW_LIST_TYPE_DISK, disk, label, icon)
# Populate list of NICs
for net in self.vm.get_network_devices():
mac = net.macaddr
update_hwlist(HW_LIST_TYPE_NIC, net,
"NIC %s" % mac[-9:], "network-idle")
# Populate list of input devices
for inp in self.vm.get_input_devices():
inptype = inp.type
icon = "input-mouse"
if inptype == "tablet":
label = _("Tablet")
icon = "input-tablet"
elif inptype == "mouse":
label = _("Mouse")
else:
label = _("Input")
update_hwlist(HW_LIST_TYPE_INPUT, inp, label, icon)
# Populate list of graphics devices
for gfx in self.vm.get_graphics_devices():
update_hwlist(HW_LIST_TYPE_GRAPHICS, gfx,
_("Display %s") % gfx.pretty_type_simple(gfx.type),
"video-display")
# Populate list of sound devices
for sound in self.vm.get_sound_devices():
update_hwlist(HW_LIST_TYPE_SOUND, sound,
_("Sound: %s" % sound.model), "audio-card")
# Populate list of char devices
for chardev in self.vm.get_char_devices():
devtype = chardev.virtual_device_type
port = chardev.target_port
label = devtype.capitalize()
if devtype not in ["console", "channel"]:
# Don't show port for console
label += " %s" % (int(port) + 1)
update_hwlist(HW_LIST_TYPE_CHAR, chardev, label,
"device_serial")
# Populate host devices
for hostdev in self.vm.get_hostdev_devices():
devtype = hostdev.type
label = build_hostdev_label(hostdev)[1]
if devtype == "usb":
icon = "device_usb"
else:
icon = "device_pci"
update_hwlist(HW_LIST_TYPE_HOSTDEV, hostdev, label, icon)
# Populate redir devices
for redirdev in self.vm.get_redirdev_devices():
bus = redirdev.bus
label = build_redir_label(redirdev)[1]
if bus == "usb":
icon = "device_usb"
else:
icon = "device_pci"
update_hwlist(HW_LIST_TYPE_REDIRDEV, redirdev, label, icon)
# Populate video devices
for vid in self.vm.get_video_devices():
update_hwlist(HW_LIST_TYPE_VIDEO, vid,
_("Video %s") % vid.pretty_model(vid.model_type),
"video-display")
# Populate watchdog devices
for watch in self.vm.get_watchdog_devices():
update_hwlist(HW_LIST_TYPE_WATCHDOG, watch, _("Watchdog"),
"device_pci")
# Populate controller devices
for cont in self.vm.get_controller_devices():
# skip USB2 ICH9 companion controllers
if cont.model in ["ich9-uhci1", "ich9-uhci2", "ich9-uhci3"]:
continue
pretty_type = virtinst.VirtualController.pretty_type(cont.type)
update_hwlist(HW_LIST_TYPE_CONTROLLER, cont,
_("Controller %s") % pretty_type,
"device_pci")
# Populate filesystem devices
for fs in self.vm.get_filesystem_devices():
target = fs.target[:8]
update_hwlist(HW_LIST_TYPE_FILESYSTEM, fs,
_("Filesystem %s") % target,
Gtk.STOCK_DIRECTORY)
# Populate list of smartcard devices
for sc in self.vm.get_smartcard_devices():
update_hwlist(HW_LIST_TYPE_SMARTCARD, sc,
_("Smartcard"), "device_serial")
devs = range(len(hw_list_model))
devs.reverse()
for i in devs:
_iter = hw_list_model.iter_nth_child(None, i)
olddev = hw_list_model[i][HW_LIST_COL_DEVICE]
# Existing device, don't remove it
if type(olddev) is str or olddev in currentDevices:
continue
hw_list_model.remove(_iter)
def repopulate_boot_list(self, bootdevs=None, dev_select=None):
boot_list = self.widget("config-boot-list")
boot_model = boot_list.get_model()
old_order = [x[BOOT_DEV_TYPE] for x in boot_model]
boot_model.clear()
if bootdevs is None:
bootdevs = self.vm.get_boot_device()
boot_rows = {
"hd" : ["hd", "Hard Disk", "drive-harddisk", False],
"cdrom" : ["cdrom", "CDROM", "media-optical", False],
"network" : ["network", "Network (PXE)", "network-idle", False],
"fd" : ["fd", "Floppy", "media-floppy", False],
}
for dev in bootdevs:
foundrow = None
for key, row in boot_rows.items():
if key == dev:
foundrow = row
del(boot_rows[key])
break
if not foundrow:
# Some boot device listed that we don't know about.
foundrow = [dev, "Boot type '%s'" % dev,
"drive-harddisk", True]
foundrow[BOOT_ACTIVE] = True
boot_model.append(foundrow)
# Append all remaining boot_rows that aren't enabled
for dev in old_order:
if dev in boot_rows:
boot_model.append(boot_rows[dev])
del(boot_rows[dev])
for row in boot_rows.values():
boot_model.append(row)
boot_list.set_model(boot_model)
selection = boot_list.get_selection()
if dev_select:
idx = 0
for row in boot_model:
if row[BOOT_DEV_TYPE] == dev_select:
break
idx += 1
boot_list.get_selection().select_path(str(idx))
elif not selection.get_selected()[1]:
# Set a default selection
selection.select_path("0")
def show_pair(self, basename, show):
combo = self.widget(basename)
label = self.widget(basename + "-title")
combo.set_property("visible", show)
label.set_property("visible", show)
|
import logging
import gobject
import gtk
from .wraplabel import WrapLabel
_logger = logging.getLogger("hotwire.ui.MsgArea")
class MsgArea(gtk.HBox):
__gtype_name__ = "MsgArea"
__gsignals__ = {
"response" : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_INT,)),
"close" : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, [])
}
def __init__(self, buttons, **kwargs):
super(MsgArea, self).__init__(**kwargs)
self.__contents = None
self.__labels = []
self.__changing_style = False
self.__main_hbox = gtk.HBox(False, 16) # FIXME: use style properties
self.__main_hbox.show()
self.__main_hbox.set_border_width(8) # FIXME: use style properties
self.__action_area = gtk.VBox(True, 4); # FIXME: use style properties
self.__action_area.show()
self.__main_hbox.pack_end (self.__action_area, False, True, 0)
self.pack_start(self.__main_hbox, True, True, 0)
self.set_app_paintable(True)
self.connect("expose-event", self.__paint)
# Note that we connect to style-set on one of the internal
# widgets, not on the message area itself, since gtk does
# not deliver any further style-set signals for a widget on
# which the style has been forced with gtk_widget_set_style()
self.__main_hbox.connect("style-set", self.__on_style_set)
self.add_buttons(buttons)
def __get_response_data(self, w, create):
d = w.get_data('hotwire-msg-area-data')
if (d is None) and create:
d = {'respid': None}
w.set_data('hotwire-msg-area-data', d)
return d
def __find_button(self, respid):
children = self.__actionarea.get_children()
for child in children:
rd = self.__get_response_data(child, False)
if rd is not None and rd['respid'] == respid:
return child
def __close(self):
cancel = self.__find_button(gtk.RESPONSE_CANCEL)
if cancel is None:
return
self.response(gtk.RESPONSE_CANCEL)
def __paint(self, w, event):
gtk.Style.paint_flat_box(w.style,
w.window,
gtk.STATE_NORMAL,
gtk.SHADOW_OUT,
None,
w,
"tooltip",
w.allocation.x + 1,
w.allocation.y + 1,
w.allocation.width - 2,
w.allocation.height - 2)
return False
def __on_style_set(self, w, style):
if self.__changing_style:
return
# This is a hack needed to use the tooltip background color
window = gtk.Window(gtk.WINDOW_POPUP);
window.set_name("gtk-tooltip")
window.ensure_style()
style = window.get_style()
self.__changing_style = True
self.set_style(style)
for label in self.__labels:
label.set_style(style)
self.__changing_style = False
window.destroy()
self.queue_draw()
def __get_response_for_widget(self, w):
rd = self.__get_response_data(w, False)
if rd is None:
return gtk.RESPONSE_NONE
return rd['respid']
def __on_action_widget_activated(self, w):
response_id = self.__get_response_for_widget(w)
self.response(response_id)
def add_action_widget(self, child, respid):
rd = self.__get_response_data(child, True)
rd['respid'] = respid
if not isinstance(child, gtk.Button):
raise ValueError("Can only pack buttons as action widgets")
child.connect('clicked', self.__on_action_widget_activated)
if respid != gtk.RESPONSE_HELP:
self.__action_area.pack_start(child, False, False, 0)
else:
self.__action_area.pack_end(child, False, False, 0)
def set_contents(self, contents):
self.__contents = contents
self.__main_hbox.pack_start(contents, True, True, 0)
def add_button(self, btext, respid):
button = gtk.Button(stock=btext)
button.set_focus_on_click(False)
button.set_flags(gtk.CAN_DEFAULT)
button.show()
self.add_action_widget(button, respid)
return button
def add_buttons(self, args):
_logger.debug("init buttons: %r", args)
for (btext, respid) in args:
self.add_button(btext, respid)
def set_response_sensitive(self, respid, setting):
for child in self.__action_area.get_children():
rd = self.__get_response_data(child, False)
if rd is not None and rd['respid'] == respid:
child.set_sensitive(setting)
break
def set_default_response(self, respid):
for child in self.__action_area.get_children():
rd = self.__get_response_data(child, False)
if rd is not None and rd['respid'] == respid:
child.grab_default()
break
def response(self, respid):
self.emit('response', respid)
def add_stock_button_with_text(self, text, stockid, respid):
b = gtk.Button(label=text)
b.set_focus_on_click(False)
img = gtk.Image()
img.set_from_stock(stockid, gtk.ICON_SIZE_BUTTON)
b.set_image(img)
b.show_all()
self.add_action_widget(b, respid)
return b
def set_text_and_icon(self, stockid, primary_text, secondary_text=None):
hbox_content = gtk.HBox(False, 8)
hbox_content.show()
image = gtk.Image()
image.set_from_stock(stockid, gtk.ICON_SIZE_DIALOG)
image.show()
hbox_content.pack_start(image, False, False, 0)
image.set_alignment(0.5, 0.5)
vbox = gtk.VBox(False, 6)
vbox.show()
hbox_content.pack_start (vbox, True, True, 0)
self.__labels = []
primary_markup = "<b>%s</b>" % (primary_text,)
primary_label = WrapLabel(primary_markup)
primary_label.show()
vbox.pack_start(primary_label, True, True, 0)
primary_label.set_use_markup(True)
primary_label.set_line_wrap(True)
primary_label.set_alignment(0, 0.5)
primary_label.set_flags(gtk.CAN_FOCUS)
primary_label.set_selectable(True)
self.__labels.append(primary_label)
if secondary_text:
secondary_markup = "<small>%s</small>" % (secondary_text,)
secondary_label = WrapLabel(secondary_markup)
secondary_label.show()
vbox.pack_start(secondary_label, True, True, 0)
secondary_label.set_flags(gtk.CAN_FOCUS)
secondary_label.set_use_markup(True)
secondary_label.set_line_wrap(True)
secondary_label.set_selectable(True)
secondary_label.set_alignment(0, 0.5)
self.__labels.append(secondary_label)
self.set_contents(hbox_content)
class MsgAreaController(gtk.HBox):
__gtype_name__ = "MsgAreaController"
def __init__(self):
super(MsgAreaController, self).__init__()
self.__msgarea = None
self.__msgid = None
def has_message(self):
return self.__msgarea is not None
def get_msg_id(self):
return self.__msgid
def set_msg_id(self, msgid):
self.__msgid = msgid
def clear(self):
if self.__msgarea is not None:
self.remove(self.__msgarea)
self.__msgarea.destroy()
self.__msgarea = None
self.__msgid = None
def new_from_text_and_icon(self, stockid, primary, secondary=None, buttons=[]):
self.clear()
msgarea = self.__msgarea = MsgArea(buttons)
msgarea.set_text_and_icon(stockid, primary, secondary)
self.pack_start(msgarea, expand=True)
return msgarea
|
"""
/***************************************************************************
BirdChooserDialog
A QGIS plugin
Show bird observations
-------------------
begin : 2015-11-05
git sha : $Format:%H$
copyright : (C) 2015 by Jerome
email : jerome@guelat.ch
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
import os
import psycopg2
from PyQt4 import QtGui, uic
from qgis.core import QgsDataSourceURI, QgsVectorLayer, QgsMapLayerRegistry, QgsMarkerSymbolV2, QgsMessageLog
FORM_CLASS, _ = uic.loadUiType(os.path.join(
os.path.dirname(__file__), 'bird_chooser_dialog_base.ui'))
class BirdChooserDialog(QtGui.QDialog, FORM_CLASS):
def __init__(self, iface, parent=None):
"""Constructor."""
super(BirdChooserDialog, self).__init__(parent)
# Set up the user interface from Designer.
# After setupUI you can access any designer object by doing
# self.<objectname>, and you can use autoconnect slots - see
# http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
# #widgets-and-dialogs-with-auto-connect
self.setupUi(self)
self.iface = iface
# Connecter les slots
self._connectSlots()
#self.conn = psycopg2.connect(database = "jguelat", user = "jguelat", password = "")
self.conn = psycopg2.connect(service = "local_jguelat")
def _connectSlots(self):
self.tableCombo.activated.connect(self.getSpecies)
# Quand la fenetre est fermee (d'une maniere ou d'une autre)
self.finished.connect(self.closeConnection)
self.addLayerButton.clicked.connect(self.addLayer)
def getSpecies(self):
self.speciesCombo.clear()
cur = self.conn.cursor()
cur.execute("SELECT DISTINCT species_id from " + self.tableCombo.currentText() + " ORDER BY species_id")
rows = cur.fetchall()
self.speciesCombo.addItems([str(elem[0]) for elem in rows])
self.addLayerButton.setEnabled(True)
cur.close()
def addLayer(self):
uri = QgsDataSourceURI()
# set host name, port, database name, username and password
#uri.setConnection("localhost", "5432", "jguelat", "jguelat", "")
uri.setConnection("local_jguelat", "", "", "")
# set database schema, table name, geometry column and optionally subset (WHERE clause)
uri.setDataSource("public", self.tableCombo.currentText(), "geom", "species_id = " + self.speciesCombo.currentText())
#vlayer = self.iface.addVectorLayer(uri.uri(), "Species " + self.speciesCombo.currentText(), "postgres")
vlayer = QgsVectorLayer(uri.uri(), "Species " + self.speciesCombo.currentText(), "postgres")
props = vlayer.rendererV2().symbol().symbolLayer(0).properties()
props['size'] = '3'
props['color'] = 'blue'
vlayer.rendererV2().setSymbol(QgsMarkerSymbolV2.createSimple(props))
QgsMapLayerRegistry.instance().addMapLayer(vlayer)
QgsMessageLog.logMessage("Tout est OK", 'BirdChooser', QgsMessageLog.INFO)
def closeConnection(self):
self.conn.close()
|
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^$', views.channel_list),
url(r'^play', views.play_channel),
url(r'^hello', views.hello),
]
|
from django.conf import settings
from geopy import distance, geocoders
import pygeoip
def get_geodata_by_ip(addr):
gi = pygeoip.GeoIP(settings.GEO_CITY_FILE, pygeoip.MEMORY_CACHE)
geodata = gi.record_by_addr(addr)
return geodata
def get_geodata_by_region(*args):
gn = geocoders.GeoNames()
return gn.geocode(' '.join(args), exactly_one=False)[0]
def get_distance(location1, location2):
"""
Calculate distance between two locations, given the (lat, long) of each.
Required Arguments:
location1
A tuple of (lat, long).
location2
A tuple of (lat, long).
"""
return distance.distance(location1, location2).miles
|
import requests
import sys
class NotSupported(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class PasteSite(object):
def __init__(self, url):
self.url = url
self.paste_url = None
self.data = None
@staticmethod
def siteFactory(site_name):
if site_name == 'slexy.org':
return Slexy()
elif site_name == 'pastebin.mozilla.org':
return Mozilla()
else:
raise NotSupported("This site is not supported")
def parse(self, args):
""" Internal method used by the PasteSite class.
Returns a dictionary of the parsed input arguments.
Parses the arguments given at the command line.
Many pastebin like sites use different arguments
for the paste so this method should be implemented
for each subclass of PasteSite.
See the slexy class for an example of how to implement
this method for subclasses.
"""
self.data = args
def paste(self):
"""Posts the data to the paste site.
This method tries to post the data to the paste site.
If the resulting request does not have a ok status the
program exits else we return the resulting paste url.
The method assumes that the data is in a dictionary.
"""
if self.data == None:
print('You can only paste after a parse')
sys.exit(-1)
res = requests.post(self.url, self.data)
if not res.ok:
print('Bad response {0} {1}'.format(res.reason, res.status_code))
sys.exit(-1)
self.paste_url = res.url
class Slexy(PasteSite):
def __init__(self):
super(Slexy, self).__init__('http://slexy.org/submit')
def parse(self, args):
form_data = {}
arg_translation = {'text' : 'raw_paste',
'language' : 'language',
'expiration' : 'expire',
'comment' : 'comment',
'description' : 'descr',
'visibility' : 'permissions',
'linum' : 'linenumbers',
'author' : 'author'}
for k,v in args.items():
if arg_translation.get(k):
form_data[arg_translation[k]] = v
form_data['submit'] = 'Submit Paste'
self.data = form_data
class Mozilla(PasteSite):
def __init__(self):
super(Mozilla, self).__init__('https://pastebin.mozilla.org')
def parse(self, args):
form_data = {}
arg_translation = {'text' : 'code2',
'expiration' : 'expiry',
'syntax_highlight' : 'format',
'author' : 'poster'}
for k,v in args.items():
if arg_translation.get(k):
form_data[arg_translation[k]] = v
form_data['paste'] = 'Send'
form_data['parent_pid'] = ''
self.data = form_data
|
import os
import string
import random
import logging
from thug.ActiveX.modules import WScriptShell
from thug.ActiveX.modules import TextStream
from thug.ActiveX.modules import File
from thug.ActiveX.modules import Folder
from thug.OS.Windows import win32_files
from thug.OS.Windows import win32_folders
log = logging.getLogger("Thug")
def BuildPath(self, arg0, arg1): # pylint:disable=unused-argument
log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] BuildPath("{arg0}", "{arg1}")')
return f"{arg0}\\{arg1}"
def CopyFile(self, source, destination, overwritefiles = False): # pylint:disable=unused-argument
log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] CopyFile("{source}", "{destination}")')
log.TextFiles[destination] = log.TextFiles[source]
def DeleteFile(self, filespec, force = False): # pylint:disable=unused-argument
log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] DeleteFile("{filespec}", {force})')
def CreateTextFile(self, filename, overwrite = False, _unicode = False): # pylint:disable=unused-argument
log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] CreateTextFile("{filename}", '
f'"{overwrite}", '
f'"{_unicode}")')
stream = TextStream.TextStream()
stream._filename = filename
return stream
def CreateFolder(self, path): # pylint:disable=unused-argument
log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] CreateFolder("{path}")')
return Folder.Folder(path)
def FileExists(self, filespec): # pylint:disable=unused-argument
log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] FileExists("{filespec}")')
if not filespec:
return True
if filespec.lower() in win32_files:
return True
if getattr(log, "TextFiles", None) and filespec in log.TextFiles:
return True
return False
def FolderExists(self, folder): # pylint:disable=unused-argument
log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] FolderExists("{folder}")')
return str(folder).lower() in win32_folders
def GetExtensionName(self, path): # pylint:disable=unused-argument
log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] GetExtensionName("{path}")')
ext = os.path.splitext(path)[1]
return ext if ext else ""
def GetFile(self, filespec): # pylint:disable=unused-argument
log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] GetFile("{filespec}")')
return File.File(filespec)
def GetSpecialFolder(self, arg):
log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] GetSpecialFolder("{arg}")')
arg = int(arg)
folder = ''
if arg == 0:
folder = WScriptShell.ExpandEnvironmentStrings(self, "%windir%")
elif arg == 1:
folder = WScriptShell.ExpandEnvironmentStrings(self, "%SystemRoot%\\system32")
elif arg == 2:
folder = WScriptShell.ExpandEnvironmentStrings(self, "%TEMP%")
log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] Returning {folder} for GetSpecialFolder("{arg}")')
return folder
def GetTempName(self): # pylint:disable=unused-argument
log.ThugLogging.add_behavior_warn('[Scripting.FileSystemObject ActiveX] GetTempName()')
return ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(8))
def MoveFile(self, source, destination): # pylint:disable=unused-argument
log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] MoveFile("{source}", "{destination}")')
log.TextFiles[destination] = log.TextFiles[source]
del log.TextFiles[source]
def OpenTextFile(self, sFilePathAndName, ForWriting = True, flag = True):
log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] OpenTextFile("{sFilePathAndName}", '
f'"{ForWriting}" ,'
f'"{flag}")')
log.ThugLogging.log_exploit_event(self._window.url,
"Scripting.FileSystemObject ActiveX",
"OpenTextFile",
data = {
"filename" : sFilePathAndName,
"ForWriting": ForWriting,
"flag" : flag
},
forward = False)
if getattr(log, 'TextFiles', None) is None:
log.TextFiles = {}
if sFilePathAndName in log.TextFiles:
return log.TextFiles[sFilePathAndName]
stream = TextStream.TextStream()
stream._filename = sFilePathAndName
if log.ThugOpts.local and sFilePathAndName in (log.ThugLogging.url, ): # pragma: no cover
with open(sFilePathAndName, encoding = 'utf-8', mode = 'r') as fd:
data = fd.read()
stream.Write(data)
log.TextFiles[sFilePathAndName] = stream
return stream
|
from __future__ import absolute_import
import sys
import inspect
import unittest
from mock import patch
from mock import MagicMock
from . import get_driver
from . import get_driver_class
from . import get_driver_names
from .driverbase import VirtDeployDriverBase
if sys.version_info[0] == 3: # pragma: no cover
builtin_import = 'builtins.__import__'
else: # pragma: no cover
builtin_import = '__builtin__.__import__'
def try_import(spec):
def fake_import(name, globals={}, locals={}, fromlist=[], level=0):
try:
return spec(name, globals, locals, fromlist, level)
except ImportError:
return MagicMock()
return fake_import
class TestVirtDeployDriverBase(unittest.TestCase):
def _get_driver_methods(self):
return inspect.getmembers(VirtDeployDriverBase, inspect.ismethod)
def _get_driver_class(self, name):
with patch(builtin_import, spec=True, new_callable=try_import):
return get_driver_class(name)
def _get_driver(self, name):
with patch(builtin_import, spec=True, new_callable=try_import):
return get_driver(name)
def test_base_not_implemented(self):
driver = VirtDeployDriverBase()
for name, method in self._get_driver_methods():
spec = inspect.getargspec(method)
with self.assertRaises(NotImplementedError) as cm:
getattr(driver, name)(*(None,) * (len(spec.args) - 1))
self.assertEqual(cm.exception.args[0], name)
def test_drivers_interface(self):
for driver_name in get_driver_names():
driver = self._get_driver_class(driver_name)
for name, method in self._get_driver_methods():
driver_method = getattr(driver, name)
self.assertNotEqual(driver_method, method)
self.assertEqual(inspect.getargspec(method),
inspect.getargspec(driver_method))
def test_get_drivers(self):
for driver_name in get_driver_names():
driver = self._get_driver(driver_name)
self.assertTrue(isinstance(driver, VirtDeployDriverBase))
|
'''
This file is part of the lenstractor project.
Copyright 2012 David W. Hogg (NYU) and Phil Marshall (Oxford).
Description
-----------
General-purpose data management classes and functions:
* Order a pile of FITS files into scifiles and matching varfiles
* Read in a deck of postcard images in FITS files and return an
array of tractor image data structures.
'''
import numpy as np
import os,glob,string,pyfits,subprocess
from astrometry.util import util
import tractor
import lenstractor
def Riffle(filenames,vb=False):
if vb: print "Looking at",len(filenames),"files: ",filenames
# Break down file names. Naming convention: fruit_flavor.fits
fruits = []
flavors = []
for filename in set(filenames):
pieces = string.split(filename,'_')
fruits.append(string.join(pieces[0:-1],'_'))
flavors.append(string.split(pieces[-1],'.')[0])
if len(set(flavors)) > 2:
raise ValueError("ERROR: expecting 1 or 2 flavors of datafile, got more")
elif len(set(flavors)) == 0:
raise ValueError("ERROR: expecting 1 or 2 flavors of datafile, got none")
if 'sci' not in set(flavors):
raise ValueError("ERROR: expecting at least some files to be xxx_sci.fits")
if len(set(flavors)) == 1:
whttype = 'No-one_will_ever_choose_this_flavor'
else:
for x in (set(flavors) - set(['sci'])):
whttype = x
number = len(set(fruits))
scifiles = []
whtfiles = []
for fruit in set(fruits):
x = fruit+'_sci.fits'
if os.path.exists(x):
scifiles.append(x)
else:
scifiles.append(None)
x = fruit+'_'+whttype+'.fits'
if os.path.exists(x):
whtfiles.append(x)
else:
whtfiles.append(None)
if vb:
print "Riffled files into",number,"pair(s)"
if len(set(flavors)) == 1:
print "Only 1 flavor of file found, sci"
else:
print "2 flavors of file found: sci and",whttype
for i in range(number):
print " ",i+1,"th pair:",[scifiles[i],whtfiles[i]]
return scifiles,whtfiles
def Deal(scifiles,varfiles,SURVEY='PS1',vb=False):
images = []
bands = []
epochs = []
centroids = []
total_mags = []
for scifile,varfile in zip(scifiles,varfiles):
name = scifile.replace('_sci.fits','')
if vb:
print " "
print "Making Tractor image from "+name+"_*.fits:"
# Read in sci and wht images. Note assumptions about file format:
sci,invvar,hdr,total_flux = Read_in_data(scifile,varfile,SURVEY=SURVEY,vb=vb)
if total_flux == 0.0:
print "No flux found in image from "+scifile
print "Skipping to next image!"
continue
# Initialize a PSF object (single Gaussian by default), first
# getting FWHM from somewhere. Start with FWHM a little small,
# then refine it:
if SURVEY=='PS1':
try:
FWHM = lenstractor.PS1_IQ(hdr)
except:
FWHM = 1.4
elif SURVEY=='KIDS':
FWHM = lenstractor.KIDS_IQ(hdr)
elif SURVEY=='SDSS':
try:
FWHM = lenstractor.SDSS_IQ(hdr)
except:
FWHM = 'NaN'
if FWHM == 'NaN':
print "Problem with initialising PSF for SDSS, using (1.4,0.4) default"
FWHM = 1.4/0.4
else:
raise ValueError('Unrecognised survey name '+SURVEY)
if vb: print " PSF FWHM =",FWHM,"pixels"
# MAGIC shrinkage factor:
shrink = 0.8
psf = Initial_PSF(shrink*FWHM)
if vb: print psf
# Now get the photometric calibration from the image header.
if SURVEY=='PS1':
try:
band,photocal = lenstractor.PS1_photocal(hdr)
except:
band,photocal = lenstractor.SDSS_photocal(hdr)
elif SURVEY=='KIDS':
band,photocal = lenstractor.KIDS_photocal(hdr)
elif SURVEY=='SDSS':
band,photocal = lenstractor.SDSS_photocal(hdr)
else:
print "Unrecognised survey name "+SURVEY+", assuming SDSS"
band,photocal = lenstractor.SDSS_photocal(hdr)
if vb: print photocal
bands.append(band)
if SURVEY=='PS1':
try:
epochs.append(lenstractor.PS1_epoch(hdr))
except:
epochs.append(lenstractor.SDSS_epoch(hdr))
elif SURVEY=='KIDS':
epochs.append(lenstractor.KIDS_epoch(hdr))
elif SURVEY=='SDSS':
epochs.append(lenstractor.SDSS_epoch(hdr))
# Use photocal to return a total magnitude:
total_mag = photocal.countsToMag(total_flux)
if vb: print "Total brightness of image (mag):",total_mag
total_mags.append(total_mag)
# Set up sky to be varied:
median = np.median(sci[invvar > 0])
sky = tractor.ConstantSky(median)
delta = 0.1*np.sqrt(1.0/np.sum(invvar))
assert delta > 0
sky.stepsize = delta
if vb: print sky
# Get WCS from FITS header:
if SURVEY=='PS1':
try:
wcs = lenstractor.PS1WCS(hdr)
except:
wcs = lenstractor.SDSSWCS(hdr)
elif SURVEY=='KIDS':
wcs = lenstractor.KIDSWCS(hdr)
else:
try:
wcs = lenstractor.SDSSWCS(hdr)
except:
wcs = lenstractor.SDSSWCS(hdr)
# if vb:
# print wcs
# Compute flux-weighted centroid, in world coordinates:
NX,NY = sci.shape
x = np.outer(np.ones(NX),np.linspace(0,NY-1,NY))
y = np.outer(np.linspace(0,NX-1,NX),np.ones(NY))
x0 = np.sum(sci*x)/np.sum(sci)
y0 = np.sum(sci*y)/np.sum(sci)
# BUG: this returns pretty much the image center, not
# the object center... Need a better object finder!
radec = wcs.pixelToPosition(x0,y0)
centroids.append(radec)
print "Flux centroid: ",radec
# Make a tractor Image object out of all this stuff, and add it to the array:
images.append(tractor.Image(data=sci, invvar=invvar, name=name,
psf=psf, wcs=wcs, sky=sky, photocal=photocal))
# Figure out the unique band names and epochs:
uniqbands = np.unique(np.array(bands))
if vb:
print " "
print "Read in",len(images),"image datasets"
print " in",len(uniqbands),"bands:",uniqbands
print " at",len(epochs),"epochs"
print " "
return images,centroids,np.array(total_mags),np.array(bands)
def Read_in_data(scifile,varfile,SURVEY='PS1',vb=False):
hdulist = pyfits.open(scifile)
sci = hdulist[0].data
hdr = hdulist[0].header
hdulist.close()
NX,NY = sci.shape
if (varfile is not None):
hdulist = pyfits.open(varfile)
var = hdulist[0].data
hdulist.close()
else:
# Make a var image from the sci image...
background = np.median(sci)
diffimage = sci - background
# Get the flux-to-count conversion factor from header, at least in SDSS:
try:
tmpsurvey = hdr['ORIGIN']
if (tmpsurvey == 'SDSS'):
tempmtoc = hdr['NMGY']
else:
tempmtoc = 1.
except:
tempmtoc = 1.
background, diffimage = background/tempmtoc, diffimage/tempmtoc # units: counts
variance = np.median(diffimage*diffimage) # sky count variance
var = diffimage + variance # variance in the whole image number-counts
# Go again in fluxes
var = (tempmtoc**2)*var
# Ensure positivity:
var[var <= 0] = variance*(tempmtoc**2)
# Check image sizes...
assert sci.shape == var.shape
if SURVEY == 'KIDS':
# Var image is actually already an inverse variance image!
invvar = var.copy()
var = 1.0/invvar
else:
# Convert var to wht, and find median uncertainty as well:
# Regardless of maggy-count conversion, start again here:
invvar = 1.0/var
# Assign zero weight to var=nan, var<=0:
invvar[var != var] = 0.0
invvar[var <= 0] = 0.0
bad = np.where(invvar == 0)
# Zero out sci image where wht is 0.0:
sci[bad] = 0.0
assert(all(np.isfinite(sci.ravel())))
assert(all(np.isfinite(invvar.ravel())))
# Measure total flux in sci image:
# total_flux = np.sum(sci)
# background-subtracted
background = np.median(sci)
diffimage = sci - background
total_flux = np.sum(diffimage)
# Report on progress so far:
if vb:
print 'Science image:', sci.shape #, sci
print 'Total flux:', total_flux
print 'Variance image:', var.shape #, var
if total_flux != 0.0:
# Very rough estimates of background level and rms, never used:
good = np.where(invvar > 0)
sciback = np.median(sci[good])
scirms = np.sqrt(np.median(var[good]))
if vb:
print 'Useful variance range:', var[good].min(), var[good].max()
print 'Useful image median level:', sciback
print 'Useful image median pixel uncertainty:', scirms
return sci,invvar,hdr,total_flux
def Initial_PSF(FWHM,double=False):
# NB. FWHM of PSF is given in pixels.
if not double:
# Single Gaussian default:
w = np.array([1.0]) # amplitude at peak
mu = np.array([[0.0,0.0]]) # centroid position in pixels
var = (FWHM/2.35)**2.0
cov = np.array([[[var,0.0],[0.0,var]]]) # pixels^2, covariance matrix
else:
# Double Gaussian alternative:
w = np.array([1.0,1.0])
mu = np.array([[0.0,0.0],[0.0,0.0]])
var = (FWHM/2.35)**2.0
cov = np.array([[[1.0,0.0],[0.0,1.0]],[[var,0.0],[0.0,var]]])
return tractor.GaussianMixturePSF(w,mu,cov)
def Turnover(allbands,allmagnitudes,allcentroids,vb=False):
# Models need good initial fluxes to avoid wasting time getting these
# right. Take a quick look at the data to do this:
# 1) Get rough idea of object position from wcs of first image - works
# OK if all images are the same size and well registered, and the
# target is in the center of the field...
ra, dec = 0.0, 0.0
for radec in allcentroids:
ra += radec.ra
dec += radec.dec
ra, dec = ra/len(allcentroids), dec/len(allcentroids)
centroid = tractor.RaDecPos(ra,dec)
print "Mean flux-weighted centroid: ",centroid
# 2) Get rough idea of total object magnitudes from median of images
# in each filter. (Models have non-variable flux, by assumption!)
bandnames = np.unique(allbands)
magnitudes = np.zeros(len(bandnames))
for i,bandname in enumerate(bandnames):
index = np.where(allbands == bandname)
magnitudes[i] = np.median(allmagnitudes[index])
SED = tractor.Mags(order=bandnames, **dict(zip(bandnames,magnitudes)))
if vb: print "Mean SED: ",SED
return centroid,SED
if __name__ == '__main__':
if True:
# Basic test on lenstractor examples dir:
folder = os.environ['LENSTRACTOR_DIR']+'/examples'
inputfiles = glob.glob(os.path.join(folder,'*.fits'))
scifiles,varfiles = riffle(inputfiles)
|
"""
This file is part of quiedit.
quiedit is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
quiedit is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with quiedit. If not, see <http://www.gnu.org/licenses/>.
"""
from PyQt4 import QtGui, QtCore
import yaml
class theme(object):
"""Handles theming."""
def __init__(self, editor):
"""
Constructor.
Arguments:
editor -- A qtquiedit object.
"""
self.editor = editor
self.themeDict = yaml.load(open(self.editor.get_resource( \
u'themes.yaml')).read())
self.theme = self.recTheme(self.editor.theme)
def apply(self):
"""Applies the theme."""
stylesheet = u"""
background: %(editor_background)s;
color: %(font_color)s;
selection-color: %(editor_background)s;
selection-background-color: %(font_color)s;
font-family: %(font_family)s;
font-size: %(font_size)spt;
""" % self.theme
self.editor.main_widget.setStyleSheet(u"background: %s;" \
% self.theme[u"main_background"])
self.editor.editor_frame.setStyleSheet(u"color: %s;" \
% self.theme[u"border_color"])
self.editor.search_box.setStyleSheet(stylesheet)
self.editor.search_edit.setStyleSheet(u"border: 0;")
self.editor.search_edit.setFont(self.font())
self.editor.search_label.setFont(self.font())
self.editor.command_box.setStyleSheet(stylesheet)
self.editor.command_edit.setStyleSheet(u"border: 0;")
self.editor.command_edit.setFont(self.font())
self.editor.command_label.setFont(self.font())
self.editor.status.setFont(self.font())
self.editor.status.setStyleSheet(u"color: %s;" % self.theme[ \
u"status_color"])
self.editor.central_widget.setMinimumWidth(int(self.theme[ \
u"editor_width"]))
self.editor.central_widget.setMaximumWidth(int(self.theme[ \
u"editor_width"]))
# Apply the theme to all quieditors
for quieditor in self.editor.editor, self.editor.help, \
self.editor._markdown:
quieditor.setStyleSheet(stylesheet)
if not self.theme[u"scrollbar"]:
quieditor.setVerticalScrollBarPolicy( \
QtCore.Qt.ScrollBarAlwaysOff)
quieditor.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
# Apply the theme to the preferences screen
self.editor.prefs.setStyleSheet(stylesheet)
# Redo spellingcheck in the editor
self.editor.editor.check_entire_document()
# Hide the cursor for the main screen
self.editor.setCursor(QtCore.Qt.BlankCursor)
def font(self):
"""
Gives the theme font.
Returns:
A QFont.
"""
font = QtGui.QFont()
font.setPointSize(int(self.theme[u'font_size']))
font.setFamily(self.theme[u'font_family'])
return font
def recTheme(self, theme):
"""
Gets the current theme, respecting inheritance.
Arguments:
theme -- The theme name.
Returns:
A dictionary with with the theme information.
"""
if theme not in self.themeDict:
print(u'theme.__init__(): %s is not a valid theme' % theme)
theme = u'default'
d = self.themeDict[theme]
if u'inherits' in d:
_d = self.recTheme(d[u'inherits'])
for key, val in _d.items():
if key not in d:
d[key] = val
return d
|
import common
import connection
import m3u8
import base64
import os
import ustvpaths
import re
import simplejson
import sys
import time
import urllib
import xbmc
import xbmcaddon
import xbmcgui
import xbmcplugin
from bs4 import BeautifulSoup, SoupStrainer
addon = xbmcaddon.Addon()
pluginHandle = int(sys.argv[1])
def masterlist(SITE, SHOWS):
master_db = []
master_data = connection.getURL(SHOWS)
master_tree = simplejson.loads(master_data)
for master_item in master_tree:
if (master_item['hasNoVideo'] == 'false'):
#print master_item
try:
master_name = common.smart_unicode(master_item['detailTitle'])
master_db.append((master_name, SITE, 'seasons', urllib.quote_plus(master_item['showID'])))
except Exception,e:
print "Exception", e, master_item
return master_db
def seasons(SITE, SEASONSEPISODE, SEASONSCLIPS, EPISODES, CLIPS, season_url = common.args.url):
seasons = []
season_data = connection.getURL(SEASONSEPISODE % season_url)
season_tree = simplejson.loads(season_data)['season']
for season_item in season_tree:
season_name = 'Season ' + str(season_item)
seasons.append((season_name, SITE, 'episodes', EPISODES % (season_url, season_item), -1, -1))
season_url = common.args.url
season_data = connection.getURL(SEASONSCLIPS % season_url)
season_tree = simplejson.loads(season_data)['season']
for season_item in season_tree:
season_name = 'Season Clips ' + str(season_item)
seasons.append((season_name, SITE, 'episodes', CLIPS % (season_url, season_item), -1, -1))
return seasons
def episodes(SITE, episode_url = common.args.url):
episodes = []
episode_data = connection.getURL(episode_url)
episode_tree = simplejson.loads(episode_data)['Items']
for episode_item in episode_tree:
if episode_item['isBehindWall'] == 'false':
url = episode_item['playURL_HLS']
episode_duration = int(episode_item['totalVideoDuration']) / 1000
try:
episode_airdate = common.format_date(episode_item['airDate'].split('T')[0],'%Y-%m-%d')
except:
episode_airdate = -1
episode_name = episode_item['title']
try:
season_number = int(episode_item['season'])
except:
season_number = -1
try:
episode_number = int(episode_item['episode'])
except:
episode_number = -1
try:
episode_thumb = episode_item['thumbnailImageURL']
except:
try:
episode_thumb = episode_item['stillImageURL']
except:
try:
episode_thumb = episode_item['modalImageURL']
except:
episode_thumb = None
episode_plot = episode_item['description']
episode_showtitle = episode_item['seriesName']
try:
episode_mpaa = episode_item['rating'].upper()
except:
episode_mpaa = None
try:
episode_expires = episode_item['expirationDate'].split('T')[0]
except:
episode_expires = None
if episode_item['mrssLengthType'] == 'Episode':
episode_type = 'Full Episode'
else:
episode_type = 'Clips'
try:
if episode_item['isHD'] == 'true':
episode_HD = True
else:
episode_HD = False
except:
episode_HD = False
u = sys.argv[0]
u += '?url="' + urllib.quote_plus(url) + '"'
u += '&mode="' + SITE + '"'
u += '&sitemode="play_video"'
infoLabels={ 'title' : episode_name,
'durationinseconds' : episode_duration,
'season' : season_number,
'episode' : episode_number,
'plot' : episode_plot,
'premiered' : episode_airdate,
'TVShowTitle' : episode_showtitle,
'mpaa' : episode_mpaa }
episodes.append((u, episode_name, episode_thumb, infoLabels, 'list_qualities', episode_HD, episode_type))
return episodes
def list_qualities():
video_url = common.args.url
bitrates = []
sig = sign_url(video_url)
smil_url = re.compile('(.+)\?').findall(video_url)[0] + '?switch=hls&assetTypes=medium_video_s3&mbr=true&metafile=true&sig=' + sig
video_data = connection.getURL(smil_url)
smil_tree = BeautifulSoup(video_data, 'html.parser')
video_url2 = smil_tree.video['src']
m3u_master_data = connection.getURL(video_url2)
m3u_master = m3u8.parse(m3u_master_data)
for video_index in m3u_master.get('playlists'):
bitrate = int(video_index.get('stream_info')['bandwidth'])
display = int(bitrate) / 1024
bitrates.append((display, bitrate))
return bitrates
def play_video():
try:
qbitrate = common.args.quality
except:
qbitrate = None
closedcaption = None
video_url = common.args.url
sig = sign_url(video_url)
smil_url = re.compile('(.+)\?').findall(video_url)[0] + '?switch=hls&assetTypes=medium_video_s3&mbr=true&metafile=true&sig=' + sig
smil_data = connection.getURL(smil_url)
smil_tree = BeautifulSoup(smil_data, 'html.parser')
video_url2 = smil_tree.video['src']
try:
closedcaption = smil_tree.textstream['src']
except:
pass
m3u_master_data = connection.getURL(video_url2, savecookie = True)
m3u_master = m3u8.parse(m3u_master_data)
hbitrate = -1
sbitrate = int(addon.getSetting('quality')) * 1024
for video_index in m3u_master.get('playlists'):
bitrate = int(video_index.get('stream_info')['bandwidth'])
if qbitrate is None:
if bitrate > hbitrate and bitrate <= sbitrate:
hbitrate = bitrate
m3u8_url = video_index.get('uri')
elif bitrate == qbitrate:
m3u8_url = video_index.get('uri')
m3u_data = connection.getURL(m3u8_url, loadcookie = True)
key_url = re.compile('URI="(.*?)"').findall(m3u_data)[0]
key_data = connection.getURL(key_url, loadcookie = True)
key_file = open(ustvpaths.KEYFILE % '0', 'wb')
key_file.write(key_data)
key_file.close()
video_url5 = re.compile('(http:.*?)\n').findall(m3u_data)
for i, video_item in enumerate(video_url5):
newurl = base64.b64encode(video_item)
newurl = urllib.quote_plus(newurl)
m3u_data = m3u_data.replace(video_item, 'http://127.0.0.1:12345/0/foxstation/' + newurl)
localhttpserver = True
filestring = 'XBMC.RunScript(' + os.path.join(ustvpaths.LIBPATH,'proxy.py') + ', 12345)'
xbmc.executebuiltin(filestring)
time.sleep(20)
m3u_data = m3u_data.replace(key_url, 'http://127.0.0.1:12345/play0.key')
playfile = open(ustvpaths.PLAYFILE, 'w')
playfile.write(m3u_data)
playfile.close()
finalurl = ustvpaths.PLAYFILE
if (addon.getSetting('enablesubtitles') == 'true') and (closedcaption is not None):
convert_subtitles(closedcaption)
item = xbmcgui.ListItem(path = finalurl)
try:
item.setThumbnailImage(common.args.thumb)
except:
pass
try:
item.setInfo('Video', { 'title' : common.args.name,
'season' : common.args.season_number,
'episode' : common.args.episode_number,
'TVShowTitle' : common.args.show_title})
except:
pass
xbmcplugin.setResolvedUrl(pluginHandle, True, item)
if ((addon.getSetting('enablesubtitles') == 'true') and (closedcaption is not None)) or localhttpserver is True:
while not xbmc.Player().isPlaying():
xbmc.sleep(100)
if (addon.getSetting('enablesubtitles') == 'true') and (closedcaption is not None):
xbmc.Player().setSubtitles(ustvpaths.SUBTITLE)
if localhttpserver is True:
while xbmc.Player().isPlaying():
xbmc.sleep(1000)
connection.getURL('http://localhost:12345/stop', connectiontype = 0)
def clean_subs(data):
br = re.compile(r'<br.*?>')
tag = re.compile(r'<.*?>')
space = re.compile(r'\s\s\s+')
apos = re.compile(r'&apos;')
gt = re.compile(r'>')
sub = br.sub('\n', data)
sub = tag.sub(' ', sub)
sub = space.sub(' ', sub)
sub = apos.sub('\'', sub)
sub = gt.sub('>', sub)
return sub
def convert_subtitles(closedcaption):
str_output = ''
subtitle_data = connection.getURL(closedcaption, connectiontype = 0)
subtitle_data = BeautifulSoup(subtitle_data, 'html.parser', parse_only = SoupStrainer('div'))
srt_output = ''
lines = subtitle_data.find_all('p')
i = 0
last_start_time = ''
last_end_time = ''
for line in lines:
try:
if line is not None:
sub = clean_subs(common.smart_utf8(line))
start_time = common.smart_utf8(line['begin'].replace('.', ','))
end_time = common.smart_utf8(line['end'].replace('.', ','))
if start_time != last_start_time and end_time != last_end_time:
str_output += '\n' + str(i + 1) + '\n' + start_time + ' --> ' + end_time + '\n' + sub + '\n'
i = i + 1
last_end_time = end_time
last_start_time = start_time
else:
str_output += sub + '\n\n'
except:
pass
file = open(ustvpaths.SUBTITLE, 'w')
file.write(str_output)
file.close()
return True
def sign_url(url):
query = { 'url' : re.compile('/[sz]/(.+)\?').findall(url)[0] }
encoded = urllib.urlencode(query)
sig = connection.getURL('http://servicesaetn-a.akamaihd.net/jservice/video/components/get-signed-signature?' + encoded)
return sig
|
__author__ = 'bruno'
import unittest
import algorithms.graphs.complementGraph as ComplementGraph
class TestComplementGraph(unittest.TestCase):
def setUp(self):
pass
def test_complement_graph_1(self):
graph = {'a': {'b': 1, 'c': 1},
'b': {'a': 1, 'c': 1, 'd': 1},
'c': {'a': 1, 'b': 1, 'd': 1},
'd': {'b': 1, 'c': 1}}
self.assertEqual({'a': {'d': 1}, 'd': {'a': 1}},
ComplementGraph.make_complement_graph(graph))
def test_complement_graph_2(self):
graph = {'a': {'b': 1, 'd': 1},
'b': {'a': 1, 'c': 1},
'c': {'b': 1, 'd': 1},
'd': {'a': 1, 'c': 1}}
complement = {'a': {'c': 1},
'b': {'d': 1},
'c': {'a': 1},
'd': {'b': 1}}
self.assertEqual(complement, ComplementGraph.make_complement_graph(graph))
def test_complement_graph_3(self):
graph = {'a': {'c': 1, 'd': 1},
'b': {'c': 1, 'd': 1},
'c': {'a': 1, 'b': 1},
'd': {'a': 1, 'b': 1, 'e': 1, 'f': 1},
'e': {'d': 1, 'f': 1},
'f': {'d': 1, 'e': 1}}
complement = {'a': {'b': 1, 'e': 1, 'f': 1},
'b': {'a': 1, 'e': 1, 'f': 1},
'c': {'e': 1, 'd': 1, 'f': 1},
'd': {'c': 1},
'e': {'a': 1, 'c': 1, 'b': 1},
'f': {'a': 1, 'c': 1, 'b': 1}}
self.assertEqual(complement, ComplementGraph.make_complement_graph(graph))
def test_complement_graph_4(self):
graph = {'a': {'b': 1, 'f': 1},
'b': {'a': 1, 'c': 1},
'c': {'b': 1, 'd': 1},
'd': {'c': 1, 'e': 1},
'e': {'d': 1, 'f': 1},
'f': {'a': 1, 'e': 1}}
complement = {'a': {'c': 1, 'e': 1, 'd': 1},
'b': {'e': 1, 'd': 1, 'f': 1},
'c': {'a': 1, 'e': 1, 'f': 1},
'd': {'a': 1, 'b': 1, 'f': 1},
'e': {'a': 1, 'c': 1, 'b': 1},
'f': {'c': 1, 'b': 1, 'd': 1}}
self.assertEqual(complement, ComplementGraph.make_complement_graph(graph))
def test_complement_graph_5(self):
graph = {'a': {'b': 1, 'c': 1, 'd': 1, 'e': 1},
'b': {'a': 1, 'c': 1, 'd': 1, 'e': 1},
'c': {'a': 1, 'b': 1, 'd': 1, 'e': 1},
'd': {'a': 1, 'b': 1, 'c': 1, 'e': 1},
'e': {'a': 1, 'b': 1, 'c': 1, 'd': 1, 'f': 1},
'f': {'e': 1}}
complement = {'a': {'f': 1},
'b': {'f': 1},
'c': {'f': 1},
'd': {'f': 1},
'f': {'a': 1, 'c': 1, 'b': 1, 'd': 1}}
self.assertEqual(complement, ComplementGraph.make_complement_graph(graph))
|
import os
PROJECT_DIR = os.path.dirname(__file__)
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
ALLOWED_HOSTS = []
TIME_ZONE = 'America/Chicago'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = True
USE_L10N = True
USE_TZ = True
MEDIA_ROOT = os.path.join(PROJECT_DIR, "media")
STATIC_ROOT = os.path.join(PROJECT_DIR, "static")
MEDIA_URL = "/media/"
STATIC_URL = "/static/"
STATICFILES_DIRS = (
os.path.join(PROJECT_DIR, "site_static"),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
SECRET_KEY = 'qomeppi59pg-(^lh7o@seb!-9d(yr@5n^=*y9w&(=!yd2p7&e^'
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'imageuploads.urls'
WSGI_APPLICATION = 'imageuploads.wsgi.application'
TEMPLATE_DIRS = (
os.path.join(PROJECT_DIR, "templates"),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'south',
'crispy_forms',
'ajaxuploader',
'images',
)
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
CRISPY_TEMPLATE_PACK = 'bootstrap3'
try:
execfile(os.path.join(os.path.dirname(__file__), "local_settings.py"))
except IOError:
pass
|
from StateMachine.State import State
from StateMachine.StateMachine import StateMachine
from StateMachine.InputAction import InputAction
from GameData.GameData import GameData
class StateT(State):
state_stack = list()
game_data = GameData()
def __init__(self):
self.transitions = None
def next(self, input):
if self.transitions.has_key(input):
return self.transitions[input]
else:
raise Exception("Input not supported for current state")
class NightBegins(StateT):
def run(self):
print("NightTime Falls")
def next(self, input):
StateT.state_stack.append(self)
if not self.transitions:
self.transitions = {
InputAction.getGameData : GameStates.nightBegins,
InputAction.playHeroCard : GameStates.nightBegins,
InputAction.playQuestCard : GameStates.nightBegins,
InputAction.drawDSCard : GameStates.drawDSCard,
}
return StateT.next(self, input)
class DrawDSCard(StateT):
def run(self):
print("Darkness Spreads drawing card")
StateT.current_ds_card = StateT.game_data.ds_cards.pop()
StateT.current_ds_card.display()
print "STACK: " + str(StateT.state_stack)
def next(self, input):
StateT.state_stack.append(self)
if not self.transitions:
self.transitions = {
InputAction.getGameData : GameStates.nightBegins,
InputAction.playHeroCard : GameStates.nightBegins,
InputAction.playQuestCard : GameStates.nightBegins,
InputAction.drawDSCard : GameStates.drawDSCard,
InputAction.executeDSCard : GameStates.executeDSCard,
}
return StateT.next(self, input)
class ExecuteDSCard(StateT):
def run(self):
print("Darkness Spreads - executing card")
StateT.current_ds_card.execute(StateT.game_data)
print "STACK: " + str(StateT.state_stack)
def next(self, input):
StateT.state_stack.append(self)
if not self.transitions:
self.transitions = {
InputAction.getGameData : GameStates.nightBegins,
InputAction.playHeroCard : GameStates.nightBegins,
InputAction.playQuestCard : GameStates.nightBegins,
InputAction.drawDSCard : GameStates.drawDSCard,
InputAction.advanceToDay : GameStates.dayBegins,
}
return StateT.next(self, input)
class DayBegins(StateT):
def run(self):
print("Day Time")
print "STACK: " + str(StateT.state_stack)
def next(self, input):
if not self.transitions:
self.transitions = {
InputAction.getGameData : GameStates.nightBegins,
InputAction.playHeroCard : GameStates.nightBegins,
InputAction.PlayQuestCard : GameStates.nightBegins,
InputAction.advanceToEvening : GameStates.eveningBegins,
}
return StateT.next(self, input)
class EveningBegins(StateT):
def run(self):
print("Day Time")
print "STACK: " + str(StateT.state_stack)
def next(self, input):
if not self.transitions:
self.transitions = {
InputAction.getGameData : GameStates.nightBegins,
InputAction.playHeroCard : GameStates.nightBegins,
InputAction.PlayQuestCard : GameStates.nightBegins,
InputAction.advanceToNight : GameStates.nightBegins,
}
return StateT.next(self, input)
class GameStates(StateMachine):
def __init__(self):
# Initial state
StateMachine.__init__(self, GameStates.nightBegins)
GameStates.nightBegins = NightBegins()
GameStates.drawDSCard = DrawDSCard()
GameStates.executeDSCard = ExecuteDSCard()
GameStates.eveningBegins = EveningBegins()
GameStates.dayBegins = DayBegins()
|
import os
from distutils.core import setup
setup(name = "palabre",
version = "0.6b",
description = "XML Socket Python Server",
long_description = "Flash XML Multiuser Socket Server",
author = "Célio Conort",
author_email = "palabre-dev@lists.tuxfamily.org",
url = "http://palabre.gavroche.net/",
license = "GPL, see COPYING for details",
platforms = "Linux",
packages = ["palabre","modules"],
scripts = ["scripts/palabre","setup.py"],
data_files = [('',['Palabre.py']),
("/etc", ["etc/palabre.conf"]
),
("doc",["doc/README.txt"]),
("./",["AUTHORS","COPYING","MANIFEST","MANIFEST.in","PKG-INFO"]),
("/usr/local/share/doc/palabre", ["doc/README.txt"])
]
)
|
import sys
if len(sys.argv) != 2:
print "Syntax: python2 flag.py <FLAG>"
sys.exit(0)
flag = sys.argv[1]
i = 0
j = len(flag)-1
l = j
flag2 = ""
while (i<l+1):
if i <= l/2:
c = 7
else:
c = 10
flag2 += chr(ord(flag[j])+c)
i = i+1
j = j-1
print flag2
|
import subprocess
import sys
import numpy as np
import fluidfoam
import matplotlib.pyplot as plt
plt.ion()
import matplotlib.ticker as mticker
from matplotlib.ticker import StrMethodFormatter, NullFormatter
from matplotlib import rc
rc('text', usetex=True)
label_size = 20
legend_size = 12
fontsize=25
linewidth=2
plt.rcParams['xtick.labelsize'] = label_size
plt.rcParams['ytick.labelsize'] = label_size
plt.rcParams['legend.fontsize'] = legend_size
plt.rcParams['lines.linewidth'] = linewidth
plt.rcParams['axes.labelsize'] = fontsize
zDEM, phiDEM, vxPDEM, vxFDEM, TDEM = np.loadtxt('DATA/BedloadTurbDEM.txt', unpack=True)
sol = '../1DBedLoadTurb/'
try:
proc = subprocess.Popen(
["foamListTimes", "-latestTime", "-case", sol],
stdout=subprocess.PIPE,)
except:
print("foamListTimes : command not found")
print("Do you have load OpenFoam environement?")
sys.exit(0)
output = proc.stdout.read() #to obtain the output of function foamListTimes from the subprocess
timeStep = output.decode().rstrip().split('\n')[0] #Some management on the output to obtain a number
X, Y, Z = fluidfoam.readmesh(sol)
z = Y
phi = fluidfoam.readscalar(sol, timeStep, 'alpha_a')
vxPart = fluidfoam.readvector(sol, timeStep, 'Ua')[0]
vxFluid = fluidfoam.readvector(sol, timeStep, 'Ub')[0]
T = fluidfoam.readscalar(sol, timeStep, 'Theta')
d = 0.006 #6mm diameter particles
plt.figure(figsize=[10,5])
plt.subplot(141)
plt.plot(phiDEM, zDEM/d, 'k--', label=r'DEM')
plt.plot(phi, z/d, label=r'SedFoam')
plt.xlabel(r'$\phi$', fontsize=25)
plt.ylabel(r'$\frac{z}{d}$', fontsize=30, rotation=True, horizontalalignment='right')
plt.grid()
plt.ylim([-1.525, 32.025])
plt.legend()
plt.subplot(142)
I = np.where(phiDEM>0.001)[0]
plt.plot(vxPDEM[I], zDEM[I]/d, 'r--')
I = np.where(phi>0.001)[0]
plt.plot(vxPart[I], z[I]/d, 'r', label=r'$v_x^p$')
plt.plot(vxFDEM, zDEM/d, 'b--')
plt.plot(vxFluid, z/d, 'b', label=r'$u_x^f$')
plt.xlabel(r'$v_x^p$, $u_x^f$', fontsize=25)
plt.ylim([-1.525, 32.025])
plt.grid()
plt.legend()
ax = plt.gca()
ax.set_yticklabels([])
plt.legend()
plt.subplot(143)
plt.plot(phiDEM*vxPDEM, zDEM/d, 'k--', label=r'DEM')
plt.plot(phi*vxPart, z/d, label=r'SedFoam')
plt.xlabel(r'$q = \phi v_x^p$', fontsize=25)
plt.grid()
plt.ylim([-1.525, 32.025])
ax = plt.gca()
ax.set_yticklabels([])
plt.subplot(144)
I = np.where(phiDEM>0.001)[0]
plt.plot(TDEM[I], zDEM[I]/d, 'k--', label=r'DEM')
I = np.where(phi>0.001)[0]
plt.plot(T[I], z[I]/d, label=r'SedFoam')
plt.xlabel(r'$T$', fontsize=25)
plt.grid()
plt.ylim([-1.525, 32.025])
ax = plt.gca()
ax.set_yticklabels([])
plt.savefig('Figures/res_TutoBedloadTurb.png', bbox_inches='tight')
plt.show(block=True)
|
import math
from gi.repository import Gtk
from meld.misc import get_common_theme
from meld.settings import meldsettings
RADIUS = 3
class LinkMap(Gtk.DrawingArea):
__gtype_name__ = "LinkMap"
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed)
def associate(self, filediff, left_view, right_view):
self.filediff = filediff
self.views = [left_view, right_view]
if self.get_direction() == Gtk.TextDirection.RTL:
self.views.reverse()
self.view_indices = [filediff.textview.index(t) for t in self.views]
self.on_setting_changed(meldsettings, 'style-scheme')
def on_setting_changed(self, settings, key):
if key == 'style-scheme':
self.fill_colors, self.line_colors = get_common_theme()
def do_draw(self, context):
if not self.filediff:
return
context.set_line_width(1.0)
allocation = self.get_allocation()
pix_start = [t.get_visible_rect().y for t in self.views]
y_offset = [
t.translate_coordinates(self, 0, 0)[1] + 1 for t in self.views]
clip_y = min(y_offset) - 1
clip_height = max(t.get_visible_rect().height for t in self.views) + 2
context.rectangle(0, clip_y, allocation.width, clip_height)
context.clip()
height = allocation.height
visible = [self.views[0].get_line_num_for_y(pix_start[0]),
self.views[0].get_line_num_for_y(pix_start[0] + height),
self.views[1].get_line_num_for_y(pix_start[1]),
self.views[1].get_line_num_for_y(pix_start[1] + height)]
wtotal = allocation.width
# For bezier control points
x_steps = [-0.5, (1. / 3) * wtotal, (2. / 3) * wtotal, wtotal + 0.5]
q_rad = math.pi / 2
left, right = self.view_indices
view_offset_line = lambda v, l: (self.views[v].get_y_for_line_num(l) -
pix_start[v] + y_offset[v])
for c in self.filediff.linediffer.pair_changes(left, right, visible):
# f and t are short for "from" and "to"
f0, f1 = [view_offset_line(0, l) for l in c[1:3]]
t0, t1 = [view_offset_line(1, l) for l in c[3:5]]
# We want the last pixel of the previous line
f1 = f1 if f1 == f0 else f1 - 1
t1 = t1 if t1 == t0 else t1 - 1
# If either endpoint is completely off-screen, we cull for clarity
if (t0 < 0 and t1 < 0) or (t0 > height and t1 > height):
if f0 == f1:
continue
context.arc(x_steps[0], f0 - 0.5 + RADIUS, RADIUS, -q_rad, 0)
context.arc(x_steps[0], f1 - 0.5 - RADIUS, RADIUS, 0, q_rad)
context.close_path()
elif (f0 < 0 and f1 < 0) or (f0 > height and f1 > height):
if t0 == t1:
continue
context.arc_negative(x_steps[3], t0 - 0.5 + RADIUS, RADIUS,
-q_rad, q_rad * 2)
context.arc_negative(x_steps[3], t1 - 0.5 - RADIUS, RADIUS,
q_rad * 2, q_rad)
context.close_path()
else:
context.move_to(x_steps[0], f0 - 0.5)
context.curve_to(x_steps[1], f0 - 0.5,
x_steps[2], t0 - 0.5,
x_steps[3], t0 - 0.5)
context.line_to(x_steps[3], t1 - 0.5)
context.curve_to(x_steps[2], t1 - 0.5,
x_steps[1], f1 - 0.5,
x_steps[0], f1 - 0.5)
context.close_path()
context.set_source_rgba(*self.fill_colors[c[0]])
context.fill_preserve()
chunk_idx = self.filediff.linediffer.locate_chunk(left, c[1])[0]
if chunk_idx == self.filediff.cursor.chunk:
highlight = self.fill_colors['current-chunk-highlight']
context.set_source_rgba(*highlight)
context.fill_preserve()
context.set_source_rgba(*self.line_colors[c[0]])
context.stroke()
def do_scroll_event(self, event):
self.filediff.next_diff(event.direction)
class ScrollLinkMap(Gtk.DrawingArea):
__gtype_name__ = "ScrollLinkMap"
def __init__(self):
self.melddoc = None
def associate(self, melddoc):
self.melddoc = melddoc
def do_scroll_event(self, event):
if not self.melddoc:
return
self.melddoc.next_diff(event.direction)
|
import csv, sqlite3
con = sqlite3.connect("toto.db") # change to 'sqlite:///your_filename.db'
cur = con.cursor()
cur.execute("CREATE TABLE t (col1, col2);") # use your column names here
with open('data.csv','r') as fin: # `with` statement available in 2.5+
# csv.DictReader uses first line in file for column headings by default
dr = csv.DictReader(fin) # comma is default delimiter
to_db = [(i['col1'], i['col2']) for i in dr]
cur.executemany("INSERT INTO t (col1, col2) VALUES (?, ?);", to_db)
con.commit()
con.close()
|
import sqlite3
def select_data(db_name, table_name, condition):
"find all the data with the same kind"
with sqlite3.connect(db_name) as db:
cursor = db.cursor()
cursor.execute("SELECT title, releaseYear FROM {0} WHERE title LIKE ?".format(table_name), (condition,))
result = cursor.fetchall()
return result
def select_from_multi(db_name, table_name, conditon):
"select from multiple tables"
with sqlite3.connect(db_name) as db:
cursor = db.cursor()
cursor.execute("SELECT title, genreName FROM {0}, {1} WHERE title=? AND genreName IN (?,?)".format(table_name[0], table_name[1]), (condition[0], condition[1], condition[2]))
result = cursor.fetchall()
return result
if __name__ == '__main__':
db_name = "movie.db"
table_name = "film"
condition = "Die Hard%"
result = select_data(db_name, table_name, condition)
print(result)
table_name = ("film", "genre")
condition = ("Die Hard", "Action", "Thriller")
result = select_from_multi(db_name, table_name, condition)
print(result)
|
import subprocess
def create_batch_file(glm_folder,batch_name):
batch_file = open('{:s}'.format(batch_name),'w')
batch_file.write('gridlabd.exe -T 0 --job\n')
#batch_file.write('pause\n')
batch_file.close()
return None
def run_batch_file(glm_folder,batch_name):
p = subprocess.Popen('{:s}'.format(batch_name),cwd=glm_folder)
code = p.wait()
#print(code)
return None
def main():
#tests here
glm_folder = 'C:\\Projects\\GridLAB-D_Builds\\trunk\\test\\input\\batch_test'
batch_name = 'C:\\Projects\\GridLAB-D_Builds\\trunk\\test\\input\\batch_test\\calibration_batch_file.bat'
create_batch_file(glm_folder,batch_name)
run_batch_file(batch_name)
if __name__ == '__main__':
main()
|
{
' (late)': ' (verspätet)',
'!=': '!=',
'!langcode!': 'de',
'!langname!': 'Deutsch (DE)',
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '""Update" ist ein optionaler Ausdruck wie "Feld1 = \'newvalue". JOIN Ergebnisse können nicht aktualisiert oder gelöscht werden',
'%(nrows)s records found': '%(nrows)s Einträge gefunden',
'%d.%m.%Y': '%d.%m.%Y',
'%s %%(shop)': '%s %%(shop)',
'%s %%(shop[0])': '%s %%(shop[0])',
'%s %%{quark[0]}': '%s %%{quark[0]}',
'%s %%{row} deleted': '%s %%{row} gelöscht',
'%s %%{row} updated': '%s %%{row} aktualisiert',
'%s %%{shop[0]}': '%s %%{shop[0]}',
'%s %%{shop}': '%s %%{shop}',
'%s selected': '%s ausgewählt',
'%Y-%m-%d': '%d.%m.%Y',
'%Y-%m-%d %H:%M:%S': '%d.%m.%Y %H:%M:%S',
'+ And': '+ Und',
'+ Or': '+ Oder',
'<': '<',
'<=': '<=',
'=': '=',
'>': '>',
'>=': '>=',
'?': '?',
'@markmin\x01**Hello World**': '**Hallo Welt**',
'@markmin\x01An error occured, please [[reload %s]] the page': 'Ein Fehler ist aufgetreten, bitte [[laden %s]] Sie die Seite neu',
'A file ({filename}) was uploaded for task {task} by {firstname} {lastname} with the hash (SHA256) {hash}.': 'Eine Datei ({filename}) für die Aufgabe {task} mit dem Hash (SHA256) {hash} wurde von {firstname} {lastname} hochgeladen.',
'About': 'Über',
'Access Control': 'Zugangskontrolle',
'Add Record': 'Eintrag hinzufügen',
'Add record to database': 'Eintrag in Datenbank hinzufügen',
'Add this to the search as an AND term': 'Add this to the search as an AND term',
'Add this to the search as an OR term': 'Add this to the search as an OR term',
'admin': 'admin',
'Administrative Interface': 'Administrationsoberfläche',
'Administrator view: Task of all users are shown!': 'Administrator-Ansicht: Es werden die Aufgaben aller Benutzer angezeigt!',
'After the file was uploaded, the chosen teacher will be informed by email. The uploader also gets an email with the hash (SHA256) of the uploaded file.': 'Nach Betätigung des Upload-Buttons wird die Datei übermittelt und die ausgewählte Lehrkraft per Mail darüber informiert. Der Uploader bekommt ebenfalls eine Benachrichtigungsmail mit der Hash (SHA256) der hochgeladenen Datei.',
'Ajax Recipes': 'Ajax Rezepte',
'appadmin is disabled because insecure channel': 'Appadmin ist deaktiviert, wegen der Benutzung eines unsicheren Kanals',
'Apply changes': 'Änderungen übernehmen',
'Are you sure you want to delete this object?': 'Sind Sie sich sicher, dass Sie dieses Objekt löschen wollen?',
'AttendingClass': 'Klasse',
'Available Databases and Tables': 'Verfügbare Datenbanken und Tabellen',
'Back': 'Zurück',
'Buy this book': 'Dieses Buch kaufen',
"Buy web2py's book": "Buy web2py's book",
'cache': 'cache',
'Cache': 'Cache',
'Cache Cleared': 'Cache geleert',
'Cache Keys': 'Cache Schlüssel',
'Cannot be empty': 'Darf nicht leer sein',
'Change Password': 'Passwort ändern',
'Change password': 'Passwort ändern',
'Check to delete': 'Auswählen um zu löschen',
'Choose a file to be uploaded!': 'Wählen Sie eine Datei aus, die hochgeladen werden soll!',
'Choose a task:': 'Wählen Sie eine Aufgabe aus:',
'choose one': 'Wählen Sie einen aus',
'Class': 'Klasse',
'Clear': 'Löschen',
'Clear CACHE?': 'CACHE löschen?',
'Clear DISK': 'DISK löschen',
'Clear RAM': 'RAM löschen',
'Click on the link %(link)s to reset your password': 'Click on the link %(link)s to reset your password',
'Client IP': 'Client IP',
'Close': 'Schließen',
'Collect uploaded files': 'Hochgeladene Dateien einsammeln',
'Comma-separated export including columns not shown; fields from other tables are exported as raw values for faster export': 'Comma-separated export including columns not shown; fields from other tables are exported as raw values for faster export',
'Comma-separated export of visible columns. Fields from other tables are exported as they appear on-screen but this may be slow for many rows': 'Comma-separated export of visible columns. Fields from other tables are exported as they appear on-screen but this may be slow for many rows',
'Community': 'Community',
'Components and Plugins': 'Komponenten und Plugins',
'Config.ini': 'Config.ini',
'Confirm Password': 'Passwort bestätigen',
'contains': 'contains',
'Controller': 'Controller',
'Copyright': 'Copyright',
'Created By': 'Erstellt von',
'Created On': 'Erstellt am',
'CSV': 'CSV',
'CSV (hidden cols)': 'CSV (versteckte Spalten)',
'Current request': 'Derzeitiger Request',
'Current response': 'Derzeitige Response',
'Current session': 'Derzeitige Session',
'customize me!': 'Pass mich an!',
'data uploaded': 'Datei hochgeladen',
'Database': 'Datenbank',
'Database %s select': 'Datenbank %s ausgewählt',
'Database Administration (appadmin)': 'Datenbankadministration (appadmin)',
'db': 'db',
'DB Model': 'Muster-DB',
'Delete': 'Löschen',
'Delete:': 'Löschen:',
'Demo': 'Demo',
'Deployment Recipes': 'Entwicklungsrezepte',
'Description': 'Beschreibung',
'design': 'Design',
'Design': 'Design',
'DISK': 'DISK',
'Disk Cache Keys': 'Disk Cache Keys',
'Disk Cleared': 'Disk gelöscht',
'Documentation': 'Dokumentation',
"Don't know what to do?": 'Wissen Sie nicht weiter?',
'done!': 'Fertig!',
'Download': 'Download',
'Download all uploaded files...': 'Alle hochgeladenen Dateien herunterladen...',
'Download files': 'Dateien herunterladen',
'Duedate': 'Fälligkeit',
'DueDate': 'Fälligkeit',
'E-mail': 'Email',
'Edit': 'Bearbeiten',
'Edit current record': 'Diesen Eintrag editieren',
'Email and SMS': 'Email und SMS',
'Email sent': 'Email wurde versandt',
'Enter a valid email address': 'Geben Sie eine gültige Email-Adresse ein',
'Enter a value': 'Geben Sie einen Wert ein',
'Enter an integer between %(min)g and %(max)g': 'Eine Zahl zwischen %(min)g und %(max)g eingeben',
'enter an integer between %(min)g and %(max)g': 'eine Zahl zwischen %(min)g und %(max)g eingeben',
'enter date and time as %(format)s': 'ein Datum und eine Uhrzeit als %(format)s eingeben',
'Enter date as %(format)s': 'Geben Sie ein Datum mit dem Format %(format)s an',
'Enter from %(min)g to %(max)g characters': 'Geben Sie zwischen %(min)g und %(max)g Zeichen ein',
'Errors': 'Fehlermeldungen',
'Errors in form, please check it out.': 'Bitte überprüfen Sie das Formular, denn es enthält Fehler.',
'export as csv file': 'als csv Datei exportieren',
'Export:': 'Export:',
'FAQ': 'FAQ',
'file': 'file',
'file ## download': 'Datei ## herunterladen',
'File size is to large!': 'Datei ist zu groß!',
'File successfully uploaded': 'Datei erfolgreich hochgeladen',
'File successfully uploaded!': 'Datei erfolgreich hochgeladen!',
'File to be uploaded': 'Hochzuladene Datei',
'File uploaded for task {task}': 'Datei hochgeladen für Aufgabe {task}',
'First name': 'Vorname',
'First Name': 'Vorname',
'FirstName': 'FirstName',
'Forgot username?': 'Benutzernamen vergessen?',
'Forms and Validators': 'Forms und Validators',
'Free Applications': 'Kostenlose Anwendungen',
'Given task and teacher does not match!': 'Angegebene Aufgabe und Lehrkraft passen nicht zusammen!',
'Graph Model': 'Muster-Graph',
'Group %(group_id)s created': 'Gruppe %(group_id)s erstellt',
'Group ID': 'Gruppen ID',
'Group uniquely assigned to user %(id)s': 'Gruppe eindeutigem Benutzer %(id)s zugewiesen',
'Groups': 'Gruppen',
'Hash': 'Hash',
'Hello World': 'Hallo Welt',
'Hello World ## Kommentar': 'Hallo Welt ',
'Hello World## Kommentar': 'Hallo Welt',
'Help': 'Hilfe',
'Helping web2py': 'web2py helfen',
'Home': 'Startseite',
'Hosted on': 'Hosted on',
'How did you get here?': 'Wie sind Sie hier her gelangt?',
'HTML': 'HTML',
'HTML export of visible columns': 'Sichtbare Spalten nach HTML exportieren',
'Id': 'Id',
'import': 'Importieren',
'Import/Export': 'Importieren/Exportieren',
'in': 'in',
'Insufficient privileges': 'Keine ausreichenden Rechte',
'Internal State': 'Innerer Zustand',
'Introduction': 'Einführung',
'Invalid email': 'Ungültige Email',
'Invalid login': 'Ungültiger Login',
'Invalid Query': 'Ungültige Query',
'invalid request': 'Ungültiger Request',
'Is Active': 'Ist aktiv',
'JSON': 'JSON',
'JSON export of visible columns': 'Sichtbare Spalten nach JSON exportieren',
'Key': 'Schlüssel',
'Klasse': 'Klasse',
'Last name': 'Nachname',
'Last Name': 'Nachname',
'LastName': 'Nachname',
'Layout': 'Layout',
'Layout Plugins': 'Layout Plugins',
'Layouts': 'Layouts',
'Live Chat': 'Live Chat',
'Log In': 'Einloggen',
'Log Out': 'Ausloggen',
'Logged in': 'Eingeloggt',
'Logged out': 'Ausgeloggt',
'Login': 'Einloggen',
'Login to UpLoad': 'In UpLoad einloggen',
'Logout': 'Ausloggen',
'Lost Password': 'Passwort vergessen',
'Lost password?': 'Passwort vergessen?',
'Mail': 'Mail',
'Manage %(action)s': '%(action)s verwalten',
'Manage Access Control': 'Zugangskontrolle verwalten',
'Manage Cache': 'Cache verwalten',
'Manage tasks': 'Aufgaben verwalten',
'Manage teachers': 'Lehrkräfte verwalten',
'Memberships': 'Mitgliedschaften',
'Menu Model': 'Menü-Muster',
'Modified By': 'Verändert von',
'Modified On': 'Verändert am',
'My Sites': 'Meine Seiten',
'Nachname': 'Nachname',
'Name': 'Name',
'New password': 'Neues Passwort',
'New Record': 'Neuer Eintrag',
'new record inserted': 'neuer Eintrag hinzugefügt',
'New Search': 'Neue Suche',
'next %s rows': 'nächste %s Reihen',
'No databases in this application': 'Keine Datenbank in dieser Anwendung',
'No hash for upload given.': 'Kein Upload mit angegebener Hash gefunden',
'No records found': 'Keine Einträge gefunden',
'No task number given.': 'Es wurde keine Aufgabe gewählt.',
'Not Authorized': 'Zugriff verboten',
'not authorized': 'Zugriff verboten',
'not in': 'not in',
'Object or table name': 'Objekt- oder Tabellenname',
'Old password': 'Altes Passwort',
'Online book': 'Online book',
'Online examples': 'Online Beispiele',
'OpenForSubmission': 'Upload freigeschaltet',
'or import from csv file': 'oder von csv Datei importieren',
'Origin': 'Ursprung',
'Other Plugins': 'Andere Plugins',
'Other Recipes': 'Andere Rezepte',
'Overview': 'Überblick',
'Password': 'Passwort',
'Password changed': 'Passwort wurde geändert',
"Password fields don't match": 'Passwortfelder sind nicht gleich',
'Password reset': 'Passwort wurde zurückgesetzt',
'Permission': 'Zugriffsrecht',
'Permissions': 'Zugriffsrechte',
'please input your password again': 'Bitte geben Sie ihr Passwort erneut ein',
'Plugins': 'Plugins',
'Powered by': 'Unterstützt von',
'Preface': 'Allgemeines',
'previous %s rows': 'vorherige %s Reihen',
'Profile': 'Profil',
'Profile updated': 'Profil aktualisiert',
'pygraphviz library not found': 'pygraphviz Bibliothek wurde nicht gefunden',
'Python': 'Python',
'Query:': 'Query:',
'Quick Examples': 'Kurze Beispiele',
'RAM': 'RAM',
'RAM Cache Keys': 'RAM Cache Keys',
'Ram Cleared': 'Ram Cleared',
'Recipes': 'Rezepte',
'Record': 'Eintrag',
'record does not exist': 'Eintrag existiert nicht',
'Record ID': 'ID des Eintrags',
'Record id': 'id des Eintrags',
'Register': 'Register',
'Registration identifier': 'Registrierungsbezeichnung',
'Registration key': 'Registierungsschlüssel',
'Registration successful': 'Registrierung erfolgreich',
'Remember me (for 30 days)': 'Eingeloggt bleiben (30 Tage lang)',
'Request reset password': 'Request reset password',
'Request Reset Password': 'Request Reset Password',
'Reset Password': 'Reset Password',
'Reset Password key': 'Passwortschlüssel zurücksetzen',
'Role': 'Rolle',
'Roles': 'Rollen',
'Rows in Table': 'Tabellenreihen',
'Rows selected': 'Reihen ausgewählt',
'Save model as...': 'Speichere Vorlage als...',
'Search': 'Suche',
'Semantic': 'Semantik',
'SendMessages': 'Sende Nachrichten',
'Services': 'Dienste',
'Sign Up': 'Sign Up',
'Size of cache:': 'Cachegröße:',
'Spreadsheet-optimised export of tab-separated content including hidden columns. May be slow': 'Spreadsheet-optimised export of tab-separated content including hidden columns. May be slow',
'Spreadsheet-optimised export of tab-separated content, visible columns only. May be slow.': 'Spreadsheet-optimised export of tab-separated content, visible columns only. May be slow.',
'Start building a new search': 'Start building a new search',
'StartDate': 'Beginn',
'starts with': 'starts with',
'state': 'Status',
'Statistics': 'Statistik',
'Stylesheet': 'Stylesheet',
'Submission for given task no yet allowed!': 'Upload für die gegebene Aufgabe ist noch nicht erlaubt!',
'submit': 'Abschicken',
'Submit': 'Abschicken',
'SubmittedOnTime': 'Pünklich abgegeben',
'Submittedontime': 'Pünklich abgegeben',
'Success!': 'Erfolg!',
'Support': 'Support',
'Table': 'Tabelle',
'Task': 'Aufgabe',
'Task is currently not open for submission.': 'Für diese Aufgabe sind im Moment keine Uploads erlaubt.',
'Teacher': 'Lehrkraft',
'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'Die "query" ist eine Bedingung wie "db.tabelle1.feld1==\'wert\'". So etwas wie "db.tabelle1.feld1==db.tabelle2.feld2" resultiert in einem SQL JOIN.',
'The Core': 'Der Core',
'The output of the file is a dictionary that was rendered by the view %s': 'Die Ausgabe der Datei ist ein "dictionary", welches vom "view" %s gerendert wurde',
'The Views': 'Die Views',
'This App': 'Diese App',
'This email already has an account': 'Zu dieser Email-Adresse gibt es bereits einen Benutzer.',
'This exact file has been uploaded already by a user.': 'Exakt diese Datei wurde bereits von einem Benutzer hochgeladen.',
'This page only works with JavaScript.': 'Diese Seite funktioniert nur mit JavaScript.',
'Time in Cache (h:m:s)': 'Zeit im Cache (h:m:s)',
'Timestamp': 'Zeitstempel',
'Token': 'Token',
'Traceback': 'Traceback',
'TSV (Spreadsheets)': 'TSV (Tabellenkalkulation)',
'TSV (Spreadsheets, hidden cols)': 'TSV (Tabellenkalkulation, versteckte Spalten)',
'Twitter': 'Twitter',
'unable to parse csv file': 'csv Datei konnte nicht geparst werden',
'Update:': 'Update:',
'Upload file': 'Datei hochladen',
'UpLoad@BBS is used to upload presentations, project documentation and tests. To upload a file you have to fill out the form with information about the uploader, the teacher and the task for which you want to upload a file. Then you can choose a file to be uploaded. The maximum file size is 5MiB.': 'UpLoad@BBS dient dem einfachen Abgeben von Projektarbeiten, Präsentationen und Klassenarbeiten. Um eine Datei hochzuladen, müssen zunächst Informationen zum Absender, der Lehrkraft und der Aufgabe angegeben werden. Anschließend ist die abzugebende Datei auszuwählen. Die maximal erlaubte Dateigröße beträgt 5MiB.',
'UploadedFile': 'Hochgeladene Datei',
'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Benutze (...)&(...) für AND, (...)|(...) für OR, und ~(...) für NOT um komplexere Queries zu erstellen.',
'User': 'Benutzer',
'User %(id)s Logged-in': 'Benutzer %(id)s hat sich eingeloggt',
'User %(id)s Logged-out': 'Benutzer %(id)s hat sich ausgeloggt',
'User %(id)s Registered': 'Benutzer %(id)s hat sich registriert',
'User ID': 'Benutzer ID',
'Users': 'Benutzer',
'value already in database or empty': 'Wert ist bereits in der Datenbank oder leer',
'Value not in database': 'Ausgewählter Wert nicht in Datenbank enthalten',
'Verify Password': 'Passwort überprüfen',
'Videos': 'Videos',
'View': 'Ansicht',
'View uploaded file': 'Hochgeladene Datei ansehen',
'View uploaded files': 'Hochgeladene Dateien ansehen',
'View uploads': 'Hochgeladene Datei ansehen',
'Welcome': 'Willkommen',
'Welcome to web2py!': 'Willkommen bei web2py!',
'Which called the function %s located in the file %s': 'Welche die Funktion %s in der Datei %s aufrief',
'Working...': 'Arbeite...',
'Wrong token for given task.': 'Ungültiger Token für gewählte Aufgabe eingegeben.',
'Wrong token given!': 'Ungültiger Token eingegeben!',
'XML': 'XML',
'XML export of columns shown': 'XML export of columns shown',
'You already created a Task with the same name. Please delete the old task or rename this one.': 'Sie haben bereits eine Aufgabe mit diesem Namen erstellt. Bitte löschen sie die alte Aufgabe oder geben Sie einen anderen Namen an.',
'You already uploaded a file for this task!': 'Sie haben bereits eine Datei für diese Aufgabe hochgeladen!',
'You are successfully running web2py': 'web2py wird erfolgreich ausgeführt',
'You can modify this application and adapt it to your needs': 'Sie können diese Anwendung verändern und Ihren Bedürfnissen anpassen',
'You can only create tasks for yourself.': 'Sie dürfen nur eigene Aufgaben erstellen.',
'You visited the url %s': 'Sie haben die URL %s besucht',
'Your file ({filename}) with the hash (SHA256) {hash} has been successfully uploaded.': 'Ihre Datei ({filename}) mit dem Hash (SHA256) {hash} wurde erfolgreich hochgeladen.',
}
|
import pygeoip
import json
from logsparser.lognormalizer import LogNormalizer as LN
import gzip
import glob
import socket
import urllib2
IP = 'IP.Of,Your.Server'
normalizer = LN('/usr/local/share/logsparser/normalizers')
gi = pygeoip.GeoIP('../GeoLiteCity.dat')
def complete(text, state):
return (glob.glob(text+'*')+[none])[state]
def sshcheck():
attacks = {}
users = {}
try:
import readline, rlcompleter
readline.set_completer_delims(' \t\n;')
readline.parse_and_bind("tab: complete")
readline.set_completer(complete)
except ImportError:
print 'No Tab Completion'
LOGs = raw_input('Enter the path to the log file: ')
for LOG in LOGs.split(' '):
if LOG.endswith('.gz'):
auth_logs = gzip.GzipFile(LOG, 'r')
else:
auth_logs = open(LOG, 'r')
if len(LOGs) is '1':
print "Parsing log file"
else:
print "Parsing log files"
for log in auth_logs:
l = {"raw": log }
normalizer.normalize(l)
if l.get('action') == 'fail' and l.get('program') == 'sshd':
u = l['user']
p = l['source_ip']
o1, o2, o3, o4 = [int(i) for i in p.split('.')]
if o1 == 192 and o2 == 168 or o1 == 172 and o2 in range(16, 32) or o1 == 10:
print "Private IP, %s No geolocation data" %str(p)
attacks[p] = attacks.get(p, 0) + 1
getip()
dojson(attacks, IP)
def getip():
global IP
if IP is 0:
try:
i = urllib2.Request("http://icanhazip.com")
p = urllib2.urlopen(i)
IP = p.read()
except:
print "can't seem to grab your IP please set IP variable so We can better map attacks"
def dojson(attacks, IP):
data = {}
for i,(a,p) in enumerate(attacks.iteritems()):
datalist = [{ 'ip': a, 'attacks': p, 'local_ip': IP }]
data[i] = datalist
newdata = data
newjson = json.dumps(newdata)
print json.loads(newjson)
send(newjson)
def send(data):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('Ip.Of.Your.Server', 9999))
s.sendall(data)
s.close()
try:
sshcheck()
except KeyboardInterrupt:
print '\nCtrl+C Exiting...'
exit(0)
|
import logging
def importVarious(context):
if context.readDataFile('sc.blueprints.soundcloud_various.txt') is None:
return
logger = logging.getLogger('sc.blueprints.soundcloud')
# add here your custom methods that need to be run when
# sc.blueprints.soundcloud is installed
|
import sys
import os
import urllib2
import readline
executable_path = os.path.split(os.path.abspath(os.path.realpath(sys.argv[0])))[0]
sys.path += [os.path.join(executable_path,os.path.pardir,"s7webserver")]
import s7webserver_repl
portnum = "5080"
if len(sys.argv)>1:
portnum = sys.argv[1]
s7webserver_repl.start("radium>", "http://localhost:"+portnum)
|
from yast import import_module
import_module('UI')
from yast import *
class Heading2Client:
def main(self):
UI.OpenDialog(
VBox(
Heading("This Is a Heading."),
Label("This is a Label."),
PushButton("&OK")
)
)
UI.UserInput()
UI.CloseDialog()
Heading2Client().main()
|
'''
Created on 2015/07/01
@author: Eric Ball
@change: 2015/12/07 eball Added information about REMOVEX CI to help text
@change: 2016/07/06 eball Separated fix into discrete methods
@change: 2017/06/02 bgonz12 - Change a conditional in reportUbuntu to search for
"manual" using regex instead of direct comparison
@change 2017/08/28 rsn Fixing to use new help text methods
@change: 2017/10/23 rsn - change to new service helper interface
@change: 2017/11/14 bgonz12 - Fix removeX dependency issue for deb systems
'''
import os
import re
import traceback
from KVEditorStonix import KVEditorStonix
from logdispatcher import LogPriority
from pkghelper import Pkghelper
from rule import Rule
from CommandHelper import CommandHelper
from ServiceHelper import ServiceHelper
from stonixutilityfunctions import iterate, readFile, writeFile, createFile
from stonixutilityfunctions import resetsecon
class DisableGUILogon(Rule):
def __init__(self, config, environ, logger, statechglogger):
Rule.__init__(self, config, environ, logger, statechglogger)
self.logger = logger
self.rulenumber = 105
self.rulename = "DisableGUILogon"
self.formatDetailedResults("initialize")
self.mandatory = False
self.applicable = {'type': 'white',
'family': ['linux']}
# Configuration item instantiation
datatype = "bool"
key = "DISABLEX"
instructions = "To enable this item, set the value of DISABLEX " + \
"to True. When enabled, this rule will disable the automatic " + \
"GUI login, and the system will instead boot to the console " + \
"(runlevel 3). This will not remove any GUI components, and the " + \
"GUI can still be started using the \"startx\" command."
default = False
self.ci1 = self.initCi(datatype, key, instructions, default)
datatype = "bool"
key = "LOCKDOWNX"
instructions = "To enable this item, set the value of LOCKDOWNX " + \
"to True. When enabled, this item will help secure X Windows by " + \
"disabling the X Font Server (xfs) service and disabling X " + \
"Window System Listening. This item should be enabled if X " + \
"Windows is disabled but will be occasionally started via " + \
"startx, unless there is a mission-critical need for xfs or " + \
"a remote display."
default = False
self.ci2 = self.initCi(datatype, key, instructions, default)
datatype = "bool"
key = "REMOVEX"
instructions = "To enable this item, set the value of REMOVEX " + \
"to True. When enabled, this item will COMPLETELY remove X " + \
"Windows from the system, and on most platforms will disable " + \
"any currently running display manager. It is therefore " + \
"recommended that this rule be run from a console session " + \
"rather than from the GUI.\nREMOVEX cannot be undone."
default = False
self.ci3 = self.initCi(datatype, key, instructions, default)
self.guidance = ["NSA 3.6.1.1", "NSA 3.6.1.2", "NSA 3.6.1.3",
"CCE 4462-8", "CCE 4422-2", "CCE 4448-7",
"CCE 4074-1"]
self.iditerator = 0
self.ph = Pkghelper(self.logger, self.environ)
self.ch = CommandHelper(self.logger)
self.sh = ServiceHelper(self.environ, self.logger)
self.myos = self.environ.getostype().lower()
self.sethelptext()
def report(self):
'''@author: Eric Ball
:param self: essential if you override this definition
:returns: bool - True if system is compliant, False if it isn't
'''
try:
compliant = True
results = ""
if os.path.exists("/bin/systemctl"):
self.initver = "systemd"
compliant, results = self.reportSystemd()
elif re.search("debian", self.myos):
self.initver = "debian"
compliant, results = self.reportDebian()
elif re.search("ubuntu", self.myos):
self.initver = "ubuntu"
compliant, results = self.reportUbuntu()
else:
self.initver = "inittab"
compliant, results = self.reportInittab()
# NSA guidance specifies disabling of X Font Server (xfs),
# however, this guidance seems to be obsolete as of RHEL 6,
# and does not apply to the Debian family.
if self.sh.auditService("xfs", _="_"):
compliant = False
results += "xfs is currently enabled\n"
xremoved = True
self.xservSecure = True
if re.search("debian|ubuntu", self.myos):
if self.ph.check("xserver-xorg-core"):
compliant = False
xremoved = False
results += "Core X11 components are present\n"
elif re.search("opensuse", self.myos):
if self.ph.check("xorg-x11-server"):
compliant = False
xremoved = False
results += "Core X11 components are present\n"
else:
if self.ph.check("xorg-x11-server-Xorg"):
compliant = False
xremoved = False
results += "Core X11 components are present\n"
# Removing X will take xserverrc with it. If X is not present, we
# do not need to check for xserverrc
if not xremoved:
self.serverrc = "/etc/X11/xinit/xserverrc"
self.xservSecure = False
if os.path.exists(self.serverrc):
serverrcText = readFile(self.serverrc, self.logger)
if re.search("opensuse", self.myos):
for line in serverrcText:
reSearch = r'exec (/usr/bin/)?X \$dspnum.*\$args'
if re.search(reSearch, line):
self.xservSecure = True
break
else:
for line in serverrcText:
reSearch = r'^exec (/usr/bin/)?X (:0 )?-nolisten tcp ("$@"|.?\$@)'
if re.search(reSearch, line):
self.xservSecure = True
break
if not self.xservSecure:
compliant = False
results += self.serverrc + " does not contain proper " \
+ "settings to disable X Window System " + \
"Listening/remote display\n"
else:
compliant = False
results += self.serverrc + " does not exist; X Window " + \
"System Listening/remote display has not " + \
"been disabled\n"
self.detailedresults = results
self.compliant = compliant
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
self.rulesuccess = False
self.detailedresults = "\n" + traceback.format_exc()
self.logger.log(LogPriority.ERROR, self.detailedresults)
self.formatDetailedResults("report", self.compliant,
self.detailedresults)
self.logger.log(LogPriority.INFO, self.detailedresults)
return self.compliant
def reportInittab(self):
compliant = False
results = ""
inittab = "/etc/inittab"
if os.path.exists(inittab):
initData = readFile(inittab, self.logger)
for line in initData:
if line.strip() == "id:3:initdefault:":
compliant = True
break
else:
self.logger.log(LogPriority.ERROR, inittab + " not found, init " +
"system unknown")
if not compliant:
results = "inittab not set to runlevel 3; GUI logon is enabled\n"
return compliant, results
def reportSystemd(self):
compliant = True
results = ""
cmd = ["/bin/systemctl", "get-default"]
self.ch.executeCommand(cmd)
defaultTarget = self.ch.getOutputString()
if not re.search("multi-user.target", defaultTarget):
compliant = False
results = "systemd default target is not multi-user.target; " + \
"GUI logon is enabled\n"
return compliant, results
def reportDebian(self):
compliant = True
results = ""
dmlist = ["gdm", "gdm3", "lightdm", "xdm", "kdm"]
for dm in dmlist:
if self.sh.auditService(dm, _="_"):
compliant = False
results = dm + \
" is still in init folders; GUI logon is enabled\n"
return compliant, results
def reportUbuntu(self):
compliant = True
results = ""
ldmover = "/etc/init/lightdm.override"
grub = "/etc/default/grub"
if os.path.exists(ldmover):
lightdmText = readFile(ldmover, self.logger)
if not re.search("manual", lightdmText[0], re.IGNORECASE):
compliant = False
results += ldmover + ' exists, but does not contain text ' + \
'"manual". GUI logon is still enabled\n'
else:
compliant = False
results += ldmover + " does not exist; GUI logon is enabled\n"
if os.path.exists(grub):
tmppath = grub + ".tmp"
data = {"GRUB_CMDLINE_LINUX_DEFAULT": '"quiet"'}
editor = KVEditorStonix(self.statechglogger, self.logger, "conf",
grub, tmppath, data, "present", "closedeq")
if not editor.report():
compliant = False
results += grub + " does not contain the correct values: " + \
str(data)
else:
compliant = False
results += "Cannot find file " + grub
if not compliant:
results += "/etc/init does not contain proper override file " + \
"for lightdm; GUI logon is enabled\n"
return compliant, results
def fix(self):
'''@author: Eric Ball
:param self: essential if you override this definition
:returns: bool - True if fix is successful, False if it isn't
'''
try:
if not self.ci1.getcurrvalue() and not self.ci2.getcurrvalue() \
and not self.ci3.getcurrvalue():
return
success = True
self.detailedresults = ""
# Delete past state change records from previous fix
self.iditerator = 0
eventlist = self.statechglogger.findrulechanges(self.rulenumber)
for event in eventlist:
self.statechglogger.deleteentry(event)
# If we are doing DISABLEX or REMOVEX, we want to boot to
# non-graphical multi-user mode.
if self.ci1.getcurrvalue() or self.ci3.getcurrvalue():
success &= self.fixBootMode()
# Since LOCKDOWNX depends on having X installed, and REMOVEX
# completely removes X from the system, LOCKDOWNX fix will only be
# executed if REMOVEX is not.
if self.ci3.getcurrvalue():
success &= self.fixRemoveX()
elif self.ci2.getcurrvalue():
success &= self.fixLockdownX()
self.rulesuccess = success
except (KeyboardInterrupt, SystemExit):
# User initiated exit
raise
except Exception:
self.rulesuccess = False
self.detailedresults += "\n" + traceback.format_exc()
self.logdispatch.log(LogPriority.ERROR, self.detailedresults)
self.formatDetailedResults("fix", self.rulesuccess,
self.detailedresults)
self.logdispatch.log(LogPriority.INFO, self.detailedresults)
return self.rulesuccess
def fixBootMode(self):
success = True
if self.initver == "systemd":
cmd = ["/bin/systemctl", "set-default",
"multi-user.target"]
if not self.ch.executeCommand(cmd):
success = False
self.detailedresults += '"systemctl set-default ' \
+ 'multi-user.target" did not succeed\n'
else:
self.iditerator += 1
myid = iterate(self.iditerator, self.rulenumber)
commandstring = "/bin/systemctl set-default " + \
"graphical.target"
event = {"eventtype": "commandstring",
"command": commandstring}
self.statechglogger.recordchgevent(myid, event)
elif self.initver == "debian":
dmlist = ["gdm", "gdm3", "lightdm", "xdm", "kdm"]
for dm in dmlist:
cmd = ["update-rc.d", "-f", dm, "disable"]
if not self.ch.executeCommand(cmd):
self.detailedresults += "Failed to disable desktop " + \
"manager " + dm
else:
self.iditerator += 1
myid = iterate(self.iditerator, self.rulenumber)
event = {"eventtype": "servicehelper",
"servicename": dm,
"startstate": "enabled",
"endstate": "disabled"}
self.statechglogger.recordchgevent(myid, event)
elif self.initver == "ubuntu":
ldmover = "/etc/init/lightdm.override"
tmpfile = ldmover + ".tmp"
created = False
if not os.path.exists(ldmover):
createFile(ldmover, self.logger)
self.iditerator += 1
myid = iterate(self.iditerator, self.rulenumber)
event = {"eventtype": "creation", "filepath": ldmover}
self.statechglogger.recordchgevent(myid, event)
created = True
writeFile(tmpfile, "manual\n", self.logger)
if not created:
self.iditerator += 1
myid = iterate(self.iditerator, self.rulenumber)
event = {"eventtype": "conf", "filepath": ldmover}
self.statechglogger.recordchgevent(myid, event)
self.statechglogger.recordfilechange(ldmover, tmpfile, myid)
os.rename(tmpfile, ldmover)
resetsecon(ldmover)
grub = "/etc/default/grub"
if not os.path.exists(grub):
createFile(grub, self.logger)
self.iditerator += 1
myid = iterate(self.iditerator, self.rulenumber)
event = {"eventtype": "creation", "filepath": grub}
self.statechglogger.recordchgevent(myid, event)
tmppath = grub + ".tmp"
data = {"GRUB_CMDLINE_LINUX_DEFAULT": '"quiet"'}
editor = KVEditorStonix(self.statechglogger, self.logger,
"conf", grub, tmppath, data,
"present", "closedeq")
editor.report()
if editor.fixables:
if editor.fix():
self.iditerator += 1
myid = iterate(self.iditerator, self.rulenumber)
editor.setEventID(myid)
debug = "kveditor fix ran successfully\n"
self.logger.log(LogPriority.DEBUG, debug)
if editor.commit():
debug = "kveditor commit ran successfully\n"
self.logger.log(LogPriority.DEBUG, debug)
else:
error = "kveditor commit did not run " + \
"successfully\n"
self.logger.log(LogPriority.ERROR, error)
success = False
else:
error = "kveditor fix did not run successfully\n"
self.logger.log(LogPriority.ERROR, error)
success = False
cmd = "update-grub"
self.ch.executeCommand(cmd)
else:
inittab = "/etc/inittab"
tmpfile = inittab + ".tmp"
if os.path.exists(inittab):
initText = open(inittab, "r").read()
initre = r"id:\d:initdefault:"
if re.search(initre, initText):
initText = re.sub(initre, "id:3:initdefault:",
initText)
writeFile(tmpfile, initText, self.logger)
self.iditerator += 1
myid = iterate(self.iditerator, self.rulenumber)
event = {"eventtype": "conf", "filepath": inittab}
self.statechglogger.recordchgevent(myid, event)
self.statechglogger.recordfilechange(inittab,
tmpfile, myid)
os.rename(tmpfile, inittab)
resetsecon(inittab)
else:
initText += "\nid:3:initdefault:\n"
writeFile(tmpfile, initText, self.logger)
self.iditerator += 1
myid = iterate(self.iditerator, self.rulenumber)
event = {"eventtype": "conf", "filepath": inittab}
self.statechglogger.recordchgevent(myid, event)
self.statechglogger.recordfilechange(inittab,
tmpfile, myid)
os.rename(tmpfile, inittab)
resetsecon(inittab)
else:
self.detailedresults += inittab + " not found, no other " + \
"init system found. If you are using a supported " + \
"Linux OS, please report this as a bug\n"
return success
def fixRemoveX(self):
success = True
# Due to automatic removal of dependent packages, the full
# removal of X and related packages cannot be undone
if re.search("opensuse", self.myos):
cmd = ["zypper", "-n", "rm", "-u", "xorg-x11*", "kde*",
"xinit*"]
self.ch.executeCommand(cmd)
elif re.search("debian|ubuntu", self.myos):
xpkgs = ["unity.*", "xserver-xorg-video-ati",
"xserver-xorg-input-synaptics",
"xserver-xorg-input-wacom", "xserver-xorg-core",
"xserver-xorg", "lightdm.*", "libx11-data"]
for xpkg in xpkgs:
self.ph.remove(xpkg)
elif re.search("fedora", self.myos):
# Fedora does not use the same group packages as other
# RHEL-based OSs. Removing this package will remove the X
# Windows system, just less efficiently than using a group
self.ph.remove("xorg-x11-server-Xorg")
self.ph.remove("xorg-x11-xinit*")
else:
cmd = ["yum", "groups", "mark", "convert"]
self.ch.executeCommand(cmd)
self.ph.remove("xorg-x11-xinit")
self.ph.remove("xorg-x11-server-Xorg")
cmd2 = ["yum", "groupremove", "-y", "X Window System"]
if not self.ch.executeCommand(cmd2):
success = False
self.detailedresults += '"yum groupremove -y X Window System" command failed\n'
return success
def fixLockdownX(self):
success = True
if self.sh.disableService("xfs", _="_"):
self.iditerator += 1
myid = iterate(self.iditerator, self.rulenumber)
event = {"eventtype": "servicehelper",
"servicename": "xfs",
"startstate": "enabled",
"endstate": "disabled"}
self.statechglogger.recordchgevent(myid, event)
else:
success = False
self.detailedresults += "STONIX was unable to disable the " + \
"xfs service\n"
if not self.xservSecure:
serverrcString = "exec X :0 -nolisten tcp $@"
if not os.path.exists(self.serverrc):
createFile(self.serverrc, self.logger)
self.iditerator += 1
myid = iterate(self.iditerator, self.rulenumber)
event = {"eventtype": "creation",
"filepath": self.serverrc}
self.statechglogger.recordchgevent(myid, event)
writeFile(self.serverrc, serverrcString, self.logger)
else:
open(self.serverrc, "a").write(serverrcString)
return success
|
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'FormPlugin'
db.create_table(u'cmsplugin_formplugin', (
(u'cmsplugin_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['cms.CMSPlugin'], unique=True, primary_key=True)),
('form_class', self.gf('django.db.models.fields.CharField')(max_length=200)),
('success_url', self.gf('django.db.models.fields.URLField')(max_length=200, null=True)),
('post_to_url', self.gf('django.db.models.fields.URLField')(max_length=200)),
))
db.send_create_signal(u'cms_form_plugin', ['FormPlugin'])
def backwards(self, orm):
# Deleting model 'FormPlugin'
db.delete_table(u'cmsplugin_formplugin')
models = {
'cms.cmsplugin': {
'Meta': {'object_name': 'CMSPlugin'},
'changed_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'language': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}),
'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.CMSPlugin']", 'null': 'True', 'blank': 'True'}),
'placeholder': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Placeholder']", 'null': 'True'}),
'plugin_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}),
'position': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})
},
'cms.placeholder': {
'Meta': {'object_name': 'Placeholder'},
'default_width': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'slot': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'})
},
u'cms_form_plugin.formplugin': {
'Meta': {'object_name': 'FormPlugin', 'db_table': "u'cmsplugin_formplugin'", '_ormbases': ['cms.CMSPlugin']},
u'cmsplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['cms.CMSPlugin']", 'unique': 'True', 'primary_key': 'True'}),
'form_class': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'post_to_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}),
'success_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True'})
}
}
complete_apps = ['cms_form_plugin']
|
from utils import scaleToZoom
def jsonScript(layer):
json = """
<script src="data/json_{layer}.js\"></script>""".format(layer=layer)
return json
def scaleDependentLayerScript(layer, layerName):
min = layer.minimumScale()
max = layer.maximumScale()
scaleDependentLayer = """
if (map.getZoom() <= {min} && map.getZoom() >= {max}) {{
feature_group.addLayer(json_{layerName}JSON);
console.log("show");
//restackLayers();
}} else if (map.getZoom() > {min} || map.getZoom() < {max}) {{
feature_group.removeLayer(json_{layerName}JSON);
console.log("hide");
//restackLayers();
}}""".format(min=scaleToZoom(min), max=scaleToZoom(max), layerName=layerName)
return scaleDependentLayer
def scaleDependentScript(layers):
scaleDependent = """
map.on("zoomend", function(e) {"""
scaleDependent += layers
scaleDependent += """
});"""
scaleDependent += layers
return scaleDependent
def openScript():
openScript = """
<script>"""
return openScript
def crsScript(crsAuthId, crsProj4):
crs = """
var crs = new L.Proj.CRS('{crsAuthId}', '{crsProj4}', {{
resolutions: [2800, 1400, 700, 350, 175, 84, 42, 21, 11.2, 5.6, 2.8, 1.4, 0.7, 0.35, 0.14, 0.07],
}});""".format(crsAuthId=crsAuthId, crsProj4=crsProj4)
return crs
def mapScript(extent, matchCRS, crsAuthId, measure, maxZoom, minZoom, bounds):
map = """
var map = L.map('map', {"""
if extent == "Canvas extent" and matchCRS and crsAuthId != 'EPSG:4326':
map += """
crs: crs,
continuousWorld: false,
worldCopyJump: false, """
if measure:
map += """
measureControl:true,"""
map += """
zoomControl:true, maxZoom:""" + unicode(maxZoom) + """, minZoom:""" + unicode(minZoom) + """
})"""
if extent == "Canvas extent":
map += """.fitBounds(""" + bounds + """);"""
map += """
var hash = new L.Hash(map);
var additional_attrib = '<a href="https://github.com/tomchadwin/qgis2web" target ="_blank">qgis2web</a>';"""
return map
def featureGroupsScript():
featureGroups = """
var feature_group = new L.featureGroup([]);
var raster_group = new L.LayerGroup([]);"""
return featureGroups
def basemapsScript(basemap, attribution):
basemaps = """
var basemap = L.tileLayer('{basemap}', {{
attribution: additional_attrib + ' {attribution}'
}});
basemap.addTo(map);""".format(basemap=basemap, attribution=attribution)
return basemaps
def layerOrderScript():
layerOrder = """
var layerOrder=new Array();
function restackLayers() {
for (index = 0; index < layerOrder.length; index++) {
feature_group.removeLayer(layerOrder[index]);
feature_group.addLayer(layerOrder[index]);
}
}
layerControl = L.control.layers({},{},{collapsed:false});"""
return layerOrder
def popFuncsScript(table):
popFuncs = """
var popupContent = {table};
layer.bindPopup(popupContent);""".format(table=table)
return popFuncs
def popupScript(safeLayerName, popFuncs):
popup = """
function pop_{safeLayerName}(feature, layer) {{{popFuncs}
}}""".format(safeLayerName=safeLayerName, popFuncs=popFuncs)
return popup
def pointToLayerScript(radius, borderWidth, borderStyle, colorName, borderColor, borderOpacity, opacity, labeltext):
pointToLayer = """
pointToLayer: function (feature, latlng) {{
return L.circleMarker(latlng, {{
radius: {radius},
fillColor: '{colorName}',
color: '{borderColor}',
weight: {borderWidth},
opacity: {borderOpacity},
dashArray: '{dashArray}',
fillOpacity: {opacity}
}}){labeltext}""".format(radius=radius,
colorName=colorName,
borderColor=borderColor,
borderWidth=borderWidth * 4,
borderOpacity=borderOpacity if borderStyle != 0 else 0,
dashArray=getLineStyle(borderStyle, borderWidth),
opacity=opacity,
labeltext=labeltext)
return pointToLayer
def pointStyleScript(pointToLayer, popFuncs):
pointStyle = """{pointToLayer}
}},
onEachFeature: function (feature, layer) {{{popFuncs}
}}""".format(pointToLayer=pointToLayer, popFuncs=popFuncs)
return pointStyle
def wfsScript(scriptTag):
wfs = """
<script src='{scriptTag}'></script>""".format(scriptTag=scriptTag)
return wfs
def jsonPointScript(safeLayerName, pointToLayer, usedFields):
if usedFields != 0:
jsonPoint = """
var json_{safeLayerName}JSON = new L.geoJson(json_{safeLayerName}, {{
onEachFeature: pop_{safeLayerName}, {pointToLayer}
}}
}});
layerOrder[layerOrder.length] = json_{safeLayerName}JSON;""".format(safeLayerName=safeLayerName, pointToLayer=pointToLayer)
else:
jsonPoint = """
var json_{safeLayerName}JSON = new L.geoJson(json_{safeLayerName}, {{
{pointToLayer}
}}
}});
layerOrder[layerOrder.length] = json_{safeLayerName}JSON;""".format(safeLayerName=safeLayerName, pointToLayer=pointToLayer)
return jsonPoint
def clusterScript(safeLayerName):
cluster = """
var cluster_group{safeLayerName}JSON = new L.MarkerClusterGroup({{showCoverageOnHover: false}});
cluster_group{safeLayerName}JSON.addLayer(json_{safeLayerName}JSON);""".format(safeLayerName=safeLayerName)
return cluster
def categorizedPointStylesScript(symbol, opacity, borderOpacity):
styleValues = """
radius: '{radius}',
fillColor: '{fillColor}',
color: '{color}',
weight: {borderWidth},
opacity: {borderOpacity},
dashArray: '{dashArray}',
fillOpacity: '{opacity}',
}};
break;""".format(radius=symbol.size() * 2,
fillColor=symbol.color().name(),
color=symbol.symbolLayer(0).borderColor().name(),
borderWidth=symbol.symbolLayer(0).outlineWidth() * 4,
borderOpacity=borderOpacity if symbol.symbolLayer(0).outlineStyle() != 0 else 0,
dashArray=getLineStyle(symbol.symbolLayer(0).outlineStyle(), symbol.symbolLayer(0).outlineWidth()),
opacity=opacity)
return styleValues
def simpleLineStyleScript(radius, colorName, penStyle, opacity):
lineStyle = """
return {{
weight: {radius},
color: '{colorName}',
dashArray: '{penStyle}',
opacity: {opacity}
}};""".format(radius=radius * 4,
colorName=colorName,
penStyle=penStyle,
opacity=opacity)
return lineStyle
def singlePolyStyleScript(radius, colorName, borderOpacity, fillColor, penStyle, opacity):
polyStyle = """
return {{
weight: {radius},
color: '{colorName}',
fillColor: '{fillColor}',
dashArray: '{penStyle}',
opacity: {borderOpacity},
fillOpacity: {opacity}
}};""".format(radius=radius,
colorName=colorName,
fillColor=fillColor,
penStyle=penStyle,
borderOpacity=borderOpacity,
opacity=opacity)
return polyStyle
def nonPointStylePopupsScript(lineStyle, popFuncs):
nonPointStylePopups = """
style: function (feature) {{{lineStyle}
}},
onEachFeature: function (feature, layer) {{{popFuncs}
}}""".format(lineStyle=lineStyle, popFuncs=popFuncs)
return nonPointStylePopups
def nonPointStyleFunctionScript(safeLayerName, lineStyle):
nonPointStyleFunction = """
function doStyle{safeLayerName}(feature) {{{lineStyle}
}}""".format(safeLayerName=safeLayerName, lineStyle=lineStyle)
return nonPointStyleFunction
def categoryScript(layerName, valueAttr):
category = """
function doStyle{layerName}(feature) {{
switch (feature.properties.{valueAttr}) {{""".format(layerName=layerName, valueAttr=valueAttr)
return category
def defaultCategoryScript():
defaultCategory = """
default:
return {"""
return defaultCategory
def eachCategoryScript(catValue):
if isinstance(catValue, basestring):
valQuote = "'"
else:
valQuote = ""
eachCategory = """
case """ + valQuote + unicode(catValue) + valQuote + """:
return {"""
return eachCategory
def endCategoryScript():
endCategory = """
}
}"""
return endCategory
def categorizedPointWFSscript(layerName, labeltext, popFuncs):
categorizedPointWFS = """
pointToLayer: function (feature, latlng) {{
return L.circleMarker(latlng, doStyle{layerName}(feature)){labeltext}
}},
onEachFeature: function (feature, layer) {{{popFuncs}
}}""".format(layerName=layerName, labeltext=labeltext, popFuncs=popFuncs)
return categorizedPointWFS
def categorizedPointJSONscript(safeLayerName, labeltext, usedFields):
if usedFields != 0:
categorizedPointJSON = """
var json_{safeLayerName}JSON = new L.geoJson(json_{safeLayerName}, {{
onEachFeature: pop_{safeLayerName},
pointToLayer: function (feature, latlng) {{
return L.circleMarker(latlng, doStyle{safeLayerName}(feature)){labeltext}
}}
}});
layerOrder[layerOrder.length] = json_{safeLayerName}JSON;""".format(safeLayerName=safeLayerName, labeltext=labeltext)
else:
categorizedPointJSON = """
var json_{safeLayerName}JSON = new L.geoJson(json_{safeLayerName}, {{
pointToLayer: function (feature, latlng) {{
return L.circleMarker(latlng, doStyle{safeLayerName}(feature)){labeltext}
}}
}});
layerOrder[layerOrder.length] = json_{safeLayerName}JSON;""".format(safeLayerName=safeLayerName, labeltext=labeltext)
return categorizedPointJSON
def categorizedLineStylesScript(symbol, opacity):
categorizedLineStyles = """
color: '{color}',
weight: '{weight}',
dashArray: '{dashArray}',
opacity: '{opacity}',
}};
break;""".format(color=symbol.color().name(),
weight=symbol.width() * 4,
dashArray=getLineStyle(symbol.symbolLayer(0).penStyle(), symbol.width()),
opacity=opacity)
return categorizedLineStyles
def categorizedNonPointStyleFunctionScript(layerName, popFuncs):
categorizedNonPointStyleFunction = """
style: doStyle{layerName},
onEachFeature: function (feature, layer) {{{popFuncs}
}}""".format(layerName=layerName, popFuncs=popFuncs)
return categorizedNonPointStyleFunction
def categorizedPolygonStylesScript(symbol, opacity, borderOpacity):
categorizedPolygonStyles = """
weight: '{weight}',
fillColor: '{fillColor}',
color: '{color}',
dashArray: '{dashArray}',
opacity: '{borderOpacity}',
fillOpacity: '{opacity}',
}};
break;""".format(weight=symbol.symbolLayer(0).borderWidth() * 4,
fillColor=symbol.color().name() if symbol.symbolLayer(0).brushStyle() != 0 else "none",
color=symbol.symbolLayer(0).borderColor().name() if symbol.symbolLayer(0).borderStyle() != 0 else "none",
dashArray=getLineStyle(symbol.symbolLayer(0).borderStyle(), symbol.symbolLayer(0).borderWidth()),
borderOpacity=borderOpacity,
opacity=opacity)
return categorizedPolygonStyles
def graduatedStyleScript(layerName):
graduatedStyle = """
function doStyle{layerName}(feature) {{""".format(layerName=layerName)
return graduatedStyle
def rangeStartScript(valueAttr, r):
rangeStart = """
if (feature.properties.{valueAttr} >= {lowerValue} && feature.properties.{valueAttr} <= {upperValue}) {{""".format(valueAttr=valueAttr, lowerValue=r.lowerValue(), upperValue=r.upperValue())
return rangeStart
def graduatedPointStylesScript(valueAttr, r, symbol, opacity, borderOpacity):
graduatedPointStyles = rangeStartScript(valueAttr, r)
graduatedPointStyles += """
return {{
radius: '{radius}',
fillColor: '{fillColor}',
color: '{color}',
weight: {lineWeight},
fillOpacity: '{opacity}',
opacity: '{borderOpacity}',
dashArray: '{dashArray}'
}}
}}""".format(radius=symbol.size() * 2,
fillColor=symbol.color().name(),
color=symbol.symbolLayer(0).borderColor().name(),
lineWeight=symbol.symbolLayer(0).outlineWidth() * 4,
opacity=opacity,
borderOpacity=borderOpacity,
dashArray=getLineStyle(symbol.symbolLayer(0).outlineStyle(), symbol.symbolLayer(0).outlineWidth()))
return graduatedPointStyles
def graduatedLineStylesScript(valueAttr, r, categoryStr, symbol, opacity):
graduatedLineStyles = rangeStartScript(valueAttr, r)
graduatedLineStyles += """
return {{
color: '{color}',
weight: '{weight}',
dashArray: '{dashArray}',
opacity: '{opacity}',
}}
}}""".format(color=symbol.symbolLayer(0).color().name(),
weight=symbol.width() * 4,
dashArray=getLineStyle(symbol.symbolLayer(0).penStyle(), symbol.width()),
opacity=opacity)
return graduatedLineStyles
def graduatedPolygonStylesScript(valueAttr, r, symbol, opacity, borderOpacity):
graduatedPolygonStyles = rangeStartScript(valueAttr, r)
graduatedPolygonStyles += """
return {{
color: '{color}',
weight: '{weight}',
dashArray: '{dashArray}',
fillColor: '{fillColor}',
opacity: '{borderOpacity}',
fillOpacity: '{opacity}',
}}
}}""".format(color=symbol.symbolLayer(0).borderColor().name(),
weight=symbol.symbolLayer(0).borderWidth() * 4 if symbol.symbolLayer(0).borderStyle() != 0 else "0",
dashArray=getLineStyle(symbol.symbolLayer(0).borderStyle(), symbol.symbolLayer(0).borderWidth() if symbol.symbolLayer(0).borderStyle() != 0 else "0"),
fillColor=symbol.color().name() if symbol.symbolLayer(0).brushStyle() != 0 else "none",
borderOpacity=borderOpacity,
opacity=opacity)
return graduatedPolygonStyles
def endGraduatedStyleScript():
endGraduatedStyle = """
}"""
return endGraduatedStyle
def customMarkerScript(safeLayerName, labeltext, usedFields):
if usedFields != 0:
customMarker = """
var json_{safeLayerName}JSON = new L.geoJson(json_{safeLayerName}, {{
onEachFeature: pop_{safeLayerName},
pointToLayer: function (feature, latlng) {{
return L.marker(latlng, {{
icon: L.icon({{
iconUrl: feature.properties.icon_exp,
iconSize: [24, 24], // size of the icon change this to scale your icon (first coordinate is x, second y from the upper left corner of the icon)
iconAnchor: [12, 12], // point of the icon which will correspond to marker's location (first coordinate is x, second y from the upper left corner of the icon)
popupAnchor: [0, -14] // point from which the popup should open relative to the iconAnchor (first coordinate is x, second y from the upper left corner of the icon)
}})
}}){labeltext}
}}}}
);""".format(safeLayerName=safeLayerName, labeltext=labeltext)
else:
customMarker = """
var json_{safeLayerName}JSON = new L.geoJson(json_{safeLayerName}, {{
pointToLayer: function (feature, latlng) {{
return L.marker(latlng, {{
icon: L.icon({{
iconUrl: feature.properties.icon_exp,
iconSize: [24, 24], // size of the icon change this to scale your icon (first coordinate is x, second y from the upper left corner of the icon)
iconAnchor: [12, 12], // point of the icon which will correspond to marker's location (first coordinate is x, second y from the upper left corner of the icon)
popupAnchor: [0, -14] // point from which the popup should open relative to the iconAnchor (first coordinate is x, second y from the upper left corner of the icon)
}})
}}){labeltext}
}}}}
);""".format(safeLayerName=safeLayerName, labeltext=labeltext)
return customMarker
def wmsScript(safeLayerName, wms_url, wms_layer, wms_format):
wms = """
var overlay_{safeLayerName} = L.tileLayer.wms('{wms_url}', {{
layers: '{wms_layer}',
format: '{wms_format}',
transparent: true,
continuousWorld : true,
}});""".format(safeLayerName=safeLayerName,
wms_url=wms_url,
wms_layer=wms_layer,
wms_format=wms_format)
return wms
def rasterScript(safeLayerName, out_raster_name, bounds):
raster = """
var img_{safeLayerName} = '{out_raster_name}';
var img_bounds_{safeLayerName} = {bounds};
var overlay_{safeLayerName} = new L.imageOverlay(img_{safeLayerName}, img_bounds_{safeLayerName});""".format(safeLayerName=safeLayerName, out_raster_name=out_raster_name, bounds=bounds)
return raster
def titleSubScript(webmap_head, webmap_subhead):
titleSub = """
var title = new L.Control();
title.onAdd = function (map) {
this._div = L.DomUtil.create('div', 'info'); // create a div with a class "info"
this.update();
return this._div;
};
title.update = function () {
this._div.innerHTML = '<h2>""" + webmap_head.encode('utf-8') + """</h2>""" + webmap_subhead.encode('utf-8') + """'
};
title.addTo(map);"""
return titleSub
def addressSearchScript():
addressSearch = """
var osmGeocoder = new L.Control.OSMGeocoder({
collapsed: false,
position: 'topright',
text: 'Search',
});
osmGeocoder.addTo(map);"""
return addressSearch
def locateScript():
locate = """
map.locate({setView: true, maxZoom: 16});
function onLocationFound(e) {
var radius = e.accuracy / 2;
L.marker(e.latlng).addTo(map)
.bindPopup("You are within " + radius + " meters from this point").openPopup();
L.circle(e.latlng, radius).addTo(map);
}
map.on('locationfound', onLocationFound);
"""
return locate
def endHTMLscript(wfsLayers):
endHTML = """
</script>{wfsLayers}
</body>
</html>""".format(wfsLayers=wfsLayers)
return endHTML
def getLineStyle(penType, lineWidth):
dash = lineWidth * 10
dot = lineWidth * 1
gap = lineWidth * 5
if penType > 1:
if penType == 2:
penStyle = [dash, gap]
if penType == 3:
penStyle = [dot, gap]
if penType == 4:
penStyle = [dash, gap, dot, gap]
if penType == 5:
penStyle = [dash, gap, dot, gap, dot, gap]
penStyle = ','.join(map(str, penStyle))
else:
penStyle = ""
return penStyle
|
class Solution:
def reverseWords(self, s) :
print 1 / 0
tks = s.split(' ');
tks = filter(None, tks)
tks.reverse();
return ' '.join(tks).strip()
test = ["the sky is blue", " a b "]
sol = Solution();
for t in test :
print sol.reverseWords(t)
|
from netools import nextIpInPool, ping, aliveHost, hostsUnDone
def main():
aliveHosts = []
# pool IP
ipStart = "192.168.56.1"
ipEnd = "192.168.56.5"
print"Pools: ", ipStart + " -> " + ipEnd
print"Scanning online Router on network..."
aliveHosts = aliveHost(ipStart, ipEnd)
print "online Router:"
print aliveHosts
if __name__ == '__main__':
main()
|
import collections
import re
import sys
import warnings
from bs4.dammit import EntitySubstitution
DEFAULT_OUTPUT_ENCODING = "utf-8"
PY3K = (sys.version_info[0] > 2)
whitespace_re = re.compile("\s+")
def _alias(attr):
"""Alias one attribute name to another for backward compatibility"""
@property
def alias(self):
return getattr(self, attr)
@alias.setter
def alias(self):
return setattr(self, attr)
return alias
class NamespacedAttribute(unicode):
def __new__(cls, prefix, name, namespace=None):
if name is None:
obj = unicode.__new__(cls, prefix)
elif prefix is None:
# Not really namespaced.
obj = unicode.__new__(cls, name)
else:
obj = unicode.__new__(cls, prefix + ":" + name)
obj.prefix = prefix
obj.name = name
obj.namespace = namespace
return obj
class AttributeValueWithCharsetSubstitution(unicode):
"""A stand-in object for a character encoding specified in HTML."""
class CharsetMetaAttributeValue(AttributeValueWithCharsetSubstitution):
"""A generic stand-in for the value of a meta tag's 'charset' attribute.
When Beautiful Soup parses the markup '<meta charset="utf8">', the
value of the 'charset' attribute will be one of these objects.
"""
def __new__(cls, original_value):
obj = unicode.__new__(cls, original_value)
obj.original_value = original_value
return obj
def encode(self, encoding):
return encoding
class ContentMetaAttributeValue(AttributeValueWithCharsetSubstitution):
"""A generic stand-in for the value of a meta tag's 'content' attribute.
When Beautiful Soup parses the markup:
<meta http-equiv="content-type" content="text/html; charset=utf8">
The value of the 'content' attribute will be one of these objects.
"""
CHARSET_RE = re.compile("((^|;)\s*charset=)([^;]*)", re.M)
def __new__(cls, original_value):
match = cls.CHARSET_RE.search(original_value)
if match is None:
# No substitution necessary.
return unicode.__new__(unicode, original_value)
obj = unicode.__new__(cls, original_value)
obj.original_value = original_value
return obj
def encode(self, encoding):
def rewrite(match):
return match.group(1) + encoding
return self.CHARSET_RE.sub(rewrite, self.original_value)
class HTMLAwareEntitySubstitution(EntitySubstitution):
"""Entity substitution rules that are aware of some HTML quirks.
Specifically, the contents of <script> and <style> tags should not
undergo entity substitution.
Incoming NavigableString objects are checked to see if they're the
direct children of a <script> or <style> tag.
"""
cdata_containing_tags = set(["script", "style"])
preformatted_tags = set(["pre"])
@classmethod
def _substitute_if_appropriate(cls, ns, f):
if (isinstance(ns, NavigableString)
and ns.parent is not None
and ns.parent.name in cls.cdata_containing_tags):
# Do nothing.
return ns
# Substitute.
return f(ns)
@classmethod
def substitute_html(cls, ns):
return cls._substitute_if_appropriate(
ns, EntitySubstitution.substitute_html)
@classmethod
def substitute_xml(cls, ns):
return cls._substitute_if_appropriate(
ns, EntitySubstitution.substitute_xml)
class PageElement(object):
"""Contains the navigational information for some part of the page
(either a tag or a piece of text)"""
# There are five possible values for the "formatter" argument passed in
# to methods like encode() and prettify():
#
# "html" - All Unicode characters with corresponding HTML entities
# are converted to those entities on output.
# "minimal" - Bare ampersands and angle brackets are converted to
# XML entities: & < >
# None - The null formatter. Unicode characters are never
# converted to entities. This is not recommended, but it's
# faster than "minimal".
# A function - This function will be called on every string that
# needs to undergo entity substitution.
#
# In an HTML document, the default "html" and "minimal" functions
# will leave the contents of <script> and <style> tags alone. For
# an XML document, all tags will be given the same treatment.
HTML_FORMATTERS = {
"html" : HTMLAwareEntitySubstitution.substitute_html,
"minimal" : HTMLAwareEntitySubstitution.substitute_xml,
None : None
}
XML_FORMATTERS = {
"html" : EntitySubstitution.substitute_html,
"minimal" : EntitySubstitution.substitute_xml,
None : None
}
def format_string(self, s, formatter='minimal'):
"""Format the given string using the given formatter."""
if not callable(formatter):
formatter = self._formatter_for_name(formatter)
if formatter is None:
output = s
else:
output = formatter(s)
return output
@property
def _is_xml(self):
"""Is this element part of an XML tree or an HTML tree?
This is used when mapping a formatter name ("minimal") to an
appropriate function (one that performs entity-substitution on
the contents of <script> and <style> tags, or not). It's
inefficient, but it should be called very rarely.
"""
if self.parent is None:
# This is the top-level object. It should have .is_xml set
# from tree creation. If not, take a guess--BS is usually
# used on HTML markup.
return getattr(self, 'is_xml', False)
return self.parent._is_xml
def _formatter_for_name(self, name):
"Look up a formatter function based on its name and the tree."
if self._is_xml:
return self.XML_FORMATTERS.get(
name, EntitySubstitution.substitute_xml)
else:
return self.HTML_FORMATTERS.get(
name, HTMLAwareEntitySubstitution.substitute_xml)
def setup(self, parent=None, previous_element=None):
"""Sets up the initial relations between this element and
other elements."""
self.parent = parent
self.previous_element = previous_element
if previous_element is not None:
self.previous_element.next_element = self
self.next_element = None
self.previous_sibling = None
self.next_sibling = None
if self.parent is not None and self.parent.contents:
self.previous_sibling = self.parent.contents[-1]
self.previous_sibling.next_sibling = self
nextSibling = _alias("next_sibling") # BS3
previousSibling = _alias("previous_sibling") # BS3
def replace_with(self, replace_with):
if replace_with is self:
return
if replace_with is self.parent:
raise ValueError("Cannot replace a Tag with its parent.")
old_parent = self.parent
my_index = self.parent.index(self)
self.extract()
old_parent.insert(my_index, replace_with)
return self
replaceWith = replace_with # BS3
def unwrap(self):
my_parent = self.parent
my_index = self.parent.index(self)
self.extract()
for child in reversed(self.contents[:]):
my_parent.insert(my_index, child)
return self
replace_with_children = unwrap
replaceWithChildren = unwrap # BS3
def wrap(self, wrap_inside):
me = self.replace_with(wrap_inside)
wrap_inside.append(me)
return wrap_inside
def extract(self):
"""Destructively rips this element out of the tree."""
if self.parent is not None:
del self.parent.contents[self.parent.index(self)]
#Find the two elements that would be next to each other if
#this element (and any children) hadn't been parsed. Connect
#the two.
last_child = self._last_descendant()
next_element = last_child.next_element
if self.previous_element is not None:
self.previous_element.next_element = next_element
if next_element is not None:
next_element.previous_element = self.previous_element
self.previous_element = None
last_child.next_element = None
self.parent = None
if self.previous_sibling is not None:
self.previous_sibling.next_sibling = self.next_sibling
if self.next_sibling is not None:
self.next_sibling.previous_sibling = self.previous_sibling
self.previous_sibling = self.next_sibling = None
return self
def _last_descendant(self):
"Finds the last element beneath this object to be parsed."
last_child = self
while hasattr(last_child, 'contents') and last_child.contents:
last_child = last_child.contents[-1]
return last_child
# BS3: Not part of the API!
_lastRecursiveChild = _last_descendant
def insert(self, position, new_child):
if new_child is self:
raise ValueError("Cannot insert a tag into itself.")
if (isinstance(new_child, basestring)
and not isinstance(new_child, NavigableString)):
new_child = NavigableString(new_child)
position = min(position, len(self.contents))
if hasattr(new_child, 'parent') and new_child.parent is not None:
# We're 'inserting' an element that's already one
# of this object's children.
if new_child.parent is self:
current_index = self.index(new_child)
if current_index < position:
# We're moving this element further down the list
# of this object's children. That means that when
# we extract this element, our target index will
# jump down one.
position -= 1
new_child.extract()
new_child.parent = self
previous_child = None
if position == 0:
new_child.previous_sibling = None
new_child.previous_element = self
else:
previous_child = self.contents[position - 1]
new_child.previous_sibling = previous_child
new_child.previous_sibling.next_sibling = new_child
new_child.previous_element = previous_child._last_descendant()
if new_child.previous_element is not None:
new_child.previous_element.next_element = new_child
new_childs_last_element = new_child._last_descendant()
if position >= len(self.contents):
new_child.next_sibling = None
parent = self
parents_next_sibling = None
while parents_next_sibling is None and parent is not None:
parents_next_sibling = parent.next_sibling
parent = parent.parent
if parents_next_sibling is not None:
# We found the element that comes next in the document.
break
if parents_next_sibling is not None:
new_childs_last_element.next_element = parents_next_sibling
else:
# The last element of this tag is the last element in
# the document.
new_childs_last_element.next_element = None
else:
next_child = self.contents[position]
new_child.next_sibling = next_child
if new_child.next_sibling is not None:
new_child.next_sibling.previous_sibling = new_child
new_childs_last_element.next_element = next_child
if new_childs_last_element.next_element is not None:
new_childs_last_element.next_element.previous_element = new_childs_last_element
self.contents.insert(position, new_child)
def append(self, tag):
"""Appends the given tag to the contents of this tag."""
self.insert(len(self.contents), tag)
def insert_before(self, predecessor):
"""Makes the given element the immediate predecessor of this one.
The two elements will have the same parent, and the given element
will be immediately before this one.
"""
if self is predecessor:
raise ValueError("Can't insert an element before itself.")
parent = self.parent
if parent is None:
raise ValueError(
"Element has no parent, so 'before' has no meaning.")
# Extract first so that the index won't be screwed up if they
# are siblings.
if isinstance(predecessor, PageElement):
predecessor.extract()
index = parent.index(self)
parent.insert(index, predecessor)
def insert_after(self, successor):
"""Makes the given element the immediate successor of this one.
The two elements will have the same parent, and the given element
will be immediately after this one.
"""
if self is successor:
raise ValueError("Can't insert an element after itself.")
parent = self.parent
if parent is None:
raise ValueError(
"Element has no parent, so 'after' has no meaning.")
# Extract first so that the index won't be screwed up if they
# are siblings.
if isinstance(successor, PageElement):
successor.extract()
index = parent.index(self)
parent.insert(index+1, successor)
def find_next(self, name=None, attrs={}, text=None, **kwargs):
"""Returns the first item that matches the given criteria and
appears after this Tag in the document."""
return self._find_one(self.find_all_next, name, attrs, text, **kwargs)
findNext = find_next # BS3
def find_all_next(self, name=None, attrs={}, text=None, limit=None,
**kwargs):
"""Returns all items that match the given criteria and appear
after this Tag in the document."""
return self._find_all(name, attrs, text, limit, self.next_elements,
**kwargs)
findAllNext = find_all_next # BS3
def find_next_sibling(self, name=None, attrs={}, text=None, **kwargs):
"""Returns the closest sibling to this Tag that matches the
given criteria and appears after this Tag in the document."""
return self._find_one(self.find_next_siblings, name, attrs, text,
**kwargs)
findNextSibling = find_next_sibling # BS3
def find_next_siblings(self, name=None, attrs={}, text=None, limit=None,
**kwargs):
"""Returns the siblings of this Tag that match the given
criteria and appear after this Tag in the document."""
return self._find_all(name, attrs, text, limit,
self.next_siblings, **kwargs)
findNextSiblings = find_next_siblings # BS3
fetchNextSiblings = find_next_siblings # BS2
def find_previous(self, name=None, attrs={}, text=None, **kwargs):
"""Returns the first item that matches the given criteria and
appears before this Tag in the document."""
return self._find_one(
self.find_all_previous, name, attrs, text, **kwargs)
findPrevious = find_previous # BS3
def find_all_previous(self, name=None, attrs={}, text=None, limit=None,
**kwargs):
"""Returns all items that match the given criteria and appear
before this Tag in the document."""
return self._find_all(name, attrs, text, limit, self.previous_elements,
**kwargs)
findAllPrevious = find_all_previous # BS3
fetchPrevious = find_all_previous # BS2
def find_previous_sibling(self, name=None, attrs={}, text=None, **kwargs):
"""Returns the closest sibling to this Tag that matches the
given criteria and appears before this Tag in the document."""
return self._find_one(self.find_previous_siblings, name, attrs, text,
**kwargs)
findPreviousSibling = find_previous_sibling # BS3
def find_previous_siblings(self, name=None, attrs={}, text=None,
limit=None, **kwargs):
"""Returns the siblings of this Tag that match the given
criteria and appear before this Tag in the document."""
return self._find_all(name, attrs, text, limit,
self.previous_siblings, **kwargs)
findPreviousSiblings = find_previous_siblings # BS3
fetchPreviousSiblings = find_previous_siblings # BS2
def find_parent(self, name=None, attrs={}, **kwargs):
"""Returns the closest parent of this Tag that matches the given
criteria."""
# NOTE: We can't use _find_one because findParents takes a different
# set of arguments.
r = None
l = self.find_parents(name, attrs, 1, **kwargs)
if l:
r = l[0]
return r
findParent = find_parent # BS3
def find_parents(self, name=None, attrs={}, limit=None, **kwargs):
"""Returns the parents of this Tag that match the given
criteria."""
return self._find_all(name, attrs, None, limit, self.parents,
**kwargs)
findParents = find_parents # BS3
fetchParents = find_parents # BS2
@property
def next(self):
return self.next_element
@property
def previous(self):
return self.previous_element
#These methods do the real heavy lifting.
def _find_one(self, method, name, attrs, text, **kwargs):
r = None
l = method(name, attrs, text, 1, **kwargs)
if l:
r = l[0]
return r
def _find_all(self, name, attrs, text, limit, generator, **kwargs):
"Iterates over a generator looking for things that match."
if isinstance(name, SoupStrainer):
strainer = name
elif text is None and not limit and not attrs and not kwargs:
# Optimization to find all tags.
if name is True or name is None:
return [element for element in generator
if isinstance(element, Tag)]
# Optimization to find all tags with a given name.
elif isinstance(name, basestring):
return [element for element in generator
if isinstance(element, Tag) and element.name == name]
else:
strainer = SoupStrainer(name, attrs, text, **kwargs)
else:
# Build a SoupStrainer
strainer = SoupStrainer(name, attrs, text, **kwargs)
results = ResultSet(strainer)
while True:
try:
i = next(generator)
except StopIteration:
break
if i:
found = strainer.search(i)
if found:
results.append(found)
if limit and len(results) >= limit:
break
return results
#These generators can be used to navigate starting from both
#NavigableStrings and Tags.
@property
def next_elements(self):
i = self.next_element
while i is not None:
yield i
i = i.next_element
@property
def next_siblings(self):
i = self.next_sibling
while i is not None:
yield i
i = i.next_sibling
@property
def previous_elements(self):
i = self.previous_element
while i is not None:
yield i
i = i.previous_element
@property
def previous_siblings(self):
i = self.previous_sibling
while i is not None:
yield i
i = i.previous_sibling
@property
def parents(self):
i = self.parent
while i is not None:
yield i
i = i.parent
# Methods for supporting CSS selectors.
tag_name_re = re.compile('^[a-z0-9]+$')
# /^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
# \---/ \---/\-------------/ \-------/
# | | | |
# | | | The value
# | | ~,|,^,$,* or =
# | Attribute
# Tag
attribselect_re = re.compile(
r'^(?P<tag>\w+)?\[(?P<attribute>\w+)(?P<operator>[=~\|\^\$\*]?)' +
r'=?"?(?P<value>[^\]"]*)"?\]$'
)
def _attr_value_as_string(self, value, default=None):
"""Force an attribute value into a string representation.
A multi-valued attribute will be converted into a
space-separated stirng.
"""
value = self.get(value, default)
if isinstance(value, list) or isinstance(value, tuple):
value =" ".join(value)
return value
def _tag_name_matches_and(self, function, tag_name):
if not tag_name:
return function
else:
def _match(tag):
return tag.name == tag_name and function(tag)
return _match
def _attribute_checker(self, operator, attribute, value=''):
"""Create a function that performs a CSS selector operation.
Takes an operator, attribute and optional value. Returns a
function that will return True for elements that match that
combination.
"""
if operator == '=':
# string representation of `attribute` is equal to `value`
return lambda el: el._attr_value_as_string(attribute) == value
elif operator == '~':
# space-separated list representation of `attribute`
# contains `value`
def _includes_value(element):
attribute_value = element.get(attribute, [])
if not isinstance(attribute_value, list):
attribute_value = attribute_value.split()
return value in attribute_value
return _includes_value
elif operator == '^':
# string representation of `attribute` starts with `value`
return lambda el: el._attr_value_as_string(
attribute, '').startswith(value)
elif operator == '$':
# string represenation of `attribute` ends with `value`
return lambda el: el._attr_value_as_string(
attribute, '').endswith(value)
elif operator == '*':
# string representation of `attribute` contains `value`
return lambda el: value in el._attr_value_as_string(attribute, '')
elif operator == '|':
# string representation of `attribute` is either exactly
# `value` or starts with `value` and then a dash.
def _is_or_starts_with_dash(element):
attribute_value = element._attr_value_as_string(attribute, '')
return (attribute_value == value or attribute_value.startswith(
value + '-'))
return _is_or_starts_with_dash
else:
return lambda el: el.has_attr(attribute)
# Old non-property versions of the generators, for backwards
# compatibility with BS3.
def nextGenerator(self):
return self.next_elements
def nextSiblingGenerator(self):
return self.next_siblings
def previousGenerator(self):
return self.previous_elements
def previousSiblingGenerator(self):
return self.previous_siblings
def parentGenerator(self):
return self.parents
class NavigableString(unicode, PageElement):
PREFIX = ''
SUFFIX = ''
def __new__(cls, value):
"""Create a new NavigableString.
When unpickling a NavigableString, this method is called with
the string in DEFAULT_OUTPUT_ENCODING. That encoding needs to be
passed in to the superclass's __new__ or the superclass won't know
how to handle non-ASCII characters.
"""
if isinstance(value, unicode):
return unicode.__new__(cls, value)
return unicode.__new__(cls, value, DEFAULT_OUTPUT_ENCODING)
def __copy__(self):
return self
def __getnewargs__(self):
return (unicode(self),)
def __getattr__(self, attr):
"""text.string gives you text. This is for backwards
compatibility for Navigable*String, but for CData* it lets you
get the string without the CData wrapper."""
if attr == 'string':
return self
else:
raise AttributeError(
"'%s' object has no attribute '%s'" % (
self.__class__.__name__, attr))
def output_ready(self, formatter="minimal"):
output = self.format_string(self, formatter)
return self.PREFIX + output + self.SUFFIX
class PreformattedString(NavigableString):
"""A NavigableString not subject to the normal formatting rules.
The string will be passed into the formatter (to trigger side effects),
but the return value will be ignored.
"""
def output_ready(self, formatter="minimal"):
"""CData strings are passed into the formatter.
But the return value is ignored."""
self.format_string(self, formatter)
return self.PREFIX + self + self.SUFFIX
class CData(PreformattedString):
PREFIX = u'<![CDATA['
SUFFIX = u']]>'
class ProcessingInstruction(PreformattedString):
PREFIX = u'<?'
SUFFIX = u'?>'
class Comment(PreformattedString):
PREFIX = u'<!--'
SUFFIX = u'-->'
class Declaration(PreformattedString):
PREFIX = u'<!'
SUFFIX = u'!>'
class Doctype(PreformattedString):
@classmethod
def for_name_and_ids(cls, name, pub_id, system_id):
value = name or ''
if pub_id is not None:
value += ' PUBLIC "%s"' % pub_id
if system_id is not None:
value += ' "%s"' % system_id
elif system_id is not None:
value += ' SYSTEM "%s"' % system_id
return Doctype(value)
PREFIX = u'<!DOCTYPE '
SUFFIX = u'>\n'
class Tag(PageElement):
"""Represents a found HTML tag with its attributes and contents."""
def __init__(self, parser=None, builder=None, name=None, namespace=None,
prefix=None, attrs=None, parent=None, previous=None):
"Basic constructor."
if parser is None:
self.parser_class = None
else:
# We don't actually store the parser object: that lets extracted
# chunks be garbage-collected.
self.parser_class = parser.__class__
if name is None:
raise ValueError("No value provided for new tag's name.")
self.name = name
self.namespace = namespace
self.prefix = prefix
if attrs is None:
attrs = {}
elif builder.cdata_list_attributes:
attrs = builder._replace_cdata_list_attribute_values(
self.name, attrs)
else:
attrs = dict(attrs)
self.attrs = attrs
self.contents = []
self.setup(parent, previous)
self.hidden = False
# Set up any substitutions, such as the charset in a META tag.
if builder is not None:
builder.set_up_substitutions(self)
self.can_be_empty_element = builder.can_be_empty_element(name)
else:
self.can_be_empty_element = False
parserClass = _alias("parser_class") # BS3
@property
def is_empty_element(self):
"""Is this tag an empty-element tag? (aka a self-closing tag)
A tag that has contents is never an empty-element tag.
A tag that has no contents may or may not be an empty-element
tag. It depends on the builder used to create the tag. If the
builder has a designated list of empty-element tags, then only
a tag whose name shows up in that list is considered an
empty-element tag.
If the builder has no designated list of empty-element tags,
then any tag with no contents is an empty-element tag.
"""
return len(self.contents) == 0 and self.can_be_empty_element
isSelfClosing = is_empty_element # BS3
@property
def string(self):
"""Convenience property to get the single string within this tag.
:Return: If this tag has a single string child, return value
is that string. If this tag has no children, or more than one
child, return value is None. If this tag has one child tag,
return value is the 'string' attribute of the child tag,
recursively.
"""
if len(self.contents) != 1:
return None
child = self.contents[0]
if isinstance(child, NavigableString):
return child
return child.string
@string.setter
def string(self, string):
self.clear()
self.append(string.__class__(string))
def _all_strings(self, strip=False, types=(NavigableString, CData)):
"""Yield all strings of certain classes, possibly stripping them.
By default, yields only NavigableString and CData objects. So
no comments, processing instructions, etc.
"""
for descendant in self.descendants:
if (
(types is None and not isinstance(descendant, NavigableString))
or
(types is not None and type(descendant) not in types)):
continue
if strip:
descendant = descendant.strip()
if len(descendant) == 0:
continue
yield descendant
strings = property(_all_strings)
@property
def stripped_strings(self):
for string in self._all_strings(True):
yield string
def get_text(self, separator=u"", strip=False,
types=(NavigableString, CData)):
"""
Get all child strings, concatenated using the given separator.
"""
return separator.join([s for s in self._all_strings(
strip, types=types)])
getText = get_text
text = property(get_text)
def decompose(self):
"""Recursively destroys the contents of this tree."""
self.extract()
i = self
while i is not None:
next = i.next_element
i.__dict__.clear()
i.contents = []
i = next
def clear(self, decompose=False):
"""
Extract all children. If decompose is True, decompose instead.
"""
if decompose:
for element in self.contents[:]:
if isinstance(element, Tag):
element.decompose()
else:
element.extract()
else:
for element in self.contents[:]:
element.extract()
def index(self, element):
"""
Find the index of a child by identity, not value. Avoids issues with
tag.contents.index(element) getting the index of equal elements.
"""
for i, child in enumerate(self.contents):
if child is element:
return i
raise ValueError("Tag.index: element not in tag")
def get(self, key, default=None):
"""Returns the value of the 'key' attribute for the tag, or
the value given for 'default' if it doesn't have that
attribute."""
return self.attrs.get(key, default)
def has_attr(self, key):
return key in self.attrs
def __hash__(self):
return str(self).__hash__()
def __getitem__(self, key):
"""tag[key] returns the value of the 'key' attribute for the tag,
and throws an exception if it's not there."""
return self.attrs[key]
def __iter__(self):
"Iterating over a tag iterates over its contents."
return iter(self.contents)
def __len__(self):
"The length of a tag is the length of its list of contents."
return len(self.contents)
def __contains__(self, x):
return x in self.contents
def __nonzero__(self):
"A tag is non-None even if it has no contents."
return True
def __setitem__(self, key, value):
"""Setting tag[key] sets the value of the 'key' attribute for the
tag."""
self.attrs[key] = value
def __delitem__(self, key):
"Deleting tag[key] deletes all 'key' attributes for the tag."
self.attrs.pop(key, None)
def __call__(self, *args, **kwargs):
"""Calling a tag like a function is the same as calling its
find_all() method. Eg. tag('a') returns a list of all the A tags
found within this tag."""
return self.find_all(*args, **kwargs)
def __getattr__(self, tag):
#print "Getattr %s.%s" % (self.__class__, tag)
if len(tag) > 3 and tag.endswith('Tag'):
# BS3: soup.aTag -> "soup.find("a")
tag_name = tag[:-3]
warnings.warn(
'.%sTag is deprecated, use .find("%s") instead.' % (
tag_name, tag_name))
return self.find(tag_name)
# We special case contents to avoid recursion.
elif not tag.startswith("__") and not tag=="contents":
return self.find(tag)
raise AttributeError(
"'%s' object has no attribute '%s'" % (self.__class__, tag))
def __eq__(self, other):
"""Returns true iff this tag has the same name, the same attributes,
and the same contents (recursively) as the given tag."""
if self is other:
return True
if (not hasattr(other, 'name') or
not hasattr(other, 'attrs') or
not hasattr(other, 'contents') or
self.name != other.name or
self.attrs != other.attrs or
len(self) != len(other)):
return False
for i, my_child in enumerate(self.contents):
if my_child != other.contents[i]:
return False
return True
def __ne__(self, other):
"""Returns true iff this tag is not identical to the other tag,
as defined in __eq__."""
return not self == other
def __repr__(self, encoding=DEFAULT_OUTPUT_ENCODING):
"""Renders this tag as a string."""
return self.encode(encoding)
def __unicode__(self):
return self.decode()
def __str__(self):
return self.encode()
if PY3K:
__str__ = __repr__ = __unicode__
def encode(self, encoding=DEFAULT_OUTPUT_ENCODING,
indent_level=None, formatter="minimal",
errors="xmlcharrefreplace"):
# Turn the data structure into Unicode, then encode the
# Unicode.
u = self.decode(indent_level, encoding, formatter)
return u.encode(encoding, errors)
def _should_pretty_print(self, indent_level):
"""Should this tag be pretty-printed?"""
return (
indent_level is not None and
(self.name not in HTMLAwareEntitySubstitution.preformatted_tags
or self._is_xml))
def decode(self, indent_level=None,
eventual_encoding=DEFAULT_OUTPUT_ENCODING,
formatter="minimal"):
"""Returns a Unicode representation of this tag and its contents.
:param eventual_encoding: The tag is destined to be
encoded into this encoding. This method is _not_
responsible for performing that encoding. This information
is passed in so that it can be substituted in if the
document contains a <META> tag that mentions the document's
encoding.
"""
# First off, turn a string formatter into a function. This
# will stop the lookup from happening over and over again.
if not callable(formatter):
formatter = self._formatter_for_name(formatter)
attrs = []
if self.attrs:
for key, val in sorted(self.attrs.items()):
if val is None:
decoded = key
else:
if isinstance(val, list) or isinstance(val, tuple):
val = ' '.join(val)
elif not isinstance(val, basestring):
val = unicode(val)
elif (
isinstance(val, AttributeValueWithCharsetSubstitution)
and eventual_encoding is not None):
val = val.encode(eventual_encoding)
text = self.format_string(val, formatter)
decoded = (
unicode(key) + '='
+ EntitySubstitution.quoted_attribute_value(text))
attrs.append(decoded)
close = ''
closeTag = ''
prefix = ''
if self.prefix:
prefix = self.prefix + ":"
if self.is_empty_element:
close = '/'
else:
closeTag = '</%s%s>' % (prefix, self.name)
pretty_print = self._should_pretty_print(indent_level)
space = ''
indent_space = ''
if indent_level is not None:
indent_space = (' ' * (indent_level - 1))
if pretty_print:
space = indent_space
indent_contents = indent_level + 1
else:
indent_contents = None
contents = self.decode_contents(
indent_contents, eventual_encoding, formatter)
if self.hidden:
# This is the 'document root' object.
s = contents
else:
s = []
attribute_string = ''
if attrs:
attribute_string = ' ' + ' '.join(attrs)
if indent_level is not None:
# Even if this particular tag is not pretty-printed,
# we should indent up to the start of the tag.
s.append(indent_space)
s.append('<%s%s%s%s>' % (
prefix, self.name, attribute_string, close))
if pretty_print:
s.append("\n")
s.append(contents)
if pretty_print and contents and contents[-1] != "\n":
s.append("\n")
if pretty_print and closeTag:
s.append(space)
s.append(closeTag)
if indent_level is not None and closeTag and self.next_sibling:
# Even if this particular tag is not pretty-printed,
# we're now done with the tag, and we should add a
# newline if appropriate.
s.append("\n")
s = ''.join(s)
return s
def prettify(self, encoding=None, formatter="minimal"):
if encoding is None:
return self.decode(True, formatter=formatter)
else:
return self.encode(encoding, True, formatter=formatter)
def decode_contents(self, indent_level=None,
eventual_encoding=DEFAULT_OUTPUT_ENCODING,
formatter="minimal"):
"""Renders the contents of this tag as a Unicode string.
:param eventual_encoding: The tag is destined to be
encoded into this encoding. This method is _not_
responsible for performing that encoding. This information
is passed in so that it can be substituted in if the
document contains a <META> tag that mentions the document's
encoding.
"""
# First off, turn a string formatter into a function. This
# will stop the lookup from happening over and over again.
if not callable(formatter):
formatter = self._formatter_for_name(formatter)
pretty_print = (indent_level is not None)
s = []
for c in self:
text = None
if isinstance(c, NavigableString):
text = c.output_ready(formatter)
elif isinstance(c, Tag):
s.append(c.decode(indent_level, eventual_encoding,
formatter))
if text and indent_level and not self.name == 'pre':
text = text.strip()
if text:
if pretty_print and not self.name == 'pre':
s.append(" " * (indent_level - 1))
s.append(text)
if pretty_print and not self.name == 'pre':
s.append("\n")
return ''.join(s)
def encode_contents(
self, indent_level=None, encoding=DEFAULT_OUTPUT_ENCODING,
formatter="minimal"):
"""Renders the contents of this tag as a bytestring."""
contents = self.decode_contents(indent_level, encoding, formatter)
return contents.encode(encoding)
# Old method for BS3 compatibility
def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING,
prettyPrint=False, indentLevel=0):
if not prettyPrint:
indentLevel = None
return self.encode_contents(
indent_level=indentLevel, encoding=encoding)
#Soup methods
def find(self, name=None, attrs={}, recursive=True, text=None,
**kwargs):
"""Return only the first child of this Tag matching the given
criteria."""
r = None
l = self.find_all(name, attrs, recursive, text, 1, **kwargs)
if l:
r = l[0]
return r
findChild = find
def find_all(self, name=None, attrs={}, recursive=True, text=None,
limit=None, **kwargs):
"""Extracts a list of Tag objects that match the given
criteria. You can specify the name of the Tag and any
attributes you want the Tag to have.
The value of a key-value pair in the 'attrs' map can be a
string, a list of strings, a regular expression object, or a
callable that takes a string and returns whether or not the
string matches for some custom definition of 'matches'. The
same is true of the tag name."""
generator = self.descendants
if not recursive:
generator = self.children
return self._find_all(name, attrs, text, limit, generator, **kwargs)
findAll = find_all # BS3
findChildren = find_all # BS2
#Generator methods
@property
def children(self):
# return iter() to make the purpose of the method clear
return iter(self.contents) # XXX This seems to be untested.
@property
def descendants(self):
if not len(self.contents):
return
stopNode = self._last_descendant().next_element
current = self.contents[0]
while current is not stopNode:
yield current
current = current.next_element
# CSS selector code
_selector_combinators = ['>', '+', '~']
_select_debug = False
def select(self, selector, _candidate_generator=None):
"""Perform a CSS selection operation on the current element."""
tokens = selector.split()
current_context = [self]
if tokens[-1] in self._selector_combinators:
raise ValueError(
'Final combinator "%s" is missing an argument.' % tokens[-1])
if self._select_debug:
print 'Running CSS selector "%s"' % selector
for index, token in enumerate(tokens):
if self._select_debug:
print ' Considering token "%s"' % token
recursive_candidate_generator = None
tag_name = None
if tokens[index-1] in self._selector_combinators:
# This token was consumed by the previous combinator. Skip it.
if self._select_debug:
print ' Token was consumed by the previous combinator.'
continue
# Each operation corresponds to a checker function, a rule
# for determining whether a candidate matches the
# selector. Candidates are generated by the active
# iterator.
checker = None
m = self.attribselect_re.match(token)
if m is not None:
# Attribute selector
tag_name, attribute, operator, value = m.groups()
checker = self._attribute_checker(operator, attribute, value)
elif '#' in token:
# ID selector
tag_name, tag_id = token.split('#', 1)
def id_matches(tag):
return tag.get('id', None) == tag_id
checker = id_matches
elif '.' in token:
# Class selector
tag_name, klass = token.split('.', 1)
classes = set(klass.split('.'))
def classes_match(candidate):
return classes.issubset(candidate.get('class', []))
checker = classes_match
elif ':' in token:
# Pseudo-class
tag_name, pseudo = token.split(':', 1)
if tag_name == '':
continue
raise ValueError(
"A pseudo-class must be prefixed with a tag name.")
pseudo_attributes = re.match('([a-zA-Z\d-]+)\(([a-zA-Z\d]+)\)', pseudo)
found = []
if pseudo_attributes is not None:
pseudo_type, pseudo_value = pseudo_attributes.groups()
if pseudo_type == 'nth-of-type':
try:
pseudo_value = int(pseudo_value)
except:
continue
raise NotImplementedError(
'Only numeric values are currently supported for the nth-of-type pseudo-class.')
if pseudo_value < 1:
continue
raise ValueError(
'nth-of-type pseudo-class value must be at least 1.')
class Counter(object):
def __init__(self, destination):
self.count = 0
self.destination = destination
def nth_child_of_type(self, tag):
self.count += 1
if self.count == self.destination:
return True
if self.count > self.destination:
# Stop the generator that's sending us
# these things.
raise StopIteration()
return False
checker = Counter(pseudo_value).nth_child_of_type
else:
continue
raise NotImplementedError(
'Only the following pseudo-classes are implemented: nth-of-type.')
elif token == '*':
# Star selector -- matches everything
pass
elif token == '>':
# Run the next token as a CSS selector against the
# direct children of each tag in the current context.
recursive_candidate_generator = lambda tag: tag.children
elif token == '~':
# Run the next token as a CSS selector against the
# siblings of each tag in the current context.
recursive_candidate_generator = lambda tag: tag.next_siblings
elif token == '+':
# For each tag in the current context, run the next
# token as a CSS selector against the tag's next
# sibling that's a tag.
def next_tag_sibling(tag):
yield tag.find_next_sibling(True)
recursive_candidate_generator = next_tag_sibling
elif self.tag_name_re.match(token):
# Just a tag name.
tag_name = token
else:
continue
raise ValueError(
'Unsupported or invalid CSS selector: "%s"' % token)
if recursive_candidate_generator:
# This happens when the selector looks like "> foo".
#
# The generator calls select() recursively on every
# member of the current context, passing in a different
# candidate generator and a different selector.
#
# In the case of "> foo", the candidate generator is
# one that yields a tag's direct children (">"), and
# the selector is "foo".
next_token = tokens[index+1]
def recursive_select(tag):
if self._select_debug:
print ' Calling select("%s") recursively on %s %s' % (next_token, tag.name, tag.attrs)
print '-' * 40
for i in tag.select(next_token, recursive_candidate_generator):
if self._select_debug:
print '(Recursive select picked up candidate %s %s)' % (i.name, i.attrs)
yield i
if self._select_debug:
print '-' * 40
_use_candidate_generator = recursive_select
elif _candidate_generator is None:
# By default, a tag's candidates are all of its
# children. If tag_name is defined, only yield tags
# with that name.
if self._select_debug:
if tag_name:
check = "[any]"
else:
check = tag_name
print ' Default candidate generator, tag name="%s"' % check
if self._select_debug:
# This is redundant with later code, but it stops
# a bunch of bogus tags from cluttering up the
# debug log.
def default_candidate_generator(tag):
for child in tag.descendants:
if not isinstance(child, Tag):
continue
if tag_name and not child.name == tag_name:
continue
yield child
_use_candidate_generator = default_candidate_generator
else:
_use_candidate_generator = lambda tag: tag.descendants
else:
_use_candidate_generator = _candidate_generator
new_context = []
new_context_ids = set([])
for tag in current_context:
if self._select_debug:
print " Running candidate generator on %s %s" % (
tag.name, repr(tag.attrs))
for candidate in _use_candidate_generator(tag):
if not isinstance(candidate, Tag):
continue
if tag_name and candidate.name != tag_name:
continue
if checker is not None:
try:
result = checker(candidate)
except StopIteration:
# The checker has decided we should no longer
# run the generator.
break
if checker is None or result:
if self._select_debug:
print " SUCCESS %s %s" % (candidate.name, repr(candidate.attrs))
if id(candidate) not in new_context_ids:
# If a tag matches a selector more than once,
# don't include it in the context more than once.
new_context.append(candidate)
new_context_ids.add(id(candidate))
elif self._select_debug:
print " FAILURE %s %s" % (candidate.name, repr(candidate.attrs))
current_context = new_context
if self._select_debug:
print "Final verdict:"
for i in current_context:
print " %s %s" % (i.name, i.attrs)
return current_context
# Old names for backwards compatibility
def childGenerator(self):
return self.children
def recursiveChildGenerator(self):
return self.descendants
def has_key(self, key):
"""This was kind of misleading because has_key() (attributes)
was different from __in__ (contents). has_key() is gone in
Python 3, anyway."""
warnings.warn('has_key is deprecated. Use has_attr("%s") instead.' % (
key))
return self.has_attr(key)
class SoupStrainer(object):
"""Encapsulates a number of ways of matching a markup element (tag or
text)."""
def __init__(self, name=None, attrs={}, text=None, **kwargs):
self.name = self._normalize_search_value(name)
if not isinstance(attrs, dict):
# Treat a non-dict value for attrs as a search for the 'class'
# attribute.
kwargs['class'] = attrs
attrs = None
if 'class_' in kwargs:
# Treat class_="foo" as a search for the 'class'
# attribute, overriding any non-dict value for attrs.
kwargs['class'] = kwargs['class_']
del kwargs['class_']
if kwargs:
if attrs:
attrs = attrs.copy()
attrs.update(kwargs)
else:
attrs = kwargs
normalized_attrs = {}
for key, value in attrs.items():
normalized_attrs[key] = self._normalize_search_value(value)
self.attrs = normalized_attrs
self.text = self._normalize_search_value(text)
def _normalize_search_value(self, value):
# Leave it alone if it's a Unicode string, a callable, a
# regular expression, a boolean, or None.
if (isinstance(value, unicode) or callable(value) or hasattr(value, 'match')
or isinstance(value, bool) or value is None):
return value
# If it's a bytestring, convert it to Unicode, treating it as UTF-8.
if isinstance(value, bytes):
return value.decode("utf8")
# If it's listlike, convert it into a list of strings.
if hasattr(value, '__iter__'):
new_value = []
for v in value:
if (hasattr(v, '__iter__') and not isinstance(v, bytes)
and not isinstance(v, unicode)):
# This is almost certainly the user's mistake. In the
# interests of avoiding infinite loops, we'll let
# it through as-is rather than doing a recursive call.
new_value.append(v)
else:
new_value.append(self._normalize_search_value(v))
return new_value
# Otherwise, convert it into a Unicode string.
# The unicode(str()) thing is so this will do the same thing on Python 2
# and Python 3.
return unicode(str(value))
def __str__(self):
if self.text:
return self.text
else:
return "%s|%s" % (self.name, self.attrs)
def search_tag(self, markup_name=None, markup_attrs={}):
found = None
markup = None
if isinstance(markup_name, Tag):
markup = markup_name
markup_attrs = markup
call_function_with_tag_data = (
isinstance(self.name, collections.Callable)
and not isinstance(markup_name, Tag))
if ((not self.name)
or call_function_with_tag_data
or (markup and self._matches(markup, self.name))
or (not markup and self._matches(markup_name, self.name))):
if call_function_with_tag_data:
match = self.name(markup_name, markup_attrs)
else:
match = True
markup_attr_map = None
for attr, match_against in list(self.attrs.items()):
if not markup_attr_map:
if hasattr(markup_attrs, 'get'):
markup_attr_map = markup_attrs
else:
markup_attr_map = {}
for k, v in markup_attrs:
markup_attr_map[k] = v
attr_value = markup_attr_map.get(attr)
if not self._matches(attr_value, match_against):
match = False
break
if match:
if markup:
found = markup
else:
found = markup_name
if found and self.text and not self._matches(found.string, self.text):
found = None
return found
searchTag = search_tag
def search(self, markup):
# print 'looking for %s in %s' % (self, markup)
found = None
# If given a list of items, scan it for a text element that
# matches.
if hasattr(markup, '__iter__') and not isinstance(markup, (Tag, basestring)):
for element in markup:
if isinstance(element, NavigableString) \
and self.search(element):
found = element
break
# If it's a Tag, make sure its name or attributes match.
# Don't bother with Tags if we're searching for text.
elif isinstance(markup, Tag):
if not self.text or self.name or self.attrs:
found = self.search_tag(markup)
# If it's text, make sure the text matches.
elif isinstance(markup, NavigableString) or \
isinstance(markup, basestring):
if not self.name and not self.attrs and self._matches(markup, self.text):
found = markup
else:
raise Exception(
"I don't know how to match against a %s" % markup.__class__)
return found
def _matches(self, markup, match_against):
# print u"Matching %s against %s" % (markup, match_against)
result = False
if isinstance(markup, list) or isinstance(markup, tuple):
# This should only happen when searching a multi-valued attribute
# like 'class'.
if (isinstance(match_against, unicode)
and ' ' in match_against):
# A bit of a special case. If they try to match "foo
# bar" on a multivalue attribute's value, only accept
# the literal value "foo bar"
#
# XXX This is going to be pretty slow because we keep
# splitting match_against. But it shouldn't come up
# too often.
return (whitespace_re.split(match_against) == markup)
else:
for item in markup:
if self._matches(item, match_against):
return True
return False
if match_against is True:
# True matches any non-None value.
return markup is not None
if isinstance(match_against, collections.Callable):
return match_against(markup)
# Custom callables take the tag as an argument, but all
# other ways of matching match the tag name as a string.
if isinstance(markup, Tag):
markup = markup.name
# Ensure that `markup` is either a Unicode string, or None.
markup = self._normalize_search_value(markup)
if markup is None:
# None matches None, False, an empty string, an empty list, and so on.
return not match_against
if isinstance(match_against, unicode):
# Exact string match
return markup == match_against
if hasattr(match_against, 'match'):
# Regexp match
return match_against.search(markup)
if hasattr(match_against, '__iter__'):
# The markup must be an exact match against something
# in the iterable.
return markup in match_against
class ResultSet(list):
"""A ResultSet is just a list that keeps track of the SoupStrainer
that created it."""
def __init__(self, source):
list.__init__([])
self.source = source
|
from unittest import TestCase
from enkel.wansgli.testhelpers import unit_case_suite, run_suite
class Test(TestCase):
def suite():
return unit_case_suite(Test)
if __name__ == '__main__':
run_suite(suite())
|
import mailbox, smtplib, sys, time, string
def main ():
print "\nMbox & Maildir to Gmail Loader (GML) by Mark Lyon <mark@marklyon.org>\n"
if len(sys.argv) in (5, 6) :
boxtype_in = sys.argv[1]
mailboxname_in = sys.argv[2]
emailname_in = sys.argv[3]
password_in = sys.argv[4]
else:
usage()
try:
smtpserver_in = sys.argv[5]
except:
smtpserver_in = 'smtp.gmail.com'
print "Using smtpserver %s\n" % smtpserver_in
count = [0,0,0]
try:
if boxtype_in == "maildir":
mb = mailbox.Maildir(mailboxname_in)
else:
mb = mailbox.UnixMailbox (file(mailboxname_in,'r'))
msg = mb.next()
except:
print "*** Can't open file or directory. Is the path correct? ***\n"
usage()
while msg is not None:
try:
document = msg.fp.read()
except:
count[2] = count[2] + 1
print "*** %d MESSAGE READ FAILED, SKIPPED" % (count[2])
msg = mb.next()
if document is not None:
fullmsg = msg.__str__( ) + '\x0a' + document
server = smtplib.SMTP(smtpserver_in)
#server.set_debuglevel(1)
server.ehlo()
server.starttls()
# smtplib won't send auth info without this second ehlo after
# starttls -- thanks to
# http://bytes.com/topic/python/answers/475531-smtplib-authentication-required-error
# for the tip
server.ehlo()
server.login(emailname_in, password_in)
server.sendmail(msg.getaddr('From')[1], emailname_in, fullmsg)
server.quit()
count[0] = count[0] + 1
print " %d Forwarded a message from: %s" % (count[0], msg.getaddr('From')[1])
msg = mb.next()
print "\nDone. Stats: %d success %d error %d skipped." % (count[0], count[1], count[2])
def usage():
print 'Usage: gml.py [mbox or maildir] [mbox file or maildir path] [gmail address] [gmail password] [Optional SMTP Server]'
print 'Exmpl: gml.py mbox "c:\mail\Inbox" marklyon@gmail.com password'
print 'Exmpl: gml.py maildir "c:\mail\Inbox\" marklyon@gmail.com password gsmtp171.google.com\n'
sys.exit()
if __name__ == '__main__':
main ()
|
"""HTML Templates for commenting features """
__revision__ = "$Id$"
import cgi
from invenio.urlutils import create_html_link
from invenio.webuser import get_user_info, collect_user_info, isGuestUser, get_email
from invenio.dateutils import convert_datetext_to_dategui
from invenio.webmessage_mailutils import email_quoted_txt2html
from invenio.webcomment_config import \
CFG_WEBCOMMENT_MAX_ATTACHED_FILES, \
CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE
from invenio.config import CFG_SITE_URL, \
CFG_SITE_SECURE_URL, \
CFG_SITE_LANG, \
CFG_SITE_NAME, \
CFG_SITE_NAME_INTL,\
CFG_SITE_SUPPORT_EMAIL,\
CFG_WEBCOMMENT_ALLOW_REVIEWS, \
CFG_WEBCOMMENT_ALLOW_COMMENTS, \
CFG_WEBCOMMENT_USE_RICH_TEXT_EDITOR, \
CFG_WEBCOMMENT_NB_REPORTS_BEFORE_SEND_EMAIL_TO_ADMIN, \
CFG_WEBCOMMENT_AUTHOR_DELETE_COMMENT_OPTION, \
CFG_CERN_SITE
from invenio.htmlutils import get_html_text_editor
from invenio.messages import gettext_set_language
from invenio.bibformat import format_record
from invenio.access_control_engine import acc_authorize_action
from invenio.websearch_templates import get_fieldvalues
class Template:
"""templating class, refer to webcomment.py for examples of call"""
def tmpl_get_first_comments_without_ranking(self, recID, ln, comments, nb_comments_total, warnings):
"""
@param recID: record id
@param ln: language
@param comments: tuple as returned from webcomment.py/query_retrieve_comments_or_remarks
@param nb_comments_total: total number of comments for this record
@param warnings: list of warning tuples (warning_msg, arg1, arg2, ...)
@return: html of comments
"""
# load the right message language
_ = gettext_set_language(ln)
# naming data fields of comments
c_nickname = 0
c_user_id = 1
c_date_creation = 2
c_body = 3
c_id = 4
warnings = self.tmpl_warnings(warnings, ln)
# comments
comment_rows = ''
max_comment_round_name = comments[-1][0]
for comment_round_name, comments_list in comments:
comment_rows += '<div id="cmtRound%i" class="cmtRound">' % (comment_round_name)
comment_rows += _('%(x_nb)i comments for round "%(x_name)s"') % {'x_nb': len(comments_list), 'x_name': comment_round_name} + "<br/>"
for comment in comments_list:
if comment[c_nickname]:
nickname = comment[c_nickname]
display = nickname
else:
(uid, nickname, display) = get_user_info(comment[c_user_id])
messaging_link = self.create_messaging_link(nickname, display, ln)
comment_rows += """
<tr>
<td>"""
report_link = '%s/record/%s/comments/report?ln=%s&comid=%s' % (CFG_SITE_URL, recID, ln, comment[c_id])
reply_link = '%s/record/%s/comments/add?ln=%s&comid=%s&action=REPLY' % (CFG_SITE_URL, recID, ln, comment[c_id])
comment_rows += self.tmpl_get_comment_without_ranking(req=None, ln=ln, nickname=messaging_link, comment_uid=comment[c_user_id],
date_creation=comment[c_date_creation],
body=comment[c_body], status='', nb_reports=0,
report_link=report_link, reply_link=reply_link, recID=recID)
comment_rows += """
<br />
<br />
</td>
</tr>"""
# Close comment round
comment_rows += '</div>'
# write button
write_button_label = _("Write a comment")
write_button_link = '%s/record/%s/comments/add' % (CFG_SITE_URL, recID)
write_button_form = '<input type="hidden" name="ln" value="%s"/>' % ln
write_button_form = self.createhiddenform(action=write_button_link, method="get", text=write_button_form, button=write_button_label)
# output
if nb_comments_total > 0:
out = warnings
comments_label = len(comments) > 1 and _("Showing the latest %i comments:") % len(comments) \
or ""
out += """
<table>
<tr>
<td class="blocknote">%(comment_title)s</td>
</tr>
</table>
%(comments_label)s<br />
<table border="0" cellspacing="5" cellpadding="5" width="100%%">
%(comment_rows)s
</table>
%(view_all_comments_link)s
<br />
<br />
%(write_button_form)s<br />""" % \
{'comment_title': _("Discuss this document"),
'comments_label': comments_label,
'nb_comments_total' : nb_comments_total,
'recID': recID,
'comment_rows': comment_rows,
'tab': ' '*4,
'siteurl': CFG_SITE_URL,
's': nb_comments_total>1 and 's' or "",
'view_all_comments_link': nb_comments_total>0 and '''<a href="%s/record/%s/comments/display">View all %s comments</a>''' \
% (CFG_SITE_URL, recID, nb_comments_total) or "",
'write_button_form': write_button_form,
'nb_comments': len(comments)
}
else:
out = """
<!-- comments title table -->
<table>
<tr>
<td class="blocknote">%(discuss_label)s:</td>
</tr>
</table>
%(detailed_info)s
<br />
%(form)s
<br />""" % {'form': write_button_form,
'discuss_label': _("Discuss this document"),
'detailed_info': _("Start a discussion about any aspect of this document.")
}
return out
def tmpl_record_not_found(self, status='missing', recID="", ln=CFG_SITE_LANG):
"""
Displays a page when bad or missing record ID was given.
@param status: 'missing' : no recID was given
'inexistant': recID doesn't have an entry in the database
'nan' : recID is not a number
'invalid' : recID is an error code, i.e. in the interval [-99,-1]
@param return: body of the page
"""
_ = gettext_set_language(ln)
if status == 'inexistant':
body = _("Sorry, the record %s does not seem to exist.") % (recID,)
elif status in ('nan', 'invalid'):
body = _("Sorry, %s is not a valid ID value.") % (recID,)
else:
body = _("Sorry, no record ID was provided.")
body += "<br /><br />"
link = "<a href=\"%s?ln=%s\">%s</a>." % (CFG_SITE_URL, ln, CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME))
body += _("You may want to start browsing from %s") % link
return body
def tmpl_get_first_comments_with_ranking(self, recID, ln, comments=None, nb_comments_total=None, avg_score=None, warnings=[]):
"""
@param recID: record id
@param ln: language
@param comments: tuple as returned from webcomment.py/query_retrieve_comments_or_remarks
@param nb_comments_total: total number of comments for this record
@param avg_score: average score of all reviews
@param warnings: list of warning tuples (warning_msg, arg1, arg2, ...)
@return: html of comments
"""
# load the right message language
_ = gettext_set_language(ln)
# naming data fields of comments
c_nickname = 0
c_user_id = 1
c_date_creation = 2
c_body = 3
c_nb_votes_yes = 4
c_nb_votes_total = 5
c_star_score = 6
c_title = 7
c_id = 8
warnings = self.tmpl_warnings(warnings, ln)
#stars
if avg_score > 0:
avg_score_img = 'stars-' + str(avg_score).split('.')[0] + '-' + str(avg_score).split('.')[1] + '.png'
else:
avg_score_img = "stars-0-0.png"
# voting links
useful_dict = { 'siteurl' : CFG_SITE_URL,
'recID' : recID,
'ln' : ln,
'yes_img' : 'smchk_gr.gif', #'yes.gif',
'no_img' : 'iconcross.gif' #'no.gif'
}
link = '<a href="%(siteurl)s/record/%(recID)s/reviews/vote?ln=%(ln)s&comid=%%(comid)s' % useful_dict
useful_yes = link + '&com_value=1">' + _("Yes") + '</a>'
useful_no = link + '&com_value=-1">' + _("No") + '</a>'
#comment row
comment_rows = ' '
max_comment_round_name = comments[-1][0]
for comment_round_name, comments_list in comments:
comment_rows += '<div id="cmtRound%i" class="cmtRound">' % (comment_round_name)
comment_rows += _('%(x_nb)i comments for round "%(x_name)s"') % {'x_nb': len(comments_list), 'x_name': comment_round_name} + "<br/>"
for comment in comments_list:
if comment[c_nickname]:
nickname = comment[c_nickname]
display = nickname
else:
(uid, nickname, display) = get_user_info(comment[c_user_id])
messaging_link = self.create_messaging_link(nickname, display, ln)
comment_rows += '''
<tr>
<td>'''
report_link = '%s/record/%s/reviews/report?ln=%s&comid=%s' % (CFG_SITE_URL, recID, ln, comment[c_id])
comment_rows += self.tmpl_get_comment_with_ranking(None, ln=ln, nickname=messaging_link,
comment_uid=comment[c_user_id],
date_creation=comment[c_date_creation],
body=comment[c_body],
status='', nb_reports=0,
nb_votes_total=comment[c_nb_votes_total],
nb_votes_yes=comment[c_nb_votes_yes],
star_score=comment[c_star_score],
title=comment[c_title], report_link=report_link, recID=recID)
comment_rows += '''
%s %s / %s<br />''' % (_("Was this review helpful?"), useful_yes % {'comid':comment[c_id]}, useful_no % {'comid':comment[c_id]})
comment_rows += '''
<br />
</td>
</tr>'''
# Close comment round
comment_rows += '</div>'
# write button
write_button_link = '''%s/record/%s/reviews/add''' % (CFG_SITE_URL, recID)
write_button_form = ' <input type="hidden" name="ln" value="%s"/>' % ln
write_button_form = self.createhiddenform(action=write_button_link, method="get", text=write_button_form, button=_("Write a review"))
if nb_comments_total > 0:
avg_score_img = str(avg_score_img)
avg_score = str(avg_score)
nb_comments_total = str(nb_comments_total)
score = '<b>'
score += _("Average review score: %(x_nb_score)s based on %(x_nb_reviews)s reviews") % \
{'x_nb_score': '</b><img src="' + CFG_SITE_URL + '/img/' + avg_score_img + '" alt="' + avg_score + '" />',
'x_nb_reviews': nb_comments_total}
useful_label = _("Readers found the following %s reviews to be most helpful.")
useful_label %= len(comments) > 1 and len(comments) or ""
view_all_comments_link ='<a href="%s/record/%s/reviews/display?ln=%s&do=hh">' % (CFG_SITE_URL, recID, ln)
view_all_comments_link += _("View all %s reviews") % nb_comments_total
view_all_comments_link += '</a><br />'
out = warnings + """
<!-- review title table -->
<table>
<tr>
<td class="blocknote">%(comment_title)s:</td>
</tr>
</table>
%(score_label)s<br />
%(useful_label)s
<!-- review table -->
<table style="border: 0px; border-collapse: separate; border-spacing: 5px; padding: 5px; width: 100%%">
%(comment_rows)s
</table>
%(view_all_comments_link)s
%(write_button_form)s<br />
""" % \
{ 'comment_title' : _("Rate this document"),
'score_label' : score,
'useful_label' : useful_label,
'recID' : recID,
'view_all_comments' : _("View all %s reviews") % (nb_comments_total,),
'write_comment' : _("Write a review"),
'comment_rows' : comment_rows,
'tab' : ' '*4,
'siteurl' : CFG_SITE_URL,
'view_all_comments_link': nb_comments_total>0 and view_all_comments_link or "",
'write_button_form' : write_button_form
}
else:
out = '''
<!-- review title table -->
<table>
<tr>
<td class="blocknote">%s:</td>
</tr>
</table>
%s<br />
%s
<br />''' % (_("Rate this document"),
_("Be the first to review this document."),
write_button_form)
return out
def tmpl_get_comment_without_ranking(self, req, ln, nickname, comment_uid, date_creation, body, status, nb_reports, reply_link=None, report_link=None, undelete_link=None, delete_links=None, unreport_link=None, recID=-1, com_id='', attached_files=None):
"""
private function
@param req: request object to fetch user info
@param ln: language
@param nickname: nickname
@param date_creation: date comment was written
@param body: comment body
@param status: status of the comment:
da: deleted by author
dm: deleted by moderator
ok: active
@param nb_reports: number of reports the comment has
@param reply_link: if want reply and report, give the http links
@param report_link: if want reply and report, give the http links
@param undelete_link: http link to delete the message
@param delete_links: http links to delete the message
@param unreport_link: http link to unreport the comment
@param recID: recID where the comment is posted
@param com_id: ID of the comment displayed
@param attached_files: list of attached files
@return: html table of comment
"""
from invenio.search_engine import guess_primary_collection_of_a_record
# load the right message language
_ = gettext_set_language(ln)
date_creation = convert_datetext_to_dategui(date_creation, ln=ln)
if attached_files is None:
attached_files = []
out = ''
final_body = email_quoted_txt2html(body)
title = _('%(x_name)s wrote on %(x_date)s:') % {'x_name': nickname,
'x_date': '<i>' + date_creation + '</i>'}
title += '<a name=%s></a>' % com_id
links = ''
moderator_links = ''
if reply_link:
links += '<a href="' + reply_link +'">' + _("Reply") +'</a>'
if report_link and status != 'ap':
links += ' | '
if report_link and status != 'ap':
links += '<a href="' + report_link +'">' + _("Report abuse") + '</a>'
# Check if user is a comment moderator
record_primary_collection = guess_primary_collection_of_a_record(recID)
user_info = collect_user_info(req)
(auth_code, auth_msg) = acc_authorize_action(user_info, 'moderatecomments', collection=record_primary_collection)
if status in ['dm', 'da'] and req:
if not auth_code:
if status == 'dm':
final_body = '<div style="color:#a3a3a3;font-style:italic;">(Comment deleted by the moderator) - not visible for users<br /><br />' +\
final_body + '</div>'
else:
final_body = '<div style="color:#a3a3a3;font-style:italic;">(Comment deleted by the author) - not visible for users<br /><br />' +\
final_body + '</div>'
links = ''
moderator_links += '<a style="color:#8B0000;" href="' + undelete_link + '">' + _("Undelete comment") + '</a>'
else:
if status == 'dm':
final_body = '<div style="color:#a3a3a3;font-style:italic;">Comment deleted by the moderator</div>'
else:
final_body = '<div style="color:#a3a3a3;font-style:italic;">Comment deleted by the author</div>'
links = ''
else:
if not auth_code:
moderator_links += '<a style="color:#8B0000;" href="' + delete_links['mod'] +'">' + _("Delete comment") + '</a>'
elif (user_info['uid'] == comment_uid) and CFG_WEBCOMMENT_AUTHOR_DELETE_COMMENT_OPTION:
moderator_links += '<a style="color:#8B0000;" href="' + delete_links['auth'] +'">' + _("Delete comment") + '</a>'
if nb_reports >= CFG_WEBCOMMENT_NB_REPORTS_BEFORE_SEND_EMAIL_TO_ADMIN:
if not auth_code:
final_body = '<div style="color:#a3a3a3;font-style:italic;">(Comment reported. Pending approval) - not visible for users<br /><br />' + final_body + '</div>'
links = ''
moderator_links += ' | '
moderator_links += '<a style="color:#8B0000;" href="' + unreport_link +'">' + _("Unreport comment") + '</a>'
else:
final_body = '<div style="color:#a3a3a3;font-style:italic;">This comment is pending approval due to user reports</div>'
links = ''
if links and moderator_links:
links = links + ' || ' + moderator_links
elif not links:
links = moderator_links
attached_files_html = ''
if attached_files:
attached_files_html = '<div class="cmtfilesblock"><b>%s:</b><br/>' % (len(attached_files) == 1 and _("Attached file") or _("Attached files"))
for (filename, filepath, fileurl) in attached_files:
attached_files_html += create_html_link(urlbase=fileurl, urlargd={},
link_label=cgi.escape(filename)) + '<br />'
attached_files_html += '</div>'
out += """
<div style="margin-bottom:20px;background:#F9F9F9;border:1px solid #DDD">%(title)s<br />
<blockquote>
%(body)s
</blockquote>
<br />
%(attached_files_html)s
<div style="float:right">%(links)s</div>
</div>""" % \
{'title' : '<div style="background-color:#EEE;padding:2px;"><img src="%s/img/user-icon-1-24x24.gif" alt="" /> %s</div>' % (CFG_SITE_URL, title),
'body' : final_body,
'links' : links,
'attached_files_html': attached_files_html}
return out
def tmpl_get_comment_with_ranking(self, req, ln, nickname, comment_uid, date_creation, body, status, nb_reports, nb_votes_total, nb_votes_yes, star_score, title, report_link=None, delete_links=None, undelete_link=None, unreport_link=None, recID=-1):
"""
private function
@param req: request object to fetch user info
@param ln: language
@param nickname: nickname
@param date_creation: date comment was written
@param body: comment body
@param status: status of the comment
@param nb_reports: number of reports the comment has
@param nb_votes_total: total number of votes for this review
@param nb_votes_yes: number of positive votes for this record
@param star_score: star score for this record
@param title: title of review
@param report_link: if want reply and report, give the http links
@param undelete_link: http link to delete the message
@param delete_link: http link to delete the message
@param unreport_link: http link to unreport the comment
@param recID: recID where the comment is posted
@return: html table of review
"""
from invenio.search_engine import guess_primary_collection_of_a_record
# load the right message language
_ = gettext_set_language(ln)
if star_score > 0:
star_score_img = 'stars-' + str(star_score) + '-0.png'
else:
star_score_img = 'stars-0-0.png'
out = ""
date_creation = convert_datetext_to_dategui(date_creation, ln=ln)
reviewed_label = _("Reviewed by %(x_nickname)s on %(x_date)s") % {'x_nickname': nickname, 'x_date':date_creation}
useful_label = _("%(x_nb_people)i out of %(x_nb_total)i people found this review useful") % {'x_nb_people': nb_votes_yes,
'x_nb_total': nb_votes_total}
links = ''
_body = ''
if body != '':
_body = '''
<blockquote>
%s
</blockquote>''' % email_quoted_txt2html(body, linebreak_html='')
# Check if user is a comment moderator
record_primary_collection = guess_primary_collection_of_a_record(recID)
user_info = collect_user_info(req)
(auth_code, auth_msg) = acc_authorize_action(user_info, 'moderatecomments', collection=record_primary_collection)
if status in ['dm', 'da'] and req:
if not auth_code:
if status == 'dm':
_body = '<div style="color:#a3a3a3;font-style:italic;">(Review deleted by moderator) - not visible for users<br /><br />' +\
_body + '</div>'
else:
_body = '<div style="color:#a3a3a3;font-style:italic;">(Review deleted by author) - not visible for users<br /><br />' +\
_body + '</div>'
links = '<a style="color:#8B0000;" href="' + undelete_link + '">' + _("Undelete review") + '</a>'
else:
if status == 'dm':
_body = '<div style="color:#a3a3a3;font-style:italic;">Review deleted by moderator</div>'
else:
_body = '<div style="color:#a3a3a3;font-style:italic;">Review deleted by author</div>'
links = ''
else:
if not auth_code:
links += '<a style="color:#8B0000;" href="' + delete_links['mod'] +'">' + _("Delete review") + '</a>'
if nb_reports >= CFG_WEBCOMMENT_NB_REPORTS_BEFORE_SEND_EMAIL_TO_ADMIN:
if not auth_code:
_body = '<div style="color:#a3a3a3;font-style:italic;">(Review reported. Pending approval) - not visible for users<br /><br />' + _body + '</div>'
links += ' | '
links += '<a style="color:#8B0000;" href="' + unreport_link +'">' + _("Unreport review") + '</a>'
else:
_body = '<div style="color:#a3a3a3;font-style:italic;">This review is pending approval due to user reports.</div>'
links = ''
out += '''
<div style="background:#F9F9F9;border:1px solid #DDD">
<div style="background-color:#EEE;padding:2px;">
<img src="%(siteurl)s/img/%(star_score_img)s" alt="%(star_score)s" style="margin-right:10px;"/><b>%(title)s</b><br />
%(reviewed_label)s<br />
%(useful_label)s
</div>
%(body)s
</div>
%(abuse)s''' % {'siteurl' : CFG_SITE_URL,
'star_score_img': star_score_img,
'star_score' : star_score,
'title' : title,
'reviewed_label': reviewed_label,
'useful_label' : useful_label,
'body' : _body,
'abuse' : links
}
return out
def tmpl_get_comments(self, req, recID, ln,
nb_per_page, page, nb_pages,
display_order, display_since,
CFG_WEBCOMMENT_ALLOW_REVIEWS,
comments, total_nb_comments,
avg_score,
warnings,
border=0, reviews=0,
total_nb_reviews=0,
nickname='', uid=-1, note='',score=5,
can_send_comments=False,
can_attach_files=False,
user_is_subscribed_to_discussion=False,
user_can_unsubscribe_from_discussion=False,
display_comment_rounds=None):
"""
Get table of all comments
@param recID: record id
@param ln: language
@param nb_per_page: number of results per page
@param page: page number
@param display_order: hh = highest helpful score, review only
lh = lowest helpful score, review only
hs = highest star score, review only
ls = lowest star score, review only
od = oldest date
nd = newest date
@param display_since: all= no filtering by date
nd = n days ago
nw = n weeks ago
nm = n months ago
ny = n years ago
where n is a single digit integer between 0 and 9
@param CFG_WEBCOMMENT_ALLOW_REVIEWS: is ranking enable, get from config.py/CFG_WEBCOMMENT_ALLOW_REVIEWS
@param comments: tuple as returned from webcomment.py/query_retrieve_comments_or_remarks
@param total_nb_comments: total number of comments for this record
@param avg_score: average score of reviews for this record
@param warnings: list of warning tuples (warning_msg, color)
@param border: boolean, active if want to show border around each comment/review
@param reviews: boolean, enabled for reviews, disabled for comments
@param can_send_comments: boolean, if user can send comments or not
@param can_attach_files: boolean, if user can attach file to comment or not
@param user_is_subscribed_to_discussion: True if user already receives new comments by email
@param user_can_unsubscribe_from_discussion: True is user is allowed to unsubscribe from discussion
"""
# load the right message language
_ = gettext_set_language(ln)
# CERN hack begins: display full ATLAS user name. Check further below too.
current_user_fullname = ""
override_nickname_p = False
if CFG_CERN_SITE:
from invenio.search_engine import get_all_collections_of_a_record
user_info = collect_user_info(uid)
if 'atlas-readaccess-active-members [CERN]' in user_info['group']:
# An ATLAS member is never anonymous to its colleagues
# when commenting inside ATLAS collections
recid_collections = get_all_collections_of_a_record(recID)
if 'ATLAS' in str(recid_collections):
override_nickname_p = True
current_user_fullname = user_info.get('external_fullname', '')
# CERN hack ends
# naming data fields of comments
if reviews:
c_nickname = 0
c_user_id = 1
c_date_creation = 2
c_body = 3
c_status = 4
c_nb_reports = 5
c_nb_votes_yes = 6
c_nb_votes_total = 7
c_star_score = 8
c_title = 9
c_id = 10
c_round_name = 11
c_restriction = 12
reply_to = 13
discussion = 'reviews'
comments_link = '<a href="%s/record/%s/comments/">%s</a> (%i)' % (CFG_SITE_URL, recID, _('Comments'), total_nb_comments)
reviews_link = '<b>%s (%i)</b>' % (_('Reviews'), total_nb_reviews)
add_comment_or_review = self.tmpl_add_comment_form_with_ranking(recID, uid, current_user_fullname or nickname, ln, '', score, note, warnings, show_title_p=True, can_attach_files=can_attach_files)
else:
c_nickname = 0
c_user_id = 1
c_date_creation = 2
c_body = 3
c_status = 4
c_nb_reports = 5
c_id = 6
c_round_name = 7
c_restriction = 8
reply_to = 9
discussion = 'comments'
comments_link = '<b>%s (%i)</b>' % (_('Comments'), total_nb_comments)
reviews_link = '<a href="%s/record/%s/reviews/">%s</a> (%i)' % (CFG_SITE_URL, recID, _('Reviews'), total_nb_reviews)
add_comment_or_review = self.tmpl_add_comment_form(recID, uid, nickname, ln, note, warnings, can_attach_files=can_attach_files, user_is_subscribed_to_discussion=user_is_subscribed_to_discussion)
# voting links
useful_dict = { 'siteurl' : CFG_SITE_URL,
'recID' : recID,
'ln' : ln,
'do' : display_order,
'ds' : display_since,
'nb' : nb_per_page,
'p' : page,
'reviews' : reviews,
'discussion' : discussion
}
useful_yes = '<a href="%(siteurl)s/record/%(recID)s/%(discussion)s/vote?ln=%(ln)s&comid=%%(comid)s&com_value=1&do=%(do)s&ds=%(ds)s&nb=%(nb)s&p=%(p)s&referer=%(siteurl)s/record/%(recID)s/%(discussion)s/display">' + _("Yes") + '</a>'
useful_yes %= useful_dict
useful_no = '<a href="%(siteurl)s/record/%(recID)s/%(discussion)s/vote?ln=%(ln)s&comid=%%(comid)s&com_value=-1&do=%(do)s&ds=%(ds)s&nb=%(nb)s&p=%(p)s&referer=%(siteurl)s/record/%(recID)s/%(discussion)s/display">' + _("No") + '</a>'
useful_no %= useful_dict
warnings = self.tmpl_warnings(warnings, ln)
link_dic = { 'siteurl' : CFG_SITE_URL,
'module' : 'comments',
'function' : 'index',
'discussion': discussion,
'arguments' : 'do=%s&ds=%s&nb=%s' % (display_order, display_since, nb_per_page),
'arg_page' : '&p=%s' % page,
'page' : page,
'rec_id' : recID}
if not req:
req = None
## comments table
comments_rows = ''
last_comment_round_name = None
comment_round_names = [comment[0] for comment in comments]
if comment_round_names:
last_comment_round_name = comment_round_names[-1]
for comment_round_name, comments_list in comments:
comment_round_style = "display:none;"
comment_round_is_open = False
if comment_round_name in display_comment_rounds:
comment_round_is_open = True
comment_round_style = ""
comments_rows += '<div id="cmtRound%s" class="cmtround">' % (comment_round_name)
if not comment_round_is_open and \
(comment_round_name or len(comment_round_names) > 1):
new_cmtgrp = list(display_comment_rounds)
new_cmtgrp.append(comment_round_name)
comments_rows += '''<img src="/img/right-trans.gif" id="cmtarrowiconright%(grp_id)s" alt="Open group" /><img src="/img/down-trans.gif" id="cmtarrowicondown%(grp_id)s" alt="Close group" style="display:none" />
<a class="cmtgrpswitch" name="cmtgrpLink%(grp_id)s" onclick="var cmtarrowicondown=document.getElementById('cmtarrowicondown%(grp_id)s');var cmtarrowiconright=document.getElementById('cmtarrowiconright%(grp_id)s');var subgrp=document.getElementById('cmtSubRound%(grp_id)s');if (subgrp.style.display==''){subgrp.style.display='none';cmtarrowiconright.style.display='';cmtarrowicondown.style.display='none';}else{subgrp.style.display='';cmtarrowiconright.style.display='none';cmtarrowicondown.style.display='';};return false;"''' % {'grp_id': comment_round_name}
comments_rows += 'href=\"%(siteurl)s/record/%(rec_id)s/%(discussion)s/%(function)s?%(arguments)s&%(arg_page)s' % link_dic
comments_rows += '&' + '&'.join(["cmtgrp=" + grp for grp in new_cmtgrp if grp != 'none']) + \
'#cmtgrpLink%s' % (comment_round_name) + '\">'
comments_rows += _('%(x_nb)i comments for round "%(x_name)s"') % {'x_nb': len(comments_list), 'x_name': comment_round_name} + "</a><br/>"
elif comment_round_name or len(comment_round_names) > 1:
new_cmtgrp = list(display_comment_rounds)
new_cmtgrp.remove(comment_round_name)
comments_rows += '''<img src="/img/right-trans.gif" id="cmtarrowiconright%(grp_id)s" alt="Open group" style="display:none" /><img src="/img/down-trans.gif" id="cmtarrowicondown%(grp_id)s" alt="Close group" />
<a class="cmtgrpswitch" name="cmtgrpLink%(grp_id)s" onclick="var cmtarrowicondown=document.getElementById('cmtarrowicondown%(grp_id)s');var cmtarrowiconright=document.getElementById('cmtarrowiconright%(grp_id)s');var subgrp=document.getElementById('cmtSubRound%(grp_id)s');if (subgrp.style.display==''){subgrp.style.display='none';cmtarrowiconright.style.display='';cmtarrowicondown.style.display='none';}else{subgrp.style.display='';cmtarrowiconright.style.display='none';cmtarrowicondown.style.display='';};return false;"''' % {'grp_id': comment_round_name}
comments_rows += 'href=\"%(siteurl)s/record/%(rec_id)s/%(discussion)s/%(function)s?%(arguments)s&%(arg_page)s' % link_dic
comments_rows += '&' + ('&'.join(["cmtgrp=" + grp for grp in new_cmtgrp if grp != 'none']) or 'cmtgrp=none' ) + \
'#cmtgrpLink%s' % (comment_round_name) + '\">'
comments_rows += _('%(x_nb)i comments for round "%(x_name)s"') % {'x_nb': len(comments_list), 'x_name': comment_round_name}+ "</a><br/>"
comments_rows += '<div id="cmtSubRound%s" class="cmtsubround" style="%s">' % (comment_round_name,
comment_round_style)
thread_history = [0]
for comment in comments_list:
if comment[reply_to] not in thread_history:
# Going one level down in the thread
thread_history.append(comment[reply_to])
depth = thread_history.index(comment[reply_to])
else:
depth = thread_history.index(comment[reply_to])
thread_history = thread_history[:depth + 1]
# CERN hack begins: display full ATLAS user name.
comment_user_fullname = ""
if CFG_CERN_SITE and override_nickname_p:
comment_user_fullname = get_email(comment[c_user_id])
# CERN hack ends
if comment[c_nickname]:
_nickname = comment[c_nickname]
display = _nickname
else:
(uid, _nickname, display) = get_user_info(comment[c_user_id])
messaging_link = self.create_messaging_link(_nickname, comment_user_fullname or display, ln)
from invenio.webcomment import get_attached_files # FIXME
files = get_attached_files(recID, comment[c_id])
# do NOT delete the HTML comment below. It is used for parsing... (I plead unguilty!)
comments_rows += """
<!-- start comment row -->
<div style="margin-left:%spx">""" % (depth*20)
delete_links = {}
if not reviews:
report_link = '%(siteurl)s/record/%(recID)s/comments/report?ln=%(ln)s&comid=%%(comid)s&do=%(do)s&ds=%(ds)s&nb=%(nb)s&p=%(p)s&referer=%(siteurl)s/record/%(recID)s/comments/display' % useful_dict % {'comid':comment[c_id]}
reply_link = '%(siteurl)s/record/%(recID)s/comments/add?ln=%(ln)s&action=REPLY&comid=%%(comid)s' % useful_dict % {'comid':comment[c_id]}
delete_links['mod'] = "%s/admin/webcomment/webcommentadmin.py/del_single_com_mod?ln=%s&id=%s" % (CFG_SITE_URL, ln, comment[c_id])
delete_links['auth'] = "%s/admin/webcomment/webcommentadmin.py/del_single_com_auth?ln=%s&id=%s" % (CFG_SITE_URL, ln, comment[c_id])
undelete_link = "%s/admin/webcomment/webcommentadmin.py/undel_com?ln=%s&id=%s" % (CFG_SITE_URL, ln, comment[c_id])
unreport_link = "%s/admin/webcomment/webcommentadmin.py/unreport_com?ln=%s&id=%s" % (CFG_SITE_URL, ln, comment[c_id])
comments_rows += self.tmpl_get_comment_without_ranking(req, ln, messaging_link, comment[c_user_id], comment[c_date_creation], comment[c_body], comment[c_status], comment[c_nb_reports], reply_link, report_link, undelete_link, delete_links, unreport_link, recID, comment[c_id], files)
else:
report_link = '%(siteurl)s/record/%(recID)s/reviews/report?ln=%(ln)s&comid=%%(comid)s&do=%(do)s&ds=%(ds)s&nb=%(nb)s&p=%(p)s&referer=%(siteurl)s/record/%(recID)s/reviews/display' % useful_dict % {'comid': comment[c_id]}
delete_links['mod'] = "%s/admin/webcomment/webcommentadmin.py/del_single_com_mod?ln=%s&id=%s" % (CFG_SITE_URL, ln, comment[c_id])
delete_links['auth'] = "%s/admin/webcomment/webcommentadmin.py/del_single_com_auth?ln=%s&id=%s" % (CFG_SITE_URL, ln, comment[c_id])
undelete_link = "%s/admin/webcomment/webcommentadmin.py/undel_com?ln=%s&id=%s" % (CFG_SITE_URL, ln, comment[c_id])
unreport_link = "%s/admin/webcomment/webcommentadmin.py/unreport_com?ln=%s&id=%s" % (CFG_SITE_URL, ln, comment[c_id])
comments_rows += self.tmpl_get_comment_with_ranking(req, ln, messaging_link, comment[c_user_id], comment[c_date_creation], comment[c_body], comment[c_status], comment[c_nb_reports], comment[c_nb_votes_total], comment[c_nb_votes_yes], comment[c_star_score], comment[c_title], report_link, delete_links, undelete_link, unreport_link, recID)
helpful_label = _("Was this review helpful?")
report_abuse_label = "(" + _("Report abuse") + ")"
yes_no_separator = '<td> / </td>'
if comment[c_nb_reports] >= CFG_WEBCOMMENT_NB_REPORTS_BEFORE_SEND_EMAIL_TO_ADMIN or comment[c_status] in ['dm', 'da']:
report_abuse_label = ""
helpful_label = ""
useful_yes = ""
useful_no = ""
yes_no_separator = ""
comments_rows += """
<table>
<tr>
<td>%(helpful_label)s %(tab)s</td>
<td> %(yes)s </td>
%(yes_no_separator)s
<td> %(no)s </td>
<td class="reportabuse">%(tab)s%(tab)s<a href="%(report)s">%(report_abuse_label)s</a></td>
</tr>
</table>""" \
% {'helpful_label': helpful_label,
'yes' : useful_yes % {'comid':comment[c_id]},
'yes_no_separator': yes_no_separator,
'no' : useful_no % {'comid':comment[c_id]},
'report' : report_link % {'comid':comment[c_id]},
'report_abuse_label': comment[c_nb_reports] >= CFG_WEBCOMMENT_NB_REPORTS_BEFORE_SEND_EMAIL_TO_ADMIN and '' or report_abuse_label,
'tab' : ' '*2}
# do NOT remove HTML comment below. It is used for parsing...
comments_rows += """
</div>
<!-- end comment row -->"""
comments_rows += '</div></div>'
## page links
page_links = ''
# Previous
if page != 1:
link_dic['arg_page'] = 'p=%s' % (page - 1)
page_links += '<a href=\"%(siteurl)s/record/%(rec_id)s/%(discussion)s/%(function)s?%(arguments)s&%(arg_page)s\"><<</a> ' % link_dic
else:
page_links += ' %s ' % (' '*(len(_('Previous'))+7))
# Page Numbers
for i in range(1, nb_pages+1):
link_dic['arg_page'] = 'p=%s' % i
link_dic['page'] = '%s' % i
if i != page:
page_links += '''
<a href=\"%(siteurl)s/record/%(rec_id)s/%(discussion)s/%(function)s?%(arguments)s&%(arg_page)s\">%(page)s</a> ''' % link_dic
else:
page_links += ''' <b>%s</b> ''' % i
# Next
if page != nb_pages:
link_dic['arg_page'] = 'p=%s' % (page + 1)
page_links += '''
<a href=\"%(siteurl)s/record/%(rec_id)s/%(discussion)s/%(function)s?%(arguments)s&%(arg_page)s\">>></a> ''' % link_dic
else:
page_links += '%s' % (' '*(len(_('Next'))+7))
## stuff for ranking if enabled
if reviews:
if avg_score > 0:
avg_score_img = 'stars-' + str(avg_score).split('.')[0] + '-' + str(avg_score).split('.')[1] + '.png'
else:
avg_score_img = "stars-0-0.png"
ranking_average = '<br /><b>'
ranking_average += _("Average review score: %(x_nb_score)s based on %(x_nb_reviews)s reviews") % \
{'x_nb_score': '</b><img src="' + CFG_SITE_URL + '/img/' + avg_score_img + '" alt="' + str(avg_score) + '" />',
'x_nb_reviews': str(total_nb_reviews)}
ranking_average += '<br />'
else:
ranking_average = ""
write_button_link = '''%s/record/%s/%s/add''' % (CFG_SITE_URL, recID, discussion)
write_button_form = '<input type="hidden" name="ln" value="%s"/>'
write_button_form = self.createhiddenform(action=write_button_link,
method="get",
text=write_button_form,
button = reviews and _('Write a review') or _('Write a comment'))
if reviews:
total_label = _("There is a total of %s reviews")
else:
total_label = _("There is a total of %s comments")
total_label %= total_nb_comments
review_or_comment_first = ''
if reviews == 0 and total_nb_comments == 0 and can_send_comments:
review_or_comment_first = _("Start a discussion about any aspect of this document.") + '<br />'
elif reviews == 1 and total_nb_reviews == 0 and can_send_comments:
review_or_comment_first = _("Be the first to review this document.") + '<br />'
# do NOT remove the HTML comments below. Used for parsing
body = '''
%(comments_and_review_tabs)s
<!-- start comments table -->
<div style="border: %(border)spx solid black; width: 95%%; margin:10px;font-size:small">
%(comments_rows)s
</div>
<!-- end comments table -->
%(review_or_comment_first)s
<br />''' % \
{ 'record_label': _("Record"),
'back_label': _("Back to search results"),
'total_label': total_label,
'write_button_form' : write_button_form,
'write_button_form_again' : total_nb_comments>3 and write_button_form or "",
'comments_rows' : comments_rows,
'total_nb_comments' : total_nb_comments,
'comments_or_reviews' : reviews and _('review') or _('comment'),
'comments_or_reviews_title' : reviews and _('Review') or _('Comment'),
'siteurl' : CFG_SITE_URL,
'module' : "comments",
'recid' : recID,
'ln' : ln,
'border' : border,
'ranking_avg' : ranking_average,
'comments_and_review_tabs' : CFG_WEBCOMMENT_ALLOW_REVIEWS and \
CFG_WEBCOMMENT_ALLOW_COMMENTS and \
'%s | %s <br />' % \
(comments_link, reviews_link) or '',
'review_or_comment_first' : review_or_comment_first
}
# form is not currently used. reserved for an eventual purpose
#form = """
# Display <select name="nb" size="1"> per page
# <option value="all">All</option>
# <option value="10">10</option>
# <option value="25">20</option>
# <option value="50">50</option>
# <option value="100" selected="selected">100</option>
# </select>
# comments per page that are <select name="ds" size="1">
# <option value="all" selected="selected">Any age</option>
# <option value="1d">1 day old</option>
# <option value="3d">3 days old</option>
# <option value="1w">1 week old</option>
# <option value="2w">2 weeks old</option>
# <option value="1m">1 month old</option>
# <option value="3m">3 months old</option>
# <option value="6m">6 months old</option>
# <option value="1y">1 year old</option>
# </select>
# and sorted by <select name="do" size="1">
# <option value="od" selected="selected">Oldest first</option>
# <option value="nd">Newest first</option>
# %s
# </select>
# """ % \
# (reviews==1 and '''
# <option value=\"hh\">most helpful</option>
# <option value=\"lh\">least helpful</option>
# <option value=\"hs\">highest star ranking</option>
# <option value=\"ls\">lowest star ranking</option>
# </select>''' or '''
# </select>''')
#
#form_link = "%(siteurl)s/%(module)s/%(function)s" % link_dic
#form = self.createhiddenform(action=form_link, method="get", text=form, button='Go', recid=recID, p=1)
pages = """
<div>
%(v_label)s %(comments_or_reviews)s %(results_nb_lower)s-%(results_nb_higher)s <br />
%(page_links)s
</div>
""" % \
{'v_label': _("Viewing"),
'page_links': _("Page:") + page_links ,
'comments_or_reviews': reviews and _('review') or _('comment'),
'results_nb_lower': len(comments)>0 and ((page-1) * nb_per_page)+1 or 0,
'results_nb_higher': page == nb_pages and (((page-1) * nb_per_page) + len(comments)) or (page * nb_per_page)}
if nb_pages > 1:
#body = warnings + body + form + pages
body = warnings + body + pages
else:
body = warnings + body
if reviews == 0:
if not user_is_subscribed_to_discussion:
body += '<small>'
body += '<div class="comment-subscribe">' + '<img src="%s/img/mail-icon-12x8.gif" border="0" alt="" />' % CFG_SITE_URL + \
' ' + '<b>' + create_html_link(urlbase=CFG_SITE_URL + '/record/' + \
str(recID) + '/comments/subscribe',
urlargd={},
link_label=_('Subscribe')) + \
'</b>' + ' to this discussion. You will then receive all new comments by email.' + '</div>'
body += '</small><br />'
elif user_can_unsubscribe_from_discussion:
body += '<small>'
body += '<div class="comment-subscribe">' + '<img src="%s/img/mail-icon-12x8.gif" border="0" alt="" />' % CFG_SITE_URL + \
' ' + '<b>' + create_html_link(urlbase=CFG_SITE_URL + '/record/' + \
str(recID) + '/comments/unsubscribe',
urlargd={},
link_label=_('Unsubscribe')) + \
'</b>' + ' from this discussion. You will no longer receive emails about new comments.' + '</div>'
body += '</small><br />'
if can_send_comments:
body += add_comment_or_review
else:
body += '<br/><em>' + _("You are not authorized to comment or review.") + '</em>'
return '<div style="margin-left:10px;margin-right:10px;">' + body + '</div>'
def create_messaging_link(self, to, display_name, ln=CFG_SITE_LANG):
"""prints a link to the messaging system"""
link = "%s/yourmessages/write?msg_to=%s&ln=%s" % (CFG_SITE_URL, to, ln)
if to:
return '<a href="%s" class="maillink">%s</a>' % (link, display_name)
else:
return display_name
def createhiddenform(self, action="", method="get", text="", button="confirm", cnfrm='', **hidden):
"""
create select with hidden values and submit button
@param action: name of the action to perform on submit
@param method: 'get' or 'post'
@param text: additional text, can also be used to add non hidden input
@param button: value/caption on the submit button
@param cnfrm: if given, must check checkbox to confirm
@param **hidden: dictionary with name=value pairs for hidden input
@return: html form
"""
output = """
<form action="%s" method="%s">""" % (action, method.lower().strip() in ['get', 'post'] and method or 'get')
output += """
<table style="width:90%">
<tr>
<td style="vertical-align: top">
"""
output += text + '\n'
if cnfrm:
output += """
<input type="checkbox" name="confirm" value="1" />"""
for key in hidden.keys():
if type(hidden[key]) is list:
for value in hidden[key]:
output += """
<input type="hidden" name="%s" value="%s" />""" % (key, value)
else:
output += """
<input type="hidden" name="%s" value="%s" />""" % (key, hidden[key])
output += """
</td>
</tr>
<tr>
<td>"""
output += """
<input class="adminbutton" type="submit" value="%s" />""" % (button, )
output += """
</td>
</tr>
</table>
</form>"""
return output
def create_write_comment_hiddenform(self, action="", method="get", text="", button="confirm", cnfrm='', enctype='', **hidden):
"""
create select with hidden values and submit button
@param action: name of the action to perform on submit
@param method: 'get' or 'post'
@param text: additional text, can also be used to add non hidden input
@param button: value/caption on the submit button
@param cnfrm: if given, must check checkbox to confirm
@param **hidden: dictionary with name=value pairs for hidden input
@return: html form
"""
enctype_attr = ''
if enctype:
enctype_attr = 'enctype=' + enctype
output = """
<form action="%s" method="%s" %s>""" % (action, method.lower().strip() in ['get', 'post'] and method or 'get', enctype_attr)
if cnfrm:
output += """
<input type="checkbox" name="confirm" value="1" />"""
for key in hidden.keys():
if type(hidden[key]) is list:
for value in hidden[key]:
output += """
<input type="hidden" name="%s" value="%s" />""" % (key, value)
else:
output += """
<input type="hidden" name="%s" value="%s" />""" % (key, hidden[key])
output += text + '\n'
output += """
</form>"""
return output
def tmpl_warnings(self, warnings, ln=CFG_SITE_LANG):
"""
Prepare the warnings list
@param warnings: list of warning tuples (warning_msg, arg1, arg2, etc)
@return: html string of warnings
"""
red_text_warnings = ['WRN_WEBCOMMENT_FEEDBACK_NOT_RECORDED',
'WRN_WEBCOMMENT_ALREADY_VOTED']
green_text_warnings = ['WRN_WEBCOMMENT_FEEDBACK_RECORDED',
'WRN_WEBCOMMENT_SUBSCRIBED',
'WRN_WEBCOMMENT_UNSUBSCRIBED']
from invenio.errorlib import get_msgs_for_code_list
span_class = 'important'
out = ""
if type(warnings) is not list:
warnings = [warnings]
if len(warnings) > 0:
warnings_parsed = get_msgs_for_code_list(warnings, 'warning', ln)
for (warning_code, warning_text) in warnings_parsed:
if not warning_code.startswith('WRN'):
#display only warnings that begin with WRN to user
continue
if warning_code in red_text_warnings:
span_class = 'important'
elif warning_code in green_text_warnings:
span_class = 'exampleleader'
else:
span_class = 'important'
out += '''
<span class="%(span_class)s">%(warning)s</span><br />''' % \
{ 'span_class' : span_class,
'warning' : warning_text }
return out
else:
return ""
def tmpl_add_comment_form(self, recID, uid, nickname, ln, msg,
warnings, textual_msg=None, can_attach_files=False,
user_is_subscribed_to_discussion=False, reply_to=None):
"""
Add form for comments
@param recID: record id
@param uid: user id
@param ln: language
@param msg: comment body contents for when refreshing due to
warning, or when replying to a comment
@param textual_msg: same as 'msg', but contains the textual
version in case user cannot display FCKeditor
@param warnings: list of warning tuples (warning_msg, color)
@param can_attach_files: if user can upload attach file to record or not
@param user_is_subscribed_to_discussion: True if user already receives new comments by email
@param reply_to: the ID of the comment we are replying to. None if not replying
@return html add comment form
"""
_ = gettext_set_language(ln)
link_dic = { 'siteurl' : CFG_SITE_URL,
'module' : 'comments',
'function' : 'add',
'arguments' : 'ln=%s&action=%s' % (ln, 'SUBMIT'),
'recID' : recID}
if textual_msg is None:
textual_msg = msg
# FIXME a cleaner handling of nicknames is needed.
if not nickname:
(uid, nickname, display) = get_user_info(uid)
if nickname:
note = _("Note: Your nickname, %s, will be displayed as author of this comment.") % ('<i>' + nickname + '</i>')
else:
(uid, nickname, display) = get_user_info(uid)
link = '<a href="%s/youraccount/edit">' % CFG_SITE_SECURE_URL
note = _("Note: you have not %(x_url_open)sdefined your nickname%(x_url_close)s. %(x_nickname)s will be displayed as the author of this comment.") % \
{'x_url_open': link,
'x_url_close': '</a>',
'x_nickname': ' <br /><i>' + display + '</i>'}
if not CFG_WEBCOMMENT_USE_RICH_TEXT_EDITOR:
note += '<br />' + ' '*10 + cgi.escape('You can use some HTML tags: <a href>, <strong>, <blockquote>, <br />, <p>, <em>, <ul>, <li>, <b>, <i>')
#from invenio.search_engine import print_record
#record_details = print_record(recID=recID, format='hb', ln=ln)
warnings = self.tmpl_warnings(warnings, ln)
# Prepare file upload settings. We must enable file upload in
# the fckeditor + a simple file upload interface (independant from editor)
file_upload_url = None
simple_attach_file_interface = ''
if isGuestUser(uid):
simple_attach_file_interface = "<small><em>%s</em></small><br/>" % _("Once logged in, authorized users can also attach files.")
if can_attach_files:
# Note that files can be uploaded only when user is logged in
#file_upload_url = '%s/record/%i/comments/attachments/put' % \
# (CFG_SITE_URL, recID)
simple_attach_file_interface = '''
<div id="uploadcommentattachmentsinterface">
<small>%(attach_msg)s: <em>(%(nb_files_limit_msg)s. %(file_size_limit_msg)s)</em></small><br />
<input class="multi max-%(CFG_WEBCOMMENT_MAX_ATTACHED_FILES)s" type="file" name="commentattachment[]"/><br />
<noscript>
<input type="file" name="commentattachment[]" /><br />
</noscript>
</div>
''' % \
{'CFG_WEBCOMMENT_MAX_ATTACHED_FILES': CFG_WEBCOMMENT_MAX_ATTACHED_FILES,
'attach_msg': CFG_WEBCOMMENT_MAX_ATTACHED_FILES == 1 and _("Optionally, attach a file to this comment") or \
_("Optionally, attach files to this comment"),
'nb_files_limit_msg': _("Max one file") and CFG_WEBCOMMENT_MAX_ATTACHED_FILES == 1 or \
_("Max %i files") % CFG_WEBCOMMENT_MAX_ATTACHED_FILES,
'file_size_limit_msg': CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE > 0 and _("Max %(x_nb_bytes)s per file") % {'x_nb_bytes': (CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE < 1024*1024 and (str(CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE/1024) + 'KB') or (str(CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE/(1024*1024)) + 'MB'))} or ''}
editor = get_html_text_editor(name='msg',
content=msg,
textual_content=textual_msg,
width='100%',
height='400px',
enabled=CFG_WEBCOMMENT_USE_RICH_TEXT_EDITOR,
file_upload_url=file_upload_url,
toolbar_set = "WebComment")
subscribe_to_discussion = ''
if not user_is_subscribed_to_discussion:
# Offer to subscribe to discussion
subscribe_to_discussion = '<small><input type="checkbox" name="subscribe" id="subscribe"/><label for="subscribe">%s</label></small>' % _("Send me an email when a new comment is posted")
form = """<div id="comment-write"><h2>%(add_comment)s</h2>
%(editor)s
<br />
%(simple_attach_file_interface)s
<span class="reportabuse">%(note)s</span>
<div class="submit-area">
%(subscribe_to_discussion)s<br />
<input class="adminbutton" type="submit" value="Add comment" />
%(reply_to)s
</div>
""" % {'note': note,
'record_label': _("Article") + ":",
'comment_label': _("Comment") + ":",
'add_comment': _('Add comment'),
'editor': editor,
'subscribe_to_discussion': subscribe_to_discussion,
'reply_to': reply_to and '<input type="hidden" name="comid" value="%s"/>' % reply_to or '',
'simple_attach_file_interface': simple_attach_file_interface}
form_link = "%(siteurl)s/record/%(recID)s/comments/%(function)s?%(arguments)s" % link_dic
form = self.create_write_comment_hiddenform(action=form_link, method="post", text=form, button='Add comment',
enctype='multipart/form-data')
form += '</div>'
return warnings + form
def tmpl_add_comment_form_with_ranking(self, recID, uid, nickname, ln, msg, score, note,
warnings, textual_msg=None, show_title_p=False,
can_attach_files=False):
"""
Add form for reviews
@param recID: record id
@param uid: user id
@param ln: language
@param msg: comment body contents for when refreshing due to warning
@param textual_msg: the textual version of 'msg' when user cannot display FCKeditor
@param score: review score
@param note: review title
@param warnings: list of warning tuples (warning_msg, color)
@param show_title_p: if True, prefix the form with "Add Review" as title
@param can_attach_files: if user can upload attach file to record or not
@return: html add review form
"""
_ = gettext_set_language(ln)
link_dic = { 'siteurl' : CFG_SITE_URL,
'module' : 'comments',
'function' : 'add',
'arguments' : 'ln=%s&action=%s' % (ln, 'SUBMIT'),
'recID' : recID}
warnings = self.tmpl_warnings(warnings, ln)
if textual_msg is None:
textual_msg = msg
#from search_engine import print_record
#record_details = print_record(recID=recID, format='hb', ln=ln)
if nickname:
note_label = _("Note: Your nickname, %s, will be displayed as the author of this review.")
note_label %= ('<i>' + nickname + '</i>')
else:
(uid, nickname, display) = get_user_info(uid)
link = '<a href="%s/youraccount/edit">' % CFG_SITE_SECURE_URL
note_label = _("Note: you have not %(x_url_open)sdefined your nickname%(x_url_close)s. %(x_nickname)s will be displayed as the author of this comment.") % \
{'x_url_open': link,
'x_url_close': '</a>',
'x_nickname': ' <br /><i>' + display + '</i>'}
selected0 = ''
selected1 = ''
selected2 = ''
selected3 = ''
selected4 = ''
selected5 = ''
if score == 0:
selected0 = ' selected="selected"'
elif score == 1:
selected1 = ' selected="selected"'
elif score == 2:
selected2 = ' selected="selected"'
elif score == 3:
selected3 = ' selected="selected"'
elif score == 4:
selected4 = ' selected="selected"'
elif score == 5:
selected5 = ' selected="selected"'
editor = get_html_text_editor(name='msg',
content=msg,
textual_content=msg,
width='90%',
height='400px',
enabled=CFG_WEBCOMMENT_USE_RICH_TEXT_EDITOR,
toolbar_set = "WebComment")
form = """%(add_review)s
<table style="width: 100%%">
<tr>
<td style="padding-bottom: 10px;">%(rate_label)s:
<select name=\"score\" size=\"1\">
<option value=\"0\"%(selected0)s>-%(select_label)s-</option>
<option value=\"5\"%(selected5)s>***** (best)</option>
<option value=\"4\"%(selected4)s>****</option>
<option value=\"3\"%(selected3)s>***</option>
<option value=\"2\"%(selected2)s>**</option>
<option value=\"1\"%(selected1)s>* (worst)</option>
</select>
</td>
</tr>
<tr>
<td>%(title_label)s:</td>
</tr>
<tr>
<td style="padding-bottom: 10px;">
<input type="text" name="note" maxlength="250" style="width:90%%" value="%(note)s" />
</td>
</tr>
<tr>
<td>%(write_label)s:</td>
</tr>
<tr>
<td>
%(editor)s
</td>
</tr>
<tr>
<td class="reportabuse">%(note_label)s</td></tr>
</table>
""" % {'article_label': _('Article'),
'rate_label': _("Rate this article"),
'select_label': _("Select a score"),
'title_label': _("Give a title to your review"),
'write_label': _("Write your review"),
'note_label': note_label,
'note' : note!='' and note or "",
'msg' : msg!='' and msg or "",
#'record' : record_details
'add_review': show_title_p and ('<h2>'+_('Add review')+'</h2>') or '',
'selected0': selected0,
'selected1': selected1,
'selected2': selected2,
'selected3': selected3,
'selected4': selected4,
'selected5': selected5,
'editor': editor,
}
form_link = "%(siteurl)s/record/%(recID)s/reviews/%(function)s?%(arguments)s" % link_dic
form = self.createhiddenform(action=form_link, method="post", text=form, button=_('Add Review'))
return warnings + form
def tmpl_add_comment_successful(self, recID, ln, reviews, warnings, success):
"""
@param recID: record id
@param ln: language
@return: html page of successfully added comment/review
"""
_ = gettext_set_language(ln)
link_dic = { 'siteurl' : CFG_SITE_URL,
'module' : 'comments',
'function' : 'display',
'arguments' : 'ln=%s&do=od' % ln,
'recID' : recID,
'discussion': reviews == 1 and 'reviews' or 'comments'}
link = "%(siteurl)s/record/%(recID)s/%(discussion)s/%(function)s?%(arguments)s" % link_dic
if warnings:
out = self.tmpl_warnings(warnings, ln) + '<br /><br />'
else:
if reviews:
out = _("Your review was successfully added.") + '<br /><br />'
else:
out = _("Your comment was successfully added.") + '<br /><br />'
link += "#%s" % success
out += '<a href="%s">' % link
out += _('Back to record') + '</a>'
return out
def tmpl_create_multiple_actions_form(self,
form_name="",
form_action="",
method="get",
action_display={},
action_field_name="",
button_label="",
button_name="",
content="",
**hidden):
""" Creates an HTML form with a multiple choice of actions and a button to select it.
@param form_action: link to the receiver of the formular
@param form_name: name of the HTML formular
@param method: either 'GET' or 'POST'
@param action_display: dictionary of actions.
action is HTML name (name of action)
display is the string provided in the popup
@param action_field_name: html name of action field
@param button_label: what's written on the button
@param button_name: html name of the button
@param content: what's inside te formular
@param **hidden: dictionary of name/value pairs of hidden fields.
"""
output = """
<form action="%s" method="%s">""" % (form_action, method)
output += """
<table>
<tr>
<td style="vertical-align: top" colspan="2">
"""
output += content + '\n'
for key in hidden.keys():
if type(hidden[key]) is list:
for value in hidden[key]:
output += """
<input type="hidden" name="%s" value="%s" />""" % (key, value)
else:
output += """
<input type="hidden" name="%s" value="%s" />""" % (key, hidden[key])
output += """
</td>
</tr>
<tr>
<td style="text-align:right;">"""
if type(action_display) is dict and len(action_display.keys()):
output += """
<select name="%s">""" % action_field_name
for (key, value) in action_display.items():
output += """
<option value="%s">%s</option>""" % (key, value)
output += """
</select>"""
output += """
</td>
<td style="text-align:left;">
<input class="adminbutton" type="submit" value="%s" name="%s"/>""" % (button_label, button_name)
output += """
</td>
</tr>
</table>
</form>"""
return output
def tmpl_admin_index(self, ln):
"""
Index page
"""
# load the right message language
_ = gettext_set_language(ln)
out = '<ol>'
if CFG_WEBCOMMENT_ALLOW_COMMENTS or CFG_WEBCOMMENT_ALLOW_REVIEWS:
if CFG_WEBCOMMENT_ALLOW_COMMENTS:
out += '<h3>Comments status</h3>'
out += '<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/hot?ln=%(ln)s&comments=1">%(hot_cmt_label)s</a></li>' % \
{'siteurl': CFG_SITE_URL, 'ln': ln, 'hot_cmt_label': _("View most commented records")}
out += '<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/latest?ln=%(ln)s&comments=1">%(latest_cmt_label)s</a></li>' % \
{'siteurl': CFG_SITE_URL, 'ln': ln, 'latest_cmt_label': _("View latest commented records")}
out += '<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/comments?ln=%(ln)s&reviews=0">%(reported_cmt_label)s</a></li>' % \
{'siteurl': CFG_SITE_URL, 'ln': ln, 'reported_cmt_label': _("View all comments reported as abuse")}
if CFG_WEBCOMMENT_ALLOW_REVIEWS:
out += '<h3>Reviews status</h3>'
out += '<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/hot?ln=%(ln)s&comments=0">%(hot_rev_label)s</a></li>' % \
{'siteurl': CFG_SITE_URL, 'ln': ln, 'hot_rev_label': _("View most reviewed records")}
out += '<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/latest?ln=%(ln)s&comments=0">%(latest_rev_label)s</a></li>' % \
{'siteurl': CFG_SITE_URL, 'ln': ln, 'latest_rev_label': _("View latest reviewed records")}
out += '<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/comments?ln=%(ln)s&reviews=1">%(reported_rev_label)s</a></li>' % \
{'siteurl': CFG_SITE_URL, 'ln': ln, 'reported_rev_label': _("View all reviews reported as abuse")}
#<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/delete?ln=%(ln)s&comid=-1">%(delete_label)s</a></li>
out +="""
<h3>General</h3>
<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/users?ln=%(ln)s">%(view_users)s</a></li>
<li><a href="%(siteurl)s/help/admin/webcomment-admin-guide">%(guide)s</a></li>
""" % {'siteurl' : CFG_SITE_URL,
#'delete_label': _("Delete/Undelete comment(s) or suppress abuse report(s)"),
'view_users': _("View all users who have been reported"),
'ln' : ln,
'guide' : _("Guide")}
else:
out += _("Comments and reviews are disabled") + '<br />'
out += '</ol>'
from invenio.bibrankadminlib import addadminbox
return addadminbox('<b>%s</b>'% _("Menu"), [out])
def tmpl_admin_delete_form(self, ln, warnings):
"""
Display admin interface to fetch list of records to delete
@param warnings: list of warning_tuples where warning_tuple is (warning_message, text_color)
see tmpl_warnings, color is optional
"""
# load the right message language
_ = gettext_set_language(ln)
warnings = self.tmpl_warnings(warnings, ln)
out = '''
<br />
%s<br />
<br />'''% _("Please enter the ID of the comment/review so that you can view it before deciding whether to delete it or not")
form = '''
<table>
<tr>
<td>%s</td>
<td><input type=text name="comid" size="10" maxlength="10" value="" /></td>
</tr>
<tr>
<td><br /></td>
<tr>
</table>
<br />
%s <br/>
<br />
<table>
<tr>
<td>%s</td>
<td><input type=text name="recid" size="10" maxlength="10" value="" /></td>
</tr>
<tr>
<td><br /></td>
<tr>
</table>
<br />
''' % (_("Comment ID:"),
_("Or enter a record ID to list all the associated comments/reviews:"),
_("Record ID:"))
form_link = "%s/admin/webcomment/webcommentadmin.py/delete?ln=%s" % (CFG_SITE_URL, ln)
form = self.createhiddenform(action=form_link, method="get", text=form, button=_('View Comment'))
return warnings + out + form
def tmpl_admin_users(self, ln, users_data):
"""
@param users_data: tuple of ct, i.e. (ct, ct, ...)
where ct is a tuple (total_number_reported, total_comments_reported, total_reviews_reported, total_nb_votes_yes_of_reported,
total_nb_votes_total_of_reported, user_id, user_email, user_nickname)
sorted by order of ct having highest total_number_reported
"""
_ = gettext_set_language(ln)
u_reports = 0
u_comment_reports = 1
u_reviews_reports = 2
u_nb_votes_yes = 3
u_nb_votes_total = 4
u_uid = 5
u_email = 6
u_nickname = 7
if not users_data:
return self.tmpl_warnings([(_("There have been no reports so far."), 'green')])
user_rows = ""
for utuple in users_data:
com_label = _("View all %s reported comments") % utuple[u_comment_reports]
com_link = '''<a href="%s/admin/webcomment/webcommentadmin.py/comments?ln=%s&uid=%s&reviews=0">%s</a><br />''' % \
(CFG_SITE_URL, ln, utuple[u_uid], com_label)
rev_label = _("View all %s reported reviews") % utuple[u_reviews_reports]
rev_link = '''<a href="%s/admin/webcomment/webcommentadmin.py/comments?ln=%s&uid=%s&reviews=1">%s</a>''' % \
(CFG_SITE_URL, ln, utuple[u_uid], rev_label)
if not utuple[u_nickname]:
user_info = get_user_info(utuple[u_uid])
nickname = user_info[2]
else:
nickname = utuple[u_nickname]
if CFG_WEBCOMMENT_ALLOW_REVIEWS:
review_row = """
<td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td>
<td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td>
<td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td>"""
review_row %= (utuple[u_nb_votes_yes],
utuple[u_nb_votes_total] - utuple[u_nb_votes_yes],
utuple[u_nb_votes_total])
else:
review_row = ''
user_rows += """
<tr>
<td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%(nickname)s</td>
<td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%(email)s</td>
<td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%(uid)s</td>%(review_row)s
<td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray; font-weight: bold;">%(reports)s</td>
<td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%(com_link)s%(rev_link)s</td>
</tr>""" % { 'nickname' : nickname,
'email' : utuple[u_email],
'uid' : utuple[u_uid],
'reports' : utuple[u_reports],
'review_row': review_row,
'siteurl' : CFG_SITE_URL,
'ln' : ln,
'com_link' : CFG_WEBCOMMENT_ALLOW_COMMENTS and com_link or "",
'rev_link' : CFG_WEBCOMMENT_ALLOW_REVIEWS and rev_link or ""
}
out = "<br />"
out += _("Here is a list, sorted by total number of reports, of all users who have had a comment reported at least once.")
out += """
<br />
<br />
<table class="admin_wvar" style="width: 100%%;">
<thead>
<tr class="adminheaderleft">
<th>"""
out += _("Nickname") + '</th>\n'
out += '<th>' + _("Email") + '</th>\n'
out += '<th>' + _("User ID") + '</th>\n'
if CFG_WEBCOMMENT_ALLOW_REVIEWS > 0:
out += '<th>' + _("Number positive votes") + '</th>\n'
out += '<th>' + _("Number negative votes") + '</th>\n'
out += '<th>' + _("Total number votes") + '</th>\n'
out += '<th>' + _("Total number of reports") + '</th>\n'
out += '<th>' + _("View all user's reported comments/reviews") + '</th>\n'
out += """
</tr>
</thead>
<tbody>%s
</tbody>
</table>
""" % user_rows
return out
def tmpl_admin_select_comment_checkbox(self, cmt_id):
""" outputs a checkbox named "comidXX" where XX is cmt_id """
return '<input type="checkbox" name="comid%i" />' % int(cmt_id)
def tmpl_admin_user_info(self, ln, nickname, uid, email):
""" prepares informations about a user"""
_ = gettext_set_language(ln)
out = """
%(nickname_label)s: %(messaging)s<br />
%(uid_label)s: %(uid)i<br />
%(email_label)s: <a href="mailto:%(email)s">%(email)s</a>"""
out %= {'nickname_label': _("Nickname"),
'messaging': self.create_messaging_link(uid, nickname, ln),
'uid_label': _("User ID"),
'uid': int(uid),
'email_label': _("Email"),
'email': email}
return out
def tmpl_admin_review_info(self, ln, reviews, nb_reports, cmt_id, rec_id, status):
""" outputs information about a review """
_ = gettext_set_language(ln)
if reviews:
reported_label = _("This review has been reported %i times")
else:
reported_label = _("This comment has been reported %i times")
reported_label %= int(nb_reports)
out = """
%(reported_label)s<br />
<a href="%(siteurl)s/record/%(rec_id)i?ln=%(ln)s">%(rec_id_label)s</a><br />
%(cmt_id_label)s"""
out %= {'reported_label': reported_label,
'rec_id_label': _("Record") + ' #' + str(rec_id),
'siteurl': CFG_SITE_URL,
'rec_id': int(rec_id),
'cmt_id_label': _("Comment") + ' #' + str(cmt_id),
'ln': ln}
if status in ['dm', 'da']:
out += '<br /><div style="color:red;">Marked as deleted</div>'
return out
def tmpl_admin_latest(self, ln, comment_data, comments, error, user_collections, collection):
"""
@param comment_data: same type of tuple as that
which is return by webcommentadminlib.py/query_get_latest i.e.
tuple (nickname, uid, date_creation, body, id) if latest comments or
tuple (nickname, uid, date_creation, body, star_score, id) if latest reviews
"""
_ = gettext_set_language(ln)
out = """
<script type='text/javascript'>
function collectionChange()
{
document.collection_form.submit();
}
</script>
"""
out += '<form method="get" name="collection_form" action="%s/admin/webcomment/webcommentadmin.py/latest?ln=%s&comments=%s">' % (CFG_SITE_URL, ln, comments)
out += '<input type="hidden" name="ln" value=%s>' % ln
out += '<input type="hidden" name="comments" value=%s>' % comments
out += '<div> Filter by collection: <select name="collection" onchange="javascript:collectionChange();">'
for collection_name in user_collections:
if collection_name == collection:
out += '<option "SELECTED" value="%(collection_name)s">%(collection_name)s</option>' % {'collection_name': cgi.escape(collection_name)}
else:
out += '<option value="%(collection_name)s">%(collection_name)s</option>' % {'collection_name': cgi.escape(collection_name)}
out += '</select></div></form><br />'
if error == 1:
out += "<i>User is not authorized to view such collection.</i><br />"
return out
elif error == 2:
out += "<i>There are no %s for this collection.</i><br />" % (comments and 'comments' or 'reviews')
return out
out += """
<ol>
"""
for (cmt_tuple, meta_data) in comment_data:
bibrec_id = meta_data[3]
content = format_record(bibrec_id, "hs")
if not comments:
out += """
<li> %(content)s <br/> <span class="moreinfo"> <a class="moreinfo" href=%(comment_url)s> reviewed by %(user)s</a>
(%(stars)s) \"%(body)s\" on <i> %(date)s </i></li> </span> <br/>
""" % {'content': content,
'comment_url': CFG_SITE_URL + '/record/' + str(bibrec_id) + '/reviews',
'user':cmt_tuple[0] ,
'stars': '*' * int(cmt_tuple[4]) ,
'body': cmt_tuple[3][:20] + '...',
'date': cmt_tuple[2]}
else:
out += """
<li> %(content)s <br/> <span class="moreinfo"> <a class="moreinfo" href=%(comment_url)s> commented by %(user)s</a>,
\"%(body)s\" on <i> %(date)s </i></li> </span> <br/>
""" % {'content': content,
'comment_url': CFG_SITE_URL + '/record/' + str(bibrec_id) + '/comments',
'user':cmt_tuple[0] ,
'body': cmt_tuple[3][:20] + '...',
'date': cmt_tuple[2]}
out += """</ol>"""
return out
def tmpl_admin_hot(self, ln, comment_data, comments, error, user_collections, collection):
"""
@param comment_data: same type of tuple as that
which is return by webcommentadminlib.py/query_get_hot i.e.
tuple (id_bibrec, date_last_comment, users, count)
"""
_ = gettext_set_language(ln)
out = """
<script type='text/javascript'>
function collectionChange()
{
document.collection_form.submit();
}
</script>
"""
out += '<form method="get" name="collection_form" action="%s/admin/webcomment/webcommentadmin.py/hot?ln=%s&comments=%s">' % (CFG_SITE_URL, ln, comments)
out += '<input type="hidden" name="ln" value=%s>' % ln
out += '<input type="hidden" name="comments" value=%s>' % comments
out += '<div> Filter by collection: <select name="collection" onchange="javascript:collectionChange();">'
for collection_name in user_collections:
if collection_name == collection:
out += '<option "SELECTED" value="%(collection_name)s">%(collection_name)s</option>' % {'collection_name': cgi.escape(collection_name)}
else:
out += '<option value="%(collection_name)s">%(collection_name)s</option>' % {'collection_name': cgi.escape(collection_name)}
out += '</select></div></form><br />'
if error == 1:
out += "<i>User is not authorized to view such collection.</i><br />"
return out
elif error == 2:
out += "<i>There are no %s for this collection.</i><br />" % (comments and 'comments' or 'reviews')
return out
for cmt_tuple in comment_data:
bibrec_id = cmt_tuple[0]
content = format_record(bibrec_id, "hs")
last_comment_date = cmt_tuple[1]
total_users = cmt_tuple[2]
total_comments = cmt_tuple[3]
if comments:
comment_url = CFG_SITE_URL + '/record/' + str(bibrec_id) + '/comments'
str_comment = int(total_comments) > 1 and 'comments' or 'comment'
else:
comment_url = CFG_SITE_URL + '/record/' + str(bibrec_id) + '/reviews'
str_comment = int(total_comments) > 1 and 'reviews' or 'review'
out += """
<li> %(content)s <br/> <span class="moreinfo"> <a class="moreinfo" href=%(comment_url)s> %(total_comments)s
%(str_comment)s</a>
(%(total_users)s %(user)s), latest on <i> %(last_comment_date)s </i></li> </span> <br/>
""" % {'content': content,
'comment_url': comment_url ,
'total_comments': total_comments,
'str_comment': str_comment,
'total_users': total_users,
'user': int(total_users) > 1 and 'users' or 'user',
'last_comment_date': last_comment_date}
out += """</ol>"""
return out
def tmpl_admin_comments(self, ln, uid, comID, recID, comment_data, reviews, error, user_collections, collection):
"""
@param comment_data: same type of tuple as that
which is returned by webcomment.py/query_retrieve_comments_or_remarks i.e.
tuple of comment where comment is
tuple (nickname,
date_creation,
body,
id) if ranking disabled or
tuple (nickname,
date_creation,
body,
nb_votes_yes,
nb_votes_total,
star_score,
title,
id)
"""
_ = gettext_set_language(ln)
coll_form = """
<script type='text/javascript'>
function collectionChange()
{
document.collection_form.submit();
}
</script>
"""
coll_form += '<form method="get" name="collection_form" action="%s/admin/webcomment/webcommentadmin.py/comments?ln=%s&reviews=%s">' % (CFG_SITE_URL, ln, reviews)
coll_form += '<input type="hidden" name="ln" value=%s>' % ln
coll_form += '<input type="hidden" name="reviews" value=%s>' % reviews
coll_form += '<div> Filter by collection: <select name="collection" onchange="javascript:collectionChange();">'
for collection_name in user_collections:
if collection_name == collection:
coll_form += '<option "SELECTED" value="%(collection_name)s">%(collection_name)s</option>' % {'collection_name': cgi.escape(collection_name)}
else:
coll_form += '<option value="%(collection_name)s">%(collection_name)s</option>' % {'collection_name': cgi.escape(collection_name)}
coll_form += '</select></div></form><br />'
if error == 1:
coll_form += "<i>User is not authorized to view such collection.</i><br />"
return coll_form
elif error == 2:
coll_form += "<i>There are no %s for this collection.</i><br />" % (reviews and 'reviews' or 'comments')
return coll_form
comments = []
comments_info = []
checkboxes = []
users = []
for (cmt_tuple, meta_data) in comment_data:
if reviews:
comments.append(self.tmpl_get_comment_with_ranking(None,#request object
ln,
cmt_tuple[0],#nickname
cmt_tuple[1],#userid
cmt_tuple[2],#date_creation
cmt_tuple[3],#body
cmt_tuple[9],#status
0,
cmt_tuple[5],#nb_votes_total
cmt_tuple[4],#nb_votes_yes
cmt_tuple[6],#star_score
cmt_tuple[7]))#title
else:
comments.append(self.tmpl_get_comment_without_ranking(None,#request object
ln,
cmt_tuple[0],#nickname
cmt_tuple[1],#userid
cmt_tuple[2],#date_creation
cmt_tuple[3],#body
cmt_tuple[5],#status
0,
None, #reply_link
None, #report_link
None, #undelete_link
None)) #delete_links
users.append(self.tmpl_admin_user_info(ln,
meta_data[0], #nickname
meta_data[1], #uid
meta_data[2]))#email
if reviews:
status = cmt_tuple[9]
else:
status = cmt_tuple[5]
comments_info.append(self.tmpl_admin_review_info(ln,
reviews,
meta_data[5], # nb abuse reports
meta_data[3], # cmt_id
meta_data[4], # rec_id
status)) # status
checkboxes.append(self.tmpl_admin_select_comment_checkbox(meta_data[3]))
form_link = "%s/admin/webcomment/webcommentadmin.py/del_com?ln=%s" % (CFG_SITE_URL, ln)
out = """
<table class="admin_wvar" style="width:100%%;">
<thead>
<tr class="adminheaderleft">
<th>%(review_label)s</th>
<th>%(written_by_label)s</th>
<th>%(review_info_label)s</th>
<th>%(select_label)s</th>
</tr>
</thead>
<tbody>""" % {'review_label': reviews and _("Review") or _("Comment"),
'written_by_label': _("Written by"),
'review_info_label': _("General informations"),
'select_label': _("Select")}
for i in range (0, len(comments)):
out += """
<tr>
<td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td>
<td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td>
<td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td>
<td class="admintd" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td>
</tr>""" % (comments[i], users[i], comments_info[i], checkboxes[i])
out += """
</tbody>
</table>"""
if reviews:
action_display = {
'delete': _('Delete selected reviews'),
'unreport': _('Suppress selected abuse report'),
'undelete': _('Undelete selected reviews')
}
else:
action_display = {
'undelete': _('Undelete selected comments'),
'delete': _('Delete selected comments'),
'unreport': _('Suppress selected abuse report')
}
form = self.tmpl_create_multiple_actions_form(form_name="admin_comment",
form_action=form_link,
method="post",
action_display=action_display,
action_field_name='action',
button_label=_("OK"),
button_name="okbutton",
content=out)
if uid > 0:
header = '<br />'
if reviews:
header += _("Here are the reported reviews of user %s") % uid
else:
header += _("Here are the reported comments of user %s") % uid
header += '<br /><br />'
if comID > 0 and recID <= 0 and uid <= 0:
if reviews:
header = '<br />' +_("Here is review %s")% comID + '<br /><br />'
else:
header = '<br />' +_("Here is comment %s")% comID + '<br /><br />'
if uid > 0 and comID > 0 and recID <= 0:
if reviews:
header = '<br />' + _("Here is review %(x_cmtID)s written by user %(x_user)s") % {'x_cmtID': comID, 'x_user': uid}
else:
header = '<br />' + _("Here is comment %(x_cmtID)s written by user %(x_user)s") % {'x_cmtID': comID, 'x_user': uid}
header += '<br/ ><br />'
if comID <= 0 and recID <= 0 and uid <= 0:
header = '<br />'
if reviews:
header += _("Here are all reported reviews sorted by the most reported")
else:
header += _("Here are all reported comments sorted by the most reported")
header += "<br /><br />"
elif recID > 0:
header = '<br />'
if reviews:
header += _("Here are all reviews for record %i, sorted by the most reported" % recID)
header += '<br /><a href="%s/admin/webcomment/webcommentadmin.py/delete?comid=&recid=%s&reviews=0">%s</a>' % (CFG_SITE_URL, recID, _("Show comments"))
else:
header += _("Here are all comments for record %i, sorted by the most reported" % recID)
header += '<br /><a href="%s/admin/webcomment/webcommentadmin.py/delete?comid=&recid=%s&reviews=1">%s</a>' % (CFG_SITE_URL, recID, _("Show reviews"))
header += "<br /><br />"
return coll_form + header + form
def tmpl_admin_del_com(self, del_res, ln=CFG_SITE_LANG):
"""
@param del_res: list of the following tuple (comment_id, was_successfully_deleted),
was_successfully_deleted is boolean (0=false, >0=true
"""
_ = gettext_set_language(ln)
table_rows = ''
for deltuple in del_res:
table_rows += """
<tr>
<td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td>
<td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td>
</tr>""" % (deltuple[0], deltuple[1]>0 and _("Yes") or "<span class=\"important\">" +_("No") + "</span>")
out = """
<table class="admin_wvar">
<tr class="adminheaderleft">
<td style="padding-right:10px;">%s</td>
<td>%s</td>
</tr>%s
<table>""" % (_("comment ID"), _("successfully deleted"), table_rows)
return out
def tmpl_admin_undel_com(self, del_res, ln=CFG_SITE_LANG):
"""
@param del_res: list of the following tuple (comment_id, was_successfully_undeleted),
was_successfully_undeleted is boolean (0=false, >0=true
"""
_ = gettext_set_language(ln)
table_rows = ''
for deltuple in del_res:
table_rows += """
<tr>
<td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td>
<td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td>
</tr>""" % (deltuple[0], deltuple[1]>0 and _("Yes") or "<span class=\"important\">" +_("No") + "</span>")
out = """
<table class="admin_wvar">
<tr class="adminheaderleft">
<td style="padding-right:10px;">%s</td>
<td>%s</td>
</tr>%s
<table>""" % (_("comment ID"), _("successfully undeleted"), table_rows)
return out
def tmpl_admin_suppress_abuse_report(self, del_res, ln=CFG_SITE_LANG):
"""
@param del_res: list of the following tuple (comment_id, was_successfully_deleted),
was_successfully_deleted is boolean (0=false, >0=true
"""
_ = gettext_set_language(ln)
table_rows = ''
for deltuple in del_res:
table_rows += """
<tr>
<td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td>
<td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td>
</tr>""" % (deltuple[0], deltuple[1]>0 and _("Yes") or "<span class=\"important\">" +_("No") + "</span>")
out = """
<table class="admin_wvar">
<tr class="adminheaderleft">
<td style ="padding-right: 10px;">%s</td>
<td>%s</td>
</tr>%s
<table>""" % (_("comment ID"), _("successfully suppressed abuse report"), table_rows)
return out
def tmpl_mini_review(self, recID, ln=CFG_SITE_LANG, action='SUBMIT',
avg_score=0, nb_comments_total=0):
"""Display the mini version of reviews (only the grading part)"""
_ = gettext_set_language(ln)
url = '%s/record/%s/reviews/add?ln=%s&action=%s' % (CFG_SITE_URL, recID, ln, action)
if avg_score > 0:
score = _("Average review score: %(x_nb_score)s based on %(x_nb_reviews)s reviews") % \
{'x_nb_score': '<b>%.1f</b>' % avg_score,
'x_nb_reviews': nb_comments_total}
else:
score = '(' +_("Not yet reviewed") + ')'
if avg_score == 5:
s1, s2, s3, s4, s5 = 'full', 'full', 'full', 'full', 'full'
elif avg_score >= 4.5:
s1, s2, s3, s4, s5 = 'full', 'full', 'full', 'full', 'half'
elif avg_score >= 4:
s1, s2, s3, s4, s5 = 'full', 'full', 'full', 'full', ''
elif avg_score >= 3.5:
s1, s2, s3, s4, s5 = 'full', 'full', 'full', 'half', ''
elif avg_score >= 3:
s1, s2, s3, s4, s5 = 'full', 'full', 'full', '', ''
elif avg_score >= 2.5:
s1, s2, s3, s4, s5 = 'full', 'full', 'half', '', ''
elif avg_score >= 2:
s1, s2, s3, s4, s5 = 'full', 'full', '', '', ''
elif avg_score >= 1.5:
s1, s2, s3, s4, s5 = 'full', 'half', '', '', ''
elif avg_score == 1:
s1, s2, s3, s4, s5 = 'full', '', '', '', ''
else:
s1, s2, s3, s4, s5 = '', '', '', '', ''
out = '''
<small class="detailedRecordActions">%(rate)s:</small><br /><br />
<div style="margin:auto;width:160px;">
<span style="display:none;">Rate this document:</span>
<div class="star %(s1)s" ><a href="%(url)s&score=1">1</a>
<div class="star %(s2)s" ><a href="%(url)s&score=2">2</a>
<div class="star %(s3)s" ><a href="%(url)s&score=3">3</a>
<div class="star %(s4)s" ><a href="%(url)s&score=4">4</a>
<div class="star %(s5)s" ><a href="%(url)s&score=5">5</a></div></div></div></div></div>
<div style="clear:both"> </div>
</div>
<small>%(score)s</small>
''' % {'url': url,
'score': score,
'rate': _("Rate this document"),
's1': s1,
's2': s2,
's3': s3,
's4': s4,
's5': s5
}
return out
def tmpl_email_new_comment_header(self, recID, title, reviews,
comID, report_numbers,
can_unsubscribe=True,
ln=CFG_SITE_LANG, uid=-1):
"""
Prints the email header used to notify subscribers that a new
comment/review was added.
@param recid: the ID of the commented/reviewed record
@param title: the title of the commented/reviewed record
@param reviews: True if it is a review, else if a comment
@param comID: the comment ID
@param report_numbers: the report number(s) of the record
@param can_unsubscribe: True if user can unsubscribe from alert
@param ln: language
"""
# load the right message language
_ = gettext_set_language(ln)
user_info = collect_user_info(uid)
out = _("Hello:") + '\n\n' + \
(reviews and _("The following review was sent to %(CFG_SITE_NAME)s by %(user_nickname)s:") or \
_("The following comment was sent to %(CFG_SITE_NAME)s by %(user_nickname)s:")) % \
{'CFG_SITE_NAME': CFG_SITE_NAME,
'user_nickname': user_info['nickname']}
out += '\n(<%s>)' % (CFG_SITE_URL + '/record/' + str(recID))
out += '\n\n\n'
return out
def tmpl_email_new_comment_footer(self, recID, title, reviews,
comID, report_numbers,
can_unsubscribe=True,
ln=CFG_SITE_LANG):
"""
Prints the email footer used to notify subscribers that a new
comment/review was added.
@param recid: the ID of the commented/reviewed record
@param title: the title of the commented/reviewed record
@param reviews: True if it is a review, else if a comment
@param comID: the comment ID
@param report_numbers: the report number(s) of the record
@param can_unsubscribe: True if user can unsubscribe from alert
@param ln: language
"""
# load the right message language
_ = gettext_set_language(ln)
out = '\n\n-- \n'
out += _("This is an automatic message, please don't reply to it.")
out += '\n'
out += _("To post another comment, go to <%(x_url)s> instead.") % \
{'x_url': CFG_SITE_URL + '/record/' + str(recID) + \
(reviews and '/reviews' or '/comments') + '/add'}
out += '\n'
if not reviews:
out += _("To specifically reply to this comment, go to <%(x_url)s>") % \
{'x_url': CFG_SITE_URL + '/record/' + str(recID) + \
'/comments/add?action=REPLY&comid=' + str(comID)}
out += '\n'
if can_unsubscribe:
out += _("To unsubscribe from this discussion, go to <%(x_url)s>") % \
{'x_url': CFG_SITE_URL + '/record/' + str(recID) + \
'/comments/unsubscribe'}
out += '\n'
out += _("For any question, please use <%(CFG_SITE_SUPPORT_EMAIL)s>") % \
{'CFG_SITE_SUPPORT_EMAIL': CFG_SITE_SUPPORT_EMAIL}
return out
def tmpl_email_new_comment_admin(self, recID):
"""
Prints the record information used in the email to notify the
system administrator that a new comment has been posted.
@param recID: the ID of the commented/reviewed record
"""
out = ""
title = get_fieldvalues(recID, "245__a")
authors = ', '.join(get_fieldvalues(recID, "100__a") + get_fieldvalues(recID, "700__a"))
#res_author = ""
#res_rep_num = ""
#for author in authors:
# res_author = res_author + ' ' + author
dates = get_fieldvalues(recID, "260__c")
report_nums = get_fieldvalues(recID, "037__a")
report_nums += get_fieldvalues(recID, "088__a")
report_nums = ', '.join(report_nums)
#for rep_num in report_nums:
# res_rep_num = res_rep_num + ', ' + rep_num
out += " Title = %s \n" % (title and title[0] or "No Title")
out += " Authors = %s \n" % authors
if dates:
out += " Date = %s \n" % dates[0]
out += " Report number = %s" % report_nums
return out
|
import os, subprocess
amsDecode = "/usr/local/bin/amsDecode"
path = "/usr/local/bin"
specDataFile = "specData.csv"
f = open("processFile.log", "w")
if os.path.exists(specDataFile):
os.remove(specDataFile)
for fileName in os.listdir('.'):
if fileName.endswith('.bin'):
#print 'file :' + fileName
cmnd = [amsDecode,
fileName,
"-t -95",
"-b",
"68",
"468" ]
subprocess.call(cmnd,stdout=f)
f.close
|
from distutils.core import setup
setup(name='PySh',
version='0.0.1',
py_modules=['pysh'],
description="A tiny interface to intuitively access shell commands.",
author="Bede Kelly",
author_email="bedekelly97@gmail.com",
url="https://github.com/bedekelly/pysh",
provides=['pysh'])
|
__author__ = 'Frederic Bayer'
|
from socket import *
import sys
clientSocket = socket(AF_INET, SOCK_STREAM) #creates socket
server_address = ('127.0.0.1', 80)#create connection at this given port
print >>sys.stderr, 'CONNECTING TO %s AT PORT %s' % server_address
clientSocket.connect(server_address)#connect to server at given address
filename=raw_input("ENTER THE FILENAME: ")
f = open(filename[0:])
outputdata = f.read()#read the input file into variable
print "HTML CODE OF THE GIVEN FILE:", outputdata #display the html code of the file
clientSocket.close() #close the connection
|
import contextvars
import gettext
import os
from telebot.asyncio_handler_backends import BaseMiddleware
try:
from babel.support import LazyProxy
babel_imported = True
except ImportError:
babel_imported = False
class I18N(BaseMiddleware):
"""
This middleware provides high-level tool for internationalization
It is based on gettext util.
"""
context_lang = contextvars.ContextVar('language', default=None)
def __init__(self, translations_path, domain_name: str):
super().__init__()
self.update_types = self.process_update_types()
self.path = translations_path
self.domain = domain_name
self.translations = self.find_translations()
@property
def available_translations(self):
return list(self.translations)
def gettext(self, text: str, lang: str = None):
"""
Singular translations
"""
if lang is None:
lang = self.context_lang.get()
if lang not in self.translations:
return text
translator = self.translations[lang]
return translator.gettext(text)
def ngettext(self, singular: str, plural: str, lang: str = None, n=1):
"""
Plural translations
"""
if lang is None:
lang = self.context_lang.get()
if lang not in self.translations:
if n == 1:
return singular
return plural
translator = self.translations[lang]
return translator.ngettext(singular, plural, n)
def lazy_gettext(self, text: str, lang: str = None):
if not babel_imported:
raise RuntimeError('babel module is not imported. Check that you installed it.')
return LazyProxy(self.gettext, text, lang, enable_cache=False)
def lazy_ngettext(self, singular: str, plural: str, lang: str = None, n=1):
if not babel_imported:
raise RuntimeError('babel module is not imported. Check that you installed it.')
return LazyProxy(self.ngettext, singular, plural, lang, n, enable_cache=False)
async def get_user_language(self, obj):
"""
You need to override this method and return user language
"""
raise NotImplementedError
def process_update_types(self) -> list:
"""
You need to override this method and return any update types which you want to be processed
"""
raise NotImplementedError
async def pre_process(self, message, data):
"""
context language variable will be set each time when update from 'process_update_types' comes
value is the result of 'get_user_language' method
"""
self.context_lang.set(await self.get_user_language(obj=message))
async def post_process(self, message, data, exception):
pass
def find_translations(self):
"""
Looks for translations with passed 'domain' in passed 'path'
"""
if not os.path.exists(self.path):
raise RuntimeError(f"Translations directory by path: {self.path!r} was not found")
result = {}
for name in os.listdir(self.path):
translations_path = os.path.join(self.path, name, 'LC_MESSAGES')
if not os.path.isdir(translations_path):
continue
po_file = os.path.join(translations_path, self.domain + '.po')
mo_file = po_file[:-2] + 'mo'
if os.path.isfile(po_file) and not os.path.isfile(mo_file):
raise FileNotFoundError(f"Translations for: {name!r} were not compiled!")
with open(mo_file, 'rb') as file:
result[name] = gettext.GNUTranslations(file)
return result
|
import bpy
from bpy.types import Header, Menu, Panel
from bpy.app.translations import pgettext_iface as iface_
from bpy.app.translations import contexts as i18n_contexts
def opengl_lamp_buttons(column, lamp):
split = column.row()
split.prop(lamp, "use", text="", icon='OUTLINER_OB_LAMP' if lamp.use else 'LAMP_DATA')
col = split.column()
col.active = lamp.use
row = col.row()
row.label(text="Diffuse:")
row.prop(lamp, "diffuse_color", text="")
row = col.row()
row.label(text="Specular:")
row.prop(lamp, "specular_color", text="")
col = split.column()
col.active = lamp.use
col.prop(lamp, "direction", text="")
class USERPREF_HT_header(Header):
bl_space_type = 'USER_PREFERENCES'
def draw(self, context):
layout = self.layout
layout.template_header()
userpref = context.user_preferences
layout.operator_context = 'EXEC_AREA'
layout.operator("wm.save_userpref")
layout.operator_context = 'INVOKE_DEFAULT'
if userpref.active_section == 'INPUT':
layout.operator("wm.keyconfig_import")
layout.operator("wm.keyconfig_export")
elif userpref.active_section == 'ADDONS':
layout.operator("wm.addon_install", icon='FILESEL')
layout.operator("wm.addon_refresh", icon='FILE_REFRESH')
layout.menu("USERPREF_MT_addons_online_resources")
elif userpref.active_section == 'THEMES':
layout.operator("ui.reset_default_theme")
layout.operator("wm.theme_install")
class USERPREF_PT_tabs(Panel):
bl_label = ""
bl_space_type = 'USER_PREFERENCES'
bl_region_type = 'WINDOW'
bl_options = {'HIDE_HEADER'}
def draw(self, context):
layout = self.layout
userpref = context.user_preferences
layout.prop(userpref, "active_section", expand=True)
class USERPREF_MT_interaction_presets(Menu):
bl_label = "Presets"
preset_subdir = "interaction"
preset_operator = "script.execute_preset"
draw = Menu.draw_preset
class USERPREF_MT_appconfigs(Menu):
bl_label = "AppPresets"
preset_subdir = "keyconfig"
preset_operator = "wm.appconfig_activate"
def draw(self, context):
self.layout.operator("wm.appconfig_default", text="Blender (default)")
# now draw the presets
Menu.draw_preset(self, context)
class USERPREF_MT_splash(Menu):
bl_label = "Splash"
def draw(self, context):
layout = self.layout
split = layout.split()
row = split.row()
row.label("")
row = split.row()
row.label("Interaction:")
text = bpy.path.display_name(context.window_manager.keyconfigs.active.name)
if not text:
text = "Blender (default)"
row.menu("USERPREF_MT_appconfigs", text=text)
class USERPREF_MT_splash_footer(Menu):
bl_label = ""
def draw(self, context):
pass
class USERPREF_PT_interface(Panel):
bl_space_type = 'USER_PREFERENCES'
bl_label = "Interface"
bl_region_type = 'WINDOW'
bl_options = {'HIDE_HEADER'}
@classmethod
def poll(cls, context):
userpref = context.user_preferences
return (userpref.active_section == 'INTERFACE')
def draw(self, context):
import sys
layout = self.layout
userpref = context.user_preferences
view = userpref.view
row = layout.row()
col = row.column()
col.label(text="Display:")
col.prop(view, "show_tooltips")
col.prop(view, "show_tooltips_python")
col.prop(view, "show_object_info", text="Object Info")
col.prop(view, "show_large_cursors")
col.prop(view, "show_view_name", text="View Name")
col.prop(view, "show_playback_fps", text="Playback FPS")
col.prop(view, "use_global_scene")
col.prop(view, "object_origin_size")
col.separator()
col.separator()
col.separator()
col.prop(view, "show_mini_axis", text="Display Mini Axis")
sub = col.column()
sub.active = view.show_mini_axis
sub.prop(view, "mini_axis_size", text="Size")
sub.prop(view, "mini_axis_brightness", text="Brightness")
col.separator()
if sys.platform[:3] == "win":
col.label("Warnings")
col.prop(view, "use_quit_dialog")
row.separator()
row.separator()
col = row.column()
col.label(text="View Manipulation:")
col.prop(view, "use_mouse_depth_cursor")
col.prop(view, "use_mouse_depth_navigate")
col.prop(view, "use_zoom_to_mouse")
col.prop(view, "use_rotate_around_active")
col.prop(view, "use_global_pivot")
col.prop(view, "use_camera_lock_parent")
col.separator()
col.prop(view, "use_auto_perspective")
col.prop(view, "smooth_view")
col.prop(view, "rotation_angle")
col.separator()
col.separator()
col.label(text="2D Viewports:")
col.prop(view, "view2d_grid_spacing_min", text="Minimum Grid Spacing")
col.prop(view, "timecode_style")
col.prop(view, "view_frame_type")
if (view.view_frame_type == 'SECONDS'):
col.prop(view, "view_frame_seconds")
elif (view.view_frame_type == 'KEYFRAMES'):
col.prop(view, "view_frame_keyframes")
row.separator()
row.separator()
col = row.column()
#Toolbox doesn't exist yet
#col.label(text="Toolbox:")
#col.prop(view, "show_column_layout")
#col.label(text="Open Toolbox Delay:")
#col.prop(view, "open_left_mouse_delay", text="Hold LMB")
#col.prop(view, "open_right_mouse_delay", text="Hold RMB")
col.prop(view, "show_manipulator")
sub = col.column()
sub.active = view.show_manipulator
sub.prop(view, "manipulator_size", text="Size")
sub.prop(view, "manipulator_handle_size", text="Handle Size")
sub.prop(view, "manipulator_hotspot", text="Hotspot")
col.separator()
col.separator()
col.separator()
col.label(text="Menus:")
col.prop(view, "use_mouse_over_open")
sub = col.column()
sub.active = view.use_mouse_over_open
sub.prop(view, "open_toplevel_delay", text="Top Level")
sub.prop(view, "open_sublevel_delay", text="Sub Level")
col.separator()
col.label(text="Pie Menus:")
sub = col.column(align=True)
sub.prop(view, "pie_animation_timeout")
sub.prop(view, "pie_initial_timeout")
sub.prop(view, "pie_menu_radius")
sub.prop(view, "pie_menu_threshold")
sub.prop(view, "pie_menu_confirm")
col.separator()
col.separator()
col.separator()
col.prop(view, "show_splash")
class USERPREF_PT_edit(Panel):
bl_space_type = 'USER_PREFERENCES'
bl_label = "Edit"
bl_region_type = 'WINDOW'
bl_options = {'HIDE_HEADER'}
@classmethod
def poll(cls, context):
userpref = context.user_preferences
return (userpref.active_section == 'EDITING')
def draw(self, context):
layout = self.layout
userpref = context.user_preferences
edit = userpref.edit
row = layout.row()
col = row.column()
col.label(text="Link Materials To:")
col.prop(edit, "material_link", text="")
col.separator()
col.separator()
col.separator()
col.label(text="New Objects:")
col.prop(edit, "use_enter_edit_mode")
col.label(text="Align To:")
col.prop(edit, "object_align", text="")
col.separator()
col.separator()
col.separator()
col.label(text="Undo:")
col.prop(edit, "use_global_undo")
col.prop(edit, "undo_steps", text="Steps")
col.prop(edit, "undo_memory_limit", text="Memory Limit")
row.separator()
row.separator()
col = row.column()
col.label(text="Grease Pencil:")
col.prop(edit, "grease_pencil_eraser_radius", text="Eraser Radius")
col.separator()
col.prop(edit, "grease_pencil_manhattan_distance", text="Manhattan Distance")
col.prop(edit, "grease_pencil_euclidean_distance", text="Euclidean Distance")
col.separator()
col.prop(edit, "grease_pencil_default_color", text="Default Color")
col.separator()
col.prop(edit, "use_grease_pencil_simplify_stroke", text="Simplify Stroke")
col.separator()
col.separator()
col.separator()
col.separator()
col.label(text="Playback:")
col.prop(edit, "use_negative_frames")
col.separator()
col.separator()
col.separator()
col.label(text="Node Editor:")
col.prop(edit, "node_margin")
col.label(text="Animation Editors:")
col.prop(edit, "fcurve_unselected_alpha", text="F-Curve Visibility")
row.separator()
row.separator()
col = row.column()
col.label(text="Keyframing:")
col.prop(edit, "use_visual_keying")
col.prop(edit, "use_keyframe_insert_needed", text="Only Insert Needed")
col.separator()
col.prop(edit, "use_auto_keying", text="Auto Keyframing:")
col.prop(edit, "use_auto_keying_warning")
sub = col.column()
#~ sub.active = edit.use_keyframe_insert_auto # incorrect, time-line can enable
sub.prop(edit, "use_keyframe_insert_available", text="Only Insert Available")
col.separator()
col.label(text="New F-Curve Defaults:")
col.prop(edit, "keyframe_new_interpolation_type", text="Interpolation")
col.prop(edit, "keyframe_new_handle_type", text="Handles")
col.prop(edit, "use_insertkey_xyz_to_rgb", text="XYZ to RGB")
col.separator()
col.separator()
col.separator()
col.label(text="Transform:")
col.prop(edit, "use_drag_immediately")
row.separator()
row.separator()
col = row.column()
col.prop(edit, "sculpt_paint_overlay_color", text="Sculpt Overlay Color")
col.separator()
col.separator()
col.separator()
col.label(text="Duplicate Data:")
col.prop(edit, "use_duplicate_mesh", text="Mesh")
col.prop(edit, "use_duplicate_surface", text="Surface")
col.prop(edit, "use_duplicate_curve", text="Curve")
col.prop(edit, "use_duplicate_text", text="Text")
col.prop(edit, "use_duplicate_metaball", text="Metaball")
col.prop(edit, "use_duplicate_armature", text="Armature")
col.prop(edit, "use_duplicate_lamp", text="Lamp")
col.prop(edit, "use_duplicate_material", text="Material")
col.prop(edit, "use_duplicate_texture", text="Texture")
#col.prop(edit, "use_duplicate_fcurve", text="F-Curve")
col.prop(edit, "use_duplicate_action", text="Action")
col.prop(edit, "use_duplicate_particle", text="Particle")
class USERPREF_PT_system(Panel):
bl_space_type = 'USER_PREFERENCES'
bl_label = "System"
bl_region_type = 'WINDOW'
bl_options = {'HIDE_HEADER'}
@classmethod
def poll(cls, context):
userpref = context.user_preferences
return (userpref.active_section == 'SYSTEM')
def draw(self, context):
import sys
layout = self.layout
userpref = context.user_preferences
system = userpref.system
split = layout.split()
# 1. Column
column = split.column()
colsplit = column.split(percentage=0.85)
col = colsplit.column()
col.label(text="General:")
col.prop(system, "dpi")
col.label("Virtual Pixel Mode:")
col.prop(system, "virtual_pixel_mode", text="")
col.separator()
col.prop(system, "frame_server_port")
col.prop(system, "scrollback", text="Console Scrollback")
col.separator()
col.label(text="Sound:")
col.row().prop(system, "audio_device", expand=False)
sub = col.column()
sub.active = system.audio_device != 'NONE' and system.audio_device != 'Null'
#sub.prop(system, "use_preview_images")
sub.prop(system, "audio_channels", text="Channels")
sub.prop(system, "audio_mixing_buffer", text="Mixing Buffer")
sub.prop(system, "audio_sample_rate", text="Sample Rate")
sub.prop(system, "audio_sample_format", text="Sample Format")
col.separator()
col.label(text="Screencast:")
col.prop(system, "screencast_fps")
col.prop(system, "screencast_wait_time")
col.separator()
if userpref.addons.find('cycles') != -1:
userpref.addons['cycles'].preferences.draw_impl(col, context)
if hasattr(system, "opensubdiv_compute_type"):
col.label(text="OpenSubdiv compute:")
col.row().prop(system, "opensubdiv_compute_type", text="")
# 2. Column
column = split.column()
colsplit = column.split(percentage=0.85)
col = colsplit.column()
col.label(text="OpenGL:")
col.prop(system, "gl_clip_alpha", slider=True)
col.prop(system, "use_mipmaps")
col.prop(system, "use_gpu_mipmap")
col.prop(system, "use_16bit_textures")
col.separator()
col.label(text="Selection")
col.prop(system, "select_method", text="")
col.separator()
col.label(text="Anisotropic Filtering")
col.prop(system, "anisotropic_filter", text="")
col.separator()
col.label(text="Window Draw Method:")
col.prop(system, "window_draw_method", text="")
col.prop(system, "multi_sample", text="")
if sys.platform == "linux" and system.multi_sample != 'NONE':
col.label(text="Might fail for Mesh editing selection!")
col.separator()
col.prop(system, "use_region_overlap")
col.separator()
col.label(text="Text Draw Options:")
col.prop(system, "use_text_antialiasing")
col.separator()
col.label(text="Textures:")
col.prop(system, "gl_texture_limit", text="Limit Size")
col.prop(system, "texture_time_out", text="Time Out")
col.prop(system, "texture_collection_rate", text="Collection Rate")
col.separator()
col.label(text="Images Draw Method:")
col.prop(system, "image_draw_method", text="")
col.separator()
col.label(text="Sequencer/Clip Editor:")
# currently disabled in the code
# col.prop(system, "prefetch_frames")
col.prop(system, "memory_cache_limit")
# 3. Column
column = split.column()
column.label(text="Solid OpenGL lights:")
split = column.split(percentage=0.1)
split.label()
split.label(text="Colors:")
split.label(text="Direction:")
lamp = system.solid_lights[0]
opengl_lamp_buttons(column, lamp)
lamp = system.solid_lights[1]
opengl_lamp_buttons(column, lamp)
lamp = system.solid_lights[2]
opengl_lamp_buttons(column, lamp)
column.separator()
column.label(text="Color Picker Type:")
column.row().prop(system, "color_picker_type", text="")
column.separator()
column.prop(system, "use_weight_color_range", text="Custom Weight Paint Range")
sub = column.column()
sub.active = system.use_weight_color_range
sub.template_color_ramp(system, "weight_color_range", expand=True)
column.separator()
column.prop(system, "font_path_ui")
column.prop(system, "font_path_ui_mono")
if bpy.app.build_options.international:
column.prop(system, "use_international_fonts")
if system.use_international_fonts:
column.prop(system, "language")
row = column.row()
row.label(text="Translate:", text_ctxt=i18n_contexts.id_windowmanager)
row = column.row(align=True)
row.prop(system, "use_translate_interface", text="Interface", toggle=True)
row.prop(system, "use_translate_tooltips", text="Tooltips", toggle=True)
row.prop(system, "use_translate_new_dataname", text="New Data", toggle=True)
class USERPREF_MT_interface_theme_presets(Menu):
bl_label = "Presets"
preset_subdir = "interface_theme"
preset_operator = "script.execute_preset"
preset_type = 'XML'
preset_xml_map = (
("user_preferences.themes[0]", "Theme"),
("user_preferences.ui_styles[0]", "ThemeStyle"),
)
draw = Menu.draw_preset
class USERPREF_PT_theme(Panel):
bl_space_type = 'USER_PREFERENCES'
bl_label = "Themes"
bl_region_type = 'WINDOW'
bl_options = {'HIDE_HEADER'}
# not essential, hard-coded UI delimiters for the theme layout
ui_delimiters = {
'VIEW_3D': {
"text_grease_pencil",
"text_keyframe",
"speaker",
"freestyle_face_mark",
"split_normal",
"bone_solid",
"paint_curve_pivot",
},
'GRAPH_EDITOR': {
"handle_vertex_select",
},
'IMAGE_EDITOR': {
"paint_curve_pivot",
},
'NODE_EDITOR': {
"layout_node",
},
'CLIP_EDITOR': {
"handle_vertex_select",
}
}
@staticmethod
def _theme_generic(split, themedata, theme_area):
col = split.column()
def theme_generic_recurse(data):
col.label(data.rna_type.name)
row = col.row()
subsplit = row.split(percentage=0.95)
padding1 = subsplit.split(percentage=0.15)
padding1.column()
subsplit = row.split(percentage=0.85)
padding2 = subsplit.split(percentage=0.15)
padding2.column()
colsub_pair = padding1.column(), padding2.column()
props_type = {}
for i, prop in enumerate(data.rna_type.properties):
if prop.identifier == "rna_type":
continue
props_type.setdefault((prop.type, prop.subtype), []).append(prop)
th_delimiters = USERPREF_PT_theme.ui_delimiters.get(theme_area)
for props_type, props_ls in sorted(props_type.items()):
if props_type[0] == 'POINTER':
for i, prop in enumerate(props_ls):
theme_generic_recurse(getattr(data, prop.identifier))
else:
if th_delimiters is None:
# simple, no delimiters
for i, prop in enumerate(props_ls):
colsub_pair[i % 2].row().prop(data, prop.identifier)
else:
# add hard coded delimiters
i = 0
for prop in props_ls:
colsub = colsub_pair[i]
colsub.row().prop(data, prop.identifier)
i = (i + 1) % 2
if prop.identifier in th_delimiters:
if i:
colsub = colsub_pair[1]
colsub.row().label("")
colsub_pair[0].row().label("")
colsub_pair[1].row().label("")
i = 0
theme_generic_recurse(themedata)
@staticmethod
def _theme_widget_style(layout, widget_style):
row = layout.row()
subsplit = row.split(percentage=0.95)
padding = subsplit.split(percentage=0.15)
colsub = padding.column()
colsub = padding.column()
colsub.row().prop(widget_style, "outline")
colsub.row().prop(widget_style, "item", slider=True)
colsub.row().prop(widget_style, "inner", slider=True)
colsub.row().prop(widget_style, "inner_sel", slider=True)
subsplit = row.split(percentage=0.85)
padding = subsplit.split(percentage=0.15)
colsub = padding.column()
colsub = padding.column()
colsub.row().prop(widget_style, "text")
colsub.row().prop(widget_style, "text_sel")
colsub.prop(widget_style, "show_shaded")
subsub = colsub.column(align=True)
subsub.active = widget_style.show_shaded
subsub.prop(widget_style, "shadetop")
subsub.prop(widget_style, "shadedown")
layout.separator()
@staticmethod
def _ui_font_style(layout, font_style):
split = layout.split()
col = split.column()
col.label(text="Kerning Style:")
col.row().prop(font_style, "font_kerning_style", expand=True)
col.prop(font_style, "points")
col = split.column()
col.label(text="Shadow Offset:")
col.prop(font_style, "shadow_offset_x", text="X")
col.prop(font_style, "shadow_offset_y", text="Y")
col = split.column()
col.prop(font_style, "shadow")
col.prop(font_style, "shadow_alpha")
col.prop(font_style, "shadow_value")
layout.separator()
@classmethod
def poll(cls, context):
userpref = context.user_preferences
return (userpref.active_section == 'THEMES')
def draw(self, context):
layout = self.layout
theme = context.user_preferences.themes[0]
split_themes = layout.split(percentage=0.2)
sub = split_themes.column()
sub.label(text="Presets:")
subrow = sub.row(align=True)
subrow.menu("USERPREF_MT_interface_theme_presets", text=USERPREF_MT_interface_theme_presets.bl_label)
subrow.operator("wm.interface_theme_preset_add", text="", icon='ZOOMIN')
subrow.operator("wm.interface_theme_preset_add", text="", icon='ZOOMOUT').remove_active = True
sub.separator()
sub.prop(theme, "theme_area", expand=True)
split = layout.split(percentage=0.4)
layout.separator()
layout.separator()
split = split_themes.split()
if theme.theme_area == 'USER_INTERFACE':
col = split.column()
ui = theme.user_interface
col.label(text="Regular:")
self._theme_widget_style(col, ui.wcol_regular)
col.label(text="Tool:")
self._theme_widget_style(col, ui.wcol_tool)
col.label(text="Radio Buttons:")
self._theme_widget_style(col, ui.wcol_radio)
col.label(text="Text:")
self._theme_widget_style(col, ui.wcol_text)
col.label(text="Option:")
self._theme_widget_style(col, ui.wcol_option)
col.label(text="Toggle:")
self._theme_widget_style(col, ui.wcol_toggle)
col.label(text="Number Field:")
self._theme_widget_style(col, ui.wcol_num)
col.label(text="Value Slider:")
self._theme_widget_style(col, ui.wcol_numslider)
col.label(text="Box:")
self._theme_widget_style(col, ui.wcol_box)
col.label(text="Menu:")
self._theme_widget_style(col, ui.wcol_menu)
col.label(text="Pie Menu:")
self._theme_widget_style(col, ui.wcol_pie_menu)
col.label(text="Pulldown:")
self._theme_widget_style(col, ui.wcol_pulldown)
col.label(text="Menu Back:")
self._theme_widget_style(col, ui.wcol_menu_back)
col.label(text="Tooltip:")
self._theme_widget_style(col, ui.wcol_tooltip)
col.label(text="Menu Item:")
self._theme_widget_style(col, ui.wcol_menu_item)
col.label(text="Scroll Bar:")
self._theme_widget_style(col, ui.wcol_scroll)
col.label(text="Progress Bar:")
self._theme_widget_style(col, ui.wcol_progress)
col.label(text="List Item:")
self._theme_widget_style(col, ui.wcol_list_item)
ui_state = theme.user_interface.wcol_state
col.label(text="State:")
row = col.row()
subsplit = row.split(percentage=0.95)
padding = subsplit.split(percentage=0.15)
colsub = padding.column()
colsub = padding.column()
colsub.row().prop(ui_state, "inner_anim")
colsub.row().prop(ui_state, "inner_anim_sel")
colsub.row().prop(ui_state, "inner_driven")
colsub.row().prop(ui_state, "inner_driven_sel")
subsplit = row.split(percentage=0.85)
padding = subsplit.split(percentage=0.15)
colsub = padding.column()
colsub = padding.column()
colsub.row().prop(ui_state, "inner_key")
colsub.row().prop(ui_state, "inner_key_sel")
colsub.row().prop(ui_state, "blend")
col.separator()
col.separator()
col.label("Styles:")
row = col.row()
subsplit = row.split(percentage=0.95)
padding = subsplit.split(percentage=0.15)
colsub = padding.column()
colsub = padding.column()
colsub.row().prop(ui, "menu_shadow_fac")
subsplit = row.split(percentage=0.85)
padding = subsplit.split(percentage=0.15)
colsub = padding.column()
colsub = padding.column()
colsub.row().prop(ui, "menu_shadow_width")
row = col.row()
subsplit = row.split(percentage=0.95)
padding = subsplit.split(percentage=0.15)
colsub = padding.column()
colsub = padding.column()
colsub.row().prop(ui, "icon_alpha")
subsplit = row.split(percentage=0.85)
padding = subsplit.split(percentage=0.15)
colsub = padding.column()
colsub = padding.column()
colsub.row().prop(ui, "widget_emboss")
col.separator()
col.separator()
col.label("Axis Colors:")
row = col.row()
subsplit = row.split(percentage=0.95)
padding = subsplit.split(percentage=0.15)
colsub = padding.column()
colsub = padding.column()
colsub.row().prop(ui, "axis_x")
colsub.row().prop(ui, "axis_y")
colsub.row().prop(ui, "axis_z")
subsplit = row.split(percentage=0.85)
padding = subsplit.split(percentage=0.15)
colsub = padding.column()
colsub = padding.column()
layout.separator()
layout.separator()
elif theme.theme_area == 'BONE_COLOR_SETS':
col = split.column()
for i, ui in enumerate(theme.bone_color_sets):
col.label(text=iface_("Color Set %d:") % (i + 1), translate=False) # i starts from 0
row = col.row()
subsplit = row.split(percentage=0.95)
padding = subsplit.split(percentage=0.15)
colsub = padding.column()
colsub = padding.column()
colsub.row().prop(ui, "normal")
colsub.row().prop(ui, "select")
colsub.row().prop(ui, "active")
subsplit = row.split(percentage=0.85)
padding = subsplit.split(percentage=0.15)
colsub = padding.column()
colsub = padding.column()
colsub.row().prop(ui, "show_colored_constraints")
elif theme.theme_area == 'STYLE':
col = split.column()
style = context.user_preferences.ui_styles[0]
col.label(text="Panel Title:")
self._ui_font_style(col, style.panel_title)
col.separator()
col.label(text="Widget:")
self._ui_font_style(col, style.widget)
col.separator()
col.label(text="Widget Label:")
self._ui_font_style(col, style.widget_label)
else:
self._theme_generic(split, getattr(theme, theme.theme_area.lower()), theme.theme_area)
class USERPREF_PT_file(Panel):
bl_space_type = 'USER_PREFERENCES'
bl_label = "Files"
bl_region_type = 'WINDOW'
bl_options = {'HIDE_HEADER'}
@classmethod
def poll(cls, context):
userpref = context.user_preferences
return (userpref.active_section == 'FILES')
def draw(self, context):
layout = self.layout
userpref = context.user_preferences
paths = userpref.filepaths
system = userpref.system
split = layout.split(percentage=0.7)
col = split.column()
col.label(text="File Paths:")
colsplit = col.split(percentage=0.95)
col1 = colsplit.split(percentage=0.3)
sub = col1.column()
sub.label(text="Fonts:")
sub.label(text="Textures:")
sub.label(text="Render Output:")
sub.label(text="Scripts:")
sub.label(text="Sounds:")
sub.label(text="Temp:")
sub.label(text="Render Cache:")
sub.label(text="I18n Branches:")
sub.label(text="Image Editor:")
sub.label(text="Animation Player:")
sub = col1.column()
sub.prop(paths, "font_directory", text="")
sub.prop(paths, "texture_directory", text="")
sub.prop(paths, "render_output_directory", text="")
sub.prop(paths, "script_directory", text="")
sub.prop(paths, "sound_directory", text="")
sub.prop(paths, "temporary_directory", text="")
sub.prop(paths, "render_cache_directory", text="")
sub.prop(paths, "i18n_branches_directory", text="")
sub.prop(paths, "image_editor", text="")
subsplit = sub.split(percentage=0.3)
subsplit.prop(paths, "animation_player_preset", text="")
subsplit.prop(paths, "animation_player", text="")
col.separator()
col.separator()
colsplit = col.split(percentage=0.95)
sub = colsplit.column()
row = sub.split(percentage=0.3)
row.label(text="Auto Execution:")
row.prop(system, "use_scripts_auto_execute")
if system.use_scripts_auto_execute:
box = sub.box()
row = box.row()
row.label(text="Excluded Paths:")
row.operator("wm.userpref_autoexec_path_add", text="", icon='ZOOMIN', emboss=False)
for i, path_cmp in enumerate(userpref.autoexec_paths):
row = box.row()
row.prop(path_cmp, "path", text="")
row.prop(path_cmp, "use_glob", text="", icon='FILTER')
row.operator("wm.userpref_autoexec_path_remove", text="", icon='X', emboss=False).index = i
col = split.column()
col.label(text="Save & Load:")
col.prop(paths, "use_relative_paths")
col.prop(paths, "use_file_compression")
col.prop(paths, "use_load_ui")
col.prop(paths, "use_filter_files")
col.prop(paths, "show_hidden_files_datablocks")
col.prop(paths, "hide_recent_locations")
col.prop(paths, "hide_system_bookmarks")
col.prop(paths, "show_thumbnails")
col.separator()
col.prop(paths, "save_version")
col.prop(paths, "recent_files")
col.prop(paths, "use_save_preview_images")
col.separator()
col.label(text="Auto Save:")
col.prop(paths, "use_keep_session")
col.prop(paths, "use_auto_save_temporary_files")
sub = col.column()
sub.active = paths.use_auto_save_temporary_files
sub.prop(paths, "auto_save_time", text="Timer (mins)")
col.separator()
col.label(text="Text Editor:")
col.prop(system, "use_tabs_as_spaces")
colsplit = col.split(percentage=0.95)
col1 = colsplit.split(percentage=0.3)
sub = col1.column()
sub.label(text="Author:")
sub = col1.column()
sub.prop(system, "author", text="")
class USERPREF_MT_ndof_settings(Menu):
# accessed from the window key-bindings in C (only)
bl_label = "3D Mouse Settings"
def draw(self, context):
layout = self.layout
input_prefs = context.user_preferences.inputs
is_view3d = context.space_data.type == 'VIEW_3D'
layout.prop(input_prefs, "ndof_sensitivity")
layout.prop(input_prefs, "ndof_orbit_sensitivity")
layout.prop(input_prefs, "ndof_deadzone")
if is_view3d:
layout.separator()
layout.prop(input_prefs, "ndof_show_guide")
layout.separator()
layout.label(text="Orbit style")
layout.row().prop(input_prefs, "ndof_view_navigate_method", text="")
layout.row().prop(input_prefs, "ndof_view_rotate_method", text="")
layout.separator()
layout.label(text="Orbit options")
layout.prop(input_prefs, "ndof_rotx_invert_axis")
layout.prop(input_prefs, "ndof_roty_invert_axis")
layout.prop(input_prefs, "ndof_rotz_invert_axis")
# view2d use pan/zoom
layout.separator()
layout.label(text="Pan options")
layout.prop(input_prefs, "ndof_panx_invert_axis")
layout.prop(input_prefs, "ndof_pany_invert_axis")
layout.prop(input_prefs, "ndof_panz_invert_axis")
layout.prop(input_prefs, "ndof_pan_yz_swap_axis")
layout.label(text="Zoom options")
layout.prop(input_prefs, "ndof_zoom_invert")
if is_view3d:
layout.separator()
layout.label(text="Fly/Walk options")
layout.prop(input_prefs, "ndof_fly_helicopter", icon='NDOF_FLY')
layout.prop(input_prefs, "ndof_lock_horizon", icon='NDOF_DOM')
class USERPREF_MT_keyconfigs(Menu):
bl_label = "KeyPresets"
preset_subdir = "keyconfig"
preset_operator = "wm.keyconfig_activate"
def draw(self, context):
props = self.layout.operator("wm.context_set_value", text="Blender (default)")
props.data_path = "window_manager.keyconfigs.active"
props.value = "context.window_manager.keyconfigs.default"
# now draw the presets
Menu.draw_preset(self, context)
class USERPREF_PT_input(Panel):
bl_space_type = 'USER_PREFERENCES'
bl_label = "Input"
bl_region_type = 'WINDOW'
bl_options = {'HIDE_HEADER'}
@classmethod
def poll(cls, context):
userpref = context.user_preferences
return (userpref.active_section == 'INPUT')
@staticmethod
def draw_input_prefs(inputs, layout):
import sys
# General settings
row = layout.row()
col = row.column()
sub = col.column()
sub.label(text="Presets:")
subrow = sub.row(align=True)
subrow.menu("USERPREF_MT_interaction_presets", text=bpy.types.USERPREF_MT_interaction_presets.bl_label)
subrow.operator("wm.interaction_preset_add", text="", icon='ZOOMIN')
subrow.operator("wm.interaction_preset_add", text="", icon='ZOOMOUT').remove_active = True
sub.separator()
sub.label(text="Mouse:")
sub1 = sub.column()
sub1.active = (inputs.select_mouse == 'RIGHT')
sub1.prop(inputs, "use_mouse_emulate_3_button")
sub.prop(inputs, "use_mouse_continuous")
sub.prop(inputs, "drag_threshold")
sub.prop(inputs, "tweak_threshold")
sub.label(text="Select With:")
sub.row().prop(inputs, "select_mouse", expand=True)
sub = col.column()
sub.label(text="Double Click:")
sub.prop(inputs, "mouse_double_click_time", text="Speed")
sub.separator()
sub.prop(inputs, "use_emulate_numpad")
sub.separator()
sub.label(text="Orbit Style:")
sub.row().prop(inputs, "view_rotate_method", expand=True)
sub.separator()
sub.label(text="Zoom Style:")
sub.row().prop(inputs, "view_zoom_method", text="")
if inputs.view_zoom_method in {'DOLLY', 'CONTINUE'}:
sub.row().prop(inputs, "view_zoom_axis", expand=True)
sub.prop(inputs, "invert_mouse_zoom", text="Invert Mouse Zoom Direction")
#sub.prop(inputs, "use_mouse_mmb_paste")
#col.separator()
sub = col.column()
sub.prop(inputs, "invert_zoom_wheel", text="Invert Wheel Zoom Direction")
#sub.prop(view, "wheel_scroll_lines", text="Scroll Lines")
if sys.platform == "darwin":
sub = col.column()
sub.prop(inputs, "use_trackpad_natural", text="Natural Trackpad Direction")
col.separator()
sub = col.column()
sub.label(text="View Navigation:")
sub.row().prop(inputs, "navigation_mode", expand=True)
if inputs.navigation_mode == 'WALK':
walk = inputs.walk_navigation
sub.prop(walk, "use_mouse_reverse")
sub.prop(walk, "mouse_speed")
sub.prop(walk, "teleport_time")
sub = col.column(align=True)
sub.prop(walk, "walk_speed")
sub.prop(walk, "walk_speed_factor")
sub.separator()
sub.prop(walk, "use_gravity")
sub = col.column(align=True)
sub.active = walk.use_gravity
sub.prop(walk, "view_height")
sub.prop(walk, "jump_height")
if inputs.use_ndof:
col.separator()
col.label(text="NDOF Device:")
sub = col.column(align=True)
sub.prop(inputs, "ndof_sensitivity", text="NDOF Sensitivity")
sub.prop(inputs, "ndof_orbit_sensitivity", text="NDOF Orbit Sensitivity")
sub.prop(inputs, "ndof_deadzone", text="NDOF Deadzone")
sub = col.column(align=True)
sub.row().prop(inputs, "ndof_view_navigate_method", expand=True)
sub.row().prop(inputs, "ndof_view_rotate_method", expand=True)
row.separator()
def draw(self, context):
from rna_keymap_ui import draw_keymaps
layout = self.layout
#import time
#start = time.time()
userpref = context.user_preferences
inputs = userpref.inputs
split = layout.split(percentage=0.25)
# Input settings
self.draw_input_prefs(inputs, split)
# Keymap Settings
draw_keymaps(context, split)
#print("runtime", time.time() - start)
class USERPREF_MT_addons_online_resources(Menu):
bl_label = "Online Resources"
# menu to open web-pages with addons development guides
def draw(self, context):
layout = self.layout
layout.operator(
"wm.url_open", text="Add-ons Catalog", icon='URL',
).url = "http://wiki.blender.org/index.php/Extensions:2.6/Py/Scripts"
layout.separator()
layout.operator(
"wm.url_open", text="How to share your add-on", icon='URL',
).url = "http://wiki.blender.org/index.php/Dev:Py/Sharing"
layout.operator(
"wm.url_open", text="Add-on Guidelines", icon='URL',
).url = "http://wiki.blender.org/index.php/Dev:2.5/Py/Scripts/Guidelines/Addons"
layout.operator(
"wm.url_open", text="API Concepts", icon='URL',
).url = bpy.types.WM_OT_doc_view._prefix + "/info_quickstart.html"
layout.operator("wm.url_open", text="Add-on Tutorial", icon='URL',
).url = "http://www.blender.org/api/blender_python_api_current/info_tutorial_addon.html"
class USERPREF_PT_addons(Panel):
bl_space_type = 'USER_PREFERENCES'
bl_label = "Add-ons"
bl_region_type = 'WINDOW'
bl_options = {'HIDE_HEADER'}
_support_icon_mapping = {
'OFFICIAL': 'FILE_BLEND',
'COMMUNITY': 'POSE_DATA',
'TESTING': 'MOD_EXPLODE',
}
@classmethod
def poll(cls, context):
userpref = context.user_preferences
return (userpref.active_section == 'ADDONS')
@staticmethod
def is_user_addon(mod, user_addon_paths):
import os
if not user_addon_paths:
for path in (bpy.utils.script_path_user(),
bpy.utils.script_path_pref()):
if path is not None:
user_addon_paths.append(os.path.join(path, "addons"))
for path in user_addon_paths:
if bpy.path.is_subdir(mod.__file__, path):
return True
return False
@staticmethod
def draw_error(layout, message):
lines = message.split("\n")
box = layout.box()
sub = box.row()
sub.label(lines[0])
sub.label(icon='ERROR')
for l in lines[1:]:
box.label(l)
def draw(self, context):
import os
import addon_utils
layout = self.layout
userpref = context.user_preferences
used_ext = {ext.module for ext in userpref.addons}
userpref_addons_folder = os.path.join(userpref.filepaths.script_directory, "addons")
scripts_addons_folder = bpy.utils.user_resource('SCRIPTS', "addons")
# collect the categories that can be filtered on
addons = [(mod, addon_utils.module_bl_info(mod)) for mod in addon_utils.modules(refresh=False)]
split = layout.split(percentage=0.2)
col = split.column()
col.prop(context.window_manager, "addon_search", text="", icon='VIEWZOOM')
col.label(text="Supported Level")
col.prop(context.window_manager, "addon_support", expand=True)
col.label(text="Categories")
col.prop(context.window_manager, "addon_filter", expand=True)
col = split.column()
# set in addon_utils.modules_refresh()
if addon_utils.error_duplicates:
self.draw_error(col,
"Multiple addons using the same name found!\n"
"likely a problem with the script search path.\n"
"(see console for details)",
)
if addon_utils.error_encoding:
self.draw_error(col,
"One or more addons do not have UTF-8 encoding\n"
"(see console for details)",
)
filter = context.window_manager.addon_filter
search = context.window_manager.addon_search.lower()
support = context.window_manager.addon_support
# initialized on demand
user_addon_paths = []
for mod, info in addons:
module_name = mod.__name__
is_enabled = module_name in used_ext
if info["support"] not in support:
continue
# check if addon should be visible with current filters
if ((filter == "All") or
(filter == info["category"]) or
(filter == "Enabled" and is_enabled) or
(filter == "Disabled" and not is_enabled) or
(filter == "User" and (mod.__file__.startswith((scripts_addons_folder, userpref_addons_folder))))
):
if search and search not in info["name"].lower():
if info["author"]:
if search not in info["author"].lower():
continue
else:
continue
# Addon UI Code
col_box = col.column()
box = col_box.box()
colsub = box.column()
row = colsub.row(align=True)
row.operator(
"wm.addon_expand",
icon='TRIA_DOWN' if info["show_expanded"] else 'TRIA_RIGHT',
emboss=False,
).module = module_name
row.operator(
"wm.addon_disable" if is_enabled else "wm.addon_enable",
icon='CHECKBOX_HLT' if is_enabled else 'CHECKBOX_DEHLT', text="",
emboss=False,
).module = module_name
sub = row.row()
sub.active = is_enabled
sub.label(text='%s: %s' % (info["category"], info["name"]))
if info["warning"]:
sub.label(icon='ERROR')
# icon showing support level.
sub.label(icon=self._support_icon_mapping.get(info["support"], 'QUESTION'))
# Expanded UI (only if additional info is available)
if info["show_expanded"]:
if info["description"]:
split = colsub.row().split(percentage=0.15)
split.label(text="Description:")
split.label(text=info["description"])
if info["location"]:
split = colsub.row().split(percentage=0.15)
split.label(text="Location:")
split.label(text=info["location"])
if mod:
split = colsub.row().split(percentage=0.15)
split.label(text="File:")
split.label(text=mod.__file__, translate=False)
if info["author"]:
split = colsub.row().split(percentage=0.15)
split.label(text="Author:")
split.label(text=info["author"], translate=False)
if info["version"]:
split = colsub.row().split(percentage=0.15)
split.label(text="Version:")
split.label(text='.'.join(str(x) for x in info["version"]), translate=False)
if info["warning"]:
split = colsub.row().split(percentage=0.15)
split.label(text="Warning:")
split.label(text=' ' + info["warning"], icon='ERROR')
user_addon = USERPREF_PT_addons.is_user_addon(mod, user_addon_paths)
tot_row = bool(info["wiki_url"]) + bool(user_addon)
if tot_row:
split = colsub.row().split(percentage=0.15)
split.label(text="Internet:")
if info["wiki_url"]:
split.operator("wm.url_open", text="Documentation", icon='HELP').url = info["wiki_url"]
split.operator("wm.url_open", text="Report a Bug", icon='URL').url = info.get(
"tracker_url",
"https://developer.blender.org/maniphest/task/edit/form/2")
if user_addon:
split.operator("wm.addon_remove", text="Remove", icon='CANCEL').module = mod.__name__
for i in range(4 - tot_row):
split.separator()
# Show addon user preferences
if is_enabled:
addon_preferences = userpref.addons[module_name].preferences
if addon_preferences is not None:
draw = getattr(addon_preferences, "draw", None)
if draw is not None:
addon_preferences_class = type(addon_preferences)
box_prefs = col_box.box()
box_prefs.label("Preferences:")
addon_preferences_class.layout = box_prefs
try:
draw(context)
except:
import traceback
traceback.print_exc()
box_prefs.label(text="Error (see console)", icon='ERROR')
del addon_preferences_class.layout
# Append missing scripts
# First collect scripts that are used but have no script file.
module_names = {mod.__name__ for mod, info in addons}
missing_modules = {ext for ext in used_ext if ext not in module_names}
if missing_modules and filter in {"All", "Enabled"}:
col.column().separator()
col.column().label(text="Missing script files")
module_names = {mod.__name__ for mod, info in addons}
for module_name in sorted(missing_modules):
is_enabled = module_name in used_ext
# Addon UI Code
box = col.column().box()
colsub = box.column()
row = colsub.row(align=True)
row.label(text="", icon='ERROR')
if is_enabled:
row.operator("wm.addon_disable", icon='CHECKBOX_HLT', text="", emboss=False).module = module_name
row.label(text=module_name, translate=False)
if __name__ == "__main__": # only for live edit.
bpy.utils.register_module(__name__)
|
__author__ = 'Artur Barseghyan <artur.barseghyan@gmail.com>'
__copyright__ = 'Copyright (c) 2013 Artur Barseghyan'
__license__ = 'GPL 2.0/LGPL 2.1'
__all__ = ('FIT_METHOD_CROP_SMART', 'FIT_METHOD_CROP_CENTER', 'FIT_METHOD_CROP_SCALE',
'FIT_METHOD_FIT_WIDTH', 'FIT_METHOD_FIT_HEIGHT', 'DEFAULT_FIT_METHOD', 'FIT_METHODS_CHOICES',
'FIT_METHODS_CHOICES_WITH_EMPTY_OPTION', 'IMAGES_UPLOAD_DIR')
from django.utils.translation import ugettext_lazy as _
FIT_METHOD_CROP_SMART = 'smart'
FIT_METHOD_CROP_CENTER = 'center'
FIT_METHOD_CROP_SCALE = 'scale'
FIT_METHOD_FIT_WIDTH = 'fit_width'
FIT_METHOD_FIT_HEIGHT = 'fit_height'
DEFAULT_FIT_METHOD = FIT_METHOD_CROP_CENTER
FIT_METHODS_CHOICES = (
(FIT_METHOD_CROP_SMART, _("Smart crop")),
(FIT_METHOD_CROP_CENTER, _("Crop center")),
(FIT_METHOD_CROP_SCALE, _("Crop scale")),
(FIT_METHOD_FIT_WIDTH, _("Fit width")),
(FIT_METHOD_FIT_HEIGHT, _("Fit height")),
)
FIT_METHODS_CHOICES_WITH_EMPTY_OPTION = [('', '---------')] + list(FIT_METHODS_CHOICES)
IMAGES_UPLOAD_DIR = 'dash-image-plugin-images'
|
"""Layman is a complete library for the operation and maintainance
on all gentoo repositories and overlays
"""
import sys
try:
from layman.api import LaymanAPI
from layman.config import BareConfig
from layman.output import Message
except ImportError:
sys.stderr.write("!!! Layman API imports failed.")
raise
class Layman(LaymanAPI):
"""A complete high level interface capable of performing all
overlay repository actions."""
def __init__(self, stdout=sys.stdout, stdin=sys.stdin, stderr=sys.stderr,
config=None, read_configfile=True, quiet=False, quietness=4,
verbose=False, nocolor=False, width=0, root=None
):
"""Input parameters are optional to override the defaults.
sets up our LaymanAPI with defaults or passed in values
and returns an instance of it"""
self.message = Message(out=stdout, err=stderr)
self.config = BareConfig(
output=self.message,
stdout=stdout,
stdin=stdin,
stderr=stderr,
config=config,
read_configfile=read_configfile,
quiet=quiet,
quietness=quietness,
verbose=verbose,
nocolor=nocolor,
width=width,
root=root
)
LaymanAPI.__init__(self, self.config,
report_errors=True,
output=self.config['output']
)
return
|
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
('dispatch', '0017_subsections'),
]
operations = [
migrations.CreateModel(
name='Podcast',
fields=[
('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)),
('slug', models.SlugField(unique=True)),
('title', models.CharField(max_length=255)),
('description', models.TextField()),
('author', models.CharField(max_length=255)),
('owner_name', models.CharField(max_length=255)),
('owner_email', models.EmailField(max_length=255)),
('category', models.CharField(max_length=255)),
('image', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='dispatch.Image')),
],
),
migrations.CreateModel(
name='PodcastEpisode',
fields=[
('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)),
('title', models.CharField(max_length=255)),
('description', models.TextField()),
('author', models.CharField(max_length=255)),
('duration', models.PositiveIntegerField(null=True)),
('published_at', models.DateTimeField()),
('explicit', models.CharField(choices=[(b'no', b'No'), (b'yes', b'Yes'), (b'clean', b'Clean')], default=b'no', max_length=5)),
('file', models.FileField(upload_to=b'podcasts/')),
('type', models.CharField(default='audio/mp3', max_length=255)),
('image', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='dispatch.Image')),
('podcast', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='dispatch.Podcast')),
],
),
]
|
"""
This module instructs the setuptools to setpup this package properly
:copyright: (c) 2016 by Mehdy Khoshnoody.
:license: GPLv3, see LICENSE for more details.
"""
import os
from distutils.core import setup
setup(
name='pyeez',
version='0.1.0',
packages=['pyeez'],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
keywords='terminal console',
url='https://github.com/mehdy/pyeez',
license='GPLv3',
author='Mehdy Khoshnoody',
author_email='me@mehdy.net',
description='A micro-framework to create console-based applications like'
'htop, vim and etc'
)
|
import re
import sys
from urllib import urlopen
def isup(domain):
resp = urlopen("http://www.isup.me/%s" % domain).read()
return "%s" % ("UP" if re.search("It's just you.", resp,
re.DOTALL) else "DOWN")
if __name__ == '__main__':
if len(sys.argv) > 1:
print "\n".join(isup(d) for d in sys.argv[1:])
else:
print "usage: %s domain1 [domain2 .. domainN]" % sys.argv[0]
|
from django import forms
from django.forms import ModelForm
from models import *
from django.forms import Textarea
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import Group
class OgretimElemaniFormu(ModelForm):
parolasi=forms.CharField(label="Parolasi",
help_text='Parola yazilmazsa onceki parola gecerlidir',
required=False)
class Meta:
model = OgretimElemani
fields = ('unvani','first_name','last_name',
'username','parolasi','email','telefonu')
def save(self,commit=True):
instance = super(OgretimElemaniFormu,self).save(commit=False)
if self.cleaned_data.get('parolasi'):
instance.password=make_password(self.cleaned_data['parolasi'])
if commit:
instance.save()
if instance.group.filter(name='ogretimelemanlari'):
grp = Group.objects.get(name='ogretimelemanlari')
instance.group.add(grp)
return instance
class DersFormu(ModelForm):
class Meta:
model = Ders
widgets = {
'tanimi':Textarea(attrs={'cols':35, 'rows':5}),
}
#exclude=('unvani','telefonu') bu da ayni gorevi gorur
# fields kullanarak hangi sirada gozukmesini istiyorsak ayarlayabiliriz
# yada exclude diyerek istemedigimiz alanlari formdan cikartabiliriz
class AramaFormu(forms.Form):
aranacak_kelime = forms.CharField()
def clean_aranacak_kelime(self):
kelime=self.cleaned_data['aranacak_kelime']
if len(kelime) < 3:
raise forms.ValidationError('Aranacak kelime 3 harften az olamaz')
return kelime
|
import unittest
import ldc
import uuid
class TestLDCDNSInterface(unittest.TestCase):
def test_ldcdns(self):
rand_str = str(uuid.uuid4())
ldc.dns.add(rand_str, '1.1.1.1')
assert ldc.dns.resolve(rand_str) == [ '1.1.1.1' ]
ldc.dns.replace_all(rand_str,'2.2.2.2')
assert ldc.dns.resolve(rand_str) == [ '2.2.2.2' ]
ldc.dns.delete(rand_str)
assert ldc.dns.resolve(rand_str) == []
if __name__ == '__main__':
unittest.main()
|
"""
Script: GotoLineCol.py
Utility: 1. Moves the cursor position to the specified line and column for a file in Notepad++.
Especially useful for inspecting data files in fixed-width record formats.
2. Also, displays the character code (SBCS & LTR) in decimal and hex at the specified position.
Requires: Python Script plugin in Notepad++
Customizable parameters for the goToLineCol function call in main():
bRepeatPrompt: Whether to repeat prompting when the specified number value is out of range
iEdgeBuffer: Ensures that the caret will be that many characters inside the left and right edges of the editor viewing area, when possible
iCaretHiliteDuration: Caret will be in Block mode for specified seconds
bCallTipAutoHide: Whether to hide the call tip automatically in sync when caret highlighting is turned off
bBraceHilite: Whether to use brace highlighting style for the character at the specified position. Automatically turns off when current line changes.
Known Issues: 1. Character code display in the call tip is functional with SBCS (Single-Byte Character Sets) and LTR (left-to-right) direction.
With MBCS (Bulti-Bytes Character Sets) or RTL (right-to-left) direction, results will not be reliable.
2. If iCaretHiliteDuration is set to a high value (>3 seconds), and the user tries to rerun the script
while the previous execution is still running, the Python Script plugin will display an error message:
"Another script is still running..." So set this parameter to 3 seconds or lower.
Author: Shridhar Kumar
Date: 2019-08-15
"""
def main():
goToLineCol(bRepeatPrompt = True,
iEdgeBuffer = 5,
iCaretHiliteDuration = 5,
bCallTipAutoHide = False,
bBraceHilite = True)
def getDisplayLineCol():
iCurrLine = editor.lineFromPosition(editor.getCurrentPos())
iCurrCol = editor.getCurrentPos() - editor.positionFromLine(iCurrLine)
return str(iCurrLine + 1), str(iCurrCol + 1)
def promptValue(sInfoText, sTitleText, sDefaultVal, iMinVal, iMaxVal, sRangeError, bRepeatPrompt):
while True:
sNewVal = notepad.prompt(sInfoText, sTitleText, sDefaultVal)
if sNewVal == None:
return None
try:
iNewVal = int(sNewVal)
if iMinVal <= iNewVal <= iMaxVal:
return iNewVal
else:
raise
except:
notepad.messageBox(sRangeError + '.\n\nYou specified: ' + sNewVal +
'\n\nPlease specify a number between ' + str(iMinVal) + ' and ' + str(iMaxVal) + '.',
'Specified value is out of range')
if not bRepeatPrompt:
return None
def goToLineCol(bRepeatPrompt, iEdgeBuffer, iCaretHiliteDuration, bCallTipAutoHide, bBraceHilite):
import time
sCurrLine, sCurrCol = getDisplayLineCol()
iMaxLines = editor.getLineCount()
iNewLine = promptValue(sInfoText = 'Line number (between 1 and ' + str(iMaxLines) + '):',
sTitleText = 'Specify line number',
sDefaultVal = sCurrLine,
iMinVal = 1,
iMaxVal = iMaxLines,
sRangeError = 'File line count is only ' + str(iMaxLines),
bRepeatPrompt = bRepeatPrompt)
if iNewLine == None:
return
# Get the character count plus 1 for the specified line
# Plus 1 is to account for the caret position at the end of the line, past all characters but before EOL/EOF
# Since lineLength already includes EOL, we just need to subtract 1 only when EOL is 2 chars. i.e., CRLF
# For the last line in file, there is no 2-character CRLF EOL; only a single character EOF.
iMaxCols = max(1, editor.lineLength(iNewLine - 1))
if (editor.getEOLMode() == ENDOFLINE.CRLF) and (iNewLine < iMaxLines):
iMaxCols -= 1
iNewCol = promptValue(sInfoText = 'Column position (between 1 and ' + str(iMaxCols) + ') for line ' + str(iNewLine) + ':',
sTitleText = 'Specify column position',
sDefaultVal = sCurrCol,
iMinVal = 1,
iMaxVal = iMaxCols,
sRangeError = 'There are only ' + str(iMaxCols) + ' characters in line ' + str(iNewLine),
bRepeatPrompt = bRepeatPrompt)
# Navigate to the specified position in the document
iLineStartPos = editor.positionFromLine(iNewLine - 1)
iNewPos = iLineStartPos + iNewCol - 1
editor.ensureVisible(iNewLine - 1)
editor.gotoPos( min(iLineStartPos + iMaxCols, iNewPos + iEdgeBuffer) ) # Ensure that caret is 'iEdgeBuffer' characters inside right edge when possible
editor.gotoPos( max(iLineStartPos, iNewPos - iEdgeBuffer) ) # Ensure that caret is 'iEdgeBuffer' characters inside left edge when possible
editor.gotoPos(iNewPos) # Finally, move caret to the specified position
# Obtain current caret style to restore it later on
currCS = editor.getCaretStyle()
# Set the caret to block style to highlight the new position
editor.setCaretStyle(CARETSTYLE.BLOCK)
# Display a call tip with the new line and column numbers with verification
# Also display the character code in decimal and hex
sCurrLine, sCurrCol = getDisplayLineCol()
editor.callTipShow(iNewPos, ' Line: ' + sCurrLine +
'\n Column: ' + sCurrCol +
'\nChar Code: ' + str(editor.getCharAt(iNewPos)) + ' [' + hex(editor.getCharAt(iNewPos)) + ']')
if iCaretHiliteDuration > 0:
time.sleep(iCaretHiliteDuration)
# Reset the caret style
editor.setCaretStyle(currCS)
if bCallTipAutoHide:
editor.callTipCancel()
if bBraceHilite:
editor.braceHighlight(iNewPos, iNewPos)
main()
|
'''
Created on 22/02/2015
@author: Ismail Faizi
'''
import models
class ModelFactory(object):
"""
Factory for creating entities of models
"""
@classmethod
def create_user(cls, name, email, training_journal):
"""
Factory method for creating User entity.
NOTE: you must explicitly call the put() method
"""
user = models.User(parent=models.USER_KEY)
user.name = name
user.email = email
user.training_journal = training_journal.key
return user
@classmethod
def create_training_journal(cls):
"""
Factory method for creating TrainingJournal entity.
NOTE: you must explicitly call the put() method
"""
return models.TrainingJournal(parent=models.TRAINING_JOURNAL_KEY)
@classmethod
def create_workout_session(cls, started_at, ended_at, training_journal):
"""
Factory method for creating WorkoutSession entity.
NOTE: you must explicitly call the put() method
"""
workout_session = models.WorkoutSession(parent=models.WORKOUT_SESSION_KEY)
workout_session.started_at = started_at
workout_session.ended_at = ended_at
workout_session.training_journal = training_journal.key
return workout_session
@classmethod
def create_workout_set(cls, repetitions, weight, workout_session, workout):
"""
Factory method for creating WorkoutSet entity.
NOTE: you must explicitly call the put() method
"""
workout_set = models.WorkoutSet(parent=models.WORKOUT_SET_KEY)
workout_set.repetitions = repetitions
workout_set.weight = weight
workout_set.workout_session = workout_session.key
workout_set.workout = workout.key
return workout_set
@classmethod
def create_workout(cls, muscle_group, names=[], description='', images=[]):
"""
Factory method for creating WorkoutSet entity.
NOTE: you must explicitly call the put() method
"""
workout = models.Workout(parent=models.WORKOUT_KEY)
workout.names = names
workout.muscle_group = muscle_group
workout.description = description
workout.images = images
return workout
|
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
if QT_VERSION < 0x0040500:
sys.stderr.write("You need Qt 4.5 or newer to run this example.\n")
sys.exit(1)
SNAP_THRESHOLD = 10
class SnapView(QWebView):
def __init__(self):
QWebView.__init__(self)
self.snapEnabled = True
self.setWindowTitle(self.tr("Snap-scrolling is ON"))
# rects hit by the line, in main frame's view coordinate
def hitBoundingRects(self, line):
hitRects = []
points = 8
delta = QPoint(line.dx() / points, line.dy() / points)
point = line.p1()
i = 0
while i < points - 1:
point += delta
hit = self.page().mainFrame().hitTestContent(point)
if not hit.boundingRect().isEmpty():
hitRects.append(hit.boundingRect())
i += 1
return hitRects
def keyPressEvent(self, event):
# toggle snapping
if event.key() == Qt.Key_F3:
self.snapEnabled = not self.snapEnabled
if self.snapEnabled:
self.setWindowTitle(self.tr("Snap-scrolling is ON"))
else:
self.setWindowTitle(self.tr("Snap-scrolling is OFF"))
event.accept()
return
# no snapping? do not bother...
if not self.snapEnabled:
QWebView.keyReleaseEvent(self, event)
return
previousOffset = self.page().mainFrame().scrollPosition()
QWebView.keyReleaseEvent(self, event)
if not event.isAccepted():
return
if event.key() == Qt.Key_Down:
ofs = self.page().mainFrame().scrollPosition()
jump = ofs.y() - previousOffset.y()
if jump == 0:
return
jump += SNAP_THRESHOLD
rects = self.hitBoundingRects(QLine(1, 1, self.width() - 1, 1))
i = 0
while i < len(rects):
j = rects[i].top() - previousOffset.y()
if j > SNAP_THRESHOLD and j < jump:
jump = j
i += 1
self.page().mainFrame().setScrollPosition(previousOffset + QPoint(0, jump))
if __name__ == "__main__":
app = QApplication(sys.argv)
view = SnapView()
view.load(QUrl("http://news.bbc.co.uk/text_only.stm"))
view.resize(320, 500)
view.show()
QMessageBox.information(view, "Hint", "Use F3 to toggle snapping on and off")
sys.exit(app.exec_())
|
import sys
from wsnamelet import wsnamelet_globals
if wsnamelet_globals.debug:
sys.stdout = open ("/home/munizao/hacks/wsnamelet/debug.stdout", "w", buffering=1)
sys.stderr = open ("/home/munizao/hacks/wsnamelet/debug.stderr", "w", buffering=1)
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("MatePanelApplet", "4.0")
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GObject
from gi.repository import Pango
from gi.repository import MatePanelApplet
gi.require_version ("Wnck", "3.0")
from gi.repository import Wnck
from gi.repository import Gio
import locale
import gettext
gettext.bindtextdomain('wsnamelet', wsnamelet_globals.localedir)
gettext.textdomain('wsnamelet')
locale.bindtextdomain('wsnamelet', wsnamelet_globals.localedir)
locale.textdomain('wsnamelet')
gettext.install('wsnamelet', wsnamelet_globals.localedir)
class WSNamePrefs(object):
def __init__(self, applet):
self.applet = applet
self.dialog = Gtk.Dialog("Workspace Name Applet Preferences",
None,
Gtk.DialogFlags.DESTROY_WITH_PARENT,
(Gtk.STOCK_CLOSE, Gtk.ResponseType.CLOSE))
self.dialog.set_border_width(10)
width_spin_label = Gtk.Label(label=_("Applet width in pixels:"))
width_adj = Gtk.Adjustment(lower=30, upper=500, step_incr=1)
self.width_spin_button = Gtk.SpinButton.new(width_adj, 0.0, 0)
self.applet.settings.bind("width", self.width_spin_button, "value", Gio.SettingsBindFlags.DEFAULT)
width_spin_hbox = Gtk.HBox()
width_spin_hbox.pack_start(width_spin_label, True, True, 0)
width_spin_hbox.pack_start(self.width_spin_button, True, True, 0)
self.dialog.vbox.add(width_spin_hbox)
class WSNameEntry(Gtk.Entry):
def __init__(self, applet):
Gtk.Widget.__init__(self)
self.connect("activate", self._on_activate)
self.connect("key-release-event", self._on_key_release)
self.applet = applet
def _on_activate(self, event):
text = self.get_text()
self.applet.workspace.change_name(text)
self.applet.label.set_text(text)
self.applet.exit_editing()
def _on_key_release(self, widget, event):
if event.keyval == Gdk.KEY_Escape:
self.applet.exit_editing()
class WSNameApplet(MatePanelApplet.Applet):
_name_change_handler_id = None
workspace = None
settings = None
prefs = None
width = 100
editing = False
def __init__(self, applet):
self.applet = applet;
menuxml = """
<menuitem name="Prefs" action="Prefs" />
<menuitem name="About" action="About" />
"""
actions = [("Prefs", Gtk.STOCK_PREFERENCES, "Preferences", None, None, self._display_prefs),
("About", Gtk.STOCK_ABOUT, "About", None, None, self._display_about)]
actiongroup = Gtk.ActionGroup.new("WsnameActions")
actiongroup.add_actions(actions, None)
applet.setup_menu(menuxml, actiongroup)
self.init()
def _display_about(self, action):
about = Gtk.AboutDialog()
about.set_program_name("Workspace Name Applet")
about.set_version(wsnamelet_globals.version)
about.set_copyright("© 2006 - 2015 Alexandre Muñiz")
about.set_comments("View and change the name of the current workspace.\n\nTo change the workspace name, click on the applet, type the new name, and press Enter.")
about.set_website("https://github.com/munizao/mate-workspace-name-applet")
about.connect ("response", lambda self, *args: self.destroy ())
about.show_all()
def _display_prefs(self, action):
self.prefs.dialog.show_all()
self.prefs.dialog.run()
self.prefs.dialog.hide()
def set_width(self, width):
self.width = width
self.button.set_size_request(width, -1)
self.button.queue_resize()
self.entry.set_size_request(width, -1)
self.entry.queue_resize()
def on_width_changed(self, settings, key):
width = settings.get_int(key)
self.set_width(width)
def init(self):
self.button = Gtk.Button()
self.button.connect("button-press-event", self._on_button_press)
self.button.connect("button-release-event", self._on_button_release)
self.label = Gtk.Label()
self.label.set_ellipsize(Pango.EllipsizeMode.END)
self.applet.add(self.button)
self.button.add(self.label)
self.entry = WSNameEntry(self)
self.entry.connect("button-press-event", self._on_entry_button_press)
try:
self.settings = Gio.Settings.new("com.puzzleapper.wsname-applet-py")
self.set_width(self.settings.get_int("width"))
self.settings.connect("changed::width", self.on_width_changed)
except:
self.set_width(100)
self.screen = Wnck.Screen.get_default()
self.workspace = really_get_active_workspace(self.screen)
self.screen.connect("active_workspace_changed", self._on_workspace_changed)
self.button.set_tooltip_text(_("Click to change the name of the current workspace"))
self._name_change_handler_id = None
self.prefs = WSNamePrefs(self)
self.show_workspace_name()
self.applet.show_all()
return True
def _on_button_press(self, button, event, data=None):
if event.button != 1:
button.stop_emission("button-press-event")
def _on_button_release(self, button, event, data=None):
if event.type == Gdk.EventType.BUTTON_RELEASE and event.button == 1:
self.editing = True
self.applet.remove(self.button)
self.applet.add(self.entry)
self.entry.set_text(self.workspace.get_name())
self.entry.set_position(-1)
self.entry.select_region(0, -1)
self.applet.request_focus(event.time)
GObject.timeout_add(0, self.entry.grab_focus)
self.applet.show_all()
def _on_entry_button_press(self, entry, event, data=None):
self.applet.request_focus(event.time)
def _on_workspace_changed(self, event, old_workspace):
if self.editing:
self.exit_editing()
if (self._name_change_handler_id):
self.workspace.disconnect(self._name_change_handler_id)
self.workspace = really_get_active_workspace(self.screen)
self._name_change_handler_id = self.workspace.connect("name-changed", self._on_workspace_name_changed)
self.show_workspace_name()
def _on_workspace_name_changed(self, event):
self.show_workspace_name()
def show_workspace_name(self):
if self.workspace:
self.label.set_text(self.workspace.get_name())
self.applet.show_all()
def exit_editing(self):
self.editing = False
self.applet.remove(self.entry)
self.applet.add(self.button)
def really_get_active_workspace(screen):
# This bit is needed because wnck is asynchronous.
while Gtk.events_pending():
Gtk.main_iteration()
return screen.get_active_workspace()
def applet_factory(applet, iid, data):
WSNameApplet(applet)
return True
MatePanelApplet.Applet.factory_main("WsnameAppletFactory",
True,
MatePanelApplet.Applet.__gtype__,
applet_factory,
None)
|
"""
Created on Wed Aug 19 17:08:36 2015
@author: jgimenez
"""
from PyQt4 import QtGui, QtCore
import os
import time
import subprocess
types = {}
types['p'] = 'scalar'
types['U'] = 'vector'
types['p_rgh'] = 'scalar'
types['k'] = 'scalar'
types['epsilon'] = 'scalar'
types['omega'] = 'scalar'
types['alpha'] = 'scalar'
types['nut'] = 'scalar'
types['nuTilda'] = 'scalar'
types['nuSgs'] = 'scalar'
unknowns = ['U','p','p_rgh','alpha','k','nuSgs','epsilon','omega','nuTilda','nut']
def drange(start, stop, step):
r = start
while r < stop:
yield r
r += step
def command_window(palette):
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush)
def currentFields(currentFolder,filterTurb=True,nproc=1):
#veo los campos que tengo en el directorio inicial
timedir = 0
currtime = 0
logname = '%s/dirFeatures.log'%currentFolder
logerrorname = '%s/error.log'%currentFolder
#print 'nproc: %s'%nproc
if nproc<=1:
command = 'dirFeaturesFoam -case %s 1> %s 2> %s' % (currentFolder,logname,logerrorname)
else:
command = 'mpirun -np %s dirFeaturesFoam -case %s -parallel 1> %s 2> %s' % (nproc,currentFolder,logname,logerrorname)
#print 'command: %s'%command
#p = subprocess.Popen([command],shell=True)
#p.wait()
os.system(command)
log = open(logname, 'r')
for linea in log:
if "Current Time" in linea:
currtime = linea.split('=')[1].strip()
timedir = '%s/%s'%(currentFolder,currtime)
from PyFoam.RunDictionary.ParsedParameterFile import ParsedParameterFile
#Levanto todos los campos y me fijo cual se ca a utilizar (dependiendo del turbulence model)
allturb = ['k','epsilon','omega','nuSgs','nut','nuTilda']
#le dejo los que voy a utilizar
filename = '%s/constant/turbulenceProperties'%currentFolder
e=False
try:
tprop = ParsedParameterFile(filename,createZipped=False)
except IOError as e:
tprop = {}
if (not e):
if tprop['simulationType']=='RASModel':
filename = '%s/constant/RASProperties'%currentFolder
Rprop = ParsedParameterFile(filename,createZipped=False)
if Rprop['RASModel']=='kEpsilon':
allturb.remove('k')
allturb.remove('epsilon')
if Rprop['RASModel']=='kOmega' or Rprop['RASModel']=='kOmegaSST':
allturb.remove('k')
allturb.remove('omega')
elif tprop['simulationType']=='LESModel':
filename = '%s/constant/LESProperties'%currentFolder
Lprop = ParsedParameterFile(filename,createZipped=False)
if Lprop['LESModel']=='Smagorinsky':
allturb.remove('nuSgs')
NO_FIELDS = ['T0', 'T1', 'T2', 'T3', 'T4', 'nonOrth', 'skew']
if filterTurb:
for it in allturb:
NO_FIELDS.append(it)
command = 'rm -f %s/*~ %s/*.old'%(timedir,timedir)
os.system(command)
while not os.path.isfile(logname):
continue
#Esta linea la agrego porque a veces se resetea el caso y se borra
#el folder de currentTime. Por eso uso el 0, siempre estoy seguro que
#esta presente
if not os.path.isdir(str(timedir)):
timedir = '%s/0'%currentFolder
fields = [ f for f in os.listdir(timedir) if (f not in NO_FIELDS and f in unknowns) ]
return [timedir,fields,currtime]
def backupFile(f):
filename = f
if os.path.isfile(filename) and os.path.getsize(filename) > 0:
newfilepath = filename+'.backup'
command = 'cp %s %s'%(filename,newfilepath)
os.system(command)
def get_screen_resolutions():
output = subprocess.Popen('xrandr | grep "\*" | cut -d" " -f4',shell=True, stdout=subprocess.PIPE).communicate()[0]
resolution = output.split()[0].split(b'x')
return resolution
|
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm, colors
initDir = '../init/'
nlat = 31
nlon = 30
L = 1.5e7
c0 = 2
timeDim = L / c0 / (60. * 60. * 24)
H = 200
tau_0 = 1.0922666667e-2
delta_T = 1.
sampFreq = 0.35 / 0.06 * 12 # (in year^-1)
muRng = np.array([2.1, 2.5, 2.7, 2.75, 2.8, 2.85, 2.9, 2.95,
3., 3.1, 3.3, 3.7])
amu0Rng = np.array([0.75, 1.])
epsRng = np.array([0.])
sNoise = 'without noise'
spinup = 0
timeWin = np.array([0, int(sampFreq * 1000)])
neof = 1
prefix = 'zc'
simType = '_%deof_seasonal' % (neof,)
indicesDir = '../observables/'
field_h = (1, 'Thermocline depth', r'$h$', 'm', H, r'$h^2$')
field_T = (2, 'SST', 'T', r'$^\circ C$', delta_T, r'$(^\circ C)^2$')
nino3Def = ('Eastern', 'nino3')
nino4Def = ('Western', 'nino4')
fieldDef = field_T
indexDef = nino3Def
fs_default = 'x-large'
fs_latex = 'xx-large'
fs_xlabel = fs_default
fs_ylabel = fs_default
fs_xticklabels = fs_default
fs_yticklabels = fs_default
fs_legend_title = fs_default
fs_legend_labels = fs_default
fs_cbar_label = fs_default
figFormat = 'png'
dpi = 300
for eps in epsRng:
for amu0 in amu0Rng:
for mu in muRng:
postfix = '_mu%04d_amu0%04d_eps%04d' \
% (np.round(mu * 1000, 1), np.round(amu0 * 1000, 1),
np.round(eps * 1000, 1))
resDir = '%s%s%s/' % (prefix, simType, postfix)
indicesPath = '%s/%s' % (indicesDir, resDir)
pltDir = resDir
os.system('mkdir %s %s 2> /dev/null' % (pltDir, indicesPath))
# Read dataset
indexData = np.loadtxt('%s/%s.txt' % (indicesPath, indexDef[1]))
timeND = indexData[:, 0]
timeFull = timeND * timeDim / 365
indexFull = indexData[:, fieldDef[0]] * fieldDef[4]
# Remove spinup
index = indexFull[spinup:]
time = timeFull[spinup:]
nt = time.shape[0]
# Plot time-series
linewidth = 2
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(time[timeWin[0]:timeWin[1]], index[timeWin[0]:timeWin[1]],
linewidth=linewidth)
# plt.title('Time-series of %s averaged over %s\nfor mu = %.4f and eps = %.4f' % (fieldDef[1], indexDef[0], mu, eps))
ax.set_xlabel('years', fontsize=fs_latex)
ax.set_ylabel('%s %s (%s)' \
% (indexDef[0], fieldDef[1], fieldDef[3]),
fontsize=fs_latex)
plt.setp(ax.get_xticklabels(), fontsize=fs_xticklabels)
plt.setp(ax.get_yticklabels(), fontsize=fs_yticklabels)
fig.savefig('%s/%s%s%s.png' % (pltDir, indexDef[1], fieldDef[2],
postfix), bbox_inches='tight')
# Get periodogram of zonal wind stress averaged over index
nRAVG = 1
window = np.hamming(nt)
# Get nearest larger power of 2
if np.log2(nt) != int(np.log2(nt)):
nfft = 2**(int(np.log2(nt)) + 1)
else:
nfft = nt
# Get frequencies and shift zero frequency to center
freq = np.fft.fftfreq(nfft, d=1./sampFreq)
freq = np.fft.fftshift(freq)
ts = index - index.mean(0)
# Apply window
tsWindowed = ts * window
# Fourier transform and shift zero frequency to center
fts = np.fft.fft(tsWindowed, nfft, 0)
fts = np.fft.fftshift(fts)
# Get periodogram
perio = np.abs(fts / nt)**2
# Apply running average
perioRAVG = perio.copy()
for iavg in np.arange(nRAVG/2, nfft-nRAVG/2):
perioRAVG[iavg] = perio[iavg-nRAVG/2:iavg+nRAVG/2 + 1].mean()\
/ nRAVG
# Plot
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(freq, np.log10(perioRAVG), '-k')
# ax.set_xscale('log')
# ax.set_yscale('log')
ax.set_xlim(0, 4)
#ax.set_ylim(0, vmax)
ax.set_xlabel(r'years$^{-1}$', fontsize=fs_latex)
ax.set_ylabel(fieldDef[5], fontsize=fs_latex)
plt.setp(ax.get_xticklabels(), fontsize=fs_xticklabels)
plt.setp(ax.get_yticklabels(), fontsize=fs_yticklabels)
xlim = ax.get_xlim()
ylim = ax.get_ylim()
ax.text(xlim[0] + 0.2 * (xlim[1] - xlim[0]),
ylim[0] + 0.1 * (ylim[1] - ylim[0]),
r'$\mu = %.3f$ %s' % (mu, sNoise), fontsize=32)
# plt.title('Periodogram of %s averaged over %s\nfor mu = %.1f and eps = %.2f' % (fieldDef[1], indexDef[0], mu, eps))
fig.savefig('%s/%s%sPerio%s.%s' \
% (pltDir, indexDef[1], fieldDef[2],
postfix, figFormat),
bbox_inches='tight', dpi=dpi)
|
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "annotator.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
import wx
import _widgets as _wgt
from wx.lib.wordwrap import wordwrap
__version__ = '1.0.0'
import logging
log = logging.getLogger('root')
class CustomDialog(wx.Dialog):
def __init__(self, parent, *arg, **kw):
style = (wx.NO_BORDER | wx.CLIP_CHILDREN)
self.borderColour = wx.BLACK
wx.Dialog.__init__(self, parent, title='Fancy', style = style)
self.Bind(wx.EVT_MOTION, self.OnMouse)
self.Bind(wx.EVT_PAINT, self.OnPaint)
def OnSetBorderColour(self, color):
self.borderColour = color
def OnPaint(self, event):
evtObj = event.GetEventObject()
evtObjBG = evtObj.GetBackgroundColour()
dc = wx.PaintDC(evtObj)
dc = wx.GCDC(dc)
w, h = self.GetSizeTuple()
r = 10
dc.SetPen( wx.Pen(self.borderColour,3) )
dc.SetBrush( wx.Brush(evtObjBG))
dc.DrawRectangle( 0,0,w,h )
def OnMouse(self, event):
"""implement dragging"""
if not event.Dragging():
self._dragPos = None
return
self.CaptureMouse()
if not self._dragPos:
self._dragPos = event.GetPosition()
else:
pos = event.GetPosition()
displacement = self._dragPos - pos
self.SetPosition( self.GetPosition() - displacement )
self.ReleaseMouse()
event.Skip()
class MyMessageDialog(CustomDialog):
def __init__(self, parent, msg, myStyle, *arg, **kw):
self._msg = msg
self._style = myStyle
super(MyMessageDialog, self).__init__(parent, *arg, **kw)
self._panel = wx.Panel(self)
self._message = wordwrap(str(self._msg), 350, wx.ClientDC(self))
self.stcText = wx.StaticText(self._panel, -1, self._message)
self.stcText.SetFocus()
self.btnOk = _wgt.CustomPB(self._panel, id=wx.ID_OK, label='OK')
mainSizer = wx.BoxSizer(wx.HORIZONTAL)
panelSizer = wx.BoxSizer(wx.VERTICAL)
panelSizer.Add(self.stcText, 1, wx.ALL|wx.EXPAND|wx.CENTRE, 2)
btnSizer = wx.BoxSizer(wx.HORIZONTAL)
btnSizer.Add(self.btnOk, 0, wx.ALL|wx.CENTRE, 5)
if self._style != None and 'INC_CANCEL' in self._style:
self.btnCancel = _wgt.CustomPB(self._panel,
id=wx.ID_CANCEL, label='Cancel')
btnSizer.Add(self.btnCancel, 0, wx.ALL|wx.CENTRE, 5)
panelSizer.Add(btnSizer, 0, wx.ALL|wx.CENTRE, 5)
self._panel.SetSizer(panelSizer)
mainSizer.Add(self._panel, 1, wx.ALL|wx.EXPAND|wx.CENTRE, 2)
self.SetSizerAndFit(mainSizer)
self._panel.Bind(wx.EVT_MOTION, self.OnMouse)
self.Bind(wx.EVT_BUTTON, self.OnOk, id=wx.ID_OK)
self.CenterOnParent()
def OnOk(self, event):
self.EndModal(wx.ID_OK)
class ClearBtnLocks(CustomDialog):
def __init__(self, parent, *arg, **kw):
super(ClearBtnLocks, self).__init__(parent, *arg, **kw)
self.parent = parent
self.OnInitUI()
self.OnInitLayout()
self.OnBindEvents()
self.CenterOnParent()
self.OnSetBorderColour(wx.Colour(46,139,87,255))
def OnInitUI(self):
self._panel = wx.Panel(self)
self.cbDayStart = wx.CheckBox(self._panel, -1, 'Clear Start of Day')
self.cbLunchStart = wx.CheckBox(self._panel, -1, 'Clear Start of Lunch')
self.cbLunchEnd = wx.CheckBox(self._panel, -1, 'Clear End of Lunch')
self.cbDayEnd = wx.CheckBox(self._panel, -1, 'Clear End of Day')
self.cbCheckAll = wx.CheckBox(self._panel, 0, 'Select All')
self.cbList = ( self.cbDayStart, self.cbLunchStart,
self.cbLunchEnd, self.cbDayEnd )
self.btnOk = _wgt.CustomPB(self._panel, id=wx.ID_OK, label='OK')
self.btnCancel = _wgt.CustomPB(self._panel, id=wx.ID_CANCEL, label='Cancel')
def OnInitLayout(self):
mainSizer = wx.BoxSizer(wx.HORIZONTAL)
panelSizer = wx.BoxSizer(wx.VERTICAL)
statBox = wx.StaticBox(self._panel, label='Which Buttons to Enable?')
sbSizer = wx.StaticBoxSizer(statBox, wx.VERTICAL)
cbSizer = wx.FlexGridSizer(3, 2, 3, 3)
cbSizer.AddMany(
[
(self.cbDayStart, 0, wx.ALL, 1),
(self.cbLunchStart, 0, wx.ALL, 1),
(self.cbLunchEnd, 0, wx.ALL, 1),
(self.cbDayEnd, 0, wx.ALL, 1),
(self.cbCheckAll, 0, wx.ALL, 1)
]
)
sbSizer.Add(cbSizer, 0, wx.ALL, 1)
btnSizer = wx.BoxSizer(wx.HORIZONTAL)
btnSizer.Add(self.btnOk, 0, wx.ALL, 5)
btnSizer.Add(self.btnCancel, 0, wx.ALL, 5)
sbSizer.Add(btnSizer, 1, wx.ALL|wx.CENTRE, 1)
panelSizer.Add(sbSizer, 0, wx.ALL | wx.EXPAND, 5)
self._panel.SetSizer(panelSizer)
mainSizer.Add(self._panel, 1, wx.ALL|wx.EXPAND|wx.CENTRE, 2)
self.SetSizerAndFit(mainSizer)
def OnBindEvents(self):
self._panel.Bind(wx.EVT_MOTION, self.OnMouse)
self.Bind(wx.EVT_BUTTON, self.OnOk, id=wx.ID_OK)
for cbOption in self.cbList:
cbOption.Bind(wx.EVT_CHECKBOX, self.ClearSelectAll)
self.cbCheckAll.Bind(wx.EVT_CHECKBOX, self.OnSelectAll)
def OnSelectAll(self, event):
if self.cbCheckAll.GetValue():
self.cbDayStart.SetValue(True)
self.cbLunchStart.SetValue(True)
self.cbLunchEnd.SetValue(True)
self.cbDayEnd.SetValue(True)
else:
self.cbDayStart.SetValue(False)
self.cbLunchStart.SetValue(False)
self.cbLunchEnd.SetValue(False)
self.cbDayEnd.SetValue(False)
def ClearSelectAll(self, event):
self.cbCheckAll.SetValue(False)
def OnOk(self, event):
log.debug('User prompted: Confirm button reset.')
_msg = 'You are about to reset button locks!\nDo you wish to continue?'
_style = 'INC_CANCEL'
dlg = MyMessageDialog(self, msg=_msg, myStyle=_style)
dlg.OnSetBorderColour(wx.Colour(255,165,0,255))
if dlg.ShowModal() == wx.ID_OK:
if self.cbDayStart.GetValue():
self.parent.btnStartDay.Enable(True)
self.parent.txtStartDay.SetValue('')
log.debug(
'\'Start of Day\' button enabled by user.')
if self.cbLunchStart.GetValue():
self.parent.btnStartLunch.Enable(True)
self.parent.txtStartLunch.SetValue('')
log.debug(
'\'Start of Lunch\' button enabled by user.')
if self.cbLunchEnd.GetValue():
self.parent.btnEndLunch.Enable(True)
self.parent.txtEndLunch.SetValue('')
log.debug(
'\'End of Lunch\' button enabled by user.')
if self.cbDayEnd.GetValue():
self.parent.btnEndDay.Enable(True)
self.parent.txtEndDay.SetValue('')
log.debug(
'\'End of Day\' button enabled by user.')
event.Skip()
self.EndModal(wx.ID_OK)
def OnCancel(self, event):
self.EndModal(wx.ID_CANCEL)
class EnterEmail(CustomDialog):
def __init__(self, parent, eType, *arg, **kw):
self.eType = eType
super(EnterEmail, self).__init__(parent, *arg, **kw)
self.parent = parent
self.idEmail = wx.NewId()
self.OnInitUI()
self.OnInitLayout()
self.OnBindEvents()
self.OnSetBorderColour(wx.Colour(205,133,63,255))
def OnInitUI(self):
self._panel = wx.Panel(self)
self.sb = wx.StaticBox(self._panel, label='')
self.dEmail = wx.TextCtrl(self._panel, id=self.idEmail,
value='',
style=wx.TE_PROCESS_ENTER|wx.SIMPLE_BORDER)
if self.eType == 'DEST':
self.sb.SetLabel('Confirm destination email address:')
#log.debug(
# 'User is updating Destination email address.')
self.dEmail.SetValue('enter @ default . email')
elif self.eType == 'CC':
#log.debug(
# 'User is updating CC email address.')
self.sb.SetLabel('Enter email address to CC:')
elif self.eType == 'BUG':
self.sb.SetLabel('Confirm email address for Bug Reports:')
self.dEmail.SetValue('bug @ report . email')
self.btnOk = _wgt.CustomPB(self._panel, id=wx.ID_OK, label='OK')
self.btnCancel = _wgt.CustomPB(self._panel, id=wx.ID_CANCEL, label='Cancel')
def OnInitLayout(self):
mainSizer = wx.BoxSizer(wx.HORIZONTAL)
panelSizer = wx.BoxSizer(wx.VERTICAL)
sbSizer1 = wx.StaticBoxSizer(self.sb, wx.VERTICAL)
sbSizer1.Add(self.dEmail, 1, wx.ALL|wx.EXPAND, 5)
btnSizer = wx.BoxSizer(wx.HORIZONTAL)
btnSizer.Add(self.btnOk, 1, wx.ALL, 5)
btnSizer.Add(self.btnCancel, 1, wx.ALL, 5)
sbSizer1.Add(btnSizer, 1, wx.ALL|wx.EXPAND, 5)
panelSizer.Add(sbSizer1, 1, wx.ALL|wx.EXPAND, 3)
self._panel.SetSizer(panelSizer)
mainSizer.Add(self._panel, 1, wx.ALL|wx.EXPAND, 2)
self.SetSizerAndFit(mainSizer)
self.SetPosition( (400,300) )
def OnBindEvents(self):
self._panel.Bind(wx.EVT_MOTION, self.OnMouse)
self.dEmail.Bind(wx.EVT_TEXT_ENTER, self.OnOk)
def GetAddress(self):
emailAddress = self.dEmail.GetValue()
if '@' in emailAddress and '.' in emailAddress.split('@')[1]:
return emailAddress
else:
return ''
def OnOk(self, event):
self.EndModal(wx.ID_OK)
class ViewEmail(CustomDialog):
def __init__(self, parent, eType, eMail, *arg, **kw):
self.eType = eType
self.eMail = eMail
super(ViewEmail, self).__init__(parent, *arg, **kw)
self.OnInitUI()
self.OnInitLayout()
self.OnSetBorderColour(wx.Colour(55,95,215,255))
def OnInitUI(self):
self._panel = wx.Panel(self)
self.statBox = wx.StaticBox(self._panel, label='')
self.statEmail = wx.StaticText(self._panel, label='')
statFont = wx.Font(14, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
self.statEmail.SetFont(statFont)
if self.eType == 'DEST':
self.statBox.SetLabel('Destination Address:')
elif self.eType == 'CC':
self.statBox.SetLabel('\'Carbon Copy\' Address:')
elif self.eType == 'BUG':
self.statBox.SetLabel('\'Bug Report\' Address:')
emailString = wordwrap(
str(self.eMail),
350,wx.ClientDC(self._panel))
self.statEmail.SetLabel(emailString)
self.btnOk = _wgt.CustomPB(self._panel, id=wx.ID_OK, label='OK')
def OnInitLayout(self):
mainSizer = wx.BoxSizer(wx.HORIZONTAL)
panelSizer = wx.BoxSizer(wx.VERTICAL)
sbSizer1 = wx.StaticBoxSizer(self.statBox, wx.VERTICAL)
sbSizer1.Add(self.statEmail, 1, wx.ALL|wx.CENTER, 3)
btnSizer = wx.BoxSizer(wx.HORIZONTAL)
btnSizer.Add(self.btnOk, 1, wx.ALL|wx.CENTER, 5)
sbSizer1.Add(btnSizer, 1, wx.ALL|wx.CENTER, 5)
panelSizer.Add(sbSizer1, 1, wx.ALL|wx.EXPAND, 5)
self._panel.SetSizer(panelSizer)
mainSizer.Add(self._panel, 1, wx.ALL|wx.EXPAND, 3)
self.SetSizerAndFit(mainSizer)
def OnOk(self, event):
if self.IsModal():
self.EndModal(wx.ID_OK)
class AboutWindow(CustomDialog):
def __init__(self, parent, ver, *arg, **kw):
self._ver = ver
super(AboutWindow, self).__init__(parent, *arg, **kw)
'''Create and define the About dialog window.'''
self._idHyperlink = wx.NewId()
self.OnInitWidgets()
self.OnInitLayout()
self.OnBindEvents()
self.CenterOnParent()
def OnInitWidgets(self):
self._panel = wx.Panel(self)
self.titleText = wx.StaticText(self._panel, -1,
'Clock Punch v%s' % self._ver)
titleFont = wx.Font(14, wx.DECORATIVE, wx.NORMAL, wx.BOLD)
self.titleText.SetFont(titleFont)
self.webLink = _wgt.CustomHyperlink(self._panel,
self._idHyperlink,
label = 'Written using Python',
url = "http://en.wikipedia.org/wiki/Python_programming_language"
)
description = wordwrap(
"This is the Clock Puncher."
" \n-The original Time Punch application re-written."
" \nIt allows you to easily send the various time punch"
" emails at the click of a button."
"\n\nPlease do not report any issues with this program to DS IT as"
" it is not an officially supported application.",
350, wx.ClientDC(self))
self.descText = wx.StaticText(self._panel, -1, description)
self.licenseHeader = wx.StaticText(self._panel, -1, 'Licensing:')
licenseFont = wx.Font(12, wx.DECORATIVE, wx.NORMAL, wx.BOLD)
self.licenseHeader.SetFont(licenseFont)
license = wordwrap('Main program: GPL v3'
'\nPython: PSF License'
'\npyWin32: PSF License'
'\nWMI: MIT License'
'\nwxPython: wxWidgets License',
350, wx.ClientDC(self))
self.licenseText = wx.StaticText(self._panel, -1, license)
self.devHeader = wx.StaticText(self._panel, -1, 'Developer(s):')
devFont = wx.Font(12, wx.DECORATIVE, wx.NORMAL, wx.BOLD)
self.devHeader.SetFont(devFont)
developers = wordwrap(
'Program Writer:'
'\nMichael Stover',
500, wx.ClientDC(self))
self.devText = wx.StaticText(self._panel, -1, developers)
self.btnOk = _wgt.CustomPB(self._panel,
id=wx.ID_OK, label='OK', size=(50,-1))
def OnInitLayout(self):
mainSizer = wx.BoxSizer(wx.HORIZONTAL)
panelSizer = wx.BoxSizer(wx.VERTICAL)
titleSizer = wx.BoxSizer(wx.HORIZONTAL)
titleSizer.Add(self.titleText, 0, wx.ALL|wx.EXPAND|wx.ALIGN_CENTER, 2)
descriptSizer = wx.BoxSizer(wx.VERTICAL)
descriptSizer.Add(self.descText, 1, wx.ALL|wx.EXPAND, 2)
descriptSizer.Add(self.webLink, 0, wx.ALL, 2)
licenseSizer = wx.BoxSizer(wx.VERTICAL)
licenseSizer.Add(self.licenseHeader, 0, wx.ALL|wx.EXPAND|wx.CENTER, 2)
licenseSizer.Add(self.licenseText, 1, wx.ALL|wx.EXPAND, 2)
developSizer = wx.BoxSizer(wx.VERTICAL)
developSizer.Add(self.devHeader, 0, wx.ALL|wx.EXPAND|wx.CENTER, 2)
developSizer.Add(self.devText, 1, wx.ALL|wx.EXPAND, 2)
buttonSizer = wx.BoxSizer(wx.HORIZONTAL)
buttonSizer.Add(self.btnOk, 0, wx.ALL|wx.ALIGN_RIGHT, 2)
panelSizer.Add(titleSizer, 0, wx.ALL|wx.EXPAND|wx.ALIGN_CENTER, 2)
panelSizer.Add(descriptSizer, 0, wx.ALL|wx.EXPAND, 2)
panelSizer.Add(wx.StaticLine(
self._panel, -1,
style=wx.LI_HORIZONTAL
),
1, wx.ALL|wx.EXPAND, 5
)
panelSizer.Add(licenseSizer, 0, wx.ALL|wx.EXPAND, 2)
panelSizer.Add(wx.StaticLine(
self._panel, -1,
style=wx.LI_HORIZONTAL
),
1, wx.ALL|wx.EXPAND, 5
)
panelSizer.Add(developSizer, 0, wx.ALL|wx.EXPAND, 2)
panelSizer.Add(buttonSizer, 0, wx.ALL|wx.ALIGN_CENTER, 2)
self._panel.SetSizer(panelSizer)
mainSizer.Add(self._panel, 1, wx.ALL|wx.EXPAND, 2)
self.SetSizerAndFit(mainSizer)
def OnBindEvents(self):
self.Bind(wx.EVT_HYPERLINK, self.OnLinkClicked, id=self._idHyperlink)
self._panel.Bind(wx.EVT_MOTION, self.OnMouse)
def OnLinkClicked(self, event=None):
evtObj = event.GetEventObject()
if isinstance(evtObj, wx.HyperlinkCtrl):
print evtObj.GetURL()
def OnOk(self, event):
if self.IsModal():
self.EndModal(wx.ID_OK)
class HelpWindow(CustomDialog):
def __init__(self, parent, *arg, **kw):
super(HelpWindow, self).__init__(parent, *arg, **kw)
pass
class BugReport(CustomDialog):
def __init__(self, parent, *arg, **kw):
super(BugReport, self).__init__(parent, *arg, **kw)
self.OnSetBorderColour(wx.Colour(153, 0, 0, 255))
self.OnInitUI()
self.OnInitLayout()
self.OnBindEvents()
def OnInitUI(self):
self._panel = wx.Panel(self)
self._panel.SetBackgroundColour(wx.Colour(230,230,230,255))
self._titleBox = wx.StaticText(
self._panel, -1, ' Bug Report Submission',
style=wx.NO_BORDER
)
titleFont = wx.Font(12, wx.DECORATIVE, wx.NORMAL, wx.BOLD)
self._titleBox.SetFont(titleFont)
self._titleBox.SetBackgroundColour(wx.WHITE)
summary = wordwrap(
'Thank you for taking this opportunity to submit '
'a bug report for this program.\n\nPlease enter a '
'brief description into the box below. I will '
'investigate the bug report as soon as possible.'
'\n\nUpon clicking Submit the program will also '
'locate and collect any logs for review. These '
'will be sent as attachments to the email.'
'\n\nNo personal information is collected.'
'\nYou will be able to preview the report before '
'it is sent.',
350, wx.ClientDC(self))
self.bugTips = wx.StaticText(self._panel, -1, summary,
style=wx.NO_BORDER|wx.TE_CENTER
)
self.bugTips.SetBackgroundColour(wx.WHITE)
self.summaryBox = wx.TextCtrl(self._panel, -1, value='',
style=wx.TE_MULTILINE|wx.SIMPLE_BORDER)
self.btnOk = _wgt.CustomPB(self._panel, id=wx.ID_OK, label='OK')
self.btnCancel = _wgt.CustomPB(self._panel, id=wx.ID_CANCEL, label='Cancel')
def OnInitLayout(self):
mainSizer = wx.BoxSizer(wx.HORIZONTAL)
panelSizer = wx.BoxSizer(wx.VERTICAL)
titleSizer = wx.BoxSizer(wx.HORIZONTAL)
titleSizer.Add(self._titleBox, 1, wx.ALL|wx.EXPAND, 3)
panelSizer.Add(titleSizer, 0, wx.EXPAND|wx.CENTRE, 3)
tipsSizer = wx.BoxSizer(wx.HORIZONTAL)
tipsSizer.Add(self.bugTips, 1, wx.EXPAND, 3)
panelSizer.Add(tipsSizer, 1, wx.ALL|wx.EXPAND, 3)
summarySizer = wx.BoxSizer(wx.HORIZONTAL)
summarySizer.Add(self.summaryBox, 1, wx.ALL|wx.EXPAND, 3)
panelSizer.Add(summarySizer, 1, wx.ALL|wx.EXPAND, 1)
buttonSizer = wx.BoxSizer(wx.HORIZONTAL)
buttonSizer.Add(self.btnOk, 1, wx.ALL, 3)
buttonSizer.Add(self.btnCancel, 1, wx.ALL, 3)
panelSizer.Add(buttonSizer, 0, wx.EXPAND, 1)
self._panel.SetSizer(panelSizer)
mainSizer.Add(self._panel, 1, wx.ALL, 3)
self.SetSizerAndFit(mainSizer)
def OnBindEvents(self):
self._panel.Bind(wx.EVT_MOTION, self.OnMouse)
self._titleBox.Bind(wx.EVT_MOTION, self.OnMouse)
self.bugTips.Bind(wx.EVT_MOTION, self.OnMouse)
def OnGetSummary(self, event=None):
return self.summaryBox.GetValue()
def OnClose(self, event):
self.EndModal(event.GetId())
import logging
log = logging.getLogger('root')
log.debug('Dialogs Module %s Initialized.' % __version__)
|
"""
WSGI config for SysuLesson project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "SysuLesson.settings")
application = get_wsgi_application()
|
from sys import argv
script, filename = argv
txt = open(filename)
print "Here's your file %r:" % filename
print txt.read()
# String kein Attribut read haben!!!
# AttributeError: 'str' object has no attribute 'read'
print "Type the filename again:"
file_again = open(raw_input("> "))
print file_again.read(), 'geht!!!'
txt_again = open('ex15_sample.txt')
print txt_again.read(), 'das geht auch'
|
"""DockWidget test.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = 'sirneeraj@gmail.com'
__date__ = '2016-12-20'
__copyright__ = 'Copyright 2016, neeraj'
import unittest
from PyQt4.QtGui import QDockWidget
from pt_stop_calc_dockwidget import PTStopCalcDockWidget
from utilities import get_qgis_app
QGIS_APP = get_qgis_app()
class PTStopCalcDockWidgetTest(unittest.TestCase):
"""Test dockwidget works."""
def setUp(self):
"""Runs before each test."""
self.dockwidget = PTStopCalcDockWidget(None)
def tearDown(self):
"""Runs after each test."""
self.dockwidget = None
def test_dockwidget_ok(self):
"""Test we can click OK."""
pass
if __name__ == "__main__":
suite = unittest.makeSuite(PTStopCalcDialogTest)
runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite)
|
from django.db import models
from django_crypto_fields.fields import EncryptedTextField
from edc_base.model.models import BaseUuidModel
try:
from edc_sync.mixins import SyncMixin
except ImportError:
SyncMixin = type('SyncMixin', (object, ), {})
from ..managers import CallLogManager
class CallLog (SyncMixin, BaseUuidModel):
"""Maintains a log of calls for a particular participant."""
subject_identifier = models.CharField(
verbose_name="Subject Identifier",
max_length=50,
blank=True,
db_index=True,
unique=True,
)
locator_information = EncryptedTextField(
help_text=('This information has been imported from'
'the previous locator. You may update as required.')
)
contact_notes = EncryptedTextField(
null=True,
blank=True,
help_text=''
)
label = models.CharField(
max_length=25,
null=True,
editable=False,
help_text="from followup list"
)
objects = CallLogManager()
def natural_key(self):
return self.subject_identifier
class Meta:
app_label = 'edc_contact'
|
import copy
import pandas as pd
import scipy
from SecuML.core.Tools import matrix_tools
from .AnnotationQuery import AnnotationQuery
class Category(object):
def __init__(self, label=None, family=None):
self.assignLabelFamily(label, family)
self.instances_ids = []
self.probas = []
self.entropy = []
self.likelihood = []
self.df = None
self.annotation_queries = {}
self.annotated_instances = []
self.num_annotated_instances = 0
# To display the annotation queries in the web GUI
self.queries = []
self.queries_confidence = []
def generateAnnotationQuery(self, instance_id, predicted_proba,
suggested_label, suggested_family, confidence=None):
return AnnotationQuery(instance_id, predicted_proba,
suggested_label, suggested_family, confidence=confidence)
def assignLabelFamily(self, label, family):
self.family = family
if label != 'all':
self.label = label
else:
self.label = label
def numInstances(self):
return len(self.instances_ids)
def setWeight(self, weight):
self.weight = weight
def setNumAnnotations(self, num_annotations):
self.num_annotations = num_annotations
def addInstance(self, instance_id, probas, annotated):
self.instances_ids.append(instance_id)
entropy = None
proba = None
likelihood = None
if probas is not None:
entropy = scipy.stats.entropy(probas)
proba = max(probas)
self.entropy.append(entropy)
self.probas.append(proba)
self.likelihood.append(likelihood)
if annotated:
self.annotated_instances.append(instance_id)
self.num_annotated_instances += 1
def finalComputation(self):
self.df = pd.DataFrame({'proba': self.probas,
'entropy': self.entropy,
'likelihood': self.likelihood},
index=list(map(str, self.instances_ids)))
def annotateAuto(self, iteration):
for k, queries in self.annotation_queries.items():
for q, query in enumerate(queries):
query.annotateAuto(iteration, self.label)
def getManualAnnotations(self, iteration):
for k, queries in self.annotation_queries.items():
for q, query in enumerate(queries):
query.getManualAnnotation(iteration)
def checkAnnotationQueriesAnswered(self, iteration):
for k, queries in self.annotation_queries.items():
for q, query in enumerate(queries):
if not query.checkAnswered(iteration):
return False
return True
def setLikelihood(self, likelihood):
self.likelihood = likelihood
self.df['likelihood'] = likelihood
def getLikelihood(self, instances):
df = pd.DataFrame({'likelihood': self.likelihood},
index=list(map(str, self.instances_ids)))
selected_df = df.loc[list(map(str, instances)), :]
return selected_df['likelihood'].tolist()
def getCategoryLabel(self):
return self.label
def getCategoryFamily(self):
return self.family
def toJson(self):
obj = {}
obj['label'] = self.label
obj['family'] = self.family
obj['annotation_queries'] = {}
for kind, queries in self.annotation_queries.items():
obj['annotation_queries'][kind] = []
for q, query in enumerate(queries):
obj['annotation_queries'][kind].append(query.toJson())
return obj
@staticmethod
def fromJson(obj):
category = Category()
category.instances_ids = obj['instances_ids']
category.label = obj['label']
return category
def exportAnnotationQueries(self):
annotation_queries = {}
annotation_queries['instance_ids'] = self.queries
annotation_queries['confidence'] = self.queries_confidence
annotation_queries['label'] = self.label
return annotation_queries
def generateAnnotationQueries(self, cluster_strategy):
queries_types = cluster_strategy.split('_')
num_queries_types = len(queries_types)
total_num_queries = 0
annotated_instances = copy.deepcopy(self.annotated_instances)
for q, queries_type in enumerate(queries_types):
if q == (num_queries_types - 1):
num_queries = self.num_annotations - total_num_queries
else:
num_queries = self.num_annotations // num_queries_types
if queries_type == 'center':
queries = self.queryHighLikelihoodInstances(
annotated_instances, num_queries)
elif queries_type == 'anomalous':
queries = self.queryLowLikelihoodInstances(
annotated_instances, num_queries)
elif queries_type == 'uncertain':
queries = self.queryUncertainInstances(
annotated_instances, num_queries)
elif queries_type == 'random':
queries = self.queryRandomInstances(
annotated_instances, num_queries)
else:
raise ValueError()
annotated_instances += queries
total_num_queries += len(queries)
assert(total_num_queries == self.num_annotations)
def queryUncertainInstances(self, drop_instances, num_instances):
if num_instances == 0:
return []
queries_df = self.getSelectedInstancesDataframe(drop_instances)
matrix_tools.sortDataFrame(queries_df, 'entropy', False, True)
queries_df = queries_df.head(num_instances)
self.addAnnotationQueries('uncertain', 'low', queries_df)
return list(map(int, queries_df.index.values.tolist()))
def queryHighLikelihoodInstances(self, drop_instances, num_instances):
if num_instances == 0:
return []
queries_df = self.getSelectedInstancesDataframe(drop_instances)
matrix_tools.sortDataFrame(queries_df, 'likelihood', False, True)
queries_df = queries_df.head(num_instances)
self.addAnnotationQueries('high_likelihood', 'high', queries_df)
return list(map(int, queries_df.index.values.tolist()))
def queryLowLikelihoodInstances(self, drop_instances, num_instances):
if num_instances == 0:
return []
queries_df = self.getSelectedInstancesDataframe(drop_instances)
matrix_tools.sortDataFrame(queries_df, 'likelihood', True, True)
queries_df = queries_df.head(num_instances)
self.addAnnotationQueries('low_likelihood', 'low', queries_df)
return list(map(int, queries_df.index.values.tolist()))
def queryRandomInstances(self, drop_instances, num_instances):
if num_instances == 0:
return []
queries_df = self.getSelectedInstancesDataframe(drop_instances)
queries_df = queries_df.sample(n=num_instances, axis=0)
self.addAnnotationQueries('random', 'low', queries_df)
return list(map(int, queries_df.index.values.tolist()))
def addAnnotationQueries(self, kind, confidence, queries_df):
if kind not in list(self.annotation_queries.keys()):
self.annotation_queries[kind] = []
for index, row in queries_df.iterrows():
query = self.generateAnnotationQuery(int(index), row['likelihood'],
self.label, self.family, confidence=confidence)
self.annotation_queries[kind].append(query)
self.queries.append(int(index))
self.queries_confidence.append(confidence)
def getSelectedInstancesDataframe(self, drop_instances):
if drop_instances is None:
selected_instances = self.instances_ids
else:
selected_instances = [
x for x in self.instances_ids if x not in drop_instances]
selected_df = self.df.loc[list(map(str, selected_instances)), :]
return selected_df
|
"""
python library for the AR.Drone 1.0 (1.11.5) and 2.0 (2.2.9).
parts of code from Bastian Venthur, Jean-Baptiste Passot, Florian Lacrampe.
tested with Python 2.7.3 and AR.Drone vanilla firmware 1.11.5.
"""
import logging
import multiprocessing
import sys
import threading
import time
import arATCmds
import arNetwork
import arIPCThread
w_logLvl = logging.ERROR
class ARDrone ( object ):
"""
ARDrone class.
instanciate this class to control AR.Drone and receive decoded video and navdata.
"""
# ---------------------------------------------------------------------------------------------
# ARDrone::__init__
# ---------------------------------------------------------------------------------------------
def __init__ ( self ):
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::__init__" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
self.seq_nr = 1
self.timer_t = 0.2
self.com_watchdog_timer = threading.Timer ( self.timer_t, self.commwdg )
self.lock = threading.Lock ()
self.speed = 0.2
self.at ( arATCmds.at_config, "general:navdata_demo", "TRUE" )
self.vid_pipe, vid_pipe_other = multiprocessing.Pipe ()
self.nav_pipe, nav_pipe_other = multiprocessing.Pipe ()
self.com_pipe, com_pipe_other = multiprocessing.Pipe ()
self.network_process = arNetwork.ARDroneNetworkProcess ( nav_pipe_other, vid_pipe_other, com_pipe_other )
self.network_process.start ()
self.ipc_thread = arIPCThread.IPCThread ( self )
self.ipc_thread.start ()
self.image = None
self.navdata = {}
self.time = 0
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone::apply_command
# ---------------------------------------------------------------------------------------------
def apply_command ( self, f_command ):
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::apply_command" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
las_available_commands = [ "emergency", "hover", "land",
"move_backward", "move_down", "move_forward",
"move_left", "move_right", "move_up",
"takeoff", "turn_left", "turn_right", ]
# validade command
if ( f_command not in las_available_commands ):
# sherlock logger
# l_log.error ( "Command %s not recognized !" % f_command )
# sherlock logger
# l_log.debug ( "<< (E01)" )
return
if ( "hover" != f_command ):
self.last_command_is_hovering = False
if ( "emergency" == f_command ):
self.reset ()
elif (( "hover" == f_command ) and ( not self.last_command_is_hovering )):
self.hover ()
self.last_command_is_hovering = True
elif ( "land" == f_command ):
self.land ()
self.last_command_is_hovering = True
elif ( "move_backward" == f_command ):
self.move_backward ()
elif ( "move_forward" == f_command ):
self.move_forward ()
elif ( "move_down" == f_command ):
self.move_down ()
elif ( "move_up" == f_command ):
self.move_up ()
elif ( "move_left" == f_command ):
self.move_left ()
elif ( "move_right" == f_command ):
self.move_right ()
elif ( "takeoff" == f_command ):
self.takeoff ()
self.last_command_is_hovering = True
elif ( "turn_left" == f_command ):
self.turn_left ()
elif ( "turn_right" == f_command ):
self.turn_right ()
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone::at
# ---------------------------------------------------------------------------------------------
def at ( self, f_cmd, *args, **kwargs ):
"""
wrapper for the low level at commands.
this method takes care that the sequence number is increased after each at command and the
watchdog timer is started to make sure the drone receives a command at least every second.
"""
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::at" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
self.lock.acquire ()
self.com_watchdog_timer.cancel ()
f_cmd ( self.seq_nr, *args, **kwargs )
self.seq_nr += 1
self.com_watchdog_timer = threading.Timer ( self.timer_t, self.commwdg )
self.com_watchdog_timer.start ()
self.lock.release ()
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone::commwdg
# ---------------------------------------------------------------------------------------------
def commwdg ( self ):
"""
communication watchdog signal.
this needs to be send regulary to keep the communication with the drone alive.
"""
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::commwdg" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
self.at ( arATCmds.at_comwdg )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone::event_boom
# ---------------------------------------------------------------------------------------------
def event_boom ( self ):
"""
boom event
"""
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::event_boom" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
# animation to play
li_anim = arDefs.ARDRONE_LED_ANIMATION_DOUBLE_MISSILE
# frequence in HZ of the animation
lf_freq = 2.
# total duration in seconds of the animation
lf_secs = 4
# play LED animation
self.at ( arATCmds.at_led, li_anim, lf_freq, lf_secs )
# animation to play
li_anim = arDefs.ARDRONE_ANIMATION_THETA_30_DEG
# total duration in seconds of the animation
lf_secs = 1000
# play motion animation
self.at ( arATCmds.at_anim, li_anim, lf_secs )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone::event_thetamixed
# ---------------------------------------------------------------------------------------------
def event_thetamixed ( self ):
"""
make the drone execute thetamixed !
"""
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::event_thetamixed" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
# animation to play
li_anim = arDefs.ARDRONE_LED_ANIMATION_DOUBLE_MISSILE
# frequence in HZ of the animation
lf_freq = 2.
# total duration in seconds of the animation
lf_secs = 4
# play LED animation
self.at ( arATCmds.at_led, li_anim, lf_freq, lf_secs )
# animation to play
li_anim = arDefs.ARDRONE_ANIMATION_THETA_MIXED
# total duration in seconds of the animation
lf_secs = 5000
# play motion animation
self.at ( arATCmds.at_anim, li_anim, lf_secs )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone::event_turnarround
# ---------------------------------------------------------------------------------------------
def event_turnarround ( self ):
"""
make the drone turnarround.
"""
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::event_turnarround" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
# animation to play
li_anim = arDefs.ARDRONE_LED_ANIMATION_DOUBLE_MISSILE
# frequence in HZ of the animation
lf_freq = 2.
# total duration in seconds of the animation
lf_secs = 4
# play LED animation
self.at ( arATCmds.at_led, li_anim, lf_freq, lf_secs )
# animation to play
li_anim = arDefs.ARDRONE_ANIMATION_TURNAROUND
# total duration in seconds of the animation
lf_secs = 5000
# play motion animation
self.at ( arATCmds.at_anim, li_anim, lf_secs )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone::event_yawdance
# ---------------------------------------------------------------------------------------------
def event_yawdance ( self ):
"""
make the drone execute yawdance YEAH !
"""
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::event_yawdance" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
# animation to play
li_anim = arDefs.ARDRONE_LED_ANIMATION_DOUBLE_MISSILE
# frequence in HZ of the animation
lf_freq = 2.
# total duration in seconds of the animation
lf_secs = 4
# play LED animation
self.at ( arATCmds.at_led, li_anim, lf_freq, lf_secs )
# animation to play
li_anim = arDefs.ARDRONE_ANIMATION_YAW_DANCE
# total duration in seconds of the animation
lf_secs = 5000
# play motion animation
self.at ( arATCmds.at_anim, li_anim, lf_secs )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone::event_yawshake
# ---------------------------------------------------------------------------------------------
def event_yawshake ( self ):
"""
Make the drone execute yawshake YEAH !
"""
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::event_yawshake" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
# animation to play
li_anim = arDefs.ARDRONE_LED_ANIMATION_DOUBLE_MISSILE
# frequence in HZ of the animation
lf_freq = 2.
# total duration in seconds of the animation
lf_secs = 4
# play LED animation
self.at ( arATCmds.at_led, li_anim, lf_freq, lf_secs )
# animation to play
li_anim = arDefs.ARDRONE_ANIMATION_YAW_SHAKE
# total duration in seconds of the animation
lf_secs = 2000
# play motion animation
self.at ( arATCmds.at_anim, li_anim, lf_secs )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone::get_image
# ---------------------------------------------------------------------------------------------
def get_image ( self ):
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::get_image" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
_im = np.copy ( self.image )
# sherlock logger
# l_log.debug ( "<<" )
return _im
# ---------------------------------------------------------------------------------------------
# ARDrone::get_navdata
# ---------------------------------------------------------------------------------------------
def get_navdata ( self ):
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::get_navdata" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( "><" )
return self.navdata
# ---------------------------------------------------------------------------------------------
# ARDrone::halt
# ---------------------------------------------------------------------------------------------
def halt ( self ):
"""
shutdown the drone.
does not land or halt the actual drone, but the communication with the drone. Should call
it at the end of application to close all sockets, pipes, processes and threads related
with this object.
"""
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::halt" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
self.lock.acquire ()
self.com_watchdog_timer.cancel ()
self.com_pipe.send ( "die!" )
self.network_process.terminate () # 2.0 ?
self.network_process.join ()
self.ipc_thread.stop () # 2.0 ?
self.ipc_thread.join () # 2.0 ?
self.lock.release ()
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone::hover
# ---------------------------------------------------------------------------------------------
def hover ( self ):
"""
make the drone hover.
"""
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::hover" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
self.at ( arATCmds.at_pcmd, False, 0, 0, 0, 0 )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone::land
# ---------------------------------------------------------------------------------------------
def land ( self ):
"""
make the drone land.
"""
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::land" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
self.at ( arATCmds.at_ref, False )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone::move
# ---------------------------------------------------------------------------------------------
def move ( self, ff_lr, ff_fb, ff_vv, ff_va ):
"""
makes the drone move (translate/rotate).
@param lr : left-right tilt: float [-1..1] negative: left / positive: right
@param rb : front-back tilt: float [-1..1] negative: forwards / positive: backwards
@param vv : vertical speed: float [-1..1] negative: go down / positive: rise
@param va : angular speed: float [-1..1] negative: spin left / positive: spin right
"""
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::move" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
# validate inputs
# assert ( 1. >= ff_lr >= -1. )
# assert ( 1. >= ff_fb >= -1. )
# assert ( 1. >= ff_vv >= -1. )
# assert ( 1. >= ff_va >= -1. )
# move drone
self.at ( arATCmds.at_pcmd, True, float ( ff_lr ), float ( ff_fb ), float ( ff_vv ), float ( ff_va ))
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone::move_backward
# ---------------------------------------------------------------------------------------------
def move_backward ( self ):
"""
make the drone move backwards.
"""
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::move_backward" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
self.at ( arATCmds.at_pcmd, True, 0, self.speed, 0, 0 )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone::move_down
# ---------------------------------------------------------------------------------------------
def move_down ( self ):
"""
make the drone decent downwards.
"""
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::move_down" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
self.at ( arATCmds.at_pcmd, True, 0, 0, -self.speed, 0 )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone::move_forward
# ---------------------------------------------------------------------------------------------
def move_forward ( self ):
"""
make the drone move forward.
"""
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::move_forward" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
self.at ( arATCmds.at_pcmd, True, 0, -self.speed, 0, 0 )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone::move_left
# ---------------------------------------------------------------------------------------------
def move_left ( self ):
"""
make the drone move left.
"""
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::move_left" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
self.at ( arATCmds.at_pcmd, True, -self.speed, 0, 0, 0 )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone::move_right
# ---------------------------------------------------------------------------------------------
def move_right ( self ):
"""
make the drone move right.
"""
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::move_right" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
self.at ( arATCmds.at_pcmd, True, self.speed, 0, 0, 0 )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone::move_up
# ---------------------------------------------------------------------------------------------
def move_up ( self ):
"""
make the drone rise upwards.
"""
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::move_up" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
self.at ( arATCmds.at_pcmd, True, 0, 0, self.speed, 0 )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone::reset
# ---------------------------------------------------------------------------------------------
def reset ( self ):
"""
toggle the drone's emergency state.
"""
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::reset" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
self.at ( arATCmds.at_ftrim )
time.sleep ( 0.1 )
self.at ( arATCmds.at_ref, False, True )
time.sleep ( 0.1 )
self.at ( arATCmds.at_ref, False, False )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone::set_image
# ---------------------------------------------------------------------------------------------
def set_image ( self, fo_image ):
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::set_image" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
if ( f_image.shape == self.image_shape ):
self.image = fo_image
self.image = fo_image
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone::set_navdata
# ---------------------------------------------------------------------------------------------
def set_navdata ( self, fo_navdata ):
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::set_navdata" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
self.navdata = fo_navdata
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone::set_speed
# ---------------------------------------------------------------------------------------------
def set_speed ( self, ff_speed ):
"""
set the drone's speed.
valid values are floats from [0..1]
"""
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::set_speed" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
# validate input
# assert ( 1. >= ff_speed >= 0. )
# set speed
self.speed = float ( ff_speed )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone::takeoff
# ---------------------------------------------------------------------------------------------
def takeoff ( self ):
"""
make the drone takeoff.
"""
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::takeoff" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
# calibrate drone
self.at ( arATCmds.at_ftrim )
# set maximum altitude
self.at ( arATCmds.at_config, "control:altitude_max", "20000" )
# take-off
self.at ( arATCmds.at_ref, True )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone::trim
# ---------------------------------------------------------------------------------------------
def trim ( self ):
"""
flat trim the drone.
"""
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::trim" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
self.at ( arATCmds.at_ftrim )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone::turn_left
# ---------------------------------------------------------------------------------------------
def turn_left ( self ):
"""
make the drone rotate left.
"""
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::turn_left" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
self.at ( arATCmds.at_pcmd, True, 0, 0, 0, -self.speed )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone::turn_right
# ---------------------------------------------------------------------------------------------
def turn_right ( self ):
"""
make the drone rotate right.
"""
# sherlock logger
# l_log = logging.getLogger ( "ARDrone::turn_right" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
self.at ( arATCmds.at_pcmd, True, 0, 0, 0, self.speed )
# sherlock logger
# l_log.debug ( "<<" )
class ARDrone2 ( ARDrone ):
"""
ARDrone2 class
instanciate this class to control your drone and receive decoded video and navdata.
"""
# ---------------------------------------------------------------------------------------------
# ARDrone2::__init__
# ---------------------------------------------------------------------------------------------
def __init__ ( self, is_ar_drone_2 = True, hd = False ):
# sherlock logger
# l_log = logging.getLogger ( "ARDrone2::__init__" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
# init super class
ARDrone.__init__ ( self )
self.seq_nr = 1
self.timer_t = 0.2
self.com_watchdog_timer = threading.Timer ( self.timer_t, self.commwdg )
self.lock = threading.Lock ()
self.speed = 0.2
self.image_shape = ( 720, 1080, 1 )
time.sleep ( 0.2 )
self.config_ids_string = [ arDefs.SESSION_ID, arDefs.USER_ID, arDefs.APP_ID ]
self.configure_multisession ( arDefs.SESSION_ID, arDefs.USER_ID, arDefs.APP_ID, self.config_ids_string )
self.set_session_id ( self.config_ids_string, arDefs.SESSION_ID )
time.sleep ( 0.2 )
self.set_profile_id ( self.config_ids_string, arDefs.USER_ID )
time.sleep ( 0.2 )
self.set_app_id ( self.config_ids_string, arDefs.APP_ID )
time.sleep ( 0.2 )
self.set_video_bitrate_control_mode ( self.config_ids_string, "1" )
time.sleep ( 0.2 )
self.set_video_bitrate ( self.config_ids_string, "500" )
time.sleep ( 0.2 )
self.set_max_bitrate ( self.config_ids_string, "500" )
time.sleep ( 0.2 )
self.set_fps ( self.config_ids_string, "30" )
time.sleep ( 0.2 )
self.set_video_codec ( self.config_ids_string, 0x80 )
self.last_command_is_hovering = True
self.com_pipe, com_pipe_other = multiprocessing.Pipe ()
self.navdata = {}
self.navdata [ 0 ] = { "ctrl_state":0, "battery":0, "theta":0, "phi":0, "psi":0, "altitude":0, "vx":0, "vy":0, "vz":0, "num_frames":0 }
self.network_process = arNetwork.ARDrone2NetworkProcess ( com_pipe_other, is_ar_drone_2, self )
self.network_process.start ()
self.image = np.zeros ( self.image_shape, np.uint8 )
self.time = 0
self.last_command_is_hovering = True
time.sleep ( 1.0 )
self.at ( arATCmds.at_config_ids, self.config_ids_string )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone2::configure_multisession
# ---------------------------------------------------------------------------------------------
def configure_multisession ( self, f_session_id, f_user_id, f_app_id, f_config_ids_string ):
# sherlock logger
# l_log = logging.getLogger ( "ARDrone2::configure_multisession" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
self.at ( arATCmds.at_config, "custom:session_id", f_session_id )
self.at ( arATCmds.at_config, "custom:profile_id", f_user_id )
self.at ( arATCmds.at_config, "custom:application_id", f_app_id )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone2::set_app_id
# ---------------------------------------------------------------------------------------------
def set_app_id ( self, f_config_ids_string, f_app_id ):
# sherlock logger
# l_log = logging.getLogger ( "ARDrone2::set_app_id" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
self.at ( arATCmds.at_config_ids, f_config_ids_string )
self.at ( arATCmds.at_config, "custom:application_id", f_app_id )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone2::set_fps
# ---------------------------------------------------------------------------------------------
def set_fps ( self, f_config_ids_string, f_fps ):
# sherlock logger
# l_log = logging.getLogger ( "ARDrone2::set_fps" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
self.at ( arATCmds.at_config_ids, f_config_ids_string )
self.at ( arATCmds.at_config, "video:codec_fps", f_fps )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone2::set_max_bitrate
# ---------------------------------------------------------------------------------------------
def set_max_bitrate ( self, f_config_ids_string, f_max_bitrate ):
# sherlock logger
# l_log = logging.getLogger ( "ARDrone2::set_max_bitrate" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
self.at ( arATCmds.at_config_ids, f_config_ids_string )
self.at ( arATCmds.at_config, "video:max_bitrate", f_max_bitrate )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone2::set_profile_id
# ---------------------------------------------------------------------------------------------
def set_profile_id ( self, f_config_ids_string, f_profile_id ):
# sherlock logger
# l_log = logging.getLogger ( "ARDrone2::set_profile_id" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
self.at ( arATCmds.at_config_ids, f_config_ids_string )
self.at ( arATCmds.at_config, "custom:profile_id", f_profile_id )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone2::set_session_id
# ---------------------------------------------------------------------------------------------
def set_session_id ( self, f_config_ids_string, f_session_id ):
# sherlock logger
# l_log = logging.getLogger ( "ARDrone2::set_session_id" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
self.at ( arATCmds.at_config_ids, f_config_ids_string )
self.at ( arATCmds.at_config, "custom:session_id", f_session_id )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone2::set_video_bitrate
# ---------------------------------------------------------------------------------------------
def set_video_bitrate ( self, f_config_ids_string, f_bitrate ):
# sherlock logger
# l_log = logging.getLogger ( "ARDrone2::set_video_bitrate" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
self.at ( arATCmds.at_config_ids, f_config_ids_string )
self.at ( arATCmds.at_config, "video:bitrate", f_bitrate )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone2::set_video_bitrate_control_mode
# ---------------------------------------------------------------------------------------------
def set_video_bitrate_control_mode ( self, f_config_ids_string, f_mode ):
# sherlock logger
# l_log = logging.getLogger ( "ARDrone2::set_video_bitrate_control_mode" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
self.at ( arATCmds.at_config_ids, f_config_ids_string )
self.at ( arATCmds.at_config, "video:bitrate_control_mode", f_mode )
# sherlock logger
# l_log.debug ( "<<" )
# ---------------------------------------------------------------------------------------------
# ARDrone2::set_video_codec
# ---------------------------------------------------------------------------------------------
def set_video_codec ( self, f_config_ids_string, f_codec ):
# sherlock logger
# l_log = logging.getLogger ( "ARDrone2::set_video_codec" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
self.at ( arATCmds.at_config_ids, f_config_ids_string )
self.at ( arATCmds.at_config, "video:video_codec", f_codec )
# sherlock logger
# l_log.debug ( "<<" )
if ( "__main__" == __name__ ):
import termios
import fcntl
import os
l_fd = sys.stdin.fileno ()
l_old_term = termios.tcgetattr ( l_fd )
l_new_attr = termios.tcgetattr ( l_fd )
l_new_attr [ 3 ] = l_new_attr [ 3 ] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr ( l_fd, termios.TCSANOW, l_new_attr )
l_old_flags = fcntl.fcntl ( l_fd, fcntl.F_GETFL )
fcntl.fcntl ( l_fd, fcntl.F_SETFL, l_old_flags | os.O_NONBLOCK )
lo_drone = ARDrone ()
# assert ( lo_drone )
try:
while ( True ):
try:
lc_c = sys.stdin.read ( 1 )
lc_c = lc_c.lower ()
print "Got character", lc_c
# left ?
if ( 'a' == lc_c ):
lo_drone.move_left ()
# right ?
elif ( 'd' == lc_c ):
lo_drone.move_right ()
# forward ?
elif ( 'w' == lc_c ):
lo_drone.move_forward ()
# backward ?
elif ( 's' == lc_c ):
lo_drone.move_backward ()
# land ?
elif ( ' ' == lc_c ):
lo_drone.land ()
# takeoff ?
elif ( '\n' == lc_c ):
lo_drone.takeoff ()
# turn left ?
elif ( 'q' == lc_c ):
lo_drone.turn_left ()
# turn right ?
elif ( 'e' == lc_c ):
lo_drone.turn_right ()
# move up ?
elif ( '1' == lc_c ):
lo_drone.move_up ()
# hover ?
elif ( '2' == lc_c ):
lo_drone.hover ()
# move down ?
elif ( '3' == lc_c ):
lo_drone.move_down ()
# reset ?
elif ( 't' == lc_c ):
lo_drone.reset ()
# hover ?
elif ( 'x' == lc_c ):
lo_drone.hover ()
# trim ?
elif ( 'y' == lc_c ):
lo_drone.trim ()
except IOError:
pass
finally:
termios.tcsetattr ( l_fd, termios.TCSAFLUSH, l_old_term )
fcntl.fcntl ( l_fd, fcntl.F_SETFL, l_old_flags )
lo_drone.halt ()
|
import logging
from gettext import gettext as _
from typing import Tuple
from aai_framework.dial import ColorTxt
from aai_framework.interface import ModuleInterface
from .main import vars_, Vars
logger = logging.getLogger(__name__)
class Module(ModuleInterface):
ID = 'pkgs'
LEN_INSTALL = 2665
@property
def vars_(self) -> Vars:
return vars_
@property
def name(self) -> str:
return _('Дополнительное ПО')
@property
def menu_item(self) -> Tuple[str, str]:
text = [ColorTxt('(' + _('ВЫПОЛНЕНО') + ')').green.bold if self.is_run else '']
return super().get_menu_item(text)
|
'''This module contains helper classes for running external applications.
See L{zim.gui.applications} for classes with desktop integration for
applications defined in desktop entry files.
'''
import sys
import os
import logging
import subprocess
import gobject
import zim.fs
import zim.errors
from zim.fs import File
from zim.parsing import split_quoted_strings, is_uri_re, is_win32_path_re
from zim.environ import environ
logger = logging.getLogger('zim.applications')
def _main_is_frozen():
# Detect whether we are running py2exe compiled version
return hasattr(sys, 'frozen') and sys.frozen
class ApplicationError(zim.errors.Error):
'''Error raises for error in sub process errors'''
description = None
def __init__(self, cmd, args, retcode, stderr):
'''Constructor
@param cmd: the application command as string
@param args: tuple of arguments given to the command
@param retcode: the return code of the command (non-zero!)
@param stderr: the error output of the command
'''
self.msg = _('Failed to run application: %s') % cmd
# T: Error message when external application failed, %s is the command
self.description = \
_('%(cmd)s\nreturned non-zero exit status %(code)i') \
% {'cmd': cmd + ' "' + '" "'.join(args) + '"', 'code': retcode}
# T: Error message when external application failed, %(cmd)s is the command, %(code)i the exit code
if stderr:
self.description += '\n\n' + stderr
class Application(object):
'''Base class for objects representing an external application or
command.
@ivar name: the name of the command (default to first item of C{cmd})
@ivar cmd: the command and arguments as a tuple or a string
(when given as a string it will be parsed for quoted arguments)
@ivar tryexeccmd: the command to check in L{tryexec()}, if C{None}
fall back to first item of C{cmd}
'''
STATUS_OK = 0 #: return code when the command executed succesfully
def __init__(self, cmd, tryexeccmd=None, encoding=None):
'''Constructor
@param cmd: the command for the external application, either a
string for the command, or a tuple or list with the command
and arguments
@param tryexeccmd: command to check in L{tryexec()} as string.
If C{None} will default to C{cmd} or the first item of C{cmd}.
@param encoding: the encoding to use for commandline args
if known, else falls back to system default
'''
if isinstance(cmd, basestring):
cmd = split_quoted_strings(cmd)
else:
assert isinstance(cmd, (tuple, list))
assert tryexeccmd is None or isinstance(tryexeccmd, basestring)
self.cmd = tuple(cmd)
self.tryexeccmd = tryexeccmd
self.encoding = encoding or zim.fs.ENCODING
if self.encoding == 'mbcs':
self.encoding = 'utf-8'
def __repr__(self):
if hasattr(self, 'key'):
return '<%s: %s>' % (self.__class__.__name__, self.key)
elif hasattr(self, 'cmd'):
return '<%s: %s>' % (self.__class__.__name__, self.cmd)
else:
return '<%s: %s>' % (self.__class__.__name__, self.name)
@property
def name(self):
return self.cmd[0]
@staticmethod
def _lookup(cmd):
'''Lookup cmd in PATH'''
if zim.fs.isabs(cmd):
if zim.fs.isfile(cmd):
return cmd
else:
return None
elif os.name == 'nt':
# Check executable extensions from windows environment
extensions = environ.get_list('PATHEXT', '.com;.exe;.bat;.cmd')
for dir in environ.get_list('PATH'):
for ext in extensions:
file = os.sep.join((dir, cmd + ext))
if zim.fs.isfile(file) and os.access(file, os.X_OK):
return file
else:
return None
else:
# On POSIX no extension is needed to make scripts executable
for dir in environ.get_list('PATH'):
file = os.sep.join((dir, cmd))
if zim.fs.isfile(file) and os.access(file, os.X_OK):
return file
else:
return None
def _cmd(self, args):
# substitute args in the command - to be overloaded by child classes
if args:
return self.cmd + tuple(map(unicode, args))
else:
return self.cmd
def tryexec(self):
'''Check if the executable exists without calling it. This
method is used e.g. to decide what applications to show in the
gui. Uses the C{tryexeccmd}, or the first item of C{cmd} as the
executable name.
@returns: C{True} when the executable was found
'''
cmd = self.tryexeccmd or self.cmd[0]
return not self._lookup(cmd) is None
def _checkargs(self, cwd, args):
assert args is None or isinstance(args, (tuple, list))
argv = self._cmd(args)
# Expand home dir
if argv[0].startswith('~'):
cmd = File(argv[0]).path
argv = list(argv)
argv[0] = cmd
# if it is a python script, insert interpreter as the executable
if argv[0].endswith('.py') and not _main_is_frozen():
argv = list(argv)
argv.insert(0, sys.executable)
# TODO: consider an additional commandline arg to re-use compiled python interpreter
argv = [a.encode(self.encoding) for a in argv]
if cwd:
cwd = unicode(cwd).encode(zim.fs.ENCODING)
return cwd, argv
def run(self, args=None, cwd=None):
'''Run the application in a sub-process and wait for it to finish.
Even when the application runs successfully, any message to stderr
is logged as a warning by zim.
@param args: additional arguments to give to the command as tuple or list
@param cwd: the folder to set as working directory for the command
@raises ApplicationError: if the sub-process returned an error.
'''
cwd, argv = self._checkargs(cwd, args)
logger.info('Running: %s (cwd: %s)', argv, cwd)
if os.name == 'nt':
# http://code.activestate.com/recipes/409002/
info = subprocess.STARTUPINFO()
try:
info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
except AttributeError:
info.dwFlags |= 1 # STARTF_USESHOWWINDOW = 0x01
p = subprocess.Popen(argv,
cwd=cwd,
stdout=open(os.devnull, 'w'),
stderr=subprocess.PIPE,
startupinfo=info,
bufsize=4096,
#~ close_fds=True
)
else:
p = subprocess.Popen(argv,
cwd=cwd,
stdout=open(os.devnull, 'w'),
stderr=subprocess.PIPE,
bufsize=4096,
close_fds=True
)
stdout, stderr = p.communicate()
if not p.returncode == self.STATUS_OK:
raise ApplicationError(argv[0], argv[1:], p.returncode, stderr)
#~ elif stderr:
#~ logger.warn(stderr)
def pipe(self, args=None, cwd=None, input=None):
'''Run the application in a sub-process and capture the output.
Like L{run()}, but connects to stdin and stdout for the sub-process.
@note: The data read is buffered in memory, so do not use this
method if the data size is large or unlimited.
@param args: additional arguments to give to the command as tuple or list
@param cwd: the folder to set as working directory for the command
@param input: input for the command as string
@returns: output as a list of lines
@raises ApplicationError: if the sub-process returned an error.
'''
cwd, argv = self._checkargs(cwd, args)
logger.info('Running: %s (cwd: %s)', argv, cwd)
p = subprocess.Popen(argv, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate(input)
# TODO: handle ApplicationERror here as well ?
#~ if not p.returncode == self.STATUS_OK:
#~ raise ApplicationError(argv[0], argv[1:], p.returncode, stderr)
#~ elif stderr:
if stderr:
logger.warn(stderr)
# TODO: allow user to get this error as well - e.g. for logging image generator cmd
# Explicit newline conversion, e.g. on windows \r\n -> \n
# FIXME Assume local encoding is respected (!?)
text = [unicode(line + '\n', errors='replace') for line in stdout.splitlines()]
if text and text[-1].endswith('\n') and not stdout.endswith('\n'):
text[-1] = text[-1][:-1] # strip additional \n
return text
def spawn(self, args=None, callback=None, data=None, cwd=None):
'''Start the application in the background and return immediately.
This is used to start an external in parallel with zim that is
not expected to exit immediatly, so we do not want to wait for
it - e.g. a webbrowser to show an URL that was clicked.
@param args: additional arguments to give to the command as tuple or list
@param callback: optional callback can be used to trigger when
the application exits. The signature is::
callback(status, data)
where 'C{status}' is the exit status of the process. The
application object provides a constant 'C{STATUS_OK}' which can
be used to test if the application was successful or not.
@param data: additional data for the callback
@param cwd: the folder to set as working directory for the command
@returns: the PID for the new process
'''
cwd, argv = self._checkargs(cwd, args)
opts = {}
flags = gobject.SPAWN_SEARCH_PATH
if callback:
flags |= gobject.SPAWN_DO_NOT_REAP_CHILD
# without this flag child is reaped automatically -> no zombies
if not cwd:
cwd = os.getcwd()
logger.info('Spawning: %s (cwd: %s)', argv, cwd)
try:
pid, stdin, stdout, stderr = \
gobject.spawn_async(argv, flags=flags, working_directory=cwd, **opts)
except gobject.GError:
from zim.gui.widgets import ErrorDialog
ErrorDialog(None, _('Failed running: %s') % argv[0]).run()
#~ # T: error when application failed to start
return None
else:
logger.debug('Process started with PID: %i', pid)
if callback:
# child watch does implicit reaping -> no zombies
if data is None:
gobject.child_watch_add(pid,
lambda pid, status: callback(status))
else:
gobject.child_watch_add(pid,
lambda pid, status, data: callback(status, data), data)
return pid
class WebBrowser(Application):
'''Application wrapper for the C{webbrowser} module. Can be used as
fallback if no webbrowser is configured.
'''
name = _('Default') + ' (webbrowser)' # T: label for default webbrowser
key = 'webbrowser' # Used by zim.gui.applications
def __init__(self, encoding=None):
import webbrowser
self.controller = None
try:
self.controller = webbrowser.get()
except webbrowser.Error:
pass # webbrowser throws an error when no browser is found
self.encoding = encoding or zim.fs.ENCODING
if self.encoding == 'mbcs':
self.encoding = 'utf-8'
def tryexec(self):
return not self.controller is None
def run(self, args):
'''This method is not supported by this class
@raises NotImplementedError: always
'''
raise NotImplementedError('WebBrowser can not run in foreground')
def spawn(self, args, callback=None):
if callback:
raise NotImplementedError('WebBrowser can not handle callback')
for url in args:
if isinstance(url, (zim.fs.File, zim.fs.Dir)):
url = url.uri
url = url.encode(self.encoding)
logger.info('Opening in webbrowser: %s', url)
self.controller.open(url)
class StartFile(Application):
'''Application wrapper for C{os.startfile()}. Can be used on
windows to open files and URLs with the default application.
'''
name = _('Default') + ' (os)' # T: label for default application
key = 'startfile' # Used by zim.gui.applications
def __init__(self):
pass
def tryexec(self):
return hasattr(os, 'startfile')
def run(self, args):
'''This method is not supported by this class
@raises NotImplementedError: always
'''
raise NotImplementedError('StartFile can not run in foreground')
def spawn(self, args, callback=None):
if callback:
logger.warn('os.startfile does not support a callback')
for arg in args:
if isinstance(arg, (zim.fs.File, zim.fs.Dir)):
path = os.path.normpath(arg.path)
elif is_uri_re.match(arg) and not is_win32_path_re.match(arg):
# URL or e.g. mailto: or outlook: URI
path = unicode(arg)
else:
# must be file
path = os.path.normpath(unicode(arg))
logger.info('Opening with os.startfile: %s', path)
os.startfile(path)
|
"""
/***************************************************************************
QuickMapServices
A QGIS plugin
Collection of internet map services
-------------------
begin : 2014-11-21
git sha : $Format:%H$
copyright : (C) 2014 by NextGIS
email : info@nextgis.com
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
from __future__ import absolute_import
import codecs
import os
import sys
from qgis.PyQt.QtCore import QCoreApplication
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QMenu
from qgis.core import QgsMessageLog
from .config_reader_helper import ConfigReaderHelper
from . import extra_sources
from .custom_translator import CustomTranslator
from .group_info import GroupInfo, GroupCategory
from .plugin_locale import Locale
from .compat import configparser, get_file_dir
from .compat2qgis import message_log_levels
CURR_PATH = get_file_dir(__file__)
INTERNAL_GROUP_PATHS = [os.path.join(CURR_PATH, extra_sources.GROUPS_DIR_NAME), ]
CONTRIBUTE_GROUP_PATHS = [os.path.join(extra_sources.CONTRIBUTE_DIR_PATH, extra_sources.GROUPS_DIR_NAME), ]
USER_GROUP_PATHS = [os.path.join(extra_sources.USER_DIR_PATH, extra_sources.GROUPS_DIR_NAME), ]
ALL_GROUP_PATHS = INTERNAL_GROUP_PATHS + CONTRIBUTE_GROUP_PATHS + USER_GROUP_PATHS
ROOT_MAPPING = {
INTERNAL_GROUP_PATHS[0]: GroupCategory.BASE,
CONTRIBUTE_GROUP_PATHS[0]: GroupCategory.CONTRIB,
USER_GROUP_PATHS[0]: GroupCategory.USER
}
class GroupsList(object):
def __init__(self, group_paths=ALL_GROUP_PATHS):
self.locale = Locale.get_locale()
self.translator = CustomTranslator()
self.paths = group_paths
self.groups = {}
self._fill_groups_list()
def _fill_groups_list(self):
self.groups = {}
for gr_path in self.paths:
if gr_path in ROOT_MAPPING.keys():
category = ROOT_MAPPING[gr_path]
else:
category = GroupCategory.USER
for root, dirs, files in os.walk(gr_path):
for ini_file in [f for f in files if f.endswith('.ini')]:
self._read_ini_file(root, ini_file, category)
def _read_ini_file(self, root, ini_file_path, category):
try:
ini_full_path = os.path.join(root, ini_file_path)
parser = configparser.ConfigParser()
with codecs.open(ini_full_path, 'r', 'utf-8') as ini_file:
if hasattr(parser, "read_file"):
parser.read_file(ini_file)
else:
parser.readfp(ini_file)
#read config
group_id = parser.get('general', 'id')
group_alias = parser.get('ui', 'alias')
icon_file = ConfigReaderHelper.try_read_config(parser, 'ui', 'icon')
group_icon_path = os.path.join(root, icon_file) if icon_file else None
#try read translations
posible_trans = parser.items('ui')
for key, val in posible_trans:
if type(key) is unicode and key == 'alias[%s]' % self.locale:
self.translator.append(group_alias, val)
break
#create menu
group_menu = QMenu(self.tr(group_alias))
group_menu.setIcon(QIcon(group_icon_path))
#append to all groups
# set contrib&user
self.groups[group_id] = GroupInfo(group_id, group_alias, group_icon_path, ini_full_path, group_menu, category)
except Exception as e:
error_message = self.tr('Group INI file can\'t be parsed: ') + e.message
QgsMessageLog.logMessage(error_message, level=message_log_levels["Critical"])
def get_group_menu(self, group_id):
if group_id in self.groups:
return self.groups[group_id].menu
else:
info = GroupInfo(group_id=group_id, menu=QMenu(group_id))
self.groups[group_id] = info
return info.menu
# noinspection PyMethodMayBeStatic
def tr(self, message):
# noinspection PyTypeChecker,PyArgumentList,PyCallByClass
return self.translator.translate('QuickMapServices', message)
|
import fauxfactory
import pytest
from cfme import test_requirements
from cfme.control.explorer.policies import VMControlPolicy
from cfme.infrastructure.provider.virtualcenter import VMwareProvider
from cfme.markers.env_markers.provider import ONE_PER_TYPE
from cfme.services.myservice import MyService
from cfme.utils.appliance.implementations.ui import navigate_to
from cfme.utils.conf import cfme_data
from cfme.utils.conf import credentials
from cfme.utils.update import update
from cfme.utils.wait import wait_for
pytestmark = [
pytest.mark.ignore_stream("upstream"),
pytest.mark.long_running,
pytest.mark.provider([VMwareProvider], selector=ONE_PER_TYPE, scope="module"),
test_requirements.ansible,
]
@pytest.fixture(scope="module")
def wait_for_ansible(appliance):
appliance.server.settings.enable_server_roles("embedded_ansible")
appliance.wait_for_embedded_ansible()
yield
appliance.server.settings.disable_server_roles("embedded_ansible")
@pytest.fixture(scope="module")
def ansible_repository(appliance, wait_for_ansible):
repositories = appliance.collections.ansible_repositories
try:
repository = repositories.create(
name=fauxfactory.gen_alpha(),
url=cfme_data.ansible_links.playbook_repositories.embedded_ansible,
description=fauxfactory.gen_alpha())
except KeyError:
pytest.skip("Skipping since no such key found in yaml")
view = navigate_to(repository, "Details")
wait_for(
lambda: view.entities.summary("Properties").get_text_of("Status") == "successful",
timeout=60,
fail_func=view.toolbar.refresh.click
)
yield repository
repository.delete_if_exists()
@pytest.fixture(scope="module")
def ansible_catalog_item(appliance, ansible_repository):
cat_item = appliance.collections.catalog_items.create(
appliance.collections.catalog_items.ANSIBLE_PLAYBOOK,
fauxfactory.gen_alphanumeric(),
fauxfactory.gen_alphanumeric(),
display_in_catalog=True,
provisioning={
"repository": ansible_repository.name,
"playbook": "dump_all_variables.yml",
"machine_credential": "CFME Default Credential",
"create_new": True,
"provisioning_dialog_name": fauxfactory.gen_alphanumeric()
}
)
yield cat_item
cat_item.delete_if_exists()
@pytest.fixture(scope="module")
def ansible_action(appliance, ansible_catalog_item):
action_collection = appliance.collections.actions
action = action_collection.create(
fauxfactory.gen_alphanumeric(),
action_type="Run Ansible Playbook",
action_values={
"run_ansible_playbook": {
"playbook_catalog_item": ansible_catalog_item.name
}
}
)
yield action
action.delete_if_exists()
@pytest.fixture(scope="module")
def policy_for_testing(appliance, full_template_vm_modscope, provider, ansible_action):
vm = full_template_vm_modscope
policy = appliance.collections.policies.create(
VMControlPolicy,
fauxfactory.gen_alpha(),
scope="fill_field(VM and Instance : Name, INCLUDES, {})".format(vm.name)
)
policy.assign_actions_to_event("Tag Complete", [ansible_action.description])
policy_profile = appliance.collections.policy_profiles.create(
fauxfactory.gen_alpha(), policies=[policy])
provider.assign_policy_profiles(policy_profile.description)
yield
if policy.exists:
policy.assign_events()
provider.unassign_policy_profiles(policy_profile.description)
policy_profile.delete()
policy.delete()
@pytest.fixture(scope="module")
def ansible_credential(wait_for_ansible, appliance, full_template_modscope):
credential = appliance.collections.ansible_credentials.create(
fauxfactory.gen_alpha(),
"Machine",
username=credentials[full_template_modscope.creds]["username"],
password=credentials[full_template_modscope.creds]["password"]
)
yield credential
credential.delete_if_exists()
@pytest.fixture
def service_request(appliance, ansible_catalog_item):
request_desc = "Provisioning Service [{0}] from [{0}]".format(ansible_catalog_item.name)
_service_request = appliance.collections.requests.instantiate(request_desc)
yield _service_request
_service_request.delete_if_exists()
@pytest.fixture
def service(appliance, ansible_catalog_item):
service_ = MyService(appliance, ansible_catalog_item.name)
yield service_
if service_.exists:
service_.delete()
@pytest.mark.tier(3)
def test_action_run_ansible_playbook_localhost(request, ansible_catalog_item, ansible_action,
policy_for_testing, full_template_vm_modscope, ansible_credential, service_request,
service):
"""Tests a policy with ansible playbook action against localhost.
Polarion:
assignee: sbulage
initialEstimate: 1/6h
casecomponent: Ansible
"""
with update(ansible_action):
ansible_action.run_ansible_playbook = {"inventory": {"localhost": True}}
added_tag = full_template_vm_modscope.add_tag()
request.addfinalizer(lambda: full_template_vm_modscope.remove_tag(added_tag))
wait_for(service_request.exists, num_sec=600)
service_request.wait_for_request()
view = navigate_to(service, "Details")
assert view.provisioning.details.get_text_of("Hosts") == "localhost"
assert view.provisioning.results.get_text_of("Status") == "successful"
@pytest.mark.tier(3)
def test_action_run_ansible_playbook_manual_address(request, ansible_catalog_item, ansible_action,
policy_for_testing, full_template_vm_modscope, ansible_credential, service_request,
service):
"""Tests a policy with ansible playbook action against manual address.
Polarion:
assignee: sbulage
initialEstimate: 1/6h
casecomponent: Ansible
"""
vm = full_template_vm_modscope
with update(ansible_catalog_item):
ansible_catalog_item.provisioning = {"machine_credential": ansible_credential.name}
with update(ansible_action):
ansible_action.run_ansible_playbook = {
"inventory": {
"specific_hosts": True,
"hosts": vm.ip_address
}
}
added_tag = vm.add_tag()
request.addfinalizer(lambda: vm.remove_tag(added_tag))
wait_for(service_request.exists, num_sec=600)
service_request.wait_for_request()
view = navigate_to(service, "Details")
assert view.provisioning.details.get_text_of("Hosts") == vm.ip_address
assert view.provisioning.results.get_text_of("Status") == "successful"
@pytest.mark.tier(3)
def test_action_run_ansible_playbook_target_machine(request, ansible_catalog_item, ansible_action,
policy_for_testing, full_template_vm_modscope, ansible_credential, service_request,
service):
"""Tests a policy with ansible playbook action against target machine.
Polarion:
assignee: sbulage
initialEstimate: 1/6h
casecomponent: Ansible
"""
vm = full_template_vm_modscope
with update(ansible_action):
ansible_action.run_ansible_playbook = {"inventory": {"target_machine": True}}
added_tag = vm.add_tag()
request.addfinalizer(lambda: vm.remove_tag(added_tag))
wait_for(service_request.exists, num_sec=600)
service_request.wait_for_request()
view = navigate_to(service, "Details")
assert view.provisioning.details.get_text_of("Hosts") == vm.ip_address
assert view.provisioning.results.get_text_of("Status") == "successful"
@pytest.mark.tier(3)
def test_action_run_ansible_playbook_unavailable_address(request, ansible_catalog_item,
full_template_vm_modscope, ansible_action, policy_for_testing, ansible_credential,
service_request, service):
"""Tests a policy with ansible playbook action against unavailable address.
Polarion:
assignee: sbulage
initialEstimate: 1/6h
casecomponent: Ansible
"""
vm = full_template_vm_modscope
with update(ansible_catalog_item):
ansible_catalog_item.provisioning = {"machine_credential": ansible_credential.name}
with update(ansible_action):
ansible_action.run_ansible_playbook = {
"inventory": {
"specific_hosts": True,
"hosts": "unavailable_address"
}
}
added_tag = vm.add_tag()
request.addfinalizer(lambda: vm.remove_tag(added_tag))
wait_for(service_request.exists, num_sec=600)
service_request.wait_for_request()
view = navigate_to(service, "Details")
assert view.provisioning.details.get_text_of("Hosts") == "unavailable_address"
assert view.provisioning.results.get_text_of("Status") == "failed"
@pytest.mark.tier(3)
def test_control_action_run_ansible_playbook_in_requests(request,
full_template_vm_modscope, policy_for_testing, service_request):
"""Checks if execution of the Action result in a Task/Request being created.
Polarion:
assignee: sbulage
initialEstimate: 1/6h
casecomponent: Ansible
"""
vm = full_template_vm_modscope
added_tag = vm.add_tag()
request.addfinalizer(lambda: vm.remove_tag(added_tag))
assert service_request.exists
|
import numpy
import re
def parseFLATBuffer(buf, index=True):
"""
Parse FLAT buffer and return the structured data
"""
sections_list = []
section = None
activesection = None
# Pick appropriate return format
sections = None
if index:
sections = {}
else:
sections = []
# Start processing the buffer line-by-line
for line in buf.splitlines():
# Process lines
if not line:
# Empty line
pass
elif "# BEGIN " in line:
# Ignore labels found some times in AIDA files
dat = line.split(" ")
section = dat[2]
sectiontype = 0
# Get additional section title
title = ""
if len(dat) > 3:
title = " ".join(dat[3:])
# Allocate section record
activesection = { "d": { }, "v": [ ], "t": title }
elif ("# END " in line) and (section != None):
# Section end
if index:
sections[section] = activesection
else:
activesection['n'] = section
sections.append(activesection)
section = None
elif line.startswith("#") or line.startswith(";"):
# Comment
pass
elif section:
# Data inside section
# "SPECIAL" section is not parsable here
if section == "SPECIAL":
continue
# Try to split
data = line.split("=",1)
# Could not split : They are histogram data
if len(data) == 1:
# Split data values
data = FLATParser.WHITESPACE.split(line.strip())
# Check for faulty values
if len(data) < 3:
continue
# Otherwise collect
activesection['v'].append( numpy.array(data, dtype=numpy.float64) )
else:
# Store value
activesection['d'][data[0]] = data[1]
# Return sections
return sections
class FLATParser:
"""
Simple function to parser histograms in FLAT format
"""
# Precompiled regex entry
WHITESPACE = re.compile("\s+")
@staticmethod
def parseFileObject(fileobject, index=True):
"""
Function to read a FLAT file (by the file object descriptor) into python structures
"""
# Read entire file and use parseBuffer
return parseFLATBuffer(fileobject.read(), index)
@staticmethod
def parse(filename, index=True):
"""
Function to read a FLAT file into python structures
"""
# Open file
with open(filename, 'r') as f:
# Use FileObject parser to read the file
return parseFLATBuffer(f.read(), index)
def parseBuffer(buf, index=True):
"""
Parse FLAT file from buffer
"""
return parseFLATBuffer(buf, index)
|
ERROR_AUTH_FAILED = "Authorization failed"
NO_SUCH_BACKEND = "No such backend"
REDIRECTION_FAILED = "Redirection failed"
|
corto = 10
largo = long(corto)
print type(corto)
print type(largo)
|
import sys
import getopt
import collections
import binascii
import hashlib
import itertools
verbose_opt = False
decrypt_opt = False
key_phrase = '' # clear text key phrase
key_hashed = '' # hashed key phrase
clear_text = '' # starting message input
pigpen_message = '' # message after pigpen stage
encrypted_message = '' # the encrypted message
decrypted_message = '' # the decrypted message
pigpen_A = {'A':'ETL', 'B':'ETM', 'C':'ETR', 'D':'EML', 'E':'EMM', 'F':'EMR', 'G':'EBL', 'H':'EBM', 'I':'EBR', 'J':'DTL',
'K':'DTM', 'L':'DTR', 'M':'DML', 'N':'DMM', 'O':'DMR', 'P':'DBL', 'Q':'DBM', 'R':'DBR', 'S':'EXT', 'T':'EXL', 'U':'EXR',
'V':'EXB', 'W':'DXT', 'X':'DXL', 'Y':'DXR', 'Z':'DXB', ' ':'EPS', '.':'EPF', ',':'EPC', '!':'EPE', '?':'EPQ', '"':'EPD',
'@':'EPA','0':'NTL', '1':'NTM', '2':'NTR', '3':'NML', '4':'NMM', '5':'NMR', '6':'NBL', '7':'NBM', '8':'NBR','9':'NXT'}
pigpen_B = {'C':'ETL', 'D':'ETM', 'A':'ETR', 'B':'EML', 'G':'EMM', 'H':'EMR', 'E':'EBL', 'F':'EBM', 'K':'EBR', 'L':'DTL',
'I':'DTM', 'J':'DTR', 'O':'DML', 'P':'DMM', 'M':'DMR', 'N':'DBL', 'S':'DBM', 'T':'DBR', 'Q':'EXT', 'R':'EXL', 'W':'EXR',
'X':'EXB', 'U':'DXT', 'V':'DXL', ' ':'DXR', ',':'DXB', 'Y':'EPS', '!':'EPF', 'Z':'EPC', '.':'EPE', '@':'EPQ', '0':'EPD',
'?':'EPA','"':'NTL', '3':'NTM', '4':'NTR', '1':'NML', '2':'NMM', '7':'NMR', '8':'NBL', '9':'NBM', '5':'NBR', '6':'NXT'}
pigpen_C = {'K':'ETL', 'L':'ETM', 'M':'ETR', 'N':'EML', 'O':'EMM', 'P':'EMR', 'Q':'EBL', 'R':'EBM', 'S':'EBR', 'U':'DTL',
'V':'DTM', 'W':'DTR', 'X':'DML', 'Y':'DMM', 'Z':'DMR', ' ':'DBL', '.':'DBM', ',':'DBR', '!':'EXT', '"':'EXL', '?':'EXR',
'@':'EXB', '0':'DXT', '1':'DXL', '2':'DXR', '3':'DXB', '4':'EPS', '5':'EPF', '6':'EPC', '7':'EPE', '8':'EPQ', '9':'EPD',
'A':'EPA','B':'NTL', 'C':'NTM', 'D':'NTR', 'E':'NML', 'F':'NMM', 'G':'NMR', 'H':'NBL', 'I':'NBM', 'J':'NBR','T':'NXT'}
def keyGenerate():
global key_hashed
# create the hashes of the key phrase string
md5_hash = hashlib.md5(key_phrase.encode())
sha256_hash = hashlib.sha256(key_phrase.encode())
sha512_hash = hashlib.sha512(key_phrase.encode())
# concatenate the hash digests into one key
key_hashed = md5_hash.hexdigest() + sha256_hash.hexdigest() + sha512_hash.hexdigest()
# hash the entire key (so far) one more time and concatenate to make 1024bit key
key_hashed_hash = hashlib.md5(key_hashed.encode())
key_hashed += key_hashed_hash.hexdigest()
# vebose mode if verbose option is set
if verbose_opt:
print("[KEY GENERATION]: The key phrase is: \"" + key_phrase + "\"")
print("[KEY GENERATION]: \"" + key_phrase + "\" is independantly hashed 3 times using MD5, SHA256 and SHA512")
print("[KEY GENERATION]: The 3 hashes are concatenated with 1 more md5 hash, resulting in the 1024bit key:")
print("[KEY GENERATION]: \"" + key_hashed + "\"\n")
return
def selectDict():
# sum ASCII value of each character in the clear text key phrase
ascii_total = 0
for x in key_phrase:
ascii_total += ord(x)
# modulo 3 ascii_total to find 0-3 result to select pigpen dict
if ascii_total % 3 == 0:
pigpen_dict = pigpen_A
elif ascii_total % 3 == 1:
pigpen_dict = pigpen_B
elif ascii_total % 3 == 2:
pigpen_dict = pigpen_C
# return the dictionary
return pigpen_dict
def pigpenForward():
global pigpen_message
# convert clear message to uppercase
message = clear_text.upper()
# itterate through dict looking for chars
for letter in message:
if letter in selectDict():
pigpen_message += selectDict().get(letter)
# verbose mode if verbose option is set
if verbose_opt:
print("[ENCRYPTION - Phase 1]: The clear text is:")
print("[ENCRYPTION - Phase 1]: \"" + clear_text + "\"")
print("[ENCRYPTION - Phase 1]: 1 of 3 dictionaries is derived from the sum of the pre-hashed key ASCII values (mod 3)")
print("[ENCRYPTION - Phase 1]: The clear text is converted into pigpen cipher text using the selected dictionary:")
print("[ENCRYPTION - Phase 1]: \"" + pigpen_message + "\"\n")
return
def pigpenBackward():
global decrypted_message
# convert encrypted message (int array) back to a single ascii string
message = ''
try:
for i in decrypted_message:
message += chr(i)
except:
print("[ERROR]: Incorrect key. Cannot decrypt.")
usageText()
# retrieve each 3 chars (one pigpen value) and form a list
message_list = [message[i:i+3] for i in range(0, len(message), 3)]
# zero out decrypted message string in order to store pigpen deciphered characters
decrypted_message = ''
# itterate through list elements and compare against pigpen dict
# to find correct key (clear text letter) and create decrypted string
for element in message_list:
for key, value in selectDict().iteritems():
if value == element:
decrypted_message += key
# verbose mode if verbose option is set
if verbose_opt:
print("[DECRYPTION - Phase 3]: 1 of 3 dictionaries is derived from the sum of the pre-hashed key ASCII values (mod 3)")
print("[DECRYPTION - Phase 3]: The values of the pigpen cipher text are looked up in the selected dictionary")
print("[DECRYPTION - Phase 3]: The pigpen cipher text is converted back into clear text:\n")
print("[DECRYPTION - COMPLETE]: \"" + decrypted_message + "\"\n")
return
def keyConfusion(message):
# create array of base10 ints from ascii values of chars in hashed key
key = []
for x in key_hashed:
key.append(ord(x))
# create a variable for cycling through the key array (in case the message is longer than key)
key_cycle = itertools.cycle(key)
# loop through the key and XOR the resultant value with the corresponding value in the message
for i in range(len(message)):
# find the value pointed to by the value of each element of the key (for each value in the message array)
key_pointer = key_cycle.next() % 128 # get the next key byte. mod 128 because 128 bytes in 1024bits
key_byte = key[key_pointer]
# XOR message byte with current key_byte
message[i] = message[i] ^ key_byte
# XOR message byte with the key byte pointed to by previous key byte value
key_byte = key[(key_byte % 128)]
message[i] = message[i] ^ key_byte
# once again XOR message byte with the next key byte pointed to by previous key byte value
key_byte = key[(key_byte % 128)]
message[i] = message[i] ^ key_byte
# verbose mode if verbose option is set
if verbose_opt:
# are we decrypting or encrypting?
if decrypt_opt:
en_or_de = "[DECRYPTION - Phase 2]: "
en_or_de_text = " pigpen cipher text:"
else:
en_or_de = "[ENCRYPTION - Phase 2]: "
en_or_de_text = " partially encrypted string:"
# print the appropriate output for encrypting or decrypting
print(en_or_de + "Each byte of the pigpen cipher is then XOR'ed against 3 bytes of the key")
print(en_or_de + "The key byte is XOR'ed against the byte of the message and then used to select the")
print(en_or_de + "position in the key array of the next key byte value. This occurs three times.")
print(en_or_de + "Resulting in the" + en_or_de_text)
print(en_or_de + "\"" + message + "\"\n")
return message
def xorForward():
global encrypted_message
# convert key and message into ints for xoring
message = bytearray(pigpen_message)
key = bytearray(key_hashed)
# send pigpen message off for permution
message = keyConfusion(message)
# iterate over message and xor each character against each value in the key
for x in range(len(message)):
for y in range(len(key)):
xored = key[y] ^ message[x]
message[x] = xored
# store hex value of encrypted string in global variable
encrypted_message = binascii.hexlify(bytearray(message))
# verbose mode is verbose option is set
if verbose_opt:
print("[ENCRYPTION - Phase 3]: The partially encrypted cipher text and key are converted into a byte arrays")
print("[ENCRYPTION - Phase 3]: Each byte of the message is XOR'ed against each byte of the key")
print("[ENCRYPTION - Phase 3]: Resulting in the cipher text hex string:\n")
print("[ENCRYPTION - COMPLETE]: \"" + encrypted_message + "\"\n")
return
def xorBackward():
global decrypted_message
# create byte array for key and to store decrypted message
reverse_key = key_hashed[::-1]
key = bytearray(reverse_key)
# try to convert the encrypted message from hex to int, error if incorrect string
try:
message = bytearray(binascii.unhexlify(clear_text))
except:
print("[ERROR]: Incorrect string. Cannot decrypt.")
usageText()
# iterate over the encrypted message and xor each value against each value in the key
for x in range(len(message)):
for y in range(len(key)):
xored = key[y] ^ message[x]
message[x] = xored
# verbose mode is verbose option is set
if verbose_opt:
print("[DECRYPTION - Phase 1]: The cipher text is:")
print("[DECRYPTION - Phase 1]: \"" + clear_text + "\"")
print("[DECRYPTION - Phase 1]: The cipher text and key are converted into a byte arrays")
print("[DECRYPTION - Phase 1]: The key is reversed in order to reverse this stage of XOR'ing")
print("[DECRYPTION - Phase 1]: Each byte of the cipher text is XOR'ed against each byte of the key")
print("[DECRYPTION - Phase 1]: Resulting in the partially decrypted string:")
print("[DECRYPTION - Phase 1]: \"" + message + "\"\n")
# send decrypted array off for permutation (reverse encrypted XOR'ing)
decrypted_message = keyConfusion(message)
return
def usageText():
print("\n[USAGE]: franken.py -v (verbose) -d (decrypt) --keyphrase (-k) <phrase> --message (-m) <message to encrypt>")
print("[USAGE]: -v and -d arguments are optional. --keyphrase(-k) and --message(-m) are required")
print("\n[EXAMPLE]: python franken.py -v --keyphrase \"super secret\" --message \"This is a super secret message\"\n")
print("[!] As with any cipher, your message is only as secure as your key phrase.")
print("[!] REMEMBER: The more complicated your key phrase, the stronger your encrypted message will be!\n")
sys.exit(2)
if len(sys.argv) < 2:
usageText()
try:
opts, args = getopt.getopt(sys.argv[1:], 'vdk:m:', ["verbose", "decrypt", "keyphrase=", "message="])
except getopt.GetoptError:
usageText()
for opt, arg in opts:
if opt == '-v':
verbose_opt = True
if opt == '-d':
decrypt_opt = True
if opt in ('-k', '--keyphrase'):
key_phrase = arg
if opt in ('-m', '--message'):
clear_text = arg
if not key_phrase or not clear_text:
usageText()
print(
'''
__ _
/ _| | |
| |_ _ __ __ _ _ __ | | _____ _ __
| _| '__/ _` | '_ \| |/ / _ \ '_ \
| | | | | (_| | | | | < __/ | | |
|_| |_| \__,_|_| |_|_|\_\___|_| |_|
_ _
__(_)_ __| |_ ___ _ _
/ _| | '_ \ ' \/ -_) '_|
\__|_| .__/_||_\___|_|
|_|
[!] franken.py
An encryption algorithm inspired by a number of existing ciphers.
Created for CC6004 Course Work 1. 2016/17
[@] Dan C and james@forscience.xyz
__________________________________________________
'''
)
if decrypt_opt:
keyGenerate()
xorBackward()
pigpenBackward()
if not verbose_opt:
print("[DECRYPTED]: " + decrypted_message + "\n")
else:
keyGenerate()
pigpenForward()
xorForward()
if not verbose_opt:
print("[ENCRYPTED]: " + encrypted_message + "\n")
|
from distutils.core import setup
setup(
name="flowtools",
description="Tools for flow maps from modified Gromacs simulations",
long_description="See README.md",
license='GPLv3',
version='0.2.30',
url="https://github.com/pjohansson/flowtools",
author="Petter Johansson",
author_email="petter.johansson@scilifelab.se",
packages=['flowtools'],
requires=[
'numpy (>=1.7.0)',
'matplotlib (>=1.2.0)',
'pandas (>=0.10.1)',
'scipy (>=0.11.0)'
],
scripts=[
'scripts/f_collect_spread.py',
'scripts/f_combine_maps.py',
'scripts/f_flowmaps.py',
'scripts/f_print.py',
'scripts/f_spread_delta_t.py',
'scripts/f_spread_plot.py',
'scripts/f_spread_ttest.py',
'scripts/f_spread_com.py',
'scripts/f_spread_std.py',
'scripts/f_velprofile.py',
'scripts/f_average_maps.py',
'scripts/f_spread_vel.py',
'scripts/f_combine_cells.py',
'scripts/f_viscous_dissipation.py',
'scripts/f_interface.py',
'scripts/f_shearmax.py',
'scripts/f_contactline.py'
]
)
|
__productname__ = 'dotinstall'
__version__ = '0.1'
__copyright__ = "Copyright (C) 2014 Cinghio Pinghio"
__author__ = "Cinghio Pinghio"
__author_email__ = "cinghio@linuxmail.org"
__description__ = "Install dotfiles"
__long_description__ = "Install dofile based on some rules"
__url__ = "cinghiopinghio...."
__license__ = "Licensed under the GNU GPL v3+."
|
__all__ = ['appie.appie', 'appie.extensions']
from appie.appie import *
from appie.extensions import *
|
from django.contrib.auth.models import User
from django.views.generic.edit import CreateView, FormView
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.core.context_processors import csrf
from django.http import HttpResponse, JsonResponse
from django.contrib.auth.decorators import login_required
def test_page(request):
return render(request, "test.html")
|
"""Pacman-Mirrors Translation Module"""
import os
import sys
import locale
import gettext
APP_NAME = "pacman_mirrors"
APP_DIR = os.path.join(sys.prefix, "share")
LOCALE_DIR = os.path.join(APP_DIR, "locale")
CODESET = "utf-8"
LANGUAGES = []
try:
user_locale = locale.getdefaultlocale()[0]
if user_locale:
LANGUAGES += user_locale
except ValueError:
pass
LANGUAGES += os.environ.get("LANGUAGE", "").split(":")
LANGUAGES += ["en_US"]
gettext.install(True)
gettext.bindtextdomain(APP_NAME, LOCALE_DIR)
gettext.bind_textdomain_codeset(APP_NAME, codeset=CODESET)
gettext.textdomain(APP_NAME)
language = gettext.translation(APP_NAME, LOCALE_DIR, LANGUAGES, fallback=True)
|
"""A QProcess which shows notifications in the GUI."""
import locale
import shlex
from PyQt5.QtCore import (pyqtSlot, pyqtSignal, QObject, QProcess,
QProcessEnvironment)
from qutebrowser.utils import message, log, utils
from qutebrowser.browser import qutescheme
class GUIProcess(QObject):
"""An external process which shows notifications in the GUI.
Args:
cmd: The command which was started.
args: A list of arguments which gets passed.
verbose: Whether to show more messages.
_output_messages: Show output as messages.
_started: Whether the underlying process is started.
_proc: The underlying QProcess.
_what: What kind of thing is spawned (process/editor/userscript/...).
Used in messages.
Signals:
error/finished/started signals proxied from QProcess.
"""
error = pyqtSignal(QProcess.ProcessError)
finished = pyqtSignal(int, QProcess.ExitStatus)
started = pyqtSignal()
def __init__(self, what, *, verbose=False, additional_env=None,
output_messages=False, parent=None):
super().__init__(parent)
self._what = what
self.verbose = verbose
self._output_messages = output_messages
self._started = False
self.cmd = None
self.args = None
self._proc = QProcess(self)
self._proc.errorOccurred.connect(self._on_error)
self._proc.errorOccurred.connect(self.error)
self._proc.finished.connect(self._on_finished)
self._proc.finished.connect(self.finished)
self._proc.started.connect(self._on_started)
self._proc.started.connect(self.started)
if additional_env is not None:
procenv = QProcessEnvironment.systemEnvironment()
for k, v in additional_env.items():
procenv.insert(k, v)
self._proc.setProcessEnvironment(procenv)
@pyqtSlot(QProcess.ProcessError)
def _on_error(self, error):
"""Show a message if there was an error while spawning."""
if error == QProcess.Crashed and not utils.is_windows:
# Already handled via ExitStatus in _on_finished
return
msg = self._proc.errorString()
message.error("Error while spawning {}: {}".format(self._what, msg))
@pyqtSlot(int, QProcess.ExitStatus)
def _on_finished(self, code, status):
"""Show a message when the process finished."""
self._started = False
log.procs.debug("Process finished with code {}, status {}.".format(
code, status))
encoding = locale.getpreferredencoding(do_setlocale=False)
stderr = self._proc.readAllStandardError().data().decode(
encoding, 'replace')
stdout = self._proc.readAllStandardOutput().data().decode(
encoding, 'replace')
if self._output_messages:
if stdout:
message.info(stdout.strip())
if stderr:
message.error(stderr.strip())
if status == QProcess.CrashExit:
exitinfo = "{} crashed.".format(self._what.capitalize())
message.error(exitinfo)
elif status == QProcess.NormalExit and code == 0:
exitinfo = "{} exited successfully.".format(
self._what.capitalize())
if self.verbose:
message.info(exitinfo)
else:
assert status == QProcess.NormalExit
# We call this 'status' here as it makes more sense to the user -
# it's actually 'code'.
exitinfo = ("{} exited with status {}, see :messages for "
"details.").format(self._what.capitalize(), code)
message.error(exitinfo)
if stdout:
log.procs.error("Process stdout:\n" + stdout.strip())
if stderr:
log.procs.error("Process stderr:\n" + stderr.strip())
qutescheme.spawn_output = self._spawn_format(exitinfo, stdout, stderr)
def _spawn_format(self, exitinfo, stdout, stderr):
"""Produce a formatted string for spawn output."""
stdout = (stdout or "(No output)").strip()
stderr = (stderr or "(No output)").strip()
spawn_string = ("{}\n"
"\nProcess stdout:\n {}"
"\nProcess stderr:\n {}").format(exitinfo,
stdout, stderr)
return spawn_string
@pyqtSlot()
def _on_started(self):
"""Called when the process started successfully."""
log.procs.debug("Process started.")
assert not self._started
self._started = True
def _pre_start(self, cmd, args):
"""Prepare starting of a QProcess."""
if self._started:
raise ValueError("Trying to start a running QProcess!")
self.cmd = cmd
self.args = args
fake_cmdline = ' '.join(shlex.quote(e) for e in [cmd] + list(args))
log.procs.debug("Executing: {}".format(fake_cmdline))
if self.verbose:
message.info('Executing: ' + fake_cmdline)
def start(self, cmd, args):
"""Convenience wrapper around QProcess::start."""
log.procs.debug("Starting process.")
self._pre_start(cmd, args)
self._proc.start(cmd, args)
self._proc.closeWriteChannel()
def start_detached(self, cmd, args):
"""Convenience wrapper around QProcess::startDetached."""
log.procs.debug("Starting detached.")
self._pre_start(cmd, args)
ok, _pid = self._proc.startDetached(
cmd, args, None) # type: ignore[call-arg]
if not ok:
message.error("Error while spawning {}".format(self._what))
return False
log.procs.debug("Process started.")
self._started = True
return True
def exit_status(self):
return self._proc.exitStatus()
|
"""Weighted maximum matching in general graphs.
The algorithm is taken from "Efficient Algorithms for Finding Maximum
Matching in Graphs" by Zvi Galil, ACM Computing Surveys, 1986.
It is based on the "blossom" method for finding augmenting paths and
the "primal-dual" method for finding a matching of maximum weight, both
due to Jack Edmonds.
Some ideas came from "Implementation of algorithms for maximum matching
on non-bipartite graphs" by H.J. Gabow, Standford Ph.D. thesis, 1973.
A C program for maximum weight matching by Ed Rothberg was used extensively
to validate this new code.
http://jorisvr.nl/article/maximum-matching#ref:4
"""
from __future__ import print_function
DEBUG = None
"""def DEBUG(s):
from sys import stderr
print('DEBUG:', s, file=stderr)
"""
CHECK_DELTA = False
CHECK_OPTIMUM = True
def maxWeightMatching(edges, maxcardinality=False):
"""Compute a maximum-weighted matching in the general undirected
weighted graph given by "edges". If "maxcardinality" is true,
only maximum-cardinality matchings are considered as solutions.
Edges is a sequence of tuples (i, j, wt) describing an undirected
edge between vertex i and vertex j with weight wt. There is at most
one edge between any two vertices; no vertex has an edge to itself.
Vertices are identified by consecutive, non-negative integers.
Return a list "mate", such that mate[i] == j if vertex i is
matched to vertex j, and mate[i] == -1 if vertex i is not matched.
This function takes time O(n ** 3)."""
#
# Vertices are numbered 0 .. (nvertex-1).
# Non-trivial blossoms are numbered nvertex .. (2*nvertex-1)
#
# Edges are numbered 0 .. (nedge-1).
# Edge endpoints are numbered 0 .. (2*nedge-1), such that endpoints
# (2*k) and (2*k+1) both belong to edge k.
#
# Many terms used in the comments (sub-blossom, T-vertex) come from
# the paper by Galil; read the paper before reading this code.
#
# Python 2/3 compatibility.
from sys import version as sys_version
if sys_version < '3':
integer_types = (int, long)
else:
integer_types = (int,)
# Deal swiftly with empty graphs.
if not edges:
return [ ]
# Count vertices.
nedge = len(edges)
nvertex = 0
for (i, j, w) in edges:
assert i >= 0 and j >= 0 and i != j
if i >= nvertex:
nvertex = i + 1
if j >= nvertex:
nvertex = j + 1
# Find the maximum edge weight.
maxweight = max(0, max([ wt for (i, j, wt) in edges ]))
# If p is an edge endpoint,
# endpoint[p] is the vertex to which endpoint p is attached.
# Not modified by the algorithm.
endpoint = [ edges[p//2][p%2] for p in range(2*nedge) ]
# If v is a vertex,
# neighbend[v] is the list of remote endpoints of the edges attached to v.
# Not modified by the algorithm.
neighbend = [ [ ] for i in range(nvertex) ]
for k in range(len(edges)):
(i, j, w) = edges[k]
neighbend[i].append(2*k+1)
neighbend[j].append(2*k)
# If v is a vertex,
# mate[v] is the remote endpoint of its matched edge, or -1 if it is single
# (i.e. endpoint[mate[v]] is v's partner vertex).
# Initially all vertices are single; updated during augmentation.
mate = nvertex * [ -1 ]
# If b is a top-level blossom,
# label[b] is 0 if b is unlabeled (free);
# 1 if b is an S-vertex/blossom;
# 2 if b is a T-vertex/blossom.
# The label of a vertex is found by looking at the label of its
# top-level containing blossom.
# If v is a vertex inside a T-blossom,
# label[v] is 2 iff v is reachable from an S-vertex outside the blossom.
# Labels are assigned during a stage and reset after each augmentation.
label = (2 * nvertex) * [ 0 ]
# If b is a labeled top-level blossom,
# labelend[b] is the remote endpoint of the edge through which b obtained
# its label, or -1 if b's base vertex is single.
# If v is a vertex inside a T-blossom and label[v] == 2,
# labelend[v] is the remote endpoint of the edge through which v is
# reachable from outside the blossom.
labelend = (2 * nvertex) * [ -1 ]
# If v is a vertex,
# inblossom[v] is the top-level blossom to which v belongs.
# If v is a top-level vertex, v is itself a blossom (a trivial blossom)
# and inblossom[v] == v.
# Initially all vertices are top-level trivial blossoms.
inblossom = list(range(nvertex))
# If b is a sub-blossom,
# blossomparent[b] is its immediate parent (sub-)blossom.
# If b is a top-level blossom, blossomparent[b] is -1.
blossomparent = (2 * nvertex) * [ -1 ]
# If b is a non-trivial (sub-)blossom,
# blossomchilds[b] is an ordered list of its sub-blossoms, starting with
# the base and going round the blossom.
blossomchilds = (2 * nvertex) * [ None ]
# If b is a (sub-)blossom,
# blossombase[b] is its base VERTEX (i.e. recursive sub-blossom).
blossombase = list(range(nvertex)) + nvertex * [ -1 ]
# If b is a non-trivial (sub-)blossom,
# blossomendps[b] is a list of endpoints on its connecting edges,
# such that blossomendps[b][i] is the local endpoint of blossomchilds[b][i]
# on the edge that connects it to blossomchilds[b][wrap(i+1)].
blossomendps = (2 * nvertex) * [ None ]
# If v is a free vertex (or an unreached vertex inside a T-blossom),
# bestedge[v] is the edge to an S-vertex with least slack,
# or -1 if there is no such edge.
# If b is a (possibly trivial) top-level S-blossom,
# bestedge[b] is the least-slack edge to a different S-blossom,
# or -1 if there is no such edge.
# This is used for efficient computation of delta2 and delta3.
bestedge = (2 * nvertex) * [ -1 ]
# If b is a non-trivial top-level S-blossom,
# blossombestedges[b] is a list of least-slack edges to neighbouring
# S-blossoms, or None if no such list has been computed yet.
# This is used for efficient computation of delta3.
blossombestedges = (2 * nvertex) * [ None ]
# List of currently unused blossom numbers.
unusedblossoms = list(range(nvertex, 2*nvertex))
# If v is a vertex,
# dualvar[v] = 2 * u(v) where u(v) is the v's variable in the dual
# optimization problem (multiplication by two ensures integer values
# throughout the algorithm if all edge weights are integers).
# If b is a non-trivial blossom,
# dualvar[b] = z(b) where z(b) is b's variable in the dual optimization
# problem.
dualvar = nvertex * [ maxweight ] + nvertex * [ 0 ]
# If allowedge[k] is true, edge k has zero slack in the optimization
# problem; if allowedge[k] is false, the edge's slack may or may not
# be zero.
allowedge = nedge * [ False ]
# Queue of newly discovered S-vertices.
queue = [ ]
# Return 2 * slack of edge k (does not work inside blossoms).
def slack(k):
(i, j, wt) = edges[k]
return dualvar[i] + dualvar[j] - 2 * wt
# Generate the leaf vertices of a blossom.
def blossomLeaves(b):
if b < nvertex:
yield b
else:
for t in blossomchilds[b]:
if t < nvertex:
yield t
else:
for v in blossomLeaves(t):
yield v
# Assign label t to the top-level blossom containing vertex w
# and record the fact that w was reached through the edge with
# remote endpoint p.
def assignLabel(w, t, p):
if DEBUG: DEBUG('assignLabel(%d,%d,%d)' % (w, t, p))
b = inblossom[w]
assert label[w] == 0 and label[b] == 0
label[w] = label[b] = t
labelend[w] = labelend[b] = p
bestedge[w] = bestedge[b] = -1
if t == 1:
# b became an S-vertex/blossom; add it(s vertices) to the queue.
queue.extend(blossomLeaves(b))
if DEBUG: DEBUG('PUSH ' + str(list(blossomLeaves(b))))
elif t == 2:
# b became a T-vertex/blossom; assign label S to its mate.
# (If b is a non-trivial blossom, its base is the only vertex
# with an external mate.)
base = blossombase[b]
assert mate[base] >= 0
assignLabel(endpoint[mate[base]], 1, mate[base] ^ 1)
# Trace back from vertices v and w to discover either a new blossom
# or an augmenting path. Return the base vertex of the new blossom or -1.
def scanBlossom(v, w):
if DEBUG: DEBUG('scanBlossom(%d,%d)' % (v, w))
# Trace back from v and w, placing breadcrumbs as we go.
path = [ ]
base = -1
while v != -1 or w != -1:
# Look for a breadcrumb in v's blossom or put a new breadcrumb.
b = inblossom[v]
if label[b] & 4:
base = blossombase[b]
break
assert label[b] == 1
path.append(b)
label[b] = 5
# Trace one step back.
assert labelend[b] == mate[blossombase[b]]
if labelend[b] == -1:
# The base of blossom b is single; stop tracing this path.
v = -1
else:
v = endpoint[labelend[b]]
b = inblossom[v]
assert label[b] == 2
# b is a T-blossom; trace one more step back.
assert labelend[b] >= 0
v = endpoint[labelend[b]]
# Swap v and w so that we alternate between both paths.
if w != -1:
v, w = w, v
# Remove breadcrumbs.
for b in path:
label[b] = 1
# Return base vertex, if we found one.
return base
# Construct a new blossom with given base, containing edge k which
# connects a pair of S vertices. Label the new blossom as S; set its dual
# variable to zero; relabel its T-vertices to S and add them to the queue.
def addBlossom(base, k):
(v, w, wt) = edges[k]
bb = inblossom[base]
bv = inblossom[v]
bw = inblossom[w]
# Create blossom.
b = unusedblossoms.pop()
if DEBUG: DEBUG('addBlossom(%d,%d) (v=%d w=%d) -> %d' % (base, k, v, w, b))
blossombase[b] = base
blossomparent[b] = -1
blossomparent[bb] = b
# Make list of sub-blossoms and their interconnecting edge endpoints.
blossomchilds[b] = path = [ ]
blossomendps[b] = endps = [ ]
# Trace back from v to base.
while bv != bb:
# Add bv to the new blossom.
blossomparent[bv] = b
path.append(bv)
endps.append(labelend[bv])
assert (label[bv] == 2 or
(label[bv] == 1 and labelend[bv] == mate[blossombase[bv]]))
# Trace one step back.
assert labelend[bv] >= 0
v = endpoint[labelend[bv]]
bv = inblossom[v]
# Reverse lists, add endpoint that connects the pair of S vertices.
path.append(bb)
path.reverse()
endps.reverse()
endps.append(2*k)
# Trace back from w to base.
while bw != bb:
# Add bw to the new blossom.
blossomparent[bw] = b
path.append(bw)
endps.append(labelend[bw] ^ 1)
assert (label[bw] == 2 or
(label[bw] == 1 and labelend[bw] == mate[blossombase[bw]]))
# Trace one step back.
assert labelend[bw] >= 0
w = endpoint[labelend[bw]]
bw = inblossom[w]
# Set label to S.
assert label[bb] == 1
label[b] = 1
labelend[b] = labelend[bb]
# Set dual variable to zero.
dualvar[b] = 0
# Relabel vertices.
for v in blossomLeaves(b):
if label[inblossom[v]] == 2:
# This T-vertex now turns into an S-vertex because it becomes
# part of an S-blossom; add it to the queue.
queue.append(v)
inblossom[v] = b
# Compute blossombestedges[b].
bestedgeto = (2 * nvertex) * [ -1 ]
for bv in path:
if blossombestedges[bv] is None:
# This subblossom does not have a list of least-slack edges;
# get the information from the vertices.
nblists = [ [ p // 2 for p in neighbend[v] ]
for v in blossomLeaves(bv) ]
else:
# Walk this subblossom's least-slack edges.
nblists = [ blossombestedges[bv] ]
for nblist in nblists:
for k in nblist:
(i, j, wt) = edges[k]
if inblossom[j] == b:
i, j = j, i
bj = inblossom[j]
if (bj != b and label[bj] == 1 and
(bestedgeto[bj] == -1 or
slack(k) < slack(bestedgeto[bj]))):
bestedgeto[bj] = k
# Forget about least-slack edges of the subblossom.
blossombestedges[bv] = None
bestedge[bv] = -1
blossombestedges[b] = [ k for k in bestedgeto if k != -1 ]
# Select bestedge[b].
bestedge[b] = -1
for k in blossombestedges[b]:
if bestedge[b] == -1 or slack(k) < slack(bestedge[b]):
bestedge[b] = k
if DEBUG: DEBUG('blossomchilds[%d]=' % b + repr(blossomchilds[b]))
# Expand the given top-level blossom.
def expandBlossom(b, endstage):
if DEBUG: DEBUG('expandBlossom(%d,%d) %s' % (b, endstage, repr(blossomchilds[b])))
# Convert sub-blossoms into top-level blossoms.
for s in blossomchilds[b]:
blossomparent[s] = -1
if s < nvertex:
inblossom[s] = s
elif endstage and dualvar[s] == 0:
# Recursively expand this sub-blossom.
expandBlossom(s, endstage)
else:
for v in blossomLeaves(s):
inblossom[v] = s
# If we expand a T-blossom during a stage, its sub-blossoms must be
# relabeled.
if (not endstage) and label[b] == 2:
# Start at the sub-blossom through which the expanding
# blossom obtained its label, and relabel sub-blossoms untili
# we reach the base.
# Figure out through which sub-blossom the expanding blossom
# obtained its label initially.
assert labelend[b] >= 0
entrychild = inblossom[endpoint[labelend[b] ^ 1]]
# Decide in which direction we will go round the blossom.
j = blossomchilds[b].index(entrychild)
if j & 1:
# Start index is odd; go forward and wrap.
j -= len(blossomchilds[b])
jstep = 1
endptrick = 0
else:
# Start index is even; go backward.
jstep = -1
endptrick = 1
# Move along the blossom until we get to the base.
p = labelend[b]
while j != 0:
# Relabel the T-sub-blossom.
label[endpoint[p ^ 1]] = 0
label[endpoint[blossomendps[b][j-endptrick]^endptrick^1]] = 0
assignLabel(endpoint[p ^ 1], 2, p)
# Step to the next S-sub-blossom and note its forward endpoint.
allowedge[blossomendps[b][j-endptrick]//2] = True
j += jstep
p = blossomendps[b][j-endptrick] ^ endptrick
# Step to the next T-sub-blossom.
allowedge[p//2] = True
j += jstep
# Relabel the base T-sub-blossom WITHOUT stepping through to
# its mate (so don't call assignLabel).
bv = blossomchilds[b][j]
label[endpoint[p ^ 1]] = label[bv] = 2
labelend[endpoint[p ^ 1]] = labelend[bv] = p
bestedge[bv] = -1
# Continue along the blossom until we get back to entrychild.
j += jstep
while blossomchilds[b][j] != entrychild:
# Examine the vertices of the sub-blossom to see whether
# it is reachable from a neighbouring S-vertex outside the
# expanding blossom.
bv = blossomchilds[b][j]
if label[bv] == 1:
# This sub-blossom just got label S through one of its
# neighbours; leave it.
j += jstep
continue
for v in blossomLeaves(bv):
if label[v] != 0:
break
# If the sub-blossom contains a reachable vertex, assign
# label T to the sub-blossom.
if label[v] != 0:
assert label[v] == 2
assert inblossom[v] == bv
label[v] = 0
label[endpoint[mate[blossombase[bv]]]] = 0
assignLabel(v, 2, labelend[v])
j += jstep
# Recycle the blossom number.
label[b] = labelend[b] = -1
blossomchilds[b] = blossomendps[b] = None
blossombase[b] = -1
blossombestedges[b] = None
bestedge[b] = -1
unusedblossoms.append(b)
# Swap matched/unmatched edges over an alternating path through blossom b
# between vertex v and the base vertex. Keep blossom bookkeeping consistent.
def augmentBlossom(b, v):
if DEBUG: DEBUG('augmentBlossom(%d,%d)' % (b, v))
# Bubble up through the blossom tree from vertex v to an immediate
# sub-blossom of b.
t = v
while blossomparent[t] != b:
t = blossomparent[t]
# Recursively deal with the first sub-blossom.
if t >= nvertex:
augmentBlossom(t, v)
# Decide in which direction we will go round the blossom.
i = j = blossomchilds[b].index(t)
if i & 1:
# Start index is odd; go forward and wrap.
j -= len(blossomchilds[b])
jstep = 1
endptrick = 0
else:
# Start index is even; go backward.
jstep = -1
endptrick = 1
# Move along the blossom until we get to the base.
while j != 0:
# Step to the next sub-blossom and augment it recursively.
j += jstep
t = blossomchilds[b][j]
p = blossomendps[b][j-endptrick] ^ endptrick
if t >= nvertex:
augmentBlossom(t, endpoint[p])
# Step to the next sub-blossom and augment it recursively.
j += jstep
t = blossomchilds[b][j]
if t >= nvertex:
augmentBlossom(t, endpoint[p ^ 1])
# Match the edge connecting those sub-blossoms.
mate[endpoint[p]] = p ^ 1
mate[endpoint[p ^ 1]] = p
if DEBUG: DEBUG('PAIR %d %d (k=%d)' % (endpoint[p], endpoint[p^1], p//2))
# Rotate the list of sub-blossoms to put the new base at the front.
blossomchilds[b] = blossomchilds[b][i:] + blossomchilds[b][:i]
blossomendps[b] = blossomendps[b][i:] + blossomendps[b][:i]
blossombase[b] = blossombase[blossomchilds[b][0]]
assert blossombase[b] == v
# Swap matched/unmatched edges over an alternating path between two
# single vertices. The augmenting path runs through edge k, which
# connects a pair of S vertices.
def augmentMatching(k):
(v, w, wt) = edges[k]
if DEBUG: DEBUG('augmentMatching(%d) (v=%d w=%d)' % (k, v, w))
if DEBUG: DEBUG('PAIR %d %d (k=%d)' % (v, w, k))
for (s, p) in ((v, 2*k+1), (w, 2*k)):
# Match vertex s to remote endpoint p. Then trace back from s
# until we find a single vertex, swapping matched and unmatched
# edges as we go.
while 1:
bs = inblossom[s]
assert label[bs] == 1
assert labelend[bs] == mate[blossombase[bs]]
# Augment through the S-blossom from s to base.
if bs >= nvertex:
augmentBlossom(bs, s)
# Update mate[s]
mate[s] = p
# Trace one step back.
if labelend[bs] == -1:
# Reached single vertex; stop.
break
t = endpoint[labelend[bs]]
bt = inblossom[t]
assert label[bt] == 2
# Trace one step back.
assert labelend[bt] >= 0
s = endpoint[labelend[bt]]
j = endpoint[labelend[bt] ^ 1]
# Augment through the T-blossom from j to base.
assert blossombase[bt] == t
if bt >= nvertex:
augmentBlossom(bt, j)
# Update mate[j]
mate[j] = labelend[bt]
# Keep the opposite endpoint;
# it will be assigned to mate[s] in the next step.
p = labelend[bt] ^ 1
if DEBUG: DEBUG('PAIR %d %d (k=%d)' % (s, t, p//2))
# Verify that the optimum solution has been reached.
def verifyOptimum():
if maxcardinality:
# Vertices may have negative dual;
# find a constant non-negative number to add to all vertex duals.
vdualoffset = max(0, -min(dualvar[:nvertex]))
else:
vdualoffset = 0
# 0. all dual variables are non-negative
assert min(dualvar[:nvertex]) + vdualoffset >= 0
assert min(dualvar[nvertex:]) >= 0
# 0. all edges have non-negative slack and
# 1. all matched edges have zero slack;
for k in range(nedge):
(i, j, wt) = edges[k]
s = dualvar[i] + dualvar[j] - 2 * wt
iblossoms = [ i ]
jblossoms = [ j ]
while blossomparent[iblossoms[-1]] != -1:
iblossoms.append(blossomparent[iblossoms[-1]])
while blossomparent[jblossoms[-1]] != -1:
jblossoms.append(blossomparent[jblossoms[-1]])
iblossoms.reverse()
jblossoms.reverse()
for (bi, bj) in zip(iblossoms, jblossoms):
if bi != bj:
break
s += 2 * dualvar[bi]
assert s >= 0
if mate[i] // 2 == k or mate[j] // 2 == k:
assert mate[i] // 2 == k and mate[j] // 2 == k
assert s == 0
# 2. all single vertices have zero dual value;
for v in range(nvertex):
assert mate[v] >= 0 or dualvar[v] + vdualoffset == 0
# 3. all blossoms with positive dual value are full.
for b in range(nvertex, 2*nvertex):
if blossombase[b] >= 0 and dualvar[b] > 0:
assert len(blossomendps[b]) % 2 == 1
for p in blossomendps[b][1::2]:
assert mate[endpoint[p]] == p ^ 1
assert mate[endpoint[p ^ 1]] == p
# Ok.
# Check optimized delta2 against a trivial computation.
def checkDelta2():
for v in range(nvertex):
if label[inblossom[v]] == 0:
bd = None
bk = -1
for p in neighbend[v]:
k = p // 2
w = endpoint[p]
if label[inblossom[w]] == 1:
d = slack(k)
if bk == -1 or d < bd:
bk = k
bd = d
if DEBUG and (bestedge[v] != -1 or bk != -1) and (bestedge[v] == -1 or bd != slack(bestedge[v])):
DEBUG('v=' + str(v) + ' bk=' + str(bk) + ' bd=' + str(bd) + ' bestedge=' + str(bestedge[v]) + ' slack=' + str(slack(bestedge[v])))
assert (bk == -1 and bestedge[v] == -1) or (bestedge[v] != -1 and bd == slack(bestedge[v]))
# Check optimized delta3 against a trivial computation.
def checkDelta3():
bk = -1
bd = None
tbk = -1
tbd = None
for b in range(2 * nvertex):
if blossomparent[b] == -1 and label[b] == 1:
for v in blossomLeaves(b):
for p in neighbend[v]:
k = p // 2
w = endpoint[p]
if inblossom[w] != b and label[inblossom[w]] == 1:
d = slack(k)
if bk == -1 or d < bd:
bk = k
bd = d
if bestedge[b] != -1:
(i, j, wt) = edges[bestedge[b]]
assert inblossom[i] == b or inblossom[j] == b
assert inblossom[i] != b or inblossom[j] != b
assert label[inblossom[i]] == 1 and label[inblossom[j]] == 1
if tbk == -1 or slack(bestedge[b]) < tbd:
tbk = bestedge[b]
tbd = slack(bestedge[b])
if DEBUG and bd != tbd:
DEBUG('bk=%d tbk=%d bd=%s tbd=%s' % (bk, tbk, repr(bd), repr(tbd)))
assert bd == tbd
# Main loop: continue until no further improvement is possible.
for t in range(nvertex):
# Each iteration of this loop is a "stage".
# A stage finds an augmenting path and uses that to improve
# the matching.
if DEBUG: DEBUG('STAGE %d' % t)
# Remove labels from top-level blossoms/vertices.
label[:] = (2 * nvertex) * [ 0 ]
# Forget all about least-slack edges.
bestedge[:] = (2 * nvertex) * [ -1 ]
blossombestedges[nvertex:] = nvertex * [ None ]
# Loss of labeling means that we can not be sure that currently
# allowable edges remain allowable througout this stage.
allowedge[:] = nedge * [ False ]
# Make queue empty.
queue[:] = [ ]
# Label single blossoms/vertices with S and put them in the queue.
for v in range(nvertex):
if mate[v] == -1 and label[inblossom[v]] == 0:
assignLabel(v, 1, -1)
# Loop until we succeed in augmenting the matching.
augmented = 0
while 1:
# Each iteration of this loop is a "substage".
# A substage tries to find an augmenting path;
# if found, the path is used to improve the matching and
# the stage ends. If there is no augmenting path, the
# primal-dual method is used to pump some slack out of
# the dual variables.
if DEBUG: DEBUG('SUBSTAGE')
# Continue labeling until all vertices which are reachable
# through an alternating path have got a label.
while queue and not augmented:
# Take an S vertex from the queue.
v = queue.pop()
if DEBUG: DEBUG('POP v=%d' % v)
assert label[inblossom[v]] == 1
# Scan its neighbours:
for p in neighbend[v]:
k = p // 2
w = endpoint[p]
# w is a neighbour to v
if inblossom[v] == inblossom[w]:
# this edge is internal to a blossom; ignore it
continue
if not allowedge[k]:
kslack = slack(k)
if kslack <= 0:
# edge k has zero slack => it is allowable
allowedge[k] = True
if allowedge[k]:
if label[inblossom[w]] == 0:
# (C1) w is a free vertex;
# label w with T and label its mate with S (R12).
assignLabel(w, 2, p ^ 1)
elif label[inblossom[w]] == 1:
# (C2) w is an S-vertex (not in the same blossom);
# follow back-links to discover either an
# augmenting path or a new blossom.
base = scanBlossom(v, w)
if base >= 0:
# Found a new blossom; add it to the blossom
# bookkeeping and turn it into an S-blossom.
addBlossom(base, k)
else:
# Found an augmenting path; augment the
# matching and end this stage.
augmentMatching(k)
augmented = 1
break
elif label[w] == 0:
# w is inside a T-blossom, but w itself has not
# yet been reached from outside the blossom;
# mark it as reached (we need this to relabel
# during T-blossom expansion).
assert label[inblossom[w]] == 2
label[w] = 2
labelend[w] = p ^ 1
elif label[inblossom[w]] == 1:
# keep track of the least-slack non-allowable edge to
# a different S-blossom.
b = inblossom[v]
if bestedge[b] == -1 or kslack < slack(bestedge[b]):
bestedge[b] = k
elif label[w] == 0:
# w is a free vertex (or an unreached vertex inside
# a T-blossom) but we can not reach it yet;
# keep track of the least-slack edge that reaches w.
if bestedge[w] == -1 or kslack < slack(bestedge[w]):
bestedge[w] = k
if augmented:
break
# There is no augmenting path under these constraints;
# compute delta and reduce slack in the optimization problem.
# (Note that our vertex dual variables, edge slacks and delta's
# are pre-multiplied by two.)
deltatype = -1
delta = deltaedge = deltablossom = None
# Verify data structures for delta2/delta3 computation.
if CHECK_DELTA:
checkDelta2()
checkDelta3()
# Compute delta1: the minumum value of any vertex dual.
if not maxcardinality:
deltatype = 1
delta = min(dualvar[:nvertex])
# Compute delta2: the minimum slack on any edge between
# an S-vertex and a free vertex.
for v in range(nvertex):
if label[inblossom[v]] == 0 and bestedge[v] != -1:
d = slack(bestedge[v])
if deltatype == -1 or d < delta:
delta = d
deltatype = 2
deltaedge = bestedge[v]
# Compute delta3: half the minimum slack on any edge between
# a pair of S-blossoms.
for b in range(2 * nvertex):
if ( blossomparent[b] == -1 and label[b] == 1 and
bestedge[b] != -1 ):
kslack = slack(bestedge[b])
if isinstance(kslack, integer_types):
assert (kslack % 2) == 0
d = kslack // 2
else:
d = kslack / 2
if deltatype == -1 or d < delta:
delta = d
deltatype = 3
deltaedge = bestedge[b]
# Compute delta4: minimum z variable of any T-blossom.
for b in range(nvertex, 2*nvertex):
if ( blossombase[b] >= 0 and blossomparent[b] == -1 and
label[b] == 2 and
(deltatype == -1 or dualvar[b] < delta) ):
delta = dualvar[b]
deltatype = 4
deltablossom = b
if deltatype == -1:
# No further improvement possible; max-cardinality optimum
# reached. Do a final delta update to make the optimum
# verifyable.
assert maxcardinality
deltatype = 1
delta = max(0, min(dualvar[:nvertex]))
# Update dual variables according to delta.
for v in range(nvertex):
if label[inblossom[v]] == 1:
# S-vertex: 2*u = 2*u - 2*delta
dualvar[v] -= delta
elif label[inblossom[v]] == 2:
# T-vertex: 2*u = 2*u + 2*delta
dualvar[v] += delta
for b in range(nvertex, 2*nvertex):
if blossombase[b] >= 0 and blossomparent[b] == -1:
if label[b] == 1:
# top-level S-blossom: z = z + 2*delta
dualvar[b] += delta
elif label[b] == 2:
# top-level T-blossom: z = z - 2*delta
dualvar[b] -= delta
# Take action at the point where minimum delta occurred.
if DEBUG: DEBUG('delta%d=%f' % (deltatype, delta))
if deltatype == 1:
# No further improvement possible; optimum reached.
break
elif deltatype == 2:
# Use the least-slack edge to continue the search.
allowedge[deltaedge] = True
(i, j, wt) = edges[deltaedge]
if label[inblossom[i]] == 0:
i, j = j, i
assert label[inblossom[i]] == 1
queue.append(i)
elif deltatype == 3:
# Use the least-slack edge to continue the search.
allowedge[deltaedge] = True
(i, j, wt) = edges[deltaedge]
assert label[inblossom[i]] == 1
queue.append(i)
elif deltatype == 4:
# Expand the least-z blossom.
expandBlossom(deltablossom, False)
# End of a this substage.
# Stop when no more augmenting path can be found.
if not augmented:
break
# End of a stage; expand all S-blossoms which have dualvar = 0.
for b in range(nvertex, 2*nvertex):
if ( blossomparent[b] == -1 and blossombase[b] >= 0 and
label[b] == 1 and dualvar[b] == 0 ):
expandBlossom(b, True)
# Verify that we reached the optimum solution.
if CHECK_OPTIMUM:
verifyOptimum()
# Transform mate[] such that mate[v] is the vertex to which v is paired.
for v in range(nvertex):
if mate[v] >= 0:
mate[v] = endpoint[mate[v]]
for v in range(nvertex):
assert mate[v] == -1 or mate[mate[v]] == v
return mate
|
import os
import unittest
import shutil
import datetime
from bioport_repository.common import to_date, format_date
class CommonTestCase(unittest.TestCase):
def test_to_date(self):
self.assertEqual(to_date('2000'), datetime.datetime(2000, 1, 1, 0, 0))
self.assertEqual(to_date('2000-02'), datetime.datetime(2000, 2, 1, 0, 0))
self.assertEqual(to_date('2000-02-03'), datetime.datetime(2000, 2, 3, 0, 0))
self.assertEqual(to_date('2001-02', round='up'), datetime.datetime(2001, 2, 28, 0, 0))
#2000 is a leap year
self.assertEqual(to_date('2000-02', round='up'), datetime.datetime(2000, 2, 29, 0, 0))
self.assertEqual(to_date('2000-12', round='up'), datetime.datetime(2000, 12, 31, 0, 0))
self.assertEqual(to_date('2000', round='up'), datetime.datetime(2000, 12, 31, 0, 0))
self.assertEqual(to_date('0200', round='up'), datetime.datetime(200, 12, 31, 0, 0))
self.assertEqual(to_date('1200', ), datetime.datetime(1200, 1, 1, 0, 0))
def test_format_date(self):
d = datetime.datetime(1700, 3, 2)
self.assertEqual(format_date(d), '1700-03-02 00:00')
d = datetime.datetime(1, 3, 2)
self.assertEqual(format_date(d), '0001-03-02 00:00')
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(CommonTestCase, 'test'),
))
if __name__=='__main__':
unittest.main(defaultTest='test_suite')
|
import datetime
from ecl.util.util import BoolVector
from ecl.util.test import TestAreaContext
from tests import ResTest
from res.enkf import ObsBlock
class ObsBlockTest(ResTest):
def test_create(self):
block = ObsBlock("OBS" , 1000)
self.assertTrue( isinstance( block , ObsBlock ))
self.assertEqual( 1000 , block.totalSize())
self.assertEqual( 0 , block.activeSize())
def test_access(self):
obs_size = 10
block = ObsBlock("OBS" , obs_size)
with self.assertRaises(IndexError):
block[100] = (1,1)
with self.assertRaises(IndexError):
block[-100] = (1,1)
with self.assertRaises(TypeError):
block[4] = 10
with self.assertRaises(TypeError):
block[4] = (1,1,9)
#------
with self.assertRaises(IndexError):
v = block[100]
with self.assertRaises(IndexError):
v = block[-100]
block[0] = (10,1)
v = block[0]
self.assertEqual( v , (10,1))
self.assertEqual( 1 , block.activeSize())
block[-1] = (17,19)
self.assertEqual( block[-1], (17,19))
|
"""Configure batch3dfier with the input data."""
import os.path
from subprocess import call
from shapely.geometry import shape
from shapely import geos
from psycopg2 import sql
import fiona
def call_3dfier(db, tile, schema_tiles,
pc_file_name, pc_tile_case, pc_dir,
table_index_pc, fields_index_pc,
table_index_footprint, fields_index_footprint, uniqueid,
extent_ewkb, clip_prefix, prefix_tile_footprint,
yml_dir, tile_out, output_format, output_dir,
path_3dfier, thread):
"""Call 3dfier with the YAML config created by yamlr().
Note
----
For the rest of the parameters see batch3dfier_config.yml.
Parameters
----------
db : db Class instance
tile : str
Name of of the 2D tile.
schema_tiles : str
Schema of the footprint tiles.
pc_file_name : str
Naming convention for the pointcloud files. See 'dataset_name' in batch3dfier_config.yml.
pc_tile_case : str
How the string matching is done for pc_file_name. See 'tile_case' in batch3dfier_config.yml.
pc_dir : str
Directory of the pointcloud files. See 'dataset_dir' in batch3dfier_config.yml.
thread : str
Name/ID of the active thread.
extent_ewkb : str
EWKB representation of 'extent' in batch3dfier_config.yml.
clip_prefix : str
Prefix for naming the clipped/united views. This value shouldn't be a substring of the pointcloud file names.
prefix_tile_footprint : str or None
Prefix prepended to the footprint tile view names. If None, the views are named as
the values in fields_index_fooptrint['unit_name'].
Returns
-------
list
The tiles that are skipped because no corresponding pointcloud file
was found in 'dataset_dir' (YAML)
"""
pc_tiles = find_pc_tiles(db, table_index_pc, fields_index_pc,
table_index_footprint, fields_index_footprint,
extent_ewkb, tile_footprint=tile,
prefix_tile_footprint=prefix_tile_footprint)
pc_path = find_pc_files(pc_tiles, pc_dir, pc_file_name, pc_tile_case)
# prepare output file name
if not tile_out:
tile_out = tile.replace(clip_prefix, '', 1)
# Call 3dfier ------------------------------------------------------------
if pc_path:
# Needs a YAML per thread so one doesn't overwrite it while the other
# uses it
yml_name = thread + "_config.yml"
yml_path = os.path.join(yml_dir, yml_name)
config = yamlr(dbname=db.dbname, host=db.host, user=db.user,
pw=db.password, schema_tiles=schema_tiles,
bag_tile=tile, pc_path=pc_path,
output_format=output_format, uniqueid=uniqueid)
# Write temporary config file
try:
with open(yml_path, "w") as text_file:
text_file.write(config)
except BaseException:
print("Error: cannot write _config.yml")
# Prep output file name
if "obj" in output_format.lower():
o = tile_out + ".obj"
output_path = os.path.join(output_dir, o)
elif "csv" in output_format.lower():
o = tile_out + ".csv"
output_path = os.path.join(output_dir, o)
else:
output_path = os.path.join(output_dir, tile_out)
# Run 3dfier
command = (path_3dfier + " {yml} -o {out}").format(
yml=yml_path, out=output_path)
try:
call(command, shell=True)
except BaseException:
print("\nCannot run 3dfier on tile " + tile)
tile_skipped = tile
else:
print(
"\nPointcloud file(s) " +
str(pc_tiles) +
" not available. Skipping tile.\n")
tile_skipped = tile
return({'tile_skipped': tile_skipped,
'out_path': None})
return({'tile_skipped': None,
'out_path': output_path})
def yamlr(dbname, host, user, pw, schema_tiles,
bag_tile, pc_path, output_format, uniqueid):
"""Parse the YAML config file for 3dfier.
Parameters
----------
See batch3dfier_config.yml.
Returns
-------
string
the YAML config file for 3dfier
"""
pc_dataset = ""
if len(pc_path) > 1:
for p in pc_path:
pc_dataset += "- " + p + "\n" + " "
else:
pc_dataset += "- " + pc_path[0]
# !!! Do not correct the indentation of the config template, otherwise it
# results in 'YAML::TypedBadConversion<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >'
# because every line is indented as here
config = """
input_polygons:
- datasets:
- "PG:dbname={dbname} host={host} user={user} password={pw} schemas={schema_tiles} tables={bag_tile}"
uniqueid: {uniqueid}
lifting: Building
lifting_options:
Building:
height_roof: percentile-90
height_floor: percentile-10
lod: 1
input_elevation:
- datasets:
{pc_path}
omit_LAS_classes:
thinning: 0
options:
building_radius_vertex_elevation: 2.0
radius_vertex_elevation: 1.0
threshold_jump_edges: 0.5
output:
format: {output_format}
building_floor: true
vertical_exaggeration: 0
""".format(dbname=dbname,
host=host,
user=user,
pw=pw,
schema_tiles=schema_tiles,
bag_tile=bag_tile,
uniqueid=uniqueid,
pc_path=pc_dataset,
output_format=output_format)
return(config)
def find_pc_files(pc_tiles, pc_dir, pc_file_name, pc_tile_case):
"""Find pointcloud files in the file system when given a list of pointcloud tile names
"""
# Prepare AHN file names -------------------------------------------------
if pc_tile_case == "upper":
tiles = [pc_file_name.format(tile=t.upper()) for t in pc_tiles]
elif pc_tile_case == "lower":
tiles = [pc_file_name.format(tile=t.lower()) for t in pc_tiles]
elif pc_tile_case == "mixed":
tiles = [pc_file_name.format(tile=t) for t in pc_tiles]
else:
raise "Please provide one of the allowed values for pc_tile_case."
# use the tile list in tiles to parse the pointcloud file names
pc_path = [os.path.join(pc_dir, pc_tile) for pc_tile in tiles]
if all([os.path.isfile(p) for p in pc_path]):
return(pc_path)
else:
return(None)
def find_pc_tiles(db, table_index_pc, fields_index_pc,
table_index_footprint=None, fields_index_footprint=None,
extent_ewkb=None, tile_footprint=None,
prefix_tile_footprint=None):
"""Find pointcloud tiles in tile index that intersect the extent or the footprint tile.
Parameters
----------
prefix_tile_footprint : str or None
Prefix prepended to the footprint tile view names. If None, the views are named as
the values in fields_index_fooptrint['unit_name'].
"""
if extent_ewkb:
tiles = get_2Dtiles(db, table_index_pc, fields_index_pc, extent_ewkb)
else:
schema_pc_q = sql.Identifier(table_index_pc['schema'])
table_pc_q = sql.Identifier(table_index_pc['table'])
field_pc_geom_q = sql.Identifier(fields_index_pc['geometry'])
field_pc_unit_q = sql.Identifier(fields_index_pc['unit_name'])
schema_ftpr_q = sql.Identifier(table_index_footprint['schema'])
table_ftpr_q = sql.Identifier(table_index_footprint['table'])
field_ftpr_geom_q = sql.Identifier(fields_index_footprint['geometry'])
field_ftpr_unit_q = sql.Identifier(fields_index_footprint['unit_name'])
if prefix_tile_footprint:
tile_footprint = tile_footprint.replace(
prefix_tile_footprint, '', 1)
tile_q = sql.Literal(tile_footprint)
query = sql.SQL("""
SELECT
{table_pc}.{field_pc_unit}
FROM
{schema_pc}.{table_pc},
{schema_ftpr}.{table_ftpr}
WHERE
{table_ftpr}.{field_ftpr_unit} = {tile}
AND st_intersects(
{table_pc}.{field_pc_geom},
{table_ftpr}.{field_ftpr_geom}
);
""").format(table_pc=table_pc_q,
field_pc_unit=field_pc_unit_q,
schema_pc=schema_pc_q,
schema_ftpr=schema_ftpr_q,
table_ftpr=table_ftpr_q,
field_ftpr_unit=field_ftpr_unit_q,
tile=tile_q,
field_pc_geom=field_pc_geom_q,
field_ftpr_geom=field_ftpr_geom_q)
resultset = db.getQuery(query)
tiles = [tile[0] for tile in resultset]
return(tiles)
def extent_to_ewkb(db, table_index, file):
"""Reads a polygon from a file and returns its EWKB.
I didn't find a simple way to safely get SRIDs from the input geometry
with Shapely, therefore it is obtained from the database and the CRS of the
polygon is assumed to be the same as of the tile indexes.
Parameters
----------
db : db Class instance
table_index : dict
{'schema' : str, 'table' : str} of the table of tile index.
file : str
Path to the polygon for clipping the input.
Must be in the same CRS as the table_index.
Returns
-------
[Shapely polygon, EWKB str]
"""
schema = sql.Identifier(table_index['schema'])
table = sql.Identifier(table_index['table'])
query = sql.SQL("""SELECT st_srid(geom) AS srid
FROM {schema}.{table}
LIMIT 1;""").format(schema=schema, table=table)
srid = db.getQuery(query)[0][0]
assert srid is not None
# Get clip polygon and set SRID
with fiona.open(file, 'r') as src:
poly = shape(src[0]['geometry'])
# Change a the default mode to add this, if SRID is set
geos.WKBWriter.defaults['include_srid'] = True
# set SRID for polygon
geos.lgeos.GEOSSetSRID(poly._geom, srid)
ewkb = poly.wkb_hex
return([poly, ewkb])
def get_2Dtiles(db, table_index, fields_index, ewkb):
"""Returns a list of tiles that overlap the output extent.
Parameters
----------
db : db Class instance
table_index : dict
{'schema' : str, 'table' : str} of the table of tile index.
fields_index : dict
{'primary_key' : str, 'geometry' : str, 'unit_name' : str}
primary_key: Name of the primary_key field in table_index.
geometry: Name of the geometry field in table_index.
unit: Name of the field in table_index that contains the index unit names.
ewkb : str
EWKB representation of a polygon.
Returns
-------
[tile IDs]
Tiles that are intersected by the polygon that is provided in 'extent' (YAML).
"""
schema = sql.Identifier(table_index['schema'])
table = sql.Identifier(table_index['table'])
field_idx_geom_q = sql.Identifier(fields_index['geometry'])
field_idx_unit_q = sql.Identifier(fields_index['unit_name'])
ewkb_q = sql.Literal(ewkb)
# TODO: user input for a.unit
query = sql.SQL("""
SELECT {table}.{field_idx_unit}
FROM {schema}.{table}
WHERE st_intersects({table}.{field_idx_geom}, {ewkb}::geometry);
""").format(schema=schema,
table=table,
field_idx_unit=field_idx_unit_q,
field_idx_geom=field_idx_geom_q,
ewkb=ewkb_q)
resultset = db.getQuery(query)
tiles = [tile[0] for tile in resultset]
print("Nr. of tiles in clip extent: " + str(len(tiles)))
return(tiles)
def get_2Dtile_area(db, table_index):
"""Get the area of a 2D tile.
Note
----
Assumes that all tiles have equal area. Area is in units of the tile CRS.
Parameters
----------
db : db Class instance
table_index : list of str
{'schema' : str, 'table' : str} of the table of tile index.
Returns
-------
float
"""
schema = sql.Identifier(table_index['schema'])
table = sql.Identifier(table_index['table'])
query = sql.SQL("""
SELECT public.st_area(geom) AS area
FROM {schema}.{table}
LIMIT 1;
""").format(schema=schema, table=table)
area = db.getQuery(query)[0][0]
return(area)
def get_2Dtile_views(db, schema_tiles, tiles):
"""Get View names of the 2D tiles. It tries to find views in schema_tiles
that contain the respective tile ID in their name.
Parameters
----------
db : db Class instance
schema_tiles: str
Name of the schema where the 2D tile views are stored.
tiles : list
Tile IDs
Returns
-------
list
Name of the view that contain the tile ID as substring.
"""
# Get View names for the tiles
t = ["%" + str(tile) + "%" for tile in tiles]
t = sql.Literal(t)
schema_tiles = sql.Literal(schema_tiles)
query = sql.SQL("""SELECT table_name
FROM information_schema.views
WHERE table_schema = {}
AND table_name LIKE any({});
""").format(schema_tiles, t)
resultset = db.getQuery(query)
tile_views = [tile[0] for tile in resultset]
return(tile_views)
def clip_2Dtiles(db, user_schema, schema_tiles, tiles, poly, clip_prefix,
fields_view):
"""Creates views for the clipped tiles.
Parameters
----------
db : db Class instance
user_schema: str
schema_tiles : str
tiles : list
poly : Shapely polygon
clip_prefix : str
Returns
-------
list
Name of the views of the clipped tiles.
"""
user_schema = sql.Identifier(user_schema)
schema_tiles = sql.Identifier(schema_tiles)
tiles_clipped = []
fields_all = fields_view['all']
field_geom_q = sql.Identifier(fields_view['geometry'])
for tile in tiles:
t = clip_prefix + tile
tiles_clipped.append(t)
view = sql.Identifier(t)
tile_view = sql.Identifier(tile)
fields_q = parse_sql_select_fields(tile, fields_all)
wkb = sql.Literal(poly.wkb_hex)
query = sql.SQL("""
CREATE OR REPLACE VIEW {user_schema}.{view} AS
SELECT
{fields}
FROM
{schema_tiles}.{tile_view}
WHERE
st_within({tile_view}.{geom}, {wkb}::geometry)"""
).format(user_schema=user_schema,
schema_tiles=schema_tiles,
view=view,
fields=fields_q,
tile_view=tile_view,
geom=field_geom_q,
wkb=wkb)
db.sendQuery(query)
try:
db.conn.commit()
print(
str(
len(tiles_clipped)) +
" views with prefix '{}' are created in schema {}.".format(
clip_prefix,
user_schema))
except BaseException:
print("Cannot create view {user_schema}.{clip_prefix}{tile}".format(
schema_tiles=schema_tiles, clip_prefix=clip_prefix))
db.conn.rollback()
return(tiles_clipped)
def union_2Dtiles(db, user_schema, tiles_clipped, clip_prefix, fields_view):
"""Union the clipped tiles into a single view.
Parameters
----------
db : db Class instance
user_schema : str
tiles_clipped : list
clip_prefix : str
Returns
-------
str
Name of the united view.
"""
# Check if there are enough tiles to unite
assert len(tiles_clipped) > 1, "Need at least 2 tiles for union"
user_schema = sql.Identifier(user_schema)
u = "{clip_prefix}union".format(clip_prefix=clip_prefix)
union_view = sql.Identifier(u)
sql_query = sql.SQL("CREATE OR REPLACE VIEW {user_schema}.{view} AS ").format(
user_schema=user_schema, view=union_view)
fields_all = fields_view['all']
for tile in tiles_clipped[:-1]:
view = sql.Identifier(tile)
fields_q = parse_sql_select_fields(tile, fields_all)
sql_subquery = sql.SQL("""SELECT {fields}
FROM {user_schema}.{view}
UNION ALL """).format(fields=fields_q,
user_schema=user_schema,
view=view)
sql_query = sql_query + sql_subquery
# The last statement
tile = tiles_clipped[-1]
view = sql.Identifier(tile)
fields_q = parse_sql_select_fields(tile, fields_all)
sql_subquery = sql.SQL("""SELECT {fields}
FROM {user_schema}.{view};
""").format(fields=fields_q,
user_schema=user_schema,
view=view)
sql_query = sql_query + sql_subquery
db.sendQuery(sql_query)
try:
db.conn.commit()
print("View {} created in schema {}.".format(u, user_schema))
except BaseException:
print("Cannot create view {}.{}".format(user_schema, u))
db.conn.rollback()
return(False)
return(u)
def get_view_fields(db, user_schema, tile_views):
"""Get the fields in a 2D tile view
Parameters
----------
tile_views : list of str
Returns
-------
{'all' : list, 'geometry' : str}
"""
if len(tile_views) > 0:
schema_q = sql.Literal(user_schema)
view_q = sql.Literal(tile_views[0])
resultset = db.getQuery(sql.SQL("""
SELECT
column_name
FROM
information_schema.columns
WHERE
table_schema = {schema}
AND table_name = {view};
""").format(schema=schema_q,
view=view_q))
f = [field[0] for field in resultset]
geom_res = db.getQuery(sql.SQL("""
SELECT
f_geometry_column
FROM
public.geometry_columns
WHERE
f_table_schema = {schema}
AND f_table_name = {view};
""").format(schema=schema_q,
view=view_q))
f_geom = geom_res[0][0]
fields = {}
fields['all'] = f
fields['geometry'] = f_geom
return(fields)
else:
return(None)
def parse_sql_select_fields(table, fields):
"""Parses a list of field names into "table"."field" to insert into a SELECT ... FROM table
Parameters
----------
fields : list of str
Returns
-------
psycopg2.sql.Composable
"""
s = []
for f in fields:
s.append(sql.SQL('.').join([sql.Identifier(table), sql.Identifier(f)]))
sql_fields = sql.SQL(', ').join(s)
return(sql_fields)
def drop_2Dtiles(db, user_schema, views_to_drop):
"""Drops Views in a given schema.
Note
----
Used for dropping the views created by clip_2Dtiles() and union_2Dtiles().
Parameters
----------
db : db Class instance
user_schema : str
views_to_drop : list
Returns
-------
bool
"""
user_schema = sql.Identifier(user_schema)
for view in views_to_drop:
view = sql.Identifier(view)
query = sql.SQL("DROP VIEW IF EXISTS {user_schema}.{view} CASCADE;").format(
user_schema=user_schema, view=view)
db.sendQuery(query)
try:
db.conn.commit()
print("Dropped {} in schema {}.".format(views_to_drop, user_schema))
# sql.Identifier("tile_index").as_string(dbs.conn)
return(True)
except BaseException:
print("Cannot drop views ", views_to_drop)
db.conn.rollback()
return(False)
|
def get_page(page):
import urllib2
source = urllib2.urlopen(page)
return source.read()
title = 'WinSCP Updater'
target = 'Downloading WinSCP'
url = 'http://winscp.net/eng/download.php'
print 'Running: ' + title
print 'Target: ' + target
print 'URL: ' + url
try:
page = get_page(url)
except:
page = None
else:
print 'Got page...'
def msg_box(message, box_type):
import win32api
user_input = win32api.MessageBox(0, message, title, box_type)
return user_input
def stop():
import sys
sys.exit()
if page == None:
msg_box('Could not download the page. You may not be connected to the internet.', 0)
stop()
def find_site_ver(page):
T1 = page.find(target)
if T1 == -1:
return None, None
T2 = page.find('>WinSCP ', T1)
T3 = page.find('<', T2)
T4 = page.find('winscp', T3)
T5 = page.find('.exe', T4)
return page[T2+8:T3], page[T4:T5+4] # 5.1.5, winscp515setup.exe
try:
site_version, FN = find_site_ver(page)
except:
msg_box('Could not search the page.', 0)
stop()
else:
print 'Found: ' + site_version
if site_version == None:
msg_box('The search target has not been found on the page. The formatting, or the text on the page, may have been changed.', 0)
stop()
import os
tmp = os.getenv('TEMP')
PF = os.getenv('PROGRAMFILES')
WinSCP_exe = PF + '\\WinSCP\\WinSCP.exe'
DL = tmp + '\\' + FN
command = [DL, '/SILENT', '/NORESTART']
def DL_file():
import urllib
url = 'http://downloads.sourceforge.net/project/winscp/WinSCP/' + site_version + '/' + FN
urllib.urlretrieve(url, DL)
def sub_proc(command):
import subprocess
p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
stdout, stderr = p.communicate()
return p.returncode # is 0 if success
def download_install():
try:
DL_file()
except:
msg_box('Failed to download ' + FN + ' to ' + tmp + '.', 0)
stop()
else:
print 'Downloaded: ' + FN
try:
RC = sub_proc(command)
except:
RC = None
if RC == None:
msg_box('Failed to execute ' + FN + '.', 0)
stop()
elif RC == 0:
msg_box('Successfully updated to version ' + site_version + '.', 0)
stop()
else:
msg_box('Successfully spawned new process for ' + FN + '. But the installation appears to have failed.', 0)
stop()
if not os.path.isfile(WinSCP_exe):
# No: Download and install WinSCP, and quit.
print 'WinSCP.exe file doesn\'t exist.'
print 'Installing WinSCP for the first time...'
download_install()
print 'Ending...'
delay(5)
stop()
import win32api
try:
info = win32api.GetFileVersionInfo(WinSCP_exe, "\\")
ms = info['FileVersionMS']
ls = info['FileVersionLS']
file_version = "%d.%d.%d.%d" % (win32api.HIWORD(ms), win32api.LOWORD (ms),
win32api.HIWORD (ls), win32api.LOWORD (ls))
except:
msg_box('Cannot find the file version of the local WinSCP.exe file.', 0)
stop()
else:
print 'Got local file version information...'
def clean(text):
import re
return re.sub('[^0-9]', '', text)
clean_site_version = clean(site_version)
clean_file_version = clean(file_version)[:len(clean_site_version)]
print 'Local version: ' + clean_file_version
print 'Site version: ' + clean_site_version
def delay(sec):
import time
time.sleep(sec)
if clean_file_version.find(clean_site_version) != -1:
# Yes: Quit.
print 'Match!'
print 'Ending...'
delay(5)
stop()
def find_proc(exe):
import subprocess
cmd = 'WMIC PROCESS get Caption'
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
for line in proc.stdout:
if line.find(exe) != -1:
return True
while find_proc('WinSCP.exe'):
print 'WinSCP is running. Close WinSCP now!'
user_input = msg_box('There is a new version of WinSCP available. Please close WinSCP and press OK to continue.', 1)
if user_input == 1:
pass
elif user_input == 2:
stop()
user_input = msg_box('If you use a custom WinSCP.ini file, back it up now and then press OK when you are ready to proceed with the update.', 1)
if user_input == 2:
stop()
download_install()
print 'Ending...'
delay(5)
|
bl_info = {
"name": "Rigacar (Generates Car Rig)",
"author": "David Gayerie",
"version": (7, 0),
"blender": (2, 83, 0),
"location": "View3D > Add > Armature",
"description": "Adds a deformation rig for vehicules, generates animation rig and bake wheels animation.",
"wiki_url": "http://digicreatures.net/articles/rigacar.html",
"tracker_url": "https://github.com/digicreatures/rigacar/issues",
"category": "Rigging"}
if "bpy" in locals():
import importlib
if "bake_operators" in locals():
importlib.reload(bake_operators)
if "car_rig" in locals():
importlib.reload(car_rig)
if "widgets" in locals():
importlib.reload(widgets)
else:
import bpy
from . import bake_operators
from . import car_rig
def enumerate_ground_sensors(bones):
bone = bones.get('GroundSensor.Axle.Ft')
if bone is not None:
yield bone
for bone in bones:
if bone.name.startswith('GroundSensor.Ft'):
yield bone
bone = bones.get('GroundSensor.Axle.Bk')
if bone is not None:
yield bone
for bone in bones:
if bone.name.startswith('GroundSensor.Bk'):
yield bone
class RIGACAR_PT_mixin:
def __init__(self):
self.layout.use_property_split = True
self.layout.use_property_decorate = False
@classmethod
def is_car_rig(cls, context):
return context.object is not None and context.object.data is not None and 'Car Rig' in context.object.data
@classmethod
def is_car_rig_generated(cls, context):
return cls.is_car_rig(context) and context.object.data['Car Rig']
def display_generate_section(self, context):
self.layout.operator(car_rig.POSE_OT_carAnimationRigGenerate.bl_idname, text='Generate')
def display_bake_section(self, context):
self.layout.operator(bake_operators.ANIM_OT_carSteeringBake.bl_idname)
self.layout.operator(bake_operators.ANIM_OT_carWheelsRotationBake.bl_idname)
self.layout.operator(bake_operators.ANIM_OT_carClearSteeringWheelsRotation.bl_idname)
def display_rig_props_section(self, context):
layout = self.layout.column()
layout.prop(context.object, '["wheels_on_y_axis"]', text="Wheels on Y axis")
layout.prop(context.object, '["suspension_factor"]', text="Pitch factor")
layout.prop(context.object, '["suspension_rolling_factor"]', text="Roll factor")
def display_ground_sensors_section(self, context):
for ground_sensor in enumerate_ground_sensors(context.object.pose.bones):
ground_projection_constraint = ground_sensor.constraints.get('Ground projection')
self.layout.label(text=ground_sensor.name, icon='BONE_DATA')
if ground_projection_constraint is not None:
self.layout.prop(ground_projection_constraint, 'target', text='Ground')
if ground_projection_constraint.target is not None:
self.layout.prop(ground_projection_constraint, 'shrinkwrap_type')
if ground_projection_constraint.shrinkwrap_type == 'PROJECT':
self.layout.prop(ground_projection_constraint, 'project_limit')
self.layout.prop(ground_projection_constraint, 'influence')
ground_projection_limit_constraint = ground_sensor.constraints.get('Ground projection limitation')
if ground_projection_limit_constraint is not None:
self.layout.prop(ground_projection_limit_constraint, 'min_z', text='Min local Z')
self.layout.prop(ground_projection_limit_constraint, 'max_z', text='Max local Z')
self.layout.separator()
class RIGACAR_PT_rigProperties(bpy.types.Panel, RIGACAR_PT_mixin):
bl_label = "Rigacar"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "data"
bl_options = {'DEFAULT_CLOSED'}
@classmethod
def poll(cls, context):
return RIGACAR_PT_mixin.is_car_rig(context)
def draw(self, context):
if RIGACAR_PT_mixin.is_car_rig_generated(context):
self.display_rig_props_section(context)
self.layout.separator()
self.display_bake_section(context)
else:
self.display_generate_section(context)
class RIGACAR_PT_groundSensorsProperties(bpy.types.Panel, RIGACAR_PT_mixin):
bl_label = "Ground Sensors"
bl_parent_id = "RIGACAR_PT_rigProperties"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "data"
bl_options = {'DEFAULT_CLOSED'}
@classmethod
def poll(cls, context):
return RIGACAR_PT_mixin.is_car_rig_generated(context)
def draw(self, context):
self.display_ground_sensors_section(context)
class RIGACAR_PT_animationRigView(bpy.types.Panel, RIGACAR_PT_mixin):
bl_category = "Rigacar"
bl_label = "Animation Rig"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
@classmethod
def poll(cls, context):
return RIGACAR_PT_mixin.is_car_rig(context)
def draw(self, context):
if RIGACAR_PT_mixin.is_car_rig_generated(context):
self.display_rig_props_section(context)
else:
self.display_generate_section(context)
class RIGACAR_PT_wheelsAnimationView(bpy.types.Panel, RIGACAR_PT_mixin):
bl_category = "Rigacar"
bl_label = "Wheels animation"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
@classmethod
def poll(cls, context):
return RIGACAR_PT_mixin.is_car_rig_generated(context)
def draw(self, context):
self.display_bake_section(context)
class RIGACAR_PT_groundSensorsView(bpy.types.Panel, RIGACAR_PT_mixin):
bl_category = "Rigacar"
bl_label = "Ground Sensors"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_options = {'DEFAULT_CLOSED'}
@classmethod
def poll(cls, context):
return RIGACAR_PT_mixin.is_car_rig_generated(context)
def draw(self, context):
self.display_ground_sensors_section(context)
def menu_entries(menu, context):
menu.layout.operator(car_rig.OBJECT_OT_armatureCarDeformationRig.bl_idname, text="Car (deformation rig)", icon='AUTO')
classes = (
RIGACAR_PT_rigProperties,
RIGACAR_PT_groundSensorsProperties,
RIGACAR_PT_animationRigView,
RIGACAR_PT_wheelsAnimationView,
RIGACAR_PT_groundSensorsView,
)
def register():
bpy.types.VIEW3D_MT_armature_add.append(menu_entries)
for c in classes:
bpy.utils.register_class(c)
car_rig.register()
bake_operators.register()
def unregister():
bake_operators.unregister()
car_rig.unregister()
for c in classes:
bpy.utils.unregister_class(c)
bpy.types.VIEW3D_MT_armature_add.remove(menu_entries)
if __name__ == "__main__":
register()
|
import os
import jsonschema
import yaml
from snapcraft.internal import common
class SnapcraftSchemaError(Exception):
@property
def message(self):
return self._message
def __init__(self, message):
self._message = message
class Validator:
def __init__(self, snapcraft_yaml=None):
"""Create a validation instance for snapcraft_yaml."""
self._snapcraft = snapcraft_yaml if snapcraft_yaml else {}
self._load_schema()
@property
def schema(self):
"""Return all schema properties."""
return self._schema['properties'].copy()
@property
def part_schema(self):
"""Return part-specific schema properties."""
sub = self.schema['parts']['patternProperties']
properties = sub['^(?!plugins$)[a-z0-9][a-z0-9+-\/]*$']['properties']
return properties
def _load_schema(self):
schema_file = os.path.abspath(os.path.join(
common.get_schemadir(), 'snapcraft.yaml'))
try:
with open(schema_file) as fp:
self._schema = yaml.load(fp)
except FileNotFoundError:
raise SnapcraftSchemaError(
'snapcraft validation file is missing from installation path')
def validate(self):
format_check = jsonschema.FormatChecker()
try:
jsonschema.validate(
self._snapcraft, self._schema, format_checker=format_check)
except jsonschema.ValidationError as e:
messages = [e.message]
path = []
while e.absolute_path:
element = e.absolute_path.popleft()
# assume numbers are indices and use 'xxx[123]' notation.
if isinstance(element, int):
path[-1] = '{}[{}]'.format(path[-1], element)
else:
path.append(str(element))
if path:
messages.insert(0, "The '{}' property does not match the "
"required schema:".format('/'.join(path)))
if e.cause:
messages.append('({})'.format(e.cause))
raise SnapcraftSchemaError(' '.join(messages))
|
from d51.django.auth.decorators import auth_required
from django.contrib.sites.models import Site
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.exceptions import ImproperlyConfigured
from .services import load_service, SharingServiceInvalidForm
from .models import URL
SHARE_KEY='u'
@auth_required()
def share_url(request, service_name):
# TODO: this view needs testing
response = HttpResponseRedirect(request.GET.get('next', '/'))
url_to_share = request.GET.get(SHARE_KEY, None)
if url_to_share is None:
# TODO change to a 400
raise Http404
else:
full_url_to_share = 'http://%s%s' % ((Site.objects.get_current().domain, url_to_share)) if url_to_share.find(':') == -1 else url_to_share
url, created = URL.objects.get_or_create(
url=full_url_to_share,
)
try:
url.send(service_name, request.user, request.POST)
except SharingServiceInvalidForm:
service = load_service(service_name, url)
input = [] if request.method != 'POST' else [request.POST]
form = service.get_form_class()(*input)
templates, context = [
'sharing/%s/prompt.html'%service_name,
'sharing/prompt.html'
],{
'service_name':service_name,
'form': form,
'url':url_to_share,
'SHARE_KEY':SHARE_KEY,
'next':request.GET.get('next','/')
}
response = render_to_response(templates, context, context_instance=RequestContext(request))
except ImproperlyConfigured:
raise Http404
return response
|
import gpxpy
import datetime
import time
import os
import gpxpy.gpx
import sqlite3
import pl
import re
DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
filebase = os.environ["XDG_DATA_HOME"]+"/"+os.environ["APP_ID"].split('_')[0]
def create_gpx():
gpx = gpxpy.gpx.GPX()
gpx_track = gpxpy.gpx.GPXTrack()
gpx.tracks.append(gpx_track)
gpx_segment = gpxpy.gpx.GPXTrackSegment()
gpx_track.segments.append(gpx_segment)
return gpx
def write_gpx(gpx,name,act_type):
tzname=None
npoints=None
# polyline encoder default values
numLevels = 18;
zoomFactor = 2;
epsilon = 0.0;
forceEndpoints = True;
##print('Created GPX:', gpx.to_xml())
ts = int(time.time())
filename = "%s/%i.gpx" % (filebase,ts)
a = open(filename, 'w')
a.write(gpx.to_xml())
a.close()
gpx.simplify()
#gpx.reduce_points(1000)
trk = pl.read_gpx_trk(gpx.to_xml(),tzname,npoints,2,None)
try:
polyline=pl.print_gpx_google_polyline(trk,numLevels,zoomFactor,epsilon,forceEndpoints)
except UnboundLocalError as er:
print(er)
print("Not enough points to create a polyline")
polyline=""
#polyline="polyline"
add_run(gpx,name,act_type,filename,polyline)
def add_point(gpx,lat,lng,elev):
gpx.tracks[0].segments[0].points.append(gpxpy.gpx.GPXTrackPoint(lat, lng, elevation=elev,time=datetime.datetime.now()))
def add_run(gpx, name,act_type,filename,polyline):
conn = sqlite3.connect('%s/activities.db' % filebase)
cursor = conn.cursor()
cursor.execute("""CREATE TABLE if not exists activities
(id INTEGER PRIMARY KEY AUTOINCREMENT,name text, act_date text, distance text,
speed text, act_type text,filename text,polyline text)""")
sql = "INSERT INTO activities VALUES (?,?,?,?,?,?,?,?)"
start_time, end_time = gpx.get_time_bounds()
l2d='{:.3f}'.format(gpx.length_2d() / 1000.)
moving_time, stopped_time, moving_distance, stopped_distance, max_speed = gpx.get_moving_data()
print(max_speed)
#print('%sStopped distance: %sm' % stopped_distance)
maxspeed = 'Max speed: {:.2f}km/h'.format(max_speed * 60. ** 2 / 1000. if max_speed else 0)
duration = 'Duration: {:.2f}min'.format(gpx.get_duration() / 60)
print("-------------------------")
print(name)
print(start_time)
print(l2d)
print(maxspeed)
print("-------------------------")
try:
cursor.execute(sql, [None, name,start_time,l2d,duration,act_type,filename,polyline])
conn.commit()
except sqlite3.Error as er:
print(er)
conn.close()
def get_runs():
#add_run("1", "2", "3", "4")
os.makedirs(filebase, exist_ok=True)
conn = sqlite3.connect('%s/activities.db' % filebase)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute("""CREATE TABLE if not exists activities
(id INTEGER PRIMARY KEY AUTOINCREMENT,name text, act_date text, distance text,
speed text, act_type text,filename text,polyline text)""")
ret_data=[]
sql = "SELECT * FROM activities LIMIT 30"
for i in cursor.execute(sql):
ret_data.append(dict(i))
conn.close()
return ret_data
def get_units():
os.makedirs(filebase, exist_ok=True)
conn = sqlite3.connect('%s/activities.db' % filebase)
cursor = conn.cursor()
cursor.execute("""CREATE TABLE if not exists settings
(units text)""")
ret_data=[]
sql = "SELECT units FROM settings"
cursor.execute(sql)
data=cursor.fetchone()
if data is None:
print("NONESIES")
cursor.execute("INSERT INTO settings VALUES ('kilometers')")
conn.commit()
conn.close()
return "kilometers"
return data
def set_units(label):
os.makedirs(filebase, exist_ok=True)
conn = sqlite3.connect('%s/activities.db' % filebase)
cursor = conn.cursor()
cursor.execute("UPDATE settings SET units=? WHERE 1", (label,))
conn.commit()
conn.close()
def onetime_db_fix():
os.makedirs(filebase, exist_ok=True)
filename = "%s/%s" % (filebase,".dbfixed")
if not os.path.exists(filename):
print("Fixing db")
conn = sqlite3.connect('%s/activities.db' % filebase)
numonly = re.compile("(\d*\.\d*)")
cursor = conn.cursor()
a=get_runs()
sql="UPDATE activities SET distance=? WHERE id=?"
for i in a:
print(i["distance"])
b=numonly.search(i["distance"])
print(b.group(0))
print(b)
cursor.execute(sql, (b.group(0), i["id"]))
conn.commit()
conn.close()
dotfile=open(filename, "w")
dotfile.write("db fixed")
dotfile.close
else:
print("db already fixed")
def rm_run(run):
conn = sqlite3.connect('%s/activities.db' % filebase)
cursor = conn.cursor()
sql = "DELETE from activities WHERE id=?"
try:
cursor.execute(sql, [run])
conn.commit()
except sqlite3.Error as er:
print("-------------______---_____---___----____--____---___-----")
print(er)
conn.close()
def km_to_mi(km):
return km * 0.62137
def get_data():
moving_time, stopped_time, moving_distance, stopped_distance, max_speed = gpx.get_moving_data()
return moving_distance, moving_time
|
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Product.date_added'
db.add_column(u'clone_product', 'date_added',
self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, default=datetime.datetime(2014, 8, 3, 0, 0), blank=True),
keep_default=False)
def backwards(self, orm):
# Deleting field 'Product.date_added'
db.delete_column(u'clone_product', 'date_added')
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'clone.product': {
'Meta': {'object_name': 'Product'},
'base_price': ('django.db.models.fields.FloatField', [], {}),
'currency': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'date_added': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'username': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['clone']
|
class Video(object):
def __init__(self, json):
self.id = json['id']
self.slug = json['slug']
self.title = json['title']
self.presenters = json['presenters']
self.host = json['host']
self.embed_code = json['embed_code']
def presenter_names(self):
return ', '.join(map(lambda p: p['first_name'] + ' ' + p['last_name'], self.presenters))
def url(self):
return 'plugin://plugin.video.%s/?action=play_video&videoid=%s' % (self.host, self.embed_code)
def is_available(self):
return True if self.embed_code else False
|
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1161, 620)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.channel1Check = QtWidgets.QCheckBox(self.centralwidget)
self.channel1Check.setGeometry(QtCore.QRect(10, 10, 161, 17))
self.channel1Check.setChecked(True)
self.channel1Check.setObjectName("channel1Check")
self.channel2Check = QtWidgets.QCheckBox(self.centralwidget)
self.channel2Check.setGeometry(QtCore.QRect(10, 30, 151, 17))
self.channel2Check.setChecked(True)
self.channel2Check.setObjectName("channel2Check")
self.modeWidget = QtWidgets.QTabWidget(self.centralwidget)
self.modeWidget.setGeometry(QtCore.QRect(10, 60, 1131, 451))
self.modeWidget.setObjectName("modeWidget")
self.presetTab = QtWidgets.QWidget()
self.presetTab.setObjectName("presetTab")
self.presetModeWidget = QtWidgets.QTabWidget(self.presetTab)
self.presetModeWidget.setGeometry(QtCore.QRect(6, 10, 1101, 411))
self.presetModeWidget.setLayoutDirection(QtCore.Qt.LeftToRight)
self.presetModeWidget.setObjectName("presetModeWidget")
self.fixedTab = QtWidgets.QWidget()
self.fixedTab.setObjectName("fixedTab")
self.groupBox = QtWidgets.QGroupBox(self.fixedTab)
self.groupBox.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox.setObjectName("groupBox")
self.fixedList = QtWidgets.QListWidget(self.groupBox)
self.fixedList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.fixedList.setObjectName("fixedList")
self.fixedAdd = QtWidgets.QPushButton(self.groupBox)
self.fixedAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.fixedAdd.setObjectName("fixedAdd")
self.fixedDelete = QtWidgets.QPushButton(self.groupBox)
self.fixedDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.fixedDelete.setObjectName("fixedDelete")
self.presetModeWidget.addTab(self.fixedTab, "")
self.breathingTab = QtWidgets.QWidget()
self.breathingTab.setObjectName("breathingTab")
self.groupBox_2 = QtWidgets.QGroupBox(self.breathingTab)
self.groupBox_2.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_2.setObjectName("groupBox_2")
self.breathingList = QtWidgets.QListWidget(self.groupBox_2)
self.breathingList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.breathingList.setObjectName("breathingList")
self.breathingAdd = QtWidgets.QPushButton(self.groupBox_2)
self.breathingAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.breathingAdd.setObjectName("breathingAdd")
self.breathingDelete = QtWidgets.QPushButton(self.groupBox_2)
self.breathingDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.breathingDelete.setObjectName("breathingDelete")
self.groupBox_11 = QtWidgets.QGroupBox(self.breathingTab)
self.groupBox_11.setGeometry(QtCore.QRect(240, 0, 321, 361))
self.groupBox_11.setObjectName("groupBox_11")
self.breathingSpeed = QtWidgets.QSlider(self.groupBox_11)
self.breathingSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.breathingSpeed.setMaximum(4)
self.breathingSpeed.setProperty("value", 2)
self.breathingSpeed.setOrientation(QtCore.Qt.Vertical)
self.breathingSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.breathingSpeed.setObjectName("breathingSpeed")
self.label_2 = QtWidgets.QLabel(self.groupBox_11)
self.label_2.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_2.setObjectName("label_2")
self.label_4 = QtWidgets.QLabel(self.groupBox_11)
self.label_4.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_4.setObjectName("label_4")
self.label_5 = QtWidgets.QLabel(self.groupBox_11)
self.label_5.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_5.setObjectName("label_5")
self.presetModeWidget.addTab(self.breathingTab, "")
self.fadingTab = QtWidgets.QWidget()
self.fadingTab.setObjectName("fadingTab")
self.groupBox_3 = QtWidgets.QGroupBox(self.fadingTab)
self.groupBox_3.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_3.setObjectName("groupBox_3")
self.fadingList = QtWidgets.QListWidget(self.groupBox_3)
self.fadingList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.fadingList.setObjectName("fadingList")
self.fadingAdd = QtWidgets.QPushButton(self.groupBox_3)
self.fadingAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.fadingAdd.setObjectName("fadingAdd")
self.fadingDelete = QtWidgets.QPushButton(self.groupBox_3)
self.fadingDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.fadingDelete.setObjectName("fadingDelete")
self.groupBox_12 = QtWidgets.QGroupBox(self.fadingTab)
self.groupBox_12.setGeometry(QtCore.QRect(240, 0, 321, 361))
self.groupBox_12.setObjectName("groupBox_12")
self.fadingSpeed = QtWidgets.QSlider(self.groupBox_12)
self.fadingSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.fadingSpeed.setMaximum(4)
self.fadingSpeed.setProperty("value", 2)
self.fadingSpeed.setOrientation(QtCore.Qt.Vertical)
self.fadingSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.fadingSpeed.setObjectName("fadingSpeed")
self.label_9 = QtWidgets.QLabel(self.groupBox_12)
self.label_9.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_9.setObjectName("label_9")
self.label_10 = QtWidgets.QLabel(self.groupBox_12)
self.label_10.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_10.setObjectName("label_10")
self.label_11 = QtWidgets.QLabel(self.groupBox_12)
self.label_11.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_11.setObjectName("label_11")
self.presetModeWidget.addTab(self.fadingTab, "")
self.marqueeTab = QtWidgets.QWidget()
self.marqueeTab.setObjectName("marqueeTab")
self.groupBox_4 = QtWidgets.QGroupBox(self.marqueeTab)
self.groupBox_4.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_4.setObjectName("groupBox_4")
self.marqueeList = QtWidgets.QListWidget(self.groupBox_4)
self.marqueeList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.marqueeList.setObjectName("marqueeList")
self.marqueeAdd = QtWidgets.QPushButton(self.groupBox_4)
self.marqueeAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.marqueeAdd.setObjectName("marqueeAdd")
self.marqueeDelete = QtWidgets.QPushButton(self.groupBox_4)
self.marqueeDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.marqueeDelete.setObjectName("marqueeDelete")
self.groupBox_13 = QtWidgets.QGroupBox(self.marqueeTab)
self.groupBox_13.setGeometry(QtCore.QRect(240, 0, 321, 361))
self.groupBox_13.setObjectName("groupBox_13")
self.marqueeSpeed = QtWidgets.QSlider(self.groupBox_13)
self.marqueeSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.marqueeSpeed.setMaximum(4)
self.marqueeSpeed.setProperty("value", 2)
self.marqueeSpeed.setOrientation(QtCore.Qt.Vertical)
self.marqueeSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.marqueeSpeed.setObjectName("marqueeSpeed")
self.label_15 = QtWidgets.QLabel(self.groupBox_13)
self.label_15.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_15.setObjectName("label_15")
self.label_16 = QtWidgets.QLabel(self.groupBox_13)
self.label_16.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_16.setObjectName("label_16")
self.label_17 = QtWidgets.QLabel(self.groupBox_13)
self.label_17.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_17.setObjectName("label_17")
self.marqueeSize = QtWidgets.QSlider(self.groupBox_13)
self.marqueeSize.setGeometry(QtCore.QRect(185, 70, 31, 160))
self.marqueeSize.setMaximum(3)
self.marqueeSize.setProperty("value", 2)
self.marqueeSize.setOrientation(QtCore.Qt.Vertical)
self.marqueeSize.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.marqueeSize.setObjectName("marqueeSize")
self.label_18 = QtWidgets.QLabel(self.groupBox_13)
self.label_18.setGeometry(QtCore.QRect(240, 210, 62, 20))
self.label_18.setObjectName("label_18")
self.label_19 = QtWidgets.QLabel(self.groupBox_13)
self.label_19.setGeometry(QtCore.QRect(180, 40, 62, 20))
self.label_19.setObjectName("label_19")
self.label_20 = QtWidgets.QLabel(self.groupBox_13)
self.label_20.setGeometry(QtCore.QRect(240, 60, 62, 20))
self.label_20.setObjectName("label_20")
self.marqueeBackwards = QtWidgets.QCheckBox(self.groupBox_13)
self.marqueeBackwards.setGeometry(QtCore.QRect(20, 260, 89, 26))
self.marqueeBackwards.setObjectName("marqueeBackwards")
self.presetModeWidget.addTab(self.marqueeTab, "")
self.coverMarqueeTab = QtWidgets.QWidget()
self.coverMarqueeTab.setObjectName("coverMarqueeTab")
self.groupBox_5 = QtWidgets.QGroupBox(self.coverMarqueeTab)
self.groupBox_5.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_5.setObjectName("groupBox_5")
self.coverMarqueeList = QtWidgets.QListWidget(self.groupBox_5)
self.coverMarqueeList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.coverMarqueeList.setObjectName("coverMarqueeList")
self.coverMarqueeAdd = QtWidgets.QPushButton(self.groupBox_5)
self.coverMarqueeAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.coverMarqueeAdd.setObjectName("coverMarqueeAdd")
self.coverMarqueeDelete = QtWidgets.QPushButton(self.groupBox_5)
self.coverMarqueeDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.coverMarqueeDelete.setObjectName("coverMarqueeDelete")
self.groupBox_15 = QtWidgets.QGroupBox(self.coverMarqueeTab)
self.groupBox_15.setGeometry(QtCore.QRect(240, 0, 321, 361))
self.groupBox_15.setObjectName("groupBox_15")
self.coverMarqueeSpeed = QtWidgets.QSlider(self.groupBox_15)
self.coverMarqueeSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.coverMarqueeSpeed.setMaximum(4)
self.coverMarqueeSpeed.setProperty("value", 2)
self.coverMarqueeSpeed.setOrientation(QtCore.Qt.Vertical)
self.coverMarqueeSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.coverMarqueeSpeed.setObjectName("coverMarqueeSpeed")
self.label_27 = QtWidgets.QLabel(self.groupBox_15)
self.label_27.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_27.setObjectName("label_27")
self.label_28 = QtWidgets.QLabel(self.groupBox_15)
self.label_28.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_28.setObjectName("label_28")
self.label_29 = QtWidgets.QLabel(self.groupBox_15)
self.label_29.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_29.setObjectName("label_29")
self.coverMarqueeBackwards = QtWidgets.QCheckBox(self.groupBox_15)
self.coverMarqueeBackwards.setGeometry(QtCore.QRect(20, 260, 89, 26))
self.coverMarqueeBackwards.setObjectName("coverMarqueeBackwards")
self.presetModeWidget.addTab(self.coverMarqueeTab, "")
self.pulseTab = QtWidgets.QWidget()
self.pulseTab.setObjectName("pulseTab")
self.groupBox_6 = QtWidgets.QGroupBox(self.pulseTab)
self.groupBox_6.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_6.setObjectName("groupBox_6")
self.pulseList = QtWidgets.QListWidget(self.groupBox_6)
self.pulseList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.pulseList.setObjectName("pulseList")
self.pulseAdd = QtWidgets.QPushButton(self.groupBox_6)
self.pulseAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.pulseAdd.setObjectName("pulseAdd")
self.pulseDelete = QtWidgets.QPushButton(self.groupBox_6)
self.pulseDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.pulseDelete.setObjectName("pulseDelete")
self.groupBox_16 = QtWidgets.QGroupBox(self.pulseTab)
self.groupBox_16.setGeometry(QtCore.QRect(240, 0, 321, 361))
self.groupBox_16.setObjectName("groupBox_16")
self.pulseSpeed = QtWidgets.QSlider(self.groupBox_16)
self.pulseSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.pulseSpeed.setMaximum(4)
self.pulseSpeed.setProperty("value", 2)
self.pulseSpeed.setOrientation(QtCore.Qt.Vertical)
self.pulseSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.pulseSpeed.setObjectName("pulseSpeed")
self.label_33 = QtWidgets.QLabel(self.groupBox_16)
self.label_33.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_33.setObjectName("label_33")
self.label_34 = QtWidgets.QLabel(self.groupBox_16)
self.label_34.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_34.setObjectName("label_34")
self.label_35 = QtWidgets.QLabel(self.groupBox_16)
self.label_35.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_35.setObjectName("label_35")
self.presetModeWidget.addTab(self.pulseTab, "")
self.spectrumTab = QtWidgets.QWidget()
self.spectrumTab.setObjectName("spectrumTab")
self.groupBox_17 = QtWidgets.QGroupBox(self.spectrumTab)
self.groupBox_17.setGeometry(QtCore.QRect(0, 0, 321, 361))
self.groupBox_17.setObjectName("groupBox_17")
self.spectrumSpeed = QtWidgets.QSlider(self.groupBox_17)
self.spectrumSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.spectrumSpeed.setMaximum(4)
self.spectrumSpeed.setProperty("value", 2)
self.spectrumSpeed.setOrientation(QtCore.Qt.Vertical)
self.spectrumSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.spectrumSpeed.setObjectName("spectrumSpeed")
self.label_39 = QtWidgets.QLabel(self.groupBox_17)
self.label_39.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_39.setObjectName("label_39")
self.label_40 = QtWidgets.QLabel(self.groupBox_17)
self.label_40.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_40.setObjectName("label_40")
self.label_41 = QtWidgets.QLabel(self.groupBox_17)
self.label_41.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_41.setObjectName("label_41")
self.spectrumBackwards = QtWidgets.QCheckBox(self.groupBox_17)
self.spectrumBackwards.setGeometry(QtCore.QRect(20, 260, 89, 26))
self.spectrumBackwards.setObjectName("spectrumBackwards")
self.presetModeWidget.addTab(self.spectrumTab, "")
self.alternatingTab = QtWidgets.QWidget()
self.alternatingTab.setObjectName("alternatingTab")
self.groupBox_7 = QtWidgets.QGroupBox(self.alternatingTab)
self.groupBox_7.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_7.setObjectName("groupBox_7")
self.alternatingList = QtWidgets.QListWidget(self.groupBox_7)
self.alternatingList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.alternatingList.setObjectName("alternatingList")
self.alternatingAdd = QtWidgets.QPushButton(self.groupBox_7)
self.alternatingAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.alternatingAdd.setObjectName("alternatingAdd")
self.alternatingDelete = QtWidgets.QPushButton(self.groupBox_7)
self.alternatingDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.alternatingDelete.setObjectName("alternatingDelete")
self.groupBox_18 = QtWidgets.QGroupBox(self.alternatingTab)
self.groupBox_18.setGeometry(QtCore.QRect(240, 0, 321, 361))
self.groupBox_18.setObjectName("groupBox_18")
self.alternatingSpeed = QtWidgets.QSlider(self.groupBox_18)
self.alternatingSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.alternatingSpeed.setMaximum(4)
self.alternatingSpeed.setProperty("value", 2)
self.alternatingSpeed.setOrientation(QtCore.Qt.Vertical)
self.alternatingSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.alternatingSpeed.setObjectName("alternatingSpeed")
self.label_45 = QtWidgets.QLabel(self.groupBox_18)
self.label_45.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_45.setObjectName("label_45")
self.label_46 = QtWidgets.QLabel(self.groupBox_18)
self.label_46.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_46.setObjectName("label_46")
self.label_47 = QtWidgets.QLabel(self.groupBox_18)
self.label_47.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_47.setObjectName("label_47")
self.alternatingSize = QtWidgets.QSlider(self.groupBox_18)
self.alternatingSize.setGeometry(QtCore.QRect(185, 70, 31, 160))
self.alternatingSize.setMaximum(3)
self.alternatingSize.setProperty("value", 2)
self.alternatingSize.setOrientation(QtCore.Qt.Vertical)
self.alternatingSize.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.alternatingSize.setObjectName("alternatingSize")
self.label_48 = QtWidgets.QLabel(self.groupBox_18)
self.label_48.setGeometry(QtCore.QRect(240, 210, 62, 20))
self.label_48.setObjectName("label_48")
self.label_49 = QtWidgets.QLabel(self.groupBox_18)
self.label_49.setGeometry(QtCore.QRect(180, 40, 62, 20))
self.label_49.setObjectName("label_49")
self.label_50 = QtWidgets.QLabel(self.groupBox_18)
self.label_50.setGeometry(QtCore.QRect(240, 60, 62, 20))
self.label_50.setObjectName("label_50")
self.alternatingBackwards = QtWidgets.QCheckBox(self.groupBox_18)
self.alternatingBackwards.setGeometry(QtCore.QRect(20, 260, 89, 26))
self.alternatingBackwards.setObjectName("alternatingBackwards")
self.alternatingMoving = QtWidgets.QCheckBox(self.groupBox_18)
self.alternatingMoving.setGeometry(QtCore.QRect(20, 290, 89, 26))
self.alternatingMoving.setObjectName("alternatingMoving")
self.presetModeWidget.addTab(self.alternatingTab, "")
self.candleTab = QtWidgets.QWidget()
self.candleTab.setObjectName("candleTab")
self.groupBox_8 = QtWidgets.QGroupBox(self.candleTab)
self.groupBox_8.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_8.setObjectName("groupBox_8")
self.candleList = QtWidgets.QListWidget(self.groupBox_8)
self.candleList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.candleList.setObjectName("candleList")
self.candleAdd = QtWidgets.QPushButton(self.groupBox_8)
self.candleAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.candleAdd.setObjectName("candleAdd")
self.candleDelete = QtWidgets.QPushButton(self.groupBox_8)
self.candleDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.candleDelete.setObjectName("candleDelete")
self.presetModeWidget.addTab(self.candleTab, "")
self.wingsTab = QtWidgets.QWidget()
self.wingsTab.setObjectName("wingsTab")
self.groupBox_9 = QtWidgets.QGroupBox(self.wingsTab)
self.groupBox_9.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_9.setObjectName("groupBox_9")
self.wingsList = QtWidgets.QListWidget(self.groupBox_9)
self.wingsList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.wingsList.setObjectName("wingsList")
self.wingsAdd = QtWidgets.QPushButton(self.groupBox_9)
self.wingsAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.wingsAdd.setObjectName("wingsAdd")
self.wingsDelete = QtWidgets.QPushButton(self.groupBox_9)
self.wingsDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.wingsDelete.setObjectName("wingsDelete")
self.groupBox_20 = QtWidgets.QGroupBox(self.wingsTab)
self.groupBox_20.setGeometry(QtCore.QRect(240, 0, 321, 361))
self.groupBox_20.setObjectName("groupBox_20")
self.wingsSpeed = QtWidgets.QSlider(self.groupBox_20)
self.wingsSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.wingsSpeed.setMaximum(4)
self.wingsSpeed.setProperty("value", 2)
self.wingsSpeed.setOrientation(QtCore.Qt.Vertical)
self.wingsSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.wingsSpeed.setObjectName("wingsSpeed")
self.label_57 = QtWidgets.QLabel(self.groupBox_20)
self.label_57.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_57.setObjectName("label_57")
self.label_58 = QtWidgets.QLabel(self.groupBox_20)
self.label_58.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_58.setObjectName("label_58")
self.label_59 = QtWidgets.QLabel(self.groupBox_20)
self.label_59.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_59.setObjectName("label_59")
self.presetModeWidget.addTab(self.wingsTab, "")
self.audioLevelTab = QtWidgets.QWidget()
self.audioLevelTab.setObjectName("audioLevelTab")
self.groupBox_21 = QtWidgets.QGroupBox(self.audioLevelTab)
self.groupBox_21.setGeometry(QtCore.QRect(240, 0, 321, 361))
self.groupBox_21.setObjectName("groupBox_21")
self.label_60 = QtWidgets.QLabel(self.groupBox_21)
self.label_60.setGeometry(QtCore.QRect(10, 30, 62, 20))
self.label_60.setObjectName("label_60")
self.label_61 = QtWidgets.QLabel(self.groupBox_21)
self.label_61.setGeometry(QtCore.QRect(10, 80, 81, 20))
self.label_61.setObjectName("label_61")
self.audioLevelTolerance = QtWidgets.QDoubleSpinBox(self.groupBox_21)
self.audioLevelTolerance.setGeometry(QtCore.QRect(10, 50, 68, 23))
self.audioLevelTolerance.setDecimals(1)
self.audioLevelTolerance.setProperty("value", 1.0)
self.audioLevelTolerance.setObjectName("audioLevelTolerance")
self.audioLevelSmooth = QtWidgets.QDoubleSpinBox(self.groupBox_21)
self.audioLevelSmooth.setGeometry(QtCore.QRect(10, 100, 68, 23))
self.audioLevelSmooth.setDecimals(0)
self.audioLevelSmooth.setProperty("value", 3.0)
self.audioLevelSmooth.setObjectName("audioLevelSmooth")
self.groupBox_10 = QtWidgets.QGroupBox(self.audioLevelTab)
self.groupBox_10.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_10.setObjectName("groupBox_10")
self.audioLevelList = QtWidgets.QListWidget(self.groupBox_10)
self.audioLevelList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.audioLevelList.setObjectName("audioLevelList")
self.audioLevelAdd = QtWidgets.QPushButton(self.groupBox_10)
self.audioLevelAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.audioLevelAdd.setObjectName("audioLevelAdd")
self.audioLevelDelete = QtWidgets.QPushButton(self.groupBox_10)
self.audioLevelDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.audioLevelDelete.setObjectName("audioLevelDelete")
self.presetModeWidget.addTab(self.audioLevelTab, "")
self.customTab = QtWidgets.QWidget()
self.customTab.setObjectName("customTab")
self.groupBox_22 = QtWidgets.QGroupBox(self.customTab)
self.groupBox_22.setGeometry(QtCore.QRect(630, 0, 321, 371))
self.groupBox_22.setObjectName("groupBox_22")
self.customSpeed = QtWidgets.QSlider(self.groupBox_22)
self.customSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.customSpeed.setMaximum(4)
self.customSpeed.setProperty("value", 2)
self.customSpeed.setOrientation(QtCore.Qt.Vertical)
self.customSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.customSpeed.setObjectName("customSpeed")
self.label_62 = QtWidgets.QLabel(self.groupBox_22)
self.label_62.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_62.setObjectName("label_62")
self.label_63 = QtWidgets.QLabel(self.groupBox_22)
self.label_63.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_63.setObjectName("label_63")
self.label_64 = QtWidgets.QLabel(self.groupBox_22)
self.label_64.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_64.setObjectName("label_64")
self.customMode = QtWidgets.QComboBox(self.groupBox_22)
self.customMode.setGeometry(QtCore.QRect(190, 70, 86, 25))
self.customMode.setObjectName("customMode")
self.customMode.addItem("")
self.customMode.addItem("")
self.customMode.addItem("")
self.label_65 = QtWidgets.QLabel(self.groupBox_22)
self.label_65.setGeometry(QtCore.QRect(190, 40, 62, 20))
self.label_65.setObjectName("label_65")
self.groupBox_19 = QtWidgets.QGroupBox(self.customTab)
self.groupBox_19.setGeometry(QtCore.QRect(0, 0, 611, 371))
self.groupBox_19.setObjectName("groupBox_19")
self.customTable = QtWidgets.QTableWidget(self.groupBox_19)
self.customTable.setGeometry(QtCore.QRect(10, 30, 471, 331))
self.customTable.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self.customTable.setDragDropOverwriteMode(False)
self.customTable.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
self.customTable.setRowCount(40)
self.customTable.setColumnCount(2)
self.customTable.setObjectName("customTable")
item = QtWidgets.QTableWidgetItem()
self.customTable.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.customTable.setHorizontalHeaderItem(1, item)
self.customTable.verticalHeader().setVisible(False)
self.customEdit = QtWidgets.QPushButton(self.groupBox_19)
self.customEdit.setGeometry(QtCore.QRect(500, 40, 83, 28))
self.customEdit.setObjectName("customEdit")
self.presetModeWidget.addTab(self.customTab, "")
self.profileTab = QtWidgets.QWidget()
self.profileTab.setObjectName("profileTab")
self.groupBox_14 = QtWidgets.QGroupBox(self.profileTab)
self.groupBox_14.setGeometry(QtCore.QRect(0, 0, 421, 361))
self.groupBox_14.setObjectName("groupBox_14")
self.profileList = QtWidgets.QListWidget(self.groupBox_14)
self.profileList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.profileList.setObjectName("profileList")
self.profileAdd = QtWidgets.QPushButton(self.groupBox_14)
self.profileAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.profileAdd.setObjectName("profileAdd")
self.profileDelete = QtWidgets.QPushButton(self.groupBox_14)
self.profileDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.profileDelete.setObjectName("profileDelete")
self.profileRefresh = QtWidgets.QPushButton(self.groupBox_14)
self.profileRefresh.setGeometry(QtCore.QRect(130, 130, 83, 28))
self.profileRefresh.setObjectName("profileRefresh")
self.profileName = QtWidgets.QLineEdit(self.groupBox_14)
self.profileName.setGeometry(QtCore.QRect(300, 50, 113, 28))
self.profileName.setObjectName("profileName")
self.label_3 = QtWidgets.QLabel(self.groupBox_14)
self.label_3.setGeometry(QtCore.QRect(220, 50, 62, 20))
self.label_3.setObjectName("label_3")
self.presetModeWidget.addTab(self.profileTab, "")
self.animatedTab = QtWidgets.QWidget()
self.animatedTab.setObjectName("animatedTab")
self.groupBox_23 = QtWidgets.QGroupBox(self.animatedTab)
self.groupBox_23.setGeometry(QtCore.QRect(0, 0, 721, 371))
self.groupBox_23.setObjectName("groupBox_23")
self.animatedTable = QtWidgets.QTableWidget(self.groupBox_23)
self.animatedTable.setGeometry(QtCore.QRect(230, 30, 361, 331))
self.animatedTable.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self.animatedTable.setDragDropOverwriteMode(False)
self.animatedTable.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
self.animatedTable.setRowCount(40)
self.animatedTable.setColumnCount(2)
self.animatedTable.setObjectName("animatedTable")
item = QtWidgets.QTableWidgetItem()
self.animatedTable.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.animatedTable.setHorizontalHeaderItem(1, item)
self.animatedTable.verticalHeader().setVisible(False)
self.animatedEdit = QtWidgets.QPushButton(self.groupBox_23)
self.animatedEdit.setGeometry(QtCore.QRect(610, 40, 83, 28))
self.animatedEdit.setObjectName("animatedEdit")
self.animatedList = QtWidgets.QListWidget(self.groupBox_23)
self.animatedList.setGeometry(QtCore.QRect(10, 40, 111, 291))
self.animatedList.setObjectName("animatedList")
self.animatedDelete = QtWidgets.QPushButton(self.groupBox_23)
self.animatedDelete.setGeometry(QtCore.QRect(130, 80, 83, 28))
self.animatedDelete.setObjectName("animatedDelete")
self.animatedAdd = QtWidgets.QPushButton(self.groupBox_23)
self.animatedAdd.setGeometry(QtCore.QRect(130, 40, 83, 28))
self.animatedAdd.setObjectName("animatedAdd")
self.animatedRoundName = QtWidgets.QLineEdit(self.groupBox_23)
self.animatedRoundName.setGeometry(QtCore.QRect(130, 120, 81, 25))
self.animatedRoundName.setObjectName("animatedRoundName")
self.groupBox_24 = QtWidgets.QGroupBox(self.animatedTab)
self.groupBox_24.setGeometry(QtCore.QRect(740, 0, 331, 371))
self.groupBox_24.setObjectName("groupBox_24")
self.label_66 = QtWidgets.QLabel(self.groupBox_24)
self.label_66.setGeometry(QtCore.QRect(10, 40, 201, 20))
self.label_66.setObjectName("label_66")
self.animatedSpeed = QtWidgets.QDoubleSpinBox(self.groupBox_24)
self.animatedSpeed.setGeometry(QtCore.QRect(10, 70, 68, 26))
self.animatedSpeed.setDecimals(0)
self.animatedSpeed.setMinimum(15.0)
self.animatedSpeed.setMaximum(5000.0)
self.animatedSpeed.setSingleStep(10.0)
self.animatedSpeed.setProperty("value", 50.0)
self.animatedSpeed.setObjectName("animatedSpeed")
self.label_21 = QtWidgets.QLabel(self.groupBox_24)
self.label_21.setGeometry(QtCore.QRect(40, 130, 261, 71))
self.label_21.setWordWrap(True)
self.label_21.setObjectName("label_21")
self.presetModeWidget.addTab(self.animatedTab, "")
self.modeWidget.addTab(self.presetTab, "")
self.timesTab = QtWidgets.QWidget()
self.timesTab.setObjectName("timesTab")
self.label_7 = QtWidgets.QLabel(self.timesTab)
self.label_7.setGeometry(QtCore.QRect(30, 20, 461, 17))
self.label_7.setObjectName("label_7")
self.offTime = QtWidgets.QLineEdit(self.timesTab)
self.offTime.setGeometry(QtCore.QRect(30, 40, 113, 25))
self.offTime.setObjectName("offTime")
self.onTime = QtWidgets.QLineEdit(self.timesTab)
self.onTime.setGeometry(QtCore.QRect(30, 100, 113, 25))
self.onTime.setObjectName("onTime")
self.label_8 = QtWidgets.QLabel(self.timesTab)
self.label_8.setGeometry(QtCore.QRect(30, 80, 461, 17))
self.label_8.setObjectName("label_8")
self.label_12 = QtWidgets.QLabel(self.timesTab)
self.label_12.setGeometry(QtCore.QRect(160, 50, 131, 17))
self.label_12.setObjectName("label_12")
self.label_13 = QtWidgets.QLabel(self.timesTab)
self.label_13.setGeometry(QtCore.QRect(160, 110, 131, 17))
self.label_13.setObjectName("label_13")
self.label_14 = QtWidgets.QLabel(self.timesTab)
self.label_14.setGeometry(QtCore.QRect(30, 140, 341, 111))
font = QtGui.QFont()
font.setPointSize(11)
self.label_14.setFont(font)
self.label_14.setWordWrap(True)
self.label_14.setObjectName("label_14")
self.timeSave = QtWidgets.QPushButton(self.timesTab)
self.timeSave.setGeometry(QtCore.QRect(40, 290, 82, 25))
self.timeSave.setObjectName("timeSave")
self.modeWidget.addTab(self.timesTab, "")
self.applyBtn = QtWidgets.QPushButton(self.centralwidget)
self.applyBtn.setGeometry(QtCore.QRect(490, 530, 101, 41))
self.applyBtn.setObjectName("applyBtn")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(940, 20, 62, 20))
self.label.setObjectName("label")
self.portTxt = QtWidgets.QLineEdit(self.centralwidget)
self.portTxt.setGeometry(QtCore.QRect(1000, 20, 113, 28))
self.portTxt.setObjectName("portTxt")
self.label_6 = QtWidgets.QLabel(self.centralwidget)
self.label_6.setGeometry(QtCore.QRect(180, -10, 741, 91))
font = QtGui.QFont()
font.setPointSize(13)
self.label_6.setFont(font)
self.label_6.setWordWrap(True)
self.label_6.setObjectName("label_6")
self.unitLEDBtn = QtWidgets.QPushButton(self.centralwidget)
self.unitLEDBtn.setGeometry(QtCore.QRect(840, 50, 121, 21))
self.unitLEDBtn.setObjectName("unitLEDBtn")
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
self.modeWidget.setCurrentIndex(0)
self.presetModeWidget.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
MainWindow.setTabOrder(self.channel1Check, self.channel2Check)
MainWindow.setTabOrder(self.channel2Check, self.modeWidget)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "hue_plus"))
self.channel1Check.setText(_translate("MainWindow", "Channel 1"))
self.channel2Check.setText(_translate("MainWindow", "Channel 2"))
self.groupBox.setTitle(_translate("MainWindow", "Colors"))
self.fixedAdd.setText(_translate("MainWindow", "Add color"))
self.fixedDelete.setText(_translate("MainWindow", "Delete color"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.fixedTab), _translate("MainWindow", "Fixed"))
self.groupBox_2.setTitle(_translate("MainWindow", "Colors"))
self.breathingAdd.setText(_translate("MainWindow", "Add color"))
self.breathingDelete.setText(_translate("MainWindow", "Delete color"))
self.groupBox_11.setTitle(_translate("MainWindow", "Other"))
self.label_2.setText(_translate("MainWindow", "Speed"))
self.label_4.setText(_translate("MainWindow", "Fastest"))
self.label_5.setText(_translate("MainWindow", "Slowest"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.breathingTab), _translate("MainWindow", "Breathing"))
self.groupBox_3.setTitle(_translate("MainWindow", "Colors"))
self.fadingAdd.setText(_translate("MainWindow", "Add color"))
self.fadingDelete.setText(_translate("MainWindow", "Delete color"))
self.groupBox_12.setTitle(_translate("MainWindow", "Other"))
self.label_9.setText(_translate("MainWindow", "Speed"))
self.label_10.setText(_translate("MainWindow", "Fastest"))
self.label_11.setText(_translate("MainWindow", "Slowest"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.fadingTab), _translate("MainWindow", "Fading"))
self.groupBox_4.setTitle(_translate("MainWindow", "Colors"))
self.marqueeAdd.setText(_translate("MainWindow", "Add color"))
self.marqueeDelete.setText(_translate("MainWindow", "Delete color"))
self.groupBox_13.setTitle(_translate("MainWindow", "Other"))
self.label_15.setText(_translate("MainWindow", "Speed"))
self.label_16.setText(_translate("MainWindow", "Fastest"))
self.label_17.setText(_translate("MainWindow", "Slowest"))
self.label_18.setText(_translate("MainWindow", "Smaller"))
self.label_19.setText(_translate("MainWindow", "Size"))
self.label_20.setText(_translate("MainWindow", "Larger"))
self.marqueeBackwards.setText(_translate("MainWindow", "Backwards"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.marqueeTab), _translate("MainWindow", "Marquee"))
self.groupBox_5.setTitle(_translate("MainWindow", "Colors"))
self.coverMarqueeAdd.setText(_translate("MainWindow", "Add color"))
self.coverMarqueeDelete.setText(_translate("MainWindow", "Delete color"))
self.groupBox_15.setTitle(_translate("MainWindow", "Other"))
self.label_27.setText(_translate("MainWindow", "Speed"))
self.label_28.setText(_translate("MainWindow", "Fastest"))
self.label_29.setText(_translate("MainWindow", "Slowest"))
self.coverMarqueeBackwards.setText(_translate("MainWindow", "Backwards"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.coverMarqueeTab), _translate("MainWindow", "Covering Marquee"))
self.groupBox_6.setTitle(_translate("MainWindow", "Colors"))
self.pulseAdd.setText(_translate("MainWindow", "Add color"))
self.pulseDelete.setText(_translate("MainWindow", "Delete color"))
self.groupBox_16.setTitle(_translate("MainWindow", "Other"))
self.label_33.setText(_translate("MainWindow", "Speed"))
self.label_34.setText(_translate("MainWindow", "Fastest"))
self.label_35.setText(_translate("MainWindow", "Slowest"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.pulseTab), _translate("MainWindow", "Pulse"))
self.groupBox_17.setTitle(_translate("MainWindow", "Other"))
self.label_39.setText(_translate("MainWindow", "Speed"))
self.label_40.setText(_translate("MainWindow", "Fastest"))
self.label_41.setText(_translate("MainWindow", "Slowest"))
self.spectrumBackwards.setText(_translate("MainWindow", "Backwards"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.spectrumTab), _translate("MainWindow", "Spectrum"))
self.groupBox_7.setTitle(_translate("MainWindow", "Colors"))
self.alternatingAdd.setText(_translate("MainWindow", "Add color"))
self.alternatingDelete.setText(_translate("MainWindow", "Delete color"))
self.groupBox_18.setTitle(_translate("MainWindow", "Other"))
self.label_45.setText(_translate("MainWindow", "Speed"))
self.label_46.setText(_translate("MainWindow", "Fastest"))
self.label_47.setText(_translate("MainWindow", "Slowest"))
self.label_48.setText(_translate("MainWindow", "Smaller"))
self.label_49.setText(_translate("MainWindow", "Size"))
self.label_50.setText(_translate("MainWindow", "Larger"))
self.alternatingBackwards.setText(_translate("MainWindow", "Backwards"))
self.alternatingMoving.setText(_translate("MainWindow", "Moving"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.alternatingTab), _translate("MainWindow", "Alternating"))
self.groupBox_8.setTitle(_translate("MainWindow", "Colors"))
self.candleAdd.setText(_translate("MainWindow", "Add color"))
self.candleDelete.setText(_translate("MainWindow", "Delete color"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.candleTab), _translate("MainWindow", "Candle"))
self.groupBox_9.setTitle(_translate("MainWindow", "Colors"))
self.wingsAdd.setText(_translate("MainWindow", "Add color"))
self.wingsDelete.setText(_translate("MainWindow", "Delete color"))
self.groupBox_20.setTitle(_translate("MainWindow", "Other"))
self.label_57.setText(_translate("MainWindow", "Speed"))
self.label_58.setText(_translate("MainWindow", "Fastest"))
self.label_59.setText(_translate("MainWindow", "Slowest"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.wingsTab), _translate("MainWindow", "Wings"))
self.groupBox_21.setTitle(_translate("MainWindow", "Other"))
self.label_60.setText(_translate("MainWindow", "Tolerance"))
self.label_61.setText(_translate("MainWindow", "Smoothness"))
self.groupBox_10.setTitle(_translate("MainWindow", "Colors"))
self.audioLevelAdd.setText(_translate("MainWindow", "Add color"))
self.audioLevelDelete.setText(_translate("MainWindow", "Delete color"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.audioLevelTab), _translate("MainWindow", "Audio Level"))
self.groupBox_22.setTitle(_translate("MainWindow", "Other"))
self.label_62.setText(_translate("MainWindow", "Speed"))
self.label_63.setText(_translate("MainWindow", "Fastest"))
self.label_64.setText(_translate("MainWindow", "Slowest"))
self.customMode.setItemText(0, _translate("MainWindow", "Fixed"))
self.customMode.setItemText(1, _translate("MainWindow", "Breathing"))
self.customMode.setItemText(2, _translate("MainWindow", "Wave"))
self.label_65.setText(_translate("MainWindow", "Mode"))
self.groupBox_19.setTitle(_translate("MainWindow", "Colors"))
item = self.customTable.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "LED #"))
item = self.customTable.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "Colors"))
self.customEdit.setText(_translate("MainWindow", "Edit Color"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.customTab), _translate("MainWindow", "Custom"))
self.groupBox_14.setTitle(_translate("MainWindow", "Profiles"))
self.profileAdd.setText(_translate("MainWindow", "Add profile"))
self.profileDelete.setText(_translate("MainWindow", "Delete profile"))
self.profileRefresh.setText(_translate("MainWindow", "Refresh"))
self.profileName.setText(_translate("MainWindow", "profile1"))
self.label_3.setText(_translate("MainWindow", "Name:"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.profileTab), _translate("MainWindow", "Profiles"))
self.groupBox_23.setTitle(_translate("MainWindow", "Colors"))
item = self.animatedTable.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "LED #"))
item = self.animatedTable.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "Colors"))
self.animatedEdit.setText(_translate("MainWindow", "Edit Color"))
self.animatedDelete.setText(_translate("MainWindow", "Delete round"))
self.animatedAdd.setText(_translate("MainWindow", "Add round"))
self.animatedRoundName.setText(_translate("MainWindow", "round1"))
self.groupBox_24.setTitle(_translate("MainWindow", "Other"))
self.label_66.setText(_translate("MainWindow", "Speed between refresh, in ms"))
self.label_21.setText(_translate("MainWindow", "To use, simply set a custom pattern for each round."))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.animatedTab), _translate("MainWindow", "Custom Animated"))
self.modeWidget.setTabText(self.modeWidget.indexOf(self.presetTab), _translate("MainWindow", "Preset"))
self.label_7.setText(_translate("MainWindow", "The time to turn off the lights (in 24 hour time, separated by a colon)"))
self.offTime.setText(_translate("MainWindow", "00:00"))
self.onTime.setText(_translate("MainWindow", "00:00"))
self.label_8.setText(_translate("MainWindow", "The time to turn on the lights (in 24 hour time, separated by a colon)"))
self.label_12.setText(_translate("MainWindow", "00:00 means none"))
self.label_13.setText(_translate("MainWindow", "00:00 means none"))
self.label_14.setText(_translate("MainWindow", "This looks for a profile called previous and uses that. If that profile does not exist, the time will not work."))
self.timeSave.setText(_translate("MainWindow", "Save"))
self.modeWidget.setTabText(self.modeWidget.indexOf(self.timesTab), _translate("MainWindow", "Times"))
self.applyBtn.setText(_translate("MainWindow", "Apply"))
self.label.setText(_translate("MainWindow", "Port:"))
self.portTxt.setText(_translate("MainWindow", "/dev/ttyACM0"))
self.label_6.setText(_translate("MainWindow", "Now with support for turning on and off at specific times, audio on Windows, a way to make your own modes, and more!"))
self.unitLEDBtn.setText(_translate("MainWindow", "Toggle Unit LED"))
|
import praw
import json
import requests
import tweepy
import time
import os
import csv
import re
import configparser
import urllib.parse
import sys
from glob import glob
from gfycat.client import GfycatClient
from imgurpython import ImgurClient
import distutils.core
import itertools
import photohash
from PIL import Image
import urllib.request
CONFIG_FILE = 'config.ini'
def strip_title(title):
# Shortlink is 22 characters long, plus one character for a space
if len(title) < 280:
return title
else:
return title[:276] + '...'
def save_file(img_url, file_path):
resp = requests.get(img_url, stream=True)
if resp.status_code == 200:
with open(file_path, 'wb') as image_file:
for chunk in resp:
image_file.write(chunk)
# Return the path of the image, which is always the same since we just overwrite images
return file_path
else:
print('[EROR] File failed to download. Status code: ' + str(resp.status_code))
return
def get_media(img_url, post_id):
if any(s in img_url for s in ('i.redd.it', 'i.reddituploads.com')):
file_name = os.path.basename(urllib.parse.urlsplit(img_url).path)
file_extension = os.path.splitext(img_url)[-1].lower()
# Fix for issue with i.reddituploads.com links not having a file extension in the URL
if not file_extension:
file_extension += '.jpg'
file_name += '.jpg'
img_url += '.jpg'
# Grab the GIF versions of .GIFV links
# When Tweepy adds support for video uploads, we can use grab the MP4 versions
if (file_extension == '.gifv'):
file_extension = file_extension.replace('.gifv', '.gif')
file_name = file_name.replace('.gifv', '.gif')
img_url = img_url.replace('.gifv', '.gif')
# Download the file
file_path = IMAGE_DIR + '/' + file_name
print('[ OK ] Downloading file at URL ' + img_url + ' to ' + file_path + ', file type identified as ' + file_extension)
img = save_file(img_url, file_path)
return img
elif ('imgur.com' in img_url): # Imgur
try:
client = ImgurClient(IMGUR_CLIENT, IMGUR_CLIENT_SECRET)
except BaseException as e:
print ('[EROR] Error while authenticating with Imgur:', str(e))
return
# Working demo of regex: https://regex101.com/r/G29uGl/2
regex = r"(?:.*)imgur\.com(?:\/gallery\/|\/a\/|\/)(.*?)(?:\/.*|\.|$)"
m = re.search(regex, img_url, flags=0)
if m:
# Get the Imgur image/gallery ID
id = m.group(1)
if any(s in img_url for s in ('/a/', '/gallery/')): # Gallery links
images = client.get_album_images(id)
# Only the first image in a gallery is used
imgur_url = images[0].link
else: # Single image
imgur_url = client.get_image(id).link
# If the URL is a GIFV link, change it to a GIF
file_extension = os.path.splitext(imgur_url)[-1].lower()
if (file_extension == '.gifv'):
file_extension = file_extension.replace('.gifv', '.gif')
img_url = imgur_url.replace('.gifv', '.gif')
# Download the image
file_path = IMAGE_DIR + '/' + id + file_extension
print('[ OK ] Downloading Imgur image at URL ' + imgur_url + ' to ' + file_path)
imgur_file = save_file(imgur_url, file_path)
# Imgur will sometimes return a single-frame thumbnail instead of a GIF, so we need to check for this
if (file_extension == '.gif'):
# Open the file using the Pillow library
img = Image.open(imgur_file)
# Get the MIME type
mime = Image.MIME[img.format]
if (mime == 'image/gif'):
# Image is indeed a GIF, so it can be posted
img.close()
return imgur_file
else:
# Image is not actually a GIF, so don't post it
print('[EROR] Imgur has not processed a GIF version of this link, so it can not be posted')
img.close()
# Delete the image
try:
os.remove(imgur_file)
except BaseException as e:
print ('[EROR] Error while deleting media file:', str(e))
return
else:
return imgur_file
else:
print('[EROR] Could not identify Imgur image/gallery ID in this URL:', img_url)
return
elif ('gfycat.com' in img_url): # Gfycat
gfycat_name = os.path.basename(urllib.parse.urlsplit(img_url).path)
client = GfycatClient()
gfycat_info = client.query_gfy(gfycat_name)
# Download the 2MB version because Tweepy has a 3MB upload limit for GIFs
gfycat_url = gfycat_info['gfyItem']['max2mbGif']
file_path = IMAGE_DIR + '/' + gfycat_name + '.gif'
print('[ OK ] Downloading Gfycat at URL ' + gfycat_url + ' to ' + file_path)
gfycat_file = save_file(gfycat_url, file_path)
return gfycat_file
elif ('giphy.com' in img_url): # Giphy
# Working demo of regex: https://regex101.com/r/o8m1kA/2
regex = r"https?://((?:.*)giphy\.com/media/|giphy.com/gifs/|i.giphy.com/)(.*-)?(\w+)(/|\n)"
m = re.search(regex, img_url, flags=0)
if m:
# Get the Giphy ID
id = m.group(3)
# Download the 2MB version because Tweepy has a 3MB upload limit for GIFs
giphy_url = 'https://media.giphy.com/media/' + id + '/giphy-downsized.gif'
file_path = IMAGE_DIR + '/' + id + '-downsized.gif'
print('[ OK ] Downloading Giphy at URL ' + giphy_url + ' to ' + file_path)
giphy_file = save_file(giphy_url, file_path)
return giphy_file
else:
print('[EROR] Could not identify Giphy ID in this URL:', img_url)
return
else:
print('[WARN] Post', post_id, 'doesn\'t point to an image/GIF:', img_url)
return
def tweet_creator(subreddit_info):
post_dict = {}
print ('[ OK ] Getting posts from Reddit')
for submission in subreddit_info.hot(limit=POST_LIMIT):
# If the OP has deleted his account, save it as "a deleted user"
if submission.author is None:
submission.author = "a deleted user"
submission.author.name = "a deleted user"
else:
submission.author.name = "/u/" + submission.author.name
if (submission.over_18 and NSFW_POSTS_ALLOWED is False):
# Skip over NSFW posts if they are disabled in the config file
print('[ OK ] Skipping', submission.id, 'because it is marked as NSFW')
continue
else:
post_dict[strip_title(submission.title)] = [submission.id,submission.url,submission.shortlink,submission.author.name]
return post_dict
def setup_connection_reddit(subreddit):
print ('[ OK ] Setting up connection with Reddit...')
r = praw.Reddit(
user_agent='memebot',
client_id=REDDIT_AGENT,
client_secret=REDDIT_CLIENT_SECRET)
return r.subreddit(subreddit)
def duplicate_check(id):
value = False
with open(CACHE_CSV, 'rt', newline='') as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
if id in row:
value = True
return value
def hash_check(hash):
if hash:
value = False
# Only extract last three lines from cache file
post_list = []
with open(CACHE_CSV, 'rt', newline='') as f:
for line in f:
post_list.append(line)
if len(post_list) > REPOST_LIMIT:
post_list.pop(0)
if any(hash in s for s in post_list):
value = True
else:
value = True
return value
def log_post(id, hash, tweetID):
with open(CACHE_CSV, 'a', newline='') as cache:
date = time.strftime("%d/%m/%Y") + ' ' + time.strftime("%H:%M:%S")
wr = csv.writer(cache, delimiter=',')
wr.writerow([id, date, hash, tweetID])
def main():
# Make sure logging file and media directory exists
if not os.path.exists(CACHE_CSV):
with open(CACHE_CSV, 'w', newline='') as cache:
default = ['Post','Date and time','Image hash', 'Tweet link']
wr = csv.writer(cache)
wr.writerow(default)
print ('[ OK ] ' + CACHE_CSV + ' file not found, created a new one')
if not os.path.exists(IMAGE_DIR):
os.makedirs(IMAGE_DIR)
print ('[ OK ] ' + IMAGE_DIR + ' folder not found, created a new one')
# Continue with script
subreddit = setup_connection_reddit(SUBREDDIT_TO_MONITOR)
post_dict = tweet_creator(subreddit)
tweeter(post_dict)
def alt_tweeter(post_link, op, username, newestTweet):
try:
# Log into alternate account
auth = tweepy.OAuthHandler(ALT_CONSUMER_KEY, ALT_CONSUMER_SECRET)
auth.set_access_token(ALT_ACCESS_TOKEN, ALT_ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)
# Post the tweet
tweetText = '@' + username + ' Originally posted by ' + op + ' on Reddit: ' + post_link
print('[ OK ] Posting this on alt Twitter account:', tweetText)
api.update_status(tweetText, newestTweet)
except BaseException as e:
print ('[EROR] Error while posting tweet on alt account:', str(e))
return
def tweeter(post_dict):
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_secret)
api = tweepy.API(auth)
for post in post_dict:
# Grab post details from dictionary
post_id = post_dict[post][0]
if not duplicate_check(post_id): # Make sure post is not a duplicate
file_path = get_media(post_dict[post][1], post_dict[post][0])
post_link = post_dict[post][2]
post_op = post_dict[post][3]
# Make sure the post contains media (if it doesn't, then file_path would be blank)
if (file_path):
# Scan the image against previously-posted images
try:
hash = photohash.average_hash(file_path)
print ('[ OK ] Image hash check:', hash_check(hash))
except:
# Set hash to an empty string if the check failed
hash = ""
print ('[WARN] Could not check image hash, skipping.')
# Only make a tweet if the post has not already been posted (if repost protection is enabled)
if ((REPOST_PROTECTION is True) and (hash_check(hash) is False)):
print ('[ OK ] Posting this on main twitter account:', post, file_path)
try:
# Post the tweet
api.update_with_media(filename=file_path, status=post)
# Log the tweet
username = api.me().screen_name
latestTweets = api.user_timeline(screen_name = username, count = 1, include_rts = False)
newestTweet = latestTweets[0].id_str
log_post(post_id, hash, 'https://twitter.com/' + username + '/status/' + newestTweet + '/')
# Post alt tweet
if ALT_ACCESS_TOKEN:
alt_tweeter(post_link, post_op, username, newestTweet)
else:
print('[WARN] No authentication info for alternate account in config.ini, skipping alt tweet.')
print('[ OK ] Sleeping for', DELAY_BETWEEN_TWEETS, 'seconds')
time.sleep(DELAY_BETWEEN_TWEETS)
except BaseException as e:
print ('[EROR] Error while posting tweet:', str(e))
# Log the post anyways
log_post(post_id, hash, 'Error while posting tweet: ' + str(e))
else:
print ('[ OK ] Skipping', post_id, 'because it is a repost or Memebot previously failed to post it')
log_post(post_id, hash, 'Post was already tweeted or was identified as a repost')
# Cleanup media file
try:
os.remove(file_path)
print ('[ OK ] Deleted media file at ' + file_path)
except BaseException as e:
print ('[EROR] Error while deleting media file:', str(e))
else:
print ('[ OK ] Ignoring', post_id, 'because there was not a media file downloaded')
else:
print ('[ OK ] Ignoring', post_id, 'because it was already posted')
if __name__ == '__main__':
# Check for updates
try:
with urllib.request.urlopen("https://raw.githubusercontent.com/corbindavenport/memebot/update-check/current-version.txt") as url:
s = url.read()
new_version = s.decode("utf-8").rstrip()
current_version = 3.0 # Current version of script
if (current_version < float(new_version)):
print('IMPORTANT: A new version of Memebot (' + str(new_version) + ') is available! (you have ' + str(current_version) + ')')
print ('IMPORTANT: Get the latest update from here: https://github.com/corbindavenport/memebot/releases')
else:
print('[ OK ] You have the latest version of Memebot (' + str(current_version) + ')')
except BaseException as e:
print ('[EROR] Error while checking for updates:', str(e))
# Make sure config file exists
try:
config = configparser.ConfigParser()
config.read(CONFIG_FILE)
except BaseException as e:
print ('[EROR] Error while reading config file:', str(e))
sys.exit()
# Create variables from config file
CACHE_CSV = config['BotSettings']['CacheFile']
IMAGE_DIR = config['BotSettings']['MediaFolder']
DELAY_BETWEEN_TWEETS = int(config['BotSettings']['DelayBetweenTweets'])
POST_LIMIT = int(config['BotSettings']['PostLimit'])
SUBREDDIT_TO_MONITOR = config['BotSettings']['SubredditToMonitor']
NSFW_POSTS_ALLOWED = bool(distutils.util.strtobool(config['BotSettings']['NSFWPostsAllowed']))
REPOST_PROTECTION = bool(distutils.util.strtobool(config['RepostSettings']['RepostProtection']))
REPOST_LIMIT = int(config['RepostSettings']['RepostLimit'])
ACCESS_TOKEN = config['PrimaryTwitterKeys']['AccessToken']
ACCESS_TOKEN_secret = config['PrimaryTwitterKeys']['AccessTokenSecret']
CONSUMER_KEY = config['PrimaryTwitterKeys']['ConsumerKey']
CONSUMER_SECRET = config['PrimaryTwitterKeys']['ConsumerSecret']
ALT_ACCESS_TOKEN = config['AltTwitterKeys']['AccessToken']
ALT_ACCESS_TOKEN_SECRET = config['AltTwitterKeys']['AccessTokenSecret']
ALT_CONSUMER_KEY = config['AltTwitterKeys']['ConsumerKey']
ALT_CONSUMER_SECRET = config['AltTwitterKeys']['ConsumerSecret']
REDDIT_AGENT = config['Reddit']['Agent']
REDDIT_CLIENT_SECRET = config['Reddit']['ClientSecret']
IMGUR_CLIENT = config['Imgur']['ClientID']
IMGUR_CLIENT_SECRET = config['Imgur']['ClientSecret']
# Set the command line window title on Windows
if os.name == 'nt':
try:
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_secret)
api = tweepy.API(auth)
username = api.me().screen_name
title = '@' + username + ' - Memebot'
except:
title = 'Memebot'
os.system('title ' + title)
# Run the main script
while True:
main()
print('[ OK ] Sleeping for', DELAY_BETWEEN_TWEETS, 'seconds')
time.sleep(DELAY_BETWEEN_TWEETS)
print('[ OK ] Restarting main()...')
|
from __future__ import unicode_literals
import collections
import os
import shutil
import sys
if sys.version_info >= (3, 0):
compat_getenv = os.getenv
compat_expanduser = os.path.expanduser
def compat_setenv(key, value, env=os.environ):
env[key] = value
else:
# Environment variables should be decoded with filesystem encoding.
# Otherwise it will fail if any non-ASCII characters present (see #3854 #3217 #2918)
def compat_getenv(key, default=None):
from .utils import get_filesystem_encoding
env = os.getenv(key, default)
if env:
env = env.decode(get_filesystem_encoding())
return env
try:
def _testfunc(x):
pass
_testfunc(**{'x': 0})
except TypeError:
def compat_kwargs(kwargs):
return dict((bytes(k), v) for k, v in kwargs.items())
else:
compat_kwargs = lambda kwargs: kwargs
if hasattr(shutil, 'get_terminal_size'): # Python >= 3.3
compat_get_terminal_size = shutil.get_terminal_size
else:
_terminal_size = collections.namedtuple('terminal_size', ['columns', 'lines'])
def compat_get_terminal_size(fallback=(80, 24)):
columns = compat_getenv('COLUMNS')
if columns:
columns = int(columns)
else:
columns = None
lines = compat_getenv('LINES')
if lines:
lines = int(lines)
else:
lines = None
if columns is None or lines is None or columns <= 0 or lines <= 0:
try:
sp = subprocess.Popen(
['stty', 'size'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = sp.communicate()
_lines, _columns = map(int, out.split())
except Exception:
_columns, _lines = _terminal_size(*fallback)
if columns is None or columns <= 0:
columns = _columns
if lines is None or lines <= 0:
lines = _lines
return _terminal_size(columns, lines)
|
"""This module provides unit tests for the ``tigerlily.utility.archive``
module.
As with all unit test modules, the tests it contains can be executed in many
ways, but most easily by going to the project root dir and executing
``python3 setup.py nosetests``.
"""
import unittest
import os
import tigerlily.utility.archive as ar
from tigerlily.sequences import parseFASTA
class ArchiveTests(unittest.TestCase):
"""Test harness for ``tigerlily.utility.archive.Archive`` class.
"""
def setUp(self):
"""archive.py: Create the testing environment"""
self.test_dir = os.path.join(os.path.dirname(__file__),'test_archives')
self.targz = os.path.join(self.test_dir, 'test_fasta_archive.tar.gz')
self.tarbz2 = os.path.join(self.test_dir, 'test_fasta_archive.tar.bz2')
self.tar = os.path.join(self.test_dir, 'test_fasta_archive.tar')
self.zip = os.path.join(self.test_dir, 'test_fasta_archive.zip')
def test_targz(self):
"archive.py: Test .tar.gz archive support"
arch = ar.Archive(filepath=self.targz)
self._handle_arch(arch)
def test_tarbz2(self):
"archive.py: Test .tar.bz2 archive support"
arch = ar.Archive(filepath=self.tarbz2)
self._handle_arch(arch)
def test_tar(self):
"archive.py: Test .tar archive support"
arch = ar.Archive(filepath=self.tar)
self._handle_arch(arch)
def test_zip(self):
"archive.py: Test .zip archive support"
arch = ar.Archive(filepath=self.zip)
self._handle_arch(arch)
def _handle_arch(self,arch):
"handler for testing an Archive object regardless of format"
self.assertEqual(len(arch.getnames()),4)
fasta_files = [f for f in arch.getfasta()]
self.assertEqual(len(fasta_files),3)
nofasta_files = [f for f in arch.getnofasta()]
self.assertEqual(len(nofasta_files),1)
# Finally, just test to make sure that FASTA can handle the test files
# This isn't really a test of this unit, but it's a logical extension
# and it would be bad if it failed, so let's do the test.
for fasta_fileobj in arch.getfasta():
for fasta_seq in parseFASTA(fasta_fileobj):
self.assertTrue(len(fasta_seq.sequence) > 0)
self.assertTrue(fasta_seq.identifier.startswith('seq'))
|
"""abydos.distance._roberts.
Roberts similarity
"""
from typing import Any, Optional
from ._token_distance import _TokenDistance
from ..tokenizer import _Tokenizer
__all__ = ['Roberts']
class Roberts(_TokenDistance):
r"""Roberts similarity.
For two multisets X and Y drawn from an alphabet S, Roberts similarity
:cite:`Roberts:1986` is
.. math::
sim_{Roberts}(X, Y) =
\frac{\Big[\sum_{i \in S} (X_i + Y_i) \cdot
\frac{min(X_i, Y_i)}{max(X_i, Y_i)}\Big]}
{\sum_{i \in S} (X_i + Y_i)}
.. versionadded:: 0.4.0
"""
def __init__(
self, tokenizer: Optional[_Tokenizer] = None, **kwargs: Any
) -> None:
"""Initialize Roberts instance.
Parameters
----------
tokenizer : _Tokenizer
A tokenizer instance from the :py:mod:`abydos.tokenizer` package
**kwargs
Arbitrary keyword arguments
Other Parameters
----------------
qval : int
The length of each q-gram. Using this parameter and tokenizer=None
will cause the instance to use the QGram tokenizer with this
q value.
.. versionadded:: 0.4.0
"""
super(Roberts, self).__init__(tokenizer=tokenizer, **kwargs)
def sim(self, src: str, tar: str) -> float:
"""Return the Roberts similarity of two strings.
Parameters
----------
src : str
Source string (or QGrams/Counter objects) for comparison
tar : str
Target string (or QGrams/Counter objects) for comparison
Returns
-------
float
Roberts similarity
Examples
--------
>>> cmp = Roberts()
>>> cmp.sim('cat', 'hat')
0.5
>>> cmp.sim('Niall', 'Neil')
0.36363636363636365
>>> cmp.sim('aluminum', 'Catalan')
0.11764705882352941
>>> cmp.sim('ATCG', 'TAGC')
0.0
.. versionadded:: 0.4.0
"""
if src == tar:
return 1.0
self._tokenize(src, tar)
alphabet = self._total().keys()
return sum(
(self._src_tokens[i] + self._tar_tokens[i])
* min(self._src_tokens[i], self._tar_tokens[i])
/ max(self._src_tokens[i], self._tar_tokens[i])
for i in alphabet
) / sum((self._src_tokens[i] + self._tar_tokens[i]) for i in alphabet)
if __name__ == '__main__':
import doctest
doctest.testmod()
|
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Graph.slug'
db.alter_column('muparse_graph', 'slug', self.gf('django.db.models.fields.SlugField')(max_length=128, null=True))
# Adding index on 'Graph', fields ['slug']
db.create_index('muparse_graph', ['slug'])
# Changing field 'Graph.name'
db.alter_column('muparse_graph', 'name', self.gf('django.db.models.fields.CharField')(max_length=255))
# Removing index on 'Graph', fields ['name']
db.delete_index('muparse_graph', ['name'])
def backwards(self, orm):
# Adding index on 'Graph', fields ['name']
db.create_index('muparse_graph', ['name'])
# Removing index on 'Graph', fields ['slug']
db.delete_index('muparse_graph', ['slug'])
# Changing field 'Graph.slug'
db.alter_column('muparse_graph', 'slug', self.gf('django.db.models.fields.CharField')(max_length=128, null=True))
# Changing field 'Graph.name'
db.alter_column('muparse_graph', 'name', self.gf('django.db.models.fields.SlugField')(max_length=255))
models = {
'muparse.graph': {
'Meta': {'ordering': "['name']", 'object_name': 'Graph'},
'category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['muparse.GraphCategory']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'muparse.graphcategory': {
'Meta': {'ordering': "['name']", 'object_name': 'GraphCategory'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.SlugField', [], {'max_length': '255'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'muparse.node': {
'Meta': {'ordering': "['name']", 'object_name': 'Node'},
'graphs': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['muparse.Graph']", 'null': 'True', 'through': "orm['muparse.NodeGraphs']", 'blank': 'True'}),
'group': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['muparse.NodeGroup']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.SlugField', [], {'max_length': '255'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'url': ('django.db.models.fields.CharField', [], {'max_length': '512'})
},
'muparse.nodegraphs': {
'Meta': {'object_name': 'NodeGraphs'},
'baseurl': ('django.db.models.fields.CharField', [], {'max_length': '512'}),
'graph': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['muparse.Graph']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'node': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['muparse.Node']"}),
'pageurl': ('django.db.models.fields.CharField', [], {'max_length': '512'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'muparse.nodegroup': {
'Meta': {'ordering': "['name']", 'object_name': 'NodeGroup'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'url': ('django.db.models.fields.CharField', [], {'max_length': '512'})
},
'muparse.savedsearch': {
'Meta': {'object_name': 'SavedSearch'},
'description': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'display_type': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'graphs': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['muparse.NodeGraphs']", 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
}
}
complete_apps = ['muparse']
|
from builtins import str
import os
import zipfile
from urllib.parse import quote_plus
from urllib.request import urlopen
from django import template
from django.conf import settings
from django.contrib.auth.models import User
from django.db.models import Q
from creation.models import *
from creation.views import (
is_administrator,
is_contenteditor,
is_contributor,
is_domainreviewer,
is_external_contributor,
is_internal_contributor,
is_qualityreviewer,
is_videoreviewer,
is_language_manager
)
from spoken.forms import TutorialSearchForm
register = template.Library()
def format_component_title(name):
return name.replace('_', ' ').capitalize()
def get_url_name(name):
return quote_plus(name)
def get_zip_content(path):
file_names = None
try:
zf = zipfile.ZipFile(path, 'r')
file_names = zf.namelist()
return file_names
except Exception as e:
return False
def is_script_available(path):
try:
code = urlopen(script_path).code
except Exception as e:
code = e.code
if(int(code) == 200):
return True
return False
def get_review_status_list(key):
status_list = ['Pending', 'Waiting for Admin Review', 'Waiting for Domain Review', 'Waiting for Quality Review', 'Accepted', 'Need Improvement', 'Not Required']
return status_list[key];
def get_review_status_class(key):
status_list = ['danger', 'active', 'warning', 'info', 'success', 'danger', 'success']
return status_list[key];
def get_review_status_symbol(key):
status_list = ['fa fa-1 fa-minus-circle review-pending-upload', 'fa fa-1 fa-check-circle review-admin-review', 'fa fa-1 fa-check-circle review-domain-review', 'fa fa-1 fa-check-circle review-quality-review', 'fa fa-1 fa-check-circle review-accepted', 'fa fa-1 fa-times-circle review-pending-upload', 'fa fa-1 fa-ban review-accepted']
return status_list[key];
def get_username(key):
user = User.objects.get(pk = key)
return user.username
def get_last_video_upload_time(key):
rec = None
try:
rec = ContributorLog.objects.filter(tutorial_resource_id = key.id).order_by('-created')[0]
tmpdt = key.updated
for tmp in rec:
tmpdt = rec.created
return tmpdt
except:
return key.updated
def get_component_name(comp):
comps = {
1: 'Outline',
2: 'Script',
3: 'Video',
4: 'Slides',
5: 'Codefiles',
6: 'Assignment'
}
key = ''
try:
key = comps[comp]
except:
pass
return key.title()
def get_missing_component_reply(mcid):
rows = TutorialMissingComponentReply.objects.filter(missing_component_id = mcid)
replies = ''
for row in rows:
replies += '<p>' + row.reply_message + '<b> -' + row.user.username + '</b></p>'
if replies:
replies = '<br /><b>Replies:</b>' + replies
return replies
def formatismp4(path):
'''
** Registered to be used in jinja template **
Function takes in a file name and checks if the
last 3 characters are `mp4`.
'''
return path[-3:] == 'mp4' or path[-3:] == 'mov'
def instruction_sheet(foss, lang):
file_path = settings.MEDIA_ROOT + 'videos/' + str(foss.id) + '/' + foss.foss.replace(' ', '-') + '-Instruction-Sheet-' + lang.name + '.pdf'
if lang.name != 'English':
if os.path.isfile(file_path):
file_path = settings.MEDIA_URL + 'videos/' + str(foss.id) + '/' + foss.foss.replace(' ', '-') + '-Instruction-Sheet-' + lang.name + '.pdf'
return file_path
file_path = settings.MEDIA_ROOT + 'videos/' + str(foss.id) + '/' + foss.foss.replace(' ', '-') + '-Instruction-Sheet-English.pdf'
if os.path.isfile(file_path):
file_path = settings.MEDIA_URL + 'videos/' + str(foss.id) + '/' + foss.foss.replace(' ', '-') + '-Instruction-Sheet-English.pdf'
return file_path
return False
def installation_sheet(foss, lang):
file_path = settings.MEDIA_ROOT + 'videos/' + str(foss.id) + '/' + foss.foss.replace(' ', '-') + '-Installation-Sheet-' + lang.name + '.pdf'
if lang.name != 'English':
if os.path.isfile(file_path):
file_path = settings.MEDIA_URL + 'videos/' + str(foss.id) + '/' + foss.foss.replace(' ', '-') + '-Installation-Sheet-' + lang.name + '.pdf'
return file_path
file_path = settings.MEDIA_ROOT + 'videos/' + str(foss.id) + '/' + foss.foss.replace(' ', '-') + '-Installation-Sheet-English.pdf'
if os.path.isfile(file_path):
file_path = settings.MEDIA_URL + 'videos/' + str(foss.id) + '/' + foss.foss.replace(' ', '-') + '-Installation-Sheet-English.pdf'
return file_path
return False
def brochure(foss, lang):
file_path = settings.MEDIA_ROOT + 'videos/' + str(foss.id) + '/' + foss.foss.replace(' ', '-') + '-Brochure-' + lang.name + '.pdf'
if lang.name != 'English':
if os.path.isfile(file_path):
file_path = settings.MEDIA_URL + 'videos/' + str(foss.id) + '/' + foss.foss.replace(' ', '-') + '-Brochure-' + lang.name + '.pdf'
return file_path
file_path = settings.MEDIA_ROOT + 'videos/' + str(foss.id) + '/' + foss.foss.replace(' ', '-') + '-Brochure-English.pdf'
if os.path.isfile(file_path):
file_path = settings.MEDIA_URL + 'videos/' + str(foss.id) + '/' + foss.foss.replace(' ', '-') + '-Brochure-English.pdf'
return file_path
return False
def get_thumb_path(row, append_str):
path = settings.MEDIA_URL + 'videos/' + str(row.foss_id) + '/' + str(row.id) + '/' + row.tutorial.replace(' ', '-') + '-' + append_str + '.png'
return path
def get_srt_path(tr):
data = ''
english_srt = settings.MEDIA_ROOT + 'videos/' + str(tr.tutorial_detail.foss_id) + '/' + str(tr.tutorial_detail_id) + '/' + tr.tutorial_detail.tutorial.replace(' ', '-') + '-English.srt'
if os.path.isfile(english_srt):
data = '<track kind="captions" src="'+ settings.MEDIA_URL + 'videos/' + str(tr.tutorial_detail.foss_id) + '/' + str(tr.tutorial_detail_id) + '/' + tr.tutorial_detail.tutorial.replace(' ', '-') + '-English.srt' + '" srclang="en" label="English"></track>'
if tr.language.name != 'English':
native_srt = settings.MEDIA_ROOT + 'videos/' + str(tr.tutorial_detail.foss_id) + '/' + str(tr.tutorial_detail_id) + '/' + tr.tutorial_detail.tutorial.replace(' ', '-') + '-' + tr.language.name +'.srt'
print(native_srt)
if os.path.isfile(native_srt):
data += '<track kind="captions" src="'+ settings.MEDIA_URL + 'videos/' + str(tr.tutorial_detail.foss_id) + '/' + str(tr.tutorial_detail_id) + '/' + tr.tutorial_detail.tutorial.replace(' ', '-') + '-' + tr.language.name + '.srt' + '" srclang="en" label="' + tr.language.name + '"></track>'
return data
def get_video_visits(tr):
tr.hit_count = tr.hit_count + 1
tr.save()
return tr.hit_count
def get_prerequisite(tr, td):
print((tr, td))
try:
tr_rec = TutorialResource.objects.get(Q(status = 1) | Q(status = 2), tutorial_detail = td, language_id = tr.language_id)
return get_url_name(td.foss.foss) + '/' + get_url_name(td.tutorial) + '/' + tr_rec.language.name
except Exception as e:
print(e)
if tr.language.name != 'English':
try:
tr_rec = TutorialResource.objects.get(Q(status = 1) | Q(status = 2), tutorial_detail = td, language__name = 'English')
return get_url_name(td.foss.foss) + '/' + get_url_name(td.tutorial) + '/English'
except:
return None
pass
return None
def get_prerequisite_from_td(td, lang):
try:
tr_rec = TutorialResource.objects.get(Q(status = 1) | Q(status = 2), tutorial_detail = td, language_id = lang.id)
return tr_rec.id
except:
if lang.name != 'English':
try:
tr_rec = TutorialResource.objects.get(Q(status = 1) | Q(status = 2), tutorial_detail = td, language__name = 'English')
return tr_rec.id
except:
pass
return None
def get_timed_script(script_path, timed_script_path):
if timed_script_path:
timed_script = settings.SCRIPT_URL + timed_script_path
else:
timed_script = settings.SCRIPT_URL + script_path + '-timed'
print(script_path)
code = 0
try:
code = urlopen(timed_script).code
except Exception as e:
timed_script = settings.SCRIPT_URL + \
script_path.replace(' ', '-').replace('_', '-') + '-timed'
print(timed_script)
try:
code = urlopen(timed_script).code
except Exception as e:
print((code, '----', e))
code = 0
if(int(code) == 200):
return timed_script
return ''
def tutorialsearch():
context = {
'form': TutorialSearchForm()
}
return context
def get_mp4_video(tr):
video_name = tr.video
splitat = -4
tname, text = video_name[:splitat], video_name[splitat:]
path = settings.MEDIA_ROOT + 'videos/' + str(tr.tutorial_detail.foss_id) + '/' + str(tr.tutorial_detail_id) + '/' + tname + '.mp4'
if os.path.isfile(path):
return 'videos/' + str(tr.tutorial_detail.foss_id) + '/' + str(tr.tutorial_detail_id) + '/' + tname + '.mp4'
return False
register.inclusion_tag('spoken/templates/tutorial_search_form.html')(tutorialsearch)
register.filter('get_timed_script', get_timed_script)
register.filter('formatismp4', formatismp4)
register.filter('get_prerequisite_from_td', get_prerequisite_from_td)
register.filter('get_prerequisite', get_prerequisite)
register.filter('get_video_visits', get_video_visits)
register.filter('get_srt_path', get_srt_path)
register.filter('get_thumb_path', get_thumb_path)
register.filter('get_missing_component_reply', get_missing_component_reply)
register.filter('get_component_name', get_component_name)
register.filter('get_url_name', get_url_name)
register.filter('get_zip_content', get_zip_content)
register.filter('get_contributor', is_contributor)
register.filter('get_internal_contributor', is_internal_contributor)
register.filter('get_external_contributor', is_external_contributor)
register.filter('get_videoreviewer', is_videoreviewer)
register.filter('get_domainreviewer', is_domainreviewer)
register.filter('get_qualityreviewer', is_qualityreviewer)
register.filter('get_administrator', is_administrator)
register.filter('get_last_video_upload_time', get_last_video_upload_time)
register.filter('get_review_status_list', get_review_status_list)
register.filter('get_review_status_symbol', get_review_status_symbol)
register.filter('get_review_status_class', get_review_status_class)
register.filter('get_username', get_username)
register.filter('instruction_sheet', instruction_sheet)
register.filter('installation_sheet', installation_sheet)
register.filter('brochure', brochure)
register.filter('get_contenteditor', is_contenteditor)
register.filter('format_component_title', format_component_title)
register.filter('get_mp4_video', get_mp4_video)
register.filter('get_language_manager',is_language_manager)
|
import sysconfig
import os
from PyInstaller.utils.hooks import relpath_to_config_or_make
_CONFIG_H = sysconfig.get_config_h_filename()
if hasattr(sysconfig, 'get_makefile_filename'):
# sysconfig.get_makefile_filename is missing in Python < 2.7.9
_MAKEFILE = sysconfig.get_makefile_filename()
else:
_MAKEFILE = sysconfig._get_makefile_filename()
datas = [(_CONFIG_H, relpath_to_config_or_make(_CONFIG_H))]
if os.path.exists(_MAKEFILE):
datas.append((_MAKEFILE, relpath_to_config_or_make(_MAKEFILE)))
|
"""
crate_anon/nlp_manager/number.py
===============================================================================
Copyright (C) 2015-2021 Rudolf Cardinal (rudolf@pobox.com).
This file is part of CRATE.
CRATE is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CRATE is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with CRATE. If not, see <https://www.gnu.org/licenses/>.
===============================================================================
**Number conversion functions.**
"""
from typing import Optional
def to_float(s: str) -> Optional[float]:
"""
Convert a string to a float, or return ``None``.
Before converting:
- strips out commas (as thousands separator); this is not internationalized
well!
- replace Unicode minus and en dash with a hyphen (minus sign)
"""
if s:
s = s.replace(',', '') # comma as thousands separator
s = s.replace('−', '-') # Unicode minus
s = s.replace('–', '-') # en dash
try:
return float(s)
except (TypeError, ValueError):
return None
def to_pos_float(s: str) -> Optional[float]:
"""
Converts a string to a positive float, by using :func:`to_float` followed
by :func:`abs`. Returns ``None`` on failure.
"""
try:
return abs(to_float(s))
except TypeError: # to_float() returned None
return None
|
"""!
@brief Cluster analysis algorithm: Expectation-Maximization Algorithm for Gaussian Mixture Model.
@details Implementation based on paper @cite article::ema::1.
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2020
@copyright BSD-3-Clause
"""
import numpy
import random
from pyclustering.cluster import cluster_visualizer
from pyclustering.cluster.center_initializer import kmeans_plusplus_initializer
from pyclustering.cluster.kmeans import kmeans
from pyclustering.utils import pi, calculate_ellipse_description, euclidean_distance_square
from enum import IntEnum
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import patches
def gaussian(data, mean, covariance):
"""!
@brief Calculates gaussian for dataset using specified mean (mathematical expectation) and variance or covariance in case
multi-dimensional data.
@param[in] data (list): Data that is used for gaussian calculation.
@param[in] mean (float|numpy.array): Mathematical expectation used for calculation.
@param[in] covariance (float|numpy.array): Variance or covariance matrix for calculation.
@return (list) Value of gaussian function for each point in dataset.
"""
dimension = float(len(data[0]))
if dimension != 1.0:
inv_variance = numpy.linalg.pinv(covariance)
else:
inv_variance = 1.0 / covariance
divider = (pi * 2.0) ** (dimension / 2.0) * numpy.sqrt(numpy.linalg.norm(covariance))
if divider != 0.0:
right_const = 1.0 / divider
else:
right_const = float('inf')
result = []
for point in data:
mean_delta = point - mean
point_gaussian = right_const * numpy.exp( -0.5 * mean_delta.dot(inv_variance).dot(numpy.transpose(mean_delta)) )
result.append(point_gaussian)
return result
class ema_init_type(IntEnum):
"""!
@brief Enumeration of initialization types for Expectation-Maximization algorithm.
"""
## Means are randomly taken from input dataset and variance or covariance is calculated based on
## spherical data that belongs to the chosen means.
RANDOM_INITIALIZATION = 0
## Two step initialization. The first is calculation of initial centers using K-Means++ method.
## The second is K-Means clustering using obtained centers in the first step. Obtained clusters
## and its centers are used for calculation of variance (covariance in case of multi-dimensional)
## data.
KMEANS_INITIALIZATION = 1
class ema_initializer():
"""!
@brief Provides services for preparing initial means and covariances for Expectation-Maximization algorithm.
@details Initialization strategy is defined by enumerator 'ema_init_type': random initialization and
kmeans with kmeans++ initialization. Here an example of initialization using kmeans strategy:
@code
from pyclustering.utils import read_sample
from pyclustering.samples.definitions import FAMOUS_SAMPLES
from pyclustering.cluster.ema import ema_initializer
sample = read_sample(FAMOUS_SAMPLES.SAMPLE_OLD_FAITHFUL)
amount_clusters = 2
initial_means, initial_covariance = ema_initializer(sample, amount_clusters).initialize()
print(initial_means)
print(initial_covariance)
@endcode
"""
__MAX_GENERATION_ATTEMPTS = 10
def __init__(self, sample, amount):
"""!
@brief Constructs EM initializer.
@param[in] sample (list): Data that will be used by the EM algorithm.
@param[in] amount (uint): Amount of clusters that should be allocated by the EM algorithm.
"""
self.__sample = sample
self.__amount = amount
def initialize(self, init_type = ema_init_type.KMEANS_INITIALIZATION):
"""!
@brief Calculates initial parameters for EM algorithm: means and covariances using
specified strategy.
@param[in] init_type (ema_init_type): Strategy for initialization.
@return (float|list, float|numpy.array) Initial means and variance (covariance matrix in case multi-dimensional data).
"""
if init_type == ema_init_type.KMEANS_INITIALIZATION:
return self.__initialize_kmeans()
elif init_type == ema_init_type.RANDOM_INITIALIZATION:
return self.__initialize_random()
raise NameError("Unknown type of EM algorithm initialization is specified.")
def __calculate_initial_clusters(self, centers):
"""!
@brief Calculate Euclidean distance to each point from the each cluster.
@brief Nearest points are captured by according clusters and as a result clusters are updated.
@return (list) updated clusters as list of clusters. Each cluster contains indexes of objects from data.
"""
clusters = [[] for _ in range(len(centers))]
for index_point in range(len(self.__sample)):
index_optim, dist_optim = -1, 0.0
for index in range(len(centers)):
dist = euclidean_distance_square(self.__sample[index_point], centers[index])
if (dist < dist_optim) or (index == 0):
index_optim, dist_optim = index, dist
clusters[index_optim].append(index_point)
return clusters
def __calculate_initial_covariances(self, initial_clusters):
covariances = []
for initial_cluster in initial_clusters:
if len(initial_cluster) > 1:
cluster_sample = [self.__sample[index_point] for index_point in initial_cluster]
covariances.append(numpy.cov(cluster_sample, rowvar=False))
else:
dimension = len(self.__sample[0])
covariances.append(numpy.zeros((dimension, dimension)) + random.random() / 10.0)
return covariances
def __initialize_random(self):
initial_means = []
for _ in range(self.__amount):
mean = self.__sample[ random.randint(0, len(self.__sample)) - 1 ]
attempts = 0
while (mean in initial_means) and (attempts < ema_initializer.__MAX_GENERATION_ATTEMPTS):
mean = self.__sample[ random.randint(0, len(self.__sample)) - 1 ]
attempts += 1
if attempts == ema_initializer.__MAX_GENERATION_ATTEMPTS:
mean = [ value + (random.random() - 0.5) * value * 0.2 for value in mean ]
initial_means.append(mean)
initial_clusters = self.__calculate_initial_clusters(initial_means)
initial_covariance = self.__calculate_initial_covariances(initial_clusters)
return initial_means, initial_covariance
def __initialize_kmeans(self):
initial_centers = kmeans_plusplus_initializer(self.__sample, self.__amount).initialize()
kmeans_instance = kmeans(self.__sample, initial_centers, ccore = True)
kmeans_instance.process()
means = kmeans_instance.get_centers()
covariances = []
initial_clusters = kmeans_instance.get_clusters()
for initial_cluster in initial_clusters:
if len(initial_cluster) > 1:
cluster_sample = [ self.__sample[index_point] for index_point in initial_cluster ]
covariances.append(numpy.cov(cluster_sample, rowvar=False))
else:
dimension = len(self.__sample[0])
covariances.append(numpy.zeros((dimension, dimension)) + random.random() / 10.0)
return means, covariances
class ema_observer:
"""!
@brief Observer of EM algorithm for collecting algorithm state on each step.
@details It can be used to obtain whole picture about clustering process of EM algorithm. Allocated clusters,
means and covariances are stored in observer on each step. Here an example of usage:
@code
from pyclustering.cluster.ema import ema, ema_observer
from pyclustering.utils import read_sample
from pyclustering.samples.definitions import SIMPLE_SAMPLES
# Read data from text file.
sample = read_sample(SIMPLE_SAMPLES.SAMPLE_SIMPLE3)
# Create EM observer.
observer = ema_observer()
# Create EM algorithm to allocated four clusters and pass observer to it.
ema_instance = ema(sample, 4, observer=observer)
# Run clustering process.
ema_instance.process()
# Print amount of steps that were done by the algorithm.
print("EMA steps:", observer.get_iterations())
# Print evolution of means and covariances.
print("Means evolution:", observer.get_evolution_means())
print("Covariances evolution:", observer.get_evolution_covariances())
# Print evolution of clusters.
print("Clusters evolution:", observer.get_evolution_clusters())
# Print final clusters.
print("Allocated clusters:", observer.get_evolution_clusters()[-1])
@endcode
"""
def __init__(self):
"""!
@brief Initializes EM observer.
"""
self.__means_evolution = []
self.__covariances_evolution = []
self.__clusters_evolution = []
def __len__(self):
"""!
@return (uint) Amount of iterations that were done by the EM algorithm.
"""
return len(self.__means_evolution)
def get_iterations(self):
"""!
@return (uint) Amount of iterations that were done by the EM algorithm.
"""
return len(self.__means_evolution)
def get_evolution_means(self):
"""!
@return (list) Mean of each cluster on each step of clustering.
"""
return self.__means_evolution
def get_evolution_covariances(self):
"""!
@return (list) Covariance matrix (or variance in case of one-dimensional data) of each cluster on each step of clustering.
"""
return self.__covariances_evolution
def get_evolution_clusters(self):
"""!
@return (list) Allocated clusters on each step of clustering.
"""
return self.__clusters_evolution
def notify(self, means, covariances, clusters):
"""!
@brief This method is used by the algorithm to notify observer about changes where the algorithm
should provide new values: means, covariances and allocated clusters.
@param[in] means (list): Mean of each cluster on currect step.
@param[in] covariances (list): Covariances of each cluster on current step.
@param[in] clusters (list): Allocated cluster on current step.
"""
self.__means_evolution.append(means)
self.__covariances_evolution.append(covariances)
self.__clusters_evolution.append(clusters)
class ema_visualizer:
"""!
@brief Visualizer of EM algorithm's results.
@details Provides services for visualization of particular features of the algorithm, for example,
in case of two-dimensional dataset it shows covariance ellipses.
"""
@staticmethod
def show_clusters(clusters, sample, covariances, means, figure=None, display=True):
"""!
@brief Draws clusters and in case of two-dimensional dataset draws their ellipses.
@details Allocated figure by this method should be closed using `close()` method of this visualizer.
@param[in] clusters (list): Clusters that were allocated by the algorithm.
@param[in] sample (list): Dataset that were used for clustering.
@param[in] covariances (list): Covariances of the clusters.
@param[in] means (list): Means of the clusters.
@param[in] figure (figure): If 'None' then new is figure is creater, otherwise specified figure is used
for visualization.
@param[in] display (bool): If 'True' then figure will be shown by the method, otherwise it should be
shown manually using matplotlib function 'plt.show()'.
@return (figure) Figure where clusters were drawn.
"""
visualizer = cluster_visualizer()
visualizer.append_clusters(clusters, sample)
if figure is None:
figure = visualizer.show(display=False)
else:
visualizer.show(figure=figure, display=False)
if len(sample[0]) == 2:
ema_visualizer.__draw_ellipses(figure, visualizer, clusters, covariances, means)
if display is True:
plt.show()
return figure
@staticmethod
def close(figure):
"""!
@brief Closes figure object that was used or allocated by the visualizer.
@param[in] figure (figure): Figure object that was used or allocated by the visualizer.
"""
plt.close(figure)
@staticmethod
def animate_cluster_allocation(data, observer, animation_velocity = 75, movie_fps = 1, save_movie = None):
"""!
@brief Animates clustering process that is performed by EM algorithm.
@param[in] data (list): Dataset that is used for clustering.
@param[in] observer (ema_observer): EM observer that was used for collection information about clustering process.
@param[in] animation_velocity (uint): Interval between frames in milliseconds (for run-time animation only).
@param[in] movie_fps (uint): Defines frames per second (for rendering movie only).
@param[in] save_movie (string): If it is specified then animation will be stored to file that is specified in this parameter.
"""
figure = plt.figure()
def init_frame():
return frame_generation(0)
def frame_generation(index_iteration):
figure.clf()
figure.suptitle("EM algorithm (iteration: " + str(index_iteration) +")", fontsize = 18, fontweight = 'bold')
clusters = observer.get_evolution_clusters()[index_iteration]
covariances = observer.get_evolution_covariances()[index_iteration]
means = observer.get_evolution_means()[index_iteration]
ema_visualizer.show_clusters(clusters, data, covariances, means, figure, False)
figure.subplots_adjust(top=0.85)
return [figure.gca()]
iterations = len(observer)
cluster_animation = animation.FuncAnimation(figure, frame_generation, iterations, interval = animation_velocity, init_func = init_frame, repeat_delay = 5000)
if save_movie is not None:
cluster_animation.save(save_movie, writer='ffmpeg', fps=movie_fps, bitrate=1500)
else:
plt.show()
plt.close(figure)
@staticmethod
def __draw_ellipses(figure, visualizer, clusters, covariances, means):
ax = figure.get_axes()[0]
for index in range(len(clusters)):
angle, width, height = calculate_ellipse_description(covariances[index])
color = visualizer.get_cluster_color(index, 0)
ema_visualizer.__draw_ellipse(ax, means[index][0], means[index][1], angle, width, height, color)
@staticmethod
def __draw_ellipse(ax, x, y, angle, width, height, color):
if (width > 0.0) and (height > 0.0):
ax.plot(x, y, color=color, marker='x', markersize=6)
ellipse = patches.Ellipse((x, y), width, height, alpha=0.2, angle=-angle, linewidth=2, fill=True, zorder=2, color=color)
ax.add_patch(ellipse)
class ema:
"""!
@brief Expectation-Maximization clustering algorithm for Gaussian Mixture Model (GMM).
@details The algorithm provides only clustering services (unsupervised learning).
Here an example of data clustering process:
@code
from pyclustering.cluster.ema import ema, ema_visualizer
from pyclustering.utils import read_sample
from pyclustering.samples.definitions import FCPS_SAMPLES
# Read data from text file.
sample = read_sample(FCPS_SAMPLES.SAMPLE_LSUN)
# Create EM algorithm to allocated four clusters.
ema_instance = ema(sample, 3)
# Run clustering process.
ema_instance.process()
# Get clustering results.
clusters = ema_instance.get_clusters()
covariances = ema_instance.get_covariances()
means = ema_instance.get_centers()
# Visualize obtained clustering results.
ema_visualizer.show_clusters(clusters, sample, covariances, means)
@endcode
Here is clustering results of the Expectation-Maximization clustering algorithm where popular sample 'OldFaithful' was used.
Initial random means and covariances were used in the example. The first step is presented on the left side of the figure and
final result (the last step) is on the right side:
@image html ema_old_faithful_clustering.png
@see ema_visualizer
@see ema_observer
"""
def __init__(self, data, amount_clusters, means=None, variances=None, observer=None, tolerance=0.00001, iterations=100):
"""!
@brief Initializes Expectation-Maximization algorithm for cluster analysis.
@param[in] data (list): Dataset that should be analysed and where each point (object) is represented by the list of coordinates.
@param[in] amount_clusters (uint): Amount of clusters that should be allocated.
@param[in] means (list): Initial means of clusters (amount of means should be equal to amount of clusters for allocation).
If this parameter is 'None' then K-Means algorithm with K-Means++ method will be used for initialization by default.
@param[in] variances (list): Initial cluster variances (or covariances in case of multi-dimensional data). Amount of
covariances should be equal to amount of clusters that should be allocated. If this parameter is 'None' then
K-Means algorithm with K-Means++ method will be used for initialization by default.
@param[in] observer (ema_observer): Observer for gathering information about clustering process.
@param[in] tolerance (float): Defines stop condition of the algorithm (when difference between current and
previous log-likelihood estimation is less then 'tolerance' then clustering is over).
@param[in] iterations (uint): Additional stop condition parameter that defines maximum number of steps that can be
performed by the algorithm during clustering process.
"""
self.__data = numpy.array(data)
self.__amount_clusters = amount_clusters
self.__tolerance = tolerance
self.__iterations = iterations
self.__observer = observer
self.__means = means
self.__variances = variances
self.__verify_arguments()
if (means is None) or (variances is None):
self.__means, self.__variances = ema_initializer(data, amount_clusters).initialize(ema_init_type.KMEANS_INITIALIZATION)
if len(self.__means) != amount_clusters:
self.__amount_clusters = len(self.__means)
self.__rc = [ [0.0] * len(self.__data) for _ in range(amount_clusters) ]
self.__pic = [1.0] * amount_clusters
self.__clusters = []
self.__gaussians = [ [] for _ in range(amount_clusters) ]
self.__stop = False
def process(self):
"""!
@brief Run clustering process of the algorithm.
@return (ema) Returns itself (EMA instance).
"""
previous_likelihood = -200000
current_likelihood = -100000
current_iteration = 0
while(self.__stop is False) and (abs(previous_likelihood - current_likelihood) > self.__tolerance) and (current_iteration < self.__iterations):
self.__expectation_step()
self.__maximization_step()
current_iteration += 1
self.__extract_clusters()
self.__notify()
previous_likelihood = current_likelihood
current_likelihood = self.__log_likelihood()
self.__stop = self.__get_stop_condition()
self.__normalize_probabilities()
return self
def get_clusters(self):
"""!
@return (list) Allocated clusters where each cluster is represented by list of indexes of points from dataset,
for example, two cluster may have following representation [[0, 1, 4], [2, 3, 5, 6]].
"""
return self.__clusters
def get_centers(self):
"""!
@return (list) Corresponding centers (means) of clusters.
"""
return self.__means
def get_covariances(self):
"""!
@return (list) Corresponding variances (or covariances in case of multi-dimensional data) of clusters.
"""
return self.__variances
def get_probabilities(self):
"""!
@brief Returns 2-dimensional list with belong probability of each object from data to cluster correspondingly,
where that first index is for cluster and the second is for point.
@code
# Get belong probablities
probabilities = ema_instance.get_probabilities();
# Show porbability of the fifth element in the first and in the second cluster
index_point = 5;
print("Probability in the first cluster:", probabilities[0][index_point]);
print("Probability in the first cluster:", probabilities[1][index_point]);
@endcode
@return (list) 2-dimensional list with belong probability of each object from data to cluster.
"""
return self.__rc
def __erase_empty_clusters(self):
clusters, means, variances, pic, gaussians, rc = [], [], [], [], [], []
for index_cluster in range(len(self.__clusters)):
if len(self.__clusters[index_cluster]) > 0:
clusters.append(self.__clusters[index_cluster])
means.append(self.__means[index_cluster])
variances.append(self.__variances[index_cluster])
pic.append(self.__pic[index_cluster])
gaussians.append(self.__gaussians[index_cluster])
rc.append(self.__rc[index_cluster])
if len(self.__clusters) != len(clusters):
self.__clusters, self.__means, self.__variances, self.__pic = clusters, means, variances, pic
self.__gaussians, self.__rc = gaussians, rc
self.__amount_clusters = len(self.__clusters)
def __notify(self):
if self.__observer is not None:
self.__observer.notify(self.__means, self.__variances, self.__clusters)
def __extract_clusters(self):
self.__clusters = [[] for _ in range(self.__amount_clusters)]
for index_point in range(len(self.__data)):
candidates = []
for index_cluster in range(self.__amount_clusters):
candidates.append((index_cluster, self.__rc[index_cluster][index_point]))
index_winner = max(candidates, key=lambda candidate: candidate[1])[0]
self.__clusters[index_winner].append(index_point)
self.__erase_empty_clusters()
def __log_likelihood(self):
likelihood = 0.0
for index_point in range(len(self.__data)):
particle = 0.0
for index_cluster in range(self.__amount_clusters):
particle += self.__pic[index_cluster] * self.__gaussians[index_cluster][index_point]
if particle > 0.0:
likelihood += numpy.log(particle)
return likelihood
def __probabilities(self, index_cluster, index_point):
divider = 0.0
for i in range(self.__amount_clusters):
divider += self.__pic[i] * self.__gaussians[i][index_point]
if (divider != 0.0) and (divider != float('inf')):
return self.__pic[index_cluster] * self.__gaussians[index_cluster][index_point] / divider
return 1.0
def __expectation_step(self):
self.__gaussians = [ [] for _ in range(self.__amount_clusters) ]
for index in range(self.__amount_clusters):
self.__gaussians[index] = gaussian(self.__data, self.__means[index], self.__variances[index])
self.__rc = [ [0.0] * len(self.__data) for _ in range(self.__amount_clusters) ]
for index_cluster in range(self.__amount_clusters):
for index_point in range(len(self.__data)):
self.__rc[index_cluster][index_point] = self.__probabilities(index_cluster, index_point)
def __maximization_step(self):
self.__pic = []
self.__means = []
self.__variances = []
amount_impossible_clusters = 0
for index_cluster in range(self.__amount_clusters):
mc = numpy.sum(self.__rc[index_cluster])
if mc == 0.0:
amount_impossible_clusters += 1
continue
self.__pic.append( mc / len(self.__data) )
self.__means.append( self.__update_mean(self.__rc[index_cluster], mc) )
self.__variances.append( self.__update_covariance(self.__means[-1], self.__rc[index_cluster], mc) )
self.__amount_clusters -= amount_impossible_clusters
def __get_stop_condition(self):
for covariance in self.__variances:
if numpy.linalg.norm(covariance) == 0.0:
return True
return False
def __update_covariance(self, means, rc, mc):
covariance = 0.0
for index_point in range(len(self.__data)):
deviation = numpy.array([self.__data[index_point] - means])
covariance += rc[index_point] * deviation.T.dot(deviation)
covariance = covariance / mc
return covariance
def __update_mean(self, rc, mc):
mean = 0.0
for index_point in range(len(self.__data)):
mean += rc[index_point] * self.__data[index_point]
mean = mean / mc
return mean
def __normalize_probabilities(self):
for index_point in range(len(self.__data)):
probability = 0.0
for index_cluster in range(len(self.__clusters)):
probability += self.__rc[index_cluster][index_point]
if abs(probability - 1.0) > 0.000001:
self.__normalize_probability(index_point, probability)
def __normalize_probability(self, index_point, probability):
if probability == 0.0:
return
normalization = 1.0 / probability
for index_cluster in range(len(self.__clusters)):
self.__rc[index_cluster][index_point] *= normalization
def __verify_arguments(self):
"""!
@brief Verify input parameters for the algorithm and throw exception in case of incorrectness.
"""
if len(self.__data) == 0:
raise ValueError("Input data is empty (size: '%d')." % len(self.__data))
if self.__amount_clusters < 1:
raise ValueError("Amount of clusters (current value '%d') should be greater or equal to 1." %
self.__amount_clusters)
|
"""
**constants.py**
**Platform:**
Windows, Linux, Mac Os X.
**Description:**
Defines **Foundations** package default constants through the :class:`Constants` class.
**Others:**
"""
from __future__ import unicode_literals
import os
import platform
import foundations
__author__ = "Thomas Mansencal"
__copyright__ = "Copyright (C) 2008 - 2014 - Thomas Mansencal"
__license__ = "GPL V3.0 - http://www.gnu.org/licenses/"
__maintainer__ = "Thomas Mansencal"
__email__ = "thomas.mansencal@gmail.com"
__status__ = "Production"
__all__ = ["Constants"]
class Constants():
"""
Defines **Foundations** package default constants.
"""
application_name = "Foundations"
"""
:param application_name: Package Application name.
:type application_name: unicode
"""
major_version = "2"
"""
:param major_version: Package major version.
:type major_version: unicode
"""
minor_version = "1"
"""
:param minor_version: Package minor version.
:type minor_version: unicode
"""
change_version = "0"
"""
:param change_version: Package change version.
:type change_version: unicode
"""
version = ".".join((major_version, minor_version, change_version))
"""
:param version: Package version.
:type version: unicode
"""
logger = "Foundations_Logger"
"""
:param logger: Package logger name.
:type logger: unicode
"""
verbosity_level = 3
"""
:param verbosity_level: Default logging verbosity level.
:type verbosity_level: int
"""
verbosity_labels = ("Critical", "Error", "Warning", "Info", "Debug")
"""
:param verbosity_labels: Logging verbosity labels.
:type verbosity_labels: tuple
"""
logging_default_formatter = "Default"
"""
:param logging_default_formatter: Default logging formatter name.
:type logging_default_formatter: unicode
"""
logging_separators = "*" * 96
"""
:param logging_separators: Logging separators.
:type logging_separators: unicode
"""
default_codec = "utf-8"
"""
:param default_codec: Default codec.
:type default_codec: unicode
"""
codec_error = "ignore"
"""
:param codec_error: Default codec error behavior.
:type codec_error: unicode
"""
application_directory = os.sep.join(("Foundations", ".".join((major_version, minor_version))))
"""
:param application_directory: Package Application directory.
:type application_directory: unicode
"""
if platform.system() == "Windows" or platform.system() == "Microsoft" or platform.system() == "Darwin":
provider_directory = "HDRLabs"
"""
:param provider_directory: Package provider directory.
:type provider_directory: unicode
"""
elif platform.system() == "Linux":
provider_directory = ".HDRLabs"
"""
:param provider_directory: Package provider directory.
:type provider_directory: unicode
"""
null_object = "None"
"""
:param null_object: Default null object string.
:type null_object: unicode
"""
|
import os
|
from .bot import Stashbot
__all__ = (
'Stashbot',
)
any((
Stashbot,
))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.