示例#1
0
def twoFactorAuthentication(handler, p_action):
    handler.title("Two-Factor Authentication")
    requirePriv(handler, "User")

    if p_action == "enable":
        handler.session["user"].hotpKey = b32encode("".join(chr(randrange(256)) for _ in range(10)))
        handler.session["user"].save()
        Event.tfa(handler, handler.session["user"])

        print SuccessBox("Two-factor authentication is <b>enabled</b>")
        print "Your HOTP key is <b>%s</b>:<br><br>" % handler.session["user"].hotpKey
        print '<div style="text-align: center"><img src="https://chart.googleapis.com/chart?chs=200x200&chld=M|0&cht=qr&chl=otpauth://totp/Sprint%%3Fsecret%%3D%s"></div><br>' % handler.session[
            "user"
        ].hotpKey

        print "This key will not be displayed again &mdash; be sure to write it down, or add it to your Google Authenticator list now"
    elif p_action == "disable":
        handler.session["user"].hotpKey = ""
        handler.session["user"].save()
        Event.tfa(handler, handler.session["user"])

        delay(handler, SuccessBox("Two-factor authentication is <b>disabled</b>"))
        redirect("/users/%s" % handler.session["user"].username)
    else:
        ErrorBox.die("Unexpected action: <b>%s</b>" % stripTags(p_action))
示例#2
0
 def __init__(self):
     self.__progress = QuestsProgress()
     self.__waitForSync = False
     self.__invalidateCbID = None
     self.onSyncStarted = Event()
     self.onSyncCompleted = Event()
     return
示例#3
0
 def __init__(self):
     Event.__init__(self)
     self.base = 'adventure'
     self.desc = "+1 Buy, Look at the top 5 cards of your deck. Discard 3 of them and put the rest back in any order"
     self.name = "Scouting Party"
     self.buys = 1
     self.cost = 2
示例#4
0
文件: clancache.py 项目: webiumsk/WoT
 def __init__(self):
     self.__waitForSync = False
     self.__fortProvider = ClientFortProvider()
     self.__clanMembersLen = None
     self.onSyncStarted = Event()
     self.onSyncCompleted = Event()
     return
示例#5
0
文件: admin.py 项目: mrozekma/Sprint
def adminReplPost(handler, p_code):
	def makeStr(v):
		if isinstance(v, list):
			return "<ul>%s</ul>" % ''.join("<li>%s</li>" % item for item in v)
		return str(v)

	handler.wrappers = False

	p_code = re.sub('^!([A-Za-z]+)$', 'from \\1 import \\1', p_code)
	match = re.match('!([A-Za-z ]+)$', p_code)
	if match:
		parts = match.group(1).split(' ')
		res = []
		for part in parts:
			w = ResponseWriter()
			adminReplPost(handler, "!%s" % part)
			res.append(fromJS(w.done()))
		print toJS(res)
		done()

	if 'admin-repl' not in handler.session:
		print toJS({'code': highlightCode(p_code), 'stdout': '', 'stderr': ['Session Expired', 'REPL session no longer exists'], 'vars': {}})
		done()

	writer = ResponseWriter()
	try:
		Event.repl(handler, p_code)
		exec compile(p_code, '<admin repl>', 'single') in handler.session['admin-repl']
		stderr = ''
	except:
		stderr = map(str, [sys.exc_info()[0].__name__, sys.exc_info()[1]])
	stdout = writer.done()

	vars = sorted([(k, pformat(v), makeStr(v)) for (k, v) in handler.session['admin-repl'].items() if k != '__builtins__'], lambda (k1, v1, vs1), (k2, v2, vs2): cmp(k1, k2))
	print toJS({'code': highlightCode(p_code), 'stdout': stdout, 'stderr': stderr, 'vars': vars})
示例#6
0
文件: prefs.py 项目: mrozekma/Sprint
def prefsPost(handler, p_default_sprint_tab, p_default_tasks_tab, p_backlog_style, p_messages = []):
	def die(msg):
		print msg
		done()

	handler.wrappers = False

	if not handler.session['user']:
		die("You must be logged in to modify preferences")
	if p_default_sprint_tab not in sprintTabs():
		die("Unrecognized default sprint tab <b>%s</b>" % stripTags(p_default_sprint_tab))
	if p_default_tasks_tab not in taskTabs:
		die("Unrecognized default task tab <b>%s</b>" % stripTags(p_default_tasks_tab))
	if set(p_backlog_style.keys()) != set(name for block in statusMenu for name in block):
		die("Backlog style key mismatch")
	if not set(p_messages.keys()) <= set(name for name, desc in messageTypes):
		die("Message type mismatch")

	prefs = handler.session['user'].getPrefs()
	prefs.defaultSprintTab = p_default_sprint_tab
	prefs.defaultTasksTab = p_default_tasks_tab
	prefs.backlogStyles = p_backlog_style
	prefs.messages = dict((name, name in p_messages.keys()) for name, desc in messageTypes)
	prefs.save()

	handler.responseCode = 299
	print "Saved changes"
	Event.prefs(handler)
示例#7
0
 def __init__(self):
     self.__vehInvID = 0
     self.__changeCallbackID = None
     self.__historicalBattle = None
     self.onChanged = Event()
     self.onChangeStarted = Event()
     return
示例#8
0
 def __init__(self):
     Event.__init__(self)
     self.base = 'empires'
     self.desc = "+1VP, Gain a Gold."
     self.name = "Wedding"
     self.cost = 4
     self.debtcost = 3
示例#9
0
	def receiveEvent(self, event, emitter):		
		if event.attributes['signature'] == 'game_tick':
			self.attributes['tick_count'] += 1
		
		filterFunc	= (lambda receiver: receiver.attributes['signature'] == event.attributes['signature'])
	
		for handler in filter(filterFunc, self.attributes['event_handlers']):
			newEvent = Event()
		
			newEvent.attributes = {
				'signature'		: event.attributes['signature'],
				'data'			: event.attributes['data'].copy(),
				'flags'			: event.attributes['flags'][:],
				'receiver'		: self,
				'event_target'	: None
			}
			
			handler.receiveEvent(newEvent)
			
		if self.attributes.has_key('AI'):			
			newEvent = Event()
		
			newEvent.attributes = {
				'signature'		: event.attributes['signature'],
				'data'			: event.attributes['data'].copy(),
				'flags'			: event.attributes['flags'][:],
				'receiver'		: self,
				'event_target'	: None
			}
			
			self.attributes['AI'].receiveEvent(newEvent, emitter)
示例#10
0
 def __init__(self):
     Event.__init__(self)
     self.base = 'empires'
     self.desc = "After this turn, put all cards from your deck and discard pile into your hand, trash any number, shuffle your hand into your deck, then draw 5 cards."
     self.name = "Donate"
     self.cost = 0
     self.debtcost = 8
示例#11
0
 def __init__(self):
     Event.__init__(self)
     self.base = 'empires'
     self.desc = "Gain a Curse. If you do, trash a card from your hand. +1VP per Coin it cost."
     self.name = "Ritual"
     self.cost = 4
     self.required_cards = ['Curse']
示例#12
0
文件: groups.py 项目: mrozekma/Sprint
def newGroupPost(handler, p_group, p_name):
	def die(msg):
		print msg
		done()

	handler.title('New Group')
	requirePriv(handler, 'User')
	handler.wrappers = False

	predid = to_int(p_group, 'group', die)
	pred = Group.load(predid)
	if not pred:
		die("No group with ID <b>%d</b>" % predid)
	elif p_name.strip() == '':
		die("Group must have a non-empty name")

	group = Group(pred.sprint.id, p_name, pred.seq + 1)
	group.save()

	handler.responseCode = 299
	delay(handler, """
<script type=\"text/javascript\">
$(document).ready(function() {
	$('#group%d').effect('highlight', {}, 3000);
});
</script>""" % group.id)
	print "/sprints/%d#group%d" % (group.sprint.id, group.id)
	Event.newGroup(handler, group)
示例#13
0
 def __init__(self):
     Event.__init__(self)
     self.base = 'empires'
     self.desc = """Once per turn: Turn your Journey token over; then if it's face up,
     choose up to 3 differently named cards you have in play and gain a copy of each."""
     self.name = "Pilgrimage"
     self.cost = 4
示例#14
0
class DisposableEntity(object):

    def __init__(self):
        super(DisposableEntity, self).__init__()
        self.onModuleDispose = Event()
        self.__created = False
        self.__disposed = False

    def create(self):
        self.__created = True
        self.__disposed = False
        self._populate()

    def destroy(self):
        if self.__disposed:
            return
        self.onModuleDispose(self)
        self.onModuleDispose.clear()
        self._dispose()
        self.__disposed = True

    def _populate(self):
        pass

    def _dispose(self):
        pass

    def _isCreated(self):
        return self.__created

    def isDisposed(self):
        return self.__disposed
示例#15
0
文件: List.py 项目: nbudin/solidfuel
class List(list):
    def __init__(self, *args, **kwargs):
        list.__init__(self, *args, **kwargs)
        
        # addEvent(pos, item)
        self._addEvent = Event()
        # removeEvent(pos, item)
        self._removeEvent = Event()
        # setitemEvent(pos, item)
        self._setitemEvent = Event()
    
    def __setitem__(self, key, value):
        self._setitemEvent.trigger(key, value)
        return list.__setitem__(self, key, value)
    
    def __delitem__(self, key):
        self._removeEvent.trigger(key, self[key])
        return list.__delitem__(self, key)
    
    def append(self, item):
        self._addEvent.trigger(len(self), item)
        return list.append(self, item)
    
    def insert(self, pos, item):
        self._addEvent.trigger(pos, item)
        return list.insert(self, pos, item)
    
    def pop(self, pos=-1):
        self._removeEvent.trigger(pos, self[pos])
        return list.pop(self, pos)
    
    def remove(self, item):
        pos = self.index(item)
        del self[pos]
示例#16
0
文件: tasks.py 项目: nolandda/Sprint
def newNoteModify(handler, taskid, id, p_action):
    handler.title("New Note")
    requirePriv(handler, "User")

    if p_action != "delete":
        ErrorBox.die("Invalid Action", "Unrecognized action <b>%s</b>" % p_action)

    taskid = int(taskid)
    task = Task.load(taskid)
    if not task or task.sprint.isHidden(handler.session["user"]):
        ErrorBox.die("Invalid Task", "No task with ID <b>%d</b>" % taskid)

    id = int(id)
    note = Note.load(id)
    if not note:
        ErrorBox.die("Invalid Note", "No note with ID <b>%d</b>" % noteid)
    elif note.task != task:  # Doesn't really matter, but shouldn't happen
        ErrorBox.die("Task mismatch", "Note/task mismatch")
    elif note.user != handler.session["user"]:
        ErrorBox.die("Permission denied", "Notes can only be deleted by their creators")

    note.delete()
    delay(handler, SuccessBox("Deleted note", close=3))
    Event.deleteNote(handler, note)
    redirect("/tasks/%d" % task.id)
