Exemple #1
0
	def syncDiscProceed(self):
		
		src = str(self.uic.Source.text())
		dst = str(self.uic.DestinationPath.text())
		
		if platform.system() == 'Windows':
			srcsplit = src.split(':')
			src = '/cygdrive/'+srcsplit[0].lower()+(''.join(srcsplit[1:]).replace('\\','/'))
		if platform.system() == 'Windows':
			dstsplit = dst.split(':')
			dst = '/cygdrive/'+dstsplit[0].lower()+(''.join(dstsplit[1:]).replace('\\','/'))
			c = wmi.WMI()
			serial = c.Win32_LogicalDisk(["VolumeSerialNumber"], Caption = dstsplit[0].upper()+":")
			if(not serial):
				serial = None
			else:
				serial = serial[0].VolumeSerialNumber
			
		syncadd= {'Address':None,
				  'Username':None,
				  'Password':None,
				  'Transportation':None,
				  'SyncName':self.syncname,
				  'Source':src,
				  'Destination':dst,
				  'RsyncUsername':None,
				  'RsyncPassword':None,
				  'DiskID':serial}
				  
		dispatcher.dispatch('SyncAdd',syncadd)
		dispatcher.dispatch('InfoMsg','A New Sync has been added!')
		self.stackedWidget.setCurrentWidget(self.uic.Start)
Exemple #2
0
 def handle_read(self):
     try:
         self.read_buffer += self.recv(2)
     except socket.error:
         return
     while len(self.read_buffer) > 0:
         dispatch(self, self.protodef)
Exemple #3
0
	def servercheck(self):
		# rsync --contimeout=3 servername::
		self.serverlistlock.acquire()
		if len(self.serverlist) == 0:
			disp.dispatch('ServerStatus',0)
			self.serverlistlock.release()
			return 0
		for key in self.serverlist:
			if self.servertime[key] > 0:
				self.servertime[key]-=1
				continue
			print('Checking server %s'%(key))
			addr = self.serverlist[key]['Address']
			cmd = rsyncexec(cmd=self.config['RsyncCmd'],src='',dst=addr+"::",args=['--contimeout=3'])
			ret = cmd.verify_connection(3)
			if(ret == 0):
				self.servertime[key] = self.onlinepolling
				if not key in self.activeservers:
					self.activeservers.append(key)
			else:
				self.servertime[key] = self.offlinepolling
				if key in self.activeservers:
					self.activeservers.remove(key)

		servercount = len(self.activeservers)
		if servercount == len(self.serverlist):
			disp.dispatch('ServerStatus',2)
		elif servercount != 0:
			disp.dispatch('ServerStatus',1)
		else:
			disp.dispatch('ServerStatus',0)
			
		self.serverlistlock.release()
Exemple #4
0
def build():
    try:
        for t in targets.targets:
            dispatcher.dispatch(t)
    except OSError as e:
        if (verbose_except):
            raise
        else:
            print e.strerror
    except Exception as e:
        if (verbose_except):
            raise
        else:
            print e
Exemple #5
0
def build():
    try:
        for t in targets.targets:
            dispatcher.dispatch(t)
    except OSError as e:
        if (verbose_except):
            raise
        else:
            print e.strerror
    except Exception as e:
        if (verbose_except):
            raise
        else:
            print e
Exemple #6
0
    def on_chat_message(self, msg):
        # try:
            with open("log.txt", "a", encoding="utf-8") as f:
                f.write(str(msg) + '\n')
            pprint(msg)
            self.first_name = msg["from"]["first_name"]
            # By writing "state", the state will be shown
            # if msg["text"] is None:
            #     return
            if "text" in msg.keys():
                if msg["text"] == "state":
                    self.sender.sendMessage(text=str(self.state))
                    return

            dispatcher.dispatch(self, msg)
    def sum_sq_err(T):
        print(T)
        if (T < 0):
            return numpy.inf;

        states = boltzmann.thermal_JKM_ensemble(T,molecule,Jmax,percentile,anisotropy);
        t,cos2,cos2d,psi = dispatcher.dispatch(states,pulses,Jmax,Nshells,molecule,dt,t_end,probe_waist,calculate_cos2d,do_psi_pulse=False)
        
        f = scipy.interpolate.interp1d(t,cos2d,kind='linear');
        cos2d_calc = f(t_data);
        error = numpy.sum((cos2d_calc-cos2d_data)**2);
        return error;
