repo_name
stringlengths 5
92
| path
stringlengths 4
221
| copies
stringclasses 19
values | size
stringlengths 4
6
| content
stringlengths 766
896k
| license
stringclasses 15
values | hash
int64 -9,223,277,421,539,062,000
9,223,102,107B
| line_mean
float64 6.51
99.9
| line_max
int64 32
997
| alpha_frac
float64 0.25
0.96
| autogenerated
bool 1
class | ratio
float64 1.5
13.6
| config_test
bool 2
classes | has_no_keywords
bool 2
classes | few_assignments
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
luntos/bianalyzer
|
bianalyzer/main.py
|
1
|
4399
|
# -*- coding: utf-8 -*-
import sys
import getopt
from bianalyzer import BianalyzerText
from bianalyzer.abstracts import download_abstracts
from bianalyzer.biclustering import get_keyword_biclusters, GreedyBBox, get_keyword_text_biclusters, \
save_keyword_text_biclusters
from bianalyzer.biclustering.keywords_analysis import save_keyword_biclusters
from bianalyzer.keywords import extract_keywords_via_textrank
from bianalyzer.relevance import construct_relevance_matrix, construct_similarity_matrix
usage = "Bianalyzer should be called as:\n" \
"bianalyzer [-s <source>] [-S <springer_api_key>] [-m <relevance_metric>] [-q <query>] [-r] [-d] biclusters " \
"<abtracts_number> <path_to_file>"
supported_sources = ['IEEE', 'Springer']
supported_relevance_metrics = ['tf-idf', 'bm25', 'ast', 'frequency', 'normalized_frequency']
def main():
def print_error(message):
print message + '\n'
print usage
args = sys.argv[1:]
opts, args = getopt.getopt(args, "s:S:m:q:rd")
opts = dict(opts)
opts.setdefault('-s', 'IEEE')
opts.setdefault('-S', None)
opts.setdefault('-m', 'bm25')
opts.setdefault('-q', 'cluster analysis')
opts.setdefault('-r', False)
opts.setdefault('-d', False)
if opts['-r'] == '':
opts['-r'] = True
if opts['-d'] == '':
opts['-d'] = True
# print opts, args
if opts['-d'] and opts['-r']:
print_error('Cannot use both options -r and -d simultaneously')
return 1
if opts['-s'] not in supported_sources:
print_error('Invalid source of abstracts. It should be either IEEE or Springer')
return 1
if opts['-m'] not in supported_relevance_metrics:
print_error('Invalid relevance metric. It should be tf-idf, bm25, ast, frequency or normalized_frequency')
return 1
if opts['-s'] == 'Springer' and opts['-S'] == '':
print_error('Invalid Springer API key')
if len(args) < 3:
print_error('Invalid command format. Please use the following format: biclusters <number> <path_to_file>')
return 1
command = args[0]
abstracts_number = args[1]
path_to_file = args[2]
parsed = True
try:
abstracts_number = int(abstracts_number)
except ValueError:
parsed = False
if not parsed or (abstracts_number > 5000) or (abstracts_number < 1):
print_error('Invalid number of abstracts to download. It should be in range [1, 5000]')
return 1
if command == 'biclusters':
try:
biclusters_file = open(path_to_file, 'w')
except Exception:
print_error('Could not create/open the file specified')
return 1
try:
articles = download_abstracts(opts['-s'], opts['-q'], abstracts_number, springer_api_key=opts['-S'])
except Exception, e:
print_error('Error occurred while downloading: %s' % e)
return 1
bianalyzer_texts = [BianalyzerText(article.abstract_text) for article in articles]
keywords = extract_keywords_via_textrank(bianalyzer_texts)
relevance_matrix = construct_relevance_matrix(keywords, bianalyzer_texts, opts['-m'])
if not opts['-r']:
similarity_matrix = construct_similarity_matrix(relevance_matrix, 0.2)
keyword_biclusters = get_keyword_biclusters(similarity_matrix, GreedyBBox)
save_keyword_biclusters(keyword_biclusters, biclusters_file, min_density=0.1)
if opts['-d']:
try:
from bianalyzer.graphs import construct_keyword_graph, draw_keyword_biclusters
edges = construct_keyword_graph(keyword_biclusters.biclusters, biclusters_num=100)
draw_keyword_biclusters(edges)
except Exception:
print '-------------------------'
print 'Could not draw the graph! Please, install the nodebox-opengl package'
else:
keyword_text_biclusters = get_keyword_text_biclusters(relevance_matrix, GreedyBBox)
save_keyword_text_biclusters(keyword_text_biclusters, biclusters_file, min_density=0.1)
biclusters_file.close()
else:
print_error('Invalid command format. Please use the following format: biclusters <number> <path_to_file>')
return 1
if __name__ == "__main__":
main()
|
mit
| -5,883,963,076,646,310,000
| 38.630631
| 119
| 0.629234
| false
| 3.808658
| false
| false
| false
|
kyleam/pymc3
|
pymc/sampling.py
|
1
|
7330
|
from . import backends
from .backends.base import merge_traces, BaseTrace, MultiTrace
from .backends.ndarray import NDArray
import multiprocessing as mp
from time import time
from .core import *
from . import step_methods
from .progressbar import progress_bar
from numpy.random import seed
__all__ = ['sample', 'iter_sample']
def sample(draws, step, start=None, trace=None, chain=0, njobs=1, tune=None,
progressbar=True, model=None, random_seed=None):
"""
Draw a number of samples using the given step method.
Multiple step methods supported via compound step method
returns the amount of time taken.
Parameters
----------
draws : int
The number of samples to draw
step : function
A step function
start : dict
Starting point in parameter space (or partial point)
Defaults to trace.point(-1)) if there is a trace provided and
model.test_point if not (defaults to empty dict)
trace : backend, list, or MultiTrace
This should be a backend instance, a list of variables to track,
or a MultiTrace object with past values. If a MultiTrace object
is given, it must contain samples for the chain number `chain`.
If None or a list of variables, the NDArray backend is used.
Passing either "text" or "sqlite" is taken as a shortcut to set
up the corresponding backend (with "mcmc" used as the base
name).
chain : int
Chain number used to store sample in backend. If `njobs` is
greater than one, chain numbers will start here.
njobs : int
Number of parallel jobs to start. If None, set to number of cpus
in the system - 2.
tune : int
Number of iterations to tune, if applicable (defaults to None)
progressbar : bool
Flag for progress bar
model : Model (optional if in `with` context)
random_seed : int or list of ints
A list is accepted if more if `njobs` is greater than one.
Returns
-------
MultiTrace object with access to sampling values
"""
if njobs is None:
njobs = max(mp.cpu_count() - 2, 1)
if njobs > 1:
try:
if not len(random_seed) == njobs:
random_seeds = [random_seed] * njobs
else:
random_seeds = random_seed
except TypeError: # None, int
random_seeds = [random_seed] * njobs
chains = list(range(chain, chain + njobs))
pbars = [progressbar] + [False] * (njobs - 1)
argset = zip([draws] * njobs,
[step] * njobs,
[start] * njobs,
[trace] * njobs,
chains,
[tune] * njobs,
pbars,
[model] * njobs,
random_seeds)
sample_func = _mp_sample
sample_args = [njobs, argset]
else:
sample_func = _sample
sample_args = [draws, step, start, trace, chain,
tune, progressbar, model, random_seed]
return sample_func(*sample_args)
def _sample(draws, step, start=None, trace=None, chain=0, tune=None,
progressbar=True, model=None, random_seed=None):
sampling = _iter_sample(draws, step, start, trace, chain,
tune, model, random_seed)
progress = progress_bar(draws)
try:
for i, trace in enumerate(sampling):
if progressbar:
progress.update(i)
except KeyboardInterrupt:
trace.close()
return MultiTrace([trace])
def iter_sample(draws, step, start=None, trace=None, chain=0, tune=None,
model=None, random_seed=None):
"""
Generator that returns a trace on each iteration using the given
step method. Multiple step methods supported via compound step
method returns the amount of time taken.
Parameters
----------
draws : int
The number of samples to draw
step : function
A step function
start : dict
Starting point in parameter space (or partial point)
Defaults to trace.point(-1)) if there is a trace provided and
model.test_point if not (defaults to empty dict)
trace : backend, list, or MultiTrace
This should be a backend instance, a list of variables to track,
or a MultiTrace object with past values. If a MultiTrace object
is given, it must contain samples for the chain number `chain`.
If None or a list of variables, the NDArray backend is used.
chain : int
Chain number used to store sample in backend. If `njobs` is
greater than one, chain numbers will start here.
tune : int
Number of iterations to tune, if applicable (defaults to None)
model : Model (optional if in `with` context)
random_seed : int or list of ints
A list is accepted if more if `njobs` is greater than one.
Example
-------
for trace in iter_sample(500, step):
...
"""
sampling = _iter_sample(draws, step, start, trace, chain, tune,
model, random_seed)
for i, trace in enumerate(sampling):
yield trace[:i + 1]
def _iter_sample(draws, step, start=None, trace=None, chain=0, tune=None,
model=None, random_seed=None):
model = modelcontext(model)
draws = int(draws)
seed(random_seed)
if draws < 1:
raise ValueError('Argument `draws` should be above 0.')
if start is None:
start = {}
trace = _choose_backend(trace, chain, model=model)
if len(trace) > 0:
_soft_update(start, trace.point(-1))
else:
_soft_update(start, model.test_point)
try:
step = step_methods.CompoundStep(step)
except TypeError:
pass
point = Point(start, model=model)
trace.setup(draws, chain)
for i in range(draws):
if i == tune:
step = stop_tuning(step)
point = step.step(point)
trace.record(point)
yield trace
else:
trace.close()
def _choose_backend(trace, chain, shortcuts=None, **kwds):
if isinstance(trace, BaseTrace):
return trace
if isinstance(trace, MultiTrace):
return trace._traces[chain]
if trace is None:
return NDArray(**kwds)
if shortcuts is None:
shortcuts = backends._shortcuts
try:
backend = shortcuts[trace]['backend']
name = shortcuts[trace]['name']
return backend(name, **kwds)
except TypeError:
return NDArray(vars=trace, **kwds)
except KeyError:
raise ValueError('Argument `trace` is invalid.')
def _mp_sample(njobs, args):
p = mp.Pool(njobs)
traces = p.map(argsample, args)
p.close()
return merge_traces(traces)
def stop_tuning(step):
""" stop tuning the current step method """
if hasattr(step, 'tune'):
step.tune = False
elif hasattr(step, 'methods'):
step.methods = [stop_tuning(s) for s in step.methods]
return step
def argsample(args):
""" defined at top level so it can be pickled"""
return _sample(*args)
def _soft_update(a, b):
"""As opposed to dict.update, don't overwrite keys if present.
"""
a.update({k: v for k, v in b.items() if k not in a})
|
apache-2.0
| 3,758,578,631,098,075,600
| 30.324786
| 76
| 0.605866
| false
| 4.014239
| false
| false
| false
|
muisit/freezer
|
model/archive.py
|
1
|
4651
|
#
# Copyright Muis IT 2011 - 2016
#
# This file is part of AWS Freezer
#
# AWS Freezer 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.
#
# AWS Freezer 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 AWS Freezer (see the COPYING file).
# If not, see <http://www.gnu.org/licenses/>.
import awsobj
import globals
class Archive(awsobj.Object):
def __init__(self):
self.name=''
self.id=None
self.vault_id=-1
self.lastupload=''
self.size=0
self.created=''
self.description=''
self.local_file=''
self.key_id=-1
def add_files(self, lst):
for f in lst:
f.save()
if f.id != None:
obj={'a': self.id, 'f': f.id, 'p': f.path}
globals.DB.connection.execute("delete from archive_file where archive_id=:a and file_id=:f",obj)
globals.DB.connection.execute("INSERT INTO archive_file (archive_id, file_id,path) VALUES(:a,:f,:p)",obj)
globals.DB.connection.execute("UPDATE file SET is_dirty=1 WHERE id=:f",obj)
def by_name(self, name):
row=globals.DB.connection.execute("select * from archive where name=:n",{'n': name}).fetchone()
if row != None:
self.read(row)
else:
self.id=None
@staticmethod
def by_vault(vault):
rows=globals.DB.connection.execute("SELECT * FROM archive WHERE vault_id=:n",{'n': vault.id}).fetchall()
retval=[]
for row in rows:
archive = Archive()
archive.read(row)
retval.append(archive)
return retval
def load(self,id=None):
if id != None:
self.id=id
row=globals.DB.connection.execute("select * from archive where id=:id",{'id':self.id}).fetchone()
if row != None:
self.read(row)
else:
self.id=None
def read(self,row):
self.id=self.to_int(row['id'])
self.name=self.to_str(row['name'])
self.vault_id=self.to_int(row['vault_id'])
self.size=self.to_int(row['size'])
self.lastupload=self.to_str(row['lastupload'])
self.created=self.to_str(row['created'])
self.description=self.to_str(row['description'])
self.local_file=self.to_str(row['local_file'])
self.key_id=self.to_int(row['key_id'])
def save(self):
obj = {
"id": self.id,
"n": self.name,
"v": self.vault_id,
"s": self.size,
"d": self.description,
"l": self.lastupload,
"c": self.created,
"lf": self.local_file,
'k': self.key_id
}
if not self.id:
globals.DB.connection.execute("INSERT INTO archive (name,vault_id,size,lastupload,created,description,local_file,key_id) VALUES(:n,:v,:s,:l,:c,:d,:lf,:k)",obj)
else:
globals.DB.connection.execute("UPDATE archive SET name=:n, vault_id=:v, size=:s, lastupload=:l, created=:c, description=:d, local_file=:lf, key_id=:k where id=:id",obj)
globals.DB.connection.commit()
if not self.id:
row = globals.DB.connection.execute("SELECT max(id) as id FROM archive").fetchone()
if row != None:
self.id = row['id']
def import_aws(self, v):
globals.Reporter.message("importing AWS Archive " + str(v),"db")
self.name = self.to_str(v['ArchiveId'])
self.description = self.to_str(v['ArchiveDescription'])
self.lastupload = self.to_str(v['CreationDate'])
self.size = self.to_int(v['Size'])
def copy(self, v):
self.name=v.name
self.description=v.description
self.lastupload=v.lastupload
self.size=v.size
def delete(self):
if self.id != None:
obj = {'id': self.id}
globals.DB.connection.execute("UPDATE file SET is_dirty=1 WHERE id in (SELECT file_id FROM archive_file WHERE archive_id=:id)",obj)
globals.DB.connection.execute("DELETE FROM archive_file WHERE archive_id=:id",obj)
globals.DB.connection.execute("DELETE FROM archive WHERE id=:id",obj)
globals.DB.connection.commit()
|
gpl-3.0
| 763,632,750,901,110,500
| 36.813008
| 180
| 0.592346
| false
| 3.536882
| false
| false
| false
|
wenhulove333/ScutServer
|
Sample/ClientSource/tools/bindings-generator/generator.py
|
1
|
34942
|
#!/usr/bin/env python
# generator.py
# simple C++ generator, originally targetted for Spidermonkey bindings
#
# Copyright (c) 2011 - Zynga Inc.
from clang import cindex
import sys
import pdb
import ConfigParser
import yaml
import re
import os
import inspect
from Cheetah.Template import Template
type_map = {
cindex.TypeKind.VOID : "void",
cindex.TypeKind.BOOL : "bool",
cindex.TypeKind.CHAR_U : "unsigned char",
cindex.TypeKind.UCHAR : "unsigned char",
cindex.TypeKind.CHAR16 : "char",
cindex.TypeKind.CHAR32 : "char",
cindex.TypeKind.USHORT : "unsigned short",
cindex.TypeKind.UINT : "unsigned int",
cindex.TypeKind.ULONG : "unsigned long",
cindex.TypeKind.ULONGLONG : "unsigned long long",
cindex.TypeKind.CHAR_S : "char",
cindex.TypeKind.SCHAR : "char",
cindex.TypeKind.WCHAR : "wchar_t",
cindex.TypeKind.SHORT : "short",
cindex.TypeKind.INT : "int",
cindex.TypeKind.LONG : "long",
cindex.TypeKind.LONGLONG : "long long",
cindex.TypeKind.FLOAT : "float",
cindex.TypeKind.DOUBLE : "double",
cindex.TypeKind.LONGDOUBLE : "long double",
cindex.TypeKind.NULLPTR : "NULL",
cindex.TypeKind.OBJCID : "id",
cindex.TypeKind.OBJCCLASS : "class",
cindex.TypeKind.OBJCSEL : "SEL",
# cindex.TypeKind.ENUM : "int"
}
INVALID_NATIVE_TYPE = "??"
default_arg_type_arr = [
# An integer literal.
cindex.CursorKind.INTEGER_LITERAL,
# A floating point number literal.
cindex.CursorKind.FLOATING_LITERAL,
# An imaginary number literal.
cindex.CursorKind.IMAGINARY_LITERAL,
# A string literal.
cindex.CursorKind.STRING_LITERAL,
# A character literal.
cindex.CursorKind.CHARACTER_LITERAL,
# [C++ 2.13.5] C++ Boolean Literal.
cindex.CursorKind.CXX_BOOL_LITERAL_EXPR,
# [C++0x 2.14.7] C++ Pointer Literal.
cindex.CursorKind.CXX_NULL_PTR_LITERAL_EXPR
]
def native_name_from_type(ntype, underlying=False):
kind = ntype.get_canonical().kind
const = "const " if ntype.is_const_qualified() else ""
if not underlying and kind == cindex.TypeKind.ENUM:
decl = ntype.get_declaration()
return namespaced_name(decl)
elif kind in type_map:
return const + type_map[kind]
elif kind == cindex.TypeKind.RECORD:
# might be an std::string
decl = ntype.get_declaration()
parent = decl.semantic_parent
if decl.spelling == "string" and parent and parent.spelling == "std":
return "std::string"
else:
# print >> sys.stderr, "probably a function pointer: " + str(decl.spelling)
return const + decl.spelling
else:
# name = ntype.get_declaration().spelling
# print >> sys.stderr, "Unknown type: " + str(kind) + " " + str(name)
return INVALID_NATIVE_TYPE
# pdb.set_trace()
def build_namespace(cursor, namespaces=[]):
'''
build the full namespace for a specific cursor
'''
if cursor:
parent = cursor.semantic_parent
if parent:
if parent.kind == cindex.CursorKind.NAMESPACE or parent.kind == cindex.CursorKind.CLASS_DECL:
namespaces.append(parent.displayname)
build_namespace(parent, namespaces)
return namespaces
def namespaced_name(declaration_cursor):
ns_list = build_namespace(declaration_cursor, [])
ns_list.reverse()
ns = "::".join(ns_list)
if len(ns) > 0:
return ns + "::" + declaration_cursor.displayname
return declaration_cursor.displayname
class NativeType(object):
def __init__(self, ntype):
self.type = ntype
self.is_pointer = False
self.is_object = False
self.not_supported = False
self.namespaced_name = ""
self.name = ""
if ntype.kind == cindex.TypeKind.POINTER:
pointee = ntype.get_pointee()
self.is_pointer = True
if pointee.kind == cindex.TypeKind.RECORD:
decl = pointee.get_declaration()
self.is_object = True
self.name = decl.displayname
self.namespaced_name = namespaced_name(decl)
else:
self.name = native_name_from_type(pointee)
self.namespaced_name = self.name
self.name += "*"
self.namespaced_name += "*"
elif ntype.kind == cindex.TypeKind.LVALUEREFERENCE:
pointee = ntype.get_pointee()
decl = pointee.get_declaration()
self.namespaced_name = namespaced_name(decl)
if pointee.kind == cindex.TypeKind.RECORD:
self.name = decl.displayname
self.is_object = True
else:
self.name = native_name_from_type(pointee)
else:
if ntype.kind == cindex.TypeKind.RECORD:
decl = ntype.get_declaration()
self.is_object = True
self.name = decl.displayname
self.namespaced_name = namespaced_name(decl)
else:
self.name = native_name_from_type(ntype)
self.namespaced_name = self.name
# mark argument as not supported
if self.name == INVALID_NATIVE_TYPE:
self.not_supported = True
def from_native(self, convert_opts):
assert(convert_opts.has_key('generator'))
generator = convert_opts['generator']
name = self.name
if self.is_object:
if self.is_pointer and not name in generator.config['conversions']['from_native']:
name = "object"
elif not generator.config['conversions']['from_native'].has_key(name):
name = "object"
elif self.type.get_canonical().kind == cindex.TypeKind.ENUM:
name = "int"
if generator.config['conversions']['from_native'].has_key(name):
tpl = generator.config['conversions']['from_native'][name]
tpl = Template(tpl, searchList=[convert_opts])
return str(tpl).rstrip()
return "#pragma warning NO CONVERSION FROM NATIVE FOR " + name
def to_native(self, convert_opts):
assert('generator' in convert_opts)
generator = convert_opts['generator']
name = self.name
if self.is_object:
if self.is_pointer and not name in generator.config['conversions']['to_native']:
name = "object"
elif not name in generator.config['conversions']['to_native']:
name = "object"
elif self.type.get_canonical().kind == cindex.TypeKind.ENUM:
name = "int"
if generator.config['conversions']['to_native'].has_key(name):
tpl = generator.config['conversions']['to_native'][name]
tpl = Template(tpl, searchList=[convert_opts])
return str(tpl).rstrip()
return "#pragma warning NO CONVERSION TO NATIVE FOR " + name
def to_string(self, generator):
conversions = generator.config['conversions']
if conversions.has_key('native_types') and conversions['native_types'].has_key(self.namespaced_name):
return conversions['native_types'][self.namespaced_name]
return self.namespaced_name
def __str__(self):
return self.namespaced_name
class NativeField(object):
def __init__(self, cursor):
cursor = cursor.canonical
self.cursor = cursor
self.name = cursor.displayname
self.kind = cursor.type.kind
self.location = cursor.location
member_field_re = re.compile('m_(\w+)')
match = member_field_re.match(self.name)
if match:
self.pretty_name = match.group(1)
else:
self.pretty_name = self.name
# return True if found default argument.
def iterate_param_node(param_node):
for node in param_node.get_children():
if (node.kind in default_arg_type_arr):
# print("------ "+str(node.kind))
return True
if (iterate_param_node(node)):
return True
return False
class NativeFunction(object):
def __init__(self, cursor):
self.cursor = cursor
self.func_name = cursor.spelling
self.signature_name = self.func_name
self.arguments = []
self.static = cursor.kind == cindex.CursorKind.CXX_METHOD and cursor.is_method_static()
self.implementations = []
self.is_constructor = False
self.not_supported = False
result = cursor.result_type
# get the result
if result.kind == cindex.TypeKind.LVALUEREFERENCE:
result = result.get_pointee()
self.ret_type = NativeType(cursor.result_type)
# parse the arguments
# if self.func_name == "spriteWithFile":
# pdb.set_trace()
for arg in cursor.type.argument_types():
nt = NativeType(arg)
self.arguments.append(nt)
# mark the function as not supported if at least one argument is not supported
if nt.not_supported:
self.not_supported = True
found_default_arg = False
index = -1
for arg_node in self.cursor.get_children():
if arg_node.kind == cindex.CursorKind.PARM_DECL:
index+=1
if (iterate_param_node(arg_node)):
found_default_arg = True
break
self.min_args = index if found_default_arg else len(self.arguments)
def generate_code(self, current_class=None, generator=None):
gen = current_class.generator if current_class else generator
config = gen.config
tpl = Template(file=os.path.join(gen.target, "templates", "function.h"),
searchList=[current_class, self])
gen.head_file.write(str(tpl))
if self.static:
if config['definitions'].has_key('sfunction'):
tpl = Template(config['definitions']['sfunction'],
searchList=[current_class, self])
self.signature_name = str(tpl)
tpl = Template(file=os.path.join(gen.target, "templates", "sfunction.c"),
searchList=[current_class, self])
else:
if not self.is_constructor:
if config['definitions'].has_key('ifunction'):
tpl = Template(config['definitions']['ifunction'],
searchList=[current_class, self])
self.signature_name = str(tpl)
else:
if config['definitions'].has_key('constructor'):
tpl = Template(config['definitions']['constructor'],
searchList=[current_class, self])
self.signature_name = str(tpl)
tpl = Template(file=os.path.join(gen.target, "templates", "ifunction.c"),
searchList=[current_class, self])
gen.impl_file.write(str(tpl))
apidoc_function_js = Template(file=os.path.join(gen.target,
"templates",
"apidoc_function.js"),
searchList=[current_class, self])
gen.doc_file.write(str(apidoc_function_js))
class NativeOverloadedFunction(object):
def __init__(self, func_array):
self.implementations = func_array
self.func_name = func_array[0].func_name
self.signature_name = self.func_name
self.min_args = 100
self.is_constructor = False
for m in func_array:
self.min_args = min(self.min_args, m.min_args)
def append(self, func):
self.min_args = min(self.min_args, func.min_args)
self.implementations.append(func)
def generate_code(self, current_class=None):
gen = current_class.generator
config = gen.config
static = self.implementations[0].static
tpl = Template(file=os.path.join(gen.target, "templates", "function.h"),
searchList=[current_class, self])
gen.head_file.write(str(tpl))
if static:
if config['definitions'].has_key('sfunction'):
tpl = Template(config['definitions']['sfunction'],
searchList=[current_class, self])
self.signature_name = str(tpl)
tpl = Template(file=os.path.join(gen.target, "templates", "sfunction_overloaded.c"),
searchList=[current_class, self])
else:
if not self.is_constructor:
if config['definitions'].has_key('ifunction'):
tpl = Template(config['definitions']['ifunction'],
searchList=[current_class, self])
self.signature_name = str(tpl)
else:
if config['definitions'].has_key('constructor'):
tpl = Template(config['definitions']['constructor'],
searchList=[current_class, self])
self.signature_name = str(tpl)
tpl = Template(file=os.path.join(gen.target, "templates", "ifunction_overloaded.c"),
searchList=[current_class, self])
gen.impl_file.write(str(tpl))
class NativeClass(object):
def __init__(self, cursor, generator):
# the cursor to the implementation
self.cursor = cursor
self.class_name = cursor.displayname
self.namespaced_class_name = self.class_name
self.parents = []
self.fields = []
self.methods = {}
self.static_methods = {}
self.generator = generator
self.is_abstract = self.class_name in generator.abstract_classes
self._current_visibility = cindex.AccessSpecifierKind.PRIVATE
registration_name = generator.get_class_or_rename_class(self.class_name)
if generator.remove_prefix:
self.target_class_name = re.sub('^'+generator.remove_prefix, '', registration_name)
else:
self.target_class_name = registration_name
self.namespaced_class_name = namespaced_name(cursor)
self.parse()
def parse(self):
'''
parse the current cursor, getting all the necesary information
'''
self._deep_iterate(self.cursor)
def methods_clean(self):
'''
clean list of methods (without the ones that should be skipped)
'''
ret = []
for name, impl in self.methods.iteritems():
should_skip = False
if name == 'constructor':
should_skip = True
else:
if self.generator.should_skip(self.class_name, name):
should_skip = True
if not should_skip:
ret.append({"name": name, "impl": impl})
return ret
def static_methods_clean(self):
'''
clean list of static methods (without the ones that should be skipped)
'''
ret = []
for name, impl in self.static_methods.iteritems():
should_skip = self.generator.should_skip(self.class_name, name)
if not should_skip:
ret.append({"name": name, "impl": impl})
return ret
def generate_code(self):
'''
actually generate the code. it uses the current target templates/rules in order to
generate the right code
'''
config = self.generator.config
prelude_h = Template(file=os.path.join(self.generator.target, "templates", "prelude.h"),
searchList=[{"current_class": self}])
prelude_c = Template(file=os.path.join(self.generator.target, "templates", "prelude.c"),
searchList=[{"current_class": self}])
apidoc_classhead_js = Template(file=os.path.join(self.generator.target,
"templates",
"apidoc_classhead.js"),
searchList=[{"current_class": self}])
self.generator.head_file.write(str(prelude_h))
self.generator.impl_file.write(str(prelude_c))
self.generator.doc_file.write(str(apidoc_classhead_js))
for m in self.methods_clean():
m['impl'].generate_code(self)
for m in self.static_methods_clean():
m['impl'].generate_code(self)
# generate register section
register = Template(file=os.path.join(self.generator.target, "templates", "register.c"),
searchList=[{"current_class": self}])
apidoc_classfoot_js = Template(file=os.path.join(self.generator.target,
"templates",
"apidoc_classfoot.js"),
searchList=[{"current_class": self}])
self.generator.impl_file.write(str(register))
self.generator.doc_file.write(str(apidoc_classfoot_js))
def _deep_iterate(self, cursor=None):
for node in cursor.get_children():
if self._process_node(node):
self._deep_iterate(node)
def _process_node(self, cursor):
'''
process the node, depending on the type. If returns true, then it will perform a deep
iteration on its children. Otherwise it will continue with its siblings (if any)
@param: cursor the cursor to analyze
'''
if cursor.kind == cindex.CursorKind.CXX_BASE_SPECIFIER and not self.class_name in self.generator.classes_have_no_parents:
parent = cursor.get_definition()
if parent.displayname not in self.generator.base_classes_to_skip:
#if parent and self.generator.in_listed_classes(parent.displayname):
if not self.generator.generated_classes.has_key(parent.displayname):
parent = NativeClass(parent, self.generator)
self.generator.generated_classes[parent.class_name] = parent
else:
parent = self.generator.generated_classes[parent.displayname]
self.parents.append(parent)
elif cursor.kind == cindex.CursorKind.FIELD_DECL:
self.fields.append(NativeField(cursor))
elif cursor.kind == cindex.CursorKind.CXX_ACCESS_SPEC_DECL:
self._current_visibility = cursor.get_access_specifier()
elif cursor.kind == cindex.CursorKind.CXX_METHOD:
# skip if variadic
if self._current_visibility == cindex.AccessSpecifierKind.PUBLIC and not cursor.type.is_function_variadic():
m = NativeFunction(cursor)
registration_name = self.generator.should_rename_function(self.class_name, m.func_name) or m.func_name
# bail if the function is not supported (at least one arg not supported)
if m.not_supported:
return
if m.static:
if not self.static_methods.has_key(registration_name):
self.static_methods[registration_name] = m
else:
previous_m = self.static_methods[registration_name]
if isinstance(previous_m, NativeOverloadedFunction):
previous_m.append(m)
else:
self.static_methods[registration_name] = NativeOverloadedFunction([m, previous_m])
else:
if not self.methods.has_key(registration_name):
self.methods[registration_name] = m
else:
previous_m = self.methods[registration_name]
if isinstance(previous_m, NativeOverloadedFunction):
previous_m.append(m)
else:
self.methods[registration_name] = NativeOverloadedFunction([m, previous_m])
return True
elif self._current_visibility == cindex.AccessSpecifierKind.PUBLIC and cursor.kind == cindex.CursorKind.CONSTRUCTOR and not self.is_abstract:
m = NativeFunction(cursor)
m.is_constructor = True
if not self.methods.has_key('constructor'):
self.methods['constructor'] = m
else:
previous_m = self.methods['constructor']
if isinstance(previous_m, NativeOverloadedFunction):
previous_m.append(m)
else:
m = NativeOverloadedFunction([m, previous_m])
m.is_constructor = True
self.methods['constructor'] = m
return True
# else:
# print >> sys.stderr, "unknown cursor: %s - %s" % (cursor.kind, cursor.displayname)
return False
class Generator(object):
def __init__(self, opts):
self.index = cindex.Index.create()
self.outdir = opts['outdir']
self.prefix = opts['prefix']
self.headers = opts['headers'].split(' ')
self.classes = opts['classes']
self.classes_have_no_parents = opts['classes_have_no_parents'].split(' ')
self.base_classes_to_skip = opts['base_classes_to_skip'].split(' ')
self.abstract_classes = opts['abstract_classes'].split(' ')
self.clang_args = opts['clang_args']
self.target = opts['target']
self.remove_prefix = opts['remove_prefix']
self.target_ns = opts['target_ns']
self.impl_file = None
self.head_file = None
self.skip_classes = {}
self.generated_classes = {}
self.rename_functions = {}
self.rename_classes = {}
self.out_file = opts['out_file']
self.script_control_cpp = opts['script_control_cpp'] == "yes"
if opts['skip']:
list_of_skips = re.split(",\n?", opts['skip'])
for skip in list_of_skips:
class_name, methods = skip.split("::")
self.skip_classes[class_name] = []
match = re.match("\[([^]]+)\]", methods)
if match:
self.skip_classes[class_name] = match.group(1).split(" ")
else:
raise Exception("invalid list of skip methods")
if opts['rename_functions']:
list_of_function_renames = re.split(",\n?", opts['rename_functions'])
for rename in list_of_function_renames:
class_name, methods = rename.split("::")
self.rename_functions[class_name] = {}
match = re.match("\[([^]]+)\]", methods)
if match:
list_of_methods = match.group(1).split(" ")
for pair in list_of_methods:
k, v = pair.split("=")
self.rename_functions[class_name][k] = v
else:
raise Exception("invalid list of rename methods")
if opts['rename_classes']:
list_of_class_renames = re.split(",\n?", opts['rename_classes'])
for rename in list_of_class_renames:
class_name, renamed_class_name = rename.split("::")
self.rename_classes[class_name] = renamed_class_name
def should_rename_function(self, class_name, method_name):
if self.rename_functions.has_key(class_name) and self.rename_functions[class_name].has_key(method_name):
# print >> sys.stderr, "will rename %s to %s" % (method_name, self.rename_functions[class_name][method_name])
return self.rename_functions[class_name][method_name]
return None
def get_class_or_rename_class(self, class_name):
if self.rename_classes.has_key(class_name):
# print >> sys.stderr, "will rename %s to %s" % (method_name, self.rename_functions[class_name][method_name])
return self.rename_classes[class_name]
return class_name
def should_skip(self, class_name, method_name, verbose=False):
if class_name == "*" and self.skip_classes.has_key("*"):
for func in self.skip_classes["*"]:
if re.match(func, method_name):
return True
else:
for key in self.skip_classes.iterkeys():
if key == "*" or re.match("^" + key + "$", class_name):
if verbose:
print "%s in skip_classes" % (class_name)
if len(self.skip_classes[key]) == 1 and self.skip_classes[key][0] == "*":
if verbose:
print "%s will be skipped completely" % (class_name)
return True
if method_name != None:
for func in self.skip_classes[key]:
if re.match(func, method_name):
if verbose:
print "%s will skip method %s" % (class_name, method_name)
return True
if verbose:
print "%s will be accepted (%s, %s)" % (class_name, key, self.skip_classes[key])
return False
def in_listed_classes(self, class_name):
"""
returns True if the class is in the list of required classes and it's not in the skip list
"""
for key in self.classes:
md = re.match("^" + key + "$", class_name)
if md and not self.should_skip(class_name, None):
return True
return False
def sorted_classes(self):
'''
sorted classes in order of inheritance
'''
sorted_list = []
for class_name in self.generated_classes.iterkeys():
nclass = self.generated_classes[class_name]
sorted_list += self._sorted_parents(nclass)
# remove dupes from the list
no_dupes = []
[no_dupes.append(i) for i in sorted_list if not no_dupes.count(i)]
return no_dupes
def _sorted_parents(self, nclass):
'''
returns the sorted list of parents for a native class
'''
sorted_parents = []
for p in nclass.parents:
if p.class_name in self.generated_classes.keys():
sorted_parents += self._sorted_parents(p)
if nclass.class_name in self.generated_classes.keys():
sorted_parents.append(nclass.class_name)
return sorted_parents
def generate_code(self):
# must read the yaml file first
stream = file(os.path.join(self.target, "conversions.yaml"), "r")
data = yaml.load(stream)
self.config = data
implfilepath = os.path.join(self.outdir, self.out_file + ".cpp")
headfilepath = os.path.join(self.outdir, self.out_file + ".hpp")
docfilepath = os.path.join(self.outdir, self.out_file + "_api.js")
self.impl_file = open(implfilepath, "w+")
self.head_file = open(headfilepath, "w+")
self.doc_file = open(docfilepath, "w+")
layout_h = Template(file=os.path.join(self.target, "templates", "layout_head.h"),
searchList=[self])
layout_c = Template(file=os.path.join(self.target, "templates", "layout_head.c"),
searchList=[self])
apidoc_ns_js = Template(file=os.path.join(self.target, "templates", "apidoc_ns.js"),
searchList=[self])
self.head_file.write(str(layout_h))
self.impl_file.write(str(layout_c))
self.doc_file.write(str(apidoc_ns_js))
self._parse_headers()
layout_h = Template(file=os.path.join(self.target, "templates", "layout_foot.h"),
searchList=[self])
layout_c = Template(file=os.path.join(self.target, "templates", "layout_foot.c"),
searchList=[self])
self.head_file.write(str(layout_h))
self.impl_file.write(str(layout_c))
self.impl_file.close()
self.head_file.close()
self.doc_file.close()
def _pretty_print(self, diagnostics):
print("====\nErrors in parsing headers:")
severities=['Ignored', 'Note', 'Warning', 'Error', 'Fatal']
for idx, d in enumerate(diagnostics):
print "%s. <severity = %s,\n location = %r,\n details = %r>" % (
idx+1, severities[d.severity], d.location, d.spelling)
print("====\n")
def _parse_headers(self):
for header in self.headers:
tu = self.index.parse(header, self.clang_args)
if len(tu.diagnostics) > 0:
self._pretty_print(tu.diagnostics)
is_fatal = False
for d in tu.diagnostics:
if d.severity >= cindex.Diagnostic.Error:
is_fatal = True
if is_fatal:
print("*** Found errors - can not continue")
raise Exception("Fatal error in parsing headers")
self._deep_iterate(tu.cursor)
def _deep_iterate(self, cursor, depth=0):
# get the canonical type
if cursor.kind == cindex.CursorKind.CLASS_DECL:
if cursor == cursor.type.get_declaration() and self.in_listed_classes(cursor.displayname):
if not self.generated_classes.has_key(cursor.displayname):
nclass = NativeClass(cursor, self)
nclass.generate_code()
self.generated_classes[cursor.displayname] = nclass
return
for node in cursor.get_children():
# print("%s %s - %s" % (">" * depth, node.displayname, node.kind))
self._deep_iterate(node, depth + 1)
def main():
from optparse import OptionParser
parser = OptionParser("usage: %prog [options] {configfile}")
parser.add_option("-s", action="store", type="string", dest="section",
help="sets a specific section to be converted")
parser.add_option("-t", action="store", type="string", dest="target",
help="specifies the target vm. Will search for TARGET.yaml")
parser.add_option("-o", action="store", type="string", dest="outdir",
help="specifies the output directory for generated C++ code")
parser.add_option("-n", action="store", type="string", dest="out_file",
help="specifcies the name of the output file, defaults to the prefix in the .ini file")
(opts, args) = parser.parse_args()
# script directory
workingdir = os.path.dirname(inspect.getfile(inspect.currentframe()))
if len(args) == 0:
parser.error('invalid number of arguments')
userconfig = ConfigParser.SafeConfigParser()
userconfig.read('userconf.ini')
print 'Using userconfig \n ', userconfig.items('DEFAULT')
config = ConfigParser.SafeConfigParser()
config.read(args[0])
if (0 == len(config.sections())):
raise Exception("No sections defined in config file")
sections = []
if opts.section:
if (opts.section in config.sections()):
sections = []
sections.append(opts.section)
else:
raise Exception("Section not found in config file")
else:
print("processing all sections")
sections = config.sections()
# find available targets
targetdir = os.path.join(workingdir, "targets")
targets = []
if (os.path.isdir(targetdir)):
targets = [entry for entry in os.listdir(targetdir)
if (os.path.isdir(os.path.join(targetdir, entry)))]
if 0 == len(targets):
raise Exception("No targets defined")
if opts.target:
if (opts.target in targets):
targets = []
targets.append(opts.target)
if opts.outdir:
outdir = opts.outdir
else:
outdir = os.path.join(workingdir, "gen")
if not os.path.exists(outdir):
os.makedirs(outdir)
for t in targets:
# Fix for hidden '.svn', '.cvs' and '.git' etc. folders - these must be ignored or otherwise they will be interpreted as a target.
if t == ".svn" or t == ".cvs" or t == ".git" or t == ".gitignore":
continue
print "\n.... Generating bindings for target", t
for s in sections:
print "\n.... .... Processing section", s, "\n"
gen_opts = {
'prefix': config.get(s, 'prefix'),
'headers': (config.get(s, 'headers' , 0, dict(userconfig.items('DEFAULT')))),
'classes': config.get(s, 'classes').split(' '),
'clang_args': (config.get(s, 'extra_arguments', 0, dict(userconfig.items('DEFAULT'))) or "").split(" "),
'target': os.path.join(workingdir, "targets", t),
'outdir': outdir,
'remove_prefix': config.get(s, 'remove_prefix'),
'target_ns': config.get(s, 'target_namespace'),
'classes_have_no_parents': config.get(s, 'classes_have_no_parents'),
'base_classes_to_skip': config.get(s, 'base_classes_to_skip'),
'abstract_classes': config.get(s, 'abstract_classes'),
'skip': config.get(s, 'skip'),
'rename_functions': config.get(s, 'rename_functions'),
'rename_classes': config.get(s, 'rename_classes'),
'out_file': opts.out_file or config.get(s, 'prefix'),
'script_control_cpp': config.get(s, 'script_control_cpp') if config.has_option(s, 'script_control_cpp') else 'no'
}
generator = Generator(gen_opts)
generator.generate_code()
if __name__ == '__main__':
try:
main()
except Exception as e:
print e
sys.exit(1)
|
mit
| 4,857,824,112,327,277,000
| 41.568579
| 149
| 0.548509
| false
| 4.159267
| true
| false
| false
|
saily/flake8-isort
|
setup.py
|
1
|
1504
|
# -*- coding: utf-8 -*-
from setuptools import setup
short_description = 'flake8 plugin that integrates isort .'
long_description = '{0}\n{1}'.format(
open('README.rst').read(),
open('CHANGES.rst').read()
)
setup(
name='flake8-isort',
version='0.3.dev0',
description=short_description,
long_description=long_description,
# Get more from http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 3 - Alpha',
"License :: OSI Approved :: GNU General Public License v2 (GPLv2)",
"Operating System :: OS Independent",
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development',
],
keywords='pep8 flake8 isort imports',
author='Gil Forcada',
author_email='gil.gnome@gmail.com',
url='https://github.com/gforcada/flake8-isort',
license='GPL version 2',
py_modules=['flake8_isort', ],
include_package_data=True,
test_suite = 'run_tests',
zip_safe=False,
install_requires=[
'flake8',
'isort',
],
extras_require={
'test': [
'testfixtures',
'tox',
],
},
entry_points={
'flake8.extension': ['I00 = flake8_isort:Flake8Isort'],
},
)
|
gpl-2.0
| 5,845,875,406,787,083,000
| 27.923077
| 75
| 0.588431
| false
| 3.650485
| false
| true
| false
|
timrchavez/capomastro
|
capomastro/settings.py
|
1
|
2529
|
"""
Django settings for capomastro project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'south',
'bootstrap3',
'jenkins',
'projects',
'credentials',
'archives',
'capomastro.site'
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
# Added django.core.context_processors.request'
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.core.context_processors.tz',
'django.core.context_processors.request',
'django.contrib.messages.context_processors.messages'
)
ROOT_URLCONF = 'capomastro.urls'
WSGI_APPLICATION = 'capomastro.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = '/static/'
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'capomastro', 'templates'),
)
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'capomastro', 'static'),
)
try:
from local_settings import * # noqa
except ImportError, e:
pass
|
mit
| -5,883,969,919,784,102,000
| 24.039604
| 71
| 0.710953
| false
| 3.332016
| false
| false
| false
|
StephenLujan/Naith
|
game/plugins/dirlight/dirlight.py
|
1
|
2681
|
# -*- coding: utf-8 -*-
# Copyright Tom SF Haines, Aaron Snoswell
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from pandac.PandaModules import NodePath, VBase4, BitMask32
from pandac.PandaModules import DirectionalLight as PDirectionalLight
class DirLight:
"""Creates a simple directional light"""
def __init__(self,manager,xml):
self.light = PDirectionalLight('dlight')
self.lightNode = NodePath(self.light)
self.lightNode.setCompass()
if hasattr(self.lightNode.node(), "setCameraMask"):
self.lightNode.node().setCameraMask(BitMask32.bit(3))
self.reload(manager,xml)
def reload(self,manager,xml):
color = xml.find('color')
if color!=None:
self.light.setColor(VBase4(float(color.get('r')), float(color.get('g')), float(color.get('b')), 1.0))
pos = xml.find('pos')
if pos!=None:
self.lightNode.setPos(float(pos.get('x')), float(pos.get('y')), float(pos.get('z')))
else:
self.lightNode.setPos(0, 0, 0)
lookAt = xml.find('lookAt')
if lookAt!=None:
self.lightNode.lookAt(float(lookAt.get('x')), float(lookAt.get('y')), float(lookAt.get('z')))
lens = xml.find('lens')
if lens!=None and hasattr(self.lightNode.node(), 'getLens'):
if bool(int(lens.get('auto'))):
self.lightNode.reparentTo(base.camera)
else:
self.lightNode.reparentTo(render)
lobj = self.lightNode.node().getLens()
lobj.setNearFar(float(lens.get('near', 1.0)), float(lens.get('far', 100000.0)))
lobj.setFilmSize(float(lens.get('width', 1.0)), float(lens.get('height', 1.0)))
lobj.setFilmOffset(float(lens.get('x', 0.0)), float(lens.get('y', 0.0)))
if hasattr(self.lightNode.node(), 'setShadowCaster'):
shadows = xml.find('shadows')
if shadows!=None:
self.lightNode.node().setShadowCaster(True, int(shadows.get('width', 512)), int(shadows.get('height', 512)), int(shadows.get('sort', -10)))
#self.lightNode.node().setPushBias(float(shadows.get('bias', 0.5)))
else:
self.lightNode.node().setShadowCaster(False)
def start(self):
render.setLight(self.lightNode)
def stop(self):
render.clearLight(self.lightNode)
|
apache-2.0
| 6,424,593,677,426,341,000
| 37.3
| 147
| 0.675121
| false
| 3.203106
| false
| false
| false
|
davesque/django-rest-framework-simplejwt
|
rest_framework_simplejwt/compat.py
|
1
|
1286
|
import warnings
try:
from django.urls import reverse, reverse_lazy
except ImportError:
from django.core.urlresolvers import reverse, reverse_lazy # NOQA
class RemovedInDjango20Warning(DeprecationWarning):
pass
class CallableBool: # pragma: no cover
"""
An boolean-like object that is also callable for backwards compatibility.
"""
do_not_call_in_templates = True
def __init__(self, value):
self.value = value
def __bool__(self):
return self.value
def __call__(self):
warnings.warn(
"Using user.is_authenticated() and user.is_anonymous() as a method "
"is deprecated. Remove the parentheses to use it as an attribute.",
RemovedInDjango20Warning, stacklevel=2
)
return self.value
def __nonzero__(self): # Python 2 compatibility
return self.value
def __repr__(self):
return 'CallableBool(%r)' % self.value
def __eq__(self, other):
return self.value == other
def __ne__(self, other):
return self.value != other
def __or__(self, other):
return bool(self.value or other)
def __hash__(self):
return hash(self.value)
CallableFalse = CallableBool(False)
CallableTrue = CallableBool(True)
|
mit
| -1,465,149,060,535,745,800
| 23.264151
| 80
| 0.629082
| false
| 4.272425
| false
| false
| false
|
aroth-arsoft/arsoft-web-crashupload
|
app/crashdump/xmlreport.py
|
1
|
58814
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# kate: space-indent on; indent-width 4; mixedindent off; indent-mode python;
import sys
import base64
import struct
from datetime import datetime, tzinfo, timedelta
from uuid import UUID
from lxml import etree
from crashdump.exception_info import exception_code_names_per_platform_type, exception_info_per_platform_type
from crashdump.utils import format_version_number, format_memory_usagetype
ZERO = timedelta(0)
# A UTC class.
class UTC(tzinfo):
"""UTC"""
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return ZERO
class HexDumpMemoryBlock(object):
def __init__(self, memory):
self._memory = memory
self._hexdump = None
@property
def raw(self):
return self._memory
@property
def size(self):
return len(self._memory)
def __len__(self):
return len(self._memory)
@property
def hexdump(self):
if not self._hexdump:
self._hexdump = self._generate_hexdump()
return self._hexdump
class HexDumpLine(object):
def __init__(self, offset, memory_line, line_length):
self.offset = offset
self.raw = memory_line
self.hex = ''
self.ascii = ''
idx = 0
while idx < 16:
if idx != 0:
self.hex += ' '
if idx < line_length:
c = memory_line[idx]
c_i = int(c)
self.hex += '%02X' % c_i
if c_i < 32 or c_i >= 127:
self.ascii += '.'
else:
self.ascii += chr(c)
else:
self.hex += ' '
self.ascii += ' '
idx += 1
def __str__(self):
return '%06x %32s %16s\n' % (self.offset, self.hex, self.ascii)
class HexDump(object):
def __init__(self, size):
if size > 65536:
self.offset_width = 6
elif size > 256:
self.offset_width = 4
else:
self.offset_width = 2
self._lines = []
self._raw_offset = None
self._raw_hex = None
self._raw_ascii = None
def __iter__(self):
return iter(self._lines)
def _generate_raw(self):
self._raw_offset = ''
self._raw_hex = ''
self._raw_ascii = ''
offset_fmt = '0x%%0%dX' % self.offset_width
first = True
for line in self._lines:
if not first:
self._raw_offset += '\r\n'
self._raw_hex += '\r\n'
self._raw_ascii += '\r\n'
self._raw_offset += offset_fmt % line.offset
self._raw_hex += line.hex
self._raw_ascii += line.ascii
first = False
@property
def raw_offset(self):
if self._raw_offset is None:
self._generate_raw()
return self._raw_offset
@property
def raw_hex(self):
if self._raw_hex is None:
self._generate_raw()
return self._raw_hex
@property
def raw_ascii(self):
if self._raw_ascii is None:
self._generate_raw()
return self._raw_ascii
def __str__(self):
ret = ''
for l in self._lines:
ret += str(l)
return ret
def _generate_hexdump(self):
offset = 0
total_size = len(self._memory)
ret = HexDumpMemoryBlock.HexDump(total_size)
while offset < total_size:
max_row = 16
remain = total_size - offset
if remain < 16:
max_row = remain
line = HexDumpMemoryBlock.HexDumpLine(offset, self._memory[offset:offset + max_row], max_row)
ret._lines.append(line)
offset += 16
return ret
def __getitem__(self, index):
if isinstance(index, int):
return self._memory[index]
elif isinstance(index, slice):
return self._memory[index.start:index.stop: index.step]
else:
raise TypeError("index %s" % index)
def __str__(self):
return str(self.hexdump)
def find(self, needle, start=0):
if isinstance(needle, bytes):
return self._memory.find(needle, start)
elif isinstance(needle, str):
return self._memory.find(needle.encode('us-ascii'), start)
else:
raise TypeError('insupported type for search in memory block: %s' % type(needle))
class MemObject(object):
def __init__(self, owner, memory, is_64_bit):
self._owner = owner
self._memory = memory
self._is_64_bit = is_64_bit
def _read_int32(self, offset):
if offset >= len(self._memory):
raise IndexError(offset)
return struct.unpack('I', self._memory[offset:offset+4])[0]
def _read_ptr(self, offset):
if offset >= len(self._memory):
raise IndexError(offset)
if self._is_64_bit:
return struct.unpack('Q', self._memory[offset:offset+8])[0]
else:
return struct.unpack('I', self._memory[offset:offset+4])[0]
# https://en.wikipedia.org/wiki/Win32_Thread_Information_Block
class Win32_TIB(MemObject):
def __init__(self, owner, memory, is_64_bit):
MemObject.__init__(self, owner, memory, is_64_bit)
self._tls_slots = None
self._tls_array_memory = None
self._hexdump = None
class Win32_TLS_Slots(object):
def __init__(self, teb):
self._teb = teb
def __getitem__(self, index):
if index < 0 or index >= 64:
raise IndexError(index)
offset = (0x1480 + (index * 8)) if self._teb._is_64_bit else (0xE10 + (index * 4))
#print('teb tls slot at %x' % offset)
return self._teb._read_ptr(offset)
class Win32_TLS_Array(MemObject):
def __init__(self, owner, memory, is_64_bit):
MemObject.__init__(self, owner, memory, is_64_bit)
def __getitem__(self, index):
offset = (8 * index) if self._is_64_bit else (4 * index)
return self._read_ptr(offset)
@property
def threadid(self):
if self._is_64_bit:
return self._read_int32(0x48)
else:
return self._read_int32(0x24)
@property
def peb_address(self):
if self._is_64_bit:
return self._read_ptr(0x60)
else:
return self._read_ptr(0x30)
@property
def thread_local_storage_array_address(self):
if self._is_64_bit:
return self._read_int32(0x58)
else:
return self._read_int32(0x2C)
@property
def thread_local_storage_array(self):
if self._tls_array_memory is None:
mem = self._owner._get_memory_block(self.thread_local_storage_array_address)
if mem is not None:
self._tls_array_memory = Win32_TIB.Win32_TLS_Array(self._owner, mem, self._is_64_bit)
return self._tls_array_memory
@property
def tls_slots(self):
if self._tls_slots is None:
self._tls_slots = Win32_TIB.Win32_TLS_Slots(self)
return self._tls_slots
@property
def hexdump(self):
if self._hexdump is None:
self._hexdump = HexDumpMemoryBlock(self._memory)
return self._hexdump
# https://en.wikipedia.org/wiki/Process_Environment_Block
# https://ntopcode.wordpress.com/2018/02/26/anatomy-of-the-process-environment-block-peb-windows-internals/
class Win32_PEB(MemObject):
def __init__(self, owner, memory, is_64_bit):
MemObject.__init__(self, owner, memory, is_64_bit)
@property
def image_base_address(self):
return self._read_ptr(0x10)
class XMLReport(object):
_main_fields = ['crash_info', 'platform_type', 'system_info', 'file_info', 'exception',
'assertion', 'modules', 'threads', 'memory_regions',
'memory_blocks', 'handles', 'stackdumps', 'simplified_info', 'processstatuslinux', 'processstatuswin32',
'processmemoryinfowin32', 'misc_info',
'fast_protect_version_info', 'fast_protect_system_info']
_crash_dump_fields = ['uuid', 'crash_timestamp',
'report_time', 'report_fqdn', 'report_username', 'report_hostname', 'report_domain',
'application', 'command_line',
'symbol_directories', 'image_directories', 'usefulness_id', 'environment']
_system_info_fields = ['platform_type', 'platform_type_id', 'cpu_type', 'cpu_type_id', 'cpu_name', 'cpu_level', 'cpu_revision', 'cpu_vendor',
'number_of_cpus', 'os_version', 'os_version_number', 'os_build_number', 'os_version_info',
'distribution_id', 'distribution_release', 'distribution_codename', 'distribution_description' ]
_file_info_fields = ['log']
_file_info_log_message_fields = ['time', 'text']
_exception_fields = ['threadid', 'code', 'address', 'flags', 'numparams', 'param0', 'param1', 'param2', 'param3']
_assertion_fields = ['expression', 'function', 'source', 'line', 'typeid']
_module_fields = ['base', 'size', 'timestamp', 'product_version', 'product_version_number',
'file_version', 'file_version_number', 'name', 'symbol_file', 'symbol_id', 'symbol_type', 'symbol_type_number',
'image_name', 'module_name', 'module_id',
'flags' ]
_thread_fields = ['id', 'exception', ('name', '_name'), 'memory', 'start_addr', 'main_thread',
'create_time', 'exit_time', 'kernel_time', 'user_time',
'exit_status', 'cpu_affinity', 'stack_addr',
'suspend_count', 'priority_class', 'priority', 'teb', 'tls', 'tib',
'dump_flags', 'dump_error', 'rpc_thread'
]
_memory_region_fields = ['base_addr', 'size', 'alloc_base', 'alloc_prot', 'type', 'protect', 'state' ]
_memory_region_usage_fields = ['threadid', 'usagetype' ]
_memory_block_fields = ['num', 'base', 'size', 'memory']
_handle_fields = ['handle', 'type', 'name', 'count', 'pointers' ]
_stackdump_fields = ['threadid', 'simplified', 'exception']
_stack_frame_fields = ['num', 'addr', 'retaddr', 'param0', 'param1', 'param2', 'param3', 'infosrc', 'trust_level', 'module', 'module_base', 'function', 'funcoff', 'source', 'line', 'lineoff' ]
_simplified_info_fields = ['threadid', 'missing_debug_symbols', 'missing_image_files', 'first_useful_modules', 'first_useful_functions']
_processstatuslinux_fields = ['name', 'state', 'thread_group', 'pid',
'parent_pid', 'tracer_pid', 'real_uid', 'real_gid',
'effective_uid', 'effective_gid', 'saved_set_uid', 'saved_set_gid',
'filesystem_uid', 'filesystem_gid', 'num_file_descriptors', 'supplement_groups',
'vmpeak', 'vmsize', 'vmlocked', 'vmpinned', 'vmhighwatermark',
'vmresidentsetsize', 'vmdata', 'vmstack', 'vmexe', 'vmlib', 'vmpte',
'vmswap', 'num_threads', 'voluntary_context_switches', 'nonvoluntary_context_switches',
]
_processstatuswin32_fields = ['dll_path', 'image_path',
'window_title', 'desktop_name', 'shell_info',
'runtime_data', 'drive_letter_cwd',
'stdin_handle', 'stdout_handle', 'stderr_handle',
'debug_flags', 'console_handle', 'console_flags',
'session_id',
]
_processmemoryinfowin32_fields = [
'page_fault_count', 'peak_working_set_size',
'working_set_size', 'quota_peak_paged_pool_usage',
'quota_paged_pool_usage', 'quota_peak_non_paged_pool_usage',
'quota_non_paged_pool_usage', 'pagefile_usage',
'peak_pagefile_usage', 'private_usage'
]
_misc_info_fields = ['processid', 'process_create_time',
'user_time', 'kernel_time',
'processor_max_mhz', 'processor_current_mhz', 'processor_mhz_limit',
'processor_max_idle_state', 'processor_current_idle_state',
'process_integrity_level',
'process_execute_flags', 'protected_process',
'timezone_id', 'timezone_bias',
'timezone_standard_name', 'timezone_standard_bias', 'timezone_standard_date',
'timezone_daylight_name', 'timezone_daylight_bias', 'timezone_daylight_date',
'build_info', 'debug_build_info'
]
_fast_protect_version_info_fields = [
'product_name',
'product_code_name',
'product_version',
'product_target_version',
'product_build_type',
'product_build_postfix',
'root_revision',
'buildtools_revision',
'external_revision',
'third_party_revision',
'terra3d_revision',
'manual_revision',
'jenkins_job_name',
'jenkins_build_number',
'jenkins_build_id',
'jenkins_build_tag',
'jenkins_build_url',
'jenkins_git_revision',
'jenkins_git_branch',
'jenkins_master',
'jenkins_nodename',
'thread_name_tls_slot',
]
_fast_protect_system_info_fields = [
'hostname',
'domain',
'fqdn',
'username',
'timestamp',
'system_temp_path',
'user_temp_path',
'user_persistent_path',
'terminal_session_id',
'virtual_machine',
'remote_session',
'opengl_vendor',
'opengl_renderer',
'opengl_version',
'opengl_vendor_id',
'opengl_driver_id',
'opengl_chip_class',
'opengl_driver_version',
'opengl_hardware_ok',
'opengl_use_pbuffer',
'opengl_hardware_error',
'opengl_pbuffer_error',
'cpu_name',
'cpu_vendor',
'num_logical_cpus',
'num_physical_cpus',
'hyperthread',
'rawdata'
]
class XMLReportException(Exception):
def __init__(self, report, message):
super(XMLReport.XMLReportException, self).__init__(message)
self.report = report
def __str__(self):
return '%s(%s): %s' % (type(self).__name__, self.report._filename, self.message)
class XMLReportIOError(XMLReportException):
def __init__(self, report, message):
super(XMLReport.XMLReportIOError, self).__init__(report, message)
class XMLReportParserError(XMLReportException):
def __init__(self, report, message):
super(XMLReport.XMLReportParserError, self).__init__(report, message)
class ProxyObject(object):
def __init__(self, report, field_name):
object.__setattr__(self, '_report', report)
object.__setattr__(self, '_field_name', field_name)
object.__setattr__(self, '_real_object', None)
def __getattr__(self, key):
if self._real_object is None:
object.__setattr__(self, '_real_object', getattr(self._report, self._field_name))
if self._real_object is None:
return None
return getattr(self._real_object, key)
def __setattr__(self, key, value):
if self._real_object is None:
object.__setattr__(self, '_real_object', getattr(self._report, self._field_name))
if self._real_object is None:
return None
return setattr(self._real_object, key, value)
def __iter__(self):
if self._real_object is None:
object.__setattr__(self, '_real_object', getattr(self._report, self._field_name))
if self._real_object is None:
return None
return iter(self._real_object)
def __nonzero__(self):
if self._real_object is None:
object.__setattr__(self, '_real_object', getattr(self._report, self._field_name))
if self._real_object is None:
return False
return bool(self._real_object)
def __bool__(self):
if self._real_object is None:
object.__setattr__(self, '_real_object', getattr(self._report, self._field_name))
if self._real_object is None:
return False
return bool(self._real_object)
def __len__(self):
if self._real_object is None:
object.__setattr__(self, '_real_object', getattr(self._report, self._field_name))
if self._real_object is None:
return None
if hasattr(self._real_object, '__len__'):
return len(self._real_object)
else:
return 0
def __contains__(self, key):
if self._real_object is None:
object.__setattr__(self, '_real_object', getattr(self._report, self._field_name))
if self._real_object is None:
return False
return key in self._real_object
def __getitem__(self, key):
if self._real_object is None:
object.__setattr__(self, '_real_object', getattr(self._report, self._field_name))
return self._real_object[key]
def __repr__(self):
if self._real_object is None:
object.__setattr__(self, '_real_object', getattr(self._report, self._field_name))
return 'ProxyObject(%s, %s, %r)' % (
getattr(self, '_report'),
getattr(self, '_field_name'),
getattr(self, '_real_object')
)
@staticmethod
def unique(items):
found = set()
keep = []
for item in items:
if item not in found:
found.add(item)
keep.append(item)
return keep
def __init__(self, filename=None):
self._filename = filename
self._xml = None
self._crash_info = None
self._system_info = None
self._file_info = None
self._exception = None
self._assertion = None
self._threads = None
self._modules = None
self._memory_regions = None
self._memory_blocks = None
self._handles = None
self._stackdumps = None
self._simplified_info = None
self._processstatuslinux = None
self._processstatuswin32 = None
self._processmemoryinfowin32 = None
self._misc_info = None
self._fast_protect_version_info = None
self._fast_protect_system_info = None
self._is_64_bit = None
self._peb = None
self._peb_address = None
self._peb_memory_block = None
if self._filename:
try:
self._xml = etree.parse(self._filename)
except IOError as e:
raise XMLReport.XMLReportIOError(self, str(e))
except etree.XMLSyntaxError as e:
raise XMLReport.XMLReportParserError(self, str(e))
@property
def is_platform_windows(self):
return self.platform_type == 'Win32' or self.platform_type == 'Windows NT'
class XMLReportEntity(object):
def __init__(self, owner):
self._owner = owner
def __str__(self):
ret = ''
for (k,v) in self.__dict__.items():
if k[0] != '_':
if ret:
ret += ', '
ret = ret + '%s=%s' % (k,v)
return ret
class CrashInfo(XMLReportEntity):
def __init__(self, owner):
super(XMLReport.CrashInfo, self).__init__(owner)
@property
def path(self):
ret = []
env = getattr(self, 'environment', None)
if env:
for (k,v) in env.iteritems():
if k.lower() == 'path':
if self._owner.is_platform_windows:
ret = v.split(';')
else:
ret = v.split(':')
break
return ret
class SystemInfo(XMLReportEntity):
def __init__(self, owner):
super(XMLReport.SystemInfo, self).__init__(owner)
class FileInfoLogMessage(XMLReportEntity):
def __init__(self, owner):
super(XMLReport.FileInfoLogMessage, self).__init__(owner)
class FileInfo(XMLReportEntity):
def __init__(self, owner):
super(XMLReport.FileInfo, self).__init__(owner)
self.log = []
class Exception(XMLReportEntity):
def __init__(self, owner):
super(XMLReport.Exception, self).__init__(owner)
@property
def thread(self):
ret = None
for thread in self._owner.threads:
if thread.id == self.threadid:
ret = thread
break
return ret
@property
def involved_modules(self):
t = self.thread
if t:
return t.stackdump.involved_modules
else:
return None
@property
def params(self):
ret = []
if self.numparams >= 1:
ret.append(self.param0)
if self.numparams >= 2:
ret.append(self.param1)
if self.numparams >= 3:
ret.append(self.param2)
if self.numparams >= 4:
ret.append(self.param3)
return ret
@property
def name(self):
if self._owner.platform_type in exception_code_names_per_platform_type:
code_to_name_map = exception_code_names_per_platform_type[self._owner.platform_type]
if self.code in code_to_name_map:
return code_to_name_map[self.code]
else:
return 'Unknown(%x)' % (self._owner.platform_type, self.code)
else:
return 'UnknownPlatform(%s, %x)' % (self.code, self.code)
@property
def info(self):
if self._owner.platform_type in exception_info_per_platform_type:
ex_info_func = exception_info_per_platform_type[self._owner.platform_type]
return ex_info_func(self)
else:
return 'UnknownPlatform(%s, %x)' % (self.code, self.code)
class Assertion(XMLReportEntity):
def __init__(self, owner):
super(XMLReport.Assertion, self).__init__(owner)
class Module(XMLReportEntity):
def __init__(self, owner):
super(XMLReport.Module, self).__init__(owner)
self._basename = None
@property
def basename(self):
if self._basename is None:
name = self.name
if name is None:
return None
idx = name.rfind('/')
if idx < 0:
idx = name.rfind('\\')
if idx >= 0:
self._basename = name[idx+1:]
else:
self._basename = name
return self._basename
class Thread(XMLReportEntity):
def __init__(self, owner):
super(XMLReport.Thread, self).__init__(owner)
self._teb_memory_block = None
self._teb_memory_region = None
self._teb = None
self._tls_slots = None
self._thread_name = None
@property
def stackdump(self):
ret = None
for st in self._owner.stackdumps:
if st.threadid == self.id and not st.simplified:
ret = st
break
return ret
@property
def simplified_stackdump(self):
ret = None
for st in self._owner.stackdumps:
if st.threadid == self.id and st.simplified:
ret = st
break
return ret
@property
def teb_memory_block(self):
if self._teb_memory_block is None:
self._teb_memory_block = self._owner._get_memory_block(self.teb)
return self._teb_memory_block
@property
def teb_memory_region(self):
if self._teb_memory_region is None:
self._teb_memory_region = self._owner._get_memory_region(self.teb)
return self._teb_memory_region
@property
def teb_data(self):
if self._teb is None:
m = self.teb_memory_block
if m is None:
return None
data = m.get_addr(self.teb, None)
if data:
self._teb = Win32_TIB(self._owner, data, self._owner.is_64_bit)
return self._teb
@property
def peb_address(self):
t = self.teb_data
print('t=%s' % t)
if t is not None:
return t.peb_address
else:
return None
@property
def tls_slots(self):
return self.teb_data.tls_slots
@property
def name(self):
if self._name is not None:
return self._name
elif self._thread_name is None:
tls_slot_index = self._owner.thread_name_tls_slot
if tls_slot_index is not None:
teb = self.teb_data
if teb is not None:
addr = teb.tls_slots[tls_slot_index]
self._thread_name = self._owner._read_memory(addr, max_len=16)
return self._thread_name
@property
def location(self):
s = self.stackdump
if s is not None:
return s.top
else:
return None
class MemoryRegion(XMLReportEntity):
def __init__(self, owner):
super(XMLReport.MemoryRegion, self).__init__(owner)
@property
def base(self):
return self.base_addr
@property
def end_addr(self):
return self.base_addr + self.size
def __str__(self):
if self.base_addr != self.alloc_base:
return 'base=0x%x, alloc=0x%x, size=%i, end=0x%x, type=%i, protect=%x, state=%x, usage=%s' % (self.base_addr, self.alloc_base, self.size, self.end_addr, self.type, self.protect, self.state, self.usage)
else:
return 'base=0x%x, size=%i, end=0x%x, type=%i, protect=%x, state=%x, usage=%s' % (self.base_addr, self.size, self.end_addr, self.type, self.protect, self.state, self.usage)
class MemoryRegionUsage(XMLReportEntity):
def __init__(self, owner, region):
super(XMLReport.MemoryRegionUsage, self).__init__(owner)
self._region = region
@property
def thread(self):
ret = None
for thread in self._owner.threads:
if thread.id == self.threadid:
ret = thread
break
return ret
def __str__(self):
return '(0x%x, %s)' % (self.threadid, format_memory_usagetype(self.usagetype))
def __repr__(self):
return str(self)
class MemoryBlock(XMLReportEntity):
def __init__(self, owner):
super(XMLReport.MemoryBlock, self).__init__(owner)
self._thread_id = None
@property
def hexdump(self):
return self.memory.hexdump
@property
def threadid(self):
if self._thread_id is None:
for thread in self._owner.threads:
if thread.memory == self.base:
self._thread_id = thread.id
break
return self._thread_id
@property
def end_addr(self):
return self.base + self.size
def get_addr(self, addr, size=None):
if addr < self.base or addr > self.end_addr:
return None
offset = addr - self.base
if size is None:
actual_size = self.size - offset
else:
actual_size = min(self.size - offset, size)
return self.memory[offset:offset+actual_size]
def find(self, needle, start=0):
return self.memory.find(needle, start)
def __len__(self):
return len(self.memory)
def __getitem__(self, index):
return self.memory[index]
def __str__(self):
return 'num=%i, base=0x%x, size=%i, end=0x%x' % (self.num, self.base, self.size, self.end_addr)
class Handle(XMLReportEntity):
def __init__(self, owner):
super(XMLReport.Handle, self).__init__(owner)
class StackDumpList(XMLReportEntity):
def __init__(self, owner):
super(XMLReport.StackDumpList, self).__init__(owner)
self._list = []
def append(self, dump):
self._list.append(dump)
def __iter__(self):
return iter(self._list)
def __len__(self):
return len(self._list)
def __contains__(self, key):
if isinstance(key, int):
for d in self._list:
if d.threadid == key and d.simplified == False:
return True
elif isinstance(key, str):
if key == 'simplified':
for d in self._list:
if d.simplified:
return True
elif key == 'exception':
for d in self._list:
if d.exception:
return True
return False
def __getitem__(self, key):
if isinstance(key, int):
for d in self._list:
if d.threadid == key and d.simplified == False:
return d
elif isinstance(key, str):
if key == 'simplified':
for d in self._list:
if d.simplified:
return d
elif key == 'exception':
for d in self._list:
if d.exception:
return d
raise KeyError(key)
class StackDump(XMLReportEntity):
def __init__(self, owner):
super(XMLReport.StackDump, self).__init__(owner)
self._thread = None
@property
def thread(self):
if self._thread is None:
for thread in self._owner.threads:
if thread.id == self.threadid:
self._thread = thread
break
return self._thread
@property
def involved_modules(self):
module_order = []
for frm in self.callstack:
if frm.module:
module_order.append(frm.module)
return XMLReport.unique(module_order)
@property
def top(self):
if self.callstack:
return self.callstack[0]
else:
return None
class StackFrame(XMLReportEntity):
def __init__(self, owner, dump):
super(XMLReport.StackFrame, self).__init__(owner)
self._dump = dump
@property
def source_url(self):
if self.source:
return 'file:///' + self.source
else:
return None
@property
def params(self):
# for the moment there are always four parameters
ret = [ self.param0, self.param1, self.param2, self.param3]
return ret
class SimplifiedInfo(XMLReportEntity):
def __init__(self, owner):
super(XMLReport.SimplifiedInfo, self).__init__(owner)
class MiscInfo(XMLReportEntity):
def __init__(self, owner):
super(XMLReport.MiscInfo, self).__init__(owner)
class FastProtectVersionInfo(XMLReportEntity):
def __init__(self, owner):
super(XMLReport.FastProtectVersionInfo, self).__init__(owner)
class FastProtectSystemInfo(XMLReportEntity):
def __init__(self, owner):
super(XMLReport.FastProtectSystemInfo, self).__init__(owner)
self._sytem_info_report = None
self._sytem_info_report_loaded = False
@property
def sytem_info_report(self):
if not self._sytem_info_report_loaded:
from crashdump.systeminforeport import SystemInfoReport
self._sytem_info_report = SystemInfoReport(xmlreport=self._owner)
self._sytem_info_report_loaded = True
return self._sytem_info_report
@property
def machine_type(self):
rep = self.sytem_info_report
return rep['System/MachineType']
@property
def text(self):
rep = self.sytem_info_report
return rep.text
class ProcessStatusLinux(XMLReportEntity):
def __init__(self, owner):
super(XMLReport.ProcessStatusLinux, self).__init__(owner)
class ProcessStatusWin32(XMLReportEntity):
def __init__(self, owner):
super(XMLReport.ProcessStatusWin32, self).__init__(owner)
class ProcessMemoryInfoWin32(XMLReportEntity):
def __init__(self, owner):
super(XMLReport.ProcessMemoryInfoWin32, self).__init__(owner)
@staticmethod
def _value_convert(value_str, data_type):
if data_type == 'uuid':
try:
return UUID(value_str)
except ValueError:
return None
elif data_type == 'QString':
return value_str
elif data_type == 'QDateTime':
try:
dt = datetime.strptime(value_str, '%Y-%m-%d %H:%M:%S')
return dt.replace(tzinfo=UTC())
except ValueError:
return None
elif data_type == 'bool':
if value_str == 'true':
return True
elif value_str == 'false':
return False
else:
return None
elif data_type == 'int' or data_type == 'qlonglong':
try:
return int(value_str, 10)
except ValueError:
return None
elif data_type == 'uint' or data_type == 'qulonglong':
try:
return int(value_str, 16)
except ValueError:
return None
else:
return str(value_str)
@staticmethod
def _get_node_value(node, child, default_value=None):
if node is None:
return default_value
r = node.xpath(child + '/@type')
data_type = r[0] if r else None
if data_type == 'QStringList':
all_subitems = node.xpath(child + '/item/text()')
ret = []
for c in all_subitems:
ret.append(str(c))
elif data_type == 'QVariantMap':
all_subitems = node.xpath(child + '/item')
ret = {}
for item in all_subitems:
r = item.xpath('@key')
item_key = str(r[0]) if r else None
r = item.xpath('@type')
item_data_type = str(r[0]) if r else None
r = item.xpath('text()')
item_value = r[0] if r else None
ret[item_key] = XMLReport._value_convert(item_value, item_data_type)
elif data_type == 'QByteArray':
r = node.xpath(child + '/@encoding-type')
encoding_type = r[0] if r else None
r = node.xpath(child + '/text()')
value = r[0] if r else None
if r:
if encoding_type == 'base64':
ret = HexDumpMemoryBlock(base64.b64decode(r[0]))
else:
ret = HexDumpMemoryBlock(str(r[0]))
else:
ret = default_value
else:
r = node.xpath(child + '/text()')
if r:
ret = XMLReport._value_convert(r[0], data_type)
else:
ret = default_value
return ret
@staticmethod
def _get_attribute(node, attr_name, default_value=None):
if node is None:
return default_value
r = node.xpath('@' + attr_name)
attr_value = r[0] if r else None
ok = False
ret = None
if attr_value:
attr_value_low = attr_value.lower()
if attr_value_low == 'true' or attr_value_low == 'on':
ret = True
ok = True
elif attr_value_low == 'false' or attr_value_low == 'off':
ret = False
ok = True
if not ok:
if attr_value.startswith('0x'):
try:
ret = int(attr_value[2:], 16)
ok = True
except ValueError:
pass
if not ok:
try:
ret = int(attr_value)
ok = True
except ValueError:
pass
if not ok:
ret = str(attr_value)
return ret
@staticmethod
def _get_first_node(node, child):
if node is None:
return None
r = node.xpath('/' + str(child))
return r[0] if r else None
@property
def filename(self):
return self._filename
def _get_memory_block(self, addr):
for m in self.memory_blocks:
if addr >= m.base and addr < m.end_addr:
#print('got %x >= %x < %x' % (m.base, addr, m.end_addr))
return m
return None
def _get_memory_region(self, addr):
for m in self.memory_regions:
if addr >= m.base and addr < m.end_addr:
#print('got %x >= %x < %x' % (m.base, addr, m.end_addr))
return m
return None
def _read_memory(self, addr, max_len=None):
m = self._get_memory_block(addr)
if m is not None:
return m.get_addr(addr, max_len)
else:
return None
def find_in_memory_blocks(self, needle, start=0):
ret = []
for m in self.memory_blocks:
index = m.find(needle, start=start)
if index >= 0:
#print('got %x >= %x < %x' % (m.base, addr, m.end_addr))
ret.append( (m, index) )
return ret
@property
def crash_info(self):
if self._crash_info is None:
i = XMLReport._get_first_node(self._xml, 'crash_dump')
self._crash_info = XMLReport.CrashInfo(self) if i is not None else None
if i is not None:
for f in XMLReport._crash_dump_fields:
setattr(self._crash_info, f, XMLReport._get_node_value(i, f))
return self._crash_info
@property
def platform_type(self):
s = self.system_info
if s is None:
return None
return s.platform_type
@property
def is_64_bit(self):
if self._is_64_bit is None:
s = self.system_info
if s is None:
return None
# CPUTypeUnknown=-1
# CPUTypeX86=0
# CPUTypeMIPS=1
# CPUTypeAlpha=2
# CPUTypePowerPC=3
# CPUTypeSHX=4
# CPUTypeARM=5
# CPUTypeIA64=6
# CPUTypeAlpha64=7
# CPUTypeMSIL=8
# CPUTypeAMD64=9
# CPUTypeX64_Win64=10
# CPUTypeSparc=11
# CPUTypePowerPC64=12
# CPUTypeARM64=13
if s.cpu_type_id == 0 or \
s.cpu_type_id == 1 or \
s.cpu_type_id == 2 or \
s.cpu_type_id == 3 or \
s.cpu_type_id == 4 or \
s.cpu_type_id == 5 or \
s.cpu_type_id == -1:
self._is_64_bit = False
elif s.cpu_type_id == 6 or \
s.cpu_type_id == 7 or \
s.cpu_type_id == 8 or \
s.cpu_type_id == 9 or \
s.cpu_type_id == 10 or \
s.cpu_type_id == 11 or \
s.cpu_type_id == 12 or \
s.cpu_type_id == 13:
self._is_64_bit = True
else:
self._is_64_bit = False
return self._is_64_bit
@property
def system_info(self):
if self._system_info is None:
i = XMLReport._get_first_node(self._xml, 'crash_dump/system_info')
self._system_info = XMLReport.SystemInfo(self) if i is not None else None
if i is not None:
for f in XMLReport._system_info_fields:
setattr(self._system_info, f, XMLReport._get_node_value(i, f))
if self._system_info.os_version_number is not None and ((self._system_info.os_version_number >> 48) & 0xffff) == 0:
# convert old OS version number with two 32-bit integers
# to the new format using four 16-bit integers
major = (self._system_info.os_version_number >> 32) & 0xffffffff
minor = self._system_info.os_version_number & 0xffffffff
patch = 0
build = (self._system_info.os_build_number & 0xffff)
self._system_info.os_version_number = major << 48 | minor << 32 | patch << 16 | build
return self._system_info
@property
def file_info(self):
if self._file_info is None:
i = XMLReport._get_first_node(self._xml, 'crash_dump/file_info')
self._file_info = XMLReport.FileInfo(self) if i is not None else None
if i is not None:
for f in XMLReport._file_info_fields:
if f != 'log':
setattr(self._file_info, f, XMLReport._get_node_value(i, f))
i = XMLReport._get_first_node(self._xml, 'crash_dump/file_info/log')
all_subitems = i.xpath('message') if i is not None else None
if all_subitems is not None:
for item in all_subitems:
m = XMLReport.FileInfoLogMessage(self)
for f in XMLReport._file_info_log_message_fields:
setattr(m, f, XMLReport._get_node_value(item, f))
self._file_info.log.append(m)
return self._file_info
@property
def exception(self):
if self._exception is None:
i = XMLReport._get_first_node(self._xml, 'crash_dump/exception')
self._exception = XMLReport.Exception(self) if i is not None else None
if i is not None:
for f in XMLReport._exception_fields:
setattr(self._exception, f, XMLReport._get_node_value(i, f))
return self._exception
@property
def assertion(self):
if self._assertion is None:
i = XMLReport._get_first_node(self._xml, 'crash_dump/assertion')
self._assertion = XMLReport.Assertion(self) if i is not None else None
if i is not None:
for f in XMLReport._assertion_fields:
setattr(self._assertion, f, XMLReport._get_node_value(i, f))
return self._assertion
@property
def modules(self):
if self._modules is None:
i = XMLReport._get_first_node(self._xml, 'crash_dump/modules')
self._modules = []
all_subitems = i.xpath('module') if i is not None else None
if all_subitems is not None:
for item in all_subitems:
m = XMLReport.Module(self)
for f in XMLReport._module_fields:
setattr(m, f, XMLReport._get_node_value(item, f))
if m.file_version is None:
m.file_version = format_version_number(m.file_version_number)
if m.product_version is None:
m.product_version = format_version_number(m.product_version_number)
self._modules.append(m)
return self._modules
@property
def threads(self):
if self._threads is None:
i = XMLReport._get_first_node(self._xml, 'crash_dump/threads')
self._threads = []
all_subitems = i.xpath('thread') if i is not None else None
if all_subitems is not None:
for item in all_subitems:
m = XMLReport.Thread(self)
for f in XMLReport._thread_fields:
if isinstance(f, tuple):
f_xml, f_prop = f
setattr(m, f_prop, XMLReport._get_node_value(item, f_xml))
else:
setattr(m, f, XMLReport._get_node_value(item, f))
if not self._threads:
m.main_thread = True
self._threads.append(m)
return self._threads
@property
def peb_address(self):
if self._peb_address is None:
for t in self.threads:
self._peb_address = t.peb_address
break
return self._peb_address
@property
def peb_memory_block(self):
if self._peb_memory_block is None:
self._peb_memory_block = self._get_memory_block(self.peb_address)
return self._peb_memory_block
@property
def peb(self):
if self._peb is None:
m = self.peb_memory_block
if m is None:
return None
data = m.get_addr(self.peb_address, 64)
if data:
self._peb = Win32_PEB(self, data, self.is_64_bit)
return self._peb
@property
def memory_regions(self):
if self._memory_regions is None:
i = XMLReport._get_first_node(self._xml, 'crash_dump/memory_info')
self._memory_regions = []
all_subitems = i.xpath('memory') if i is not None else None
if all_subitems is not None:
for item in all_subitems:
m = XMLReport.MemoryRegion(self)
for f in XMLReport._memory_region_fields:
setattr(m, f, XMLReport._get_node_value(item, f))
m.usage = []
all_subitems = item.xpath('usage')
if all_subitems is not None:
for item in all_subitems:
usage = XMLReport.MemoryRegionUsage(self, m)
for f in XMLReport._memory_region_usage_fields:
setattr(usage, f, XMLReport._get_node_value(item, f))
m.usage.append(usage)
self._memory_regions.append(m)
self._memory_regions = sorted(self._memory_regions, key=lambda region: region.base_addr)
return self._memory_regions
@property
def memory_blocks(self):
if self._memory_blocks is None:
i = XMLReport._get_first_node(self._xml, 'crash_dump/memory_blocks')
self._memory_blocks = []
all_subitems = i.xpath('memory_block') if i is not None else None
if all_subitems is not None:
for item in all_subitems:
m = XMLReport.MemoryBlock(self)
for f in XMLReport._memory_block_fields:
setattr(m, f, XMLReport._get_node_value(item, f))
self._memory_blocks.append(m)
self._memory_blocks = sorted(self._memory_blocks, key=lambda block: block.base)
return self._memory_blocks
@property
def handles(self):
if self._handles is None:
i = XMLReport._get_first_node(self._xml, 'crash_dump/handle')
self._handles = []
all_subitems = i.xpath('handle') if i is not None else None
if all_subitems is not None:
for item in all_subitems:
m = XMLReport.Handle(self)
for f in XMLReport._handle_fields:
setattr(m, f, XMLReport._get_node_value(item, f))
self._handles.append(m)
return self._handles
@property
def stackdumps(self):
if self._stackdumps is None:
i = XMLReport._get_first_node(self._xml, 'crash_dump/stackdumps')
all_subitems = i.xpath('stackdump') if i is not None else None
if all_subitems is not None:
self._stackdumps = XMLReport.StackDumpList(self)
for item in all_subitems:
dump = XMLReport.StackDump(self)
for f in XMLReport._stackdump_fields:
setattr(dump, f, XMLReport._get_attribute(item, f))
dump.callstack = []
all_subitems = item.xpath('frame')
if all_subitems is not None:
for item in all_subitems:
frame = XMLReport.StackFrame(self, dump)
for f in XMLReport._stack_frame_fields:
setattr(frame, f, XMLReport._get_node_value(item, f))
dump.callstack.append(frame)
self._stackdumps.append(dump)
return self._stackdumps
@property
def simplified_info(self):
if self._simplified_info is None:
i = XMLReport._get_first_node(self._xml, 'crash_dump/simplified_info')
self._simplified_info = XMLReport.SimplifiedInfo(self) if i is not None else None
if i is not None:
for f in XMLReport._simplified_info_fields:
setattr(self._simplified_info, f, XMLReport._get_node_value(i, f))
return self._simplified_info
@property
def processstatuslinux(self):
if self._processstatuslinux is None:
i = XMLReport._get_first_node(self._xml, 'crash_dump/processstatuslinux')
self._processstatuslinux = XMLReport.ProcessStatusLinux(self) if i is not None else None
if i is not None:
for f in XMLReport._processstatuslinux_fields:
setattr(self._processstatuslinux, f, XMLReport._get_node_value(i, f))
return self._processstatuslinux
@property
def processstatuswin32(self):
if self._processstatuswin32 is None:
i = XMLReport._get_first_node(self._xml, 'crash_dump/processstatuswin32')
self._processstatuswin32 = XMLReport.ProcessStatusWin32(self) if i is not None else None
if i is not None:
for f in XMLReport._processstatuswin32_fields:
setattr(self._processstatuswin32, f, XMLReport._get_node_value(i, f))
return self._processstatuswin32
@property
def processmemoryinfowin32(self):
if self._processmemoryinfowin32 is None:
i = XMLReport._get_first_node(self._xml, 'crash_dump/processmemoryinfowin32')
self._processmemoryinfowin32 = XMLReport.ProcessMemoryInfoWin32(self) if i is not None else None
if i is not None:
for f in XMLReport._processmemoryinfowin32_fields:
setattr(self._processmemoryinfowin32, f, XMLReport._get_node_value(i, f))
return self._processmemoryinfowin32
@property
def misc_info(self):
if self._misc_info is None:
i = XMLReport._get_first_node(self._xml, 'crash_dump/misc_info')
self._misc_info = XMLReport.MiscInfo(self) if i is not None else None
if i is not None:
for f in XMLReport._processstatuslinux_fields:
setattr(self._misc_info, f, XMLReport._get_node_value(i, f))
return self._misc_info
@property
def fast_protect_version_info(self):
if self._fast_protect_version_info is None:
i = XMLReport._get_first_node(self._xml, 'crash_dump/fast_protect_version_info')
self._fast_protect_version_info = XMLReport.FastProtectVersionInfo(self) if i is not None else None
if i is not None:
for f in XMLReport._fast_protect_version_info_fields:
setattr(self._fast_protect_version_info, f, XMLReport._get_node_value(i, f))
return self._fast_protect_version_info
@property
def thread_name_tls_slot(self):
s = self.fast_protect_version_info
if s is None:
return None
return s.thread_name_tls_slot
@property
def fast_protect_system_info(self):
if self._fast_protect_system_info is None:
i = XMLReport._get_first_node(self._xml, 'crash_dump/fast_protect_system_info')
self._fast_protect_system_info = XMLReport.FastProtectSystemInfo(self) if i is not None else None
if i is not None:
for f in XMLReport._fast_protect_system_info_fields:
setattr(self._fast_protect_system_info, f, XMLReport._get_node_value(i, f))
return self._fast_protect_system_info
@property
def fields(self):
return self._main_fields
if __name__ == '__main__':
if len(sys.argv) < 2:
print('No crash report XML file(s) specified')
sys.exit(1)
xmlreport = XMLReport(sys.argv[1])
#print(xmlreport.crash_info)
#print(xmlreport.system_info)
#print(xmlreport.file_info)
#for m in xmlreport.modules:
#print(m)
#for m in xmlreport.threads:
#print(m)
#for m in xmlreport.handles:
#print(m)
#for m in xmlreport.memory_regions:
#print(m)
for m in xmlreport.stackdumps:
print('thread %u %s exception (simple %s)' % (m.threadid, 'with' if m.exception else 'without', 'yes' if m.simplified else 'no'))
for f in m.callstack:
print(f)
#dump = xmlreport.stackdumps['exception']
#for f in dump.callstack:
#print(f)
#dump = xmlreport.stackdumps['simplified']
#for f in dump.callstack:
#print(f)
#for m in xmlreport.memory_blocks:
#fmt = '0x%%0%ix: %%s - %%s' % m.hexdump.offset_width
#for l in m.hexdump:
#print(fmt % (l.offset, l.hex, l.ascii))
#for m in xmlreport.memory_blocks:
#print(m.threadid)
#for m in xmlreport.threads:
#print(type(m.id))
def dump_report_entity(entity, indent=0):
for (k,v) in entity.__dict__.items():
if k[0] != '_':
if isinstance(v, list):
dump_report_list(v, indent+2)
else:
print((' ' * indent) + '%s=%s' % (k,v))
def dump_report_list(list, indent=0):
for num, data_elem in enumerate(list):
print((' ' * indent) + '%i:' % num)
dump_report_entity(data_elem, indent + 2)
def dump_report(rep, field, indent=0):
print((' ' * indent) + field + ':')
data = getattr(rep, field)
if data is None:
print(' None')
elif isinstance(data, list):
dump_report_list(data, indent+2)
else:
dump_report_entity(data, indent + 2)
#dump_report(xmlreport, 'crash_info')
#dump_report(xmlreport, 'system_info')
#dump_report(xmlreport, 'file_info')
#dump_report(xmlreport, 'fast_protect_version_info')
#dump_report(xmlreport, 'fast_protect_system_info')
#print('machine_type=%s' % xmlreport.fast_protect_system_info.machine_type)
#dump_report(xmlreport, 'simplified_info')
#dump_report(xmlreport, 'modules')
#if xmlreport.exception is not None:
#print(xmlreport.exception.involved_modules)
#print(xmlreport.exception.params)
#dump_report(xmlreport, 'threads')
#print(xmlreport.peb.image_base_address)
#slot = xmlreport.fast_protect_version_info.thread_name_tls_slot
#print('slot index=%i'% slot)
#r = xmlreport.find_in_memory_blocks('Clt')
#for (m, index) in r:
# print(m)
# print(str(m.hexdump))
#for t in [ xmlreport.threads[0] ]:
#for t in xmlreport.threads:
# teb = t.teb_data
# if teb:
# #print('%05x - %05x, PEB %x, TLS array %x' % (t.id, teb.threadid, teb.peb_address, teb.thread_local_storage_array_address))
# #if teb.thread_local_storage_array:
# #print('%05x - %x' % (t.id, teb.thread_local_storage_array[slot]))
# #print('%05x - %x' % (t.id, teb.tls_slots[1]))
# #print(' %05x - %s' % (t.id, t.teb_memory_region))
# print(' %05x - %s thread name at %x' % (t.id, t.name, teb.tls_slots[slot]))
# #print(teb.hexdump)
# #print('%i - %x, %x, %x' % (t.id, teb.threadid, teb.peb_address, teb.thread_local_storage_array))
#
# #for i in range(slot + 1):
# #print(' slot[%i]=%x' %(i, t.tls_slots[i]))
#dump_report(xmlreport, 'memory_blocks')
#dump_report(xmlreport, 'memory_regions')
#dump_report(xmlreport, 'exception')
#dump_report(xmlreport, 'processmemoryinfowin32')
#pp = XMLReport.ProxyObject(xmlreport, 'memory_regions')
#print(len(pp))
#pp = XMLReport.ProxyObject(xmlreport, 'memory_blocks')
#print(len(pp))
#for m in pp:
#print(m)
#dump_report(xmlreport, 'memory_regions')
#print(xmlreport.crash_info.path)
#sys.stdout.write(xmlreport.fast_protect_system_info.rawdata.raw)
#if xmlreport.exception.thread.stackdump:
#for (no, f) in enumerate(xmlreport.exception.thread.stackdump.callstack):
#print('%i: %s' % (no, f))
#else:
#print(' no stackdump available')
#print('Simplified Stackdump')
#if xmlreport.exception.thread.simplified_stackdump:
#for (no, f) in enumerate(xmlreport.exception.thread.simplified_stackdump.callstack):
#print('%i: %s' % (no, f))
#print('%i: %s' % (no, f.params))
#else:
#print(' no simplified stackdump available')
|
gpl-3.0
| -559,323,098,969,346,050
| 35.850877
| 217
| 0.524909
| false
| 3.941429
| false
| false
| false
|
flags/Reactor-3
|
tools/ReactorWatch.py
|
1
|
1492
|
#This tool was rushed together over the course of an hour or so. Be gentle.
from flask import Flask, render_template, request
import threading
import socket
import json
app = Flask(__name__)
def request(request, value=None):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)
sock.connect(('127.0.0.1', 3335))
sock.sendall(json.dumps({'type': 'get', 'what': request, 'value': value}))
data = json.loads(sock.recv(9048))
sock.close()
return data
@app.route('/memory/<life_id>')
def memory(life_id):
memories = request('memory', value=int(life_id))
return render_template('memory.html', life_id=life_id, memories=memories)
@app.route('/life/<life_id>')
def life(life_id):
life = request('life', value=int(life_id))
knows = life['know'].values()
return render_template('life.html', life=life, knows=knows)
@app.route('/camp/<camp_id>')
def camp(camp_id):
camp = request('camp', value=int(camp_id))
return render_template('camp.html', camp=camp)
@app.route('/group/<group_id>')
def group(group_id):
groups = request('groups')
group = groups[group_id]
return render_template('group.html', group_id=group_id, group=group)
@app.route('/')
def index():
groups = request('groups')
life = request('life_list')
life.sort()
#camps = request('camp_list')
#camps.sort()
stats = request('stats')
return render_template('index.html', stats=stats, life=life, groups=groups)
if __name__ == '__main__':
app.run(debug=True, port=3336)
|
mit
| -1,046,577,889,139,109,800
| 23.080645
| 76
| 0.683646
| false
| 2.902724
| false
| false
| false
|
tuskar/tuskar-ui
|
openstack_dashboard/dashboards/admin/users/tests.py
|
1
|
18692
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from socket import timeout as socket_timeout
from django.core.urlresolvers import reverse
from django import http
from mox import IgnoreArg
from mox import IsA
from openstack_dashboard import api
from openstack_dashboard.test import helpers as test
USERS_INDEX_URL = reverse('horizon:admin:users:index')
USER_CREATE_URL = reverse('horizon:admin:users:create')
USER_UPDATE_URL = reverse('horizon:admin:users:update', args=[1])
class UsersViewTests(test.BaseAdminViewTests):
def _get_domain_id(self):
return self.request.session.get('domain_context', None)
def _get_users(self, domain_id):
if not domain_id:
users = self.users.list()
else:
users = [user for user in self.users.list()
if user.domain_id == domain_id]
return users
@test.create_stubs({api.keystone: ('user_list',)})
def test_index(self):
domain_id = self._get_domain_id()
users = self._get_users(domain_id)
api.keystone.user_list(IgnoreArg(), domain=domain_id) \
.AndReturn(users)
self.mox.ReplayAll()
res = self.client.get(USERS_INDEX_URL)
self.assertTemplateUsed(res, 'admin/users/index.html')
self.assertItemsEqual(res.context['table'].data, users)
if domain_id:
for user in res.context['table'].data:
self.assertItemsEqual(user.domain_id, domain_id)
def test_index_with_domain(self):
domain = self.domains.get(id="1")
self.setSessionValues(domain_context=domain.id,
domain_context_name=domain.name)
self.test_index()
@test.create_stubs({api.keystone: ('user_create',
'tenant_list',
'add_tenant_user_role',
'get_default_role',
'role_list')})
def test_create(self):
user = self.users.get(id="1")
domain_id = self._get_domain_id()
role = self.roles.first()
api.keystone.tenant_list(IgnoreArg(), user=None) \
.AndReturn([self.tenants.list(), False])
api.keystone.user_create(IgnoreArg(),
name=user.name,
email=user.email,
password=user.password,
project=self.tenant.id,
enabled=True,
domain=domain_id).AndReturn(user)
api.keystone.role_list(IgnoreArg()).AndReturn(self.roles.list())
api.keystone.get_default_role(IgnoreArg()).AndReturn(role)
api.keystone.add_tenant_user_role(IgnoreArg(), self.tenant.id,
user.id, role.id)
self.mox.ReplayAll()
formData = {'method': 'CreateUserForm',
'name': user.name,
'email': user.email,
'password': user.password,
'project': self.tenant.id,
'role_id': self.roles.first().id,
'confirm_password': user.password}
res = self.client.post(USER_CREATE_URL, formData)
self.assertNoFormErrors(res)
self.assertMessageCount(success=1)
def test_create_with_domain(self):
domain = self.domains.get(id="1")
self.setSessionValues(domain_context=domain.id,
domain_context_name=domain.name)
self.test_create()
@test.create_stubs({api.keystone: ('tenant_list',
'role_list',
'get_default_role')})
def test_create_with_password_mismatch(self):
user = self.users.get(id="1")
api.keystone.tenant_list(IgnoreArg(), user=None) \
.AndReturn([self.tenants.list(), False])
api.keystone.role_list(IgnoreArg()).AndReturn(self.roles.list())
api.keystone.get_default_role(IgnoreArg()) \
.AndReturn(self.roles.first())
self.mox.ReplayAll()
formData = {'method': 'CreateUserForm',
'name': user.name,
'email': user.email,
'password': user.password,
'project': self.tenant.id,
'role_id': self.roles.first().id,
'confirm_password': "doesntmatch"}
res = self.client.post(USER_CREATE_URL, formData)
self.assertFormError(res, "form", None, ['Passwords do not match.'])
@test.create_stubs({api.keystone: ('tenant_list',
'role_list',
'get_default_role')})
def test_create_validation_for_password_too_short(self):
user = self.users.get(id="1")
api.keystone.tenant_list(IgnoreArg(), user=None) \
.AndReturn([self.tenants.list(), False])
api.keystone.role_list(IgnoreArg()).AndReturn(self.roles.list())
api.keystone.get_default_role(IgnoreArg()) \
.AndReturn(self.roles.first())
self.mox.ReplayAll()
# check password min-len verification
formData = {'method': 'CreateUserForm',
'name': user.name,
'email': user.email,
'password': 'four',
'project': self.tenant.id,
'role_id': self.roles.first().id,
'confirm_password': 'four'}
res = self.client.post(USER_CREATE_URL, formData)
self.assertFormError(
res, "form", 'password',
['Password must be between 8 and 18 characters.'])
@test.create_stubs({api.keystone: ('tenant_list',
'role_list',
'get_default_role')})
def test_create_validation_for_password_too_long(self):
user = self.users.get(id="1")
api.keystone.tenant_list(IgnoreArg(), user=None) \
.AndReturn([self.tenants.list(), False])
api.keystone.role_list(IgnoreArg()).AndReturn(self.roles.list())
api.keystone.get_default_role(IgnoreArg()) \
.AndReturn(self.roles.first())
self.mox.ReplayAll()
# check password min-len verification
formData = {'method': 'CreateUserForm',
'name': user.name,
'email': user.email,
'password': 'MoreThanEighteenChars',
'project': self.tenant.id,
'role_id': self.roles.first().id,
'confirm_password': 'MoreThanEighteenChars'}
res = self.client.post(USER_CREATE_URL, formData)
self.assertFormError(
res, "form", 'password',
['Password must be between 8 and 18 characters.'])
@test.create_stubs({api.keystone: ('user_get',
'tenant_list',
'user_update_tenant',
'user_update_password',
'user_update',
'roles_for_user', )})
def test_update(self):
user = self.users.get(id="1")
test_password = 'normalpwd'
api.keystone.user_get(IsA(http.HttpRequest), '1',
admin=True).AndReturn(user)
api.keystone.tenant_list(IgnoreArg(), user=user.id) \
.AndReturn([self.tenants.list(), False])
api.keystone.user_update(IsA(http.HttpRequest),
user.id,
email=u'test@example.com',
name=u'test_user',
password=test_password,
project=self.tenant.id).AndReturn(None)
self.mox.ReplayAll()
formData = {'method': 'UpdateUserForm',
'id': user.id,
'name': user.name,
'email': user.email,
'password': test_password,
'project': self.tenant.id,
'confirm_password': test_password}
res = self.client.post(USER_UPDATE_URL, formData)
self.assertNoFormErrors(res)
@test.create_stubs({api.keystone: ('user_get',
'tenant_list',
'user_update_tenant',
'keystone_can_edit_user',
'roles_for_user', )})
def test_update_with_keystone_can_edit_user_false(self):
user = self.users.get(id="1")
api.keystone.user_get(IsA(http.HttpRequest),
'1',
admin=True).AndReturn(user)
api.keystone.tenant_list(IgnoreArg(), user=user.id) \
.AndReturn([self.tenants.list(), False])
api.keystone.keystone_can_edit_user().AndReturn(False)
api.keystone.keystone_can_edit_user().AndReturn(False)
self.mox.ReplayAll()
formData = {'method': 'UpdateUserForm',
'id': user.id,
'name': user.name,
'project': self.tenant.id, }
res = self.client.post(USER_UPDATE_URL, formData)
self.assertNoFormErrors(res)
self.assertMessageCount(error=1)
@test.create_stubs({api.keystone: ('user_get', 'tenant_list')})
def test_update_validation_for_password_too_short(self):
user = self.users.get(id="1")
api.keystone.user_get(IsA(http.HttpRequest), '1',
admin=True).AndReturn(user)
api.keystone.tenant_list(IgnoreArg(), user=user.id) \
.AndReturn([self.tenants.list(), False])
self.mox.ReplayAll()
formData = {'method': 'UpdateUserForm',
'id': user.id,
'name': user.name,
'email': user.email,
'password': 't',
'project': self.tenant.id,
'confirm_password': 't'}
res = self.client.post(USER_UPDATE_URL, formData)
self.assertFormError(
res, "form", 'password',
['Password must be between 8 and 18 characters.'])
@test.create_stubs({api.keystone: ('user_get', 'tenant_list')})
def test_update_validation_for_password_too_long(self):
user = self.users.get(id="1")
api.keystone.user_get(IsA(http.HttpRequest), '1',
admin=True).AndReturn(user)
api.keystone.tenant_list(IgnoreArg(), user=user.id) \
.AndReturn([self.tenants.list(), False])
self.mox.ReplayAll()
formData = {'method': 'UpdateUserForm',
'id': user.id,
'name': user.name,
'email': user.email,
'password': 'ThisIsASuperLongPassword',
'project': self.tenant.id,
'confirm_password': 'ThisIsASuperLongPassword'}
res = self.client.post(USER_UPDATE_URL, formData)
self.assertFormError(
res, "form", 'password',
['Password must be between 8 and 18 characters.'])
@test.create_stubs({api.keystone: ('user_update_enabled', 'user_list')})
def test_enable_user(self):
user = self.users.get(id="2")
domain_id = self._get_domain_id()
users = self._get_users(domain_id)
user.enabled = False
api.keystone.user_list(IgnoreArg(), domain=domain_id).AndReturn(users)
api.keystone.user_update_enabled(IgnoreArg(),
user.id,
True).AndReturn(user)
self.mox.ReplayAll()
formData = {'action': 'users__toggle__%s' % user.id}
res = self.client.post(USERS_INDEX_URL, formData)
self.assertRedirectsNoFollow(res, USERS_INDEX_URL)
@test.create_stubs({api.keystone: ('user_update_enabled', 'user_list')})
def test_disable_user(self):
user = self.users.get(id="2")
domain_id = self._get_domain_id()
users = self._get_users(domain_id)
self.assertTrue(user.enabled)
api.keystone.user_list(IgnoreArg(), domain=domain_id) \
.AndReturn(users)
api.keystone.user_update_enabled(IgnoreArg(),
user.id,
False).AndReturn(user)
self.mox.ReplayAll()
formData = {'action': 'users__toggle__%s' % user.id}
res = self.client.post(USERS_INDEX_URL, formData)
self.assertRedirectsNoFollow(res, USERS_INDEX_URL)
@test.create_stubs({api.keystone: ('user_update_enabled', 'user_list')})
def test_enable_disable_user_exception(self):
user = self.users.get(id="2")
domain_id = self._get_domain_id()
users = self._get_users(domain_id)
user.enabled = False
api.keystone.user_list(IgnoreArg(), domain=domain_id) \
.AndReturn(users)
api.keystone.user_update_enabled(IgnoreArg(), user.id, True) \
.AndRaise(self.exceptions.keystone)
self.mox.ReplayAll()
formData = {'action': 'users__toggle__%s' % user.id}
res = self.client.post(USERS_INDEX_URL, formData)
self.assertRedirectsNoFollow(res, USERS_INDEX_URL)
@test.create_stubs({api.keystone: ('user_list',)})
def test_disabling_current_user(self):
domain_id = self._get_domain_id()
users = self._get_users(domain_id)
for i in range(0, 2):
api.keystone.user_list(IgnoreArg(), domain=domain_id) \
.AndReturn(users)
self.mox.ReplayAll()
formData = {'action': 'users__toggle__%s' % self.request.user.id}
res = self.client.post(USERS_INDEX_URL, formData, follow=True)
self.assertEqual(list(res.context['messages'])[0].message,
u'You cannot disable the user you are currently '
u'logged in as.')
@test.create_stubs({api.keystone: ('user_list',)})
def test_delete_user_with_improper_permissions(self):
domain_id = self._get_domain_id()
users = self._get_users(domain_id)
for i in range(0, 2):
api.keystone.user_list(IgnoreArg(), domain=domain_id) \
.AndReturn(users)
self.mox.ReplayAll()
formData = {'action': 'users__delete__%s' % self.request.user.id}
res = self.client.post(USERS_INDEX_URL, formData, follow=True)
self.assertEqual(list(res.context['messages'])[0].message,
u'You do not have permission to delete user: %s'
% self.request.user.username)
class SeleniumTests(test.SeleniumAdminTestCase):
@test.create_stubs({api.keystone: ('tenant_list',
'get_default_role',
'role_list',
'user_list')})
def test_modal_create_user_with_passwords_not_matching(self):
api.keystone.tenant_list(IgnoreArg(), user=None) \
.AndReturn([self.tenants.list(), False])
api.keystone.role_list(IgnoreArg()).AndReturn(self.roles.list())
api.keystone.user_list(IgnoreArg(), domain=None) \
.AndReturn(self.users.list())
api.keystone.get_default_role(IgnoreArg()) \
.AndReturn(self.roles.first())
self.mox.ReplayAll()
self.selenium.get("%s%s" % (self.live_server_url, USERS_INDEX_URL))
# Open the modal menu
self.selenium.find_element_by_id("users__action_create") \
.send_keys("\n")
wait = self.ui.WebDriverWait(self.selenium, 10,
ignored_exceptions=[socket_timeout])
wait.until(lambda x: self.selenium.find_element_by_id("id_name"))
body = self.selenium.find_element_by_tag_name("body")
self.assertFalse("Passwords do not match" in body.text,
"Error message should not be visible at loading time")
self.selenium.find_element_by_id("id_name").send_keys("Test User")
self.selenium.find_element_by_id("id_password").send_keys("test")
self.selenium.find_element_by_id("id_confirm_password").send_keys("te")
self.selenium.find_element_by_id("id_email").send_keys("a@b.com")
body = self.selenium.find_element_by_tag_name("body")
self.assertTrue("Passwords do not match" in body.text,
"Error message not found in body")
@test.create_stubs({api.keystone: ('tenant_list', 'user_get')})
def test_update_user_with_passwords_not_matching(self):
api.keystone.user_get(IsA(http.HttpRequest), '1',
admin=True).AndReturn(self.user)
api.keystone.tenant_list(IgnoreArg(), user=self.user.id) \
.AndReturn([self.tenants.list(), False])
self.mox.ReplayAll()
self.selenium.get("%s%s" % (self.live_server_url, USER_UPDATE_URL))
body = self.selenium.find_element_by_tag_name("body")
self.assertFalse("Passwords do not match" in body.text,
"Error message should not be visible at loading time")
self.selenium.find_element_by_id("id_password").send_keys("test")
self.selenium.find_element_by_id("id_confirm_password").send_keys("te")
self.selenium.find_element_by_id("id_email").clear()
body = self.selenium.find_element_by_tag_name("body")
self.assertTrue("Passwords do not match" in body.text,
"Error message not found in body")
|
apache-2.0
| -2,188,680,730,515,127,000
| 39.458874
| 79
| 0.546223
| false
| 4.105425
| true
| false
| false
|
laserson/rock-health-python
|
luigi/luigi-ngrams.py
|
1
|
1715
|
import os
import re
import luigi
import luigi.hadoop
import luigi.hdfs
class InputText(luigi.ExternalTask):
path = luigi.Parameter()
def output(self):
return luigi.hdfs.HdfsTarget(self.path)
class Ngrams(luigi.hadoop.JobTask):
source = luigi.Parameter()
destination = luigi.Parameter()
# overrides superclass; gets set as jobconf:
n_reduce_tasks = luigi.IntParameter(default=10)
def requires(self):
tasks = []
paths = luigi.hdfs.HdfsClient().listdir(self.source, ignore_directories=True, recursive=True)
for path in paths:
tasks.append(InputText(path))
return tasks
def output(self):
return luigi.hdfs.HdfsTarget(self.destination)
def init_mapper(self):
try:
input_file = os.environ['map_input_file']
except KeyError:
input_file = os.environ['mapreduce_map_input_file']
self.expected_tokens = int(re.findall(r'([\d]+)gram', os.path.basename(input_file))[0])
def mapper(self, line):
data = line.split('\t')
if len(data) < 3:
return
# unpack data
ngram = data[0].split()
year = data[1]
count = int(data[2])
if len(ngram) != self.expected_tokens:
return
# generate key
pair = sorted([ngram[0], ngram[self.expected_tokens - 1]])
k = pair + [year]
yield (k, count)
def combiner(self, key, values):
yield (key, sum(values))
def reducer(self, key, values):
yield "%s\t%s\t%s" % tuple(key), str(sum(values))
if __name__ == '__main__':
luigi.run()
|
apache-2.0
| 8,702,826,489,544,018,000
| 25.796875
| 101
| 0.566764
| false
| 3.802661
| false
| false
| false
|
phac-nml/dynamic-tool-destination
|
tests/mockGalaxy.py
|
1
|
3562
|
"""
# =============================================================================
Copyright Government of Canada 2015
Written by: Eric Enns, Public Health Agency of Canada,
National Microbiology Laboratory
Daniel Bouchard, Public Health Agency of Canada,
National Microbiology Laboratory
Funded by the National Micriobiology Laboratory
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this work except in compliance with the License. You may obtain a copy of the
License at:
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
# =============================================================================
"""
'''
Created on June 23rd, 2015
@author: Daniel Bouchard
'''
from collections import namedtuple
#Job mock and helpers=======================================
class Job(object):
def __init__(self):
self.input_datasets = []
self.input_library_datasets = []
self.param_values = dict()
def get_param_values(self, app, ignore_errors=False):
return self.param_values
def set_arg_value(self, key, value):
self.param_values[key] = value
def add_input_dataset(self, dataset):
self.input_datasets.append(dataset)
class InputDataset(object):
def __init__(self, name, dataset):
self.name = name
self.dataset = dataset
class NotAFile(object):
pass
class Dataset(object):
def __init__(self, file_name, file_ext, value):
self.file_name = file_name
self.datatype = Datatype(file_ext)
self.ext = file_ext
self.metadata = dict()
self.metadata['sequences'] = value
def get_metadata(self):
return self.metadata
class Datatype(object):
def __init__(self, file_ext):
self.file_ext = file_ext
#Tool mock and helpers=========================================
class Tool(object):
def __init__(self, id):
self.old_id = id
self.installed_tool_dependencies = []
def add_tool_dependency(self, dependency):
self.installed_tool_dependencies.append(dependency)
class ToolDependency(object):
def __init__(self, name, dir_name):
self.name = name
self.dir_name = dir_name
def installation_directory(self, app):
return self.dir_name
#App mock=======================================================
class App(object):
def __init__(self, tool_id, params):
self.job_config = JobConfig( tool_id, params )
class JobConfig(object):
def __init__(self, tool_id, params):
self.info = namedtuple('info', ['id', 'nativeSpec', 'runner'])
self.tool_id = tool_id
self.nativeSpec = params
self.default_id = "waffles_default"
self.defNativeSpec = "-q test.q"
self.defRunner = "drmaa"
self.keys = { tool_id: self.info( self.tool_id, self.nativeSpec, self.defRunner ),
"waffles_default": self.info( self.default_id, self.defNativeSpec, self.defRunner ), }
def get_destination(self, tool_id):
return self.keys[tool_id]
#JobMappingException mock=======================================
class JobMappingException(Exception):
pass
class JobDestination(object):
def __init__(self, **kwd):
self.id = kwd.get('id')
self.nativeSpec = kwd.get('params')['nativeSpecification']
self.runner = kwd.get('runner')
|
apache-2.0
| 8,361,889,673,550,643,000
| 29.444444
| 107
| 0.624088
| false
| 3.706556
| false
| false
| false
|
benschmaus/catapult
|
telemetry/telemetry/internal/backends/chrome_inspector/inspector_backend.py
|
1
|
18595
|
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import functools
import logging
import socket
import sys
from py_trace_event import trace_event
from telemetry.core import exceptions
from telemetry import decorators
from telemetry.internal.backends.chrome_inspector import devtools_http
from telemetry.internal.backends.chrome_inspector import inspector_console
from telemetry.internal.backends.chrome_inspector import inspector_memory
from telemetry.internal.backends.chrome_inspector import inspector_page
from telemetry.internal.backends.chrome_inspector import inspector_runtime
from telemetry.internal.backends.chrome_inspector import inspector_websocket
from telemetry.internal.backends.chrome_inspector import websocket
from telemetry.util import js_template
import py_utils
def _HandleInspectorWebSocketExceptions(func):
"""Decorator for converting inspector_websocket exceptions.
When an inspector_websocket exception is thrown in the original function,
this decorator converts it into a telemetry exception and adds debugging
information.
"""
@functools.wraps(func)
def inner(inspector_backend, *args, **kwargs):
try:
return func(inspector_backend, *args, **kwargs)
except (socket.error, websocket.WebSocketException,
inspector_websocket.WebSocketDisconnected) as e:
inspector_backend._ConvertExceptionFromInspectorWebsocket(e)
return inner
class InspectorBackend(object):
"""Class for communicating with a devtools client.
The owner of an instance of this class is responsible for calling
Disconnect() before disposing of the instance.
"""
__metaclass__ = trace_event.TracedMetaClass
def __init__(self, app, devtools_client, context, timeout=120):
self._websocket = inspector_websocket.InspectorWebsocket()
self._websocket.RegisterDomain(
'Inspector', self._HandleInspectorDomainNotification)
self._app = app
self._devtools_client = devtools_client
# Be careful when using the context object, since the data may be
# outdated since this is never updated once InspectorBackend is
# created. Consider an updating strategy for this. (For an example
# of the subtlety, see the logic for self.url property.)
self._context = context
logging.debug('InspectorBackend._Connect() to %s', self.debugger_url)
try:
self._websocket.Connect(self.debugger_url, timeout)
self._console = inspector_console.InspectorConsole(self._websocket)
self._memory = inspector_memory.InspectorMemory(self._websocket)
self._page = inspector_page.InspectorPage(
self._websocket, timeout=timeout)
self._runtime = inspector_runtime.InspectorRuntime(self._websocket)
except (websocket.WebSocketException, exceptions.TimeoutException,
py_utils.TimeoutException) as e:
self._ConvertExceptionFromInspectorWebsocket(e)
def Disconnect(self):
"""Disconnects the inspector websocket.
This method intentionally leaves the self._websocket object around, so that
future calls it to it will fail with a relevant error.
"""
if self._websocket:
self._websocket.Disconnect()
def __del__(self):
self.Disconnect()
@property
def app(self):
return self._app
@property
def url(self):
"""Returns the URL of the tab, as reported by devtools.
Raises:
devtools_http.DevToolsClientConnectionError
"""
return self._devtools_client.GetUrl(self.id)
@property
def id(self):
return self._context['id']
@property
def debugger_url(self):
return self._context['webSocketDebuggerUrl']
def GetWebviewInspectorBackends(self):
"""Returns a list of InspectorBackend instances associated with webviews.
Raises:
devtools_http.DevToolsClientConnectionError
"""
inspector_backends = []
devtools_context_map = self._devtools_client.GetUpdatedInspectableContexts()
for context in devtools_context_map.contexts:
if context['type'] == 'webview':
inspector_backends.append(
devtools_context_map.GetInspectorBackend(context['id']))
return inspector_backends
def IsInspectable(self):
"""Whether the tab is inspectable, as reported by devtools."""
try:
return self._devtools_client.IsInspectable(self.id)
except devtools_http.DevToolsClientConnectionError:
return False
# Public methods implemented in JavaScript.
@property
@decorators.Cache
def screenshot_supported(self):
return True
@_HandleInspectorWebSocketExceptions
def Screenshot(self, timeout):
assert self.screenshot_supported, 'Browser does not support screenshotting'
return self._page.CaptureScreenshot(timeout)
# Memory public methods.
@_HandleInspectorWebSocketExceptions
def GetDOMStats(self, timeout):
"""Gets memory stats from the DOM.
Raises:
inspector_memory.InspectorMemoryException
exceptions.TimeoutException
exceptions.DevtoolsTargetCrashException
"""
dom_counters = self._memory.GetDOMCounters(timeout)
return {
'document_count': dom_counters['documents'],
'node_count': dom_counters['nodes'],
'event_listener_count': dom_counters['jsEventListeners']
}
# Page public methods.
@_HandleInspectorWebSocketExceptions
def WaitForNavigate(self, timeout):
self._page.WaitForNavigate(timeout)
@_HandleInspectorWebSocketExceptions
def Navigate(self, url, script_to_evaluate_on_commit, timeout):
self._page.Navigate(url, script_to_evaluate_on_commit, timeout)
@_HandleInspectorWebSocketExceptions
def GetCookieByName(self, name, timeout):
return self._page.GetCookieByName(name, timeout)
# Console public methods.
@_HandleInspectorWebSocketExceptions
def GetCurrentConsoleOutputBuffer(self, timeout=10):
return self._console.GetCurrentConsoleOutputBuffer(timeout)
# Runtime public methods.
@_HandleInspectorWebSocketExceptions
def ExecuteJavaScript(self, statement, **kwargs):
"""Executes a given JavaScript statement. Does not return the result.
Example: runner.ExecuteJavaScript('var foo = {{ value }};', value='hi');
Args:
statement: The statement to execute (provided as a string).
Optional keyword args:
timeout: The number of seconds to wait for the statement to execute.
context_id: The id of an iframe where to execute the code; the main page
has context_id=1, the first iframe context_id=2, etc.
Additional keyword arguments provide values to be interpolated within
the statement. See telemetry.util.js_template for details.
Raises:
py_utils.TimeoutException
exceptions.EvaluationException
exceptions.WebSocketException
exceptions.DevtoolsTargetCrashException
"""
# Use the default both when timeout=None or the option is ommited.
timeout = kwargs.pop('timeout', None) or 60
context_id = kwargs.pop('context_id', None)
statement = js_template.Render(statement, **kwargs)
self._runtime.Execute(statement, context_id, timeout)
def EvaluateJavaScript(self, expression, **kwargs):
"""Returns the result of evaluating a given JavaScript expression.
Example: runner.ExecuteJavaScript('document.location.href');
Args:
expression: The expression to execute (provided as a string).
Optional keyword args:
timeout: The number of seconds to wait for the expression to evaluate.
context_id: The id of an iframe where to execute the code; the main page
has context_id=1, the first iframe context_id=2, etc.
Additional keyword arguments provide values to be interpolated within
the expression. See telemetry.util.js_template for details.
Raises:
py_utils.TimeoutException
exceptions.EvaluationException
exceptions.WebSocketException
exceptions.DevtoolsTargetCrashException
"""
# Use the default both when timeout=None or the option is ommited.
timeout = kwargs.pop('timeout', None) or 60
context_id = kwargs.pop('context_id', None)
expression = js_template.Render(expression, **kwargs)
return self._EvaluateJavaScript(expression, context_id, timeout)
def WaitForJavaScriptCondition(self, condition, **kwargs):
"""Wait for a JavaScript condition to become truthy.
Example: runner.WaitForJavaScriptCondition('window.foo == 10');
Args:
condition: The JavaScript condition (provided as string).
Optional keyword args:
timeout: The number in seconds to wait for the condition to become
True (default to 60).
context_id: The id of an iframe where to execute the code; the main page
has context_id=1, the first iframe context_id=2, etc.
Additional keyword arguments provide values to be interpolated within
the expression. See telemetry.util.js_template for details.
Returns:
The value returned by the JavaScript condition that got interpreted as
true.
Raises:
py_utils.TimeoutException
exceptions.EvaluationException
exceptions.WebSocketException
exceptions.DevtoolsTargetCrashException
"""
# Use the default both when timeout=None or the option is ommited.
timeout = kwargs.pop('timeout', None) or 60
context_id = kwargs.pop('context_id', None)
condition = js_template.Render(condition, **kwargs)
def IsJavaScriptExpressionTrue():
return self._EvaluateJavaScript(condition, context_id, timeout)
try:
return py_utils.WaitFor(IsJavaScriptExpressionTrue, timeout)
except py_utils.TimeoutException as e:
# Try to make timeouts a little more actionable by dumping console output.
debug_message = None
try:
debug_message = (
'Console output:\n%s' %
self.GetCurrentConsoleOutputBuffer())
except Exception as e:
debug_message = (
'Exception thrown when trying to capture console output: %s' %
repr(e))
raise py_utils.TimeoutException(
e.message + '\n' + debug_message)
@_HandleInspectorWebSocketExceptions
def EnableAllContexts(self):
"""Allows access to iframes.
Raises:
exceptions.WebSocketDisconnected
exceptions.TimeoutException
exceptions.DevtoolsTargetCrashException
"""
return self._runtime.EnableAllContexts()
@_HandleInspectorWebSocketExceptions
def SynthesizeScrollGesture(self, x=100, y=800, xDistance=0, yDistance=-500,
xOverscroll=None, yOverscroll=None,
preventFling=None, speed=None,
gestureSourceType=None, repeatCount=None,
repeatDelayMs=None, interactionMarkerName=None,
timeout=60):
"""Runs an inspector command that causes a repeatable browser driven scroll.
Args:
x: X coordinate of the start of the gesture in CSS pixels.
y: Y coordinate of the start of the gesture in CSS pixels.
xDistance: Distance to scroll along the X axis (positive to scroll left).
yDistance: Distance to scroll along the Y axis (positive to scroll up).
xOverscroll: Number of additional pixels to scroll back along the X axis.
xOverscroll: Number of additional pixels to scroll back along the Y axis.
preventFling: Prevents a fling gesture.
speed: Swipe speed in pixels per second.
gestureSourceType: Which type of input events to be generated.
repeatCount: Number of additional repeats beyond the first scroll.
repeatDelayMs: Number of milliseconds delay between each repeat.
interactionMarkerName: The name of the interaction markers to generate.
Raises:
exceptions.TimeoutException
exceptions.DevtoolsTargetCrashException
"""
params = {
'x': x,
'y': y,
'xDistance': xDistance,
'yDistance': yDistance
}
if preventFling is not None:
params['preventFling'] = preventFling
if xOverscroll is not None:
params['xOverscroll'] = xOverscroll
if yOverscroll is not None:
params['yOverscroll'] = yOverscroll
if speed is not None:
params['speed'] = speed
if repeatCount is not None:
params['repeatCount'] = repeatCount
if gestureSourceType is not None:
params['gestureSourceType'] = gestureSourceType
if repeatDelayMs is not None:
params['repeatDelayMs'] = repeatDelayMs
if interactionMarkerName is not None:
params['interactionMarkerName'] = interactionMarkerName
scroll_command = {
'method': 'Input.synthesizeScrollGesture',
'params': params
}
return self._runtime.RunInspectorCommand(scroll_command, timeout)
@_HandleInspectorWebSocketExceptions
def DispatchKeyEvent(self, keyEventType='char', modifiers=None,
timestamp=None, text=None, unmodifiedText=None,
keyIdentifier=None, domCode=None, domKey=None,
windowsVirtualKeyCode=None, nativeVirtualKeyCode=None,
autoRepeat=None, isKeypad=None, isSystemKey=None,
timeout=60):
"""Dispatches a key event to the page.
Args:
type: Type of the key event. Allowed values: 'keyDown', 'keyUp',
'rawKeyDown', 'char'.
modifiers: Bit field representing pressed modifier keys. Alt=1, Ctrl=2,
Meta/Command=4, Shift=8 (default: 0).
timestamp: Time at which the event occurred. Measured in UTC time in
seconds since January 1, 1970 (default: current time).
text: Text as generated by processing a virtual key code with a keyboard
layout. Not needed for for keyUp and rawKeyDown events (default: '').
unmodifiedText: Text that would have been generated by the keyboard if no
modifiers were pressed (except for shift). Useful for shortcut
(accelerator) key handling (default: "").
keyIdentifier: Unique key identifier (e.g., 'U+0041') (default: '').
windowsVirtualKeyCode: Windows virtual key code (default: 0).
nativeVirtualKeyCode: Native virtual key code (default: 0).
autoRepeat: Whether the event was generated from auto repeat (default:
False).
isKeypad: Whether the event was generated from the keypad (default:
False).
isSystemKey: Whether the event was a system key event (default: False).
Raises:
exceptions.TimeoutException
exceptions.DevtoolsTargetCrashException
"""
params = {
'type': keyEventType,
}
if modifiers is not None:
params['modifiers'] = modifiers
if timestamp is not None:
params['timestamp'] = timestamp
if text is not None:
params['text'] = text
if unmodifiedText is not None:
params['unmodifiedText'] = unmodifiedText
if keyIdentifier is not None:
params['keyIdentifier'] = keyIdentifier
if domCode is not None:
params['code'] = domCode
if domKey is not None:
params['key'] = domKey
if windowsVirtualKeyCode is not None:
params['windowsVirtualKeyCode'] = windowsVirtualKeyCode
if nativeVirtualKeyCode is not None:
params['nativeVirtualKeyCode'] = nativeVirtualKeyCode
if autoRepeat is not None:
params['autoRepeat'] = autoRepeat
if isKeypad is not None:
params['isKeypad'] = isKeypad
if isSystemKey is not None:
params['isSystemKey'] = isSystemKey
key_command = {
'method': 'Input.dispatchKeyEvent',
'params': params
}
return self._runtime.RunInspectorCommand(key_command, timeout)
# Methods used internally by other backends.
def _HandleInspectorDomainNotification(self, res):
if (res['method'] == 'Inspector.detached' and
res.get('params', {}).get('reason', '') == 'replaced_with_devtools'):
self._WaitForInspectorToGoAway()
return
if res['method'] == 'Inspector.targetCrashed':
exception = exceptions.DevtoolsTargetCrashException(self.app)
self._AddDebuggingInformation(exception)
raise exception
def _WaitForInspectorToGoAway(self):
self._websocket.Disconnect()
raw_input('The connection to Chrome was lost to the inspector ui.\n'
'Please close the inspector and press enter to resume '
'Telemetry run...')
raise exceptions.DevtoolsTargetCrashException(
self.app, 'Devtool connection with the browser was interrupted due to '
'the opening of an inspector.')
def _ConvertExceptionFromInspectorWebsocket(self, error):
"""Converts an Exception from inspector_websocket.
This method always raises a Telemetry exception. It appends debugging
information. The exact exception raised depends on |error|.
Args:
error: An instance of socket.error or websocket.WebSocketException.
Raises:
exceptions.TimeoutException: A timeout occurred.
exceptions.DevtoolsTargetCrashException: On any other error, the most
likely explanation is that the devtool's target crashed.
"""
if isinstance(error, websocket.WebSocketTimeoutException):
new_error = exceptions.TimeoutException()
new_error.AddDebuggingMessage(exceptions.AppCrashException(
self.app, 'The app is probably crashed:\n'))
else:
new_error = exceptions.DevtoolsTargetCrashException(self.app)
original_error_msg = 'Original exception:\n' + str(error)
new_error.AddDebuggingMessage(original_error_msg)
self._AddDebuggingInformation(new_error)
raise new_error, None, sys.exc_info()[2]
def _AddDebuggingInformation(self, error):
"""Adds debugging information to error.
Args:
error: An instance of exceptions.Error.
"""
if self.IsInspectable():
msg = (
'Received a socket error in the browser connection and the tab '
'still exists. The operation probably timed out.'
)
else:
msg = (
'Received a socket error in the browser connection and the tab no '
'longer exists. The tab probably crashed.'
)
error.AddDebuggingMessage(msg)
error.AddDebuggingMessage('Debugger url: %s' % self.debugger_url)
@_HandleInspectorWebSocketExceptions
def _EvaluateJavaScript(self, expression, context_id, timeout):
return self._runtime.Evaluate(expression, context_id, timeout)
@_HandleInspectorWebSocketExceptions
def CollectGarbage(self):
self._page.CollectGarbage()
|
bsd-3-clause
| -3,750,426,105,838,133,000
| 35.821782
| 80
| 0.703469
| false
| 4.352762
| false
| false
| false
|
dyzajash/scanlation_cms
|
scanlation_cms/app.py
|
1
|
3430
|
# -*- coding: utf-8 -*-
"""The app module, containing the app factory function."""
from flask import Flask, render_template, request, send_from_directory
from flask.ext.principal import RoleNeed, UserNeed, identity_loaded
from flask_login import current_user
from scanlation_cms import api, panel, public, user
from scanlation_cms.assets import assets
from scanlation_cms.extensions import (babel, bcrypt, cache, db, debug_toolbar,
flask_log, img_resize, login_manager,
migrate, principal)
from scanlation_cms.settings import LANGUAGES, Config, ProdConfig
from scanlation_cms.utils import RegexConverter
def create_app(config_object=ProdConfig):
"""An application factory.
:param config_object: The configuration object to use.
"""
app = Flask(__name__)
app.config.from_object(config_object)
register_extensions(app)
register_blueprints(app)
register_errorhandlers(app)
identity_loaded.connect(on_identity_loaded, app, False)
register_special_routes(app)
return app
def register_extensions(app):
"""Register Flask extensions."""
assets.init_app(app)
bcrypt.init_app(app)
cache.init_app(app)
db.init_app(app)
login_manager.init_app(app)
principal.init_app(app)
debug_toolbar.init_app(app)
flask_log.init_app(app)
migrate.init_app(app, db)
img_resize.init_app(app)
babel.init_app(app)
babel.localeselector(get_locale)
return None
def register_blueprints(app):
"""Register Flask blueprints."""
app.register_blueprint(public.views.blueprint)
app.register_blueprint(user.views.blueprint)
app.register_blueprint(panel.views.blueprint)
app.register_blueprint(api.views.blueprint)
return None
def register_errorhandlers(app):
"""Register error handlers."""
def render_error(error):
"""Render error template."""
# If a HTTPException, pull the `code` attribute; default to 500
error_code = getattr(error, 'code', 500)
return render_template('errors/{0}.html'.format(error_code)), error_code
for errcode in [401, 403, 404, 500]:
app.errorhandler(errcode)(render_error)
return None
def register_special_routes(app):
"""Register special app routes."""
app.url_map.converters['regex'] = RegexConverter
if app.config['ENV'] != 'prod':
app.add_url_rule(
'/uploads/<regex("([\w\d_/-]+)?.(?:jpe?g|gif|png)"):filename>',
'uploaded_file',
uploaded_file
)
return None
def on_identity_loaded(sender, identity):
"""Flask-Principal signal handler."""
# Set the identity user object
identity.user = current_user
# Add the UserNeed to the identity
if hasattr(current_user, 'get_id'):
identity.provides.add(UserNeed(current_user.get_id))
# Assuming the User model has a list of roles, update the
# identity with the roles that the user provides
if hasattr(current_user, 'roles'):
if current_user.roles:
for role in current_user.roles:
identity.provides.add(RoleNeed(role.name))
def uploaded_file(filename):
"""Sample upload file handler for development."""
return send_from_directory(Config.UPLOADS_DIR, filename)
def get_locale():
"""Get request locale."""
return request.accept_languages.best_match(LANGUAGES.keys())
|
bsd-3-clause
| 9,077,521,675,694,444,000
| 31.666667
| 80
| 0.669971
| false
| 3.853933
| true
| false
| false
|
Panagiotis-Kon/empower-runtime
|
empower/vbsp/vbspconnection.py
|
1
|
15120
|
#!/usr/bin/env python3
#
# Copyright (c) 2016 Supreeth Herle
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""VBSP Connection."""
import time
import tornado.ioloop
import socket
import sys
from protobuf_to_dict import protobuf_to_dict
from empower.vbsp import EMAGE_VERSION
from empower.vbsp import PRT_UE_JOIN
from empower.vbsp import PRT_UE_LEAVE
from empower.vbsp import PRT_VBSP_HELLO
from empower.vbsp import PRT_VBSP_BYE
from empower.vbsp import PRT_VBSP_REGISTER
from empower.vbsp import PRT_VBSP_TRIGGER_EVENT
from empower.vbsp import PRT_VBSP_AGENT_SCHEDULED_EVENT
from empower.vbsp import PRT_VBSP_SINGLE_EVENT
from empower.vbsp.messages import main_pb2
from empower.vbsp.messages import configs_pb2
from empower.core.utils import hex_to_ether
from empower.core.utils import ether_to_hex
from empower.core.ue import UE
from empower.main import RUNTIME
import empower.logger
LOG = empower.logger.get_logger()
def create_header(t_id, b_id, header):
"""Create message header."""
if not header:
LOG.error("header parameter is None")
header.vers = EMAGE_VERSION
# Set the transaction identifier (module id).
header.t_id = t_id
# Set the Base station identifier.
header.b_id = b_id
# Start the sequence number for messages from zero.
header.seq = 0
def serialize_message(message):
"""Serialize message."""
if not message:
LOG.error("message parameter is None")
return None
return message.SerializeToString()
def deserialize_message(serialized_data):
"""De-Serialize message."""
if not serialized_data:
LOG.error("Received serialized data is None")
return None
msg = main_pb2.emage_msg()
msg.ParseFromString(serialized_data)
return msg
class VBSPConnection(object):
"""VBSP Connection.
Represents a connection to a ENB (EUTRAN Base Station) using
the VBSP Protocol. One VBSPConnection object is created for every
ENB in the network. The object implements the logic for handling
incoming messages. The currently supported messages are:
Attributes:
stream: The stream object used to talk with the ENB.
address: The connection source address, i.e. the ENB IP address.
server: Pointer to the server object.
vbs: Pointer to a VBS object.
"""
def __init__(self, stream, addr, server):
self.stream = stream
self.stream.set_nodelay(True)
self.addr = addr
self.server = server
self.vbs = None
self.seq = 0
self.stream.set_close_callback(self._on_disconnect)
self.__buffer = b''
self._hb_interval_ms = 500
self._hb_worker = tornado.ioloop.PeriodicCallback(self._heartbeat_cb,
self._hb_interval_ms)
self.endian = sys.byteorder
self._hb_worker.start()
self._wait()
def to_dict(self):
"""Return dict representation of object."""
return self.addr
def _heartbeat_cb(self):
"""Check if connection is still active."""
if self.vbs and not self.stream.closed():
timeout = (self.vbs.period / 1000) * 3
if (self.vbs.last_seen_ts + timeout) < time.time():
LOG.info('Client inactive %s at %r', self.vbs.addr, self.addr)
self.stream.close()
def stream_send(self, message):
"""Send message."""
# Update the sequence number of the messages
message.head.seq = self.seq + 1
size = message.ByteSize()
print(message.__str__())
size_bytes = (socket.htonl(size)).to_bytes(4, byteorder=self.endian)
send_buff = serialize_message(message)
buff = size_bytes + send_buff
if buff is None:
LOG.error("errno %u occured")
self.stream.write(buff)
def _on_read(self, line):
""" Appends bytes read from socket to a buffer. Once the full packet
has been read the parser is invoked and the buffers is cleared. The
parsed packet is then passed to the suitable method or dropped if the
packet type in unknown. """
self.__buffer = b''
if line is not None:
self.__buffer = self.__buffer + line
if len(line) == 4:
temp_size = int.from_bytes(line, byteorder=self.endian)
size = socket.ntohl(int(temp_size))
self.stream.read_bytes(size, self._on_read)
return
deserialized_msg = deserialize_message(line)
# Update the sequency number from received message
self.seq = deserialized_msg.head.seq
print(deserialized_msg.__str__())
self._trigger_message(deserialized_msg)
self._wait()
def _trigger_message(self, deserialized_msg):
event_type = deserialized_msg.WhichOneof("event_types")
if event_type == PRT_VBSP_SINGLE_EVENT:
msg_type = deserialized_msg.se.WhichOneof("events")
elif event_type == PRT_VBSP_AGENT_SCHEDULED_EVENT:
msg_type = deserialized_msg.sche.WhichOneof("events")
elif event_type == PRT_VBSP_TRIGGER_EVENT:
msg_type = deserialized_msg.te.WhichOneof("events")
else:
LOG.error("Unknown message event type %s", event_type)
if not msg_type or msg_type not in self.server.pt_types:
LOG.error("Unknown message type %s", msg_type)
return
if msg_type != PRT_VBSP_HELLO and not self.vbs:
return
handler_name = "_handle_%s" % self.server.pt_types[msg_type]
if hasattr(self, handler_name):
handler = getattr(self, handler_name)
handler(deserialized_msg)
if msg_type in self.server.pt_types_handlers:
for handler in self.server.pt_types_handlers[msg_type]:
handler(deserialized_msg)
def _handle_hello(self, main_msg):
"""Handle an incoming HELLO message.
Args:
main_msg, a emage_msg containing HELLO message
Returns:
None
"""
enb_id = main_msg.head.b_id
vbs_id = hex_to_ether(enb_id)
try:
vbs = RUNTIME.vbses[vbs_id]
except KeyError:
LOG.error("Hello from unknown VBS (%s)", (vbs_id))
return
LOG.info("Hello from %s VBS %s seq %u", self.addr[0], vbs.addr,
main_msg.head.seq)
# New connection
if not vbs.connection:
# set pointer to pnfdev object
self.vbs = vbs
# set connection
vbs.connection = self
# request registered UEs
self.send_UEs_id_req()
# generate register message
self.send_register_message_to_self()
# Update VBSP params
vbs.period = main_msg.se.mHello.repl.period
vbs.last_seen = main_msg.head.seq
vbs.last_seen_ts = time.time()
def _handle_UEs_id_repl(self, main_msg):
"""Handle an incoming UEs ID reply.
Args:
message, a emage_msg containing UE IDs (RNTIs)
Returns:
None
"""
active_ues = {}
inactive_ues = {}
event_type = main_msg.WhichOneof("event_types")
msg = protobuf_to_dict(main_msg)
ues_id_msg_repl = msg[event_type]["mUEs_id"]["repl"]
if ues_id_msg_repl["status"] != configs_pb2.CREQS_SUCCESS:
return
# List of active UEs
if "active_ue_id" in ues_id_msg_repl:
for ue in ues_id_msg_repl["active_ue_id"]:
active_ues[(self.vbs.addr, ue["rnti"])] = {}
if "imsi" in ue:
active_ues[(self.vbs.addr, ue["rnti"])]["imsi"] = ue["imsi"]
else:
active_ues[(self.vbs.addr, ue["rnti"])]["imsi"] = None
if "plmn_id" in ue:
active_ues[(self.vbs.addr, ue["rnti"])]["plmn_id"] = \
ue["plmn_id"]
else:
active_ues[(self.vbs.addr, ue["rnti"])]["plmn_id"] = None
# List of inactive UEs
if "inactive_ue_id" in ues_id_msg_repl:
for ue in ues_id_msg_repl["inactive_ue_id"]:
inactive_ues[(self.vbs.addr, ue["rnti"])] = {}
if "imsi" in ue:
inactive_ues[(self.vbs.addr, ue["rnti"])]["imsi"] = \
ue["imsi"]
else:
inactive_ues[(self.vbs.addr, ue["rnti"])]["imsi"] = None
if "plmn_id" in ue:
inactive_ues[(self.vbs.addr, ue["rnti"])]["plmn_id"] = \
ue["plmn_id"]
else:
inactive_ues[(self.vbs.addr, ue["rnti"])]["plmn_id"] = None
for vbs_id, rnti in active_ues.keys():
ue_id = (self.vbs.addr, rnti)
if ue_id not in RUNTIME.ues:
new_ue = UE(ue_id, ue_id[1], self.vbs)
RUNTIME.ues[ue_id] = new_ue
ue = RUNTIME.ues[ue_id]
imsi = active_ues[ue_id]["imsi"]
plmn_id = int(active_ues[ue_id]["plmn_id"])
# Setting IMSI of UE
ue.imsi = imsi
if not ue.plmn_id and plmn_id:
# Setting tenant
ue.tenant = RUNTIME.load_tenant_by_plmn_id(plmn_id)
if ue.tenant:
# Adding UE to tenant
LOG.info("Adding %s to tenant %s", ue.addr,
ue.tenant.plmn_id)
ue.tenant.ues[ue.addr] = ue
# Raise UE join
self.server.send_ue_join_message_to_self(ue)
# Create a trigger for reporting RRC measurements config.
from empower.ue_confs.ue_rrc_meas_confs import ue_rrc_meas_confs
conf_req = {
"event_type": "trigger"
}
ue_rrc_meas_confs(tenant_id=ue.tenant.tenant_id,
vbs=ue.vbs.addr,
ue=ue.rnti,
conf_req=conf_req)
if ue.plmn_id and not plmn_id:
# Raise UE leave
self.server.send_ue_leave_message_to_self(ue)
# Removing UE from tenant
LOG.info("Removing %s from tenant %s", ue.addr,
ue.tenant.plmn_id)
del ue.tenant.ues[ue.addr]
# Resetting tenant
ue.tenant = None
existing_ues = []
existing_ues.extend(RUNTIME.ues.keys())
for ue_addr in existing_ues:
if ue_addr not in active_ues:
RUNTIME.remove_ue(ue_addr)
def _handle_rrc_meas_conf_repl(self, main_msg):
"""Handle an incoming UE's RRC Measurements configuration reply.
Args:
message, a message containing RRC Measurements configuration in UE
Returns:
None
"""
event_type = main_msg.WhichOneof("event_types")
msg = protobuf_to_dict(main_msg)
rrc_m_conf_repl = msg[event_type]["mUE_rrc_meas_conf"]["repl"]
rnti = rrc_m_conf_repl["rnti"]
ue_id = (self.vbs.addr, rnti)
if ue_id not in RUNTIME.ues:
return
ue = RUNTIME.ues[ue_id]
if rrc_m_conf_repl["status"] != configs_pb2.CREQS_SUCCESS:
return
del rrc_m_conf_repl["rnti"]
del rrc_m_conf_repl["status"]
if "ue_rrc_state" in rrc_m_conf_repl:
ue.rrc_state = rrc_m_conf_repl["ue_rrc_state"]
del rrc_m_conf_repl["ue_rrc_state"]
if "capabilities" in rrc_m_conf_repl:
ue.capabilities = rrc_m_conf_repl["capabilities"]
del rrc_m_conf_repl["capabilities"]
ue.rrc_meas_config = rrc_m_conf_repl
def send_UEs_id_req(self):
""" Send request for UEs ID registered in VBS """
ues_id_req = main_pb2.emage_msg()
enb_id = ether_to_hex(self.vbs.addr)
# Transaction identifier is zero by default.
create_header(0, enb_id, ues_id_req.head)
# Creating a trigger message to fetch UE RNTIs
trigger_msg = ues_id_req.te
trigger_msg.action = main_pb2.EA_ADD
UEs_id_msg = trigger_msg.mUEs_id
UEs_id_req_msg = UEs_id_msg.req
UEs_id_req_msg.dummy = 1
LOG.info("Sending UEs request to VBS %s (%u)",
self.vbs.addr, enb_id)
self.stream_send(ues_id_req)
def send_rrc_meas_conf_req(self, ue):
""" Sends a request for RRC measurements configuration of UE """
rrc_m_conf_req = main_pb2.emage_msg()
enb_id = ether_to_hex(self.vbs.addr)
# Transaction identifier is zero by default.
create_header(0, enb_id, rrc_m_conf_req.head)
# Creating a trigger message to fetch UE RNTIs
trigger_msg = rrc_m_conf_req.te
trigger_msg.action = main_pb2.EA_ADD
rrc_m_conf_msg = trigger_msg.mUE_rrc_meas_conf
rrc_m_conf_req_msg = rrc_m_conf_msg.req
rrc_m_conf_req_msg.rnti = ue.rnti
LOG.info("Sending UEs RRC measurement config request to VBS %s (%u)",
self.vbs.addr, enb_id)
self.stream_send(rrc_m_conf_req)
def _wait(self):
""" Wait for incoming packets on signalling channel """
self.stream.read_bytes(4, self._on_read)
def _on_disconnect(self):
"""Handle VBSP disconnection."""
if not self.vbs:
return
LOG.info("VBS disconnected: %s", self.vbs.addr)
# remove hosted ues
for addr in list(RUNTIME.ues.keys()):
ue = RUNTIME.ues[addr]
if ue.vbs == self.vbs:
RUNTIME.remove_ue(ue.addr)
# reset state
self.vbs.last_seen = 0
self.vbs.connection = None
self.vbs.ues = {}
self.vbs.period = 0
self.vbs = None
def send_bye_message_to_self(self):
"""Send a unsollicited BYE message to self."""
for handler in self.server.pt_types_handlers[PRT_VBSP_BYE]:
handler(self.vbs)
def send_register_message_to_self(self):
"""Send a REGISTER message to self."""
for handler in self.server.pt_types_handlers[PRT_VBSP_REGISTER]:
handler(self.vbs)
|
apache-2.0
| -7,264,704,974,746,397,000
| 30.565762
| 84
| 0.56164
| false
| 3.585487
| true
| false
| false
|
OmkarPathak/pygorithm
|
pygorithm/dynamic_programming/lis.py
|
1
|
1439
|
"""
Author: Omkar Pathak
Created At: 25th August 2017
"""
import inspect
def longest_increasing_subsequence(_list):
"""
The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a
given sequence such that all elements of the subsequence are sorted in increasing order. For example,
the length of LIS for [10, 22, 9, 33, 21, 50, 41, 60, 80] is 6 and LIS is [10, 22, 33, 50, 60, 80].
:param _list: an array of elements
:return: returns a tuple of maximum length of lis and an array of the elements of lis
"""
# Initialize list with some value
lis = [1] * len(_list)
# list for storing the elements in an lis
elements = [0] * len(_list)
# Compute optimized LIS values in bottom up manner
for i in range(1, len(_list)):
for j in range(0, i):
if _list[i] > _list[j] and lis[i] < lis[j] + 1:
lis[i] = lis[j]+1
elements[i] = j
# find the maximum of the whole list and get its index in idx
maximum = max(lis)
idx = lis.index(maximum)
# for printing the elements later
seq = [_list[idx]]
while idx != elements[idx]:
idx = elements[idx]
seq.append(_list[idx])
return (maximum, seq[::-1])
def get_code():
"""
returns the code for the longest_increasing_subsequence function
"""
return inspect.getsource(longest_increasing_subsequence)
|
mit
| 7,613,543,510,586,332,000
| 30.977778
| 106
| 0.628909
| false
| 3.544335
| false
| false
| false
|
CCI-MOC/nova
|
nova/image/glance.py
|
1
|
26640
|
# Copyright 2010 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Implementation of an image service that uses Glance as the backend."""
from __future__ import absolute_import
import copy
import itertools
import random
import sys
import time
import glanceclient
import glanceclient.exc
from oslo_config import cfg
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_service import sslutils
from oslo_utils import excutils
from oslo_utils import netutils
from oslo_utils import timeutils
import six
from six.moves import range
import six.moves.urllib.parse as urlparse
from nova import exception
from nova.i18n import _LE, _LI, _LW
import nova.image.download as image_xfers
glance_opts = [
cfg.StrOpt('host',
default='$my_ip',
help='Default glance hostname or IP address'),
cfg.IntOpt('port',
default=9292,
min=1,
max=65535,
help='Default glance port'),
cfg.StrOpt('protocol',
default='http',
choices=('http', 'https'),
help='Default protocol to use when connecting to glance. '
'Set to https for SSL.'),
cfg.ListOpt('api_servers',
help='A list of the glance api servers available to nova. '
'Prefix with https:// for ssl-based glance api servers. '
'([hostname|ip]:port)'),
cfg.BoolOpt('api_insecure',
default=False,
help='Allow to perform insecure SSL (https) requests to '
'glance'),
cfg.IntOpt('num_retries',
default=0,
help='Number of retries when uploading / downloading an image '
'to / from glance.'),
cfg.ListOpt('allowed_direct_url_schemes',
default=[],
help='A list of url scheme that can be downloaded directly '
'via the direct_url. Currently supported schemes: '
'[file].'),
]
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
CONF.register_opts(glance_opts, 'glance')
CONF.import_opt('auth_strategy', 'nova.api.auth')
CONF.import_opt('my_ip', 'nova.netconf')
def generate_glance_url():
"""Generate the URL to glance."""
glance_host = CONF.glance.host
if netutils.is_valid_ipv6(glance_host):
glance_host = '[%s]' % glance_host
return "%s://%s:%d" % (CONF.glance.protocol, glance_host,
CONF.glance.port)
def generate_image_url(image_ref):
"""Generate an image URL from an image_ref."""
return "%s/images/%s" % (generate_glance_url(), image_ref)
def _parse_image_ref(image_href):
"""Parse an image href into composite parts.
:param image_href: href of an image
:returns: a tuple of the form (image_id, host, port)
:raises ValueError
"""
o = urlparse.urlparse(image_href)
port = o.port or 80
host = o.netloc.rsplit(':', 1)[0]
image_id = o.path.split('/')[-1]
use_ssl = (o.scheme == 'https')
return (image_id, host, port, use_ssl)
def generate_identity_headers(context, status='Confirmed'):
return {
'X-Auth-Token': getattr(context, 'auth_token', None),
'X-User-Id': getattr(context, 'user', None),
'X-Tenant-Id': getattr(context, 'tenant', None),
'X-Roles': ','.join(context.roles),
'X-Identity-Status': status,
}
def _create_glance_client(context, host, port, use_ssl, version=1):
"""Instantiate a new glanceclient.Client object."""
params = {}
if use_ssl:
scheme = 'https'
# https specific params
params['insecure'] = CONF.glance.api_insecure
params['ssl_compression'] = False
sslutils.is_enabled(CONF)
if CONF.ssl.cert_file:
params['cert_file'] = CONF.ssl.cert_file
if CONF.ssl.key_file:
params['key_file'] = CONF.ssl.key_file
if CONF.ssl.ca_file:
params['cacert'] = CONF.ssl.ca_file
else:
scheme = 'http'
if CONF.auth_strategy == 'keystone':
# NOTE(isethi): Glanceclient <= 0.9.0.49 accepts only
# keyword 'token', but later versions accept both the
# header 'X-Auth-Token' and 'token'
params['token'] = context.auth_token
params['identity_headers'] = generate_identity_headers(context)
if netutils.is_valid_ipv6(host):
# if so, it is ipv6 address, need to wrap it with '[]'
host = '[%s]' % host
endpoint = '%s://%s:%s' % (scheme, host, port)
#
# from keystoneauth1 import identity
# from keystoneauth1 import session as ks
# from keystoneauth1.identity.v3.k2k import Keystone2Keystone
#
# if hasattr(context, 'blabla_service_provider'):
# idp_auth = identity.Token(auth_url='http://localhost:35357',
# token=context.auth_token,
# project_id=context.tenant)
#
# auth = Keystone2Keystone(idp_auth,
# context.service_provider,
# project_name='admin',
# project_domain_id='default')
#
# session = ks.Session(auth=auth)
# return glanceclient.Client(str(version), session=session)
return glanceclient.Client(str(version), endpoint, **params)
def get_api_servers():
"""Shuffle a list of CONF.glance.api_servers and return an iterator
that will cycle through the list, looping around to the beginning
if necessary.
"""
api_servers = []
configured_servers = (['%s:%s' % (CONF.glance.host, CONF.glance.port)]
if CONF.glance.api_servers is None
else CONF.glance.api_servers)
for api_server in configured_servers:
if '//' not in api_server:
api_server = 'http://' + api_server
o = urlparse.urlparse(api_server)
port = o.port or 80
host = o.netloc.rsplit(':', 1)[0]
if host[0] == '[' and host[-1] == ']':
host = host[1:-1]
use_ssl = (o.scheme == 'https')
api_servers.append((host, port, use_ssl))
random.shuffle(api_servers)
return itertools.cycle(api_servers)
class GlanceClientWrapper(object):
"""Glance client wrapper class that implements retries."""
def __init__(self, context=None, host=None, port=None, use_ssl=False,
version=1):
if host is not None:
self.client = self._create_static_client(context,
host, port,
use_ssl, version)
else:
self.client = None
self.api_servers = None
def _create_static_client(self, context, host, port, use_ssl, version):
"""Create a client that we'll use for every call."""
self.host = host
self.port = port
self.use_ssl = use_ssl
self.version = version
return _create_glance_client(context,
self.host, self.port,
self.use_ssl, self.version)
def _create_onetime_client(self, context, version):
"""Create a client that will be used for one call."""
if self.api_servers is None:
self.api_servers = get_api_servers()
self.host, self.port, self.use_ssl = next(self.api_servers)
return _create_glance_client(context,
self.host, self.port,
self.use_ssl, version)
def call(self, context, version, method, *args, **kwargs):
"""Call a glance client method. If we get a connection error,
retry the request according to CONF.glance.num_retries.
"""
retry_excs = (glanceclient.exc.ServiceUnavailable,
glanceclient.exc.InvalidEndpoint,
glanceclient.exc.CommunicationError)
retries = CONF.glance.num_retries
if retries < 0:
LOG.warning(_LW("Treating negative config value (%(retries)s) for "
"'glance.num_retries' as 0."),
{'retries': retries})
retries = 0
num_attempts = retries + 1
for attempt in range(1, num_attempts + 1):
client = self.client or self._create_onetime_client(context,
version)
try:
return getattr(client.images, method)(*args, **kwargs)
except retry_excs as e:
host = self.host
port = self.port
if attempt < num_attempts:
extra = "retrying"
else:
extra = 'done trying'
LOG.exception(_LE("Error contacting glance server "
"'%(host)s:%(port)s' for '%(method)s', "
"%(extra)s."),
{'host': host, 'port': port,
'method': method, 'extra': extra})
if attempt == num_attempts:
raise exception.GlanceConnectionFailed(
host=host, port=port, reason=six.text_type(e))
time.sleep(1)
class GlanceImageService(object):
"""Provides storage and retrieval of disk image objects within Glance."""
def __init__(self, client=None):
self._client = client or GlanceClientWrapper()
# NOTE(jbresnah) build the table of download handlers at the beginning
# so that operators can catch errors at load time rather than whenever
# a user attempts to use a module. Note this cannot be done in glance
# space when this python module is loaded because the download module
# may require configuration options to be parsed.
self._download_handlers = {}
download_modules = image_xfers.load_transfer_modules()
for scheme, mod in six.iteritems(download_modules):
if scheme not in CONF.glance.allowed_direct_url_schemes:
continue
try:
self._download_handlers[scheme] = mod.get_download_handler()
except Exception as ex:
LOG.error(_LE('When loading the module %(module_str)s the '
'following error occurred: %(ex)s'),
{'module_str': str(mod), 'ex': ex})
def detail(self, context, **kwargs):
"""Calls out to Glance for a list of detailed image information."""
params = _extract_query_params(kwargs)
try:
images = self._client.call(context, 1, 'list', **params)
except Exception:
_reraise_translated_exception()
_images = []
for image in images:
if _is_image_available(context, image):
_images.append(_translate_from_glance(image))
return _images
def show(self, context, image_id, include_locations=False,
show_deleted=True):
"""Returns a dict with image data for the given opaque image id.
:param context: The context object to pass to image client
:param image_id: The UUID of the image
:param include_locations: (Optional) include locations in the returned
dict of information if the image service API
supports it. If the image service API does
not support the locations attribute, it will
still be included in the returned dict, as an
empty list.
:param show_deleted: (Optional) show the image even the status of
image is deleted.
"""
version = 1
if include_locations:
version = 2
try:
image = self._client.call(context, version, 'get', image_id)
except Exception:
_reraise_translated_image_exception(image_id)
if not show_deleted and getattr(image, 'deleted', False):
raise exception.ImageNotFound(image_id=image_id)
if not _is_image_available(context, image):
raise exception.ImageNotFound(image_id=image_id)
image = _translate_from_glance(image,
include_locations=include_locations)
if include_locations:
locations = image.get('locations', None) or []
du = image.get('direct_url', None)
if du:
locations.append({'url': du, 'metadata': {}})
image['locations'] = locations
return image
def _get_transfer_module(self, scheme):
try:
return self._download_handlers[scheme]
except KeyError:
return None
except Exception:
LOG.error(_LE("Failed to instantiate the download handler "
"for %(scheme)s"), {'scheme': scheme})
return
def download(self, context, image_id, data=None, dst_path=None):
"""Calls out to Glance for data and writes data."""
if CONF.glance.allowed_direct_url_schemes and dst_path is not None:
image = self.show(context, image_id, include_locations=True)
for entry in image.get('locations', []):
loc_url = entry['url']
loc_meta = entry['metadata']
o = urlparse.urlparse(loc_url)
xfer_mod = self._get_transfer_module(o.scheme)
if xfer_mod:
try:
xfer_mod.download(context, o, dst_path, loc_meta)
LOG.info(_LI("Successfully transferred "
"using %s"), o.scheme)
return
except Exception:
LOG.exception(_LE("Download image error"))
try:
image_chunks = self._client.call(context, 1, 'data', image_id)
except Exception:
_reraise_translated_image_exception(image_id)
close_file = False
if data is None and dst_path:
data = open(dst_path, 'wb')
close_file = True
if data is None:
return image_chunks
else:
try:
for chunk in image_chunks:
data.write(chunk)
except Exception as ex:
with excutils.save_and_reraise_exception():
LOG.error(_LE("Error writing to %(path)s: %(exception)s"),
{'path': dst_path, 'exception': ex})
finally:
if close_file:
data.close()
def create(self, context, image_meta, data=None):
"""Store the image data and return the new image object."""
sent_service_image_meta = _translate_to_glance(image_meta)
if data:
sent_service_image_meta['data'] = data
try:
recv_service_image_meta = self._client.call(
context, 1, 'create', **sent_service_image_meta)
except glanceclient.exc.HTTPException:
_reraise_translated_exception()
return _translate_from_glance(recv_service_image_meta)
def update(self, context, image_id, image_meta, data=None,
purge_props=True):
"""Modify the given image with the new data."""
image_meta = _translate_to_glance(image_meta)
image_meta['purge_props'] = purge_props
# NOTE(bcwaldon): id is not an editable field, but it is likely to be
# passed in by calling code. Let's be nice and ignore it.
image_meta.pop('id', None)
if data:
image_meta['data'] = data
try:
image_meta = self._client.call(context, 1, 'update',
image_id, **image_meta)
except Exception:
_reraise_translated_image_exception(image_id)
else:
return _translate_from_glance(image_meta)
def delete(self, context, image_id):
"""Delete the given image.
:raises: ImageNotFound if the image does not exist.
:raises: NotAuthorized if the user is not an owner.
:raises: ImageNotAuthorized if the user is not authorized.
"""
try:
self._client.call(context, 1, 'delete', image_id)
except glanceclient.exc.NotFound:
raise exception.ImageNotFound(image_id=image_id)
except glanceclient.exc.HTTPForbidden:
raise exception.ImageNotAuthorized(image_id=image_id)
return True
def _extract_query_params(params):
_params = {}
accepted_params = ('filters', 'marker', 'limit',
'page_size', 'sort_key', 'sort_dir')
for param in accepted_params:
if params.get(param):
_params[param] = params.get(param)
# ensure filters is a dict
_params.setdefault('filters', {})
# NOTE(vish): don't filter out private images
_params['filters'].setdefault('is_public', 'none')
return _params
def _is_image_available(context, image):
"""Check image availability.
This check is needed in case Nova and Glance are deployed
without authentication turned on.
"""
# The presence of an auth token implies this is an authenticated
# request and we need not handle the noauth use-case.
if hasattr(context, 'auth_token') and context.auth_token:
return True
def _is_image_public(image):
# NOTE(jaypipes) V2 Glance API replaced the is_public attribute
# with a visibility attribute. We do this here to prevent the
# glanceclient for a V2 image model from throwing an
# exception from warlock when trying to access an is_public
# attribute.
if hasattr(image, 'visibility'):
return str(image.visibility).lower() == 'public'
else:
return image.is_public
if context.is_admin or _is_image_public(image):
return True
properties = image.properties
if context.project_id and ('owner_id' in properties):
return str(properties['owner_id']) == str(context.project_id)
if context.project_id and ('project_id' in properties):
return str(properties['project_id']) == str(context.project_id)
try:
user_id = properties['user_id']
except KeyError:
return False
return str(user_id) == str(context.user_id)
def _translate_to_glance(image_meta):
image_meta = _convert_to_string(image_meta)
image_meta = _remove_read_only(image_meta)
return image_meta
def _translate_from_glance(image, include_locations=False):
image_meta = _extract_attributes(image,
include_locations=include_locations)
image_meta = _convert_timestamps_to_datetimes(image_meta)
image_meta = _convert_from_string(image_meta)
return image_meta
def _convert_timestamps_to_datetimes(image_meta):
"""Returns image with timestamp fields converted to datetime objects."""
for attr in ['created_at', 'updated_at', 'deleted_at']:
if image_meta.get(attr):
image_meta[attr] = timeutils.parse_isotime(image_meta[attr])
return image_meta
# NOTE(bcwaldon): used to store non-string data in glance metadata
def _json_loads(properties, attr):
prop = properties[attr]
if isinstance(prop, six.string_types):
properties[attr] = jsonutils.loads(prop)
def _json_dumps(properties, attr):
prop = properties[attr]
if not isinstance(prop, six.string_types):
properties[attr] = jsonutils.dumps(prop)
_CONVERT_PROPS = ('block_device_mapping', 'mappings')
def _convert(method, metadata):
metadata = copy.deepcopy(metadata)
properties = metadata.get('properties')
if properties:
for attr in _CONVERT_PROPS:
if attr in properties:
method(properties, attr)
return metadata
def _convert_from_string(metadata):
return _convert(_json_loads, metadata)
def _convert_to_string(metadata):
return _convert(_json_dumps, metadata)
def _extract_attributes(image, include_locations=False):
# NOTE(hdd): If a key is not found, base.Resource.__getattr__() may perform
# a get(), resulting in a useless request back to glance. This list is
# therefore sorted, with dependent attributes as the end
# 'deleted_at' depends on 'deleted'
# 'checksum' depends on 'status' == 'active'
IMAGE_ATTRIBUTES = ['size', 'disk_format', 'owner',
'container_format', 'status', 'id',
'name', 'created_at', 'updated_at',
'deleted', 'deleted_at', 'checksum',
'min_disk', 'min_ram', 'is_public',
'direct_url', 'locations']
queued = getattr(image, 'status') == 'queued'
queued_exclude_attrs = ['disk_format', 'container_format']
include_locations_attrs = ['direct_url', 'locations']
output = {}
for attr in IMAGE_ATTRIBUTES:
if attr == 'deleted_at' and not output['deleted']:
output[attr] = None
elif attr == 'checksum' and output['status'] != 'active':
output[attr] = None
# image may not have 'name' attr
elif attr == 'name':
output[attr] = getattr(image, attr, None)
# NOTE(liusheng): queued image may not have these attributes and 'name'
elif queued and attr in queued_exclude_attrs:
output[attr] = getattr(image, attr, None)
# NOTE(mriedem): Only get location attrs if including locations.
elif attr in include_locations_attrs:
if include_locations:
output[attr] = getattr(image, attr, None)
# NOTE(mdorman): 'size' attribute must not be 'None', so use 0 instead
elif attr == 'size':
output[attr] = getattr(image, attr) or 0
else:
# NOTE(xarses): Anything that is caught with the default value
# will result in a additional lookup to glance for said attr.
# Notable attributes that could have this issue:
# disk_format, container_format, name, deleted, checksum
output[attr] = getattr(image, attr, None)
output['properties'] = getattr(image, 'properties', {})
return output
def _remove_read_only(image_meta):
IMAGE_ATTRIBUTES = ['status', 'updated_at', 'created_at', 'deleted_at']
output = copy.deepcopy(image_meta)
for attr in IMAGE_ATTRIBUTES:
if attr in output:
del output[attr]
return output
def _reraise_translated_image_exception(image_id):
"""Transform the exception for the image but keep its traceback intact."""
exc_type, exc_value, exc_trace = sys.exc_info()
new_exc = _translate_image_exception(image_id, exc_value)
six.reraise(new_exc, None, exc_trace)
def _reraise_translated_exception():
"""Transform the exception but keep its traceback intact."""
exc_type, exc_value, exc_trace = sys.exc_info()
new_exc = _translate_plain_exception(exc_value)
six.reraise(new_exc, None, exc_trace)
def _translate_image_exception(image_id, exc_value):
if isinstance(exc_value, (glanceclient.exc.Forbidden,
glanceclient.exc.Unauthorized)):
return exception.ImageNotAuthorized(image_id=image_id)
if isinstance(exc_value, glanceclient.exc.NotFound):
return exception.ImageNotFound(image_id=image_id)
if isinstance(exc_value, glanceclient.exc.BadRequest):
return exception.Invalid(six.text_type(exc_value))
return exc_value
def _translate_plain_exception(exc_value):
if isinstance(exc_value, (glanceclient.exc.Forbidden,
glanceclient.exc.Unauthorized)):
return exception.Forbidden(six.text_type(exc_value))
if isinstance(exc_value, glanceclient.exc.NotFound):
return exception.NotFound(six.text_type(exc_value))
if isinstance(exc_value, glanceclient.exc.BadRequest):
return exception.Invalid(six.text_type(exc_value))
return exc_value
def get_remote_image_service(context, image_href):
"""Create an image_service and parse the id from the given image_href.
The image_href param can be an href of the form
'http://example.com:9292/v1/images/b8b2c6f7-7345-4e2f-afa2-eedaba9cbbe3',
or just an id such as 'b8b2c6f7-7345-4e2f-afa2-eedaba9cbbe3'. If the
image_href is a standalone id, then the default image service is returned.
:param image_href: href that describes the location of an image
:returns: a tuple of the form (image_service, image_id)
"""
# NOTE(bcwaldon): If image_href doesn't look like a URI, assume its a
# standalone image ID
if '/' not in str(image_href):
image_service = get_default_image_service()
return image_service, image_href
try:
(image_id, glance_host, glance_port, use_ssl) = \
_parse_image_ref(image_href)
glance_client = GlanceClientWrapper(context=context,
host=glance_host, port=glance_port, use_ssl=use_ssl)
except ValueError:
raise exception.InvalidImageRef(image_href=image_href)
image_service = GlanceImageService(client=glance_client)
return image_service, image_id
def get_default_image_service():
return GlanceImageService()
class UpdateGlanceImage(object):
def __init__(self, context, image_id, metadata, stream):
self.context = context
self.image_id = image_id
self.metadata = metadata
self.image_stream = stream
def start(self):
image_service, image_id = (
get_remote_image_service(self.context, self.image_id))
image_service.update(self.context, image_id, self.metadata,
self.image_stream, purge_props=False)
|
apache-2.0
| -405,195,565,436,879,100
| 37.002853
| 79
| 0.589902
| false
| 4.143079
| false
| false
| false
|
steny138/SE3Borrow
|
home/decorator.py
|
1
|
1389
|
# -*- coding: utf-8 -*-
try:
from functools import wraps
except ImportError:
from django.utils.functional import wraps # Python 2.4 fallback.
from django.utils.decorators import available_attrs
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect
from django.contrib import messages
default_message = "您沒有管理者權限。"
def user_passes_test(test_func, message=default_message, redirect_url="/"):
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
decorated_view_func = login_required(request)
if not decorated_view_func.user.is_authenticated():
return decorated_view_func(request) # return redirect to signin
if not test_func(request.user):
messages.error(request, message)
return redirect(redirect_url)
return view_func(request, *args, **kwargs)
return _wrapped_view
return decorator
def super_login_required(view_func=None, message=default_message, redirect_url="/"):
super_login_func = user_passes_test(
lambda u: u.is_superuser,
message=message,
redirect_url=redirect_url
)
if view_func:
return super_login_func(view_func)
return super_login_func
|
apache-2.0
| -5,133,462,619,210,425,000
| 34.153846
| 84
| 0.665937
| false
| 3.894886
| false
| false
| false
|
opendatakosovo/bpo
|
utils/importer/import_idams.py
|
1
|
6870
|
# -*- coding: UTF-8 -*-
import csv
import os
import re
from datetime import datetime
from pymongo import MongoClient
import json
# Connect to defualt local instance of MongoClient
client = MongoClient()
# Get database and collection
db = client.bpo
collection = db.idams
def parse():
collection.remove({})
print "Importing Data"
dir_path = os.path.dirname(os.path.realpath(__file__))
count = 0
other_v_count = 0
for filename in os.listdir(dir_path + '/idams/'):
print filename
json_obj = None
if (filename.endswith(".json")):
with open(dir_path + '/idams/' + filename, 'rb') as jsonfile:
json_obj = json.load(jsonfile)
for elem in json_obj:
new_json = {}
if 'actors' in elem['_source']:
if len(elem['_source']['smart_tags']['smart_tags']) > 0 and \
elem['_source']['smart_tags']['smart_tags'][0] != '' and elem['_source']['smart_tags']['smart_tags'][0] =='Terrorism':
new_json['incident_date'] = datetime.strptime(elem['_source']['summary']['date'], '%Y-%m-%d')
new_json['violence_actor'] = elem['_source']['actors']['responders']
new_json['description'] = elem['_source']['summary']['description']
new_json['lat'] = elem['_source']['location_and_source']['latitude']
new_json['lon'] = elem['_source']['location_and_source']['longitude']
new_json['source'] = elem['_source']['location_and_source']['source_url']
new_json['violence_type'] = 'Violent Extremism'
if 'Islamic State of Iraq and Syria' in elem['_source']['actors']['instigators']:
new_json['responders'] = ['New-JMB']
else:
new_json['responders'] = elem['_source']['actors']['instigators']
new_json['causes'] = elem['_source']['causes_of_incident']['causes']
new_json['property_destroyed_type'] = []
new_json['injuries_count'] = 0
new_json['deaths_count'] = 0
new_json['property_destroyed_count'] = 0
if 'victims_and_perpetrators' in elem['_source']:
if len(elem['_source']['victims_and_perpetrators']) > 0:
if elem['_source']['victims_and_perpetrators'][0]['consequence'] == 'Death':
new_json['deaths_count'] = elem['_source']['victims_and_perpetrators'][0]['victims'][
'count']
elif elem['_source']['victims_and_perpetrators'][0]['consequence'] == 'Injury':
new_json['injuries_count'] = elem['_source']['victims_and_perpetrators'][0]['victims'][
'count']
elif elem['_source']['victims_and_perpetrators'][0][
'consequence'] == 'Private property damaged' or \
elem['_source']['victims_and_perpetrators'][0][
'consequence'] == 'Public property damaged':
new_json['property_destroyed_count'] = \
elem['_source']['victims_and_perpetrators'][0]['victims']['count']
new_json['division'] = elem['_source']['location_and_source']['division']
new_json['district'] = elem['_source']['location_and_source']['district']
new_json['upazila'] = elem['_source']['location_and_source']['upazila']
count = count + 1
elif elem['_source']['summary']['incident_type'] in ['Political dispute', 'Border incident', 'IED Attack', 'Arson attack', 'Mob Violence', 'Violent crime']:
new_json['incident_date'] = datetime.strptime(elem['_source']['summary']['date'], '%Y-%m-%d')
new_json['violence_actor'] = elem['_source']['actors']['responders']
new_json['description'] = elem['_source']['summary']['description']
new_json['lat'] = elem['_source']['location_and_source']['latitude']
new_json['lon'] = elem['_source']['location_and_source']['longitude']
new_json['source'] = elem['_source']['location_and_source']['source_url']
if elem['_source']['summary']['incident_type'] == 'Violent crime':
new_json['violence_type'] = 'Violent Crime - Homicides'
else:
new_json['violence_type'] = elem['_source']['summary']['incident_type']
if 'Islamic State of Iraq and Syria' in elem['_source']['actors']['instigators']:
new_json['responders'] = ['New-JMB']
else:
new_json['responders'] = elem['_source']['actors']['instigators']
new_json['causes'] = elem['_source']['causes_of_incident']['causes']
new_json['property_destroyed_type'] = []
new_json['injuries_count'] = 0
new_json['deaths_count'] = 0
new_json['property_destroyed_count'] = 0
if 'victims_and_perpetrators' in elem['_source']:
if len(elem['_source']['victims_and_perpetrators']) > 0:
if elem['_source']['victims_and_perpetrators'][0]['consequence'] == 'Death':
new_json['deaths_count'] = elem['_source']['victims_and_perpetrators'][0]['victims'][
'count']
elif elem['_source']['victims_and_perpetrators'][0]['consequence'] == 'Injury':
new_json['injuries_count'] = elem['_source']['victims_and_perpetrators'][0]['victims']['count']
elif elem['_source']['victims_and_perpetrators'][0]['consequence']=='Private property damaged' or elem['_source']['victims_and_perpetrators'][0]['consequence']=='Public property damaged':
new_json['property_destroyed_count'] = elem['_source']['victims_and_perpetrators'][0]['victims']['count']
new_json['division'] = elem['_source']['location_and_source']['division']
new_json['district'] = elem['_source']['location_and_source']['district']
new_json['upazila'] = elem['_source']['location_and_source']['upazila']
other_v_count = other_v_count + 1
else:
pass
if new_json:
collection.insert(new_json)
parse()
|
cc0-1.0
| -4,839,804,771,402,337,000
| 59.80531
| 215
| 0.496943
| false
| 4.178832
| false
| false
| false
|
cariaso/zebraguide
|
zebraguide/zebraguide.py
|
1
|
9159
|
#!/usr/bin/env python
import argparse
import Bio.SeqIO
import sys
def get_args():
parser = argparse.ArgumentParser(
description="""Make the BoulderIO formatter config file for primer3 to direct guide sequences against a reference.
Typical usage:
./zebraguide.py sample2.fasta | primer3_core -format_output
""",
epilog="cariaso@gmail.com Copyright 2016"
)
parser.add_argument('fasta',
help='fasta file of references and guides')
parser.add_argument('--size-limit', type=int, default=20,
help='cutoff length of references vs guides')
parser.add_argument('--out',
help='output filename, defaults to stdout')
parser.add_argument('--add', action='append', dest='primer3tags',
default=[],
help='Add these tags to each record')
args = parser.parse_args()
return args
def analyze(out, guide, ref, args=None):
guideseq = guide.seq.tostring().upper()
refseq = ref.seq.tostring().upper()
guidestartpos = refseq.find(guideseq)
if guidestartpos == -1:
out.write('COMMENT=%s not found in %s\n' % (guide.name, ref.name))
out.write('=\n')
return
guidendpos = guidestartpos + len(guide)
out.write('SEQUENCE_ID=%s-%s\n' % (guide.name, ref.name))
out.write('SEQUENCE_TEMPLATE=%s\n' % ref.seq.tostring())
out.write('SEQUENCE_TARGET=%s,%s\n' % (guidestartpos, guidendpos))
#out.write('PRIMER_THERMODYNAMIC_PARAMETERS_PATH=/usr/local/Cellar/primer3/2.3.6/share/primer3/primer3_config/\n')
out.write('PRIMER_EXPLAIN_FLAG=1\n')
if args:
for tag in args.primer3tags:
out.write('%s\n' % tag)
# out.write('PRIMER_FIRST_BASE_INDEX=1\n')
# out.write('PRIMER_THERMODYNAMIC_OLIGO_ALIGNMENT=1\n')
# out.write('PRIMER_THERMODYNAMIC_TEMPLATE_ALIGNMENT=0\n')
# out.write('PRIMER_PICK_LEFT_PRIMER=1\n')
# out.write('PRIMER_PICK_INTERNAL_OLIGO=0\n')
# out.write('PRIMER_PICK_RIGHT_PRIMER=1\n')
# out.write('PRIMER_LIBERAL_BASE=1\n')
# out.write('PRIMER_LIB_AMBIGUITY_CODES_CONSENSUS=0\n')
# out.write('PRIMER_LOWERCASE_MASKING=0\n')
# out.write('PRIMER_PICK_ANYWAY=1\n')
# out.write('PRIMER_EXPLAIN_FLAG=1\n')
# out.write('PRIMER_TASK=generic\n')
# out.write('PRIMER_MIN_QUALITY=0\n')
# out.write('PRIMER_MIN_END_QUALITY=0\n')
# out.write('PRIMER_QUALITY_RANGE_MIN=0\n')
# out.write('PRIMER_QUALITY_RANGE_MAX=100\n')
# out.write('PRIMER_MIN_SIZE=18\n')
# out.write('PRIMER_OPT_SIZE=20\n')
# out.write('PRIMER_MAX_SIZE=23\n')
# out.write('PRIMER_MIN_TM=57.0\n')
# out.write('PRIMER_OPT_TM=59.0\n')
# out.write('PRIMER_MAX_TM=62.0\n')
# out.write('PRIMER_PAIR_MAX_DIFF_TM=5.0\n')
# out.write('PRIMER_TM_FORMULA=1\n')
# out.write('PRIMER_PRODUCT_MIN_TM=-1000000.0\n')
# out.write('PRIMER_PRODUCT_OPT_TM=0.0\n')
# out.write('PRIMER_PRODUCT_MAX_TM=1000000.0\n')
# out.write('PRIMER_MIN_GC=30.0\n')
# out.write('PRIMER_OPT_GC_PERCENT=50.0\n')
# out.write('PRIMER_MAX_GC=70.0\n')
# out.write('PRIMER_PRODUCT_SIZE_RANGE=150-250 100-300 301-400 401-500 501-600 601-700 701-850 851-1000\n')
# out.write('PRIMER_NUM_RETURN=5\n')
# out.write('PRIMER_MAX_END_STABILITY=9.0\n')
# out.write('PRIMER_MAX_LIBRARY_MISPRIMING=12.00\n')
# out.write('PRIMER_PAIR_MAX_LIBRARY_MISPRIMING=20.00\n')
# out.write('PRIMER_MAX_TEMPLATE_MISPRIMING_TH=40.00\n')
# out.write('PRIMER_PAIR_MAX_TEMPLATE_MISPRIMING_TH=70.00\n')
# out.write('PRIMER_MAX_SELF_ANY_TH=45.0\n')
# out.write('PRIMER_MAX_SELF_END_TH=35.0\n')
# out.write('PRIMER_PAIR_MAX_COMPL_ANY_TH=45.0\n')
# out.write('PRIMER_PAIR_MAX_COMPL_END_TH=35.0\n')
# out.write('PRIMER_MAX_HAIRPIN_TH=24.0\n')
# out.write('PRIMER_MAX_TEMPLATE_MISPRIMING=12.00\n')
# out.write('PRIMER_PAIR_MAX_TEMPLATE_MISPRIMING=24.00\n')
# out.write('PRIMER_MAX_SELF_ANY=8.00\n')
# out.write('PRIMER_MAX_SELF_END=3.00\n')
# out.write('PRIMER_PAIR_MAX_COMPL_ANY=8.00\n')
# out.write('PRIMER_PAIR_MAX_COMPL_END=3.00\n')
# out.write('PRIMER_MAX_NS_ACCEPTED=0\n')
# out.write('PRIMER_MAX_POLY_X=4\n')
# out.write('PRIMER_INSIDE_PENALTY=-1.0\n')
# out.write('PRIMER_OUTSIDE_PENALTY=0\n')
# out.write('PRIMER_GC_CLAMP=0\n')
# out.write('PRIMER_MAX_END_GC=5\n')
# out.write('PRIMER_MIN_LEFT_THREE_PRIME_DISTANCE=3\n')
# out.write('PRIMER_MIN_RIGHT_THREE_PRIME_DISTANCE=3\n')
# out.write('PRIMER_MIN_5_PRIME_OVERLAP_OF_JUNCTION=7\n')
# out.write('PRIMER_MIN_3_PRIME_OVERLAP_OF_JUNCTION=4\n')
# out.write('PRIMER_SALT_MONOVALENT=50.0\n')
# out.write('PRIMER_SALT_CORRECTIONS=1\n')
# out.write('PRIMER_SALT_DIVALENT=1.5\n')
# out.write('PRIMER_DNTP_CONC=0.6\n')
# out.write('PRIMER_DNA_CONC=50.0\n')
# out.write('PRIMER_SEQUENCING_SPACING=500\n')
# out.write('PRIMER_SEQUENCING_INTERVAL=250\n')
# out.write('PRIMER_SEQUENCING_LEAD=50\n')
# out.write('PRIMER_SEQUENCING_ACCURACY=20\n')
# out.write('PRIMER_WT_SIZE_LT=1.0\n')
# out.write('PRIMER_WT_SIZE_GT=1.0\n')
# out.write('PRIMER_WT_TM_LT=1.0\n')
# out.write('PRIMER_WT_TM_GT=1.0\n')
# out.write('PRIMER_WT_GC_PERCENT_LT=0.0\n')
# out.write('PRIMER_WT_GC_PERCENT_GT=0.0\n')
# out.write('PRIMER_WT_SELF_ANY_TH=0.0\n')
# out.write('PRIMER_WT_SELF_END_TH=0.0\n')
# out.write('PRIMER_WT_HAIRPIN_TH=0.0\n')
# out.write('PRIMER_WT_TEMPLATE_MISPRIMING_TH=0.0\n')
# out.write('PRIMER_WT_SELF_ANY=0.0\n')
# out.write('PRIMER_WT_SELF_END=0.0\n')
# out.write('PRIMER_WT_TEMPLATE_MISPRIMING=0.0\n')
# out.write('PRIMER_WT_NUM_NS=0.0\n')
# out.write('PRIMER_WT_LIBRARY_MISPRIMING=0.0\n')
# out.write('PRIMER_WT_SEQ_QUAL=0.0\n')
# out.write('PRIMER_WT_END_QUAL=0.0\n')
# out.write('PRIMER_WT_POS_PENALTY=0.0\n')
# out.write('PRIMER_WT_END_STABILITY=0.0\n')
# out.write('PRIMER_PAIR_WT_PRODUCT_SIZE_LT=0.0\n')
# out.write('PRIMER_PAIR_WT_PRODUCT_SIZE_GT=0.0\n')
# out.write('PRIMER_PAIR_WT_PRODUCT_TM_LT=0.0\n')
# out.write('PRIMER_PAIR_WT_PRODUCT_TM_GT=0.0\n')
# out.write('PRIMER_PAIR_WT_COMPL_ANY_TH=0.0\n')
# out.write('PRIMER_PAIR_WT_COMPL_END_TH=0.0\n')
# out.write('PRIMER_PAIR_WT_TEMPLATE_MISPRIMING_TH=0.0\n')
# out.write('PRIMER_PAIR_WT_COMPL_ANY=0.0\n')
# out.write('PRIMER_PAIR_WT_COMPL_END=0.0\n')
# out.write('PRIMER_PAIR_WT_TEMPLATE_MISPRIMING=0.0\n')
# out.write('PRIMER_PAIR_WT_DIFF_TM=0.0\n')
# out.write('PRIMER_PAIR_WT_LIBRARY_MISPRIMING=0.0\n')
# out.write('PRIMER_PAIR_WT_PR_PENALTY=1.0\n')
# out.write('PRIMER_PAIR_WT_IO_PENALTY=0.0\n')
# out.write('PRIMER_INTERNAL_MIN_SIZE=18\n')
# out.write('PRIMER_INTERNAL_OPT_SIZE=20\n')
# out.write('PRIMER_INTERNAL_MAX_SIZE=27\n')
# out.write('PRIMER_INTERNAL_MIN_TM=57.0\n')
# out.write('PRIMER_INTERNAL_OPT_TM=60.0\n')
# out.write('PRIMER_INTERNAL_MAX_TM=63.0\n')
# out.write('PRIMER_INTERNAL_MIN_GC=20.0\n')
# out.write('PRIMER_INTERNAL_OPT_GC_PERCENT=50.0\n')
# out.write('PRIMER_INTERNAL_MAX_GC=80.0\n')
# out.write('PRIMER_INTERNAL_MAX_SELF_ANY_TH=47.00\n')
# out.write('PRIMER_INTERNAL_MAX_SELF_END_TH=47.00\n')
# out.write('PRIMER_INTERNAL_MAX_HAIRPIN_TH=47.00\n')
# out.write('PRIMER_INTERNAL_MAX_SELF_ANY=12.00\n')
# out.write('PRIMER_INTERNAL_MAX_SELF_END=12.00\n')
# out.write('PRIMER_INTERNAL_MIN_QUALITY=0\n')
# out.write('PRIMER_INTERNAL_MAX_NS_ACCEPTED=0\n')
# out.write('PRIMER_INTERNAL_MAX_POLY_X=5\n')
# out.write('PRIMER_INTERNAL_MAX_LIBRARY_MISHYB=12.00\n')
# out.write('PRIMER_INTERNAL_SALT_MONOVALENT=50.0\n')
# out.write('PRIMER_INTERNAL_DNA_CONC=50.0\n')
# out.write('PRIMER_INTERNAL_SALT_DIVALENT=1.5\n')
# out.write('PRIMER_INTERNAL_DNTP_CONC=0.0\n')
# out.write('PRIMER_INTERNAL_WT_SIZE_LT=1.0\n')
# out.write('PRIMER_INTERNAL_WT_SIZE_GT=1.0\n')
# out.write('PRIMER_INTERNAL_WT_TM_LT=1.0\n')
# out.write('PRIMER_INTERNAL_WT_TM_GT=1.0\n')
# out.write('PRIMER_INTERNAL_WT_GC_PERCENT_LT=0.0\n')
# out.write('PRIMER_INTERNAL_WT_GC_PERCENT_GT=0.0\n')
# out.write('PRIMER_INTERNAL_WT_SELF_ANY_TH=0.0\n')
# out.write('PRIMER_INTERNAL_WT_SELF_END_TH=0.0\n')
# out.write('PRIMER_INTERNAL_WT_HAIRPIN_TH=0.0\n')
# out.write('PRIMER_INTERNAL_WT_SELF_ANY=0.0\n')
# out.write('PRIMER_INTERNAL_WT_SELF_END=0.0\n')
# out.write('PRIMER_INTERNAL_WT_NUM_NS=0.0\n')
# out.write('PRIMER_INTERNAL_WT_LIBRARY_MISHYB=0.0\n')
# out.write('PRIMER_INTERNAL_WT_SEQ_QUAL=0.0\n')
# out.write('PRIMER_INTERNAL_WT_END_QUAL=0.0\n')
out.write('=\n')
def main():
args = get_args()
infastafh = open(args.fasta)
seq_stream = Bio.SeqIO.parse(infastafh, 'fasta')
if args.out:
outfh = file(args.out,'w')
else:
outfh = sys.stdout
ref = None
for seqobj in seq_stream:
if len(seqobj) > args.size_limit:
ref = seqobj
else:
analyze(outfh, seqobj, ref, args)
if __name__ == '__main__':
main()
|
mit
| -370,202,171,412,303,400
| 41.799065
| 122
| 0.632165
| false
| 2.361176
| false
| false
| false
|
unreal666/outwiker
|
src/outwiker/gui/controls/ultimatelistctrl.py
|
2
|
456589
|
# --------------------------------------------------------------------------------- #
# ULTIMATELISTCTRL wxPython IMPLEMENTATION
# Inspired by and heavily based on the wxWidgets C++ generic version of wxListCtrl.
#
# Andrea Gavana, @ 08 May 2009
# Latest Revision: 27 Dec 2012, 21.00 GMT
#
#
# TODO List
#
# 1) Subitem selection;
# 2) Watermark? (almost, does not work very well :-( );
# 3) Groups? (Maybe, check ObjectListView);
# 4) Scrolling items as headers and footers;
# 5) Alpha channel for text/background of items;
# 6) Custom renderers for headers/footers (done);
# 7) Fading in and out on mouse motion (a la Windows Vista Aero);
# 8) Sub-text for headers/footers (grey text below the header/footer text);
# 9) Fixing the columns to the left or right side of the control layout;
# 10) Skins for header and scrollbars (implemented for headers/footers).
#
#
# For all kind of problems, requests of enhancements and bug reports, please
# write to me at:
#
# andrea.gavana@gmail.com
# andrea.gavana@maerskoil.com
#
# Or, obviously, to the wxPython mailing list!!!
#
# Tags: phoenix-port, documented, unittest, py3-port
#
# End Of Comments
# --------------------------------------------------------------------------------- #
"""
Description
===========
UltimateListCtrl is a class that mimics the behaviour of :class:`ListCtrl`, with almost
the same base functionalities plus some more enhancements. This class does
not rely on the native control, as it is a full owner-drawn list control.
In addition to the standard :class:`ListCtrl` behaviour this class supports:
Appearance
==========
* Multiple images for items/subitems;
* Images can be of any size and not limited to a single specific pair of `width`, `height`
as it is the case of :class:`wx.ImageList`. Simply use :class:`PyImageList` instead of :class:`wx.ImageList`
to add your images.
* Font, colour, background, custom renderers and formatting for items and subitems;
* Ability to add persistent data to an item using :meth:`~UltimateListCtrl.SetItemPyData` and :meth:`~UltimateListCtrl.GetItemPyData`:
the data can be any Python object and not necessarily an integer as in :class:`ListCtrl`;
* CheckBox-type items and subitems;
* RadioButton-type items and subitems;
* Overflowing items/subitems, a la :class:`grid.Grid`, i.e. an item/subitem may overwrite neighboring
items/subitems if its text would not normally fit in the space allotted to it;
* Hyperlink-type items and subitems: they look like an hyperlink, with the proper mouse
cursor on hovering;
* Multiline text items and subitems;
* Variable row heights depending on the item/subitem kind/text/window;
* User defined item/subitem renderers: these renderer classes **must** implement the methods
`DrawSubItem`, `GetLineHeight` and `GetSubItemWidth` (see the demo);
* Enabling/disabling items (together with their plain or grayed out icons);
* Whatever non-toplevel widget can be attached next to an item/subitem;
* Column headers are fully customizable in terms of icons, colour, font, alignment etc...;
* Column headers can have their own checkbox/radiobutton;
* Column footers are fully customizable in terms of icons, colour, font, alignment etc...;
* Column footers can have their own checkbox/radiobutton;
* Ability to hide/show columns;
* Default selection style, gradient (horizontal/vertical) selection style and Windows
Vista selection style.
And a lot more. Check the demo for an almost complete review of the functionalities.
Usage
=====
Usage example::
import sys
import wx
import wx.lib.agw.ultimatelistctrl as ULC
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, parent, -1, "UltimateListCtrl Demo")
list = ULC.UltimateListCtrl(self, wx.ID_ANY, agwStyle=wx.LC_REPORT | wx.LC_VRULES | wx.LC_HRULES | wx.LC_SINGLE_SEL)
list.InsertColumn(0, "Column 1")
list.InsertColumn(1, "Column 2")
index = list.InsertStringItem(sys.maxint, "Item 1")
list.SetStringItem(index, 1, "Sub-item 1")
index = list.InsertStringItem(sys.maxint, "Item 2")
list.SetStringItem(index, 1, "Sub-item 2")
choice = wx.Choice(list, -1, choices=["one", "two"])
index = list.InsertStringItem(sys.maxint, "A widget")
list.SetItemWindow(index, 1, choice, expand=True)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(list, 1, wx.EXPAND)
self.SetSizer(sizer)
# our normal wxApp-derived class, as usual
app = wx.App(0)
frame = MyFrame(None)
app.SetTopWindow(frame)
frame.Show()
app.MainLoop()
Window Styles
=============
This class supports the following window styles:
=============================== =========== ====================================================================================================
Window Styles Hex Value Description
=============================== =========== ====================================================================================================
``ULC_VRULES`` 0x1 Draws light vertical rules between rows in report mode.
``ULC_HRULES`` 0x2 Draws light horizontal rules between rows in report mode.
``ULC_ICON`` 0x4 Large icon view, with optional labels.
``ULC_SMALL_ICON`` 0x8 Small icon view, with optional labels.
``ULC_LIST`` 0x10 Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don't set columns as in ``ULC_REPORT``. In other words, the list wraps, unlike a :class:`ListBox`.
``ULC_REPORT`` 0x20 Single or multicolumn report view, with optional header.
``ULC_ALIGN_TOP`` 0x40 Icons align to the top. Win32 default, Win32 only.
``ULC_ALIGN_LEFT`` 0x80 Icons align to the left.
``ULC_AUTOARRANGE`` 0x100 Icons arrange themselves. Win32 only.
``ULC_VIRTUAL`` 0x200 The application provides items text on demand. May only be used with ``ULC_REPORT``.
``ULC_EDIT_LABELS`` 0x400 Labels are editable: the application will be notified when editing starts.
``ULC_NO_HEADER`` 0x800 No header in report mode.
``ULC_NO_SORT_HEADER`` 0x1000 No Docs.
``ULC_SINGLE_SEL`` 0x2000 Single selection (default is multiple).
``ULC_SORT_ASCENDING`` 0x4000 Sort in ascending order. (You must still supply a comparison callback in :meth:`ListCtrl.SortItems`.)
``ULC_SORT_DESCENDING`` 0x8000 Sort in descending order. (You must still supply a comparison callback in :meth:`ListCtrl.SortItems`.)
``ULC_TILE`` 0x10000 Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented).
``ULC_NO_HIGHLIGHT`` 0x20000 No highlight when an item is selected.
``ULC_STICKY_HIGHLIGHT`` 0x40000 Items are selected by simply hovering on them, with no need to click on them.
``ULC_STICKY_NOSELEVENT`` 0x80000 Don't send a selection event when using ``ULC_STICKY_HIGHLIGHT`` style.
``ULC_SEND_LEFTCLICK`` 0x100000 Send a left click event when an item is selected.
``ULC_HAS_VARIABLE_ROW_HEIGHT`` 0x200000 The list has variable row heights.
``ULC_AUTO_CHECK_CHILD`` 0x400000 When a column header has a checkbox associated, auto-check all the subitems in that column.
``ULC_AUTO_TOGGLE_CHILD`` 0x800000 When a column header has a checkbox associated, toggle all the subitems in that column.
``ULC_AUTO_CHECK_PARENT`` 0x1000000 Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well.
``ULC_SHOW_TOOLTIPS`` 0x2000000 Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text.
``ULC_HOT_TRACKING`` 0x4000000 Enable hot tracking of items on mouse motion.
``ULC_BORDER_SELECT`` 0x8000000 Changes border colour whan an item is selected, instead of highlighting the item.
``ULC_TRACK_SELECT`` 0x10000000 Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the `win32api` call `win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)`, and is defaulted to 400ms on other platforms. This style applies to all views of `UltimateListCtrl`.
``ULC_HEADER_IN_ALL_VIEWS`` 0x20000000 Show column headers in all view modes.
``ULC_NO_FULL_ROW_SELECT`` 0x40000000 When an item is selected, the only the item in the first column is highlighted.
``ULC_FOOTER`` 0x80000000 Show a footer too (only when header is present).
``ULC_USER_ROW_HEIGHT`` 0x100000000 Allows to set a custom row height (one value for all the items, only in report mode).
=============================== =========== ====================================================================================================
Events Processing
=================
This class processes the following events:
======================================== ====================================================================================================
Event Name Description
======================================== ====================================================================================================
``EVT_LIST_BEGIN_DRAG`` Begin dragging with the left mouse button.
``EVT_LIST_BEGIN_RDRAG`` Begin dragging with the right mouse button.
``EVT_LIST_BEGIN_LABEL_EDIT`` Begin editing a label. This can be prevented by calling `Veto()`.
``EVT_LIST_END_LABEL_EDIT`` Finish editing a label. This can be prevented by calling `Veto()`.
``EVT_LIST_DELETE_ITEM`` An item was deleted.
``EVT_LIST_DELETE_ALL_ITEMS`` All items were deleted.
``EVT_LIST_KEY_DOWN`` A key has been pressed.
``EVT_LIST_INSERT_ITEM`` An item has been inserted.
``EVT_LIST_COL_CLICK`` A column (`m_col`) has been left-clicked.
``EVT_LIST_COL_RIGHT_CLICK`` A column (`m_col`) has been right-clicked.
``EVT_LIST_COL_BEGIN_DRAG`` The user started resizing a column - can be vetoed.
``EVT_LIST_COL_END_DRAG`` The user finished resizing a column.
``EVT_LIST_COL_DRAGGING`` The divider between columns is being dragged.
``EVT_LIST_ITEM_SELECTED`` The item has been selected.
``EVT_LIST_ITEM_DESELECTED`` The item has been deselected.
``EVT_LIST_ITEM_RIGHT_CLICK`` The right mouse button has been clicked on an item.
``EVT_LIST_ITEM_MIDDLE_CLICK`` The middle mouse button has been clicked on an item.
``EVT_LIST_ITEM_ACTIVATED`` The item has been activated (``ENTER`` or double click).
``EVT_LIST_ITEM_FOCUSED`` The currently focused item has changed.
``EVT_LIST_CACHE_HINT`` Prepare cache for a virtual list control.
``EVT_LIST_ITEM_CHECKING`` An item/subitem is being checked.
``EVT_LIST_ITEM_CHECKED`` An item/subitem has been checked.
``EVT_LIST_COL_CHECKING`` A column header is being checked.
``EVT_LIST_COL_CHECKED`` A column header has being checked.
``EVT_LIST_FOOTER_CHECKING`` A column footer is being checked.
``EVT_LIST_FOOTER_CHECKED`` A column footer has being checked.
``EVT_LIST_ITEM_HYPERLINK`` An hyperlink item has been clicked.
``EVT_LIST_FOOTER_CLICK`` The user left-clicked on a column footer.
``EVT_LIST_FOOTER_RIGHT_CLICK`` The user right-clicked on a column footer.
``EVT_LIST_ITEM_LEFT_CLICK`` Send a left-click event after an item is selected.
``EVT_LIST_END_DRAG`` Notify an end-drag operation.
======================================== ====================================================================================================
Supported Platforms
===================
UltimateListCtrl has been tested on the following platforms:
* Windows (Windows XP);
License And Version
===================
UltimateListCtrl is distributed under the wxPython license.
Latest Revision: Andrea Gavana @ 27 Dec 2012, 21.00 GMT
Version 0.8
"""
import wx
import math
import bisect
import zlib
from functools import cmp_to_key
import six
from wx.lib.expando import ExpandoTextCtrl
# Version Info
__version__ = "0.8"
# wxPython version string
_VERSION_STRING = wx.VERSION_STRING
# ----------------------------------------------------------------------------
# UltimateListCtrl constants
# ----------------------------------------------------------------------------
# style flags
ULC_VRULES = wx.LC_VRULES
""" Draws light vertical rules between rows in report mode. """
ULC_HRULES = wx.LC_HRULES
""" Draws light horizontal rules between rows in report mode. """
ULC_ICON = wx.LC_ICON
ULC_SMALL_ICON = wx.LC_SMALL_ICON
ULC_LIST = wx.LC_LIST
ULC_REPORT = wx.LC_REPORT
ULC_TILE = 0x10000
ULC_ALIGN_TOP = wx.LC_ALIGN_TOP
ULC_ALIGN_LEFT = wx.LC_ALIGN_LEFT
ULC_AUTOARRANGE = wx.LC_AUTOARRANGE
ULC_VIRTUAL = wx.LC_VIRTUAL
ULC_EDIT_LABELS = wx.LC_EDIT_LABELS
ULC_NO_HEADER = wx.LC_NO_HEADER
ULC_NO_SORT_HEADER = wx.LC_NO_SORT_HEADER
ULC_SINGLE_SEL = wx.LC_SINGLE_SEL
ULC_SORT_ASCENDING = wx.LC_SORT_ASCENDING
ULC_SORT_DESCENDING = wx.LC_SORT_DESCENDING
ULC_NO_HIGHLIGHT = 0x20000
ULC_STICKY_HIGHLIGHT = 0x40000
ULC_STICKY_NOSELEVENT = 0x80000
ULC_SEND_LEFTCLICK = 0x100000
ULC_HAS_VARIABLE_ROW_HEIGHT = 0x200000
ULC_AUTO_CHECK_CHILD = 0x400000 # only meaningful for checkboxes
ULC_AUTO_TOGGLE_CHILD = 0x800000 # only meaningful for checkboxes
ULC_AUTO_CHECK_PARENT = 0x1000000 # only meaningful for checkboxes
ULC_SHOW_TOOLTIPS = 0x2000000 # shows tooltips on items with ellipsis (...)
ULC_HOT_TRACKING = 0x4000000 # enable hot tracking on mouse motion
ULC_BORDER_SELECT = 0x8000000 # changes border colour whan an item is selected, instead of highlighting the item
ULC_TRACK_SELECT = 0x10000000 # Enables hot-track selection in a list control. Hot track selection means that an item
# is automatically selected when the cursor remains over the item for a certain period
# of time. The delay is retrieved on Windows using the win32api call
# win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME), and is defaulted to 400ms
# on other platforms. This style applies to all styles of UltimateListCtrl.
ULC_HEADER_IN_ALL_VIEWS = 0x20000000 # Show column headers in all view modes
ULC_NO_FULL_ROW_SELECT = 0x40000000 # When an item is selected, the only the item in the first column is highlighted
ULC_FOOTER = 0x80000000 # Show a footer too (only when header is present)
ULC_USER_ROW_HEIGHT = 0x100000000 # Allows to set a custom row height (one value for all the items, only in report mode).
ULC_MASK_TYPE = ULC_ICON | ULC_SMALL_ICON | ULC_LIST | ULC_REPORT | ULC_TILE
ULC_MASK_ALIGN = ULC_ALIGN_TOP | ULC_ALIGN_LEFT
ULC_MASK_SORT = ULC_SORT_ASCENDING | ULC_SORT_DESCENDING
# for compatibility only
ULC_USER_TEXT = ULC_VIRTUAL
# Omitted because
# (a) too much detail
# (b) not enough style flags
# (c) not implemented anyhow in the generic version
#
# ULC_NO_SCROLL
# ULC_NO_LABEL_WRAP
# ULC_OWNERDRAW_FIXED
# ULC_SHOW_SEL_ALWAYS
# Mask flags to tell app/GUI what fields of UltimateListItem are valid
ULC_MASK_STATE = wx.LIST_MASK_STATE
ULC_MASK_TEXT = wx.LIST_MASK_TEXT
ULC_MASK_IMAGE = wx.LIST_MASK_IMAGE
ULC_MASK_DATA = wx.LIST_MASK_DATA
ULC_SET_ITEM = wx.LIST_SET_ITEM
ULC_MASK_WIDTH = wx.LIST_MASK_WIDTH
ULC_MASK_FORMAT = wx.LIST_MASK_FORMAT
ULC_MASK_FONTCOLOUR = 0x0080
ULC_MASK_FONT = 0x0100
ULC_MASK_BACKCOLOUR = 0x0200
ULC_MASK_KIND = 0x0400
ULC_MASK_ENABLE = 0x0800
ULC_MASK_CHECK = 0x1000
ULC_MASK_HYPERTEXT = 0x2000
ULC_MASK_WINDOW = 0x4000
ULC_MASK_PYDATA = 0x8000
ULC_MASK_SHOWN = 0x10000
ULC_MASK_RENDERER = 0x20000
ULC_MASK_OVERFLOW = 0x40000
ULC_MASK_FOOTER_TEXT = 0x80000
ULC_MASK_FOOTER_IMAGE = 0x100000
ULC_MASK_FOOTER_FORMAT = 0x200000
ULC_MASK_FOOTER_FONT = 0x400000
ULC_MASK_FOOTER_CHECK = 0x800000
ULC_MASK_FOOTER_KIND = 0x1000000
ULC_MASK_TOOLTIP = 0x2000000
# State flags for indicating the state of an item
ULC_STATE_DONTCARE = wx.LIST_STATE_DONTCARE
ULC_STATE_DROPHILITED = wx.LIST_STATE_DROPHILITED # MSW only
ULC_STATE_FOCUSED = wx.LIST_STATE_FOCUSED
ULC_STATE_SELECTED = wx.LIST_STATE_SELECTED
ULC_STATE_CUT = wx.LIST_STATE_CUT # MSW only
ULC_STATE_DISABLED = wx.LIST_STATE_DISABLED # OS2 only
ULC_STATE_FILTERED = wx.LIST_STATE_FILTERED # OS2 only
ULC_STATE_INUSE = wx.LIST_STATE_INUSE # OS2 only
ULC_STATE_PICKED = wx.LIST_STATE_PICKED # OS2 only
ULC_STATE_SOURCE = wx.LIST_STATE_SOURCE # OS2 only
# Hit test flags, used in HitTest
ULC_HITTEST_ABOVE = wx.LIST_HITTEST_ABOVE # Above the client area.
ULC_HITTEST_BELOW = wx.LIST_HITTEST_BELOW # Below the client area.
ULC_HITTEST_NOWHERE = wx.LIST_HITTEST_NOWHERE # In the client area but below the last item.
ULC_HITTEST_ONITEMICON = wx.LIST_HITTEST_ONITEMICON # On the bitmap associated with an item.
ULC_HITTEST_ONITEMLABEL = wx.LIST_HITTEST_ONITEMLABEL # On the label (string) associated with an item.
ULC_HITTEST_ONITEMRIGHT = wx.LIST_HITTEST_ONITEMRIGHT # In the area to the right of an item.
ULC_HITTEST_ONITEMSTATEICON = wx.LIST_HITTEST_ONITEMSTATEICON # On the state icon for a tree view item that is in a user-defined state.
ULC_HITTEST_TOLEFT = wx.LIST_HITTEST_TOLEFT # To the left of the client area.
ULC_HITTEST_TORIGHT = wx.LIST_HITTEST_TORIGHT # To the right of the client area.
ULC_HITTEST_ONITEMCHECK = 0x1000 # On the checkbox (if any)
ULC_HITTEST_ONITEM = ULC_HITTEST_ONITEMICON | ULC_HITTEST_ONITEMLABEL | ULC_HITTEST_ONITEMSTATEICON | ULC_HITTEST_ONITEMCHECK
# Flags for GetNextItem (MSW only except ULC_NEXT_ALL)
ULC_NEXT_ABOVE = wx.LIST_NEXT_ABOVE # Searches for an item above the specified item
ULC_NEXT_ALL = wx.LIST_NEXT_ALL # Searches for subsequent item by index
ULC_NEXT_BELOW = wx.LIST_NEXT_BELOW # Searches for an item below the specified item
ULC_NEXT_LEFT = wx.LIST_NEXT_LEFT # Searches for an item to the left of the specified item
ULC_NEXT_RIGHT = wx.LIST_NEXT_RIGHT # Searches for an item to the right of the specified item
# Alignment flags for Arrange (MSW only except ULC_ALIGN_LEFT)
ULC_ALIGN_DEFAULT = wx.LIST_ALIGN_DEFAULT
ULC_ALIGN_SNAP_TO_GRID = wx.LIST_ALIGN_SNAP_TO_GRID
# Column format (MSW only except ULC_FORMAT_LEFT)
ULC_FORMAT_LEFT = wx.LIST_FORMAT_LEFT
ULC_FORMAT_RIGHT = wx.LIST_FORMAT_RIGHT
ULC_FORMAT_CENTRE = wx.LIST_FORMAT_CENTRE
ULC_FORMAT_CENTER = ULC_FORMAT_CENTRE
# Autosize values for SetColumnWidth
ULC_AUTOSIZE = wx.LIST_AUTOSIZE
ULC_AUTOSIZE_USEHEADER = wx.LIST_AUTOSIZE_USEHEADER # partly supported by generic version
ULC_AUTOSIZE_FILL = -3
# Flag values for GetItemRect
ULC_RECT_BOUNDS = wx.LIST_RECT_BOUNDS
ULC_RECT_ICON = wx.LIST_RECT_ICON
ULC_RECT_LABEL = wx.LIST_RECT_LABEL
# Flag values for FindItem (MSW only)
ULC_FIND_UP = wx.LIST_FIND_UP
ULC_FIND_DOWN = wx.LIST_FIND_DOWN
ULC_FIND_LEFT = wx.LIST_FIND_LEFT
ULC_FIND_RIGHT = wx.LIST_FIND_RIGHT
# Items/subitems rect
ULC_GETSUBITEMRECT_WHOLEITEM = wx.LIST_GETSUBITEMRECT_WHOLEITEM
# ----------------------------------------------------------------------------
# UltimateListCtrl event macros
# ----------------------------------------------------------------------------
wxEVT_COMMAND_LIST_BEGIN_DRAG = wx.wxEVT_COMMAND_LIST_BEGIN_DRAG
wxEVT_COMMAND_LIST_BEGIN_RDRAG = wx.wxEVT_COMMAND_LIST_BEGIN_RDRAG
wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT = wx.wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT
wxEVT_COMMAND_LIST_END_LABEL_EDIT = wx.wxEVT_COMMAND_LIST_END_LABEL_EDIT
wxEVT_COMMAND_LIST_DELETE_ITEM = wx.wxEVT_COMMAND_LIST_DELETE_ITEM
wxEVT_COMMAND_LIST_DELETE_ALL_ITEMS = wx.wxEVT_COMMAND_LIST_DELETE_ALL_ITEMS
wxEVT_COMMAND_LIST_ITEM_SELECTED = wx.wxEVT_COMMAND_LIST_ITEM_SELECTED
wxEVT_COMMAND_LIST_ITEM_DESELECTED = wx.wxEVT_COMMAND_LIST_ITEM_DESELECTED
wxEVT_COMMAND_LIST_KEY_DOWN = wx.wxEVT_COMMAND_LIST_KEY_DOWN
wxEVT_COMMAND_LIST_INSERT_ITEM = wx.wxEVT_COMMAND_LIST_INSERT_ITEM
wxEVT_COMMAND_LIST_COL_CLICK = wx.wxEVT_COMMAND_LIST_COL_CLICK
wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK = wx.wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK
wxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK = wx.wxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK
wxEVT_COMMAND_LIST_ITEM_ACTIVATED = wx.wxEVT_COMMAND_LIST_ITEM_ACTIVATED
wxEVT_COMMAND_LIST_CACHE_HINT = wx.wxEVT_COMMAND_LIST_CACHE_HINT
wxEVT_COMMAND_LIST_COL_RIGHT_CLICK = wx.wxEVT_COMMAND_LIST_COL_RIGHT_CLICK
wxEVT_COMMAND_LIST_COL_BEGIN_DRAG = wx.wxEVT_COMMAND_LIST_COL_BEGIN_DRAG
wxEVT_COMMAND_LIST_COL_DRAGGING = wx.wxEVT_COMMAND_LIST_COL_DRAGGING
wxEVT_COMMAND_LIST_COL_END_DRAG = wx.wxEVT_COMMAND_LIST_COL_END_DRAG
wxEVT_COMMAND_LIST_ITEM_FOCUSED = wx.wxEVT_COMMAND_LIST_ITEM_FOCUSED
wxEVT_COMMAND_LIST_FOOTER_CLICK = wx.NewEventType()
wxEVT_COMMAND_LIST_FOOTER_RIGHT_CLICK = wx.NewEventType()
wxEVT_COMMAND_LIST_FOOTER_CHECKING = wx.NewEventType()
wxEVT_COMMAND_LIST_FOOTER_CHECKED = wx.NewEventType()
wxEVT_COMMAND_LIST_ITEM_LEFT_CLICK = wx.NewEventType()
wxEVT_COMMAND_LIST_ITEM_CHECKING = wx.NewEventType()
wxEVT_COMMAND_LIST_ITEM_CHECKED = wx.NewEventType()
wxEVT_COMMAND_LIST_ITEM_HYPERLINK = wx.NewEventType()
wxEVT_COMMAND_LIST_END_DRAG = wx.NewEventType()
wxEVT_COMMAND_LIST_COL_CHECKING = wx.NewEventType()
wxEVT_COMMAND_LIST_COL_CHECKED = wx.NewEventType()
EVT_LIST_BEGIN_DRAG = wx.EVT_LIST_BEGIN_DRAG
EVT_LIST_BEGIN_RDRAG = wx.EVT_LIST_BEGIN_RDRAG
EVT_LIST_BEGIN_LABEL_EDIT = wx.EVT_LIST_BEGIN_LABEL_EDIT
EVT_LIST_END_LABEL_EDIT = wx.EVT_LIST_END_LABEL_EDIT
EVT_LIST_DELETE_ITEM = wx.EVT_LIST_DELETE_ITEM
EVT_LIST_DELETE_ALL_ITEMS = wx.EVT_LIST_DELETE_ALL_ITEMS
EVT_LIST_KEY_DOWN = wx.EVT_LIST_KEY_DOWN
EVT_LIST_INSERT_ITEM = wx.EVT_LIST_INSERT_ITEM
EVT_LIST_COL_CLICK = wx.EVT_LIST_COL_CLICK
EVT_LIST_COL_RIGHT_CLICK = wx.EVT_LIST_COL_RIGHT_CLICK
EVT_LIST_COL_BEGIN_DRAG = wx.EVT_LIST_COL_BEGIN_DRAG
EVT_LIST_COL_END_DRAG = wx.EVT_LIST_COL_END_DRAG
EVT_LIST_COL_DRAGGING = wx.EVT_LIST_COL_DRAGGING
EVT_LIST_ITEM_SELECTED = wx.EVT_LIST_ITEM_SELECTED
EVT_LIST_ITEM_DESELECTED = wx.EVT_LIST_ITEM_DESELECTED
EVT_LIST_ITEM_RIGHT_CLICK = wx.EVT_LIST_ITEM_RIGHT_CLICK
EVT_LIST_ITEM_MIDDLE_CLICK = wx.EVT_LIST_ITEM_MIDDLE_CLICK
EVT_LIST_ITEM_ACTIVATED = wx.EVT_LIST_ITEM_ACTIVATED
EVT_LIST_ITEM_FOCUSED = wx.EVT_LIST_ITEM_FOCUSED
EVT_LIST_CACHE_HINT = wx.EVT_LIST_CACHE_HINT
EVT_LIST_ITEM_LEFT_CLICK = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_LEFT_CLICK, 1)
EVT_LIST_ITEM_CHECKING = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_CHECKING, 1)
EVT_LIST_ITEM_CHECKED = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_CHECKED, 1)
EVT_LIST_ITEM_HYPERLINK = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_HYPERLINK, 1)
EVT_LIST_END_DRAG = wx.PyEventBinder(wxEVT_COMMAND_LIST_END_DRAG, 1)
EVT_LIST_COL_CHECKING = wx.PyEventBinder(wxEVT_COMMAND_LIST_COL_CHECKING, 1)
EVT_LIST_COL_CHECKED = wx.PyEventBinder(wxEVT_COMMAND_LIST_COL_CHECKED, 1)
EVT_LIST_FOOTER_CLICK = wx.PyEventBinder(wxEVT_COMMAND_LIST_FOOTER_CLICK, 1)
EVT_LIST_FOOTER_RIGHT_CLICK = wx.PyEventBinder(wxEVT_COMMAND_LIST_FOOTER_RIGHT_CLICK, 1)
EVT_LIST_FOOTER_CHECKING = wx.PyEventBinder(wxEVT_COMMAND_LIST_FOOTER_CHECKING, 1)
EVT_LIST_FOOTER_CHECKED = wx.PyEventBinder(wxEVT_COMMAND_LIST_FOOTER_CHECKED, 1)
# NOTE: If using the wxExtListBox visual attributes works everywhere then this can
# be removed, as well as the #else case below.
_USE_VISATTR = 0
# ----------------------------------------------------------------------------
# Constants
# ----------------------------------------------------------------------------
SCROLL_UNIT_X = 15
SCROLL_UNIT_Y = 15
# the spacing between the lines (in report mode)
LINE_SPACING = 0
# extra margins around the text label
EXTRA_WIDTH = 4
EXTRA_HEIGHT = 4
if wx.Platform == "__WXGTK__":
EXTRA_HEIGHT = 6
# margin between the window and the items
EXTRA_BORDER_X = 2
EXTRA_BORDER_Y = 2
# offset for the header window
HEADER_OFFSET_X = 1
HEADER_OFFSET_Y = 1
# margin between rows of icons in [small] icon view
MARGIN_BETWEEN_ROWS = 6
# when autosizing the columns, add some slack
AUTOSIZE_COL_MARGIN = 10
# default and minimal widths for the header columns
WIDTH_COL_DEFAULT = 80
WIDTH_COL_MIN = 10
# the space between the image and the text in the report mode
IMAGE_MARGIN_IN_REPORT_MODE = 5
# the space between the image and the text in the report mode in header
HEADER_IMAGE_MARGIN_IN_REPORT_MODE = 2
# and the width of the icon, if any
MARGIN_BETWEEN_TEXT_AND_ICON = 2
# Background Image Style
_StyleTile = 0
_StyleStretch = 1
# Windows Vista Colours
_rgbSelectOuter = wx.Colour(170, 200, 245)
_rgbSelectInner = wx.Colour(230, 250, 250)
_rgbSelectTop = wx.Colour(210, 240, 250)
_rgbSelectBottom = wx.Colour(185, 215, 250)
_rgbNoFocusTop = wx.Colour(250, 250, 250)
_rgbNoFocusBottom = wx.Colour(235, 235, 235)
_rgbNoFocusOuter = wx.Colour(220, 220, 220)
_rgbNoFocusInner = wx.Colour(245, 245, 245)
# Mouse hover time for track selection
HOVER_TIME = 400
if wx.Platform == "__WXMSW__":
try:
import win32gui, win32con
HOVER_TIME = win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)
except ImportError:
pass
# For PyImageList
IL_FIXED_SIZE = 0
IL_VARIABLE_SIZE = 1
# Python integers, to make long types to work with CreateListItem
INTEGER_TYPES = six.integer_types
# ----------------------------------------------------------------------------
# Functions
# ----------------------------------------------------------------------------
# Utility method
def to_list(input):
"""
Converts the input data into a Python list.
:param `input`: can be an integer or a Python list (in which case nothing will
be done to `input`.
"""
if isinstance(input, list):
return input
elif isinstance(input, INTEGER_TYPES):
return [input]
else:
raise Exception("Invalid parameter passed to `to_list`: only integers and list are accepted.")
def CheckVariableRowHeight(listCtrl, text):
"""
Checks whether a `text` contains multiline strings and if the `listCtrl` window
style is compatible with multiline strings.
:param `listCtrl`: an instance of :class:`UltimateListCtrl`;
:param `text`: the text to analyze.
"""
if not listCtrl.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
if "\n" in text:
raise Exception("Multiline text items are not allowed without the ULC_HAS_VARIABLE_ROW_HEIGHT style.")
def CreateListItem(itemOrId, col):
"""
Creates a new instance of :class:`UltimateListItem`.
:param `itemOrId`: can be an instance of :class:`UltimateListItem` or an integer;
:param `col`: the item column.
"""
if type(itemOrId) in INTEGER_TYPES:
item = UltimateListItem()
item._itemId = itemOrId
item._col = col
else:
item = itemOrId
return item
# ----------------------------------------------------------------------------
def MakeDisabledBitmap(original):
"""
Creates a disabled-looking bitmap starting from the input one.
:param `original`: an instance of :class:`wx.Bitmap` to be greyed-out.
"""
img = original.ConvertToImage()
return wx.Bitmap(img.ConvertToGreyscale())
# ----------------------------------------------------------------------------
#----------------------------------------------------------------------
def GetdragcursorData():
""" Returns the drag and drop cursor image as a decompressed stream of characters. """
return zlib.decompress(
b"x\xda\xeb\x0c\xf0s\xe7\xe5\x92\xe2b``\xe0\xf5\xf4p\t\x02\xd2\xa2@,\xcf\xc1\
\x06$9z\xda>\x00)\xce\x02\x8f\xc8b\x06\x06na\x10fd\x985G\x02(\xd8W\xe2\x1aQ\
\xe2\x9c\x9f\x9b\x9b\x9aW\xc2\x90\xec\x11\xe4\xab\x90\x9cQ\x9a\x97\x9d\x93\
\x9a\xa7`l\xa4\x90\x99\x9e\x97_\x94\x9a\xc2\xeb\x18\xec\xec\xe9i\xa5\xa0\xa7\
W\xa5\xaa\x07\x01P:7\x1eH\xe4\xe8\xe9\xd9\x808\x11\xbc\x1e\xae\x11V\n\x06@`\
\xeehd\n\xa2-\x0c,\x8cA\xb4\x9b\t\x94o\xe2b\x08\xa2\xcd\\L\xdd@\xb4\xab\x85\
\x993\x886v\xb6p\x02\xd1\x86N\xa6\x16\x12\xf7~\xdf\x05\xbal\xa9\xa7\x8bcH\
\xc5\x9c3W9\xb9\x1a\x14\x04X/\xec\xfc\xbft\xed\x02\xa5\xf4\xc2m\xfa*<N\x17??\
\x0frqy\x9c\xd3\xb2f5\xaf\x89\x8f9Gk\xbc\x08\xa7\xbf\x06\x97\x98\x06S\xd8E\
\xbd\x9cE\xb2\x15\x9da\x89\xe2k\x0f\x9c\xb6|\x1a\xea\x14X\x1d6G\x83E\xe7\x9c\
\x1dO\xa8\xde\xb6\x84l\x15\x9eS\xcf\xc2tf\x15\xde\xf7\xb5\xb2]\xf0\x96+\xf5@\
D\x90\x1d\xef19_\xf5\xde5y\xb6+\xa7\xdeZ\xfbA\x9bu\x9f`\xffD\xafYn\xf6\x9eW\
\xeb>\xb6\x7f\x98\\U\xcb\xf5\xd5\xcb\x9a'\xe7\xf4\xd7\x0b\xba\x9e\xdb\x17E\
\xfdf\x97Z\xcb\xcc\xc0\xf0\xff?3\xc3\x92\xabN\x8arB\xc7\x8f\x03\x1d\xcc\xe0\
\xe9\xea\xe7\xb2\xce)\xa1\t\x00B7|\x00" )
def GetdragcursorBitmap():
""" Returns the drag and drop cursor image as a :class:`wx.Bitmap`. """
return wx.Bitmap(GetdragcursorImage())
def GetdragcursorImage():
""" Returns the drag and drop cursor image as a :class:`wx.Image`. """
stream = six.BytesIO(GetdragcursorData())
return wx.Image(stream)
#-----------------------------------------------------------------------------
# PyImageList
#-----------------------------------------------------------------------------
class PyImageList(object):
"""
A :class:`PyImageList` contains a list of images. Images can have masks for
transparent drawing, and can be made from a variety of sources including
bitmaps and icons.
:class:`PyImageList` is used in conjunction with :class:`UltimateListCtrl`.
:note: The main improvements that :class:`PyImageList` introduces is the removal
of the limitation of same-size images inside the image list. If you use
the style ``IL_VARIABLE_SIZE`` then each image can have any size (in terms
of width and height).
"""
def __init__(self, width, height, mask=True, initialCount=1, style=IL_VARIABLE_SIZE):
"""
Default class constructor.
:param `width`: the width of the images in the image list, in pixels (unused
if you specify the ``IL_VARIABLE_SIZE`` style;
:param `height`: the height of the images in the image list, in pixels (unused
if you specify the ``IL_VARIABLE_SIZE`` style;
:param `mask`: ``True`` if masks should be created for all images (unused in
:class:`PyImageList`);
:param `initialCount`: the initial size of the list (unused in :class:`PyImageList`);
:param `style`: can be one of the following bits:
==================== ===== =================================
Style Flag Value Description
==================== ===== =================================
``IL_FIXED_SIZE`` 0 All the images in :class:`PyImageList` have the same size (width, height)
``IL_VARIABLE_SIZE`` 1 Each image can have any size (in terms of width and height)
==================== ===== =================================
"""
self._width = width
self._height = height
self._mask = mask
self._initialCount = 1
self._style = style
self._images = []
def GetImageCount(self):
""" Returns the number of images in the list. """
return len(self._images)
def Add(self, bitmap):
"""
Adds a new image or images using a bitmap.
:param `bitmap`: a valid :class:`wx.Bitmap` object.
:return: The new zero-based image index.
:note: If the bitmap is wider than the images in the list and you are not using
the ``IL_VARIABLE_SIZE`` style, then the bitmap will automatically be split
into smaller images, each matching the dimensions of the image list.
"""
index = len(self._images)
# Mimic behavior of Windows ImageList_Add that automatically breaks up the added
# bitmap into sub-images of the correct size
if self._style & IL_FIXED_SIZE:
if self._width > 0 and bitmap.GetWidth() > self._width and \
bitmap.GetHeight() >= self._height:
numImages = bitmap.GetWidth()/self._width
for subIndex in range(numImages):
rect = wx.Rect(self._width * subIndex, 0, self._width, self._height)
tmpBmp = bitmap.GetSubBitmap(rect)
self._images.append(tmpBmp)
else:
self._images.append(bitmap)
else:
self._images.append(bitmap)
if self._width == 0 and self._height == 0:
self._width = bitmap.GetWidth()
self._height = bitmap.GetHeight()
return index
def AddIcon(self, icon):
"""
Adds a new image using an icon.
:param `icon`: a valid :class:`Icon` object.
:return: The new zero-based image index.
:note: If the icon is wider than the images in the list and you are not using
the ``IL_VARIABLE_SIZE`` style, then the icon will automatically be split
into smaller images, each matching the dimensions of the image list.
"""
return self.Add(wx.Bitmap(icon))
def AddWithColourMask(self, bitmap, maskColour):
"""
Adds a new image or images using a bitmap and a colour mask.
:param `bitmap`: a valid :class:`wx.Bitmap` object;
:param `colour`: an instance of :class:`wx.Colour`, a colour indicating which parts
of the image are transparent.
:return: The new zero-based image index.
:note: If the bitmap is wider than the images in the list and you are not using
the ``IL_VARIABLE_SIZE`` style, then the bitmap will automatically be split
into smaller images, each matching the dimensions of the image list.
"""
img = bitmap.ConvertToImage()
img.SetMaskColour(maskColour.Red(), maskColour.Green(), maskColour.Blue())
return self.Add(wx.Bitmap(img))
def GetBitmap(self, index):
"""
Returns the bitmap corresponding to the given `index`, or :class:`NullBitmap`
if the index is invalid.
:param `index`: the bitmap index.
"""
if index >= len(self._images):
return wx.NullBitmap
return self._images[index]
def GetIcon(self, index):
"""
Returns the icon corresponding to the given `index`, or :class:`NullIcon`
if the index is invalid.
:param `index`: the icon index.
"""
if index >= len(self._images):
return wx.NullIcon
icon = wx.Icon()
icon.CopyFromBitmap(self.GetBitmap(index))
return icon
def Replace(self, index, bitmap):
"""
Replaces the existing image with the new bitmap.
:param `index`: the index at which the image should be replaced;
:param `bitmap`: the new bitmap to add to the image list, an instance of
:class:`wx.Bitmap`.
"""
if index >= len(self._images):
raise Exception("Wrong index in image list")
self._images[index] = bitmap
return True
def ReplaceIcon(self, index, icon):
"""
Replaces the existing image with the new icon.
:param `index`: the index at which the image should be replaced;
:param `icon`: the new icon to add to the image list, an instance of
:class:`Icon`.
"""
return self.Replace(index, wx.Bitmap(icon))
def Remove(self, index):
"""
Removes the image at the given position.
:param `index`: the zero-based index of the image to be removed.
"""
if index >= len(self._images):
raise Exception("Wrong index in image list")
self._images.pop(index)
return True
def RemoveAll(self):
""" Removes all the images in the list. """
self._images = []
return True
def GetSize(self, index):
"""
Retrieves the size of an image in the list.
:param `index`: the zero-based index of the image.
:return: a tuple of `(width, height)` properties of the chosen bitmap.
"""
if index >= len(self._images):
raise Exception("Wrong index in image list")
bmp = self._images[index]
return bmp.GetWidth(), bmp.GetHeight()
def Draw(self, index, dc, x, y, flags, solidBackground=True):
"""
Draws a specified image onto a device context.
:param `index`: the image index, starting from zero;
:param `dc`: an instance of :class:`wx.DC`;
:param `x`: x position on the device context;
:param `y`: y position on the device context;
:param `flags`: how to draw the image. A bitlist of a selection of the following:
================================= =======================================
Flag Paarameter Description
================================= =======================================
``wx.IMAGELIST_DRAW_NORMAL`` Draw the image normally
``wx.IMAGELIST_DRAW_TRANSPARENT`` Draw the image with transparency
``wx.IMAGELIST_DRAW_SELECTED`` Draw the image in selected state
``wx.IMAGELIST_DRAW_FOCUSED`` Draw the image in a focused state
================================= =======================================
:param `solidBackground`: currently unused.
"""
if index >= len(self._images):
raise Exception("Wrong index in image list")
bmp = self._images[index]
dc.DrawBitmap(bmp, x, y, (flags & wx.IMAGELIST_DRAW_TRANSPARENT) > 0)
return True
class SelectionStore(object):
"""
SelectionStore is used to store the selected items in the virtual
controls, i.e. it is well suited for storing even when the control contains
a huge (practically infinite) number of items.
Of course, internally it still has to store the selected items somehow (as
an array currently) but the advantage is that it can handle the selection
of all items (common operation) efficiently and that it could be made even
smarter in the future (e.g. store the selections as an array of ranges +
individual items) without changing its API.
"""
def __init__(self):
""" Default class constructor. """
# the array of items whose selection state is different from default
self._itemsSel = []
# the default state: normally, False (i.e. off) but maybe set to true if
# there are more selected items than non selected ones - this allows to
# handle selection of all items efficiently
self._defaultState = False
# the total number of items we handle
self._count = 0
# special case of SetItemCount(0)
def Clear(self):
""" Clears the number of selected items. """
self._itemsSel = []
self._count = 0
self._defaultState = False
# return the total number of selected items
def GetSelectedCount(self):
""" Return the total number of selected items. """
return (self._defaultState and [self._count - len(self._itemsSel)] or [len(self._itemsSel)])[0]
def IsSelected(self, item):
"""
Returns ``True`` if the given item is selected.
:param `item`: the item to check for selection state.
"""
isSel = item in self._itemsSel
# if the default state is to be selected, being in m_itemsSel means that
# the item is not selected, so we have to inverse the logic
return (self._defaultState and [not isSel] or [isSel])[0]
def SelectItem(self, item, select=True):
"""
Selects the given item.
:param `item`: the item to select;
:param `select`: ``True`` to select the item, ``False`` otherwise.
:return: ``True`` if the items selection really changed.
"""
# search for the item ourselves as like this we get the index where to
# insert it later if needed, so we do only one search in the array instead
# of two (adding item to a sorted array requires a search)
index = bisect.bisect_right(self._itemsSel, item)
isSel = index < len(self._itemsSel) and self._itemsSel[index] == item
if select != self._defaultState:
if item not in self._itemsSel:
bisect.insort_right(self._itemsSel, item)
return True
else: # reset to default state
if item in self._itemsSel:
self._itemsSel.remove(item)
return True
return False
def SelectRange(self, itemFrom, itemTo, select=True):
"""
Selects a range of items.
:param `itemFrom`: the first index of the selection range;
:param `itemTo`: the last index of the selection range;
:param `select`: ``True`` to select the items, ``False`` otherwise.
:return: ``True`` and fill the `itemsChanged` array with the indices of items
which have changed state if "few" of them did, otherwise return ``False``
(meaning that too many items changed state to bother counting them individually).
"""
# 100 is hardcoded but it shouldn't matter much: the important thing is
# that we don't refresh everything when really few (e.g. 1 or 2) items
# change state
MANY_ITEMS = 100
# many items (> half) changed state
itemsChanged = []
# are we going to have more [un]selected items than the other ones?
if itemTo - itemFrom > self._count/2:
if select != self._defaultState:
# the default state now becomes the same as 'select'
self._defaultState = select
# so all the old selections (which had state select) shouldn't be
# selected any more, but all the other ones should
selOld = self._itemsSel[:]
self._itemsSel = []
# TODO: it should be possible to optimize the searches a bit
# knowing the possible range
for item in range(itemFrom):
if item not in selOld:
self._itemsSel.append(item)
for item in range(itemTo + 1, self._count):
if item not in selOld:
self._itemsSel.append(item)
else: # select == self._defaultState
# get the inclusive range of items between itemFrom and itemTo
count = len(self._itemsSel)
start = bisect.bisect_right(self._itemsSel, itemFrom)
end = bisect.bisect_right(self._itemsSel, itemTo)
if itemFrom < start:
start = itemFrom
if start == count or self._itemsSel[start] < itemFrom:
start += 1
if end == count or self._itemsSel[end] > itemTo:
end -= 1
if start <= end:
# delete all of them (from end to avoid changing indices)
for i in range(end, start-1, -1):
if itemsChanged:
if len(itemsChanged) > MANY_ITEMS:
# stop counting (see comment below)
itemsChanged = []
else:
itemsChanged.append(self._itemsSel[i])
self._itemsSel.pop(i)
else:
self._itemsSel = []
else: # "few" items change state
if itemsChanged:
itemsChanged = []
# just add the items to the selection
for item in range(itemFrom, itemTo+1):
if self.SelectItem(item, select) and itemsChanged:
itemsChanged.append(item)
if len(itemsChanged) > MANY_ITEMS:
# stop counting them, we'll just eat gobs of memory
# for nothing at all - faster to refresh everything in
# this case
itemsChanged = []
# we set it to None if there are many items changing state
return itemsChanged
def OnItemDelete(self, item):
"""
Must be called when an item is deleted.
:param `item`: the item that is being deleted.
"""
count = len(self._itemsSel)
i = bisect.bisect_right(self._itemsSel, item)
if i < count and self._itemsSel[i] == item:
# this item itself was in m_itemsSel, remove it from there
self._itemsSel.pop(i)
count -= 1
# and adjust the index of all which follow it
while i < count:
i += 1
self._itemsSel[i] -= 1
def SetItemCount(self, count):
"""
Sets the total number of items we handle.
:param `count`: the total number of items we handle.
"""
# forget about all items whose indices are now invalid if the size
# decreased
if count < self._count:
for i in range(len(self._itemsSel), 0, -1):
if self._itemsSel[i - 1] >= count:
self._itemsSel.pop(i - 1)
# remember the new number of items
self._count = count
# ----------------------------------------------------------------------------
# UltimateListItemAttr: a structure containing the visual attributes of an item
# ----------------------------------------------------------------------------
class UltimateListItemAttr(object):
"""
Represents the attributes (colour, font, ...) of a :class:`UltimateListCtrl`
:class:`UltimateListItem`.
"""
def __init__(self, colText=wx.NullColour, colBack=wx.NullColour, font=wx.NullFont,
enabled=True, footerColText=wx.NullColour, footerColBack=wx.NullColour,
footerFont=wx.NullFont):
"""
Default class constructor.
:param `colText`: the item text colour;
:param `colBack`: the item background colour;
:param `font`: the item font;
:param `enabled`: ``True`` if the item should be enabled, ``False`` if it is disabled;
:param `footerColText`: for footer items, the item text colour;
:param `footerColBack`: for footer items, the item background colour;
:param `footerFont`: for footer items, the item font.
"""
self._colText = colText
self._colBack = colBack
self._font = font
self._enabled = enabled
self._footerColText = footerColText
self._footerColBack = footerColBack
self._footerFont = footerFont
# setters
def SetTextColour(self, colText):
"""
Sets a new text colour.
:param `colText`: an instance of :class:`wx.Colour`.
"""
self._colText = colText
def SetBackgroundColour(self, colBack):
"""
Sets a new background colour.
:param `colBack`: an instance of :class:`wx.Colour`.
"""
self._colBack = colBack
def SetFont(self, font):
"""
Sets a new font for the item.
:param `font`: an instance of :class:`wx.Font`.
"""
self._font = font
def Enable(self, enable=True):
"""
Enables or disables the item.
:param `enable`: ``True`` to enable the item, ``False`` to disable it.
"""
self._enabled = enable
def SetFooterTextColour(self, colText):
"""
Sets a new footer item text colour.
:param `colText`: an instance of :class:`wx.Colour`.
"""
self._footerColText = colText
def SetFooterBackgroundColour(self, colBack):
"""
Sets a new footer item background colour.
:param `colBack`: an instance of :class:`wx.Colour`.
"""
self._footerColBack = colBack
def SetFooterFont(self, font):
"""
Sets a new font for the footer item.
:param `font`: an instance of :class:`wx.Font`.
"""
self._footerFont = font
# accessors
def HasTextColour(self):
""" Returns ``True`` if the currently set text colour is valid. """
return self._colText.IsOk()
def HasBackgroundColour(self):
""" Returns ``True`` if the currently set background colour is valid. """
return self._colBack.IsOk()
def HasFont(self):
""" Returns ``True`` if the currently set font is valid. """
return self._font.IsOk()
def HasFooterTextColour(self):
"""
Returns ``True`` if the currently set text colour for the footer item
is valid.
"""
return self._footerColText.IsOk()
def HasFooterBackgroundColour(self):
"""
Returns ``True`` if the currently set background colour for the footer item
is valid.
"""
return self._footerColBack.IsOk()
def HasFooterFont(self):
"""
Returns ``True`` if the currently set font for the footer item
is valid.
"""
return self._footerFont.IsOk()
# getters
def GetTextColour(self):
""" Returns the currently set text colour. """
return self._colText
def GetBackgroundColour(self):
""" Returns the currently set background colour. """
return self._colBack
def GetFont(self):
""" Returns the currently set item font. """
return self._font
def GetFooterTextColour(self):
""" Returns the currently set text colour for a footer item. """
return self._footerColText
def GetFooterBackgroundColour(self):
""" Returns the currently set background colour for a footer item. """
return self._footerColBack
def GetFooterFont(self):
""" Returns the currently set font for a footer item. """
return self._footerFont
def IsEnabled(self):
""" Returns ``True`` if the item is enabled. """
return self._enabled
# ----------------------------------------------------------------------------
# UltimateListItem: the item or column info, used to exchange data with UltimateListCtrl
# ----------------------------------------------------------------------------
class UltimateListItem(wx.Object):
""" This class stores information about a :class:`UltimateListCtrl` item or column. """
def __init__(self, item=None):
"""
Default class constructor.
:param `item`: if not ``None``, another instance of :class:`UltimateListItem`.
"""
if not item:
self.Init()
self._attr = None
else:
self._mask = item._mask # Indicates what fields are valid
self._itemId = item._itemId # The zero-based item position
self._col = item._col # Zero-based column, if in report mode
self._state = item._state # The state of the item
self._stateMask = item._stateMask # Which flags of self._state are valid (uses same flags)
self._text = item._text # The label/header text
self._tooltip = item._tooltip # The label/header tooltip text
self._image = item._image[:] # The zero-based indexes into an image list
self._data = item._data # App-defined data
self._pyData = item._pyData # Python-specific data
self._format = item._format # left, right, centre
self._width = item._width # width of column
self._colour = item._colour # item text colour
self._font = item._font # item font
self._checked = item._checked # The checking state for the item (if kind > 0)
self._kind = item._kind # Whether it is a normal, checkbox-like or a radiobutton-like item
self._enabled = item._enabled # Whether the item is enabled or not
self._hypertext = item._hypertext # indicates if the item is hypertext
self._visited = item._visited # visited state for an hypertext item
self._wnd = item._wnd
self._windowenabled = item._windowenabled
self._windowsize = item._windowsize
self._isColumnShown = item._isColumnShown
self._customRenderer = item._customRenderer
self._overFlow = item._overFlow
self._footerChecked = item._footerChecked
self._footerFormat = item._footerFormat
self._footerImage = item._footerImage
self._footerKind = item._footerKind
self._footerText = item._footerText
self._expandWin = item._expandWin
self._attr = None
# copy list item attributes
if item.HasAttributes():
self._attr = item.GetAttributes()[:]
# resetting
def Clear(self):
""" Resets the item state to the default. """
self.Init()
self._text = ""
self.ClearAttributes()
def ClearAttributes(self):
""" Deletes the item attributes if they have been stored. """
if self._attr:
del self._attr
self._attr = None
# setters
def SetMask(self, mask):
"""
Sets the mask of valid fields.
:param `mask`: any combination of the following bits:
============================ ========= ==============================
Mask Bits Hex Value Description
============================ ========= ==============================
``ULC_MASK_STATE`` 0x1 :meth:`~UltimateListItem.GetState` is valid
``ULC_MASK_TEXT`` 0x2 :meth:`~UltimateListItem.GetText` is valid
``ULC_MASK_IMAGE`` 0x4 :meth:`~UltimateListItem.GetImage` is valid
``ULC_MASK_DATA`` 0x8 :meth:`~UltimateListItem.GetData` is valid
``ULC_MASK_WIDTH`` 0x20 :meth:`~UltimateListItem.GetWidth` is valid
``ULC_MASK_FORMAT`` 0x40 :meth:`~UltimateListItem.GetFormat` is valid
``ULC_MASK_FONTCOLOUR`` 0x80 :meth:`~UltimateListItem.GetTextColour` is valid
``ULC_MASK_FONT`` 0x100 :meth:`~UltimateListItem.GetFont` is valid
``ULC_MASK_BACKCOLOUR`` 0x200 :meth:`~UltimateListItem.GetBackgroundColour` is valid
``ULC_MASK_KIND`` 0x400 :meth:`~UltimateListItem.GetKind` is valid
``ULC_MASK_ENABLE`` 0x800 :meth:`~UltimateListItem.IsEnabled` is valid
``ULC_MASK_CHECK`` 0x1000 :meth:`~UltimateListItem.IsChecked` is valid
``ULC_MASK_HYPERTEXT`` 0x2000 :meth:`~UltimateListItem.IsHyperText` is valid
``ULC_MASK_WINDOW`` 0x4000 :meth:`~UltimateListItem.GetWindow` is valid
``ULC_MASK_PYDATA`` 0x8000 :meth:`~UltimateListItem.GetPyData` is valid
``ULC_MASK_SHOWN`` 0x10000 :meth:`~UltimateListItem.IsShown` is valid
``ULC_MASK_RENDERER`` 0x20000 :meth:`~UltimateListItem.GetCustomRenderer` is valid
``ULC_MASK_OVERFLOW`` 0x40000 :meth:`~UltimateListItem.GetOverFlow` is valid
``ULC_MASK_FOOTER_TEXT`` 0x80000 :meth:`~UltimateListItem.GetFooterText` is valid
``ULC_MASK_FOOTER_IMAGE`` 0x100000 :meth:`~UltimateListItem.GetFooterImage` is valid
``ULC_MASK_FOOTER_FORMAT`` 0x200000 :meth:`~UltimateListItem.GetFooterFormat` is valid
``ULC_MASK_FOOTER_FONT`` 0x400000 :meth:`~UltimateListItem.GetFooterFont` is valid
``ULC_MASK_FOOTER_CHECK`` 0x800000 :meth:`~UltimateListItem.IsFooterChecked` is valid
``ULC_MASK_FOOTER_KIND`` 0x1000000 :meth:`~UltimateListItem.GetFooterKind` is valid
============================ ========= ==============================
"""
self._mask = mask
def SetId(self, id):
"""
Sets the zero-based item position.
:param `id`: the zero-based item position.
"""
self._itemId = id
def SetColumn(self, col):
"""
Sets the zero-based column.
:param `col`: the zero-based column.
:note: This method is neaningful only in report mode.
"""
self._col = col
def SetState(self, state):
"""
Sets the item state flags.
:param `state`: any combination of the following bits:
============================ ========= ==============================
State Bits Hex Value Description
============================ ========= ==============================
``ULC_STATE_DONTCARE`` 0x0 Don't care what the state is
``ULC_STATE_DROPHILITED`` 0x1 The item is highlighted to receive a drop event
``ULC_STATE_FOCUSED`` 0x2 The item has the focus
``ULC_STATE_SELECTED`` 0x4 The item is selected
``ULC_STATE_CUT`` 0x8 The item is in the cut state
``ULC_STATE_DISABLED`` 0x10 The item is disabled
``ULC_STATE_FILTERED`` 0x20 The item has been filtered
``ULC_STATE_INUSE`` 0x40 The item is in use
``ULC_STATE_PICKED`` 0x80 The item has been picked
``ULC_STATE_SOURCE`` 0x100 The item is a drag and drop source
============================ ========= ==============================
:note: The valid state flags are influenced by the value of the state mask.
:see: :meth:`~UltimateListItem.SetStateMask`
"""
self._mask |= ULC_MASK_STATE
self._state = state
self._stateMask |= state
def SetStateMask(self, stateMask):
"""
Sets the bitmask that is used to determine which of the state flags are
to be set.
:param `stateMask`: the state bitmask.
:see: :meth:`~UltimateListItem.SetState` for a list of valid state bits.
"""
self._stateMask = stateMask
def SetText(self, text):
"""
Sets the text label for the item.
:param `text`: the text label for the item.
"""
self._mask |= ULC_MASK_TEXT
self._text = text
def SetToolTip(self, text):
"""
Sets the tooltip text for the item.
:param `text`: the tooltip text for the item.
"""
self._mask |= ULC_MASK_TOOLTIP
self._tooltip = text
def SetImage(self, image):
"""
Sets the zero-based indexes of the images associated with the item into the
image list.
:param `image`: a Python list with the zero-based indexes of the images
associated with the item into the image list.
"""
self._mask |= ULC_MASK_IMAGE
if image is None:
image = []
self._image = to_list(image)
def SetData(self, data):
"""
Sets client data for the item.
:param `data`: the client data associated to the item.
:note: Please note that client data is associated with the item and not
with subitems.
"""
self._mask |= ULC_MASK_DATA
self._data = data
def SetPyData(self, pyData):
"""
Sets data for the item, which can be any Python object.
:param `data`: any Python object associated to the item.
:note: Please note that Python data is associated with the item and not
with subitems.
"""
self._mask |= ULC_MASK_PYDATA
self._pyData = pyData
def SetWidth(self, width):
"""
Sets the column width.
:param `width`: the column width.
:note: This method is meaningful only for column headers in report mode.
"""
self._mask |= ULC_MASK_WIDTH
self._width = width
def SetAlign(self, align):
"""
Sets the alignment for the item.
:param `align`: one of the following bits:
============================ ========= ==============================
Alignment Bits Hex Value Description
============================ ========= ==============================
``ULC_FORMAT_LEFT`` 0x0 The item is left-aligned
``ULC_FORMAT_RIGHT`` 0x1 The item is right-aligned
``ULC_FORMAT_CENTRE`` 0x2 The item is centre-aligned
``ULC_FORMAT_CENTER`` 0x2 The item is center-aligned
============================ ========= ==============================
"""
self._mask |= ULC_MASK_FORMAT
self._format = align
def SetTextColour(self, colText):
"""
Sets the text colour for the item.
:param `colText`: a valid :class:`wx.Colour` object.
"""
self.Attributes().SetTextColour(colText)
def SetBackgroundColour(self, colBack):
"""
Sets the background colour for the item.
:param `colBack`: a valid :class:`wx.Colour` object.
"""
self.Attributes().SetBackgroundColour(colBack)
def SetFont(self, font):
"""
Sets the font for the item.
:param `font`: a valid :class:`wx.Font` object.
"""
self.Attributes().SetFont(font)
def SetFooterTextColour(self, colText):
"""
Sets the text colour for the footer item.
:param `colText`: a valid :class:`wx.Colour` object.
"""
self.Attributes().SetFooterTextColour(colText)
def SetFooterBackgroundColour(self, colBack):
"""
Sets the background colour for the footer item.
:param `colBack`: a valid :class:`wx.Colour` object.
"""
self.Attributes().SetFooterBackgroundColour(colBack)
def SetFooterFont(self, font):
"""
Sets the font for the footer item.
:param `font`: a valid :class:`wx.Font` object.
"""
self.Attributes().SetFooterFont(font)
def Enable(self, enable=True):
"""
Enables or disables the item.
:param `enable`: ``True`` to enable the item, ``False`` to disable it.
"""
self.Attributes().Enable(enable)
# accessors
def GetMask(self):
"""
Returns a bit mask indicating which fields of the structure are valid.
:see: :meth:`~UltimateListItem.SetMask` for a list of valid bit masks.
"""
return self._mask
def GetId(self):
""" Returns the zero-based item position. """
return self._itemId
def GetColumn(self):
"""
Returns the zero-based column.
:note: This method is meaningful only in report mode.
"""
return self._col
def GetFormat(self):
""" Returns the header item format. """
return self._format
def GetState(self):
"""
Returns a bit field representing the state of the item.
:see: :meth:`~UltimateListItem.SetState` for a list of valid item states.
"""
return self._state & self._stateMask
def GetText(self):
""" Returns the label/header text. """
return self._text
def GetToolTip(self):
""" Returns the label/header tooltip. """
return self._tooltip
def GetImage(self):
"""
Returns a Python list with the zero-based indexes of the images associated
with the item into the image list.
"""
return self._image
def GetData(self):
"""
Returns client data associated with the control.
:note: Please note that client data is associated with the item and not
with subitems.
"""
return self._data
def GetPyData(self):
"""
Returns data for the item, which can be any Python object.
:note: Please note that Python data is associated with the item and not
with subitems.
"""
return self._pyData
def GetWidth(self):
"""
Returns the column width.
:note: This method is meaningful only for column headers in report mode.
"""
return self._width
def GetAlign(self):
"""
Returns the alignment for the item.
:see: :meth:`~UltimateListItem.SetAlign` for a list of valid alignment bits.
"""
return self._format
def GetAttributes(self):
""" Returns the associated :class:`UltimateListItemAttr` attributes. """
return self._attr
def HasAttributes(self):
""" Returns ``True`` if the item has attributes associated with it. """
return self._attr != None
def GetTextColour(self):
""" Returns the text colour. """
return (self.HasAttributes() and [self._attr.GetTextColour()] or [wx.NullColour])[0]
def GetBackgroundColour(self):
""" Returns the background colour. """
return (self.HasAttributes() and [self._attr.GetBackgroundColour()] or [wx.NullColour])[0]
def GetFont(self):
""" Returns the item font. """
return (self.HasAttributes() and [self._attr.GetFont()] or [wx.NullFont])[0]
def IsEnabled(self):
""" Returns ``True`` if the item is enabled. """
return (self.HasAttributes() and [self._attr.IsEnabled()] or [True])[0]
# creates self._attr if we don't have it yet
def Attributes(self):
"""
Returns the associated attributes if they exist, or create a new :class:`UltimateListItemAttr`
structure and associate it with this item.
"""
if not self._attr:
self._attr = UltimateListItemAttr()
return self._attr
def SetKind(self, kind):
"""
Sets the item kind.
:param `kind`: may be one of the following integers:
=============== ==========================
Item Kind Description
=============== ==========================
0 A normal item
1 A checkbox-like item
2 A radiobutton-type item
=============== ==========================
"""
self._mask |= ULC_MASK_KIND
self._kind = kind
def GetKind(self):
"""
Returns the item kind.
:see: :meth:`~UltimateListItem.SetKind` for a valid list of item's kind.
"""
return self._kind
def IsChecked(self):
""" Returns whether the item is checked or not. """
return self._checked
def Check(self, checked=True):
"""
Checks/unchecks an item.
:param `checked`: ``True`` to check an item, ``False`` to uncheck it.
:note: This method is meaningful only for check and radio items.
"""
self._mask |= ULC_MASK_CHECK
self._checked = checked
def IsShown(self):
""" Returns ``True`` if the item is shown, or ``False`` if it is hidden. """
return self._isColumnShown
def SetShown(self, shown=True):
"""
Sets an item as shown/hidden.
:param `shown`: ``True`` to show the item, ``False`` to hide it.
"""
self._mask |= ULC_MASK_SHOWN
self._isColumnShown = shown
def SetHyperText(self, hyper=True):
"""
Sets whether the item is hypertext or not.
:param `hyper`: ``True`` to set hypertext behaviour, ``False`` otherwise.
"""
self._mask |= ULC_MASK_HYPERTEXT
self._hypertext = hyper
def SetVisited(self, visited=True):
"""
Sets whether an hypertext item was visited or not.
:param `visited`: ``True`` to set a hypertext item as visited, ``False`` otherwise.
"""
self._mask |= ULC_MASK_HYPERTEXT
self._visited = visited
def GetVisited(self):
""" Returns whether an hypertext item was visited or not. """
return self._visited
def IsHyperText(self):
""" Returns whether the item is hypetext or not. """
return self._hypertext
def SetWindow(self, wnd, expand=False):
"""
Sets the window associated to the item.
:param `wnd`: a non-toplevel window to be displayed next to the item;
:param `expand`: ``True`` to expand the column where the item/subitem lives,
so that the window will be fully visible.
"""
self._mask |= ULC_MASK_WINDOW
self._wnd = wnd
listCtrl = wnd.GetParent()
mainWin = listCtrl._mainWin
wnd.Reparent(mainWin)
if wnd.GetSizer(): # the window is a complex one hold by a sizer
size = wnd.GetBestSize()
else: # simple window, without sizers
size = wnd.GetSize()
# We have to bind the wx.EVT_SET_FOCUS for the associated window
# No other solution to handle the focus changing from an item in
# UltimateListCtrl and the window associated to an item
# Do better strategies exist?
self._wnd.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
self._windowsize = size
# The window is enabled only if the item is enabled
self._wnd.Enable(self._enabled)
self._windowenabled = self._enabled
self._expandWin = expand
mainWin._hasWindows = True
mainWin._itemWithWindow.append(self)
# This is needed as otherwise widgets that should be invisible
# are shown at the top left corner of ULC
mainWin.HideWindows()
mainWin.Refresh()
def GetWindow(self):
""" Returns the window associated to the item. """
return self._wnd
def DeleteWindow(self):
""" Deletes the window associated to the item (if any). """
if self._wnd:
listCtrl = self._wnd.GetParent()
if self in listCtrl._itemWithWindow:
listCtrl._itemWithWindow.remove(self)
self._wnd.Destroy()
self._wnd = None
def GetWindowEnabled(self):
""" Returns whether the associated window is enabled or not. """
if not self._wnd:
raise Exception("\nERROR: This Item Has No Window Associated")
return self._windowenabled
def SetWindowEnabled(self, enable=True):
"""
Sets whether the associated window is enabled or not.
:param `enable`: ``True`` to enable the associated window, ``False`` to disable it.
"""
if not self._wnd:
raise Exception("\nERROR: This Item Has No Window Associated")
self._windowenabled = enable
self._wnd.Enable(enable)
def GetWindowSize(self):
""" Returns the associated window size. """
return self._windowsize
def SetCustomRenderer(self, renderer):
"""
Associate a custom renderer to this item.
:param `renderer`: a class able to correctly render the item.
:note: the renderer class **must** implement the methods `DrawSubItem`,
`GetLineHeight` and `GetSubItemWidth`.
"""
self._mask |= ULC_MASK_RENDERER
self._customRenderer = renderer
def GetCustomRenderer(self):
""" Returns the custom renderer associated with this item (if any). """
return self._customRenderer
def SetOverFlow(self, over=True):
"""
Sets the item in the overflow/non overflow state.
An item/subitem may overwrite neighboring items/subitems if its text would
not normally fit in the space allotted to it.
:param `over`: ``True`` to set the item in a overflow state, ``False`` otherwise.
"""
self._mask |= ULC_MASK_OVERFLOW
self._overFlow = over
def GetOverFlow(self):
"""
Returns if the item is in the overflow state.
An item/subitem may overwrite neighboring items/subitems if its text would
not normally fit in the space allotted to it.
"""
return self._overFlow
def Init(self):
""" Initializes an empty :class:`UltimateListItem`. """
self._mask = 0
self._itemId = 0
self._col = 0
self._state = 0
self._stateMask = 0
self._image = []
self._data = 0
self._pyData = None
self._text = ""
self._tooltip = ""
self._format = ULC_FORMAT_CENTRE
self._width = 0
self._colour = wx.Colour(0, 0, 0)
self._font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
self._kind = 0
self._checked = False
self._enabled = True
self._hypertext = False # indicates if the item is hypertext
self._visited = False # visited state for an hypertext item
self._wnd = None
self._windowenabled = False
self._windowsize = wx.Size()
self._isColumnShown = True
self._customRenderer = None
self._overFlow = False
self._footerChecked = False
self._footerFormat = ULC_FORMAT_CENTRE
self._footerImage = []
self._footerKind = 0
self._footerText = ""
self._expandWin = False
def SetFooterKind(self, kind):
"""
Sets the footer item kind.
:see: :meth:`~UltimateListItem.SetKind` for a list of valid items kind.
"""
self._mask |= ULC_MASK_FOOTER_KIND
self._footerKind = kind
def GetFooterKind(self):
"""
Returns the footer item kind.
:see: :meth:`~UltimateListItem.SetKind` for a list of valid items kind.
"""
return self._footerKind
def IsFooterChecked(self):
""" Returns whether the footer item is checked or not. """
return self._footerChecked
def CheckFooter(self, checked=True):
"""
Checks/unchecks a footer item.
:param `checked`: ``True`` to check an item, ``False`` to uncheck it.
:note: This method is meaningful only for check and radio footer items.
"""
self._mask |= ULC_MASK_FOOTER_CHECK
self._footerChecked = checked
def GetFooterFormat(self):
""" Returns the footer item format. """
return self._footerFormat
def SetFooterFormat(self, format):
"""
Sets the footer item format.
:param `format`: the footer item format.
"""
self._mask |= ULC_MASK_FOOTER_FORMAT
self._footerFormat = format
def GetFooterText(self):
""" Returns the footer text. """
return self._footerText
def SetFooterText(self, text):
"""
Sets the text label for the footer item.
:param `text`: the text label for the footer item.
"""
self._mask |= ULC_MASK_FOOTER_TEXT
self._footerText = text
def GetFooterImage(self):
"""
Returns the zero-based index of the image associated with the footer item into
the image list.
"""
return self._footerImage
def SetFooterImage(self, image):
"""
Sets the zero-based index of the image associated with the footer item into the
image list.
:param `image`: the zero-based index of the image associated with the footer item
into the image list.
"""
self._mask |= ULC_MASK_FOOTER_IMAGE
self._footerImage = to_list(image)
def GetFooterTextColour(self):
""" Returns the footer item text colour. """
return (self.HasAttributes() and [self._attr.GetFooterTextColour()] or [wx.NullColour])[0]
def GetFooterBackgroundColour(self):
""" Returns the footer item background colour. """
return (self.HasAttributes() and [self._attr.GetFooterBackgroundColour()] or [wx.NullColour])[0]
def GetFooterFont(self):
""" Returns the footer item font. """
return (self.HasAttributes() and [self._attr.GetFooterFont()] or [wx.NullFont])[0]
def SetFooterAlign(self, align):
"""
Sets the alignment for the footer item.
:see: :meth:`~UltimateListItem.SetAlign` for a list of valid alignment flags.
"""
self._mask |= ULC_MASK_FOOTER_FORMAT
self._footerFormat = align
def GetFooterAlign(self):
"""
Returns the alignment for the footer item.
:see: :meth:`~UltimateListItem.SetAlign` for a list of valid alignment flags.
"""
return self._footerFormat
def OnSetFocus(self, event):
"""
Handles the ``wx.EVT_SET_FOCUS`` event for the window associated to an item.
:param `event`: a :class:`FocusEvent` event to be processed.
"""
listCtrl = self._wnd.GetParent()
select = listCtrl.GetItemState(self._itemId, ULC_STATE_SELECTED)
# If the window is associated to an item that currently is selected
# (has focus) we don't kill the focus. Otherwise we do it.
if not select:
listCtrl._hasFocus = False
else:
listCtrl._hasFocus = True
listCtrl.SetFocus()
event.Skip()
# ----------------------------------------------------------------------------
# ListEvent - the event class for the UltimateListCtrl notifications
# ----------------------------------------------------------------------------
class CommandListEvent(wx.PyCommandEvent):
"""
A list event holds information about events associated with :class:`UltimateListCtrl`
objects.
"""
def __init__(self, commandTypeOrEvent=None, winid=0):
"""
Default class constructor.
For internal use: do not call it in your code!
:param `commandTypeOrEvent`: the event type or another instance of
:class:`PyCommandEvent`;
:param `winid`: the event identifier.
"""
if type(commandTypeOrEvent) in INTEGER_TYPES:
wx.PyCommandEvent.__init__(self, commandTypeOrEvent, winid)
self.m_code = 0
self.m_oldItemIndex = 0
self.m_itemIndex = 0
self.m_col = 0
self.m_pointDrag = wx.Point()
self.m_item = UltimateListItem()
self.m_editCancelled = False
else:
wx.PyCommandEvent.__init__(self, commandTypeOrEvent.GetEventType(), commandTypeOrEvent.GetId())
self.m_code = commandTypeOrEvent.m_code
self.m_oldItemIndex = commandTypeOrEvent.m_oldItemIndex
self.m_itemIndex = commandTypeOrEvent.m_itemIndex
self.m_col = commandTypeOrEvent.m_col
self.m_pointDrag = commandTypeOrEvent.m_pointDrag
self.m_item = commandTypeOrEvent.m_item
self.m_editCancelled = commandTypeOrEvent.m_editCancelled
def GetKeyCode(self):
""" Returns the key code if the event is a keypress event. """
return self.m_code
def GetIndex(self):
""" Returns the item index. """
return self.m_itemIndex
Index = property(GetIndex, doc="See `GetIndex`")
def GetColumn(self):
"""
Returns the column position: it is only used with ``COL`` events.
For the column dragging events, it is the column to the left of the divider
being dragged, for the column click events it may be -1 if the user clicked
in the list control header outside any column.
"""
return self.m_col
def GetPoint(self):
""" Returns the position of the mouse pointer if the event is a drag event. """
return self.m_pointDrag
def GetLabel(self):
""" Returns the (new) item label for ``EVT_LIST_END_LABEL_EDIT`` event. """
return self.m_item._text
def GetText(self):
""" Returns the item text. """
return self.m_item._text
def GetImage(self):
""" Returns the item image. """
return self.m_item._image
def GetData(self):
""" Returns the item data. """
return self.m_item._data
def GetMask(self):
""" Returns the item mask. """
return self.m_item._mask
def GetItem(self):
""" Returns the item itself. """
return self.m_item
# for wxEVT_COMMAND_LIST_CACHE_HINT only
def GetCacheFrom(self):
"""
Returns the first item which the list control advises us to cache.
:note: This method is meaningful for ``EVT_LIST_CACHE_HINT`` event only.
"""
return self.m_oldItemIndex
def GetCacheTo(self):
"""
Returns the last item (inclusive) which the list control advises us to cache.
:note: This method is meaningful for ``EVT_LIST_CACHE_HINT`` event only.
"""
return self.m_itemIndex
# was label editing canceled? (for wxEVT_COMMAND_LIST_END_LABEL_EDIT only)
def IsEditCancelled(self):
"""
Returns ``True`` if it the label editing has been cancelled by the user
(:meth:`~CommandListEvent.GetLabel` returns an empty string in this case but it doesn't allow
the application to distinguish between really cancelling the edit and
the admittedly rare case when the user wants to rename it to an empty
string).
:note: This method only makes sense for ``EVT_LIST_END_LABEL_EDIT`` messages.
"""
return self.m_editCancelled
def SetEditCanceled(self, editCancelled):
"""
Sets the item editing as cancelled/not cancelled.
:param `editCancelled`: ``True`` to set the item editing as cancelled, ``False``
otherwise.
:note: This method only makes sense for ``EVT_LIST_END_LABEL_EDIT`` messages.
"""
self.m_editCancelled = editCancelled
# ----------------------------------------------------------------------------
# UltimateListEvent is a special class for all events associated with list controls
#
# NB: note that not all accessors make sense for all events, see the event
# descriptions below
# ----------------------------------------------------------------------------
class UltimateListEvent(CommandListEvent):
"""
A list event holds information about events associated with :class:`UltimateListCtrl`
objects.
"""
def __init__(self, commandTypeOrEvent=None, winid=0):
"""
Default class constructor.
For internal use: do not call it in your code!
:param `commandTypeOrEvent`: the event type or another instance of
:class:`PyCommandEvent`;
:param `winid`: the event identifier.
"""
CommandListEvent.__init__(self, commandTypeOrEvent, winid)
if type(commandTypeOrEvent) in INTEGER_TYPES:
self.notify = wx.NotifyEvent(commandTypeOrEvent, winid)
else:
self.notify = wx.NotifyEvent(commandTypeOrEvent.GetEventType(), commandTypeOrEvent.GetId())
def GetNotifyEvent(self):
""" Returns the actual :class:`NotifyEvent`. """
return self.notify
def IsAllowed(self):
"""
Returns ``True`` if the change is allowed (:meth:`~UltimateListEvent.Veto` hasn't been called) or
``False`` otherwise (if it was).
"""
return self.notify.IsAllowed()
def Veto(self):
"""
Prevents the change announced by this event from happening.
:note: It is in general a good idea to notify the user about the reasons
for vetoing the change because otherwise the applications behaviour (which
just refuses to do what the user wants) might be quite surprising.
"""
self.notify.Veto()
def Allow(self):
"""
This is the opposite of :meth:`~UltimateListEvent.Veto`: it explicitly allows the event to be processed.
For most events it is not necessary to call this method as the events are
allowed anyhow but some are forbidden by default (this will be mentioned
in the corresponding event description).
"""
self.notify.Allow()
# ============================================================================
# private classes
# ============================================================================
#-----------------------------------------------------------------------------
# ColWidthInfo (internal)
#-----------------------------------------------------------------------------
class ColWidthInfo(object):
""" A simple class which holds information about :class:`UltimateListCtrl` columns. """
def __init__(self, w=0, needsUpdate=True):
"""
Default class constructor
:param `w`: the initial width of the column;
:param `needsUpdate`: ``True`` if the column needs refreshing, ``False``
otherwise.
"""
self._nMaxWidth = w
self._bNeedsUpdate = needsUpdate
#-----------------------------------------------------------------------------
# UltimateListItemData (internal)
#-----------------------------------------------------------------------------
class UltimateListItemData(object):
"""
A simple class which holds information about :class:`UltimateListItem` visual
attributes (client rectangles, positions, etc...).
"""
def __init__(self, owner):
"""
Default class constructor
:param `owner`: an instance of :class:`UltimateListCtrl`.
"""
# the list ctrl we are in
self._owner = owner
self.Init()
# the item coordinates are not used in report mode, instead this pointer
# is None and the owner window is used to retrieve the item position and
# size
if owner.InReportView():
self._rect = None
else:
self._rect = wx.Rect()
def SetImage(self, image):
"""
Sets the zero-based indexes of the images associated with the item into the
image list.
:param `image`: a Python list with the zero-based indexes of the images
associated with the item into the image list.
"""
self._image = to_list(image)
def SetData(self, data):
"""
Sets client data for the item.
:param `data`: the client data associated to the item.
:note: Please note that client data is associated with the item and not
with subitems.
"""
self._data = data
def HasText(self):
""" Returns ``True`` if the item text is not the empty string. """
return self._text != ""
def GetText(self):
""" Returns the item text. """
return self._text
def GetToolTip(self):
""" Returns the item tooltip. """
return self._tooltip
def GetBackgroundColour(self):
""" Returns the currently set background colour. """
return self._backColour
def GetColour(self):
""" Returns the currently set text colour. """
return self._colour
def GetFont(self):
""" Returns the currently set font. """
return (self._hasFont and [self._font] or [wx.NullFont])[0]
def SetText(self, text):
"""
Sets the text label for the item.
:param `text`: the text label for the item.
"""
self._text = text
def SetToolTip(self, tooltip):
"""
Sets the tooltip for the item
:param `tooltip`: the tooltip text
"""
self._tooltip = tooltip
def SetColour(self, colour):
"""
Sets the text colour for the item.
:param `colour`: an instance of :class:`wx.Colour`.
"""
if colour == wx.NullColour or colour == None:
if self._hasColour:
self._hasColour = False
del self._colour
return
self._hasColour = True
self._colour = colour
def SetFont(self, font):
"""
Sets the text font for the item.
:param `font`: an instance of :class:`wx.Font`.
"""
if font == wx.NullFont:
self._hasFont = False
del self._font
return
self._hasFont = True
self._font = font
def SetBackgroundColour(self, colour):
"""
Sets the background colour for the item.
:param `colour`: an instance of :class:`wx.Colour`.
"""
if colour == wx.NullColour:
self._hasBackColour = False
del self._backColour
return
self._hasBackColour = True
self._backColour = colour
# we can't use empty string for measuring the string width/height, so
# always return something
def GetTextForMeasuring(self):
"""
Returns the item text or a simple string if the item text is the
empty string.
"""
s = self.GetText()
if not s.strip():
s = 'H'
return s
def GetImage(self):
"""
Returns a Python list with the zero-based indexes of the images associated
with the item into the image list.
"""
return self._image
def HasImage(self):
""" Returns ``True`` if the item has at least one image associated with it. """
return len(self._image) > 0
def SetKind(self, kind):
"""
Sets the item kind.
:param `kind`: may be one of the following integers:
=============== ==========================
Item Kind Description
=============== ==========================
0 A normal item
1 A checkbox-like item
2 A radiobutton-type item
=============== ==========================
"""
self._kind = kind
def GetKind(self):
"""
Returns the item kind.
:see: :meth:`~UltimateListItemData.SetKind` for a list of valid item kinds.
"""
return self._kind
def IsChecked(self):
""" Returns whether the item is checked or not. """
return self._checked
def Check(self, checked=True):
"""
Checks/unchecks an item.
:param `checked`: ``True`` to check an item, ``False`` to uncheck it.
:note: This method is meaningful only for check and radio items.
"""
self._checked = checked
def SetHyperText(self, hyper=True):
"""
Sets whether the item is hypertext or not.
:param `hyper`: ``True`` to set hypertext behaviour, ``False`` otherwise.
"""
self._hypertext = hyper
def SetVisited(self, visited=True):
"""
Sets whether an hypertext item was visited or not.
:param `visited`: ``True`` to set a hypertext item as visited, ``False`` otherwise.
"""
self._visited = visited
def GetVisited(self):
"""Returns whether an hypertext item was visited or not."""
return self._visited
def IsHyperText(self):
"""Returns whether the item is hypetext or not."""
return self._hypertext
def SetWindow(self, wnd, expand=False):
"""
Sets the window associated to the item.
:param `wnd`: a non-toplevel window to be displayed next to the item;
:param `expand`: ``True`` to expand the column where the item/subitem lives,
so that the window will be fully visible.
"""
self._mask |= ULC_MASK_WINDOW
self._wnd = wnd
if wnd.GetSizer(): # the window is a complex one hold by a sizer
size = wnd.GetBestSize()
else: # simple window, without sizers
size = wnd.GetSize()
# We have to bind the wx.EVT_SET_FOCUS for the associated window
# No other solution to handle the focus changing from an item in
# UltimateListCtrl and the window associated to an item
# Do better strategies exist?
self._windowsize = size
# The window is enabled only if the item is enabled
self._wnd.Enable(self._enabled)
self._windowenabled = self._enabled
self._expandWin = expand
def GetWindow(self):
""" Returns the window associated to the item. """
return self._wnd
def DeleteWindow(self):
""" Deletes the window associated to the item (if any). """
if self._wnd:
self._wnd.Destroy()
self._wnd = None
def GetWindowEnabled(self):
""" Returns whether the associated window is enabled or not. """
if not self._wnd:
raise Exception("\nERROR: This Item Has No Window Associated")
return self._windowenabled
def SetWindowEnabled(self, enable=True):
"""
Sets whether the associated window is enabled or not.
:param `enable`: ``True`` to enable the associated window, ``False`` to disable it.
"""
if not self._wnd:
raise Exception("\nERROR: This Item Has No Window Associated")
self._windowenabled = enable
self._wnd.Enable(enable)
def GetWindowSize(self):
""" Returns the associated window size. """
return self._windowsize
def SetAttr(self, attr):
"""
Sets the item attributes.
:param `attr`: an instance of :class:`UltimateListItemAttr`.
"""
self._attr = attr
def GetAttr(self):
""" Returns the item attributes. """
return self._attr
def HasColour(self):
""" Returns ``True`` if the currently set text colour is valid. """
return self._hasColour
def HasFont(self):
""" Returns ``True`` if the currently set font is valid. """
return self._hasFont
def HasBackgroundColour(self):
""" Returns ``True`` if the currently set background colour is valid. """
return self._hasBackColour
def SetCustomRenderer(self, renderer):
"""
Associate a custom renderer to this item.
:param `renderer`: a class able to correctly render the item.
:note: the renderer class **must** implement the methods `DrawSubItem`,
`GetLineHeight` and `GetSubItemWidth`.
"""
self._mask |= ULC_MASK_RENDERER
self._customRenderer = renderer
def GetCustomRenderer(self):
""" Returns the custom renderer associated with this item (if any). """
return self._customRenderer
def SetOverFlow(self, over=True):
"""
Sets the item in the overflow/non overflow state.
An item/subitem may overwrite neighboring items/subitems if its text would
not normally fit in the space allotted to it.
:param `over`: ``True`` to set the item in a overflow state, ``False`` otherwise.
"""
self._mask |= ULC_MASK_OVERFLOW
self._overFlow = over
def GetOverFlow(self):
"""
Returns if the item is in the overflow state.
An item/subitem may overwrite neighboring items/subitems if its text would
not normally fit in the space allotted to it.
"""
return self._overFlow
def Init(self):
""" Initializes the item data structure. """
# the item image or -1
self._image = []
# user data associated with the item
self._data = 0
self._pyData = None
self._colour = wx.Colour(0, 0, 0)
self._hasColour = False
self._hasFont = False
self._hasBackColour = False
self._text = ""
self._tooltip = ""
# kind = 0: normal item
# kind = 1: checkbox-type item
self._kind = 0
self._checked = False
self._enabled = True
# custom attributes or None
self._attr = None
self._hypertext = False
self._visited = False
self._wnd = None
self._windowenabled = True
self._windowsize = wx.Size()
self._isColumnShown = True
self._customRenderer = None
self._overFlow = False
self._expandWin = False
def SetItem(self, info):
"""
Sets information about the item.
:param `info`: an instance of :class:`UltimateListItemData`.
"""
if info._mask & ULC_MASK_TEXT:
CheckVariableRowHeight(self._owner, info._text)
self.SetText(info._text)
if info._mask & ULC_MASK_TOOLTIP:
self.SetToolTip(info._tooltip)
if info._mask & ULC_MASK_KIND:
self._kind = info._kind
if info._mask & ULC_MASK_CHECK:
self._checked = info._checked
if info._mask & ULC_MASK_ENABLE:
self._enabled = info._enabled
if info._mask & ULC_MASK_IMAGE:
self._image = info._image[:]
if info._mask & ULC_MASK_DATA:
self._data = info._data
if info._mask & ULC_MASK_PYDATA:
self._pyData = info._pyData
if info._mask & ULC_MASK_HYPERTEXT:
self._hypertext = info._hypertext
self._visited = info._visited
if info._mask & ULC_MASK_FONTCOLOUR:
self.SetColour(info.GetTextColour())
if info._mask & ULC_MASK_FONT:
self.SetFont(info.GetFont())
if info._mask & ULC_MASK_BACKCOLOUR:
self.SetBackgroundColour(info.GetBackgroundColour())
if info._mask & ULC_MASK_WINDOW:
self._wnd = info._wnd
self._windowenabled = info._windowenabled
self._windowsize = info._windowsize
self._expandWin = info._expandWin
if info._mask & ULC_MASK_SHOWN:
self._isColumnShown = info._isColumnShown
if info._mask & ULC_MASK_RENDERER:
self._customRenderer = info._customRenderer
if info._mask & ULC_MASK_OVERFLOW:
self._overFlow = info._overFlow
if info.HasAttributes():
if self._attr:
self._attr = info.GetAttributes()
else:
self._attr = UltimateListItemAttr(info.GetTextColour(), info.GetBackgroundColour(),
info.GetFont(), info.IsEnabled(), info.GetFooterTextColour(),
info.GetFooterBackgroundColour(), info.GetFooterFont())
if self._rect:
self._rect.x = -1
self._rect.y = -1
self._rect.height = 0
self._rect.width = info._width
def SetPosition(self, x, y):
"""
Sets the item position.
:param `x`: the item `x` position;
:param `y`: the item `y` position.
"""
self._rect.x = x
self._rect.y = y
def SetSize(self, width, height):
"""
Sets the item size.
:param `width`: the item width, in pixels;
:param `height`: the item height, in pixels.
"""
if width != -1:
self._rect.width = width
if height != -1:
self._rect.height = height
def IsHit(self, x, y):
"""
Returns ``True`` if the input position is inside the item client rectangle.
:param `x`: the `x` mouse position;
:param `y`: the `y` mouse position.
"""
return wx.Rect(self.GetX(), self.GetY(), self.GetWidth(), self.GetHeight()).Contains((x, y))
def GetX(self):
""" Returns the item `x` position. """
return self._rect.x
def GetY(self):
""" Returns the item `y` position. """
return self._rect.y
def GetWidth(self):
""" Returns the item width, in pixels. """
return self._rect.width
def GetHeight(self):
""" Returns the item height, in pixels. """
return self._rect.height
def GetItem(self, info):
"""
Returns information about the item.
:param `info`: an instance of :class:`UltimateListItemData`.
"""
mask = info._mask
if not mask:
# by default, get everything for backwards compatibility
mask = -1
if mask & ULC_MASK_TEXT:
info._text = self._text
if mask & ULC_MASK_TOOLTIP:
info._tooltip = self._tooltip
if mask & ULC_MASK_IMAGE:
info._image = self._image[:]
if mask & ULC_MASK_DATA:
info._data = self._data
if mask & ULC_MASK_PYDATA:
info._pyData = self._pyData
if info._mask & ULC_MASK_FONT:
info.SetFont(self.GetFont())
if mask & ULC_MASK_KIND:
info._kind = self._kind
if mask & ULC_MASK_CHECK:
info._checked = self._checked
if mask & ULC_MASK_ENABLE:
info._enabled = self._enabled
if mask & ULC_MASK_HYPERTEXT:
info._hypertext = self._hypertext
info._visited = self._visited
if mask & ULC_MASK_WINDOW:
info._wnd = self._wnd
info._windowenabled = self._windowenabled
info._windowsize = self._windowsize
info._expandWin = self._expandWin
if mask & ULC_MASK_SHOWN:
info._isColumnShown = self._isColumnShown
if mask & ULC_MASK_RENDERER:
info._customRenderer = self._customRenderer
if mask & ULC_MASK_OVERFLOW:
info._overFlow = self._overFlow
if self._attr:
if self._attr.HasTextColour():
info.SetTextColour(self._attr.GetTextColour())
if self._attr.HasBackgroundColour():
info.SetBackgroundColour(self._attr.GetBackgroundColour())
if self._attr.HasFont():
info.SetFont(self._attr.GetFont())
info.Enable(self._attr.IsEnabled())
return info
def IsEnabled(self):
""" Returns ``True`` if the item is enabled, ``False`` if it is disabled. """
return self._enabled
def Enable(self, enable=True):
"""
Enables or disables the item.
:param `enable`: ``True`` to enable the item, ``False`` to disable it.
"""
self._enabled = enable
#-----------------------------------------------------------------------------
# UltimateListHeaderData (internal)
#-----------------------------------------------------------------------------
class UltimateListHeaderData(object):
"""
A simple class which holds information about :class:`UltimateListItem` visual
attributes for the header/footer items (client rectangles, positions, etc...).
"""
def __init__(self, item=None):
"""
Default class constructor.
:param `item`: another instance of :class:`UltimateListHeaderData`.
"""
self.Init()
if item:
self.SetItem(item)
def HasText(self):
""" Returns ``True`` if the currently set text colour is valid. """
return self._text != ""
def GetText(self):
""" Returns the header/footer item text. """
return self._text
def GetToolTip(self):
""" Returns the header/footer item tooltip. """
return self._tooltip
def SetText(self, text):
"""
Sets the header/footer item text.
:param `text`: the new header/footer text.
"""
self._text = text
def SetToolTip(self, tip):
"""
Sets the header/footer item tooltip.
:param `tip`: the new header/footer tooltip.
"""
self._tip = tip
def GetFont(self):
""" Returns the header/footer item font. """
return self._font
def Init(self):
""" Initializes the header/footer item. """
self._mask = 0
self._image = []
self._format = 0
self._width = 0
self._xpos = 0
self._ypos = 0
self._height = 0
self._text = ""
self._tooltip = ""
self._kind = 0
self._checked = False
self._font = wx.NullFont
self._state = 0
self._isColumnShown = True
self._customRenderer = None
self._footerImage = []
self._footerFormat = 0
self._footerText = ""
self._footerKind = 0
self._footerChecked = False
self._footerFont = wx.NullFont
def SetItem(self, item):
"""
Sets information about the header/footer item.
:param `info`: an instance of :class:`UltimateListHeaderData`.
"""
self._mask = item._mask
if self._mask & ULC_MASK_TEXT:
self._text = item._text
if self._mask & ULC_MASK_TOOLTIP:
self._tooltip = item._tooltip
if self._mask & ULC_MASK_FOOTER_TEXT:
self._footerText = item._footerText
if self._mask & ULC_MASK_IMAGE:
self._image = item._image[:]
if self._mask & ULC_MASK_FOOTER_IMAGE:
self._footerImage = item._footerImage[:]
if self._mask & ULC_MASK_FORMAT:
self._format = item._format
if self._mask & ULC_MASK_FOOTER_FORMAT:
self._footerFormat = item._footerFormat
if self._mask & ULC_MASK_WIDTH:
self.SetWidth(item._width)
if self._mask & ULC_MASK_FONT:
self._font = item._font
if self._mask & ULC_MASK_FOOTER_FONT:
self._footerFont = item._footerFont
if self._mask & ULC_MASK_FOOTER_KIND:
self._footerKind = item._footerKind
self._footerChecked = item._footerChecked
if self._mask & ULC_MASK_KIND:
self._kind = item._kind
self._checked = item._checked
if self._mask & ULC_MASK_CHECK:
self._kind = item._kind
self._checked = item._checked
if self._mask & ULC_MASK_FOOTER_CHECK:
self._footerKind = item._footerKind
self._footerChecked = item._footerChecked
if self._mask & ULC_MASK_STATE:
self.SetState(item._state)
if self._mask & ULC_MASK_SHOWN:
self._isColumnShown = item._isColumnShown
if self._mask & ULC_MASK_RENDERER:
self._customRenderer = item._customRenderer
def SetState(self, flag):
"""
Sets the item state flags.
:param `state`: any combination of the following bits:
============================ ========= ==============================
State Bits Hex Value Description
============================ ========= ==============================
``ULC_STATE_DONTCARE`` 0x0 Don't care what the state is
``ULC_STATE_DROPHILITED`` 0x1 The item is highlighted to receive a drop event
``ULC_STATE_FOCUSED`` 0x2 The item has the focus
``ULC_STATE_SELECTED`` 0x4 The item is selected
``ULC_STATE_CUT`` 0x8 The item is in the cut state
``ULC_STATE_DISABLED`` 0x10 The item is disabled
``ULC_STATE_FILTERED`` 0x20 The item has been filtered
``ULC_STATE_INUSE`` 0x40 The item is in use
``ULC_STATE_PICKED`` 0x80 The item has been picked
``ULC_STATE_SOURCE`` 0x100 The item is a drag and drop source
============================ ========= ==============================
"""
self._state = flag
def SetPosition(self, x, y):
"""
Sets the header/footer item position.
:param `x`: the item `x` position;
:param `y`: the item `y` position.
"""
self._xpos = x
self._ypos = y
def SetHeight(self, h):
"""
Sets the header/footer item height, in pixels.
:param `h`: an integer value representing the header/footer height.
"""
self._height = h
def SetWidth(self, w):
"""
Sets the header/footer item width, in pixels.
:param `w`: an integer value representing the header/footer width.
"""
self._width = w
if self._width < 0:
self._width = WIDTH_COL_DEFAULT
elif self._width < WIDTH_COL_MIN:
self._width = WIDTH_COL_MIN
def SetFormat(self, format):
"""
Sets the header item format.
:param `format`: the header item format.
"""
self._format = format
def SetFooterFormat(self, format):
"""
Sets the footer item format.
:param `format`: the footer item format.
"""
self._footerFormat = format
def HasImage(self):
"""
Returns ``True`` if the header item has at least one image associated
with it.
"""
return len(self._image) > 0
def HasFooterImage(self):
"""
Returns ``True`` if the footer item has at least one image associated
with it.
"""
return len(self._footerImage) > 0
def IsHit(self, x, y):
"""
Returns ``True`` if the input position is inside the item client rectangle.
:param `x`: the `x` mouse position;
:param `y`: the `y` mouse position.
"""
return ((x >= self._xpos) and (x <= self._xpos+self._width) and (y >= self._ypos) and (y <= self._ypos+self._height))
def GetItem(self, item):
"""
Returns information about the item.
:param `item`: an instance of :class:`UltimateListHeaderData`.
"""
item._mask = self._mask
item._text = self._text
item._tooltip = self._tooltip
item._image = self._image[:]
item._format = self._format
item._width = self._width
if self._font:
item._font = self._font
item.Attributes().SetFont(self._font)
item._kind = self._kind
item._checked = self._checked
item._state = self._state
item._isColumnShown = self._isColumnShown
item._footerImage = self._footerImage
item._footerFormat = self._footerFormat
item._footerText = self._footerText
item._footerKind = self._footerKind
item._footerChecked = self._footerChecked
item._footerFont = self._footerFont
item._customRenderer = self._customRenderer
return item
def GetState(self):
"""
Returns a bit field representing the state of the item.
:see: :meth:`~UltimateListHeaderData.SetState` for a list of valid item states.
"""
return self._state
def GetImage(self):
"""
Returns a Python list with the zero-based indexes of the images associated
with the header item into the image list.
"""
return self._image
def GetFooterImage(self):
"""
Returns a Python list with the zero-based indexes of the images associated
with the footer item into the image list.
"""
return self._footerImage
def GetWidth(self):
""" Returns the header/footer item width, in pixels. """
return self._width
def GetFormat(self):
""" Returns the header item format. """
return self._format
def GetFooterFormat(self):
""" Returns the footer item format. """
return self._footerFormat
def SetFont(self, font):
"""
Sets a new font for the header item.
:param `font`: an instance of :class:`wx.Font`.
"""
self._font = font
def SetFooterFont(self, font):
"""
Sets a new font for the footer item.
:param `font`: an instance of :class:`wx.Font`.
"""
self._footerFont = font
def SetKind(self, kind):
"""
Sets the header item kind.
:param `kind`: may be one of the following integers:
=============== ==========================
Item Kind Description
=============== ==========================
0 A normal item
1 A checkbox-like item
2 A radiobutton-type item
=============== ==========================
"""
self._kind = kind
def SetFooterKind(self, kind):
"""
Sets the footer item kind.
:param `kind`: the footer item kind.
:see: :meth:`~UltimateListHeaderData.SetKind` for a list of valid item kinds.
"""
self._footerKind = kind
def GetKind(self):
"""
Returns the header item kind.
:see: :meth:`~UltimateListHeaderData.SetKind` for a list of valid item kinds.
"""
return self._kind
def GetFooterKind(self):
"""
Returns the footer item kind.
:see: :meth:`~UltimateListHeaderData.SetKind` for a list of valid item kinds.
"""
return self._footerKind
def IsChecked(self):
""" Returns whether the header item is checked or not. """
return self._checked
def Check(self, checked=True):
"""
Checks/unchecks a header item.
:param `checked`: ``True`` to check an item, ``False`` to uncheck it.
:note: This method is meaningful only for check and radio header items.
"""
self._checked = checked
def IsFooterChecked(self):
""" Returns whether the footer item is checked or not. """
return self._footerChecked
def CheckFooter(self, check=True):
"""
Checks/unchecks a footer item.
:param `checked`: ``True`` to check an item, ``False`` to uncheck it.
:note: This method is meaningful only for check and radio footer items.
"""
self._footerChecked = check
def SetCustomRenderer(self, renderer):
"""
Associate a custom renderer to this item.
:param `renderer`: a class able to correctly render the item.
:note: the renderer class **must** implement the methods `DrawHeaderButton`
and `GetForegroundColor`.
"""
self._mask |= ULC_MASK_RENDERER
self._customRenderer = renderer
def GetCustomRenderer(self):
""" Returns the custom renderer associated with this item (if any). """
return self._customRenderer
#-----------------------------------------------------------------------------
# GeometryInfo (internal)
# this is not used in report view
#-----------------------------------------------------------------------------
class GeometryInfo(object):
"""
A simple class which holds items geometries for :class:`UltimateListCtrl` not in
report mode.
"""
def __init__(self):
""" Default class constructor. """
# total item rect
self._rectAll = wx.Rect()
# label only
self._rectLabel = wx.Rect()
# icon only
self._rectIcon = wx.Rect()
# the part to be highlighted
self._rectHighlight = wx.Rect()
# the checkbox/radiobutton rect (if any)
self._rectCheck = wx.Rect()
# extend all our rects to be centered inside the one of given width
def ExtendWidth(self, w):
"""
Extends all our rectangles to be centered inside the one of given width.
:param `w`: the given width.
"""
if self._rectAll.width > w:
raise Exception("width can only be increased")
self._rectAll.width = w
self._rectLabel.x = self._rectAll.x + (w - self._rectLabel.width)/2
self._rectIcon.x = self._rectAll.x + (w - self._rectIcon.width)/2
self._rectHighlight.x = self._rectAll.x + (w - self._rectHighlight.width)/2
#-----------------------------------------------------------------------------
# UltimateListLineData (internal)
#-----------------------------------------------------------------------------
class UltimateListLineData(object):
""" A simple class which holds line geometries for :class:`UltimateListCtrl`. """
def __init__(self, owner):
"""
Default class constructor.
:param `owner`: an instance of :class:`UltimateListCtrl`.
"""
# the list of subitems: only may have more than one item in report mode
self._items = []
# is this item selected? [NB: not used in virtual mode]
self._highlighted = False
# back pointer to the list ctrl
self._owner = owner
self._height = self._width = self._x = self._y = -1
if self.InReportView():
self._gi = None
else:
self._gi = GeometryInfo()
if self.GetMode() in [ULC_REPORT, ULC_TILE] or self.HasMode(ULC_HEADER_IN_ALL_VIEWS):
self.InitItems(self._owner.GetColumnCount())
else:
self.InitItems(1)
def SetReportView(self, inReportView):
"""
Sets whether :class:`UltimateListLineData` is in report view or not.
:param `inReportView`: ``True`` to set :class:`UltimateListLineData` in report view, ``False``
otherwise.
"""
# we only need m_gi when we're not in report view so update as needed
if inReportView:
del self._gi
self._gi = None
else:
self._gi = GeometryInfo()
def GetHeight(self):
""" Returns the line height, in pixels. """
return self._height
def SetHeight(self, height):
"""
Sets the line height.
:param `height`: the new line height.
"""
self._height = height
def GetWidth(self):
""" Returns the line width. """
return self._width
def SetWidth(self, width):
"""
Sets the line width.
:param `width`: the new line width.
"""
self._width = width
def GetX(self):
""" Returns the line `x` position. """
return self._x
def SetX(self, x):
"""
Sets the line `x` position.
:param `x`: the new line `x` position.
"""
self._x = x
def GetY(self):
""" Returns the line `y` position. """
return self._y
def SetY(self, y):
"""
Sets the line `y` position.
:param `y`: the new line `y` position.
"""
self._y = y
def ResetDimensions(self):
""" Resets the line dimensions (client rectangle). """
self._height = self._width = self._x = self._y = -1
def HasImage(self, col=0):
"""
Returns ``True`` if the first item in the line has at least one image
associated with it.
"""
return self.GetImage(col) != []
def HasText(self):
"""
Returns ``True`` if the text of first item in the line is not the empty
string.
"""
return self.GetText(0) != ""
def IsHighlighted(self):
""" Returns ``True`` if the line is highlighted. """
if self.IsVirtual():
raise Exception("unexpected call to IsHighlighted")
return self._highlighted
def GetMode(self):
""" Returns the current highlighting mode. """
return self._owner.GetListCtrl().GetAGWWindowStyleFlag() & ULC_MASK_TYPE
def HasMode(self, mode):
"""
Returns ``True`` if the parent :class:`UltimateListCtrl` has the window
style specified by `mode`.
:param `mode`: the window style to check.
"""
return self._owner.GetListCtrl().HasAGWFlag(mode)
def InReportView(self):
""" Returns ``True`` if the parent :class:`UltimateListCtrl` is in report view. """
return self._owner.HasAGWFlag(ULC_REPORT)
def IsVirtual(self):
""" Returns ``True`` if the parent :class:`UltimateListCtrl` has the ``ULC_VIRTUAL`` style set. """
return self._owner.IsVirtual()
def CalculateSize(self, dc, spacing):
"""
Calculates the line size and item positions.
:param `dc`: an instance of :class:`wx.DC`;
:param `spacing`: the spacing between the items, in pixels.
"""
item = self._items[0]
mode = self.GetMode()
if mode in [ULC_ICON, ULC_SMALL_ICON]:
self._gi._rectAll.width = spacing
s = item.GetText()
if not s:
lh = -1
self._gi._rectLabel.width = 0
self._gi._rectLabel.height = 0
else:
lw, lh = dc.GetTextExtent(s)
lw += EXTRA_WIDTH
lh += EXTRA_HEIGHT
self._gi._rectAll.height = spacing + lh
if lw > spacing:
self._gi._rectAll.width = lw
self._gi._rectLabel.width = lw
self._gi._rectLabel.height = lh
if item.HasImage():
w, h = self._owner.GetImageSize(item.GetImage())
self._gi._rectIcon.width = w + 8
self._gi._rectIcon.height = h + 8
if self._gi._rectIcon.width > self._gi._rectAll.width:
self._gi._rectAll.width = self._gi._rectIcon.width
if self._gi._rectIcon.height + lh > self._gi._rectAll.height - 4:
self._gi._rectAll.height = self._gi._rectIcon.height + lh + 4
if item.HasText():
self._gi._rectHighlight.width = self._gi._rectLabel.width
self._gi._rectHighlight.height = self._gi._rectLabel.height
else:
self._gi._rectHighlight.width = self._gi._rectIcon.width
self._gi._rectHighlight.height = self._gi._rectIcon.height
elif mode == ULC_LIST:
s = item.GetTextForMeasuring()
lw, lh = dc.GetTextExtent(s)
lw += EXTRA_WIDTH
lh += EXTRA_HEIGHT
self._gi._rectLabel.width = lw
self._gi._rectLabel.height = lh
self._gi._rectAll.width = lw
self._gi._rectAll.height = lh
if item.HasImage():
w, h = self._owner.GetImageSize(item.GetImage())
h += 4
self._gi._rectIcon.width = w
self._gi._rectIcon.height = h
self._gi._rectAll.width += 4 + w
if h > self._gi._rectAll.height:
self._gi._rectAll.height = h
if item.GetKind() in [1, 2]:
w, h = self._owner.GetCheckboxImageSize()
h += 4
self._gi._rectCheck.width = w
self._gi._rectCheck.height = h
self._gi._rectAll.width += 4 + w
if h > self._gi._rectAll.height:
self._gi._rectAll.height = h
self._gi._rectHighlight.width = self._gi._rectAll.width
self._gi._rectHighlight.height = self._gi._rectAll.height
elif mode == ULC_REPORT:
raise Exception("unexpected call to SetSize")
else:
raise Exception("unknown mode")
def SetPosition(self, x, y, spacing):
"""
Sets the line position.
:param `x`: the current `x` coordinate;
:param `y`: the current `y` coordinate;
:param `spacing`: the spacing between items, in pixels.
"""
item = self._items[0]
mode = self.GetMode()
if mode in [ULC_ICON, ULC_SMALL_ICON]:
self._gi._rectAll.x = x
self._gi._rectAll.y = y
if item.HasImage():
self._gi._rectIcon.x = self._gi._rectAll.x + 4 + (self._gi._rectAll.width - self._gi._rectIcon.width)/2
self._gi._rectIcon.y = self._gi._rectAll.y + 4
if item.HasText():
if self._gi._rectLabel.width > spacing:
self._gi._rectLabel.x = self._gi._rectAll.x + 2
else:
self._gi._rectLabel.x = self._gi._rectAll.x + 2 + (spacing/2) - (self._gi._rectLabel.width/2)
self._gi._rectLabel.y = self._gi._rectAll.y + self._gi._rectAll.height + 2 - self._gi._rectLabel.height
self._gi._rectHighlight.x = self._gi._rectLabel.x - 2
self._gi._rectHighlight.y = self._gi._rectLabel.y - 2
else:
self._gi._rectHighlight.x = self._gi._rectIcon.x - 4
self._gi._rectHighlight.y = self._gi._rectIcon.y - 4
elif mode == ULC_LIST:
self._gi._rectAll.x = x
self._gi._rectAll.y = y
wcheck = hcheck = 0
if item.GetKind() in [1, 2]:
wcheck, hcheck = self._owner.GetCheckboxImageSize()
wcheck += 2
self._gi._rectCheck.x = self._gi._rectAll.x + 2
self._gi._rectCheck.y = self._gi._rectAll.y + 2
self._gi._rectHighlight.x = self._gi._rectAll.x
self._gi._rectHighlight.y = self._gi._rectAll.y
self._gi._rectLabel.y = self._gi._rectAll.y + 2
if item.HasImage():
self._gi._rectIcon.x = self._gi._rectAll.x + wcheck + 2
self._gi._rectIcon.y = self._gi._rectAll.y + 2
self._gi._rectLabel.x = self._gi._rectAll.x + 6 + self._gi._rectIcon.width + wcheck
else:
self._gi._rectLabel.x = self._gi._rectAll.x + 2 + wcheck
elif mode == ULC_REPORT:
raise Exception("unexpected call to SetPosition")
else:
raise Exception("unknown mode")
def InitItems(self, num):
"""
Initializes the list of items.
:param `num`: the initial number of items to store.
"""
for i in range(num):
self._items.append(UltimateListItemData(self._owner))
def SetItem(self, index, info):
"""
Sets information about the item.
:param `index`: the index of the item;
:param `info`: an instance of :class:`UltimateListItem`.
"""
item = self._items[index]
item.SetItem(info)
def GetItem(self, index, info):
"""
Returns information about the item.
:param `index`: the index of the item;
:param `info`: an instance of :class:`UltimateListItem`.
"""
item = self._items[index]
return item.GetItem(info)
def GetText(self, index):
"""
Returns the item text at the position `index`.
:param `index`: the index of the item.
"""
item = self._items[index]
return item.GetText()
def SetText(self, index, s):
"""
Sets the item text at the position `index`.
:param `index`: the index of the item;
:param `s`: the new item text.
"""
item = self._items[index]
item.SetText(s)
def GetToolTip(self, index):
"""
Returns the item tooltip at the position `index`.
:param `index`: the index of the item.
"""
item = self._items[index]
return item.GetToolTip()
def SetToolTip(self, index, s):
"""
Sets the item tooltip at the position `index`.
:param `index`: the index of the item;
:param `s`: the new item tooltip.
"""
item = self._items[index]
item.SetToolTip(s)
def SetImage(self, index, image):
"""
Sets the zero-based indexes of the images associated with the item into the
image list.
:param `index`: the index of the item;
:param `image`: a Python list with the zero-based indexes of the images
associated with the item into the image list.
"""
item = self._items[index]
item.SetImage(image)
def GetImage(self, index=0):
"""
Returns a Python list with the zero-based indexes of the images associated
with the item into the image list.
:param `index`: the index of the item.
"""
item = self._items[index]
return item.GetImage()
def Check(self, index, checked=True):
"""
Checks/unchecks an item.
:param `index`: the index of the item;
:param `checked`: ``True`` to check an item, ``False`` to uncheck it.
:note: This method is meaningful only for check and radio items.
"""
item = self._items[index]
item.Check(checked)
def SetKind(self, index, kind=0):
"""
Sets the item kind.
:param `index`: the index of the item;
:param `kind`: may be one of the following integers:
=============== ==========================
Item Kind Description
=============== ==========================
0 A normal item
1 A checkbox-like item
2 A radiobutton-type item
=============== ==========================
"""
item = self._items[index]
item.SetKind(kind)
def GetKind(self, index=0):
"""
Returns the item kind.
:param `index`: the index of the item.
:see: :meth:`~UltimateListLineData.SetKind` for a list of valid item kinds.
"""
item = self._items[index]
return item.GetKind()
def IsChecked(self, index):
"""
Returns whether the item is checked or not.
:param `index`: the index of the item.
"""
item = self._items[index]
return item.IsChecked()
def SetColour(self, index, c):
"""
Sets the text colour for the item.
:param `index`: the index of the item;
:param `c`: an instance of :class:`wx.Colour`.
"""
item = self._items[index]
item.SetColour(c)
def GetAttr(self):
"""
Returns an instance of :class:`UltimateListItemAttr` associated with the first item
in the line.
"""
item = self._items[0]
return item.GetAttr()
def SetAttr(self, attr):
"""
Sets an instance of :class:`UltimateListItemAttr` to the first item in the line.
:param `attr`: an instance of :class:`UltimateListItemAttr`.
"""
item = self._items[0]
item.SetAttr(attr)
def SetAttributes(self, dc, attr, highlighted):
"""
Sets various attributes to the input device context.
:param `dc`: an instance of :class:`wx.DC`;
:param `attr`: an instance of :class:`UltimateListItemAttr`;
:param `highlighted`: ``True`` if the item is highlighted, ``False`` otherwise.
"""
listctrl = self._owner.GetParent()
# fg colour
# don't use foreground colour for drawing highlighted items - this might
# make them completely invisible (and there is no way to do bit
# arithmetics on wxColour, unfortunately)
if not self._owner.HasAGWFlag(ULC_BORDER_SELECT) and not self._owner.HasAGWFlag(ULC_NO_FULL_ROW_SELECT):
if highlighted:
if wx.Platform == "__WXMAC__":
if self._owner.HasFocus():
colText = wx.WHITE
else:
colText = wx.BLACK
else:
colText = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT)
else:
if attr and attr.HasTextColour():
colText = attr.GetTextColour()
else:
colText = listctrl.GetForegroundColour()
elif attr and attr.HasTextColour():
colText = attr.GetTextColour()
else:
colText = listctrl.GetForegroundColour()
dc.SetTextForeground(colText)
# font
if attr and attr.HasFont():
font = attr.GetFont()
else:
font = listctrl.GetFont()
dc.SetFont(font)
# bg colour
hasBgCol = attr and attr.HasBackgroundColour()
if highlighted or hasBgCol:
if highlighted:
dc.SetBrush(self._owner.GetHighlightBrush())
else:
dc.SetBrush(wx.Brush(attr.GetBackgroundColour(), wx.BRUSHSTYLE_SOLID))
dc.SetPen(wx.TRANSPARENT_PEN)
return True
return False
def Draw(self, line, dc):
"""
Draws the line on the specified device context.
:param `line`: an instance of :class:`UltimateListLineData`;
:param `dc`: an instance of :class:`wx.DC`.
"""
item = self._items[0]
highlighted = self.IsHighlighted()
attr = self.GetAttr()
useGradient, gradientStyle = self._owner._usegradients, self._owner._gradientstyle
useVista = self._owner._vistaselection
hasFocus = self._owner._hasFocus
borderOnly = self._owner.HasAGWFlag(ULC_BORDER_SELECT)
drawn = False
if self.SetAttributes(dc, attr, highlighted):
drawn = True
if not borderOnly:
if useGradient:
if gradientStyle == 0:
# horizontal gradient
self.DrawHorizontalGradient(dc, self._gi._rectAll, hasFocus)
else:
# vertical gradient
self.DrawVerticalGradient(dc, self._gi._rectAll, hasFocus)
elif useVista:
# Vista selection style
self.DrawVistaRectangle(dc, self._gi._rectAll, hasFocus)
else:
if highlighted:
flags = wx.CONTROL_SELECTED
if self._owner.HasFocus() and wx.Platform == "__WXMAC__":
flags |= wx.CONTROL_FOCUSED
wx.RendererNative.Get().DrawItemSelectionRect(self._owner, dc, self._gi._rectHighlight, flags)
else:
dc.DrawRectangle(self._gi._rectHighlight)
else:
if borderOnly:
dc.SetBrush(wx.WHITE_BRUSH)
dc.SetPen(wx.TRANSPARENT_PEN)
dc.DrawRectangle(self._gi._rectAll)
if item.GetKind() in [1, 2]:
rectCheck = self._gi._rectCheck
self._owner.DrawCheckbox(dc, rectCheck.x, rectCheck.y, item.GetKind(), item.IsChecked(), item.IsEnabled())
if item.HasImage():
# centre the image inside our rectangle, this looks nicer when items
# ae aligned in a row
rectIcon = self._gi._rectIcon
self._owner.DrawImage(item.GetImage()[0], dc, rectIcon.x, rectIcon.y, True)
if item.HasText():
rectLabel = self._gi._rectLabel
dc.SetClippingRegion(rectLabel)
dc.DrawText(item.GetText(), rectLabel.x, rectLabel.y)
dc.DestroyClippingRegion()
if self._owner.HasAGWFlag(ULC_HOT_TRACKING):
if line == self._owner._newHotCurrent and not drawn:
r = wx.Rect(*self._gi._rectAll)
dc.SetBrush(wx.TRANSPARENT_BRUSH)
dc.SetPen(wx.Pen(wx.Colour("orange")))
dc.DrawRoundedRectangle(r, 3)
if borderOnly and drawn:
dc.SetPen(wx.Pen(wx.Colour(0, 191, 255), 2))
dc.SetBrush(wx.TRANSPARENT_BRUSH)
r = wx.Rect(*self._gi._rectAll)
r.x += 1
r.y += 1
r.width -= 1
r.height -= 1
dc.DrawRoundedRectangle(r, 4)
def HideItemWindow(self, item):
"""
If the input item has a window associated with it, hide it.
:param `item`: an instance of :class:`UltimateListItem`.
"""
wnd = item.GetWindow()
if wnd and wnd.IsShown():
wnd.Hide()
def DrawInReportMode(self, dc, line, rect, rectHL, highlighted, current, enabled, oldPN, oldBR):
"""
Draws the line on the specified device context when the parent :class:`UltimateListCtrl`
is in report mode.
:param `dc`: an instance of :class:`wx.DC`;
:param `line`: an instance of :class:`UltimateListLineData`;
:param `rect`: the item client rectangle;
:param `rectHL`: the item client rectangle when the item is highlighted;
:param `highlighted`: ``True`` if the item is highlighted, ``False`` otherwise;
:param `current`: ``True`` if the item is the current item;
:param `enabled`: ``True`` if the item is enabled, ``False`` otherwise;
:param `oldPN`: an instance of :class:`wx.Pen`, to save and restore at the end of
the drawing;
:param `oldBR`: an instance of :class:`wx.Brush`, to save and restore at the end of
the drawing.
"""
attr = self.GetAttr()
useGradient, gradientStyle = self._owner._usegradients, self._owner._gradientstyle
useVista = self._owner._vistaselection
hasFocus = self._owner._hasFocus
borderOnly = self._owner.HasAGWFlag(ULC_BORDER_SELECT)
nofullRow = self._owner.HasAGWFlag(ULC_NO_FULL_ROW_SELECT)
drawn = False
dc.SetBrush(wx.TRANSPARENT_BRUSH)
if nofullRow:
x = rect.x + HEADER_OFFSET_X
y = rect.y
height = rect.height
for col, item in enumerate(self._items):
width = self._owner.GetColumnWidth(col)
if self._owner.IsColumnShown(col):
paintRect = wx.Rect(x, y, self._owner.GetColumnWidth(col)-2*HEADER_OFFSET_X, rect.height)
break
xOld = x
x += width
else:
paintRect = wx.Rect(*rectHL)
if self.SetAttributes(dc, attr, highlighted) and enabled:
drawn = True
if not borderOnly:
if useGradient:
if gradientStyle == 0:
# horizontal gradient
self.DrawHorizontalGradient(dc, paintRect, hasFocus)
else:
# vertical gradient
self.DrawVerticalGradient(dc, paintRect, hasFocus)
elif useVista:
# Vista selection style
self.DrawVistaRectangle(dc, paintRect, hasFocus)
else:
if highlighted:
flags = wx.CONTROL_SELECTED
if hasFocus:
flags |= wx.CONTROL_FOCUSED
if current:
flags |= wx.CONTROL_CURRENT
wx.RendererNative.Get().DrawItemSelectionRect(self._owner, dc, paintRect, flags)
else:
dc.DrawRectangle(paintRect)
else:
if borderOnly:
dc.SetBrush(wx.WHITE_BRUSH)
dc.SetPen(wx.TRANSPARENT_PEN)
dc.DrawRectangle(paintRect)
x = rect.x + HEADER_OFFSET_X
y = rect.y
height = rect.height
boldFont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
boldFont.SetWeight(wx.FONTWEIGHT_BOLD)
for col, item in enumerate(self._items):
if not self._owner.IsColumnShown(col):
self.HideItemWindow(item)
continue
width = self._owner.GetColumnWidth(col)
xOld = x
x += width
if item.GetCustomRenderer():
customRect = wx.Rect(xOld-HEADER_OFFSET_X, rect.y, width, rect.height)
item.GetCustomRenderer().DrawSubItem(dc, customRect, line, highlighted, enabled)
continue
overflow = item.GetOverFlow() and item.HasText()
if item.GetKind() in [1, 2]:
# We got a checkbox-type item
ix, iy = self._owner.GetCheckboxImageSize()
checked = item.IsChecked()
self._owner.DrawCheckbox(dc, xOld, y + (height-iy+1)/2, item.GetKind(), checked, enabled)
xOld += ix
width -= ix
if item.HasImage():
images = item.GetImage()
for img in images:
ix, iy = self._owner.GetImageSize([img])
self._owner.DrawImage(img, dc, xOld, y + (height-iy)/2, enabled)
xOld += ix
width -= ix
## if images:
## width -= IMAGE_MARGIN_IN_REPORT_MODE - MARGIN_BETWEEN_TEXT_AND_ICON
wnd = item.GetWindow()
xSize = 0
if wnd:
xSize, ySize = item.GetWindowSize()
wndx = xOld - HEADER_OFFSET_X + width - xSize - 3
xa, ya = self._owner.CalcScrolledPosition((0, rect.y))
wndx += xa
if rect.height > ySize and not item._expandWin:
ya += (rect.height - ySize)/2
itemRect = wx.Rect(xOld-2*HEADER_OFFSET_X, rect.y, width-xSize-HEADER_OFFSET_X, rect.height)
if overflow:
itemRect = wx.Rect(xOld-2*HEADER_OFFSET_X, rect.y, rectHL.width-xSize-HEADER_OFFSET_X, rect.height)
dc.SetClippingRegion(itemRect)
if item.HasBackgroundColour():
dc.SetBrush(wx.Brush(item.GetBackgroundColour()))
dc.SetPen(wx.Pen(item.GetBackgroundColour()))
dc.DrawRectangle(itemRect)
dc.SetBrush(oldBR)
dc.SetPen(oldPN)
if item.HasText():
coloured = item.HasColour()
c = dc.GetTextForeground()
oldTF = wx.Colour(c.Red(),c.Green(),c.Blue())
oldFT = dc.GetFont()
font = item.HasFont()
if not enabled:
dc.SetTextForeground(self._owner.GetDisabledTextColour())
else:
if coloured:
dc.SetTextForeground(item.GetColour())
elif useVista and drawn:
dc.SetTextForeground(wx.BLACK)
if item.IsHyperText():
dc.SetFont(self._owner.GetHyperTextFont())
if item.GetVisited():
dc.SetTextForeground(self._owner.GetHyperTextVisitedColour())
else:
dc.SetTextForeground(self._owner.GetHyperTextNewColour())
font = True
coloured = True
else:
if font:
dc.SetFont(item.GetFont())
itemRect = wx.Rect(itemRect.x+MARGIN_BETWEEN_TEXT_AND_ICON, itemRect.y, itemRect.width-8, itemRect.height)
self.DrawTextFormatted(dc, item.GetText(), line, col, itemRect, overflow)
if coloured:
dc.SetTextForeground(oldTF)
if font:
dc.SetFont(oldFT)
dc.DestroyClippingRegion()
if wnd:
if not wnd.IsShown():
wnd.Show()
if item._expandWin:
wRect = wx.Rect(*itemRect)
wRect.x += xa + 2
wRect.width = width - 8
wRect.y = ya + 2
wRect.height -= 4
if wnd.GetRect() != wRect:
wnd.SetRect(wRect)
else:
if wnd.GetPosition() != (wndx, ya):
wnd.SetPosition((wndx, ya))
if self._owner.HasAGWFlag(ULC_HOT_TRACKING):
if line == self._owner._newHotCurrent and not drawn:
r = wx.Rect(*paintRect)
r.y += 1
r.height -= 1
dc.SetBrush(wx.TRANSPARENT_BRUSH)
dc.SetPen(wx.Pen(wx.Colour("orange")))
dc.DrawRoundedRectangle(r, 3)
dc.SetPen(oldPN)
if borderOnly and drawn:
dc.SetPen(wx.Pen(wx.Colour(0, 191, 255), 2))
dc.SetBrush(wx.TRANSPARENT_BRUSH)
rect = wx.Rect(*paintRect)
rect.y += 1
rect.height -= 1
dc.DrawRoundedRectangle(rect, 3)
dc.SetPen(oldPN)
def DrawTextFormatted(self, dc, text, row, col, itemRect, overflow):
"""
Draws the item text, correctly formatted.
:param `dc`: an instance of :class:`wx.DC`;
:param `text`: the item text;
:param `row`: the line number to which this item belongs to;
:param `col`: the column number to which this item belongs to;
:param `itemRect`: the item client rectangle;
:param `overflow`: ``True`` if the item should overflow into neighboring columns,
``False`` otherwise.
"""
# determine if the string can fit inside the current width
w, h, dummy = dc.GetFullMultiLineTextExtent(text)
width = itemRect.width
shortItems = self._owner._shortItems
tuples = (row, col)
# it can, draw it using the items alignment
item = self._owner.GetColumn(col)
align = item.GetAlign()
if align == ULC_FORMAT_RIGHT:
textAlign = wx.ALIGN_RIGHT
elif align == ULC_FORMAT_CENTER:
textAlign = wx.ALIGN_CENTER
else:
textAlign = wx.ALIGN_LEFT
if w <= width:
if tuples in shortItems:
shortItems.remove(tuples)
dc.DrawLabel(text, itemRect, textAlign|wx.ALIGN_CENTER_VERTICAL)
else: # otherwise, truncate and add an ellipsis if possible
if tuples not in shortItems:
shortItems.append(tuples)
# determine the base width
ellipsis = "..."
base_w, h = dc.GetTextExtent(ellipsis)
# continue until we have enough space or only one character left
newText = text.split("\n")
theText = ""
for text in newText:
lenText = len(text)
drawntext = text
w, dummy = dc.GetTextExtent(text)
while lenText > 1:
if w + base_w <= width:
break
w_c, h_c = dc.GetTextExtent(drawntext[-1])
drawntext = drawntext[0:-1]
lenText -= 1
w -= w_c
# if still not enough space, remove ellipsis characters
while len(ellipsis) > 0 and w + base_w > width:
ellipsis = ellipsis[0:-1]
base_w, h = dc.GetTextExtent(ellipsis)
theText += drawntext + ellipsis + "\n"
theText = theText.rstrip()
# now draw the text
dc.DrawLabel(theText, itemRect, textAlign|wx.ALIGN_CENTER_VERTICAL)
def DrawVerticalGradient(self, dc, rect, hasfocus):
"""
Gradient fill from colour 1 to colour 2 from top to bottom.
:param `dc`: an instance of :class:`wx.DC`;
:param `rect`: the rectangle to be filled with the gradient shading;
:param `hasfocus`: ``True`` if the main :class:`UltimateListCtrl` has focus, ``False``
otherwise.
"""
oldpen = dc.GetPen()
oldbrush = dc.GetBrush()
dc.SetPen(wx.TRANSPARENT_PEN)
# calculate gradient coefficients
if hasfocus:
col2 = self._owner._secondcolour
col1 = self._owner._firstcolour
else:
col2 = self._owner._highlightUnfocusedBrush.GetColour()
col1 = self._owner._highlightUnfocusedBrush2.GetColour()
r1, g1, b1 = int(col1.Red()), int(col1.Green()), int(col1.Blue())
r2, g2, b2 = int(col2.Red()), int(col2.Green()), int(col2.Blue())
flrect = float(rect.height)
rstep = float((r2 - r1)) / flrect
gstep = float((g2 - g1)) / flrect
bstep = float((b2 - b1)) / flrect
rf, gf, bf = 0, 0, 0
for y in range(rect.y, rect.y + rect.height):
currCol = (r1 + rf, g1 + gf, b1 + bf)
dc.SetBrush(wx.Brush(currCol, wx.BRUSHSTYLE_SOLID))
dc.DrawRectangle(rect.x, y, rect.width, 1)
rf = rf + rstep
gf = gf + gstep
bf = bf + bstep
dc.SetPen(oldpen)
dc.SetBrush(wx.TRANSPARENT_BRUSH)
dc.DrawRectangle(rect)
dc.SetBrush(oldbrush)
def DrawHorizontalGradient(self, dc, rect, hasfocus):
"""
Gradient fill from colour 1 to colour 2 from left to right.
:param `dc`: an instance of :class:`wx.DC`;
:param `rect`: the rectangle to be filled with the gradient shading;
:param `hasfocus`: ``True`` if the main :class:`UltimateListCtrl` has focus, ``False``
otherwise.
"""
oldpen = dc.GetPen()
oldbrush = dc.GetBrush()
dc.SetPen(wx.TRANSPARENT_PEN)
# calculate gradient coefficients
if hasfocus:
col2 = self._owner._secondcolour
col1 = self._owner._firstcolour
else:
col2 = self._owner._highlightUnfocusedBrush.GetColour()
col1 = self._owner._highlightUnfocusedBrush2.GetColour()
r1, g1, b1 = int(col1.Red()), int(col1.Green()), int(col1.Blue())
r2, g2, b2 = int(col2.Red()), int(col2.Green()), int(col2.Blue())
flrect = float(rect.width)
rstep = float((r2 - r1)) / flrect
gstep = float((g2 - g1)) / flrect
bstep = float((b2 - b1)) / flrect
rf, gf, bf = 0, 0, 0
for x in range(rect.x, rect.x + rect.width):
currCol = (int(r1 + rf), int(g1 + gf), int(b1 + bf))
dc.SetBrush(wx.Brush(currCol, wx.BRUSHSTYLE_SOLID))
dc.DrawRectangle(x, rect.y, 1, rect.height)
rf = rf + rstep
gf = gf + gstep
bf = bf + bstep
dc.SetPen(oldpen)
dc.SetBrush(wx.TRANSPARENT_BRUSH)
dc.DrawRectangle(rect)
dc.SetBrush(oldbrush)
def DrawVistaRectangle(self, dc, rect, hasfocus):
"""
Draws the selected item(s) with the Windows Vista style.
:param `dc`: an instance of :class:`wx.DC`;
:param `rect`: the rectangle to be filled with the gradient shading;
:param `hasfocus`: ``True`` if the main :class:`UltimateListCtrl` has focus, ``False``
otherwise.
"""
if hasfocus:
outer = _rgbSelectOuter
inner = _rgbSelectInner
top = _rgbSelectTop
bottom = _rgbSelectBottom
else:
outer = _rgbNoFocusOuter
inner = _rgbNoFocusInner
top = _rgbNoFocusTop
bottom = _rgbNoFocusBottom
oldpen = dc.GetPen()
oldbrush = dc.GetBrush()
bdrRect = wx.Rect(*rect.Get())
filRect = wx.Rect(*rect.Get())
filRect.Deflate(1,1)
r1, g1, b1 = int(top.Red()), int(top.Green()), int(top.Blue())
r2, g2, b2 = int(bottom.Red()), int(bottom.Green()), int(bottom.Blue())
flrect = float(filRect.height)
if flrect < 1:
flrect = self._owner._lineHeight
rstep = float((r2 - r1)) / flrect
gstep = float((g2 - g1)) / flrect
bstep = float((b2 - b1)) / flrect
rf, gf, bf = 0, 0, 0
dc.SetPen(wx.TRANSPARENT_PEN)
for y in range(filRect.y, filRect.y + filRect.height):
currCol = (r1 + rf, g1 + gf, b1 + bf)
dc.SetBrush(wx.Brush(currCol, wx.BRUSHSTYLE_SOLID))
dc.DrawRectangle(filRect.x, y, filRect.width, 1)
rf = rf + rstep
gf = gf + gstep
bf = bf + bstep
dc.SetBrush(wx.TRANSPARENT_BRUSH)
dc.SetPen(wx.Pen(outer))
dc.DrawRoundedRectangle(bdrRect, 3)
bdrRect.Deflate(1, 1)
dc.SetPen(wx.Pen(inner))
dc.DrawRoundedRectangle(bdrRect, 2)
dc.SetPen(oldpen)
dc.SetBrush(oldbrush)
def Highlight(self, on):
"""
Sets the current line as highlighted or not highlighted.
:param `on`: ``True`` to set the current line as highlighted, ``False``
otherwise.
"""
if on == self._highlighted:
return False
self._highlighted = on
return True
def ReverseHighlight(self):
"""
Reverses the line highlighting, switching it off if it was on and vice-versa.
"""
self.Highlight(not self.IsHighlighted())
#-----------------------------------------------------------------------------
# UltimateListHeaderWindow (internal)
#-----------------------------------------------------------------------------
class UltimateListHeaderWindow(wx.Control):
"""
This class holds the header window for :class:`UltimateListCtrl`.
"""
def __init__(self, win, id, owner, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=0, validator=wx.DefaultValidator,
name="UltimateListCtrlcolumntitles", isFooter=False):
"""
Default class constructor.
:param `parent`: parent window. Must not be ``None``;
:param `id`: window identifier. A value of -1 indicates a default value;
:param `owner`: an instance of :class:`UltimateListCtrl`;
:param `pos`: the control position. A value of (-1, -1) indicates a default position,
chosen by either the windowing system or wxPython, depending on platform;
:param `size`: the control size. A value of (-1, -1) indicates a default size,
chosen by either the windowing system or wxPython, depending on platform;
:param `style`: the window style;
:param `validator`: the window validator;
:param `name`: the window name;
:param `isFooter`: ``True`` if the :class:`UltimateListHeaderWindow` is in a footer
position, ``False`` otherwise.
"""
wx.Control.__init__(self, win, id, pos, size, style|wx.NO_BORDER, validator, name)
self._isFooter = isFooter
self._owner = owner
self._currentCursor = wx.NullCursor
self._resizeCursor = wx.Cursor(wx.CURSOR_SIZEWE)
self._isDragging = False
self._headerHeight = None
self._footerHeight = None
# Custom renderer for every column
self._headerCustomRenderer = None
# column being resized or -1
self._column = -1
# divider line position in logical (unscrolled) coords
self._currentX = 0
# minimal position beyond which the divider line can't be dragged in
# logical coords
self._minX = 0
# needs refresh
self._dirty = False
self._hasFont = False
self._sendSetColumnWidth = False
self._colToSend = -1
self._widthToSend = 0
self._leftDown = False
self._enter = False
self._currentColumn = -1
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_ERASE_BACKGROUND, lambda e: None)
self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
self.Bind(wx.EVT_ENTER_WINDOW, self.OnEnterWindow)
self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)
if _USE_VISATTR:
attr = wx.Panel.GetClassDefaultAttributes()
self.SetOwnForegroundColour(attr.colFg)
self.SetOwnBackgroundColour(attr.colBg)
if not self._hasFont:
self.SetOwnFont(attr.font)
else:
self.SetOwnForegroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT))
self.SetOwnBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE))
if not self._hasFont:
self.SetOwnFont(wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT))
def SetCustomRenderer(self, renderer=None):
"""
Associate a custom renderer with the header - all columns will use it
:param `renderer`: a class able to correctly render header buttons
:note: the renderer class **must** implement the methods `DrawHeaderButton`
and `GetForegroundColor`.
"""
if not self._owner.HasAGWFlag(ULC_REPORT):
raise Exception("Custom renderers can be used on with style = ULC_REPORT")
self._headerCustomRenderer = renderer
def DoGetBestSize(self):
"""
Gets the size which best suits the window: for a control, it would be the
minimal size which doesn't truncate the control, for a panel - the same size
as it would have after a call to `Fit()`.
"""
if not self._isFooter:
if self._headerHeight is not None:
self.GetParent()._headerHeight = self._headerHeight
return wx.Size(200, self._headerHeight)
else:
if self._footerHeight is not None:
self.GetParent()._footerHeight = self._footerHeight
return wx.Size(200, self._footerHeight)
w, h, d, dummy = self.GetFullTextExtent("Hg")
maxH = self.GetTextHeight()
nativeH = wx.RendererNative.Get().GetHeaderButtonHeight(self.GetParent())
if not self._isFooter:
maxH = max(max(h, maxH), nativeH)
maxH += d
self.GetParent()._headerHeight = maxH
else:
maxH = max(h, nativeH)
maxH += d
self.GetParent()._footerHeight = maxH
return wx.Size(200, maxH)
def GetWindowHeight(self):
""" Returns the :class:`UltimateListHeaderWindow` height, in pixels. """
return self.DoGetBestSize()
def IsColumnShown(self, column):
"""
Returns ``True`` if the input column is shown, ``False`` if it is hidden.
:param `column`: an integer specifying the column index.
"""
if column < 0 or column >= self._owner.GetColumnCount():
raise Exception("Invalid column")
return self._owner.IsColumnShown(column)
# shift the DC origin to match the position of the main window horz
# scrollbar: this allows us to always use logical coords
def AdjustDC(self, dc):
"""
Shifts the :class:`wx.DC` origin to match the position of the main window horizontal
scrollbar: this allows us to always use logical coordinates.
:param `dc`: an instance of :class:`wx.DC`.
"""
xpix, dummy = self._owner.GetScrollPixelsPerUnit()
x, dummy = self._owner.GetViewStart()
# account for the horz scrollbar offset
dc.SetDeviceOrigin(-x*xpix, 0)
def GetTextHeight(self):
""" Returns the column text height, in pixels. """
maxH = 0
numColumns = self._owner.GetColumnCount()
dc = wx.ClientDC(self)
for i in range(numColumns):
if not self.IsColumnShown(i):
continue
item = self._owner.GetColumn(i)
if item.GetFont().IsOk():
dc.SetFont(item.GetFont())
else:
dc.SetFont(self.GetFont())
wLabel, hLabel, dummy = dc.GetFullMultiLineTextExtent(item.GetText())
maxH = max(maxH, hLabel)
return maxH
def OnPaint(self, event):
"""
Handles the ``wx.EVT_PAINT`` event for :class:`UltimateListHeaderWindow`.
:param `event`: a :class:`PaintEvent` event to be processed.
"""
dc = wx.BufferedPaintDC(self)
# width and height of the entire header window
w, h = self.GetClientSize()
w, dummy = self._owner.CalcUnscrolledPosition(w, 0)
dc.SetBrush(wx.Brush(wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE)))
dc.SetPen(wx.TRANSPARENT_PEN)
dc.DrawRectangle(0, -1, w, h+2)
self.AdjustDC(dc)
dc.SetBackgroundMode(wx.TRANSPARENT)
dc.SetTextForeground(self.GetForegroundColour())
x = HEADER_OFFSET_X
numColumns = self._owner.GetColumnCount()
item = UltimateListItem()
renderer = wx.RendererNative.Get()
enabled = self.GetParent().IsEnabled()
virtual = self._owner.IsVirtual()
isFooter = self._isFooter
for i in range(numColumns):
# Reset anything in the dc that a custom renderer might have changed
dc.SetTextForeground(self.GetForegroundColour())
if x >= w:
break
if not self.IsColumnShown(i):
continue # do next column if not shown
item = self._owner.GetColumn(i)
wCol = item._width
cw = wCol
ch = h
flags = 0
if not enabled:
flags |= wx.CONTROL_DISABLED
# NB: The code below is not really Mac-specific, but since we are close
# to 2.8 release and I don't have time to test on other platforms, I
# defined this only for wxMac. If this behavior is desired on
# other platforms, please go ahead and revise or remove the #ifdef.
if "__WXMAC__" in wx.PlatformInfo:
if not virtual and item._mask & ULC_MASK_STATE and item._state & ULC_STATE_SELECTED:
flags |= wx.CONTROL_SELECTED
if i == 0:
flags |= wx.CONTROL_SPECIAL # mark as first column
if i == self._currentColumn:
if self._leftDown:
flags |= wx.CONTROL_PRESSED
else:
if self._enter:
flags |= wx.CONTROL_CURRENT
# the width of the rect to draw: make it smaller to fit entirely
# inside the column rect
header_rect = wx.Rect(x-1, HEADER_OFFSET_Y-1, cw-1, ch)
if self._headerCustomRenderer != None:
self._headerCustomRenderer.DrawHeaderButton(dc, header_rect, flags)
# The custom renderer will specify the color to draw the header text and buttons
dc.SetTextForeground(self._headerCustomRenderer.GetForegroundColour())
elif item._mask & ULC_MASK_RENDERER:
item.GetCustomRenderer().DrawHeaderButton(dc, header_rect, flags)
# The custom renderer will specify the color to draw the header text and buttons
dc.SetTextForeground(item.GetCustomRenderer().GetForegroundColour())
else:
renderer.DrawHeaderButton(self, dc, header_rect, flags)
# see if we have enough space for the column label
if isFooter:
if item.GetFooterFont().IsOk():
dc.SetFont(item.GetFooterFont())
else:
dc.SetFont(self.GetFont())
else:
if item.GetFont().IsOk():
dc.SetFont(item.GetFont())
else:
dc.SetFont(self.GetFont())
wcheck = hcheck = 0
kind = (isFooter and [item.GetFooterKind()] or [item.GetKind()])[0]
checked = (isFooter and [item.IsFooterChecked()] or [item.IsChecked()])[0]
if kind in [1, 2]:
# We got a checkbox-type item
ix, iy = self._owner.GetCheckboxImageSize()
# We draw it on the left, always
self._owner.DrawCheckbox(dc, x + HEADER_OFFSET_X, HEADER_OFFSET_Y + (h - 4 - iy)/2, kind, checked, enabled)
wcheck += ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE
cw -= ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE
# for this we need the width of the text
text = (isFooter and [item.GetFooterText()] or [item.GetText()])[0]
wLabel, hLabel, dummy = dc.GetFullMultiLineTextExtent(text)
wLabel += 2*EXTRA_WIDTH
# and the width of the icon, if any
image = (isFooter and [item._footerImage] or [item._image])[0]
if image:
imageList = self._owner._small_image_list
if imageList:
for img in image:
if img >= 0:
ix, iy = imageList.GetSize(img)
wLabel += ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE
else:
imageList = None
# ignore alignment if there is not enough space anyhow
align = (isFooter and [item.GetFooterAlign()] or [item.GetAlign()])[0]
align = (wLabel < cw and [align] or [ULC_FORMAT_LEFT])[0]
if align == ULC_FORMAT_LEFT:
xAligned = x + wcheck
elif align == ULC_FORMAT_RIGHT:
xAligned = x + cw - wLabel - HEADER_OFFSET_X
elif align == ULC_FORMAT_CENTER:
xAligned = x + wcheck + (cw - wLabel)/2
# if we have an image, draw it on the right of the label
if imageList:
for indx, img in enumerate(image):
if img >= 0:
imageList.Draw(img, dc,
xAligned + wLabel - (ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE)*(indx+1),
HEADER_OFFSET_Y + (h - 4 - iy)/2,
wx.IMAGELIST_DRAW_TRANSPARENT)
cw -= ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE
# draw the text clipping it so that it doesn't overwrite the column
# boundary
dc.SetClippingRegion(x, HEADER_OFFSET_Y, cw, h - 4)
self.DrawTextFormatted(dc, text, wx.Rect(xAligned+EXTRA_WIDTH, HEADER_OFFSET_Y, cw-EXTRA_WIDTH, h-4))
x += wCol
dc.DestroyClippingRegion()
# Fill in what's missing to the right of the columns, otherwise we will
# leave an unpainted area when columns are removed (and it looks better)
if x < w:
header_rect = wx.Rect(x, HEADER_OFFSET_Y, w - x, h)
if self._headerCustomRenderer != None:
# Why does the custom renderer need this adjustment??
header_rect.x = header_rect.x - 1
header_rect.y = header_rect.y - 1
self._headerCustomRenderer.DrawHeaderButton(dc, header_rect, wx.CONTROL_SPECIAL)
else:
renderer.DrawHeaderButton(self, dc, header_rect, wx.CONTROL_SPECIAL) # mark as last column
def DrawTextFormatted(self, dc, text, rect):
"""
Draws the item text, correctly formatted.
:param `dc`: an instance of :class:`wx.DC`;
:param `text`: the item text;
:param `rect`: the item client rectangle.
"""
# determine if the string can fit inside the current width
w, h, dummy = dc.GetFullMultiLineTextExtent(text)
width = rect.width
if w <= width:
dc.DrawLabel(text, rect, wx.ALIGN_CENTER_VERTICAL)
else:
# determine the base width
ellipsis = "..."
base_w, h = dc.GetTextExtent(ellipsis)
# continue until we have enough space or only one character left
newText = text.split("\n")
theText = ""
for text in newText:
lenText = len(text)
drawntext = text
w, dummy = dc.GetTextExtent(text)
while lenText > 1:
if w + base_w <= width:
break
w_c, h_c = dc.GetTextExtent(drawntext[-1])
drawntext = drawntext[0:-1]
lenText -= 1
w -= w_c
# if still not enough space, remove ellipsis characters
while len(ellipsis) > 0 and w + base_w > width:
ellipsis = ellipsis[0:-1]
base_w, h = dc.GetTextExtent(ellipsis)
theText += drawntext + ellipsis + "\n"
theText = theText.rstrip()
dc.DrawLabel(theText, rect, wx.ALIGN_CENTER_VERTICAL)
def OnInternalIdle(self):
"""
This method is normally only used internally, but sometimes an application
may need it to implement functionality that should not be disabled by an
application defining an `OnIdle` handler in a derived class.
This method may be used to do delayed painting, for example, and most
implementations call :meth:`wx.Window.UpdateWindowUI` in order to send update events
to the window in idle time.
"""
wx.Control.OnInternalIdle(self)
if self._isFooter:
return
if self._sendSetColumnWidth:
self._owner.SetColumnWidth(self._colToSend, self._widthToSend)
self._sendSetColumnWidth = False
def DrawCurrent(self):
""" Force the redrawing of the column window. """
self._sendSetColumnWidth = True
self._colToSend = self._column
self._widthToSend = self._currentX - self._minX
def OnMouse(self, event):
"""
Handles the ``wx.EVT_MOUSE_EVENTS`` event for :class:`UltimateListHeaderWindow`.
:param `event`: a :class:`MouseEvent` event to be processed.
"""
# we want to work with logical coords
x, dummy = self._owner.CalcUnscrolledPosition(event.GetX(), 0)
y = event.GetY()
columnX, columnY = x, y
if self._isDragging:
self.SendListEvent(wxEVT_COMMAND_LIST_COL_DRAGGING, event.GetPosition())
# we don't draw the line beyond our window, but we allow dragging it
# there
w, dummy = self.GetClientSize()
w, dummy = self._owner.CalcUnscrolledPosition(w, 0)
w -= 6
# erase the line if it was drawn
if self._currentX < w:
self.DrawCurrent()
if event.ButtonUp():
self.ReleaseMouse()
self._isDragging = False
self._dirty = True
self._owner.SetColumnWidth(self._column, self._currentX - self._minX)
self.SendListEvent(wxEVT_COMMAND_LIST_COL_END_DRAG, event.GetPosition())
else:
if x > self._minX + 7:
self._currentX = x
else:
self._currentX = self._minX + 7
# draw in the new location
if self._currentX < w:
self.DrawCurrent()
else: # not dragging
self._minX = 0
hit_border = False
# end of the current column
xpos = 0
# find the column where this event occurred
countCol = self._owner.GetColumnCount()
broken = False
tipCol = -1
for col in range(countCol):
if not self.IsColumnShown(col):
continue
xpos += self._owner.GetColumnWidth(col)
self._column = col
if abs(x-xpos) < 3 and y < 22:
# near the column border
hit_border = True
broken = True
tipCol = col
break
if x < xpos:
# inside the column
broken = True
tipCol = col
break
self._minX = xpos
if not broken:
self._column = -1
if tipCol >= 0:
# First check to see if we have a tooltip to display
colItem = self._owner.GetColumn(col)
if colItem.GetToolTip() != "":
self.SetToolTip(colItem.GetToolTip())
else:
self.SetToolTip("")
if event.LeftUp():
self._leftDown = False
self.Refresh()
if event.LeftDown() or event.RightUp():
if hit_border and event.LeftDown():
if not self._isFooter:
if self.SendListEvent(wxEVT_COMMAND_LIST_COL_BEGIN_DRAG,
event.GetPosition()):
self._isDragging = True
self._currentX = x
self.CaptureMouse()
self.DrawCurrent()
#else: column resizing was vetoed by the user code
else: # click on a column
# record the selected state of the columns
if event.LeftDown():
for i in range(self._owner.GetColumnCount()):
if not self.IsColumnShown(col):
continue
colItem = self._owner.GetColumn(i)
state = colItem.GetState()
if i == self._column:
colItem.SetState(state | ULC_STATE_SELECTED)
theX = x
else:
colItem.SetState(state & ~ULC_STATE_SELECTED)
self._leftDown = True
self._owner.SetColumn(i, colItem)
x += self._owner.GetColumnWidth(i)
if self.HandleColumnCheck(self._column, event.GetPosition()):
return
if not self._isFooter:
self.SendListEvent((event.LeftDown() and [wxEVT_COMMAND_LIST_COL_CLICK] or \
[wxEVT_COMMAND_LIST_COL_RIGHT_CLICK])[0], event.GetPosition())
else:
self.SendListEvent((event.LeftDown() and [wxEVT_COMMAND_LIST_FOOTER_CLICK] or \
[wxEVT_COMMAND_LIST_FOOTER_RIGHT_CLICK])[0], event.GetPosition())
self._leftDown = True
self._currentColumn = self._column
elif event.Moving():
setCursor = False
if not self._isFooter:
if hit_border:
setCursor = self._currentCursor == wx.STANDARD_CURSOR
self._currentCursor = self._resizeCursor
else:
setCursor = self._currentCursor != wx.STANDARD_CURSOR
self._currentCursor = wx.STANDARD_CURSOR
if setCursor:
self.SetCursor(self._currentCursor)
else:
column = self.HitTestColumn(columnX, columnY)
self._enter = True
self._currentColumn = column
if _VERSION_STRING < "2.9":
leftDown = wx.GetMouseState().LeftDown()
else:
leftDown = wx.GetMouseState().LeftIsDown()
self._leftDown = leftDown
self.Refresh()
elif event.ButtonDClick():
self.HandleColumnCheck(self._column, event.GetPosition())
def HandleColumnCheck(self, column, pos):
"""
Handles the case in which a column contains a checkbox-like item.
:param `column`: the column index;
:param `pos`: the mouse position.
"""
if column < 0 or column >= self._owner.GetColumnCount():
return False
colItem = self._owner.GetColumn(column)
# Let's see if it is a checkbox-type item
kind = (self._isFooter and [colItem.GetFooterKind()] or [colItem.GetKind()])[0]
if kind not in [1, 2]:
return False
x = HEADER_OFFSET_X
for i in range(self._owner.GetColumnCount()):
if not self.IsColumnShown(i):
continue
if i == self._column:
theX = x
break
x += self._owner.GetColumnWidth(i)
parent = self.GetParent()
w, h = self.GetClientSize()
ix, iy = self._owner.GetCheckboxImageSize()
rect = wx.Rect(theX + HEADER_OFFSET_X, HEADER_OFFSET_Y + (h - 4 - iy)/2, ix, iy)
if rect.Contains(pos):
# User clicked on the checkbox
evt = (self._isFooter and [wxEVT_COMMAND_LIST_FOOTER_CHECKING] or [wxEVT_COMMAND_LIST_COL_CHECKING])[0]
if self.SendListEvent(evt, pos):
# No veto for the item checking
if self._isFooter:
isChecked = colItem.IsFooterChecked()
colItem.CheckFooter(not isChecked)
else:
isChecked = colItem.IsChecked()
colItem.Check(not isChecked)
self._owner.SetColumn(column, colItem)
self.RefreshRect(rect)
if self._isFooter:
return True
if parent.HasAGWFlag(ULC_AUTO_CHECK_CHILD):
self._owner.AutoCheckChild(isChecked, self._column)
elif parent.HasAGWFlag(ULC_AUTO_TOGGLE_CHILD):
self._owner.AutoToggleChild(self._column)
evt = (self._isFooter and [wxEVT_COMMAND_LIST_FOOTER_CHECKED] or [wxEVT_COMMAND_LIST_COL_CHECKED])[0]
self.SendListEvent(evt, pos)
return True
return False
def OnEnterWindow(self, event):
"""
Handles the ``wx.EVT_ENTER_WINDOW`` event for :class:`UltimateListHeaderWindow`.
:param `event`: a :class:`MouseEvent` event to be processed.
"""
x, y = self._owner.CalcUnscrolledPosition(*self.ScreenToClient(wx.GetMousePosition()))
column = self.HitTestColumn(x, y)
if _VERSION_STRING < "2.9":
leftDown = wx.GetMouseState().LeftDown()
else:
leftDown = wx.GetMouseState().LeftIsDown()
self._leftDown = leftDown
self._enter = column >= 0 and column < self._owner.GetColumnCount()
self._currentColumn = column
self.Refresh()
def OnLeaveWindow(self, event):
"""
Handles the ``wx.EVT_LEAVE_WINDOW`` event for :class:`UltimateListHeaderWindow`.
:param `event`: a :class:`MouseEvent` event to be processed.
"""
self._enter = False
self._leftDown = False
self._currentColumn = -1
self.Refresh()
def HitTestColumn(self, x, y):
"""
HitTest method for column headers.
:param `x`: the mouse `x` position;
:param `y`: the mouse `y` position.
:return: The column index if any column client rectangle contains the mouse
position, ``wx.NOT_FOUND`` otherwise.
"""
xOld = 0
for i in range(self._owner.GetColumnCount()):
if not self.IsColumnShown(i):
continue
xOld += self._owner.GetColumnWidth(i)
if x <= xOld:
return i
return -1
def OnSetFocus(self, event):
"""
Handles the ``wx.EVT_SET_FOCUS`` event for :class:`UltimateListHeaderWindow`.
:param `event`: a :class:`FocusEvent` event to be processed.
"""
self._owner.SetFocusIgnoringChildren()
self._owner.Update()
def SendListEvent(self, eventType, pos):
"""
Sends a :class:`UltimateListEvent` for the parent window.
:param `eventType`: the event type;
:param `pos`: an instance of :class:`wx.Point`.
"""
parent = self.GetParent()
le = UltimateListEvent(eventType, parent.GetId())
le.SetEventObject(parent)
le.m_pointDrag = pos
# the position should be relative to the parent window, not
# this one for compatibility with MSW and common sense: the
# user code doesn't know anything at all about this header
# window, so why should it get positions relative to it?
le.m_pointDrag.y -= self.GetSize().y
le.m_col = self._column
return (not parent.GetEventHandler().ProcessEvent(le) or le.IsAllowed())
def GetOwner(self):
""" Returns the header window owner, an instance of :class:`UltimateListCtrl`. """
return self._owner
#-----------------------------------------------------------------------------
# UltimateListRenameTimer (internal)
#-----------------------------------------------------------------------------
class UltimateListRenameTimer(wx.Timer):
""" Timer used for enabling in-place edit. """
def __init__(self, owner):
"""
Default class constructor.
For internal use: do not call it in your code!
:param `owner`: an instance of :class:`UltimateListCtrl`.
"""
wx.Timer.__init__(self)
self._owner = owner
def Notify(self):
""" The timer has expired. """
self._owner.OnRenameTimer()
#-----------------------------------------------------------------------------
# UltimateListTextCtrl (internal)
#-----------------------------------------------------------------------------
class UltimateListTextCtrl(ExpandoTextCtrl):
"""
Control used for in-place edit.
This is a subclass of :class:`~wx.lib.expando.ExpandoTextCtrl` as :class:`UltimateListCtrl`
supports multiline text items.
:note: To add a newline character in a multiline item, press ``Shift`` + ``Enter``
as the ``Enter`` key alone is consumed by :class:`UltimateListCtrl` to finish
the editing and ``Ctrl`` + ``Enter`` is consumed by the platform for tab navigation.
"""
def __init__(self, owner, itemEdit):
"""
Default class constructor.
For internal use: do not call it in your code!
:param `owner`: the control parent (an instance of :class:`UltimateListCtrl` );
:param `itemEdit`: an instance of :class:`UltimateListItem`.
"""
self._startValue = owner.GetItemText(itemEdit)
self._currentValue = self._startValue
self._itemEdited = itemEdit
self._owner = owner
self._finished = False
self._aboutToFinish = False
rectLabel = owner.GetLineLabelRect(itemEdit)
rectLabel.x, rectLabel.y = self._owner.CalcScrolledPosition(rectLabel.x, rectLabel.y)
xSize, ySize = rectLabel.width + 10, rectLabel.height
expandoStyle = wx.WANTS_CHARS
if wx.Platform in ["__WXGTK__", "__WXMAC__"]:
expandoStyle |= wx.SIMPLE_BORDER
else:
expandoStyle |= wx.SUNKEN_BORDER
ExpandoTextCtrl.__init__(self, owner, -1, self._startValue, wx.Point(rectLabel.x, rectLabel.y),
wx.Size(xSize, ySize), expandoStyle)
self.Bind(wx.EVT_CHAR, self.OnChar)
self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
def AcceptChanges(self):
""" Accepts/refuses the changes made by the user. """
value = self.GetValue()
if value == self._startValue:
# nothing changed, always accept
# when an item remains unchanged, the owner
# needs to be notified that the user decided
# not to change the tree item label, and that
# the edit has been cancelled
self._owner.OnRenameCancelled(self._itemEdited)
return True
if not self._owner.OnRenameAccept(self._itemEdited, value):
# vetoed by the user
return False
# accepted, do rename the item
self._owner.SetItemText(self._itemEdited, value)
if value.count("\n") != self._startValue.count("\n"):
self._owner.ResetLineDimensions()
self._owner.Refresh()
return True
def Finish(self):
""" Finish editing. """
try:
if not self._finished:
self._finished = True
self._owner.SetFocusIgnoringChildren()
self._owner.ResetTextControl()
except RuntimeError:
return
def OnChar(self, event):
"""
Handles the ``wx.EVT_CHAR`` event for :class:`UltimateListTextCtrl`.
:param `event`: a :class:`KeyEvent` event to be processed.
"""
keycode = event.GetKeyCode()
shiftDown = event.ShiftDown()
if keycode in [wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER]:
if shiftDown:
event.Skip()
else:
self._aboutToFinish = True
self.SetValue(self._currentValue)
# Notify the owner about the changes
self.AcceptChanges()
# Even if vetoed, close the control (consistent with MSW)
wx.CallAfter(self.Finish)
elif keycode == wx.WXK_ESCAPE:
self.StopEditing()
else:
event.Skip()
def OnKeyUp(self, event):
"""
Handles the ``wx.EVT_KEY_UP`` event for :class:`UltimateListTextCtrl`.
:param `event`: a :class:`KeyEvent` event to be processed.
"""
if not self._finished:
# auto-grow the textctrl:
parentSize = self._owner.GetSize()
myPos = self.GetPosition()
mySize = self.GetSize()
dc = wx.ClientDC(self)
sx, sy, dummy = dc.GetFullMultiLineTextExtent(self.GetValue() + "M")
if myPos.x + sx > parentSize.x:
sx = parentSize.x - myPos.x
if mySize.x > sx:
sx = mySize.x
self.SetSize((sx, -1))
self._currentValue = self.GetValue()
event.Skip()
def OnKillFocus(self, event):
"""
Handles the ``wx.EVT_KILL_FOCUS`` event for :class:`UltimateListTextCtrl`.
:param `event`: a :class:`FocusEvent` event to be processed.
"""
if not self._finished and not self._aboutToFinish:
# We must finish regardless of success, otherwise we'll get
# focus problems:
if not self.AcceptChanges():
self._owner.OnRenameCancelled(self._itemEdited)
# We must let the native text control handle focus, too, otherwise
# it could have problems with the cursor (e.g., in wxGTK).
event.Skip()
wx.CallAfter(self.Finish)
def StopEditing(self):
""" Suddenly stops the editing. """
self._owner.OnRenameCancelled(self._itemEdited)
self.Finish()
#-----------------------------------------------------------------------------
# UltimateListMainWindow (internal)
#-----------------------------------------------------------------------------
class UltimateListMainWindow(wx.ScrolledWindow):
"""
This is the main widget implementation of :class:`UltimateListCtrl`.
"""
def __init__(self, parent, id, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=0, agwStyle=0, name="listctrlmainwindow"):
"""
Default class constructor.
:param `parent`: parent window. Must not be ``None``;
:param `id`: window identifier. A value of -1 indicates a default value;
:param `pos`: the control position. A value of (-1, -1) indicates a default position,
chosen by either the windowing system or wxPython, depending on platform;
:param `size`: the control size. A value of (-1, -1) indicates a default size,
chosen by either the windowing system or wxPython, depending on platform;
:param `style`: the underlying :class:`ScrolledWindow` window style;
:param `agwStyle`: the AGW-specific window style; can be almost any combination of the following
bits:
=============================== =========== ====================================================================================================
Window Styles Hex Value Description
=============================== =========== ====================================================================================================
``ULC_VRULES`` 0x1 Draws light vertical rules between rows in report mode.
``ULC_HRULES`` 0x2 Draws light horizontal rules between rows in report mode.
``ULC_ICON`` 0x4 Large icon view, with optional labels.
``ULC_SMALL_ICON`` 0x8 Small icon view, with optional labels.
``ULC_LIST`` 0x10 Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don't set columns as in ``ULC_REPORT``. In other words, the list wraps, unlike a :class:`ListBox`.
``ULC_REPORT`` 0x20 Single or multicolumn report view, with optional header.
``ULC_ALIGN_TOP`` 0x40 Icons align to the top. Win32 default, Win32 only.
``ULC_ALIGN_LEFT`` 0x80 Icons align to the left.
``ULC_AUTOARRANGE`` 0x100 Icons arrange themselves. Win32 only.
``ULC_VIRTUAL`` 0x200 The application provides items text on demand. May only be used with ``ULC_REPORT``.
``ULC_EDIT_LABELS`` 0x400 Labels are editable: the application will be notified when editing starts.
``ULC_NO_HEADER`` 0x800 No header in report mode.
``ULC_NO_SORT_HEADER`` 0x1000 No Docs.
``ULC_SINGLE_SEL`` 0x2000 Single selection (default is multiple).
``ULC_SORT_ASCENDING`` 0x4000 Sort in ascending order. (You must still supply a comparison callback in :meth:`ListCtrl.SortItems`.)
``ULC_SORT_DESCENDING`` 0x8000 Sort in descending order. (You must still supply a comparison callback in :meth:`ListCtrl.SortItems`.)
``ULC_TILE`` 0x10000 Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented).
``ULC_NO_HIGHLIGHT`` 0x20000 No highlight when an item is selected.
``ULC_STICKY_HIGHLIGHT`` 0x40000 Items are selected by simply hovering on them, with no need to click on them.
``ULC_STICKY_NOSELEVENT`` 0x80000 Don't send a selection event when using ``ULC_STICKY_HIGHLIGHT`` style.
``ULC_SEND_LEFTCLICK`` 0x100000 Send a left click event when an item is selected.
``ULC_HAS_VARIABLE_ROW_HEIGHT`` 0x200000 The list has variable row heights.
``ULC_AUTO_CHECK_CHILD`` 0x400000 When a column header has a checkbox associated, auto-check all the subitems in that column.
``ULC_AUTO_TOGGLE_CHILD`` 0x800000 When a column header has a checkbox associated, toggle all the subitems in that column.
``ULC_AUTO_CHECK_PARENT`` 0x1000000 Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well.
``ULC_SHOW_TOOLTIPS`` 0x2000000 Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text.
``ULC_HOT_TRACKING`` 0x4000000 Enable hot tracking of items on mouse motion.
``ULC_BORDER_SELECT`` 0x8000000 Changes border colour whan an item is selected, instead of highlighting the item.
``ULC_TRACK_SELECT`` 0x10000000 Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the `win32api` call `win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)`, and is defaulted to 400ms on other platforms. This style applies to all views of `UltimateListCtrl`.
``ULC_HEADER_IN_ALL_VIEWS`` 0x20000000 Show column headers in all view modes.
``ULC_NO_FULL_ROW_SELECT`` 0x40000000 When an item is selected, the only the item in the first column is highlighted.
``ULC_FOOTER`` 0x80000000 Show a footer too (only when header is present).
``ULC_USER_ROW_HEIGHT`` 0x100000000 Allows to set a custom row height (one value for all the items, only in report mode).
=============================== =========== ====================================================================================================
:param `name`: the window name.
"""
wx.ScrolledWindow.__init__(self, parent, id, pos, size, style|wx.HSCROLL|wx.VSCROLL, name)
# the list of column objects
self._columns = []
# the array of all line objects for a non virtual list control (for the
# virtual list control we only ever use self._lines[0])
self._lines = []
# currently focused item or -1
self._current = -1
# the number of lines per page
self._linesPerPage = 0
# Automatically resized column - this column expands to fill the width of the window
self._resizeColumn = -1
self._resizeColMinWidth = None
# this flag is set when something which should result in the window
# redrawing happens (i.e. an item was added or deleted, or its appearance
# changed) and OnPaint() doesn't redraw the window while it is set which
# allows to minimize the number of repaintings when a lot of items are
# being added. The real repainting occurs only after the next OnIdle()
# call
self._dirty = False
self._parent = parent
self.Init()
self._highlightBrush = wx.Brush(wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT), wx.BRUSHSTYLE_SOLID)
btnshadow = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNSHADOW)
self._highlightUnfocusedBrush = wx.Brush(btnshadow, wx.BRUSHSTYLE_SOLID)
r, g, b = btnshadow.Red(), btnshadow.Green(), btnshadow.Blue()
backcolour = (max((r >> 1) - 20, 0),
max((g >> 1) - 20, 0),
max((b >> 1) - 20, 0))
backcolour = wx.Colour(backcolour[0], backcolour[1], backcolour[2])
self._highlightUnfocusedBrush2 = wx.Brush(backcolour)
self.SetScrollbars(0, 0, 0, 0, 0, 0)
attr = wx.ListCtrl.GetClassDefaultAttributes()
self.SetOwnForegroundColour(attr.colFg)
self.SetOwnBackgroundColour(attr.colBg)
self.SetOwnFont(attr.font)
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
self.Bind(wx.EVT_CHILD_FOCUS, self.OnChildFocus)
self.Bind(wx.EVT_CHAR, self.OnChar)
self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
self.Bind(wx.EVT_SCROLLWIN, self.OnScroll)
self.Bind(wx.EVT_TIMER, self.OnHoverTimer, self._hoverTimer)
def Init(self):
""" Initializes the :class:`UltimateListMainWindow` widget. """
self._dirty = True
self._countVirt = 0
self._lineFrom = None
self._lineTo = - 1
self._linesPerPage = 0
self._headerWidth = 0
self._lineHeight = 0
self._userLineHeight = None
self._small_image_list = None
self._normal_image_list = None
self._small_spacing = 30
self._normal_spacing = 40
self._hasFocus = False
self._dragCount = 0
self._isCreated = False
self._lastOnSame = False
self._renameTimer = UltimateListRenameTimer(self)
self._textctrl = None
self._current = -1
self._lineLastClicked = -1
self._lineSelectSingleOnUp = -1
self._lineBeforeLastClicked = -1
self._dragStart = wx.Point(-1, -1)
self._aColWidths = []
self._selStore = SelectionStore()
self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
# Background image settings
self._backgroundImage = None
self._imageStretchStyle = _StyleTile
# Disabled items colour
self._disabledColour = wx.Colour(180, 180, 180)
# Gradient selection colours
self._firstcolour = colour= wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT)
self._secondcolour = wx.WHITE
self._usegradients = False
self._gradientstyle = 1 # Vertical Gradient
# Vista Selection Styles
self._vistaselection = False
self.SetImageListCheck(16, 16)
# Disabled items colour
self._disabledColour = wx.Colour(180, 180, 180)
# Hyperlinks things
normalFont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
self._hypertextfont = wx.Font(normalFont.GetPointSize(), normalFont.GetFamily(),
normalFont.GetStyle(), wx.FONTWEIGHT_NORMAL, True,
normalFont.GetFaceName(), normalFont.GetEncoding())
self._hypertextnewcolour = wx.BLUE
self._hypertextvisitedcolour = wx.Colour(200, 47, 200)
self._isonhyperlink = False
self._itemWithWindow = []
self._hasWindows = False
self._shortItems = []
self._isDragging = False
self._cursor = wx.STANDARD_CURSOR
image = GetdragcursorImage()
# since this image didn't come from a .cur file, tell it where the hotspot is
image.SetOption(wx.IMAGE_OPTION_CUR_HOTSPOT_X, 1)
image.SetOption(wx.IMAGE_OPTION_CUR_HOTSPOT_Y, 1)
# make the image into a cursor
self._dragCursor = wx.Cursor(image)
self._dragItem = None
self._dropTarget = None
self._oldHotCurrent = None
self._newHotCurrent = None
self._waterMark = None
self._hoverTimer = wx.Timer(self, wx.ID_ANY)
self._hoverItem = -1
def GetMainWindowOfCompositeControl(self):
""" Returns the :class:`UltimateListMainWindow` parent. """
return self.GetParent()
def DoGetBestSize(self):
"""
Gets the size which best suits the window: for a control, it would be the
minimal size which doesn't truncate the control, for a panel - the same size
as it would have after a call to `Fit()`.
"""
return wx.Size(100, 80)
def HasAGWFlag(self, flag):
"""
Returns ``True`` if the window has the given `flag` bit set.
:param `flag`: the bit to check.
:see: :meth:`UltimateListCtrl.SetSingleStyle() <UltimateListCtrl.SetSingleStyle>` for a list of valid flags.
"""
return self._parent.HasAGWFlag(flag)
def IsColumnShown(self, column):
"""
Returns ``True`` if the input column is shown, ``False`` if it is hidden.
:param `column`: an integer specifying the column index.
"""
return self.GetColumn(column).IsShown()
# return True if this is a virtual list control
def IsVirtual(self):
""" Returns ``True`` if the window has the ``ULC_VIRTUAL`` style set. """
return self.HasAGWFlag(ULC_VIRTUAL)
# return True if the control is in report mode
def InReportView(self):
""" Returns ``True`` if the window is in report mode. """
return self.HasAGWFlag(ULC_REPORT)
def InTileView(self):
"""
Returns ``True`` if the window is in tile mode (partially implemented).
.. todo:: Fully implement tile view for :class:`UltimateListCtrl`.
"""
return self.HasAGWFlag(ULC_TILE)
# return True if we are in single selection mode, False if multi sel
def IsSingleSel(self):
""" Returns ``True`` if we are in single selection mode, ``False`` if multi selection. """
return self.HasAGWFlag(ULC_SINGLE_SEL)
def HasFocus(self):
""" Returns ``True`` if the window has focus. """
return self._hasFocus
# do we have a header window?
def HasHeader(self):
""" Returns ``True`` if the header window is shown. """
if (self.InReportView() or self.InTileView()) and not self.HasAGWFlag(ULC_NO_HEADER):
return True
if self.HasAGWFlag(ULC_HEADER_IN_ALL_VIEWS):
return True
return False
# do we have a footer window?
def HasFooter(self):
""" Returns ``True`` if the footer window is shown. """
if self.HasHeader() and self.HasAGWFlag(ULC_FOOTER):
return True
return False
# toggle the line state and refresh it
def ReverseHighlight(self, line):
"""
Toggles the line state and refreshes it.
:param `line`: an instance of :class:`UltimateListLineData`.
"""
self.HighlightLine(line, not self.IsHighlighted(line))
self.RefreshLine(line)
def SetUserLineHeight(self, height):
"""
Sets a custom value for the :class:`UltimateListMainWindow` item height.
:param `height`: the custom height for all the items, in pixels.
:note: This method can be used only with ``ULC_REPORT`` and ``ULC_USER_ROW_HEIGHT`` styles set.
"""
if self.HasAGWFlag(ULC_REPORT) and self.HasAGWFlag(ULC_USER_ROW_HEIGHT):
self._userLineHeight = height
return
raise Exception("SetUserLineHeight can only be used with styles ULC_REPORT and ULC_USER_ROW_HEIGHT set.")
def GetUserLineHeight(self):
"""
Returns the custom value for the :class:`UltimateListMainWindow` item height, if previously set with
:meth:`~UltimateListMainWindow.SetUserLineHeight`.
:note: This method can be used only with ``ULC_REPORT`` and ``ULC_USER_ROW_HEIGHT`` styles set.
"""
if self.HasAGWFlag(ULC_REPORT) and self.HasAGWFlag(ULC_USER_ROW_HEIGHT):
return self._userLineHeight
raise Exception("GetUserLineHeight can only be used with styles ULC_REPORT and ULC_USER_ROW_HEIGHT set.")
# get the size of the total line rect
def GetLineSize(self, line):
"""
Returns the size of the total line client rectangle.
:param `line`: an instance of :class:`UltimateListLineData`.
"""
return self.GetLineRect(line).GetSize()
# bring the current item into view
def MoveToFocus(self):
""" Brings tyhe current item into view. """
self.MoveToItem(self._current)
def GetColumnCount(self):
""" Returns the total number of columns in the :class:`UltimateListCtrl`. """
return len(self._columns)
def GetItemText(self, item):
"""
Returns the item text.
:param `item`: an instance of :class:`UltimateListItem`.
"""
info = UltimateListItem()
info._mask = ULC_MASK_TEXT
info._itemId = item
info = self.GetItem(info)
return info._text
def SetItemText(self, item, value):
"""
Sets the item text.
:param `item`: an instance of :class:`UltimateListItem`;
:param `value`: the new item text.
"""
info = UltimateListItem()
info._mask = ULC_MASK_TEXT
info._itemId = item
info._text = value
self.SetItem(info)
def IsEmpty(self):
""" Returns ``True`` if the window has no items in it. """
return self.GetItemCount() == 0
def ResetCurrent(self):
""" Resets the current item to ``None``. """
self.ChangeCurrent(-1)
def HasCurrent(self):
"""
Returns ``True`` if the current item has been set, either programmatically
or by user intervention.
"""
return self._current != -1
# override base class virtual to reset self._lineHeight when the font changes
def SetFont(self, font):
"""
Overridden base class virtual to reset the line height when the font changes.
:param `font`: a valid :class:`wx.Font` object.
:note: Overridden from :class:`ScrolledWindow`.
"""
if not wx.ScrolledWindow.SetFont(self, font):
return False
self._lineHeight = 0
self.ResetLineDimensions()
return True
def ResetLineDimensions(self, force=False):
"""
Resets the line dimensions, so that client rectangles and positions are
recalculated.
:param `force`: ``True`` to reset all line dimensions.
"""
if (self.HasAGWFlag(ULC_REPORT) and self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT) and not self.IsVirtual()) or force:
for l in range(self.GetItemCount()):
line = self.GetLine(l)
line.ResetDimensions()
# these are for UltimateListLineData usage only
# get the backpointer to the list ctrl
def GetListCtrl(self):
""" Returns the parent widget, an instance of :class:`UltimateListCtrl`. """
return self.GetParent()
# get the brush to use for the item highlighting
def GetHighlightBrush(self):
""" Returns the brush to use for the item highlighting. """
return (self._hasFocus and [self._highlightBrush] or [self._highlightUnfocusedBrush])[0]
# get the line data for the given index
def GetLine(self, n):
"""
Returns the line data for the given index.
:param `n`: the line index.
"""
if self.IsVirtual():
self.CacheLineData(n)
n = 0
return self._lines[n]
# force us to recalculate the range of visible lines
def ResetVisibleLinesRange(self, reset=False):
"""
Forces us to recalculate the range of visible lines.
:param `reset`: ``True`` to reset all line dimensions, which will then be
recalculated.
"""
self._lineFrom = -1
if self.IsShownOnScreen() and reset:
self.ResetLineDimensions()
# Called on EVT_SIZE to resize the _resizeColumn to fill the width of the window
def ResizeColumns(self):
"""
If ``ULC_AUTOSIZE_FILL`` was passed to :meth:`UltimateListCtrl.SetColumnWidth() <UltimateListCtrl.SetColumnWidth>` then
that column's width will be expanded to fill the window on a resize event.
Called by :meth:`UltimateListCtrl.OnSize() <UltimateListCtrl.OnSize>` when the window is resized.
"""
if not self: # Avoid RuntimeError on Mac
return
if self._resizeColumn == -1:
return
numCols = self.GetColumnCount()
if numCols == 0: return # Nothing to resize.
resizeCol = self._resizeColumn
if self._resizeColMinWidth == None:
self._resizeColMinWidth = self.GetColumnWidth(resizeCol)
# We're showing the vertical scrollbar -> allow for scrollbar width
# NOTE: on GTK, the scrollbar is included in the client size, but on
# Windows it is not included
listWidth = self.GetClientSize().width
if wx.Platform != '__WXMSW__':
if self.GetItemCount() > self.GetCountPerPage():
scrollWidth = wx.SystemSettings.GetMetric(wx.SYS_VSCROLL_X)
listWidth = listWidth - scrollWidth
totColWidth = 0 # Width of all columns except last one.
for col in range(numCols):
if col != (resizeCol) and self.IsColumnShown(col):
totColWidth = totColWidth + self.GetColumnWidth(col)
resizeColWidth = self.GetColumnWidth(resizeCol)
if totColWidth + self._resizeColMinWidth > listWidth:
# We haven't got the width to show the last column at its minimum
# width -> set it to its minimum width and allow the horizontal
# scrollbar to show.
self.SetColumnWidth(resizeCol, self._resizeColMinWidth)
return
# Resize the last column to take up the remaining available space.
self.SetColumnWidth(resizeCol, listWidth - totColWidth)
# get the colour to be used for drawing the rules
def GetRuleColour(self):
""" Returns the colour to be used for drawing the horizontal and vertical rules. """
return wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT)
def SetReportView(self, inReportView):
"""
Sets whether :class:`UltimateListCtrl` is in report view or not.
:param `inReportView`: ``True`` to set :class:`UltimateListCtrl` in report view, ``False``
otherwise.
"""
for line in self._lines:
line.SetReportView(inReportView)
def CacheLineData(self, line):
"""
Saves the current line attributes.
:param `line`: an instance of :class:`UltimateListLineData`.
:note: This method is used only if the :class:`UltimateListCtrl` has the ``ULC_VIRTUAL``
style set.
"""
listctrl = self.GetListCtrl()
ld = self.GetDummyLine()
countCol = self.GetColumnCount()
for col in range(countCol):
ld.SetText(col, listctrl.OnGetItemText(line, col))
ld.SetToolTip(col, listctrl.OnGetItemToolTip(line, col))
ld.SetColour(col, listctrl.OnGetItemTextColour(line, col))
ld.SetImage(col, listctrl.OnGetItemColumnImage(line, col))
kind = listctrl.OnGetItemColumnKind(line, col)
ld.SetKind(col, kind)
if kind > 0:
ld.Check(col, listctrl.OnGetItemColumnCheck(line, col))
ld.SetAttr(listctrl.OnGetItemAttr(line))
def GetDummyLine(self):
"""
Returns a dummy line.
:note: This method is used only if the :class:`UltimateListCtrl` has the ``ULC_VIRTUAL``
style set.
"""
if self.IsEmpty():
raise Exception("invalid line index")
if not self.IsVirtual():
raise Exception("GetDummyLine() shouldn't be called")
# we need to recreate the dummy line if the number of columns in the
# control changed as it would have the incorrect number of fields
# otherwise
if len(self._lines) > 0 and len(self._lines[0]._items) != self.GetColumnCount():
self._lines = []
if not self._lines:
line = UltimateListLineData(self)
self._lines.append(line)
return self._lines[0]
# ----------------------------------------------------------------------------
# line geometry (report mode only)
# ----------------------------------------------------------------------------
def GetLineHeight(self, item=None):
"""
Returns the line height for a specific item.
:param `item`: if not ``None``, an instance of :class:`UltimateListItem`.
"""
# we cache the line height as calling GetTextExtent() is slow
if self.HasAGWFlag(ULC_REPORT) and self.HasAGWFlag(ULC_USER_ROW_HEIGHT):
if self._userLineHeight is not None:
return self._userLineHeight
if item is None or not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
if not self._lineHeight:
dc = wx.ClientDC(self)
dc.SetFont(self.GetFont())
dummy, y = dc.GetTextExtent("H")
if self._small_image_list and self._small_image_list.GetImageCount():
iw, ih = self._small_image_list.GetSize(0)
y = max(y, ih)
y += EXTRA_HEIGHT
self._lineHeight = y + LINE_SPACING
return self._lineHeight
else:
line = self.GetLine(item)
LH = line.GetHeight()
if LH != -1:
return LH
dc = wx.ClientDC(self)
allTextY = 0
for col, items in enumerate(line._items):
if items.GetCustomRenderer():
allTextY = max(allTextY, items.GetCustomRenderer().GetLineHeight())
continue
if items.HasFont():
dc.SetFont(items.GetFont())
else:
dc.SetFont(self.GetFont())
text_x, text_y, dummy = dc.GetFullMultiLineTextExtent(items.GetText())
allTextY = max(text_y, allTextY)
if items.GetWindow():
xSize, ySize = items.GetWindowSize()
allTextY = max(allTextY, ySize)
if self._small_image_list and self._small_image_list.GetImageCount():
for img in items._image:
iw, ih = self._small_image_list.GetSize(img)
allTextY = max(allTextY, ih)
allTextY += EXTRA_HEIGHT
line.SetHeight(allTextY)
return allTextY
def GetLineY(self, line):
"""
Returns the line `y` position.
:param `line`: an instance of :class:`UltimateListLineData`.
"""
if self.IsVirtual():
return LINE_SPACING + line*self.GetLineHeight()
lineItem = self.GetLine(line)
lineY = lineItem.GetY()
if lineY != -1:
return lineY
lineY = 0
for l in range(line):
lineY += self.GetLineHeight(l)
lineItem.SetY(LINE_SPACING + lineY)
return LINE_SPACING + lineY
def GetLineRect(self, line):
"""
Returns the line client rectangle.
:param `line`: an instance of :class:`UltimateListLineData`.
"""
if not self.InReportView():
return self.GetLine(line)._gi._rectAll
rect = wx.Rect(HEADER_OFFSET_X, self.GetLineY(line), self.GetHeaderWidth(), self.GetLineHeight(line))
return rect
def GetLineLabelRect(self, line, col=0):
"""
Returns the line client rectangle for the item text only.
Note this is the full column width unless an image or
checkbox exists. It is not the width of the text itself
:param `line`: an instance of :class:`UltimateListLineData`.
"""
if not self.InReportView():
return self.GetLine(line)._gi._rectLabel
image_x = 0
image_width = 0
for c in range(col):
image_x += self.GetColumnWidth(c)
item = self.GetLine(line)
if item.HasImage(col):
ix, iy = self.GetImageSize(item.GetImage(col))
image_x += ix
image_width = ix
if item.GetKind(col) in [1, 2]:
image_x += self.GetCheckboxImageSize()[0]
image_width += self.GetCheckboxImageSize()[0]
rect = wx.Rect(image_x + HEADER_OFFSET_X, self.GetLineY(line), self.GetColumnWidth(col) - image_width, self.GetLineHeight(line))
return rect
def GetLineIconRect(self, line):
"""
Returns the line client rectangle for the item image only.
:param `line`: an instance of :class:`UltimateListLineData`.
"""
if not self.InReportView():
return self.GetLine(line)._gi._rectIcon
ld = self.GetLine(line)
image_x = HEADER_OFFSET_X
if ld.GetKind() in [1, 2]:
image_x += self.GetCheckboxImageSize()[0]
rect = wx.Rect(image_x, self.GetLineY(line), *self.GetImageSize(ld.GetImage()))
return rect
def GetLineCheckboxRect(self, line):
"""
Returns the line client rectangle for the item checkbox image only.
:param `line`: an instance of :class:`UltimateListLineData`.
"""
if not self.InReportView():
return self.GetLine(line)._gi._rectCheck
ld = self.GetLine(line)
LH = self.GetLineHeight(line)
wcheck, hcheck = self.GetCheckboxImageSize()
rect = wx.Rect(HEADER_OFFSET_X, self.GetLineY(line) + LH/2 - hcheck/2, wcheck, hcheck)
return rect
def GetLineHighlightRect(self, line):
"""
Returns the line client rectangle when the line is highlighted.
:param `line`: an instance of :class:`UltimateListLineData`.
"""
return (self.InReportView() and [self.GetLineRect(line)] or [self.GetLine(line)._gi._rectHighlight])[0]
def HitTestLine(self, line, x, y):
"""
HitTest method for a :class:`UltimateListCtrl` line.
:param `line`: an instance of :class:`UltimateListLineData`;
:param `x`: the mouse `x` position;
:param `y`: the mouse `y` position.
:return: a tuple of values, representing the item hit and a hit flag. The
hit flag can be one of the following bits:
=============================== ========= ================================
HitTest Flag Hex Value Description
=============================== ========= ================================
``ULC_HITTEST_ABOVE`` 0x1 Above the client area
``ULC_HITTEST_BELOW`` 0x2 Below the client area
``ULC_HITTEST_NOWHERE`` 0x4 In the client area but below the last item
``ULC_HITTEST_ONITEM`` 0x2a0 Anywhere on the item (text, icon, checkbox image)
``ULC_HITTEST_ONITEMICON`` 0x20 On the bitmap associated with an item
``ULC_HITTEST_ONITEMLABEL`` 0x80 On the label (string) associated with an item
``ULC_HITTEST_ONITEMRIGHT`` 0x100 In the area to the right of an item
``ULC_HITTEST_ONITEMSTATEICON`` 0x200 On the state icon for a list view item that is in a user-defined state
``ULC_HITTEST_TOLEFT`` 0x400 To the left of the client area
``ULC_HITTEST_TORIGHT`` 0x800 To the right of the client area
``ULC_HITTEST_ONITEMCHECK`` 0x1000 On the item checkbox (if any)
=============================== ========= ================================
"""
ld = self.GetLine(line)
if self.InReportView():# and not self.IsVirtual():
lineY = self.GetLineY(line)
xstart = HEADER_OFFSET_X
for col, item in enumerate(ld._items):
if not self.IsColumnShown(col):
continue
width = self.GetColumnWidth(col)
xOld = xstart
xstart += width
ix = 0
#if (line, col) in self._shortItems:
#rect = wx.Rect(xOld, lineY, width, self.GetLineHeight(line))
rect = self.GetLineLabelRect(line,col)
if rect.Contains((x, y)):
newItem = self.GetParent().GetItem(line, col)
return newItem, ULC_HITTEST_ONITEMLABEL
if item.GetKind() in [1, 2]:
# We got a checkbox-type item
ix, iy = self.GetCheckboxImageSize()
LH = self.GetLineHeight(line)
rect = wx.Rect(xOld, lineY + LH/2 - iy/2, ix, iy)
if rect.Contains((x, y)):
newItem = self.GetParent().GetItem(line, col)
return newItem, ULC_HITTEST_ONITEMCHECK
if item.IsHyperText():
start, end = self.GetItemTextSize(item)
label_rect = self.GetLineLabelRect(line, col)
rect = wx.Rect(xOld+start, lineY, min(end, label_rect.width), self.GetLineHeight(line))
if rect.Contains((x, y)):
newItem = self.GetParent().GetItem(line, col)
return newItem, ULC_HITTEST_ONITEMLABEL
xOld += ix
if ld.HasImage() and self.GetLineIconRect(line).Contains((x, y)):
return self.GetParent().GetItem(line), ULC_HITTEST_ONITEMICON
# VS: Testing for "ld.HasText() || InReportView()" instead of
# "ld.HasText()" is needed to make empty lines in report view
# possible
if ld.HasText() or self.InReportView():
if self.InReportView():
rect = self.GetLineRect(line)
else:
checkRect = self.GetLineCheckboxRect(line)
if checkRect.Contains((x, y)):
return self.GetParent().GetItem(line), ULC_HITTEST_ONITEMCHECK
rect = self.GetLineLabelRect(line)
if rect.Contains((x, y)):
return self.GetParent().GetItem(line), ULC_HITTEST_ONITEMLABEL
rect = self.GetLineRect(line)
if rect.Contains((x, y)):
return self.GetParent().GetItem(line), ULC_HITTEST_ONITEM
return None, 0
# ----------------------------------------------------------------------------
# highlight (selection) handling
# ----------------------------------------------------------------------------
def IsHighlighted(self, line):
"""
Returns ``True`` if the input line is highlighted.
:param `line`: an instance of :class:`UltimateListLineData`.
"""
if self.IsVirtual():
return self._selStore.IsSelected(line)
else: # !virtual
ld = self.GetLine(line)
return ld.IsHighlighted()
def HighlightLines(self, lineFrom, lineTo, highlight=True):
"""
Highlights a range of lines in :class:`UltimateListCtrl`.
:param `lineFrom`: an integer representing the first line to highlight;
:param `lineTo`: an integer representing the last line to highlight;
:param `highlight`: ``True`` to highlight the lines, ``False`` otherwise.
"""
if self.IsVirtual():
linesChanged = self._selStore.SelectRange(lineFrom, lineTo, highlight)
if not linesChanged:
# many items changed state, refresh everything
self.RefreshLines(lineFrom, lineTo)
else: # only a few items changed state, refresh only them
for n in range(len(linesChanged)):
self.RefreshLine(linesChanged[n])
else: # iterate over all items in non report view
for line in range(lineFrom, lineTo+1):
if self.HighlightLine(line, highlight):
self.RefreshLine(line)
def HighlightLine(self, line, highlight=True):
"""
Highlights a line in :class:`UltimateListCtrl`.
:param `line`: an instance of :class:`UltimateListLineData`;
:param `highlight`: ``True`` to highlight the line, ``False`` otherwise.
"""
changed = False
if self.IsVirtual():
changed = self._selStore.SelectItem(line, highlight)
else: # !virtual
ld = self.GetLine(line)
changed = ld.Highlight(highlight)
dontNotify = self.HasAGWFlag(ULC_STICKY_HIGHLIGHT) and self.HasAGWFlag(ULC_STICKY_NOSELEVENT)
if changed and not dontNotify:
self.SendNotify(line, (highlight and [wxEVT_COMMAND_LIST_ITEM_SELECTED] or [wxEVT_COMMAND_LIST_ITEM_DESELECTED])[0])
return changed
def RefreshLine(self, line):
"""
Redraws the input line.
:param `line`: an instance of :class:`UltimateListLineData`.
"""
if self.InReportView():
visibleFrom, visibleTo = self.GetVisibleLinesRange()
if line < visibleFrom or line > visibleTo:
return
rect = self.GetLineRect(line)
rect.x, rect.y = self.CalcScrolledPosition(rect.x, rect.y)
self.RefreshRect(rect)
def RefreshLines(self, lineFrom, lineTo):
"""
Redraws a range of lines in :class:`UltimateListCtrl`.
:param `lineFrom`: an integer representing the first line to refresh;
:param `lineTo`: an integer representing the last line to refresh.
"""
if self.InReportView():
visibleFrom, visibleTo = self.GetVisibleLinesRange()
if lineFrom < visibleFrom:
lineFrom = visibleFrom
if lineTo > visibleTo:
lineTo = visibleTo
rect = wx.Rect()
rect.x = 0
rect.y = self.GetLineY(lineFrom)
rect.width = self.GetClientSize().x
rect.height = self.GetLineY(lineTo) - rect.y + self.GetLineHeight(lineTo)
rect.x, rect.y = self.CalcScrolledPosition(rect.x, rect.y)
self.RefreshRect(rect)
else: # !report
# TODO: this should be optimized...
for line in range(lineFrom, lineTo+1):
self.RefreshLine(line)
def RefreshAfter(self, lineFrom):
"""
Redraws all the lines after the input one.
:param `lineFrom`: an integer representing the first line to refresh.
"""
if self.InReportView():
visibleFrom, visibleTo = self.GetVisibleLinesRange()
if lineFrom < visibleFrom:
lineFrom = visibleFrom
elif lineFrom > visibleTo:
return
rect = wx.Rect()
rect.x = 0
rect.y = self.GetLineY(lineFrom)
rect.x, rect.y = self.CalcScrolledPosition(rect.x, rect.y)
size = self.GetClientSize()
rect.width = size.x
# refresh till the bottom of the window
rect.height = size.y - rect.y
self.RefreshRect(rect)
else: # !report
# TODO: how to do it more efficiently?
self._dirty = True
def RefreshSelected(self):
""" Redraws the selected lines. """
if self.IsEmpty():
return
if self.InReportView():
fromm, to = self.GetVisibleLinesRange()
else: # !virtual
fromm = 0
to = self.GetItemCount() - 1
if self.HasCurrent() and self._current >= fromm and self._current <= to:
self.RefreshLine(self._current)
for line in range(fromm, to+1):
# NB: the test works as expected even if self._current == -1
if line != self._current and self.IsHighlighted(line):
self.RefreshLine(line)
def HideWindows(self):
""" Hides the windows associated to the items. Used internally. """
for child in self._itemWithWindow:
wnd = child.GetWindow()
if wnd:
wnd.Hide()
def OnPaint(self, event):
"""
Handles the ``wx.EVT_PAINT`` event for :class:`UltimateListMainWindow`.
:param `event`: a :class:`PaintEvent` event to be processed.
"""
# Note: a wxPaintDC must be constructed even if no drawing is
# done (a Windows requirement).
dc = wx.BufferedPaintDC(self)
dc.SetBackgroundMode(wx.TRANSPARENT)
self.PrepareDC(dc)
dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
dc.SetPen(wx.TRANSPARENT_PEN)
dc.Clear()
self.TileBackground(dc)
self.PaintWaterMark(dc)
if self.IsEmpty():
# nothing to draw or not the moment to draw it
return
if self._dirty:
# delay the repainting until we calculate all the items positions
self.RecalculatePositions(False)
useVista, useGradient = self._vistaselection, self._usegradients
dev_x, dev_y = self.CalcScrolledPosition(0, 0)
dc.SetFont(self.GetFont())
if self.InReportView():
visibleFrom, visibleTo = self.GetVisibleLinesRange()
# mrcs: draw additional items
if visibleFrom > 0:
visibleFrom -= 1
if visibleTo < self.GetItemCount() - 1:
visibleTo += 1
xOrig = dc.LogicalToDeviceX(0)
yOrig = dc.LogicalToDeviceY(0)
# tell the caller cache to cache the data
if self.IsVirtual():
evCache = UltimateListEvent(wxEVT_COMMAND_LIST_CACHE_HINT, self.GetParent().GetId())
evCache.SetEventObject(self.GetParent())
evCache.m_oldItemIndex = visibleFrom
evCache.m_itemIndex = visibleTo
self.GetParent().GetEventHandler().ProcessEvent(evCache)
no_highlight = self.HasAGWFlag(ULC_NO_HIGHLIGHT)
for line in range(visibleFrom, visibleTo+1):
rectLine = self.GetLineRect(line)
if not self.IsExposed(rectLine.x + xOrig, rectLine.y + yOrig, rectLine.width, rectLine.height):
# don't redraw unaffected lines to avoid flicker
continue
theLine = self.GetLine(line)
enabled = theLine.GetItem(0, CreateListItem(line, 0)).IsEnabled()
oldPN, oldBR = dc.GetPen(), dc.GetBrush()
theLine.DrawInReportMode(dc, line, rectLine,
self.GetLineHighlightRect(line),
self.IsHighlighted(line) and not no_highlight,
line==self._current, enabled, oldPN, oldBR)
if self.HasAGWFlag(ULC_HRULES):
pen = wx.Pen(self.GetRuleColour(), 1, wx.PENSTYLE_SOLID)
clientSize = self.GetClientSize()
# Don't draw the first one
start = (visibleFrom > 0 and [visibleFrom] or [1])[0]
dc.SetPen(pen)
dc.SetBrush(wx.TRANSPARENT_BRUSH)
for i in range(start, visibleTo+1):
lineY = self.GetLineY(i)
dc.DrawLine(0 - dev_x, lineY, clientSize.x - dev_x, lineY)
# Draw last horizontal rule
if visibleTo == self.GetItemCount() - 1:
lineY = self.GetLineY(visibleTo) + self.GetLineHeight(visibleTo)
dc.SetPen(pen)
dc.SetBrush(wx.TRANSPARENT_BRUSH)
dc.DrawLine(0 - dev_x, lineY, clientSize.x - dev_x , lineY)
# Draw vertical rules if required
if self.HasAGWFlag(ULC_VRULES) and not self.IsEmpty():
pen = wx.Pen(self.GetRuleColour(), 1, wx.PENSTYLE_SOLID)
firstItemRect = self.GetItemRect(visibleFrom)
lastItemRect = self.GetItemRect(visibleTo)
x = firstItemRect.GetX()
dc.SetPen(pen)
dc.SetBrush(wx.TRANSPARENT_BRUSH)
for col in range(self.GetColumnCount()):
if not self.IsColumnShown(col):
continue
colWidth = self.GetColumnWidth(col)
x += colWidth
x_pos = x - dev_x
if col < self.GetColumnCount()-1:
x_pos -= 2
dc.DrawLine(x_pos, firstItemRect.GetY() - 1 - dev_y, x_pos, lastItemRect.GetBottom() + 1 - dev_y)
else: # !report
for i in range(self.GetItemCount()):
self.GetLine(i).Draw(i, dc)
if wx.Platform not in ["__WXMAC__", "__WXGTK__"]:
# Don't draw rect outline under Mac at all.
# Draw it elsewhere on GTK
if self.HasCurrent():
if self._hasFocus and not self.HasAGWFlag(ULC_NO_HIGHLIGHT) and not useVista and not useGradient \
and not self.HasAGWFlag(ULC_BORDER_SELECT) and not self.HasAGWFlag(ULC_NO_FULL_ROW_SELECT):
dc.SetPen(wx.BLACK_PEN)
dc.SetBrush(wx.TRANSPARENT_BRUSH)
dc.DrawRectangle(self.GetLineHighlightRect(self._current))
def OnEraseBackground(self, event):
"""
Handles the ``wx.EVT_ERASE_BACKGROUND`` event for :class:`UltimateListMainWindow`.
:param `event`: a :class:`EraseEvent` event to be processed.
:note: This method is intentionally empty to reduce flicker.
"""
pass
def TileBackground(self, dc):
"""
Tiles the background image to fill all the available area.
:param `dc`: an instance of :class:`wx.DC`.
.. todo:: Support background images also in stretch and centered modes.
"""
if not self._backgroundImage:
return
if self._imageStretchStyle != _StyleTile:
# Can we actually do something here (or in OnPaint()) To Handle
# background images that are stretchable or always centered?
# I tried but I get enormous flickering...
return
sz = self.GetClientSize()
w = self._backgroundImage.GetWidth()
h = self._backgroundImage.GetHeight()
x = 0
while x < sz.width:
y = 0
while y < sz.height:
dc.DrawBitmap(self._backgroundImage, x, y, True)
y = y + h
x = x + w
def PaintWaterMark(self, dc):
"""
Draws a watermark at the bottom right of :class:`UltimateListCtrl`.
:param `dc`: an instance of :class:`wx.DC`.
.. todo:: Better support for this is needed.
"""
if not self._waterMark:
return
width, height = self.CalcUnscrolledPosition(*self.GetClientSize())
bitmapW = self._waterMark.GetWidth()
bitmapH = self._waterMark.GetHeight()
x = width - bitmapW - 5
y = height - bitmapH - 5
dc.DrawBitmap(self._waterMark, x, y, True)
def HighlightAll(self, on=True):
"""
Highlights/unhighlights all the lines in :class:`UltimateListCtrl`.
:param `on`: ``True`` to highlight all the lines, ``False`` to unhighlight them.
"""
if self.IsSingleSel():
if on:
raise Exception("can't do this in a single sel control")
# we just have one item to turn off
if self.HasCurrent() and self.IsHighlighted(self._current):
self.HighlightLine(self._current, False)
self.RefreshLine(self._current)
else: # multi sel
if not self.IsEmpty():
self.HighlightLines(0, self.GetItemCount() - 1, on)
def OnChildFocus(self, event):
"""
Handles the ``wx.EVT_CHILD_FOCUS`` event for :class:`UltimateListMainWindow`.
:param `event`: a :class:`ChildFocusEvent` event to be processed.
.. note::
This method is intentionally empty to prevent the default handler in
:class:`ScrolledWindow` from needlessly scrolling the window when the edit
control is dismissed.
"""
# Do nothing here. This prevents the default handler in wx.ScrolledWindow
# from needlessly scrolling the window when the edit control is
# dismissed. See ticket #9563.
pass
def SendNotify(self, line, command, point=wx.DefaultPosition):
"""
Actually sends a :class:`UltimateListEvent`.
:param `line`: an instance of :class:`UltimateListLineData`;
:param `command`: the event type to send;
:param `point`: an instance of :class:`wx.Point`.
"""
bRet = True
le = UltimateListEvent(command, self.GetParent().GetId())
le.SetEventObject(self.GetParent())
le.m_itemIndex = line
# set only for events which have position
if point != wx.DefaultPosition:
le.m_pointDrag = point
# don't try to get the line info for virtual list controls: the main
# program has it anyhow and if we did it would result in accessing all
# the lines, even those which are not visible now and this is precisely
# what we're trying to avoid
if not self.IsVirtual():
if line != -1:
self.GetLine(line).GetItem(0, le.m_item)
#else: this happens for wxEVT_COMMAND_LIST_ITEM_FOCUSED event
#else: there may be no more such item
self.GetParent().GetEventHandler().ProcessEvent(le)
bRet = le.IsAllowed()
return bRet
def ChangeCurrent(self, current):
"""
Changes the current line to the specified one.
:param `current`: an integer specifying the index of the current line.
"""
self._current = current
# as the current item changed, we shouldn't start editing it when the
# "slow click" timer expires as the click happened on another item
if self._renameTimer.IsRunning():
self._renameTimer.Stop()
self.SendNotify(current, wxEVT_COMMAND_LIST_ITEM_FOCUSED)
def EditLabel(self, item):
"""
Starts editing an item label.
:param `item`: an instance of :class:`UltimateListItem`.
"""
if item < 0 or item >= self.GetItemCount():
raise Exception("wrong index in UltimateListCtrl.EditLabel()")
le = UltimateListEvent(wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT, self.GetParent().GetId())
le.SetEventObject(self.GetParent())
le.m_itemIndex = item
data = self.GetLine(item)
le.m_item = data.GetItem(0, le.m_item)
self._textctrl = UltimateListTextCtrl(self, item)
if self.GetParent().GetEventHandler().ProcessEvent(le) and not le.IsAllowed():
# vetoed by user code
return
# We have to call this here because the label in question might just have
# been added and no screen update taken place.
if self._dirty:
wx.SafeYield()
# Pending events dispatched by wx.SafeYield might have changed the item
# count
if item >= self.GetItemCount():
return None
# modified
self._textctrl.SetFocus()
return self._textctrl
def OnRenameTimer(self):
""" The timer for renaming has expired. Start editing. """
if not self.HasCurrent():
raise Exception("unexpected rename timer")
self.EditLabel(self._current)
def OnRenameAccept(self, itemEdit, value):
"""
Called by :class:`UltimateListTextCtrl`, to accept the changes and to send the
``EVT_LIST_END_LABEL_EDIT`` event.
:param `itemEdit`: an instance of :class:`UltimateListItem`;
:param `value`: the new value of the item label.
"""
le = UltimateListEvent(wxEVT_COMMAND_LIST_END_LABEL_EDIT, self.GetParent().GetId())
le.SetEventObject(self.GetParent())
le.m_itemIndex = itemEdit
data = self.GetLine(itemEdit)
le.m_item = data.GetItem(0, le.m_item)
le.m_item._text = value
return not self.GetParent().GetEventHandler().ProcessEvent(le) or le.IsAllowed()
def OnRenameCancelled(self, itemEdit):
"""
Called by :class:`UltimateListTextCtrl`, to cancel the changes and to send the
``EVT_LIST_END_LABEL_EDIT`` event.
:param `item`: an instance of :class:`UltimateListItem`.
"""
# let owner know that the edit was cancelled
le = UltimateListEvent(wxEVT_COMMAND_LIST_END_LABEL_EDIT, self.GetParent().GetId())
le.SetEditCanceled(True)
le.SetEventObject(self.GetParent())
le.m_itemIndex = itemEdit
data = self.GetLine(itemEdit)
le.m_item = data.GetItem(0, le.m_item)
self.GetEventHandler().ProcessEvent(le)
def OnMouse(self, event):
"""
Handles the ``wx.EVT_MOUSE_EVENTS`` event for :class:`UltimateListMainWindow`.
:param `event`: a :class:`MouseEvent` event to be processed.
"""
if wx.Platform == "__WXMAC__":
# On wxMac we can't depend on the EVT_KILL_FOCUS event to properly
# shutdown the edit control when the mouse is clicked elsewhere on the
# listctrl because the order of events is different (or something like
# that,) so explicitly end the edit if it is active.
if event.LeftDown() and self._textctrl:
self._textctrl.AcceptChanges()
self._textctrl.Finish()
if event.LeftDown():
self.SetFocusIgnoringChildren()
event.SetEventObject(self.GetParent())
if self.GetParent().GetEventHandler().ProcessEvent(event):
return
if event.GetEventType() == wx.wxEVT_MOUSEWHEEL:
# let the base handle mouse wheel events.
self.Refresh()
event.Skip()
return
if self.IsEmpty():
if event.RightDown():
self.SendNotify(-1, wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK, event.GetPosition())
evtCtx = wx.ContextMenuEvent(wx.wxEVT_CONTEXT_MENU, self.GetParent().GetId(),
self.ClientToScreen(event.GetPosition()))
evtCtx.SetEventObject(self.GetParent())
self.GetParent().GetEventHandler().ProcessEvent(evtCtx)
return
if self._dirty:
return
if not (event.Dragging() or event.ButtonDown() or event.LeftUp() or \
event.ButtonDClick() or event.Moving() or event.RightUp()):
return
x = event.GetX()
y = event.GetY()
x, y = self.CalcUnscrolledPosition(x, y)
# where did we hit it (if we did)?
hitResult = 0
newItem = None
count = self.GetItemCount()
if self.InReportView():
if not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
current = y // self.GetLineHeight()
if current < count:
newItem, hitResult = self.HitTestLine(current, x, y)
else:
return
else:
for current in range(count):
newItem, hitResult = self.HitTestLine(current, x, y)
if hitResult:
break
else:
# TODO: optimize it too! this is less simple than for report view but
# enumerating all items is still not a way to do it!!
for current in range(count):
newItem, hitResult = self.HitTestLine(current, x, y)
if hitResult:
break
theItem = None
if not self.IsVirtual():
theItem = CreateListItem(current, 0)
theItem = self.GetItem(theItem)
if event.GetEventType() == wx.wxEVT_MOTION and not event.Dragging():
if current >= 0 and current < count and self.HasAGWFlag(ULC_TRACK_SELECT) and not self._hoverTimer.IsRunning():
self._hoverItem = current
self._hoverTimer.Start(HOVER_TIME, wx.TIMER_ONE_SHOT)
if newItem and newItem.IsHyperText() and (hitResult & ULC_HITTEST_ONITEMLABEL) and theItem and theItem.IsEnabled():
self.SetCursor(wx.Cursor(wx.CURSOR_HAND))
self._isonhyperlink = True
else:
if self._isonhyperlink:
self.SetCursor(wx.Cursor(wx.CURSOR_ARROW))
self._isonhyperlink = False
if self.HasAGWFlag(ULC_STICKY_HIGHLIGHT) and hitResult:
if not self.IsHighlighted(current):
self.HighlightAll(False)
self.ChangeCurrent(current)
self.ReverseHighlight(self._current)
if self.HasAGWFlag(ULC_SHOW_TOOLTIPS):
if newItem and hitResult & ULC_HITTEST_ONITEMLABEL:
r,c = (newItem._itemId, newItem._col)
line = self.GetLine(r)
tt = line.GetToolTip(c)
if tt and not tt == "":
if self.GetToolTip() and self.GetToolTip().GetTip() != tt:
self.SetToolTip(tt)
elif (r,c) in self._shortItems: # if the text didn't fit in the column
text = newItem.GetText()
if self.GetToolTip() and self.GetToolTip().GetTip() != text:
self.SetToolTip(text)
else:
self.SetToolTip("")
else:
self.SetToolTip("")
if self.HasAGWFlag(ULC_HOT_TRACKING):
if hitResult:
if self._oldHotCurrent != current:
if self._oldHotCurrent is not None:
self.RefreshLine(self._oldHotCurrent)
self._newHotCurrent = current
self.RefreshLine(self._newHotCurrent)
self._oldHotCurrent = current
event.Skip()
return
if event.Dragging():
if not self._isDragging:
if self._lineLastClicked == -1 or not hitResult or not theItem or not theItem.IsEnabled():
return
if self._dragCount == 0:
# we have to report the raw, physical coords as we want to be
# able to call HitTest(event.m_pointDrag) from the user code to
# get the item being dragged
self._dragStart = event.GetPosition()
self._dragCount += 1
if self._dragCount != 3:
return
command = (event.RightIsDown() and [wxEVT_COMMAND_LIST_BEGIN_RDRAG] or [wxEVT_COMMAND_LIST_BEGIN_DRAG])[0]
le = UltimateListEvent(command, self.GetParent().GetId())
le.SetEventObject(self.GetParent())
le.m_itemIndex = self._lineLastClicked
le.m_pointDrag = self._dragStart
self.GetParent().GetEventHandler().ProcessEvent(le)
# we're going to drag this item
self._isDragging = True
self._dragItem = current
# remember the old cursor because we will change it while
# dragging
self._oldCursor = self._cursor
self.SetCursor(self._dragCursor)
else:
if current != self._dropTarget:
self.SetCursor(self._dragCursor)
# unhighlight the previous drop target
if self._dropTarget is not None:
self.RefreshLine(self._dropTarget)
move = current
if self._dropTarget:
move = (current > self._dropTarget and [current+1] or [current-1])[0]
self._dropTarget = current
self.MoveToItem(move)
else:
if self._dragItem == current:
self.SetCursor(wx.Cursor(wx.CURSOR_NO_ENTRY))
if self.HasAGWFlag(ULC_REPORT) and self._dragItem != current:
self.DrawDnDArrow()
return
else:
self._dragCount = 0
if theItem and not theItem.IsEnabled():
self.DragFinish(event)
event.Skip()
return
if not hitResult:
# outside of any item
if event.RightDown():
self.SendNotify(-1, wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK, event.GetPosition())
evtCtx = wx.ContextMenuEvent(wx.wxEVT_CONTEXT_MENU, self.GetParent().GetId(),
self.ClientToScreen(event.GetPosition()))
evtCtx.SetEventObject(self.GetParent())
self.GetParent().GetEventHandler().ProcessEvent(evtCtx)
else:
self.HighlightAll(False)
self.DragFinish(event)
return
forceClick = False
if event.ButtonDClick():
if self._renameTimer.IsRunning():
self._renameTimer.Stop()
self._lastOnSame = False
if current == self._lineLastClicked:
self.SendNotify(current, wxEVT_COMMAND_LIST_ITEM_ACTIVATED)
if newItem and newItem.GetKind() in [1, 2] and (hitResult & ULC_HITTEST_ONITEMCHECK):
self.CheckItem(newItem, not self.IsItemChecked(newItem))
return
else:
# The first click was on another item, so don't interpret this as
# a double click, but as a simple click instead
forceClick = True
if event.LeftUp():
if self.DragFinish(event):
return
if self._lineSelectSingleOnUp != - 1:
# select single line
self.HighlightAll(False)
self.ReverseHighlight(self._lineSelectSingleOnUp)
if self._lastOnSame:
if (current == self._current) and (hitResult == ULC_HITTEST_ONITEMLABEL) and self.HasAGWFlag(ULC_EDIT_LABELS):
if not self.InReportView() or self.GetLineLabelRect(current).Contains((x, y)):
# This wx.SYS_DCLICK_MSEC is not yet wrapped in wxPython...
# dclick = wx.SystemSettings.GetMetric(wx.SYS_DCLICK_MSEC)
# m_renameTimer->Start(dclick > 0 ? dclick : 250, True)
self._renameTimer.Start(250, True)
self._lastOnSame = False
self._lineSelectSingleOnUp = -1
elif event.RightUp():
if self.DragFinish(event):
return
else:
# This is necessary, because after a DnD operation in
# from and to ourself, the up event is swallowed by the
# DnD code. So on next non-up event (which means here and
# now) self._lineSelectSingleOnUp should be reset.
self._lineSelectSingleOnUp = -1
if event.RightDown():
if self.SendNotify(current, wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK, event.GetPosition()):
self._lineBeforeLastClicked = self._lineLastClicked
self._lineLastClicked = current
# If the item is already selected, do not update the selection.
# Multi-selections should not be cleared if a selected item is clicked.
if not self.IsHighlighted(current):
self.HighlightAll(False)
self.ChangeCurrent(current)
self.ReverseHighlight(self._current)
# Allow generation of context menu event
event.Skip()
elif event.MiddleDown():
self.SendNotify(current, wxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK)
elif event.LeftDown() or forceClick:
self._lineBeforeLastClicked = self._lineLastClicked
self._lineLastClicked = current
oldCurrent = self._current
oldWasSelected = self.IsHighlighted(self._current)
cmdModifierDown = event.CmdDown()
if self.IsSingleSel() or not (cmdModifierDown or event.ShiftDown()):
if self.IsSingleSel() or not self.IsHighlighted(current):
self.HighlightAll(False)
self.ChangeCurrent(current)
self.ReverseHighlight(self._current)
else: # multi sel & current is highlighted & no mod keys
self._lineSelectSingleOnUp = current
self.ChangeCurrent(current) # change focus
else: # multi sel & either ctrl or shift is down
if cmdModifierDown:
self.ChangeCurrent(current)
self.ReverseHighlight(self._current)
elif event.ShiftDown():
self.ChangeCurrent(current)
lineFrom, lineTo = oldCurrent, current
shift = 0
if lineTo < lineFrom:
lineTo = lineFrom
lineFrom = self._current
if not self.IsHighlighted(lineFrom):
shift = 1
for i in range(lineFrom+1, lineTo+1):
if self.IsHighlighted(i):
self.HighlightLine(i, False)
self.RefreshLine(i)
lineTo -= 1
self.HighlightLines(lineFrom, lineTo+shift)
else: # !ctrl, !shift
# test in the enclosing if should make it impossible
raise Exception("how did we get here?")
if newItem:
if event.LeftDown():
if newItem.GetKind() in [1, 2] and (hitResult & ULC_HITTEST_ONITEMCHECK):
self.CheckItem(newItem, not self.IsItemChecked(newItem))
if newItem.IsHyperText():
self.SetItemVisited(newItem, True)
self.HandleHyperLink(newItem)
if self._current != oldCurrent:
self.RefreshLine(oldCurrent)
# forceClick is only set if the previous click was on another item
self._lastOnSame = not forceClick and (self._current == oldCurrent) and oldWasSelected
if self.HasAGWFlag(ULC_STICKY_HIGHLIGHT) and self.HasAGWFlag(ULC_STICKY_NOSELEVENT) and self.HasAGWFlag(ULC_SEND_LEFTCLICK):
self.SendNotify(current, wxEVT_COMMAND_LIST_ITEM_LEFT_CLICK, event.GetPosition())
def DrawDnDArrow(self):
""" Draws a drag and drop visual representation of an arrow. """
dc = wx.ClientDC(self)
lineY = self.GetLineY(self._dropTarget)
width = self.GetTotalWidth()
dc.SetPen(wx.Pen(wx.BLACK, 2))
x, y = self.CalcScrolledPosition(HEADER_OFFSET_X, lineY+2*HEADER_OFFSET_Y)
tri1 = [wx.Point(x+1, y-2), wx.Point(x+1, y+4), wx.Point(x+4, y+1)]
tri2 = [wx.Point(x+width-1, y-2), wx.Point(x+width-1, y+4), wx.Point(x+width-4, y+1)]
dc.DrawPolygon(tri1)
dc.DrawPolygon(tri2)
dc.DrawLine(x, y+1, width, y+1)
def DragFinish(self, event):
"""
A drag and drop operation has just finished.
:param `event`: a :class:`MouseEvent` event to be processed.
"""
if not self._isDragging:
return False
self._isDragging = False
self._dragCount = 0
self._dragItem = None
self.SetCursor(self._oldCursor)
self.Refresh()
le = UltimateListEvent(wxEVT_COMMAND_LIST_END_DRAG, self.GetParent().GetId())
le.SetEventObject(self.GetParent())
le.m_itemIndex = self._dropTarget
le.m_pointDrag = event.GetPosition()
self.GetParent().GetEventHandler().ProcessEvent(le)
return True
def HandleHyperLink(self, item):
"""
Handles the hyperlink items, sending the ``EVT_LIST_ITEM_HYPERLINK`` event.
:param `item`: an instance of :class:`UltimateListItem`.
"""
if self.IsItemHyperText(item):
self.SendNotify(item._itemId, wxEVT_COMMAND_LIST_ITEM_HYPERLINK)
def OnHoverTimer(self, event):
"""
Handles the ``wx.EVT_TIMER`` event for :class:`UltimateListMainWindow`.
:param `event`: a :class:`TimerEvent` event to be processed.
"""
x, y = self.ScreenToClient(wx.GetMousePosition())
x, y = self.CalcUnscrolledPosition(x, y)
item, hitResult = self.HitTestLine(self._hoverItem, x, y)
if item and item._itemId == self._hoverItem:
if not self.IsHighlighted(self._hoverItem):
dontNotify = self.HasAGWFlag(ULC_STICKY_HIGHLIGHT) and self.HasAGWFlag(ULC_STICKY_NOSELEVENT)
if not dontNotify:
self.SendNotify(self._hoverItem, wxEVT_COMMAND_LIST_ITEM_SELECTED)
self.HighlightAll(False)
self.ChangeCurrent(self._hoverItem)
self.ReverseHighlight(self._current)
def MoveToItem(self, item):
"""
Scrolls the input item into view.
:param `item`: an instance of :class:`UltimateListItem`.
"""
if item == -1:
return
if item >= self.GetItemCount():
item = self.GetItemCount() - 1
rect = self.GetLineRect(item)
client_w, client_h = self.GetClientSize()
hLine = self.GetLineHeight(item)
view_x = SCROLL_UNIT_X*self.GetScrollPos(wx.HORIZONTAL)
view_y = hLine*self.GetScrollPos(wx.VERTICAL)
if self.InReportView():
# the next we need the range of lines shown it might be different, so
# recalculate it
self.ResetVisibleLinesRange()
if not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
if rect.y < view_y:
self.Scroll(-1, rect.y/hLine)
if rect.y+rect.height+5 > view_y+client_h:
self.Scroll(-1, (rect.y+rect.height-client_h+hLine)/hLine)
if wx.Platform == "__WXMAC__":
# At least on Mac the visible lines value will get reset inside of
# Scroll *before* it actually scrolls the window because of the
# Update() that happens there, so it will still have the wrong value.
# So let's reset it again and wait for it to be recalculated in the
# next paint event. I would expect this problem to show up in wxGTK
# too but couldn't duplicate it there. Perhaps the order of events
# is different... --Robin
self.ResetVisibleLinesRange()
else:
view_y = SCROLL_UNIT_Y*self.GetScrollPos(wx.VERTICAL)
start_y, height = rect.y, rect.height
if start_y < view_y:
while start_y > view_y:
start_y -= SCROLL_UNIT_Y
self.Scroll(-1, start_y/SCROLL_UNIT_Y)
if start_y + height > view_y + client_h:
while start_y + height < view_y + client_h:
start_y += SCROLL_UNIT_Y
self.Scroll(-1, (start_y+height-client_h+SCROLL_UNIT_Y)/SCROLL_UNIT_Y)
else: # !report
sx = sy = -1
if rect.x-view_x < 5:
sx = (rect.x - 5)/SCROLL_UNIT_X
if rect.x+rect.width-5 > view_x+client_w:
sx = (rect.x + rect.width - client_w + SCROLL_UNIT_X)/SCROLL_UNIT_X
if rect.y-view_y < 5:
sy = (rect.y - 5)/hLine
if rect.y + rect.height - 5 > view_y + client_h:
sy = (rect.y + rect.height - client_h + hLine)/hLine
self.Scroll(sx, sy)
# ----------------------------------------------------------------------------
# keyboard handling
# ----------------------------------------------------------------------------
def GetNextActiveItem(self, item, down=True):
"""
Returns the next active item. Used Internally at present.
:param `item`: an instance of :class:`UltimateListItem`;
:param `down`: ``True`` to search downwards for an active item, ``False``
to search upwards.
"""
count = self.GetItemCount()
initialItem = item
while 1:
if item >= count or item < 0:
return initialItem
listItem = CreateListItem(item, 0)
listItem = self.GetItem(listItem, 0)
if listItem.IsEnabled():
return item
item = (down and [item+1] or [item-1])[0]
def OnArrowChar(self, newCurrent, event):
"""
Handles the keyboard arrows key events.
:param `newCurrent`: an integer specifying the new current item;
:param `event`: a :class:`KeyEvent` event to be processed.
"""
oldCurrent = self._current
newCurrent = self.GetNextActiveItem(newCurrent, newCurrent > oldCurrent)
# in single selection we just ignore Shift as we can't select several
# items anyhow
if event.ShiftDown() and not self.IsSingleSel():
self.ChangeCurrent(newCurrent)
# refresh the old focus to remove it
self.RefreshLine(oldCurrent)
# select all the items between the old and the new one
if oldCurrent > newCurrent:
newCurrent = oldCurrent
oldCurrent = self._current
self.HighlightLines(oldCurrent, newCurrent)
else: # !shift
# all previously selected items are unselected unless ctrl is held
# in a multi-selection control
if not event.ControlDown() or self.IsSingleSel():
self.HighlightAll(False)
self.ChangeCurrent(newCurrent)
# refresh the old focus to remove it
self.RefreshLine(oldCurrent)
if not event.ControlDown() or self.IsSingleSel():
self.HighlightLine(self._current, True)
self.RefreshLine(self._current)
self.MoveToFocus()
def OnKeyDown(self, event):
"""
Handles the ``wx.EVT_KEY_DOWN`` event for :class:`UltimateListMainWindow`.
:param `event`: a :class:`KeyEvent` event to be processed.
"""
parent = self.GetParent()
# we propagate the key event upwards
ke = event.Clone()
ke.SetEventObject(parent)
if parent.GetEventHandler().ProcessEvent(ke):
event.Skip()
return
event.Skip()
def OnKeyUp(self, event):
"""
Handles the ``wx.EVT_KEY_UP`` event for :class:`UltimateListMainWindow`.
:param `event`: a :class:`KeyEvent` event to be processed.
"""
parent = self.GetParent()
# we propagate the key event upwards
ke = event.Clone()
ke.SetEventObject(parent)
if parent.GetEventHandler().ProcessEvent(ke):
return
event.Skip()
def OnChar(self, event):
"""
Handles the ``wx.EVT_CHAR`` event for :class:`UltimateListMainWindow`.
:param `event`: a :class:`KeyEvent` event to be processed.
"""
parent = self.GetParent()
if self.IsVirtual() and self.GetItemCount() == 0:
event.Skip()
return
# we send a list_key event up
if self.HasCurrent():
le = UltimateListEvent(wxEVT_COMMAND_LIST_KEY_DOWN, self.GetParent().GetId())
le.m_itemIndex = self._current
le.m_item = self.GetLine(self._current).GetItem(0, le.m_item)
le.m_code = event.GetKeyCode()
le.SetEventObject(parent)
parent.GetEventHandler().ProcessEvent(le)
keyCode = event.GetKeyCode()
if keyCode not in [wx.WXK_UP, wx.WXK_DOWN, wx.WXK_RIGHT, wx.WXK_LEFT, \
wx.WXK_PAGEUP, wx.WXK_PAGEDOWN, wx.WXK_END, wx.WXK_HOME]:
# propagate the char event upwards
ke = event.Clone()
ke.SetEventObject(parent)
if parent.GetEventHandler().ProcessEvent(ke):
return
if event.GetKeyCode() == wx.WXK_TAB:
nevent = wx.NavigationKeyEvent()
nevent.SetWindowChange(event.ControlDown())
nevent.SetDirection(not event.ShiftDown())
nevent.SetEventObject(self.GetParent().GetParent())
nevent.SetCurrentFocus(self._parent)
if self.GetParent().GetParent().GetEventHandler().ProcessEvent(nevent):
return
# no item . nothing to do
if not self.HasCurrent():
event.Skip()
return
keyCode = event.GetKeyCode()
if keyCode == wx.WXK_UP:
if self._current > 0:
self.OnArrowChar(self._current - 1, event)
if self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
self._dirty = True
elif keyCode == wx.WXK_DOWN:
if self._current < self.GetItemCount() - 1:
self.OnArrowChar(self._current + 1, event)
if self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
self._dirty = True
elif keyCode == wx.WXK_END:
if not self.IsEmpty():
self.OnArrowChar(self.GetItemCount() - 1, event)
self._dirty = True
elif keyCode == wx.WXK_HOME:
if not self.IsEmpty():
self.OnArrowChar(0, event)
self._dirty = True
elif keyCode == wx.WXK_PAGEUP:
steps = (self.InReportView() and [self._linesPerPage - 1] or [self._current % self._linesPerPage])[0]
index = self._current - steps
if index < 0:
index = 0
self.OnArrowChar(index, event)
self._dirty = True
elif keyCode == wx.WXK_PAGEDOWN:
steps = (self.InReportView() and [self._linesPerPage - 1] or [self._linesPerPage - (self._current % self._linesPerPage) - 1])[0]
index = self._current + steps
count = self.GetItemCount()
if index >= count:
index = count - 1
self.OnArrowChar(index, event)
self._dirty = True
elif keyCode == wx.WXK_LEFT:
if not self.InReportView():
index = self._current - self._linesPerPage
if index < 0:
index = 0
self.OnArrowChar(index, event)
elif keyCode == wx.WXK_RIGHT:
if not self.InReportView():
index = self._current + self._linesPerPage
count = self.GetItemCount()
if index >= count:
index = count - 1
self.OnArrowChar(index, event)
elif keyCode == wx.WXK_SPACE:
if self.IsSingleSel():
if event.ControlDown():
self.ReverseHighlight(self._current)
else: # normal space press
self.SendNotify(self._current, wxEVT_COMMAND_LIST_ITEM_ACTIVATED)
else:
# select it in ReverseHighlight() below if unselected
self.ReverseHighlight(self._current)
elif keyCode in [wx.WXK_RETURN, wx.WXK_EXECUTE, wx.WXK_NUMPAD_ENTER]:
self.SendNotify(self._current, wxEVT_COMMAND_LIST_ITEM_ACTIVATED)
else:
event.Skip()
# ----------------------------------------------------------------------------
# focus handling
# ----------------------------------------------------------------------------
def OnSetFocus(self, event):
"""
Handles the ``wx.EVT_SET_FOCUS`` event for :class:`UltimateListMainWindow`.
:param `event`: a :class:`FocusEvent` event to be processed.
"""
if self.GetParent():
event = wx.FocusEvent(wx.wxEVT_SET_FOCUS, self.GetParent().GetId())
event.SetEventObject(self.GetParent())
if self.GetParent().GetEventHandler().ProcessEvent(event):
return
# wxGTK sends us EVT_SET_FOCUS events even if we had never got
# EVT_KILL_FOCUS before which means that we finish by redrawing the items
# which are already drawn correctly resulting in horrible flicker - avoid
# it
if not self._hasFocus:
self._hasFocus = True
self.Refresh()
def OnKillFocus(self, event):
"""
Handles the ``wx.EVT_KILL_FOCUS`` event for :class:`UltimateListMainWindow`.
:param `event`: a :class:`FocusEvent` event to be processed.
"""
if self.GetParent():
event = wx.FocusEvent(wx.wxEVT_KILL_FOCUS, self.GetParent().GetId())
event.SetEventObject(self.GetParent())
if self.GetParent().GetEventHandler().ProcessEvent(event):
return
self._hasFocus = False
self.Refresh()
def DrawImage(self, index, dc, x, y, enabled):
"""
Draws one of the item images.
:param `index`: the index of the image inside the image list;
:param `dc`: an instance of :class:`wx.DC`;
:param `x`: the x position where to draw the image;
:param `y`: the y position where to draw the image;
:param `enabled`: ``True`` if the item is enabled, ``False`` if it is disabled.
"""
if self.HasAGWFlag(ULC_ICON) and self._normal_image_list:
imgList = (enabled and [self._normal_image_list] or [self._normal_grayed_image_list])[0]
imgList.Draw(index, dc, x, y, wx.IMAGELIST_DRAW_TRANSPARENT)
elif self.HasAGWFlag(ULC_SMALL_ICON) and self._small_image_list:
imgList = (enabled and [self._small_image_list] or [self._small_grayed_image_list])[0]
imgList.Draw(index, dc, x, y, wx.IMAGELIST_DRAW_TRANSPARENT)
elif self.HasAGWFlag(ULC_LIST) and self._small_image_list:
imgList = (enabled and [self._small_image_list] or [self._small_grayed_image_list])[0]
imgList.Draw(index, dc, x, y, wx.IMAGELIST_DRAW_TRANSPARENT)
elif self.InReportView() and self._small_image_list:
imgList = (enabled and [self._small_image_list] or [self._small_grayed_image_list])[0]
imgList.Draw(index, dc, x, y, wx.IMAGELIST_DRAW_TRANSPARENT)
def DrawCheckbox(self, dc, x, y, kind, checked, enabled):
"""
Draws the item checkbox/radiobutton image.
:param `dc`: an instance of :class:`wx.DC`;
:param `x`: the x position where to draw the image;
:param `y`: the y position where to draw the image;
:param `kind`: may be one of the following integers:
=============== ==========================
Item Kind Description
=============== ==========================
0 A normal item
1 A checkbox-like item
2 A radiobutton-type item
=============== ==========================
:param `checked`: ``True`` if the item is checked, ``False`` otherwise;
:param `enabled`: ``True`` if the item is enabled, ``False`` if it is disabled.
"""
imgList = (enabled and [self._image_list_check] or [self._grayed_check_list])[0]
if kind == 1:
# checkbox
index = (checked and [0] or [1])[0]
else:
# radiobutton
index = (checked and [2] or [3])[0]
imgList.Draw(index, dc, x, y, wx.IMAGELIST_DRAW_TRANSPARENT)
def GetCheckboxImageSize(self):
""" Returns the checkbox/radiobutton image size. """
bmp = self._image_list_check.GetBitmap(0)
return bmp.GetWidth(), bmp.GetHeight()
def GetImageSize(self, index):
"""
Returns the image size for the item.
:param `index`: the image index.
"""
width = height = 0
if self.HasAGWFlag(ULC_ICON) and self._normal_image_list:
for indx in index:
w, h = self._normal_image_list.GetSize(indx)
width += w + MARGIN_BETWEEN_TEXT_AND_ICON
height = max(height, h)
elif self.HasAGWFlag(ULC_SMALL_ICON) and self._small_image_list:
for indx in index:
w, h = self._small_image_list.GetSize(indx)
width += w + MARGIN_BETWEEN_TEXT_AND_ICON
height = max(height, h)
elif self.HasAGWFlag(ULC_LIST) and self._small_image_list:
for indx in index:
w, h = self._small_image_list.GetSize(indx)
width += w + MARGIN_BETWEEN_TEXT_AND_ICON
height = max(height, h)
elif self.InReportView() and self._small_image_list:
for indx in index:
w, h = self._small_image_list.GetSize(indx)
width += w + MARGIN_BETWEEN_TEXT_AND_ICON
height = max(height, h)
return width, height
def GetTextLength(self, s):
"""
Returns the text width for the input string.
:param `s`: the string to measure.
"""
dc = wx.ClientDC(self)
dc.SetFont(self.GetFont())
lw, lh, dummy = dc.GetFullMultiLineTextExtent(s)
return lw + AUTOSIZE_COL_MARGIN
def SetImageList(self, imageList, which):
"""
Sets the image list associated with the control.
:param `imageList`: an instance of :class:`wx.ImageList` or an instance of :class:`PyImageList`;
:param `which`: one of ``wx.IMAGE_LIST_NORMAL``, ``wx.IMAGE_LIST_SMALL``,
``wx.IMAGE_LIST_STATE`` (the last is unimplemented).
:note: Using :class:`PyImageList` enables you to have images of different size inside the
image list. In your derived class, instead of doing this::
imageList = wx.ImageList(16, 16)
imageList.Add(someBitmap)
self.SetImageList(imageList, wx.IMAGE_LIST_SMALL)
You should do this::
imageList = PyImageList(16, 16)
imageList.Add(someBitmap)
self.SetImageList(imageList, wx.IMAGE_LIST_SMALL)
"""
self._dirty = True
if isinstance(imageList, PyImageList):
# We have a custom PyImageList with variable image sizes
cls = PyImageList
else:
cls = wx.ImageList
# calc the spacing from the icon size
width = height = 0
if imageList and imageList.GetImageCount():
width, height = imageList.GetSize(0)
if which == wx.IMAGE_LIST_NORMAL:
self._normal_image_list = imageList
self._normal_grayed_image_list = cls(width, height, True, 0)
for ii in range(imageList.GetImageCount()):
bmp = imageList.GetBitmap(ii)
newbmp = MakeDisabledBitmap(bmp)
self._normal_grayed_image_list.Add(newbmp)
self._normal_spacing = width + 8
if which == wx.IMAGE_LIST_SMALL:
self._small_image_list = imageList
self._small_spacing = width + 14
self._small_grayed_image_list = cls(width, height, True, 0)
for ii in range(imageList.GetImageCount()):
bmp = imageList.GetBitmap(ii)
newbmp = MakeDisabledBitmap(bmp)
self._small_grayed_image_list.Add(newbmp)
self._lineHeight = 0 # ensure that the line height will be recalc'd
self.ResetLineDimensions()
def SetImageListCheck(self, sizex, sizey, imglist=None):
"""
Sets the checkbox/radiobutton image list.
:param `sizex`: the width of the bitmaps in the `imglist`;
:param `sizey`: the height of the bitmaps in the `imglist`;
:param `imglist`: an instance of :class:`wx.ImageList`.
"""
# Image list to hold disabled versions of each control
self._grayed_check_list = wx.ImageList(sizex, sizey, True, 0)
if imglist is None:
self._image_list_check = wx.ImageList(sizex, sizey)
# Get the Checkboxes
self._image_list_check.Add(self.GetControlBmp(checkbox=True,
checked=True,
enabled=True,
x=sizex, y=sizey))
self._grayed_check_list.Add(self.GetControlBmp(checkbox=True,
checked=True,
enabled=False,
x=sizex, y=sizey))
self._image_list_check.Add(self.GetControlBmp(checkbox=True,
checked=False,
enabled=True,
x=sizex, y=sizey))
self._grayed_check_list.Add(self.GetControlBmp(checkbox=True,
checked=False,
enabled=False,
x=sizex, y=sizey))
# Get the Radio Buttons
self._image_list_check.Add(self.GetControlBmp(checkbox=False,
checked=True,
enabled=True,
x=sizex, y=sizey))
self._grayed_check_list.Add(self.GetControlBmp(checkbox=False,
checked=True,
enabled=False,
x=sizex, y=sizey))
self._image_list_check.Add(self.GetControlBmp(checkbox=False,
checked=False,
enabled=True,
x=sizex, y=sizey))
self._grayed_check_list.Add(self.GetControlBmp(checkbox=False,
checked=False,
enabled=False,
x=sizex, y=sizey))
else:
sizex, sizey = imglist.GetSize(0)
self._image_list_check = imglist
for ii in range(self._image_list_check.GetImageCount()):
bmp = self._image_list_check.GetBitmap(ii)
newbmp = MakeDisabledBitmap(bmp)
self._grayed_check_list.Add(newbmp)
self._dirty = True
if imglist:
self.RecalculatePositions()
def GetControlBmp(self, checkbox=True, checked=False, enabled=True, x=16, y=16):
"""
Returns a native looking checkbox or radio button bitmap.
:param `checkbox`: ``True`` to get a checkbox image, ``False`` for a radiobutton
one;
:param `checked`: ``True`` if the control is marked, ``False`` if it is not;
:param `enabled`: ``True`` if the control is enabled, ``False`` if it is not;
:param `x`: the width of the bitmap, in pixels;
:param `y`: the height of the bitmap, in pixels.
"""
bmp = wx.Bitmap(x, y)
mdc = wx.MemoryDC(bmp)
mdc.SetBrush(wx.BLACK_BRUSH)
mdc.Clear()
render = wx.RendererNative.Get()
if checked:
flag = wx.CONTROL_CHECKED
else:
flag = 0
if not enabled:
flag |= wx.CONTROL_DISABLED
if checkbox:
render.DrawCheckBox(self, mdc, (0, 0, x, y), flag)
else:
if _VERSION_STRING < "2.9":
render.DrawRadioButton(self, mdc, (0, 0, x, y), flag)
else:
render.DrawRadioBitmap(self, mdc, (0, 0, x, y), flag)
mdc.SelectObject(wx.NullBitmap)
return bmp
def SetItemSpacing(self, spacing, isSmall=False):
"""
Sets the spacing between item texts and icons.
:param `spacing`: the spacing between item texts and icons, in pixels;
:param `isSmall`: ``True`` if using a ``wx.IMAGE_LIST_SMALL`` image list,
``False`` if using a ``wx.IMAGE_LIST_NORMAL`` image list.
"""
self._dirty = True
if isSmall:
self._small_spacing = spacing
else:
self._normal_spacing = spacing
def GetItemSpacing(self, isSmall=False):
"""
Returns the spacing between item texts and icons, in pixels.
:param `isSmall`: ``True`` if using a ``wx.IMAGE_LIST_SMALL`` image list,
``False`` if using a ``wx.IMAGE_LIST_NORMAL`` image list.
"""
return (isSmall and [self._small_spacing] or [self._normal_spacing])[0]
# ----------------------------------------------------------------------------
# columns
# ----------------------------------------------------------------------------
def SetColumn(self, col, item):
"""
Sets information about this column.
:param `col`: an integer specifying the column index;
:param `item`: an instance of :class:`UltimateListItem`.
"""
column = self._columns[col]
if item._width == ULC_AUTOSIZE_USEHEADER:
item._width = self.GetTextLength(item._text)
column.SetItem(item)
headerWin = self.GetListCtrl()._headerWin
if headerWin:
headerWin._dirty = True
self._dirty = True
# invalidate it as it has to be recalculated
self._headerWidth = 0
def SetColumnWidth(self, col, width):
"""
Sets the column width.
:param `width`: can be a width in pixels or ``wx.LIST_AUTOSIZE`` (-1) or
``wx.LIST_AUTOSIZE_USEHEADER`` (-2) or ``ULC_AUTOSIZE_FILL`` (-3).
``wx.LIST_AUTOSIZE`` will resize the column to the length of its longest
item. ``wx.LIST_AUTOSIZE_USEHEADER`` will resize the column to the
length of the header (Win32) or 80 pixels (other platforms).
``ULC_AUTOSIZE_FILL`` will resize the column fill the remaining width
of the window.
:note: In small or normal icon view, col must be -1, and the column width
is set for all columns.
"""
if col < 0:
raise Exception("invalid column index")
if not self.InReportView() and not self.InTileView() and not self.HasAGWFlag(ULC_HEADER_IN_ALL_VIEWS):
raise Exception("SetColumnWidth() can only be called in report/tile modes or with the ULC_HEADER_IN_ALL_VIEWS flag set.")
self._dirty = True
headerWin = self.GetListCtrl()._headerWin
footerWin = self.GetListCtrl()._footerWin
if headerWin:
headerWin._dirty = True
if footerWin:
footerWin._dirty = True
column = self._columns[col]
count = self.GetItemCount()
if width == ULC_AUTOSIZE_FILL:
width = self.GetColumnWidth(col)
if width == 0:
width = WIDTH_COL_DEFAULT
self._resizeColumn = col
elif width == ULC_AUTOSIZE_USEHEADER:
width = self.GetTextLength(column.GetText())
width += 2*EXTRA_WIDTH
if column.GetKind() in [1, 2]:
ix, iy = self._owner.GetCheckboxImageSize()
width += ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE
# check for column header's image availability
images = column.GetImage()
for img in images:
if self._small_image_list:
ix, iy = self._small_image_list.GetSize(img)
width += ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE
elif width == ULC_AUTOSIZE:
if self.IsVirtual() or not self.InReportView():
# TODO: determine the max width somehow...
width = WIDTH_COL_DEFAULT
else: # !virtual
maxW = AUTOSIZE_COL_MARGIN
# if the cached column width isn't valid then recalculate it
if self._aColWidths[col]._bNeedsUpdate:
for i in range(count):
line = self.GetLine(i)
itemData = line._items[col]
item = UltimateListItem()
item = itemData.GetItem(item)
itemWidth = self.GetItemWidthWithImage(item)
if itemWidth > maxW and not item._overFlow:
maxW = itemWidth
self._aColWidths[col]._bNeedsUpdate = False
self._aColWidths[col]._nMaxWidth = maxW
maxW = self._aColWidths[col]._nMaxWidth
width = maxW + AUTOSIZE_COL_MARGIN
column.SetWidth(width)
# invalidate it as it has to be recalculated
self._headerWidth = 0
self._footerWidth = 0
if footerWin:
footerWin.Refresh()
def GetHeaderWidth(self):
""" Returns the header window width, in pixels. """
if not self._headerWidth:
count = self.GetColumnCount()
for col in range(count):
if not self.IsColumnShown(col):
continue
self._headerWidth += self.GetColumnWidth(col)
if self.HasAGWFlag(ULC_FOOTER):
self._footerWidth = self._headerWidth
return self._headerWidth
def GetColumn(self, col):
"""
Returns information about this column.
:param `col`: an integer specifying the column index.
"""
item = UltimateListItem()
column = self._columns[col]
item = column.GetItem(item)
return item
def GetColumnWidth(self, col):
"""
Returns the column width for the input column.
:param `col`: an integer specifying the column index.
"""
column = self._columns[col]
return column.GetWidth()
def GetTotalWidth(self):
""" Returns the total width of the columns in :class:`UltimateListCtrl`. """
width = 0
for column in self._columns:
width += column.GetWidth()
return width
# ----------------------------------------------------------------------------
# item state
# ----------------------------------------------------------------------------
def SetItem(self, item):
"""
Sets information about the item.
:param `item`: an instance of :class:`UltimateListItemData`.
"""
id = item._itemId
if id < 0 or id >= self.GetItemCount():
raise Exception("invalid item index in SetItem")
if not self.IsVirtual():
line = self.GetLine(id)
line.SetItem(item._col, item)
# Set item state if user wants
if item._mask & ULC_MASK_STATE:
self.SetItemState(item._itemId, item._state, item._state)
if self.InReportView():
# update the Max Width Cache if needed
width = self.GetItemWidthWithImage(item)
if width > self._aColWidths[item._col]._nMaxWidth:
self._aColWidths[item._col]._nMaxWidth = width
self._aColWidths[item._col]._bNeedsUpdate = True
if self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
line.ResetDimensions()
# update the item on screen
if self.InReportView():
rectItem = self.GetItemRect(id)
self.RefreshRect(rectItem)
def SetItemStateAll(self, state, stateMask):
"""
Sets the item state flags for all the items.
:param `state`: any combination of the following bits:
============================ ========= ==============================
State Bits Hex Value Description
============================ ========= ==============================
``ULC_STATE_DONTCARE`` 0x0 Don't care what the state is
``ULC_STATE_DROPHILITED`` 0x1 The item is highlighted to receive a drop event
``ULC_STATE_FOCUSED`` 0x2 The item has the focus
``ULC_STATE_SELECTED`` 0x4 The item is selected
``ULC_STATE_CUT`` 0x8 The item is in the cut state
``ULC_STATE_DISABLED`` 0x10 The item is disabled
``ULC_STATE_FILTERED`` 0x20 The item has been filtered
``ULC_STATE_INUSE`` 0x40 The item is in use
``ULC_STATE_PICKED`` 0x80 The item has been picked
``ULC_STATE_SOURCE`` 0x100 The item is a drag and drop source
============================ ========= ==============================
:param `stateMask`: the bitmask for the state flag.
:note: The valid state flags are influenced by the value of the state mask.
"""
if self.IsEmpty():
return
# first deal with selection
if stateMask & ULC_STATE_SELECTED:
# set/clear select state
if self.IsVirtual():
# optimized version for virtual listctrl.
self._selStore.SelectRange(0, self.GetItemCount() - 1, state==ULC_STATE_SELECTED)
self.Refresh()
elif state & ULC_STATE_SELECTED:
count = self.GetItemCount()
for i in range(count):
self.SetItemState(i, ULC_STATE_SELECTED, ULC_STATE_SELECTED)
else:
# clear for non virtual (somewhat optimized by using GetNextItem())
i = -1
while 1:
i += 1
if self.GetNextItem(i, ULC_NEXT_ALL, ULC_STATE_SELECTED) == -1:
break
self.SetItemState(i, 0, ULC_STATE_SELECTED)
if self.HasCurrent() and state == 0 and stateMask & ULC_STATE_FOCUSED:
# unfocus all: only one item can be focussed, so clearing focus for
# all items is simply clearing focus of the focussed item.
self.SetItemState(self._current, state, stateMask)
#(setting focus to all items makes no sense, so it is not handled here.)
def SetItemState(self, litem, state, stateMask):
"""
Sets the item state flags for the input item.
:param `litem`: the index of the item; if defaulted to -1, the state flag
will be set for all the items;
:param `state`: the item state flag;
:param `stateMask`: the bitmask for the state flag.
:see: :meth:`~UltimateListMainWindow.SetItemStateAll` for a list of valid state flags.
"""
if litem == -1:
self.SetItemStateAll(state, stateMask)
return
if litem < 0 or litem >= self.GetItemCount():
raise Exception("invalid item index in SetItemState")
oldCurrent = self._current
item = litem # safe because of the check above
# do we need to change the focus?
if stateMask & ULC_STATE_FOCUSED:
if state & ULC_STATE_FOCUSED:
# don't do anything if this item is already focused
if item != self._current:
self.ChangeCurrent(item)
if oldCurrent != - 1:
if self.IsSingleSel():
self.HighlightLine(oldCurrent, False)
self.RefreshLine(oldCurrent)
self.RefreshLine(self._current)
else: # unfocus
# don't do anything if this item is not focused
if item == self._current:
self.ResetCurrent()
if self.IsSingleSel():
# we must unselect the old current item as well or we
# might end up with more than one selected item in a
# single selection control
self.HighlightLine(oldCurrent, False)
self.RefreshLine(oldCurrent)
# do we need to change the selection state?
if stateMask & ULC_STATE_SELECTED:
on = (state & ULC_STATE_SELECTED) != 0
if self.IsSingleSel():
if on:
# selecting the item also makes it the focused one in the
# single sel mode
if self._current != item:
self.ChangeCurrent(item)
if oldCurrent != - 1:
self.HighlightLine(oldCurrent, False)
self.RefreshLine(oldCurrent)
else: # off
# only the current item may be selected anyhow
if item != self._current:
return
if self.HighlightLine(item, on):
self.RefreshLine(item)
def GetItemState(self, item, stateMask):
"""
Returns the item state flags for the input item.
:param `item`: the index of the item;
:param `stateMask`: the bitmask for the state flag.
:see: :meth:`~UltimateListMainWindow.SetItemStateAll` for a list of valid state flags.
"""
if item < 0 or item >= self.GetItemCount():
raise Exception("invalid item index in GetItemState")
ret = ULC_STATE_DONTCARE
if stateMask & ULC_STATE_FOCUSED:
if item == self._current:
ret |= ULC_STATE_FOCUSED
if stateMask & ULC_STATE_SELECTED:
if self.IsHighlighted(item):
ret |= ULC_STATE_SELECTED
return ret
def GetItem(self, item, col=0):
"""
Returns the information about the input item.
:param `item`: an instance of :class:`UltimateListItem`;
:param `col`: the column to which the item belongs to.
"""
if item._itemId < 0 or item._itemId >= self.GetItemCount():
raise Exception("invalid item index in GetItem")
line = self.GetLine(item._itemId)
item = line.GetItem(col, item)
# Get item state if user wants it
if item._mask & ULC_MASK_STATE:
item._state = self.GetItemState(item._itemId, ULC_STATE_SELECTED | ULC_STATE_FOCUSED)
return item
def CheckItem(self, item, checked=True, sendEvent=True):
"""
Actually checks/uncheks an item, sending (eventually) the two
events ``EVT_LIST_ITEM_CHECKING`` / ``EVT_LIST_ITEM_CHECKED``.
:param `item`: an instance of :class:`UltimateListItem`;
:param `checked`: ``True`` to check an item, ``False`` to uncheck it;
:param `sendEvent`: ``True`` to send a {UltimateListEvent}, ``False`` otherwise.
:note: This method is meaningful only for checkbox-like and radiobutton-like items.
"""
# Should we raise an error here?!?
if item.GetKind() == 0 or not item.IsEnabled():
return
if sendEvent:
parent = self.GetParent()
le = UltimateListEvent(wxEVT_COMMAND_LIST_ITEM_CHECKING, parent.GetId())
le.m_itemIndex = item._itemId
le.m_item = item
le.SetEventObject(parent)
if parent.GetEventHandler().ProcessEvent(le):
# Blocked by user
return
item.Check(checked)
self.SetItem(item)
self.RefreshLine(item._itemId)
if not sendEvent:
return
le = UltimateListEvent(wxEVT_COMMAND_LIST_ITEM_CHECKED, parent.GetId())
le.m_itemIndex = item._itemId
le.m_item = item
le.SetEventObject(parent)
parent.GetEventHandler().ProcessEvent(le)
def AutoCheckChild(self, isChecked, column):
"""
Checks/unchecks all the items.
:param `isChecked`: ``True`` to check the items, ``False`` to uncheck them;
:param `column`: the column to which the items belongs to.
:note: This method is meaningful only for checkbox-like and radiobutton-like items.
"""
for indx in range(self.GetItemCount()):
item = CreateListItem(indx, column)
newItem = self.GetItem(item, column)
self.CheckItem(newItem, not isChecked, False)
def AutoToggleChild(self, column):
"""
Toggles all the items.
:param `column`: the column to which the items belongs to.
:note: This method is meaningful only for checkbox-like and radiobutton-like items.
"""
for indx in range(self.GetItemCount()):
item = CreateListItem(indx, column)
newItem = self.GetItem(item, column)
if newItem.GetKind() != 1:
continue
self.CheckItem(newItem, not item.IsChecked(), False)
def IsItemChecked(self, item):
"""
Returns whether an item is checked or not.
:param `item`: an instance of :class:`UltimateListItem`.
"""
item = self.GetItem(item, item._col)
return item.IsChecked()
def IsItemEnabled(self, item):
"""
Returns whether an item is enabled or not.
:param `item`: an instance of :class:`UltimateListItem`.
"""
item = self.GetItem(item, item._col)
return item.IsEnabled()
def EnableItem(self, item, enable=True):
"""
Enables/disables an item.
:param `item`: an instance of :class:`UltimateListItem`;
:param `enable`: ``True`` to enable the item, ``False`` otherwise.
"""
item = self.GetItem(item, 0)
if item.IsEnabled() == enable:
return False
item.Enable(enable)
wnd = item.GetWindow()
# Handles the eventual window associated to the item
if wnd:
wnd.Enable(enable)
self.SetItem(item)
return True
def GetItemKind(self, item):
"""
Returns the item kind.
:param `item`: an instance of :class:`UltimateListItem`.
:see: :meth:`~UltimateListMainWindow.SetItemKind` for a list of valid item kinds.
"""
item = self.GetItem(item, item._col)
return item.GetKind()
def SetItemKind(self, item, kind):
"""
Sets the item kind.
:param `item`: an instance of :class:`UltimateListItem`;
:param `kind`: may be one of the following integers:
=============== ==========================
Item Kind Description
=============== ==========================
0 A normal item
1 A checkbox-like item
2 A radiobutton-type item
=============== ==========================
"""
item = self.GetItem(item, item._col)
item.SetKind(kind)
self.SetItem(item)
return True
def IsItemHyperText(self, item):
"""
Returns whether an item is hypertext or not.
:param `item`: an instance of :class:`UltimateListItem`.
"""
item = self.GetItem(item, item._col)
return item.IsHyperText()
def SetItemHyperText(self, item, hyper=True):
"""
Sets whether the item is hypertext or not.
:param `item`: an instance of :class:`UltimateListItem`;
:param `hyper`: ``True`` to have an item with hypertext behaviour, ``False`` otherwise.
"""
item = self.GetItem(item, item._col)
item.SetHyperText(hyper)
self.SetItem(item)
return True
def GetHyperTextFont(self):
"""Returns the font used to render an hypertext item."""
return self._hypertextfont
def SetHyperTextFont(self, font):
"""
Sets the font used to render hypertext items.
:param `font`: a valid :class:`wx.Font` instance.
"""
self._hypertextfont = font
self._dirty = True
def SetHyperTextNewColour(self, colour):
"""
Sets the colour used to render a non-visited hypertext item.
:param `colour`: a valid :class:`wx.Colour` instance.
"""
self._hypertextnewcolour = colour
self._dirty = True
def GetHyperTextNewColour(self):
""" Returns the colour used to render a non-visited hypertext item. """
return self._hypertextnewcolour
def SetHyperTextVisitedColour(self, colour):
"""
Sets the colour used to render a visited hypertext item.
:param `colour`: a valid :class:`wx.Colour` instance.
"""
self._hypertextvisitedcolour = colour
self._dirty = True
def GetHyperTextVisitedColour(self):
""" Returns the colour used to render a visited hypertext item. """
return self._hypertextvisitedcolour
def SetItemVisited(self, item, visited=True):
"""
Sets whether an hypertext item was visited.
:param `item`: an instance of :class:`UltimateListItem`;
:param `visited`: ``True`` to mark an hypertext item as visited, ``False`` otherwise.
"""
newItem = self.GetItem(item, item._col)
newItem.SetVisited(visited)
self.SetItem(newItem)
return True
def GetItemVisited(self, item):
"""
Returns whether an hypertext item was visited.
:param `item`: an instance of :class:`UltimateListItem`.
"""
item = self.GetItem(item, item._col)
return item.GetVisited()
def GetItemWindow(self, item):
"""
Returns the window associated to the item (if any).
:param `item`: an instance of :class:`UltimateListItem`.
"""
item = self.GetItem(item, item._col)
return item.GetWindow()
def SetItemWindow(self, item, wnd, expand=False):
"""
Sets the window for the given item.
:param `item`: an instance of :class:`UltimateListItem`;
:param `wnd`: if not ``None``, a non-toplevel window to be displayed next to
the item;
:param `expand`: ``True`` to expand the column where the item/subitem lives,
so that the window will be fully visible.
"""
if not self.InReportView() or not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
raise Exception("Widgets are only allowed in report mode and with the ULC_HAS_VARIABLE_ROW_HEIGHT style.")
item = self.GetItem(item, item._col)
if wnd is not None:
self._hasWindows = True
if item not in self._itemWithWindow:
self._itemWithWindow.append(item)
else:
self.DeleteItemWindow(item)
else:
self.DeleteItemWindow(item)
item.SetWindow(wnd, expand)
self.SetItem(item)
self.RecalculatePositions()
self.Refresh()
def DeleteItemWindow(self, item):
"""
Deletes the window associated to an item (if any).
:param `item`: an instance of :class:`UltimateListItem`.
"""
if item.GetWindow() is None:
return
item.DeleteWindow()
if item in self._itemWithWindow:
self._itemWithWindow.remove(item)
self.SetItem(item)
self.RecalculatePositions()
def GetItemWindowEnabled(self, item):
"""
Returns whether the window associated to the item is enabled.
:param `item`: an instance of :class:`UltimateListItem`.
"""
item = self.GetItem(item, item._col)
return item.GetWindowEnabled()
def SetItemWindowEnabled(self, item, enable=True):
"""
Enables/disables the window associated to the item.
:param `item`: an instance of :class:`UltimateListItem`;
:param `enable`: ``True`` to enable the associated window, ``False`` to
disable it.
"""
item = self.GetItem(item, item._col)
item.SetWindowEnabled(enable)
self.SetItem(item)
self.Refresh()
def SetColumnCustomRenderer(self, col=0, renderer=None):
"""
Associate a custom renderer to this column's header
:param `col`: the column index.
:param `renderer`: a class able to correctly render the input item.
:note: the renderer class **must** implement the methods `DrawHeaderButton`
and `GetForegroundColor`.
"""
self._columns[col].SetCustomRenderer(renderer)
def GetColumnCustomRenderer(self, col):
"""
Returns the custom renderer used to draw the column header
:param `col`: the column index.
"""
return self._columns[col].GetCustomRenderer()
def GetItemCustomRenderer(self, item):
"""
Returns the custom renderer used to draw the input item (if any).
:param `item`: an instance of :class:`UltimateListItem`.
"""
item = self.GetItem(item, item._col)
return item.GetCustomRenderer()
def SetItemCustomRenderer(self, item, renderer=None):
"""
Associate a custom renderer to this item.
:param `item`: an instance of :class:`UltimateListItem`;
:param `renderer`: a class able to correctly render the item.
:note: the renderer class **must** implement the methods `DrawSubItem`,
`GetLineHeight` and `GetSubItemWidth`.
"""
item = self.GetItem(item, item._col)
item.SetCustomRenderer(renderer)
self.SetItem(item)
self.ResetLineDimensions()
self.Refresh()
def GetItemOverFlow(self, item):
"""
Returns if the item is in the overflow state.
An item/subitem may overwrite neighboring items/subitems if its text would
not normally fit in the space allotted to it.
:param `item`: an instance of :class:`UltimateListItem`.
"""
item = self.GetItem(item, item._col)
return item.GetOverFlow()
def SetItemOverFlow(self, item, over=True):
"""
Sets the item in the overflow/non overflow state.
An item/subitem may overwrite neighboring items/subitems if its text would
not normally fit in the space allotted to it.
:param `item`: an instance of :class:`UltimateListItem`;
:param `over`: ``True`` to set the item in a overflow state, ``False`` otherwise.
"""
item = self.GetItem(item, item._col)
item.SetOverFlow(over)
self.SetItem(item)
self.Refresh()
# ----------------------------------------------------------------------------
# item count
# ----------------------------------------------------------------------------
def GetItemCount(self):
""" Returns the number of items in the :class:`UltimateListCtrl`. """
return (self.IsVirtual() and [self._countVirt] or [len(self._lines)])[0]
def SetItemCount(self, count):
"""
This method can only be used with virtual :class:`UltimateListCtrl`. It is used to
indicate to the control the number of items it contains. After calling it,
the main program should be ready to handle calls to various item callbacks
(such as :meth:`UltimateListCtrl.OnGetItemText() <UltimateListCtrl.OnGetItemText>`) for all items in the range from 0 to `count`.
:param `count`: the total number of items in :class:`UltimateListCtrl`.
"""
self._selStore.SetItemCount(count)
self._countVirt = count
self.ResetVisibleLinesRange()
# scrollbars must be reset
self._dirty = True
def GetSelectedItemCount(self):
""" Returns the number of selected items in :class:`UltimateListCtrl`. """
# deal with the quick case first
if self.IsSingleSel():
return (self.HasCurrent() and [self.IsHighlighted(self._current)] or [False])[0]
# virtual controls remmebers all its selections itself
if self.IsVirtual():
return self._selStore.GetSelectedCount()
# TODO: we probably should maintain the number of items selected even for
# non virtual controls as enumerating all lines is really slow...
countSel = 0
count = self.GetItemCount()
for line in range(count):
if self.GetLine(line).IsHighlighted():
countSel += 1
return countSel
# ----------------------------------------------------------------------------
# item position/size
# ----------------------------------------------------------------------------
def GetViewRect(self):
"""
Returns the rectangle taken by all items in the control. In other words,
if the controls client size were equal to the size of this rectangle, no
scrollbars would be needed and no free space would be left.
:note: This function only works in the icon and small icon views, not in
list or report views.
"""
if self.HasAGWFlag(ULC_LIST):
raise Exception("UltimateListCtrl.GetViewRect() not implemented for list view")
# we need to find the longest/tallest label
xMax = yMax = 0
count = self.GetItemCount()
if count:
for i in range(count):
# we need logical, not physical, coordinates here, so use
# GetLineRect() instead of GetItemRect()
r = self.GetLineRect(i)
x, y = r.GetRight(), r.GetBottom()
if x > xMax:
xMax = x
if y > yMax:
yMax = y
# some fudge needed to make it look prettier
xMax += 2*EXTRA_BORDER_X
yMax += 2*EXTRA_BORDER_Y
# account for the scrollbars if necessary
sizeAll = self.GetClientSize()
if xMax > sizeAll.x:
yMax += wx.SystemSettings.GetMetric(wx.SYS_HSCROLL_Y)
if yMax > sizeAll.y:
xMax += wx.SystemSettings.GetMetric(wx.SYS_VSCROLL_X)
return wx.Rect(0, 0, xMax, yMax)
def GetSubItemRect(self, item, subItem):
"""
Returns the rectangle representing the size and position, in physical coordinates,
of the given subitem, i.e. the part of the row `item` in the column `subItem`.
:param `item`: the row in which the item lives;
:param `subItem`: the column in which the item lives. If set equal to the special
value ``ULC_GETSUBITEMRECT_WHOLEITEM`` the return value is the same as for
:meth:`~UltimateListMainWindow.GetItemRect`.
:note: This method is only meaningful when the :class:`UltimateListCtrl` is in the
report mode.
"""
if not self.InReportView() and subItem == ULC_GETSUBITEMRECT_WHOLEITEM:
raise Exception("GetSubItemRect only meaningful in report view")
if item < 0 or item >= self.GetItemCount():
raise Exception("invalid item in GetSubItemRect")
# ensure that we're laid out, otherwise we could return nonsense
if self._dirty:
self.RecalculatePositions(True)
rect = self.GetLineRect(item)
# Adjust rect to specified column
if subItem != ULC_GETSUBITEMRECT_WHOLEITEM:
if subItem < 0 or subItem >= self.GetColumnCount():
raise Exception("invalid subItem in GetSubItemRect")
for i in range(subItem):
rect.x += self.GetColumnWidth(i)
rect.width = self.GetColumnWidth(subItem)
rect.x, rect.y = self.CalcScrolledPosition(rect.x, rect.y)
return rect
def GetItemRect(self, item):
"""
Returns the rectangle representing the item's size and position, in physical
coordinates.
:param `item`: the row in which the item lives.
"""
return self.GetSubItemRect(item, ULC_GETSUBITEMRECT_WHOLEITEM)
def GetItemPosition(self, item):
"""
Returns the position of the item, in icon or small icon view.
:param `item`: the row in which the item lives.
"""
rect = self.GetItemRect(item)
return wx.Point(rect.x, rect.y)
# ----------------------------------------------------------------------------
# geometry calculation
# ----------------------------------------------------------------------------
def RecalculatePositions(self, noRefresh=False):
"""
Recalculates all the items positions, and sets the scrollbars positions
too.
:param `noRefresh`: ``True`` to avoid calling `Refresh`, ``False`` otherwise.
"""
count = self.GetItemCount()
if self.HasAGWFlag(ULC_ICON) and self._normal_image_list:
iconSpacing = self._normal_spacing
elif self.HasAGWFlag(ULC_SMALL_ICON) and self._small_image_list:
iconSpacing = self._small_spacing
else:
iconSpacing = 0
# Note that we do not call GetClientSize() here but
# GetSize() and subtract the border size for sunken
# borders manually. This is technically incorrect,
# but we need to know the client area's size WITHOUT
# scrollbars here. Since we don't know if there are
# any scrollbars, we use GetSize() instead. Another
# solution would be to call SetScrollbars() here to
# remove the scrollbars and call GetClientSize() then,
# but this might result in flicker and - worse - will
# reset the scrollbars to 0 which is not good at all
# if you resize a dialog/window, but don't want to
# reset the window scrolling. RR.
# Furthermore, we actually do NOT subtract the border
# width as 2 pixels is just the extra space which we
# need around the actual content in the window. Other-
# wise the text would e.g. touch the upper border. RR.
clientWidth, clientHeight = self.GetSize()
if self.InReportView():
self.ResetVisibleLinesRange()
if not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
# all lines have the same height and we scroll one line per step
lineHeight = self.GetLineHeight()
entireHeight = count*lineHeight + LINE_SPACING
decrement = 0
if entireHeight > self.GetClientSize()[1]:
decrement = SCROLL_UNIT_X
self._linesPerPage = clientHeight//lineHeight
self.SetScrollbars(SCROLL_UNIT_X, lineHeight,
(self.GetHeaderWidth()-decrement)/SCROLL_UNIT_X,
(entireHeight + lineHeight - 1)/lineHeight,
self.GetScrollPos(wx.HORIZONTAL),
self.GetScrollPos(wx.VERTICAL),
True)
else:
if count > 0:
entireHeight = self.GetLineY(count-1) + self.GetLineHeight(count-1) + LINE_SPACING
lineFrom, lineTo = self.GetVisibleLinesRange()
self._linesPerPage = lineTo - lineFrom + 1
else:
lineHeight = self.GetLineHeight()
entireHeight = count*lineHeight + LINE_SPACING
self._linesPerPage = clientHeight/lineHeight
decrement = 0
if entireHeight > self.GetClientSize()[1]:
decrement = SCROLL_UNIT_X
self.SetScrollbars(SCROLL_UNIT_X, SCROLL_UNIT_Y,
(self.GetHeaderWidth()-decrement)/SCROLL_UNIT_X,
(entireHeight + SCROLL_UNIT_Y - 1)/SCROLL_UNIT_Y,
self.GetScrollPos(wx.HORIZONTAL),
self.GetScrollPos(wx.VERTICAL),
True)
else: # !report
dc = wx.ClientDC(self)
dc.SetFont(self.GetFont())
lineHeight = self.GetLineHeight()
# we have 3 different layout strategies: either layout all items
# horizontally/vertically (ULC_ALIGN_XXX styles explicitly given) or
# to arrange them in top to bottom, left to right (don't ask me why
# not the other way round...) order
if self.HasAGWFlag(ULC_ALIGN_LEFT | ULC_ALIGN_TOP):
x = EXTRA_BORDER_X
y = EXTRA_BORDER_Y
widthMax = 0
for i in range(count):
line = self.GetLine(i)
line.CalculateSize(dc, iconSpacing)
line.SetPosition(x, y, iconSpacing)
sizeLine = self.GetLineSize(i)
if self.HasAGWFlag(ULC_ALIGN_TOP):
if sizeLine.x > widthMax:
widthMax = sizeLine.x
y += sizeLine.y
else: # ULC_ALIGN_LEFT
x += sizeLine.x + MARGIN_BETWEEN_ROWS
if self.HasAGWFlag(ULC_ALIGN_TOP):
# traverse the items again and tweak their sizes so that they are
# all the same in a row
for i in range(count):
line = self.GetLine(i)
line._gi.ExtendWidth(widthMax)
self.SetScrollbars(SCROLL_UNIT_X, lineHeight,
(x + SCROLL_UNIT_X)/SCROLL_UNIT_X,
(y + lineHeight)/lineHeight,
self.GetScrollPos(wx.HORIZONTAL),
self.GetScrollPos(wx.VERTICAL),
True)
else: # "flowed" arrangement, the most complicated case
# at first we try without any scrollbars, if the items don't fit into
# the window, we recalculate after subtracting the space taken by the
# scrollbar
entireWidth = 0
for tries in range(2):
entireWidth = 2*EXTRA_BORDER_X
if tries == 1:
# Now we have decided that the items do not fit into the
# client area, so we need a scrollbar
entireWidth += SCROLL_UNIT_X
x = EXTRA_BORDER_X
y = EXTRA_BORDER_Y
maxWidthInThisRow = 0
self._linesPerPage = 0
currentlyVisibleLines = 0
for i in range(count):
currentlyVisibleLines += 1
line = self.GetLine(i)
line.CalculateSize(dc, iconSpacing)
line.SetPosition(x, y, iconSpacing)
sizeLine = self.GetLineSize(i)
if maxWidthInThisRow < sizeLine.x:
maxWidthInThisRow = sizeLine.x
y += sizeLine.y
if currentlyVisibleLines > self._linesPerPage:
self._linesPerPage = currentlyVisibleLines
if y + sizeLine.y >= clientHeight:
currentlyVisibleLines = 0
y = EXTRA_BORDER_Y
maxWidthInThisRow += MARGIN_BETWEEN_ROWS
x += maxWidthInThisRow
entireWidth += maxWidthInThisRow
maxWidthInThisRow = 0
# We have reached the last item.
if i == count - 1:
entireWidth += maxWidthInThisRow
if tries == 0 and entireWidth + SCROLL_UNIT_X > clientWidth:
clientHeight -= wx.SystemSettings.GetMetric(wx.SYS_HSCROLL_Y)
self._linesPerPage = 0
break
if i == count - 1:
break # Everything fits, no second try required.
self.SetScrollbars(SCROLL_UNIT_X, lineHeight,
(entireWidth + SCROLL_UNIT_X)/SCROLL_UNIT_X,
0,
self.GetScrollPos(wx.HORIZONTAL),
0,
True)
self._dirty = False
if not noRefresh:
self.RefreshAll()
def RefreshAll(self):
""" Refreshes the entire :class:`UltimateListCtrl`. """
self._dirty = False
self.Refresh()
headerWin = self.GetListCtrl()._headerWin
if headerWin and headerWin._dirty:
headerWin._dirty = False
headerWin.Refresh()
def UpdateCurrent(self):
""" Updates the current line selection. """
if not self.HasCurrent() and not self.IsEmpty():
self.ChangeCurrent(0)
def GetNextItem(self, item, geometry=ULC_NEXT_ALL, state=ULC_STATE_DONTCARE):
"""
Searches for an item with the given `geometry` or `state`, starting from `item`
but excluding the `item` itself.
:param `item`: the item at which starting the search. If set to -1, the first
item that matches the specified flags will be returned.
:param `geometry`: can be one of:
=================== ========= =================================
Geometry Flag Hex Value Description
=================== ========= =================================
``ULC_NEXT_ABOVE`` 0x0 Searches for an item above the specified item
``ULC_NEXT_ALL`` 0x1 Searches for subsequent item by index
``ULC_NEXT_BELOW`` 0x2 Searches for an item below the specified item
``ULC_NEXT_LEFT`` 0x3 Searches for an item to the left of the specified item
``ULC_NEXT_RIGHT`` 0x4 Searches for an item to the right of the specified item
=================== ========= =================================
:param `state`: any combination of the following bits:
============================ ========= ==============================
State Bits Hex Value Description
============================ ========= ==============================
``ULC_STATE_DONTCARE`` 0x0 Don't care what the state is
``ULC_STATE_DROPHILITED`` 0x1 The item is highlighted to receive a drop event
``ULC_STATE_FOCUSED`` 0x2 The item has the focus
``ULC_STATE_SELECTED`` 0x4 The item is selected
``ULC_STATE_CUT`` 0x8 The item is in the cut state
``ULC_STATE_DISABLED`` 0x10 The item is disabled
``ULC_STATE_FILTERED`` 0x20 The item has been filtered
``ULC_STATE_INUSE`` 0x40 The item is in use
``ULC_STATE_PICKED`` 0x80 The item has been picked
``ULC_STATE_SOURCE`` 0x100 The item is a drag and drop source
============================ ========= ==============================
:return: The first item with given `state` following `item` or -1 if no such item found.
:note: This function may be used to find all selected items in the
control like this::
item = -1
while 1:
item = listctrl.GetNextItem(item, ULC_NEXT_ALL, ULC_STATE_SELECTED)
if item == -1:
break
# This item is selected - do whatever is needed with it
wx.LogMessage("Item %ld is selected."%item)
"""
ret = item
maxI = self.GetItemCount()
# notice that we start with the next item (or the first one if item == -1)
# and this is intentional to allow writing a simple loop to iterate over
# all selected items
ret += 1
if ret == maxI:
# this is not an error because the index was ok initially, just no
# such item
return -1
if not state:
# any will do
return ret
for line in range(ret, maxI):
if state & ULC_STATE_FOCUSED and line == self._current:
return line
if state & ULC_STATE_SELECTED and self.IsHighlighted(line):
return line
return -1
# ----------------------------------------------------------------------------
# deleting stuff
# ----------------------------------------------------------------------------
def DeleteItem(self, lindex):
"""
Deletes the specified item.
:param `lindex`: the index of the item to delete.
:note: This function sends the ``EVT_LIST_DELETE_ITEM`` event for the item
being deleted.
"""
count = self.GetItemCount()
if lindex < 0 or lindex >= self.GetItemCount():
raise Exception("invalid item index in DeleteItem")
# we don't need to adjust the index for the previous items
if self.HasCurrent() and self._current >= lindex:
# if the current item is being deleted, we want the next one to
# become selected - unless there is no next one - so don't adjust
# self._current in this case
if self._current != lindex or self._current == count - 1:
self._current -= 1
if self.InReportView():
# mark the Column Max Width cache as dirty if the items in the line
# we're deleting contain the Max Column Width
line = self.GetLine(lindex)
item = UltimateListItem()
for i in range(len(self._columns)):
itemData = line._items[i]
item = itemData.GetItem(item)
itemWidth = self.GetItemWidthWithImage(item)
if itemWidth >= self._aColWidths[i]._nMaxWidth:
self._aColWidths[i]._bNeedsUpdate = True
if item.GetWindow():
self.DeleteItemWindow(item)
self.ResetVisibleLinesRange(True)
self._current = -1
self.SendNotify(lindex, wxEVT_COMMAND_LIST_DELETE_ITEM)
if self.IsVirtual():
self._countVirt -= 1
self._selStore.OnItemDelete(lindex)
else:
self._lines.pop(lindex)
# we need to refresh the (vert) scrollbar as the number of items changed
self._dirty = True
self._lineHeight = 0
self.ResetLineDimensions(True)
self.RecalculatePositions()
self.RefreshAfter(lindex)
def DeleteColumn(self, col):
"""
Deletes the specified column.
:param `col`: the index of the column to delete.
"""
self._columns.pop(col)
self._dirty = True
if not self.IsVirtual():
# update all the items
for i in range(len(self._lines)):
line = self.GetLine(i)
line._items.pop(col)
if self.InReportView(): # we only cache max widths when in Report View
self._aColWidths.pop(col)
# invalidate it as it has to be recalculated
self._headerWidth = 0
def DoDeleteAllItems(self):
""" Actually performs the deletion of all the items. """
if self.IsEmpty():
# nothing to do - in particular, don't send the event
return
self.ResetCurrent()
# to make the deletion of all items faster, we don't send the
# notifications for each item deletion in this case but only one event
# for all of them: this is compatible with wxMSW and documented in
# DeleteAllItems() description
event = UltimateListEvent(wxEVT_COMMAND_LIST_DELETE_ALL_ITEMS, self.GetParent().GetId())
event.SetEventObject(self.GetParent())
self.GetParent().GetEventHandler().ProcessEvent(event)
if self.IsVirtual():
self._countVirt = 0
self._selStore.Clear()
if self.InReportView():
self.ResetVisibleLinesRange(True)
for i in range(len(self._aColWidths)):
self._aColWidths[i]._bNeedsUpdate = True
for item in self._itemWithWindow[:]:
if item.GetWindow():
self.DeleteItemWindow(item)
self._lines = []
self._itemWithWindow = []
self._hasWindows = False
def DeleteAllItems(self):
"""
Deletes all items in the :class:`UltimateListCtrl`.
:note: This function does not send the ``EVT_LIST_DELETE_ITEM`` event because
deleting many items from the control would be too slow then (unlike :meth:`~UltimateListMainWindow.DeleteItem`).
"""
self.DoDeleteAllItems()
self.RecalculatePositions()
def DeleteEverything(self):
""" Deletes all items in the :class:`UltimateListCtrl`, resetting column widths to zero. """
self.DeleteAllItems()
count = len(self._columns)
for n in range(count):
self.DeleteColumn(0)
self.RecalculatePositions()
self.GetListCtrl().Refresh()
# ----------------------------------------------------------------------------
# scanning for an item
# ----------------------------------------------------------------------------
def EnsureVisible(self, index):
"""
Ensures this item is visible.
:param `index`: the index of the item to scroll into view.
"""
if index < 0 or index >= self.GetItemCount():
raise Exception("invalid item index in EnsureVisible")
# We have to call this here because the label in question might just have
# been added and its position is not known yet
if self._dirty:
self.RecalculatePositions(True)
self.MoveToItem(index)
def FindItem(self, start, string, partial=False):
"""
Find an item whose label matches this string.
:param `start`: the starting point of the input `string` or the beginning
if `start` is -1;
:param `string`: the string to look for matches;
:param `partial`: if ``True`` then this method will look for items which
begin with `string`.
:note: The string comparison is case insensitive.
"""
if start < 0:
start = 0
str_upper = string.upper()
count = self.GetItemCount()
for i in range(start, count):
line = self.GetLine(i)
text = line.GetText(0)
line_upper = text.upper()
if not partial:
if line_upper == str_upper:
return i
else:
if line_upper.find(str_upper) == 0:
return i
return wx.NOT_FOUND
def FindItemData(self, start, data):
"""
Find an item whose data matches this data.
:param `start`: the starting point of the input `data` or the beginning
if `start` is -1;
:param `data`: the data to look for matches.
"""
if start < 0:
start = 0
count = self.GetItemCount()
for i in range(start, count):
line = self.GetLine(i)
item = UltimateListItem()
item = line.GetItem(0, item)
if item._data == data:
return i
return wx.NOT_FOUND
def FindItemAtPos(self, pt):
"""
Find an item nearest this position.
:param `pt`: an instance of :class:`wx.Point`.
"""
topItem, dummy = self.GetVisibleLinesRange()
p = self.GetItemPosition(self.GetItemCount()-1)
if p.y == 0:
return topItem
id = int(math.floor(pt.y*float(self.GetItemCount()-topItem-1)/p.y+topItem))
if id >= 0 and id < self.GetItemCount():
return id
return wx.NOT_FOUND
def HitTest(self, x, y):
"""
HitTest method for a :class:`UltimateListCtrl`.
:param `x`: the mouse `x` position;
:param `y`: the mouse `y` position.
:see: :meth:`~UltimateListMainWindow.HitTestLine` for a list of return flags.
"""
x, y = self.CalcUnscrolledPosition(x, y)
count = self.GetItemCount()
if self.InReportView():
if not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
current = y // self.GetLineHeight()
if current < count:
newItem, flags = self.HitTestLine(current, x, y)
if flags:
return current, flags
else:
for current in range(self._lineFrom, count):
newItem, flags = self.HitTestLine(current, x, y)
if flags:
return current, flags
else:
# TODO: optimize it too! this is less simple than for report view but
# enumerating all items is still not a way to do it!!
for current in range(count):
newItem, flags = self.HitTestLine(current, x, y)
if flags:
return current, flags
return wx.NOT_FOUND, None
# ----------------------------------------------------------------------------
# adding stuff
# ----------------------------------------------------------------------------
def InsertItem(self, item):
"""
Inserts an item into :class:`UltimateListCtrl`.
:param `item`: an instance of :class:`UltimateListItem`.
"""
if self.IsVirtual():
raise Exception("can't be used with virtual control")
count = self.GetItemCount()
if item._itemId < 0:
raise Exception("invalid item index")
CheckVariableRowHeight(self, item._text)
if item._itemId > count:
item._itemId = count
id = item._itemId
self._dirty = True
if self.InReportView():
self.ResetVisibleLinesRange(True)
# calculate the width of the item and adjust the max column width
pWidthInfo = self._aColWidths[item.GetColumn()]
width = self.GetItemWidthWithImage(item)
item.SetWidth(width)
if width > pWidthInfo._nMaxWidth:
pWidthInfo._nMaxWidth = width
line = UltimateListLineData(self)
line.SetItem(item._col, item)
self._lines.insert(id, line)
self._dirty = True
# If an item is selected at or below the point of insertion, we need to
# increment the member variables because the current row's index has gone
# up by one
if self.HasCurrent() and self._current >= id:
self._current += 1
self.SendNotify(id, wxEVT_COMMAND_LIST_INSERT_ITEM)
self.RefreshLines(id, self.GetItemCount() - 1)
def InsertColumn(self, col, item):
"""
Inserts a column into :class:`UltimateListCtrl`.
:param `col`: the column index at which we wish to insert a new column;
:param `item`: an instance of :class:`UltimateListItem`.
:return: the index at which the column has been inserted.
:note: This method is meaningful only if :class:`UltimateListCtrl` has the ``ULC_REPORT``
or the ``ULC_TILE`` styles set.
"""
self._dirty = True
if self.InReportView() or self.InTileView() or self.HasAGWFlag(ULC_HEADER_IN_ALL_VIEWS):
if item._width == ULC_AUTOSIZE_USEHEADER:
item._width = self.GetTextLength(item._text)
column = UltimateListHeaderData(item)
colWidthInfo = ColWidthInfo()
insert = (col >= 0) and (col < len(self._columns))
if insert:
self._columns.insert(col, column)
self._aColWidths.insert(col, colWidthInfo)
idx = col
else:
self._columns.append(column)
self._aColWidths.append(colWidthInfo)
idx = len(self._columns)-1
if not self.IsVirtual():
# update all the items
for i in range(len(self._lines)):
line = self.GetLine(i)
data = UltimateListItemData(self)
if insert:
line._items.insert(col, data)
else:
line._items.append(data)
# invalidate it as it has to be recalculated
self._headerWidth = 0
return idx
def GetItemWidthWithImage(self, item):
"""
Returns the item width, in pixels, considering the item text and its images.
:param `item`: an instance of :class:`UltimateListItem`.
"""
if item.GetCustomRenderer():
return item.GetCustomRenderer().GetSubItemWidth()
width = 0
dc = wx.ClientDC(self)
if item.GetFont().IsOk():
font = item.GetFont()
else:
font = self.GetFont()
dc.SetFont(font)
if item.GetKind() in [1, 2]:
ix, iy = self.GetCheckboxImageSize()
width += ix
if item.GetImage():
ix, iy = self.GetImageSize(item.GetImage())
width += ix + IMAGE_MARGIN_IN_REPORT_MODE
if item.GetText():
w, h, dummy = dc.GetFullMultiLineTextExtent(item.GetText())
width += w
if item.GetWindow():
width += item._windowsize.x + 5
return width
def GetItemTextSize(self, item):
"""
Returns the item width, in pixels, considering only the item text.
:param `item`: an instance of :class:`UltimateListItem`.
"""
width = ix = iy = start = end = 0
dc = wx.ClientDC(self)
if item.HasFont():
font = item.GetFont()
else:
font = self.GetFont()
dc.SetFont(font)
if item.GetKind() in [1, 2]:
ix, iy = self.GetCheckboxImageSize()
start += ix
if item.GetImage():
ix, iy = self.GetImageSize(item.GetImage())
start += ix + IMAGE_MARGIN_IN_REPORT_MODE
if item.GetText():
w, h, dummy = dc.GetFullMultiLineTextExtent(item.GetText())
end = w
return start, end
# ----------------------------------------------------------------------------
# sorting
# ----------------------------------------------------------------------------
def OnCompareItems(self, line1, line2):
"""
Returns whether 2 lines have the same index.
Override this function in the derived class to change the sort order of the items
in the :class:`UltimateListCtrl`. The function should return a negative, zero or positive
value if the first line is less than, equal to or greater than the second one.
:param `line1`: an instance of :class:`UltimateListLineData`;
:param `line2`: another instance of :class:`UltimateListLineData`.
:note: The base class version compares lines by their index.
"""
item = UltimateListItem()
item1 = line1.GetItem(0, item)
item = UltimateListItem()
item2 = line2.GetItem(0, item)
data1 = item1._data
data2 = item2._data
if self.__func:
return self.__func(item1, item2)
else:
return (data1 > data2) - (data1 < data2)
def SortItems(self, func):
"""
Call this function to sort the items in the :class:`UltimateListCtrl`. Sorting is done
using the specified function `func`. This function must have the
following prototype::
def OnCompareItems(self, line1, line2):
DoSomething(line1, line2)
# function code
It is called each time when the two items must be compared and should return 0
if the items are equal, negative value if the first item is less than the second
one and positive value if the first one is greater than the second one.
:param `func`: the method to use to sort the items. The default is to use the
:meth:`~UltimateListMainWindow.OnCompareItems` method.
"""
self.HighlightAll(False)
self.ResetCurrent()
if self._hasWindows:
self.HideWindows()
if not func:
self.__func = None
else:
self.__func = func
self._lines.sort(key=cmp_to_key(self.OnCompareItems))
if self.IsShownOnScreen():
self._dirty = True
self._lineHeight = 0
self.ResetLineDimensions(True)
self.RecalculatePositions(True)
# ----------------------------------------------------------------------------
# scrolling
# ----------------------------------------------------------------------------
def OnScroll(self, event):
"""
Handles the ``wx.EVT_SCROLLWIN`` event for :class:`UltimateListMainWindow`.
:param `event`: a :class:`ScrollEvent` event to be processed.
"""
event.Skip()
# update our idea of which lines are shown when we redraw the window the
# next time
self.ResetVisibleLinesRange()
if self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
wx.CallAfter(self.RecalculatePositions, True)
if event.GetOrientation() == wx.HORIZONTAL:
lc = self.GetListCtrl()
if self.HasHeader():
lc._headerWin.Refresh()
lc._headerWin.Update()
if self.HasFooter():
lc._footerWin.Refresh()
lc._footerWin.Update()
def GetCountPerPage(self):
"""
Returns the number of items that can fit vertically in the visible area
of the :class:`UltimateListCtrl` (list or report view) or the total number of
items in the list control (icon or small icon view).
"""
if not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
if not self._linesPerPage:
self._linesPerPage = self.GetClientSize().y/self.GetLineHeight()
return self._linesPerPage
visibleFrom, visibleTo = self.GetVisibleLinesRange()
self._linesPerPage = visibleTo - visibleFrom + 1
return self._linesPerPage
def GetVisibleLinesRange(self):
"""
Returns the range of visible items on screen.
:note: This method can be used only if :class:`UltimateListCtrl` has the ``ULC_REPORT``
style set.
"""
if not self.InReportView():
raise Exception("this is for report mode only")
if self._lineFrom == -1:
count = self.GetItemCount()
if count:
if self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
view_x, view_y = self.GetViewStart()
view_y *= SCROLL_UNIT_Y
for i in range(0, count):
rc = self.GetLineY(i)
if rc > view_y:
self._lineFrom = i - 1
break
if self._lineFrom < 0:
self._lineFrom = 0
self._lineTo = self._lineFrom
clientWidth, clientHeight = self.GetClientSize()
for i in range(self._lineFrom, count):
rc = self.GetLineY(i) + self.GetLineHeight(i)
if rc > view_y + clientHeight - 5:
break
self._lineTo += 1
else:
# No variable row height
self._lineFrom = self.GetScrollPos(wx.VERTICAL)
# this may happen if SetScrollbars() hadn't been called yet
if self._lineFrom >= count:
self._lineFrom = count - 1
self._lineTo = self._lineFrom + self._linesPerPage
# we redraw one extra line but this is needed to make the redrawing
# logic work when there is a fractional number of lines on screen
if self._lineTo >= count:
self._lineTo = count - 1
else: # empty control
self._lineFrom = -1
self._lineTo = -1
return self._lineFrom, self._lineTo
def ResetTextControl(self):
""" Called by :class:`UltimateListTextCtrl` when it marks itself for deletion."""
self._textctrl.Destroy()
self._textctrl = None
self.RecalculatePositions()
self.Refresh()
def SetFirstGradientColour(self, colour=None):
"""
Sets the first gradient colour for gradient-style selections.
:param `colour`: if not ``None``, a valid :class:`wx.Colour` instance. Otherwise,
the colour is taken from the system value ``wx.SYS_COLOUR_HIGHLIGHT``.
"""
if colour is None:
colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT)
self._firstcolour = colour
if self._usegradients:
self.RefreshSelected()
def SetSecondGradientColour(self, colour=None):
"""
Sets the second gradient colour for gradient-style selections.
:param `colour`: if not ``None``, a valid :class:`wx.Colour` instance. Otherwise,
the colour generated is a slightly darker version of the :class:`UltimateListCtrl`
background colour.
"""
if colour is None:
# No colour given, generate a slightly darker from the
# UltimateListCtrl background colour
colour = self.GetBackgroundColour()
r, g, b = int(colour.Red()), int(colour.Green()), int(colour.Blue())
colour = ((r >> 1) + 20, (g >> 1) + 20, (b >> 1) + 20)
colour = wx.Colour(colour[0], colour[1], colour[2])
self._secondcolour = colour
if self._usegradients:
self.RefreshSelected()
def GetFirstGradientColour(self):
""" Returns the first gradient colour for gradient-style selections. """
return self._firstcolour
def GetSecondGradientColour(self):
""" Returns the second gradient colour for gradient-style selections. """
return self._secondcolour
def EnableSelectionGradient(self, enable=True):
"""
Globally enables/disables drawing of gradient selections.
:param `enable`: ``True`` to enable gradient-style selections, ``False``
to disable it.
:note: Calling this method disables any Vista-style selection previously
enabled.
"""
self._usegradients = enable
self._vistaselection = False
self.RefreshSelected()
def SetGradientStyle(self, vertical=0):
"""
Sets the gradient style for gradient-style selections.
:param `vertical`: 0 for horizontal gradient-style selections, 1 for vertical
gradient-style selections.
"""
# 0 = Horizontal, 1 = Vertical
self._gradientstyle = vertical
if self._usegradients:
self.RefreshSelected()
def GetGradientStyle(self):
"""
Returns the gradient style for gradient-style selections.
:return: 0 for horizontal gradient-style selections, 1 for vertical
gradient-style selections.
"""
return self._gradientstyle
def EnableSelectionVista(self, enable=True):
"""
Globally enables/disables drawing of Windows Vista selections.
:param `enable`: ``True`` to enable Vista-style selections, ``False`` to
disable it.
:note: Calling this method disables any gradient-style selection previously
enabled.
"""
self._usegradients = False
self._vistaselection = enable
self.RefreshSelected()
def SetBackgroundImage(self, image):
"""
Sets the :class:`UltimateListCtrl` background image.
:param `image`: if not ``None``, an instance of :class:`wx.Bitmap`.
:note: At present, the background image can only be used in "tile" mode.
.. todo:: Support background images also in stretch and centered modes.
"""
self._backgroundImage = image
self.Refresh()
def GetBackgroundImage(self):
"""
Returns the :class:`UltimateListCtrl` background image (if any).
:note: At present, the background image can only be used in "tile" mode.
.. todo:: Support background images also in stretch and centered modes.
"""
return self._backgroundImage
def SetWaterMark(self, watermark):
"""
Sets the :class:`UltimateListCtrl` watermark image to be displayed in the bottom
right part of the window.
:param `watermark`: if not ``None``, an instance of :class:`wx.Bitmap`.
.. todo:: Better support for this is needed.
"""
self._waterMark = watermark
self.Refresh()
def GetWaterMark(self):
"""
Returns the :class:`UltimateListCtrl` watermark image (if any), displayed in the
bottom right part of the window.
.. todo:: Better support for this is needed.
"""
return self._waterMark
def SetDisabledTextColour(self, colour):
"""
Sets the items disabled colour.
:param `colour`: an instance of :class:`wx.Colour`.
"""
# Disabled items colour
self._disabledColour = colour
self.Refresh()
def GetDisabledTextColour(self):
""" Returns the items disabled colour. """
return self._disabledColour
def ScrollList(self, dx, dy):
"""
Scrolls the :class:`UltimateListCtrl`.
:param `dx`: if in icon, small icon or report view mode, specifies the number
of pixels to scroll. If in list view mode, `dx` specifies the number of
columns to scroll.
:param `dy`: always specifies the number of pixels to scroll vertically.
"""
if not self.InReportView():
# TODO: this should work in all views but is not implemented now
return False
top, bottom = self.GetVisibleLinesRange()
if bottom == -1:
return 0
self.ResetVisibleLinesRange()
if not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
hLine = self.GetLineHeight()
self.Scroll(-1, top + dy/hLine)
else:
self.Scroll(-1, top + dy/SCROLL_UNIT_Y)
if wx.Platform == "__WXMAC__":
# see comment in MoveToItem() for why we do this
self.ResetVisibleLinesRange()
return True
# -------------------------------------------------------------------------------------
# UltimateListCtrl
# -------------------------------------------------------------------------------------
class UltimateListCtrl(wx.Control):
"""
UltimateListCtrl is a class that mimics the behaviour of :class:`ListCtrl`, with almost
the same base functionalities plus some more enhancements. This class does
not rely on the native control, as it is a full owner-drawn list control.
"""
def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
style=0, agwStyle=0, validator=wx.DefaultValidator, name="UltimateListCtrl"):
"""
Default class constructor.
:param `parent`: parent window. Must not be ``None``;
:param `id`: window identifier. A value of -1 indicates a default value;
:param `pos`: the control position. A value of (-1, -1) indicates a default position,
chosen by either the windowing system or wxPython, depending on platform;
:param `size`: the control size. A value of (-1, -1) indicates a default size,
chosen by either the windowing system or wxPython, depending on platform;
:param `style`: the underlying :class:`wx.Control` window style;
:param `agwStyle`: the AGW-specific window style; can be almost any combination of the following
bits:
=============================== =========== ====================================================================================================
Window Styles Hex Value Description
=============================== =========== ====================================================================================================
``ULC_VRULES`` 0x1 Draws light vertical rules between rows in report mode.
``ULC_HRULES`` 0x2 Draws light horizontal rules between rows in report mode.
``ULC_ICON`` 0x4 Large icon view, with optional labels.
``ULC_SMALL_ICON`` 0x8 Small icon view, with optional labels.
``ULC_LIST`` 0x10 Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don't set columns as in ``ULC_REPORT``. In other words, the list wraps, unlike a :class:`ListBox`.
``ULC_REPORT`` 0x20 Single or multicolumn report view, with optional header.
``ULC_ALIGN_TOP`` 0x40 Icons align to the top. Win32 default, Win32 only.
``ULC_ALIGN_LEFT`` 0x80 Icons align to the left.
``ULC_AUTOARRANGE`` 0x100 Icons arrange themselves. Win32 only.
``ULC_VIRTUAL`` 0x200 The application provides items text on demand. May only be used with ``ULC_REPORT``.
``ULC_EDIT_LABELS`` 0x400 Labels are editable: the application will be notified when editing starts.
``ULC_NO_HEADER`` 0x800 No header in report mode.
``ULC_NO_SORT_HEADER`` 0x1000 No Docs.
``ULC_SINGLE_SEL`` 0x2000 Single selection (default is multiple).
``ULC_SORT_ASCENDING`` 0x4000 Sort in ascending order. (You must still supply a comparison callback in :meth:`ListCtrl.SortItems`.)
``ULC_SORT_DESCENDING`` 0x8000 Sort in descending order. (You must still supply a comparison callback in :meth:`ListCtrl.SortItems`.)
``ULC_TILE`` 0x10000 Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented).
``ULC_NO_HIGHLIGHT`` 0x20000 No highlight when an item is selected.
``ULC_STICKY_HIGHLIGHT`` 0x40000 Items are selected by simply hovering on them, with no need to click on them.
``ULC_STICKY_NOSELEVENT`` 0x80000 Don't send a selection event when using ``ULC_STICKY_HIGHLIGHT`` style.
``ULC_SEND_LEFTCLICK`` 0x100000 Send a left click event when an item is selected.
``ULC_HAS_VARIABLE_ROW_HEIGHT`` 0x200000 The list has variable row heights.
``ULC_AUTO_CHECK_CHILD`` 0x400000 When a column header has a checkbox associated, auto-check all the subitems in that column.
``ULC_AUTO_TOGGLE_CHILD`` 0x800000 When a column header has a checkbox associated, toggle all the subitems in that column.
``ULC_AUTO_CHECK_PARENT`` 0x1000000 Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well.
``ULC_SHOW_TOOLTIPS`` 0x2000000 Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text.
``ULC_HOT_TRACKING`` 0x4000000 Enable hot tracking of items on mouse motion.
``ULC_BORDER_SELECT`` 0x8000000 Changes border colour whan an item is selected, instead of highlighting the item.
``ULC_TRACK_SELECT`` 0x10000000 Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the `win32api` call `win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)`, and is defaulted to 400ms on other platforms. This style applies to all views of `UltimateListCtrl`.
``ULC_HEADER_IN_ALL_VIEWS`` 0x20000000 Show column headers in all view modes.
``ULC_NO_FULL_ROW_SELECT`` 0x40000000 When an item is selected, the only the item in the first column is highlighted.
``ULC_FOOTER`` 0x80000000 Show a footer too (only when header is present).
``ULC_USER_ROW_HEIGHT`` 0x100000000 Allows to set a custom row height (one value for all the items, only in report mode).
=============================== =========== ====================================================================================================
:param `validator`: the window validator;
:param `name`: the window name.
"""
self._imageListNormal = None
self._imageListSmall = None
self._imageListState = None
if not agwStyle & ULC_MASK_TYPE:
raise Exception("UltimateListCtrl style should have exactly one mode bit set")
if not (agwStyle & ULC_REPORT) and agwStyle & ULC_HAS_VARIABLE_ROW_HEIGHT:
raise Exception("Style ULC_HAS_VARIABLE_ROW_HEIGHT can only be used in report, non-virtual mode")
if agwStyle & ULC_STICKY_HIGHLIGHT and agwStyle & ULC_TRACK_SELECT:
raise Exception("Styles ULC_STICKY_HIGHLIGHT and ULC_TRACK_SELECT can not be combined")
if agwStyle & ULC_NO_HEADER and agwStyle & ULC_HEADER_IN_ALL_VIEWS:
raise Exception("Styles ULC_NO_HEADER and ULC_HEADER_IN_ALL_VIEWS can not be combined")
if agwStyle & ULC_USER_ROW_HEIGHT and (agwStyle & ULC_REPORT) == 0:
raise Exception("Style ULC_USER_ROW_HEIGHT can be used only with ULC_REPORT")
wx.Control.__init__(self, parent, id, pos, size, style|wx.CLIP_CHILDREN, validator, name)
self._mainWin = None
self._headerWin = None
self._footerWin = None
self._headerHeight = wx.RendererNative.Get().GetHeaderButtonHeight(self)
self._footerHeight = self._headerHeight
if wx.Platform == "__WXGTK__":
style &= ~wx.BORDER_MASK
style |= wx.BORDER_THEME
else:
if style & wx.BORDER_THEME:
style -= wx.BORDER_THEME
self._agwStyle = agwStyle
if style & wx.SUNKEN_BORDER:
style -= wx.SUNKEN_BORDER
self._mainWin = UltimateListMainWindow(self, wx.ID_ANY, wx.Point(0, 0), wx.DefaultSize, style, agwStyle)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self._mainWin, 1, wx.GROW)
self.SetSizer(sizer)
self.Bind(wx.EVT_SIZE, self.OnSize)
self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
self.CreateOrDestroyHeaderWindowAsNeeded()
self.CreateOrDestroyFooterWindowAsNeeded()
self.SetInitialSize(size)
wx.CallAfter(self.Layout)
def CreateOrDestroyHeaderWindowAsNeeded(self):
""" Creates or destroys the header window depending on the window style flags. """
needs_header = self.HasHeader()
has_header = self._headerWin is not None
if needs_header == has_header:
return
if needs_header:
self._headerWin = UltimateListHeaderWindow(self, wx.ID_ANY, self._mainWin,
wx.Point(0, 0),
wx.DefaultSize,
wx.TAB_TRAVERSAL, isFooter=False)
# ----------------------------------------------------
# How do you translate all this blah-blah to wxPython?
# ----------------------------------------------------
#if defined( __WXMAC__ ) && wxOSX_USE_COCOA_OR_CARBON
# wxFont font
#if wxOSX_USE_ATSU_TEXT
# font.MacCreateFromThemeFont( kThemeSmallSystemFont )
#else
# font.MacCreateFromUIFont( kCTFontSystemFontType )
#endif
# m_headerWin->SetFont( font )
#endif
self.GetSizer().Prepend(self._headerWin, 0, wx.GROW)
else:
self.GetSizer().Detach(self._headerWin)
self._headerWin.Destroy()
self._headerWin = None
def CreateOrDestroyFooterWindowAsNeeded(self):
""" Creates or destroys the footer window depending on the window style flags. """
needs_footer = self.HasFooter()
has_footer = self._footerWin is not None
if needs_footer == has_footer:
return
if needs_footer:
self._footerWin = UltimateListHeaderWindow(self, wx.ID_ANY, self._mainWin,
wx.Point(0, 0),
wx.DefaultSize,
wx.TAB_TRAVERSAL, isFooter=True)
# ----------------------------------------------------
# How do you translate all this blah-blah to wxPython?
# ----------------------------------------------------
#if defined( __WXMAC__ ) && wxOSX_USE_COCOA_OR_CARBON
# wxFont font
#if wxOSX_USE_ATSU_TEXT
# font.MacCreateFromThemeFont( kThemeSmallSystemFont )
#else
# font.MacCreateFromUIFont( kCTFontSystemFontType )
#endif
# m_headerWin->SetFont( font )
#endif
self.GetSizer().Add(self._footerWin, 0, wx.GROW)
else:
self.GetSizer().Detach(self._footerWin)
self._footerWin.Destroy()
self._footerWin = None
def HasHeader(self):
""" Returns ``True`` if :class:`UltimateListCtrl` has a header window. """
return self._mainWin.HasHeader()
def HasFooter(self):
""" Returns ``True`` if :class:`UltimateListCtrl` has a footer window. """
return self._mainWin.HasFooter()
def GetDefaultBorder(self):
""" Returns the default window border. """
return wx.BORDER_THEME
def SetSingleStyle(self, style, add=True):
"""
Adds or removes a single window style.
:param `style`: can be one of the following bits:
=============================== =========== ====================================================================================================
Window Styles Hex Value Description
=============================== =========== ====================================================================================================
``ULC_VRULES`` 0x1 Draws light vertical rules between rows in report mode.
``ULC_HRULES`` 0x2 Draws light horizontal rules between rows in report mode.
``ULC_ICON`` 0x4 Large icon view, with optional labels.
``ULC_SMALL_ICON`` 0x8 Small icon view, with optional labels.
``ULC_LIST`` 0x10 Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don't set columns as in ``ULC_REPORT``. In other words, the list wraps, unlike a :class:`ListBox`.
``ULC_REPORT`` 0x20 Single or multicolumn report view, with optional header.
``ULC_ALIGN_TOP`` 0x40 Icons align to the top. Win32 default, Win32 only.
``ULC_ALIGN_LEFT`` 0x80 Icons align to the left.
``ULC_AUTOARRANGE`` 0x100 Icons arrange themselves. Win32 only.
``ULC_VIRTUAL`` 0x200 The application provides items text on demand. May only be used with ``ULC_REPORT``.
``ULC_EDIT_LABELS`` 0x400 Labels are editable: the application will be notified when editing starts.
``ULC_NO_HEADER`` 0x800 No header in report mode.
``ULC_NO_SORT_HEADER`` 0x1000 No Docs.
``ULC_SINGLE_SEL`` 0x2000 Single selection (default is multiple).
``ULC_SORT_ASCENDING`` 0x4000 Sort in ascending order. (You must still supply a comparison callback in :meth:`ListCtrl.SortItems`.)
``ULC_SORT_DESCENDING`` 0x8000 Sort in descending order. (You must still supply a comparison callback in :meth:`ListCtrl.SortItems`.)
``ULC_TILE`` 0x10000 Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented).
``ULC_NO_HIGHLIGHT`` 0x20000 No highlight when an item is selected.
``ULC_STICKY_HIGHLIGHT`` 0x40000 Items are selected by simply hovering on them, with no need to click on them.
``ULC_STICKY_NOSELEVENT`` 0x80000 Don't send a selection event when using ``ULC_STICKY_HIGHLIGHT`` style.
``ULC_SEND_LEFTCLICK`` 0x100000 Send a left click event when an item is selected.
``ULC_HAS_VARIABLE_ROW_HEIGHT`` 0x200000 The list has variable row heights.
``ULC_AUTO_CHECK_CHILD`` 0x400000 When a column header has a checkbox associated, auto-check all the subitems in that column.
``ULC_AUTO_TOGGLE_CHILD`` 0x800000 When a column header has a checkbox associated, toggle all the subitems in that column.
``ULC_AUTO_CHECK_PARENT`` 0x1000000 Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well.
``ULC_SHOW_TOOLTIPS`` 0x2000000 Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text.
``ULC_HOT_TRACKING`` 0x4000000 Enable hot tracking of items on mouse motion.
``ULC_BORDER_SELECT`` 0x8000000 Changes border colour whan an item is selected, instead of highlighting the item.
``ULC_TRACK_SELECT`` 0x10000000 Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the `win32api` call `win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)`, and is defaulted to 400ms on other platforms. This style applies to all views of `UltimateListCtrl`.
``ULC_HEADER_IN_ALL_VIEWS`` 0x20000000 Show column headers in all view modes.
``ULC_NO_FULL_ROW_SELECT`` 0x40000000 When an item is selected, the only the item in the first column is highlighted.
``ULC_FOOTER`` 0x80000000 Show a footer too (only when header is present).
=============================== =========== ====================================================================================================
:param `add`: ``True`` to add the window style, ``False`` to remove it.
:note: The style ``ULC_VIRTUAL`` can not be set/unset after construction.
"""
if style & ULC_VIRTUAL:
raise Exception("ULC_VIRTUAL can't be [un]set")
flag = self.GetAGWWindowStyleFlag()
if add:
if style & ULC_MASK_TYPE:
flag &= ~(ULC_MASK_TYPE | ULC_VIRTUAL)
if style & ULC_MASK_ALIGN:
flag &= ~ULC_MASK_ALIGN
if style & ULC_MASK_SORT:
flag &= ~ULC_MASK_SORT
if add:
flag |= style
else:
flag &= ~style
# some styles can be set without recreating everything (as happens in
# SetAGWWindowStyleFlag() which calls ListMainWindow.DeleteEverything())
if not style & ~(ULC_HRULES | ULC_VRULES):
self.Refresh()
self.SetAGWWindowStyleFlag(self, flag)
else:
self.SetAGWWindowStyleFlag(flag)
def GetAGWWindowStyleFlag(self):
"""
Returns the :class:`UltimateListCtrl` AGW-specific style flag.
:see: :meth:`~UltimateListCtrl.SetAGWWindowStyleFlag` for a list of possible style flags.
"""
return self._agwStyle
def SetAGWWindowStyleFlag(self, style):
"""
Sets the :class:`UltimateListCtrl` AGW-specific style flag.
:param `style`: the AGW-specific window style; can be almost any combination of the following
bits:
=============================== =========== ====================================================================================================
Window Styles Hex Value Description
=============================== =========== ====================================================================================================
``ULC_VRULES`` 0x1 Draws light vertical rules between rows in report mode.
``ULC_HRULES`` 0x2 Draws light horizontal rules between rows in report mode.
``ULC_ICON`` 0x4 Large icon view, with optional labels.
``ULC_SMALL_ICON`` 0x8 Small icon view, with optional labels.
``ULC_LIST`` 0x10 Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don't set columns as in ``ULC_REPORT``. In other words, the list wraps, unlike a :class:`ListBox`.
``ULC_REPORT`` 0x20 Single or multicolumn report view, with optional header.
``ULC_ALIGN_TOP`` 0x40 Icons align to the top. Win32 default, Win32 only.
``ULC_ALIGN_LEFT`` 0x80 Icons align to the left.
``ULC_AUTOARRANGE`` 0x100 Icons arrange themselves. Win32 only.
``ULC_VIRTUAL`` 0x200 The application provides items text on demand. May only be used with ``ULC_REPORT``.
``ULC_EDIT_LABELS`` 0x400 Labels are editable: the application will be notified when editing starts.
``ULC_NO_HEADER`` 0x800 No header in report mode.
``ULC_NO_SORT_HEADER`` 0x1000 No Docs.
``ULC_SINGLE_SEL`` 0x2000 Single selection (default is multiple).
``ULC_SORT_ASCENDING`` 0x4000 Sort in ascending order. (You must still supply a comparison callback in :meth:`ListCtrl.SortItems`.)
``ULC_SORT_DESCENDING`` 0x8000 Sort in descending order. (You must still supply a comparison callback in :meth:`ListCtrl.SortItems`.)
``ULC_TILE`` 0x10000 Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented).
``ULC_NO_HIGHLIGHT`` 0x20000 No highlight when an item is selected.
``ULC_STICKY_HIGHLIGHT`` 0x40000 Items are selected by simply hovering on them, with no need to click on them.
``ULC_STICKY_NOSELEVENT`` 0x80000 Don't send a selection event when using ``ULC_STICKY_HIGHLIGHT`` style.
``ULC_SEND_LEFTCLICK`` 0x100000 Send a left click event when an item is selected.
``ULC_HAS_VARIABLE_ROW_HEIGHT`` 0x200000 The list has variable row heights.
``ULC_AUTO_CHECK_CHILD`` 0x400000 When a column header has a checkbox associated, auto-check all the subitems in that column.
``ULC_AUTO_TOGGLE_CHILD`` 0x800000 When a column header has a checkbox associated, toggle all the subitems in that column.
``ULC_AUTO_CHECK_PARENT`` 0x1000000 Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well.
``ULC_SHOW_TOOLTIPS`` 0x2000000 Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text.
``ULC_HOT_TRACKING`` 0x4000000 Enable hot tracking of items on mouse motion.
``ULC_BORDER_SELECT`` 0x8000000 Changes border colour whan an item is selected, instead of highlighting the item.
``ULC_TRACK_SELECT`` 0x10000000 Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the `win32api` call `win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)`, and is defaulted to 400ms on other platforms. This style applies to all views of `UltimateListCtrl`.
``ULC_HEADER_IN_ALL_VIEWS`` 0x20000000 Show column headers in all view modes.
``ULC_NO_FULL_ROW_SELECT`` 0x40000000 When an item is selected, the only the item in the first column is highlighted.
``ULC_FOOTER`` 0x80000000 Show a footer too (only when header is present).
``ULC_USER_ROW_HEIGHT`` 0x100000000 Allows to set a custom row height (one value for all the items, only in report mode).
=============================== =========== ====================================================================================================
"""
if style & ULC_HAS_VARIABLE_ROW_HEIGHT and not self.HasAGWFlag(ULC_REPORT):
raise Exception("ULC_HAS_VARIABLE_ROW_HEIGHT style can be used only in report mode")
wasInReportView = self.HasAGWFlag(ULC_REPORT)
self._agwStyle = style
if self._mainWin:
inReportView = (style & ULC_REPORT) != 0
if inReportView != wasInReportView:
# we need to notify the main window about this change as it must
# update its data structures
self._mainWin.SetReportView(inReportView)
self.CreateOrDestroyHeaderWindowAsNeeded()
self.CreateOrDestroyFooterWindowAsNeeded()
self.GetSizer().Layout()
if style & ULC_HAS_VARIABLE_ROW_HEIGHT:
self._mainWin.ResetLineDimensions()
self._mainWin.ResetVisibleLinesRange()
self.Refresh()
def HasAGWFlag(self, flag):
"""
Returns ``True`` if the window has the given flag bit set.
:param `flag`: the window style to check.
:see: :meth:`~UltimateListCtrl.SetAGWWindowStyleFlag` for a list of valid window styles.
"""
return self._agwStyle & flag
def SetUserLineHeight(self, height):
"""
Sets a custom value for the :class:`UltimateListCtrl` item height.
:param `height`: the custom height for all the items, in pixels.
:note: This method can be used only with ``ULC_REPORT`` and ``ULC_USER_ROW_HEIGHT`` styles set.
"""
if self._mainWin:
self._mainWin.SetUserLineHeight(height)
def GetUserLineHeight(self):
"""
Returns the custom value for the :class:`UltimateListCtrl` item height, if previously set with
:meth:`~UltimateListCtrl.SetUserLineHeight`.
:note: This method can be used only with ``ULC_REPORT`` and ``ULC_USER_ROW_HEIGHT`` styles set.
"""
if self._mainWin:
return self._mainWin.GetUserLineHeight()
def GetColumn(self, col):
"""
Returns information about this column.
:param `col`: an integer specifying the column index.
"""
return self._mainWin.GetColumn(col)
def SetColumn(self, col, item):
"""
Sets information about this column.
:param `col`: an integer specifying the column index;
:param `item`: an instance of :class:`UltimateListItem`.
"""
self._mainWin.SetColumn(col, item)
return True
def GetColumnWidth(self, col):
"""
Returns the column width for the input column.
:param `col`: an integer specifying the column index.
"""
return self._mainWin.GetColumnWidth(col)
def SetColumnWidth(self, col, width):
"""
Sets the column width.
:param `width`: can be a width in pixels or ``wx.LIST_AUTOSIZE`` (-1) or
``wx.LIST_AUTOSIZE_USEHEADER`` (-2) or ``LIST_AUTOSIZE_FILL`` (-3).
``wx.LIST_AUTOSIZE`` will resize the column to the length of its longest
item. ``wx.LIST_AUTOSIZE_USEHEADER`` will resize the column to the
length of the header (Win32) or 80 pixels (other platforms).
``LIST_AUTOSIZE_FILL`` will resize the column fill the remaining width
of the window.
:note: In small or normal icon view, col must be -1, and the column width
is set for all columns.
"""
self._mainWin.SetColumnWidth(col, width)
return True
def GetCountPerPage(self):
"""
Returns the number of items that can fit vertically in the visible area
of the :class:`UltimateListCtrl` (list or report view) or the total number of
items in the list control (icon or small icon view).
"""
return self._mainWin.GetCountPerPage() # different from Windows ?
def GetItem(self, itemOrId, col=0):
"""
Returns the information about the input item.
:param `itemOrId`: an instance of :class:`UltimateListItem` or an integer specifying
the item index;
:param `col`: the column to which the item belongs to.
"""
item = CreateListItem(itemOrId, col)
return self._mainWin.GetItem(item, col)
def SetItem(self, info):
"""
Sets the information about the input item.
:param `info`: an instance of :class:`UltimateListItem`.
"""
self._mainWin.SetItem(info)
return True
def SetStringItem(self, index, col, label, imageIds=[], it_kind=0):
"""
Sets a string or image at the given location.
:param `index`: the item index;
:param `col`: the column to which the item belongs to;
:param `label`: the item text;
:param `imageIds`: a Python list containing the image indexes for the
images associated to this item;
:param `it_kind`: the item kind. May be one of the following integers:
=============== ==========================
Item Kind Description
=============== ==========================
0 A normal item
1 A checkbox-like item
2 A radiobutton-type item
=============== ==========================
"""
info = UltimateListItem()
info._text = label
info._mask = ULC_MASK_TEXT
if it_kind:
info._mask |= ULC_MASK_KIND
info._kind = it_kind
info._itemId = index
info._col = col
for ids in to_list(imageIds):
if ids > -1:
info._image.append(ids)
if info._image:
info._mask |= ULC_MASK_IMAGE
self._mainWin.SetItem(info)
return index
def GetItemState(self, item, stateMask):
"""
Returns the item state flags for the input item.
:param `item`: the index of the item;
:param `stateMask`: the bitmask for the state flag.
:see: :meth:`~UltimateListCtrl.SetItemState` for a list of valid state flags.
"""
return self._mainWin.GetItemState(item, stateMask)
def SetItemState(self, item, state, stateMask):
"""
Sets the item state flags for the input item.
:param `item`: the index of the item; if defaulted to -1, the state flag
will be set for all the items;
:param `state`: any combination of the following bits:
============================ ========= ==============================
State Bits Hex Value Description
============================ ========= ==============================
``ULC_STATE_DONTCARE`` 0x0 Don't care what the state is
``ULC_STATE_DROPHILITED`` 0x1 The item is highlighted to receive a drop event
``ULC_STATE_FOCUSED`` 0x2 The item has the focus
``ULC_STATE_SELECTED`` 0x4 The item is selected
``ULC_STATE_CUT`` 0x8 The item is in the cut state
``ULC_STATE_DISABLED`` 0x10 The item is disabled
``ULC_STATE_FILTERED`` 0x20 The item has been filtered
``ULC_STATE_INUSE`` 0x40 The item is in use
``ULC_STATE_PICKED`` 0x80 The item has been picked
``ULC_STATE_SOURCE`` 0x100 The item is a drag and drop source
============================ ========= ==============================
:param `stateMask`: the bitmask for the state flag.
"""
self._mainWin.SetItemState(item, state, stateMask)
return True
def SetItemImage(self, item, image, selImage=-1):
"""
Sets a Python list of image indexes associated with the item.
:param `item`: an integer specifying the item index;
:param `image`: a Python list of indexes into the image list associated
with the :class:`UltimateListCtrl`. In report view, this only sets the images
for the first column;
:param `selImage`: not used at present.
"""
return self.SetItemColumnImage(item, 0, image)
def SetItemColumnImage(self, item, column, image):
"""
Sets a Python list of image indexes associated with the item in the input
column.
:param `item`: an integer specifying the item index;
:param `column`: the column to which the item belongs to;
:param `image`: a Python list of indexes into the image list associated
with the :class:`UltimateListCtrl`.
"""
info = UltimateListItem()
info._image = to_list(image)
info._mask = ULC_MASK_IMAGE
info._itemId = item
info._col = column
self._mainWin.SetItem(info)
return True
def GetItemText(self, item):
"""
Returns the item text.
:param `item`: an instance of :class:`UltimateListItem` or an integer specifying
the item index.
"""
return self._mainWin.GetItemText(item)
def SetItemText(self, item, text):
"""
Sets the item text.
:param `item`: an instance of :class:`UltimateListItem` or an integer specifying
the item index;
:param `text`: the new item text.
"""
self._mainWin.SetItemText(item, text)
def GetItemData(self, item):
"""
Gets the application-defined data associated with this item.
:param `item`: an integer specifying the item index.
"""
info = UltimateListItem()
info._mask = ULC_MASK_DATA
info._itemId = item
self._mainWin.GetItem(info)
return info._data
def SetItemData(self, item, data):
"""
Sets the application-defined data associated with this item.
:param `item`: an integer specifying the item index;
:param `data`: the data to be associated with the input item.
:note: This function cannot be used to associate pointers with
the control items, use :meth:`~UltimateListCtrl.SetItemPyData` instead.
"""
info = UltimateListItem()
info._mask = ULC_MASK_DATA
info._itemId = item
info._data = data
self._mainWin.SetItem(info)
return True
def GetItemPyData(self, item):
"""
Returns the data for the item, which can be any Python object.
:param `item`: an integer specifying the item index.
:note: Please note that Python data is associated with the item and not
with subitems.
"""
info = UltimateListItem()
info._mask = ULC_MASK_PYDATA
info._itemId = item
self._mainWin.GetItem(info)
return info._pyData
def SetItemPyData(self, item, pyData):
"""
Sets the data for the item, which can be any Python object.
:param `item`: an integer specifying the item index;
:param `pyData`: any Python object.
:note: Please note that Python data is associated with the item and not
with subitems.
"""
info = UltimateListItem()
info._mask = ULC_MASK_PYDATA
info._itemId = item
info._pyData = pyData
self._mainWin.SetItem(info)
return True
SetPyData = SetItemPyData
GetPyData = GetItemPyData
def GetViewRect(self):
"""
Returns the rectangle taken by all items in the control. In other words,
if the controls client size were equal to the size of this rectangle, no
scrollbars would be needed and no free space would be left.
:note: This function only works in the icon and small icon views, not in
list or report views.
"""
return self._mainWin.GetViewRect()
def GetItemRect(self, item, code=ULC_RECT_BOUNDS):
"""
Returns the rectangle representing the item's size and position, in physical
coordinates.
:param `item`: the row in which the item lives;
:param `code`: one of ``ULC_RECT_BOUNDS``, ``ULC_RECT_ICON``, ``ULC_RECT_LABEL``.
"""
return self.GetSubItemRect(item, ULC_GETSUBITEMRECT_WHOLEITEM, code)
def GetSubItemRect(self, item, subItem, code):
"""
Returns the rectangle representing the size and position, in physical coordinates,
of the given subitem, i.e. the part of the row `item` in the column `subItem`.
:param `item`: the row in which the item lives;
:param `subItem`: the column in which the item lives. If set equal to the special
value ``ULC_GETSUBITEMRECT_WHOLEITEM`` the return value is the same as for
:meth:`~UltimateListCtrl.GetItemRect`;
:param `code`: one of ``ULC_RECT_BOUNDS``, ``ULC_RECT_ICON``, ``ULC_RECT_LABEL``.
:note: This method is only meaningful when the :class:`UltimateListCtrl` is in the
report mode.
"""
rect = self._mainWin.GetSubItemRect(item, subItem)
if self._mainWin.HasHeader():
rect.y += self._headerHeight + 1
return rect
def GetItemPosition(self, item):
"""
Returns the position of the item, in icon or small icon view.
:param `item`: the row in which the item lives.
"""
return self._mainWin.GetItemPosition(item)
def SetItemPosition(self, item, pos):
"""
Sets the position of the item, in icon or small icon view.
:param `item`: the row in which the item lives;
:param `pos`: the item position.
:note: This method is currently unimplemented and does nothing.
"""
return False
def GetItemCount(self):
""" Returns the number of items in the :class:`UltimateListCtrl`. """
return self._mainWin.GetItemCount()
def GetColumnCount(self):
""" Returns the total number of columns in the :class:`UltimateListCtrl`. """
return self._mainWin.GetColumnCount()
def SetItemSpacing(self, spacing, isSmall=False):
"""
Sets the spacing between item texts and icons.
:param `spacing`: the spacing between item texts and icons, in pixels;
:param `isSmall`: ``True`` if using a ``wx.IMAGE_LIST_SMALL`` image list,
``False`` if using a ``wx.IMAGE_LIST_NORMAL`` image list.
"""
self._mainWin.SetItemSpacing(spacing, isSmall)
def GetItemSpacing(self, isSmall=False):
"""
Returns the spacing between item texts and icons, in pixels.
:param `isSmall`: ``True`` if using a ``wx.IMAGE_LIST_SMALL`` image list,
``False`` if using a ``wx.IMAGE_LIST_NORMAL`` image list.
"""
return self._mainWin.GetItemSpacing(isSmall)
def SetItemTextColour(self, item, col):
"""
Sets the item text colour.
:param `item`: the index of the item;
:param `col`: a valid :class:`wx.Colour` object.
"""
info = UltimateListItem()
info._itemId = item
info = self._mainWin.GetItem(info)
info.SetTextColour(col)
self._mainWin.SetItem(info)
def GetItemTextColour(self, item):
"""
Returns the item text colour.
:param `item`: the index of the item.
"""
info = UltimateListItem()
info._itemId = item
info = self._mainWin.GetItem(info)
return info.GetTextColour()
def SetItemBackgroundColour(self, item, col):
"""
Sets the item background colour.
:param `item`: the index of the item;
:param `col`: a valid :class:`wx.Colour` object.
"""
info = UltimateListItem()
info._itemId = item
info = self._mainWin.GetItem(info)
info.SetBackgroundColour(col)
self._mainWin.SetItem(info)
def GetItemBackgroundColour(self, item):
"""
Returns the item background colour.
:param `item`: the index of the item.
"""
info = UltimateListItem()
info._itemId = item
info = self._mainWin.GetItem(info)
return info.GetBackgroundColour()
def SetItemFont(self, item, f):
"""
Sets the item font.
:param `item`: the index of the item;
:param `f`: a valid :class:`wx.Font` object.
"""
info = UltimateListItem()
info._itemId = item
info = self._mainWin.GetItem(info)
info.SetFont(f)
info.SetBackgroundColour(self.GetItemBackgroundColour(item))
self._mainWin.SetItem(info)
def GetItemFont(self, item):
"""
Returns the item font.
:param `item`: the index of the item.
"""
info = UltimateListItem()
info._itemId = item
info = self._mainWin.GetItem(info)
return info.GetFont()
def GetSelectedItemCount(self):
""" Returns the number of selected items in :class:`UltimateListCtrl`. """
return self._mainWin.GetSelectedItemCount()
def GetTextColour(self):
""" Returns the :class:`UltimateListCtrl` foreground colour. """
return self.GetForegroundColour()
def SetTextColour(self, col):
"""
Sets the :class:`UltimateListCtrl` foreground colour.
:param `col`: a valid :class:`wx.Colour` object.
"""
self.SetForegroundColour(col)
def GetTopItem(self):
""" Gets the index of the topmost visible item when in list or report view. """
top, dummy = self._mainWin.GetVisibleLinesRange()
return top
def GetNextItem(self, item, geometry=ULC_NEXT_ALL, state=ULC_STATE_DONTCARE):
"""
Searches for an item with the given `geometry` or `state`, starting from `item`
but excluding the `item` itself.
:param `item`: the item at which starting the search. If set to -1, the first
item that matches the specified flags will be returned.
:param `geometry`: can be one of:
=================== ========= =================================
Geometry Flag Hex Value Description
=================== ========= =================================
``ULC_NEXT_ABOVE`` 0x0 Searches for an item above the specified item
``ULC_NEXT_ALL`` 0x1 Searches for subsequent item by index
``ULC_NEXT_BELOW`` 0x2 Searches for an item below the specified item
``ULC_NEXT_LEFT`` 0x3 Searches for an item to the left of the specified item
``ULC_NEXT_RIGHT`` 0x4 Searches for an item to the right of the specified item
=================== ========= =================================
:param `state`: any combination of the following bits:
============================ ========= ==============================
State Bits Hex Value Description
============================ ========= ==============================
``ULC_STATE_DONTCARE`` 0x0 Don't care what the state is
``ULC_STATE_DROPHILITED`` 0x1 The item is highlighted to receive a drop event
``ULC_STATE_FOCUSED`` 0x2 The item has the focus
``ULC_STATE_SELECTED`` 0x4 The item is selected
``ULC_STATE_CUT`` 0x8 The item is in the cut state
``ULC_STATE_DISABLED`` 0x10 The item is disabled
``ULC_STATE_FILTERED`` 0x20 The item has been filtered
``ULC_STATE_INUSE`` 0x40 The item is in use
``ULC_STATE_PICKED`` 0x80 The item has been picked
``ULC_STATE_SOURCE`` 0x100 The item is a drag and drop source
============================ ========= ==============================
:return: The first item with given `state` following `item` or -1 if no such item found.
:note: This function may be used to find all selected items in the
control like this::
item = -1
while 1:
item = listctrl.GetNextItem(item, ULC_NEXT_ALL, ULC_STATE_SELECTED)
if item == -1:
break
# This item is selected - do whatever is needed with it
wx.LogMessage("Item %ld is selected."%item)
"""
return self._mainWin.GetNextItem(item, geometry, state)
def GetImageList(self, which):
"""
Returns the image list associated with the control.
:param `which`: one of ``wx.IMAGE_LIST_NORMAL``, ``wx.IMAGE_LIST_SMALL``,
``wx.IMAGE_LIST_STATE`` (the last is unimplemented).
:note:
As :class:`UltimateListCtrl` allows you to use a standard :class:`wx.ImageList` or
:class:`PyImageList`, the returned object depends on which kind of image list you
chose.
"""
if which == wx.IMAGE_LIST_NORMAL:
return self._imageListNormal
elif which == wx.IMAGE_LIST_SMALL:
return self._imageListSmall
elif which == wx.IMAGE_LIST_STATE:
return self._imageListState
return None
def SetImageList(self, imageList, which):
"""
Sets the image list associated with the control.
:param `imageList`: an instance of :class:`wx.ImageList` or an instance of :class:`PyImageList`;
:param `which`: one of ``wx.IMAGE_LIST_NORMAL``, ``wx.IMAGE_LIST_SMALL``,
``wx.IMAGE_LIST_STATE`` (the last is unimplemented).
:note: Using :class:`PyImageList` enables you to have images of different size inside the
image list. In your derived class, instead of doing this::
imageList = wx.ImageList(16, 16)
imageList.Add(someBitmap)
self.SetImageList(imageList, wx.IMAGE_LIST_SMALL)
You should do this::
imageList = PyImageList(16, 16)
imageList.Add(someBitmap)
self.SetImageList(imageList, wx.IMAGE_LIST_SMALL)
"""
if which == wx.IMAGE_LIST_NORMAL:
self._imageListNormal = imageList
elif which == wx.IMAGE_LIST_SMALL:
self._imageListSmall = imageList
elif which == wx.IMAGE_LIST_STATE:
self._imageListState = imageList
self._mainWin.SetImageList(imageList, which)
def AssignImageList(self, imageList, which):
"""
Assigns the image list associated with the control.
:param `imageList`: an instance of :class:`wx.ImageList` or an instance of :class:`PyImageList`;
:param `which`: one of ``wx.IMAGE_LIST_NORMAL``, ``wx.IMAGE_LIST_SMALL``,
``wx.IMAGE_LIST_STATE`` (the last is unimplemented).
:note: Using :class:`PyImageList` enables you to have images of different size inside the
image list. In your derived class, instead of doing this::
imageList = wx.ImageList(16, 16)
imageList.Add(someBitmap)
self.SetImageList(imageList, wx.IMAGE_LIST_SMALL)
You should do this::
imageList = PyImageList(16, 16)
imageList.Add(someBitmap)
self.SetImageList(imageList, wx.IMAGE_LIST_SMALL)
"""
self.SetImageList(imageList, which)
def Arrange(self, flag):
"""
Arranges the items in icon or small icon view.
:param `flag`: one of the following bits:
========================== ========= ===============================
Alignment Flag Hex Value Description
========================== ========= ===============================
``ULC_ALIGN_DEFAULT`` 0x0 Default alignment
``ULC_ALIGN_SNAP_TO_GRID`` 0x3 Snap to grid
========================== ========= ===============================
:note: This method is currently unimplemented and does nothing.
"""
return 0
def DeleteItem(self, item):
"""
Deletes the specified item.
:param `item`: the index of the item to delete.
:note: This function sends the ``EVT_LIST_DELETE_ITEM`` event for the item
being deleted.
"""
self._mainWin.DeleteItem(item)
return True
def DeleteAllItems(self):
"""
Deletes all items in the :class:`UltimateListCtrl`.
:note: This function does not send the ``EVT_LIST_DELETE_ITEM`` event because
deleting many items from the control would be too slow then (unlike :meth:`~UltimateListCtrl.DeleteItem`).
"""
self._mainWin.DeleteAllItems()
return True
def DeleteAllColumns(self):
""" Deletes all the column in :class:`UltimateListCtrl`. """
count = len(self._mainWin._columns)
for n in range(count):
self.DeleteColumn(0)
return True
def ClearAll(self):
""" Deletes everything in :class:`UltimateListCtrl`. """
self._mainWin.DeleteEverything()
def DeleteColumn(self, col):
"""
Deletes the specified column.
:param `col`: the index of the column to delete.
"""
self._mainWin.DeleteColumn(col)
return True
def EditLabel(self, item):
"""
Starts editing an item label.
:param `item`: the index of the item to edit.
"""
self._mainWin.EditLabel(item)
def EnsureVisible(self, item):
"""
Ensures this item is visible.
:param `index`: the index of the item to scroll into view.
"""
self._mainWin.EnsureVisible(item)
return True
def FindItem(self, start, str, partial=False):
"""
Find an item whose label matches this string.
:param `start`: the starting point of the input `string` or the beginning
if `start` is -1;
:param `string`: the string to look for matches;
:param `partial`: if ``True`` then this method will look for items which
begin with `string`.
:note: The string comparison is case insensitive.
"""
return self._mainWin.FindItem(start, str, partial)
def FindItemData(self, start, data):
"""
Find an item whose data matches this data.
:param `start`: the starting point of the input `data` or the beginning
if `start` is -1;
:param `data`: the data to look for matches.
"""
return self._mainWin.FindItemData(start, data)
def FindItemAtPos(self, start, pt):
"""
Find an item nearest this position.
:param `pt`: an instance of :class:`wx.Point`.
"""
return self._mainWin.FindItemAtPos(pt)
def HitTest(self, pointOrTuple):
"""
HitTest method for a :class:`UltimateListCtrl`.
:param `pointOrTuple`: an instance of :class:`wx.Point` or a tuple representing
the mouse `x`, `y` position.
:see: :meth:`UltimateListMainWindow.HitTestLine() <UltimateListMainWindow.HitTestLine>` for a list of return flags.
"""
if isinstance(pointOrTuple, wx.Point):
x, y = pointOrTuple.x, pointOrTuple.y
else:
x, y = pointOrTuple
return self._mainWin.HitTest(x, y)
def InsertItem(self, info):
"""
Inserts an item into :class:`UltimateListCtrl`.
:param `info`: an instance of :class:`UltimateListItem`.
"""
self._mainWin.InsertItem(info)
return info._itemId
def InsertStringItem(self, index, label, it_kind=0):
"""
Inserts a string item at the given location.
:param `index`: the index at which we wish to insert the item;
:param `label`: the item text;
:param `it_kind`: the item kind.
:see: :meth:`~UltimateListCtrl.SetStringItem` for a list of valid item kinds.
"""
info = UltimateListItem()
info._text = label
info._mask = ULC_MASK_TEXT
if it_kind:
info._mask |= ULC_MASK_KIND
info._kind = it_kind
info._itemId = index
return self.InsertItem(info)
def InsertImageItem(self, index, imageIds, it_kind=0):
"""
Inserts an image item at the given location.
:param `index`: the index at which we wish to insert the item;
:param `imageIds`: a Python list containing the image indexes for the
images associated to this item;
:param `it_kind`: the item kind.
:see: :meth:`~UltimateListCtrl.SetStringItem` for a list of valid item kinds.
"""
info = UltimateListItem()
info._mask = ULC_MASK_IMAGE
if it_kind:
info._mask |= ULC_MASK_KIND
info._kind = it_kind
info._image = to_list(imageIds)
info._itemId = index
return self.InsertItem(info)
def InsertImageStringItem(self, index, label, imageIds, it_kind=0):
"""
Inserts an image+string item at the given location.
:param `index`: the index at which we wish to insert the item;
:param `label`: the item text;
:param `imageIds`: a Python list containing the image indexes for the
images associated to this item;
:param `it_kind`: the item kind.
:see: :meth:`~UltimateListCtrl.SetStringItem` for a list of valid item kinds.
"""
info = UltimateListItem()
info._text = label
info._image = to_list(imageIds)
info._mask = ULC_MASK_TEXT | ULC_MASK_IMAGE
if it_kind:
info._mask |= ULC_MASK_KIND
info._kind = it_kind
info._itemId = index
return self.InsertItem(info)
def InsertColumnInfo(self, col, item):
"""
Inserts a column into :class:`UltimateListCtrl`.
:param `col`: the column index at which we wish to insert a column;
:param `item`: an instance of :class:`UltimateListItem`.
:return: the index at which the column has been inserted.
"""
if not self._mainWin.InReportView() and not self.HasAGWFlag(ULC_HEADER_IN_ALL_VIEWS) and \
not self._mainWin.InTileView():
raise Exception("Can't add column in non report/tile modes or without the ULC_HEADER_IN_ALL_VIEWS style set")
idx = self._mainWin.InsertColumn(col, item)
if self._headerWin:
self._headerWin.Refresh()
return idx
def InsertColumn(self, col, heading, format=ULC_FORMAT_LEFT, width=-1):
"""
Inserts a column into :class:`UltimateListCtrl`.
:param `col`: the column index at which we wish to insert a column;
:param `heading`: the header text;
:param `format`: the column alignment flag. This can be one of the following
bits:
============================ ========= ==============================
Alignment Bits Hex Value Description
============================ ========= ==============================
``ULC_FORMAT_LEFT`` 0x0 The item is left-aligned
``ULC_FORMAT_RIGHT`` 0x1 The item is right-aligned
``ULC_FORMAT_CENTRE`` 0x2 The item is centre-aligned
``ULC_FORMAT_CENTER`` 0x2 The item is center-aligned
============================ ========= ==============================
:param `width`: can be a width in pixels or ``wx.LIST_AUTOSIZE`` (-1) or
``wx.LIST_AUTOSIZE_USEHEADER`` (-2) or ``LIST_AUTOSIZE_FILL`` (-3).
``wx.LIST_AUTOSIZE`` will resize the column to the length of its longest
item. ``wx.LIST_AUTOSIZE_USEHEADER`` will resize the column to the
length of the header (Win32) or 80 pixels (other platforms).
``LIST_AUTOSIZE_FILL`` will resize the column fill the remaining width
of the window.
:return: the index at which the column has been inserted.
"""
item = UltimateListItem()
item._mask = ULC_MASK_TEXT | ULC_MASK_FORMAT | ULC_MASK_FONT
item._text = heading
if width >= -2:
item._mask |= ULC_MASK_WIDTH
item._width = width
item._format = format
return self.InsertColumnInfo(col, item)
def IsColumnShown(self, column):
"""
Returns ``True`` if the input column is shown, ``False`` if it is hidden.
:param `column`: an integer specifying the column index.
"""
if self._headerWin:
return self._mainWin.IsColumnShown(column)
raise Exception("Showing/hiding columns works only with the header shown")
def SetColumnShown(self, column, shown=True):
"""
Sets the specified column as shown or hidden.
:param `column`: an integer specifying the column index;
:param `shown`: ``True`` to show the column, ``False`` to hide it.
"""
col = self.GetColumn(column)
col._mask |= ULC_MASK_SHOWN
col.SetShown(shown)
self._mainWin.SetColumn(column, col)
self.Update()
def ScrollList(self, dx, dy):
"""
Scrolls the :class:`UltimateListCtrl`.
:param `dx`: if in icon, small icon or report view mode, specifies the number
of pixels to scroll. If in list view mode, `dx` specifies the number of
columns to scroll.
:param `dy`: always specifies the number of pixels to scroll vertically.
"""
return self._mainWin.ScrollList(dx, dy)
# Sort items.
# The return value is a negative number if the first item should precede the second
# item, a positive number of the second item should precede the first,
# or zero if the two items are equivalent.
def SortItems(self, func=None):
"""
Call this function to sort the items in the :class:`UltimateListCtrl`. Sorting is done
using the specified function `func`. This function must have the
following prototype::
def OnCompareItems(self, line1, line2):
DoSomething(line1, line2)
# function code
It is called each time when the two items must be compared and should return 0
if the items are equal, negative value if the first item is less than the second
one and positive value if the first one is greater than the second one.
:param `func`: the method to use to sort the items. The default is to use the
:meth:`UltimateListMainWindow.OnCompareItems() <UltimateListMainWindow.OnCompareItems>` method.
"""
self._mainWin.SortItems(func)
wx.CallAfter(self.Refresh)
return True
# ----------------------------------------------------------------------------
# event handlers
# ----------------------------------------------------------------------------
def OnSize(self, event):
"""
Handles the ``wx.EVT_SIZE`` event for :class:`UltimateListCtrl`.
:param `event`: a :class:`wx.SizeEvent` event to be processed.
"""
if not self.IsShownOnScreen():
# We don't have the proper column sizes until we are visible so
# use CallAfter to resize the columns on the first display
if self._mainWin:
wx.CallAfter(self._mainWin.ResizeColumns)
if not self._mainWin:
return
# We need to override OnSize so that our scrolled
# window a) does call Layout() to use sizers for
# positioning the controls but b) does not query
# the sizer for their size and use that for setting
# the scrollable area as set that ourselves by
# calling SetScrollbar() further down.
self.DoLayout()
def OnSetFocus(self, event):
"""
Handles the ``wx.EVT_SET_FOCUS`` event for :class:`UltimateListCtrl`.
:param `event`: a :class:`FocusEvent` event to be processed.
"""
if self._mainWin:
self._mainWin.SetFocusIgnoringChildren()
self._mainWin.Update()
event.Skip()
def OnInternalIdle(self):
"""
This method is normally only used internally, but sometimes an application
may need it to implement functionality that should not be disabled by an
application defining an `OnIdle` handler in a derived class.
This method may be used to do delayed painting, for example, and most
implementations call :meth:`wx.Window.UpdateWindowUI` in order to send update events
to the window in idle time.
"""
wx.Control.OnInternalIdle(self)
# do it only if needed
if self._mainWin and self._mainWin._dirty:
self._mainWin._shortItems = []
self._mainWin.RecalculatePositions()
# ----------------------------------------------------------------------------
# font/colours
# ----------------------------------------------------------------------------
def SetBackgroundColour(self, colour):
"""
Changes the background colour of :class:`UltimateListCtrl`.
:param `colour`: the colour to be used as the background colour, pass
:class:`NullColour` to reset to the default colour.
:note: The background colour is usually painted by the default :class:`EraseEvent`
event handler function under Windows and automatically under GTK.
:note: Setting the background colour does not cause an immediate refresh, so
you may wish to call :meth:`wx.Window.ClearBackground` or :meth:`wx.Window.Refresh` after
calling this function.
:note: Overridden from :class:`wx.Control`.
"""
if self._mainWin:
self._mainWin.SetBackgroundColour(colour)
self._mainWin._dirty = True
return True
def SetForegroundColour(self, colour):
"""
Changes the foreground colour of :class:`UltimateListCtrl`.
:param `colour`: the colour to be used as the foreground colour, pass
:class:`NullColour` to reset to the default colour.
:note: Overridden from :class:`wx.Control`.
"""
if not wx.Control.SetForegroundColour(self, colour):
return False
if self._mainWin:
self._mainWin.SetForegroundColour(colour)
self._mainWin._dirty = True
if self._headerWin:
self._headerWin.SetForegroundColour(colour)
return True
def SetFont(self, font):
"""
Sets the :class:`UltimateListCtrl` font.
:param `font`: a valid :class:`wx.Font` instance.
:note: Overridden from :class:`wx.Control`.
"""
if not wx.Control.SetFont(self, font):
return False
if self._mainWin:
self._mainWin.SetFont(font)
self._mainWin._dirty = True
if self._headerWin:
self._headerWin.SetFont(font)
self.Refresh()
return True
def GetClassDefaultAttributes(self, variant):
"""
Returns the default font and colours which are used by the control. This is
useful if you want to use the same font or colour in your own control as in
a standard control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the users system,
especially if it uses themes.
This static method is "overridden'' in many derived classes and so calling,
for example, :meth:`Button.GetClassDefaultAttributes` () will typically return the
values appropriate for a button which will be normally different from those
returned by, say, :meth:`ListCtrl.GetClassDefaultAttributes` ().
:note: The :class:`VisualAttributes` structure has at least the fields `font`,
`colFg` and `colBg`. All of them may be invalid if it was not possible to
determine the default control appearance or, especially for the background
colour, if the field doesn't make sense as is the case for `colBg` for the
controls with themed background.
:note: Overridden from :class:`wx.Control`.
"""
attr = wx.VisualAttributes()
attr.colFg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_LISTBOXTEXT)
attr.colBg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_LISTBOX)
attr.font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
return attr
def GetScrolledWin(self):
""" Returns the header window owner. """
return self._headerWin.GetOwner()
# ----------------------------------------------------------------------------
# methods forwarded to self._mainWin
# ----------------------------------------------------------------------------
def SetDropTarget(self, dropTarget):
"""
Associates a drop target with this window.
If the window already has a drop target, it is deleted.
:param `dropTarget`: an instance of :class:`DropTarget`.
:note: Overridden from :class:`wx.Control`.
"""
self._mainWin.SetDropTarget(dropTarget)
def GetDropTarget(self):
"""
Returns the associated drop target, which may be ``None``.
:note: Overridden from :class:`wx.Control`.
"""
return self._mainWin.GetDropTarget()
def SetCursor(self, cursor):
"""
Sets the window's cursor.
:param `cursor`: specifies the cursor that the window should normally display.
The `cursor` may be :class:`NullCursor` in which case the window cursor will be
reset back to default.
:note: The window cursor also sets it for the children of the window implicitly.
:note: Overridden from :class:`wx.Control`.
"""
return (self._mainWin and [self._mainWin.SetCursor(cursor)] or [False])[0]
def GetBackgroundColour(self):
"""
Returns the background colour of the window.
:note: Overridden from :class:`wx.Control`.
"""
return (self._mainWin and [self._mainWin.GetBackgroundColour()] or [wx.NullColour])[0]
def GetForegroundColour(self):
"""
Returns the foreground colour of the window.
:note: Overridden from :class:`wx.Control`.
"""
return (self._mainWin and [self._mainWin.GetForegroundColour()] or [wx.NullColour])[0]
def PopupMenu(self, menu, pos=wx.DefaultPosition):
"""
Pops up the given `menu` at the specified coordinates, relative to this window,
and returns control when the user has dismissed the menu. If a menu item is
selected, the corresponding menu event is generated and will be processed as
usual. If the coordinates are not specified, the current mouse cursor position
is used.
:param `menu`: an instance of :class:`wx.Menu` to pop up;
:param `pos`: the position where the menu will appear.
:note: Overridden from :class:`wx.Control`.
"""
return self._mainWin.PopupMenu(menu, pos)
def ClientToScreen(self, pointOrTuple):
"""
Converts to screen coordinates from coordinates relative to this window.
:param `pointOrTuple`: an instance of :class:`wx.Point` or a tuple representing the
`x`, `y` coordinates for this point.
:return: the coordinates relative to the screen.
:note: Overridden from :class:`wx.Control`.
"""
return self._mainWin.ClientToScreen(*pointOrTuple)
def ClientToScreenXY(self, x, y):
"""
Converts to screen coordinates from coordinates relative to this window.
:param `x`: an integer specifying the `x` client coordinate;
:param `y`: an integer specifying the `y` client coordinate.
:return: the coordinates relative to the screen.
:note: Overridden from :class:`wx.Control`.
"""
return self._mainWin.ClientToScreen(x, y)
def ScreenToClient(self, pointOrTuple):
"""
Converts from screen to client window coordinates.
:param `pointOrTuple`: an instance of :class:`wx.Point` or a tuple representing the
`x`, `y` coordinates for this point.
:return: the coordinates relative to this window.
:note: Overridden from :class:`wx.Control`.
"""
return self._mainWin.ScreenToClient(*pointOrTuple)
def ScreenToClientXY(self, x, y):
"""
Converts from screen to client window coordinates.
:param `x`: an integer specifying the `x` screen coordinate;
:param `y`: an integer specifying the `y` screen coordinate.
:return: the coordinates relative to this window.
:note: Overridden from :class:`wx.Control`.
"""
return self._mainWin.ScreenToClient(x, y)
def SetFocus(self):
""" This sets the window to receive keyboard input. """
# The test in window.cpp fails as we are a composite
# window, so it checks against "this", but not self._mainWin.
if wx.Window.FindFocus() != self:
self._mainWin.SetFocusIgnoringChildren()
def DoGetBestSize(self):
"""
Gets the size which best suits the window: for a control, it would be the
minimal size which doesn't truncate the control, for a panel - the same size
as it would have after a call to `Fit()`.
"""
# Something is better than nothing...
# 100x80 is what the MSW version will get from the default
# wx.Control.DoGetBestSize
return wx.Size(100, 80)
# ----------------------------------------------------------------------------
# virtual list control support
# ----------------------------------------------------------------------------
def OnGetItemText(self, item, col):
"""
This function **must** be overloaded in the derived class for a control with
``ULC_VIRTUAL`` style. It should return the string containing the text of
the given column for the specified item.
:param `item`: an integer specifying the item index;
:param `col`: the column index to which the item belongs to.
"""
# this is a pure virtual function, in fact - which is not really pure
# because the controls which are not virtual don't need to implement it
raise Exception("UltimateListCtrl.OnGetItemText not supposed to be called")
def OnGetItemTextColour(self, item, col):
"""
This function **must** be overloaded in the derived class for a control with
``ULC_VIRTUAL`` style. It should return a :class:`wx.Colour` object or ``None`` for
the default color.
:param `item`: an integer specifying the item index;
:param `col`: the column index to which the item belongs to.
"""
# this is a pure virtual function, in fact - which is not really pure
# because the controls which are not virtual don't need to implement it
raise Exception("UltimateListCtrl.OnGetItemTextColour not supposed to be called")
def OnGetItemToolTip(self, item, col):
"""
This function **must** be overloaded in the derived class for a control with
``ULC_VIRTUAL`` style. It should return the string containing the text of
the tooltip for the specified item.
:param `item`: an integer specifying the item index;
:param `col`: the column index to which the item belongs to.
"""
# this is a pure virtual function, in fact - which is not really pure
# because the controls which are not virtual don't need to implement it
raise Exception("UltimateListCtrl.OnGetItemToolTip not supposed to be called")
def OnGetItemImage(self, item):
"""
This function **must** be overloaded in the derived class for a control with
``ULC_VIRTUAL`` style having an image list (if the control doesn't have an
image list, it is not necessary to overload it). It should return a Python
list of indexes representing the images associated to the input item or an
empty list for no images.
:param `item`: an integer specifying the item index;
:note: In a control with ``ULC_REPORT`` style, :meth:`~UltimateListCtrl.OnGetItemImage` only gets called
for the first column of each line.
:note: The base class version always returns an empty Python list.
"""
if self.GetImageList(wx.IMAGE_LIST_SMALL):
raise Exception("List control has an image list, OnGetItemImage should be overridden.")
return []
def OnGetItemColumnImage(self, item, column=0):
"""
This function **must** be overloaded in the derived class for a control with
``ULC_VIRTUAL`` and ``ULC_REPORT`` style. It should return a Python list of
indexes representing the images associated to the input item or an empty list
for no images.
:param `item`: an integer specifying the item index.
:note: The base class version always returns an empty Python list.
"""
if column == 0:
return self.OnGetItemImage(item)
return []
def OnGetItemAttr(self, item):
"""
This function may be overloaded in the derived class for a control with
``ULC_VIRTUAL`` style. It should return the attribute for the specified
item or ``None`` to use the default appearance parameters.
:param `item`: an integer specifying the item index.
:note:
:class:`UltimateListCtrl` will not delete the pointer or keep a reference of it.
You can return the same :class:`UltimateListItemAttr` pointer for every
:meth:`~UltimateListCtrl.OnGetItemAttr` call.
:note: The base class version always returns ``None``.
"""
if item < 0 or item > self.GetItemCount():
raise Exception("Invalid item index in OnGetItemAttr()")
# no attributes by default
return None
def OnGetItemCheck(self, item):
"""
This function may be overloaded in the derived class for a control with
``ULC_VIRTUAL`` style. It should return whether a checkbox-like item or
a radiobutton-like item is checked or unchecked.
:param `item`: an integer specifying the item index.
:note: The base class version always returns an empty list.
"""
return []
def OnGetItemColumnCheck(self, item, column=0):
"""
This function **must** be overloaded in the derived class for a control with
``ULC_VIRTUAL`` and ``ULC_REPORT`` style. It should return whether a
checkbox-like item or a radiobutton-like item in the column header is checked
or unchecked.
:param `item`: an integer specifying the item index.
:note: The base class version always returns an empty Python list.
"""
if column == 0:
return self.OnGetItemCheck(item)
return []
def OnGetItemKind(self, item):
"""
This function **must** be overloaded in the derived class for a control with
``ULC_VIRTUAL`` style. It should return the item kind for the input item.
:param `item`: an integer specifying the item index.
:note: The base class version always returns 0 (a standard item).
:see: :meth:`~UltimateListCtrl.SetItemKind` for a list of valid item kinds.
"""
return 0
def OnGetItemColumnKind(self, item, column=0):
"""
This function **must** be overloaded in the derived class for a control with
``ULC_VIRTUAL`` style. It should return the item kind for the input item in
the header window.
:param `item`: an integer specifying the item index;
:param `column`: the column index.
:note: The base class version always returns 0 (a standard item).
:see: :meth:`~UltimateListCtrl.SetItemKind` for a list of valid item kinds.
"""
if column == 0:
return self.OnGetItemKind(item)
return 0
def SetItemCount(self, count):
"""
Sets the total number of items we handle.
:param `count`: the total number of items we handle.
"""
if not self._mainWin.IsVirtual():
raise Exception("This is for virtual controls only")
self._mainWin.SetItemCount(count)
def RefreshItem(self, item):
"""
Redraws the given item.
:param `item`: an integer specifying the item index;
:note: This is only useful for the virtual list controls as without calling
this function the displayed value of the item doesn't change even when the
underlying data does change.
"""
self._mainWin.RefreshLine(item)
def RefreshItems(self, itemFrom, itemTo):
"""
Redraws the items between `itemFrom` and `itemTo`.
The starting item must be less than or equal to the ending one.
Just as :meth:`~UltimateListCtrl.RefreshItem` this is only useful for virtual list controls
:param `itemFrom`: the first index of the refresh range;
:param `itemTo`: the last index of the refresh range.
"""
self._mainWin.RefreshLines(itemFrom, itemTo)
#
# Generic UltimateListCtrl is more or less a container for two other
# windows which drawings are done upon. These are namely
# 'self._headerWin' and 'self._mainWin'.
# Here we override 'virtual wxWindow::Refresh()' to mimic the
# behaviour UltimateListCtrl has under wxMSW.
#
def Refresh(self, eraseBackground=True, rect=None):
"""
Causes this window, and all of its children recursively (except under wxGTK1
where this is not implemented), to be repainted.
:param `eraseBackground`: If ``True``, the background will be erased;
:param `rect`: If not ``None``, only the given rectangle will be treated as damaged.
:note: Note that repainting doesn't happen immediately but only during the next
event loop iteration, if you need to update the window immediately you should
use :meth:`~UltimateListCtrl.Update` instead.
:note: Overridden from :class:`wx.Control`.
"""
if not rect:
# The easy case, no rectangle specified.
if self._headerWin:
self._headerWin.Refresh(eraseBackground)
if self._mainWin:
self._mainWin.Refresh(eraseBackground)
else:
# Refresh the header window
if self._headerWin:
rectHeader = self._headerWin.GetRect()
rectHeader.Intersect(rect)
if rectHeader.GetWidth() and rectHeader.GetHeight():
x, y = self._headerWin.GetPosition()
rectHeader.OffsetXY(-x, -y)
self._headerWin.Refresh(eraseBackground, rectHeader)
# Refresh the main window
if self._mainWin:
rectMain = self._mainWin.GetRect()
rectMain.Intersect(rect)
if rectMain.GetWidth() and rectMain.GetHeight():
x, y = self._mainWin.GetPosition()
rectMain.OffsetXY(-x, -y)
self._mainWin.Refresh(eraseBackground, rectMain)
def Update(self):
"""
Calling this method immediately repaints the invalidated area of the window
and all of its children recursively while this would usually only happen when
the flow of control returns to the event loop.
:note: This function doesn't invalidate any area of the window so nothing
happens if nothing has been invalidated (i.e. marked as requiring a redraw).
Use :meth:`~UltimateListCtrl.Refresh` first if you want to immediately redraw the window unconditionally.
:note: Overridden from :class:`wx.Control`.
"""
self._mainWin.ResetVisibleLinesRange(True)
wx.Control.Update(self)
def GetEditControl(self):
"""
Returns a pointer to the edit :class:`UltimateListTextCtrl` if the item is being edited or
``None`` otherwise (it is assumed that no more than one item may be edited
simultaneously).
"""
retval = None
if self._mainWin:
retval = self._mainWin.GetEditControl()
return retval
def Select(self, idx, on=True):
"""
Selects/deselects an item.
:param `idx`: the index of the item to select;
:param `on`: ``True`` to select the item, ``False`` to deselect it.
"""
item = CreateListItem(idx, 0)
item = self._mainWin.GetItem(item, 0)
if not item.IsEnabled():
return
if on:
state = ULC_STATE_SELECTED
else:
state = 0
self.SetItemState(idx, state, ULC_STATE_SELECTED)
def Focus(self, idx):
"""
Focus and show the given item.
:param `idx`: the index of the item to be focused.
"""
self.SetItemState(idx, ULC_STATE_FOCUSED, ULC_STATE_FOCUSED)
self.EnsureVisible(idx)
def GetFocusedItem(self):
""" Returns the currently focused item or -1 if none is focused. """
return self.GetNextItem(-1, ULC_NEXT_ALL, ULC_STATE_FOCUSED)
def GetFirstSelected(self):
""" Return first selected item, or -1 when none is selected. """
return self.GetNextSelected(-1)
def GetNextSelected(self, item):
"""
Returns subsequent selected items, or -1 when no more are selected.
:param `item`: the index of the item.
"""
return self.GetNextItem(item, ULC_NEXT_ALL, ULC_STATE_SELECTED)
def IsSelected(self, idx):
"""
Returns ``True`` if the item is selected.
:param `idx`: the index of the item to check for selection.
"""
return (self.GetItemState(idx, ULC_STATE_SELECTED) & ULC_STATE_SELECTED) != 0
def IsItemChecked(self, itemOrId, col=0):
"""
Returns whether an item is checked or not.
:param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
:param `col`: the column index to which the input item belongs to.
"""
item = CreateListItem(itemOrId, col)
return self._mainWin.IsItemChecked(item)
def IsItemEnabled(self, itemOrId, col=0):
"""
Returns whether an item is enabled or not.
:param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
:param `col`: the column index to which the input item belongs to.
"""
item = CreateListItem(itemOrId, col)
return self._mainWin.IsItemEnabled(item)
def GetItemKind(self, itemOrId, col=0):
"""
Returns the item kind.
:param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
:param `col`: the column index to which the input item belongs to.
:see: :meth:`~UltimateListCtrl.SetItemKind` for a list of valid item kinds.
"""
item = CreateListItem(itemOrId, col)
return self._mainWin.GetItemKind(item)
def SetItemKind(self, itemOrId, col=0, kind=0):
"""
Sets the item kind.
:param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
:param `col`: the column index to which the input item belongs to;
:param `kind`: may be one of the following integers:
=============== ==========================
Item Kind Description
=============== ==========================
0 A normal item
1 A checkbox-like item
2 A radiobutton-type item
=============== ==========================
"""
item = CreateListItem(itemOrId, col)
return self._mainWin.SetItemKind(item, kind)
def EnableItem(self, itemOrId, col=0, enable=True):
"""
Enables/disables an item.
:param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
:param `col`: the column index to which the input item belongs to;
:param `enable`: ``True`` to enable the item, ``False`` otherwise.
"""
item = CreateListItem(itemOrId, col)
return self._mainWin.EnableItem(item, enable)
def IsItemHyperText(self, itemOrId, col=0):
"""
Returns whether an item is hypertext or not.
:param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
:param `col`: the column index to which the input item belongs to.
"""
item = CreateListItem(itemOrId, col)
return self._mainWin.IsItemHyperText(item)
def SetItemHyperText(self, itemOrId, col=0, hyper=True):
"""
Sets whether the item is hypertext or not.
:param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
:param `col`: the column index to which the input item belongs to;
:param `hyper`: ``True`` to have an item with hypertext behaviour, ``False`` otherwise.
"""
item = CreateListItem(itemOrId, col)
return self._mainWin.SetItemHyperText(item, hyper)
def SetColumnToolTip(self, col, tip):
"""
Sets the tooltip for the column header
:param `col`: the column index;
:param `tip`: the tooltip text
"""
item = self.GetColumn(col)
item.SetToolTip(tip)
self.SetColumn(col, item)
def SetColumnImage(self, col, image):
"""
Sets one or more images to the specified column.
:param `col`: the column index;
:param `image`: a Python list containing the image indexes for the
images associated to this column item.
"""
item = self.GetColumn(col)
# preserve all other attributes too
item.SetMask(ULC_MASK_STATE |
ULC_MASK_TEXT |
ULC_MASK_IMAGE |
ULC_MASK_DATA |
ULC_SET_ITEM |
ULC_MASK_WIDTH |
ULC_MASK_FORMAT |
ULC_MASK_FONTCOLOUR |
ULC_MASK_FONT |
ULC_MASK_BACKCOLOUR |
ULC_MASK_KIND |
ULC_MASK_CHECK
)
item.SetImage(image)
self.SetColumn(col, item)
def ClearColumnImage(self, col):
"""
Clears all the images in the specified column.
:param `col`: the column index;
"""
self.SetColumnImage(col, -1)
def Append(self, entry):
"""
Append an item to the :class:`UltimateListCtrl`.
:param `entry`: should be a sequence with an item for each column.
"""
if entry:
pos = self.GetItemCount()
self.InsertStringItem(pos, six.u(entry[0]))
for i in range(1, len(entry)):
self.SetStringItem(pos, i, six.u(entry[i]))
return pos
def SetFirstGradientColour(self, colour=None):
"""
Sets the first gradient colour for gradient-style selections.
:param `colour`: if not ``None``, a valid :class:`wx.Colour` instance. Otherwise,
the colour is taken from the system value ``wx.SYS_COLOUR_HIGHLIGHT``.
"""
self._mainWin.SetFirstGradientColour(colour)
def SetSecondGradientColour(self, colour=None):
"""
Sets the second gradient colour for gradient-style selections.
:param `colour`: if not ``None``, a valid :class:`wx.Colour` instance. Otherwise,
the colour generated is a slightly darker version of the :class:`UltimateListCtrl`
background colour.
"""
self._mainWin.SetSecondGradientColour(colour)
def GetFirstGradientColour(self):
""" Returns the first gradient colour for gradient-style selections. """
return self._mainWin.GetFirstGradientColour()
def GetSecondGradientColour(self):
""" Returns the second gradient colour for gradient-style selections. """
return self._mainWin.GetSecondGradientColour()
def EnableSelectionGradient(self, enable=True):
"""
Globally enables/disables drawing of gradient selections.
:param `enable`: ``True`` to enable gradient-style selections, ``False``
to disable it.
:note: Calling this method disables any Vista-style selection previously
enabled.
"""
self._mainWin.EnableSelectionGradient(enable)
def SetGradientStyle(self, vertical=0):
"""
Sets the gradient style for gradient-style selections.
:param `vertical`: 0 for horizontal gradient-style selections, 1 for vertical
gradient-style selections.
"""
self._mainWin.SetGradientStyle(vertical)
def GetGradientStyle(self):
"""
Returns the gradient style for gradient-style selections.
:return: 0 for horizontal gradient-style selections, 1 for vertical
gradient-style selections.
"""
return self._mainWin.GetGradientStyle()
def EnableSelectionVista(self, enable=True):
"""
Globally enables/disables drawing of Windows Vista selections.
:param `enable`: ``True`` to enable Vista-style selections, ``False`` to
disable it.
:note: Calling this method disables any gradient-style selection previously
enabled.
"""
self._mainWin.EnableSelectionVista(enable)
def SetBackgroundImage(self, image=None):
"""
Sets the :class:`UltimateListCtrl` background image.
:param `image`: if not ``None``, an instance of :class:`wx.Bitmap`.
:note: At present, the background image can only be used in "tile" mode.
.. todo:: Support background images also in stretch and centered modes.
"""
self._mainWin.SetBackgroundImage(image)
def GetBackgroundImage(self):
"""
Returns the :class:`UltimateListCtrl` background image (if any).
:note: At present, the background image can only be used in "tile" mode.
.. todo:: Support background images also in stretch and centered modes.
"""
return self._mainWin.GetBackgroundImage()
def SetWaterMark(self, watermark=None):
"""
Sets the :class:`UltimateListCtrl` watermark image to be displayed in the bottom
right part of the window.
:param `watermark`: if not ``None``, an instance of :class:`wx.Bitmap`.
.. todo:: Better support for this is needed.
"""
self._mainWin.SetWaterMark(watermark)
def GetWaterMark(self):
"""
Returns the :class:`UltimateListCtrl` watermark image (if any), displayed in the
bottom right part of the window.
.. todo:: Better support for this is needed.
"""
return self._mainWin.GetWaterMark()
def SetDisabledTextColour(self, colour):
"""
Sets the items disabled colour.
:param `colour`: an instance of :class:`wx.Colour`.
"""
self._mainWin.SetDisabledTextColour(colour)
def GetDisabledTextColour(self):
""" Returns the items disabled colour. """
return self._mainWin.GetDisabledTextColour()
def GetHyperTextFont(self):
""" Returns the font used to render an hypertext item. """
return self._mainWin.GetHyperTextFont()
def SetHyperTextFont(self, font):
"""
Sets the font used to render hypertext items.
:param `font`: a valid :class:`wx.Font` instance.
"""
self._mainWin.SetHyperTextFont(font)
def SetHyperTextNewColour(self, colour):
"""
Sets the colour used to render a non-visited hypertext item.
:param `colour`: a valid :class:`wx.Colour` instance.
"""
self._mainWin.SetHyperTextNewColour(colour)
def GetHyperTextNewColour(self):
""" Returns the colour used to render a non-visited hypertext item. """
return self._mainWin.GetHyperTextNewColour()
def SetHyperTextVisitedColour(self, colour):
"""
Sets the colour used to render a visited hypertext item.
:param `colour`: a valid :class:`wx.Colour` instance.
"""
self._mainWin.SetHyperTextVisitedColour(colour)
def GetHyperTextVisitedColour(self):
""" Returns the colour used to render a visited hypertext item. """
return self._mainWin.GetHyperTextVisitedColour()
def SetItemVisited(self, itemOrId, col=0, visited=True):
"""
Sets whether an hypertext item was visited or not.
:param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
:param `col`: the column index to which the input item belongs to;
:param `visited`: ``True`` to mark an hypertext item as visited, ``False`` otherwise.
"""
item = CreateListItem(itemOrId, col)
return self._mainWin.SetItemVisited(item, visited)
def GetItemVisited(self, itemOrId, col=0):
"""
Returns whether an hypertext item was visited.
:param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
:param `col`: the column index to which the input item belongs to.
"""
item = CreateListItem(itemOrId, col)
return self._mainWin.GetItemVisited(item)
def GetItemWindow(self, itemOrId, col=0):
"""
Returns the window associated to the item (if any).
:param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
:param `col`: the column index to which the input item belongs to.
"""
item = CreateListItem(itemOrId, col)
return self._mainWin.GetItemWindow(item)
def SetItemWindow(self, itemOrId, col=0, wnd=None, expand=False):
"""
Sets the window for the given item.
:param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
:param `col`: the column index to which the input item belongs to;
:param `wnd`: a non-toplevel window to be displayed next to the item;
:param `expand`: ``True`` to expand the column where the item/subitem lives,
so that the window will be fully visible.
"""
item = CreateListItem(itemOrId, col)
return self._mainWin.SetItemWindow(item, wnd, expand)
def DeleteItemWindow(self, itemOrId, col=0):
"""
Deletes the window associated to an item (if any).
:param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
:param `col`: the column index to which the input item belongs to.
"""
item = CreateListItem(itemOrId, col)
return self._mainWin.DeleteItemWindow(item)
def GetItemWindowEnabled(self, itemOrId, col=0):
"""
Returns whether the window associated to the item is enabled.
:param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
:param `col`: the column index to which the input item belongs to;
"""
item = CreateListItem(itemOrId, col)
return self._mainWin.GetItemWindowEnabled(item)
def SetItemWindowEnabled(self, itemOrId, col=0, enable=True):
"""
Enables/disables the window associated to the item.
:param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
:param `col`: the column index to which the input item belongs to;
:param `enable`: ``True`` to enable the associated window, ``False`` to disable it.
"""
item = CreateListItem(itemOrId, col)
return self._mainWin.SetItemWindowEnabled(item, enable)
def GetItemCustomRenderer(self, itemOrId, col=0):
"""
Returns the custom renderer used to draw the input item (if any).
:param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
:param `col`: the column index to which the input item belongs to.
"""
item = CreateListItem(itemOrId, col)
return self._mainWin.GetItemCustomRenderer(item)
def SetHeaderCustomRenderer(self, renderer=None):
"""
Associate a custom renderer with the header - all columns will use it.
:param `renderer`: a class able to correctly render header buttons
:note: the renderer class **must** implement the methods `DrawHeaderButton`
and `GetForegroundColor`.
"""
if not self.HasAGWFlag(ULC_REPORT):
raise Exception("Custom renderers can be used on with style = ULC_REPORT")
self._headerWin.SetCustomRenderer(renderer)
def SetFooterCustomRenderer(self, renderer=None):
"""
Associate a custom renderer with the footer - all columns will use it.
:param `renderer`: a class able to correctly render header buttons
:note: the renderer class **must** implement the methods `DrawHeaderButton`
and `GetForegroundColor`.
"""
if not self.HasAGWFlag(ULC_REPORT) or not self.HasAGWFlag(ULC_FOOTER):
raise Exception("Custom renderers can only be used on with style = ULC_REPORT | ULC_FOOTER")
self._footerWin.SetCustomRenderer(renderer)
def SetColumnCustomRenderer(self, col=0, renderer=None):
"""
Associate a custom renderer to this column's header.
:param `col`: the column index.
:param `renderer`: a class able to correctly render the input item.
:note: the renderer class **must** implement the methods `DrawHeaderButton`
and `GetForegroundColor`.
"""
if not self.HasAGWFlag(ULC_REPORT):
raise Exception("Custom renderers can be used on with style = ULC_REPORT")
return self._mainWin.SetCustomRenderer(col, renderer)
def SetItemCustomRenderer(self, itemOrId, col=0, renderer=None):
"""
Associate a custom renderer to this item.
:param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
:param `col`: the column index to which the input item belongs to;
:param `renderer`: a class able to correctly render the input item.
:note: the renderer class **must** implement the methods `DrawSubItem`,
`GetLineHeight` and `GetSubItemWidth`.
"""
if not self.HasAGWFlag(ULC_REPORT) or not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
raise Exception("Custom renderers can be used on with style = ULC_REPORT | ULC_HAS_VARIABLE_ROW_HEIGHT")
item = CreateListItem(itemOrId, col)
return self._mainWin.SetItemCustomRenderer(item, renderer)
def SetItemOverFlow(self, itemOrId, col=0, over=True):
"""
Sets the item in the overflow/non overflow state.
An item/subitem may overwrite neighboring items/subitems if its text would
not normally fit in the space allotted to it.
:param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
:param `col`: the column index to which the input item belongs to;
:param `over`: ``True`` to set the item in a overflow state, ``False`` otherwise.
"""
if not self.HasAGWFlag(ULC_REPORT) or self._mainWin.IsVirtual():
raise Exception("Overflowing items can be used only in report, non-virtual mode")
item = CreateListItem(itemOrId, col)
return self._mainWin.SetItemOverFlow(item, over)
def GetItemOverFlow(self, itemOrId, col=0):
"""
Returns if the item is in the overflow state.
An item/subitem may overwrite neighboring items/subitems if its text would
not normally fit in the space allotted to it.
:param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
:param `col`: the column index to which the input item belongs to.
"""
item = CreateListItem(itemOrId, col)
return self._mainWin.GetItemOverFlow(item)
def IsVirtual(self):
""" Returns ``True`` if the :class:`UltimateListCtrl` has the ``ULC_VIRTUAL`` style set. """
return self._mainWin.IsVirtual()
def GetScrollPos(self):
"""
Returns the scrollbar position.
:note: This method is forwarded to :class:`UltimateListMainWindow`.
"""
if self._mainWin:
return self._mainWin.GetScrollPos()
return 0
def SetScrollPos(self, orientation, pos, refresh=True):
"""
Sets the scrollbar position.
:param `orientation`: determines the scrollbar whose position is to be set.
May be ``wx.HORIZONTAL`` or ``wx.VERTICAL``;
:param `pos`: the scrollbar position in scroll units;
:param `refresh`: ``True`` to redraw the scrollbar, ``False`` otherwise.
:note: This method is forwarded to :class:`UltimateListMainWindow`.
"""
if self._mainWin:
self._mainWin.SetScrollPos(orientation, pos, refresh)
def GetScrollThumb(self):
"""
Returns the scrollbar size in pixels.
:note: This method is forwarded to :class:`UltimateListMainWindow`.
"""
if self._mainWin:
return self._mainWin.GetScrollThumb()
return 0
def GetScrollRange(self):
"""
Returns the scrollbar range in pixels.
:note: This method is forwarded to :class:`UltimateListMainWindow`.
"""
if self._mainWin:
return self._mainWin.GetScrollRange()
return 0
def SetHeaderHeight(self, height):
"""
Sets the :class:`UltimateListHeaderWindow` height, in pixels. This overrides the default
header window size derived from :class:`RendererNative`. If `height` is ``None``, the
default behaviour is restored.
:param `height`: the header window height, in pixels (if it is ``None``, the default
height obtained using :class:`RendererNative` is used).
"""
if not self._headerWin:
return
if height is not None and height < 1:
raise Exception("Invalid height passed to SetHeaderHeight: %s"%repr(height))
self._headerWin._headerHeight = height
self.DoLayout()
def GetHeaderHeight(self):
""" Returns the :class:`UltimateListHeaderWindow` height, in pixels. """
if not self._headerWin:
return -1
return self._headerWin.GetWindowHeight()
def SetFooterHeight(self, height):
"""
Sets the :class:`UltimateListHeaderWindow` height, in pixels. This overrides the default
footer window size derived from :class:`RendererNative`. If `height` is ``None``, the
default behaviour is restored.
:param `height`: the footer window height, in pixels (if it is ``None``, the default
height obtained using :class:`RendererNative` is used).
"""
if not self._footerWin:
return
if height is not None and height < 1:
raise Exception("Invalid height passed to SetFooterHeight: %s"%repr(height))
self._footerWin._footerHeight = height
self.DoLayout()
def GetFooterHeight(self):
""" Returns the :class:`UltimateListHeaderWindow` height, in pixels. """
if not self._footerWin:
return -1
return self._headerWin.GetWindowHeight()
def DoLayout(self):
"""
Layouts the header, main and footer windows. This is an auxiliary method to avoid code
duplication.
"""
self.Layout()
self._mainWin.ResizeColumns()
self._mainWin.ResetVisibleLinesRange(True)
self._mainWin.RecalculatePositions()
self._mainWin.AdjustScrollbars()
if self._headerWin:
self._headerWin.Refresh()
if self._footerWin:
self._footerWin.Refresh()
|
gpl-3.0
| -2,917,967,209,524,716,500
| 32.50866
| 459
| 0.561998
| false
| 4.191697
| false
| false
| false
|
rackerlabs/heat-pyrax
|
pyrax/autoscale.py
|
1
|
46139
|
# -*- coding: utf-8 -*-
# Copyright (c)2013 Rackspace US, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import base64
import pyrax
from pyrax.client import BaseClient
from pyrax.cloudloadbalancers import CloudLoadBalancer
import pyrax.exceptions as exc
from pyrax.manager import BaseManager
from pyrax.resource import BaseResource
import pyrax.utils as utils
class ScalingGroup(BaseResource):
def __init__(self, *args, **kwargs):
super(ScalingGroup, self).__init__(*args, **kwargs)
self._non_display = ["active", "launchConfiguration", "links",
"groupConfiguration", "policies", "scalingPolicies"]
self._repr_properties = ["name", "cooldown", "metadata",
"min_entities", "max_entities"]
self._make_policies()
def _make_policies(self):
"""
Convert the 'scalingPolicies' dictionary into AutoScalePolicy objects.
"""
self.policies = [AutoScalePolicy(self.manager, dct, self)
for dct in self.scalingPolicies]
def get_state(self):
"""
Returns the current state of this scaling group.
"""
return self.manager.get_state(self)
def pause(self):
"""
Pauses all execution of the policies for this scaling group.
"""
return self.manager.pause(self)
def resume(self):
"""
Resumes execution of the policies for this scaling group.
"""
return self.manager.resume(self)
def update(self, name=None, cooldown=None, min_entities=None,
max_entities=None, metadata=None):
"""
Updates this ScalingGroup. One or more of the attributes can be
specified.
NOTE: if you specify metadata, it will *replace* any existing metadata.
If you want to add to it, you either need to pass the complete dict of
metadata, or call the update_metadata() method.
"""
return self.manager.update(self, name=name,
cooldown=cooldown, min_entities=min_entities,
max_entities=max_entities, metadata=metadata)
def update_metadata(self, metadata):
"""
Adds the given metadata dict to the existing metadata for this scaling
group.
"""
return self.manager.update_metadata(self, metadata=metadata)
def get_configuration(self):
"""
Returns the scaling group configuration in a dictionary.
"""
return self.manager.get_configuration(self)
def get_launch_config(self):
"""
Returns the launch configuration for this scaling group.
"""
return self.manager.get_launch_config(self)
def update_launch_config(self, scaling_group, launch_config_type,
**kwargs):
"""
Updates the server launch configuration for this scaling group.
One or more of the available attributes can be specified.
NOTE: if you specify metadata, it will *replace* any existing metadata.
If you want to add to it, you either need to pass the complete dict of
metadata, or call the update_launch_metadata() method.
"""
return self.manager.update_launch_config(scaling_group,
launch_config_type, **kwargs)
def update_launch_metadata(self, metadata):
"""
Adds the given metadata dict to the existing metadata for this scaling
group's launch configuration.
"""
return self.manager.update_launch_metadata(self, metadata)
def add_policy(self, name, policy_type, cooldown, change=None,
is_percent=False, desired_capacity=None, args=None):
"""
Adds a policy with the given values to this scaling group. The
'change' parameter is treated as an absolute amount, unless
'is_percent' is True, in which case it is treated as a percentage.
"""
return self.manager.add_policy(self, name, policy_type, cooldown,
change=change, is_percent=is_percent,
desired_capacity=desired_capacity, args=args)
def list_policies(self):
"""
Returns a list of all policies defined for this scaling group.
"""
return self.manager.list_policies(self)
def get_policy(self, policy):
"""
Gets the detail for the specified policy.
"""
return self.manager.get_policy(self, policy)
def update_policy(self, policy, name=None, policy_type=None, cooldown=None,
change=None, is_percent=False, desired_capacity=None, args=None):
"""
Updates the specified policy. One or more of the parameters may be
specified.
"""
return self.manager.update_policy(scaling_group=self, policy=policy,
name=name, policy_type=policy_type, cooldown=cooldown,
change=change, is_percent=is_percent,
desired_capacity=desired_capacity, args=args)
def execute_policy(self, policy):
"""
Executes the specified policy for this scaling group.
"""
return self.manager.execute_policy(scaling_group=self, policy=policy)
def delete_policy(self, policy):
"""
Deletes the specified policy from this scaling group.
"""
return self.manager.delete_policy(scaling_group=self, policy=policy)
def add_webhook(self, policy, name, metadata=None):
"""
Adds a webhook to the specified policy.
"""
return self.manager.add_webhook(self, policy, name, metadata=metadata)
def list_webhooks(self, policy):
"""
Returns a list of all webhooks for the specified policy.
"""
return self.manager.list_webhooks(self, policy)
def update_webhook(self, policy, webhook, name=None, metadata=None):
"""
Updates the specified webhook. One or more of the parameters may be
specified.
"""
return self.manager.update_webhook(scaling_group=self, policy=policy,
webhook=webhook, name=name, metadata=metadata)
def update_webhook_metadata(self, policy, webhook, metadata):
"""
Adds the given metadata dict to the existing metadata for the specified
webhook.
"""
return self.manager.update_webhook_metadata(self, policy, webhook,
metadata)
def delete_webhook(self, policy, webhook):
"""
Deletes the specified webhook from the specified policy.
"""
return self.manager.delete_webhook(self, policy, webhook)
@property
def policy_count(self):
return len(self.policies)
##################################################################
# The following property declarations allow access to the base attributes
# of the ScalingGroup held in the 'groupConfiguration' dict as if they
# were native attributes.
##################################################################
@property
def name(self):
return self.groupConfiguration.get("name")
@name.setter
def name(self, val):
self.groupConfiguration["name"] = val
@property
def cooldown(self):
return self.groupConfiguration.get("cooldown")
@cooldown.setter
def cooldown(self, val):
self.groupConfiguration["cooldown"] = val
@property
def metadata(self):
return self.groupConfiguration.get("metadata")
@metadata.setter
def metadata(self, val):
self.groupConfiguration["metadata"] = val
@property
def min_entities(self):
return self.groupConfiguration.get("minEntities")
@min_entities.setter
def min_entities(self, val):
self.groupConfiguration["minEntities"] = val
@property
def max_entities(self):
return self.groupConfiguration.get("maxEntities")
@max_entities.setter
def max_entities(self, val):
self.groupConfiguration["maxEntities"] = val
##################################################################
class ScalingGroupManager(BaseManager):
def __init__(self, api, resource_class=None, response_key=None,
plural_response_key=None, uri_base=None):
super(ScalingGroupManager, self).__init__(api,
resource_class=resource_class, response_key=response_key,
plural_response_key=plural_response_key, uri_base=uri_base)
def get_state(self, scaling_group):
"""
Returns the current state of the specified scaling group as a
dictionary.
"""
uri = "/%s/%s/state" % (self.uri_base, utils.get_id(scaling_group))
resp, resp_body = self.api.method_get(uri)
data = resp_body["group"]
ret = {}
ret["active"] = [itm["id"] for itm in data["active"]]
ret["active_capacity"] = data["activeCapacity"]
ret["desired_capacity"] = data["desiredCapacity"]
ret["pending_capacity"] = data["pendingCapacity"]
ret["paused"] = data["paused"]
return ret
def pause(self, scaling_group):
"""
Pauses all execution of the policies for the specified scaling group.
"""
uri = "/%s/%s/pause" % (self.uri_base, utils.get_id(scaling_group))
resp, resp_body = self.api.method_post(uri)
return None
def resume(self, scaling_group):
"""
Resumes execution of the policies for the specified scaling group.
"""
uri = "/%s/%s/resume" % (self.uri_base, utils.get_id(scaling_group))
resp, resp_body = self.api.method_post(uri)
return None
def get_configuration(self, scaling_group):
"""
Returns the scaling group's configuration in a dictionary.
"""
uri = "/%s/%s/config" % (self.uri_base, utils.get_id(scaling_group))
resp, resp_body = self.api.method_get(uri)
return resp_body.get("groupConfiguration")
def replace(self, scaling_group, name, cooldown, min_entities,
max_entities, metadata=None):
"""
Replace an existing ScalingGroup configuration. All of the attributes
must be specified If you wish to delete any of the optional attributes,
pass them in as None.
"""
body = self._create_group_config_body(name, cooldown, min_entities,
max_entities, metadata=metadata)
group_id = utils.get_id(scaling_group)
uri = "/%s/%s/config" % (self.uri_base, group_id)
resp, resp_body = self.api.method_put(uri, body=body)
def update(self, scaling_group, name=None, cooldown=None,
min_entities=None, max_entities=None, metadata=None):
"""
Updates an existing ScalingGroup. One or more of the attributes can
be specified.
NOTE: if you specify metadata, it will *replace* any existing metadata.
If you want to add to it, you either need to pass the complete dict of
metadata, or call the update_metadata() method.
"""
if not isinstance(scaling_group, ScalingGroup):
scaling_group = self.get(scaling_group)
uri = "/%s/%s/config" % (self.uri_base, scaling_group.id)
if cooldown is None:
cooldown = scaling_group.cooldown
if min_entities is None:
min_entities = scaling_group.min_entities
if max_entities is None:
max_entities = scaling_group.max_entities
body = {"name": name or scaling_group.name,
"cooldown": cooldown,
"minEntities": min_entities,
"maxEntities": max_entities,
"metadata": metadata or scaling_group.metadata,
}
resp, resp_body = self.api.method_put(uri, body=body)
return None
def update_metadata(self, scaling_group, metadata):
"""
Adds the given metadata dict to the existing metadata for the scaling
group.
"""
if not isinstance(scaling_group, ScalingGroup):
scaling_group = self.get(scaling_group)
curr_meta = scaling_group.metadata
curr_meta.update(metadata)
return self.update(scaling_group, metadata=curr_meta)
def get_launch_config(self, scaling_group):
"""
Returns the launch configuration for the specified scaling group.
"""
uri = "/%s/%s/launch" % (self.uri_base, utils.get_id(scaling_group))
resp, resp_body = self.api.method_get(uri)
ret = {}
data = resp_body.get("launchConfiguration")
ret["type"] = data.get("type")
args = data.get("args", {})
if ret['type'] == 'launch_server':
key_map = {
"OS-DCF:diskConfig": "disk_config",
"flavorRef": "flavor",
"imageRef": "image",
}
ret['args'] = {}
ret['args']["load_balancers"] = args.get("loadBalancers")
for key, value in args.get("server", {}).items():
norm_key = key_map.get(key, key)
ret['args'][norm_key] = value
elif ret['type'] == 'launch_stack':
ret['args'] = args.get("stack", {})
return ret
def replace_launch_config(self, scaling_group, launch_config_type,
**kwargs):
"""
Replace an existing launch configuration. All of the attributes must be
specified. If you wish to delete any of the optional attributes, pass
them in as None.
"""
group_id = utils.get_id(scaling_group)
uri = "/%s/%s/launch" % (self.uri_base, group_id)
body = self._create_launch_config_body(launch_config_type,
**kwargs)
resp, resp_body = self.api.method_put(uri, body=body)
def _update_server_launch_config_body(
self, scaling_group, server_name=None, image=None, flavor=None,
disk_config=None, metadata=None, personality=None, networks=None,
load_balancers=None, key_name=None, config_drive=False,
user_data=None):
if not isinstance(scaling_group, ScalingGroup):
scaling_group = self.get(scaling_group)
largs = scaling_group.launchConfiguration.get("args", {})
srv_args = largs.get("server", {})
lb_args = largs.get("loadBalancers", {})
flav = flavor or srv_args.get("flavorRef")
dconf = disk_config or srv_args.get("OS-DCF:diskConfig", "AUTO")
if personality is None:
personality = srv_args.get("personality", [])
cfg_drv = config_drive or srv_args.get("config_drive")
if user_data:
user_data = base64.b64encode(user_data)
usr_data = user_data or srv_args.get("user_data")
update_metadata = metadata or srv_args.get("metadata")
body = {"type": "launch_server",
"args": {
"server": {
"name": server_name or srv_args.get("name"),
"imageRef": image or srv_args.get("imageRef"),
"flavorRef": flav,
"OS-DCF:diskConfig": dconf,
"networks": networks or srv_args.get("networks"),
},
"loadBalancers": load_balancers or lb_args,
},
}
bas = body["args"]["server"]
if cfg_drv:
bas["config_drive"] = cfg_drv
if usr_data:
bas["user_data"] = usr_data
if personality:
bas["personality"] = self._encode_personality(personality)
if update_metadata:
bas["metadata"] = update_metadata
key_name = key_name or srv_args.get("key_name")
if key_name:
bas["key_name"] = key_name
return body
def _update_stack_launch_config_body(self, **kwargs):
return self._create_stack_launch_config_body(**kwargs)
def update_launch_config(self, scaling_group, launch_config_type,
**kwargs):
"""
Updates the server launch configuration for an existing scaling group.
One or more of the available attributes can be specified.
NOTE: if you specify metadata, it will *replace* any existing metadata.
If you want to add to it, you either need to pass the complete dict of
metadata, or call the update_launch_metadata() method.
"""
uri = "/%s/%s/launch" % (self.uri_base, scaling_group.id)
if launch_config_type == 'launch_server':
body = self._update_server_launch_config_body(
scaling_group=scaling_group, **kwargs)
elif launch_config_type == 'launch_stack':
body = self._update_stack_launch_config_body(**kwargs)
resp, resp_body = self.api.method_put(uri, body=body)
def update_launch_metadata(self, scaling_group, metadata):
"""
Adds the given metadata dict to the existing metadata for the scaling
group's launch configuration.
"""
if not isinstance(scaling_group, ScalingGroup):
scaling_group = self.get(scaling_group)
curr_meta = scaling_group.launchConfiguration.get("args", {}).get(
"server", {}).get("metadata", {})
curr_meta.update(metadata)
return self.update_launch_config(scaling_group, metadata=curr_meta)
def add_policy(self, scaling_group, name, policy_type, cooldown,
change=None, is_percent=False, desired_capacity=None, args=None):
"""
Adds a policy with the given values to the specified scaling group. The
'change' parameter is treated as an absolute amount, unless
'is_percent' is True, in which case it is treated as a percentage.
"""
uri = "/%s/%s/policies" % (self.uri_base, utils.get_id(scaling_group))
body = self._create_policy_body(name, policy_type, cooldown,
change=change, is_percent=is_percent,
desired_capacity=desired_capacity, args=args)
# "body" needs to be a list
body = [body]
resp, resp_body = self.api.method_post(uri, body=body)
pol_info = resp_body.get("policies")[0]
return AutoScalePolicy(self, pol_info, scaling_group)
def _create_policy_body(self, name, policy_type, cooldown, change=None,
is_percent=None, desired_capacity=None, args=None):
body = {"name": name, "cooldown": cooldown, "type": policy_type}
if change is not None:
if is_percent:
body["changePercent"] = change
else:
body["change"] = change
if desired_capacity is not None:
body["desiredCapacity"] = desired_capacity
if args is not None:
body["args"] = args
return body
def list_policies(self, scaling_group):
"""
Returns a list of all policies defined for the specified scaling group.
"""
uri = "/%s/%s/policies" % (self.uri_base, utils.get_id(scaling_group))
resp, resp_body = self.api.method_get(uri)
return [AutoScalePolicy(self, data, scaling_group)
for data in resp_body.get("policies", [])]
def get_policy(self, scaling_group, policy):
"""
Gets the detail for the specified policy.
"""
uri = "/%s/%s/policies/%s" % (self.uri_base,
utils.get_id(scaling_group), utils.get_id(policy))
resp, resp_body = self.api.method_get(uri)
data = resp_body.get("policy")
return AutoScalePolicy(self, data, scaling_group)
def replace_policy(self, scaling_group, policy, name,
policy_type, cooldown, change=None, is_percent=False,
desired_capacity=None, args=None):
"""
Replace an existing policy. All of the attributes must be specified. If
you wish to delete any of the optional attributes, pass them in as
None.
"""
policy_id = utils.get_id(policy)
group_id = utils.get_id(scaling_group)
uri = "/%s/%s/policies/%s" % (self.uri_base, group_id, policy_id)
body = self._create_policy_body(name=name, policy_type=policy_type,
cooldown=cooldown, change=change, is_percent=is_percent,
desired_capacity=desired_capacity, args=args)
resp, resp_body = self.api.method_put(uri, body=body)
def update_policy(self, scaling_group, policy, name=None, policy_type=None,
cooldown=None, change=None, is_percent=False,
desired_capacity=None, args=None):
"""
Updates the specified policy. One or more of the parameters may be
specified.
"""
uri = "/%s/%s/policies/%s" % (self.uri_base,
utils.get_id(scaling_group), utils.get_id(policy))
if not isinstance(policy, AutoScalePolicy):
# Received an ID
policy = self.get_policy(scaling_group, policy)
body = {"name": name or policy.name,
"type": policy_type or policy.type,
"cooldown": cooldown or policy.cooldown,
}
if desired_capacity is not None:
body["desiredCapacity"] = desired_capacity
elif change is not None:
if is_percent:
body["changePercent"] = change
else:
body["change"] = change
else:
if getattr(policy, "changePercent", None) is not None:
body["changePercent"] = policy.changePercent
elif getattr(policy, "change", None) is not None:
body["change"] = policy.change
elif getattr(policy, "desiredCapacity", None) is not None:
body["desiredCapacity"] = policy.desiredCapacity
args = args or getattr(policy, "args", None)
if args is not None:
body["args"] = args
resp, resp_body = self.api.method_put(uri, body=body)
return None
def execute_policy(self, scaling_group, policy):
"""
Executes the specified policy for this scaling group.
"""
uri = "/%s/%s/policies/%s/execute" % (self.uri_base,
utils.get_id(scaling_group), utils.get_id(policy))
resp, resp_body = self.api.method_post(uri)
return None
def delete_policy(self, scaling_group, policy):
"""
Deletes the specified policy from the scaling group.
"""
uri = "/%s/%s/policies/%s" % (self.uri_base,
utils.get_id(scaling_group), utils.get_id(policy))
resp, resp_body = self.api.method_delete(uri)
def _create_webhook_body(self, name, metadata=None):
if metadata is None:
# If updating a group with existing metadata, metadata MUST be
# passed. Leaving it out causes Otter to return 400.
metadata = {}
body = {"name": name, "metadata": metadata}
return body
def add_webhook(self, scaling_group, policy, name, metadata=None):
"""
Adds a webhook to the specified policy.
"""
uri = "/%s/%s/policies/%s/webhooks" % (self.uri_base,
utils.get_id(scaling_group), utils.get_id(policy))
body = self._create_webhook_body(name, metadata=metadata)
# "body" needs to be a list
body = [body]
resp, resp_body = self.api.method_post(uri, body=body)
data = resp_body.get("webhooks")[0]
return AutoScaleWebhook(self, data, policy, scaling_group)
def list_webhooks(self, scaling_group, policy):
"""
Returns a list of all webhooks for the specified policy.
"""
uri = "/%s/%s/policies/%s/webhooks" % (self.uri_base,
utils.get_id(scaling_group), utils.get_id(policy))
resp, resp_body = self.api.method_get(uri)
return [AutoScaleWebhook(self, data, policy, scaling_group)
for data in resp_body.get("webhooks", [])]
def get_webhook(self, scaling_group, policy, webhook):
"""
Gets the detail for the specified webhook.
"""
uri = "/%s/%s/policies/%s/webhooks/%s" % (self.uri_base,
utils.get_id(scaling_group), utils.get_id(policy),
utils.get_id(webhook))
resp, resp_body = self.api.method_get(uri)
data = resp_body.get("webhook")
return AutoScaleWebhook(self, data, policy, scaling_group)
def replace_webhook(self, scaling_group, policy, webhook, name,
metadata=None):
"""
Replace an existing webhook. All of the attributes must be specified.
If you wish to delete any of the optional attributes, pass them in as
None.
"""
uri = "/%s/%s/policies/%s/webhooks/%s" % (self.uri_base,
utils.get_id(scaling_group), utils.get_id(policy),
utils.get_id(webhook))
group_id = utils.get_id(scaling_group)
policy_id = utils.get_id(policy)
webhook_id = utils.get_id(webhook)
body = self._create_webhook_body(name, metadata=metadata)
resp, resp_body = self.api.method_put(uri, body=body)
def update_webhook(self, scaling_group, policy, webhook, name=None,
metadata=None):
"""
Updates the specified webhook. One or more of the parameters may be
specified.
"""
uri = "/%s/%s/policies/%s/webhooks/%s" % (self.uri_base,
utils.get_id(scaling_group), utils.get_id(policy),
utils.get_id(webhook))
if not isinstance(webhook, AutoScaleWebhook):
# Received an ID
webhook = self.get_webhook(scaling_group, policy, webhook)
body = {"name": name or webhook.name,
"metadata": metadata or webhook.metadata,
}
resp, resp_body = self.api.method_put(uri, body=body)
webhook.reload()
return webhook
def update_webhook_metadata(self, scaling_group, policy, webhook, metadata):
"""
Adds the given metadata dict to the existing metadata for the specified
webhook.
"""
if not isinstance(webhook, AutoScaleWebhook):
webhook = self.get_webhook(scaling_group, policy, webhook)
curr_meta = webhook.metadata or {}
curr_meta.update(metadata)
return self.update_webhook(scaling_group, policy, webhook,
metadata=curr_meta)
def delete_webhook(self, scaling_group, policy, webhook):
"""
Deletes the specified webhook from the specified policy.
"""
uri = "/%s/%s/policies/%s/webhooks/%s" % (self.uri_base,
utils.get_id(scaling_group), utils.get_id(policy),
utils.get_id(webhook))
resp, resp_body = self.api.method_delete(uri)
return None
@staticmethod
def _resolve_lbs(load_balancers):
"""
Takes either a single LB reference or a list of references and returns
the dictionary required for creating a Scaling Group.
References can be either a dict that matches the structure required by
the autoscale API, a CloudLoadBalancer instance, or the ID of the load
balancer.
"""
lb_args = []
if not isinstance(load_balancers, list):
lbs = [load_balancers]
else:
lbs = load_balancers
for lb in lbs:
if isinstance(lb, dict):
lb_args.append(lb)
elif isinstance(lb, CloudLoadBalancer):
lb_args.append({
"loadBalancerId": lb.id,
"port": lb.port,
})
elif isinstance(lb, tuple):
lb_args.append({"loadBalancerId": lb[0],
"port": lb[1]})
else:
# See if it's an ID for a Load Balancer
try:
instance = pyrax.cloud_loadbalancers.get(lb)
except Exception:
raise exc.InvalidLoadBalancer("Received an invalid "
"specification for a Load Balancer: '%s'" % lb)
lb_args.append({
"loadBalancerId": instance.id,
"port": instance.port,
})
return lb_args
def _encode_personality(self, personality):
"""
Personality files must be base64-encoded before transmitting.
"""
if personality is None:
personality = []
else:
personality = utils.coerce_to_list(personality)
for pfile in personality:
if "contents" in pfile:
pfile["contents"] = base64.b64encode(pfile["contents"])
return personality
def _create_launch_config_body(self, launch_config_type, **kwargs):
if launch_config_type == 'launch_server':
return self._create_server_launch_config_body(**kwargs)
elif launch_config_type == 'launch_stack':
return self._create_stack_launch_config_body(**kwargs)
def _create_body(self, name, cooldown, min_entities, max_entities,
launch_config_type, group_metadata=None,
scaling_policies=None, **kwargs):
"""
Used to create the dict required to create any of the following:
A Scaling Group
"""
group_config = self._create_group_config_body(
name, cooldown, min_entities, max_entities,
metadata=group_metadata)
if scaling_policies is None:
scaling_policies = []
launch_config = self._create_launch_config_body(launch_config_type,
**kwargs)
body = {
"groupConfiguration": group_config,
"launchConfiguration": launch_config,
"scalingPolicies": scaling_policies,
}
return body
def _create_group_config_body(self, name, cooldown, min_entities,
max_entities, metadata=None):
if metadata is None:
# If updating a group with existing metadata, metadata MUST be
# passed. Leaving it out causes Otter to return 400.
metadata = {}
body = {
"name": name,
"cooldown": cooldown,
"minEntities": min_entities,
"maxEntities": max_entities,
"metadata": metadata,
}
return body
def _create_stack_launch_config_body(
self, template=None, template_url=None, disable_rollback=True,
environment=None, files=None, parameters=None, timeout_mins=None):
st_args = {
'template': template,
'template_url': template_url,
'disable_rollback': disable_rollback,
'environment': environment,
'files': files,
'parameters': parameters,
'timeout_mins': timeout_mins
}
st_args = {
k: st_args[k] for k in st_args if st_args[k] is not None}
return {"type": 'launch_stack', "args": {"stack": st_args}}
def _create_server_launch_config_body(
self, server_name=None, image=None, flavor=None, disk_config=None,
metadata=None, personality=None, networks=None,
load_balancers=None, key_name=None, config_drive=False,
user_data=None):
if metadata is None:
metadata = {}
server_args = {
"flavorRef": "%s" % flavor,
"name": server_name,
"imageRef": utils.get_id(image),
}
if metadata is not None:
server_args["metadata"] = metadata
if personality is not None:
server_args["personality"] = self._encode_personality(personality)
if networks is not None:
server_args["networks"] = networks
if disk_config is not None:
server_args["OS-DCF:diskConfig"] = disk_config
if key_name is not None:
server_args["key_name"] = key_name
if config_drive is not False:
server_args['config_drive'] = config_drive
if user_data is not None:
server_args['user_data'] = base64.b64encode(user_data)
if load_balancers is None:
load_balancers = []
load_balancer_args = self._resolve_lbs(load_balancers)
return {"type": 'launch_server',
"args": {"server": server_args,
"loadBalancers": load_balancer_args}}
class AutoScalePolicy(BaseResource):
def __init__(self, manager, info, scaling_group, *args, **kwargs):
super(AutoScalePolicy, self).__init__(manager, info, *args, **kwargs)
if not isinstance(scaling_group, ScalingGroup):
scaling_group = manager.get(scaling_group)
self.scaling_group = scaling_group
self._non_display = ["links", "scaling_group"]
def get(self):
"""
Gets the details for this policy.
"""
return self.manager.get_policy(self.scaling_group, self)
reload = get
def delete(self):
"""
Deletes this policy.
"""
return self.manager.delete_policy(self.scaling_group, self)
def update(self, name=None, policy_type=None, cooldown=None, change=None,
is_percent=False, desired_capacity=None, args=None):
"""
Updates this policy. One or more of the parameters may be
specified.
"""
return self.manager.update_policy(scaling_group=self.scaling_group,
policy=self, name=name, policy_type=policy_type,
cooldown=cooldown, change=change, is_percent=is_percent,
desired_capacity=desired_capacity, args=args)
def execute(self):
"""
Executes this policy.
"""
return self.manager.execute_policy(self.scaling_group, self)
def add_webhook(self, name, metadata=None):
"""
Adds a webhook to this policy.
"""
return self.manager.add_webhook(self.scaling_group, self, name,
metadata=metadata)
def list_webhooks(self):
"""
Returns a list of all webhooks for this policy.
"""
return self.manager.list_webhooks(self.scaling_group, self)
def get_webhook(self, webhook):
"""
Gets the detail for the specified webhook.
"""
return self.manager.get_webhook(self.scaling_group, self, webhook)
def update_webhook(self, webhook, name=None, metadata=None):
"""
Updates the specified webhook. One or more of the parameters may be
specified.
"""
return self.manager.update_webhook(self.scaling_group, policy=self,
webhook=webhook, name=name, metadata=metadata)
def update_webhook_metadata(self, webhook, metadata):
"""
Adds the given metadata dict to the existing metadata for the specified
webhook.
"""
return self.manager.update_webhook_metadata(self.scaling_group, self,
webhook, metadata)
def delete_webhook(self, webhook):
"""
Deletes the specified webhook from this policy.
"""
return self.manager.delete_webhook(self.scaling_group, self, webhook)
class AutoScaleWebhook(BaseResource):
def __init__(self, manager, info, policy, scaling_group, *args, **kwargs):
super(AutoScaleWebhook, self).__init__(manager, info, *args, **kwargs)
if not isinstance(policy, AutoScalePolicy):
policy = manager.get_policy(scaling_group, policy)
self.policy = policy
self._non_display = ["links", "policy"]
def get(self):
return self.policy.get_webhook(self)
reload = get
def update(self, name=None, metadata=None):
"""
Updates this webhook. One or more of the parameters may be specified.
"""
return self.policy.update_webhook(self, name=name, metadata=metadata)
def update_metadata(self, metadata):
"""
Adds the given metadata dict to the existing metadata for this webhook.
"""
return self.policy.update_webhook_metadata(self, metadata)
def delete(self):
"""
Deletes this webhook.
"""
return self.policy.delete_webhook(self)
class AutoScaleClient(BaseClient):
"""
This is the primary class for interacting with AutoScale.
"""
name = "Autoscale"
def _configure_manager(self):
"""
Creates a manager to handle autoscale operations.
"""
self._manager = ScalingGroupManager(self,
resource_class=ScalingGroup, response_key="group",
uri_base="groups")
def get_state(self, scaling_group):
"""
Returns the current state of the specified scaling group.
"""
return self._manager.get_state(scaling_group)
def pause(self, scaling_group):
"""
Pauses all execution of the policies for the specified scaling group.
"""
# NOTE: This is not yet implemented. The code is based on the docs,
# so it should either work or be pretty close.
return self._manager.pause(scaling_group)
def resume(self, scaling_group):
"""
Resumes execution of the policies for the specified scaling group.
"""
# NOTE: This is not yet implemented. The code is based on the docs,
# so it should either work or be pretty close.
return self._manager.resume(scaling_group)
def replace(self, scaling_group, name, cooldown, min_entities,
max_entities, metadata=None):
"""
Replace an existing ScalingGroup configuration. All of the attributes
must be specified. If you wish to delete any of the optional
attributes, pass them in as None.
"""
return self._manager.replace(scaling_group, name, cooldown,
min_entities, max_entities, metadata=metadata)
def update(self, scaling_group, name=None, cooldown=None, min_entities=None,
max_entities=None, metadata=None):
"""
Updates an existing ScalingGroup. One or more of the attributes can be
specified.
NOTE: if you specify metadata, it will *replace* any existing metadata.
If you want to add to it, you either need to pass the complete dict of
metadata, or call the update_metadata() method.
"""
return self._manager.update(scaling_group, name=name, cooldown=cooldown,
min_entities=min_entities, max_entities=max_entities,
metadata=metadata)
def update_metadata(self, scaling_group, metadata):
"""
Adds the given metadata dict to the existing metadata for the scaling
group.
"""
return self._manager.update_metadata(scaling_group, metadata)
def get_configuration(self, scaling_group):
"""
Returns the scaling group's configuration in a dictionary.
"""
return self._manager.get_configuration(scaling_group)
def get_launch_config(self, scaling_group):
"""
Returns the launch configuration for the specified scaling group.
"""
return self._manager.get_launch_config(scaling_group)
def replace_launch_config(self, scaling_group, launch_config_type,
**kwargs):
"""
Replace an existing launch configuration. All of the attributes must be
specified. If you wish to delete any of the optional attributes, pass
them in as None.
"""
return self._manager.replace_launch_config(scaling_group,
launch_config_type, **kwargs)
def update_launch_config(self, scaling_group, launch_config_type,
**kwargs):
"""
Updates the server launch configuration for an existing scaling group.
One or more of the available attributes can be specified.
NOTE: if you specify metadata, it will *replace* any existing metadata.
If you want to add to it, you either need to pass the complete dict of
metadata, or call the update_launch_metadata() method.
"""
return self._manager.update_launch_config(
scaling_group, launch_config_type, **kwargs)
def update_launch_metadata(self, scaling_group, metadata):
"""
Adds the given metadata dict to the existing metadata for the scaling
group's launch configuration.
"""
return self._manager.update_launch_metadata(scaling_group, metadata)
def add_policy(self, scaling_group, name, policy_type, cooldown,
change=None, is_percent=False, desired_capacity=None, args=None):
"""
Adds a policy with the given values to the specified scaling group. The
'change' parameter is treated as an absolute amount, unless
'is_percent' is True, in which case it is treated as a percentage.
"""
return self._manager.add_policy(scaling_group, name, policy_type,
cooldown, change=change, is_percent=is_percent,
desired_capacity=desired_capacity, args=args)
def list_policies(self, scaling_group):
"""
Returns a list of all policies defined for the specified scaling group.
"""
return self._manager.list_policies(scaling_group)
def get_policy(self, scaling_group, policy):
"""
Gets the detail for the specified policy.
"""
return self._manager.get_policy(scaling_group, policy)
def replace_policy(self, scaling_group, policy, name,
policy_type, cooldown, change=None, is_percent=False,
desired_capacity=None, args=None):
"""
Replace an existing policy. All of the attributes must be specified. If
you wish to delete any of the optional attributes, pass them in as
None.
"""
return self._manager.replace_policy(scaling_group, policy, name,
policy_type, cooldown, change=change, is_percent=is_percent,
desired_capacity=desired_capacity, args=args)
def update_policy(self, scaling_group, policy, name=None, policy_type=None,
cooldown=None, change=None, is_percent=False,
desired_capacity=None, args=None):
"""
Updates the specified policy. One or more of the parameters may be
specified.
"""
return self._manager.update_policy(scaling_group, policy, name=name,
policy_type=policy_type, cooldown=cooldown, change=change,
is_percent=is_percent, desired_capacity=desired_capacity,
args=args)
def execute_policy(self, scaling_group, policy):
"""
Executes the specified policy for the scaling group.
"""
return self._manager.execute_policy(scaling_group=scaling_group,
policy=policy)
def delete_policy(self, scaling_group, policy):
"""
Deletes the specified policy from the scaling group.
"""
return self._manager.delete_policy(scaling_group=scaling_group,
policy=policy)
def add_webhook(self, scaling_group, policy, name, metadata=None):
"""
Adds a webhook to the specified policy.
"""
return self._manager.add_webhook(scaling_group, policy, name,
metadata=metadata)
def list_webhooks(self, scaling_group, policy):
"""
Returns a list of all webhooks defined for the specified policy.
"""
return self._manager.list_webhooks(scaling_group, policy)
def get_webhook(self, scaling_group, policy, webhook):
"""
Gets the detail for the specified webhook.
"""
return self._manager.get_webhook(scaling_group, policy, webhook)
def replace_webhook(self, scaling_group, policy, webhook, name,
metadata=None):
"""
Replace an existing webhook. All of the attributes must be specified.
If you wish to delete any of the optional attributes, pass them in as
None.
"""
return self._manager.replace_webhook(scaling_group, policy, webhook,
name, metadata=metadata)
def update_webhook(self, scaling_group, policy, webhook, name=None,
metadata=None):
"""
Updates the specified webhook. One or more of the parameters may be
specified.
"""
return self._manager.update_webhook(scaling_group=scaling_group,
policy=policy, webhook=webhook, name=name, metadata=metadata)
def update_webhook_metadata(self, scaling_group, policy, webhook, metadata):
"""
Adds the given metadata dict to the existing metadata for the specified
webhook.
"""
return self._manager.update_webhook_metadata(scaling_group, policy,
webhook, metadata)
def delete_webhook(self, scaling_group, policy, webhook):
"""
Deletes the specified webhook from the policy.
"""
return self._manager.delete_webhook(scaling_group, policy, webhook)
|
apache-2.0
| -1,451,871,668,392,427,000
| 35.531275
| 80
| 0.592731
| false
| 4.265021
| true
| false
| false
|
gplepage/lsqfit
|
examples/p-corr.py
|
1
|
1909
|
"""
p-corr.py - Code for "Correlated Parameters"
"""
# Copyright (c) 2017-20 G. Peter Lepage.
#
# 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 3 of the License, or
# any later version (see <http://www.gnu.org/licenses/>).
#
# This program 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.
from __future__ import print_function # makes this work for python2 and 3
import sys
import numpy as np
import gvar as gv
import lsqfit
if sys.argv[1:]:
SHOW_PLOT = eval(sys.argv[1]) # display picture of grid ?
else:
SHOW_PLOT = True
if SHOW_PLOT:
try:
import matplotlib
except ImportError:
SHOW_PLOT = False
def main():
x, y = make_data()
prior = make_prior()
fit = lsqfit.nonlinear_fit(prior=prior, data=(x,y), fcn=fcn)
print(fit)
print('p1/p0 =', fit.p[1] / fit.p[0], 'p3/p2 =', fit.p[3] / fit.p[2])
print('corr(p0,p1) = {:.4f}'.format(gv.evalcorr(fit.p[:2])[1,0]))
if SHOW_PLOT:
fit.qqplot_residuals().show()
def make_data():
x = np.array([
4., 2., 1., 0.5, 0.25, 0.167, 0.125, 0.1, 0.0833, 0.0714, 0.0625
])
y = gv.gvar([
'0.198(14)', '0.216(15)', '0.184(23)', '0.156(44)', '0.099(49)',
'0.142(40)', '0.108(32)', '0.065(26)', '0.044(22)', '0.041(19)',
'0.044(16)'
])
return x, y
def make_prior():
p = gv.gvar(['0(1)', '0(1)', '0(1)', '0(1)'])
p[1] = 20 * p[0] + gv.gvar('0.0(1)') # p[1] correlated with p[0]
return p
def fcn(x, p):
return (p[0] * (x**2 + p[1] * x)) / (x**2 + x * p[2] + p[3])
if __name__ == '__main__':
main()
|
gpl-3.0
| -3,654,074,718,163,940,400
| 28.369231
| 75
| 0.584075
| false
| 2.723252
| false
| false
| false
|
cpatrick/comic-django
|
django/filetransfers/views.py
|
1
|
9577
|
import pdb
import posixpath
import re
import os
try:
from urllib.parse import unquote
except ImportError: # Python 2
from urllib import unquote
from exceptions import Exception
from django.core.files import File
from django.core.files.storage import DefaultStorage
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse, HttpResponseForbidden
from django.shortcuts import get_object_or_404, render
from django.http import Http404
from django.utils.translation import ugettext as _, ugettext_noop
#from django.views.generic.simple import direct_to_template
from filetransfers.forms import UploadForm
# FIXME : Sjoerd: comicmodels and filetransfers are being merged here. How to keep original Filetransfers seperate from this?
# Right now I feel as though I am entangeling things.. come back to this later
from filetransfers.api import prepare_upload, serve_file
from comicmodels.models import FileSystemDataset,ComicSite,UploadModel,ComicSiteModel
from django.conf import settings
def upload_handler(request):
view_url = reverse('filetransfers.views.upload_handler')
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect(view_url)
upload_url, upload_data = prepare_upload(request, view_url)
form = UploadForm()
#return direct_to_template(request, 'upload/upload.html',
return render(request, 'upload/upload.html',
{'form': form, 'upload_url': upload_url, 'upload_data': upload_data,
'uploads': UploadModel.objects.all()})
def download_handler(request, pk):
upload = get_object_or_404(UploadModel, pk=pk)
return serve_file(request, upload.file, save_as=True)
def uploadedfileserve_handler(request, pk):
""" Serve a file through django, for displaying images etc. """
upload = get_object_or_404(UploadModel, pk=pk)
#if request.user.has_perm("comicmodels.view_ComicSiteModel"):
if upload.can_be_viewed_by(request.user):
return serve_file(request, upload.file, save_as=False)
else:
return HttpResponse("You do not have permission to view this.")
def download_handler_dataset_file(request, project_name, dataset_title,filename):
"""offer file for download based on filename and dataset"""
dataset = FileSystemDataset.objects.get(comicsite__short_name=project_name,title=dataset_title)
filefolder = dataset.get_full_folder_path()
filepath = os.path.join(filefolder,filename)
f = open(filepath, 'r')
file = File(f) # create django file object
return serve_file(request, file, save_as=True)
def download_handler_file(request, filepath):
"""offer file for download based on filepath relative to django root"""
f = open(filepath, 'r')
file = File(f) # create django file object
return serve_file(request, file, save_as=True)
def delete_handler(request, pk):
if request.method == 'POST':
upload = get_object_or_404(UploadModel, pk=pk)
comicsitename = upload.comicsite.short_name
try:
upload.file.delete() #if no file object can be found just continue
except:
pass
finally:
pass
upload.delete()
return HttpResponseRedirect(reverse('comicmodels.views.upload_handler',kwargs={'site_short_name':comicsitename}))
def can_access(user,path,project_name,override_permission=""):
""" Does this user have permission to access folder path which is part of
project named project_name?
Override permission can be used to make certain folders servable through
code even though this would not be allowed otherwise
"""
if override_permission == "":
required = _required_permission(user,path,project_name)
else:
choices = [x[0] for x in ComicSiteModel.PERMISSIONS_CHOICES]
if not override_permission in choices:
raise Exeption("input parameters should be one of [%s], "
"found '%s' " % (",".join(choices),needed))
required = override_permission
if required == ComicSiteModel.ALL:
return True
elif required == ComicSiteModel.REGISTERED_ONLY:
project = ComicSite.objects.get(short_name=project_name)
if project.is_participant(user):
return True
else:
return False
elif required == ComicSiteModel.ADMIN_ONLY:
project = ComicSite.objects.get(short_name=project_name)
if project.is_admin(user):
return True
else:
return False
else:
return False
def _sufficient_permission(needed,granted):
""" Return true if granted permission is greater than or equal to needed
permission.
"""
choices = [x[0] for x in CoomicSiteModel.PERMISSIONS_CHOICES]
if not needed in choices:
raise Exeption("input parameters should be one of [%s], found '%s' " % (",".join(choices),needed))
if not granted in choices:
raise Exeption("input parameters should be one of [%s], found '%s' " % (",".join(choices),granted))
if ComicSiteModel.PERMISSION_WEIGHTS[needed] >= ComicSiteModel.PERMISSION_WEIGHTS[granted]:
return True
else:
return False
def _required_permission(user,path,project_name):
""" Given a file path on local filesystem, which permission level is needed
to view this?
"""
#some config checking.
# TODO : check this once at server start but not every time this method is
# called. It is too late to throw this error once a user clicks
# something.
if not hasattr(settings,"COMIC_PUBLIC_FOLDER_NAME"):
raise ImproperlyConfigured("Don't know from which folder serving publiv files"
"is allowed. Please add a setting like "
"'COMIC_PUBLIC_FOLDER_NAME = \"public_html\""
" to your .conf file." )
if not hasattr(settings,"COMIC_REGISTERED_ONLY_FOLDER_NAME"):
raise ImproperlyConfigured("Don't know from which folder serving protected files"
"is allowed. Please add a setting like "
"'COMIC_REGISTERED_ONLY_FOLDER_NAME = \"datasets\""
" to your .conf file." )
if hasattr(settings,"COMIC_ADDITIONAL_PUBLIC_FOLDER_NAMES"):
if startwith_any(path,settings.COMIC_ADDITIONAL_PUBLIC_FOLDER_NAMES):
return ComicSiteModel.ALL
if path.startswith(settings.COMIC_PUBLIC_FOLDER_NAME):
return ComicSiteModel.ALL
elif path.startswith(settings.COMIC_REGISTERED_ONLY_FOLDER_NAME):
return ComicSiteModel.REGISTERED_ONLY
else:
return ComicSiteModel.ADMIN_ONLY
def startwith_any(path,start_options):
""" Return true if path starts with any of the strings in string array start_options
"""
for option in start_options:
if path.startswith(option):
return True
return False
def serve(request, project_name, path, document_root=None,override_permission=""):
"""
Serve static file for a given project.
This is meant as a replacement for the inefficient debug only
'django.views.static.serve' way of serving files under /media urls.
"""
if document_root == None:
document_root = settings.MEDIA_ROOT
path = posixpath.normpath(unquote(path))
path = path.lstrip('/')
newpath = ''
for part in path.split('/'):
if not part:
# Strip empty path components.
continue
drive, part = os.path.splitdrive(part)
head, part = os.path.split(part)
if part in (os.curdir, os.pardir):
# Strip '.' and '..' in path.
continue
newpath = os.path.join(newpath, part).replace('\\', '/')
if newpath and path != newpath:
return HttpResponseRedirect(newpath)
fullpath = os.path.join(document_root,project_name, newpath)
storage = DefaultStorage()
if not storage.exists(fullpath):
# On case sensitive filesystems you can have problems if the project
# nameurl in the url is not exactly the same case as the filepath.
# find the correct case for projectname then.
# Also case sensitive file systems are weird.
# who would ever want to have a folder 'data' and 'Data' contain
# different files?
projectlist = ComicSite.objects.filter(short_name=project_name)
if projectlist == []:
raise Http404(_("project '%s' does not exist" % project_name ))
project_name = projectlist[0].short_name
fullpath = os.path.join(document_root,project_name, newpath)
if not storage.exists(fullpath):
raise Http404(_('"%(path)s" does not exist') % {'path': fullpath})
if can_access(request.user,path,project_name,override_permission):
f = storage.open(fullpath, 'rb')
file = File(f) # create django file object
# Do not offer to save images, but show them directly
return serve_file(request, file, save_as=True)
else:
return HttpResponseForbidden("This file is not available without "
"credentials")
|
apache-2.0
| -8,936,553,819,921,376,000
| 36.120155
| 125
| 0.6454
| false
| 4.207821
| false
| false
| false
|
larsborn/hetzner-zonefiles
|
dns.py
|
1
|
3978
|
import requests
import re
import os
import sys
from BeautifulSoup import BeautifulSoup
base_url = 'https://robot.your-server.de'
zonefiledir = 'zonefiles'
def log(msg, level = ''):
print '[%s] %s' % (level, msg)
def login(username, password):
login_form_url = base_url + '/login'
login_url = base_url + '/login/check'
r = requests.get(login_form_url)
r = requests.post(login_url, data={'user': username, 'password': password}, cookies=r.cookies)
# ugly: the hetzner status code is always 200 (delivering the login form
# as an "error message")
if 'Herzlich Willkommen auf Ihrer' not in r.text:
return False
return r.history[0].cookies
def list_zonefile_ids(cookies):
ret = {}
last_count = -1
page = 1
while last_count != len(ret):
last_count = len(ret)
dns_url = base_url + '/dns/index/page/%i' % page
r = requests.get(dns_url, cookies=cookies)
soup = BeautifulSoup(r.text, convertEntities=BeautifulSoup.HTML_ENTITIES)
boxes = soup.findAll('table', attrs={'class': 'box_title'})
for box in boxes:
expandBoxJavascript = dict(box.attrs)['onclick']
zoneid = _javascript_to_zoneid(expandBoxJavascript)
td = box.find('td', attrs={'class': 'title'})
domain = td.renderContents()
ret[zoneid] = domain
page += 1
return ret
def get_zonefile(cookies, id):
dns_url = base_url + '/dns/update/id/%i' % id
r = requests.get(dns_url, cookies=cookies)
soup = BeautifulSoup(r.text, convertEntities=BeautifulSoup.HTML_ENTITIES)
textarea = soup.find('textarea')
zonefile = textarea.renderContents()
return zonefile
def write_zonefile(cookies, id, zonefile):
update_url = base_url + '/dns/update'
r = requests.post(
update_url,
cookies=cookies,
data={'id': id, 'zonefile': zonefile}
)
# ugly: the hetzner status code is always 200 (delivering the login form
# as an "error message")
return 'Vielen Dank' in r.text
def logout(cookies):
logout_url = base_url + '/login/logout'
r = requests.get(logout_url, cookies=cookies)
return r.status_code == 200
def _javascript_to_zoneid(s):
r = re.compile('\'(\d+)\'')
m = r.search(s)
if not m: return False
return int(m.group(1))
def print_usage():
print 'Usage: %s [download|update] <username> <password>' % sys.argv[0]
if len(sys.argv) != 4:
print_usage()
exit()
command = sys.argv[1]
username = sys.argv[2]
password = sys.argv[3]
log('Logging in...')
cookies = login(username, password)
if not cookies:
print 'Cannot login'
exit()
if command == 'download':
log('Requesting list of zonefiles...')
list = list_zonefile_ids(cookies)
log('Found %i zonefiles.' % len(list))
for zoneid, domain in list.iteritems():
log('Loading zonefile for %s...' % domain)
zonefile = get_zonefile(cookies, zoneid)
filename = os.path.join(zonefiledir, '%i_%s.txt' % (zoneid, domain))
log('Saving zonefile to %s...' % filename)
f = open(filename, 'w+')
f.write(zonefile)
f.close()
elif command == 'update':
for file in os.listdir(zonefiledir):
domainid = int(file.split('_')[0])
filename = os.path.join(zonefiledir, file)
log('Updating zonefile %s' % filename)
f = open(filename)
zonefile = ''.join(f.readlines())
f.close()
success = write_zonefile(cookies, domainid, zonefile)
if success:
log('Update successfull.')
else:
log('Error updating')
else:
log('Invalid command "%s"' % command)
print_usage()
log('Logging out')
logout(cookies)
|
mit
| 5,876,934,618,418,820,000
| 26.414286
| 98
| 0.578431
| false
| 3.580558
| false
| false
| false
|
misterresse/astrid-tp
|
tests/mail/tests.py
|
1
|
1766
|
# -*- coding: utf-8 -*-
# Copyright the original authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__authors__ = [
'"John Resse" <mister.resse@outlook.com>'
]
from tp import core
from tp.builders import text
from tp.processors import smtp
def build():
return [core.MetaRequest({'name': 'lion', 'email': '1012003162@qq.com'}),
core.MetaRequest({'name': 'invalid', 'email': 'invalid'})]
def process(request):
string = '亲爱的 {0},您好:\n' \
'我公司在进行一项关于个人收入的调查......' \
'请勿回复此邮件\n{1}'
to = request.get('email')
subject = '来自Python邮件客户端的测试邮件'
msg = string.format(request.get('name'), to)
return {'to': to, 'subject': subject, 'msg': msg}
class Process2(object):
def process(self, request):
print('Sending to ' + request['to'] + ', ' + request['subject'])
return request
if __name__ == '__main__':
s = core.Scheduler()
s.add_requests_builders([build, text.TextFileRequestsBuilder('mail/test.csv', text.build_meta_request_csv)])
s.add_request_processors([process, Process2(), smtp.QQSTMPSendMailProcessor('1174751315', 'nnqqgmdwykcnhhjc')])
s.run()
|
apache-2.0
| -8,088,331,116,841,964,000
| 32.62
| 115
| 0.656548
| false
| 3.175803
| false
| false
| false
|
lizhuangzi/QSQuantificationCode
|
QSQuantifier/DataGetter.py
|
1
|
4473
|
#!/usr/bin python
# coding=utf-8
# This Module provides some functions about getting stock's data.
import DataConnection as dc
import datetime
import numpy as np
import db_func
LEAST_DATE = '2016-01-01 00:00:00'
def string_toDatetime(timestr):
return datetime.datetime.strptime(timestr,"%Y-%m-%d %H:%M:%S")
def last_days(current_time,num = 1):
return current_time + datetime.timedelta(days = -num)
def add_zero_forsomeproperties(query_properties):
qpitks = query_properties.keys()
has_pre_close = 'pre_close' in qpitks
query_properties['high_limit'].append(0.0)
query_properties['low_limit'].append(0.0)
if has_pre_close:
query_properties['pre_close'].append(0.0)
# make statistics for datas
def make_statisticsByProperty(tuple_result,query_properties={},allcount=0):
qpitks = query_properties.keys()
# if len(tuple_result) == 0:
# for v in query_properties.itervalues():
# v.append(0.0)
# return
volume = 0.0
money = 0.0
opens = 0.0
close = 0.0
if len(tuple_result)!=0:
opens = tuple_result[0]['newest']
close = tuple_result[-1]['newest']
hasmoney = 'money' in qpitks
hasavg = 'avg' in qpitks
haslow = 'low' in qpitks
hashigh = 'high' in qpitks
has_pre_close = 'pre_close' in qpitks
high = 0.0
low = 0.0
avg = 0.0
for x in tuple_result:
volume += x['deal_amount']
money += x['deal_money']
if high<x['newest']:
high = x['newest']
if low>x['newest']:
low = x['newest']
if volume != 0:
avg = round(money/volume,2)
if hasmoney:
query_properties['money'].append(money)
if hasavg:
query_properties['avg'].append(avg)
if haslow:
query_properties['low'].append(low)
if hashigh:
query_properties['high'].append(high)
close_arr = query_properties['close']
#if has yestady data
if len(close_arr)!=0:
last_close = close
if has_pre_close:
query_properties['pre_close'].append(last_close)
high_limit = round(last_close + last_close*0.1,2)
low_limit = round(last_close - last_close*0.1,2)
query_properties['high_limit'].append(high_limit)
query_properties['low_limit'].append(low_limit)
query_properties['close'].append(close)
query_properties['open'].append(opens)
query_properties['volume'].append(volume)
if len(close_arr) == allcount:
add_zero_forsomeproperties(query_properties)
def serach_timelist(collection,query_time,unit,count,skip_paused=True,query_properties={}):
time_list = []
unit_type = -1
if unit == 'd':
unit_type = 0
elif unit == 'm':
unit_type = 1
elif unit == 's':
unit_type = 2
else:
print('The parameter unit is illegal')
return
i= 0; t=0
while i < count+1:
if unit_type == 0:
temp = query_time + datetime.timedelta(days = -1)
#if it is the loop to search day.
if t == 0:
tempstr = str(temp)
strArr = tempstr.split(" ")
newStr = strArr[0]+" "+"09:00:00"
temp = string_toDatetime(newStr)
query_time = string_toDatetime(strArr[0] +" "+"22:00:00")
elif unit_type == 1:
temp = query_time + datetime.timedelta(minutes = -1)
else:
temp = query_time + datetime.timedelta(seconds = -1)
# beyound threshold
if temp < string_toDatetime(LEAST_DATE):
add_zero_forsomeproperties(query_properties)
print('Warning: There is no early datas')
break;
results = db_func.query_dataThreshold(collection,str(query_time),str(temp))
# no skip
if (skip_paused and unit_type==0 and results.count()==0) == False:
i += 1
time_list.append(temp)
make_statisticsByProperty(tuple(results.clone()), query_properties,count+1)
del(results)
query_time = temp
t += 1
return time_list
def attribute_history(security,current_time,count,unit='d',fields=['open','close','high_limit','low_limit','volume'],skip_paused=True,fq='pre'):
db = dc.startConnection('192.168.69.54',27017)
if db == None:
return
# get collection from db by security
collection = db[security]
#Convert
query_time= string_toDatetime(current_time)
query_properties = {x:[] for x in fields}
#Return a dictionary key:datetime,value:tuple(query datas)
cds = serach_timelist(collection,query_time,unit,count,skip_paused,query_properties)
#show Search days
for x in xrange(0, count if (len(cds)==count+1) else len(cds)):
print "Searching time is %s" %cds[x]
#finall result dictionary
query_result = {}
# change all value to numpy.ndataArray
for k,v in query_properties.iteritems():
if len(cds)==count+1:
v = v[0:-1]
query_result[k] = np.array(v)
return query_result
|
apache-2.0
| -8,739,037,170,679,827,000
| 22.919786
| 144
| 0.678068
| false
| 2.785181
| false
| false
| false
|
DirectXMan12/nova-hacking
|
nova/tests/api/openstack/compute/contrib/test_server_start_stop.py
|
1
|
3702
|
# Copyright (c) 2012 Midokura Japan K.K.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import mox
import webob
from nova.api.openstack.compute.contrib import server_start_stop
from nova.compute import api as compute_api
from nova import db
from nova import exception
from nova import test
from nova.tests.api.openstack import fakes
def fake_instance_get(self, context, instance_id):
result = fakes.stub_instance(id=1, uuid=instance_id)
result['created_at'] = None
result['deleted_at'] = None
result['updated_at'] = None
result['deleted'] = 0
result['info_cache'] = {'network_info': 'foo',
'instance_uuid': result['uuid']}
return result
def fake_start_stop_not_ready(self, context, instance):
raise exception.InstanceNotReady(instance_id=instance["uuid"])
class ServerStartStopTest(test.TestCase):
def setUp(self):
super(ServerStartStopTest, self).setUp()
self.controller = server_start_stop.ServerStartStopActionController()
def test_start(self):
self.stubs.Set(db, 'instance_get_by_uuid', fake_instance_get)
self.mox.StubOutWithMock(compute_api.API, 'start')
compute_api.API.start(mox.IgnoreArg(), mox.IgnoreArg())
self.mox.ReplayAll()
req = fakes.HTTPRequest.blank('/v2/fake/servers/test_inst/action')
body = dict(start="")
self.controller._start_server(req, 'test_inst', body)
def test_start_not_ready(self):
self.stubs.Set(db, 'instance_get_by_uuid', fake_instance_get)
self.stubs.Set(compute_api.API, 'start', fake_start_stop_not_ready)
req = fakes.HTTPRequest.blank('/v2/fake/servers/test_inst/action')
body = dict(start="")
self.assertRaises(webob.exc.HTTPConflict,
self.controller._start_server, req, 'test_inst', body)
def test_stop(self):
self.stubs.Set(db, 'instance_get_by_uuid', fake_instance_get)
self.mox.StubOutWithMock(compute_api.API, 'stop')
compute_api.API.stop(mox.IgnoreArg(), mox.IgnoreArg())
self.mox.ReplayAll()
req = fakes.HTTPRequest.blank('/v2/fake/servers/test_inst/action')
body = dict(stop="")
self.controller._stop_server(req, 'test_inst', body)
def test_stop_not_ready(self):
self.stubs.Set(db, 'instance_get_by_uuid', fake_instance_get)
self.stubs.Set(compute_api.API, 'stop', fake_start_stop_not_ready)
req = fakes.HTTPRequest.blank('/v2/fake/servers/test_inst/action')
body = dict(start="")
self.assertRaises(webob.exc.HTTPConflict,
self.controller._stop_server, req, 'test_inst', body)
def test_start_with_bogus_id(self):
req = fakes.HTTPRequest.blank('/v2/fake/servers/test_inst/action')
body = dict(start="")
self.assertRaises(webob.exc.HTTPNotFound,
self.controller._start_server, req, 'test_inst', body)
def test_stop_with_bogus_id(self):
req = fakes.HTTPRequest.blank('/v2/fake/servers/test_inst/action')
body = dict(start="")
self.assertRaises(webob.exc.HTTPNotFound,
self.controller._stop_server, req, 'test_inst', body)
|
apache-2.0
| -2,595,194,122,138,429,400
| 38.806452
| 78
| 0.667747
| false
| 3.615234
| true
| false
| false
|
valkyriesavage/invenio
|
modules/bibedit/lib/bibedit_engine.py
|
1
|
51248
|
## This file is part of Invenio.
## Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 CERN.
##
## Invenio 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.
##
## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
# pylint: disable=C0103
"""Invenio BibEdit Engine."""
__revision__ = "$Id"
from invenio.bibedit_config import CFG_BIBEDIT_AJAX_RESULT_CODES, \
CFG_BIBEDIT_JS_CHECK_SCROLL_INTERVAL, CFG_BIBEDIT_JS_HASH_CHECK_INTERVAL, \
CFG_BIBEDIT_JS_CLONED_RECORD_COLOR, \
CFG_BIBEDIT_JS_CLONED_RECORD_COLOR_FADE_DURATION, \
CFG_BIBEDIT_JS_NEW_ADD_FIELD_FORM_COLOR, \
CFG_BIBEDIT_JS_NEW_ADD_FIELD_FORM_COLOR_FADE_DURATION, \
CFG_BIBEDIT_JS_NEW_CONTENT_COLOR, \
CFG_BIBEDIT_JS_NEW_CONTENT_COLOR_FADE_DURATION, \
CFG_BIBEDIT_JS_NEW_CONTENT_HIGHLIGHT_DELAY, \
CFG_BIBEDIT_JS_STATUS_ERROR_TIME, CFG_BIBEDIT_JS_STATUS_INFO_TIME, \
CFG_BIBEDIT_JS_TICKET_REFRESH_DELAY, CFG_BIBEDIT_MAX_SEARCH_RESULTS, \
CFG_BIBEDIT_TAG_FORMAT, CFG_BIBEDIT_AJAX_RESULT_CODES_REV, \
CFG_BIBEDIT_AUTOSUGGEST_TAGS, CFG_BIBEDIT_AUTOCOMPLETE_TAGS_KBS,\
CFG_BIBEDIT_KEYWORD_TAXONOMY, CFG_BIBEDIT_KEYWORD_TAG, \
CFG_BIBEDIT_KEYWORD_RDFLABEL
from invenio.config import CFG_SITE_LANG, CFG_DEVEL_SITE
from invenio.bibedit_dblayer import get_name_tags_all, reserve_record_id, \
get_related_hp_changesets, get_hp_update_xml, delete_hp_change, \
get_record_last_modification_date, get_record_revision_author, \
get_marcxml_of_record_revision, delete_related_holdingpen_changes, \
get_record_revisions
from invenio.bibedit_utils import cache_exists, cache_expired, \
create_cache_file, delete_cache_file, get_bibrecord, \
get_cache_file_contents, get_cache_mtime, get_record_templates, \
get_record_template, latest_record_revision, record_locked_by_other_user, \
record_locked_by_queue, save_xml_record, touch_cache_file, \
update_cache_file_contents, get_field_templates, get_marcxml_of_revision, \
revision_to_timestamp, timestamp_to_revision, \
get_record_revision_timestamps, record_revision_exists, \
can_record_have_physical_copies
from invenio.bibrecord import create_record, print_rec, record_add_field, \
record_add_subfield_into, record_delete_field, \
record_delete_subfield_from, \
record_modify_subfield, record_move_subfield, \
create_field, record_replace_field, record_move_fields, \
record_modify_controlfield, record_get_field_values
from invenio.config import CFG_BIBEDIT_PROTECTED_FIELDS, CFG_CERN_SITE, \
CFG_SITE_URL
from invenio.search_engine import record_exists, search_pattern
from invenio.webuser import session_param_get, session_param_set
from invenio.bibcatalog import bibcatalog_system
from invenio.webpage import page
from invenio.bibknowledge import get_kbd_values_for_bibedit, get_kbr_values, \
get_kbt_items_for_bibedit #autosuggest
from invenio.bibcirculation_dblayer import get_number_copies, has_copies
from invenio.bibcirculation_utils import create_item_details_url
from datetime import datetime
import re
import difflib
import zlib
import sys
if sys.hexversion < 0x2060000:
try:
import simplejson as json
simplejson_available = True
except ImportError:
# Okay, no Ajax app will be possible, but continue anyway,
# since this package is only recommended, not mandatory.
simplejson_available = False
else:
import json
simplejson_available = True
import invenio.template
bibedit_templates = invenio.template.load('bibedit')
re_revdate_split = re.compile('^(\d\d\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)')
def get_empty_fields_templates():
"""
Returning the templates of empty fields :
- an empty data field
- an empty control field
"""
return [{
"name": "Empty field",
"description": "The data field not containing any " + \
"information filled in",
"tag" : "",
"ind1" : "",
"ind2" : "",
"subfields" : [("","")],
"isControlfield" : False
},{
"name" : "Empty control field",
"description" : "The controlfield not containing any " + \
"data or tag description",
"isControlfield" : True,
"tag" : "",
"value" : ""
}]
def get_available_fields_templates():
"""
A method returning all the available field templates
Returns a list of descriptors. Each descriptor has
the same structure as a full field descriptor inside the
record
"""
templates = get_field_templates()
result = get_empty_fields_templates()
for template in templates:
tplTag = template[3].keys()[0]
field = template[3][tplTag][0]
if (field[0] == []):
# if the field is a controlField, add different structure
result.append({
"name" : template[1],
"description" : template[2],
"isControlfield" : True,
"tag" : tplTag,
"value" : field[3]
})
else:
result.append({
"name": template[1],
"description": template[2],
"tag" : tplTag,
"ind1" : field[1],
"ind2" : field[2],
"subfields" : field[0],
"isControlfield" : False
})
return result
def perform_request_init(uid, ln, req, lastupdated):
"""Handle the initial request by adding menu and JavaScript to the page."""
errors = []
warnings = []
body = ''
# Add script data.
record_templates = get_record_templates()
record_templates.sort()
tag_names = get_name_tags_all()
protected_fields = ['001']
protected_fields.extend(CFG_BIBEDIT_PROTECTED_FIELDS.split(','))
history_url = '"' + CFG_SITE_URL + '/admin/bibedit/bibeditadmin.py/history"'
cern_site = 'false'
if not simplejson_available:
title = 'Record Editor'
body = '''Sorry, the record editor cannot operate when the
`simplejson' module is not installed. Please see the INSTALL
file.'''
return page(title = title,
body = body,
errors = [],
warnings = [],
uid = uid,
language = ln,
navtrail = "",
lastupdated = lastupdated,
req = req)
if CFG_CERN_SITE:
cern_site = 'true'
data = {'gRECORD_TEMPLATES': record_templates,
'gTAG_NAMES': tag_names,
'gPROTECTED_FIELDS': protected_fields,
'gSITE_URL': '"' + CFG_SITE_URL + '"',
'gHISTORY_URL': history_url,
'gCERN_SITE': cern_site,
'gHASH_CHECK_INTERVAL': CFG_BIBEDIT_JS_HASH_CHECK_INTERVAL,
'gCHECK_SCROLL_INTERVAL': CFG_BIBEDIT_JS_CHECK_SCROLL_INTERVAL,
'gSTATUS_ERROR_TIME': CFG_BIBEDIT_JS_STATUS_ERROR_TIME,
'gSTATUS_INFO_TIME': CFG_BIBEDIT_JS_STATUS_INFO_TIME,
'gCLONED_RECORD_COLOR':
'"' + CFG_BIBEDIT_JS_CLONED_RECORD_COLOR + '"',
'gCLONED_RECORD_COLOR_FADE_DURATION':
CFG_BIBEDIT_JS_CLONED_RECORD_COLOR_FADE_DURATION,
'gNEW_ADD_FIELD_FORM_COLOR':
'"' + CFG_BIBEDIT_JS_NEW_ADD_FIELD_FORM_COLOR + '"',
'gNEW_ADD_FIELD_FORM_COLOR_FADE_DURATION':
CFG_BIBEDIT_JS_NEW_ADD_FIELD_FORM_COLOR_FADE_DURATION,
'gNEW_CONTENT_COLOR': '"' + CFG_BIBEDIT_JS_NEW_CONTENT_COLOR + '"',
'gNEW_CONTENT_COLOR_FADE_DURATION':
CFG_BIBEDIT_JS_NEW_CONTENT_COLOR_FADE_DURATION,
'gNEW_CONTENT_HIGHLIGHT_DELAY':
CFG_BIBEDIT_JS_NEW_CONTENT_HIGHLIGHT_DELAY,
'gTICKET_REFRESH_DELAY': CFG_BIBEDIT_JS_TICKET_REFRESH_DELAY,
'gRESULT_CODES': CFG_BIBEDIT_AJAX_RESULT_CODES,
'gAUTOSUGGEST_TAGS' : CFG_BIBEDIT_AUTOSUGGEST_TAGS,
'gAUTOCOMPLETE_TAGS' : CFG_BIBEDIT_AUTOCOMPLETE_TAGS_KBS.keys(),
'gKEYWORD_TAG' : '"' + CFG_BIBEDIT_KEYWORD_TAG + '"'
}
body += '<script type="text/javascript">\n'
for key in data:
body += ' var %s = %s;\n' % (key, data[key])
body += ' </script>\n'
# Adding the information about field templates
fieldTemplates = get_available_fields_templates()
body += "<script>\n" + \
" var fieldTemplates = %s\n" % (json.dumps(fieldTemplates), ) + \
"</script>\n"
# Add scripts (the ordering is NOT irrelevant).
scripts = ['jquery.min.js', 'jquery.effects.core.min.js',
'jquery.effects.highlight.min.js', 'jquery.autogrow.js',
'jquery.jeditable.mini.js', 'jquery.hotkeys.min.js', 'json2.js',
'bibedit_display.js', 'bibedit_engine.js', 'bibedit_keys.js',
'bibedit_menu.js', 'bibedit_holdingpen.js', 'marcxml.js',
'bibedit_clipboard.js']
for script in scripts:
body += ' <script type="text/javascript" src="%s/js/%s">' \
'</script>\n' % (CFG_SITE_URL, script)
# Build page structure and menu.
# rec = create_record(format_record(235, "xm"))[0]
#oaiId = record_extract_oai_id(rec)
body += bibedit_templates.menu()
body += ' <div id="bibEditContent"></div>\n'
return body, errors, warnings
def get_xml_comparison(header1, header2, xml1, xml2):
"""
Return diffs of two MARCXML records.
"""
return "".join(difflib.unified_diff(xml1.splitlines(1),
xml2.splitlines(1), header1, header2))
def get_marcxml_of_revision_id(recid, revid):
"""
Return MARCXML string with corresponding to revision REVID
(=RECID.REVDATE) of a record. Return empty string if revision
does not exist.
"""
res = ""
job_date = "%s-%s-%s %s:%s:%s" % re_revdate_split.search(revid).groups()
tmp_res = get_marcxml_of_record_revision(recid, job_date)
if tmp_res:
for row in tmp_res:
res += zlib.decompress(row[0]) + "\n"
return res
def perform_request_compare(ln, recid, rev1, rev2):
"""Handle a request for comparing two records"""
body = ""
errors = []
warnings = []
if (not record_revision_exists(recid, rev1)) or \
(not record_revision_exists(recid, rev2)):
body = "The requested record revision does not exist !"
else:
xml1 = get_marcxml_of_revision_id(recid, rev1)
xml2 = get_marcxml_of_revision_id(recid, rev2)
fullrevid1 = "%i.%s" % (recid, rev1)
fullrevid2 = "%i.%s" % (recid, rev2)
comparison = bibedit_templates.clean_value(
get_xml_comparison(fullrevid1, fullrevid2, xml1, xml2),
'text').replace('\n', '<br />\n ')
job_date1 = "%s-%s-%s %s:%s:%s" % re_revdate_split.search(rev1).groups()
job_date2 = "%s-%s-%s %s:%s:%s" % re_revdate_split.search(rev2).groups()
body += bibedit_templates.history_comparebox(ln, job_date1,
job_date2, comparison)
return body, errors, warnings
def perform_request_newticket(recid, uid):
"""create a new ticket with this record's number
@param recid: record id
@param uid: user id
@return: (error_msg, url)
"""
t_id = bibcatalog_system.ticket_submit(uid, "", recid, "")
t_url = ""
errmsg = ""
if t_id:
#get the ticket's URL
t_url = bibcatalog_system.ticket_get_attribute(uid, t_id, 'url_modify')
else:
errmsg = "ticket_submit failed"
return (errmsg, t_url)
def perform_request_ajax(req, recid, uid, data, isBulk = False, \
ln = CFG_SITE_LANG):
"""Handle Ajax requests by redirecting to appropriate function."""
response = {}
request_type = data['requestType']
undo_redo = None
if data.has_key("undoRedo"):
undo_redo = data["undoRedo"]
# Call function based on request type.
if request_type == 'searchForRecord':
# Search request.
response.update(perform_request_search(data))
elif request_type in ['changeTagFormat']:
# User related requests.
response.update(perform_request_user(req, request_type, recid, data))
elif request_type in ('getRecord', 'submit', 'cancel', 'newRecord',
'deleteRecord', 'deleteRecordCache', 'prepareRecordMerge', 'revert'):
# 'Major' record related requests.
response.update(perform_request_record(req, request_type, recid, uid,
data))
elif request_type in ('addField', 'addSubfields', \
'addFieldsSubfieldsOnPositions', 'modifyContent', \
'moveSubfield', 'deleteFields', 'moveField', \
'modifyField', 'otherUpdateRequest', \
'disableHpChange', 'deactivateHoldingPenChangeset'):
# Record updates.
cacheMTime = data['cacheMTime']
if data.has_key('hpChanges'):
hpChanges = data['hpChanges']
else:
hpChanges = {}
response.update(perform_request_update_record(request_type, recid, \
uid, cacheMTime, data, \
hpChanges, undo_redo, \
isBulk, ln))
elif request_type in ('autosuggest', 'autocomplete', 'autokeyword'):
response.update(perform_request_autocomplete(request_type, recid, uid, \
data))
elif request_type in ('getTickets', ):
# BibCatalog requests.
response.update(perform_request_bibcatalog(request_type, recid, uid))
elif request_type in ('getHoldingPenUpdates', ):
response.update(perform_request_holdingpen(request_type, recid))
elif request_type in ('getHoldingPenUpdateDetails', \
'deleteHoldingPenChangeset'):
updateId = data['changesetNumber']
response.update(perform_request_holdingpen(request_type, recid, \
updateId))
elif request_type in ('applyBulkUpdates', ):
# a general version of a bulk request
changes = data['requestsData']
cacheMTime = data['cacheMTime']
response.update(perform_bulk_request_ajax(req, recid, uid, changes, \
undo_redo, cacheMTime))
return response
def perform_bulk_request_ajax(req, recid, uid, reqsData, undoRedo, cacheMTime):
""" An AJAX handler used when treating bulk updates """
lastResult = {}
lastTime = cacheMTime
isFirst = True
for data in reqsData:
assert data != None
data['cacheMTime'] = lastTime
if isFirst and undoRedo != None:
# we add the undo/redo handler to the first operation in order to
# save the handler on the server side !
data['undoRedo'] = undoRedo
isFirst = False
lastResult = perform_request_ajax(req, recid, uid, data, True)
# now we have to update the cacheMtime in next request !
# if lastResult.has_key('cacheMTime'):
try:
lastTime = lastResult['cacheMTime']
except:
raise Exception(str(lastResult))
return lastResult
def perform_request_search(data):
"""Handle search requests."""
response = {}
searchType = data['searchType']
searchPattern = data['searchPattern']
if searchType == 'anywhere':
pattern = searchPattern
else:
pattern = searchType + ':' + searchPattern
result_set = list(search_pattern(p=pattern))
response['resultCode'] = 1
response['resultSet'] = result_set[0:CFG_BIBEDIT_MAX_SEARCH_RESULTS]
return response
def perform_request_user(req, request_type, recid, data):
"""Handle user related requests."""
response = {}
if request_type == 'changeTagFormat':
try:
tagformat_settings = session_param_get(req, 'bibedit_tagformat')
except KeyError:
tagformat_settings = {}
tagformat_settings[recid] = data['tagFormat']
session_param_set(req, 'bibedit_tagformat', tagformat_settings)
response['resultCode'] = 2
return response
def perform_request_holdingpen(request_type, recId, changeId=None):
"""
A method performing the holdingPen ajax request. The following types of
requests can be made:
getHoldingPenUpdates - retrieving the holding pen updates pending
for a given record
"""
response = {}
if request_type == 'getHoldingPenUpdates':
changeSet = get_related_hp_changesets(recId)
changes = []
for change in changeSet:
changes.append((str(change[0]), str(change[1])))
response["changes"] = changes
elif request_type == 'getHoldingPenUpdateDetails':
# returning the list of changes related to the holding pen update
# the format based on what the record difference xtool returns
assert(changeId != None)
hpContent = get_hp_update_xml(changeId)
holdingPenRecord = create_record(hpContent[0], "xm")[0]
# databaseRecord = get_record(hpContent[1])
response['record'] = holdingPenRecord
response['changeset_number'] = changeId
elif request_type == 'deleteHoldingPenChangeset':
assert(changeId != None)
delete_hp_change(changeId)
return response
def perform_request_record(req, request_type, recid, uid, data, ln=CFG_SITE_LANG):
"""Handle 'major' record related requests like fetching, submitting or
deleting a record, cancel editing or preparing a record for merging.
"""
response = {}
if request_type == 'newRecord':
# Create a new record.
new_recid = reserve_record_id()
new_type = data['newType']
if new_type == 'empty':
# Create a new empty record.
create_cache_file(recid, uid)
response['resultCode'], response['newRecID'] = 6, new_recid
elif new_type == 'template':
# Create a new record from XML record template.
template_filename = data['templateFilename']
template = get_record_template(template_filename)
if not template:
response['resultCode'] = 108
else:
record = create_record(template)[0]
if not record:
response['resultCode'] = 109
else:
record_add_field(record, '001',
controlfield_value=str(new_recid))
create_cache_file(new_recid, uid, record, True)
response['resultCode'], response['newRecID'] = 7, new_recid
elif new_type == 'clone':
# Clone an existing record (from the users cache).
existing_cache = cache_exists(recid, uid)
if existing_cache:
try:
record = get_cache_file_contents(recid, uid)[2]
except:
# if, for example, the cache format was wrong (outdated)
record = get_bibrecord(recid)
else:
# Cache missing. Fall back to using original version.
record = get_bibrecord(recid)
record_delete_field(record, '001')
record_add_field(record, '001', controlfield_value=str(new_recid))
create_cache_file(new_recid, uid, record, True)
response['resultCode'], response['newRecID'] = 8, new_recid
elif request_type == 'getRecord':
# Fetch the record. Possible error situations:
# - Non-existing record
# - Deleted record
# - Record locked by other user
# - Record locked by queue
# A cache file will be created if it does not exist.
# If the cache is outdated (i.e., not based on the latest DB revision),
# cacheOutdated will be set to True in the response.
record_status = record_exists(recid)
existing_cache = cache_exists(recid, uid)
read_only_mode = False
if data.has_key("inReadOnlyMode"):
read_only_mode = data['inReadOnlyMode']
if record_status == 0:
response['resultCode'] = 102
elif record_status == -1:
response['resultCode'] = 103
elif not read_only_mode and not existing_cache and \
record_locked_by_other_user(recid, uid):
response['resultCode'] = 104
elif not read_only_mode and existing_cache and \
cache_expired(recid, uid) and \
record_locked_by_other_user(recid, uid):
response['resultCode'] = 104
elif not read_only_mode and record_locked_by_queue(recid):
response['resultCode'] = 105
else:
if data.get('deleteRecordCache'):
delete_cache_file(recid, uid)
existing_cache = False
pending_changes = []
disabled_hp_changes = {}
if read_only_mode:
if data.has_key('recordRevision'):
record_revision_ts = data['recordRevision']
record_xml = get_marcxml_of_revision(recid, \
record_revision_ts)
record = create_record(record_xml)[0]
record_revision = timestamp_to_revision(record_revision_ts)
pending_changes = []
disabled_hp_changes = {}
else:
# a normal cacheless retrieval of a record
record = get_bibrecord(recid)
record_revision = get_record_last_modification_date(recid)
if record_revision == None:
record_revision = datetime.now().timetuple()
pending_changes = []
disabled_hp_changes = {}
cache_dirty = False
mtime = 0
undo_list = []
redo_list = []
elif not existing_cache:
record_revision, record = create_cache_file(recid, uid)
mtime = get_cache_mtime(recid, uid)
pending_changes = []
disabled_hp_changes = {}
undo_list = []
redo_list = []
cache_dirty = False
else:
#TODO: This try except should be replaced with something nicer,
# like an argument indicating if a new cache file is to
# be created
try:
cache_dirty, record_revision, record, pending_changes, \
disabled_hp_changes, undo_list, redo_list = \
get_cache_file_contents(recid, uid)
touch_cache_file(recid, uid)
mtime = get_cache_mtime(recid, uid)
if not latest_record_revision(recid, record_revision) and \
get_record_revisions(recid) != ():
# This sould prevent from using old cache in case of
# viewing old version. If there are no revisions,
# it means we should skip this step because this
# is a new record
response['cacheOutdated'] = True
except:
record_revision, record = create_cache_file(recid, uid)
mtime = get_cache_mtime(recid, uid)
pending_changes = []
disabled_hp_changes = {}
cache_dirty = False
undo_list = []
redo_list = []
if data['clonedRecord']:
response['resultCode'] = 9
else:
response['resultCode'] = 3
revision_author = get_record_revision_author(recid, record_revision)
latest_revision = get_record_last_modification_date(recid)
if latest_revision == None:
latest_revision = datetime.now().timetuple()
last_revision_ts = revision_to_timestamp(latest_revision)
revisions_history = get_record_revision_timestamps(recid)
number_of_physical_copies = get_number_copies(recid)
bibcirc_details_URL = create_item_details_url(recid, ln)
can_have_copies = can_record_have_physical_copies(recid)
response['cacheDirty'], response['record'], \
response['cacheMTime'], response['recordRevision'], \
response['revisionAuthor'], response['lastRevision'], \
response['revisionsHistory'], response['inReadOnlyMode'], \
response['pendingHpChanges'], response['disabledHpChanges'], \
response['undoList'], response['redoList'] = cache_dirty, \
record, mtime, revision_to_timestamp(record_revision), \
revision_author, last_revision_ts, revisions_history, \
read_only_mode, pending_changes, disabled_hp_changes, \
undo_list, redo_list
response['numberOfCopies'] = number_of_physical_copies
response['bibCirculationUrl'] = bibcirc_details_URL
response['canRecordHavePhysicalCopies'] = can_have_copies
# Set tag format from user's session settings.
try:
tagformat_settings = session_param_get(req, 'bibedit_tagformat')
tagformat = tagformat_settings[recid]
except KeyError:
tagformat = CFG_BIBEDIT_TAG_FORMAT
response['tagFormat'] = tagformat
elif request_type == 'submit':
# Submit the record. Possible error situations:
# - Missing cache file
# - Cache file modified in other editor
# - Record locked by other user
# - Record locked by queue
# - Invalid XML characters
# If the cache is outdated cacheOutdated will be set to True in the
# response.
if not cache_exists(recid, uid):
response['resultCode'] = 106
elif not get_cache_mtime(recid, uid) == data['cacheMTime']:
response['resultCode'] = 107
elif cache_expired(recid, uid) and \
record_locked_by_other_user(recid, uid):
response['resultCode'] = 104
elif record_locked_by_queue(recid):
response['resultCode'] = 105
else:
try:
tmp_result = get_cache_file_contents(recid, uid)
record_revision = tmp_result[1]
record = tmp_result[2]
pending_changes = tmp_result[3]
# disabled_changes = tmp_result[4]
xml_record = print_rec(record)
record, status_code, list_of_errors = create_record(xml_record)
if status_code == 0:
response['resultCode'], response['errors'] = 110, \
list_of_errors
elif not data['force'] and \
not latest_record_revision(recid, record_revision):
response['cacheOutdated'] = True
if CFG_DEVEL_SITE:
response['record_revision'] = record_revision.__str__()
response['newest_record_revision'] = \
get_record_last_modification_date(recid).__str__()
else:
save_xml_record(recid, uid)
response['resultCode'] = 4
except Exception, e:
response['resultCode'] = CFG_BIBEDIT_AJAX_RESULT_CODES_REV[ \
'error_wrong_cache_file_format']
if CFG_DEVEL_SITE: # return debug information in the request
response['exception_message'] = e.__str__()
elif request_type == 'revert':
revId = data['revId']
job_date = "%s-%s-%s %s:%s:%s" % re_revdate_split.search(revId).groups()
revision_xml = get_marcxml_of_revision(recid, job_date)
save_xml_record(recid, uid, revision_xml)
if (cache_exists(recid, uid)):
delete_cache_file(recid, uid)
response['resultCode'] = 4
elif request_type == 'cancel':
# Cancel editing by deleting the cache file. Possible error situations:
# - Cache file modified in other editor
if cache_exists(recid, uid):
if get_cache_mtime(recid, uid) == data['cacheMTime']:
delete_cache_file(recid, uid)
response['resultCode'] = 5
else:
response['resultCode'] = 107
else:
response['resultCode'] = 5
elif request_type == 'deleteRecord':
# Submit the record. Possible error situations:
# - Record locked by other user
# - Record locked by queue
# As the user is requesting deletion we proceed even if the cache file
# is missing and we don't check if the cache is outdated or has
# been modified in another editor.
existing_cache = cache_exists(recid, uid)
pending_changes = []
if has_copies(recid):
response['resultCode'] = \
CFG_BIBEDIT_AJAX_RESULT_CODES_REV['error_physical_copies_exist']
elif existing_cache and cache_expired(recid, uid) and \
record_locked_by_other_user(recid, uid):
response['resultCode'] = \
CFG_BIBEDIT_AJAX_RESULT_CODES_REV['error_rec_locked_by_user']
elif record_locked_by_queue(recid):
response['resultCode'] = \
CFG_BIBEDIT_AJAX_RESULT_CODES_REV['error_rec_locked_by_queue']
else:
if not existing_cache:
record_revision, record, pending_changes, \
deactivated_hp_changes, undo_list, redo_list = \
create_cache_file(recid, uid)
else:
try:
record_revision, record, pending_changes, \
deactivated_hp_changes, undo_list, redo_list = \
get_cache_file_contents(recid, uid)[1:]
except:
record_revision, record, pending_changes, \
deactivated_hp_changes = create_cache_file(recid, uid)
record_add_field(record, '980', ' ', ' ', '', [('c', 'DELETED')])
undo_list = []
redo_list = []
update_cache_file_contents(recid, uid, record_revision, record, \
pending_changes, \
deactivated_hp_changes, undo_list, \
redo_list)
save_xml_record(recid, uid)
delete_related_holdingpen_changes(recid) # we don't need any changes
# related to a deleted record
response['resultCode'] = 10
elif request_type == 'deleteRecordCache':
# Delete the cache file. Ignore the request if the cache has been
# modified in another editor.
if cache_exists(recid, uid) and get_cache_mtime(recid, uid) == \
data['cacheMTime']:
delete_cache_file(recid, uid)
response['resultCode'] = 11
elif request_type == 'prepareRecordMerge':
# We want to merge the cache with the current DB version of the record,
# so prepare an XML file from the file cache, to be used by BibMerge.
# Possible error situations:
# - Missing cache file
# - Record locked by other user
# - Record locked by queue
# We don't check if cache is outdated (a likely scenario for this
# request) or if it has been modified in another editor.
if not cache_exists(recid, uid):
response['resultCode'] = 106
elif cache_expired(recid, uid) and \
record_locked_by_other_user(recid, uid):
response['resultCode'] = 104
elif record_locked_by_queue(recid):
response['resultCode'] = 105
else:
save_xml_record(recid, uid, to_upload=False, to_merge=True)
response['resultCode'] = 12
return response
def perform_request_update_record(request_type, recid, uid, cacheMTime, data, \
hpChanges, undoRedoOp, isBulk=False, \
ln=CFG_SITE_LANG):
"""Handle record update requests like adding, modifying, moving or deleting
of fields or subfields. Possible common error situations:
- Missing cache file
- Cache file modified in other editor
Explanation of some parameters:
undoRedoOp - Indicates in "undo"/"redo"/undo_descriptor operation is
performed by a current request.
"""
response = {}
if not cache_exists(recid, uid):
response['resultCode'] = 106
elif not get_cache_mtime(recid, uid) == cacheMTime and isBulk == False:
# In case of a bulk request, the changes are deliberately performed
# imemdiately one after another
response['resultCode'] = 107
else:
try:
record_revision, record, pending_changes, deactivated_hp_changes, \
undo_list, redo_list = get_cache_file_contents(recid, uid)[1:]
except:
response['resultCode'] = CFG_BIBEDIT_AJAX_RESULT_CODES_REV[ \
'error_wrong_cache_file_format']
return response
# process all the Holding Pen changes operations ... regardles the
# request type
# import rpdb2;
# rpdb2.start_embedded_debugger('password', fAllowRemote=True)
if hpChanges.has_key("toDisable"):
for changeId in hpChanges["toDisable"]:
pending_changes[changeId]["applied_change"] = True
if hpChanges.has_key("toEnable"):
for changeId in hpChanges["toEnable"]:
pending_changes[changeId]["applied_change"] = False
if hpChanges.has_key("toOverride"):
pending_changes = hpChanges["toOverride"]
if hpChanges.has_key("changesetsToDeactivate"):
for changesetId in hpChanges["changesetsToDeactivate"]:
deactivated_hp_changes[changesetId] = True
if hpChanges.has_key("changesetsToActivate"):
for changesetId in hpChanges["changesetsToActivate"]:
deactivated_hp_changes[changesetId] = False
# processing the undo/redo entries
if undoRedoOp == "undo":
try:
redo_list = [undo_list[-1]] + redo_list
undo_list = undo_list[:-1]
except:
raise Exception("An exception occured when undoing previous" + \
" operation. Undo list: " + str(undo_list) + \
" Redo list " + str(redo_list))
elif undoRedoOp == "redo":
try:
undo_list = undo_list + [redo_list[0]]
redo_list = redo_list[1:]
except:
raise Exception("An exception occured when redoing previous" + \
" operation. Undo list: " + str(undo_list) + \
" Redo list " + str(redo_list))
else:
# This is a genuine operation - we have to add a new descriptor
# to the undo list and cancel the redo unless the operation is
# a bulk operation
if undoRedoOp != None:
undo_list = undo_list + [undoRedoOp]
redo_list = []
else:
assert isBulk == True
field_position_local = data.get('fieldPosition')
if field_position_local is not None:
field_position_local = int(field_position_local)
if request_type == 'otherUpdateRequest':
# An empty request. Might be useful if we want to perform
# operations that require only the actions performed globally,
# like modifying the holdingPen changes list
response['resultCode'] = CFG_BIBEDIT_AJAX_RESULT_CODES_REV[ \
'editor_modifications_changed']
elif request_type == 'deactivateHoldingPenChangeset':
# the changeset has been marked as processed ( user applied it in
# the editor). Marking as used in the cache file.
# CAUTION: This function has been implemented here because logically
# it fits with the modifications made to the cache file.
# No changes are made to the Holding Pen physically. The
# changesets are related to the cache because we want to
# cancel the removal every time the cache disappears for
# any reason
response['resultCode'] = CFG_BIBEDIT_AJAX_RESULT_CODES_REV[ \
'disabled_hp_changeset']
elif request_type == 'addField':
if data['controlfield']:
record_add_field(record, data['tag'],
controlfield_value=data['value'])
response['resultCode'] = 20
else:
record_add_field(record, data['tag'], data['ind1'],
data['ind2'], subfields=data['subfields'],
field_position_local=field_position_local)
response['resultCode'] = 21
elif request_type == 'addSubfields':
subfields = data['subfields']
for subfield in subfields:
record_add_subfield_into(record, data['tag'], subfield[0],
subfield[1], subfield_position=None,
field_position_local=field_position_local)
if len(subfields) == 1:
response['resultCode'] = 22
else:
response['resultCode'] = 23
elif request_type == 'addFieldsSubfieldsOnPositions':
#1) Sorting the fields by their identifiers
fieldsToAdd = data['fieldsToAdd']
subfieldsToAdd = data['subfieldsToAdd']
for tag in fieldsToAdd.keys():
positions = fieldsToAdd[tag].keys()
positions.sort()
for position in positions:
# now adding fields at a position
isControlfield = (len(fieldsToAdd[tag][position][0]) == 0)
# if there are n subfields, this is a control field
if isControlfield:
controlfieldValue = fieldsToAdd[tag][position][3]
record_add_field(record, tag, field_position_local = \
int(position), \
controlfield_value = \
controlfieldValue)
else:
subfields = fieldsToAdd[tag][position][0]
ind1 = fieldsToAdd[tag][position][1]
ind2 = fieldsToAdd[tag][position][2]
record_add_field(record, tag, ind1, ind2, subfields = \
subfields, field_position_local = \
int(position))
# now adding the subfields
for tag in subfieldsToAdd.keys():
for fieldPosition in subfieldsToAdd[tag].keys(): #now the fields
#order not important !
subfieldsPositions = subfieldsToAdd[tag][fieldPosition]. \
keys()
subfieldsPositions.sort()
for subfieldPosition in subfieldsPositions:
subfield = subfieldsToAdd[tag][fieldPosition]\
[subfieldPosition]
record_add_subfield_into(record, tag, subfield[0], \
subfield[1], \
subfield_position = \
int(subfieldPosition), \
field_position_local = \
int(fieldPosition))
response['resultCode'] = \
CFG_BIBEDIT_AJAX_RESULT_CODES_REV['added_positioned_subfields']
elif request_type == 'modifyField': # changing the field structure
# first remove subfields and then add new... change the indices
subfields = data['subFields'] # parse the JSON representation of
# the subfields here
new_field = create_field(subfields, data['ind1'], data['ind2'])
record_replace_field(record, data['tag'], new_field, \
field_position_local = data['fieldPosition'])
response['resultCode'] = 26
elif request_type == 'modifyContent':
if data['subfieldIndex'] != None:
record_modify_subfield(record, data['tag'],
data['subfieldCode'], data['value'],
int(data['subfieldIndex']),
field_position_local=field_position_local)
else:
record_modify_controlfield(record, data['tag'], data["value"],
field_position_local=field_position_local)
response['resultCode'] = 24
elif request_type == 'moveSubfield':
record_move_subfield(record, data['tag'],
int(data['subfieldIndex']), int(data['newSubfieldIndex']),
field_position_local=field_position_local)
response['resultCode'] = 25
elif request_type == 'moveField':
if data['direction'] == 'up':
final_position_local = field_position_local-1
else: # direction is 'down'
final_position_local = field_position_local+1
record_move_fields(record, data['tag'], [field_position_local],
final_position_local)
response['resultCode'] = 32
elif request_type == 'deleteFields':
to_delete = data['toDelete']
deleted_fields = 0
deleted_subfields = 0
for tag in to_delete:
#Sorting the fields in a edcreasing order by the local position!
fieldsOrder = to_delete[tag].keys()
fieldsOrder.sort(lambda a, b: int(b) - int(a))
for field_position_local in fieldsOrder:
if not to_delete[tag][field_position_local]:
# No subfields specified - delete entire field.
record_delete_field(record, tag,
field_position_local=int(field_position_local))
deleted_fields += 1
else:
for subfield_position in \
to_delete[tag][field_position_local][::-1]:
# Delete subfields in reverse order (to keep the
# indexing correct).
record_delete_subfield_from(record, tag,
int(subfield_position),
field_position_local=int(field_position_local))
deleted_subfields += 1
if deleted_fields == 1 and deleted_subfields == 0:
response['resultCode'] = 26
elif deleted_fields and deleted_subfields == 0:
response['resultCode'] = 27
elif deleted_subfields == 1 and deleted_fields == 0:
response['resultCode'] = 28
elif deleted_subfields and deleted_fields == 0:
response['resultCode'] = 29
else:
response['resultCode'] = 30
response['cacheMTime'], response['cacheDirty'] = \
update_cache_file_contents(recid, uid, record_revision,
record, \
pending_changes, \
deactivated_hp_changes, \
undo_list, redo_list), \
True
return response
def perform_request_autocomplete(request_type, recid, uid, data):
"""
Perfrom an AJAX request associated with the retrieval of autocomplete
data.
Arguments:
request_type: Type of the currently served request
recid: the identifer of the record
uid: The identifier of the user being currently logged in
data: The request data containing possibly important additional
arguments
"""
response = {}
# get the values based on which one needs to search
searchby = data['value']
#we check if the data is properly defined
fulltag = ''
if data.has_key('maintag') and data.has_key('subtag1') and \
data.has_key('subtag2') and data.has_key('subfieldcode'):
maintag = data['maintag']
subtag1 = data['subtag1']
subtag2 = data['subtag2']
u_subtag1 = subtag1
u_subtag2 = subtag2
if (not subtag1) or (subtag1 == ' '):
u_subtag1 = '_'
if (not subtag2) or (subtag2 == ' '):
u_subtag2 = '_'
subfieldcode = data['subfieldcode']
fulltag = maintag+u_subtag1+u_subtag2+subfieldcode
if (request_type == 'autokeyword'):
#call the keyword-form-ontology function
if fulltag and searchby:
items = get_kbt_items_for_bibedit(CFG_BIBEDIT_KEYWORD_TAXONOMY, \
CFG_BIBEDIT_KEYWORD_RDFLABEL, \
searchby)
response['autokeyword'] = items
if (request_type == 'autosuggest'):
#call knowledge base function to put the suggestions in an array..
if fulltag and searchby and len(searchby) > 3:
suggest_values = get_kbd_values_for_bibedit(fulltag, "", searchby)
#remove ..
new_suggest_vals = []
for sugg in suggest_values:
if sugg.startswith(searchby):
new_suggest_vals.append(sugg)
response['autosuggest'] = new_suggest_vals
if (request_type == 'autocomplete'):
#call the values function with the correct kb_name
if CFG_BIBEDIT_AUTOCOMPLETE_TAGS_KBS.has_key(fulltag):
kbname = CFG_BIBEDIT_AUTOCOMPLETE_TAGS_KBS[fulltag]
#check if the seachby field has semicolons. Take all
#the semicolon-separated items..
items = []
vals = []
if searchby:
if searchby.rfind(';'):
items = searchby.split(';')
else:
items = [searchby.strip()]
for item in items:
item = item.strip()
kbrvals = get_kbr_values(kbname, item, '', 'e') #we want an exact match
if kbrvals and kbrvals[0]: #add the found val into vals
vals.append(kbrvals[0])
#check that the values are not already contained in other
#instances of this field
record = get_cache_file_contents(recid, uid)[2]
xml_rec = print_rec(record)
record, status_code, dummy_errors = create_record(xml_rec)
existing_values = []
if (status_code != 0):
existing_values = record_get_field_values(record,
maintag,
subtag1,
subtag2,
subfieldcode)
#get the new values.. i.e. vals not in existing
new_vals = vals
for val in new_vals:
if val in existing_values:
new_vals.remove(val)
response['autocomplete'] = new_vals
response['resultCode'] = CFG_BIBEDIT_AJAX_RESULT_CODES_REV['autosuggestion_scanned']
return response
def perform_request_bibcatalog(request_type, recid, uid):
"""Handle request to BibCatalog (RT).
"""
response = {}
if request_type == 'getTickets':
# Insert the ticket data in the response, if possible
if uid:
bibcat_resp = bibcatalog_system.check_system(uid)
if bibcat_resp == "":
tickets_found = bibcatalog_system.ticket_search(uid, \
status=['new', 'open'], recordid=recid)
t_url_str = '' #put ticket urls here, formatted for HTML display
for t_id in tickets_found:
#t_url = bibcatalog_system.ticket_get_attribute(uid, \
# t_id, 'url_display')
ticket_info = bibcatalog_system.ticket_get_info( \
uid, t_id, ['url_display', 'url_close'])
t_url = ticket_info['url_display']
t_close_url = ticket_info['url_close']
#format..
t_url_str += "#" + str(t_id) + '<a href="' + t_url + \
'">[read]</a> <a href="' + t_close_url + \
'">[close]</a><br/>'
#put ticket header and tickets links in the box
t_url_str = "<strong>Tickets</strong><br/>" + t_url_str + \
"<br/>" + '<a href="new_ticket?recid=' + str(recid) + \
'>[new ticket]</a>'
response['tickets'] = t_url_str
#add a new ticket link
else:
#put something in the tickets container, for debug
response['tickets'] = "<!--"+bibcat_resp+"-->"
response['resultCode'] = 31
return response
|
gpl-2.0
| -4,159,289,337,030,909,400
| 44.312113
| 88
| 0.550812
| false
| 4.272803
| false
| false
| false
|
who-emro/meerkat_api
|
meerkat_api/resources/epi_week.py
|
1
|
1398
|
"""
Resource to deal with epi-weeks
"""
import datetime
from dateutil.parser import parse
from flask import jsonify
from flask_restful import Resource
from meerkat_api.extensions import api
import meerkat_abacus.util.epi_week as epi_week_util
class EpiWeek(Resource):
"""
Get epi week of date(defaults to today)
Args:\n
date: date to get epi-week\n
Returns:\n
epi-week: epi-week\n
"""
def get(self, date=None):
if date:
date = parse(date)
else:
date = datetime.datetime.today()
_epi_year, _epi_week_number = epi_week_util.epi_week_for_date(date)
_epi_year_start_day_weekday = epi_week_util.epi_year_start_date(date).weekday()
return jsonify(epi_week=_epi_week_number,
year=_epi_year,
offset=_epi_year_start_day_weekday)
class EpiWeekStart(Resource):
"""
Return the start date of an epi week in the given year
Args:\n
epi-week: epi week\n
year: year\n
Returns:
start-date: start-date\n
"""
def get(self, year, epi_week):
_epi_week_start_date = epi_week_util.epi_week_start_date(year, epi_week)
return jsonify(start_date=_epi_week_start_date)
api.add_resource(EpiWeek, "/epi_week", "/epi_week/<date>")
api.add_resource(EpiWeekStart, "/epi_week_start/<year>/<epi_week>")
|
mit
| 5,886,391,900,665,190,000
| 25.377358
| 87
| 0.620887
| false
| 3.134529
| false
| false
| false
|
aftersight/After-Sight-Model-1
|
keyPress.py
|
1
|
13557
|
class _Getch:
"""Gets a single character from standard input. Does not echo to the
screen. From http://code.activestate.com/recipes/134892/"""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
try:
self.impl = _GetchMacCarbon()
except(AttributeError, ImportError):
self.impl = _GetchUnix()
def __call__(self): return self.impl()
class _GetchUnix:
def __init__(self):
import tty, sys, termios # import termios now or else you'll get the Unix version on the Mac
def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
class _GetchWindows:
def __init__(self):
import msvcrt
def __call__(self):
import msvcrt
return msvcrt.getch()
class _GetchMacCarbon:
"""
A function which returns the current ASCII key that is down;
if no ASCII key is down, the null string is returned. The
page http://www.mactech.com/macintosh-c/chap02-1.html was
very helpful in figuring out how to do this.
"""
def __init__(self):
import Carbon
Carbon.Evt #see if it has this (in Unix, it doesn't)
def __call__(self):
import Carbon
if Carbon.Evt.EventAvail(0x0008)[0]==0: # 0x0008 is the keyDownMask
return ''
else:
#
# The event contains the following info:
# (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1]
#
# The message (msg) contains the ASCII char which is
# extracted with the 0x000000FF charCodeMask; this
# number is converted to an ASCII character with chr() and
# returned
#
(what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1]
return chr(msg & 0x000000FF)
import threading
# From http://stackoverflow.com/a/2022629/2924421
class Event(list):
def __call__(self, *args, **kwargs):
for f in self:
f(*args, **kwargs)
def __repr__(self):
return "Event(%s)" % list.__repr__(self)
def getKey():
inkey = _Getch()
import sys
for i in xrange(sys.maxint):
k=inkey()
if k<>'':break
return k
class KeyCallbackFunction():
callbackParam = None
actualFunction = None
def __init__(self, actualFunction, callbackParam):
self.actualFunction = actualFunction
self.callbackParam = callbackParam
def doCallback(self, inputKey):
if not self.actualFunction is None:
if self.callbackParam is None:
callbackFunctionThread = threading.Thread(target=self.actualFunction, args=(inputKey,))
else:
callbackFunctionThread = threading.Thread(target=self.actualFunction, args=(inputKey,self.callbackParam))
callbackFunctionThread.daemon = True
callbackFunctionThread.start()
class KeyCapture():
gotKeyLock = threading.Lock()
gotKeys = []
gotKeyEvent = threading.Event()
keyBlockingSetKeyLock = threading.Lock()
addingEventsLock = threading.Lock()
keyReceiveEvents = Event()
keysGotLock = threading.Lock()
keysGot = []
keyBlockingKeyLockLossy = threading.Lock()
keyBlockingKeyLossy = None
keyBlockingEventLossy = threading.Event()
keysBlockingGotLock = threading.Lock()
keysBlockingGot = []
keyBlockingGotEvent = threading.Event()
wantToStopLock = threading.Lock()
wantToStop = False
stoppedLock = threading.Lock()
stopped = True
isRunningEvent = False
getKeyThread = None
keyFunction = None
keyArgs = None
# Begin capturing keys. A seperate thread is launched that
# captures key presses, and then these can be received via get,
# getAsync, and adding an event via addEvent. Note that this
# will prevent the system to accept keys as normal (say, if
# you are in a python shell) because it overrides that key
# capturing behavior.
# If you start capture when it's already been started, a
# InterruptedError("Keys are still being captured")
# will be thrown
# Note that get(), getAsync() and events are independent, so if a key is pressed:
#
# 1: Any calls to get() that are waiting, with lossy on, will return
# that key
# 2: It will be stored in the queue of get keys, so that get() with lossy
# off will return the oldest key pressed not returned by get() yet.
# 3: All events will be fired with that key as their input
# 4: It will be stored in the list of getAsync() keys, where that list
# will be returned and set to empty list on the next call to getAsync().
# get() call with it, aand add it to the getAsync() list.
def startCapture(self, keyFunction=None, args=None):
# Make sure we aren't already capturing keys
self.stoppedLock.acquire()
if not self.stopped:
self.stoppedLock.release()
raise InterruptedError("Keys are still being captured")
return
self.stopped = False
self.stoppedLock.release()
# If we have captured before, we need to allow the get() calls to actually
# wait for key presses now by clearing the event
if self.keyBlockingEventLossy.is_set():
self.keyBlockingEventLossy.clear()
# Have one function that we call every time a key is captured, intended for stopping capture
# as desired
self.keyFunction = keyFunction
self.keyArgs = args
# Begin capturing keys (in a seperate thread)
self.getKeyThread = threading.Thread(target=self._threadProcessKeyPresses)
self.getKeyThread.daemon = True
self.getKeyThread.start()
# Process key captures (in a seperate thread)
self.getKeyThread = threading.Thread(target=self._threadStoreKeyPresses)
self.getKeyThread.daemon = True
self.getKeyThread.start()
def capturing(self):
self.stoppedLock.acquire()
isCapturing = not self.stopped
self.stoppedLock.release()
return isCapturing
# Stops the thread that is capturing keys on the first opporunity
# has to do so. It usually can't stop immediately because getting a key
# is a blocking process, so this will probably stop capturing after the
# next key is pressed.
#
# However, Sometimes if you call stopCapture it will stop before starting capturing the
# next key, due to multithreading race conditions. So if you want to stop capturing
# reliably, call stopCapture in a function added via addEvent. Then you are
# guaranteed that capturing will stop immediately after the rest of the callback
# functions are called (before starting to capture the next key).
def stopCapture(self):
self.wantToStopLock.acquire()
self.wantToStop = True
self.wantToStopLock.release()
# Takes in a function that will be called every time a key is pressed (with that
# key passed in as the first paramater in that function)
def addEvent(self, keyPressEventFunction, args=None):
self.addingEventsLock.acquire()
callbackHolder = KeyCallbackFunction(keyPressEventFunction, args)
self.keyReceiveEvents.append(callbackHolder.doCallback)
self.addingEventsLock.release()
def clearEvents(self):
self.addingEventsLock.acquire()
self.keyReceiveEvents = Event()
self.addingEventsLock.release()
# Gets a key captured by this KeyCapture, blocking until a key is pressed.
# There is an optional lossy paramater:
# If True all keys before this call are ignored, and the next pressed key
# will be returned.
# If False this will return the oldest key captured that hasn't
# been returned by get yet. False is the default.
def get(self, lossy=False):
if lossy:
# Wait for the next key to be pressed
self.keyBlockingEventLossy.wait()
self.keyBlockingKeyLockLossy.acquire()
keyReceived = self.keyBlockingKeyLossy
self.keyBlockingKeyLockLossy.release()
return keyReceived
else:
while True:
# Wait until a key is pressed
self.keyBlockingGotEvent.wait()
# Get the key pressed
readKey = None
self.keysBlockingGotLock.acquire()
# Get a key if it exists
if len(self.keysBlockingGot) != 0:
readKey = self.keysBlockingGot.pop(0)
# If we got the last one, tell us to wait
if len(self.keysBlockingGot) == 0:
self.keyBlockingGotEvent.clear()
self.keysBlockingGotLock.release()
# Process the key (if it actually exists)
if not readKey is None:
return readKey
# Exit if we are stopping
self.wantToStopLock.acquire()
if self.wantToStop:
self.wantToStopLock.release()
return None
self.wantToStopLock.release()
def clearGetList(self):
self.keysBlockingGotLock.acquire()
self.keysBlockingGot = []
self.keysBlockingGotLock.release()
# Gets a list of all keys pressed since the last call to getAsync, in order
# from first pressed, second pressed, .., most recent pressed
def getAsync(self):
self.keysGotLock.acquire();
keysPressedList = list(self.keysGot)
self.keysGot = []
self.keysGotLock.release()
return keysPressedList
def clearAsyncList(self):
self.keysGotLock.acquire();
self.keysGot = []
self.keysGotLock.release();
def _processKey(self, readKey):
# Append to list for GetKeyAsync
self.keysGotLock.acquire()
self.keysGot.append(readKey)
self.keysGotLock.release()
# Call lossy blocking key events
self.keyBlockingKeyLockLossy.acquire()
self.keyBlockingKeyLossy = readKey
self.keyBlockingEventLossy.set()
self.keyBlockingEventLossy.clear()
self.keyBlockingKeyLockLossy.release()
# Call non-lossy blocking key events
self.keysBlockingGotLock.acquire()
self.keysBlockingGot.append(readKey)
if len(self.keysBlockingGot) == 1:
self.keyBlockingGotEvent.set()
self.keysBlockingGotLock.release()
# Call events added by AddEvent
self.addingEventsLock.acquire()
self.keyReceiveEvents(readKey)
self.addingEventsLock.release()
def _threadProcessKeyPresses(self):
while True:
# Wait until a key is pressed
self.gotKeyEvent.wait()
# Get the key pressed
readKey = None
self.gotKeyLock.acquire()
# Get a key if it exists
if len(self.gotKeys) != 0:
readKey = self.gotKeys.pop(0)
# If we got the last one, tell us to wait
if len(self.gotKeys) == 0:
self.gotKeyEvent.clear()
self.gotKeyLock.release()
# Process the key (if it actually exists)
if not readKey is None:
self._processKey(readKey)
# Exit if we are stopping
self.wantToStopLock.acquire()
if self.wantToStop:
self.wantToStopLock.release()
break
self.wantToStopLock.release()
def _threadStoreKeyPresses(self):
while True:
# Get a key
readKey = getKey()
# Run the potential shut down function
if not self.keyFunction is None:
self.keyFunction(readKey, self.keyArgs)
# Add the key to the list of pressed keys
self.gotKeyLock.acquire()
self.gotKeys.append(readKey)
if len(self.gotKeys) == 1:
self.gotKeyEvent.set()
self.gotKeyLock.release()
# Exit if we are stopping
self.wantToStopLock.acquire()
if self.wantToStop:
self.wantToStopLock.release()
self.gotKeyEvent.set()
break
self.wantToStopLock.release()
# If we have reached here we stopped capturing
# All we need to do to clean up is ensure that
# all the calls to .get() now return None.
# To ensure no calls are stuck never returning,
# we will leave the event set so any tasks waiting
# for it immediately exit. This will be unset upon
# starting key capturing again.
self.stoppedLock.acquire()
# We also need to set this to True so we can start up
# capturing again.
self.stopped = True
self.stopped = True
self.keyBlockingKeyLockLossy.acquire()
self.keyBlockingKeyLossy = None
self.keyBlockingEventLossy.set()
self.keyBlockingKeyLockLossy.release()
self.keysBlockingGotLock.acquire()
self.keyBlockingGotEvent.set()
self.keysBlockingGotLock.release()
self.stoppedLock.release()
|
cc0-1.0
| -7,249,865,575,136,879,000
| 33.321519
| 121
| 0.619827
| false
| 4.243192
| false
| false
| false
|
rpedde/python-carbon-buildpkg
|
lib/carbon/writer.py
|
1
|
5802
|
"""Copyright 2009 Chris Davis
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License."""
import os
import time
from os.path import join, exists, dirname, basename
import whisper
from carbon import state
from carbon.cache import MetricCache
from carbon.storage import getFilesystemPath, loadStorageSchemas, loadAggregationSchemas
from carbon.conf import settings
from carbon import log, events, instrumentation
from twisted.internet import reactor
from twisted.internet.task import LoopingCall
from twisted.application.service import Service
lastCreateInterval = 0
createCount = 0
schemas = loadStorageSchemas()
agg_schemas = loadAggregationSchemas()
CACHE_SIZE_LOW_WATERMARK = settings.MAX_CACHE_SIZE * 0.95
def optimalWriteOrder():
"Generates metrics with the most cached values first and applies a soft rate limit on new metrics"
global lastCreateInterval
global createCount
metrics = MetricCache.counts()
t = time.time()
metrics.sort(key=lambda item: item[1], reverse=True) # by queue size, descending
log.msg("Sorted %d cache queues in %.6f seconds" % (len(metrics), time.time() - t))
if state.cacheTooFull and MetricCache.size < CACHE_SIZE_LOW_WATERMARK:
events.cacheSpaceAvailable()
for metric, queueSize in metrics:
dbFilePath = getFilesystemPath(metric)
dbFileExists = exists(dbFilePath)
if not dbFileExists:
createCount += 1
now = time.time()
if now - lastCreateInterval >= 60:
lastCreateInterval = now
createCount = 1
elif createCount >= settings.MAX_CREATES_PER_MINUTE:
# dropping queued up datapoints for new metrics prevents filling up the entire cache
# when a bunch of new metrics are received.
try:
MetricCache.pop(metric)
except KeyError:
pass
continue
try: # metrics can momentarily disappear from the MetricCache due to the implementation of MetricCache.store()
datapoints = MetricCache.pop(metric)
except KeyError:
log.msg("MetricCache contention, skipping %s update for now" % metric)
continue # we simply move on to the next metric when this race condition occurs
yield (metric, datapoints, dbFilePath, dbFileExists)
def writeCachedDataPoints():
"Write datapoints until the MetricCache is completely empty"
updates = 0
lastSecond = 0
while MetricCache:
dataWritten = False
for (metric, datapoints, dbFilePath, dbFileExists) in optimalWriteOrder():
dataWritten = True
if not dbFileExists:
archiveConfig = None
xFilesFactor, aggregationMethod = None, None
for schema in schemas:
if schema.matches(metric):
log.creates('new metric %s matched schema %s' % (metric, schema.name))
archiveConfig = [archive.getTuple() for archive in schema.archives]
break
for schema in agg_schemas:
if schema.matches(metric):
log.creates('new metric %s matched aggregation schema %s' % (metric, schema.name))
xFilesFactor, aggregationMethod = schema.archives
break
if not archiveConfig:
raise Exception("No storage schema matched the metric '%s', check your storage-schemas.conf file." % metric)
dbDir = dirname(dbFilePath)
os.system("mkdir -p -m 755 '%s'" % dbDir)
log.creates("creating database file %s (archive=%s xff=%s agg=%s)" %
(dbFilePath, archiveConfig, xFilesFactor, aggregationMethod))
whisper.create(dbFilePath, archiveConfig, xFilesFactor, aggregationMethod)
os.chmod(dbFilePath, 0755)
instrumentation.increment('creates')
try:
t1 = time.time()
whisper.update_many(dbFilePath, datapoints)
t2 = time.time()
updateTime = t2 - t1
except:
log.err()
instrumentation.increment('errors')
else:
pointCount = len(datapoints)
instrumentation.increment('committedPoints', pointCount)
instrumentation.append('updateTimes', updateTime)
if settings.LOG_UPDATES:
log.updates("wrote %d datapoints for %s in %.5f seconds" % (pointCount, metric, updateTime))
# Rate limit update operations
thisSecond = int(t2)
if thisSecond != lastSecond:
lastSecond = thisSecond
updates = 0
else:
updates += 1
if updates >= settings.MAX_UPDATES_PER_SECOND:
time.sleep( int(t2 + 1) - t2 )
# Avoid churning CPU when only new metrics are in the cache
if not dataWritten:
time.sleep(0.1)
def writeForever():
while reactor.running:
try:
writeCachedDataPoints()
except:
log.err()
time.sleep(1) # The writer thread only sleeps when the cache is empty or an error occurs
def reloadStorageSchemas():
global schemas
try:
schemas = loadStorageSchemas()
except:
log.msg("Failed to reload storage schemas")
log.err()
class WriterService(Service):
def __init__(self):
self.reload_task = LoopingCall(reloadStorageSchemas)
def startService(self):
self.reload_task.start(60, False)
reactor.callInThread(writeForever)
Service.startService(self)
def stopService(self):
self.reload_task.stop()
Service.stopService(self)
|
apache-2.0
| 4,351,749,073,916,351,000
| 30.362162
| 118
| 0.685453
| false
| 4.141328
| false
| false
| false
|
shellderp/sublime-robot-plugin
|
lib/robot/utils/argumentparser.py
|
1
|
15983
|
# Copyright 2008-2012 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import with_statement
import getopt # optparse was not supported by Jython 2.2
import os
import re
import sys
import glob
import string
import codecs
import textwrap
from robot.errors import DataError, Information, FrameworkError
from robot.version import get_full_version
from .misc import plural_or_not
from .encoding import decode_output, decode_from_system, utf8open
ESCAPES = dict(
space = ' ', apos = "'", quot = '"', lt = '<', gt = '>',
pipe = '|', star = '*', comma = ',', slash = '/', semic = ';',
colon = ':', quest = '?', hash = '#', amp = '&', dollar = '$',
percent = '%', at = '@', exclam = '!', paren1 = '(', paren2 = ')',
square1 = '[', square2 = ']', curly1 = '{', curly2 = '}', bslash = '\\'
)
class ArgumentParser:
_opt_line_re = re.compile('''
^\s{1,4} # 1-4 spaces in the beginning of the line
((-\S\s)*) # all possible short options incl. spaces (group 1)
--(\S{2,}) # required long option (group 3)
(\s\S+)? # optional value (group 4)
(\s\*)? # optional '*' telling option allowed multiple times (group 5)
''', re.VERBOSE)
def __init__(self, usage, name=None, version=None, arg_limits=None,
validator=None, auto_help=True, auto_version=True,
auto_escape=True, auto_pythonpath=True, auto_argumentfile=True):
"""Available options and tool name are read from the usage.
Tool name is got from the first row of the usage. It is either the
whole row or anything before first ' -- '.
"""
if not usage:
raise FrameworkError('Usage cannot be empty')
self.name = name or usage.splitlines()[0].split(' -- ')[0].strip()
self.version = version or get_full_version()
self._usage = usage
self._arg_limit_validator = ArgLimitValidator(arg_limits)
self._validator = validator
self._auto_help = auto_help
self._auto_version = auto_version
self._auto_escape = auto_escape
self._auto_pythonpath = auto_pythonpath
self._auto_argumentfile = auto_argumentfile
self._short_opts = ''
self._long_opts = []
self._multi_opts = []
self._toggle_opts = []
self._names = []
self._short_to_long = {}
self._expected_args = ()
self._create_options(usage)
def parse_args(self, args_list):
"""Parse given arguments and return options and positional arguments.
Arguments must be given as a list and are typically sys.argv[1:].
Options are retuned as a dictionary where long options are keys. Value
is a string for those options that can be given only one time (if they
are given multiple times the last value is used) or None if the option
is not used at all. Value for options that can be given multiple times
(denoted with '*' in the usage) is a list which contains all the given
values and is empty if options are not used. Options not taken
arguments have value False when they are not set and True otherwise.
Positional arguments are returned as a list in the order they are given.
If 'check_args' is True, this method will automatically check that
correct number of arguments, as parsed from the usage line, are given.
If the last argument in the usage line ends with the character 's',
the maximum number of arguments is infinite.
Possible errors in processing arguments are reported using DataError.
Some options have a special meaning and are handled automatically
if defined in the usage and given from the command line:
--escape option can be used to automatically unescape problematic
characters given in an escaped format.
--argumentfile can be used to automatically read arguments from
a specified file. When --argumentfile is used, the parser always
allows using it multiple times. Adding '*' to denote that is thus
recommend. A special value 'stdin' can be used to read arguments from
stdin instead of a file.
--pythonpath can be used to add extra path(s) to sys.path.
--help and --version automatically generate help and version messages.
Version is generated based on the tool name and version -- see __init__
for information how to set them. Help contains the whole usage given to
__init__. Possible <VERSION> text in the usage is replaced with the
given version. Possible <--ESCAPES--> is replaced with available
escapes so that they are wrapped to multiple lines but take the same
amount of horizontal space as <---ESCAPES--->. Both help and version
are wrapped to Information exception.
"""
args_list = [decode_from_system(a) for a in args_list]
if self._auto_argumentfile:
args_list = self._process_possible_argfile(args_list)
opts, args = self._parse_args(args_list)
opts, args = self._handle_special_options(opts, args)
self._arg_limit_validator(args)
if self._validator:
opts, args = self._validator(opts, args)
return opts, args
def _handle_special_options(self, opts, args):
if self._auto_escape and opts.get('escape'):
opts, args = self._unescape_opts_and_args(opts, args)
if self._auto_help and opts.get('help'):
self._raise_help()
if self._auto_version and opts.get('version'):
self._raise_version()
if self._auto_pythonpath and opts.get('pythonpath'):
sys.path = self._get_pythonpath(opts['pythonpath']) + sys.path
for auto, opt in [(self._auto_help, 'help'),
(self._auto_version, 'version'),
(self._auto_escape, 'escape'),
(self._auto_pythonpath, 'pythonpath'),
(self._auto_argumentfile, 'argumentfile')]:
if auto and opt in opts:
opts.pop(opt)
return opts, args
def _parse_args(self, args):
args = [self._lowercase_long_option(a) for a in args]
try:
opts, args = getopt.getopt(args, self._short_opts, self._long_opts)
except getopt.GetoptError, err:
raise DataError(err.msg)
return self._process_opts(opts), self._glob_args(args)
def _lowercase_long_option(self, opt):
if not opt.startswith('--'):
return opt
if '=' not in opt:
return opt.lower()
opt, value = opt.split('=', 1)
return '%s=%s' % (opt.lower(), value)
def _unescape_opts_and_args(self, opts, args):
try:
escape_strings = opts['escape']
except KeyError:
raise FrameworkError("No 'escape' in options")
escapes = self._get_escapes(escape_strings)
for name, value in opts.items():
if name != 'escape':
opts[name] = self._unescape(value, escapes)
return opts, [self._unescape(arg, escapes) for arg in args]
def _process_possible_argfile(self, args):
argfile_opts = ['--argumentfile']
for sopt, lopt in self._short_to_long.items():
if lopt == 'argumentfile':
argfile_opts.append('-'+sopt)
while True:
try:
index = self._get_argfile_index(args, argfile_opts)
path = args[index+1]
except IndexError:
break
args[index:index+2] = self._get_args_from_file(path)
return args
def _get_argfile_index(self, args, argfile_opts):
for opt in argfile_opts:
if opt in args:
return args.index(opt)
raise IndexError
def _get_args_from_file(self, path):
if path.upper() != 'STDIN':
content = self._read_argfile(path)
else:
content = self._read_argfile_from_stdin()
return self._process_argfile(content)
def _read_argfile(self, path):
try:
with utf8open(path) as f:
content = f.read()
except (IOError, UnicodeError), err:
raise DataError("Opening argument file '%s' failed: %s"
% (path, err))
if content.startswith(codecs.BOM_UTF8.decode('UTF-8')):
content = content[1:]
return content
def _read_argfile_from_stdin(self):
content = sys.__stdin__.read()
if sys.platform != 'cli':
content = decode_output(content)
return content
def _process_argfile(self, content):
args = []
for line in content.splitlines():
line = line.strip()
if line.startswith('-'):
args.extend(line.split(' ', 1))
elif line and not line.startswith('#'):
args.append(line)
return args
def _get_escapes(self, escape_strings):
escapes = {}
for estr in escape_strings:
try:
name, value = estr.split(':', 1)
except ValueError:
raise DataError("Invalid escape string syntax '%s'. "
"Expected: what:with" % estr)
try:
escapes[value] = ESCAPES[name.lower()]
except KeyError:
raise DataError("Invalid escape '%s'. Available: %s"
% (name, self._get_available_escapes()))
return escapes
def _unescape(self, value, escapes):
if value in [None, True, False]:
return value
if isinstance(value, list):
return [self._unescape(item, escapes) for item in value]
for esc_name, esc_value in escapes.items():
if esc_name in value:
value = value.replace(esc_name, esc_value)
return value
def _process_opts(self, opt_tuple):
opts = self._init_opts()
for name, value in opt_tuple:
name = self._get_name(name)
if name in self._multi_opts:
opts[name].append(value)
elif name in self._toggle_opts:
opts[name] = not opts[name]
else:
opts[name] = value
return opts
def _glob_args(self, args):
temp = []
for path in args:
paths = sorted(glob.glob(path))
if paths:
temp.extend(paths)
else:
temp.append(path)
return temp
def _init_opts(self):
opts = {}
for name in self._names:
if name in self._multi_opts:
opts[name] = []
elif name in self._toggle_opts:
opts[name] = False
else:
opts[name] = None
return opts
def _get_name(self, name):
name = name.lstrip('-')
try:
return self._short_to_long[name]
except KeyError:
return name
def _create_options(self, usage):
for line in usage.splitlines():
res = self._opt_line_re.match(line)
if res:
self._create_option(short_opts=[o[1] for o in res.group(1).split()],
long_opt=res.group(3).lower(),
takes_arg=bool(res.group(4)),
is_multi=bool(res.group(5)))
def _create_option(self, short_opts, long_opt, takes_arg, is_multi):
if long_opt in self._names:
self._raise_option_multiple_times_in_usage('--' + long_opt)
self._names.append(long_opt)
for sopt in short_opts:
if self._short_to_long.has_key(sopt):
self._raise_option_multiple_times_in_usage('-' + sopt)
self._short_to_long[sopt] = long_opt
if is_multi:
self._multi_opts.append(long_opt)
if takes_arg:
long_opt += '='
short_opts = [sopt+':' for sopt in short_opts]
else:
self._toggle_opts.append(long_opt)
self._long_opts.append(long_opt)
self._short_opts += (''.join(short_opts))
def _get_pythonpath(self, paths):
if isinstance(paths, basestring):
paths = [paths]
temp = []
for path in self._split_pythonpath(paths):
temp.extend(glob.glob(path))
return [os.path.abspath(path) for path in temp if path]
def _split_pythonpath(self, paths):
# paths may already contain ':' as separator
tokens = ':'.join(paths).split(':')
if os.sep == '/':
return tokens
# Fix paths split like 'c:\temp' -> 'c', '\temp'
ret = []
drive = ''
for item in tokens:
item = item.replace('/', '\\')
if drive and item.startswith('\\'):
ret.append('%s:%s' % (drive, item))
drive = ''
continue
if drive:
ret.append(drive)
drive = ''
if len(item) == 1 and item in string.letters:
drive = item
else:
ret.append(item)
if drive:
ret.append(drive)
return ret
def _get_available_escapes(self):
names = sorted(ESCAPES.keys(), key=str.lower)
return ', '.join('%s (%s)' % (n, ESCAPES[n]) for n in names)
def _raise_help(self):
msg = self._usage
if self.version:
msg = msg.replace('<VERSION>', self.version)
def replace_escapes(res):
escapes = 'Available escapes: ' + self._get_available_escapes()
lines = textwrap.wrap(escapes, width=len(res.group(2)))
indent = ' ' * len(res.group(1))
return '\n'.join(indent + line for line in lines)
msg = re.sub('( *)(<-+ESCAPES-+>)', replace_escapes, msg)
raise Information(msg)
def _raise_version(self):
raise Information('%s %s' % (self.name, self.version))
def _raise_option_multiple_times_in_usage(self, opt):
raise FrameworkError("Option '%s' multiple times in usage" % opt)
class ArgLimitValidator(object):
def __init__(self, arg_limits):
self._min_args, self._max_args = self._parse_arg_limits(arg_limits)
def _parse_arg_limits(self, arg_limits):
if arg_limits is None:
return 0, sys.maxint
if isinstance(arg_limits, int):
return arg_limits, arg_limits
if len(arg_limits) == 1:
return arg_limits[0], sys.maxint
return arg_limits[0], arg_limits[1]
def __call__(self, args):
if not (self._min_args <= len(args) <= self._max_args):
self._raise_invalid_args(self._min_args, self._max_args, len(args))
def _raise_invalid_args(self, min_args, max_args, arg_count):
min_end = plural_or_not(min_args)
if min_args == max_args:
expectation = "%d argument%s" % (min_args, min_end)
elif max_args != sys.maxint:
expectation = "%d to %d arguments" % (min_args, max_args)
else:
expectation = "at least %d argument%s" % (min_args, min_end)
raise DataError("Expected %s, got %d." % (expectation, arg_count))
|
apache-2.0
| 2,738,208,641,721,807,400
| 38.27027
| 84
| 0.565789
| false
| 4.043258
| false
| false
| false
|
Yelp/paasta
|
paasta_tools/contrib/utilization_check.py
|
1
|
2057
|
#!/usr/bin/env python
"""Reads a list of hosts to stdin and produces
a utilization report for those hosts.
"""
import functools
import json
import sys
from typing import Sequence
from a_sync import block
from paasta_tools.mesos.exceptions import MasterNotAvailableException
from paasta_tools.mesos_tools import get_mesos_master
from paasta_tools.metrics.metastatus_lib import (
calculate_resource_utilization_for_slaves,
)
from paasta_tools.metrics.metastatus_lib import filter_tasks_for_slaves
from paasta_tools.metrics.metastatus_lib import get_all_tasks_from_state
from paasta_tools.metrics.metastatus_lib import (
resource_utillizations_from_resource_info,
)
from paasta_tools.utils import PaastaColors
def main(hostnames: Sequence[str]) -> None:
master = get_mesos_master()
try:
mesos_state = block(master.state)
except MasterNotAvailableException as e:
print(PaastaColors.red("CRITICAL: %s" % e.message))
sys.exit(2)
slaves = [
slave
for slave in mesos_state.get("slaves", [])
if slave["hostname"] in hostnames
]
tasks = get_all_tasks_from_state(mesos_state, include_orphans=True)
filtered_tasks = filter_tasks_for_slaves(slaves, tasks)
resource_info_dict = calculate_resource_utilization_for_slaves(
slaves, filtered_tasks
)
resource_utilizations = resource_utillizations_from_resource_info(
total=resource_info_dict["total"], free=resource_info_dict["free"]
)
output = {}
for metric in resource_utilizations:
utilization = metric.total - metric.free
if int(metric.total) == 0:
utilization_perc = 100
else:
utilization_perc = utilization / float(metric.total) * 100
output[metric.metric] = {
"total": metric.total,
"used": utilization,
"perc": utilization_perc,
}
print(json.dumps(output))
if __name__ == "__main__":
hostnames = functools.reduce(lambda x, y: x + [y.strip()], sys.stdin, [])
main(hostnames)
|
apache-2.0
| 2,211,955,582,909,433,000
| 32.177419
| 77
| 0.679144
| false
| 3.558824
| false
| false
| false
|
indictranstech/osmosis-erpnext
|
erpnext/manufacturing/doctype/production_planning_tool/production_planning_tool.py
|
1
|
17555
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import cstr, flt, cint, nowdate, add_days, comma_and
from frappe import msgprint, _
from frappe.model.document import Document
from erpnext.manufacturing.doctype.bom.bom import validate_bom_no
from erpnext.manufacturing.doctype.production_order.production_order import get_item_details
class ProductionPlanningTool(Document):
def __init__(self, arg1, arg2=None):
super(ProductionPlanningTool, self).__init__(arg1, arg2)
self.item_dict = {}
def clear_table(self, table_name):
self.set(table_name, [])
def validate_company(self):
if not self.company:
frappe.throw(_("Please enter Company"))
def get_open_sales_orders(self):
""" Pull sales orders which are pending to deliver based on criteria selected"""
so_filter = item_filter = ""
if self.from_date:
so_filter += " and so.transaction_date >= %(from_date)s"
if self.to_date:
so_filter += " and so.transaction_date <= %(to_date)s"
if self.customer:
so_filter += " and so.customer = %(customer)s"
if self.fg_item:
item_filter += " and item.name = %(item)s"
open_so = frappe.db.sql("""
select distinct so.name, so.transaction_date, so.customer, so.base_grand_total
from `tabSales Order` so, `tabSales Order Item` so_item
where so_item.parent = so.name
and so.docstatus = 1 and so.status != "Stopped"
and so.company = %(company)s
and so_item.qty > so_item.delivered_qty {0}
and (exists (select name from `tabItem` item where item.name=so_item.item_code
and ((item.is_pro_applicable = 1 or item.is_sub_contracted_item = 1) {1}))
or exists (select name from `tabPacked Item` pi
where pi.parent = so.name and pi.parent_item = so_item.item_code
and exists (select name from `tabItem` item where item.name=pi.item_code
and (item.is_pro_applicable = 1 or item.is_sub_contracted_item = 1) {2})))
""".format(so_filter, item_filter, item_filter), {
"from_date": self.from_date,
"to_date": self.to_date,
"customer": self.customer,
"item": self.fg_item,
"company": self.company
}, as_dict=1)
self.add_so_in_table(open_so)
def add_so_in_table(self, open_so):
""" Add sales orders in the table"""
self.clear_table("sales_orders")
so_list = []
for r in open_so:
if cstr(r['name']) not in so_list:
pp_so = self.append('sales_orders', {})
pp_so.sales_order = r['name']
pp_so.sales_order_date = cstr(r['transaction_date'])
pp_so.customer = cstr(r['customer'])
pp_so.grand_total = flt(r['base_grand_total'])
def get_pending_material_requests(self):
""" Pull Material Requests that are pending based on criteria selected"""
mr_filter = item_filter = ""
if self.from_date:
mr_filter += " and mr.transaction_date >= %(from_date)s"
if self.to_date:
mr_filter += " and mr.transaction_date <= %(to_date)s"
if self.warehouse:
mr_filter += " and mr_item.warehouse = %(warehouse)s"
if self.fg_item:
item_filter += " and item.name = %(item)s"
pending_mr = frappe.db.sql("""
select distinct mr.name, mr.transaction_date
from `tabMaterial Request` mr, `tabMaterial Request Item` mr_item
where mr_item.parent = mr.name
and mr.material_request_type = "Manufacture"
and mr.docstatus = 1
and mr_item.qty > mr_item.ordered_qty {0}
and (exists (select name from `tabItem` item where item.name=mr_item.item_code
and (item.is_pro_applicable = 1 or item.is_sub_contracted_item = 1 {1})))
""".format(mr_filter, item_filter), {
"from_date": self.from_date,
"to_date": self.to_date,
"warehouse": self.warehouse,
"item": self.fg_item
}, as_dict=1)
self.add_mr_in_table(pending_mr)
def add_mr_in_table(self, pending_mr):
""" Add Material Requests in the table"""
self.clear_table("material_requests")
mr_list = []
for r in pending_mr:
if cstr(r['name']) not in mr_list:
mr = self.append('material_requests', {})
mr.material_request = r['name']
mr.material_request_date = cstr(r['transaction_date'])
def get_items(self):
if self.get_items_from == "Sales Order":
self.get_so_items()
elif self.get_items_from == "Material Request":
self.get_mr_items()
def get_so_items(self):
so_list = [d.sales_order for d in self.get('sales_orders') if d.sales_order]
if not so_list:
msgprint(_("Please enter Sales Orders in the above table"))
return []
item_condition = ""
if self.fg_item:
item_condition = ' and so_item.item_code = "{0}"'.format(frappe.db.escape(self.fg_item))
items = frappe.db.sql("""select distinct parent, item_code, warehouse,
(qty - delivered_qty) as pending_qty
from `tabSales Order Item` so_item
where parent in (%s) and docstatus = 1 and qty > delivered_qty
and exists (select * from `tabItem` item where item.name=so_item.item_code
and item.is_pro_applicable = 1) %s""" % \
(", ".join(["%s"] * len(so_list)), item_condition), tuple(so_list), as_dict=1)
if self.fg_item:
item_condition = ' and pi.item_code = "{0}"'.format(frappe.db.escape(self.fg_item))
packed_items = frappe.db.sql("""select distinct pi.parent, pi.item_code, pi.warehouse as warehouse,
(((so_item.qty - so_item.delivered_qty) * pi.qty) / so_item.qty)
as pending_qty
from `tabSales Order Item` so_item, `tabPacked Item` pi
where so_item.parent = pi.parent and so_item.docstatus = 1
and pi.parent_item = so_item.item_code
and so_item.parent in (%s) and so_item.qty > so_item.delivered_qty
and exists (select * from `tabItem` item where item.name=pi.item_code
and item.is_pro_applicable = 1) %s""" % \
(", ".join(["%s"] * len(so_list)), item_condition), tuple(so_list), as_dict=1)
self.add_items(items + packed_items)
def get_mr_items(self):
mr_list = [d.material_request for d in self.get('material_requests') if d.material_request]
if not mr_list:
msgprint(_("Please enter Material Requests in the above table"))
return []
item_condition = ""
if self.fg_item:
item_condition = ' and mr_item.item_code = "' + frappe.db.escape(self.fg_item, percent=False) + '"'
items = frappe.db.sql("""select distinct parent, name, item_code, warehouse,
(qty - ordered_qty) as pending_qty
from `tabMaterial Request Item` mr_item
where parent in (%s) and docstatus = 1 and qty > ordered_qty
and exists (select * from `tabItem` item where item.name=mr_item.item_code
and item.is_pro_applicable = 1) %s""" % \
(", ".join(["%s"] * len(mr_list)), item_condition), tuple(mr_list), as_dict=1)
self.add_items(items)
def add_items(self, items):
self.clear_table("items")
for p in items:
item_details = get_item_details(p['item_code'])
pi = self.append('items', {})
pi.warehouse = p['warehouse']
pi.item_code = p['item_code']
pi.description = item_details and item_details.description or ''
pi.stock_uom = item_details and item_details.stock_uom or ''
pi.bom_no = item_details and item_details.bom_no or ''
pi.planned_qty = flt(p['pending_qty'])
pi.pending_qty = flt(p['pending_qty'])
if self.get_items_from == "Sales Order":
pi.sales_order = p['parent']
elif self.get_items_from == "Material Request":
pi.material_request = p['parent']
pi.material_request_item = p['name']
def validate_data(self):
self.validate_company()
for d in self.get('items'):
if not d.bom_no:
frappe.throw(_("Please select BOM for Item in Row {0}".format(d.idx)))
else:
validate_bom_no(d.item_code, d.bom_no)
if not flt(d.planned_qty):
frappe.throw(_("Please enter Planned Qty for Item {0} at row {1}").format(d.item_code, d.idx))
def raise_production_orders(self):
"""It will raise production order (Draft) for all distinct FG items"""
self.validate_data()
from erpnext.utilities.transaction_base import validate_uom_is_integer
validate_uom_is_integer(self, "stock_uom", "planned_qty")
items = self.get_production_items()
pro_list = []
frappe.flags.mute_messages = True
for key in items:
production_order = self.create_production_order(items[key])
if production_order:
pro_list.append(production_order)
frappe.flags.mute_messages = False
if pro_list:
pro_list = ["""<a href="#Form/Production Order/%s" target="_blank">%s</a>""" % \
(p, p) for p in pro_list]
msgprint(_("{0} created").format(comma_and(pro_list)))
else :
msgprint(_("No Production Orders created"))
def get_production_items(self):
item_dict = {}
for d in self.get("items"):
item_details= {
"production_item" : d.item_code,
"sales_order" : d.sales_order,
"material_request" : d.material_request,
"material_request_item" : d.material_request_item,
"bom_no" : d.bom_no,
"description" : d.description,
"stock_uom" : d.stock_uom,
"company" : self.company,
"wip_warehouse" : "",
"fg_warehouse" : d.warehouse,
"status" : "Draft",
}
""" Club similar BOM and item for processing in case of Sales Orders """
if self.get_items_from == "Material Request":
item_details.update({
"qty": d.planned_qty
})
item_dict[(d.item_code, d.material_request_item, d.warehouse)] = item_details
else:
item_details.update({
"qty":flt(item_dict.get((d.item_code, d.sales_order, d.warehouse),{})
.get("qty")) + flt(d.planned_qty)
})
item_dict[(d.item_code, d.sales_order, d.warehouse)] = item_details
return item_dict
def create_production_order(self, item_dict):
"""Create production order. Called from Production Planning Tool"""
from erpnext.manufacturing.doctype.production_order.production_order import OverProductionError, get_default_warehouse
warehouse = get_default_warehouse()
pro = frappe.new_doc("Production Order")
pro.update(item_dict)
pro.set_production_order_operations()
if warehouse:
pro.wip_warehouse = warehouse.get('wip_warehouse')
if not pro.fg_warehouse:
pro.fg_warehouse = warehouse.get('fg_warehouse')
try:
pro.insert()
return pro.name
except OverProductionError:
pass
def get_so_wise_planned_qty(self):
"""
bom_dict {
bom_no: ['sales_order', 'qty']
}
"""
bom_dict = {}
for d in self.get("items"):
if self.get_items_from == "Material Request":
bom_dict.setdefault(d.bom_no, []).append([d.material_request_item, flt(d.planned_qty)])
else:
bom_dict.setdefault(d.bom_no, []).append([d.sales_order, flt(d.planned_qty)])
return bom_dict
def download_raw_materials(self):
""" Create csv data for required raw material to produce finished goods"""
self.validate_data()
bom_dict = self.get_so_wise_planned_qty()
self.get_raw_materials(bom_dict)
return self.get_csv()
def get_raw_materials(self, bom_dict):
""" Get raw materials considering sub-assembly items
{
"item_code": [qty_required, description, stock_uom, min_order_qty]
}
"""
item_list = []
for bom, so_wise_qty in bom_dict.items():
bom_wise_item_details = {}
if self.use_multi_level_bom:
# get all raw materials with sub assembly childs
# Did not use qty_consumed_per_unit in the query, as it leads to rounding loss
for d in frappe.db.sql("""select fb.item_code,
ifnull(sum(fb.qty/ifnull(bom.quantity, 1)), 0) as qty,
fb.description, fb.stock_uom, it.min_order_qty
from `tabBOM Explosion Item` fb, `tabBOM` bom, `tabItem` it
where bom.name = fb.parent and it.name = fb.item_code
and (is_pro_applicable = 0 or ifnull(default_bom, "")="")
and (is_sub_contracted_item = 0 or ifnull(default_bom, "")="")
and is_stock_item = 1
and fb.docstatus<2 and bom.name=%s
group by item_code, stock_uom""", bom, as_dict=1):
bom_wise_item_details.setdefault(d.item_code, d)
else:
# Get all raw materials considering SA items as raw materials,
# so no childs of SA items
for d in frappe.db.sql("""select bom_item.item_code,
ifnull(sum(bom_item.qty/ifnull(bom.quantity, 1)), 0) as qty,
bom_item.description, bom_item.stock_uom, item.min_order_qty
from `tabBOM Item` bom_item, `tabBOM` bom, tabItem item
where bom.name = bom_item.parent and bom.name = %s and bom_item.docstatus < 2
and bom_item.item_code = item.name
and item.is_stock_item = 1
group by item_code""", bom, as_dict=1):
bom_wise_item_details.setdefault(d.item_code, d)
for item, item_details in bom_wise_item_details.items():
for so_qty in so_wise_qty:
item_list.append([item, flt(item_details.qty) * so_qty[1], item_details.description,
item_details.stock_uom, item_details.min_order_qty, so_qty[0]])
self.make_items_dict(item_list)
def make_items_dict(self, item_list):
for i in item_list:
self.item_dict.setdefault(i[0], []).append([flt(i[1]), i[2], i[3], i[4], i[5]])
def get_csv(self):
item_list = [['Item Code', 'Description', 'Stock UOM', 'Required Qty', 'Warehouse',
'Quantity Requested for Purchase', 'Ordered Qty', 'Actual Qty']]
for item in self.item_dict:
total_qty = sum([flt(d[0]) for d in self.item_dict[item]])
item_list.append([item, self.item_dict[item][0][1], self.item_dict[item][0][2], total_qty])
item_qty = frappe.db.sql("""select warehouse, indented_qty, ordered_qty, actual_qty
from `tabBin` where item_code = %s""", item, as_dict=1)
i_qty, o_qty, a_qty = 0, 0, 0
for w in item_qty:
i_qty, o_qty, a_qty = i_qty + flt(w.indented_qty), o_qty + flt(w.ordered_qty), a_qty + flt(w.actual_qty)
item_list.append(['', '', '', '', w.warehouse, flt(w.indented_qty),
flt(w.ordered_qty), flt(w.actual_qty)])
if item_qty:
item_list.append(['', '', '', '', 'Total', i_qty, o_qty, a_qty])
return item_list
def raise_material_requests(self):
"""
Raise Material Request if projected qty is less than qty required
Requested qty should be shortage qty considering minimum order qty
"""
self.validate_data()
if not self.purchase_request_for_warehouse:
frappe.throw(_("Please enter Warehouse for which Material Request will be raised"))
bom_dict = self.get_so_wise_planned_qty()
self.get_raw_materials(bom_dict)
if self.item_dict:
self.create_material_request()
def get_requested_items(self):
item_projected_qty = self.get_projected_qty()
items_to_be_requested = frappe._dict()
for item, so_item_qty in self.item_dict.items():
requested_qty = 0
total_qty = sum([flt(d[0]) for d in so_item_qty])
if total_qty > item_projected_qty.get(item, 0):
# shortage
requested_qty = total_qty - flt(item_projected_qty.get(item))
# consider minimum order qty
if requested_qty < flt(so_item_qty[0][3]):
requested_qty = flt(so_item_qty[0][3])
# distribute requested qty SO wise
for item_details in so_item_qty:
if requested_qty:
sales_order = item_details[4] or "No Sales Order"
if self.get_items_from == "Material Request":
sales_order = "No Sales Order"
if requested_qty <= item_details[0]:
adjusted_qty = requested_qty
else:
adjusted_qty = item_details[0]
items_to_be_requested.setdefault(item, {}).setdefault(sales_order, 0)
items_to_be_requested[item][sales_order] += adjusted_qty
requested_qty -= adjusted_qty
else:
break
# requested qty >= total so qty, due to minimum order qty
if requested_qty:
items_to_be_requested.setdefault(item, {}).setdefault("No Sales Order", 0)
items_to_be_requested[item]["No Sales Order"] += requested_qty
return items_to_be_requested
def get_projected_qty(self):
items = self.item_dict.keys()
item_projected_qty = frappe.db.sql("""select item_code, sum(projected_qty)
from `tabBin` where item_code in (%s) and warehouse=%s group by item_code""" %
(", ".join(["%s"]*len(items)), '%s'), tuple(items + [self.purchase_request_for_warehouse]))
return dict(item_projected_qty)
def create_material_request(self):
items_to_be_requested = self.get_requested_items()
material_request_list = []
if items_to_be_requested:
for item in items_to_be_requested:
item_wrapper = frappe.get_doc("Item", item)
material_request = frappe.new_doc("Material Request")
material_request.update({
"transaction_date": nowdate(),
"status": "Draft",
"company": self.company,
"requested_by": frappe.session.user,
"material_request_type": "Purchase"
})
for sales_order, requested_qty in items_to_be_requested[item].items():
material_request.append("items", {
"doctype": "Material Request Item",
"__islocal": 1,
"item_code": item,
"item_name": item_wrapper.item_name,
"description": item_wrapper.description,
"uom": item_wrapper.stock_uom,
"item_group": item_wrapper.item_group,
"brand": item_wrapper.brand,
"qty": requested_qty,
"schedule_date": add_days(nowdate(), cint(item_wrapper.lead_time_days)),
"warehouse": self.purchase_request_for_warehouse,
"sales_order": sales_order if sales_order!="No Sales Order" else None
})
material_request.flags.ignore_permissions = 1
material_request.submit()
material_request_list.append(material_request.name)
if material_request_list:
message = ["""<a href="#Form/Material Request/%s" target="_blank">%s</a>""" % \
(p, p) for p in material_request_list]
msgprint(_("Material Requests {0} created").format(comma_and(message)))
else:
msgprint(_("Nothing to request"))
|
agpl-3.0
| -528,266,665,888,626,050
| 36.114165
| 120
| 0.659641
| false
| 2.96838
| false
| false
| false
|
simotek/tanko-bot
|
src/test-client.py
|
1
|
1418
|
# test client - Simon Lees simon@simotek.net
# Copyright (C) 2015 Simon Lees
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
from PyLibs.uiclient import UiClient, UiClientCallbacks
import time
if __name__ == '__main__':
clientCallbacks = UiClientCallbacks()
uiClient = UiClient(clientCallbacks)
count = 0
# Main app event loop
while True:
uiClient.processMessages()
time.sleep(0.01)
count = count+1
if count > 2000:
count = 0
uiClient.sendDriveMotorSpeed(0,0)
elif count == 500:
uiClient.sendDriveMotorSpeed(60,60)
elif count == 1000:
uiClient.sendDriveMotorSpeed(-60,-60)
elif count == 1500:
uiClient.sendDriveMotorSpeed(60,-60)
|
lgpl-2.1
| -5,472,748,171,853,558,000
| 28.541667
| 80
| 0.708745
| false
| 3.884932
| false
| false
| false
|
google-coral/pycoral
|
tests/imprinting_engine_test.py
|
1
|
6413
|
# Lint as: python3
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import collections
from PIL import Image
from pycoral.adapters import classify
from pycoral.adapters import common
from pycoral.learn.imprinting.engine import ImprintingEngine
from pycoral.utils.edgetpu import make_interpreter
from tests import test_utils
import unittest
_MODEL_LIST = [
'mobilenet_v1_1.0_224_l2norm_quant.tflite',
'mobilenet_v1_1.0_224_l2norm_quant_edgetpu.tflite'
]
TrainPoint = collections.namedtuple('TainPoint', ['images', 'class_id'])
TestPoint = collections.namedtuple('TainPoint', ['image', 'class_id', 'score'])
def set_input(interpreter, image):
size = common.input_size(interpreter)
common.set_input(interpreter, image.resize(size, Image.NEAREST))
class TestImprintingEnginePythonAPI(unittest.TestCase):
def _train_and_test(self, model_path, train_points, test_points,
keep_classes):
# Train.
engine = ImprintingEngine(model_path, keep_classes)
extractor = make_interpreter(
engine.serialize_extractor_model(), device=':0')
extractor.allocate_tensors()
for point in train_points:
for image in point.images:
with test_utils.test_image('imprinting', image) as img:
set_input(extractor, img)
extractor.invoke()
embedding = classify.get_scores(extractor)
self.assertEqual(len(embedding), engine.embedding_dim)
engine.train(embedding, point.class_id)
# Test.
trained_model = engine.serialize_model()
classifier = make_interpreter(trained_model, device=':0')
classifier.allocate_tensors()
self.assertEqual(len(classifier.get_output_details()), 1)
if not keep_classes:
self.assertEqual(len(train_points), classify.num_classes(classifier))
for point in test_points:
with test_utils.test_image('imprinting', point.image) as img:
set_input(classifier, img)
classifier.invoke()
top = classify.get_classes(classifier, top_k=1)[0]
self.assertEqual(top.id, point.class_id)
self.assertGreater(top.score, point.score)
return trained_model
# Test full model, not keeping base model classes.
def test_training_l2_norm_model_not_keep_classes(self):
train_points = [
TrainPoint(images=['cat_train_0.bmp'], class_id=0),
TrainPoint(images=['dog_train_0.bmp'], class_id=1),
TrainPoint(
images=['hotdog_train_0.bmp', 'hotdog_train_1.bmp'], class_id=2),
]
test_points = [
TestPoint(image='cat_test_0.bmp', class_id=0, score=0.99),
TestPoint(image='dog_test_0.bmp', class_id=1, score=0.99),
TestPoint(image='hotdog_test_0.bmp', class_id=2, score=0.99)
]
for model_path in _MODEL_LIST:
with self.subTest(model_path=model_path):
self._train_and_test(
test_utils.test_data_path(model_path),
train_points,
test_points,
keep_classes=False)
# Test full model, keeping base model classes.
def test_training_l2_norm_model_keep_classes(self):
train_points = [
TrainPoint(images=['cat_train_0.bmp'], class_id=1001),
TrainPoint(images=['dog_train_0.bmp'], class_id=1002),
TrainPoint(
images=['hotdog_train_0.bmp', 'hotdog_train_1.bmp'], class_id=1003)
]
test_points = [
TestPoint(image='cat_test_0.bmp', class_id=1001, score=0.99),
TestPoint(image='hotdog_test_0.bmp', class_id=1003, score=0.92)
]
for model_path in _MODEL_LIST:
with self.subTest(model_path=model_path):
self._train_and_test(
test_utils.test_data_path(model_path),
train_points,
test_points,
keep_classes=True)
def test_incremental_training(self):
train_points = [TrainPoint(images=['cat_train_0.bmp'], class_id=0)]
retrain_points = [
TrainPoint(images=['dog_train_0.bmp'], class_id=1),
TrainPoint(
images=['hotdog_train_0.bmp', 'hotdog_train_1.bmp'], class_id=2)
]
test_points = [
TestPoint(image='cat_test_0.bmp', class_id=0, score=0.99),
TestPoint(image='dog_test_0.bmp', class_id=1, score=0.99),
TestPoint(image='hotdog_test_0.bmp', class_id=2, score=0.99)
]
for model_path in _MODEL_LIST:
with self.subTest(model_path=model_path):
model = self._train_and_test(
test_utils.test_data_path(model_path),
train_points, [],
keep_classes=False)
with test_utils.temporary_file(suffix='.tflite') as new_model_file:
new_model_file.write(model)
# Retrain based on cat only model.
self._train_and_test(
new_model_file.name,
retrain_points,
test_points,
keep_classes=True)
def test_imprinting_engine_saving_without_training(self):
model_list = [
'mobilenet_v1_1.0_224_l2norm_quant.tflite',
'mobilenet_v1_1.0_224_l2norm_quant_edgetpu.tflite'
]
for model in model_list:
engine = ImprintingEngine(
test_utils.test_data_path(model), keep_classes=False)
with self.assertRaisesRegex(RuntimeError, 'Model is not trained.'):
engine.serialize_model()
def test_imprinting_engine_invalid_model_path(self):
with self.assertRaisesRegex(
ValueError, 'Failed to open file: invalid_model_path.tflite'):
ImprintingEngine('invalid_model_path.tflite')
def test_imprinting_engine_load_extractor_with_wrong_format(self):
expected_message = ('Unsupported model architecture. Input model must have '
'an L2Norm layer.')
with self.assertRaisesRegex(ValueError, expected_message):
ImprintingEngine(
test_utils.test_data_path('mobilenet_v1_1.0_224_quant.tflite'))
if __name__ == '__main__':
test_utils.coral_test_main()
|
apache-2.0
| -5,368,133,874,632,009,000
| 35.856322
| 80
| 0.655076
| false
| 3.462743
| true
| false
| false
|
fritz0705/lglass
|
lglass/object.py
|
1
|
14874
|
class Object(object):
def __init__(self, data=None):
self._data = []
if data is not None:
self.extend(data)
@property
def data(self):
"""List of key-value-tuples."""
return self._data
@property
def object_class(self):
"""Object class of this object."""
return self.data[0][0]
@object_class.setter
def object_class(self, new_class):
"""Set object class to new value."""
self.data[0] = (new_class, self.object_key)
@property
def object_key(self):
"""Object key of this object."""
return self.data[0][1]
@object_key.setter
def object_key(self, new_key):
"""Set object key to new value."""
self.data[0] = (self.object_class, new_key)
@property
def type(self):
"""Alias of `object_class`."""
return self.object_class
@property
def key(self):
"""Alias of `object_key`."""
return self.object_key
@property
def primary_key(self):
"""Primary key of this object. This is the concatenation of all
primary key field values."""
return "".join(self[k] for k in self.primary_key_fields)
@property
def primary_key_fields(self):
"""List of primary key fields."""
return [self.object_class]
def primary_key_object(self):
"""Return object which consists only of the primary key fields."""
return self.__class__(
[(k, v) for k, v in self.data if k in self.primary_key_fields])
def extend(self, ex, append_group=False):
"""Extend object with another object or list."""
if isinstance(ex, str):
ex = parse_object(ex.splitlines())
self._data.extend(map(tuple, ex))
def __getitem__(self, key):
if isinstance(key, str):
key = key.replace("_", "-")
try:
return list(self.get(key))[0]
except IndexError:
raise KeyError(repr(key))
elif isinstance(key, (int, slice)):
return self.data[key]
raise TypeError(
"Expected key to be str or int, got {}".format(
type(key)))
def __setitem__(self, key, value):
if isinstance(value, (list, slice, set)):
for val in value:
self.append(key, val)
return
if isinstance(key, (int, slice)):
self.data[key] = value
elif isinstance(key, str):
key = key.replace("_", "-")
if key not in self:
self.append(key, value)
else:
index = self.indices(key)[0]
self.remove(key)
self.insert(index, key, value)
def __delitem__(self, key):
if isinstance(key, (int, slice)):
key = key.replace("_", "-")
del self.data[key]
else:
self.remove(key)
def __contains__(self, key):
""" Checks whether a given key is contained in the object instance. """
return key in set(self.keys())
def __len__(self):
return len(self.data)
def get(self, key):
"""Return a list of values for a given key."""
return [v for k, v in self._data if k == key]
def getitems(self, key):
"""Returns a list of key-value-tuples for a given key."""
return [kv for kv in self._data if kv[0] == key]
def getfirst(self, key, default=None):
"""Returns the first occurence of a field with matching key. Supports
the `default` keyword."""
try:
return self.get(key)[0]
except IndexError:
return default
def add(self, key, value, index=None):
"""Append or insert a new field."""
value = str(value)
if index is not None:
self._data.insert(index, (key, value))
else:
self._data.append((key, value))
def append(self, key, value):
return self.add(key, value)
def append_group(self, key, value):
"""Appends a field to the last group of fields of the same key."""
try:
idx = self.indices(key)[-1] + 1
return self.insert(idx, key, value)
except IndexError:
return self.append(key, value)
def insert(self, index, key, value):
return self.add(key, value, index)
def indices(self, key):
"""Returns a list of indices of fields with a given key."""
return [i for i, (k, v) in enumerate(self.data) if k == key]
def remove(self, key):
"""Remove all occurences of a key or remove a field with a given
index."""
if isinstance(key, int):
del self._data[key]
return
self._data = [kvpair for kvpair in self._data if kvpair[0] != key]
def items(self):
"""Returns an iterator of key-value-tuples."""
return iter(self.data)
def keys(self):
"""Returns an iterator of field keys."""
return (key for key, _ in self.items())
def values(self):
"""Returns an iterator of field values."""
return (value for _, value in self.items())
def pretty_print(self, min_padding=0, add_padding=8):
"""Generates a pretty-printed version of the object serialization."""
padding = max(max((len(k) for k in self.keys()),
default=0), min_padding) + add_padding
for key, value in self:
value_lines = value.splitlines() or [""]
record = "{key}:{pad}{value}\n".format(
key=key,
pad=" " * (padding - len(key)),
value=value_lines[0])
for line in value_lines[1:]:
if not line:
record += "+\n"
continue
record += "{pad}{value}\n".format(
pad=" " * (padding + 1),
value=line)
yield record
def __str__(self):
return "".join(self.pretty_print())
def __repr__(self):
return "<{module_name}.{class_name} {object_class}: {object_key}>".format(
module_name=type(self).__module__,
class_name=type(self).__name__,
object_class=self.object_class,
object_key=self.object_key)
def __eq__(self, other):
if not isinstance(other, Object):
return NotImplemented
return self.data == other.data
def __ne__(self, other):
return not self == other
def __bool__(self):
return bool(self.data)
def copy(self):
"""Creates new object with same content."""
return self.__class__(self.data)
def to_json(self):
return list(map(list, self.data))
@classmethod
def from_file(cls, fh):
"""Creates an object from a file stream."""
return cls(fh.read())
@classmethod
def from_str(cls, string):
"""Creates an object from a string representation."""
return cls(string)
def parse_objects(lines, pragmas={}):
lines_iter = iter(lines)
obj = []
for line in lines_iter:
if not line.strip() and obj:
obj = parse_object(obj, pragmas=pragmas)
if obj:
yield obj
obj = []
else:
obj.append(line)
if obj:
obj = parse_object(obj, pragmas=pragmas)
if obj:
yield obj
# TODO rewrite object parser
def parse_object(lines, pragmas={}):
r'''This is a simple RPSL parser which expects an iterable which yields lines.
This parser processes the object format, not the policy format. The object
format used by this parser is similar to the format described by the RFC:
Each line consists of key and value, which are separated by a colon ':'.
The ':' can be surrounded by whitespace characters including line breaks,
because this parser doesn't split the input into lines; it's newline unaware.
The format also supports line continuations by beginning a new line of input
with a whitespace character. This whitespace character is stripped, but the
parser will produce a '\n' in the resulting value. Line continuations are
only possible for the value part, which means, that the key and ':' must be
on the same line of input.
We also support an extended format using pragmas, which can define the
processing rules like line-break type, and whitespace preservation. Pragmas
are on their own line, which must begin with "%!", followed by any
amount of whitespace, "pragma", at least one whitespace, followed by the
pragma-specific part.
The following pragmas are supported:
``%! pragma whitespace-preserve [on|off]``
Preserve any whitespace of input in keys and values and don't strip
whitespace.
``%! pragma newline-type [cr|lf|crlf|none]``
Define type of newline by choosing between cr "Mac OS 9", lf "Unix",
crlf "Windows" and none.
``%! pragma rfc``
Reset all pragmas to the RFC-conform values.
``%! pragma stop-at-empty-line [on|off]``
Enforces the parser to stop at an empty line
``%! pragma condense-whitespace [on|off]``
Replace any sequence of whitespace characters with simple space (' ')
``%! pragma strict-ripe [on|off]``
Do completely RIPE database compilant parsing, e.g. don't allow any
space between key and the colon.
``%! pragma hash-comment [on|off]``
Recognize hash '#' as beginning of comment
'''
result = []
default_pragmas = {
"whitespace-preserve": False,
"newline-type": "lf",
"stop-at-empty-line": False,
"condense-whitespace": False,
"strict-ripe": False,
"hash-comment": False
}
_pragmas = dict(default_pragmas)
_pragmas.update(pragmas)
pragmas = _pragmas
for line in lines:
if line.startswith("%!"):
# this line defines a parser instruction, which should be a pragma
values = line[2:].strip().split()
if len(values) <= 1:
raise ValueError(
"Syntax error: Expected pragma type after 'pragma'")
if values[0] != "pragma":
raise ValueError(
"Syntax error: Only pragmas are allowed as parser instructions")
if values[1] == "rfc":
pragmas.update(default_pragmas)
elif values[1] in {"whitespace-preserve", "stop-at-empty-line",
"condense-whitespace", "strict-ripe", "hash-comment"}:
try:
if values[2] not in {"on", "off"}:
raise ValueError(
"Syntax error: Expected 'on' or 'off' as value for '{}' pragma".format(
values[1]))
pragmas[values[1]] = True if values[2] == "on" else False
except IndexError:
raise ValueError(
"Syntax error: Expected value after '{}'".format(
values[1]))
elif values[1] == "newline-type":
try:
if values[2] not in ["cr", "lf", "crlf", "none"]:
raise ValueError(
"Syntax error: Expected 'cr', 'lf', 'crlf' or 'none' as value for 'newline-type' pragma")
pragmas["newline-type"] = values[2]
except IndexError:
raise ValueError(
"Syntax error: Expected value after 'newline-type'")
else:
raise ValueError(
"Syntax error: Unknown pragma: {}".format(values))
continue
# continue if line is empty
if not line.strip():
if pragmas["stop-at-empty-line"]:
break
continue
# remove any comments (text after % and #)
line = line.split("%")[0]
if pragmas["hash-comment"]:
line = line.split("#")[0]
if not line.strip():
continue
# check for line continuations
if line[0] in [' ', '\t', "+"]:
line = line[1:]
if not pragmas["whitespace-preserve"]:
line = line.strip()
entry = result.pop()
value = ({
"cr": "\r",
"lf": "\n",
"crlf": "\r\n",
"none": ""
}[pragmas["newline-type"]]).join([entry[1], line])
result.append((entry[0], value))
continue
try:
key, value = line.split(":", 1)
except ValueError:
raise ValueError("Syntax error: Missing value")
if pragmas["strict-ripe"]:
import re
if not re.match("^[a-zA-Z0-9-]+$", key):
raise ValueError(
"Syntax error: Key doesn't match RIPE database requirements")
if not pragmas["whitespace-preserve"]:
key = key.strip()
value = value.strip()
if pragmas["condense-whitespace"]:
import re
value = re.sub(r"[\s]+", " ", value, flags=re.M | re.S)
result.append((key, value))
return result
def main():
import argparse
import sys
argparser = argparse.ArgumentParser(description="Pretty-print objects")
argparser.add_argument(
"--min-padding",
help="Minimal padding between key and value",
type=int,
default=0)
argparser.add_argument(
"--add-padding",
help="Additional padding between key and value",
type=int,
default=8)
argparser.add_argument("--whois-format", action="store_true")
argparser.add_argument("--tee", "-T", action="store_true")
argparser.add_argument("--inplace", "-i", action="store_true")
argparser.add_argument("files", nargs='*', help="Input files")
args = argparser.parse_args()
options = dict(
min_padding=args.min_padding,
add_padding=args.add_padding)
if args.whois_format:
options["min_padding"] = 16
options["add_padding"] = 0
if not args.files:
obj = Object.from_file(sys.stdin)
print("".join(obj.pretty_print(**options)))
return
for f in args.files:
with open(f, "r") as fh:
obj = Object.from_file(fh)
if args.inplace:
with open(f, "w") as fh:
fh.write("".join(obj.pretty_print(**options)))
if args.tee or not args.inplace:
print("".join(obj.pretty_print(**options)))
if __name__ == "__main__":
main()
|
mit
| 5,814,712,941,590,227,000
| 32.804545
| 117
| 0.538994
| false
| 4.20407
| false
| false
| false
|
timbuchwaldt/bundlewrap
|
bundlewrap/items/users.py
|
1
|
11714
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from logging import ERROR, getLogger
from pipes import quote
from string import ascii_lowercase, digits
from passlib.hash import bcrypt, md5_crypt, sha256_crypt, sha512_crypt
from bundlewrap.exceptions import BundleError
from bundlewrap.items import BUILTIN_ITEM_ATTRIBUTES, Item
from bundlewrap.utils.text import force_text, mark_for_translation as _
getLogger('passlib').setLevel(ERROR)
_ATTRIBUTE_NAMES = {
'full_name': _("full name"),
'gid': _("GID"),
'groups': _("groups"),
'home': _("home dir"),
'password_hash': _("password hash"),
'shell': _("shell"),
'uid': _("UID"),
}
_ATTRIBUTE_OPTIONS = {
'full_name': "-c",
'gid': "-g",
'groups': "-G",
'home': "-d",
'password_hash': "-p",
'shell': "-s",
'uid': "-u",
}
# a random static salt if users don't provide one
_DEFAULT_SALT = "uJzJlYdG"
# bcrypt needs special salts. 22 characters long, ending in ".", "O", "e", "u"
# see https://bitbucket.org/ecollins/passlib/issues/25
_DEFAULT_BCRYPT_SALT = "oo2ahgheen9Tei0IeJohTO"
HASH_METHODS = {
'md5': md5_crypt,
'sha256': sha256_crypt,
'sha512': sha512_crypt,
'bcrypt': bcrypt
}
_USERNAME_VALID_CHARACTERS = ascii_lowercase + digits + "-_"
def _group_name_for_gid(node, gid):
"""
Returns the group name that matches the gid.
"""
group_output = node.run("grep -e ':{}:[^:]*$' /etc/group".format(gid), may_fail=True)
if group_output.return_code != 0:
return None
else:
return group_output.stdout_text.split(":")[0]
def _groups_for_user(node, username):
"""
Returns the list of group names for the given username on the given
node.
"""
groups = node.run("id -Gn {}".format(username)).stdout_text.strip().split(" ")
primary_group = node.run("id -gn {}".format(username)).stdout_text.strip()
groups.remove(primary_group)
return groups
def _parse_passwd_line(line, entries):
"""
Parses a line from /etc/passwd and returns the information as a
dictionary.
"""
result = dict(zip(
entries,
line.strip().split(":"),
))
result['full_name'] = result['gecos'].split(",")[0]
return result
class User(Item):
"""
A user account.
"""
BUNDLE_ATTRIBUTE_NAME = "users"
ITEM_ATTRIBUTES = {
'delete': False,
'full_name': None,
'gid': None,
'groups': None,
'hash_method': 'sha512',
'home': None,
'password': None,
'password_hash': None,
'salt': None,
'shell': None,
'uid': None,
'use_shadow': None,
}
ITEM_TYPE_NAME = "user"
@classmethod
def block_concurrent(cls, node_os, node_os_version):
# https://github.com/bundlewrap/bundlewrap/issues/367
if node_os == 'openbsd':
return [cls.ITEM_TYPE_NAME]
else:
return []
def __repr__(self):
return "<User name:{}>".format(self.name)
def cdict(self):
if self.attributes['delete']:
return None
cdict = self.attributes.copy()
del cdict['delete']
del cdict['hash_method']
del cdict['password']
del cdict['salt']
del cdict['use_shadow']
for key in list(cdict.keys()):
if cdict[key] is None:
del cdict[key]
if 'groups' in cdict:
cdict['groups'] = set(cdict['groups'])
return cdict
def fix(self, status):
if status.must_be_deleted:
self.node.run("userdel {}".format(self.name), may_fail=True)
else:
command = "useradd " if status.must_be_created else "usermod "
for attr, option in sorted(_ATTRIBUTE_OPTIONS.items()):
if (attr in status.keys_to_fix or status.must_be_created) and \
self.attributes[attr] is not None:
if attr == 'groups':
value = ",".join(self.attributes[attr])
else:
value = str(self.attributes[attr])
command += "{} {} ".format(option, quote(value))
command += self.name
self.node.run(command, may_fail=True)
def display_dicts(self, cdict, sdict, keys):
for attr_name, attr_display_name in _ATTRIBUTE_NAMES.items():
if attr_name == attr_display_name:
# Don't change anything; the `del`s below would
# always remove the key entirely!
continue
try:
keys.remove(attr_name)
except ValueError:
pass
else:
keys.append(attr_display_name)
cdict[attr_display_name] = cdict[attr_name]
sdict[attr_display_name] = sdict[attr_name]
del cdict[attr_name]
del sdict[attr_name]
return (cdict, sdict, keys)
def get_auto_deps(self, items):
deps = []
groups = self.attributes['groups'] or []
for item in items:
if item.ITEM_TYPE_NAME == "group":
if not (item.name in groups or (
self.attributes['gid'] in [item.attributes['gid'], item.name] and
self.attributes['gid'] is not None
)):
# we don't need to depend on this group
continue
elif item.attributes['delete']:
raise BundleError(_(
"{item1} (from bundle '{bundle1}') depends on item "
"{item2} (from bundle '{bundle2}') which is set to be deleted"
).format(
item1=self.id,
bundle1=self.bundle.name,
item2=item.id,
bundle2=item.bundle.name,
))
else:
deps.append(item.id)
return deps
def sdict(self):
# verify content of /etc/passwd
if self.node.os in self.node.OS_FAMILY_BSD:
password_command = "grep -ae '^{}:' /etc/master.passwd"
else:
password_command = "grep -ae '^{}:' /etc/passwd"
passwd_grep_result = self.node.run(
password_command.format(self.name),
may_fail=True,
)
if passwd_grep_result.return_code != 0:
return None
if self.node.os in self.node.OS_FAMILY_BSD:
entries = (
'username',
'passwd_hash',
'uid',
'gid',
'class',
'change',
'expire',
'gecos',
'home',
'shell',
)
else:
entries = ('username', 'passwd_hash', 'uid', 'gid', 'gecos', 'home', 'shell')
sdict = _parse_passwd_line(passwd_grep_result.stdout_text, entries)
if self.attributes['gid'] is not None and not self.attributes['gid'].isdigit():
sdict['gid'] = _group_name_for_gid(self.node, sdict['gid'])
if self.attributes['password_hash'] is not None:
if self.attributes['use_shadow'] and self.node.os not in self.node.OS_FAMILY_BSD:
# verify content of /etc/shadow unless we are on OpenBSD
shadow_grep_result = self.node.run(
"grep -e '^{}:' /etc/shadow".format(self.name),
may_fail=True,
)
if shadow_grep_result.return_code != 0:
sdict['password_hash'] = None
else:
sdict['password_hash'] = shadow_grep_result.stdout_text.split(":")[1]
else:
sdict['password_hash'] = sdict['passwd_hash']
del sdict['passwd_hash']
# verify content of /etc/group
sdict['groups'] = set(_groups_for_user(self.node, self.name))
return sdict
def patch_attributes(self, attributes):
if attributes.get('password', None) is not None:
# defaults aren't set yet
hash_method = HASH_METHODS[attributes.get(
'hash_method',
self.ITEM_ATTRIBUTES['hash_method'],
)]
salt = attributes.get('salt', None)
if self.node.os in self.node.OS_FAMILY_BSD:
attributes['password_hash'] = bcrypt.encrypt(
force_text(attributes['password']),
rounds=8, # default rounds for OpenBSD accounts
salt=_DEFAULT_BCRYPT_SALT if salt is None else salt,
)
elif attributes.get('hash_method') == 'md5':
attributes['password_hash'] = hash_method.encrypt(
force_text(attributes['password']),
salt=_DEFAULT_SALT if salt is None else salt,
)
else:
attributes['password_hash'] = hash_method.encrypt(
force_text(attributes['password']),
rounds=5000, # default from glibc
salt=_DEFAULT_SALT if salt is None else salt,
)
if 'use_shadow' not in attributes:
attributes['use_shadow'] = self.node.use_shadow_passwords
for attr in ('gid', 'uid'):
if isinstance(attributes.get(attr), int):
attributes[attr] = str(attributes[attr])
return attributes
@classmethod
def validate_attributes(cls, bundle, item_id, attributes):
if attributes.get('delete', False):
for attr in attributes.keys():
if attr not in ['delete'] + list(BUILTIN_ITEM_ATTRIBUTES.keys()):
raise BundleError(_(
"{item} from bundle '{bundle}' cannot have other "
"attributes besides 'delete'"
).format(item=item_id, bundle=bundle.name))
if 'hash_method' in attributes and \
attributes['hash_method'] not in HASH_METHODS:
raise BundleError(
_("Invalid hash method for {item} in bundle '{bundle}': '{method}'").format(
bundle=bundle.name,
item=item_id,
method=attributes['hash_method'],
)
)
if 'password_hash' in attributes and (
'password' in attributes or
'salt' in attributes
):
raise BundleError(_(
"{item} in bundle '{bundle}': 'password_hash' "
"cannot be used with 'password' or 'salt'"
).format(bundle=bundle.name, item=item_id))
if 'salt' in attributes and 'password' not in attributes:
raise BundleError(
_("{}: salt given without a password").format(item_id)
)
@classmethod
def validate_name(cls, bundle, name):
for char in name:
if char not in _USERNAME_VALID_CHARACTERS:
raise BundleError(_(
"Invalid character in username '{user}': {char} (bundle '{bundle}')"
).format(bundle=bundle.name, char=char, user=name))
if name.endswith("_") or name.endswith("-"):
raise BundleError(_(
"Username '{user}' must not end in dash or underscore (bundle '{bundle}')"
).format(bundle=bundle.name, user=name))
if len(name) > 30:
raise BundleError(_(
"Username '{user}' is longer than 30 characters (bundle '{bundle}')"
).format(bundle=bundle.name, user=name))
|
gpl-3.0
| -5,239,586,966,625,551,000
| 33.863095
| 93
| 0.522452
| false
| 4.073018
| false
| false
| false
|
windelbouwman/ppci-mirror
|
test/test_hexutil.py
|
1
|
2515
|
import unittest
import tempfile
import io
import os
from unittest.mock import patch
from helper_util import relpath, do_long_tests
from ppci.cli.hexutil import hexutil
def new_temp_file(suffix):
""" Generate a new temporary filename """
handle, filename = tempfile.mkstemp(suffix=suffix)
os.close(handle)
return filename
@unittest.skipUnless(do_long_tests('any'), 'skipping slow tests')
class HexutilTestCase(unittest.TestCase):
@patch('sys.stdout', new_callable=io.StringIO)
def test_hexutil_help(self, mock_stdout):
""" Check hexutil help message """
with self.assertRaises(SystemExit) as cm:
hexutil(['-h'])
self.assertEqual(0, cm.exception.code)
self.assertIn('info,new,merge', mock_stdout.getvalue())
@patch('sys.stderr', new_callable=io.StringIO)
def test_hexutil_address_format(self, mock_stderr):
file1 = new_temp_file('.hex')
datafile = relpath('..', 'examples', 'build.xml')
with self.assertRaises(SystemExit) as cm:
hexutil(['new', file1, '10000000', datafile])
self.assertEqual(2, cm.exception.code)
self.assertIn('argument address', mock_stderr.getvalue())
@patch('sys.stdout', new_callable=io.StringIO)
def test_hexutil_no_command(self, mock_stdout):
""" No command given """
with self.assertRaises(SystemExit) as cm:
hexutil([])
self.assertNotEqual(0, cm.exception.code)
@patch('sys.stdout', new_callable=io.StringIO)
def test_hexutil_merge(self, mock_stdout):
""" Create three hexfiles and manipulate those """
file1 = new_temp_file('file1.hex')
file2 = new_temp_file('file2.hex')
file3 = new_temp_file('file3.hex')
datafile = relpath('..', 'docs', 'logo', 'logo.png')
hexutil(['new', file1, '0x10000000', datafile])
hexutil(['new', file2, '0x20000000', datafile])
hexutil(['merge', file1, file2, file3])
hexutil(['info', file3])
self.assertIn("Hexfile containing 2832 bytes", mock_stdout.getvalue())
@patch('sys.stdout', new_callable=io.StringIO)
def test_hexutil_info(self, mock_stdout):
file1 = new_temp_file('file1.hex')
datafile = relpath('..', 'docs', 'logo', 'logo.png')
hexutil(['new', file1, '0x10000000', datafile])
hexutil(['info', file1])
self.assertIn("Hexfile containing 1416 bytes", mock_stdout.getvalue())
if __name__ == '__main__':
unittest.main(verbosity=2)
|
bsd-2-clause
| 3,596,360,861,681,178,600
| 36.537313
| 78
| 0.638171
| false
| 3.623919
| true
| false
| false
|
bertothunder/coursera-algorithms
|
quickfind.py
|
1
|
1155
|
#!/usr/bin/env python3
class QuickFindUF(object):
def __init__(self, N):
self.__id__ = [i for i in range(N)]
self.__count__ = N
def union(self, p, q):
# Check indices
if (p > self.__count__ or q > self.__count__):
print('Indices do not exist')
elif (self.__id__[q] != self.__id__[p]): # Not connected yet
pidp = self.__id__[p]
pidq = self.__id__[q]
self.__id__[p] = pidq
for n in range(self.__count__):
if self.__id__[n] == pidp: # or self.__id__[n] == pidq:
print("Writing {} to {}".format(q, n))
self.__id__[n] = pidq
print("New values: {}".format(self.__id__))
else:
print("Something went wrong!")
def connected(self, p, q):
if (p > self.__count__ or q > self.__count__):
print("Out of indices")
return false
return (self.__id__[p] == self.__id__[q])
if __name__ == '__main__':
uf = QuickFindUF(50)
uf.union(1,49)
uf.union(0,1)
uf.union(45,4)
uf.union(46,45)
print("0:49 => {}".format(uf.connected(0,49))) #true
print("45:46 => {}".format(uf.connected(45,46))) #true
print("1:2 => {}".format(uf.connected(1,2))) #false
print("49:48 => {}".format(uf.connected(49, 48))) #false
|
gpl-3.0
| 641,932,581,429,565,000
| 27.9
| 62
| 0.550649
| false
| 2.649083
| false
| false
| false
|
fuziontech/pgshovel
|
src/main/python/pgshovel/relay/handlers/kafka.py
|
1
|
2002
|
from __future__ import absolute_import
import functools
import threading
import click
from pgshovel.interfaces.streams_pb2 import Message
from pgshovel.relay.entrypoint import entrypoint
from pgshovel.utilities import import_extras
from pgshovel.utilities.protobuf import BinaryCodec
with import_extras('kafka'):
from kafka.client import KafkaClient
from kafka.producer.simple import SimpleProducer
class KafkaWriter(object):
def __init__(self, producer, topic, codec):
self.producer = producer
self.topic = topic
self.codec = codec
# TODO: Might not need to be thread safe any more?
self.__lock = threading.Lock()
self.producer.client.ensure_topic_exists(topic)
def __str__(self):
return 'Kafka writer (topic: %s, codec: %s)' % (self.topic, type(self.codec).__name__)
def __repr__(self):
return '<%s: %s on %r>' % (
type(self).__name__,
self.topic,
[':'.join(map(str, h)) for h in self.producer.client.hosts]
)
def push(self, messages):
with self.__lock: # TODO: ensure this is required, better safe than sorry
self.producer.send_messages(self.topic, *map(self.codec.encode, messages))
@click.command(
help="Publishes mutation batches to the specified Kafka topic.",
)
@click.option(
'--kafka-hosts',
default='127.0.0.1:9092',
help="Kafka broker connection string (as a comma separated list of hosts.)",
)
@click.option(
'--kafka-topic',
default='{cluster}.{set}.mutations',
help="Destination Topic for mutation batch publishing.",
)
@entrypoint
def main(cluster, set, kafka_hosts, kafka_topic):
client = KafkaClient(kafka_hosts)
producer = SimpleProducer(client)
topic = kafka_topic.format(cluster=cluster.name, set=set)
return KafkaWriter(producer, topic, BinaryCodec(Message))
__main__ = functools.partial(main, auto_envvar_prefix='PGSHOVEL')
if __name__ == '__main__':
__main__()
|
apache-2.0
| -3,662,419,686,862,684,000
| 28.441176
| 94
| 0.663836
| false
| 3.686924
| false
| false
| false
|
imiolek-ireneusz/pysiogame
|
game_boards/game044.py
|
1
|
8476
|
# -*- coding: utf-8 -*-
import os
import pygame
import random
import classes.board
import classes.extras as ex
import classes.game_driver as gd
import classes.level_controller as lc
class Board(gd.BoardGame):
def __init__(self, mainloop, speaker, config, screen_w, screen_h):
self.level = lc.Level(self, mainloop, 1, 20)
gd.BoardGame.__init__(self, mainloop, speaker, config, screen_w, screen_h, 13, 9)
def create_game_objects(self, level=1):
self.allow_unit_animations = False
self.allow_teleport = False
self.board.decolorable = False
self.vis_buttons = [0, 1, 1, 1, 1, 1, 1, 1, 0]
self.mainloop.info.hide_buttonsa(self.vis_buttons)
self.board.draw_grid = False
outline_color = (150, 150, 150)
white = (255, 255, 255)
if self.mainloop.scheme is not None and self.mainloop.scheme.dark:
white = (0, 0, 0)
# setting level variable
# data = [x_count, y_count, number_count, top_limit, ordered]
data = [7, 6, 8, 3, 3]
self.chapters = [1, 5, 10, 15, 20]
# rescale the number of squares horizontally to better match the screen width
data[0] = self.get_x_count(data[1], even=False)
self.data = data
self.points = 9
self.layout.update_layout(data[0], data[1])
self.board.level_start(data[0], data[1], self.layout.scale)
if self.mainloop.m.game_variant == 0:
if self.mainloop.scheme is None or not self.mainloop.scheme.dark:
image_src = [os.path.join('memory', "m_img%da.png" % (i)) for i in range(1, 21)]
grey_image_src = [os.path.join('memory', "m_img%db.png" % (i)) for i in range(1, 22)]
else:
image_src = [os.path.join('schemes', "black", "match_animals", "m_img%da.png" % (i)) for i in
range(1, 21)]
grey_image_src = [os.path.join('schemes', "black", "match_animals", "m_img%db.png" % (i)) for i in
range(1, 22)]
elif self.mainloop.m.game_variant == 1:
image_src = [os.path.join('memory', "f_img%da.png" % (i)) for i in range(1, 21)]
grey_image_src = [os.path.join('memory', "m_img22b.png")]
elif self.mainloop.m.game_variant == 2:
image_src = [os.path.join('memory', "n_img%da.png" % (i)) for i in range(2, 22)]
grey_image_src = [os.path.join('memory', "m_img22b.png")]
self.bg_img_src = image_src[self.level.lvl - 1] # os.path.join('memory', "m_img13a.png")
if len(grey_image_src) > 1:
self.bg_img_grey_src = grey_image_src[self.level.lvl - 1] # os.path.join('memory', "m_img13b.png")
else:
self.bg_img_grey_src = "" # grey_image_src[0]
self.bg_img = classes.board.ImgSurf(self.board, 3, 3, white, self.bg_img_src)
self.finished = False
self.choice_list = [x for x in range(1, data[2] + 1)]
self.shuffled = self.choice_list[:]
random.shuffle(self.shuffled)
inversions = ex.inversions(self.shuffled)
if inversions % 2 != 0: # if number of inversions is odd it is unsolvable
# in unsolvable combinations swapping 2 squares will make it solvable
temp = self.shuffled[0]
self.shuffled[0] = self.shuffled[1]
self.shuffled[1] = temp
h1 = (data[1] - data[4]) // 2 # height of the top margin
h2 = data[1] - h1 - data[4] - 1 # height of the bottom margin minus 1 (game label)
w2 = (data[0] - data[3]) // 2 # side margin width
self.check = [h1, h2, w2]
self.board.add_door(w2, h1, data[3], data[4], classes.board.Door, "", white, self.bg_img_grey_src)
self.board.units[0].image.set_colorkey((1, 2, 3))
# create table to store 'binary' solution
# find position of first door square
x = w2
y = h1
self.mini_grid = []
# add objects to the board
line = []
h_start = random.randrange(0, 155, 5)
h_step = 100 // (data[2])
for i in range(data[2]):
h = (h_start + (self.shuffled[i] - 1) * h_step)
caption = str(self.shuffled[i])
self.board.add_unit(x, y, 1, 1, classes.board.ImgShip, caption, white, self.bg_img_src)
self.board.ships[-1].img = self.bg_img.img.copy()
self.board.ships[-1].readable = False
offset_x = 0
offset_y = 0
if self.shuffled[i] in [2, 5, 8]:
offset_x = self.board.scale - 0
elif self.shuffled[i] in [3, 6]:
offset_x = (self.board.scale - 0) * 2
if self.shuffled[i] in [4, 5, 6]:
offset_y = self.board.scale - 0
elif self.shuffled[i] in [7, 8]:
offset_y = (self.board.scale - 0) * 2
self.board.ships[-1].img_pos = (-offset_x, -offset_y)
line.append(i)
x += 1
if x >= w2 + data[3] or i == data[2] - 1:
x = w2
y += 1
self.mini_grid.append(line)
line = []
# mini img below game
self.board.add_unit(w2 + data[3] - 2, data[1] - 1, 1, 1, classes.board.ImgShip, "", white, self.bg_img_src)
self.preview = self.board.ships[-1]
self.preview.immobilize()
self.preview.outline = False
# draw 4 lines on the mini preview
step = self.board.scale // 3
pygame.draw.line(self.preview.img, outline_color, [step, 0], [step, step * 3], 1)
pygame.draw.line(self.preview.img, outline_color, [step * 2, 0], [step * 2, step * 3], 1)
pygame.draw.line(self.preview.img, outline_color, [0, step], [step * 3, step], 1)
pygame.draw.line(self.preview.img, outline_color, [0, step * 2], [step * 3, step * 2], 1)
self.preview.update_me = True
self.outline_all(outline_color, 1)
# horizontal
self.board.add_unit(0, 0, data[0], 1, classes.board.Obstacle, "", white, "", 7) # top
self.board.add_unit(0, h1 + data[4], data[0], 1, classes.board.Obstacle, "", white, "", 7) # bottom 1
# side obstacles
self.board.add_unit(0, h1, w2, data[4], classes.board.Obstacle, "", white, "", 7) # left
self.board.add_unit(w2 + data[3], h1, w2, data[4], classes.board.Obstacle, "", white, "", 7) # right
# self.board.all_sprites_list.move_to_front(self.board.units[0])
self.board.all_sprites_list.move_to_back(self.board.units[0])
self.board.all_sprites_list.move_to_back(self.board.board_bg)
def handle(self, event):
gd.BoardGame.handle(self, event) # send event handling up
if event.type == pygame.MOUSEBUTTONUP:
self.check_result()
def update(self, game):
game.fill((255, 255, 255))
gd.BoardGame.update(self, game) # rest of painting done by parent
def check_result(self):
if self.changed_since_check and self.finished == False:
ships = []
current = [x for x in range(self.data[2] + 1)] # self.choice_list[:]
# collect value and x position on the grid from ships list
for i in range(len(self.board.ships) - 1):
x = self.board.ships[i].grid_x - self.check[2]
y = self.board.ships[i].grid_y - self.check[0]
w = self.data[3]
h = self.data[4]
pos = x + (y * w)
current[pos] = int(self.board.ships[i].value)
del (current[-1])
if self.choice_list == current:
# self.update_score(self.points)
self.mainloop.db.update_completion(self.mainloop.userid, self.active_game.dbgameid, self.level.lvl)
self.level.update_level_dictx()
self.mainloop.redraw_needed[1] = True
self.finished = True
self.board.units[0].img = self.bg_img.img.copy()
self.board.all_sprites_list.move_to_front(self.board.units[0])
self.board.units[0].update_me = True
# copied from level controller:
index = random.randrange(0, len(self.dp["Great job!"]))
praise = self.dp["Great job!"][index]
self.say(praise, 6)
self.board.units[2].value = praise
self.board.units[2].update_me = True
|
gpl-3.0
| 6,823,931,356,465,523,000
| 43.846561
| 115
| 0.549788
| false
| 3.191265
| false
| false
| false
|
sandlbn/django-theatre
|
theatre_performance/views.py
|
1
|
6668
|
# -*- coding: utf-8 -*-
__author__ = 'sandlbn'
from .models import Performance
from .models import PerformanceFrontPage
from .models import PerformanceGenre
from .models import PerformanceTime
from .models import PerformanceDonor
from theatre_news.models import News
from .forms import PerformanceForm
from .forms import PerformanceTimeForm
from .forms import PerformanceDonorForm
from .forms import PerformanceGenreForm
from django.views.generic import ListView
from django.views.generic import DetailView
from django.views.generic import CreateView
from django.views.generic import UpdateView
from django.views.generic import DeleteView
from django.views.generic import TemplateView
from django.utils.datetime_safe import datetime
from braces.views import StaffuserRequiredMixin
from django.core.urlresolvers import reverse_lazy
from theatre_core.utils.path import template_path
class FrontPageView(ListView):
''' Start Page with promoted Performances '''
queryset = PerformanceFrontPage.objects.filter(
)
def get_context_data(self, *args, **kwargs):
context = super(FrontPageView, self).get_context_data(**kwargs)
context["performances"] = self.queryset
context['news'] = News.objects.filter(
published=True).order_by('-id')[:3]
return context
template_name = template_path(PerformanceTime, 'frontend', 'index')
class PerformanceView(DetailView):
''' Single Performance '''
model = Performance
slug_field = 'slug'
template_name = 'performance.html'
class PerformanceTimeDetailView(DetailView):
''' Single Performance Time '''
model = PerformanceTime
context_object_name = 'performance'
template_name = template_path(PerformanceTime, 'frontend', 'detail')
class PerformanceList(TemplateView):
''' Start Page with listed Performances '''
template_name = template_path(Performance, 'frontend', 'time_calendar')
class PerformanceBackendListView(StaffuserRequiredMixin, ListView):
''' Start Page with listed Performances '''
model = Performance
template_name = template_path(Performance, 'backend', 'list')
class PerformanceCreateView(StaffuserRequiredMixin, CreateView):
model = Performance
form_class = PerformanceForm
success_url = reverse_lazy('backend-performance-list')
template_name = template_path(Performance, 'backend', 'create_form')
class PerformanceUpdateView(StaffuserRequiredMixin, UpdateView):
model = Performance
form_class = PerformanceForm
success_url = reverse_lazy('backend-performance-list')
template_name = template_path(Performance, 'backend', 'update_form')
class PerformanceDeleteView(StaffuserRequiredMixin, DeleteView):
model = Performance
success_url = reverse_lazy('backend-performance-list')
template_name = template_path(Performance, 'backend', 'confirm_delete')
class PerformanceGenreBackendListView(StaffuserRequiredMixin, ListView):
''' Start Page with listed Performances '''
model = PerformanceGenre
template_name = template_path(PerformanceGenre, 'backend', 'list')
class PerformanceGenreCreateView(StaffuserRequiredMixin, CreateView):
model = PerformanceGenre
form_class = PerformanceGenreForm
success_url = reverse_lazy('backend-performance-genre-list')
template_name = template_path(PerformanceGenre, 'backend', 'create_form')
class PerformanceGenreUpdateView(StaffuserRequiredMixin, UpdateView):
model = PerformanceGenre
form_class = PerformanceGenreForm
success_url = reverse_lazy('backend-performance-genre-list')
template_name = template_path(PerformanceGenre, 'backend', 'update_form')
class PerformanceGenreDeleteView(StaffuserRequiredMixin, DeleteView):
model = PerformanceGenre
success_url = reverse_lazy('backend-performance-genre-list')
template_name = template_path(PerformanceGenre, 'backend',
'confirm_delete')
class PerformanceTimeBackendListView(StaffuserRequiredMixin, ListView):
''' Start Page with listed Performances '''
model = PerformanceTime
template_name = template_path(PerformanceTime, 'backend', 'list')
class PerformanceTimeCreateView(StaffuserRequiredMixin, CreateView):
model = PerformanceTime
form_class = PerformanceTimeForm
success_url = reverse_lazy('backend-performance-time-list')
template_name = template_path(PerformanceTime, 'backend', 'create_form')
class PerformanceTimeUpdateView(StaffuserRequiredMixin, UpdateView):
model = PerformanceTime
form_class = PerformanceTimeForm
success_url = reverse_lazy('backend-performance-time-list')
template_name = template_path(PerformanceTime, 'backend', 'update_form')
class PerformanceTimeDeleteView(StaffuserRequiredMixin, DeleteView):
model = PerformanceTime
success_url = reverse_lazy('backend-performance-time-list')
template_name = template_path(PerformanceTime, 'backend', 'confirm_delete')
class PerformanceDonorBackendListView(StaffuserRequiredMixin, ListView):
''' Start Page with listed Performance Donor '''
template_name = template_path(PerformanceDonor, 'backend', 'list')
def get_queryset(self):
performance_pk = self.kwargs['performance_pk']
return PerformanceDonor.objects.filter(performance=performance_pk)
def get_context_data(self, **kwargs):
context = super(PerformanceDonorBackendListView,
self).get_context_data(**kwargs)
context['performance_pk'] = self.kwargs['performance_pk']
return context
class PerformanceDonorCreateView(StaffuserRequiredMixin, CreateView):
model = PerformanceDonor
form_class = PerformanceDonorForm
success_url = reverse_lazy('backend-performance-donor-list')
template_name = template_path(PerformanceDonor, 'backend', 'create_form')
def get_initial(self, **kwargs):
initial = super(PerformanceDonorCreateView, self).get_initial(**kwargs)
performance_pk = self.kwargs['performance_pk']
initial['performance'] = performance_pk
return initial
class PerformanceDonorUpdateView(StaffuserRequiredMixin, UpdateView):
model = PerformanceDonor
form_class = PerformanceDonorForm
success_url = reverse_lazy('backend-performance-donor-list')
template_name = template_path(PerformanceDonor, 'backend', 'update_form')
class PerformanceDonorDeleteView(StaffuserRequiredMixin, DeleteView):
model = PerformanceTime
success_url = reverse_lazy('backend-performance-donor-list')
template_name = template_path(PerformanceDonor, 'backend',
'confirm_delete')
|
lgpl-3.0
| -5,993,623,482,546,329,000
| 32.847716
| 79
| 0.741602
| false
| 4.277101
| false
| false
| false
|
mugurrus/ally-py-common
|
hr-user/hr/user/impl/user.py
|
1
|
7083
|
'''
Created on Mar 6, 2012
@package: hr user
@copyright: 2011 Sourcefabric o.p.s.
@license http://www.gnu.org/licenses/gpl-3.0.txt
@author: Mihai Balaceanu
Implementation for user services.
'''
from functools import reduce
import hashlib
from ally.api.criteria import AsLike, AsBoolean
from ally.api.validate import validate
from ally.container import wire
from ally.container.ioc import injected
from ally.container.support import setup
from ally.internationalization import _
from sql_alchemy.impl.entity import EntityServiceAlchemy
from sql_alchemy.support.util_service import insertModel
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.sql.expression import or_
from ally.api.error_p1 import ConflictError, InvalidError
from hr.user.api.user import IUserService, QUser, User, Password, Avatar
from hr.user.meta.user import UserMapped
from ally.api.model import Content
from ally.cdm.spec import ICDM, PathNotFound
from urllib.request import urlopen
# --------------------------------------------------------------------
@injected
@validate(UserMapped)
@setup(IUserService, name='userService')
class UserServiceAlchemy(EntityServiceAlchemy, IUserService):
'''
Implementation for @see: IUserService
'''
cdmAvatar = ICDM; wire.entity('cdmAvatar')
# the content delivery manager where to publish avatar
avatar_url = 'http://www.gravatar.com/avatar/%(hash_email)s?s=%(size)s'; wire.config('avatar_url', doc='''
The url from where the avatar is loaded.''')
default_avatar_size = 200; wire.config('default_avatar_size', doc='''
Default user avatar image size.''')
allNames = {UserMapped.UserName, UserMapped.FullName, UserMapped.EMail, UserMapped.PhoneNumber}
def __init__(self):
'''
Construct the service
'''
assert isinstance(self.default_avatar_size, int), 'Invalid default user avatar image size %s' % self.default_avatar_size
assert isinstance(self.allNames, set), 'Invalid all name %s' % self.allNames
assert isinstance(self.cdmAvatar, ICDM), 'Invalid CDM %s' % self.cdmAvatar
EntityServiceAlchemy.__init__(self, UserMapped, QUser, all=self.queryAll, inactive=self.queryInactive)
def getById(self, identifier, scheme='http'):
user = super().getById(identifier)
assert isinstance(user, UserMapped)
if user.avatarPath:
try:
self.cdmAvatar.getMetadata(user.avatarPath)
user.Avatar = self.cdmAvatar.getURI(user.avatarPath, scheme)
except PathNotFound:
user.Avatar = user.avatarPath
elif user.EMail:
user.Avatar = self.avatar_url % {'hash_email': hashlib.md5(user.EMail.lower().encode()).hexdigest(),
'size': self.default_avatar_size}
return user
def getAll(self, q=None, **options):
'''
@see: IUserService.getAll
'''
if q is None: q = QUser(inactive=False)
elif QUser.inactive not in q: q.inactive = False
# Making sure that the default query is for active.
return super().getAll(q, **options)
def update(self, user):
'''
@see: IUserService.update
'''
assert isinstance(user, User), 'Invalid user %s' % user
if user.UserName is not None: user.UserName = user.UserName.lower()
self.checkUser(user, user.Id)
return super().update(user)
def insert(self, user):
'''
@see: IUserService.insert
'''
assert isinstance(user, User), 'Invalid user %s' % user
user.UserName = user.UserName.lower()
self.checkUser(user)
userDb = insertModel(UserMapped, user, password=user.Password)
assert isinstance(userDb, UserMapped), 'Invalid user %s' % userDb
return userDb.Id
def changePassword(self, id, password):
'''
@see: IUserService.changePassword
'''
assert isinstance(password, Password), 'Invalid password change %s' % password
try:
sql = self.session().query(UserMapped)
userDb = sql.filter(UserMapped.Id == id).filter(UserMapped.password == password.OldPassword).one()
except NoResultFound: raise InvalidError(_('Invalid old password'), Password.OldPassword)
assert isinstance(userDb, UserMapped), 'Invalid user %s' % userDb
userDb.password = password.NewPassword
def setAvatar(self, id, avatar, scheme='http', content=None):
'''
@see: IUserService.setAvatar
'''
assert isinstance(avatar, Avatar), 'Invalid avatar %s' % avatar
assert content is None or isinstance(content, Content), 'Invalid content %s' % content
user = super().getById(id)
assert isinstance(user, UserMapped), 'Invalid user identifer %s' % id
if avatar.URL:
try:
urlopen(avatar.URL)
user.avatarPath = avatar.URL
except ValueError:
raise InvalidError(_('Invalid avatar URL'))
elif content is not None:
user.avatarPath = '%s/%s' % (id, content.name)
self.cdmAvatar.publishContent(user.avatarPath, content, {})
avatar.URL = self.cdmAvatar.getURI(user.avatarPath, scheme)
else:
raise InvalidError(_('Avatar must be supplied'))
return avatar.URL
# ----------------------------------------------------------------
def checkUser(self, user, userId=None):
''' Checks if the user name is not conflicting with other users names.'''
if User.Active not in user or user.Active:
if user.UserName is None:
assert userId is not None, 'Invalid user id %s' % userId
userName = self.session().query(UserMapped.UserName).filter(UserMapped.Id == userId)
else: userName = user.UserName
sql = self.session().query(UserMapped.Id).filter(UserMapped.UserName == userName)
sql = sql.filter(UserMapped.Active == True)
if userId is not None: sql = sql.filter(UserMapped.Id != userId)
if sql.count() > 0: raise ConflictError(_('There is already an active user with this name'), User.UserName)
def queryAll(self, sql, crit):
'''
Processes the all query.
'''
assert isinstance(crit, AsLike), 'Invalid criteria %s' % crit
filters = []
if AsLike.like in crit:
for col in self.allNames: filters.append(col.like(crit.like))
elif AsLike.ilike in crit:
for col in self.allNames: filters.append(col.ilike(crit.ilike))
sql = sql.filter(reduce(or_, filters))
return sql
def queryInactive(self, sql, crit):
'''
Processes the inactive query.
'''
assert isinstance(crit, AsBoolean), 'Invalid criteria %s' % crit
return sql.filter(UserMapped.Active == (crit.value is False))
|
gpl-3.0
| -8,506,056,176,071,447,000
| 38.792135
| 128
| 0.620076
| false
| 4.118023
| false
| false
| false
|
shobhitmishra/CodingProblems
|
LeetCode/Session3/SencondMinInABTree.py
|
1
|
1590
|
import sys
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def findSecondMinimumValue(self, root: TreeNode) -> int:
if not root or (not root.left and not root.right):
return -1
if root.left.val < root.right.val:
secondMinInLeft = self.findSecondMinimumValue(root.left)
return root.right.val if secondMinInLeft == -1 else min(root.right.val, secondMinInLeft)
elif root.left.val > root.right.val:
secondMinInRight = self.findSecondMinimumValue(root.right)
return root.left.val if secondMinInRight == -1 else min(root.left.val, secondMinInRight)
else:
secondMinInLeft = self.findSecondMinimumValue(root.left)
secondMinInRight = self.findSecondMinimumValue(root.right)
if secondMinInLeft == -1 and secondMinInRight == -1:
return -1
elif secondMinInLeft == -1:
return secondMinInRight
elif secondMinInRight == -1:
return secondMinInLeft
return min(secondMinInLeft, secondMinInRight)
root = TreeNode(10)
root.left = TreeNode(3)
root.left.left = TreeNode(2)
root.left.right = TreeNode(8)
root.left.right.left = TreeNode(7)
root.left.right.right = TreeNode(9)
root.right = TreeNode(15)
root.right.left = TreeNode(13)
root.right.right = TreeNode(17)
root.right.right.right = TreeNode(19)
ob = Solution()
print(ob.findSecondMinimumValue(root))
|
mit
| -278,850,236,724,756,200
| 35.159091
| 100
| 0.627673
| false
| 3.613636
| false
| false
| false
|
junhaodong/misc
|
web_crawler/find_email_addresses.py
|
1
|
3846
|
import dryscrape, re, sys
from bs4 import BeautifulSoup
class EmailCrawler:
"""
Takes a domain name and prints out a list of email addresses found on that web page
or a lower level web page with the same given domain name.
Stores emails, paths, and visited_paths as sets to avoid duplicates.
Uses Dryscrape to dynamically scrape text of JavaScript generated and static websites.
Uses BeautifulSoup to search for valid href's to continue crawling on.
"""
emailRE = re.compile("[\w.+-]+@(?!\dx)[\w-]+\.[\w.-]+[\w-]+")
def __init__(self, domain):
if 'http' not in domain:
domain = 'http://' + domain
self.url = domain.lower()
self.session = dryscrape.Session(base_url=self.url)
self.emails = set()
self.paths = set()
self.visited_paths = set()
self.num_pages_limit = 50
self.session.set_attribute('auto_load_images', False)
def is_valid_tag(self, tag):
"""Checks if a tag contains a valid href that hasn't been visited yet."""
if tag.has_attr('href') and len(tag['href']) > 0:
href = tag['href']
complete_href = self.session.complete_url(href)
is_relative = self.url in complete_href
is_visited = complete_href in self.visited_paths
is_style_sheet = tag.name == "link"
is_jumpTo = "#" in href
is_mailTo = "mailto" in href
is_js = "javascript:" in href
return is_relative and \
not (is_visited or is_style_sheet or is_jumpTo or is_mailTo or is_js)
else:
return False
def find_emails_and_paths(self, path=None):
# Load the DOM
try:
self.session.visit(path)
except:
print("Error accessing the given URL")
return
# Pass the DOM as HTML into the lxml parser
print("Crawling on:\t" + path)
response = self.session.body()
soup = BeautifulSoup(response, "lxml")
# Add new emails to `self.emails`
for email in re.findall(self.emailRE, response):
self.emails.add(email)
# Mark the current path as visited
self.visited_paths.add(path)
# Add new paths to `self.paths`
for tag in soup.find_all(self.is_valid_tag):
href = self.session.complete_url(tag['href']).lower()
self.paths.add(href)
def find(self):
"""
Crawls through new paths until the page limit has been reached or
there are no more discoverable paths.
"""
self.paths.add(self.url)
while len(self.visited_paths) < self.num_pages_limit and \
len(self.paths) > 0:
self.find_emails_and_paths(path=self.paths.pop())
def print_emails(self):
# Print the emails found (if any)
if len(self.emails) > 0:
print("\nFound these email addresses:")
for email in self.emails:
print("\t" + email)
else:
print("\nNo email addresses found.")
def main():
"""
Initializes the crawler with the given domain name
and optional maximum number of pages to search.
Finds and prints any emails found.
"""
if len(sys.argv) >= 2:
crawler = EmailCrawler(sys.argv[1])
if len(sys.argv) >= 3 and sys.argv[2].isdigit():
crawler.num_pages_limit = int(sys.argv[2])
print("Beginning crawl with a limit of " + str(crawler.num_pages_limit) + " pages...\n")
crawler.find()
crawler.print_emails()
else:
print("Error: Please enter a domain to search on and an optional page limit (default=50).")
print("Example: `python find_email_addresses.py jana.com 30`")
sys.exit(1)
if __name__ == "__main__":
main()
|
mit
| -1,839,977,054,518,523,100
| 34.611111
| 99
| 0.583983
| false
| 3.900609
| false
| false
| false
|
strus38/WPaaS
|
wpars/tasks.py
|
1
|
8400
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
tasks
~~~~~
This file contains all the tasks used by the REST API
So, all the wpar commands used.
:copyright: (c) 2013 by @MIS
"""
import os
import subprocess
import config
import tarfile
from celery import Celery
from celery.result import AsyncResult
celery = Celery('tasks', backend=config.BACKEND_URI, broker=config.BROCKER_URI)
def build_cmd_line(data):
cmd_opts=[]
if 'password' in data and data['password'] != "":
cmd_opts.append('-P')
cmd_opts.append(data['password'])
if 'start' in data and data['start'] == "yes":
cmd_opts.append('-s')
if 'network' in data:
if 'address' in data['network'] and data['network']['address'] != "":
if not '-N' in cmd_opts:
cmd_opts.append('-N')
cmd_opts.append('address='+data['network']['address'])
if 'netmask' in data['network'] and data['network']['netmask'] != "":
if not '-N' in cmd_opts:
cmd_opts.append('-N')
cmd_opts.append('netmask='+data['network']['netmask'])
if 'interface' in data['network'] and data['network']['interface'] != "":
if not '-N' in cmd_opts:
cmd_opts.append('-N')
cmd_opts.append('interface='+data['network']['interface'])
if 'ipv4' in data['network'] and data['network']['ipv4'] != "":
if not '-N' in cmd_opts:
cmd_opts.append('-N')
cmd_opts.append('address='+data['network']['ipv4'])
if 'broadcast' in data['network'] and data['network']['broadcast'] != "":
if not '-N' in cmd_opts:
cmd_opts.append('-N')
cmd_opts.append('broadcast='+data['network']['broadcast'])
if 'ipv6' in data['network'] and data['network']['ipv6'] != "":
if not '-N' in cmd_opts:
cmd_opts.append('-N')
cmd_opts.append('address6='+data['network']['ipv6'])
if 'prefixlen' in data['network'] and data['network']['prefixlen'] != "":
if not '-N' in cmd_opts:
cmd_opts.append('-N')
cmd_opts.append('prefixlen='+data['network']['prefixlen'])
if 'hostname' in data:
if data['hostname'] != "":
cmd_opts.append('-h')
cmd_opts.append(data['hostname'])
if 'autostart' in data and data['autostart'] == "yes":
cmd_opts.append('-A')
if 'backupdevice' in data:
if data['backupdevice'] != "":
cmd_opts.append('-B')
cmd_opts.append(data['backupdevice'])
if 'checkpointable' in data and data['checkpointable'] == "yes":
cmd_opts.append('-c')
if 'versioned' in data and data['versioned'] == "yes":
cmd_opts.append('-C')
if 'basedir' in data:
if data['basedir'] != "":
cmd_opts.append('-d')
cmd_opts.append(data['basedir'])
if 'filesets' in data:
if data['filesets'] != "":
cmd_opts.append('-e')
cmd_opts.append(data['filesets'])
if 'force' in data and data['force'] == "yes":
cmd_opts.append('-F')
if 'vg' in data:
if data['vg'] != "":
cmd_opts.append('-g')
cmd_opts.append(data['vg'])
if 'postscript' in data:
if data['postscript'] != "":
cmd_opts.append('-k')
cmd_opts.append(data['postscript'])
if 'privateRWfs' in data and data['privateRWfs'] == "yes":
cmd_opts.append('-l')
if 'mountdir' in data:
if 'dir' in data['mountdir'] and data['mountdir']['dir'] != "":
cmd_opts.append('-M')
cmd_opts.append('directory='+data['mountdir']['dir'])
if 'vfs' in data['mountdir'] and data['mountdir']['vfs'] != "":
cmd_opts.append('vfs='+data['mountdir']['vfs'])
if 'dev' in data['mountdir'] and data['mountdir']['dev'] != "":
cmd_opts.append('dev='+data['mountdir']['dev'])
if 'dupnameresolution' in data and data['dupnameresolution'] == "yes":
cmd_opts.append('-r')
if 'devname' in data and data['devname'] != "":
if '-D' not in cmd_opts:
cmd_opts.append('-D')
cmd_opts.append('devname='+data['devname'])
if 'rootvg' in data and data['rootvg'] != "no":
if '-D' not in cmd_opts:
cmd_opts.append('-D')
cmd_opts.append('rootvg='+data['rootvg'])
return cmd_opts
def _run_cmd(cmd, wait=True):
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
if err is None or err is "":
ret = 0
if wait:
ret = process.wait()
return ret,out,err
@celery.task
def wpar_mkwpar(name, options):
wpar_cmd = ['/usr/sbin/mkwpar', '-n', name]
# Let's add more options if needed
wpar_cmd += options
# Launch the command
ret,out,err = _run_cmd(wpar_cmd)
return ret,out,err
@celery.task
def wpar_check_task(task_id):
async_res = AsyncResult(task_id)
return async_res
@celery.task
def wpar_startwpar(name):
wpar_cmd = ['/usr/sbin/startwpar', name]
ret,out,err = _run_cmd(wpar_cmd)
return ret,out,err
@celery.task
def wpar_stopwpar(name):
wpar_cmd = ['/usr/sbin/stopwpar', name]
ret,out,err = _run_cmd(wpar_cmd)
return ret,out,err
@celery.task
def wpar_rebootwpar(name):
wpar_cmd = ['/usr/sbin/rebootwpar', name]
ret,out,err = _run_cmd(wpar_cmd)
return ret,out,err
@celery.task
def wpar_rmwpar(name):
# Add the -F flag to stop it whatever its state
wpar_cmd = ['/usr/sbin/rmwpar', '-F', name]
ret,out,err = _run_cmd(wpar_cmd)
return ret,out,err
@celery.task
def wpar_restorewpar(name, file):
wpar_cmd = ['/usr/sbin/restwpar', '-f', file, name]
ret,out,err = _run_cmd(wpar_cmd)
return ret,out,err
@celery.task
def wpar_savewpar(name, file):
wpar_cmd = ['/usr/bin/savewpar', '-f', file, name]
ret,out,err = _run_cmd(wpar_cmd)
return ret,out,err
@celery.task
def wpar_migwpar(name, file):
wpar_cmd = ['/usr/sbin/migwpar', '-d', file, '-C', name]
ret,out,err = _run_cmd(wpar_cmd)
return ret,out,err
@celery.task
def wpar_syncwpar(name):
wpar_cmd = ['/usr/sbin/syncwpar', name]
ret,out,err = _run_cmd(wpar_cmd)
return ret,out,err
@celery.task
def wpar_listwpar():
wpar_list_cmd = ['/usr/sbin/lswpar','-c']
ret,out,err = _run_cmd(wpar_list_cmd)
return out
@celery.task
def wpar_listdetailswpar(wpar_name):
wpar_list_cmd = ['/usr/sbin/lswpar','-L', wpar_name]
ret,out,err = _run_cmd(wpar_list_cmd)
return out
@celery.task
def host_stats():
stat_cmd = ['/usr/bin/lparstat','-i']
ret,out,err = _run_cmd(stat_cmd)
return out
@celery.task
def host_cpustats():
proc_cmd = ['/usr/bin/pmlist','-s']
ret,out,err = _run_cmd(proc_cmd)
return out
@celery.task
def host_status():
status_cmd = ['/home/misoard/wparrip.sh']
ret,out,err = _run_cmd(status_cmd)
return out
@celery.task
def host_shutdown():
shutdown_cmd = ['/etc/shutdown']
ret,out,err = _run_cmd(shutdown_cmd)
return out
@celery.task
def host_reboot():
reboot_cmd = ['/etc/reboot','now']
ret,out,err = _run_cmd(reboot_cmd)
return out
@celery.task
def host_os_stats():
os_cmd = ['/usr/bin/oslevel']
ret,out,err = _run_cmd(os_cmd)
return out
@celery.task
def host_network_devices():
net_cmd = ['/etc/lsdev','-Cc','if']
ret,out,err = _run_cmd(net_cmd)
return out
@celery.task
def image_inspect(image_fullpath):
ls_cmd = ['/usr/bin/lsmksysb','-lf',image_fullpath]
ret,out,err = _run_cmd(ls_cmd)
return ret,out,err
@celery.task
def image_create(path, data):
files = []
# First create the <image_local>/<image_name>.info file. It acts as the image repository locally
# to know which images are used by the WPARs (do not want it to be in a DB since it could be used
# without this program.)
info_file = path+'/'+data['name']+'.info'
with open(info_file, 'w') as outfile:
json.dump(data, outfile)
# Now, depending on the image, we build a .tgz file containing either:
# - The .info file only
# - The .info file and the mksysb
# - The .info file and whatever NFS tree or program
files.append(data['name']+'.info')
if data['type'] == 'mksysb':
files.append(data['name'])
_targzip_content(files)
return 0,data['id'],""
def _targzip_content(path, files):
full=path+'/'+data['name']+'.tgz'
tar = tarfile.open(full, "w:gz")
for name in files:
tar.add(path+'/'+name)
tar.close()
return full
|
apache-2.0
| -7,396,022,001,565,113,000
| 28.166667
| 98
| 0.647143
| false
| 2.770449
| false
| false
| false
|
thisisshi/cloud-custodian
|
c7n/resources/ssm.py
|
1
|
27799
|
# Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
import json
import hashlib
import operator
from concurrent.futures import as_completed
from c7n.actions import Action
from c7n.exceptions import PolicyValidationError
from c7n.filters import Filter, CrossAccountAccessFilter
from c7n.query import QueryResourceManager, TypeInfo
from c7n.manager import resources
from c7n.tags import universal_augment
from c7n.utils import chunks, get_retry, local_session, type_schema, filter_empty
from c7n.version import version
from .aws import shape_validate
from .ec2 import EC2
@resources.register('ssm-parameter')
class SSMParameter(QueryResourceManager):
class resource_type(TypeInfo):
service = 'ssm'
enum_spec = ('describe_parameters', 'Parameters', None)
name = "Name"
id = "Name"
universal_taggable = True
arn_type = "parameter"
cfn_type = 'AWS::SSM::Parameter'
retry = staticmethod(get_retry(('Throttled',)))
permissions = ('ssm:GetParameters',
'ssm:DescribeParameters')
augment = universal_augment
@SSMParameter.action_registry.register('delete')
class DeleteParameter(Action):
schema = type_schema('delete')
permissions = ("ssm:DeleteParameter",)
def process(self, resources):
client = local_session(self.manager.session_factory).client('ssm')
for r in resources:
self.manager.retry(
client.delete_parameter, Name=r['Name'],
ignore_err_codes=('ParameterNotFound',))
@resources.register('ssm-managed-instance')
class ManagedInstance(QueryResourceManager):
class resource_type(TypeInfo):
service = 'ssm'
enum_spec = ('describe_instance_information', 'InstanceInformationList', None)
id = 'InstanceId'
name = 'Name'
date = 'RegistrationDate'
arn_type = "managed-instance"
permissions = ('ssm:DescribeInstanceInformation',)
@EC2.action_registry.register('send-command')
@ManagedInstance.action_registry.register('send-command')
class SendCommand(Action):
"""Run an SSM Automation Document on an instance.
:Example:
Find ubuntu 18.04 instances are active with ssm.
.. code-block:: yaml
policies:
- name: ec2-osquery-install
resource: ec2
filters:
- type: ssm
key: PingStatus
value: Online
- type: ssm
key: PlatformName
value: Ubuntu
- type: ssm
key: PlatformVersion
value: 18.04
actions:
- type: send-command
command:
DocumentName: AWS-RunShellScript
Parameters:
commands:
- wget https://pkg.osquery.io/deb/osquery_3.3.0_1.linux.amd64.deb
- dpkg -i osquery_3.3.0_1.linux.amd64.deb
"""
schema = type_schema(
'send-command',
command={'type': 'object'},
required=('command',))
permissions = ('ssm:SendCommand',)
shape = "SendCommandRequest"
annotation = 'c7n:SendCommand'
def validate(self):
shape_validate(self.data['command'], self.shape, 'ssm')
# If used against an ec2 resource, require an ssm status filter
# to ensure that we're not trying to send commands to instances
# that aren't in ssm.
if self.manager.type != 'ec2':
return
found = False
for f in self.manager.iter_filters():
if f.type == 'ssm':
found = True
break
if not found:
raise PolicyValidationError(
"send-command requires use of ssm filter on ec2 resources")
def process(self, resources):
client = local_session(self.manager.session_factory).client('ssm')
for resource_set in chunks(resources, 50):
self.process_resource_set(client, resource_set)
def process_resource_set(self, client, resources):
command = dict(self.data['command'])
command['InstanceIds'] = [
r['InstanceId'] for r in resources]
result = client.send_command(**command).get('Command')
for r in resources:
r.setdefault('c7n:SendCommand', []).append(result['CommandId'])
@resources.register('ssm-activation')
class SSMActivation(QueryResourceManager):
class resource_type(TypeInfo):
service = 'ssm'
enum_spec = ('describe_activations', 'ActivationList', None)
id = 'ActivationId'
name = 'Description'
date = 'CreatedDate'
arn = False
permissions = ('ssm:DescribeActivations',)
@SSMActivation.action_registry.register('delete')
class DeleteSSMActivation(Action):
schema = type_schema('delete')
permissions = ('ssm:DeleteActivation',)
def process(self, resources):
client = local_session(self.manager.session_factory).client('ssm')
for a in resources:
client.delete_activation(ActivationId=a["ActivationId"])
@resources.register('ops-item')
class OpsItem(QueryResourceManager):
"""Resource for OpsItems in SSM OpsCenter
https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter.html
"""
class resource_type(TypeInfo):
enum_spec = ('describe_ops_items', 'OpsItemSummaries', None)
service = 'ssm'
arn_type = 'opsitem'
id = 'OpsItemId'
name = 'Title'
default_report_fields = (
'Status', 'Title', 'LastModifiedTime',
'CreatedBy', 'CreatedTime')
QueryKeys = {
'Status',
'CreatedBy',
'Source',
'Priority',
'Title',
'OpsItemId',
'CreatedTime',
'LastModifiedTime',
'OperationalData',
'OperationalDataKey',
'OperationalDataValue',
'ResourceId',
'AutomationId'}
QueryOperators = {'Equal', 'LessThan', 'GreaterThan', 'Contains'}
def validate(self):
self.query = self.resource_query()
return super(OpsItem, self).validate()
def get_resources(self, ids, cache=True, augment=True):
if isinstance(ids, str):
ids = [ids]
return self.resources({
'OpsItemFilters': [{
'Key': 'OpsItemId',
'Values': [i],
'Operator': 'Equal'} for i in ids]})
def resources(self, query=None):
q = self.resource_query()
if q and query and 'OpsItemFilters' in query:
q['OpsItemFilters'].extend(query['OpsItemFilters'])
return super(OpsItem, self).resources(query=q)
def resource_query(self):
filters = []
for q in self.data.get('query', ()):
if (not isinstance(q, dict) or
not set(q.keys()) == {'Key', 'Values', 'Operator'} or
q['Key'] not in self.QueryKeys or
q['Operator'] not in self.QueryOperators):
raise PolicyValidationError(
"invalid ops-item query %s" % self.data['query'])
filters.append(q)
return {'OpsItemFilters': filters}
@OpsItem.action_registry.register('update')
class UpdateOpsItem(Action):
"""Update an ops item.
: example :
Close out open ops items older than 30 days for a given issue.
.. code-block:: yaml
policies:
- name: issue-items
resource: aws.ops-item
filters:
- Status: Open
- Title: checking-lambdas
- type: value
key: CreatedTime
value_type: age
op: greater-than
value: 30
actions:
- type: update
status: Resolved
"""
schema = type_schema(
'update',
description={'type': 'string'},
priority={'enum': list(range(1, 6))},
title={'type': 'string'},
topics={'type': 'array', 'items': {'type': 'string'}},
status={'enum': ['Open', 'In Progress', 'Resolved']},
)
permissions = ('ssm:UpdateOpsItem',)
def process(self, resources):
attrs = dict(self.data)
attrs = filter_empty({
'Description': attrs.get('description'),
'Title': attrs.get('title'),
'Priority': attrs.get('priority'),
'Status': attrs.get('status'),
'Notifications': [{'Arn': a} for a in attrs.get('topics', ())]})
modified = []
for r in resources:
for k, v in attrs.items():
if k not in r or r[k] != v:
modified.append(r)
self.log.debug("Updating %d of %d ops items", len(modified), len(resources))
client = local_session(self.manager.session_factory).client('ssm')
for m in modified:
client.update_ops_item(OpsItemId=m['OpsItemId'], **attrs)
class OpsItemFilter(Filter):
"""Filter resources associated to extant OpsCenter operational items.
:example:
Find ec2 instances with open ops items.
.. code-block:: yaml
policies:
- name: ec2-instances-ops-items
resource: ec2
filters:
- type: ops-item
# we can filter on source, title, priority
priority: [1, 2]
"""
schema = type_schema(
'ops-item',
status={'type': 'array',
'default': ['Open'],
'items': {'enum': ['Open', 'In progress', 'Resolved']}},
priority={'type': 'array', 'items': {'enum': list(range(1, 6))}},
title={'type': 'string'},
source={'type': 'string'})
schema_alias = True
permissions = ('ssm:DescribeOpsItems',)
def process(self, resources, event=None):
client = local_session(self.manager.session_factory).client('ssm')
results = []
for resource_set in chunks(resources, 10):
qf = self.get_query_filter(resource_set)
items = client.describe_ops_items(**qf).get('OpsItemSummaries')
arn_item_map = {}
for i in items:
for arn in json.loads(
i['OperationalData']['/aws/resources']['Value']):
arn_item_map.setdefault(arn['arn'], []).append(i['OpsItemId'])
for arn, r in zip(self.manager.get_arns(resource_set), resource_set):
if arn in arn_item_map:
r['c7n:opsitems'] = arn_item_map[arn]
results.append(r)
return results
def get_query_filter(self, resources):
q = []
q.append({'Key': 'Status', 'Operator': 'Equal',
'Values': self.data.get('status', ('Open',))})
if self.data.get('priority'):
q.append({'Key': 'Priority', 'Operator': 'Equal',
'Values': list(map(str, self.data['priority']))})
if self.data.get('title'):
q.append({'Key': 'Title', 'Operator': 'Contains',
'Values': [self.data['title']]})
if self.data.get('source'):
q.append({'Key': 'Source', 'Operator': 'Equal',
'Values': [self.data['source']]})
q.append({'Key': 'ResourceId', 'Operator': 'Contains',
'Values': [r[self.manager.resource_type.id] for r in resources]})
return {'OpsItemFilters': q}
@classmethod
def register_resource(cls, registry, resource_class):
if 'ops-item' not in resource_class.filter_registry:
resource_class.filter_registry.register('ops-item', cls)
resources.subscribe(OpsItemFilter.register_resource)
class PostItem(Action):
"""Post an OpsItem to AWS Systems Manager OpsCenter Dashboard.
https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter.html
Each ops item supports up to a 100 associated resources. This
action supports the builtin OpsCenter dedup logic with additional
support for associating new resources to existing Open ops items.
: Example :
Create an ops item for ec2 instances with Create User permissions
.. code-block:: yaml
policies:
- name: over-privileged-ec2
resource: aws.ec2
filters:
- type: check-permissions
match: allowed
actions:
- iam:CreateUser
actions:
- type: post-item
priority: 3
The builtin OpsCenter dedup logic will kick in if the same
resource set (ec2 instances in this case) is posted for the same
policy.
: Example :
Create an ops item for sqs queues with cross account access as ops items.
.. code-block:: yaml
policies:
- name: sqs-cross-account-access
resource: aws.sqs
filters:
- type: cross-account
actions:
- type: mark-for-op
days: 5
op: delete
- type: post-item
title: SQS Cross Account Access
description: |
Cross Account Access detected in SQS resource IAM Policy.
tags:
Topic: Security
"""
schema = type_schema(
'post-item',
description={'type': 'string'},
tags={'type': 'object'},
priority={'enum': list(range(1, 6))},
title={'type': 'string'},
topics={'type': 'string'},
)
schema_alias = True
permissions = ('ssm:CreateOpsItem',)
def process(self, resources, event=None):
client = local_session(self.manager.session_factory).client('ssm')
item_template = self.get_item_template()
resources = list(sorted(resources, key=operator.itemgetter(
self.manager.resource_type.id)))
items = self.get_items(client, item_template)
if items:
# - Use a copy of the template as we'll be passing in status changes on updates.
# - The return resources will be those that we couldn't fit into updates
# to existing resources.
resources = self.update_items(client, items, dict(item_template), resources)
item_ids = [i['OpsItemId'] for i in items[:5]]
for resource_set in chunks(resources, 100):
resource_arns = json.dumps(
[{'arn': arn} for arn in sorted(self.manager.get_arns(resource_set))])
item_template['OperationalData']['/aws/resources'] = {
'Type': 'SearchableString', 'Value': resource_arns}
if items:
item_template['RelatedOpsItems'] = [
{'OpsItemId': item_ids[:5]}]
try:
oid = client.create_ops_item(**item_template).get('OpsItemId')
item_ids.insert(0, oid)
except client.exceptions.OpsItemAlreadyExistsException:
pass
for r in resource_set:
r['c7n:opsitem'] = oid
def get_items(self, client, item_template):
qf = [
{'Key': 'OperationalDataValue',
'Operator': 'Contains',
'Values': [item_template['OperationalData'][
'/custodian/dedup']['Value']]},
{'Key': 'OperationalDataKey',
'Operator': 'Equal',
'Values': ['/custodian/dedup']},
{'Key': 'Status',
'Operator': 'Equal',
# In progress could imply activity/executions underway, we don't want to update
# the resource set out from underneath that so only look at Open state.
'Values': ['Open']},
{'Key': 'Source',
'Operator': 'Equal',
'Values': ['Cloud Custodian']}]
items = client.describe_ops_items(OpsItemFilters=qf)['OpsItemSummaries']
return list(sorted(items, key=operator.itemgetter('CreatedTime'), reverse=True))
def update_items(self, client, items, item_template, resources):
"""Update existing Open OpsItems with new resources.
Originally this tried to support attribute updates as well, but
the reasoning around that is a bit complex due to partial state
evaluation around any given execution, so its restricted atm
to just updating associated resources.
For management of ops items, use a policy on the
ops-item resource.
Rationale: Typically a custodian policy will be evaluating
some partial set of resources at any given execution (ie think
a lambda looking at newly created resources), where as a
collection of ops center items will represent the total
set. Custodian can multiplex the partial set of resource over
a set of ops items (100 resources per item) which minimizes
the item count. When updating the state of an ops item though,
we have to contend with the possibility that we're doing so
with only a partial state. Which could be confusing if we
tried to set the Status to Resolved even if we're only evaluating
a handful of resources associated to an ops item.
"""
arn_item_map = {}
item_arn_map = {}
for i in items:
item_arn_map[i['OpsItemId']] = arns = json.loads(
i['OperationalData']['/aws/resources']['Value'])
for arn in arns:
arn_item_map[arn['arn']] = i['OpsItemId']
arn_resource_map = dict(zip(self.manager.get_arns(resources), resources))
added = set(arn_resource_map).difference(arn_item_map)
updated = set()
remainder = []
# Check for resource additions
for a in added:
handled = False
for i in items:
if len(item_arn_map[i['OpsItemId']]) >= 100:
continue
item_arn_map[i['OpsItemId']].append({'arn': a})
updated.add(i['OpsItemId'])
arn_resource_map[a]['c7n:opsitem'] = i['OpsItemId']
handled = True
break
if not handled:
remainder.append(a)
for i in items:
if not i['OpsItemId'] in updated:
continue
i = dict(i)
for k in ('CreatedBy', 'CreatedTime', 'Source', 'LastModifiedBy',
'LastModifiedTime'):
i.pop(k, None)
i['OperationalData']['/aws/resources']['Value'] = json.dumps(
item_arn_map[i['OpsItemId']])
i['OperationalData'].pop('/aws/dedup', None)
client.update_ops_item(**i)
return remainder
def get_item_template(self):
title = self.data.get('title', self.manager.data['name']).strip()
dedup = ("%s %s %s %s" % (
title,
self.manager.type,
self.manager.config.region,
self.manager.config.account_id)).encode('utf8')
# size restrictions on this value is 4-20, digest is 32
dedup = hashlib.md5(dedup).hexdigest()[:20] # nosec nosemgrep
i = dict(
Title=title,
Description=self.data.get(
'description',
self.manager.data.get(
'description',
self.manager.data.get('name'))),
Priority=self.data.get('priority'),
Source="Cloud Custodian",
Tags=[{'Key': k, 'Value': v} for k, v in self.data.get(
'tags', self.manager.data.get('tags', {})).items()],
Notifications=[{'Arn': a} for a in self.data.get('topics', ())],
OperationalData={
'/aws/dedup': {
'Type': 'SearchableString',
'Value': json.dumps({'dedupString': dedup})},
'/custodian/execution-id': {
'Type': 'String',
'Value': self.manager.ctx.execution_id},
# We need our own dedup string to be able to filter
# search on it.
'/custodian/dedup': {
'Type': 'SearchableString',
'Value': dedup},
'/custodian/policy': {
'Type': 'String',
'Value': json.dumps(self.manager.data)},
'/custodian/version': {
'Type': 'String',
'Value': version},
'/custodian/policy-name': {
'Type': 'SearchableString',
'Value': self.manager.data['name']},
'/custodian/resource': {
'Type': 'SearchableString',
'Value': self.manager.type},
}
)
return filter_empty(i)
@classmethod
def register_resource(cls, registry, resource_class):
if 'post-item' not in resource_class.action_registry:
resource_class.action_registry.register('post-item', cls)
resources.subscribe(PostItem.register_resource)
@resources.register('ssm-document')
class SSMDocument(QueryResourceManager):
class resource_type(TypeInfo):
service = 'ssm'
enum_spec = ('list_documents', 'DocumentIdentifiers', {'Filters': [
{
'Key': 'Owner',
'Values': ['Self']}]})
name = 'Name'
date = 'RegistrationDate'
arn_type = 'Document'
permissions = ('ssm:ListDocuments',)
@SSMDocument.filter_registry.register('cross-account')
class SSMDocumentCrossAccount(CrossAccountAccessFilter):
"""Filter SSM documents which have cross account permissions
:example:
.. code-block:: yaml
policies:
- name: ssm-cross-account
resource: ssm-document
filters:
- type: cross-account
whitelist: [xxxxxxxxxxxx]
"""
permissions = ('ssm:DescribeDocumentPermission',)
def process(self, resources, event=None):
self.accounts = self.get_accounts()
results = []
client = local_session(self.manager.session_factory).client('ssm')
with self.executor_factory(max_workers=3) as w:
futures = []
for resource_set in chunks(resources, 10):
futures.append(w.submit(
self.process_resource_set, client, resource_set))
for f in as_completed(futures):
if f.exception():
self.log.error(
"Exception checking cross account access \n %s" % (
f.exception()))
continue
results.extend(f.result())
return results
def process_resource_set(self, client, resource_set):
results = []
for r in resource_set:
attrs = self.manager.retry(
client.describe_document_permission,
Name=r['Name'],
PermissionType='Share',
ignore_err_codes=('InvalidDocument',))['AccountSharingInfoList']
shared_accounts = {
g.get('AccountId') for g in attrs}
delta_accounts = shared_accounts.difference(self.accounts)
if delta_accounts:
r['c7n:CrossAccountViolations'] = list(delta_accounts)
results.append(r)
return results
@SSMDocument.action_registry.register('set-sharing')
class RemoveSharingSSMDocument(Action):
"""Edit list of accounts that share permissions on an SSM document. Pass in a list of account
IDs to the 'add' or 'remove' fields to edit document sharing permissions.
Set 'remove' to 'matched' to automatically remove any external accounts on a
document (use in conjunction with the cross-account filter).
:example:
.. code-block:: yaml
policies:
- name: ssm-set-sharing
resource: ssm-document
filters:
- type: cross-account
whitelist: [xxxxxxxxxxxx]
actions:
- type: set-sharing
add: [yyyyyyyyyy]
remove: matched
"""
schema = type_schema('set-sharing',
remove={
'oneOf': [
{'enum': ['matched']},
{'type': 'array', 'items': {
'type': 'string'}},
]},
add={
'type': 'array', 'items': {
'type': 'string'}})
permissions = ('ssm:ModifyDocumentPermission',)
def process(self, resources):
client = local_session(self.manager.session_factory).client('ssm')
add_accounts = self.data.get('add', [])
remove_accounts = self.data.get('remove', [])
if self.data.get('remove') == 'matched':
for r in resources:
try:
client.modify_document_permission(
Name=r['Name'],
PermissionType='Share',
AccountIdsToAdd=add_accounts,
AccountIdsToRemove=r['c7n:CrossAccountViolations']
)
except client.exceptions.InvalidDocumentOperation as e:
raise(e)
else:
for r in resources:
try:
client.modify_document_permission(
Name=r['Name'],
PermissionType='Share',
AccountIdsToAdd=add_accounts,
AccountIdsToRemove=remove_accounts
)
except client.exceptions.InvalidDocumentOperation as e:
raise(e)
@SSMDocument.action_registry.register('delete')
class DeleteSSMDocument(Action):
"""Delete SSM documents. Set force flag to True to force delete on documents that are
shared across accounts. This will remove those shared accounts, and then delete the document.
Otherwise, delete will fail and raise InvalidDocumentOperation exception
if a document is shared with other accounts. Default value for force is False.
:example:
.. code-block:: yaml
policies:
- name: ssm-delete-documents
resource: ssm-document
filters:
- type: cross-account
whitelist: [xxxxxxxxxxxx]
actions:
- type: delete
force: True
"""
schema = type_schema(
'delete',
force={'type': 'boolean'}
)
permissions = ('ssm:DeleteDocument', 'ssm:ModifyDocumentPermission',)
def process(self, resources):
client = local_session(self.manager.session_factory).client('ssm')
for r in resources:
try:
client.delete_document(Name=r['Name'], Force=True)
except client.exceptions.InvalidDocumentOperation as e:
if self.data.get('force', False):
response = client.describe_document_permission(
Name=r['Name'],
PermissionType='Share'
)
client.modify_document_permission(
Name=r['Name'],
PermissionType='Share',
AccountIdsToRemove=response.get('AccountIds', [])
)
client.delete_document(
Name=r['Name'],
Force=True
)
else:
raise(e)
|
apache-2.0
| -7,850,574,087,396,876,000
| 34.457908
| 97
| 0.548869
| false
| 4.371599
| false
| false
| false
|
ashutoshvt/psi4
|
tests/pytests/test_jkmemory.py
|
1
|
1305
|
"""
Tests for the memory estimators on JK objects
"""
import psi4
import pytest
from .utils import *
def _build_system(basis):
mol = psi4.geometry("""
Ar 0 0 0
Ar 0 0 5
Ar 0 0 15
Ar 0 0 25
Ar 0 0 35
""")
#psi4.set_options({"INTS_TOLERANCE": 0.0})
basis = psi4.core.BasisSet.build(mol, target=basis)
aux = psi4.core.BasisSet.build(basis.molecule(), "DF_BASIS_SCF",
psi4.core.get_option("SCF", "DF_BASIS_SCF"), "JKFIT",
basis.name(), basis.has_puream())
return basis, aux
@pytest.mark.parametrize("basis,jk_type,estimate",[
# Zero temps
["cc-pvdz", "DIRECT", 0],
["cc-pvdz", "OUT_OF_CORE", 0],
# pvdz tests
["cc-pvdz", "MEM_DF", 1542360],
["cc-pvdz", "DISK_DF", 1286244],
["cc-pvdz", "CD", 2916000],
["cc-pvdz", "PK", 65610000],
# 5z tests
["cc-pv5z", "MEM_DF", 55172760],
["cc-pv5z", "DISK_DF", 26984120],
]) # yapf: disable
def test_jk_memory_estimate(basis, jk_type, estimate):
basis, aux = _build_system(basis)
jk = psi4.core.JK.build(basis, aux=aux, jk_type=jk_type, do_wK=False, memory=1e9)
assert compare_integers(estimate, jk.memory_estimate(), "{} memory estimate".format(jk_type))
|
lgpl-3.0
| -1,547,428,685,653,749,200
| 24.588235
| 97
| 0.56092
| false
| 2.843137
| true
| false
| false
|
unreal666/outwiker
|
src/outwiker/gui/controls/togglebutton.py
|
3
|
9278
|
# -*- coding: utf-8 -*-
import wx
from wx.lib.buttons import ThemedGenBitmapTextToggleButton
class ToggleButton(ThemedGenBitmapTextToggleButton):
def __init__(self,
parent,
id=-1,
bitmap=None,
label='',
pos=wx.DefaultPosition,
size=wx.DefaultSize,
style=0,
validator=wx.DefaultValidator,
name="togglebutton",
align=wx.ALIGN_LEFT):
super(ToggleButton, self).__init__(parent, id, bitmap,
label, pos, size,
style, validator, name)
self.colorNormal = wx.Colour(255, 255, 255)
self.colorToggled = wx.Colour(144, 195, 212)
self.colorShadow = wx.Colour(200, 200, 200)
self.colorBorder = wx.Colour(0, 0, 0)
self.colorBorderToggled = wx.Colour(0, 0, 255)
self.colorTextNormal = wx.Colour(0, 0, 0)
self.colorTextDisabled = wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT)
self.colorTextToggled = wx.Colour(0, 0, 0)
self.toggleShiftX = 2
self.toggleShiftY = 2
self.roundRadius = 2
self.align = align
self.padding = 8
self.marginImage = 4
self._updateMinSize()
def _updateMinSize(self):
contentWidth = self.GetContentWidth()
self.SetMinSize((contentWidth + self.padding * 2 + self.toggleShiftX,
-1))
def GetColorNormal(self):
return self.colorNormal
def SetColorNormal(self, color):
self.colorNormal = color
self.Refresh()
def GetColorToggled(self):
return self.colorToggled
def SetColorToggled(self, color):
self.colorToggled = color
self.Refresh()
def GetColorShadow(self):
return self.colorShadow
def SetColorShadow(self, color):
self.colorShadow = color
self.Refresh()
def GetColorBorder(self):
return self.colorBorder
def SetColorBorder(self, color):
self.colorBorder = color
self.Refresh()
def GetColorBorderToggled(self):
return self.colorBorderToggled
def SetColorBorderToggled(self, color):
self.colorBorderToggled = color
self.Refresh()
def GetColorTextNormal(self):
return self.colorTextNormal
def SetColorTextNormal(self, color):
self.colorTextNormal = color
self.Refresh()
def GetColorTextDisabled(self):
return self.colorTextDisabled
def SetColorTextDisabled(self, color):
self.colorTextDisabled = color
self.Refresh()
def GetColorTextToggled(self):
return self.colorTextToggled
def SetColorTextToggled(self, color):
self.colorTextToggled = color
self.Refresh()
def GetAlign(self):
return self.align
def SetAlign(self, align):
self.align = align
self.Refresh()
def GetToggleShift(self):
return (self.toggleShiftX, self.toggleShiftY)
def SetToggleShift(self, shiftX, shiftY):
self.toggleShiftX = shiftX
self.toggleShiftY = shiftY
self.Refresh()
def GetRoundRadius(self):
return self.roundRadius
def SetRoundRadius(self, radius):
self.roundRadius = radius
self.Refresh()
def GetPadding(self):
return self.padding
def SetPadding(self, padding):
self.padding = padding
self._updateMinSize()
self.Refresh()
def GetMarginImage(self):
return self.marginImage
def SetMarginImage(self, margin):
self.marginImage = margin
self._updateMinSize()
self.Refresh()
def DrawFocusIndicator(self, dc, w, h):
bw = self.bezelWidth
textClr = self.GetForegroundColour()
focusIndPen = wx.Pen(textClr, 1, wx.USER_DASH)
focusIndPen.SetDashes([1, 1])
focusIndPen.SetCap(wx.CAP_BUTT)
if wx.Platform == "__WXMAC__":
dc.SetLogicalFunction(wx.XOR)
else:
focusIndPen.SetColour(self.focusClr)
dc.SetLogicalFunction(wx.INVERT)
dc.SetPen(focusIndPen)
dc.SetBrush(wx.TRANSPARENT_BRUSH)
if self.GetToggle():
shiftX = self.toggleShiftX
shiftY = self.toggleShiftY
else:
shiftX = 0
shiftY = 0
dc.DrawRoundedRectangle(bw+2 + shiftX,
bw+2 + shiftY,
w-bw*2-5 - self.toggleShiftX,
h-bw*2-5 - self.toggleShiftY,
self.roundRadius)
dc.SetLogicalFunction(wx.COPY)
def DrawBezel(self, dc, x1, y1, x2, y2):
brushBackground = wx.Brush(self.colorNormal)
penBackground = wx.Pen(self.colorNormal)
dc.SetBrush(brushBackground)
dc.SetPen(penBackground)
dc.DrawRectangle((0, 0), self.GetSize())
width_full = x2 - x1
height_full = y2 - y1
rect_width = width_full - self.toggleShiftX
rect_height = height_full - self.toggleShiftY
rect_x0 = 0 if not self.GetToggle() else self.toggleShiftX
rect_y0 = 0 if not self.GetToggle() else self.toggleShiftY
# Draw shadow
brushShadow = wx.Brush(self.colorShadow)
penShadow = wx.Pen(self.colorShadow)
dc.SetBrush(brushShadow)
dc.SetPen(penShadow)
dc.DrawRoundedRectangle(self.toggleShiftX, self.toggleShiftY,
rect_width, rect_height,
self.roundRadius)
# Draw button
color = self.colorToggled if self.GetToggle() else self.colorNormal
colorBorder = self.colorBorderToggled if self.GetToggle() else self.colorBorder
brush = wx.Brush(color)
pen = wx.Pen(colorBorder)
dc.SetBrush(brush)
dc.SetPen(pen)
dc.DrawRoundedRectangle(rect_x0, rect_y0,
rect_width, rect_height,
self.roundRadius)
dc.SetBrush(wx.NullBrush)
def _getBitmap(self):
bmp = self.bmpLabel
if bmp is not None:
# if the bitmap is used
if self.bmpDisabled and not self.IsEnabled():
bmp = self.bmpDisabled
if self.bmpFocus and self.hasFocus:
bmp = self.bmpFocus
if self.bmpSelected and not self.up:
bmp = self.bmpSelected
return bmp
def GetContentWidth(self):
bmp = self._getBitmap()
if bmp is not None:
bw = bmp.GetWidth()
else:
# no bitmap -> size is zero
bw = 0
label = self.GetLabel()
dc = wx.WindowDC(self)
dc.SetFont(self.GetFont())
# size of text
tw, th = dc.GetTextExtent(label)
contentWidth = bw + tw + self.marginImage
return contentWidth
def DrawLabel(self, dc, width, height, dx=0, dy=0):
if self.IsEnabled() and self.GetToggle():
dc.SetTextForeground(self.colorTextToggled)
elif self.IsEnabled():
dc.SetTextForeground(self.colorTextNormal)
else:
dc.SetTextForeground(self.colorTextDisabled)
bmp = self._getBitmap()
if bmp is not None:
bw, bh = bmp.GetWidth(), bmp.GetHeight()
hasMask = bmp.GetMask() is not None
else:
# no bitmap -> size is zero
bw = bh = 0
label = self.GetLabel()
dc.SetFont(self.GetFont())
# size of text
tw, th = dc.GetTextExtent(label)
if self.GetToggle():
dx = self.toggleShiftX
dy = self.toggleShiftY
contentWidth = bw + tw + self.marginImage
if self.align == wx.ALIGN_LEFT:
pos_x = self.padding + dx
elif self.align == wx.ALIGN_CENTER:
pos_x = (width - contentWidth - self.toggleShiftX) / 2 + dx
else:
assert False
if pos_x < self.padding + dx:
pos_x = self.padding + dx
if bmp is not None:
# draw bitmap if available
dc.DrawBitmap(bmp, pos_x, (height - bh) / 2 + dy, hasMask)
dc.DrawText(label, pos_x + bw + self.marginImage, (height-th)/2+dy)
class MyTestFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, wx.ID_ANY, title, size=(400, 300))
panel = wx.Panel(self)
# Build a bitmap button and a normal one
bmp = wx.ArtProvider.GetBitmap(wx.ART_INFORMATION, wx.ART_OTHER, (16, 16))
btn = ToggleButton(panel, -1, label=u'adsfasdf', pos=(10, 10))
btn.SetSize((150, 75))
btn2 = ToggleButton(panel, -1, bmp, label=u'adsfasdf', pos=(10, 110), align=wx.ALIGN_CENTER)
btn2.SetSize((150, 75))
btn3 = ToggleButton(panel, -1, bmp, label=u'adsfasdfadsf', pos=(10, 210), align=wx.ALIGN_CENTER)
btn3.SetSize(btn3.GetMinSize())
btn3.SetRoundRadius(0)
if __name__ == '__main__':
app = wx.App()
frame = MyTestFrame(None, 'ToggleButton Test')
frame.Show()
frame.SetSize((500, 600))
app.MainLoop()
|
gpl-3.0
| 532,456,159,052,573,950
| 29.221498
| 104
| 0.573184
| false
| 3.800901
| false
| false
| false
|
RobinQuetin/CAIRIS-web
|
cairis/cairis/PropertyDialog.py
|
1
|
3948
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import wx
import armid
import WidgetFactory
class PropertyDialog(wx.Dialog):
def __init__(self,parent,setProperties,values):
wx.Dialog.__init__(self,parent,armid.PROPERTY_ID,'Add Security Property',style=wx.DEFAULT_DIALOG_STYLE|wx.MAXIMIZE_BOX|wx.THICK_FRAME|wx.RESIZE_BORDER,size=(400,300))
weights = {"Confidentiality":0,"Integrity":1,"Availability":2,"Accountability":3,"Anonymity":4,"Pseudonymity":5,"Unlinkability":6,"Unobservability":7}
self.thePropertyName = ''
self.thePropertyValue = ''
self.thePropertyRationale = 'None'
self.commitLabel = 'Add'
mainSizer = wx.BoxSizer(wx.VERTICAL)
# defaultProperties = set(['Confidentiality','Integrity','Availability','Accountability','Anonymity','Pseudonymity','Unlinkability','Unobservability'])
defaultProperties = set(weights.keys())
propertyList = sorted(list(defaultProperties.difference(setProperties)), key=lambda x:weights[x])
mainSizer.Add(WidgetFactory.buildComboSizerList(self,'Property',(87,30),armid.PROPERTY_COMBOPROPERTY_ID,propertyList),0,wx.EXPAND)
mainSizer.Add(WidgetFactory.buildComboSizerList(self,'Value',(87,30),armid.PROPERTY_COMBOVALUE_ID,values),0,wx.EXPAND)
mainSizer.Add(WidgetFactory.buildMLTextSizer(self,'Rationale',(87,60),armid.PROPERTY_TEXTRATIONALE_ID),1,wx.EXPAND)
mainSizer.Add(WidgetFactory.buildAddCancelButtonSizer(self,armid.PROPERTY_BUTTONADD_ID),0,wx.ALIGN_CENTER)
self.SetSizer(mainSizer)
wx.EVT_BUTTON(self,armid.PROPERTY_BUTTONADD_ID,self.onCommit)
def load(self,pName,pValue,pRationale):
propertyCtrl = self.FindWindowById(armid.PROPERTY_COMBOPROPERTY_ID)
valueCtrl = self.FindWindowById(armid.PROPERTY_COMBOVALUE_ID)
ratCtrl = self.FindWindowById(armid.PROPERTY_TEXTRATIONALE_ID)
commitCtrl = self.FindWindowById(armid.PROPERTY_BUTTONADD_ID)
commitCtrl.SetLabel('Edit')
propertyCtrl.SetValue(pName)
valueCtrl.SetValue(pValue)
ratCtrl.SetValue(pRationale)
self.commitLabel = 'Edit'
def onCommit(self,evt):
propertyCtrl = self.FindWindowById(armid.PROPERTY_COMBOPROPERTY_ID)
valueCtrl = self.FindWindowById(armid.PROPERTY_COMBOVALUE_ID)
ratCtrl = self.FindWindowById(armid.PROPERTY_TEXTRATIONALE_ID)
self.thePropertyName = propertyCtrl.GetValue()
self.thePropertyValue = valueCtrl.GetValue()
self.thePropertyRationale = ratCtrl.GetValue()
commitTxt = self.commitLabel + ' Security Property'
if len(self.thePropertyName) == 0:
dlg = wx.MessageDialog(self,'No property selected',commitTxt,wx.OK)
dlg.ShowModal()
dlg.Destroy()
return
elif (len(self.thePropertyValue) == 0):
dlg = wx.MessageDialog(self,'No value selected',commitTxt,wx.OK)
dlg.ShowModal()
dlg.Destroy()
return
elif (len(self.thePropertyRationale) == 0):
dlg = wx.MessageDialog(self,'No rationale',commitTxt,wx.OK)
dlg.ShowModal()
dlg.Destroy()
return
else:
self.EndModal(armid.PROPERTY_BUTTONADD_ID)
def property(self): return self.thePropertyName
def value(self): return self.thePropertyValue
def rationale(self): return self.thePropertyRationale
|
apache-2.0
| 1,893,080,471,082,788,000
| 46.566265
| 170
| 0.744681
| false
| 3.421144
| false
| false
| false
|
openslack/openslack-web
|
openslack/userena/contrib/umessages/templatetags/umessages_tags.py
|
1
|
2642
|
from django import template
from userena.contrib.umessages.models import MessageRecipient
import re
register = template.Library()
class MessageCount(template.Node):
def __init__(self, um_from_user, var_name, um_to_user=None):
self.user = template.Variable(um_from_user)
self.var_name = var_name
if um_to_user:
self.um_to_user = template.Variable(um_to_user)
else:
self.um_to_user = um_to_user
def render(self, context):
try:
user = self.user.resolve(context)
except template.VariableDoesNotExist:
return ''
if not self.um_to_user:
message_count = MessageRecipient.objects.count_unread_messages_for(user)
else:
try:
um_to_user = self.um_to_user.resolve(context)
except template.VariableDoesNotExist:
return ''
message_count = MessageRecipient.objects.count_unread_messages_between(user,
um_to_user)
context[self.var_name] = message_count
return ''
@register.tag
def get_unread_message_count_for(parser, token):
"""
Returns the unread message count for a user.
Syntax::
{% get_unread_message_count_for [user] as [var_name] %}
Example usage::
{% get_unread_message_count_for pero as message_count %}
"""
try:
tag_name, arg = token.contents.split(None, 1)
except ValueError:
raise template.TemplateSyntaxError("%s tag requires arguments" % token.contents.split()[0])
m = re.search(r'(.*?) as (\w+)', arg)
if not m:
raise template.TemplateSyntaxError("%s tag had invalid arguments" % tag_name)
user, var_name = m.groups()
return MessageCount(user, var_name)
@register.tag
def get_unread_message_count_between(parser, token):
"""
Returns the unread message count between two users.
Syntax::
{% get_unread_message_count_between [user] and [user] as [var_name] %}
Example usage::
{% get_unread_message_count_between funky and wunki as message_count %}
"""
try:
tag_name, arg = token.contents.split(None, 1)
except ValueError:
raise template.TemplateSyntaxError("%s tag requires arguments" % token.contents.split()[0])
m = re.search(r'(.*?) and (.*?) as (\w+)', arg)
if not m:
raise template.TemplateSyntaxError("%s tag had invalid arguments" % tag_name)
um_from_user, um_to_user, var_name = m.groups()
return MessageCount(um_from_user, var_name, um_to_user)
|
apache-2.0
| 3,915,772,045,790,340,000
| 28.685393
| 99
| 0.604845
| false
| 3.840116
| false
| false
| false
|
leyyin/university-PC
|
elearning/course/forms.py
|
1
|
3054
|
from django import forms
from django.contrib.admin import widgets
from django.db.models.query_utils import Q
from django.forms.extras.widgets import SelectDateWidget
from django.forms.widgets import HiddenInput, Textarea, DateInput
from django.forms import ModelForm, CheckboxSelectMultiple
from django.contrib.auth.models import Group
from elearning.models import Course, Subject,UserELearning, Assignment, AssignmentGroup
# https://docs.djangoproject.com/en/1.8/topics/forms/modelforms/
class SubjectModelChoiceField(forms.ModelChoiceField):
def label_from_instance(self, obj):
return obj.name
class TeacherModelChoiceField(forms.ModelChoiceField):
def label_from_instance(self, obj):
return obj.id+obj.name
class SimpleCourseForm(ModelForm):
class Meta:
model = Course
fields = ['name']
subject = SubjectModelChoiceField(queryset=Subject.objects.all(), empty_label=None)
class TeacherEditCourseForm(SimpleCourseForm):
students = forms.ModelMultipleChoiceField(required=False, widget=CheckboxSelectMultiple, queryset=UserELearning.objects.filter(user__groups__name='student'))
assistants = forms.ModelMultipleChoiceField(required=False, widget=CheckboxSelectMultiple, queryset=UserELearning.objects.filter(user__groups__name='assistant'))
def clean_students(self):
data = self.cleaned_data['students']
return data
def clean_assistants(self):
data = self.cleaned_data['assistants']
return data
class AssignmentForm(ModelForm):
class Meta:
model = Assignment
fields = ['name', 'description', 'deadline', 'type', 'group']
widgets = {
'description': Textarea(attrs={'cols': 80, 'rows': 7}),
'deadline': SelectDateWidget(
empty_label=("Choose Year", "Choose Month", "Choose Day"),
),
}
id = forms.HiddenInput()
group = forms.ModelChoiceField(required=True, queryset=AssignmentGroup.objects.all(), empty_label=None)
class ReadOnlyAssignmentForm(AssignmentForm):
def __init__(self, *args, **kwargs):
super(AssignmentForm, self).__init__(*args, **kwargs)
for key in self.fields.keys():
self.fields[key].widget.attrs['readonly'] = True
self.fields[key].widget.attrs['disabled'] = 'disabled'
widgets = {
'deadline': forms.CharField(),
}
class AssignStudentsForm(forms.Form):
def __init__(self, assignment, *args, **kwargs):
super(forms.Form, self).__init__(*args, **kwargs)
self.fields["students"] = forms.ModelMultipleChoiceField(required=False, widget=CheckboxSelectMultiple,
queryset=assignment.course.students.all())
def clean_students(self):
data = self.cleaned_data['students']
return data
class AdminEditCourseForm(TeacherEditCourseForm):
teacher = forms.ModelChoiceField(required=True, queryset=UserELearning.objects.filter(user__groups__name='teacher'), empty_label=None)
|
mit
| -862,088,765,838,127,400
| 35.795181
| 165
| 0.69057
| false
| 4.172131
| false
| false
| false
|
harishvc/githubanalytics
|
MyMoment.py
|
1
|
1651
|
import datetime
from time import gmtime, strftime
import pytz
#Humanize time in milliseconds
#Reference: http://stackoverflow.com/questions/26276906/python-convert-seconds-from-epoch-time-into-human-readable-time
def HTM(a, context):
#print "Processing ....", a
b = int(datetime.datetime.now().strftime("%s"))
#print "Time NOW ...", b
c = b - a
#print "Time elapsed ...", c
days = c // 86400
hours = c // 3600 % 24
minutes = c // 60 % 60
seconds = c % 60
if (days > 0): return ( str(days) + " days " + context)
elif (hours > 0): return (str(hours) + " hours " + context)
elif (minutes > 0): return ( str(minutes) + " minutes " + context)
elif (seconds > 1): return (str(seconds) + " seconds " + context)
elif (seconds == 1): return (str(seconds) + " second " + context)
elif (seconds == 0): return ("< 1 second")
else: return ("Now ") #Error
#Humanize time in hours
def HTH(a):
b = int(datetime.datetime.now().strftime("%s"))
c = b - a
days = c // 86400
hours = c // 3600 % 24
return hours
#My Timestamp used in logfile
def MT():
fmt = '%Y-%m-%d %H:%M:%S'
return (datetime.datetime.now(pytz.timezone("America/Los_Angeles")).strftime(fmt))
#My Timestamp for filename
def FT():
fmt = '%d%b%Y-%H%M%S'
return ( datetime.datetime.now(pytz.timezone("America/Los_Angeles")).strftime(fmt) )
#Time now in epoch milliseconds
def TNEM():
return (int(datetime.datetime.now().strftime("%s")) * 1000)
#Time then (back in minutes) is epoch milliseconds
def TTEM(Back):
return (int(datetime.datetime.now().strftime("%s")) * 1000 - (Back * 60 * 1000))
|
mit
| 2,189,820,734,005,846,300
| 32.693878
| 119
| 0.621442
| false
| 3.25641
| false
| false
| false
|
dpetzold/dakku
|
dakku/backup.py
|
1
|
4832
|
import datetime
import logging
import re
import socket
import subprocess
import os
from django.conf import settings
from . import exceptions as dakku_exception
logger = logging.getLogger(__name__)
class BackupBase(object):
def deletefile(self, date_str):
"""Given a date in YYYYMMDD check if the file should be deleted or keep"""
today = datetime.date.today()
date = datetime.date(int(date_str[:4]), int(date_str[4:6]), int(date_str[6:8]))
age = today - date
if age < datetime.timedelta(weeks=2):
if self.verbose:
print('keeping < 2 weeks')
return False
if age < datetime.timedelta(weeks=8) and date.weekday() == 0:
if self.verbose:
print('keeping monday')
return False
if date.day == 2:
if self.verbose:
print('keeping first of the month')
return False
return True
class BackupUtil(object):
def __init__(self, router, container_name, dry_run=False, verbose=False):
from .mysql import MysqlUtil
from .rackspace import RackspaceUtil
self.mysql = MysqlUtil(router, verbose)
self.rackspace = RackspaceUtil(container_name, verbose, dry_run=dry_run)
self.verbose = verbose
self.start_time = datetime.datetime.utcnow()
if not os.path.exists(settings.BACKUP_DIR):
os.mkdir(settings.BACKUP_DIR)
def _run_cmd(self, cmd, filepath, ext=None):
if self.verbose:
print(cmd)
subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
if ext is not None:
filepath += ext
filesize = os.stat(filepath).st_size
if filesize == 0:
raise dakku_exception.BadFileSize('Bad filesize for "%s"' % (filepath))
return filepath, filesize
def tar_directory(self, directory, prefix=None):
root, name = os.path.split(directory)
name = '%s.%s-%s.tar.bz2' % \
(name, self.start_time.strftime('%Y%m%d_%H%M%S'), socket.gethostname())
if prefix is not None:
backup_dir = '%s/%s' % (settings.BACKUP_DIR, prefix)
else:
backup_dir = settings.BACKUP_DIR
if not os.path.exists(backup_dir):
os.mkdir(backup_dir)
filepath = '%s/%s' % (backup_dir, name)
cmd = '/bin/tar cfj %s %s -C %s' % (filepath, directory, root)
return self._run_cmd(cmd, filepath)
def backup_database(self):
dbfile = self.mysql.dump()
uploaded = self.rackspace.store(dbfile, 'db')
logger.info('Uploaded %s to %s %s' % (dbfile, uploaded.name, uploaded.size))
if self.verbose:
print(uploaded.name)
os.unlink(dbfile)
return uploaded
def backup_site(self):
filepath, filesize = self.tar_directory(settings.SITE_ROOT, 'site')
if self.verbose:
print('%s %s' % (filepath, filesize))
uploaded = self.rackspace.store(filepath, 'site')
logger.info('Uploaded %s to %s %s' % (filepath, uploaded.name, uploaded.size))
if self.verbose:
print(uploaded.name)
return uploaded
def backup_all(self):
self.backup_database()
self.backup_site()
deletes = self.rackspace.cull()
for deleted in deletes:
logger.info('Deleted %s' % (deleted.name))
if self.verbose:
print('Deleted: %s' % (deleted.name))
deletes = self.cull()
for deleted in deletes:
logger.info('Deleted %s' % (deleted.name))
if self.verbose:
print('Deleted: %s' % (deleted.name))
def restore(self, filename=None, remote=None):
self.mysql.dump()
self.mysql.drop()
self.mysql.create()
if remote is not None:
filename = self.rackspace.get(remote, settings.BACKUP_DIR)
return self.mysql.source(filename)
def list(self):
for obj in self.rackspace.list():
print('%s %s' % (obj.name, obj.size))
def cull_local(self):
culled = []
files = os.listdir(settings.BACKUP_DIR)
for filename in files:
filepath = '%s/%s/' % (settings.BACKUP_DIR, filename)
search = re.search(r'(\d{8})', filename)
if search is None:
continue
if self.deletefile(search.group(0)):
if self.verbose:
print('Deleting %s' % (filename))
if not self.dry_run:
os.unlink(filepath)
culled.append(filename)
elif self.verbose:
print('Keeping %s' % (filename))
return culled
def cull(self):
self.rackspace.cull()
self.cull_local()
|
bsd-3-clause
| -8,806,372,401,183,013,000
| 32.79021
| 87
| 0.569536
| false
| 3.871795
| false
| false
| false
|
chripell/mytools
|
gimp/plugins/resizer.py
|
1
|
1661
|
#!/usr/bin/env python
import ConfigParser
import errno
from gimpfu import register, PF_INT16, pdb, main
from gimpenums import INTERPOLATION_CUBIC
import gimp
import os
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
CONFIG_DIR = os.path.join(
os.path.expanduser("~"),
".config",
"GIMP_plugins")
mkdir_p(CONFIG_DIR)
CONFIG_FILE = os.path.join(
CONFIG_DIR,
"resizer_max")
config = ConfigParser.RawConfigParser()
config.read(CONFIG_FILE)
try:
msize = config.getint("sizes", "max")
except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
config.add_section("sizes")
config.set("sizes", "max", "1600")
msize = config.getint("sizes", "max")
def resizer(img, drawable, size_max):
gimp.context_push()
img.undo_group_start()
w = img.width
h = img.height
if w > h:
factor = float(size_max) / w
else:
factor = float(size_max) / h
pdb.gimp_image_scale_full(
img, w * factor, h * factor,
INTERPOLATION_CUBIC)
config.set("sizes", "max", size_max)
with open(CONFIG_FILE, 'wb') as configfile:
config.write(configfile)
img.undo_group_end()
gimp.context_pop()
register(
"python_resizer_max",
"Resize to a given maximum dimension",
"Resize to a given maximum dimension",
"chripell@gmail.com",
"Public Domain",
"2018",
"<Image>/Script-Fu/Resizer Max",
"RGB*, GRAY*",
[
(PF_INT16, "max_size", "Maximum size", msize),
],
[],
resizer)
main()
|
apache-2.0
| -2,538,402,579,378,744,300
| 21.146667
| 65
| 0.615292
| false
| 3.263261
| true
| false
| false
|
kurtraschke/camelot
|
camelot/view/controls/editors/wideeditor.py
|
1
|
1420
|
# ============================================================================
#
# Copyright (C) 2007-2010 Conceptive Engineering bvba. All rights reserved.
# www.conceptive.be / project-camelot@conceptive.be
#
# This file is part of the Camelot Library.
#
# This file may be used under the terms of the GNU General Public
# License version 2.0 as published by the Free Software Foundation
# and appearing in the file license.txt included in the packaging of
# this file. Please review this information to ensure GNU
# General Public Licensing requirements will be met.
#
# If you are unsure which license is appropriate for your use, please
# visit www.python-camelot.com or contact project-camelot@conceptive.be
#
# This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
# WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
#
# For use of this library in commercial applications, please contact
# project-camelot@conceptive.be
#
# ============================================================================
class WideEditor(object):
"""Class signaling that an editor, is a wide editor, so it's label should be displayed
on top of the editor and the editor itself should take two columns::
class WideTextLineEditor(TextLineEditor, WideEditor):
pass
will generate a test line editor where the text line takes the whole with of the
form"""
|
gpl-2.0
| 3,623,529,977,134,472,700
| 42.030303
| 90
| 0.675352
| false
| 4.201183
| false
| false
| false
|
wuchaofan/collectsource
|
mobileinterest/settings.py
|
1
|
2223
|
"""
Django settings for mobileinterest project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'wdw3xjg7g9lc1nk&5867@=1th!3)^7+2#i$f++gzt*=8jo9+kq'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
# 'django.contrib.admin',
# 'django.contrib.auth',
# 'django.contrib.contenttypes',
'views',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'mobileinterest.urls'
WSGI_APPLICATION = 'mobileinterest.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
TEMPLATE_DIRS = (
BASE_DIR+'/templates',
)
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
CACHE_BACKEND = os.path.join(BASE_DIR, 'django_cache') #'file:///var/tmp/django_cache'
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = '/static/'
|
gpl-2.0
| 5,870,867,587,422,026,000
| 23.163043
| 86
| 0.7148
| false
| 3.193966
| false
| false
| false
|
jacol12345/TP-ankiety-web-app
|
mobilepolls/polls/models.py
|
1
|
5421
|
# -*- coding: utf-8 -*-
import json
from datetime import datetime
from django.core.urlresolvers import reverse
from django.db import models
from django.contrib.auth.models import User
from model_utils.managers import InheritanceManager
class PollManager(models.Manager):
def active(self):
return self.filter(published=True).filter(expires__lte=datetime.now())
class Poll(models.Model):
MALE = 'M'
FEMALE = 'F'
NONE = 'N'
REQUIRED_GENDER_CHOICES = (
(MALE, 'Male'),
(FEMALE, 'Female'),
(NONE, 'None'),
)
title = models.CharField(max_length=200)
created = models.DateField()
expires = models.DateField()
required_gender = models.CharField(max_length=1, default=NONE,
choices=REQUIRED_GENDER_CHOICES)
required_student = models.BooleanField(default=False)
required_smoker = models.BooleanField(default=False)
required_employed = models.BooleanField(default=False)
published = models.BooleanField(default=True)
owner = models.ForeignKey(User)
objects = PollManager()
def get_absolute_url(self):
return reverse('show_poll', kwargs={'poll_id': self.id})
def get_cost(self):
return sum([
x.points for x in self.questions.all().select_subclasses()])
def get_completion_time(self):
return sum([x.time_to_complete for x
in self.questions.all().select_subclasses()])
def wrap_to_json(self):
return json.dumps(self.wrap_to_dict(), sort_keys=True, indent=4,
separators=(',', ': '))
def wrap_to_dict(self):
return {'poll_id': self.id,
'questions': [x.wrap_to_dict() for x in self.questions.all()],
'time_to_complete': self.get_completion_time(),
'points': self.get_cost(),
'title': self.title,
'author': self.owner.get_username(),}
def __unicode__(self):
return u'%s' % (self.title,)
class MobileUser(models.Model):
phone_id = models.TextField(max_length=100)
student = models.BooleanField(default=False)
employed = models.BooleanField(default=False)
male = models.BooleanField(default=False)
female = models.BooleanField(default=False)
smoking = models.BooleanField(default=False)
available_polls = models.ManyToManyField(Poll, null=True, blank=True, related_name='available_for_users')
answered_polls = models.ManyToManyField(Poll, null=True, blank=True, related_name='answered_by_users')
def __unicode__(self):
return u'%s' % (self.phone_id,)
def get_points(self):
return sum([x.get_cost() for x in self.answered_polls.all()])
class QuestionBase(models.Model):
'''
Answers are stored as a list of tuples:
[(1, "Yes"), (2, "No")]
'''
SINGLE = 'SC'
MULTI = 'MC'
STARS = 'ST'
RANK = 'RK'
QUESTION_TYPE_CHOICES = (
(SINGLE, 'Singe Choice Question'),
(MULTI, 'Mutliple Choice Question'),
(STARS, '1-5 Star Question'),
(RANK, 'Rank question'),
)
poll = models.ForeignKey(Poll, related_name='questions')
title = models.CharField(max_length=200)
available_answers = models.TextField(blank=True)
question_type = models.CharField(max_length=2, default=SINGLE,
choices=QUESTION_TYPE_CHOICES)
points = 0.0
time_to_complete = 0.0
objects = InheritanceManager()
def available_answers_to_list(self):
try:
return json.loads(self.available_answers)
except ValueError:
return ''
def list_to_available_answers(self, answers_list):
answers = [(i, answers_list[i]) for i in range(len(answers_list))]
self.available_answers = json.dumps(answers)
def wrap_to_dict(self):
return {'id': self.id,
'title': self.title,
'available_answers': self.available_answers_to_list(),
'question_type': self.question_type}
def __unicode__(self):
return u'%s' % (self.title,)
class AnswerBase(models.Model):
'''Answer single answer of respondent. Saves number of points for
each available_answer.
[(1, 0.0), (2, 0.5), (3, 0.5)]
'''
question = models.ForeignKey(QuestionBase)
respondent = models.ForeignKey(MobileUser)
answers = models.TextField()
objects = InheritanceManager()
def answers_to_list(self):
return json.loads(self.answers)
def list_to_answers(self, list_of_answers):
answers = list(list_of_answers)
self.answers = json.dumps(answers)
def __unicode__(self):
return u'answer to %s' % (self.question.title)
class SingleChoiceQuestion(QuestionBase):
points = 1.0
time_to_complete = 0.25
class MultipleChoiceQuestion(QuestionBase):
points = 1.5
time_to_complete = 0.5
class StarQuestion(QuestionBase):
points = 1.0
time_to_complete = 0.25
def available_answers_to_list(self):
return None
def list_to_available_answers(self, answers_list):
return None
def wrap_to_dict(self):
return {'id': self.id,
'title': self.title,
'available_answers': "",
'question_type': self.question_type}
class RankedQuestion(QuestionBase):
points = 2.0
time_to_complete = 0.75
|
mit
| 3,513,476,015,671,460,000
| 29.116667
| 109
| 0.617229
| false
| 3.723214
| false
| false
| false
|
YcheLanguageStudio/PythonStudy
|
bioinformatics/dynamic_programming/global_alignment.py
|
1
|
2764
|
import numpy as np
def global_alignment(seq0, seq1):
def get_dp_table():
dp_score_table = np.ndarray(shape=(len(seq0) + 1, len(seq1) + 1), dtype=int)
dp_score_table.fill(0)
for col_idx in range(dp_score_table.shape[1]):
dp_score_table[0][col_idx] = (-1) * col_idx
for row_idx in range(dp_score_table.shape[0]):
dp_score_table[row_idx][0] = (-1) * row_idx
min_size = min(len(seq0), len(seq1))
def match_score(i, j):
return 1 if seq0[i - 1] == seq1[j - 1] else -1
def transition_computation(i, j):
gap_penalty = -1
diagonal_val = dp_score_table[i - 1][j - 1] + match_score(i, j)
right_val = dp_score_table[i][j - 1] + gap_penalty
down_val = dp_score_table[i - 1][j] + gap_penalty
dp_score_table[i][j] = max(diagonal_val, right_val, down_val)
for iter_num in xrange(1, min_size + 1):
transition_computation(iter_num, iter_num)
# move right
for col_idx in xrange(iter_num + 1, dp_score_table.shape[1]):
transition_computation(iter_num, col_idx)
# move down
for row_idx in xrange(iter_num + 1, dp_score_table.shape[0]):
transition_computation(row_idx, iter_num)
return dp_score_table
def traceback(table):
"""
:type table: np.ndarray
"""
gap_penalty = -1
def match_score(i, j):
return 1 if seq0[i - 1] == seq1[j - 1] else -1
def dfs_detail(row_idx, col_idx, level):
blank_str = ''.join([" "] * level)[:-1] + '|_' if level > 0 else 'root'
print '%-50s' % (blank_str + str((row_idx, col_idx))), 'score at', str((row_idx, col_idx)), ':', \
table[row_idx][col_idx]
if row_idx != 0 and col_idx != 0:
# diagonal
if table[row_idx - 1][col_idx - 1] + match_score(row_idx, col_idx) == table[row_idx][col_idx]:
dfs_detail(row_idx - 1, col_idx - 1, level + 1)
# down
if table[row_idx - 1][col_idx] + gap_penalty == table[row_idx][col_idx]:
dfs_detail(row_idx - 1, col_idx, level + 1)
# right
if table[row_idx][col_idx - 1] + gap_penalty == table[row_idx][col_idx]:
dfs_detail(row_idx, col_idx - 1, level + 1)
dfs_detail(table.shape[0] - 1, table.shape[1] - 1, 0)
dp_score_table = get_dp_table()
print 'global alignment table:\n', dp_score_table, '\n'
traceback(dp_score_table)
if __name__ == '__main__':
seq_str0 = 'GGTTGACTA'
seq_str1 = 'TGTTACGG'
global_alignment(seq0=seq_str1, seq1=seq_str0)
|
mit
| 6,954,767,011,223,040,000
| 37.929577
| 110
| 0.517366
| false
| 3.137344
| false
| false
| false
|
wizzard/sdk
|
tests/sync_test_megacli.py
|
1
|
5819
|
"""
Application for testing syncing algorithm
(c) 2013-2014 by Mega Limited, Wellsford, New Zealand
This file is part of the MEGA SDK - Client Access Engine.
Applications using the MEGA API must present a valid application key
and comply with the the rules set forth in the Terms of Service.
The MEGA SDK 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.
@copyright Simplified (2-clause) BSD License.
You should have received a copy of the license along with this
program.
"""
import sys
import os
import time
import shutil
import unittest
import xmlrunner
import subprocess
import re
from sync_test_app import SyncTestApp
from sync_test import SyncTest
import logging
import argparse
class SyncTestMegaCliApp(SyncTestApp):
"""
operates with megacli application
"""
def __init__(self, local_mount_in, local_mount_out, delete_tmp_files=True, use_large_files=True, check_if_alive=True):
"""
local_mount_in: local upsync folder
local_mount_out: local downsync folder
"""
self.work_dir = os.path.join(".", "work_dir")
SyncTestApp.__init__(self, local_mount_in, local_mount_out, self.work_dir, delete_tmp_files, use_large_files)
self.check_if_alive = check_if_alive
def sync(self):
time.sleep(5)
def start(self):
# try to create work dir
return True
def finish(self):
try:
shutil.rmtree(self.work_dir)
except OSError, e:
logging.error("Failed to remove dir: %s (%s)" % (self.work_dir, e))
def is_alive(self):
"""
return True if application instance is running
"""
if not self.check_if_alive:
return True
s = subprocess.Popen(["ps", "axw"], stdout=subprocess.PIPE)
for x in s.stdout:
if re.search("megacli", x):
return True
return False
def pause(self):
"""
pause application
"""
# TODO: implement this !
raise NotImplementedError("Not Implemented !")
def unpause(self):
"""
unpause application
"""
# TODO: implement this !
raise NotImplementedError("Not Implemented !")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--test1", help="test_create_delete_files", action="store_true")
parser.add_argument("--test2", help="test_create_rename_delete_files", action="store_true")
parser.add_argument("--test3", help="test_create_delete_dirs", action="store_true")
parser.add_argument("--test4", help="test_create_rename_delete_dirs", action="store_true")
parser.add_argument("--test5", help="test_sync_files_write", action="store_true")
parser.add_argument("--test6", help="test_local_operations", action="store_true")
parser.add_argument("--test7", help="test_update_mtime", action="store_true")
parser.add_argument("--test8", help="test_create_rename_delete_unicode_files_dirs", action="store_true")
parser.add_argument("-a", "--all", help="run all tests", action="store_true")
parser.add_argument("-b", "--basic", help="run basic, stable tests", action="store_true")
parser.add_argument("-d", "--debug", help="use debug output", action="store_true")
parser.add_argument("-l", "--large", help="use large files for testing", action="store_true")
parser.add_argument("-n", "--nodelete", help="Do not delete work files", action="store_false")
parser.add_argument("-c", "--check", help="Do not check if megacli is running (useful, if other application is used for testing)", action="store_false")
parser.add_argument("upsync_dir", help="local upsync directory")
parser.add_argument("downsync_dir", help="local downsync directory")
args = parser.parse_args()
if args.debug:
lvl = logging.DEBUG
else:
lvl = logging.INFO
if args.all:
args.test1 = args.test2 = args.test3 = args.test4 = args.test5 = args.test6 = args.test7 = args.test8 = True
if args.basic:
args.test1 = args.test2 = args.test3 = args.test4 = True
logging.StreamHandler(sys.stdout)
logging.basicConfig(format='[%(asctime)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=lvl)
logging.info("")
logging.info("1) Start the first [megacli] and run the following command: sync " + args.upsync_dir + " [remote folder]")
logging.info("2) Start the second [megacli] and run the following command: sync " + args.downsync_dir + " [remote folder]")
logging.info("3) Wait for both folders get fully synced")
logging.info("4) Run: python %s", sys.argv[0])
logging.info("")
time.sleep(5)
with SyncTestMegaCliApp(args.upsync_dir, args.downsync_dir, args.nodelete, args.large, args.check) as app:
suite = unittest.TestSuite()
if args.test1:
suite.addTest(SyncTest("test_create_delete_files", app))
if args.test2:
suite.addTest(SyncTest("test_create_rename_delete_files", app))
if args.test3:
suite.addTest(SyncTest("test_create_delete_dirs", app, ))
if args.test4:
suite.addTest(SyncTest("test_create_rename_delete_dirs", app))
if args.test5:
suite.addTest(SyncTest("test_sync_files_write", app))
if args.test6:
suite.addTest(SyncTest("test_local_operations", app))
if args.test7:
suite.addTest(SyncTest("test_update_mtime", app))
if args.test8:
suite.addTest(SyncTest("test_create_rename_delete_unicode_files_dirs", app))
testRunner = xmlrunner.XMLTestRunner(output='test-reports')
testRunner.run(suite)
|
bsd-2-clause
| 4,365,006,259,359,789,000
| 35.829114
| 156
| 0.647534
| false
| 3.675932
| true
| false
| false
|
elitegreg/mudpy
|
mudpy/gameproperty.py
|
1
|
1060
|
# Game properties should be registered at import time
class GameProperty:
__slots__ = ('__propname', '__default', '__readonly')
def __init__(self, propname, default=None, readonly=False, tmp=False):
if not tmp:
self.__propname = '_GameProperty_' + propname
else:
self.__propname = '_TempGameProperty_' + propname
self.__default = default
self.__readonly = readonly
def __get__(self, obj, type=None):
return getattr(obj, self.__propname, self.__default)
def __set__(self, obj, value):
if self.__readonly:
raise AttributeError("{} is readonly".format(self.__propname))
obj._Object__propdict[self.__propname] = value
def __delete__(self, obj):
if self.__readonly:
raise AttributeError("{} is readonly".format(self.__propname))
delattr(obj, self.__propname)
def add_gameproperty(klass, propname, default=None, readonly=False, tmp=False):
setattr(klass, propname, GameProperty(propname, default, readonly, tmp))
|
gpl-3.0
| -9,018,803,080,407,469,000
| 34.333333
| 79
| 0.614151
| false
| 4.092664
| false
| false
| false
|
GlobalFishingWatch/vessel-classification
|
classification/metadata_test.py
|
1
|
6965
|
# Copyright 2017 Google Inc. and Skytruth Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import csv
import numpy as np
from . import metadata
import tensorflow as tf
from datetime import datetime
import six
class VesselMetadataFileReaderTest(tf.test.TestCase):
raw_lines = [
'id,label,length,split,idhash\n',
'100001,drifting_longlines,10.0,Test,2\n',
'100002,drifting_longlines,24.0,Training,3\n',
'100003,drifting_longlines,7.0,Training,4\n',
'100004,drifting_longlines,8.0,Test,5\n',
'100005,trawlers,10.0,Test,6\n',
'100006,trawlers,24.0,Test,7\n',
'100007,passenger,24.0,Training,8\n',
'100008,trawlers,24.0,Training,9\n',
'100009,trawlers,10.0,Test,10\n',
'100010,trawlers,24.0,Training,11\n',
'100011,tug,60.0,Test,12\n',
'100012,tug,5.0,Training,13\n',
'100014,tug,24.0,Test,14\n',
'100013,tug|trawlers,5.0,Training,15\n',
]
fishing_range_dict = {
b'100001': [metadata.FishingRange(
datetime(2015, 3, 1), datetime(2015, 3, 2), 1.0)],
b'100002': [metadata.FishingRange(
datetime(2015, 3, 1), datetime(2015, 3, 2), 1.0)],
b'100003': [metadata.FishingRange(
datetime(2015, 3, 1), datetime(2015, 3, 2), 1.0)],
b'100004': [metadata.FishingRange(
datetime(2015, 3, 1), datetime(2015, 3, 2), 1.0)],
b'100005': [metadata.FishingRange(
datetime(2015, 3, 1), datetime(2015, 3, 2), 1.0)],
b'100006': [metadata.FishingRange(
datetime(2015, 3, 1), datetime(2015, 3, 2), 1.0)],
b'100007': [metadata.FishingRange(
datetime(2015, 3, 1), datetime(2015, 3, 2), 1.0)],
b'100008': [metadata.FishingRange(
datetime(2015, 3, 1), datetime(2015, 3, 2), 1.0)],
b'100009':
[metadata.FishingRange(datetime(2015, 3, 1), datetime(2015, 3, 4), 1.0)
], # Thrice as much fishing
b'100010': [],
b'100011': [],
b'100012': [],
b'100013': [],
}
def test_metadata_file_reader(self):
parsed_lines = csv.DictReader(self.raw_lines)
available_vessels = set(six.ensure_binary(str(x)) for x in range(100001, 100014))
result = metadata.read_vessel_multiclass_metadata_lines(
available_vessels, parsed_lines, {})
# First one is test so weighted as 1 for now
self.assertEqual(1.0, result.vessel_weight(b'100001'))
self.assertEqual(1.118033988749895, result.vessel_weight(b'100002'))
self.assertEqual(1.0, result.vessel_weight(b'100008'))
self.assertEqual(1.2909944487358056, result.vessel_weight(b'100012'))
self.assertEqual(1.5811388300841898, result.vessel_weight(b'100007'))
self.assertEqual(1.1454972243679027, result.vessel_weight(b'100013'))
self._check_splits(result)
def test_fixed_time_reader(self):
parsed_lines = csv.DictReader(self.raw_lines)
available_vessels = set(six.ensure_binary(str(x)) for x in range(100001, 100014))
result = metadata.read_vessel_time_weighted_metadata_lines(
available_vessels, parsed_lines, self.fishing_range_dict,
'Test')
self.assertEqual(1.0, result.vessel_weight(b'100001'))
self.assertEqual(1.0, result.vessel_weight(b'100002'))
self.assertEqual(3.0, result.vessel_weight(b'100009'))
self.assertEqual(0.0, result.vessel_weight(b'100012'))
self._check_splits(result)
def _check_splits(self, result):
self.assertTrue('Training' in result.metadata_by_split)
self.assertTrue('Test' in result.metadata_by_split)
self.assertTrue('passenger', result.vessel_label('label', b'100007'))
print(result.metadata_by_split['Test'][b'100001'][0])
self.assertEqual(result.metadata_by_split['Test'][b'100001'][0],
{'label': 'drifting_longlines',
'length': '10.0',
'id': '100001',
'split': 'Test',
'idhash' : '2'})
self.assertEqual(result.metadata_by_split['Test'][b'100005'][0],
{'label': 'trawlers',
'length': '10.0',
'id': '100005',
'split': 'Test',
'idhash' : '6'})
self.assertEqual(result.metadata_by_split['Training'][b'100002'][0],
{'label': 'drifting_longlines',
'length': '24.0',
'id': '100002',
'split': 'Training',
'idhash' : '3'})
self.assertEqual(result.metadata_by_split['Training'][b'100003'][0],
{'label': 'drifting_longlines',
'length': '7.0',
'id': '100003',
'split': 'Training',
'idhash' : '4'})
def _get_metadata_files():
from pkg_resources import resource_filename
for name in ["training_classes.csv"]:
# TODO: rework to test encounters as well.
yield os.path.abspath(resource_filename('classification.data', name))
class MetadataConsistencyTest(tf.test.TestCase):
def test_metadata_consistency(self):
for metadata_file in _get_metadata_files():
self.assertTrue(os.path.exists(metadata_file))
# By putting '' in these sets we can safely remove it later
labels = set([''])
for row in metadata.metadata_file_reader(metadata_file):
label_str = row['label']
for lbl in label_str.split('|'):
labels.add(lbl.strip())
labels.remove('')
expected = set([lbl for (lbl, _) in metadata.VESSEL_CATEGORIES])
assert expected >= labels, (expected - labels, labels - expected)
class MultihotLabelConsistencyTest(tf.test.TestCase):
def test_fine_label_consistency(self):
names = []
for coarse, fine_list in metadata.VESSEL_CATEGORIES:
for fine in fine_list:
if fine not in names:
names.append(fine)
self.assertEqual(
sorted(names), sorted(metadata.VESSEL_CLASS_DETAILED_NAMES))
if __name__ == '__main__':
tf.test.main()
|
apache-2.0
| 7,179,996,861,872,246,000
| 40.706587
| 89
| 0.576741
| false
| 3.489479
| true
| false
| false
|
RIFTIO/rift.ware-descriptor-packages
|
4.3/src/vnfd/ping_vnf/scripts/ping_set_rate.py
|
1
|
3804
|
#!/usr/bin/env python3
############################################################################
# Copyright 2017 RIFT.IO Inc #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# You may obtain a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
############################################################################
import argparse
import logging
import os
import subprocess
import sys
import time
import yaml
def ping_set_rate(yaml_cfg, logger):
'''Use curl and set traffic rate on ping vnf'''
def set_rate(mgmt_ip, port, rate):
curl_cmd = '''curl -D /dev/null \
-H "Accept: application/vnd.yang.data+xml" \
-H "Content-Type: application/vnd.yang.data+json" \
-X POST \
-d "{{ \\"rate\\":{ping_rate} }}" \
http://{ping_mgmt_ip}:{ping_mgmt_port}/api/v1/ping/rate
'''.format(ping_mgmt_ip=mgmt_ip,
ping_mgmt_port=port,
ping_rate=rate)
logger.debug("Executing cmd: %s", curl_cmd)
subprocess.check_call(curl_cmd, shell=True)
# Get the ping rate
rate = yaml_cfg['parameter']['rate']
# Set ping rate
for index, vnfr in yaml_cfg['vnfr'].items():
logger.debug("VNFR {}: {}".format(index, vnfr))
# Check if it is pong vnf
if 'ping_vnfd' in vnfr['name']:
vnf_type = 'ping'
port = 18888
set_rate(vnfr['mgmt_ip_address'], port, rate)
break
def main(argv=sys.argv[1:]):
try:
parser = argparse.ArgumentParser()
parser.add_argument("yaml_cfg_file", type=argparse.FileType('r'))
parser.add_argument("-q", "--quiet", dest="verbose", action="store_false")
args = parser.parse_args()
run_dir = os.path.join(os.environ['RIFT_INSTALL'], "var/run/rift")
if not os.path.exists(run_dir):
os.makedirs(run_dir)
log_file = "{}/ping_set_rate-{}.log".format(run_dir, time.strftime("%Y%m%d%H%M%S"))
logging.basicConfig(filename=log_file, level=logging.DEBUG)
logger = logging.getLogger()
except Exception as e:
print("Exception in {}: {}".format(__file__, e))
sys.exit(1)
try:
ch = logging.StreamHandler()
if args.verbose:
ch.setLevel(logging.DEBUG)
else:
ch.setLevel(logging.INFO)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)
except Exception as e:
logger.exception(e)
raise e
try:
yaml_str = args.yaml_cfg_file.read()
# logger.debug("Input YAML file:\n{}".format(yaml_str))
yaml_cfg = yaml.load(yaml_str)
logger.debug("Input YAML: {}".format(yaml_cfg))
ping_set_rate(yaml_cfg, logger)
except Exception as e:
logger.exception(e)
raise e
if __name__ == "__main__":
main()
|
apache-2.0
| -337,360,539,746,339,460
| 33.899083
| 93
| 0.518139
| false
| 4.029661
| false
| false
| false
|
jmartinz/pyCrawler
|
10.contratacionE/pce_extrae_contratos.py
|
1
|
6399
|
# coding=utf-8
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException, TimeoutException
from bs4 import BeautifulSoup
import sys
#phantonPath = "/home/jmartinz/00.py/phantomjs/phantomjs"
phantonPath = "../phantomjs/phantomjs"
contratacionPage = "https://contrataciondelestado.es/wps/portal/!ut/p/b1/lZDLDoIwEEU_aaYParssrwLxAVZQujEsjMH42Bi_30rcGCPq7CZz7pzkgoOWKC6kYBPYgDt3t37fXfvLuTs-die2PFlEUZpRlJbFSKdxXYvMrybwQOsB_DAah3xopdQh0YislqhFVUXK_0HFnvmARbwpmlLY3CDmWRpPaxKgoeI3_4jgxW_sjPhzwkRAkRhLn_mPAvqn_13wJb8GNyBjDQzAWMXjEgrz7HLaQeuxyVY3SaVzxXARLj1WlLNVaShB5LCCNoGTO6Z-VH7g3R2UoLEz/dl4/d5/L2dBISEvZ0FBIS9nQSEh/pw/Z7_AVEQAI930OBRD02JPMTPG21004/act/id=0/p=javax.servlet.include.path_info=QCPjspQCPbusquedaQCPBusquedaVIS_UOE.jsp/299420689304/-/"
#contratacionPage="https://contrataciondelestado.es"
""" Móudlo para extraer datos de la página de contatación
del estado
"""
class Contratos():
""" Clase que devuelve los contratos de un ministerio entre unas fechas usando el dirver que se indique
driverType=1 (Firefox, online) / 2(phantomjs)
ministry:
6: MAGRAMA
7: MAExCoop
8. MDEfensa
9: MINECO
10:MEDCD
11:MESS
12:MFOM
13:MINHAP
14:MINET
15:MINJUS
16:MINPRES
17:MSSSI
18:MinTraInm
19:MinInt
20: Presidencia Gobierno
fini: dd-mm-aaaa
ffin: dd-mm-aaaa
"""
driver = "" #webdriver.PhantomJS(phantonPath, service_args=['--ignore-ssl-errors=true'])
driverType=1
expedientes =[]
ministerio = 'tafelTree_maceoArbol_id_'
ministry=0
fIni= '01-01-2015'
fFin='10-01-2015'
nContratos = 0
nPagTotal = 0
def __init__(self, driverType=1, ministry='17', fini='01-01-2015',ffin='10-01-2015'):
self.driverType=driverType
self.ministry = ministry
if driverType==1:
self.driver = webdriver.Firefox()
elif driverType==2:
self.driver = webdriver.PhantomJS(phantonPath, service_args=['--ignore-ssl-errors=true'])
self.driver.set_window_size(1120, 550)
self.ministerio = self.ministerio + ministry
self.fIni = fini
self.fFin = ffin
# self.debugPhanton()
self.extraecontratos()
def cargaPagina(self):
#Carga página
if self.driverType==2:
self.driver.implicitly_wait(10)
self.driver.set_page_load_timeout(10)
try:
self.driver.get(contratacionPage)
except TimeoutException as e: #Handle y
#Handle your exception here
print(e)
def debugPhanton(self):
self.cargaPagina()
# check phantomjs
print(self.driver.page_source)
def extraecontratos(self):
self.cargaPagina()
#Selecciona ministerio
self.driver.find_element_by_id('viewns_Z7_AVEQAI930OBRD02JPMTPG21004_:form1:idSeleccionarOCLink').click() # Organización contratante -> seleccionar
self.driver.find_elements_by_class_name('tafelTreeopenable')[1].click() # Selecciona AGE
self.driver.find_element_by_id(self.ministerio).click() # Selecciona el Ministerio pasado por parámetros
self.driver.find_element_by_id('viewns_Z7_AVEQAI930OBRD02JPMTPG21004_:form1:botonAnadirMostrarPopUpArbolEO').click()
# han añadido el boton añadir
self.driver.find_element_by_id('viewns_Z7_AVEQAI930OBRD02JPMTPG21004_:form1:botonAnadirMostrarPopUpArbolEO').click()
#Fecha publicacion entre fIni
fDesde = self.driver.find_element_by_id('viewns_Z7_AVEQAI930OBRD02JPMTPG21004_:form1:textMinFecAnuncioMAQ2')
fDesde.send_keys(self.fIni)
# y fFin
fHasta = self.driver.find_element_by_id('viewns_Z7_AVEQAI930OBRD02JPMTPG21004_:form1:textMaxFecAnuncioMAQ')
fHasta.send_keys(self.fFin)
# pulsa el botón de buscar
self.driver.find_element_by_id('viewns_Z7_AVEQAI930OBRD02JPMTPG21004_:form1:button1').click()
#Obtine el número de elementos
self.nContratos=self.driver.find_element_by_id('viewns_Z7_AVEQAI930OBRD02JPMTPG21004_:form1:textfooterTotalTotalMAQ').text
# y de páginas totales
self.nPagTotal = self.driver.find_element_by_id('viewns_Z7_AVEQAI930OBRD02JPMTPG21004_:form1:textfooterInfoTotalPaginaMAQ').text
# Recorre todas las páginas de resultados
while True: # Se ejecuta siempre hasta que no exista el enlace "siguiente"
nPag = self.driver.find_element_by_id('viewns_Z7_AVEQAI930OBRD02JPMTPG21004_:form1:textfooterInfoNumPagMAQ').text
# En linea saca los expedientes de la página
html_page = self.driver.page_source
soup = BeautifulSoup(html_page, "html5lib")
# tableExp = soup.find("table", { "id" : "myTablaBusquedaCustom" })
#
# expedientes_pag = [c.text for c in soup.findAll('td', {'class':'tdExpediente'})]
expedientes_pag = []
# Añade sólo las líneas que son de contratos
for row in soup.findAll("tr", {'class': ['rowClass1', 'rowClass2']}):
expedientes_pag.append(row)
# Los añade a los expedientes totales
self.expedientes.extend(expedientes_pag)
# Pulsa enlace siguiente, si no lo encuentra se sale del bucle
try:
enlaceSiguiente= self.driver.find_element_by_id('viewns_Z7_AVEQAI930OBRD02JPMTPG21004_:form1:footerSiguiente')
enlaceSiguiente.click()
except NoSuchElementException:
break
# Cierra el driver
self.driver.quit()
# Sólo para probar que funcina
def main():
contratosMSSSI=Contratos(driverType=2)
print(contratosMSSSI.nContratos)
print(contratosMSSSI.nPagTotal)
# abre fichero
f = open('workfile', 'w')
for exp in contratosMSSSI.expedientes:
f.write(exp.encode("UTF-8")+ "\n")
f.close()
if __name__ == "__main__":
sys.exit(main())
|
apache-2.0
| -4,426,364,085,573,958,000
| 36.757396
| 514
| 0.63501
| false
| 2.86529
| false
| false
| false
|
project-asap/IReS-Platform
|
asap-tools/monitoring/reporter_cli.py
|
1
|
5614
|
#!/usr/bin/env python
from cement.core import foundation, controller
from lib import get_backend, set_backend
from monitor import *
from pprint import PrettyPrinter
pprint = PrettyPrinter(indent=2).pprint
backend = get_backend()
def my_split(p):
"""
splits args based on '=' delim
:return:
"""
if p is None: return {}
delim = '='
def mini_split(t):
splitted = t.split(delim)
if len(splitted)<2:
raise Exception("could not split '{0}' based on '{1}'".format(t, delim))
return splitted
return dict(map(mini_split, p))
# define an application base controller
class MyAppBaseController(controller.CementBaseController):
class Meta:
label = 'base'
description = "My Application does amazing things!"
# the arguments recieved from command line
arguments = [
(['-r', '--retrieve-monitoring'], dict(action='store_true', help='retrieve the monitroing metrics from their temp file')),
(['-m', '--metrics'], dict(action='store', help='the metrics to report', nargs='*')),
(['-b', '--backend'], dict(action='store', help='the backend configuration parameters', nargs='*')),
(['-e', '--experiment-name'], dict(action='store', help='the name of the reported experiment')),
(['-q', '--query'], dict(action='store', help='the query to execute in the backend storage system')),
(['-pp', '--plot-params'], dict(action='store', help='parameters of the plot', nargs='*')),
(['-dict',], dict(action='store_true', help='get the query result in a dict')),
(['-cm', '--collect-metrics'], dict(action='store_true', help='collect the metrics of an active monitoring process')),
(['-cs', '--collect-streaming-metrics'], dict(action='store_true', help='collect the metrics of an finished streaming experiment'))
]
@controller.expose(hide=True, aliases=['run'])
def default(self):
self.app.log.error('You need to choose one of the options, or -h for help.')
@controller.expose(help='show examples of execution')
def show_examples(self):
print \
"""
# set a sqlite reporting backend with a specific sqlite file
./reporter_cli.py set-backend -b backend=sqlitebackend file=my_database.db
# Report, for experiment 'my_experiment', some metrics and their values
./reporter_cli.py report -e my_experiment -m metric1=test metric2=2
# plot a timeline of metric 'my_metric'
./reporter_cli.py plot-query -q "select cast(strftime('%s',date) as long) , my_metric from my_table;" -pp xlabel=bull title='my title'
"""
@controller.expose(aliases=['set-backend'])
def set_reporting_backend(self):
self.app.log.info("Setting reporting back-end")
if self.app.pargs.backend:
conf = my_split(self.app.pargs.backend)
set_backend(conf)
else:
self.app.log.error('No backend conf specified')
@controller.expose()
def show_backend(self):
self.app.log.info("Showing reporting back-end")
print backend
@controller.expose(help="store the required params", aliases=['r'])
def report(self):
experiment = self.app.pargs.experiment_name
if not experiment:
self.app.log.error("No experiment name provided. Please use the -e/--experiment-name parameter ")
exit()
metrics ={}
cli_metrics = my_split(self.app.pargs.metrics) # metrics from cmd args
# metrics stored into a file in the past
file_metrics = collect_future_metrics()
streaming_metrics = ganglia_metrics = {}
if self.app.pargs.collect_streaming_metrics:
# wait for and collect the streaming metrics if required
streaming_metrics = collect_streaming_metrics()
if self.app.pargs.collect_metrics:
# collect ganglia monitoring metrics if required
ganglia_metrics = collect_ganglia_metrics()
# update the metrics variable so that common common entries (if any) follow the priority
# 1)cli 2)future file 3)streaming 4)ganglia
metrics.update(ganglia_metrics)
metrics.update(streaming_metrics)
metrics.update(file_metrics)
metrics.update(cli_metrics)
# report the metrics to the backend
backend.report_dict(experiment, metrics)
@controller.expose(help="execute a query to the backend and prints the results")
def query(self):
if self.app.pargs.dict:
res = backend.dict_query(self.app.pargs.experiment_name, self.app.pargs.query)
pprint(res)
else:
res = backend.query(self.app.pargs.experiment_name, self.app.pargs.query)
for r in res:
print r
@controller.expose(help="store some metrics in a local file so that they can be reported later")
def future_report(self):
metrics = my_split(self.app.pargs.metrics)
store_future_metrics(metrics)
@controller.expose(help="execute a query to the backend and plot the results")
def plot_query(self):
pparams = self.app.pargs.plot_params
if pparams is not None: pparams = my_split(self.app.pargs.plot_params)
else: pparams = {}
backend.plot_query(self.app.pargs.experiment_name, self.app.pargs.query, **pparams)
class MyApp(foundation.CementApp):
class Meta:
label = 'reporter'
base_controller = MyAppBaseController
with MyApp() as app:
app.run()
|
apache-2.0
| -2,881,919,297,781,870,000
| 37.724138
| 144
| 0.633238
| false
| 4.00428
| false
| false
| false
|
istb-mia/miapy
|
miapy/data/conversion.py
|
1
|
6690
|
"""This module holds classes related to image conversion.
The main purpose of this module is the conversion between SimpleITK images and numpy arrays.
"""
import typing
import SimpleITK as sitk
import numpy as np
class ImageProperties:
"""Represents ITK image properties.
Holds common ITK image meta-data such as the size, origin, spacing, and direction.
See Also:
SimpleITK provides `itk::simple::Image::CopyInformation`_ to copy image information.
.. _itk::simple::Image::CopyInformation:
https://itk.org/SimpleITKDoxygen/html/classitk_1_1simple_1_1Image.html#afa8a4757400c414e809d1767ee616bd0
"""
def __init__(self, image: sitk.Image):
"""Initializes a new instance of the ImageProperties class.
Args:
image (sitk.Image): The image whose properties to hold.
"""
self.size = image.GetSize()
self.origin = image.GetOrigin()
self.spacing = image.GetSpacing()
self.direction = image.GetDirection()
self.dimensions = image.GetDimension()
self.number_of_components_per_pixel = image.GetNumberOfComponentsPerPixel()
self.pixel_id = image.GetPixelID()
def is_two_dimensional(self) -> bool:
"""Determines whether the image is two-dimensional.
Returns:
bool: True if the image is two-dimensional; otherwise, False.
"""
return self.dimensions == 2
def is_three_dimensional(self) -> bool:
"""Determines whether the image is three-dimensional.
Returns:
bool: True if the image is three-dimensional; otherwise, False.
"""
return self.dimensions == 3
def is_vector_image(self) -> bool:
"""Determines whether the image is a vector image.
Returns:
bool: True for vector images; False for scalar images.
"""
return self.number_of_components_per_pixel > 1
def __str__(self):
"""Gets a printable string representation.
Returns:
str: String representation.
"""
return 'ImageProperties:\n' \
' size: {self.size}\n' \
' origin: {self.origin}\n' \
' spacing: {self.spacing}\n' \
' direction: {self.direction}\n' \
' dimensions: {self.dimensions}\n' \
' number_of_components_per_pixel: {self.number_of_components_per_pixel}\n' \
' pixel_id: {self.pixel_id}\n' \
.format(self=self)
def __eq__(self, other):
"""Determines the equality of two ImageProperties classes.
Notes
The equality does not include the number_of_components_per_pixel and pixel_id.
Args:
other (object): An ImageProperties instance or any other object.
Returns:
bool: True if the ImageProperties are equal; otherwise, False.
"""
if isinstance(other, self.__class__):
return self.size == other.size and \
self.origin == other.origin and \
self.spacing == other.spacing and \
self.direction == other.direction and \
self.dimensions == other.dimensions
return NotImplemented
def __ne__(self, other):
"""Determines the non-equality of two ImageProperties classes.
Notes
The non-equality does not include the number_of_components_per_pixel and pixel_id.
Args:
other (object): An ImageProperties instance or any other object.
Returns:
bool: True if the ImageProperties are non-equal; otherwise, False.
"""
if isinstance(other, self.__class__):
return not self.__eq__(other)
return NotImplemented
def __hash__(self):
"""Gets the hash.
Returns:
int: The hash of the object.
"""
return hash(tuple(sorted(self.__dict__.items())))
class NumpySimpleITKImageBridge:
"""A numpy to SimpleITK bridge, which provides static methods to convert between numpy array and SimpleITK image."""
@staticmethod
def convert(array: np.ndarray, properties: ImageProperties) -> sitk.Image:
"""Converts a numpy array to a SimpleITK image.
Args:
array (np.ndarray): The image as numpy array. The shape can be either:
- shape=(n,), where n = total number of voxels
- shape=(n,v), where n = total number of voxels and v = number of components per pixel (vector image)
- shape=(<reversed image size>), what you get from sitk.GetArrayFromImage()
- shape=(<reversed image size>,v), what you get from sitk.GetArrayFromImage()
and v = number of components per pixel (vector image)
properties (ImageProperties): The image properties.
Returns:
sitk.Image: The SimpleITK image.
"""
is_vector = False
if not array.shape == properties.size[::-1]:
# we need to reshape the array
if array.ndim == 1:
array = array.reshape(properties.size[::-1])
elif array.ndim == 2:
is_vector = True
array = array.reshape((properties.size[::-1] + (array.shape[1],)))
elif array.ndim == len(properties.size) + 1:
is_vector = True
# no need to reshape
else:
raise ValueError('array shape {} not supported'.format(array.shape))
image = sitk.GetImageFromArray(array, is_vector)
image.SetOrigin(properties.origin)
image.SetSpacing(properties.spacing)
image.SetDirection(properties.direction)
return image
class SimpleITKNumpyImageBridge:
"""A SimpleITK to numpy bridge.
Converts SimpleITK images to numpy arrays. Use the ``NumpySimpleITKImageBridge`` to convert back.
"""
@staticmethod
def convert(image: sitk.Image) -> typing.Tuple[np.ndarray, ImageProperties]:
"""Converts an image to a numpy array and an ImageProperties class.
Args:
image (SimpleITK.Image): The image.
Returns:
A Tuple[np.ndarray, ImageProperties]: The image as numpy array and the image properties.
Raises:
ValueError: If `image` is `None`.
"""
if image is None:
raise ValueError('Parameter image can not be None')
return sitk.GetArrayFromImage(image), ImageProperties(image)
|
apache-2.0
| -5,434,569,577,237,771,000
| 34.210526
| 120
| 0.588789
| false
| 4.477912
| false
| false
| false
|
libvirt/libvirt-test-API
|
libvirttestapi/repos/storage/define_iscsi_pool.py
|
1
|
1805
|
# Copyright (C) 2010-2012 Red Hat, Inc.
# This work is licensed under the GNU GPLv2 or later.
# Define a storage pool of 'iscsi' type
from libvirt import libvirtError
from libvirttestapi.src import sharedmod
from libvirttestapi.repos.storage import storage_common
required_params = ('poolname', 'sourcehost', 'sourcepath',)
optional_params = {'targetpath': '/dev/disk/by-path',
'xml': 'xmls/iscsi_pool.xml',
}
def define_iscsi_pool(params):
"""
Defines a iscsi based storage pool from xml.
"""
logger = params['logger']
poolname = params['poolname']
xmlstr = params['xml']
conn = sharedmod.libvirtobj['conn']
if not storage_common.check_pool(conn, poolname, logger):
logger.error("%s storage pool is ALREADY defined" % poolname)
return 1
logger.debug("storage pool xml:\n%s" % xmlstr)
pool_num1 = conn.numOfDefinedStoragePools()
logger.info("original storage pool define number: %s" % pool_num1)
storage_common.display_pool_info(conn, logger)
try:
logger.info("define %s storage pool" % poolname)
conn.storagePoolDefineXML(xmlstr, 0)
pool_num2 = conn.numOfDefinedStoragePools()
logger.info("current storage pool define number: %s" % pool_num2)
storage_common.display_pool_info(conn, logger)
if storage_common.check_pool_define(poolname, logger) and pool_num2 > pool_num1:
logger.info("define %s storage pool is successful" % poolname)
else:
logger.error("%s storage pool is undefined" % poolname)
return 1
except libvirtError as e:
logger.error("API error message: %s, error code is %s"
% (e.get_error_message(), e.get_error_code()))
return 1
return 0
|
gpl-2.0
| 7,912,506,781,527,067,000
| 34.392157
| 88
| 0.646537
| false
| 3.729339
| false
| false
| false
|
rpm-software-management/rpmlint
|
test/test_polkit.py
|
1
|
2216
|
import os
import pytest
from rpmlint.checks.PolkitCheck import PolkitCheck
from rpmlint.filter import Filter
import Testing
from Testing import get_tested_package
def get_polkit_check(config_path):
from rpmlint.config import Config
if not os.path.isabs(config_path):
config_path = Testing.testpath() / 'configs' / config_path
config = Config([config_path])
config.info = True
output = Filter(config)
test = PolkitCheck(config, output)
return output, test
@pytest.fixture(scope='function', autouse=True)
def polkit_check():
return get_polkit_check(Testing.TEST_CONFIG[0])
@pytest.mark.parametrize('package', ['binary/testpolkitcheck'])
def test_check_actions_malformatted(tmpdir, package, polkit_check):
output, test = polkit_check
test.check(get_tested_package(package, tmpdir))
out = output.print_results(output.results)
assert 'testpolkitcheck.x86_64: E: polkit-xml-exception /usr/share/polkit-1/actions/malformatted.xml.policy raised an exception: mismatched tag: line 23, column 51' in out
@pytest.mark.parametrize('package', ['binary/testpolkitcheck'])
def test_check_actions_ghost_file(tmpdir, package, polkit_check):
output, test = polkit_check
test.check(get_tested_package(package, tmpdir))
out = output.print_results(output.results)
assert 'testpolkitcheck.x86_64: E: polkit-ghost-file /usr/share/polkit-1/actions/ghost.policy' in out
@pytest.mark.parametrize('package', ['binary/testpolkitcheck'])
def test_check_actions_missing_allow_type(tmpdir, package, polkit_check):
output, test = polkit_check
test.check(get_tested_package(package, tmpdir))
out = output.print_results(output.results)
assert 'testpolkitcheck.x86_64: E: polkit-untracked-privilege missing.allow.type (no:auth_admin_keep:auth_admin_keep)' in out
@pytest.mark.parametrize('package', ['binary/testpolkitcheck'])
def test_check_actions_auth_admin(tmpdir, package, polkit_check):
output, test = polkit_check
test.check(get_tested_package(package, tmpdir))
out = output.print_results(output.results)
assert 'testpolkitcheck.x86_64: E: polkit-untracked-privilege auth.admin.policy (auth_admin:no:auth_admin_keep)' in out
|
gpl-2.0
| -8,447,820,223,201,931,000
| 37.877193
| 175
| 0.743682
| false
| 3.268437
| true
| false
| false
|
spacecowboy/pysurvival-ann
|
setup.py
|
1
|
2269
|
#!/usr/bin/env python
"""
General instructions:
python setup.py build
python setup.py install
To include parts that depend on R's survival module, do:
python setup.py build --with-R
Info: This package depends on numpy, and optionally R, RInside
"""
from distutils.core import setup, Extension
import subprocess
import numpy
import sys
sources = ['src/PythonModule.cpp',
'src/ErrorFunctions.cpp',
'src/ErrorFunctionsGeneral.cpp',
'src/ErrorFunctionsSurvival.cpp',
'src/Statistics.cpp',
'src/RPropNetworkWrapper.cpp',
'src/RPropNetwork.cpp',
'src/drand.cpp',
'src/activationfunctions.cpp',
'src/c_index.cpp', 'src/CIndexWrapper.cpp',
'src/MatrixNetwork.cpp',
'src/MatrixNetworkWrapper.cpp',
'src/GeneticNetwork.cpp',
'src/GeneticFitness.cpp',
'src/GeneticSelection.cpp',
'src/GeneticMutation.cpp',
'src/GeneticCrossover.cpp',
'src/GeneticNetworkWrapper.cpp',
'src/ErrorFunctionsWrapper.cpp',
'src/WrapperHelpers.cpp',
'src/Random.cpp']
# Numpy stuff
numpy_include = numpy.get_include()
compileargs = []
libs = []
libdirs = []
linkargs = []
#if ("--help" in sys.argv or
if ("-h" in sys.argv or
len(sys.argv) == 1):
sys.exit(__doc__)
# Python setup
_ann = Extension('ann._ann',
sources = sources,
include_dirs = [numpy_include],
extra_compile_args = ['-std=c++0x',
'-Wall',
'-O3',
'-fopenmp'] + compileargs,
extra_link_args = ['-fopenmp'] + linkargs,
libraries=libs, library_dirs=libdirs)
setup(name = 'pysurvival-ann',
version = '0.9',
description = 'A C++ neural network package for survival data',
author = 'Jonas Kalderstam',
author_email = 'jonas@kalderstam.se',
url = 'https://github.com/spacecowboy/pysurvival-ann',
packages = ['ann'],
package_dir = {'ann': 'ann'},
ext_modules = [_ann],
setup_requires = ['numpy'],
install_requires = ['numpy>=1.7.1']
)
|
gpl-2.0
| 3,438,694,046,496,193,500
| 28.467532
| 69
| 0.557074
| false
| 3.6304
| false
| false
| false
|
patcamwol/frontendXInterfaces
|
libsrc/python/input_ports.py
|
1
|
7409
|
#
# This file is protected by Copyright. Please refer to the COPYRIGHT file
# distributed with this source distribution.
#
# This file is part of REDHAWK frontendInterfaces.
#
# REDHAWK frontendInterfaces is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# REDHAWK frontendInterfaces 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see http://www.gnu.org/licenses/.
#
import threading
from redhawk.frontendxInterfaces import FRONTENDX__POA
from redhawk.frontendxInterfaces import FRONTENDX
from redhawk.frontendInterfaces import FRONTEND
import copy
'''provides port(s)'''
class audio_delegation(object):
def getAudioType(id):
raise FRONTEND.NotSupportedException("getAudioType not supported")
def getAudioDeviceControl(id):
raise FRONTEND.NotSupportedException("getAudioDeviceControl not supported")
def getFullBandwidthChannels(id):
raise FRONTEND.NotSupportedException("getFullBandwidthChannels not supported")
def getLowFrequencyEffectChannels(id):
raise FRONTEND.NotSupportedException("getLowFrequencyEffectChannels not supported")
def setAudioEnable(id, enable):
raise FRONTEND.NotSupportedException("setAudioEnable not supported")
def getAudioEnable(id):
raise FRONTEND.NotSupportedException("getAudioEnable not supported")
def setAudioOutputSampleRate(id, sr):
raise FRONTEND.NotSupportedException("setAudioOutputSampleRate not supported")
def getAudioOutputSampleRate(id):
raise FRONTEND.NotSupportedException("getAudioOutputSampleRate not supported")
def getAudioStatus(id):
raise FRONTEND.NotSupportedException("getAudioStatus not supported")
class InFrontendAudioPort(FRONTEND__POA.FrontendAudio):
def __init__(self, name, parent=audio_delegation()):
self.name = name
self.port_lock = threading.Lock()
self.parent = parent
def getAudioType(self, id):
self.port_lock.acquire()
try:
return self.parent.getAudioType(id)
finally:
self.port_lock.release()
def getAudioDeviceControl(self, id):
self.port_lock.acquire()
try:
return self.parent.getAudioDeviceControl(id)
finally:
self.port_lock.release()
def getFullBandwidthChannels(self, id):
self.port_lock.acquire()
try:
return self.parent.getFullBandwidthChannels(id)
finally:
self.port_lock.release()
def getLowFrequencyEffectChannels(self, id):
self.port_lock.acquire()
try:
return self.parent.getLowFrequencyEffectChannels(id)
finally:
self.port_lock.release()
def setAudioEnable(self, id, enable):
self.port_lock.acquire()
try:
return self.parent.setAudioEnable(id,enable)
finally:
self.port_lock.release()
def getAudioEnable(self, id):
self.port_lock.acquire()
try:
return self.parent.getAudioEnable(id)
finally:
self.port_lock.release()
def setAudioOutputSampleRate(self, id, sr):
self.port_lock.acquire()
try:
return self.parent.setAudioOutputSampleRate(id,sr)
finally:
self.port_lock.release()
def getAudioOutputSampleRate(self, id):
self.port_lock.acquire()
try:
return self.parent.getAudioOutputSampleRate(id)
finally:
self.port_lock.release()
def getAudioStatus(self, id):
self.port_lock.acquire()
try:
return self.parent.getAudioStatus(id)
finally:
self.port_lock.release()
class video_delegation(object):
def getVideoType(id):
raise FRONTEND.NotSupportedException("getVideoType not supported")
def getVideoDeviceControl(id):
raise FRONTEND.NotSupportedException("getVideoDeviceControl not supported")
def getChannels(id):
raise FRONTEND.NotSupportedException("getChannels not supported")
def getFrameHeight(id):
raise FRONTEND.NotSupportedException("getFrameHeight not supported")
def getFrameWidth(id):
raise FRONTEND.NotSupportedException("getFrameWidth not supported")
def setVideoEnable(id, enable):
raise FRONTEND.NotSupportedException("setVideoEnable not supported")
def getVideoEnable(id):
raise FRONTEND.NotSupportedException("getVideoEnable not supported")
def setVideoOutputFrameRate(id, fr):
raise FRONTEND.NotSupportedException("setVideoOutputFrameRate not supported")
def getVideoOutputFrameRate(id):
raise FRONTEND.NotSupportedException("getVideoOutputFrameRate not supported")
def getVideoStatus(id):
raise FRONTEND.NotSupportedException("getVideoStatus not supported")
class InFrontendVideoPort(FRONTEND__POA.FrontendVideo):
def __init__(self, name, parent=audio_delegation()):
self.name = name
self.port_lock = threading.Lock()
self.parent = parent
def getVideoType(self, id):
self.port_lock.acquire()
try:
return self.parent.getVideoType(id)
finally:
self.port_lock.release()
def getVideoDeviceControl(self, id):
self.port_lock.acquire()
try:
return self.parent.getVideoDeviceControl(id)
finally:
self.port_lock.release()
def getChannels(self, id):
self.port_lock.acquire()
try:
return self.parent.getChannels(id)
finally:
self.port_lock.release()
def getFrameHeight(self, id):
self.port_lock.acquire()
try:
return self.parent.getFrameHeight(id)
finally:
self.port_lock.release()
def getFrameWidth(self, id):
self.port_lock.acquire()
try:
return self.parent.getFrameWidth(id)
finally:
self.port_lock.release()
def setVideoEnable(self, id, enable):
self.port_lock.acquire()
try:
return self.parent.setVideoEnable(id,enable)
finally:
self.port_lock.release()
def getVideoEnable(self, id):
self.port_lock.acquire()
try:
return self.parent.getVideoEnable(id)
finally:
self.port_lock.release()
def setVideoOutputFrameRate(self, id, fr):
self.port_lock.acquire()
try:
return self.parent.setVideoOutputFrameRate(id,fr)
finally:
self.port_lock.release()
def getVideoOutputFrameRate(self, id):
self.port_lock.acquire()
try:
return self.parent.getVideoOutputFrameRate(id)
finally:
self.port_lock.release()
def getVideoStatus(self, id):
self.port_lock.acquire()
try:
return self.parent.getVideoStatus(id)
finally:
self.port_lock.release()
|
lgpl-3.0
| -1,823,136,341,251,483,000
| 33.300926
| 93
| 0.668241
| false
| 4.160022
| false
| false
| false
|
Azure/azure-sdk-for-python
|
sdk/containerservice/azure-mgmt-containerservice/azure/mgmt/containerservice/v2019_06_01/aio/operations/_operations.py
|
1
|
4664
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class Operations:
"""Operations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.containerservice.v2019_06_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def list(
self,
**kwargs: Any
) -> AsyncIterable["_models.OperationListResult"]:
"""Gets a list of compute operations.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either OperationListResult or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.containerservice.v2019_06_01.models.OperationListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-06-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list.metadata['url'] # type: ignore
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('OperationListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/providers/Microsoft.ContainerService/operations'} # type: ignore
|
mit
| 1,130,047,885,149,254,000
| 43.846154
| 133
| 0.645583
| false
| 4.636183
| false
| false
| false
|
pbourgel/mybreakout
|
bounceables.py
|
1
|
7962
|
###############################################################################
# #
# bounceables.py #
# #
# Class definitions for obhects off of which the ball can bounce #
# #
# Important classes #
# Wall #
# Paddle #
# Block #
# #
# Note also three rules for the game physics. #
# #
# #
# #
###############################################################################
#If we were to keep this realistic, the only rule in place would be angle
#of incidence equals angle of reflection, but this is video games! Physics
#is just a suggestion!
#AIAR: Angle of incidence equals angle of reflection, or in this
#case, we multiply one of the dx's or dy's by -1
#WARP; adjust according to where the ball collided. If the ball collides with
#the left half of the paddle, it should make the ball move left, and vice versa.
#SPEED: colliding object imparts some speed to the ball when it collides.
#increase the frame rate or scale up the ball movement speed?
#I'm leaving this one to the player. You'll have to refactor
#Ball.process_collision and Paddle.on_collide, and see what adding it does to
#the game.
#CORNER_ENABLED: If the ball hits in a small space designated the corner,
#it will multiply both dx and dy by -1.
from __future__ import division #needed in Python 2.7 so we can divide floats without rounding off
from constants import *
import pygame
#Nothing special here, just a surface to bounce off of.
#All we're concerned with is what axis to reflect on
class Wall():
def __init__(self, x, y, width, height, axis):
self.axis = axis
self.color = BLACK
self.rect = pygame.Rect(x,y,width,height)
def on_collide(self):
return {'AIAR': self.axis}
class Paddle():
def __init__(self, color, x, y):
self.color = color
self.rect = pygame.Rect(y,x, PADDLE_WIDTH, PADDLE_HEIGHT)
self.ul_corner = pygame.Rect(y, x + (BALL_WIDTH - 2), 2, 2)
self.ur_corner = pygame.Rect(y, x + (BALL_WIDTH - 2), 2, 2)
#probably unnecessary abstraction around paddle.rect
def paddle_rect(self):
return self.rect
#handles collision. implements the three main physics rules we want: corner collisions, AIAR, and the warped paddle
def on_collide(self, ball):
if pygame.Rect.colliderect(self.ul_corner,ball.lr_corner) or pygame.Rect.colliderect(self.ur_corner,ball.ll_corner):
return {'CORNER_ENABLED': ''}
#calculate the warp offset by dividing the difference between the middle of the ball and the middle of the paddle by the block width
ball_center = ball.rect.midbottom[0]
warp_offset = (ball_center - self.rect.midtop[0]) / BLOCK_WIDTH
# print 'in on_collide, warp_offset = ' + str(warp_offset)
#the fact that this doesn't handle AIAR collisions the same way might lead to a weird bug where
#you can hold the ball in the paddle as it jiggles around a little. Someone should file a
#ticket in the Github repo about that
return {'WARP': warp_offset,'AIAR': 'y'}
#Handles paddle movement. Checks to make sure the paddle isn't at the left or
#right-hand sides of the screen first
def move_paddle(self,direction):
if direction == '-' and self.rect.x > PADDLE_SPEED and self.rect.x > 0:
self.rect.move_ip((PADDLE_SPEED*-1),0)
self.ul_corner.move_ip((PADDLE_SPEED*-1),0)
self.ur_corner.move_ip((PADDLE_SPEED*-1),0)
elif direction == '+' and (self.rect.x + PADDLE_WIDTH) < SCREENWIDTH:
self.rect.move_ip(PADDLE_SPEED,0)
self.ul_corner.move_ip((PADDLE_SPEED),0)
self.ur_corner.move_ip((PADDLE_SPEED),0)
class Block():
def __init__(self, ccounter, rct):
self.ccounter = ccounter
if self.ccounter == 6:
self.color = CYAN #Yes, this should be indigo. I didn't make it indigo because video games.
elif self.ccounter == 5:
self.color = BLUE
elif self.ccounter == 4:
self.color = GREEN
elif self.ccounter == 3:
self.color = YELLOW
elif self.ccounter == 2:
self.color = ORANGE
elif self.ccounter == 1:
self.color = RED
elif self.ccounter == 0:
self.color = BLACK
#This is the rectangle that gets drawn in the game loop
self.rect = rct
#This is worked out to handle the corner collision rule
self.ul_corner = pygame.Rect(self.rect.y, self.rect.x + (BALL_WIDTH - CORNER_CONSTANT), CORNER_CONSTANT, CORNER_CONSTANT)
self.ll_corner = pygame.Rect(self.rect.y + (BALL_HEIGHT - CORNER_CONSTANT), self.rect.x, CORNER_CONSTANT, CORNER_CONSTANT)
self.ur_corner = pygame.Rect(self.rect.y, self.rect.x + (BALL_WIDTH - CORNER_CONSTANT), CORNER_CONSTANT, CORNER_CONSTANT)
self.lr_corner = pygame.Rect(self.rect.y + (BALL_HEIGHT - CORNER_CONSTANT), self.rect.x + (BALL_WIDTH - CORNER_CONSTANT), CORNER_CONSTANT, CORNER_CONSTANT)
#return CORNER_ENABLED if it hit the corner squares
#else we just do straight angle of incidence equals angle of reflection
#to figure out which axis to reflect the ball on, calculate the ball's position
#one dx in the opposite direction. If that collides with the block, then it means
#we need to go dy y coordinates back, else we reflect on the x axis.
#This comes with one constraint
#1. We can't let the ball move so far into the block before calling on_collide that it screws with the logic, so we constrain BALL_SPEED to +- the smallest dimension of the block.
#Hey, here's an idea: In some Breakout/Arkanoid games, they play a short
#beep whenever a collision occurs. If a bunch of collisions happen in
#close succession, it's like wind chimes. Maybe you should add that.
def on_collide(self,ball):
self.ccounter-=1
self.change_color()
if pygame.Rect.colliderect(self.ll_corner, ball.ur_corner) or pygame.Rect.colliderect(self.ul_corner,ball.lr_corner) or pygame.Rect.colliderect(self.ur_corner, ball.ll_corner) or pygame.Rect.colliderect(self.lr_corner,ball.ul_corner):
return {'CORNER_ENABLED': ''}
else:
if self.rect.colliderect(ball.rect.move(ball.dx*-1,ball.dy)):
return {'AIAR': 'y'}
else:
return {'AIAR': 'x'}
#Changes the brick color in response to a collision.
def change_color(self):
if self.ccounter == 5:
self.color = BLUE
elif self.ccounter == 4:
self.color = GREEN
elif self.ccounter == 3:
self.color = YELLOW
elif self.ccounter == 2:
self.color = ORANGE
elif self.ccounter == 1:
self.color = RED
elif self.ccounter == 0:
self.color = BLACK
#Intentionally leaving this blank
#Hey, I gotta leave something for other people to build on, right?
#You might want to create a separate powerup class for this
# def drop_powerup(self):
# pass ballrect.move(0,1)
|
gpl-3.0
| -7,460,730,442,292,494,000
| 49.713376
| 242
| 0.568325
| false
| 3.910609
| false
| false
| false
|
cymplecy/codebug_tether
|
setup.py
|
1
|
1209
|
import sys
from distutils.core import setup
VERSION_FILE = 'codebug_tether/version.py'
PY3 = sys.version_info[0] >= 3
def get_version():
if PY3:
version_vars = {}
with open(VERSION_FILE) as f:
code = compile(f.read(), VERSION_FILE, 'exec')
exec(code, None, version_vars)
return version_vars['__version__']
else:
execfile(VERSION_FILE)
return __version__
setup(
name='codebug_tether',
version=get_version(),
description='Control CodeBug over Serial USB.',
author='Thomas Preston',
author_email='thomas.preston@openlx.org.uk',
license='GPLv3+',
url='https://github.com/codebugtools/codebug_tether',
packages=['codebug_tether'],
long_description=open('README.md').read() + open('CHANGELOG').read(),
classifiers=[
"License :: OSI Approved :: GNU Affero General Public License v3 or "
"later (AGPLv3+)",
"Programming Language :: Python :: 3",
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Topic :: Software Development :: Libraries :: Python Modules",
],
keywords='codebug tether raspberrypi openlx',
)
|
gpl-3.0
| -6,195,292,297,385,302,000
| 29.225
| 77
| 0.621175
| false
| 3.754658
| false
| false
| false
|
uclouvain/osis
|
ddd/logic/learning_unit/domain/model/_titles.py
|
1
|
2084
|
##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core business involves the administration of students, teachers,
# courses, programs and so on.
#
# Copyright (C) 2015-2021 Université catholique de Louvain (http://www.uclouvain.be)
#
# 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 3 of the License, or
# (at your option) any later version.
#
# This program 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.
#
# A copy of this license - GNU General Public License - is available
# at the root of the source code of this program. If not,
# see http://www.gnu.org/licenses/.
#
##############################################################################
import attr
from osis_common.ddd import interface
@attr.s(frozen=True, slots=True)
class Titles(interface.ValueObject):
common_fr = attr.ib(type=str)
specific_fr = attr.ib(type=str)
common_en = attr.ib(type=str)
specific_en = attr.ib(type=str)
@property
def complete_fr(self) -> str:
if self.common_fr and self.specific_fr:
return self.common_fr + " - " + self.specific_fr
elif self.common_fr:
return self.common_fr
else:
return self.specific_fr
@property
def complete_en(self) -> str:
if self.common_en and self.specific_en:
return self.common_en + " - " + self.specific_en
elif self.common_en:
return self.common_en
else:
return self.specific_en
|
agpl-3.0
| 9,158,577,290,105,660,000
| 37.574074
| 87
| 0.6265
| false
| 3.908068
| false
| false
| false
|
FreeOpcUa/python-opcua
|
examples/client_to_prosys.py
|
1
|
2365
|
import sys
sys.path.insert(0, "..")
import time
import logging
from opcua import Client
from opcua import ua
class SubHandler(object):
"""
Client to subscription. It will receive events from server
"""
def datachange_notification(self, node, val, data):
print("Python: New data change event", node, val)
def event_notification(self, event):
print("Python: New event", event)
if __name__ == "__main__":
#from IPython import embed
logging.basicConfig(level=logging.DEBUG)
client = Client("opc.tcp://localhost:53530/OPCUA/SimulationServer/")
#client = Client("opc.tcp://olivier:olivierpass@localhost:53530/OPCUA/SimulationServer/")
#client.set_security_string("Basic256Sha256,SignAndEncrypt,certificate-example.der,private-key-example.pem")
try:
client.connect()
root = client.get_root_node()
print("Root is", root)
print("childs of root are: ", root.get_children())
print("name of root is", root.get_browse_name())
objects = client.get_objects_node()
print("childs og objects are: ", objects.get_children())
myfloat = client.get_node("ns=4;s=Float")
mydouble = client.get_node("ns=4;s=Double")
myint64 = client.get_node("ns=4;s=Int64")
myuint64 = client.get_node("ns=4;s=UInt64")
myint32 = client.get_node("ns=4;s=Int32")
myuint32 = client.get_node("ns=4;s=UInt32")
var = client.get_node(ua.NodeId("Random1", 5))
print("var is: ", var)
print("value of var is: ", var.get_value())
var.set_value(ua.Variant([23], ua.VariantType.Double))
print("setting float value")
myfloat.set_value(ua.Variant(1.234, ua.VariantType.Float))
print("reading float value: ", myfloat.get_value())
handler = SubHandler()
sub = client.create_subscription(500, handler)
handle = sub.subscribe_data_change(var)
device = objects.get_child(["2:MyObjects", "2:MyDevice"])
method = device.get_child("2:MyMethod")
result = device.call_method(method, ua.Variant("sin"), ua.Variant(180, ua.VariantType.Double))
print("Mehtod result is: ", result)
#embed()
time.sleep(3)
sub.unsubscribe(handle)
sub.delete()
#client.close_session()
finally:
client.disconnect()
|
lgpl-3.0
| 5,179,125,964,854,195,000
| 34.298507
| 112
| 0.629598
| false
| 3.493353
| false
| false
| false
|
naoyat/latin
|
latin/latindic.py
|
1
|
1985
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import latin_noun
import latin_pronoun
import latin_adj
import latin_conj
import latin_prep
import latin_verb_reg
import latin_verb_irreg
import util
class LatinDic:
dic = {}
auto_macron_mode = False
def flatten(text):
return text.replace(u'ā',u'a').replace(u'ē',u'e').replace(u'ī',u'i').replace(u'ō',u'o').replace(u'ū',u'u').replace(u'ȳ',u'y').lower()
def register(surface, info):
if not info.has_key('pos'): return
if LatinDic.auto_macron_mode:
surface = flatten(surface)
if LatinDic.dic.has_key(surface):
LatinDic.dic[surface].append(info)
else:
LatinDic.dic[surface] = [info]
def register_items(items):
for item in items:
register(item['surface'], item)
def lookup(word):
return LatinDic.dic.get(word, None)
def dump():
for k, v in LatinDic.dic.items():
print util.render2(k, v)
def load_def(file, tags={}):
items = []
with open(file, 'r') as fp:
for line in fp:
if len(line) == 0: continue
if line[0] == '#': continue
fs = line.rstrip().split('\t')
if len(fs) < 3: continue
surface = fs[0].decode('utf-8')
pos = fs[1]
ja = fs[2]
items.append(util.aggregate_dicts({'surface':surface, 'pos':pos, 'ja':ja}, tags))
return items
def load(auto_macron_mode=False):
LatinDic.auto_macron_mode = auto_macron_mode
items = []
items += latin_noun.load()
items += latin_pronoun.load()
items += latin_adj.load()
items += latin_conj.load()
items += latin_prep.load()
items += latin_verb_reg.load()
items += latin_verb_irreg.load()
items += load_def('words/adv.def', {'pos':'adv'})
items += load_def('words/other.def')
register_items(items)
# return ld
if __name__ == '__main__':
# for k, v in dic.items():
# print util.render(k), util.render(v)
pass
|
mit
| 3,132,495,049,686,143,000
| 20.053191
| 137
| 0.583123
| false
| 3.068217
| false
| false
| false
|
hfaran/ubc-timetabler
|
timetabler/util.py
|
1
|
3085
|
from __future__ import division
from math import sqrt
#############
# Constants #
#############
DAY_LIST = ["Mon", "Tue", "Wed", "Thu", "Fri"]
###########
# Helpers #
###########
# General
def chunks(l, n):
"""Yields successive ``n``-sized chunks from ``l``
http://stackoverflow.com/a/312464/1798683
"""
for i in xrange(0, len(l), n):
yield l[i:i + n]
def check_equal(iterable):
"""Check equivalency or all items in ``iterable``
>>> check_equal(xrange(5))
False
>>> check_equal([1, 1, 1])
True
>>> check_equal([1, 2, 1])
False
"""
iterable = iter(iterable)
first = next(iterable)
return all(first == i for i in iterable)
def check_diff(iterable):
"""Returns true if any items in ``iterable`` differ
>>> check_diff([1, 1])
False
>>> check_diff([1, 2])
True
>>> check_diff(xrange(5))
True
"""
iterable = iter(iterable)
first = next(iterable)
return any(first != i for i in iterable)
def all_unique(x):
"""Check if all items in ``x`` are unique
http://stackoverflow.com/a/5281641/1798683
"""
seen = set()
return not any(i in seen or seen.add(i) for i in x)
def stddev(lst):
"""Calculate **population** (not sample) standard deviation of ``lst``
:type lst: list
:param lst: List of numbers
:returns: standard deviation of ``lst``
:rtype: float
>>> act = stddev([13,25,46,255,55])
>>> exp = 89.34517334
>>> abs(act - exp) < 1E-6
True
"""
points = len(lst)
mean = sum(lst)/points
variance = sum((i - mean)**2 for i in lst)/points
return sqrt(variance)
def setup_root_logger(log_level='INFO'):
import logging
import sys
root = logging.getLogger()
root.setLevel(getattr(logging, log_level))
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
root.addHandler(ch)
# timetabler-specific helpers
def strtime2num(s):
"""Turns ``s`` like "09:00" to 9.5"""
t = s.split(":")
t = map(int, t)
if t[1] == 30:
return t[0] + 0.5
else:
return t[0]
def iter_time(start, end):
"""Returns an iterator that gives a range of half-hourly time
from ``start`` (inclusive) to ``end`` (exclusive)
>>> list(iter_time("09:00", "12:30"))
['09:00', '09:30', '10:00', '10:30', '11:00', '11:30', '12:00']
"""
def time2tuple(t):
return tuple(map(int, t.split(":")))
def tuple2time(t):
return ":".join([str(i).zfill(2) for i in t])
current = start
while current < end:
# Put yield at the time because we do inclusive start, exclusive stop
yield current
_current = time2tuple(current)
if _current[1] == 30:
_current = (_current[0] + 1, 0)
else:
_current = (_current[0], 30)
current = tuple2time(_current)
if __name__ == '__main__':
import doctest
doctest.testmod()
|
mit
| -6,416,785,595,618,662,000
| 21.035714
| 89
| 0.561426
| false
| 3.306538
| false
| false
| false
|
cpenner461/tellmewhen
|
tmw/server.py
|
1
|
4361
|
'''
Built-in web server using Flask. Should mirror functionality offered by the
cli.
'''
from flask import Flask
from flask import render_template, request, session
import tmw.config as config
import tmw.core as core
import json
from uuid import uuid4
from multiprocessing import Pool
app = Flask(__name__)
pool = Pool(processes=2)
jobs = []
@app.route('/', methods = ["POST", "GET"])
def index():
'''The main landing page and UI for tmw'''
if request.method == "GET":
return render_template('index.html', jobs=jobs)
else:
url = request.form.get('url')
freq = int(request.form.get('frequency'))
num_checks = int(request.form.get('num_checks'))
check_type = request.form.get('check_type')
value = None
if check_type == 'status_code':
value = request.form.get('status_code')
elif check_type == 'string_match' or check_type == 'regex_match':
value = request.form.get('string_match')
check_results = None
total_checks = None
index = None
def _handle_results(results):
(check_results, total_checks, index) = results
jobs[index]['status'] = "success" if check_results else "failure"
job = pool.apply_async(
core.check_until,
(url, check_type, value, freq, num_checks, len(jobs)),
callback=_handle_results
)
jobs.append({ 'url': url, 'value': value, 'status': 'pending' })
return render_template('index.html', jobs=jobs, success=True)
@app.route('/_job_status')
def _job_status():
return json.dumps(jobs)
@app.route('/hello')
def hello():
'''Simple page useful for testing/validating your tmw setup'''
return render_template('hello.html')
@app.route('/settings', methods = ["POST", "GET"])
def settings():
'''Settings page'''
status = None
if request.method == "POST":
f = request.form
conf = config.load_config()
_set_config_param(conf, 'smtp', 'username', f)
_set_config_param(conf, 'smtp', 'sender', f)
_set_config_param(conf, 'smtp', 'recipients', f)
_set_config_param(conf, 'smtp', 'server', f)
_set_config_param(conf, 'smtp', 'port', f, number = True)
_set_config_param(conf, 'slack', 'username', f)
_set_config_param(conf, 'slack', 'channel', f, prefix = "#")
config.write_config(conf)
settings = config
status = "success"
else:
conf = config.load_config()
settings = {}
settings['smtp-username'] = _get_config_param(conf, 'smtp', 'username')
settings['smtp-sender'] = _get_config_param(conf, 'smtp', 'sender')
settings['smtp-recipients'] = _get_config_param(conf, 'smtp', 'recipients')
settings['smtp-server'] = _get_config_param(conf, 'smtp', 'server')
settings['smtp-port'] = _get_config_param(conf, 'smtp', 'port')
settings['slack-username'] = _get_config_param(conf, 'slack', 'username')
settings['slack-channel'] = _get_config_param(conf, 'slack', 'channel')
return render_template('settings.html', status=status, settings=settings)
def _set_config_param(conf, service, param, form, number = False, prefix = ""):
if not conf.get(service):
conf[service] = {}
if not conf[service].get(param):
conf[service][param] = None
value = form.get('%s-%s' % (service, param))
if value:
value = prefix + value
if number and value:
value = int(value)
conf[service][param] = value if value else conf[service][param]
def _get_config_param(conf, service, param):
if not conf.get(service):
conf[service] = {}
if not conf[service].get(param):
conf[service][param] = None
return conf[service][param]
@app.before_request
def csrf_protect():
if request.method == "POST":
token = session.pop('_csrf_token', None)
if not token or str(token) != request.form.get('_csrf_token'):
abort(403)
def _generate_csrf_token():
if '_csrf_token' not in session:
session['_csrf_token'] = uuid4()
return session['_csrf_token']
app.jinja_env.globals['csrf_token'] = _generate_csrf_token
#Remove this later
@app.route('/email-notification')
def the_path():
return render_template('email-notification.html')
|
mit
| -1,459,745,616,760,489,200
| 30.601449
| 83
| 0.608347
| false
| 3.586349
| true
| false
| false
|
googleapis/googleapis-gen
|
google/cloud/aiplatform/v1beta1/aiplatform-v1beta1-py/google/cloud/aiplatform_v1beta1/services/index_service/async_client.py
|
1
|
26691
|
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from collections import OrderedDict
import functools
import re
from typing import Dict, Sequence, Tuple, Type, Union
import pkg_resources
import google.api_core.client_options as ClientOptions # type: ignore
from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
from google.api_core import operation as gac_operation # type: ignore
from google.api_core import operation_async # type: ignore
from google.cloud.aiplatform_v1beta1.services.index_service import pagers
from google.cloud.aiplatform_v1beta1.types import deployed_index_ref
from google.cloud.aiplatform_v1beta1.types import index
from google.cloud.aiplatform_v1beta1.types import index as gca_index
from google.cloud.aiplatform_v1beta1.types import index_service
from google.cloud.aiplatform_v1beta1.types import operation as gca_operation
from google.protobuf import empty_pb2 # type: ignore
from google.protobuf import field_mask_pb2 # type: ignore
from google.protobuf import struct_pb2 # type: ignore
from google.protobuf import timestamp_pb2 # type: ignore
from .transports.base import IndexServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc_asyncio import IndexServiceGrpcAsyncIOTransport
from .client import IndexServiceClient
class IndexServiceAsyncClient:
"""A service for creating and managing Vertex AI's Index
resources.
"""
_client: IndexServiceClient
DEFAULT_ENDPOINT = IndexServiceClient.DEFAULT_ENDPOINT
DEFAULT_MTLS_ENDPOINT = IndexServiceClient.DEFAULT_MTLS_ENDPOINT
index_path = staticmethod(IndexServiceClient.index_path)
parse_index_path = staticmethod(IndexServiceClient.parse_index_path)
index_endpoint_path = staticmethod(IndexServiceClient.index_endpoint_path)
parse_index_endpoint_path = staticmethod(IndexServiceClient.parse_index_endpoint_path)
common_billing_account_path = staticmethod(IndexServiceClient.common_billing_account_path)
parse_common_billing_account_path = staticmethod(IndexServiceClient.parse_common_billing_account_path)
common_folder_path = staticmethod(IndexServiceClient.common_folder_path)
parse_common_folder_path = staticmethod(IndexServiceClient.parse_common_folder_path)
common_organization_path = staticmethod(IndexServiceClient.common_organization_path)
parse_common_organization_path = staticmethod(IndexServiceClient.parse_common_organization_path)
common_project_path = staticmethod(IndexServiceClient.common_project_path)
parse_common_project_path = staticmethod(IndexServiceClient.parse_common_project_path)
common_location_path = staticmethod(IndexServiceClient.common_location_path)
parse_common_location_path = staticmethod(IndexServiceClient.parse_common_location_path)
@classmethod
def from_service_account_info(cls, info: dict, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
info.
Args:
info (dict): The service account private key info.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
IndexServiceAsyncClient: The constructed client.
"""
return IndexServiceClient.from_service_account_info.__func__(IndexServiceAsyncClient, info, *args, **kwargs) # type: ignore
@classmethod
def from_service_account_file(cls, filename: str, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
file.
Args:
filename (str): The path to the service account private key json
file.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
IndexServiceAsyncClient: The constructed client.
"""
return IndexServiceClient.from_service_account_file.__func__(IndexServiceAsyncClient, filename, *args, **kwargs) # type: ignore
from_service_account_json = from_service_account_file
@property
def transport(self) -> IndexServiceTransport:
"""Returns the transport used by the client instance.
Returns:
IndexServiceTransport: The transport used by the client instance.
"""
return self._client.transport
get_transport_class = functools.partial(type(IndexServiceClient).get_transport_class, type(IndexServiceClient))
def __init__(self, *,
credentials: ga_credentials.Credentials = None,
transport: Union[str, IndexServiceTransport] = "grpc_asyncio",
client_options: ClientOptions = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
"""Instantiates the index service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
transport (Union[str, ~.IndexServiceTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
client_options (ClientOptions): Custom options for the client. It
won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
environment variable can also be used to override the endpoint:
"always" (always use the default mTLS endpoint), "never" (always
use the default regular endpoint) and "auto" (auto switch to the
default mTLS endpoint if client certificate is present, this is
the default value). However, the ``api_endpoint`` property takes
precedence if provided.
(2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
is "true", then the ``client_cert_source`` property can be used
to provide client certificate for mutual TLS transport. If
not provided, the default SSL client certificate will be used if
present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
set, no client certificate will be used.
Raises:
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
creation failed for any reason.
"""
self._client = IndexServiceClient(
credentials=credentials,
transport=transport,
client_options=client_options,
client_info=client_info,
)
async def create_index(self,
request: index_service.CreateIndexRequest = None,
*,
parent: str = None,
index: gca_index.Index = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> operation_async.AsyncOperation:
r"""Creates an Index.
Args:
request (:class:`google.cloud.aiplatform_v1beta1.types.CreateIndexRequest`):
The request object. Request message for
[IndexService.CreateIndex][google.cloud.aiplatform.v1beta1.IndexService.CreateIndex].
parent (:class:`str`):
Required. The resource name of the Location to create
the Index in. Format:
``projects/{project}/locations/{location}``
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
index (:class:`google.cloud.aiplatform_v1beta1.types.Index`):
Required. The Index to create.
This corresponds to the ``index`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.api_core.operation_async.AsyncOperation:
An object representing a long-running operation.
The result type for the operation will be :class:`google.cloud.aiplatform_v1beta1.types.Index` A representation of a collection of database items organized in a way that
allows for approximate nearest neighbor (a.k.a ANN)
algorithms search.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([parent, index])
if request is not None and has_flattened_params:
raise ValueError("If the `request` argument is set, then none of "
"the individual field arguments should be set.")
request = index_service.CreateIndexRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if parent is not None:
request.parent = parent
if index is not None:
request.index = index
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = gapic_v1.method_async.wrap_method(
self._client._transport.create_index,
default_timeout=5.0,
client_info=DEFAULT_CLIENT_INFO,
)
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((
("parent", request.parent),
)),
)
# Send the request.
response = await rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)
# Wrap the response in an operation future.
response = operation_async.from_gapic(
response,
self._client._transport.operations_client,
gca_index.Index,
metadata_type=index_service.CreateIndexOperationMetadata,
)
# Done; return the response.
return response
async def get_index(self,
request: index_service.GetIndexRequest = None,
*,
name: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> index.Index:
r"""Gets an Index.
Args:
request (:class:`google.cloud.aiplatform_v1beta1.types.GetIndexRequest`):
The request object. Request message for
[IndexService.GetIndex][google.cloud.aiplatform.v1beta1.IndexService.GetIndex]
name (:class:`str`):
Required. The name of the Index resource. Format:
``projects/{project}/locations/{location}/indexes/{index}``
This corresponds to the ``name`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.aiplatform_v1beta1.types.Index:
A representation of a collection of
database items organized in a way that
allows for approximate nearest neighbor
(a.k.a ANN) algorithms search.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([name])
if request is not None and has_flattened_params:
raise ValueError("If the `request` argument is set, then none of "
"the individual field arguments should be set.")
request = index_service.GetIndexRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if name is not None:
request.name = name
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = gapic_v1.method_async.wrap_method(
self._client._transport.get_index,
default_timeout=5.0,
client_info=DEFAULT_CLIENT_INFO,
)
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((
("name", request.name),
)),
)
# Send the request.
response = await rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)
# Done; return the response.
return response
async def list_indexes(self,
request: index_service.ListIndexesRequest = None,
*,
parent: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> pagers.ListIndexesAsyncPager:
r"""Lists Indexes in a Location.
Args:
request (:class:`google.cloud.aiplatform_v1beta1.types.ListIndexesRequest`):
The request object. Request message for
[IndexService.ListIndexes][google.cloud.aiplatform.v1beta1.IndexService.ListIndexes].
parent (:class:`str`):
Required. The resource name of the Location from which
to list the Indexes. Format:
``projects/{project}/locations/{location}``
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.aiplatform_v1beta1.services.index_service.pagers.ListIndexesAsyncPager:
Response message for
[IndexService.ListIndexes][google.cloud.aiplatform.v1beta1.IndexService.ListIndexes].
Iterating over this object will yield results and
resolve additional pages automatically.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([parent])
if request is not None and has_flattened_params:
raise ValueError("If the `request` argument is set, then none of "
"the individual field arguments should be set.")
request = index_service.ListIndexesRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if parent is not None:
request.parent = parent
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = gapic_v1.method_async.wrap_method(
self._client._transport.list_indexes,
default_timeout=5.0,
client_info=DEFAULT_CLIENT_INFO,
)
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((
("parent", request.parent),
)),
)
# Send the request.
response = await rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)
# This method is paged; wrap the response in a pager, which provides
# an `__aiter__` convenience method.
response = pagers.ListIndexesAsyncPager(
method=rpc,
request=request,
response=response,
metadata=metadata,
)
# Done; return the response.
return response
async def update_index(self,
request: index_service.UpdateIndexRequest = None,
*,
index: gca_index.Index = None,
update_mask: field_mask_pb2.FieldMask = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> operation_async.AsyncOperation:
r"""Updates an Index.
Args:
request (:class:`google.cloud.aiplatform_v1beta1.types.UpdateIndexRequest`):
The request object. Request message for
[IndexService.UpdateIndex][google.cloud.aiplatform.v1beta1.IndexService.UpdateIndex].
index (:class:`google.cloud.aiplatform_v1beta1.types.Index`):
Required. The Index which updates the
resource on the server.
This corresponds to the ``index`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`):
The update mask applies to the resource. For the
``FieldMask`` definition, see
[google.protobuf.FieldMask][google.protobuf.FieldMask].
This corresponds to the ``update_mask`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.api_core.operation_async.AsyncOperation:
An object representing a long-running operation.
The result type for the operation will be :class:`google.cloud.aiplatform_v1beta1.types.Index` A representation of a collection of database items organized in a way that
allows for approximate nearest neighbor (a.k.a ANN)
algorithms search.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([index, update_mask])
if request is not None and has_flattened_params:
raise ValueError("If the `request` argument is set, then none of "
"the individual field arguments should be set.")
request = index_service.UpdateIndexRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if index is not None:
request.index = index
if update_mask is not None:
request.update_mask = update_mask
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = gapic_v1.method_async.wrap_method(
self._client._transport.update_index,
default_timeout=5.0,
client_info=DEFAULT_CLIENT_INFO,
)
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((
("index.name", request.index.name),
)),
)
# Send the request.
response = await rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)
# Wrap the response in an operation future.
response = operation_async.from_gapic(
response,
self._client._transport.operations_client,
gca_index.Index,
metadata_type=index_service.UpdateIndexOperationMetadata,
)
# Done; return the response.
return response
async def delete_index(self,
request: index_service.DeleteIndexRequest = None,
*,
name: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> operation_async.AsyncOperation:
r"""Deletes an Index. An Index can only be deleted when all its
[DeployedIndexes][google.cloud.aiplatform.v1beta1.Index.deployed_indexes]
had been undeployed.
Args:
request (:class:`google.cloud.aiplatform_v1beta1.types.DeleteIndexRequest`):
The request object. Request message for
[IndexService.DeleteIndex][google.cloud.aiplatform.v1beta1.IndexService.DeleteIndex].
name (:class:`str`):
Required. The name of the Index resource to be deleted.
Format:
``projects/{project}/locations/{location}/indexes/{index}``
This corresponds to the ``name`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.api_core.operation_async.AsyncOperation:
An object representing a long-running operation.
The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated
empty messages in your APIs. A typical example is to
use it as the request or the response type of an API
method. For instance:
service Foo {
rpc Bar(google.protobuf.Empty) returns
(google.protobuf.Empty);
}
The JSON representation for Empty is empty JSON
object {}.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([name])
if request is not None and has_flattened_params:
raise ValueError("If the `request` argument is set, then none of "
"the individual field arguments should be set.")
request = index_service.DeleteIndexRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if name is not None:
request.name = name
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = gapic_v1.method_async.wrap_method(
self._client._transport.delete_index,
default_timeout=5.0,
client_info=DEFAULT_CLIENT_INFO,
)
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((
("name", request.name),
)),
)
# Send the request.
response = await rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)
# Wrap the response in an operation future.
response = operation_async.from_gapic(
response,
self._client._transport.operations_client,
empty_pb2.Empty,
metadata_type=gca_operation.DeleteOperationMetadata,
)
# Done; return the response.
return response
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=pkg_resources.get_distribution(
"google-cloud-aiplatform",
).version,
)
except pkg_resources.DistributionNotFound:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
__all__ = (
"IndexServiceAsyncClient",
)
|
apache-2.0
| -7,461,925,922,549,992,000
| 41.165877
| 185
| 0.616762
| false
| 4.62422
| false
| false
| false
|
Magicked/crits
|
crits/events/event.py
|
4
|
3783
|
import uuid
try:
from django_mongoengine import Document
except ImportError:
from mongoengine import Document
from mongoengine import StringField, UUIDField, BooleanField
from mongoengine import EmbeddedDocument
from django.conf import settings
from crits.core.crits_mongoengine import CritsBaseAttributes
from crits.core.crits_mongoengine import CritsSourceDocument
from crits.core.crits_mongoengine import CommonAccess, CritsDocumentFormatter
from crits.core.crits_mongoengine import CritsActionsDocument
from crits.events.migrate import migrate_event
from crits.vocabulary.events import EventTypes
class UnreleasableEventError(Exception):
"""
Exception for attempting to release an event relationship that is
unreleasable.
"""
def __init__(self, value, **kwargs):
self.message = "Relationship %s cannot be released to the event's \
releasability list." % value
super(UnreleasableEventError, self).__init__(**kwargs)
def __str__(self):
return repr(self.message)
class Event(CritsBaseAttributes, CritsSourceDocument, CritsActionsDocument,
Document):
"""
Event class.
"""
meta = {
"collection": settings.COL_EVENTS,
"auto_create_index": False,
"crits_type": 'Event',
"latest_schema_version": 3,
"schema_doc": {
'title': 'Title of this event',
'event_id': 'Unique event ID',
'event_type': 'Type of event based on Event Type options',
'description': 'Description of the event',
'source': ('List [] of sources who provided information about this'
' event')
},
"jtable_opts": {
'details_url': 'crits-events-views-view_event',
'details_url_key': 'id',
'default_sort': "created DESC",
'searchurl': 'crits-events-views-events_listing',
'fields': [ "title", "event_type", "created",
"source", "campaign", "status", "id"],
'jtopts_fields': [ "details",
"title",
"event_type",
"created",
"source",
"campaign",
"status",
"favorite",
"id"],
'hidden_fields': [],
'linked_fields': ["source", "campaign", "event_type"],
'details_link': 'details',
'no_sort': ['details']
}
}
title = StringField(required=True)
event_type = StringField(required=True)
# description also exists in CritsBaseAttributes, but this one is required.
description = StringField(required=True)
event_id = UUIDField(binary=True, required=True, default=uuid.uuid4)
def set_event_type(self, event_type):
"""
Set the Event Type.
:param event_type: The event type to set (must exist in DB).
:type event_type: str
"""
if event_type in EventTypes.values():
self.event_type = event_type
def migrate(self):
"""
Migrate to the latest schema version.
"""
migrate_event(self)
class EventAccess(EmbeddedDocument, CritsDocumentFormatter, CommonAccess):
"""
ACL for Events.
"""
add_sample = BooleanField(default=False)
title_edit = BooleanField(default=False)
type_edit = BooleanField(default=False)
|
mit
| 5,491,923,777,403,173,000
| 33.081081
| 79
| 0.545863
| false
| 4.563329
| false
| false
| false
|
autopower/thermeq3
|
obsolete/lib/dummy.py
|
1
|
1621
|
import thermeq3
import datetime
def add_dummy(status):
"""
:param status: is window open?
:return: nothing
"""
# valves = {valve_adr: [valve_pos, valve_temp, valve_curtemp, valve_name]}
# rooms = {id : [room_name, room_address, is_win_open, curr_temp, average valve position]}
# devices = {addr: [type, serial, name, room, OW, OW_time, status, info, temp offset]}
thermeq3.t3.eq3.rooms.update({"99": ["Dummy room", "DeadBeefValve", False, 22.0, 22]})
thermeq3.t3.eq3.devices.update({"DeadBeefWindow": [4, "IHADBW", "Dummy window", 99, 0,
datetime.datetime(2016, 01, 01, 12, 00, 00), 18, 16, 7]})
thermeq3.t3.eq3.devices.update({"DeadBeefValve": [1, "IHADBV", "Dummy valve", 99, 0,
datetime.datetime(2016, 01, 01, 12, 00, 00), 18, 56, 7]})
thermeq3.t3.eq3.valves.update({"DeadBeefValve": [20, 22.0, 22.0, "Dummy valve"]})
# TBI open/closed window
if status:
thermeq3.t3.eq3.devices["DeadBeefWindow"][4] = 2
thermeq3.t3.eq3.devices["DeadBeefWindow"][5] = \
datetime.datetime.now() - \
datetime.timedelta(seconds=((thermeq3.t3.eq3.ignore_time + 10) * 60))
thermeq3.t3.eq3.rooms["99"][2] = True
else:
thermeq3.t3.eq3.devices["DeadBeefWindow"][4] = 0
thermeq3.t3.eq3.rooms["99"][2] = False
def remove_dummy():
del thermeq3.t3.eq3.rooms["99"]
del thermeq3.t3.eq3.valves["DeadBeefValve"]
del thermeq3.t3.eq3.devices["DeadBeefWindow"]
del thermeq3.t3.eq3.devices["DeadBeefValve"]
|
gpl-3.0
| 619,798,513,470,130,000
| 45.314286
| 112
| 0.592844
| false
| 2.752122
| false
| false
| false
|
colloquium/spacewalk
|
client/solaris/smartpm/smart/channels/rpm_md.py
|
1
|
5464
|
#
# Copyright (c) 2004 Conectiva, Inc.
#
# Written by Gustavo Niemeyer <niemeyer@conectiva.com>
#
# This file is part of Smart Package Manager.
#
# Smart Package Manager 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.
#
# Smart Package Manager 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 Smart Package Manager; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
from smart.backends.rpm.metadata import RPMMetaDataLoader
from smart.util.filetools import getFileDigest
from smart.util.elementtree import ElementTree
from smart.const import SUCCEEDED, FAILED, NEVER, ALWAYS
from smart.channel import PackageChannel
from smart import *
import posixpath
NS = "{http://linux.duke.edu/metadata/repo}"
DATA = NS+"data"
LOCATION = NS+"location"
CHECKSUM = NS+"checksum"
OPENCHECKSUM = NS+"open-checksum"
class RPMMetaDataChannel(PackageChannel):
def __init__(self, baseurl, *args):
super(RPMMetaDataChannel, self).__init__(*args)
self._baseurl = baseurl
def getCacheCompareURLs(self):
return [posixpath.join(self._baseurl, "repodata/repomd.xml")]
def getFetchSteps(self):
return 3
def fetch(self, fetcher, progress):
fetcher.reset()
repomd = posixpath.join(self._baseurl, "repodata/repomd.xml")
item = fetcher.enqueue(repomd)
fetcher.run(progress=progress)
if item.getStatus() is FAILED:
progress.add(self.getFetchSteps()-1)
if fetcher.getCaching() is NEVER:
lines = [_("Failed acquiring release file for '%s':") % self,
u"%s: %s" % (item.getURL(), item.getFailedReason())]
raise Error, "\n".join(lines)
return False
digest = getFileDigest(item.getTargetPath())
if digest == self._digest:
progress.add(1)
return True
self.removeLoaders()
info = {}
root = ElementTree.parse(item.getTargetPath()).getroot()
for node in root.getchildren():
if node.tag != DATA:
continue
type = node.get("type")
info[type] = {}
for subnode in node.getchildren():
if subnode.tag == LOCATION:
info[type]["url"] = \
posixpath.join(self._baseurl, subnode.get("href"))
if subnode.tag == CHECKSUM:
info[type][subnode.get("type")] = subnode.text
if subnode.tag == OPENCHECKSUM:
info[type]["uncomp_"+subnode.get("type")] = \
subnode.text
if "primary" not in info:
raise Error, _("Primary information not found in repository "
"metadata for '%s'") % self
fetcher.reset()
item = fetcher.enqueue(info["primary"]["url"],
md5=info["primary"].get("md5"),
uncomp_md5=info["primary"].get("uncomp_md5"),
sha=info["primary"].get("sha"),
uncomp_sha=info["primary"].get("uncomp_sha"),
uncomp=True)
flitem = fetcher.enqueue(info["filelists"]["url"],
md5=info["filelists"].get("md5"),
uncomp_md5=info["filelists"].get("uncomp_md5"),
sha=info["filelists"].get("sha"),
uncomp_sha=info["filelists"].get("uncomp_sha"),
uncomp=True)
fetcher.run(progress=progress)
if item.getStatus() == SUCCEEDED and flitem.getStatus() == SUCCEEDED:
localpath = item.getTargetPath()
filelistspath = flitem.getTargetPath()
loader = RPMMetaDataLoader(localpath, filelistspath,
self._baseurl)
loader.setChannel(self)
self._loaders.append(loader)
elif (item.getStatus() == SUCCEEDED and
flitem.getStatus() == FAILED and
fetcher.getCaching() is ALWAYS):
iface.warning(_("You must fetch channel information to "
"acquire needed filelists."))
return False
elif fetcher.getCaching() is NEVER:
lines = [_("Failed acquiring information for '%s':") % self,
u"%s: %s" % (item.getURL(), item.getFailedReason())]
raise Error, "\n".join(lines)
else:
return False
self._digest = digest
return True
def create(alias, data):
return RPMMetaDataChannel(data["baseurl"],
data["type"],
alias,
data["name"],
data["manual"],
data["removable"],
data["priority"])
# vim:ts=4:sw=4:et
|
gpl-2.0
| -5,483,863,477,960,673,000
| 38.594203
| 80
| 0.554539
| false
| 4.248834
| false
| false
| false
|
DTU-ELMA/teaching-games
|
pay_as_bid/python/init.py
|
1
|
8764
|
import random, csv
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from itertools import chain,cycle,islice
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
pending = len(iterables)
nexts = cycle(iter(it).next for it in iterables)
while pending:
try:
for next in nexts:
yield next()
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending))
def steppify(x,y):
sx = roundrobin(chain([0],x),x)
sy = roundrobin(y,chain(y,[y[-1]]))
return list(sx), list(sy)
class Market:
def __init__(self,bidfile = '../php/bids.txt'):
self.players = {}
self._playerlist = set()
self.bidfile = bidfile
def update(self):
self.load_latest_bids()
self.plot()
def load_latest_bids(self):
for ID,name,bid in self.readfile():
if ID in self._playerlist:
self.players[ID].setbid(float(bid))
self.schedule_production()
price = self.get_current_pay_as_bid_price()
for p in self.players.itervalues():
p.push_bid_and_profit(price)
self.papricelist.append(price)
self.write_stats_file()
def load_first_bids(self):
for ID,name,bid in self.readfile():
self.players[ID] = Player(ID,name)
self.players[ID].setbid(float(bid))
self._playerlist.add(ID)
self.nplayers = len(self._playerlist)
# Set demand so there is a 10% chance of using the large power plant
self.demand = 10*self.nplayers - 5*1.28*0.8165*np.sqrt(self.nplayers)
self.schedule_production()
curprice = self.get_current_pay_as_bid_price()
for p in self.players.itervalues():
p.push_bid_and_profit(curprice)
self.papricelist = [curprice]
self.write_stats_file()
def readfile(self):
return csv.reader(open(self.bidfile))
def schedule_production(self):
x = 0.0
pids = {pid:self.players[pid].curbid for pid in self._playerlist}
pids = sorted(pids.keys(), key=pids.get)
for pid in pids:
x+= self.players[pid].curprod
if x < self.demand:
self.players[pid].schedprod = self.players[pid].curprod
else:
self.players[pid].schedprod = max(0.0,self.demand + self.players[pid].curprod - x)
def get_current_pay_as_bid_price(self):
x = self.demand
pids = {pid:self.players[pid].curbid for pid in self._playerlist}
pids = sorted(pids.keys(), key=pids.get)
for pid in pids:
x -= self.players[pid].curprod
if x < 0:
return self.players[pid].curbid
return 100.00
def get_current_mc_price(self):
x = self.demand
pids = {pid:self.players[pid].curbid for pid in self._playerlist}
pids = sorted(pids.keys(), key=pids.get)
for pid in pids:
x-= self.players[pid].curprod
if x < 0:
return self.players[pid].mc
return 100.00
def plot(self):
plt.ion()
plt.figure(1, figsize=(8,5), dpi=100)
plt.subplot(121)
plt.cla()
self.plot_bid_curve()
plt.subplot(122)
plt.cla()
self.plot_profits()
plt.tight_layout()
plt.savefig('../pic/out.png')
plt.figure(2, figsize=(8,5), dpi=100)
plt.subplot(121)
plt.cla()
self.plot_bid_curve()
plt.subplot(122)
plt.cla()
self.plot_profits()
plt.tight_layout()
def plot_bid_curve(self):
pids = {pid:self.players[pid].curbid for pid in self._playerlist}
pids = sorted(pids.keys(), key=pids.get)
ymc = [self.players[pid].mc for pid in pids]+[100]
ybid = [self.players[pid].curbid for pid in pids]+[100]
x = np.cumsum([self.players[pid].curprod for pid in pids]+[self.demand])
sx,symc = steppify(x,ymc)
sx,sybid = steppify(x,ybid)
tmp = [(xx,yy,zz) for xx,yy,zz in zip(sx,sybid,symc) if xx < self.demand]
tmp.append((self.demand,tmp[-1][1],tmp[-1][2]))
sxless,sybidless,symcless = zip(*tmp)
plt.fill_between(sxless,symcless,sybidless,color = 'g',alpha=0.3)
plt.plot(sx,symc,lw=3,c='k')
plt.plot(sx,sybid,lw=3,c='k')
plt.axvline(self.demand,lw=3,ls='--',c='k')
plt.axhline(sybidless[-1],lw=3,ls='..',c='k')
plt.title('Final price: {:.02f}'.format(sybidless[-1]))
plt.xlabel('Amount [MWh]')
plt.ylabel('Price [$/MWh]')
def plot_mc_curve(self):
pids = {pid:self.players[pid].mc for pid in self._playerlist}
pids = sorted(pids.keys(), key=pids.get)
ymc = [self.players[pid].mc for pid in pids]+[100]
ybid = [self.players[pid].curbid for pid in pids]+[100]
x = np.cumsum([self.players[pid].curprod for pid in pids]+[self.demand])
sx,symc = steppify(x,ymc)
sx,sybid = steppify(x,ybid)
tmp = [(xx,yy,zz) for xx,yy,zz in zip(sx,sybid,symc) if xx < self.demand]
tmp.append((self.demand,tmp[-1][1],tmp[-1][2]))
sxless,sybidless,symcless = zip(*tmp)
plt.fill_between(sxless,symcless,symcless[-1],color = 'g',alpha=0.3)
plt.plot(sx,symc,lw=3,c='k')
plt.plot(sx,sybid,lw=3,c='k')
plt.axvline(self.demand,lw=3,ls='--',c='k')
plt.axhline(sybidless[-1],lw=3,ls=':',c='k')
plt.title('Final price: {:.02f}'.format(symcless[-1]))
def plot_profits(self):
bestprofit = -100.0
for p in self.players.itervalues():
if sum(p.pabprofitlist) > bestprofit:
bestprofit = sum(p.pabprofitlist)
bestname = p.name
plt.plot(np.cumsum(p.pabprofitlist),c='k',marker='.')
# plt.plot(np.cumsum(p.mcprofitlist),c='r',marker='.')
plt.title('Current leader: {0} \n with a profit of {1:.01f}'.format(bestname, bestprofit))
plt.xlabel('Round number')
plt.ylabel('Profit [$]')
def write_stats_file(self):
outArr = []
for pid,p in self.players.iteritems():
outArr.append(map(float,[p.ID,p.curbid,p.curprod,p.schedprod,sum(p.pabprofitlist)]))
np.savetxt('../php/stats.txt',outArr,fmt='%d,%.02f,%.02f,%.02f,%.02f')
def get_pandas_dataframe(self):
df = pd.DataFrame()
for pid, p in self.players.iteritems():
df = df.append(pd.DataFrame({
"player_ID": [pid for _ in p.bidlist],
"round": [i for i,_ in enumerate(p.bidlist)],
"pab_profit": [v for v in p.pabprofitlist],
"up_profit": [v for v in p.mcprofitlist],
"scheduled": [v for v in p.prodlist],
"potential": [v for v in p.potprodlist],
"price": [v for v in p.pricelist]
}), ignore_index=True)
df['cumulative_profit'] = (df.pab_profit - df.up_profit)
df['cumulative_profit'] = df.groupby('player_ID')['cumulative_profit'].cumsum()
self.df = df
return df
def plot_pandas(self):
try:
df = self.df
except AttributeError:
df = self.get_pandas_dataframe()
plt.figure(3, figsize=(8,5), dpi=100)
ax3 = plt.axes()
df.groupby('player_ID').sum().plot(kind='scatter', x='potential', y='pab_profit', ax=ax3)
plt.ylabel('Pay-as-bid profit')
plt.figure(4, figsize=(8,5), dpi=100)
ax4 = plt.axes()
gb = df.groupby('player_ID')
for id, g in gb:
g.plot(x='round', y='cumulative_profit', marker='.', ax=ax4)
plt.xlabel('Round')
plt.ylabel('PAB Profit - UP Profit')
class Player:
def __init__(self, ID = -1,name=''):
self.ID = ID
self.name = name
# self.mc = round((int(ID) * 10.0)/30000 + 5,2)
self.mc = 0
self.bidlist = []
self.pabprofitlist = []
self.mcprofitlist = []
self.prodlist = []
self.potprodlist = []
self.pricelist = []
self.totalprod = 0
def setbid(self, bid):
self.curbid = bid
self.curprod = random.randint(1,3)*5
self.schedprod = 0.0
def push_bid_and_profit(self,price = 0.0):
self.bidlist.append(self.curbid)
self.pabprofitlist.append((self.curbid-self.mc)*self.schedprod)
self.mcprofitlist.append((price-self.mc)*self.schedprod)
self.totalprod += self.schedprod
self.prodlist.append(self.schedprod)
self.potprodlist.append(self.curprod)
self.pricelist.append(price)
|
mit
| -494,952,331,219,167,040
| 36.775862
| 98
| 0.5623
| false
| 3.191551
| false
| false
| false
|
chiamingyen/PythonCAD_py3
|
Interface/Preview/arc.py
|
1
|
3347
|
#!/usr/bin/env python
#
# Copyright (c) 2010 Matteo Boscolo
#
# This file is part of PythonCAD.
#
# PythonCAD 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.
#
# PythonCAD 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 Licensesegmentcmd.py
# along with PythonCAD; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# SegmentPreview object
#
import math
from PyQt5 import QtCore
from Interface.Preview.base import PreviewBase
from Interface.Entity.arc import Arc
from Kernel.entity import Point
from Kernel.exception import *
from Kernel.GeoEntity.point import Point as GeoPoint
from Kernel.GeoUtil.geolib import Vector
#TODO+: find a good way to retrive the geometry staff from a item in Interface.Entity.arc ..
#extend it for all the preview entity
class PreviewArc(PreviewBase):
def __init__(self,command):
super(PreviewArc, self).__init__(command)
@property
def canDraw(self):
if self.value[0]!=None:
self.xc = self.value[0].x()
self.yc = self.value[0].y()
self.h = self.value[1]*2
self.xc=self.xc-(self.h/2.0)
self.yc=self.yc-(self.h/2.0)
self.startAngle = (self.value[2]*180/math.pi)*16
self.spanAngle = (self.value[3]*180/math.pi)*16
return True
return False
def drawGeometry(self, painter,option,widget):
"""
Overloading of the paint method
"""
if self.canDraw:
Arc.__dict__['drawGeometry'](self, painter,option,widget)
def drawShape(self, painterPath):
"""
overloading of the shape method
"""
if self.canDraw:
Arc.__dict__['drawShape'](self, painterPath)
def updatePreview(self, position, distance, kernelCommand):
"""
update the data at the preview item
"""
self.prepareGeometryChange() #qtCommand for update the scene
for i in range(0, len(kernelCommand.value)):
self.value[i]=self.revertToQTObject(kernelCommand.value[i])
# Assing Command Values
index=kernelCommand.valueIndex
try:
raise kernelCommand.exception[index](None)
except(ExcPoint):
self.value[index]=self.revertToQTObject(position)
except(ExcLenght, ExcInt):
if not distance or distance !=None:
self.value[index]=distance
except(ExcAngle):
p1 = kernelCommand.value[0]
p2 = GeoPoint(position.x, position.y)
ang=Vector(p1, p2).absAng
if index==3:
ang=ang-self.value[2]
self.value[index]=ang
except:
print("updatePreview: Exception not managed")
return
|
gpl-2.0
| 1,902,915,272,490,773,000
| 34.606383
| 92
| 0.618166
| false
| 4.003589
| false
| false
| false
|
Honzin/ccs
|
tests/testAdapter/testBtcc/testOrder.py
|
1
|
1854
|
import unittest
import ccs
import time
####################################################################################################################
# BITFINEX #
####################################################################################################################
class Valid(unittest.TestCase):
def setUp(self):
self.stock = ccs.constants.BTCC
self.base = ccs.constants.BTC
self.quote = ccs.constants.CNY
self.orderbook = ccs.orderbook(self.stock, self.base, self.quote)
self.ordersA = self.orderbook.asks()
self.orderA = self.ordersA[0]
self.ordersB = self.orderbook.bids()
self.orderB = self.ordersB[0]
self.m = ccs.btcc.public.response
# time.sleep(3)
def testPrice(self):
self.assertIsInstance(self.orderA.price(), float)
self.assertIsInstance(self.orderB.price(), float)
def testAmount(self):
self.assertIsInstance(self.orderA.amount(), float)
self.assertIsInstance(self.orderB.amount(), float)
def testStock(self):
self.assertEqual(self.orderA.stock(), self.stock)
self.assertEqual(self.orderB.stock(), self.stock)
def testMethod(self):
self.assertEqual(self.orderA.method(), ccs.constants.ORDER)
self.assertEqual(self.orderB.method(), ccs.constants.ORDER)
def testUsymbol(self):
self.assertEqual(self.orderA.usymbol(), self.base + ":" + self.quote)
self.assertEqual(self.orderB.usymbol(), self.base + ":" + self.quote)
def testOsymbol(self):
pass
def testData(self):
pass
def testRaw(self):
pass
def testStr(self):
pass
if __name__ == '__main__':
unittest.main()
|
agpl-3.0
| 2,400,904,288,709,812,700
| 27.96875
| 116
| 0.515102
| false
| 4.185102
| true
| false
| false
|
lagner/academ-weather
|
bootstrap/utils.py
|
1
|
2005
|
import os
import subprocess
import logging as log
from shutil import copy2
from contextlib import contextmanager
@contextmanager
def pushd(newDir):
previousDir = os.getcwd()
os.chdir(newDir)
yield
os.chdir(previousDir)
def static_vars(**kwargs):
def decorate(func):
for k in kwargs:
setattr(func, k, kwargs[k])
return func
return decorate
def run(cmd, check_code=False):
shell = isinstance(cmd, str)
try:
log.debug('run: ' + (cmd if shell else ' '.join(cmd)))
output = subprocess.check_output(
cmd,
shell=shell,
universal_newlines=True
)
return 0, output
except subprocess.CalledProcessError as ex:
log.debug("called proces exception: " + str(ex))
if check_code:
raise
else:
return ex.returncode, ex.output
def sync_file(source, target):
if os.path.exists(target):
s = os.path.getmtime(source)
t = os.path.getmtime(target)
if t >= s:
return
target_dir = os.path.dirname(target)
if not os.path.exists(target_dir):
os.makedirs(target_dir)
copy2(source, target)
def sync_dir(source, target, remove_extra=False):
join = os.path.join
root, dirs, files = next(os.walk(source))
for d in dirs:
sync_dir(join(source, d), join(target, d), remove_extra=remove_extra)
for f in files:
sync_file(join(source, f), join(target, f))
if remove_extra:
*_, tfiles = next(os.walk(target))
for extra in (set(tfiles) - set(files)):
os.remove(extra)
# FIXME: remove extra dirs
def fs_walk(path):
for root, dirs, files in os.walk(path):
for filename in files:
yield os.path.join(root, filename)
def filenames_filter(files, extensions):
for filename in files:
basename, ext = os.path.splitext(filename)
if ext in extensions:
yield filename
|
mit
| 6,562,177,993,364,735,000
| 23.156627
| 77
| 0.6
| false
| 3.754682
| false
| false
| false
|
dimtion/jml
|
outputFiles/statistics/archives/ourIA/closest.py/0.7/3/player1.py
|
1
|
11241
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
####################################################################################################################################################################################################################################
######################################################################################################## PRE-DEFINED IMPORTS #######################################################################################################
####################################################################################################################################################################################################################################
# Imports that are necessary for the program architecture to work properly
# Do not edit this code
import ast
import sys
import os
####################################################################################################################################################################################################################################
####################################################################################################### PRE-DEFINED CONSTANTS ######################################################################################################
####################################################################################################################################################################################################################################
# Possible characters to send to the maze application
# Any other will be ignored
# Do not edit this code
UP = 'U'
DOWN = 'D'
LEFT = 'L'
RIGHT = 'R'
####################################################################################################################################################################################################################################
# Name of your team
# It will be displayed in the maze
# You have to edit this code
TEAM_NAME = "closest"
####################################################################################################################################################################################################################################
########################################################################################################## YOUR VARIABLES ##########################################################################################################
####################################################################################################################################################################################################################################
# Stores all the moves in a list to restitute them one by one
allMoves = [UP, RIGHT, UP, RIGHT, UP, RIGHT, RIGHT, RIGHT, RIGHT, RIGHT, UP, UP, UP, UP, UP, RIGHT]
####################################################################################################################################################################################################################################
####################################################################################################### PRE-DEFINED FUNCTIONS ######################################################################################################
####################################################################################################################################################################################################################################
# Writes a message to the shell
# Use for debugging your program
# Channels stdout and stdin are captured to enable communication with the maze
# Do not edit this code
def debug (text) :
# Writes to the stderr channel
sys.stderr.write(str(text) + "\n")
sys.stderr.flush()
####################################################################################################################################################################################################################################
# Reads one line of information sent by the maze application
# This function is blocking, and will wait for a line to terminate
# The received information is automatically converted to the correct type
# Do not edit this code
def readFromPipe () :
# Reads from the stdin channel and returns the structure associated to the string
try :
text = sys.stdin.readline()
return ast.literal_eval(text.strip())
except :
os._exit(-1)
####################################################################################################################################################################################################################################
# Sends the text to the maze application
# Do not edit this code
def writeToPipe (text) :
# Writes to the stdout channel
sys.stdout.write(text)
sys.stdout.flush()
####################################################################################################################################################################################################################################
# Reads the initial maze information
# The function processes the text and returns the associated variables
# The dimensions of the maze are positive integers
# Maze map is a dictionary associating to a location its adjacent locations and the associated weights
# The preparation time gives the time during which 'initializationCode' can make computations before the game starts
# The turn time gives the time during which 'determineNextMove' can make computations before returning a decision
# Player locations are tuples (line, column)
# Coins are given as a list of locations where they appear
# A boolean indicates if the game is over
# Do not edit this code
def processInitialInformation () :
# We read from the pipe
data = readFromPipe()
return (data['mazeWidth'], data['mazeHeight'], data['mazeMap'], data['preparationTime'], data['turnTime'], data['playerLocation'], data['opponentLocation'], data['coins'], data['gameIsOver'])
####################################################################################################################################################################################################################################
# Reads the information after each player moved
# The maze map and allowed times are no longer provided since they do not change
# Do not edit this code
def processNextInformation () :
# We read from the pipe
data = readFromPipe()
return (data['playerLocation'], data['opponentLocation'], data['coins'], data['gameIsOver'])
####################################################################################################################################################################################################################################
########################################################################################################## YOUR FUNCTIONS ##########################################################################################################
####################################################################################################################################################################################################################################
# This is where you should write your code to do things during the initialization delay
# This function should not return anything, but should be used for a short preprocessing
# This function takes as parameters the dimensions and map of the maze, the time it is allowed for computing, the players locations in the maze and the remaining coins locations
# Make sure to have a safety margin for the time to include processing times (communication etc.)
def initializationCode (mazeWidth, mazeHeight, mazeMap, timeAllowed, playerLocation, opponentLocation, coins) :
# Nothing to do
pass
####################################################################################################################################################################################################################################
# This is where you should write your code to determine the next direction
# This function should return one of the directions defined in the CONSTANTS section
# This function takes as parameters the dimensions and map of the maze, the time it is allowed for computing, the players locations in the maze and the remaining coins locations
# Make sure to have a safety margin for the time to include processing times (communication etc.)
def determineNextMove (mazeWidth, mazeHeight, mazeMap, timeAllowed, playerLocation, opponentLocation, coins) :
# We return the next move as described by the list
global allMoves
nextMove = allMoves[0]
allMoves = allMoves[1:]
return nextMove
####################################################################################################################################################################################################################################
############################################################################################################# MAIN LOOP ############################################################################################################
####################################################################################################################################################################################################################################
# This is the entry point when executing this file
# We first send the name of the team to the maze
# The first message we receive from the maze includes its dimensions and map, the times allowed to the various steps, and the players and coins locations
# Then, at every loop iteration, we get the maze status and determine a move
# Do not edit this code
if __name__ == "__main__" :
# We send the team name
writeToPipe(TEAM_NAME + "\n")
# We process the initial information and have a delay to compute things using it
(mazeWidth, mazeHeight, mazeMap, preparationTime, turnTime, playerLocation, opponentLocation, coins, gameIsOver) = processInitialInformation()
initializationCode(mazeWidth, mazeHeight, mazeMap, preparationTime, playerLocation, opponentLocation, coins)
# We decide how to move and wait for the next step
while not gameIsOver :
(playerLocation, opponentLocation, coins, gameIsOver) = processNextInformation()
if gameIsOver :
break
nextMove = determineNextMove(mazeWidth, mazeHeight, mazeMap, turnTime, playerLocation, opponentLocation, coins)
writeToPipe(nextMove)
####################################################################################################################################################################################################################################
####################################################################################################################################################################################################################################
|
mit
| -5,020,732,711,863,126,000
| 63.982659
| 228
| 0.356641
| false
| 7.419802
| false
| false
| false
|
invinst/ResponseBot
|
responsebot/responsebot_client.py
|
1
|
12103
|
from __future__ import absolute_import
from decorator import decorate
from tweepy.error import TweepError, RateLimitError
from responsebot.common.constants import TWITTER_PAGE_DOES_NOT_EXISTS_ERROR, TWITTER_TWEET_NOT_FOUND_ERROR, \
TWITTER_USER_NOT_FOUND_ERROR, TWITTER_DELETE_OTHER_USER_TWEET, TWITTER_ACCOUNT_SUSPENDED_ERROR,\
TWITTER_USER_IS_NOT_LIST_MEMBER_SUBSCRIBER, TWITTER_AUTOMATED_REQUEST_ERROR, TWITTER_OVER_CAPACITY_ERROR,\
TWITTER_DAILY_STATUS_UPDATE_LIMIT_ERROR, TWITTER_CHARACTER_LIMIT_ERROR_1, TWITTER_CHARACTER_LIMIT_ERROR_2, \
TWITTER_STATUS_DUPLICATE_ERROR
from responsebot.common.exceptions import APIQuotaError, AutomatedRequestError, OverCapacityError,\
DailyStatusUpdateError, CharacterLimitError, StatusDuplicateError
from responsebot.models import Tweet, User, List
from responsebot.utils.tweepy import tweepy_list_to_json
def api_error_handle(func):
def func_wrapper(f, *args, **kwargs):
try:
return f(*args, **kwargs)
except RateLimitError as e:
raise APIQuotaError(str(e))
except TweepError as e:
if e.api_code == TWITTER_AUTOMATED_REQUEST_ERROR:
raise AutomatedRequestError
elif e.api_code == TWITTER_OVER_CAPACITY_ERROR:
raise OverCapacityError
elif e.api_code in [TWITTER_CHARACTER_LIMIT_ERROR_1, TWITTER_CHARACTER_LIMIT_ERROR_2]:
raise CharacterLimitError
elif e.api_code == TWITTER_DAILY_STATUS_UPDATE_LIMIT_ERROR:
raise DailyStatusUpdateError
elif e.api_code == TWITTER_STATUS_DUPLICATE_ERROR:
raise StatusDuplicateError
else:
raise
return decorate(func, func_wrapper)
class ResponseBotClient(object):
"""
Wrapper for all Twitter API clients.
"""
def __init__(self, client, config):
self._client = client
self._current_user = None
self.config = config
@property
def tweepy_api(self):
"""
Get the actual client object.
:return: the actual client object
"""
return self._client
def get_current_user(self):
if self._current_user is None:
self._current_user = User(self._client.me()._json)
return self._current_user
@api_error_handle
def tweet(self, text, in_reply_to=None, filename=None, file=None):
"""
Post a new tweet.
:param text: the text to post
:param in_reply_to: The ID of the tweet to reply to
:param filename: If `file` param is not provided, read file from this path
:param file: A file object, which will be used instead of opening `filename`. `filename` is still required, for
MIME type detection and to use as a form field in the POST data
:return: Tweet object
"""
if filename is None:
return Tweet(self._client.update_status(status=text, in_reply_to_status_id=in_reply_to)._json)
else:
return Tweet(self._client.update_with_media(filename=filename, file=file,
status=text, in_reply_to_status_id=in_reply_to)._json)
def retweet(self, id):
"""
Retweet a tweet.
:param id: ID of the tweet in question
:return: True if success, False otherwise
"""
try:
self._client.retweet(id=id)
return True
except TweepError as e:
if e.api_code == TWITTER_PAGE_DOES_NOT_EXISTS_ERROR:
return False
raise
def get_tweet(self, id):
"""
Get an existing tweet.
:param id: ID of the tweet in question
:return: Tweet object. None if not found
"""
try:
return Tweet(self._client.get_status(id=id)._json)
except TweepError as e:
if e.api_code == TWITTER_TWEET_NOT_FOUND_ERROR:
return None
raise
def get_user(self, id):
"""
Get a user's info.
:param id: ID of the user in question
:return: User object. None if not found
"""
try:
return User(self._client.get_user(user_id=id)._json)
except TweepError as e:
if e.api_code == TWITTER_USER_NOT_FOUND_ERROR:
return None
raise
def remove_tweet(self, id):
"""
Delete a tweet.
:param id: ID of the tweet in question
:return: True if success, False otherwise
"""
try:
self._client.destroy_status(id=id)
return True
except TweepError as e:
if e.api_code in [TWITTER_PAGE_DOES_NOT_EXISTS_ERROR, TWITTER_DELETE_OTHER_USER_TWEET]:
return False
raise
def follow(self, user_id, notify=False):
"""
Follow a user.
:param user_id: ID of the user in question
:param notify: whether to notify the user about the following
:return: user that are followed
"""
try:
return User(self._client.create_friendship(user_id=user_id, follow=notify)._json)
except TweepError as e:
if e.api_code in [TWITTER_ACCOUNT_SUSPENDED_ERROR]:
return self.get_user(user_id)
raise
def unfollow(self, user_id):
"""
Follow a user.
:param user_id: ID of the user in question
:return: The user that were unfollowed
"""
return User(self._client.destroy_friendship(user_id=user_id)._json)
###################################################################################
# Lists
###################################################################################
@api_error_handle
def create_list(self, name, mode='public', description=None):
"""
Create a list
:param name: Name of the new list
:param mode: :code:`'public'` (default) or :code:`'private'`
:param description: Description of the new list
:return: The new list object
:rtype: :class:`~responsebot.models.List`
"""
return List(tweepy_list_to_json(self._client.create_list(name=name, mode=mode, description=description)))
@api_error_handle
def destroy_list(self, list_id):
"""
Destroy a list
:param list_id: list ID number
:return: The destroyed list object
:rtype: :class:`~responsebot.models.List`
"""
return List(tweepy_list_to_json(self._client.destroy_list(list_id=list_id)))
@api_error_handle
def update_list(self, list_id, name=None, mode=None, description=None):
"""
Update a list
:param list_id: list ID number
:param name: New name for the list
:param mode: :code:`'public'` (default) or :code:`'private'`
:param description: New description of the list
:return: The updated list object
:rtype: :class:`~responsebot.models.List`
"""
return List(tweepy_list_to_json(
self._client.update_list(list_id=list_id, name=name, mode=mode, description=description))
)
@api_error_handle
def lists(self):
"""
List user's lists
:return: list of :class:`~responsebot.models.List` objects
"""
return [List(tweepy_list_to_json(list)) for list in self._client.lists_all()]
@api_error_handle
def lists_memberships(self):
"""
List lists which user was added
:return: list of :class:`~responsebot.models.List` objects
"""
return [List(tweepy_list_to_json(list)) for list in self._client.lists_memberships()]
@api_error_handle
def lists_subscriptions(self):
"""
List lists which user followed
:return: list of :class:`~responsebot.models.List` objects
"""
return [List(tweepy_list_to_json(list)) for list in self._client.lists_subscriptions()]
@api_error_handle
def list_timeline(self, list_id, since_id=None, max_id=None, count=20):
"""
List the tweets of specified list.
:param list_id: list ID number
:param since_id: results will have ID greater than specified ID (more recent than)
:param max_id: results will have ID less than specified ID (older than)
:param count: number of results per page
:return: list of :class:`~responsebot.models.Tweet` objects
"""
statuses = self._client.list_timeline(list_id=list_id, since_id=since_id, max_id=max_id, count=count)
return [Tweet(tweet._json) for tweet in statuses]
@api_error_handle
def get_list(self, list_id):
"""
Get info of specified list
:param list_id: list ID number
:return: :class:`~responsebot.models.List` object
"""
return List(tweepy_list_to_json(self._client.get_list(list_id=list_id)))
@api_error_handle
def add_list_member(self, list_id, user_id):
"""
Add a user to list
:param list_id: list ID number
:param user_id: user ID number
:return: :class:`~responsebot.models.List` object
"""
return List(tweepy_list_to_json(self._client.add_list_member(list_id=list_id, user_id=user_id)))
@api_error_handle
def remove_list_member(self, list_id, user_id):
"""
Remove a user from a list
:param list_id: list ID number
:param user_id: user ID number
:return: :class:`~responsebot.models.List` object
"""
return List(tweepy_list_to_json(self._client.remove_list_member(list_id=list_id, user_id=user_id)))
@api_error_handle
def list_members(self, list_id):
"""
List users in a list
:param list_id: list ID number
:return: list of :class:`~responsebot.models.User` objects
"""
return [User(user._json) for user in self._client.list_members(list_id=list_id)]
@api_error_handle
def is_list_member(self, list_id, user_id):
"""
Check if a user is member of a list
:param list_id: list ID number
:param user_id: user ID number
:return: :code:`True` if user is member of list, :code:`False` otherwise
"""
try:
return bool(self._client.show_list_member(list_id=list_id, user_id=user_id))
except TweepError as e:
if e.api_code == TWITTER_USER_IS_NOT_LIST_MEMBER_SUBSCRIBER:
return False
raise
@api_error_handle
def subscribe_list(self, list_id):
"""
Subscribe to a list
:param list_id: list ID number
:return: :class:`~responsebot.models.List` object
"""
return List(tweepy_list_to_json(self._client.subscribe_list(list_id=list_id)))
@api_error_handle
def unsubscribe_list(self, list_id):
"""
Unsubscribe to a list
:param list_id: list ID number
:return: :class:`~responsebot.models.List` object
"""
return List(tweepy_list_to_json(self._client.unsubscribe_list(list_id=list_id)))
@api_error_handle
def list_subscribers(self, list_id):
"""
List subscribers of a list
:param list_id: list ID number
:return: :class:`~responsebot.models.User` object
"""
return [User(user._json) for user in self._client.list_subscribers(list_id=list_id)]
@api_error_handle
def is_subscribed_list(self, list_id, user_id):
"""
Check if user is a subscribed of specified list
:param list_id: list ID number
:param user_id: user ID number
:return: :code:`True` if user is subscribed of list, :code:`False` otherwise
"""
try:
return bool(self._client.show_list_subscriber(list_id=list_id, user_id=user_id))
except TweepError as e:
if e.api_code == TWITTER_USER_IS_NOT_LIST_MEMBER_SUBSCRIBER:
return False
raise
|
apache-2.0
| -2,195,622,971,623,110,000
| 33.58
| 119
| 0.592002
| false
| 3.761032
| false
| false
| false
|
praekeltfoundation/certbot
|
marathon_acme/server.py
|
1
|
3528
|
import json
from klein import Klein
from twisted.internet.endpoints import serverFromString
from twisted.logger import Logger
from twisted.web.http import NOT_IMPLEMENTED, OK, SERVICE_UNAVAILABLE
from twisted.web.server import Site
def write_request_json(request, json_obj):
request.setHeader('Content-Type', 'application/json')
request.write(json.dumps(json_obj).encode('utf-8'))
class MarathonAcmeServer(object):
app = Klein()
log = Logger()
def __init__(self, responder_resource):
"""
:param responder_resource:
An ``IResponse`` used to respond to ACME HTTP challenge validation
requests.
"""
self.responder_resource = responder_resource
self.health_handler = None
def listen(self, reactor, endpoint_description):
"""
Run the server, i.e. start listening for requests on the given host and
port.
:param reactor: The ``IReactorTCP`` to use.
:param endpoint_description:
The Twisted description for the endpoint to listen on.
:return:
A deferred that returns an object that provides ``IListeningPort``.
"""
endpoint = serverFromString(reactor, endpoint_description)
return endpoint.listen(Site(self.app.resource()))
@app.route('/.well-known/acme-challenge/', branch=True, methods=['GET'])
def acme_challenge(self, request):
"""
Respond to ACME challenge validation requests on
``/.well-known/acme-challenge/`` using the ACME responder resource.
"""
return self.responder_resource
@app.route('/.well-known/acme-challenge/ping', methods=['GET'])
def acme_challenge_ping(self, request):
"""
Respond to requests on ``/.well-known/acme-challenge/ping`` to debug
path routing issues.
"""
request.setResponseCode(OK)
write_request_json(request, {'message': 'pong'})
def set_health_handler(self, health_handler):
"""
Set the handler for the health endpoint.
:param health_handler:
The handler for health status requests. This must be a callable
that returns a Health object.
"""
self.health_handler = health_handler
@app.route('/health', methods=['GET'])
def health(self, request):
""" Listens to incoming health checks from Marathon on ``/health``. """
if self.health_handler is None:
return self._no_health_handler(request)
health = self.health_handler()
response_code = OK if health.healthy else SERVICE_UNAVAILABLE
request.setResponseCode(response_code)
write_request_json(request, health.json_message)
def _no_health_handler(self, request):
self.log.warn('Request to /health made but no handler is set')
request.setResponseCode(NOT_IMPLEMENTED)
write_request_json(request, {
'error': 'Cannot determine service health: no handler set'
})
class Health(object):
def __init__(self, healthy, json_message={}):
"""
Health objects store the current health status of the service.
:param bool healthy:
The service is either healthy (True) or unhealthy (False).
:param json_message:
An object that can be serialized as JSON that will be sent as a
message when the health status is requested.
"""
self.healthy = healthy
self.json_message = json_message
|
mit
| 7,013,790,470,706,764,000
| 33.588235
| 79
| 0.637755
| false
| 4.286756
| false
| false
| false
|
Udzu/pudzu
|
dataviz/markovtext.py
|
1
|
6426
|
import pickle
import seaborn as sns
import string
from pudzu.sandbox.markov import *
from pudzu.sandbox.bamboo import *
from pudzu.charts import *
from math import log
CORPUS = "wikienglish"
TITLE = "Letter and next-letter frequencies in English"
SUBTITLE = "measured across 1 million sentences from Wikipedia"
ENCODING = "utf-8"
LETTERS = string.ascii_lowercase + ' '
# Markov generators
def load_generator(n):
try:
logger.info("Loading ../corpora/{}_{}.p".format(CORPUS, n))
with open("../corpora/{}_{}.p".format(CORPUS, n), "rb") as f:
return pickle.load(f)
except:
logger.info("Training {} {}-grams".format(CORPUS, n))
markov = MarkovGenerator(n)
for f in tqdm.tqdm(CORPUS.split("-")):
markov.train_file("../corpora/"+f, encoding=ENCODING, normalise=partial(latin_normalise, letters=LETTERS))
logger.info("Saving to ../corpora/{}_{}.p".format(CORPUS, n))
with open("../corpora/{}_{}.p".format(CORPUS, n), "wb") as f:
pickle.dump(markov, f, pickle.HIGHEST_PROTOCOL)
return markov
g1 = load_generator(1)
g2 = load_generator(2)
# Grid chart
SCALE = 2
BOX_SIZE = 40 * SCALE
BIG_KEY = round(BOX_SIZE*1.5)
SMALL_KEY = round(BIG_KEY/2)
FONT_SIZE = round(18 * SCALE)
MAX_WIDTH = round(200 * SCALE)
MAX_WIDTH2 = round(280 * SCALE)
logger.info("Generating grid chart")
index = sorted([(x, g1.prob_dict[(x,)] / sum(g1.prob_dict.values())) for x in LETTERS if (x,) in g1.prob_dict], key=lambda p: p[1], reverse=True)
array = [[(y,n / sum(g1.markov_dict[(x,)].values())) for y,n in g1.markov_dict[(x,)].most_common()] for x,_ in index]
data = pd.DataFrame(array, index=index)
pone = tmap(RGBA, sns.color_palette("Reds", 8))
ptwo = tmap(RGBA, sns.color_palette("Blues", 8))
color_index = lambda p: 0 if p == 0 else clip(6 + int(log(p, 10) * 2), 0, 6)
def image_fn(pair, palette, row=None, size=BOX_SIZE):
if pair is None: return None
bg = palette[color_index(pair[1])]
img = Image.new("RGBA", (size,size), bg)
img.place(Image.from_text(pair[0], arial(size//2), "black", bg=bg), copy=False)
if row is not None and pair[0] != " ":
if not isinstance(row, str):
twogram = g2.markov_dict[(index[row][0], pair[0])].most_common()
row, _ = twogram[0][0], twogram[0][1] / sum(n for _,n in twogram)
img.place(Image.from_text(row, arial(round(size/3.5)), "black", bg=bg), align=(1,0), padding=(size//8,size//5), copy=False)
return img
grid = grid_chart(data, lambda p, r: image_fn(p, row=r, palette=ptwo), fg="black", bg="white", padding=round(SCALE), row_label=lambda i: image_fn(data.index[i], palette=pone))
# Main legend
type_boxes = Image.from_array([
[image_fn(('a', 0.01), pone, size=BIG_KEY),
Image.from_text("Letters and spaces sorted by overall frequency. Ignores case and accents.", arial(FONT_SIZE), padding=(BOX_SIZE//4,0), max_width=MAX_WIDTH)],
[image_fn(('n', 0.01), ptwo, row='d', size=BIG_KEY),
Image.from_text("Next letter sorted by frequency. Small letter is the most common third letter following the pair.", arial(FONT_SIZE), padding=(BOX_SIZE//4,0), max_width=MAX_WIDTH)]
], bg="white", xalign=0, padding=(0,BOX_SIZE//20))
type_leg = Image.from_column([Image.from_text("Colour key", arial(FONT_SIZE, bold=True)), type_boxes, Image.from_text("Blank letters indicate spaces.", arial(FONT_SIZE))], bg="white", xalign=0, padding=(0,BOX_SIZE//20))
color_from_index = lambda i: 10 ** ((i - 6) / 2)
color_label = lambda i: "{:.1%} to {:.1%}".format(color_from_index(i-1), color_from_index(i))
freq_boxes = Image.from_array([
[Image.new("RGBA", (SMALL_KEY,SMALL_KEY), "white" if i == 6 else pone[i]),
Image.new("RGBA", (SMALL_KEY,SMALL_KEY), ptwo[i]),
Image.from_text(color_label(i), arial(FONT_SIZE), padding=(BOX_SIZE//4,0))]
for i in reversed(range(0, 7))], bg="white", xalign=0)
freq_leg = Image.from_column([Image.from_text("Letter frequencies", arial(FONT_SIZE, bold=True)), freq_boxes], bg="white", xalign=0, padding=(0,BOX_SIZE//8))
legend_inner = Image.from_column([type_leg, freq_leg], bg="white", xalign=0, padding=BOX_SIZE//8)
legend = legend_inner.pad(SCALE, "black").pad((BOX_SIZE//2,0,BOX_SIZE//4,0), "white")
# Generated words
if CORPUS == "wikienglish":
words = ["bastrabot", "dithely", "foriticent", "gamplato", "calpereek", "amorth", "forliatitive", "asocult", "wasions", "quarm", "felogy", "winferlifterand", "loubing", "uniso", "fourn", "hise", "meembege", "whigand", "prouning", "guncelawits", "nown", "rectere", "abrip", "doesium"]
elif CORPUS == "wikifrench":
words = ["cillesil", "sulskini", "lidhemin", "plumeme", "bachogine", "crout", "taphie", "provicas", "copit", "odzzaccet", "extreiles", "pipiphien", "chetratagne", "outif", "suro", "extellages", "nans", "nutopune", "entote", "sporese", "zhiquis", "edes", "aliet", "randamelle"]
else:
words = [g2.render_word() for i in range(24)]
word_array = Image.from_array([
[Image.from_text(words[2*i], arial(FONT_SIZE, italics=True), fg="black", bg="white"),
Image.from_text(words[2*i+1], arial(FONT_SIZE, italics=True), fg="black", bg="white")] for i in range(len(words)//2)], bg="white", padding=(15,2)).pad(BOX_SIZE//8,"white")
word_title = Image.from_column([Image.from_text("Markov generators", arial(FONT_SIZE, bold=True)),
Image.from_text("The letters distributions in the chart can be used to generate pseudowords such as the ones below. A similar approach, at the word level, is used for online parody generators.", arial(FONT_SIZE),max_width=MAX_WIDTH2)], bg="white", xalign=0, padding=(0,BOX_SIZE//8))
word_box = Image.from_column([word_title, word_array], bg="white", padding=BOX_SIZE//8)
word_box = word_box.pad_to_aspect(legend_inner.width, word_box.height, align=0, bg="white").pad(SCALE, "white").pad((BOX_SIZE//2,0,BOX_SIZE//4,0), "white")
# Chart
chart = Image.from_row([grid, legend], bg="white", yalign=0)
chart = chart.place(word_box, align=1, padding=(0,BOX_SIZE))
title = Image.from_column([Image.from_text(TITLE, arial(BOX_SIZE, bold=True), bg="white"),
Image.from_text(SUBTITLE, arial(round(24 * SCALE), bold=True), bg="white")])
full = Image.from_column([title, chart], bg="white", padding=(0,BOX_SIZE//4))
full.save("output/markovtext_{}.png".format(CORPUS))
|
mit
| 4,370,538,101,888,572,400
| 53.396552
| 287
| 0.644569
| false
| 2.780614
| false
| false
| false
|
brython-dev/brython
|
www/src/Lib/test/test_eof.py
|
2
|
2490
|
"""test script for a few new invalid token catches"""
import sys
from test import support
from test.support import script_helper
import unittest
class EOFTestCase(unittest.TestCase):
def test_EOFC(self):
expect = "EOL while scanning string literal (<string>, line 1)"
try:
eval("""'this is a test\
""")
except SyntaxError as msg:
self.assertEqual(str(msg), expect)
else:
raise support.TestFailed
def test_EOFS(self):
expect = ("EOF while scanning triple-quoted string literal "
"(<string>, line 1)")
try:
eval("""'''this is a test""")
except SyntaxError as msg:
self.assertEqual(str(msg), expect)
else:
raise support.TestFailed
def test_eof_with_line_continuation(self):
expect = "unexpected EOF while parsing (<string>, line 1)"
try:
compile('"\\xhh" \\', '<string>', 'exec', dont_inherit=True)
except SyntaxError as msg:
self.assertEqual(str(msg), expect)
else:
raise support.TestFailed
def test_line_continuation_EOF(self):
"""A continuation at the end of input must be an error; bpo2180."""
expect = 'unexpected EOF while parsing (<string>, line 1)'
with self.assertRaises(SyntaxError) as excinfo:
exec('x = 5\\')
self.assertEqual(str(excinfo.exception), expect)
with self.assertRaises(SyntaxError) as excinfo:
exec('\\')
self.assertEqual(str(excinfo.exception), expect)
@unittest.skipIf(not sys.executable, "sys.executable required")
def test_line_continuation_EOF_from_file_bpo2180(self):
"""Ensure tok_nextc() does not add too many ending newlines."""
with support.temp_dir() as temp_dir:
file_name = script_helper.make_script(temp_dir, 'foo', '\\')
rc, out, err = script_helper.assert_python_failure(file_name)
self.assertIn(b'unexpected EOF while parsing', err)
self.assertIn(b'line 2', err)
self.assertIn(b'\\', err)
file_name = script_helper.make_script(temp_dir, 'foo', 'y = 6\\')
rc, out, err = script_helper.assert_python_failure(file_name)
self.assertIn(b'unexpected EOF while parsing', err)
self.assertIn(b'line 2', err)
self.assertIn(b'y = 6\\', err)
if __name__ == "__main__":
unittest.main()
|
bsd-3-clause
| 7,089,911,229,699,417,000
| 37.307692
| 77
| 0.590763
| false
| 4.08867
| true
| false
| false
|
EmanueleCannizzaro/scons
|
test/Split.py
|
1
|
2076
|
#!/usr/bin/env python
#
# Copyright (c) 2001 - 2016 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "test/Split.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog"
import TestSCons
test = TestSCons.TestSCons()
test.write('SConstruct', """
env = Environment(BBB = 'bbb', CCC = 'ccc')
print Split('aaa')
print Split('aaa $BBB')
print env.Split('bbb $CCC')
print env.Split('$BBB ccc')
print Split(['ddd', 'eee'])
SConscript('SConscript')
""")
test.write('SConscript', """
env = Environment(FFF='fff', JJJ='jjj')
print env.Split('${FFF}.f')
print Split('ggg hhh')
print env.Split(['iii', '$JJJ'])
""")
expect = """\
['aaa']
['aaa', '$BBB']
['bbb', 'ccc']
['bbb', 'ccc']
['ddd', 'eee']
['fff.f']
['ggg', 'hhh']
['iii', 'jjj']
"""
test.run(arguments = ".",
stdout = test.wrap_stdout(read_str = expect,
build_str = "scons: `.' is up to date.\n"))
test.pass_test()
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
|
mit
| 3,093,363,460,903,866,000
| 29.086957
| 87
| 0.69027
| false
| 3.431405
| true
| false
| false
|
adampresley/bottlepy-bootstrap
|
model/DateHelper.py
|
1
|
2135
|
from model.Service import Service
from datetime import tzinfo, timedelta, datetime
from dateutil import tz
class DateHelper(Service):
utc = tz.gettz("UTC")
pyToJsFormatMapping = {
"%m/%d/%Y": "MM/dd/yyyy",
"%d/%m/%Y": "dd/MM/yyyy",
"%Y-%m-%d": "yyyy-MM-dd"
}
def __init__(self, db, timezone = "UTC", dateFormat = "%m/%d/%Y", timeFormat = "%I:%M %p"):
self.db = db
self._timezone = timezone
self._dateFormat = dateFormat
self._timeFormat = timeFormat
def addDays(self, d, numDays = 1, format = "%Y-%m-%d"):
if not self.isDateType(d):
d = datetime.strptime(d, format)
newDate = d + timedelta(days = numDays)
return newDate
def dateFormat(self, d):
return self.utcToTimezone(d, self._timezone).strftime(self._dateFormat)
def dateTimeFormat(self, d):
return self.utcToTimezone(d, self._timezone).strftime("%s %s" % (self._dateFormat, self._timeFormat))
def isDateType(self, d):
result = True
try:
d.today()
except AttributeError as e:
result = False
return result
def localNow(self):
return self.utcToTimezone(datetime.now(self.utc), self._timezone)
def now(self):
return datetime.now(self.utc)
def pyToJsDateFormat(self, pyDateFormat):
return self.pyToJsFormatMapping[pyDateFormat]
def restDateFormat(self, d):
return d.strftime("%Y-%m-%d")
def restDateTime(self, d):
return d.strftime("%Y-%m-%d %H:%M")
def timeFormat(self, d):
return self.utcToTimezone(d, self._timezone).strftime(self._timeFormat)
def utcToTimezone(self, d, timezone):
targetTZ = tz.gettz(timezone)
d = d.replace(tzinfo = self.utc)
return d.astimezone(targetTZ)
def validateDateRange(self, start, end, format = "%Y-%m-%d"):
#
# Basically if the range between start and end is greater than 91
# days kick it back with today's date as default.
#
parsedStart = datetime.strptime(start, format)
parsedEnd = datetime.strptime(end, format)
delta = parsedEnd - parsedStart
newStart = start
newEnd = end
if delta.days > 91:
newStart = self.restDateFormat(self.localNow())
newEnd = self.restDateFormat(self.localNow())
return (newStart, newEnd)
|
mit
| 6,094,790,128,665,935,000
| 24.129412
| 103
| 0.685714
| false
| 2.973538
| false
| false
| false
|
domeav/sonofages-agenda
|
agenda/events.py
|
1
|
2899
|
from agenda.model import Occurrence, Event, Venue, Tag, EventTag
from agenda.forms import EventForm
from flask import render_template, request, redirect, url_for
from flask_security import login_required
from datetime import datetime
from agenda import app
@app.route('/')
@app.route('/events/')
def events():
page = request.args.get('p', 1)
target_date = request.args.get('d', datetime.now())
occurrences = Occurrence.select()\
.where(Occurrence.start >= target_date)\
.paginate(page, 30)
return render_template('agenda.html', occurrences=occurrences)
@app.route('/event/<event_id>')
def event(event_id):
event = Event.get(Event.id == event_id)
return render_template('event.html', event=event)
@app.route('/event/edit/<event_id>')
@app.route('/event/edit/')
def edit_event(event_id=None):
event = None
if event_id:
event = Event.get(Event.id == event_id)
form = EventForm(obj=event)
form.set_venues(Venue.select())
return render_template('event_edit.html', form=form,
tags=Tag.select(),
eventtags={et.tag.id for et in event.eventtags})
@app.route('/event/save/', methods=['POST'])
def save_event():
form = EventForm()
form.set_venues(Venue.select())
if not form.validate_on_submit():
return render_template('event_edit.html', form=form)
if form.id.data:
event = Event.get(Event.id == form.id.data)
else:
event = Event()
event.title = form.title.data
event.contact = form.contact.data
event.description = form.description.data
if not event.creation:
event.creation = datetime.now()
event.set_image(form.pic.data, form.pic.data.filename)
event.save()
for entry in form.occurrences.entries:
if entry.data['id']:
occurrence = Occurrence.get(Occurrence.id == entry.data['id'])
else:
occurrence = Occurrence()
occurrence.start = entry.data['start']
occurrence.end = entry.data['end']
occurrence.event = event
if entry.data['venue_id'] != 0:
occurrence.venue_id = entry.data['venue_id']
else:
occurrence.venue_id = None
occurrence.save()
if entry.data['delete_gig']:
occurrence.delete_instance()
existing_tags = { et.tag_id: et for et in event.eventtags }
for key, value in request.form.items():
if key.startswith('tag-'):
tag_id = int(value)
if tag_id not in existing_tags:
et = EventTag(event=event, tag_id=tag_id)
et.save()
else:
del(existing_tags[tag_id])
for key, value in existing_tags.items():
value.delete_instance()
return redirect(url_for('event', event_id=event.id))
|
mit
| 1,869,846,341,948,956,400
| 34.353659
| 75
| 0.601932
| false
| 3.660354
| false
| false
| false
|
endthestart/tinsparrow
|
tinsparrow/tinsparrow/views.py
|
1
|
1746
|
import os
from django.contrib import messages
from django.contrib.auth import logout as logout_user
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django import http
from django.shortcuts import get_object_or_404
from django.views.generic import TemplateView
from .models import Song
from .forms import LoginForm
def songfile(request, song_id):
song = get_object_or_404(Song, id=song_id)
song_data = open(os.path.join(song.path, song.filename)).read()
return http.HttpResponse(song_data, content_type=song.content_type)
def login(request, template_name='login.html'):
if request.user.is_authenticated():
return redirect('/')
if request.method == "POST":
form = LoginForm(request.POST)
if form.login(request):
messages.success(request, "You have successfully logged in.")
return redirect(request.POST.get('next', '/'))
else:
messages.error(request, "Your username and password do not match.")
else:
form = LoginForm()
return render_to_response(template_name, {'form': form, }, RequestContext(request))
def logout(request):
logout_user(request)
messages.success(request, "You have successfully logged out.")
return redirect('login')
class LibraryView(TemplateView):
template_name = "tinsparrow/library.html"
def get_context_data(self, **kwargs):
context = super(LibraryView, self).get_context_data(**kwargs)
return context
class LayoutView(TemplateView):
template_name = "tinsparrow/layout.html"
def get_context_data(self, **kwargs):
context = super(LayoutView, self).get_context_data(**kwargs)
return context
|
mit
| 6,564,142,620,204,948,000
| 30.178571
| 87
| 0.699885
| false
| 3.932432
| false
| false
| false
|
code-for-india/sahana_shelter_worldbank
|
private/templates/IFRC/config.py
|
1
|
76404
|
# -*- coding: utf-8 -*-
try:
# Python 2.7
from collections import OrderedDict
except:
# Python 2.6
from gluon.contrib.simplejson.ordered_dict import OrderedDict
from datetime import timedelta
from gluon import current
from gluon.storage import Storage
T = current.T
settings = current.deployment_settings
"""
Template settings for IFRC
"""
# =============================================================================
# System Settings
# -----------------------------------------------------------------------------
# Security Policy
settings.security.policy = 8 # Delegations
settings.security.map = True
# Authorization Settings
settings.auth.registration_requires_approval = True
settings.auth.registration_requires_verification = True
settings.auth.registration_requests_organisation = True
settings.auth.registration_organisation_required = True
settings.auth.registration_requests_site = True
settings.auth.registration_link_user_to = {"staff": T("Staff"),
"volunteer": T("Volunteer"),
"member": T("Member")
}
settings.auth.record_approval = True
# @ToDo: Should we fallback to organisation_id if site_id is None?
settings.auth.registration_roles = {"site_id": ["reader",
],
}
# Owner Entity
settings.auth.person_realm_human_resource_site_then_org = True
settings.auth.person_realm_member_org = True
def ifrc_realm_entity(table, row):
"""
Assign a Realm Entity to records
"""
tablename = table._tablename
# Do not apply realms for Master Data
# @ToDo: Restore Realms and add a role/functionality support for Master Data
if tablename in ("hrm_certificate",
"hrm_department",
"hrm_job_title",
"hrm_course",
"hrm_programme",
"member_membership_type",
"vol_award",
):
return None
db = current.db
s3db = current.s3db
# Entity reference fields
EID = "pe_id"
#OID = "organisation_id"
SID = "site_id"
#GID = "group_id"
PID = "person_id"
# Owner Entity Foreign Key
realm_entity_fks = dict(pr_contact = EID,
pr_contact_emergency = EID,
pr_physical_description = EID,
pr_address = EID,
pr_image = EID,
pr_identity = PID,
pr_education = PID,
pr_note = PID,
hrm_human_resource = SID,
inv_recv = SID,
inv_send = SID,
inv_track_item = "track_org_id",
inv_adj_item = "adj_id",
req_req_item = "req_id"
)
# Default Foreign Keys (ordered by priority)
default_fks = ("catalog_id",
"project_id",
"project_location_id"
)
# Link Tables
realm_entity_link_table = dict(
project_task = Storage(tablename = "project_task_project",
link_key = "task_id"
)
)
if tablename in realm_entity_link_table:
# Replace row with the record from the link table
link_table = realm_entity_link_table[tablename]
table = s3db[link_table.tablename]
rows = db(table[link_table.link_key] == row.id).select(table.id,
limitby=(0, 1))
if rows:
# Update not Create
row = rows.first()
# Check if there is a FK to inherit the realm_entity
realm_entity = 0
fk = realm_entity_fks.get(tablename, None)
fks = [fk]
fks.extend(default_fks)
for default_fk in fks:
if default_fk in table.fields:
fk = default_fk
# Inherit realm_entity from parent record
if fk == EID:
ftable = s3db.pr_person
query = (ftable[EID] == row[EID])
else:
ftablename = table[fk].type[10:] # reference tablename
ftable = s3db[ftablename]
query = (table.id == row.id) & \
(table[fk] == ftable.id)
record = db(query).select(ftable.realm_entity,
limitby=(0, 1)).first()
if record:
realm_entity = record.realm_entity
break
#else:
# Continue to loop through the rest of the default_fks
# Fall back to default get_realm_entity function
use_user_organisation = False
# Suppliers & Partners are owned by the user's organisation
if realm_entity == 0 and tablename == "org_organisation":
ott = s3db.org_organisation_type
query = (table.id == row.id) & \
(table.organisation_type_id == ott.id)
row = db(query).select(ott.name,
limitby=(0, 1)
).first()
if row and row.name != "Red Cross / Red Crescent":
use_user_organisation = True
# Groups are owned by the user's organisation
#elif tablename in ("pr_group",):
elif tablename == "pr_group":
use_user_organisation = True
user = current.auth.user
if use_user_organisation and user:
# @ToDo - this might cause issues if the user's org is different from the realm that gave them permissions to create the Org
realm_entity = s3db.pr_get_pe_id("org_organisation",
user.organisation_id)
return realm_entity
settings.auth.realm_entity = ifrc_realm_entity
# -----------------------------------------------------------------------------
# Pre-Populate
settings.base.prepopulate = ("IFRC", "IFRC_Train")
settings.base.system_name = T("Resource Management System")
settings.base.system_name_short = T("RMS")
# -----------------------------------------------------------------------------
# Theme (folder to use for views/layout.html)
settings.base.theme = "IFRC"
settings.base.xtheme = "IFRC/xtheme-ifrc.css"
settings.gis.map_height = 600
settings.gis.map_width = 869
# Display Resources recorded to Admin-Level Locations on the map
# @ToDo: Move into gis_config?
settings.gis.display_L0 = True
# -----------------------------------------------------------------------------
# L10n (Localization) settings
settings.L10n.languages = OrderedDict([
("en-gb", "English"),
("es", "Español"),
("km", "ភាសាខ្មែរ"), # Khmer
("ne", "नेपाली"), # Nepali
("prs", "دری"), # Dari
("ps", "پښتو"), # Pashto
("vi", "Tiếng Việt"), # Vietnamese
("zh-cn", "中文 (简体)"),
])
# Default Language
settings.L10n.default_language = "en-gb"
# Default timezone for users
settings.L10n.utc_offset = "UTC +0700"
# Number formats (defaults to ISO 31-0)
# Decimal separator for numbers (defaults to ,)
settings.L10n.decimal_separator = "."
# Thousands separator for numbers (defaults to space)
settings.L10n.thousands_separator = ","
# Unsortable 'pretty' date format (for use in English)
settings.L10n.date_format = "%d-%b-%Y"
# Make last name in person/user records mandatory
settings.L10n.mandatory_lastname = True
# Uncomment this to Translate Layer Names
settings.L10n.translate_gis_layer = True
# Translate Location Names
settings.L10n.translate_gis_location = True
# -----------------------------------------------------------------------------
# Finance settings
settings.fin.currencies = {
"AUD" : T("Australian Dollars"),
"CAD" : T("Canadian Dollars"),
"EUR" : T("Euros"),
"GBP" : T("Great British Pounds"),
"PHP" : T("Philippine Pesos"),
"CHF" : T("Swiss Francs"),
"USD" : T("United States Dollars"),
}
# -----------------------------------------------------------------------------
# Enable this for a UN-style deployment
#settings.ui.cluster = True
# Enable this to use the label 'Camp' instead of 'Shelter'
settings.ui.camp = True
# -----------------------------------------------------------------------------
# Filter Manager
settings.search.filter_manager = False
# -----------------------------------------------------------------------------
# Messaging
# Parser
settings.msg.parser = "IFRC"
# =============================================================================
# Module Settings
# -----------------------------------------------------------------------------
# Organisation Management
# Enable the use of Organisation Branches
settings.org.branches = True
# Set the length of the auto-generated org/site code the default is 10
settings.org.site_code_len = 3
# Set the label for Sites
settings.org.site_label = "Office/Warehouse/Facility"
# Enable certain fields just for specific Organisations
ARCS = "Afghan Red Crescent Society"
BRCS = "Bangladesh Red Crescent Society"
CVTL = "Timor-Leste Red Cross Society (Cruz Vermelha de Timor-Leste)"
PMI = "Indonesian Red Cross Society (Pelang Merah Indonesia)"
PRC = "Philippine Red Cross"
VNRC = "Viet Nam Red Cross"
settings.org.dependent_fields = \
{"pr_person.middle_name" : (CVTL, VNRC),
"pr_person_details.mother_name" : (BRCS, ),
"pr_person_details.father_name" : (ARCS, BRCS),
"pr_person_details.affiliations" : (PRC, ),
"pr_person_details.company" : (PRC, ),
"vol_details.availability" : (VNRC, ),
"vol_details.card" : (ARCS, ),
"vol_volunteer_cluster.vol_cluster_type_id" : (PRC, ),
"vol_volunteer_cluster.vol_cluster_id" : (PRC, ),
"vol_volunteer_cluster.vol_cluster_position_id" : (PRC, ),
}
# -----------------------------------------------------------------------------
# Human Resource Management
# Uncomment to allow Staff & Volunteers to be registered without an email address
settings.hrm.email_required = False
# Uncomment to filter certificates by (root) Organisation & hence not allow Certificates from other orgs to be added to a profile (except by Admin)
settings.hrm.filter_certificates = True
# Uncomment to show the Organisation name in HR represents
settings.hrm.show_organisation = True
# Uncomment to allow HRs to have multiple Job Titles
settings.hrm.multiple_job_titles = True
# Uncomment to have each root Org use a different Job Title Catalog
settings.hrm.org_dependent_job_titles = True
# Uncomment to disable the use of HR Credentials
settings.hrm.use_credentials = False
# Uncomment to enable the use of HR Education
settings.hrm.use_education = True
# Custom label for Organisations in HR module
settings.hrm.organisation_label = "National Society / Branch"
# Uncomment to consolidate tabs into a single CV
settings.hrm.cv_tab = True
# Uncomment to consolidate tabs into Staff Record
settings.hrm.record_tab = True
# Uncomment to do a search for duplicates in the new AddPersonWidget2
settings.pr.lookup_duplicates = True
# RDRT
settings.deploy.hr_label = "Member"
# Enable the use of Organisation Regions
settings.org.regions = True
# Make Organisation Regions Hierarchical
settings.org.regions_hierarchical = True
# Uncomment to allow hierarchical categories of Skills, which each need their own set of competency levels.
settings.hrm.skill_types = True
# RDRT overrides these within controller:
# Uncomment to disable Staff experience
settings.hrm.staff_experience = False
# Uncomment to disable the use of HR Skills
settings.hrm.use_skills = False
# -----------------------------------------------------------------------------
def ns_only(f, required = True, branches = True, updateable=True):
"""
Function to configure an organisation_id field to be restricted to just NS/Branch
"""
# Label
if branches:
f.label = T("National Society / Branch")
else:
f.label = T("National Society")
# Requires
db = current.db
ttable = db.org_organisation_type
try:
type_id = db(ttable.name == "Red Cross / Red Crescent").select(ttable.id,
limitby=(0, 1)
).first().id
except:
# No IFRC prepop done - skip (e.g. testing impacts of CSS changes in this theme)
return
auth = current.auth
s3_has_role = auth.s3_has_role
Admin = s3_has_role("ADMIN")
if branches:
not_filterby = None
not_filter_opts = None
if Admin:
parent = True
else:
# @ToDo: Set the represent according to whether the user can see resources of just a single NS or multiple
# @ToDo: Consider porting this into core
user = auth.user
if user:
realms = user.realms
delegations = user.delegations
if realms:
parent = True
else:
parent = False
else:
parent = True
else:
# Keep the represent function as simple as possible
parent = False
btable = current.s3db.org_organisation_branch
rows = db(btable.deleted != True).select(btable.branch_id)
branches = [row.branch_id for row in rows]
not_filterby = "id"
not_filter_opts = branches
represent = current.s3db.org_OrganisationRepresent(parent=parent)
f.represent = represent
from s3.s3validators import IS_ONE_OF
requires = IS_ONE_OF(db, "org_organisation.id",
represent,
filterby = "organisation_type_id",
filter_opts = (type_id,),
not_filterby = not_filterby,
not_filter_opts=not_filter_opts,
updateable = updateable,
orderby = "org_organisation.name",
sort = True)
if not required:
from gluon import IS_EMPTY_OR
requires = IS_EMPTY_OR(requires)
f.requires = requires
# Dropdown not Autocomplete
f.widget = None
# Comment
if Admin or s3_has_role("ORG_ADMIN"):
# Need to do import after setting Theme
from s3layouts import S3AddResourceLink
from s3.s3navigation import S3ScriptItem
add_link = S3AddResourceLink(c="org",
f="organisation",
vars={"organisation.organisation_type_id$name":"Red Cross / Red Crescent"},
label=T("Create National Society"),
title=T("National Society"),
)
comment = f.comment
if not comment or isinstance(comment, S3AddResourceLink):
f.comment = add_link
elif isinstance(comment[1], S3ScriptItem):
# Don't overwrite scripts
f.comment[0] = add_link
else:
f.comment = add_link
else:
# Not allowed to add NS/Branch
f.comment = ""
# -----------------------------------------------------------------------------
def user_org_default_filter(selector, tablename=None):
"""
Default filter for organisation_id:
* Use the user's organisation if logged in and associated with an
organisation.
"""
auth = current.auth
user_org_id = auth.is_logged_in() and auth.user.organisation_id
if user_org_id:
return user_org_id
else:
# no default
return {}
# -----------------------------------------------------------------------------
def customise_asset_asset_resource(r, tablename):
s3db = current.s3db
table = s3db.asset_asset
# Organisation needs to be an NS/Branch
ns_only(table.organisation_id,
required = True,
branches = True,
)
# Custom CRUD Form to allow ad-hoc Kits & link to Teams
from s3.s3forms import S3SQLCustomForm, S3SQLInlineComponent
table.kit.readable = table.kit.writable = True
crud_form = S3SQLCustomForm("number",
"type",
"item_id",
"organisation_id",
"site_id",
"kit",
# If not ad-hoc Kit
"sn",
"supply_org_id",
"purchase_date",
"purchase_price",
"purchase_currency",
# If ad-hoc Kit
S3SQLInlineComponent(
"item",
label = T("Items"),
fields = ["item_id",
"quantity",
"sn",
# These are too wide for the screen & hence hide the AddResourceLinks
#"supply_org_id",
#"purchase_date",
#"purchase_price",
#"purchase_currency",
"comments",
],
),
S3SQLInlineComponent(
"group",
label = T("Team"),
fields = [("", "group_id")],
filterby = dict(field = "group_type",
options = 3
),
multiple = False,
),
"comments",
)
from s3.s3filter import S3OptionsFilter
filter_widgets = s3db.get_config(tablename, "filter_widgets")
filter_widgets.insert(-2, S3OptionsFilter("group.group_id",
label = T("Team"),
represent = "%(name)s",
hidden = True,
))
s3db.configure(tablename,
crud_form = crud_form,
)
settings.customise_asset_asset_resource = customise_asset_asset_resource
# -----------------------------------------------------------------------------
def customise_auth_user_controller(**attr):
"""
Customise admin/user() and default/user() controllers
"""
#if "arg" in attr and attr["arg"] == "register":
# Organisation needs to be an NS/Branch
ns_only(current.db.auth_user.organisation_id,
required = True,
branches = True,
updateable = False, # Need to see all Orgs in Registration screens
)
# Different settings for different NS
# Not possible for registration form, so fake with language!
root_org = current.auth.root_org_name()
if root_org == VNRC or current.session.s3.language == "vi":
# Too late to do via settings
#settings.org.site_label = "Office/Center"
current.db.auth_user.site_id.label = T("Office/Center")
return attr
settings.customise_auth_user_controller = customise_auth_user_controller
# -----------------------------------------------------------------------------
def customise_deploy_alert_resource(r, tablename):
current.s3db.deploy_alert_recipient.human_resource_id.label = T("Member")
settings.customise_deploy_alert_resource = customise_deploy_alert_resource
# -----------------------------------------------------------------------------
def customise_deploy_application_resource(r, tablename):
r.table.human_resource_id.label = T("Member")
settings.customise_deploy_application_resource = customise_deploy_application_resource
# -----------------------------------------------------------------------------
def _customise_assignment_fields(**attr):
MEMBER = T("Member")
from gluon.html import DIV
hr_comment = \
DIV(_class="tooltip",
_title="%s|%s" % (MEMBER,
current.messages.AUTOCOMPLETE_HELP))
from s3.s3validators import IS_ONE_OF
atable = current.s3db.deploy_assignment
atable.human_resource_id.label = MEMBER
atable.human_resource_id.comment = hr_comment
field = atable.job_title_id
field.comment = None
field.label = T("Sector")
field.requires = IS_ONE_OF(current.db, "hrm_job_title.id",
field.represent,
filterby = "type",
filter_opts = (4,),
)
return
# -----------------------------------------------------------------------------
def customise_deploy_assignment_controller(**attr):
s3db = current.s3db
table = s3db.deploy_assignment
# Labels
table.job_title_id.label = T("RDRT Type")
table.start_date.label = T("Deployment Date")
#table.end_date.label = T("EOM")
# List fields
list_fields = [(T("Mission"), "mission_id$name"),
(T("Appeal Code"), "mission_id$code"),
(T("Country"), "mission_id$location_id"),
(T("Disaster Type"), "mission_id$event_type_id"),
# @todo: replace by date of first alert?
(T("Date"), "mission_id$created_on"),
"job_title_id",
(T("Member"), "human_resource_id$person_id"),
(T("Deploying NS"), "human_resource_id$organisation_id"),
"start_date",
"end_date",
"appraisal.rating",
# @todo: Comments of the mission (=>XLS only)
]
# Report options
report_fact = [(T("Number of Deployments"), "count(human_resource_id)"),
(T("Average Rating"), "avg(appraisal.rating)"),
]
report_axis = [(T("Appeal Code"), "mission_id$code"),
(T("Country"), "mission_id$location_id"),
(T("Disaster Type"), "mission_id$event_type_id"),
(T("RDRT Type"), "job_title_id"),
(T("Deploying NS"), "human_resource_id$organisation_id"),
]
report_options = Storage(
rows=report_axis,
cols=report_axis,
fact=report_fact,
defaults=Storage(rows="mission_id$location_id",
cols="mission_id$event_type_id",
fact="count(human_resource_id)",
totals=True
)
)
s3db.configure("deploy_assignment",
list_fields = list_fields,
report_options = report_options,
)
# CRUD Strings
current.response.s3.crud_strings["deploy_assignment"] = Storage(
label_create = T("Add Deployment"),
title_display = T("Deployment Details"),
title_list = T("Deployments"),
title_update = T("Edit Deployment Details"),
title_upload = T("Import Deployments"),
label_list_button = T("List Deployments"),
label_delete_button = T("Delete Deployment"),
msg_record_created = T("Deployment added"),
msg_record_modified = T("Deployment Details updated"),
msg_record_deleted = T("Deployment deleted"),
msg_list_empty = T("No Deployments currently registered"))
_customise_assignment_fields()
# Restrict Location to just Countries
from s3.s3fields import S3Represent
field = s3db.deploy_mission.location_id
field.represent = S3Represent(lookup="gis_location", translate=True)
return attr
settings.customise_deploy_assignment_controller = customise_deploy_assignment_controller
# -----------------------------------------------------------------------------
def customise_deploy_mission_controller(**attr):
db = current.db
s3db = current.s3db
s3 = current.response.s3
MEMBER = T("Member")
from gluon.html import DIV
hr_comment = \
DIV(_class="tooltip",
_title="%s|%s" % (MEMBER,
current.messages.AUTOCOMPLETE_HELP))
table = s3db.deploy_mission
table.code.label = T("Appeal Code")
table.event_type_id.label = T("Disaster Type")
table.organisation_id.readable = table.organisation_id.writable = False
# Restrict Location to just Countries
from s3.s3fields import S3Represent
from s3.s3widgets import S3MultiSelectWidget
field = table.location_id
field.label = current.messages.COUNTRY
field.requires = s3db.gis_country_requires
field.widget = S3MultiSelectWidget(multiple=False)
field.represent = S3Represent(lookup="gis_location", translate=True)
rtable = s3db.deploy_response
rtable.human_resource_id.label = MEMBER
rtable.human_resource_id.comment = hr_comment
_customise_assignment_fields()
# Report options
report_fact = [(T("Number of Missions"), "count(id)"),
(T("Number of Countries"), "count(location_id)"),
(T("Number of Disaster Types"), "count(event_type_id)"),
(T("Number of Responses"), "sum(response_count)"),
(T("Number of Deployments"), "sum(hrquantity)"),
]
report_axis = ["code",
"location_id",
"event_type_id",
"status",
]
report_options = Storage(rows = report_axis,
cols = report_axis,
fact = report_fact,
defaults = Storage(rows = "location_id",
cols = "event_type_id",
fact = "sum(hrquantity)",
totals = True,
),
)
s3db.configure("deploy_mission",
report_options = report_options,
)
# CRUD Strings
s3.crud_strings["deploy_assignment"] = Storage(
label_create = T("New Deployment"),
title_display = T("Deployment Details"),
title_list = T("Deployments"),
title_update = T("Edit Deployment Details"),
title_upload = T("Import Deployments"),
label_list_button = T("List Deployments"),
label_delete_button = T("Delete Deployment"),
msg_record_created = T("Deployment added"),
msg_record_modified = T("Deployment Details updated"),
msg_record_deleted = T("Deployment deleted"),
msg_list_empty = T("No Deployments currently registered"))
# Custom prep
standard_prep = s3.prep
def custom_prep(r):
# Call standard prep
if callable(standard_prep):
result = standard_prep(r)
else:
result = True
if not r.component and r.method == "create":
# Org is always IFRC
otable = s3db.org_organisation
query = (otable.name == "International Federation of Red Cross and Red Crescent Societies")
organisation = db(query).select(otable.id,
limitby = (0, 1),
).first()
if organisation:
r.table.organisation_id.default = organisation.id
return result
s3.prep = custom_prep
return attr
settings.customise_deploy_mission_controller = customise_deploy_mission_controller
# -----------------------------------------------------------------------------
def poi_marker_fn(record):
"""
Function to decide which Marker to use for PoI KML export
"""
db = current.db
table = db.gis_poi_type
type = db(table.id == record.poi_type_id).select(table.name,
limitby=(0, 1)
).first()
if type:
marker = type.name.lower().replace(" ", "_")\
.replace("_cccm", "_CCCM")\
.replace("_nfi_", "_NFI_")\
.replace("_ngo_", "_NGO_")\
.replace("_wash", "_WASH")
marker = "OCHA/%s_40px.png" % marker
else:
# Fallback
marker = "marker_red.png"
return Storage(image=marker)
# -----------------------------------------------------------------------------
def customise_gis_poi_resource(r, tablename):
if r.representation == "kml":
# Custom Marker function
current.s3db.configure("gis_poi",
marker_fn = poi_marker_fn,
)
settings.customise_gis_poi_resource = customise_gis_poi_resource
# -----------------------------------------------------------------------------
def customise_hrm_certificate_controller(**attr):
# Organisation needs to be an NS/Branch
ns_only(current.s3db.hrm_certificate.organisation_id,
required = False,
branches = False,
)
return attr
settings.customise_hrm_certificate_controller = customise_hrm_certificate_controller
# -----------------------------------------------------------------------------
def customise_hrm_course_controller(**attr):
# Organisation needs to be an NS/Branch
ns_only(current.s3db.hrm_course.organisation_id,
required = False,
branches = False,
)
return attr
settings.customise_hrm_course_controller = customise_hrm_course_controller
# -----------------------------------------------------------------------------
def customise_hrm_credential_controller(**attr):
# Currently just used by RDRT
table = current.s3db.hrm_credential
field = table.job_title_id
field.comment = None
field.label = T("Sector")
from s3.s3validators import IS_ONE_OF
field.requires = IS_ONE_OF(current.db, "hrm_job_title.id",
field.represent,
filterby = "type",
filter_opts = (4,),
)
table.organisation_id.readable = table.organisation_id.writable = False
table.performance_rating.readable = table.performance_rating.writable = False
table.start_date.readable = table.start_date.writable = False
table.end_date.readable = table.end_date.writable = False
return attr
settings.customise_hrm_credential_controller = customise_hrm_credential_controller
# -----------------------------------------------------------------------------
def customise_hrm_department_controller(**attr):
# Organisation needs to be an NS/Branch
ns_only(current.s3db.hrm_department.organisation_id,
required = False,
branches = False,
)
return attr
settings.customise_hrm_department_controller = customise_hrm_department_controller
# -----------------------------------------------------------------------------
def customise_hrm_human_resource_controller(**attr):
# Default Filter
from s3 import s3_set_default_filter
s3_set_default_filter("~.organisation_id",
user_org_default_filter,
tablename = "hrm_human_resource")
arcs = False
vnrc = False
if current.request.controller == "vol":
# Special cases for different NS
root_org = current.auth.root_org_name()
if root_org == ARCS:
arcs = True
settings.L10n.mandatory_lastname = False
settings.hrm.use_code = True
settings.hrm.use_skills = True
settings.hrm.vol_active = True
elif root_org in (CVTL, PMI, PRC):
settings.hrm.vol_active = vol_active
elif root_org == VNRC:
vnrc = True
settings.pr.name_format = "%(last_name)s %(middle_name)s %(first_name)s"
# @ToDo: Make this use the same lookup as in ns_only to check if user can see HRs from multiple NS
settings.org.regions = False
#elif vnrc:
# settings.org.site_label = "Office/Center"
s3db = current.s3db
# Organisation needs to be an NS/Branch
ns_only(s3db.hrm_human_resource.organisation_id,
required = True,
branches = True,
)
s3 = current.response.s3
# Custom prep
standard_prep = s3.prep
def custom_prep(r):
# Call standard prep
if callable(standard_prep):
result = standard_prep(r)
else:
result = True
if arcs:
field = s3db.vol_details.card
field.readable = field.writable = True
elif vnrc:
field = r.table.job_title_id
field.readable = field.writable = False
return result
s3.prep = custom_prep
# Custom postp
standard_postp = s3.postp
def custom_postp(r, output):
# Call standard postp
if callable(standard_postp):
output = standard_postp(r, output)
if isinstance(output, dict):
if r.controller == "deploy" and \
"title" in output:
output["title"] = T("RDRT Members")
elif vnrc and \
r.method != "report" and \
"form" in output and \
(r.controller == "vol" or \
r.component_name == "human_resource"):
# Remove the injected Programme field
del output["form"][0].components[4]
del output["form"][0].components[4]
return output
s3.postp = custom_postp
return attr
settings.customise_hrm_human_resource_controller = customise_hrm_human_resource_controller
# -----------------------------------------------------------------------------
def customise_hrm_job_title_controller(**attr):
s3 = current.response.s3
table = current.s3db.hrm_job_title
controller = current.request.controller
if controller == "deploy":
# Filter to just deployables
s3.filter = (table.type == 4)
else:
# Organisation needs to be an NS/Branch
ns_only(table.organisation_id,
required = False,
branches = False,
)
# Custom prep
standard_prep = s3.prep
def custom_prep(r):
# Call standard prep
if callable(standard_prep):
result = standard_prep(r)
else:
result = True
if controller == "deploy":
field = table.type
field.default = 4
field.readable = field.writable = False
table.organisation_id.readable = False
table.organisation_id.writable = False
SECTOR = T("Sector")
ADD_SECTOR = T("Create Sector")
help = T("If you don't see the Sector in the list, you can add a new one by clicking link 'Create Sector'.")
s3.crud_strings["hrm_job_title"] = Storage(
label_create=T("Create Sector"),
title_display=T("Sector Details"),
title_list=T("Sectors"),
title_update=T("Edit Sector"),
label_list_button=T("List Sectors"),
label_delete_button=T("Delete Sector"),
msg_record_created=T("Sector added"),
msg_record_modified=T("Sector updated"),
msg_record_deleted=T("Sector deleted"),
msg_list_empty=T("No Sectors currently registered"))
return result
s3.prep = custom_prep
return attr
settings.customise_hrm_job_title_controller = customise_hrm_job_title_controller
# -----------------------------------------------------------------------------
def customise_hrm_programme_controller(**attr):
s3db = current.s3db
# Organisation needs to be an NS/Branch
ns_only(s3db.hrm_programme.organisation_id,
required = False,
branches = False,
)
# Special cases for different NS
root_org = current.auth.root_org_name()
if root_org == ARCS:
settings.L10n.mandatory_lastname = False
settings.hrm.vol_active = True
elif root_org in (CVTL, PMI, PRC):
settings.hrm.vol_active = vol_active
settings.hrm.vol_active_tooltip = "A volunteer is defined as active if they've participated in an average of 8 or more hours of Program work or Trainings per month in the last year"
elif root_org == VNRC:
settings.pr.name_format = "%(last_name)s %(middle_name)s %(first_name)s"
field = s3db.hrm_programme_hours.job_title_id
field.readable = field.writable = False
# @ToDo
# def vn_age_group(age):
# settings.pr.age_group = vn_age_group
return attr
settings.customise_hrm_programme_controller = customise_hrm_programme_controller
# -----------------------------------------------------------------------------
def customise_hrm_programme_hours_controller(**attr):
# Default Filter
from s3 import s3_set_default_filter
s3_set_default_filter("~.person_id$human_resource.organisation_id",
user_org_default_filter,
tablename = "hrm_programme_hours")
# Special cases for different NS
root_org = current.auth.root_org_name()
if root_org == ARCS:
settings.L10n.mandatory_lastname = False
settings.hrm.vol_active = True
elif root_org in (CVTL, PMI, PRC):
settings.hrm.vol_active = vol_active
elif root_org == VNRC:
settings.pr.name_format = "%(last_name)s %(middle_name)s %(first_name)s"
field = current.s3db.hrm_programme_hours.job_title_id
field.readable = field.writable = False
# Remove link to download Template
attr["csv_template"] = "hide"
return attr
settings.customise_hrm_programme_hours_controller = customise_hrm_programme_hours_controller
# -----------------------------------------------------------------------------
def customise_hrm_training_controller(**attr):
# Default Filter
from s3 import s3_set_default_filter
s3_set_default_filter("~.person_id$human_resource.organisation_id",
user_org_default_filter,
tablename = "hrm_training")
# Special cases for different NS
root_org = current.auth.root_org_name()
if root_org == ARCS:
settings.L10n.mandatory_lastname = False
settings.hrm.vol_active = True
elif root_org in (CVTL, PMI, PRC):
settings.hrm.vol_active = vol_active
elif root_org == VNRC:
settings.pr.name_format = "%(last_name)s %(middle_name)s %(first_name)s"
# Remove link to download Template
attr["csv_template"] = "hide"
return attr
settings.customise_hrm_training_controller = customise_hrm_training_controller
# -----------------------------------------------------------------------------
def customise_hrm_training_event_controller(**attr):
# Special cases for different NS
root_org = current.auth.root_org_name()
if root_org == ARCS:
settings.L10n.mandatory_lastname = False
settings.hrm.vol_active = True
elif root_org in (CVTL, PMI, PRC):
settings.hrm.vol_active = vol_active
elif root_org == VNRC:
settings.pr.name_format = "%(last_name)s %(middle_name)s %(first_name)s"
# Remove link to download Template
attr["csv_template"] = "hide"
return attr
settings.customise_hrm_training_event_controller = customise_hrm_training_event_controller
# -----------------------------------------------------------------------------
def customise_inv_warehouse_resource(r, tablename):
# Special cases for different NS
root_org = current.auth.root_org_name()
if root_org == "Australian Red Cross":
# AusRC use proper Logistics workflow
settings.inv.direct_stock_edits = False
settings.customise_inv_warehouse_resource = customise_inv_warehouse_resource
# -----------------------------------------------------------------------------
def customise_member_membership_controller(**attr):
# @ToDo: If these NS start using Membership module
#s3db = current.s3db
#
# Special cases for different NS
#root_org = current.auth.root_org_name()
#if root_org == ARCS:
# settings.L10n.mandatory_lastname = False
#elif root_org == VNRC:
# settings.pr.name_format = "%(last_name)s %(middle_name)s %(first_name)s"
# # Remove link to download Template
# attr["csv_template"] = "hide"
# Organisation needs to be an NS/Branch
ns_only(current.s3db.member_membership.organisation_id,
required = True,
branches = True,
)
return attr
settings.customise_member_membership_controller = customise_member_membership_controller
# -----------------------------------------------------------------------------
def customise_member_membership_type_controller(**attr):
# Organisation needs to be an NS/Branch
ns_only(current.s3db.member_membership_type.organisation_id,
required = False,
branches = False,
)
return attr
settings.customise_member_membership_type_controller = customise_member_membership_type_controller
# -----------------------------------------------------------------------------
def customise_org_office_controller(**attr):
# Organisation needs to be an NS/Branch
ns_only(current.s3db.org_office.organisation_id,
required = True,
branches = True,
)
return attr
settings.customise_org_office_controller = customise_org_office_controller
# -----------------------------------------------------------------------------
def customise_org_organisation_controller(**attr):
s3 = current.response.s3
# Custom prep
standard_prep = s3.prep
def custom_prep(r):
# Call standard prep
if callable(standard_prep):
result = standard_prep(r)
else:
result = True
if not r.component or r.component.name == "branch":
if r.interactive or r.representation == "aadata":
s3db = current.s3db
list_fields = ["id",
"name",
"acronym",
"organisation_type_id",
#(T("Sectors"), "sector.name"),
"country",
"website"
]
type_filter = r.get_vars.get("organisation.organisation_type_id$name",
None)
if type_filter:
type_names = type_filter.split(",")
if len(type_names) == 1:
# Strip Type from list_fields
list_fields.remove("organisation_type_id")
if type_filter == "Red Cross / Red Crescent":
# Modify filter_widgets
filter_widgets = s3db.get_config("org_organisation", "filter_widgets")
# Remove type (always 'RC')
filter_widgets.pop(1)
# Remove sector (not relevant)
filter_widgets.pop(1)
# Modify CRUD Strings
ADD_NS = T("Create National Society")
s3.crud_strings.org_organisation = Storage(
label_create=ADD_NS,
title_display=T("National Society Details"),
title_list=T("Red Cross & Red Crescent National Societies"),
title_update=T("Edit National Society"),
title_upload=T("Import Red Cross & Red Crescent National Societies"),
label_list_button=T("List Red Cross & Red Crescent National Societies"),
label_delete_button=T("Delete National Society"),
msg_record_created=T("National Society added"),
msg_record_modified=T("National Society updated"),
msg_record_deleted=T("National Society deleted"),
msg_list_empty=T("No Red Cross & Red Crescent National Societies currently registered")
)
# Add Region to list_fields
list_fields.insert(-1, "region_id")
# Region is required
r.table.region_id.requires = r.table.region_id.requires.other
else:
r.table.region_id.readable = r.table.region_id.writable = False
s3db.configure("org_organisation",
list_fields = list_fields,
)
if r.interactive:
r.table.country.label = T("Country")
from s3.s3forms import S3SQLCustomForm#, S3SQLInlineComponentCheckbox
crud_form = S3SQLCustomForm(
"name",
"acronym",
"organisation_type_id",
"region_id",
"country",
#S3SQLInlineComponentCheckbox(
# "sector",
# label = T("Sectors"),
# field = "sector_id",
# cols = 3,
#),
"phone",
"website",
"logo",
"comments",
)
s3db.configure("org_organisation", crud_form=crud_form)
return result
s3.prep = custom_prep
return attr
settings.customise_org_organisation_controller = customise_org_organisation_controller
# -----------------------------------------------------------------------------
def customise_pr_contact_resource(r, tablename):
# Special cases for different NS
root_org = current.auth.root_org_name()
if root_org == VNRC:
# Hard to translate in Vietnamese
current.s3db.pr_contact.value.label = ""
settings.customise_pr_contact_resource = customise_pr_contact_resource
# -----------------------------------------------------------------------------
def customise_pr_group_controller(**attr):
s3db = current.s3db
# Organisation needs to be an NS/Branch
table = s3db.org_organisation_team.organisation_id
ns_only(table,
required = False,
branches = True,
)
s3 = current.response.s3
# Custom prep
standard_prep = s3.prep
def custom_prep(r):
# Call standard prep
if callable(standard_prep):
result = standard_prep(r)
else:
result = True
if r.component_name == "group_membership":
# Special cases for different NS
root_org = current.auth.root_org_name()
if root_org == VNRC:
settings.pr.name_format = "%(last_name)s %(middle_name)s %(first_name)s"
# Update the represent as already set
s3db.pr_group_membership.person_id.represent = s3db.pr_PersonRepresent()
return result
s3.prep = custom_prep
return attr
settings.customise_pr_group_controller = customise_pr_group_controller
# =============================================================================
def vol_active(person_id):
"""
Whether a Volunteer counts as 'Active' based on the number of hours
they've done (both Trainings & Programmes) per month, averaged over
the last year.
If nothing recorded for the last 3 months, don't penalise as assume
that data entry hasn't yet been done.
@ToDo: This should be based on the HRM record, not Person record
- could be active with Org1 but not with Org2
@ToDo: allow to be calculated differently per-Org
"""
now = current.request.utcnow
# Time spent on Programme work
htable = current.s3db.hrm_programme_hours
query = (htable.deleted == False) & \
(htable.person_id == person_id) & \
(htable.date != None)
programmes = current.db(query).select(htable.hours,
htable.date,
orderby=htable.date)
if programmes:
# Ignore up to 3 months of records
three_months_prior = (now - timedelta(days=92))
end = max(programmes.last().date, three_months_prior.date())
last_year = end - timedelta(days=365)
# Is this the Volunteer's first year?
if programmes.first().date > last_year:
# Only start counting from their first month
start = programmes.first().date
else:
# Start from a year before the latest record
start = last_year
# Total hours between start and end
programme_hours = 0
for programme in programmes:
if programme.date >= start and programme.date <= end and programme.hours:
programme_hours += programme.hours
# Average hours per month
months = max(1, (end - start).days / 30.5)
average = programme_hours / months
# Active?
if average >= 8:
return True
else:
return False
else:
return False
# -----------------------------------------------------------------------------
def customise_pr_person_controller(**attr):
s3db = current.s3db
# Special cases for different NS
arcs = False
vnrc = False
root_org = current.auth.root_org_name()
if root_org == ARCS:
arcs = True
settings.L10n.mandatory_lastname = False
# Override what has been set in the model already
s3db.pr_person.last_name.requires = None
settings.hrm.use_code = True
settings.hrm.use_skills = True
settings.hrm.vol_active = True
elif root_org == PMI:
settings.hrm.use_skills = True
settings.hrm.staff_experience = "experience"
settings.hrm.vol_experience = "both"
settings.hrm.vol_active = vol_active
settings.hrm.vol_active_tooltip = "A volunteer is defined as active if they've participated in an average of 8 or more hours of Program work or Trainings per month in the last year"
elif root_org in (CVTL, PRC):
settings.hrm.vol_active = vol_active
settings.hrm.vol_active_tooltip = "A volunteer is defined as active if they've participated in an average of 8 or more hours of Program work or Trainings per month in the last year"
elif root_org == VNRC:
vnrc = True
# Remove 'Commune' level for Addresses
#gis = current.gis
#gis.get_location_hierarchy()
#try:
# gis.hierarchy_levels.pop("L3")
#except:
# # Must be already removed
# pass
settings.gis.postcode_selector = False # Needs to be done before prep as read during model load
settings.hrm.use_skills = True
settings.hrm.vol_experience = "both"
settings.pr.name_format = "%(last_name)s %(middle_name)s %(first_name)s"
try:
settings.modules.pop("asset")
except:
# Must be already removed
pass
if current.request.controller == "deploy":
# Replace default title in imports:
attr["retitle"] = lambda r: {"title": T("Import Members")} \
if r.method == "import" else None
s3 = current.response.s3
# Custom prep
standard_prep = s3.prep
def custom_prep(r):
# Call standard prep
if callable(standard_prep):
result = standard_prep(r)
else:
result = True
component_name = r.component_name
if component_name == "appraisal":
atable = r.component.table
atable.organisation_id.readable = atable.organisation_id.writable = False
# Organisation needs to be an NS
#ns_only(atable.organisation_id,
# required = True,
# branches = False,
# )
field = atable.supervisor_id
field.readable = field.writable = False
field = atable.job_title_id
field.comment = None
field.label = T("Sector") # RDRT-specific
from s3.s3validators import IS_ONE_OF
field.requires = IS_ONE_OF(db, "hrm_job_title.id",
field.represent,
filterby = "type",
filter_opts = (4,),
)
elif r.method == "cv" or component_name == "education":
if vnrc:
# Don't enable Legacy Freetext field
# Hide the 'Name of Award' field
field = s3db.pr_education.award
field.readable = field.writable = False
elif arcs:
# Don't enable Legacy Freetext field
pass
else:
# Enable Legacy Freetext field
field = s3db.pr_education.level
field.readable = field.writable = True
field.label = T("Other Level")
field.comment = T("Use main dropdown whenever possible")
if arcs:
if not r.component:
s3db.pr_person_details.father_name.label = T("Name of Grandfather")
elif vnrc:
if not r.component:
# Use a free-text version of religion field
field = s3db.pr_person_details.religion_other
field.label = T("Religion")
field.readable = field.writable = True
# Also hide some other fields
from s3.s3forms import S3SQLCustomForm
crud_form = S3SQLCustomForm("first_name",
"middle_name",
"last_name",
"date_of_birth",
#"initials",
#"preferred_name",
#"local_name",
"gender",
"person_details.marital_status",
"person_details.nationality",
"person_details.religion_other",
"person_details.mother_name",
"person_details.father_name",
#"person_details.occupation",
#"person_details.company",
"person_details.affiliations",
"comments",
)
s3db.configure("pr_person",
crud_form = crud_form,
)
if r.method == "record" or \
component_name == "human_resource":
field = s3db.hrm_human_resource.job_title_id
field.readable = field.writable = False
field = s3db.hrm_programme_hours.job_title_id
field.readable = field.writable = False
elif component_name == "address":
settings.gis.building_name = False
settings.gis.latlon_selector = False
settings.gis.map_selector = False
elif component_name == "identity":
table = s3db.pr_identity
table.description.readable = False
table.description.writable = False
pr_id_type_opts = {1: T("Passport"),
2: T("National ID Card"),
}
from gluon.validators import IS_IN_SET
table.type.requires = IS_IN_SET(pr_id_type_opts,
zero=None)
elif component_name == "hours":
field = s3db.hrm_programme_hours.job_title_id
field.readable = field.writable = False
elif component_name == "physical_description":
# Add the less-specific blood types (as that's all the data currently available in some cases)
field = s3db.pr_physical_description.blood_type
from gluon.validators import IS_EMPTY_OR, IS_IN_SET
blood_type_opts = ("A+", "A-", "B+", "B-", "AB+", "AB-", "O+", "O-", "A", "B", "AB", "O")
field.requires = IS_EMPTY_OR(IS_IN_SET(blood_type_opts))
elif r.method == "cv" or component_name == "experience":
table = s3db.hrm_experience
# Use simple free-text variants
table.organisation.readable = True
table.organisation.writable = True
table.job_title.readable = True
table.job_title.writable = True
table.comments.label = T("Main Duties")
from s3.s3forms import S3SQLCustomForm
crud_form = S3SQLCustomForm("organisation",
"job_title",
"comments",
"start_date",
"end_date",
)
s3db.configure("hrm_experience",
crud_form = crud_form,
list_fields = ["id",
"organisation",
"job_title",
"comments",
"start_date",
"end_date",
],
)
return result
s3.prep = custom_prep
attr["rheader"] = lambda r, vnrc=vnrc: pr_rheader(r, vnrc)
if vnrc:
# Link to customised download Template
#attr["csv_template"] = ("../../themes/IFRC/formats", "volunteer_vnrc")
# Remove link to download Template
attr["csv_template"] = "hide"
return attr
settings.customise_pr_person_controller = customise_pr_person_controller
# -----------------------------------------------------------------------------
def pr_rheader(r, vnrc):
"""
Custom rheader for vol/person for vnrc
"""
if vnrc and current.request.controller == "vol":
# Simplify RHeader
settings.hrm.vol_experience = None
s3db = current.s3db
s3db.hrm_vars()
return s3db.hrm_rheader(r)
# -----------------------------------------------------------------------------
def customise_req_commit_controller(**attr):
# Request is mandatory
field = current.s3db.req_commit.req_id
field.requires = field.requires.other
return attr
settings.customise_req_commit_controller = customise_req_commit_controller
# -----------------------------------------------------------------------------
def customise_req_req_controller(**attr):
# Request is mandatory
field = current.s3db.req_commit.req_id
field.requires = field.requires.other
return attr
settings.customise_req_req_controller = customise_req_req_controller
# -----------------------------------------------------------------------------
def customise_survey_series_controller(**attr):
# Organisation needs to be an NS/Branch
ns_only(current.s3db.survey_series.organisation_id,
required = False,
branches = True,
)
return attr
settings.customise_survey_series_controller = customise_survey_series_controller
# -----------------------------------------------------------------------------
# Projects
# Uncomment this to use settings suitable for a global/regional organisation (e.g. DRR)
settings.project.mode_3w = True
# Uncomment this to use DRR (Disaster Risk Reduction) extensions
settings.project.mode_drr = True
# Uncomment this to use Codes for projects
settings.project.codes = True
# Uncomment this to call project locations 'Communities'
settings.project.community = True
# Uncomment this to enable Hazards in 3W projects
settings.project.hazards = True
# Uncomment this to use multiple Budgets per project
settings.project.multiple_budgets = True
# Uncomment this to use multiple Organisations per project
settings.project.multiple_organisations = True
# Uncomment this to enable Themes in 3W projects
settings.project.themes = True
# Uncomment this to customise
# Links to Filtered Components for Donors & Partners
settings.project.organisation_roles = {
1: T("Host National Society"),
2: T("Partner"),
3: T("Donor"),
#4: T("Customer"), # T("Beneficiary")?
#5: T("Supplier"),
9: T("Partner National Society"),
}
# -----------------------------------------------------------------------------
def customise_project_project_controller(**attr):
s3db = current.s3db
tablename = "project_project"
# Load normal model
table = s3db[tablename]
# @ToDo: S3SQLInlineComponent for Project orgs
# Get IDs for PartnerNS/Partner-Donor
# db = current.db
# ttable = db.org_organisation_type
# rows = db(ttable.deleted != True).select(ttable.id,
# ttable.name,
# )
# rc = []
# not_rc = []
# nappend = not_rc.append
# for row in rows:
# if row.name == "Red Cross / Red Crescent":
# rc.append(row.id)
# elif row.name == "Supplier":
# pass
# else:
# nappend(row.id)
# Custom Fields
# Organisation needs to be an NS (not a branch)
f = table.organisation_id
ns_only(f,
required = True,
branches = False,
)
f.label = T("Host National Society")
# Custom Crud Form
from s3.s3forms import S3SQLCustomForm, S3SQLInlineComponent, S3SQLInlineComponentCheckbox
crud_form = S3SQLCustomForm(
"organisation_id",
"name",
"code",
"description",
"status_id",
"start_date",
"end_date",
#S3SQLInlineComponent(
# "location",
# label = T("Countries"),
# fields = ["location_id"],
#),
# Outputs
S3SQLInlineComponent(
"output",
label = T("Outputs"),
#comment = "Bob",
fields = ["name", "status"],
),
S3SQLInlineComponentCheckbox(
"hazard",
label = T("Hazards"),
field = "hazard_id",
cols = 4,
translate = True,
),
S3SQLInlineComponentCheckbox(
"sector",
label = T("Sectors"),
field = "sector_id",
cols = 4,
translate = True,
),
S3SQLInlineComponentCheckbox(
"theme",
label = T("Themes"),
field = "theme_id",
cols = 4,
translate = True,
# Filter Theme by Sector
filter = {"linktable": "project_theme_sector",
"lkey": "theme_id",
"rkey": "sector_id",
},
script = '''
S3OptionsFilter({
'triggerName':'defaultsector-sector_id',
'targetName':'defaulttheme-theme_id',
'targetWidget':'defaulttheme-theme_id_widget',
'lookupResource':'theme',
'lookupURL':S3.Ap.concat('/project/theme_sector_widget?sector_ids='),
'getWidgetHTML':true,
'showEmptyField':false
})'''
),
"drr.hfa",
"objectives",
"human_resource_id",
# Disabled since we need organisation_id filtering to either organisation_type_id == RC or NOT
# & also hiding Branches from RCs
# Partner NS
# S3SQLInlineComponent(
# "organisation",
# name = "partnerns",
# label = T("Partner National Societies"),
# fields = ["organisation_id",
# "comments",
# ],
# Filter Organisation by Type
# filter = ["organisation_id": {"filterby": "organisation_type_id",
# "filterfor": rc,
# }],
# filterby = dict(field = "role",
# options = [9])
# ),
# Partner Orgs
# S3SQLInlineComponent(
# "organisation",
# name = "partner",
# label = T("Partner Organizations"),
# fields = ["organisation_id",
# "comments",
# ],
# Filter Organisation by Type
# filter = ["organisation_id": {"filterby": "organisation_type_id",
# "filterfor": not_rc,
# }],
# filterby = dict(field = "role",
# options = [2])
# ),
# Donors
# S3SQLInlineComponent(
# "organisation",
# name = "donor",
# label = T("Donor(s)"),
# fields = ["organisation_id",
# "amount",
# "currency"],
# Filter Organisation by Type
# filter = ["organisation_id": {"filterby": "organisation_type_id",
# "filterfor": not_rc,
# }],
# filterby = dict(field = "role",
# options = [3])
# ),
#"budget",
#"currency",
"comments",
)
s3db.configure(tablename,
crud_form = crud_form,
)
return attr
settings.customise_project_project_controller = customise_project_project_controller
# -----------------------------------------------------------------------------
def customise_project_location_resource(r, tablename):
from s3.s3forms import S3SQLCustomForm, S3SQLInlineComponentCheckbox
crud_form = S3SQLCustomForm(
"project_id",
"location_id",
# @ToDo: Grouped Checkboxes
S3SQLInlineComponentCheckbox(
"activity_type",
label = T("Activity Types"),
field = "activity_type_id",
cols = 3,
# Filter Activity Type by Sector
filter = {"linktable": "project_activity_type_sector",
"lkey": "activity_type_id",
"rkey": "sector_id",
"lookuptable": "project_project",
"lookupkey": "project_id",
},
translate = True,
),
"comments",
)
current.s3db.configure(tablename,
crud_form = crud_form,
)
settings.customise_project_location_resource = customise_project_location_resource
# -----------------------------------------------------------------------------
# Inventory Management
settings.inv.show_mode_of_transport = True
settings.inv.send_show_time_in = True
#settings.inv.collapse_tabs = True
# Uncomment if you need a simpler (but less accountable) process for managing stock levels
settings.inv.direct_stock_edits = True
# -----------------------------------------------------------------------------
# Request Management
# Uncomment to disable Inline Forms in Requests module
settings.req.inline_forms = False
settings.req.req_type = ["Stock"]
settings.req.use_commit = False
# Should Requests ask whether Transportation is required?
settings.req.ask_transport = True
# -----------------------------------------------------------------------------
def customise_vulnerability_data_resource(r, tablename):
# Date is required: We don't store modelled data
r.table.date.requires = r.table.date.requires.other
settings.customise_vulnerability_data_resource = customise_vulnerability_data_resource
# =============================================================================
# Template Modules
# Comment/uncomment modules here to disable/enable them
settings.modules = OrderedDict([
# Core modules which shouldn't be disabled
("default", Storage(
name_nice = "RMS",
restricted = False, # Use ACLs to control access to this module
access = None, # All Users (inc Anonymous) can see this module in the default menu & access the controller
module_type = None # This item is not shown in the menu
)),
("admin", Storage(
name_nice = T("Administration"),
#description = "Site Administration",
restricted = True,
access = "|1|", # Only Administrators can see this module in the default menu & access the controller
module_type = None # This item is handled separately for the menu
)),
("appadmin", Storage(
name_nice = T("Administration"),
#description = "Site Administration",
restricted = True,
module_type = None # No Menu
)),
("errors", Storage(
name_nice = T("Ticket Viewer"),
#description = "Needed for Breadcrumbs",
restricted = False,
module_type = None # No Menu
)),
("sync", Storage(
name_nice = T("Synchronization"),
#description = "Synchronization",
restricted = True,
access = "|1|", # Only Administrators can see this module in the default menu & access the controller
module_type = None # This item is handled separately for the menu
)),
("translate", Storage(
name_nice = T("Translation Functionality"),
#description = "Selective translation of strings based on module.",
module_type = None,
)),
# Uncomment to enable internal support requests
("support", Storage(
name_nice = T("Support"),
#description = "Support Requests",
restricted = True,
module_type = None # This item is handled separately for the menu
)),
("gis", Storage(
name_nice = T("Map"),
#description = "Situation Awareness & Geospatial Analysis",
restricted = True,
module_type = 6, # 6th item in the menu
)),
("pr", Storage(
name_nice = T("Person Registry"),
#description = "Central point to record details on People",
restricted = True,
access = "|1|", # Only Administrators can see this module in the default menu (access to controller is possible to all still)
module_type = 10
)),
("org", Storage(
name_nice = T("Organizations"),
#description = 'Lists "who is doing what & where". Allows relief agencies to coordinate their activities',
restricted = True,
module_type = 1
)),
# All modules below here should be possible to disable safely
("hrm", Storage(
name_nice = T("Staff"),
#description = "Human Resources Management",
restricted = True,
module_type = 2,
)),
("vol", Storage(
name_nice = T("Volunteers"),
#description = "Human Resources Management",
restricted = True,
module_type = 2,
)),
("doc", Storage(
name_nice = T("Documents"),
#description = "A library of digital resources, such as photos, documents and reports",
restricted = True,
module_type = 10,
)),
("msg", Storage(
name_nice = T("Messaging"),
#description = "Sends & Receives Alerts via Email & SMS",
restricted = True,
# The user-visible functionality of this module isn't normally required. Rather it's main purpose is to be accessed from other modules.
module_type = None,
)),
("supply", Storage(
name_nice = T("Supply Chain Management"),
#description = "Used within Inventory Management, Request Management and Asset Management",
restricted = True,
module_type = None, # Not displayed
)),
("inv", Storage(
name_nice = T("Warehouses"),
#description = "Receiving and Sending Items",
restricted = True,
module_type = 4
)),
("asset", Storage(
name_nice = T("Assets"),
#description = "Recording and Assigning Assets",
restricted = True,
module_type = 5,
)),
("req", Storage(
name_nice = T("Requests"),
#description = "Manage requests for supplies, assets, staff or other resources. Matches against Inventories where supplies are requested.",
restricted = True,
module_type = 10,
)),
("project", Storage(
name_nice = T("Projects"),
#description = "Tracking of Projects, Activities and Tasks",
restricted = True,
module_type = 2
)),
("survey", Storage(
name_nice = T("Assessments"),
#description = "Create, enter, and manage surveys.",
restricted = True,
module_type = 5,
)),
("event", Storage(
name_nice = T("Events"),
#description = "Events",
restricted = True,
module_type = 10
)),
("irs", Storage(
name_nice = T("Incidents"),
#description = "Incident Reporting System",
restricted = True,
module_type = 10
)),
("member", Storage(
name_nice = T("Members"),
#description = "Membership Management System",
restricted = True,
module_type = 10,
)),
("deploy", Storage(
name_nice = T("Regional Disaster Response Teams"),
#description = "Alerting and Deployment of Disaster Response Teams",
restricted = True,
module_type = 10,
)),
("stats", Storage(
name_nice = T("Statistics"),
#description = "Manages statistics",
restricted = True,
module_type = None,
)),
("vulnerability", Storage(
name_nice = T("Vulnerability"),
#description = "Manages vulnerability indicators",
restricted = True,
module_type = 10,
)),
])
|
mit
| -5,644,412,904,426,701,000
| 37.11982
| 189
| 0.511329
| false
| 4.436864
| false
| false
| false
|
liangdebin/tor
|
handlers/base.py
|
1
|
2310
|
import json
import tornado.web
import logging
logger = logging.getLogger('boilerplate.' + __name__)
class BaseHandler(tornado.web.RequestHandler):
"""A class to collect common handler methods - all other handlers should
subclass this one.
"""
def load_json(self):
"""Load JSON from the request body and store them in
self.request.arguments, like Tornado does by default for POSTed form
parameters.
If JSON cannot be decoded, raises an HTTPError with status 400.
"""
try:
self.request.arguments = json.loads(self.request.body)
except ValueError:
msg = "Could not decode JSON: %s" % self.request.body
logger.debug(msg)
raise tornado.web.HTTPError(400, msg)
def get_json_argument(self, name, default=None):
"""Find and return the argument with key 'name' from JSON request data.
Similar to Tornado's get_argument() method.
"""
if default is None:
default = self._ARG_DEFAULT
if not self.request.arguments:
self.load_json()
if name not in self.request.arguments:
if default is self._ARG_DEFAULT:
msg = "Missing argument '%s'" % name
logger.debug(msg)
raise tornado.web.HTTPError(400, msg)
logger.debug("Returning default argument %s, as we couldn't find "
"'%s' in %s" % (default, name, self.request.arguments))
return default
arg = self.request.arguments[name]
logger.debug("Found '%s': %s in JSON arguments" % (name, arg))
return arg
def write_error(self, status_code, **kwargs):
self.write("Gosh darnit, user! You caused a %d error." % status_code)
self.write( "<br/>" )
self.write( "%s"%(kwargs,) )
# self.write(json_encode(kwargs))
def prepare(self):
self.set_header("Power by","blueblue")
# self.write("Gosh darnit, user! ")
pass
def on_finish(self):
pass
def get(self):
self.req()
def post(self):
self.req()
def req(self):
# self.ROOT = settings.ROOT
# self.MEDIA_ROOT = settings.MEDIA_ROOT
# self.TEMPLATE_ROOT = settings.MEDIA_ROOT
pass
|
mit
| -580,859,130,668,034,600
| 33.477612
| 79
| 0.58658
| false
| 4.10302
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.