示例#17
0
class _SettingsCache(object):
    def __init__(self):
        self.__intSettings = IntSettingsRequester()
        self.__waitForSync = False
        self.onSyncStarted = Event()
        self.onSyncCompleted = Event()

    def init(self):
        g_clientUpdateManager.addCallbacks({"intUserSettings": self._onResync})

    def fini(self):
        self.onSyncStarted.clear()
        self.onSyncCompleted.clear()
        g_clientUpdateManager.removeObjectCallbacks(self)

    @property
    def waitForSync(self):
        return self.__waitForSync

    @property
    def settings(self):
        return self.__intSettings

    def _onResync(self, *args):
        self.__invalidateData()

    @async
    def update(self, callback=None):
        self.__invalidateData(callback)

    def getSectionSettings(self, section, defaultValue=0):
        return self.__intSettings.getSetting(section, defaultValue)

    def setSectionSettings(self, section, value):
        self.__intSettings.setSetting(section, value)

    def setSettings(self, settings):
        self.__intSettings.setSettings(settings)

    def getSetting(self, key, defaultValue=0):
        return self.__intSettings.getSetting(key, defaultValue)

    def getVersion(self, defaultValue=0):
        return self.__intSettings.getSetting("VERSION", defaultValue)

    def setVersion(self, value):
        self.__intSettings.setSetting("VERSION", value)

    def __invalidateData(self, callback=lambda *args: None):
        def cbWrapper(*args):
            self.__waitForSync = False
            self.onSyncCompleted()
            callback(*args)

        self.__waitForSync = True
        self.onSyncStarted()
        if BattleReplay.g_replayCtrl.isPlaying:
            cbWrapper(dict())
            return
        self.__intSettings.request()(cbWrapper)
示例#18
0
	def test__addSegment__right_first(self):
		e = Event(1, 1)
		s = ComparableSegment(0, 0, 1, 1)
		e.addSegment(s)
		self.assertEqual(e.right, [s])
		self.assertEqual((e.left, e.inner_inter, e.low, e.high), 
						 ([], [], [], []))
示例#19
0
 def __init__(self, fig, subplot, maxt=1, dt=0.01, ylims = (-1, 1)):
     '''
     Constructor
     '''
     
     self.maxt = maxt
     self.dt = dt
     self.subplot = subplot
     self.ylims = list(ylims)
     
     
     self.tdata = [0]
     
     self.ax = fig.add_subplot(*self.subplot)
     self.ylims_ch()
     self.ax.set_xlim(0, self.maxt)
     self.ax.grid()
     
     self.on_data = Event()
     self.__on_line_upd = Event()
     self.__on_line_rst = Event()
     self.need_stop = False
     
     self.anim = animation.FuncAnimation(fig, self.update, itertools.count, blit=True, event_source=self)
     
     
     
     pass
示例#20
0
文件: admin.py 项目: mrozekma/Sprint
def adminPrivilegesPost(handler, p_grant):
	handler.title("Privileges")
	requirePriv(handler, 'Admin')
	p_grant = {name: privs.keys() for name, privs in p_grant.iteritems()}

	privNames = set()
	for privs in p_grant.values():
		privNames |= set(privs)
	if not privNames <= set(privList.keys()):
		ErrorBox.die("Update privileges", "Unrecognized privilege name")

	for user in User.loadAll():
		for priv in privList:
			privs = p_grant.get(user.username, [])
			has = user.hasPrivilege(priv)
			if has and priv not in privs:
				print "Revoking %s from %s<br>" % (priv, user.username)
				user.privileges.remove(priv)
				Event.revokePrivilege(handler, user, priv)
			elif not has and priv in privs:
				print "Granting %s to %s<br>" % (priv, user.username)
				user.privileges.add(priv)
				Event.grantPrivilege(handler, user, priv, False)
		user.save()
	print "Done"
示例#21
0
def newSprintPost(handler, p_project, p_name, p_start, p_end, p_members = None, p_private = False, p_hidden = False):
	def die(msg):
		print msg
		done()

	handler.wrappers = False
	p_project = int(p_project)
	if not handler.session['user']:
		die("You must be logged in to create a new sprint")

	project = Project.load(p_project)
	if not project:
		die("Unknown project ID: %d" % p_project)

	if p_name == '':
		die("The sprint name cannot be empty")

	try:
		start = re.match("^(\d{1,2})/(\d{1,2})/(\d{4})$", p_start)
		if not start:
			raise ValueError
		month, day, year = map(int, start.groups())
		start = datetime(year, month, day)
	except ValueError:
		die("Malformed start date: %s" % stripTags(p_start))

	try:
		end = re.match("^(\d{1,2})/(\d{1,2})/(\d{4})$", p_end)
		if not end:
			raise ValueError
		month, day, year = map(int, end.groups())
		end = datetime(year, month, day, 23, 59, 59)
	except ValueError:
		die("Malformed end date: %s" % stripTags(p_end))

	msg = Sprint.validateDates(start, end)
	if msg:
		die(msg)

	members = set(User.load(int(memberid)) for memberid in p_members)
	if None in members:
		die("Unknown username")
	if handler.session['user'] not in members:
		die("The scrummaster (%s) must be a sprint member" % handler.session['user'])

	sprint = Sprint(project.id, p_name, handler.session['user'].id, dateToTs(start), dateToTs(end))
	sprint.members |= members
	if p_private or p_hidden:
		sprint.flags.add('private')
	if p_hidden:
		sprint.flags.add('hidden')
	sprint.save()
	# Make a default 'Miscellaneous' group so there's something to add tasks to
	Group(sprint.id, 'Miscellaneous', 1, False).save()
	# Make the standard set of sprint goals
	Goal.newSet(sprint)

	handler.responseCode = 299
	print "/sprints/%d" % sprint.id
	Event.newSprint(handler, sprint)
示例#22
0
 def __init__(self):
     Event.__init__(self)
     self.base = 'empires'
     self.desc = "+1 Buy. Gain a Silver."
     self.name = "Delve"
     self.buys = 1
     self.cost = 2
示例#23
0
文件: tasks.py 项目: nolandda/Sprint
def taskEditPost(handler, ids, p_hours, p_status, p_goal, p_assigned=[], p_include={}):
    handler.title("Edit tasks")
    requirePriv(handler, "Write")

    allIDs = map(int, uniq(ids.split(",")))
    ids = map(lambda i: to_int(i, "include", ErrorBox.die), p_include.keys())
    if not set(ids) <= set(allIDs):
        ErrorBox.die("Included tasks don't match query arguments")

    tasks = dict((id, Task.load(id)) for id in ids)
    if not all(tasks.values()):
        ids = [str(id) for (id, task) in tasks.iteritems() if not task]
        ErrorBox.die(
            "No %s with %s %s"
            % ("task" if len(ids) == 1 else "tasks", "ID" if len(ids) == 1 else "IDs", ", ".join(ids))
        )
    tasks = [tasks[id] for id in ids]
    if len(set(task.sprint for task in tasks)) > 1:
        ErrorBox.die("All tasks must be in the same sprint")
    sprint = (tasks[0] if len(tasks) > 0 else Task.load(allIDs[0])).sprint
    if sprint.isHidden(handler.session["user"]):
        ErrorBox.die(
            "No %s with %s %s"
            % ("task" if len(ids) == 1 else "tasks", "ID" if len(ids) == 1 else "IDs", ", ".join(ids))
        )
    if not sprint.canEdit(handler.session["user"]):
        ErrorBox.die("You don't have permission to modify this sprint")

    assignedids = set(to_int(i, "assigned", ErrorBox.die) for i in p_assigned)

    changes = {
        "assigned": False if assignedids == set() else {User.load(assignedid) for assignedid in assignedids},
        "hours": False if p_hours == "" else int(p_hours),
        "status": False if p_status == "" else p_status,
        "goal": False if p_goal == "" else Goal.load(int(p_goal)),
    }

    if changes["assigned"] and not all(changes["assigned"]):
        ErrorBox.die("Invalid assignee")
    if changes["assigned"] and not set(changes["assigned"]).issubset(sprint.members):
        ErrorBox.die("Unable to assign tasks to non-sprint members")
    if changes["goal"] and changes["goal"].sprint != sprint:
        ErrorBox.die("Unable to set goal to a goal outside the sprint")

    changed = set()
    for task in tasks:
        for field, value in changes.iteritems():
            if value is not False and getattr(task, field) != value:
                setattr(task, field, value)
                changed.add(task)
                Event.taskUpdate(handler, task, field, value)

    if len(changed) == 0:
        delay(handler, WarningBox("No changes necessary", close=3, fixed=True))
    else:
        for task in changed:
            task.saveRevision(handler.session["user"])
        delay(handler, SuccessBox("Updated %d %s" % (len(changed), "task" if len(changed) == 1 else "tasks")))
    redirect("/sprints/%d" % sprint.id)
示例#24
0
def main(json_event):
	json_event
	d = json.loads(json_event)
	uid = d['uid']
	lat = d['lat']
	lon = d['lon']
	timestamp = d['timestamp']
	Event.add(uid, lat, lon, timestamp)
示例#25
0
class _ItemsCache(object):

    def __init__(self):
        self.__items = ItemsRequester()
        self.__waitForSync = False
        self.onSyncStarted = Event()
        self.onSyncCompleted = Event()

    def init(self):
        g_playerEvents.onInventoryResync += self._onResync
        g_playerEvents.onDossiersResync += self._onResync
        g_playerEvents.onStatsResync += self._onResync
        g_playerEvents.onCenterIsLongDisconnected += self._onCenterIsLongDisconnected

    def fini(self):
        self.onSyncStarted.clear()
        self.onSyncCompleted.clear()
        g_playerEvents.onCenterIsLongDisconnected -= self._onCenterIsLongDisconnected
        g_playerEvents.onStatsResync -= self._onResync
        g_playerEvents.onDossiersResync -= self._onResync
        g_playerEvents.onInventoryResync -= self._onResync

    @property
    def waitForSync(self):
        return self.__waitForSync

    @property
    def items(self):
        return self.__items

    @async
    def update(self, diff = None, callback = None):
        self.__invalidateData(diff, callback)

    def clear(self):
        return self.items.clear()

    def _onResync(self, *args):
        if not self.__waitForSync:
            self.__invalidateData()

    def _onCenterIsLongDisconnected(self, isLongDisconnected):
        self.items.dossiers.onCenterIsLongDisconnected(isLongDisconnected)

    def __invalidateData(self, diff = None, callback = lambda *args: None):

        def cbWrapper(*args):
            self.__waitForSync = False
            self.onSyncCompleted()
            callback(*args)

        self.__waitForSync = True
        self.onSyncStarted()
        self.__items.invalidateCache(diff)
        self.__items.request()(cbWrapper)

    def isSynced(self):
        return self.items.isSynced()