Exemple #8
0
	def parseOutput(self,line):
		#for line in lines:
		#print('Processing: '+line)
		found = False
		
		m = self.re_progressbar.search(line)
		if m != None:
			found = True
			self.sync_progress['FilePercentage'] = int(m.group('Percentage'))
			self.sync_progress['FileTransferredSize'] = m.group('TransferredSize')
			self.sync_progress['TransferRate'] = m.group('TransferRate')
			if m.group('FileToTransfer') != None:
				self.sync_progress['FilePercentage'] = 100
				self.sync_progress['OverallPercentage'] = 100-int((int(m.group('FileToTransfer'))*100) / int(m.group('TotalFileToTransfer')))
				
			dispatcher.dispatch('SyncProgress',self.sync_progress)
			
		m = self.re_sending.search(line)
		if m != None:
			found = True
			self.sync_progress['CurrentFile'] = m.group('FileName')
			self.sync_progress['FilePercentage'] = 0
			self.sync_progress['FileTransferredSize'] = '0B'
			self.sync_progress['TransferRate'] = '0B/s'
			dispatcher.dispatch('SyncProgress',self.sync_progress)
			
		if line[0:4] == 'sent':
			found = True
			self.sync_progress['FilePercentage'] = 100
			self.sync_progress['FileTransferredSize'] = '0B'
			self.sync_progress['TransferRate'] = '0B/s'
			self.sync_progress['OverallPercentage'] = 100
			dispatcher.dispatch('SyncProgress',self.sync_progress)
		return found
Exemple #9
0
	def syncProceed(self):
		self.updateSyncName()
		serveraddress = str(self.uic.ServerAddress.lineEdit().text())
		transportation = self.uic.Transportation.currentIndex()
		username = str(self.uic.Username.text())
		if username == '':
			username = None
		password = str(self.uic.Password.text())
		if password == '':
			password = None
		#syncname = str(self.uic.SyncName.text())
		src = str(self.uic.Source.text())
		dst = str(self.uic.Destination.lineEdit().text())
		if platform.system() == 'Windows':
			srcsplit = src.split(':')
			src = '/cygdrive/'+srcsplit[0].lower()+(''.join(srcsplit[1:]).replace('\\','/'))
		rsyncusername = str(self.uic.RsyncUsername.text())
		if rsyncusername == '':
			rsyncusername = None
		rsyncpassword = str(self.uic.RsyncPassword.text())
		if rsyncpassword == '':
			rsyncpassword = None
		
		syncadd= {'Address':serveraddress,
				  'Username':username,
				  'Password':password,
				  'Transportation':transportation,
				  'SyncName':self.syncname,
				  'OldSyncName':self.uic.ManagementSyncName.currentText(),
				  'Source':src,
				  'Destination':dst,
				  'RsyncUsername':rsyncusername,
				  'RsyncPassword':rsyncpassword}
				  
		dispatcher.dispatch('SyncEdit',syncadd)
		self.stackedWidget.setCurrentWidget(self.uic.Start)
Exemple #10
0
def application(env, start_response):
    request = Request(env, config.encoding)
    out = io.BytesIO()
    response = Response(out, config.encoding)
    try:
        dispatcher.dispatch(request, response)
    except Exception as e:
        start_response('%d %s' % (500, 'Internal Server Error'), {})
    else:
        headers = response.get_headers()
        cookies = response.get_cookies()
        if cookies:
            cookien = 0
            cookiev = ''
            for cookie in response.get_cookies():
                if cookien > 0:
                    cookiev = cookiev + '\r\nSet-Cookie: '
                cookiev = cookiev + ('%s=%s' % (cookie[0], str(cookie[1])))
                if (cookie[2]):
                    cookiev = cookiev + ('; path=%s' % cookie[2])
                if (cookie[3]):
                    cookiev = cookiev + ('; domain=%s' % cookie[3])
                if (cookie[4]):
                    cookiev = cookiev + ('; expires=%s' % str(cookie[4]))
                if (cookie[5]):
                    cookiev = cookiev + ('; comment=%s' % cookie[5])
                if (cookie[6]):
                    cookiev = cookiev + ('; version=%s' % str(cookie[6]))
                if (cookie[7]):
                    cookiev = cookiev + ('; [secure]')
                cookien = cookien + 1
            headers['Set-Cookie'] = cookiev
        write = start_response('%d %s' % response.get_status(), headers)
        content = out.getvalue()
        if content:
            write(content)
