rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
html.write('<div style="display: %s;" class=sublist>' % display)
html.write('<div style="%s" class=sublist>' % display)
def render_list(ids, links): states = load_customlink_states() n = 0 for entry in links: n += 1 try: if type(entry[1]) == type(True): idss = ids + [str(n)] if states.get(''.join(idss), entry[1] and 'on' or 'off') == 'on': # open display = "" img = "link_folder_open.gif" else: display = "none" img = "link_folder.gif" ht...
if opt_verbose: sys.stderr.write(' Running %s...' % (command,))
if opt_debug: sys.stderr.write(' Running %s\n' % (command,))
def get_snmp_explicit(hostname, ipaddress, community, mib, baseoid, suffixes): if opt_verbose: sys.stderr.write('Fetching misc values from OID %s%s%s%s from IP %s\n' % \ (tty_bold, tty_green, baseoid, tty_normal, ipaddress)) info = [] if is_bulkwalk_host(hostname): cmd = "snmpbulkwalk -v2c" else: cmd = "snmpwalk -v1" ...
ajax_url = site["url_prefix"] + "check_mk/ajax_wato_files.py"
ajax_url = site["url_prefix"] + "check_mk/ajax_wato_files.py?site=" + sitename
def render_wato_files(): if not config.may("use_wato"): html.write("You are not allowed to use Check_MK's web configuration GUI.") elif len(config.config_files)== 0: html.write("No configuration files are defined.<br>" "Please set the variable <tt>config_files</tt><br>" "in <tt>multisite.mk</tt>.") else: if config.is_...
bulletlink(title, "wato.py?filename=%s" % filename)
if sitename: bulletlink(title, "/%s/check_mk/wato.py?filename=%s" % (sitename, filename)) else: bulletlink(title, "wato.py?filename=%s" % filename)
def ajax_wato_files(h): global html html = h if config.may("use_wato"): for filename, title, roles in config.config_files: if config.role in roles: bulletlink(title, "wato.py?filename=%s" % filename)
result = (3, "UNKNOWN - invalid output from agent or error in check %s. Please set <tt>debug_log</tt> to a filename in <tt>main.mk</tt> for enabling exception logging." % checkname)
result = (3, "UNKNOWN - invalid output from agent, invalid check parameters or error in implementation of check %s. Please set <tt>debug_log</tt> to a filename in <tt>main.mk</tt> for enabling exception logging." % checkname)
def do_all_checks_on_host(hostname, ipaddress): global g_aggregated_service_results g_aggregated_service_results = {} global g_hostname g_hostname = hostname num_success = 0 num_errors = 0 check_table = get_sorted_check_table(hostname) problems = [] for checkname, item, params, description, info in check_table: # In ca...
" Date: %s\n" " Host: %s\n" " Service: %s\n" " Check type: %s\n"
" Check_MK Version: %s\n" " Date: %s\n" " Host: %s\n" " Service: %s\n" " Check type: %s\n" " Item: %r\n" " Parameters: %s\n"
def do_all_checks_on_host(hostname, ipaddress): global g_aggregated_service_results g_aggregated_service_results = {} global g_hostname g_hostname = hostname num_success = 0 num_errors = 0 check_table = get_sorted_check_table(hostname) problems = [] for checkname, item, params, description, info in check_table: # In ca...
" Agent info: %s\n\n") % (
" Agent info: %s\n\n") % ( check_mk_version,
def do_all_checks_on_host(hostname, ipaddress): global g_aggregated_service_results g_aggregated_service_results = {} global g_hostname g_hostname = hostname num_success = 0 num_errors = 0 check_table = get_sorted_check_table(hostname) problems = [] for checkname, item, params, description, info in check_table: # In ca...
hostname, description, checkname,
hostname, description, checkname, item, pprint.pformat(params),
def do_all_checks_on_host(hostname, ipaddress): global g_aggregated_service_results g_aggregated_service_results = {} global g_hostname g_hostname = hostname num_success = 0 num_errors = 0 check_table = get_sorted_check_table(hostname) problems = [] for checkname, item, params, description, info in check_table: # In ca...
sys.stderr.write("'generate_hostconf = True' in main.mk.\n")
sys.stderr.write("'generate_hostconf = False' in main.mk.\n")
def read_all_autochecks(): global autochecks autochecks = [] for f in glob.glob(autochecksdir + '/*.mk'): try: autochecks += eval(file(f).read()) except SyntaxError,e: sys.stderr.write("Syntax error in file %s: %s\n" % (f, e)) sys.exit(3) except Exception, e: sys.stderr.write("Error in file %s:\n%s\n" % (f, e)) sys.exi...
if v.startswith('"'):
if v.startswith('"') and is_hex_string(v[1:-1]):
def strip_snmp_value(value): v = value.strip() if v.startswith('"'): return convert_from_hex(v[1:-1]) else: return v.strip()
if opt_verbose: sys.stderr.write(' %d items found\n' % num_found)
def get_snmp_explicit(hostname, ipaddress, community, mib, baseoid, suffixes): if opt_verbose: sys.stderr.write('Fetching misc values from OID %s%s%s%s from IP %s\n' % \ (tty_bold, tty_green, baseoid, tty_normal, ipaddress)) info = [] if is_bulkwalk_host(hostname): cmd = "snmpbulkwalk -v2c" else: cmd = "snmpwalk -v1" ...
query += self.add_headers
query += self.auth_header + self.add_headers
def send_query(self, query, add_headers = ""):
data = self.do_query(query, self.auth_header + add_headers)
data = self.do_query(query, add_headers)
def query(self, query, add_headers = ""):
def iconpaint_disabled(values, icon):
def iconpaint_disabled(values):
def iconpaint_disabled(values, icon): if values[0] == 0 and values[1] == 0: return "<img class=icon src=\"images/icon_disabled.gif\">"
icon_painters.append(("service", ["service_check_command"], iconpaint_check_mk))
icon_painters.append(("service", ["check_command"], iconpaint_check_mk))
def iconpaint_pnp(values): return pnp_link(values)
icon_painters.append(("", ["active_checks_enabled", "accepts_passive_checks"], iconpaint_disabled))
icon_painters.append(("", ["active_checks_enabled", "accept_passive_checks"], iconpaint_disabled))
def iconpaint_pnp(values): return pnp_link(values)
if w == what: prefix = "" elif w == "": prefix = what + "_" else: continue
if w and w != what: continue prefix = what + "_"
def paint_icons(what, row): # what is "host" or "service" output = "" for w, columns, paint in icon_painters: if w == what: # icon painter especially for "what" prefix = "" elif w == "": prefix = what + "_" # universal icon painter else: continue values = [] for col in columns: pcol = prefix + col if pcol not in row: v...
def painter_columns(what): cols = [] for w, columns, paint in icon_painters: if what == w or not w: cols += [ what + "_" + c for c in columns ] return cols
def paint_icons(what, row): # what is "host" or "service" output = "" for w, columns, paint in icon_painters: if w == what: # icon painter especially for "what" prefix = "" elif w == "": prefix = what + "_" # universal icon painter else: continue values = [] for col in columns: pcol = prefix + col if pcol not in row: v...
"columns" : [ "service_description" ],
"columns" : painter_columns("service"),
def paint_icons(what, row): # what is "host" or "service" output = "" for w, columns, paint in icon_painters: if w == what: # icon painter especially for "what" prefix = "" elif w == "": prefix = what + "_" # universal icon painter else: continue values = [] for col in columns: pcol = prefix + col if pcol not in row: v...
"columns" : [ "host_name" ],
"columns" : painter_columns("host"),
def paint_icons(what, row): # what is "host" or "service" output = "" for w, columns, paint in icon_painters: if w == what: # icon painter especially for "what" prefix = "" elif w == "": prefix = what + "_" # universal icon painter else: continue values = [] for col in columns: pcol = prefix + col if pcol not in row: v...
for id in service["downtimes"].split(","):
for id in service["downtimes"]:
def nagios_service_action_command(html, service): host = service["host_name"] descr = service["description"] down_from = time.time() down_to = None if html.var("enable_notifications"): command = "ENABLE_SVC_NOTIFICATIONS;%s;%s" % (host, descr) title = "<b>enable notifications</b> for" elif html.var("disable_notificat...
raise nagios.MKAuthException('Not authorized to perform actions.')
raise MKAuthException('Not authorized to perform actions.')
def do_log_ack(html): show_tabs(html, tabs, "log") host = html.var('host') file = html.var('file') fileDisplay = file.replace('\\', '/') ack = html.var('ack') # filter invalid values if ack != '1': raise MKUserError('ack', 'Invalid value for ack parameter.') if not check_mk.is_allowed_to_act(html.req.user): raise n...
raise nagios.MKGeneralException('The log file &quot;%s&quot; from host &quot;%s&quot;' ' could not be deleted.' % \ (htmllib.attrencode(fileDisplay), htmllib.attrencode(host)))
raise MKGeneralException('The log file &quot;%s&quot; from host &quot;%s&quot;' ' could not be deleted.' % \ (htmllib.attrencode(fileDisplay), htmllib.attrencode(host)))
def do_log_ack(html): show_tabs(html, tabs, "log") host = html.var('host') file = html.var('file') fileDisplay = file.replace('\\', '/') ack = html.var('ack') # filter invalid values if ack != '1': raise MKUserError('ack', 'Invalid value for ack parameter.') if not check_mk.is_allowed_to_act(html.req.user): raise n...
raise nagios.MKGeneralException('The log file &quot;%s&quot; from host &quot;%s&quot;' ' could not be opened.' % \ (htmllib.attrencode(file.replace('\\', '/')), htmllib.attrencode(host)))
raise MKGeneralException('The log file &quot;%s&quot; could not be opened.' % \ (htmllib.attrencode(file)))
def parse_file(file, hidecontext = "no"): try: f = open(file, 'r') except: raise nagios.MKGeneralException('The log file &quot;%s&quot; from host &quot;%s&quot;' ' could not be opened.' % \ (htmllib.attrencode(file.replace('\\', '/')), htmllib.attrencode(host))) chunk_open = False logs = [] log = None for line in f.rea...
if host_is_aggregated(hostname):
is_aggregated = host_is_aggregated(hostname) if is_aggregated:
def dump_host(hostname): print if is_cluster(hostname): color = tty_bgmagenta add_txt = " (cluster of " + (",".join(nodes_of(hostname))) + ")" else: color = tty_bgblue add_txt = "" print "%s%s%s%-78s %s" % (color, tty_bold, tty_white, hostname + add_txt, tty_normal) tags = tags_of_host(hostname) print tty_yellow + "Ta...
aggregated_service_name(hostname, description), ",".join(service_extra_conf(hostname, aggregated_service_name(hostname, description), summary_service_groups)),
if_aggr(aggregated_service_name(hostname, description)), if_aggr(",".join(service_extra_conf(hostname, aggregated_service_name(hostname, description), summary_service_groups))),
def dump_host(hostname): print if is_cluster(hostname): color = tty_bgmagenta add_txt = " (cluster of " + (",".join(nodes_of(hostname))) + ")" else: color = tty_bgblue add_txt = "" print "%s%s%s%-78s %s" % (color, tty_bold, tty_white, hostname + add_txt, tty_normal) tags = tags_of_host(hostname) print tty_yellow + "Ta...
out.write("extra_service_conf['_WATO'] = [ \n" " ('hirni.mk', [ 'wato', 'hirni.mk' ], ALL_HOSTS, [ 'Check_MK inventory' ] ) ]\n")
out.write("\nextra_service_conf['_WATO'] += [ \n" " ('%s', [ 'wato', '%s' ], ALL_HOSTS, [ 'Check_MK inventory' ] ) ]\n" % (g_filename, g_filename))
def write_configuration_file(): all_hosts = [] ipaddresses = {} aliases = [] hostnames = g_hosts.keys() hostnames.sort() for hostname in hostnames: alias, ipaddress, tags = g_hosts[hostname] if alias: aliases.append((alias, [hostname])) all_hosts.append("|".join([hostname] + tags + [ g_filename, 'wato' ])) if ipaddress...
def notes_matching_pattern_entries(dir, item):
def notes_matching_pattern_entries(dirs, item):
def notes_matching_pattern_entries(dir, item): from fnmatch import fnmatch matching = [] entries = filter(lambda d: d[0] != '.', os.listdir(dir)) entries.sort() entries.reverse() for pattern in entries: if pattern[0] == '.': continue if fnmatch(item, pattern): matching.append(pattern) return matching
entries = filter(lambda d: d[0] != '.', os.listdir(dir)) entries.sort() entries.reverse() for pattern in entries: if pattern[0] == '.': continue if fnmatch(item, pattern): matching.append(pattern)
for dir in dirs: entries = filter(lambda d: d[0] != '.', os.listdir(dir)) entries.sort() entries.reverse() for pattern in entries: if pattern[0] == '.': continue if fnmatch(item, pattern): matching.append(dir + "/" + pattern)
def notes_matching_pattern_entries(dir, item): from fnmatch import fnmatch matching = [] entries = filter(lambda d: d[0] != '.', os.listdir(dir)) entries.sort() entries.reverse() for pattern in entries: if pattern[0] == '.': continue if fnmatch(item, pattern): matching.append(pattern) return matching
subdirs = notes_matching_pattern_entries(notes_dir, host) if len(subdirs) == 0: return "", "" dir = notes_dir + "/" + subdirs[0]
dirs = notes_matching_pattern_entries([notes_dir], host)
def paint_custom_notes(row): host = row["host_name"] svc = row.get("service_description") if svc: notes_dir = defaults.default_config_dir + "/notes/services" subdirs = notes_matching_pattern_entries(notes_dir, host) if len(subdirs) == 0: return "", "" dir = notes_dir + "/" + subdirs[0] item = svc else: dir = defaults.d...
dir = defaults.default_config_dir + "/notes/hosts"
dirs = [ defaults.default_config_dir + "/notes/hosts" ]
def paint_custom_notes(row): host = row["host_name"] svc = row.get("service_description") if svc: notes_dir = defaults.default_config_dir + "/notes/services" subdirs = notes_matching_pattern_entries(notes_dir, host) if len(subdirs) == 0: return "", "" dir = notes_dir + "/" + subdirs[0] item = svc else: dir = defaults.d...
files = notes_matching_pattern_entries(dir, item)
files = notes_matching_pattern_entries(dirs, item)
def paint_custom_notes(row): host = row["host_name"] svc = row.get("service_description") if svc: notes_dir = defaults.default_config_dir + "/notes/services" subdirs = notes_matching_pattern_entries(notes_dir, host) if len(subdirs) == 0: return "", "" dir = notes_dir + "/" + subdirs[0] item = svc else: dir = defaults.d...
contents.append(file(dir + "/" + f).read().strip())
contents.append(replace_tags(unicode(file(f).read(), "utf-8").strip()))
def paint_custom_notes(row): host = row["host_name"] svc = row.get("service_description") if svc: notes_dir = defaults.default_config_dir + "/notes/services" subdirs = notes_matching_pattern_entries(notes_dir, host) if len(subdirs) == 0: return "", "" dir = notes_dir + "/" + subdirs[0] item = svc else: dir = defaults.d...
"short" : "notes", "columns" : [ "host_name", "service_description" ],
"short" : "Notes", "columns" : [ "host_name", "host_address", "service_description" ],
def paint_custom_notes(row): host = row["host_name"] svc = row.get("service_description") if svc: notes_dir = defaults.default_config_dir + "/notes/services" subdirs = notes_matching_pattern_entries(notes_dir, host) if len(subdirs) == 0: return "", "" dir = notes_dir + "/" + subdirs[0] item = svc else: dir = defaults.d...
"short" : "notes", "columns" : [ "host_name" ],
"short" : "Notes", "columns" : [ "host_name", "host_address" ],
def paint_host_group_memberlist(row): links = [] for group in row["host_groups"]: link = "view.py?view_name=hostgroup&hostgroup=" + group links.append('<a href="%s">%s</a>' % (link, group)) return "", ", ".join(links)
html.write(("<tr><td class=left>%s:</td><td class=right>" + format + "</td></tr>\n") % (what, sum([row[col] for row in data]))) size, usage, max = html.live.query("GET status\nColumns: external_command_buffer_slots external_command_buffer_usage external_command_buffer_max\n")[0]
html.write(("<tr><td class=left>%s:</td><td class=right>" + format + "</td></tr>\n") % (what, sum([row[col] for row in data]))) data = html.live.query("GET status\nColumns: external_command_buffer_slots external_command_buffer_max\n") size = sum([row[0] for row in data]) maxx = sum([row[1] for row in data])
def render_performance(): data = html.live.query("GET status\nColumns: service_checks_rate host_checks_rate external_commands_rate connections_rate forks_rate log_messages_rate cached_log_messages\n") html.write("<table class=performance>\n") for what, col, format in \ [("Service checks", 0, "%.2f/s"), ("Host checks", ...
"<td class=right>%d / %d</td></tr>" % (max, size))
"<td class=right>%d / %d</td></tr>" % (maxx, size))
def render_performance(): data = html.live.query("GET status\nColumns: service_checks_rate host_checks_rate external_commands_rate connections_rate forks_rate log_messages_rate cached_log_messages\n") html.write("<table class=performance>\n") for what, col, format in \ [("Service checks", 0, "%.2f/s"), ("Host checks", ...
contactgroups_to_define.update(host_contactgroups_of(all_active_hosts())) contactgroups_to_define.update(host_contactgroups_of(all_active_clusters())) cgs = list(contactgroups_to_define) cgs.sort() outfile.write("\n for name in cgs: if type(define_contactgroups) == dict: alias = define_contactgroups.get(name, name) els...
cgs = list(contactgroups_to_define) cgs.sort() outfile.write("\n for name in cgs: if type(define_contactgroups) == dict: alias = define_contactgroups.get(name, name) else: alias = name outfile.write("\ndefine contactgroup {\n" " contactgroup_name %s\n" " alias %s\n" "}\n" % (name, alias))
def create_nagios_config_contactgroups(outfile): if define_contactgroups: contactgroups_to_define.update(host_contactgroups_of(all_active_hosts())) contactgroups_to_define.update(host_contactgroups_of(all_active_clusters())) cgs = list(contactgroups_to_define) cgs.sort() outfile.write("\n# Contact groups, (controlled b...
output += value
output += urlencode(value)
def urlencode_vars(vars): output = "" for varname, value in vars: if output != "": output += "&" if type(value) == int: value = str(value) if type(value) == str: value = unicode(value, 'utf-8') output += varname output += "=" output += value return output
/*border-spacing: 5px 2px;*/
/** * Don't use border-spacing. It is not supported by IE8 with compat mode and older IE versions. * Better set cellspacing in HTML code. This works in all browsers. * border-spacing: 5px 2px; */
def render_tactical_overview(): host_query = \ "GET hosts\n" \ "Stats: state >= 0\n" \ "Stats: state > 0\n" \ "Stats: scheduled_downtime_depth = 0\n" \ "StatsAnd: 2\n" \ "Stats: state > 0\n" \ "Stats: scheduled_downtime_depth = 0\n" \ "Stats: acknowledged = 0\n" \ "StatsAnd: 3\n" \ "Filter: custom_variable_names < _REA...
assert(accept_totp(secret, '94287082', t=65, drift=-1 == (True, -1))
assert(accept_totp(secret, '94287082', t=65, drift=-1) == (True, -1))
def accept_totp(key, response, period=30, format='dec8', hash=hashlib.sha1, forward_drift=1, backward_drift=1, drift=0, t=None): '''Validate a TOTP value inside a window of [drift-bacward_drit:drift+forward_drift] of time steps. Return a pair (v,d) where v is a boolean giving the result, and d the needed drift to vali...
safe_eval(source, 'c.mode("%s", "-o "%s")' % (target, source), c)
safe_eval(source, 'c.mode("%s", "-o %s")' % (target, source), c)
def deopme(c, source, target, argv): """takes operator status from you on the current channel""" safe_eval(source, 'c.mode("%s", "-o "%s")' % (target, source), c)
if text == "more":
if text == "See more":
def handle_data(self, text): if self.ingenre: if text == "more": self.genre = "genre: " + "".join(self.genre).strip().replace('|', '/') self.ingenre = False elif text != "\n": self.genre.append(text) elif self.inruntime: self.runtime = "runtime: " + text.strip().replace('|', '/').replace(' ', ' ') if self.runtime != "...
self.resnum = 0
self.resnum = None
def reset(self): SGMLParser.reset(self) self.inabout = False self.resnum = 0
if text == " of about ": self.inabout = True elif self.inabout: self.resnum = int(text.replace(',', '')) self.inabout = False
if not self.resnum and text.startswith("About "): self.resnum = int(text.split(' ')[1].replace(',', ''))
def handle_data(self, text): if text == " of about ": self.inabout = True elif self.inabout: self.resnum = int(text.replace(',', '')) self.inabout = False
title = ': '.join(doc.getElementsByTagName("title")[0].firstChild.toxml().split(': ')[1:])
title = unescape(': '.join(doc.getElementsByTagName("title")[0].firstChild.toxml().split(': ')[1:]), {"&quot;": '"'})
def bugs(c, source, target, argv): sock = urllib.urlopen("http://bugs.frugalware.org/getinfo/%s" % argv[0][1:]) doc = minidom.parseString(sock.read()) sock.close() try: id = doc.getElementsByTagName("id")[0].firstChild.toxml() title = ': '.join(doc.getElementsByTagName("title")[0].firstChild.toxml().split(': ')[1:]) ex...
register.add_notification(options.name,enabled)
register.add_notification(notification,enabled)
def register(self): ''' Send GNTP Registration ''' register = gntp.GNTPRegister() register.add_header('Application-Name',self.applicationName) for notification in self.notifications: enabled = notification in self.defaultNotifications register.add_notification(options.name,enabled) if self.password: register.set_passwo...
if message: notice.add_header('Notification-Text',message)
if description: notice.add_header('Notification-Text',description)
def notify(self, noteType, title, description, icon=None, sticky=False, priority=None): ''' Send a GNTP notifications ''' assert noteType in self.notifications notice = gntp.GNTPNotice() notice.add_header('Application-Name',self.applicationName) notice.add_header('Notification-Name',noteType) notice.add_header('Notific...
p = sp.Popen(c.split(), stdin=prev_proc.stdout, stdout=sp.PIPE)
p = sp.Popen(c.split(), stdin=prev_proc.stdout, stdout=sp.PIPE, stderr=sp.PIPE)
def execpipe(cmd): ''' executes a pipe command in subprocesses. Returns (stdout, stderr) ''' import subprocess as sp cmdseq = cmd.split('|') prev_proc = None procs = [] for c in cmdseq: if prev_proc is not None: p = sp.Popen(c.split(), stdin=prev_proc.stdout, stdout=sp.PIPE) else: p = sp.Popen(c.split(), stdout=sp.PIPE...
p = sp.Popen(c.split(), stdout=sp.PIPE)
p = sp.Popen(c.split(), stdout=sp.PIPE, stderr=sp.PIPE)
def execpipe(cmd): ''' executes a pipe command in subprocesses. Returns (stdout, stderr) ''' import subprocess as sp cmdseq = cmd.split('|') prev_proc = None procs = [] for c in cmdseq: if prev_proc is not None: p = sp.Popen(c.split(), stdin=prev_proc.stdout, stdout=sp.PIPE) else: p = sp.Popen(c.split(), stdout=sp.PIPE...
print args.time, u.id, p.id
print args.time + dt[inc], u.id, p.id inc += 1
def interaction(args, prng, users, pages, pairs, update_opinions=True): for i, j in pairs: u = users[i] p = pages[j] u.edits += 1 p.edits += 1 if update_opinions: if p.opinion is None: # first edit of page p.opinion = u.opinion u.successes += 1 else: # subsequent edits of page ok = np.abs(u.opinion - p.opinion) < args....
help='simulation update time step Δt (in days)' )
help='simulation update time step Δt (in days). Avg editing time (conflicts are resolved in FIFO order)' )
def make_parser(): parser = ArgumentParser(description=desc, usage=usage, fromfile_prefix_chars='@') #----------------------# # positional arguments # #----------------------# parser.add_argument( 'time', type=float, help='simulated time, in number of days') parser.add_argument( 'seed', type=int, nargs='?', help='seed ...
def main(args): ret = args.func(args) if args.save: np.save(args.save, ret)
def main(args): ret = args.func(args) if args.save: np.save(args.save, ret)
main(ns)
result = ns.func(ns)
def main(args): ret = args.func(args) if args.save: np.save(args.save, ret)
from rpy2.robjects.packages import importr from rpy2.robjects import FloatVector, IntVector, r
try: from rpy2.robjects.packages import importr from rpy2.robjects import FloatVector, IntVector, r from rpy2.rinterface import RRuntimeError except ImportError: warn('''module rpy2 is missing. Please install it from: http://rpy.sourceforge.net/rpy2.html''', category=UserWarning) raise SkipTest
def R_factory(name, vector_type='float'): ''' Parameters ---------- name - string The full R function name, including the package name. It follows the rpy2 convention to replace '.' with '_' in the function name. vector_type - string R Vector type used for packing args. Either 'float' or 'int'. ''' from rpy2.robjects.p...
package = importr(package_name)
try: package = importr(package_name) except RRuntimeError: raise ImportError('rpy2: cannot import R package %s' % package_name)
def R_factory(name, vector_type='float'): ''' Parameters ---------- name - string The full R function name, including the package name. It follows the rpy2 convention to replace '.' with '_' in the function name. vector_type - string R Vector type used for packing args. Either 'float' or 'int'. ''' from rpy2.robjects.p...
return np.memmap(data_file, dtype=dty, mode='w+', shape=shape, offset=offset)
return np.memmap(data_file, dtype=np.dtype(descr), mode='w+', shape=shape, offset=offset)
def arrayfile(data_file, shape, descr, fortran=False): ''' returns an array that is memory mapped to an NPY (v1.0) file Arguments --------- data_file - a file-like object opened with write mode shape - shape of the ndarray descr - any argument that numpy.dtype() can take fortran - if True, the array uses Fortran data ...
if args.add_dimension is not None: n = len(set(args.index[args.add_dimension])) if args.color is None: args.color = [ tuple([ float(i) / n ]*3) for i in xrange(n) ] else: args.color = args.color * n elif args.color is None: args.color = 'k'
if args.func is plotcmd: if args.add_dimension is not None: n = len(set(args.index[args.add_dimension])) if args.color is None: args.color = [ tuple([ float(i) / n ]*3) for i in xrange(n) ] else: args.color = args.color * n elif args.color is None: args.color = 'k' elif args.func is listcmd: pass
def check_parser(args, parser): name = args.input.files[0].split('-')[:-1] args.name = ''.join(name) args.index = args.input[args.name+'_index'] args.defaults = args.input[args.name+'_defaults'] if args.add_dimension is not None: n = len(set(args.index[args.add_dimension])) if args.color is None: args.color = [ tuple([...
self.assertRaises(Exception, test_view('ldap_authentication'))
test_view('ldap_authentication')
def test0005views(self): ''' Test views. ''' self.assertRaises(Exception, test_view('ldap_authentication'))
selected.extend(tourny_select_chromo(sample))
selected.append(tourny_select_chromo(sample))
def main(): # for each generation # create a selected group with tourny_select_chromo() until we have enough # create a solution group by breeding random chromos in selected group # print the best, worst, and average fitness, and the chromo with best # stop loop if best fitness == 0 # Create a random sample of...
solution.sort(key = fitness)
sample = sorted(solution, key = fitness) print sample
def main(): # for each generation # create a selected group with tourny_select_chromo() until we have enough # create a solution group by breeding random chromos in selected group # print the best, worst, and average fitness, and the chromo with best # stop loop if best fitness == 0 # Create a random sample of...
>>> fitness('Hello World!')
>>> ghw = GeneticHelloWorld() >>> ghw.fitness('Hello World!')
def fitness(self, chromo): ''' Fitness of a chromo is the sum of how far each of its charactors is from the target string.
>>> fitness('Iello World!')
>>> ghw.fitness('Iello World!')
def fitness(self, chromo): ''' Fitness of a chromo is the sum of how far each of its charactors is from the target string.
>>> fitness('Iallo World!')
>>> ghw.fitness('Iallo World!')
def fitness(self, chromo): ''' Fitness of a chromo is the sum of how far each of its charactors is from the target string.
>>> fitness('Hello!')
>>> ghw.fitness('Hello!')
def fitness(self, chromo): ''' Fitness of a chromo is the sum of how far each of its charactors is from the target string.
f = fitness('a')
f = fitness(sample[0])
def main(): # Create a random sample # for each generation # create a selected group with tourny_select_chromo() until we have enough # create a solution group by breeding random chromos in selected group # print the best, worst, and average fitness, and the chromo with best # stop loop if best fitness == 0 sam...
mailingList = getattr(self.context.ListManager, self.groupInfo.id)
mailingList = getattr(self.groupInfo.groupObj.ListManager, self.groupInfo.id)
def __set_list_subscribe(self, val): mailingList = getattr(self.context.ListManager, self.groupInfo.id) if mailingList.hasProperty('subscribe'): mailingList.manage_changeProperties(subscribe=val) else: mailingList.manage_addProperty('subscribe', val, 'string') assert mailingList.getProperty('subscribe') == val, \ 'Sub...
Gtk.Table.__init__(self, label=str, **kwds)
Gtk.Label.__init__(self, label=str, **kwds)
def __init__(self, str=None, **kwds): Gtk.Table.__init__(self, label=str, **kwds)
def append(self, row):
def append(self, row=None):
def append(self, row): treeiter = Gtk.ListStore.append(self)
n_columns = self.get_n_columns(); if len(row) != n_columns: raise ValueError('row sequence has the incorrect number of elements') for i in range(n_columns): if row[i] is not None: self.set_value(treeiter, i, row[i])
if row is not None: n_columns = self.get_n_columns(); if len(row) != n_columns: raise ValueError('row sequence has the incorrect number of elements') for i in range(n_columns): if row[i] is not None: self.set_value(treeiter, i, row[i])
def append(self, row): treeiter = Gtk.ListStore.append(self)
def append(self, parent, row):
def append(self, parent, row=None):
def append(self, parent, row):
n_columns = self.get_n_columns(); if len(row) != n_columns: raise ValueError('row sequence has the incorrect number of elements') for i in range(n_columns): if row[i] is not None: self.set_value(treeiter, i, row[i])
if row is not None: n_columns = self.get_n_columns(); if len(row) != n_columns: raise ValueError('row sequence has the incorrect number of elements') for i in range(n_columns): if row[i] is not None: self.set_value(treeiter, i, row[i])
def append(self, parent, row):
enable_threading = 1
enable_threading = True
def install_templates(self): self.install_template('pygobject-%s.pc.in' % PYGTK_SUFFIX, os.path.join(self.install_dir, 'lib', 'pkgconfig'))
win.connect('destroy', Gtk.main_quit)
win.connect('destroy', lambda w: Gtk.main_quit())
def main(): win = Gtk.Window() win.connect('destroy', Gtk.main_quit) win.set_default_size(450, 550) drawingarea = Gtk.DrawingArea() win.add(drawingarea) drawingarea.connect('expose_event', expose) win.show_all() Gtk.main()
elif vfunc is not None and not \ is_function_in_classes(vfunc.im_func, cls.__bases__): hook_up_vfunc_implementation(vfunc_info, cls.__gtype__, vfunc)
elif vfunc is not None: function = vfunc if sys.version_info < (3, 0): function = vfunc.im_func if not is_function_in_classes(function, cls.__bases__): hook_up_vfunc_implementation(vfunc_info, cls.__gtype__, vfunc)
def _setup_vfuncs(cls): for base in cls.__bases__: if not hasattr(base, '__info__') or \ not hasattr(base.__info__, 'get_vfuncs'): continue for vfunc_info in base.__info__.get_vfuncs(): vfunc = getattr(cls, 'do_' + vfunc_info.get_name(), None) if vfunc is None and isinstance(base.__info__, InterfaceInfo) and \ not hasa...
import gobject
def test_dynamic_module(self): from gi.module import DynamicGObjectModule import gobject self.assertTrue(isinstance(GObject, DynamicGObjectModule)) # compare the same enum from both the pygobject attrs and gi GObject attrs self.assertEquals(GObject.SIGNAL_ACTION, GObject.SignalFlags.ACTION) # compare a static gobject a...
self.assertEquals("", Everything.test_unichar("")) self.assertEquals("\xe2\x99\xa5", Everything.test_unichar("\xe2\x99\xa5"))
if sys.version_info < (3, 0): self.assertEquals(UNICHAR, Everything.test_unichar(PY2_UNICODE_UNICHAR)) self.assertEquals(UNICHAR, Everything.test_unichar(UNICHAR)) self.assertRaises(TypeError, Everything.test_unichar, "") self.assertRaises(TypeError, Everything.test_unichar, "morethanonechar")
def test_unichar(self): self.assertEquals("c", Everything.test_unichar("c")) self.assertEquals("", Everything.test_unichar("")) self.assertEquals("\xe2\x99\xa5", Everything.test_unichar("\xe2\x99\xa5"))
def __init__(self, name): super(ActionGroup, self).__init__(name = name)
def __init__(self, name, **kwds): super(ActionGroup, self).__init__(name = name, **kwds)
def __init__(self, name): super(ActionGroup, self).__init__(name = name)
self.assertRaises(TypeError, GIMarshallingTests.NotSimpleStruct)
struct = GIMarshallingTests.NotSimpleStruct() self.assertEquals(None, struct.pointer)
def test_not_simple_struct(self): self.assertRaises(TypeError, GIMarshallingTests.NotSimpleStruct)
clipboard = Gtk.clipboard_get(atom)
clipboard = Gtk.Clipboard.get(atom)
def copy_image(self, item, data): # get the default clipboard atom = Gdk.atom_intern('CLIPBOARD', True) clipboard = Gtk.clipboard_get(atom) pixbuf = self.get_image_pixbuf(data)
clipboard = Gtk.clipboard_get(atom)
clipboard = Gtk.Clipboard.get(atom)
def paste_image(self, item, data): # get the default clipboard atom = Gdk.atom_intern('CLIPBOARD', True) clipboard = Gtk.clipboard_get(atom) pixbuf = clipboard.wait_for_image()
name = value_info.get_name().upper() setattr(wrapper, name, wrapper(value_info.get_value()))
value_name = value_info.get_name().upper() setattr(wrapper, value_name, wrapper(value_info.get_value())) if g_type != gobject.TYPE_NONE: g_type.pytype = wrapper
def __getattr__(self, name): info = repository.find_by_name(self._namespace, name) if not info: raise AttributeError("%r object has no attribute %r" % ( self.__name__, name))
module_name = base_name[0:-3] module = getattr(__import__('demos.' + module_name), module_name)
scrub_ext = f[0:-3] split_path = scrub_ext.split(os.sep) module_name = split_path[-1] base_module_name = '.'.join(split_path[:-1]) _temp = __import__(base_module_name, globals(), locals(), [module_name], -1) module = getattr(_temp, module_name)
def load_demos_from_list(self, file_list, demo_list): for f in file_list: base_name = os.path.basename(f) if base_name == '__init__.py': continue
if vfunc is None and isinstance(base.__info__, InterfaceInfo):
if vfunc is None and isinstance(base.__info__, InterfaceInfo) and \ not hasattr(cls, vfunc_info.get_name()):
def _setup_vfuncs(cls): for base in cls.__bases__: if not hasattr(base, '__info__') or \ not hasattr(base.__info__, 'get_vfuncs'): continue for vfunc_info in base.__info__.get_vfuncs(): vfunc = getattr(cls, 'do_' + vfunc_info.get_name(), None) if vfunc is None and isinstance(base.__info__, InterfaceInfo): raise TypeErr...
class ComboBox(Gtk.ComboBox):
class ComboBox(Gtk.ComboBox, Container):
def add_ui_from_string(self, buffer): if not isinstance(buffer, _basestring): raise TypeError('buffer must be a string')
class Container(Gtk.Container): def get_focus_chain(self): success, widgets = super(Container, self).get_focus_chain() if success: return widgets Container = override(Container) __all__.append('Container')
def get_active_iter(self): success, aiter = super(ComboBox, self).get_active_iter() if success: return aiter
class Dialog(Gtk.Dialog):
class Dialog(Gtk.Dialog, Container):
def add_objects_from_string(self, buffer, object_ids): if not isinstance(buffer, _basestring): raise TypeError('buffer must be a string')
class ListStore(Gtk.ListStore, TreeModel):
class TreeSortable(Gtk.TreeSortable, ): def get_sort_column_id(self): success, sort_column_id, order = super(TreeSortable, self).get_sort_column_id() if success: return (sort_column_id, order,) else: return (None, None,) TreeSortable = override(TreeSortable) __all__.append('TreeSortable') class ListStore(Gtk.ListSt...
def iter_parent(self, aiter): success, parent_iter = super(TreeModel, self).iter_parent(aiter) if success: return parent_iter
class TreeStore(Gtk.TreeStore, TreeModel):
class TreeStore(Gtk.TreeStore, TreeModel, TreeSortable):
def __ge__(self, other): return self.compare(other) >= 0
class TreeSortable(Gtk.TreeSortable): def get_sort_column_id(self): success, sort_column_id, order = super(TreeSortable, self).get_sort_column_id() if success: return (sort_column_id, order,) else: return (None, None,) TreeSortable = override(TreeSortable) __all__.append('TreeSortable') class TreeView(Gtk.TreeView):
class TreeView(Gtk.TreeView, Container):
def append(self, parent, row=None):
class Widget(Gtk.Widget): def translate_coordinates(self, dest_widget, src_x, src_y): success, dest_x, dest_y = super(Widget, self).translate_coordinates( dest_widget, src_x, src_y) if success: return (dest_x, dest_y,) Widget = override(Widget) __all__.append('Widget') class Button(Gtk.Button):
class Button(Gtk.Button, Container):
def get_selected(self): success, model, aiter = super(TreeSelection, self).get_selected() if success: return (model, aiter) else: return (model, None)
(success, m, treeiter) = selection.get_selected() if not success:
sel = selection.get_selected() if sel == ():
def selection_cb(self, selection, model): (success, m, treeiter) = selection.get_selected() if not success: return
(success, first_iter) = tree_store.get_iter_first() selection.select_iter(first_iter)
first_iter = tree_store.get_iter_first() if first_iter is not None: selection.select_iter(first_iter)
def create_tree(self): tree_store = Gtk.TreeStore(str, Demo, Pango.Style) tree_view = Gtk.TreeView() self.tree_view = tree_view tree_view.set_model(tree_store) selection = tree_view.get_selection() selection.set_mode(Gtk.SelectionMode.BROWSE) tree_view.set_size_request(200, -1)
raise ValueError('Expected string or unicode for row %i but got %s' % i, type(value))
raise ValueError('Expected string or unicode for row %i but got %s%s' % (i, value, type(value)))
def set_row(self, treeiter, row): # TODO: Accept a dictionary for row # model.append(None,{COLUMN_ICON: icon, COLUMN_NAME: name})
raise ValueError('Expected a string for row %i but got %s' % i, type(value))
raise ValueError('Expected a string for row %i but got %s' % (i, type(value)))
def set_row(self, treeiter, row): # TODO: Accept a dictionary for row # model.append(None,{COLUMN_ICON: icon, COLUMN_NAME: name})
raise ValueError('Expected a float for row %i but got %s' % i, type(value))
raise ValueError('Expected a float for row %i but got %s' % (i, type(value)))
def set_row(self, treeiter, row): # TODO: Accept a dictionary for row # model.append(None,{COLUMN_ICON: icon, COLUMN_NAME: name})
print(entry.target, entry.flags, entry.info)
def _construct_target_list(self, targets): # FIXME: this should most likely be part of Widget or a global helper # function target_entries = [] for t in targets: entry = Gtk.TargetEntry.new(*t) target_entries.append(entry) print(entry.target, entry.flags, entry.info) return target_entries
self.assertEqual(None, Everything.test_gslist_null_out()) self.assertEqual(None, Everything.test_glist_null_out())
self.assertEqual([], Everything.test_gslist_null_out()) self.assertEqual([], Everything.test_glist_null_out())
def test_out_nullable_list(self): self.assertEqual(None, Everything.test_gslist_null_out()) self.assertEqual(None, Everything.test_glist_null_out())
expected_results = (('test-action1', Gtk.Action),
expected_results = [('test-action1', Gtk.Action),
def test_radio_action_callback_data(action, current, user_data): self.assertEquals(user_data, callback_data);
('test-radio-action2', Gtk.RadioAction)) for action, cmp in zip(action_group.list_actions(), expected_results):
('test-radio-action2', Gtk.RadioAction)] for action in action_group.list_actions():
def test_radio_action_callback_data(action, current, user_data): self.assertEquals(user_data, callback_data);