示例#26
0
文件: List.py 项目: nbudin/solidfuel
 def __init__(self, *args, **kwargs):
     list.__init__(self, *args, **kwargs)
     
     # addEvent(pos, item)
     self._addEvent = Event()
     # removeEvent(pos, item)
     self._removeEvent = Event()
     # setitemEvent(pos, item)
     self._setitemEvent = Event()
示例#27
0
	def invokeHandler(self, handler, query):
		if self.log:
			filename = handler['fn'].func_code.co_filename
			if filename.startswith(basePath()):
				filename = filename[len(basePath())+1:]
			self.log = LogEntry('rorn.handle', "%s %s" % (self.method.upper(), self.path), userid = self.session['user'].id if self.session['user'] else None, ip = self.client_address[0], location = "%s(%s:%d)" % (handler['fn'].func_code.co_name, filename, handler['fn'].func_code.co_firstlineno))
			Event.pageHandle(self, handler['fn'])

		return super(HTTPHandler, self).invokeHandler(handler, query)
示例#28
0
	def test__addSegment__inner_inter_before(self):
		e = Event(0.5, 0.5)
		s1 = ComparableSegment(0, 0.5, 1, 0.5)
		s2 = ComparableSegment(0, 1, 1, 0)
		e.addSegment(s1)
		e.addSegment(s2)
		self.assertEqual(e.inner_inter, [s2, s1])
		self.assertEqual((e.left, e.right, e.low, e.high), 
						 ([], [], [], []))
示例#29
0
 def __init__(self):
     self.__waitForSync = False
     self.__fortProvider = None
     self.__clanMembersLen = None
     self.__clanMotto = ''
     self.__clanDescription = ''
     self.onSyncStarted = Event()
     self.onSyncCompleted = Event()
     return
示例#30
0
	def test__addSegment__left_after(self):
		e = Event(0, 0)
		s1 = ComparableSegment(0, 0, 1, 1)
		s2 = ComparableSegment(0, 0, 1, 2)
		e.addSegment(s1)
		e.addSegment(s2)
		self.assertEqual(e.left, [s1, s2])
		self.assertEqual((e.right, e.inner_inter, e.low, e.high), 
						 ([], [], [], []))
示例#31
0
import datetime
from Event import Event

name = input("Enter the name")
d1 = input("Enter the date")
datecheck = datetime.datetime.strptime(d1, "%d/%m/%Y").date()

p = Event(name, datecheck)
p.checkDate()
示例#32
0
from Event import Event
from sklearn.model_selection import train_test_split

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
#Reading and balancing data
file = "./magic04.data"
events = []
classCount = 6688
gammaCount = 0

with open(file, "r") as input:
    for x in input:
        y = x.split(",")
        event = Event(y[0], y[1], y[2], y[3], y[4], y[5], y[6], y[7], y[8],
                      y[9], y[10])
        if event.isGamma():
            if gammaCount < classCount:
                gammaCount += 1
                events.append(event)
        else:
            events.append(event)
    input.close()
#splitting data

training, test = train_test_split(events, test_size=0.3, random_state=42)

#preparing data

train_x = []
train_y = []
示例#33
0
 def __init__(self):
     self.__items = ItemsRequester()
     self.__waitForSync = False
     self.onSyncStarted = Event()
     self.onSyncCompleted = Event()
示例#34
0
#event_list.extend( biostats_seminar_scraper.get_events() )
event_list.extend( tumor_boards_scraper.get_events() )
event_list.sort()
cur_event_list = []

# Remove old events
today_date = datetime.now()
for e in event_list:
    start_date = datetime.strptime(e.start_time, '%Y-%m-%dT%H:%M')
    end_date = datetime.strptime(e.end_time, '%Y-%m-%dT%H:%M')
    if start_date >= today_date:
        cur_event_list.append(e)


#Build webpage from event list
templateLoader = jinja2.FileSystemLoader( searchpath="../templates/" )
templateEnv = jinja2.Environment( loader=templateLoader )

TEMPLATE_FILE = "seminar_page_template.html"
template = templateEnv.get_template( TEMPLATE_FILE )

templateVars = { "event_list" : cur_event_list }
outputText = template.render( templateVars ).encode('utf8')

with open('../WWW/bmi_seminars.ics','w') as ics:
    ics.write(Event.to_ics(cur_event_list))

with open('../WWW/seminar_page.html','w') as f:
    f.write(outputText)

示例#35
0
 def __init__(self):
     self.__oldPoints = 0
     self.__oldLevel = 0
     self.__currentMode = None
     self.__eventsManager = EventManager()
     self.__seasonChangeNotifier = SimpleNotifier(self.__getTimeToNotifySeasonChanged, self.__onNotifySeasonChanged)
     self.__extraChapterNotifier = SimpleNotifier(self.__getTimeToExtraChapterExpired, self.__onNotifyExtraChapterExpired)
     self.onPointsUpdated = Event(self.__eventsManager)
     self.onLevelUp = Event(self.__eventsManager)
     self.onBattlePassIsBought = Event(self.__eventsManager)
     self.onSelectTokenUpdated = Event(self.__eventsManager)
     self.onSeasonStateChanged = Event(self.__eventsManager)
     self.onExtraChapterExpired = Event(self.__eventsManager)
     self.onBattlePassSettingsChange = Event(self.__eventsManager)
     self.onFinalRewardStateChange = Event(self.__eventsManager)
     self.onOffersUpdated = Event(self.__eventsManager)
     self.onRewardSelectChange = Event(self.__eventsManager)
     self.onChapterChanged = Event(self.__eventsManager)
     self.__rewardLogic = None
     return
示例#36
0
# Embedded file name: scripts/client/GlobalEvents.py
from Event import BlockingEvent, Event
onChangeLocale = Event()
onRefreshResolutions = Event()
onSetFocus = Event()
onRecreateDevice = Event()
onScreenshot = Event()
onMovieLoaded = Event()
onHideModalScreen = Event()
onHangarLoaded = Event()
onOneSecondTimer = Event()
onKeyEvent = BlockingEvent()
onMouseEvent = BlockingEvent()
onAxisEvent = BlockingEvent()
示例#37
0
 def __init__(self):
     super(ClanNotificationController, self).__init__()
     self.__enabled = False
     self.onClanNotificationUpdated = Event()
示例#38
0
 def __init__(self, name, ownername, noofdays, costperday):
     Event.__init__(self, name, ownername, noofdays, costperday)
示例#39
0
 def __init__(self):
     self.__vehInvID = 0
     self.__changeCallbackID = None
     self.onChanged = Event()
     self.onChangeStarted = Event()
     self.__crew = {}
 def __init__(self):
     self.onSiegeStateChanged = Event()
     self.onRequestFail = Event()
     self.__currentState = VEHICLE_SIEGE_STATE.DISABLED
示例#41
0
 def __init__(self):
     super(VehicleGroupFinder, self).__init__()
     self.__em = EventManager()
     self.onBlocksDataChanged = Event(self.__em)
示例#42
0
 def add_event(self, id_, *args):
     '''add an event to the events queue'''
     self.events.put(Event(id_, *args))