Exemple #11
0
    def sum_sq_err(T):
        print(T)
        if (T < 0):
            return numpy.inf

        states = boltzmann.thermal_JKM_ensemble(T, molecule, Jmax, percentile,
                                                anisotropy)
        t, cos2, cos2d, psi = dispatcher.dispatch(states,
                                                  pulses,
                                                  Jmax,
                                                  Nshells,
                                                  molecule,
                                                  dt,
                                                  t_end,
                                                  probe_waist,
                                                  calculate_cos2d,
                                                  do_psi_pulse=False)

        f = scipy.interpolate.interp1d(t, cos2d, kind='linear')
        cos2d_calc = f(t_data)
        error = numpy.sum((cos2d_calc - cos2d_data)**2)
        return error
Exemple #12
0
    def enqueue(self, request, *args, **kwargs):
        taskid = dispatcher.dispatch(request.session, self.task_name, *args, **kwargs)
        # If the taskid is None, then the task result is still cached and we
        # should render it diretcly. If not, task is queued and an ajax 
        # callback is added.
        if not taskid:
            content = self.render(request,
                    self.build_context(request, kwargs))
        else:
            if not self.sub_url.endswith('/'):
                task_url = '%s/%s/' % (self.sub_url, taskid)
            else:
                task_url = '%s%s/' % (self.sub_url, taskid)
            content = '''
            <div id="%s">
                <img src="/static/core/img/spinner.gif" alt="spinner" />
                <script type="text/javascript">
                    delayed_load("%s", "%s");
                </script>
            </div>
            ''' % (taskid, taskid, task_url)

        return mark_safe(content)
Exemple #13
0
import sys
from dispatcher import dispatch


if __name__ == "__main__":

    hotels = [
        {
        'name':"vivanta goa",
        'roomType': "7"
        },
        {
        'name':"ginger hotel goa",
        'roomType': "1"
        },
        {
        'name':"crown goa",
        'roomType': "7"
        }
    ]

    payload = {'hotels':hotels}
    dispatch(payload,{})
# -*- coding: utf-8 -*-

from django.conf.urls.defaults import patterns
from django.conf.urls.defaults import url
from django.views.decorators.csrf import csrf_exempt

from dispatcher import dispatch


urlpatterns = patterns('',
    url(r'^/pick_up_flag/(?P<player_name>\w+)',
        csrf_exempt(dispatch(post='ctf_player.views.pick_up_flag')),
        name='pick_up_flag'),
    url(r'^/update_player_location/(?P<player_name>\w+)',
        csrf_exempt(dispatch(post='ctf_player.views.update_player_location')),
        name='update_player_location'),
    url(r'^/create_player',
        csrf_exempt(dispatch(post='ctf_player.views.create_player')),
        name='create_player'),
    url(r'^/(?P<player_name>\w+)/tag_nearest_player',
        csrf_exempt(dispatch(post='ctf_player.views.tag_nearest_player')),
        name='tag_nearest_player'),
    url(r'^/(?P<player_name>\w+)',
        csrf_exempt(dispatch(get='ctf_player.views.get_player')),
        name='get_player'),
    url(r'^/?$',
        csrf_exempt(dispatch(get='ctf_player.views.players')),
        name='players'),
    )
Exemple #15
0
	def schedule(self):
		sched = []
		self.servercheck()
		
		self.config.lock()
		pollingtime = self.config['PollingTime']
		self.config.unlock()
		
		self.schedlistlock.acquire()
		for key in self.schedlist:
			if(self.schedlist[key]['Server'] != None):
				if (self.schedlist[key]['NeedsUpdate'] and 
				    self.schedlist[key]['Enabled'] and 
				    (self.schedlist[key]['Server'] in self.activeservers)
				    ):
					if self.schedtime[key]>= pollingtime:
						sched.append(key)
						self.schedtime[key]=0
					else:
						self.schedtime[key]+=1
		self.schedlistlock.release()
		
		if self.paused and not self.stopped:
			self.thschedule = threading.Timer(1,self.schedule)
			self.thschedule.start()
			return
			
		disp.dispatch('BackupStatus',1)
		for key in sched:
			self.schedlistlock.acquire()
			if key in self.schedlist: # it could happens that the entry is removed between the scheduling and the execution
				if watchdogavailable:
					self.schedlist[key]['NeedsUpdate'] = False
			else:
				self.schedlistlock.release()
				continue
			
			print('Scheduled backup of %s'%(key))
			
			dest = self.schedlist[key]['Destination']
			passwd=''
			args=[]
			self.serverlistlock.acquire()
			if self.schedlist[key]['Server'] in self.serverlist:
				serv = self.schedlist[key]['Server'] 
				if(self.serverlist[serv]['Transportation'] == 0):
					dest = self.serverlist[serv]['Address']+'::'+dest
				else:
					dest = self.serverlist[serv]['Address']+'::'+dest
					args.append("-e '"+self.config['SshCmd']+" -l " + self.serverlist[serv]['Username'] + "'")
			else:	#Abort execution
				self.serverlistlock.release()
				self.schedlistlock.release()
			self.serverlistlock.release()
			if self.schedlist[key]['Username'] != None:
				dest = self.schedlist[key]['Username']+'@'+dest
			if self.schedlist[key]['Password'] != None:
				passwd = self.schedlist[key]['Password']
			self.cmd = rsyncexec(cmd=self.config['RsyncCmd'],src=self.schedlist[key]['Source'], dst=dest, pwd=passwd, args=args)
			
			self.schedlistlock.release() #It should be safe to remove the lock. Everything should be already inside rsyncexec(...right?)
			ret = self.cmd.execute()
			if ret == 0:
				disp.dispatch('InfoMsg','Sync complete!')
			else:
				disp.dispatch('InfoMsg','An error occurred during backup operation. Sync Disabled!')
				self.schedlist[key]['Enabled'] = False
			#check exit status
			#self.schedlistlock.acquire()
			#self.schedlist[key]['NeedsUpdate'] = False
			#self.schedlistlock.release()
		disp.dispatch('BackupStatus',0)
		if(not self.stopped):
			self.thschedule = threading.Timer(1,self.schedule)
			self.thschedule.start()
Exemple #16
0
def on_message(client, userdata, message):
    action = eval(message.payload.decode('utf-8'))
    dispatch(action)
Exemple #17
0
	def removeSync(self):
		key = self.uic.ManagementSyncName.currentText()
		dispatcher.dispatch('SyncRemove',{'OldSyncName':key})
		self.uic.ManagementSyncName.removeItem(self.uic.ManagementSyncName.currentIndex())
		if self.uic.ManagementSyncName.count() == 0:
			self.stackedWidget.setCurrentWidget(self.uic.Start)	
# -*- coding: utf-8 -*-

from django.conf.urls.defaults import include
from django.conf.urls.defaults import patterns
from django.conf.urls.defaults import url

from dispatcher import dispatch