def findOrthologsBySelfGlobalAlignment(strain, coverageTracker, targetStrain):
    print('Performing self-global alignment on strain: %s' %
          (strain.getName()))
    lossEvents = []
    duplicationEvents = []
    sequence = strain.getSequence()

    for x in range(0, len(coverageTracker)):
        #Check if marked
        if coverageTracker[x] == False:
            bestScore = 1000  #Make the best score some large numer
            bestEvent = None  #Initialize the event
            minDistance = 1000  #Used to track the minimum distance from singleton to operon that has an identical gene

            if len(sequence[x].split(',')) > 1:  #This is an operon
                for y in range(0, len(sequence)):
                    #make sure we're not comparing the same operons and that the second operon is NOT  a singleton
                    if x != y and len(sequence[y].split(
                            ',')) > 1 and coverageTracker[y] == True:
                        op1 = sequence[x]
                        op2 = sequence[y]

                        #Gene content differences ie which one has more genes, operons 1 and 2, and the number of unique genes between the operons being compared (ie does the operon have any unique genes)
                        geneContentDifferences, operon1, operon2, numUniqueGenes = formatAndComputeOperonDifferences(
                            op1, op2)
                        #Checks if either operons are in the - orientation
                        negativeOrientationOp1 = reverseSequence(op1)
                        negativeOrientationOp2 = reverseSequence(op2)

                        #Tracks whether we reversed the operons
                        operon1Reversed = False
                        operon2Reversed = False

                        #Create event for this comparison
                        event = Event(0)
                        event.setGenome1Operon(operon1)
                        event.setGenome2Operon(operon2)
                        event.setGenome1Name(strain.getName())
                        event.setGenome2Name(strain.getName())
                        event.isOriginallyNegativeOrientationOp1(
                            negativeOrientationOp1
                        )  #This tracks the original orientation of op1
                        event.isOriginallyNegativeOrientationOp2(
                            negativeOrientationOp2
                        )  #This tracks the original orientation of op2
                        event.setOperon1Index(x)
                        event.setOperon2Index(y)
                        event.setTechnique('Self Global Alignment (Operon)')

                        #If the orientation of the operons does not match, then flip the operon in the negative orientation to the positive orientation
                        if negativeOrientationOp1 != negativeOrientationOp2:
                            if negativeOrientationOp1:
                                operon1.reverse()
                                operon1Reversed = True
                                negativeOrientationOp1 = False

                            if negativeOrientationOp2:
                                operon2.reverse()
                                operon2Reversed = True
                                negativeOrientationOp2 = False

                        if negativeOrientationOp1 != negativeOrientationOp2:
                            print(
                                'Check code! These operons should be in the same orientation!'
                            )
                        #Track whether these operons were reversed
                        event.isReversedOp1(
                            operon1Reversed
                        )  #This tracks whether op1 was reversed
                        event.isReversedOp2(
                            operon2Reversed
                        )  #This tracks whether op2 was reversed
                        event.setAncestralOperonGeneSequence(
                            copy.deepcopy(
                                operon1))  #Set the ancestral operon sequence
                        score, event = performGlobalAlignment(
                            operon1, operon2,
                            event)  #Perform the global alignment
                        event.setScore(score)

                        threshold = max(len(operon1), len(operon2))
                        threshold = threshold // 3
                        if geneContentDifferences <= threshold and score < bestScore:
                            bestScore = score
                            bestEvent = event
            else:  #This is a singleton gene
                for y in range(0, len(sequence)):
                    if x != y and coverageTracker[
                            y] == True:  #Make sure we're not comparing the same singleton genes
                        op1 = sequence[x]
                        op2 = sequence[y]

                        #Gene content differences ie which one has more genes, operons 1 and 2, and the number of unique genes between the operons being compared (ie does the operon have any unique genes)
                        geneContentDifferences, operon1, operon2, numUniqueGenes = formatAndComputeOperonDifferences(
                            op1, op2)
                        #Checks if either operons are in the - orientation
                        negativeOrientationOp1 = reverseSequence(op1)
                        negativeOrientationOp2 = reverseSequence(op2)

                        #Tracks whether we reversed the operons
                        operon1Reversed = False
                        operon2Reversed = False

                        #Create event for this comparison
                        event = Event(0)
                        event.setGenome1Operon(operon1)
                        event.setGenome2Operon(operon2)
                        event.setGenome1Name(strain.getName())
                        event.setGenome2Name(strain.getName())
                        event.isOriginallyNegativeOrientationOp1(
                            negativeOrientationOp1
                        )  #This tracks the original orientation of op1
                        event.isOriginallyNegativeOrientationOp2(
                            negativeOrientationOp2
                        )  #This tracks the original orientation of op2
                        event.setOperon1Index(x)
                        event.setOperon2Index(y)
                        event.setTechnique('Self Global Alignment (Singleton)')

                        #If the orientation of the operons does not match, then flip the operon in the negative orientation to the positive orientation
                        if negativeOrientationOp1 != negativeOrientationOp2:
                            if negativeOrientationOp1:
                                operon1.reverse()
                                operon1Reversed = True
                                negativeOrientationOp1 = False

                            if negativeOrientationOp2:
                                operon2.reverse()
                                operon2Reversed = True
                                negativeOrientationOp2 = False

                        if negativeOrientationOp1 != negativeOrientationOp2:
                            print(
                                'Check code! These operons should be in the same orientation!'
                            )
                        #Track whether these operons were reversed
                        event.isReversedOp1(
                            operon1Reversed
                        )  #This tracks whether op1 was reversed
                        event.isReversedOp2(
                            operon2Reversed
                        )  #This tracks whether op2 was reversed
                        event.setAncestralOperonGeneSequence(
                            copy.deepcopy(
                                operon1))  #Set the ancestral operon sequence

                        if operon1[0] in operon2 and abs(
                                x - y
                        ) < minDistance:  #Checks if the singleton gene is located in the operon and if the distance is smaller
                            minDistance = abs(x - y)
                            event.setScore(0)
                            bestEvent = event

            #Take the event and append it to the duplicate event list
            if bestEvent != None:
                globals.trackingId += 1
                bestEvent.trackingEventId = globals.trackingId
                coverageTracker[x] = True
                duplicationEvents.append(bestEvent)

                #Increment the duplicate counter with size of operon since the operon is a duplication
                #incrementDuplicateSizeCounters([len(event.genome1Operon)])
                strain = addDuplicationEventsToStrain(
                    [len(event.genome1Operon)], strain)

                print('\n&&&&&& Self Global Alignment &&&&&')
                bestEvent.printEvent()
                print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n')
            else:
                coverageTracker[x] = True
                globals.trackingId += 1
                event = Event(globals.trackingId)
                event.setScore(-1)
                event.setGenome2Operon([])
                event.setGenome1Name(strain.getName())
                event.setGenome2Name('None')
                event.isOriginallyNegativeOrientationOp1(
                    reverseSequence(sequence[x]))
                event.isOriginallyNegativeOrientationOp2(False)
                event.setOperon1Index(x)
                event.setOperon2Index(-1)
                event.setTechnique('Self Global Alignment (No match!)')
                event.isReversedOp1(False)
                event.isReversedOp2(False)

                #Set the ancestral operon sequence
                ancestralGenes = []
                operonGenes = sequence[x]
                operonGenes = operonGenes.replace('-', '')
                operonGenes = operonGenes.replace('[', '')
                operonGenes = operonGenes.replace(']', '')
                operonGenesList = operonGenes.split(',')
                for gene in operonGenesList:
                    ancestralGenes.append(gene.strip())
                event.setAncestralOperonGeneSequence(ancestralGenes)
                event.setGenome1Operon(copy.deepcopy(ancestralGenes))
                lossEvents.append(event)

                #Increment the loss counter with the size of the operon since the operon is a loss
                #incrementDeletionSizeCounters([len(event.genome1Operon)])
                targetStrain = addDeletionEventsToStrain(
                    [len(event.genome1Operon)], targetStrain)

                print('\n&&&&&& Self Global Alignment &&&&&')
                event.printEvent()
                print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n')

    return duplicationEvents, lossEvents, coverageTracker, targetStrain, strain
示例#44
0
 def __init__(self, name):
     HttpServer.__init__(self, name, RequestHandler)
     self.dataReceived = Event()
class OperationReceiverBase(object):
    """
    Base class for operations recipient
    """
    __metaclass__ = ABCMeta

    def __init__(self,
                 sender,
                 loadsTransferType,
                 dumpsTransferType,
                 streamer=None):
        """
        Constructor
        @param sender: operation sender
        @type sender: MAILBOX
        @param loadsTransferType: see wgPickle.py
        @param dumpsTransferType: see wgPickle.py
        @param streamer:
        @type streamer: BigWorld.Proxy
        """
        self._sender = sender
        self.__streamer = streamer
        self.__operations = dict()
        self.__loadsTransferType = loadsTransferType
        self.__dumpsTransferType = dumpsTransferType
        self.onOperationRestoredEvent = Event()

    @property
    def sender(self):
        """
        Operation sender
        @rtype: MAILBOX
        """
        return self._sender

    @property
    def operations(self):
        """
        Received operations
        @return: dict of operations
        @rtype: dict
        """
        return self.__operations

    def destroy(self):
        """
        Destructor
        """
        self._sender = None
        self.clearOperations()
        self.__operations = None
        self.__streamer = None
        self.onOperationRestoredEvent.clear()
        self.onOperationRestoredEvent = None
        return

    @noexcept
    def backup(self):
        """
        Backup
        @return: backup data
        """
        data = list()
        for operation in self.__operations.values():
            opData = {
                BACKUP_DATA_KEY.INVOCATION_ID: operation.invocationId,
                BACKUP_DATA_KEY.OPERATION_CODE: operation.operationCode
            }
            if operation.args:
                opData[BACKUP_DATA_KEY.ARGS] = operation.args
            data.append(opData)

        return data

    @noexcept
    def restore(self, backupData):
        """
        Restore
        @param backupData: backup data
        """
        for operationData in backupData:
            operation = ReceivedOperation(
                self, operationData[BACKUP_DATA_KEY.OPERATION_CODE],
                operationData[BACKUP_DATA_KEY.INVOCATION_ID],
                operationData.get(BACKUP_DATA_KEY.ARGS, None))
            operation.onDestroy += self.__onOperationDestroy
            self.__operations[operation.invocationId] = operation
            self.onOperationRestoredEvent(operation)

        return

    @noexcept
    def receiveOperationTimeout(self, invocationId):
        """
        Receives timeout for specific operation
        @param invocationId: invocation id of the received operation
        """
        operation = self.__operations.get(invocationId, None)
        if operation is not None:
            operation.receiveTimeout()
        else:
            LOG_ERROR(
                'Received timeout notification for not existing operation (invocationId = {0})'
                .format(invocationId))
        return

    @noexcept
    def receiveOperation(self, invocationId, operationCode, argStr):
        """
        Receives operation
        @param operationCode: operation code
        @param invocationId: invocation id of the received operation, need for response
        @param argStr: pickled operation arguments
        """
        if self.__operations.has_key(invocationId):
            LOG_ERROR('Received duplicate invocation id ({0} {1})'.format(
                invocationId, self.__operations[invocationId].__dict__))
            self.__operations[invocationId].destroy()
        args = None
        if argStr:
            try:
                args = wgPickle.loads(self.__loadsTransferType, argStr)
                if not isinstance(args, tuple):
                    LOG_ERROR(
                        'Incoming operation args are corrupted (not a tuple)')
                    return
            except Exception:
                LOG_ERROR('Unable to load incoming operation argStr')
                return

        operation = ReceivedOperation(self, operationCode, invocationId, args)
        operation.onDestroy += self.__onOperationDestroy
        self.__operations[operation.invocationId] = operation
        self._onReceiveOperation(operation)
        return

    def _sendOperationResponse(self, operation, returnCode, *args):
        """
        @type operation: ReceivedOperation
        @param returnCode:
        @param args:
        """
        responseData = wgPickle.dumps(self.__dumpsTransferType, args)
        if self.__streamer:
            self.__streamer.toClientReceiveResponse(
                RESPONSE_TYPE.RESPONSE_TYPE_CMD, operation.invocationId,
                returnCode, responseData)
        else:
            self._sender.receiveOperationResponse(operation.invocationId,
                                                  returnCode, responseData)

    @abstractmethod
    def _onReceiveOperation(self, operation):
        """
        Override to implement reaction on operations
        @param operation: received operation
        @type operation: ReceivedOperation
        """
        pass

    def __onOperationDestroy(self, operation):
        del self.__operations[operation.invocationId]

    def clearOperations(self):
        for operation in self.__operations.values():
            operation.onDestroy.clear()
            operation.destroy()

        self.__operations.clear()
        LOG_DEBUG_DEV('clearOperations successed')
 def __init__(self):
     """
     @type self: Avatar.Avatar
     """
     self.eQuestCompleted = Event()