urlpatterns = patterns('',
    url(r'^/?$',
        dispatch(get='views.home'),
        name='home'),
    url(r'login',
        dispatch(get='views.glogin',
                 post='views.plogin'),
        name='login'),
    url(r'logout',
        dispatch(get='views.glogout'),
        name='logout'),
    (r'flags', include('ctf_flag.urls')),
    (r'games', include('ctf_game.urls')),
    (r'players', include('ctf_player.urls')),
    url(r'signup',
        dispatch(get='views.gsignup',
                 post='views.psignup'),
        name='signup'),
    )
    probe_waist = 20e-6;
    percentile = 0.99;
    anisotropy = 1.0;

    t_end = 30e-12

    cache = dict();
    states = [(1,0,0,0,1)];
    extra_header = ["<J>","std(J)","J_99.9%","Probability coefficients"];
    delimiter = ","
    savepath='C:\Jmax_data/'
    for i in range(len(p)):
        INTENSITY=0.6*p[i]*1e-6/(tau*(waist**2))
        pulses = [config.laserpulse(INTENSITY,tau,0,waist=31e-6)];
        t,cos2,cos2d,psi = dispatcher.dispatch(states,pulses,Jmax,Nshells,molecule,dt,t_end,probe_waist,calculate_cos2d,do_psi_pulse=True)
        psi=psi[0]
        pdf = numpy.abs(psi)**2;  
        Js = numpy.arange(0,Jmax+1);
        Jssq = Js**2;
        Javg = numpy.sum(Js*pdf,axis=1);
        Jsq_avg = numpy.sum(Jssq*pdf,axis=1); 
        std = numpy.sqrt(Jsq_avg - Javg**2);
        cdf = numpy.cumsum(numpy.abs(psi)**2,axis=1);
        percentile_999 = numpy.argmax(cdf>=0.999,axis=1);
        psi_out=numpy.abs(psi[-1])**2
        extra_columns = [Javg,std,percentile_999,psi_out];
        filename=mol+'_p'+str(int(p[i]))+'_T'+str(tau*1e12)+'.csv'
        utils.save_to_csv(savepath+filename,t,cos2,cos2d,extra_header,extra_columns,delimiter);    

Exemple #20
0
# -*- coding: utf-8 -*-

from django.conf.urls.defaults import include
from django.conf.urls.defaults import patterns
from django.conf.urls.defaults import url

from dispatcher import dispatch

urlpatterns = patterns(
    '',
    url(r'^/?$', dispatch(get='views.home'), name='home'),
    url(r'login',
        dispatch(get='views.glogin', post='views.plogin'),
        name='login'),
    url(r'logout', dispatch(get='views.glogout'), name='logout'),
    (r'flags', include('ctf_flag.urls')),
    (r'games', include('ctf_game.urls')),
    (r'players', include('ctf_player.urls')),
    url(r'signup',
        dispatch(get='views.gsignup', post='views.psignup'),
        name='signup'),
)
Exemple #21
0
# -*- coding: utf-8 -*-

from django.conf.urls.defaults import patterns
from django.conf.urls.defaults import url
from django.views.decorators.csrf import csrf_exempt

from dispatcher import dispatch


urlpatterns = patterns('',
    url(r'^/create_game',
        csrf_exempt(dispatch(post='ctf_game.views.create_game')),
        name='create_game'),
    url(r'^/(?P<game_name>\w+)/add_player',
        csrf_exempt(dispatch(post='ctf_game.views.add_player')),
        name='add_player'),
    url(r'^/(?P<game_name>\w+)',
        csrf_exempt(dispatch(get='ctf_game.views.get_game')),
        name='get_game'),
    url(r'^/?$',
        csrf_exempt(dispatch(get='ctf_game.views.games')),
        name='games'),
    )
Exemple #22
0
	def fooget(self):
		json,path,pathurl,params = parsePath(self.path)
		Session.handler = self
		Session.params = params

		Session.prefetching = 'X-moz' in self.headers and 'prefetch' in self.headers['X-moz']

		if len(path)>0 and len(path[0])>0 and path[0][0]=='~':
			mode = path[0][1:]
			page = dispatch(json,mode,path,params)
		else:
			Session.params = params
			implied = self.headers.get("X-Implied-Tags")
			if implied:
				tags = tagsModule.parse(implied,False)
			else:
				tags = tagsModule.parse("-special:rl",False)
			tags.update(User.tags())
			basic = Taglist()

			for thing in path:
				if thing:
					thing = urllib.parse.unquote(thing)
					bitt = tagsModule.parse(thing,False)
					tags.update(bitt)
					basic.update(bitt)
			tagfilter.filter(tags)
			print('effective tags',repr(tags))
			o = params.get('o')
			if o:
				o = int(o[0],0x10)
			else:
				o = 0

			if json:
				disp = jsony
			else:
				disp = pages
			def prevnext(f):
				with disp.Links():
					if json:
						disp.Links.next = o + 1
					else:
						params['o'] = o + 1
						disp.Links.next = disp.unparseQuery(params)
					if o > 0:
						if json:
							disp.Links.prev = o - 1
						else:
							params['o'] = o - 1
							disp.Links.prev = disp.unparseQuery(params)
					return f()

			if 'p' in params:
				pageSize = int(params['p'][0])
			else:
				pageSize = thumbnailPageSize
				
			def getPage():
				if 'q' in params:
					try:
						ident,name,ctype,ignoretags,*is_comic = next(withtags.searchForTags(
							tags,
							offset=o,
							limit=1))
					except StopIteration:						
						if json:
							return []
						else:
							@prevnext
							def page():
								disp.Links.next = None
								pages.makePage('No Results Found',
								               pages.d.p('No Results Found'))
								return pages.derpage
							return page
					else:
						@prevnext
						def page():
							return disp.page(
								info.pageInfo(ident),path,params)
						return page
				else:
					if o:
						offset = pageSize*o
					else:
						offset = 0
						
					return disp.media(
						pathurl,
						params,
						o,
						pageSize,
						withtags.searchForTags(
							tags,
							offset=offset,
							limit=pageSize),
						withtags.searchForTags(
							tags,
							offset=offset,
							limit=0x10,
							wantRelated=True),
						basic)
			with disp.Links():
				page = getPage()
		if json:
			Session.type = 'application/json'
			page = jsony.encode(page)
		else:
			#checkdirty.circular(page)
			page = str(page)
		page = page.encode('utf-8') + b'\n'
		self.send_response(200,"Okie Dokie Loki")
		self.send_header('Content-Type',
						 Session.type if Session.type else
						 'application/json; charset=utf-8' if json else
						 'text/html; charset=utf-8')
		if Session.modified:
			self.send_header('Last-Modified',
							 self.date_time_string(float(Session.modified)))		
		self.content_length = len(page)
		if Session.refresh:
			if Session.refresh is True:
				Session.refresh = 5
			self.send_header('Refresh',str(Session.refresh))
		self.end_headers()
		if not Session.head:
			self.wfile.write(page)
Exemple #23
0
import dispatcher

if __name__ == '__main__':
    args = dispatcher.init_args()
    error_in_args = dispatcher.is_error_in_args(args)
    if not error_in_args:
        dispatcher.dispatch(args)
    else:
        print(error_in_args)
Exemple #24
0
            "Percentile must be between 0 and 1, both not included.")
    anisotropy = args.anisotropy[0]
    if (anisotropy < 0):
        raise ValueError("Anisotropy factor must be nonnegative.")

    t_end = args.t[0] * 1e-12

    states = boltzmann.thermal_JKM_ensemble(T, molecule, Jmax, percentile,
                                            anisotropy)

    t, cos2, cos2d, psi = dispatcher.dispatch(states,
                                              pulses,
                                              Jmax,
                                              Nshells,
                                              molecule,
                                              dt,
                                              t_end,
                                              probe_waist,
                                              calculate_cos2d,
                                              xc_filename,
                                              do_psi_pulse=False)

    attributes = [
        molecule.name, Jmax, dt,
        os.path.basename(args.pulses), Nshells, T, probe_waist
    ]

    filename = out_filename
    if (filename == ""):
        filename = "data/" + ','.join([str(i) for i in attributes]) + ".npz"
def main():
	from service import create_mark_file
	create_mark_file()

	from dispatcher import dispatch
	dispatch()
# -*- coding: utf-8 -*-

from django.conf.urls.defaults import patterns
from django.conf.urls.defaults import url
from django.views.decorators.csrf import csrf_exempt

from dispatcher import dispatch


urlpatterns = patterns('',
    url(r'^/(?P<game_name>\w+)',
        csrf_exempt(dispatch(get='ctf_flag.views.get_flag')),
        name='get_flag'),
    )
Exemple #27
0
# -*- coding: utf-8 -*-

from django.conf.urls.defaults import patterns
from django.conf.urls.defaults import url
from django.views.decorators.csrf import csrf_exempt

from dispatcher import dispatch