示例#47
0
 buf = stream.read(micConfig.CHUNK)
 if buf:
     micConfig.decoder.process_raw(buf, False, False)
     if micConfig.decoder.get_in_speech() != in_speech_bf:
         in_speech_bf = micConfig.decoder.get_in_speech()
         if not in_speech_bf:
             micConfig.decoder.end_utt()
             result = micConfig.decoder.hyp().hypstr
             print('Result:[%s]' % result)
             if go == True:
                 if result == "exit":
                     break
                 if result == "play music":
                     print("You want me to execute %s" % result + reset)
                     result = "vlc ../static/music.mp3"
                     daemon.add_event(Event(result, False, 0))
                     result = ""
                 if result.startswith("change directory"):
                     print("You want me to execute %s" % result + reset)
                     result = "cd" + result[16:]
                     daemon.add_event(Event(result, False, 0))
                     result = ""
                 if result == "google":
                     print("You want me to execute %s" % result + reset)
                     result = "chromium-browser"
                     daemon.add_event(Event(result, False, 0))
                     result = ""
                 if result == "list":
                     print("You want me to execute %s" % result + reset)
                     result = "ls"
                     daemon.add_event(Event(result, False, 0))
示例#48
0
class Servers(object):
    onServersStatusChanged = Event()

    def __init__(self, loginPreferences):
        self._loginPreferences = loginPreferences
        s = Settings.g_instance
        g_preDefinedHosts.readScriptConfig(s.scriptConfig, s.userPrefs)
        g_preDefinedHosts.onCsisQueryStart += self.__onServerUpdate
        g_preDefinedHosts.onPingPerformed += self.__onServerUpdate
        g_preDefinedHosts.onCsisQueryComplete += self.__onServerUpdate
        if GUI_SETTINGS.csisRequestRate == REQUEST_RATE.ALWAYS:
            g_preDefinedHosts.startCSISUpdate()
        g_preDefinedHosts.requestPing()
        self._serverList = []
        self._selectedServerIdx = 0
        self.updateServerList()

    def fini(self):
        g_preDefinedHosts.stopCSISUpdate()
        g_preDefinedHosts.onCsisQueryStart -= self.__onServerUpdate
        g_preDefinedHosts.onPingPerformed -= self.__onServerUpdate
        g_preDefinedHosts.onCsisQueryComplete -= self.__onServerUpdate
        self._serverList = None
        return

    def updateServerList(self):
        self._setServerList(g_preDefinedHosts.shortList())

    def _setServerList(self, baseServerList):
        self._serverList = []
        self._selectedServerIdx = 0
        serverName = self._loginPreferences['server_name']
        for idx, (hostName, friendlyName, csisStatus,
                  _) in enumerate(baseServerList):
            if serverName == hostName:
                self._selectedServerIdx = idx
            self._serverList.append({
                'label': friendlyName,
                'data': hostName,
                'csisStatus': csisStatus
            })

    def startListenCsisQuery(self, startListen):
        if GUI_SETTINGS.csisRequestRate == REQUEST_RATE.ON_REQUEST:
            if startListen:
                g_preDefinedHosts.startCSISUpdate()
            else:
                g_preDefinedHosts.stopCSISUpdate()
        if startListen:
            g_preDefinedHosts.requestPing(True)

    @property
    def serverList(self):
        return self._serverList

    @property
    def selectedServerIdx(self):
        return self._selectedServerIdx

    @property
    def selectedServer(self):
        return self._serverList[
            self._selectedServerIdx] if self._selectedServerIdx < len(
                self._serverList) else None

    def __onServerUpdate(self, _=None):
        self.updateServerList()
        self.onServersStatusChanged(self._serverList)
示例#49
0
    def _item_parser(self, item, test_url=None):
        """
        Extract fields from source HTML or JSON to create Event from them
        :param item: part of source HTML or JSON which contains information about one event
        :param test_url: uses if method have download additional data from the page of concrete event and parse it
        :return: return list of Events, in most cases it will contain only one item, but if event has several dates,
        every date will have its own Event in the list
        """
        logging.debug('Enter to the method, iter: %s', item)
        events = []

        event = Event()
        # If we cannot get this features (title and url) - we won't work with this event further
        try:
            event.title = item['title']
            event.url = 'https://kudago.com/' + item['location'][
                'slug'] + '/event/' + item['slug']
            event.publication_date = item['publication_date']
        except (KeyError, AttributeError):
            return []
        # This extracting can spawn an exception
        try:
            event.description = item.get('description', None)
            event.price_kudago = item.get('price', None)
            event.price_min, event.price_max = self._get_price_from_string(
                item.get('price', ""), item.get('is_free', ""))
            event.categories = item.get('categories', []) + item.get(
                'tags', [])
            if len(item.get('images', [])) > 0:
                event.image = item['images'][0]['image']
            event.source_rating_count = item.get('favorites_count', None)
        except (KeyError, AttributeError):
            pass
        event.source = "KudaGo"
        event.status = "active"
        event.join_anytime = False

        # Complicate handling of dates
        dates = item.get('dates', [])
        if len(dates) > 1:
            # Firstly we will use unique identifier of the event - url
            # After saving to database we can use our own id
            event.duplicate_source_id = event.url
        for date_of_event in dates:
            event_for_date = copy.deepcopy(event)
            event_for_date.start_time = date_of_event['start']
            event_for_date.finish_time = date_of_event['end']
            events.append(event_for_date)
        if len(dates) == 0:
            event.start_time = 0
            event.finish_time = 0
            events.append(event)
        logging.debug('Events after item parsing: %s', events)
        return events
示例#50
0
def findOrthologsBySelfGlobalAlignment(strain, coverageTracker, sibling):
    if globals.printToConsole:
        print('Performing self-global alignment on strain: %s' % (strain.name))

    lossEvents = []
    duplicationEvents = []
    fragments = strain.genomeFragments

    for i in range(0, len(coverageTracker)):
        if coverageTracker[i] == False:  #Operon has not been marked
            bestScore = -1000  #Make the best score some large numer
            bestEvent = None  #Initialize the event
            minDistance = 1000  #Used to track the minimum distance from singleton to operon that has an identical gene
            bestJ = -999

            filteredList = iter(
                filter(
                    lambda x: x.fragmentIndex == i,
                    fragments))  #Get the fragment we need based on the index
            unmarkedFragment = next(filteredList, None)

            if len(unmarkedFragment.sequence) > 1:  #We're processing an operon
                for j in range(0, len(coverageTracker)):
                    filteredList = iter(
                        filter(lambda x: x.fragmentIndex == j, fragments)
                    )  #Get the fragment we need based on the index
                    currFragment = next(filteredList, None)

                    if i != j and currFragment.isDuplicate == False and len(
                            currFragment.sequence) > 1:
                        op1 = unmarkedFragment.sequence
                        op2 = currFragment.sequence

                        event = Event(0)
                        event.setFragmentDetails1(unmarkedFragment)
                        event.setFragmentDetails2(currFragment)
                        event.setGenome1Name(strain.name)
                        event.setGenome2Name(strain.name)
                        event.setTechnique('Self Global Alignment (Operon)')
                        event.setAncestralOperonGeneSequence(
                            copy.deepcopy(
                                op1))  #Set the ancestral operon sequence
                        score, event = performGlobalAlignment(
                            op1, op2, event)  #Perform the global alignment
                        event.setScore(score)

                        #Compute whether this comparison is interesting
                        #threshold = max(len(op1), len(op2))
                        #threshold = threshold//3
                        #numOperonDifferences = computeOperonDifferences(op1, op2)
                        #if numOperonDifferences <= threshold and score < bestScore:
                        if (score > 0 and score > bestScore) or (
                                score == bestScore
                                and abs(i - j) < minDistance):
                            bestScore = score
                            bestEvent = event
                            minDistance = abs(i - j)
                            bestJ = j
            #Make sure an origin or a terminus doesn't get mapped with a singleton gene
            elif len(
                    unmarkedFragment.sequence
            ) == 1 and unmarkedFragment.description != 'Origin' and unmarkedFragment.description != 'Terminus':
                for j in range(0, len(coverageTracker)):

                    filteredList = iter(
                        filter(lambda x: x.fragmentIndex == j, fragments)
                    )  #Get the fragment we need based on the index
                    currFragment = next(filteredList, None)

                    if i != j and currFragment.isDuplicate == False:

                        op1 = unmarkedFragment.sequence
                        op2 = currFragment.sequence

                        event = Event(0)
                        event.setFragmentDetails1(unmarkedFragment)
                        event.setFragmentDetails2(currFragment)
                        event.setGenome1Name(strain.name)
                        event.setGenome2Name(strain.name)
                        event.setTechnique('Self Global Alignment (Singleton)')
                        event.setAncestralOperonGeneSequence(
                            copy.deepcopy(
                                op1))  #Set the ancestral operon sequence

                        if op1[0] in op2 and abs(
                                i - j
                        ) < minDistance:  #Checks if the singleton gene is located in the operon and if the distance is smaller
                            minDistance = abs(i - j)
                            event.setScore(0)
                            bestEvent = event
                            bestJ = j

            if bestEvent != None:  #A match was found meaning the operon is a duplicate therefor do not add it into the ancestor
                #Handle special case where two unmarked operons are selected as the best matches
                cycleDuplication = False
                if coverageTracker[i] == False and coverageTracker[
                        bestJ] == False:
                    bestEvent.fragmentDetails2.isDuplicate = True
                    coverageTracker[bestJ] = True
                    cycleDuplication = True
                    bestEvent.setScore(-1)
                    bestEvent.setAncestralOperonGeneSequence(
                        copy.deepcopy(bestEvent.fragmentDetails2.sequence)
                    )  #insert source as ancestral operon
                    bestEvent.setTechnique(
                        'Self Global Alignment (Cyclic Duplication!)')
                    lossEvents.append(bestEvent)

                globals.trackingId += 1
                coverageTracker[i] = True
                bestEvent.trackingEventId = globals.trackingId

                if len(bestEvent.fragmentDetails1.sequence) > 1 and len(
                        bestEvent.fragmentDetails2.sequence) > 1:
                    handleDuplicateDetails(bestEvent, strain, sibling,
                                           cycleDuplication)
                else:
                    #Singleton was mapped to an operon
                    if len(bestEvent.fragmentDetails1.sequence) == 1:
                        gene = bestEvent.fragmentDetails1.sequence[0]
                        position = bestEvent.fragmentDetails1.startPositionInGenome
                    else:
                        gene = bestEvent.fragmentDetails2.sequence[0]
                        position = bestEvent.fragmentDetails2.startPositionInGenome
                    tempString = gene + ' ' + str(position) + ';'
                    strain = addDuplicationEventsToStrain(
                        strain, [1], tempString)
                duplicationEvents.append(bestEvent)

                #This is now being handled with the function handleDuplicateDetails
                #duplicationDetails = ''
                #position = bestEvent.fragmentDetails1.startPositionInGenome
                #op = copy.deepcopy(bestEvent.fragmentDetails1.sequence)

                #if bestEvent.fragmentDetails1.isNegativeOrientation == True: #Reverses the genes if the operon was originally negative to ensure the correct position is computed
                #op.reverse()

                #for gene in op:
                #duplicationDetails += gene + ' ' + str(position) + ', '
                #position += 1
                #duplicationDetails = duplicationDetails[0:(len(duplicationDetails) - 2)]
                #duplicationDetails += ';'

                #Increment the duplicate counter with size of operon since the operon is a duplication
                #strain = addDuplicationEventsToStrain(strain, [len(bestEvent.fragmentDetails1.sequence)], duplicationDetails)
                if globals.printToConsole:
                    print('\n&&&&&& Self Global Alignment &&&&&')
                    print(bestEvent.toString())
                    print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n')

            else:  #No match was found therefore it must have been lost in the sibling therefore we include it in the ancestor
                coverageTracker[i] = True
                globals.trackingId += 1

                event = Event(globals.trackingId)
                event.setScore(-1)
                event.setFragmentDetails1(unmarkedFragment)
                event.setFragmentDetails2(unmarkedFragment)
                event.setGenome1Name(strain.name)
                event.setGenome2Name(strain.name)
                event.setTechnique('Self Global Alignment (No match!)')
                event.setAncestralOperonGeneSequence(
                    copy.deepcopy(unmarkedFragment.sequence))
                lossEvents.append(event)

                position = event.fragmentDetails1.startPositionInGenome
                op = copy.deepcopy(event.fragmentDetails1.sequence)

                tempString = ''
                for n in range(0, len(op)):
                    gene = op[n]
                    if event.fragmentDetails1.isNegativeOrientation == False:
                        tempString += gene + ' ' + str(n + position) + ', '
                    else:
                        tempString = gene + ' ' + str(position + len(op) - n -
                                                      1) + ', ' + tempString
                tempString = tempString[0:(
                    len(tempString) - 2)]  #Remove the last comma and space
                tempString += ';'

                #Increment the loss counter with the size of the operon since the operon is a loss
                sibling = addDeletionEventsToStrain(
                    sibling, [len(event.fragmentDetails1.sequence)],
                    tempString)

                if globals.printToConsole:
                    print('\n&&&&&& Self Global Alignment &&&&&')
                    print(event.toString())
                    print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n')

    return duplicationEvents, lossEvents, coverageTracker, strain, sibling