urlpatterns = patterns(
    '',
    url(r'^/pick_up_flag/(?P<player_name>\w+)',
        csrf_exempt(dispatch(post='ctf_player.views.pick_up_flag')),
        name='pick_up_flag'),
    url(r'^/update_player_location/(?P<player_name>\w+)',
        csrf_exempt(dispatch(post='ctf_player.views.update_player_location')),
        name='update_player_location'),
    url(r'^/create_player',
        csrf_exempt(dispatch(post='ctf_player.views.create_player')),
        name='create_player'),
    url(r'^/(?P<player_name>\w+)/tag_nearest_player',
        csrf_exempt(dispatch(post='ctf_player.views.tag_nearest_player')),
        name='tag_nearest_player'),
    url(r'^/(?P<player_name>\w+)',
        csrf_exempt(dispatch(get='ctf_player.views.get_player')),
        name='get_player'),
    url(r'^/?$',
        csrf_exempt(dispatch(get='ctf_player.views.players')),
        name='players'),
)
Exemple #28
0
# -*- coding: utf-8 -*-

from django.conf.urls.defaults import patterns
from django.conf.urls.defaults import url
from django.views.decorators.csrf import csrf_exempt

from dispatcher import dispatch

urlpatterns = patterns(
    '',
    url(r'^/(?P<game_name>\w+)',
        csrf_exempt(dispatch(get='ctf_flag.views.get_flag')),
        name='get_flag'),
)
Exemple #29
0
 def on_callback_query(self, msg):
     # try:
         with open("log.txt", "a", encoding="utf-8") as f:
             f.write(str(msg) + '\n')
         pprint(msg)
         dispatcher.dispatch(self, msg)
Exemple #30
0
    def do_GET(self):
        Session.handler = self
        json,path,pathurl,params = parsePath(self.path)
        Session.params = params
        # Session.query = ...
        if len(path)>0 and len(path[0])>0 and path[0][0]=='~':
            mode = path[0][1:]
            page = dispatch(json,mode,path,params)
        else:
            implied = self.headers.get("X-Implied-Tags")                
            if implied:
                tags = tagsModule.parse(implied)
            else:
                tags = tagsModule.parse("-special:rl")
            tagfilter.filter(tags)
            tags.update(User.tags())
            basic = Taglist()
            # basic = visible tags to the user, i.e. not implied or user tags

            if json:
                disp = jsony
            else:
                disp = pages

            for thing in path:
                if thing:
                    thing = urllib.parse.unquote(thing)
                    if thing[0] == '-':
                        tag = tagsModule.getTag(thing[1:])
                        if tag:
                            tags.posi.discard(tag)
                            tags.nega.add(tag)
                            basic.nega.add(tag)
                        continue
                    elif thing[0] == '+':
                        thing = thing[1:]
                    tag = tagsModule.getTag(thing)
                    if tag:
                        tags.posi.add(tag)
                        basic.posi.add(tag)
            o = params.get('o')
            if 'q' in params:
                if o:
                    o = int(o[0],0x10)
                else:
                    o = 0
                ident,name,type,tags = next(withtags.searchForTags(tags,offset=o,limit=1))
                with disp.Links:
                    if json:
                        disp.Links.next = o + 1
                    else:
                        params['o'] = o + 1
                        disp.Links.next = disp.unparseQuery(params)
                    if o > 0:
                        if json:
                            disp.Links.prev = o - 1
                        else:
                            params['o'] = o - 1
                            disp.Links.prev = disp.unparseQuery(params) 
                    page = disp.page((ident,None,None,name,type,0,0,0,0,tags),path,params)
            else:
                if o:
                    o = int(o[0],0x10)
                    offset = thumbnailPageSize*o
                else:
                    offset = o = 0
                    
                page = disp.media(pathurl,params,o,
                        withtags.searchForTags(tags,offset=offset,limit=thumbnailPageSize),
                        withtags.searchForTags(tags,offset=offset,limit=thumbnailPageSize,wantRelated=True),basic)
        if json:
            page = jsony.encode(page).encode('utf-8')
        else:
            page = str(page).encode('utf-8')
        self.send_response(200,"OK")
        self.send_header('Content-Type',Session.type if Session.type else 'application/json' if json else 'text/html; charset=utf-8')
        if Session.modified:
            self.send_header('Last-Modified',self.date_time_string(float(Session.modified)))
        if not Session.head:
            self.send_header('Content-Length',len(page))
        else:
            self.send_header('Content-Length',0)
        if Session.refresh:
            if Session.refresh is True:
                Session.refresh = 5
            self.send_header('Refresh',str(Session.refresh))
        self.end_headers()
        if Session.head is False:
            self.wfile.write(page)