示例#51
0
 def addKeyEvent(self, key, handler):
     if key not in self.__keyEvents:
         self.__keyEvents[key] = Event()
     self.__keyEvents[key] += handler
示例#52
0
 def _getActionHandlers(self, actionId):
     if actionId not in self.__actionHandlers:
         handlers = self.__actionHandlers[actionId] = Event()
     else:
         handlers = self.__actionHandlers[actionId]
     return handlers
示例#53
0
class _ClanCache(object):
    itemsCache = dependency.descriptor(IItemsCache)

    def __init__(self):
        self.__waitForSync = False
        self.__strongholdProvider = None
        self.__missionsProvider = None
        self.__clanMembersLen = None
        self.__clanMotto = ''
        self.__clanDescription = ''
        self.onSyncStarted = Event()
        self.onSyncCompleted = Event()
        return

    def init(self):
        from gui.shared.stronghold.stronghold_provider import ClientStrongholdProvider
        self.__strongholdProvider = ClientStrongholdProvider()
        from gui.shared.missions.missions_provider import ClientMissionsProvider
        self.__missionsProvider = ClientMissionsProvider()

    def fini(self):
        self.onSyncStarted.clear()
        self.onSyncCompleted.clear()
        self.clear()
        self.__strongholdProvider = None
        self.__missionsProvider = None
        return

    def onAccountShowGUI(self):
        self.__startStrongholdProvider()
        self.__startMissionsProvider()

    def onAvatarBecomePlayer(self):
        self.__stopStrongholdProvider()
        self.__stopMissionsProvider()

    def onDisconnected(self):
        self.__stopStrongholdProvider()
        self.__stopMissionsProvider()

    @property
    def waitForSync(self):
        return self.__waitForSync

    @async
    def update(self, diff = None, callback = None):
        self.__invalidateData(diff, callback)

    def clear(self):
        if self.__strongholdProvider is not None:
            self.__strongholdProvider.stop()
        if self.__missionsProvider is not None:
            self.__missionsProvider.stop()
        return

    @storage_getter('users')
    def usersStorage(self):
        return None

    @property
    def clanDBID(self):
        return self.itemsCache.items.stats.clanDBID

    @property
    def isInClan(self):
        """
        @return: is current player in clan
        """
        return self.clanDBID is not None and self.clanDBID != 0

    @property
    def clanMembers(self):
        members = set()
        if self.isInClan:
            members = set(self.usersStorage.getClanMembersIterator(False))
        return members

    @property
    def clanInfo(self):
        info = self.itemsCache.items.stats.clanInfo
        if info and len(info) > 1:
            return info
        else:
            return (None, None, -1, 0, 0)

    @property
    def clanName(self):
        return passCensor(html.escape(self.clanInfo[0]))

    @property
    def clanAbbrev(self):
        return self.clanInfo[1]

    @property
    def clanMotto(self):
        return self.__clanMotto

    @property
    def clanDescription(self):
        return self.__clanDescription

    @property
    def clanTag(self):
        result = self.clanAbbrev
        if result:
            return '[%s]' % result
        return result

    @property
    def clanCommanderName(self):
        for member in self.clanMembers:
            if member.getClanRole() == CLAN_MEMBER_FLAGS.LEADER:
                return member.getName()

        return None

    @property
    def clanRole(self):
        user = self.usersStorage.getUser(getAccountDatabaseID())
        if user:
            role = user.getClanRole()
        else:
            role = 0
        return role

    @property
    def isClanLeader(self):
        return self.clanRole == CLAN_MEMBER_FLAGS.LEADER

    @async
    @process
    def getClanEmblemID(self, callback):
        clanEmblem = None
        if self.isInClan:
            tID = 'clanInfo' + BigWorld.player().name
            clanEmblem = yield self.getClanEmblemTextureID(self.clanDBID, False, tID)
        callback(clanEmblem)
        return

    @async
    def getFileFromServer(self, clanId, fileType, callback):
        if not BigWorld.player().serverSettings['file_server'].has_key(fileType):
            LOG_ERROR("Invalid server's file type: %s" % fileType)
            self._valueResponse(0, (None, None), callback)
            return None
        else:
            clan_emblems = BigWorld.player().serverSettings['file_server'][fileType]
            BigWorld.player().customFilesCache.get(clan_emblems['url_template'] % clanId, lambda url, file: self._valueResponse(0, (url, file), callback), True)
            return None

    @async
    @process
    def getClanEmblemTextureID(self, clanDBID, isBig, textureID, callback):
        import imghdr
        if clanDBID is not None and clanDBID != 0:
            _, clanEmblemFile = yield self.getFileFromServer(clanDBID, 'clan_emblems_small' if not isBig else 'clan_emblems_big')
            if clanEmblemFile and imghdr.what(None, clanEmblemFile) is not None:
                BigWorld.wg_addTempScaleformTexture(textureID, clanEmblemFile)
                callback(textureID)
                return
        callback(None)
        return

    def getClanRoleUserString(self):
        position = self.clanInfo[3]
        return getClanRoleString(position)

    def onClanInfoReceived(self, clanDBID, clanName, clanAbbrev, clanMotto, clanDescription):
        self.__clanMotto = passCensor(html.escape(clanMotto))
        self.__clanDescription = passCensor(html.escape(clanDescription))

    def _valueResponse(self, resID, value, callback):
        if resID < 0:
            LOG_ERROR('[class %s] There is error while getting data from cache: %s[%d]' % (self.__class__.__name__, code2str(resID), resID))
            return callback(value)
        callback(value)

    def _onResync(self):
        if not self.__waitForSync:
            self.__invalidateData()

    def __invalidateData(self, diff = None, callback = lambda *args: None):
        callback(True)

    def __startStrongholdProvider(self):
        self.__strongholdProvider.start()

    def __stopStrongholdProvider(self):
        self.__strongholdProvider.stop()

    def __startMissionsProvider(self):
        self.__missionsProvider.start()

    def __stopMissionsProvider(self):
        self.__missionsProvider.stop()

    def __me_onClanMembersListChanged(self):
        clanMembersLen = len(self.clanMembers)
        if self.__clanMembersLen is not None and clanMembersLen != self.__clanMembersLen:
            self.__clanMembersLen = clanMembersLen
        return
示例#54
0
    def convert(self):
        """
        Reads all selected events from input trees and stores requested features in arrays prepared in the constructor.
        """

        total_count = 0

        for file_name, tree in self.trees.items():

            input_type = self.input_types[file_name]
            data_processor = DataProcessor(tree, input_type)

            print(
                "\n\n=======================================================")
            print("Loading events from file: ", file_name)
            print("Input type was recognised to be: ", input_type)

            for iEvent in self.selections[file_name]:
                print("\n\n------------------------------")
                print("Event: ", iEvent)

                # load event
                event = Event(data_processor, iEvent, self.jet_delta_r)
                event.print()

                # check event properties
                if event.nJets < 2:
                    print("WARNING -- event has less than 2 jets! Skipping...")
                    print("------------------------------\n\n")
                    continue

                if event.has_jets_with_no_constituents(self.max_n_jets):
                    print(
                        "WARNING -- one of the jets that should be stored has no constituents. Skipping..."
                    )
                    continue

                if not event.are_jets_ordered_by_pt():
                    print(
                        "WARNING -- jets in the event are not ordered by pt! Skipping..."
                    )
                    continue

                # fill feature arrays
                self.output_arrays[OutputTypes.EventFeatures][
                    total_count, :] = np.asarray(event.get_features())

                for iJet, jet in enumerate(event.jets):
                    if iJet == self.max_n_jets:
                        break

                    self.output_arrays[OutputTypes.JetFeatures][
                        total_count, iJet, :] = jet.get_features()

                    if self.save_outputs[OutputTypes.JetConstituents]:
                        self.output_arrays[OutputTypes.JetConstituents][
                            total_count, iJet, :] = jet.get_constituents(
                                self.max_n_constituents)

                    if self.save_outputs[OutputTypes.EPFs]:
                        self.output_arrays[OutputTypes.EPFs][
                            total_count, iJet, :] = jet.get_EFPs(self.efpset)

                total_count += 1
                print("------------------------------\n\n")

            print(
                "\n\n=======================================================")

        # remove redundant rows for events that didn't meet some criteria
        for output_type in OutputTypes:
            for i in range(0, self.n_events - total_count):
                self.output_arrays[output_type] = np.delete(
                    self.output_arrays[output_type], -1, axis=0)
示例#55
0
 def __init__(self):
     super(AbstractLock, self).__init__()
     self.onLocked = Event()
     self.onUnlocked = Event()
示例#56
0
    def __init__(self, input_path, store_n_jets, jet_delta_r,
                 max_n_constituents, efp_degree):
        """
        Reads input trees, recognizes input types, initializes EFP processor and prepares all arrays needed to
        store output variables.
        """

        self.set_input_paths_and_selections(input_path=input_path)

        # read files, trees and recognize input type
        self.files = {
            path: uproot.open(path)
            for path in self.input_file_paths
        }
        self.trees = {}
        self.input_types = {}
        self.read_trees()
        self.n_all_events = sum(
            [tree.num_entries for tree in self.trees.values()])
        self.n_events = sum(map(len, list(self.selections.values()))) + 1

        print("Found {0} file(s)".format(len(self.files)))
        print("Found {0} tree(s)".format(len(self.trees)))
        print("Found ", self.n_events - 1,
              " selected events, out of a total of ", self.n_all_events)

        # set internal parameters
        self.jet_delta_r = jet_delta_r
        self.max_n_constituents = max_n_constituents if max_n_constituents > 0 else 100
        self.max_n_jets = store_n_jets
        self.EFP_size = 0

        # initialize EFP set
        if efp_degree >= 0:
            print(
                "\n\n=======================================================")
            print("Creating energyflow particle set with degree d <= {0}...".
                  format(efp_degree))
            self.efpset = ef.EFPSet("d<={0}".format(efp_degree),
                                    measure='hadr',
                                    beta=1.0,
                                    normed=True,
                                    verbose=True)
            self.EFP_size = self.efpset.count()
            print("EFP set is size: {}".format(self.EFP_size))
            print(
                "=======================================================\n\n")

        # prepare arrays for event & jet features, EFPs and jet constituents

        self.output_arrays = {
            OutputTypes.EventFeatures:
            np.empty((self.n_events, len(Event.get_features_names()))),
            OutputTypes.JetFeatures:
            np.empty((self.n_events, self.max_n_jets,
                      len(Jet.get_feature_names()))),
            OutputTypes.JetConstituents:
            np.empty((self.n_events, self.max_n_jets, self.max_n_constituents,
                      len(Jet.get_constituent_feature_names()))),
            OutputTypes.EPFs:
            np.empty((self.n_events, self.max_n_jets, self.EFP_size))
        }

        self.output_names = {
            OutputTypes.EventFeatures: "event_features",
            OutputTypes.JetFeatures: "jet_features",
            OutputTypes.JetConstituents: "jet_constituents",
            OutputTypes.EPFs: "jet_eflow_variables"
        }

        self.output_labels = {
            OutputTypes.EventFeatures: Event.get_features_names(),
            OutputTypes.JetFeatures: Jet.get_feature_names(),
            OutputTypes.JetConstituents: Jet.get_constituent_feature_names(),
            OutputTypes.EPFs: [str(i) for i in range(self.EFP_size)]
        }

        self.save_outputs = {
            OutputTypes.EventFeatures: True,
            OutputTypes.JetFeatures: True,
            OutputTypes.JetConstituents:
            False if max_n_constituents < 0 else True,
            OutputTypes.EPFs: False if efp_degree < 0 else True
        }
示例#57
0
 def __init__(self):
     self.OnStatsAccountBecomePlayer = Event()
     self.OnStatsBattleLoaded        = Event()
     self.OnStatsFullBattleLoaded    = Event()
示例#58
0
 def __init__(self):
     self.OnAsyncReports = Event()
     self.__timeDelay = 0.5
示例#59
0
class _CurrentVehicle():
    def __init__(self):
        self.__vehInvID = 0
        self.__changeCallbackID = None
        self.onChanged = Event()
        self.onChangeStarted = Event()
        self.__crew = {}

    def init(self):
        g_clientUpdateManager.addCallbacks({'inventory': self.onInventoryUpdate,
         'cache.vehsLock': self.onLocksUpdate})
        prbVehicle = self.__checkPrebattleLockedVehicle()
        storedVehInvID = AccountSettings.getFavorites(CURRENT_VEHICLE)
        self.selectVehicle(prbVehicle or storedVehInvID)

    def destroy(self):
        self.__vehInvID = 0
        self.__clearChangeCallback()
        self.onChanged.clear()
        self.onChangeStarted.clear()
        g_clientUpdateManager.removeObjectCallbacks(self)
        g_hangarSpace.removeVehicle()
        self.selectNoVehicle()

    def onInventoryUpdate(self, invDiff):
        vehsDiff = invDiff.get(GUI_ITEM_TYPE.VEHICLE, {})
        isVehicleSold = False
        isVehicleDescrChanged = False
        if 'compDescr' in vehsDiff and self.__vehInvID in vehsDiff['compDescr']:
            isVehicleSold = vehsDiff['compDescr'][self.__vehInvID] is None
            isVehicleDescrChanged = not isVehicleSold
        if isVehicleSold or self.__vehInvID == 0:
            self.selectVehicle()
        elif 'repair' in vehsDiff:
            isRepaired = self.__vehInvID in vehsDiff['repair']
            if not GUI_ITEM_TYPE.TURRET in invDiff:
                isComponentsChanged = GUI_ITEM_TYPE.GUN in invDiff
                isVehicleChanged = len(filter(lambda hive: self.__vehInvID in hive, vehsDiff.itervalues())) > 0
                (isComponentsChanged or isRepaired or isVehicleDescrChanged) and self.refreshModel()
            (isVehicleChanged or isRepaired) and self.onChanged()

        if self.isPresent():
            self.__updateViewRange()

    def onLocksUpdate(self, locksDiff):
        if self.__vehInvID in locksDiff:
            self.refreshModel()

    def refreshModel(self):
        if self.isPresent() and self.isInHangar() and self.item.modelState:
            g_hangarSpace.updateVehicle(self.item)
        else:
            g_hangarSpace.removeVehicle()

    @property
    def invID(self):
        return self.__vehInvID

    @property
    def item(self):
        if self.__vehInvID > 0:
            return g_itemsCache.items.getVehicle(self.__vehInvID)
        else:
            return None

    def isPresent(self):
        return self.item is not None

    def isBroken(self):
        return self.isPresent() and self.item.isBroken

    def isDisabledInRoaming(self):
        return self.isPresent() and self.item.isDisabledInRoaming

    def isLocked(self):
        return self.isPresent() and self.item.isLocked

    def isClanLock(self):
        return self.isPresent() and self.item.clanLock > 0

    def isCrewFull(self):
        return self.isPresent() and self.item.isCrewFull

    def isInBattle(self):
        return self.isPresent() and self.item.isInBattle

    def isInHangar(self):
        return self.isPresent() and not self.item.isInBattle

    def isAwaitingBattle(self):
        return self.isPresent() and self.item.isAwaitingBattle

    def isAlive(self):
        return self.isPresent() and self.item.isAlive

    def isReadyToPrebattle(self):
        return self.isPresent() and self.item.isReadyToPrebattle

    def isReadyToFight(self):
        return self.isPresent() and self.item.isReadyToFight

    def isAutoLoadFull(self):
        if self.isPresent() and self.item.isAutoLoad:
            for shell in self.item.shells:
                if shell.count != shell.defaultCount:
                    return False

        return True

    def isAutoEquipFull(self):
        if self.isPresent() and self.item.isAutoEquip:
            return self.item.eqs == self.item.eqsLayout
        return True

    def selectVehicle(self, vehInvID = 0):
        vehicle = g_itemsCache.items.getVehicle(vehInvID)
        if vehicle is None:
            invVehs = g_itemsCache.items.getVehicles(criteria=REQ_CRITERIA.INVENTORY)
            if len(invVehs):
                vehInvID = sorted(invVehs.itervalues())[0].invID
            else:
                vehInvID = 0
        self.__selectVehicle(vehInvID)
        return

    def selectNoVehicle(self):
        self.__selectVehicle(0)

    def getHangarMessage(self):
        if self.isPresent():
            state, stateLvl = self.item.getState()
            return ('#menu:currentVehicleStatus/' + state, stateLvl)
        return (MENU.CURRENTVEHICLESTATUS_NOTPRESENT, Vehicle.VEHICLE_STATE_LEVEL.CRITICAL)

    def __selectVehicle(self, vehInvID):
        if vehInvID == self.__vehInvID:
            return
        Waiting.show('updateCurrentVehicle', isSingle=True)
        self.onChangeStarted()
        self.__vehInvID = vehInvID
        AccountSettings.setFavorites(CURRENT_VEHICLE, vehInvID)
        self.refreshModel()
        if not self.__changeCallbackID:
            self.__changeCallbackID = BigWorld.callback(0.1, self.__changeDone)

        if self.isPresent():
            self.__updateViewRange()

    def __updateViewRange(self):
        # Set Defaults
        xvm_conf = {}

        # Load configuration
        xvm_configuration_file = os.getcwd() + os.sep + 'res_mods' + os.sep + 'xvm' + os.sep + 'tankrange.xc'
        if not os.path.exists(xvm_configuration_file):
            LOG_NOTE("Configuration file missing (" + xvm_configuration_file + "). Creating.")
        else:
            data = ""
            blockComment = False

            f = codecs.open(xvm_configuration_file, 'r', '"utf-8-sig"')
            for line in f.read().split('\n'):
                line = line.strip()
                if line != "":
                    # Start of block comment
                    comment = line.find("/*")
                    if comment != -1 and comment == 0:
                        blockComment = True
                        continue

                    # End of block comment
                    comment = line.find("*/")
                    if comment != -1:
                        blockComment = False
                        continue

                    # Block Comment
                    if blockComment == True:
                        continue

                    # Start of line comment
                    comment = line.find("//")
                    if comment != -1 and comment == 0:
                        continue

                    # Remove end of line comments
                    position = 0
                    for i in range(0,line.count("//")):
                        comment = line.find("//", position+2)
                        if comment != -1:
                            colon = line.find(":")

                            startSpeach = line.find("\"", colon+1)
                            if startSpeach > comment:
                                line = line[:comment].strip()

                            endSpeach = line.find("\"", startSpeach+1)
                            if comment > endSpeach:
                                line = line[:comment].strip()

                        position += comment

                    if line != "":
                        data += line + '\n'
            f.close()

            xvm_conf = json.loads(data)

        # add spotting_limit option to old configs (new in 1.6)
        if not xvm_conf["tankrange"].has_key("spotting_limit"):
             LOG_NOTE("add missing spotting_limit option")
             xvm_conf["tankrange"]["spotting_limit"] = True

        # Get name
        tank_name = g_itemsCache.items.getVehicle(self.__vehInvID).descriptor.type.name.split(":")[1].lower().replace("-","_")
        if xvm_conf["tankrange"]["logging"]:
            LOG_NOTE("Tank Name: ", tank_name)

        # without a crew calculation Cancel
        if not self.isCrewFull():
            if xvm_conf['tankrange']['logging']:
                LOG_NOTE('no full crew')
            return

        # Remove current circles
        remaining = []
        for tank_data in xvm_conf["circles"]["special"]:
            if tank_data.keys()[0] != tank_name:
                remaining.append(tank_data)
        xvm_conf["circles"]["special"] = remaining

        # Get type
        if xvm_conf["tankrange"]["ignore_artillery"] and "SPG" in g_itemsCache.items.getVehicle(self.__vehInvID).descriptor.type.tags:
            f = codecs.open(xvm_configuration_file, 'w', '"utf-8-sig"')
            f.write(unicode(json.dumps(xvm_conf, ensure_ascii=False, indent=2)))
            f.close()

            if xvm_conf["tankrange"]["logging"]:
                LOG_NOTE("Ignoring " + vehicle_type + " tank.")
            return

        # Get view distance
        view_distance = g_itemsCache.items.getVehicle(self.__vehInvID).descriptor.turret["circularVisionRadius"]
        if xvm_conf["tankrange"]["logging"]:
            LOG_NOTE("Base View Range: ", view_distance)

        # Check for Ventilation
        ventilation = self.__isOptionalEquipped("improvedVentilation")
        if xvm_conf["tankrange"]["logging"] and ventilation:
            LOG_NOTE("Ventilation Found")

        # Check for Consumable
        consumable = self.__isConsumableEquipped("ration")
        if xvm_conf["tankrange"]["logging"] and consumable:
            LOG_NOTE("Premium Consumable Found")

        # Update crew
        self.__updateCrew()

        # Check for Brothers In Arms
        brothers_in_arms = True
        if len(self.__crew) == 0:
            brothers_in_arms = False
        else:
            for name, data in self.__crew.iteritems():
                if "brotherhood" not in data["skill"]:
                    brothers_in_arms = False

        if xvm_conf["tankrange"]["logging"] and brothers_in_arms:
            LOG_NOTE("BIA Found")

        # Calculate commander bonus
        commander_skill = 0
        if "commander" in self.__crew:
            commander_skill = self.__crew["commander"]["level"]

            if brothers_in_arms == True:
                commander_skill += 5
            if ventilation == True:
                commander_skill += 5
            if consumable == True:
                commander_skill += 10

            if xvm_conf["tankrange"]["logging"]:
                LOG_NOTE("Commander Skill: ", commander_skill)

        # Calculate other bonuses
        other_bonus = 1.0
        for name, data in self.__crew.iteritems():
            # Calculate recon skills
            if "commander_eagleEye" in data["skill"]:
                other_bonus *= 1.0 + ( 0.0002 * data["skill"]["commander_eagleEye"] )

                if xvm_conf["tankrange"]["logging"]:
                    LOG_NOTE("Recon Bonus: ", 1.0 + ( 0.0002 * data["skill"]["commander_eagleEye"] ))

            # Calculate Situational Awareness Skill
            if "radioman_finder" in data["skill"]:
                other_bonus *= 1.0 + ( 0.0002 * data["skill"]["radioman_finder"] )

                if xvm_conf["tankrange"]["logging"]:
                    LOG_NOTE("Situational Awareness Bonus: ", 1.0 + ( 0.0003 * data["skill"]["radioman_finder"] ))

        # Check for Binoculars
        binoculars = self.__isOptionalEquipped("stereoscope")
        if xvm_conf["tankrange"]["logging"] and binoculars:
            LOG_NOTE("Binoculars Found")

        # Check for Coated Optics
        coated_optics = self.__isOptionalEquipped("coatedOptics")
        if xvm_conf["tankrange"]["logging"] and coated_optics:
            LOG_NOTE("Coated Optics Found")

        # Calculate final value
        view_distance = ((view_distance / 0.875) * (0.00375* commander_skill + 0.5)) * other_bonus

        if xvm_conf["tankrange"]["logging"]:
            LOG_NOTE("Other Bonus:", other_bonus)
            LOG_NOTE("Final View Range: ", view_distance)

        # Add binocular Circles
        if xvm_conf["tankrange"]["circle_binocular"]["enabled"] and binoculars:
            binocular_distance = view_distance * 1.25
            if xvm_conf["tankrange"]["spotting_limit"]:
                binocular_distance = min(445, binocular_distance);

            if not xvm_conf["tankrange"]["circle_binocular"]["filled"]:
                xvm_conf["circles"]["special"].append({ tank_name: { "$ref": { "path": "tankrange.circle_binocular" }, "distance": binocular_distance } })
            else:
                xvm_conf["circles"]["special"].append({ tank_name: { "$ref": { "path": "tankrange.circle_binocular" }, "thickness": (binocular_distance*0.25)-14, "distance": binocular_distance*0.5 } })

        # Add standard Circles
        if coated_optics == True:
            view_distance = min(view_distance * 1.1, 500)

        if xvm_conf["tankrange"]["circle_view"]["enabled"]:
            if xvm_conf["tankrange"]["spotting_limit"]:
                view_distance = min(445, view_distance);

            if not xvm_conf["tankrange"]["circle_view"]["filled"]:
                xvm_conf["circles"]["special"].append({ tank_name: { "$ref": { "path": "tankrange.circle_view" }, "distance": view_distance } })
            else:
                xvm_conf["circles"]["special"].append({ tank_name: { "$ref": { "path": "tankrange.circle_view" }, "thickness": (view_distance*0.25)-14, "distance": view_distance*0.5 } })


        # Add Artillery Range
        if xvm_conf["tankrange"]["circle_artillery"]["enabled"] and "SPG" in g_itemsCache.items.getVehicle(self.__vehInvID).descriptor.type.tags:
            artillery_range = 0
            for shell in g_itemsCache.items.getVehicle(self.__vehInvID).descriptor.gun["shots"]:
                artillery_range = max(artillery_range, round(math.pow(shell["speed"],2) / shell["gravity"]))

            if xvm_conf["tankrange"]["logging"]:
                LOG_NOTE("Calculated Firing Range:", artillery_range)

            if not xvm_conf["tankrange"]["circle_artillery"]["filled"]:
                xvm_conf["circles"]["special"].append({ tank_name: { "$ref": { "path": "tankrange.circle_artillery" }, "distance": artillery_range } })
            else:
                xvm_conf["circles"]["special"].append({ tank_name: { "$ref": { "path": "tankrange.circle_artillery" }, "thickness": (artillery_range*0.25)-14, "distance": artillery_range*0.5 } })

        # Write result
        f = codecs.open(xvm_configuration_file, 'w', '"utf-8-sig"')
        f.write(unicode(json.dumps(xvm_conf, ensure_ascii=False, indent=2, sort_keys=True)))
        f.close()

    @process
    def __updateCrew(self):
        from gui.shared.utils.requesters import Requester
        self.__crew.clear()

        barracks = yield Requester('tankman').getFromInventory()
        for tankman in barracks:
            for crewman in self.item.crew:
                if crewman[1] is not None and crewman[1].invID == tankman.inventoryId:
                    crew_member = { "level": tankman.descriptor.roleLevel, "skill": {} }

                    skills = []
                    for skill_name in tankman.descriptor.skills:
                        skills.append({ "name": skill_name, "level": 100 })

                    if len(skills) != 0:
                        skills[-1]["level"] = tankman.descriptor.lastSkillLevel

                    for skill in skills:
                        crew_member["skill"][skill["name"]] = skill["level"]

                    self.__crew[tankman.descriptor.role] = crew_member

    def __isOptionalEquipped(self, optional_name):
        for item in self.item.descriptor.optionalDevices:
            if item is not None and optional_name in item.name:
                return True
        return False

    def __isConsumableEquipped(self, consumable_name):
        from gui.shared.utils.requesters import VehicleItemsRequester

        for item in self.item.eqsLayout:
            if item is not None and consumable_name in item.descriptor.name:
                return True
        return False

    def __changeDone(self):
        self.__clearChangeCallback()
        if isPlayerAccount():
            self.onChanged()
        Waiting.hide('updateCurrentVehicle')

    def __clearChangeCallback(self):
        if self.__changeCallbackID is not None:
            BigWorld.cancelCallback(self.__changeCallbackID)
            self.__changeCallbackID = None

    def __checkPrebattleLockedVehicle(self):
        clientPrb = prb_control.getClientPrebattle()
        if clientPrb is not None:
            rosters = prb_control.getPrebattleRosters(prebattle=clientPrb)
            for rId, roster in rosters.iteritems():
                if BigWorld.player().id in roster:
                    vehCompDescr = roster[BigWorld.player().id].get('vehCompDescr', '')
                    if len(vehCompDescr):
                        vehDescr = vehicles.VehicleDescr(vehCompDescr)
                        vehicle = g_itemsCache.items.getItemByCD(vehDescr.type.compactDescr)
                        if vehicle is not None:
                            return vehicle.invID

        return 0

    def __repr__(self):
        return 'CurrentVehicle(%s)' % str(self.item)
        sendSocket.send(sentence.encode('utf-8'))
        sendSocket.close()


if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    sm = SubscriptionManager()
    from Subscription import Subscription
    s1 = Subscription(topic='t1', subscriberIdentifier='s1', bootid=1)
    s2 = Subscription(topic='t2', subscriberIdentifier='s2', bootid=1)
    s3 = Subscription(topic='t1', subscriberIdentifier='s3', bootid=1)
    s4 = Subscription(topic='t4', subscriberIdentifier='s4', bootid=1)

    #sm.addSubscription(s1)
    #sm.addSubscription(s2)
    #sm.addSubscription(s3)
    #sm.addSubscription(s4)

    #print(sm.subs)

    ss = SubscriptionService()
    from Event import Event
    e1 = Event('t1')
    #ss.onEvent(e1)

    from flask import Flask
    path = '/home/pi/Desktop/api/deviceInformations'
    app = Flask(__name__, static_folder=path, static_url_path='')
    app.register_blueprint(ss.api)
    app.run(host='0.0.0.0')