コード例 #1
0
ファイル: endpoint.py プロジェクト: ozw1z5rd/gdg-pescara
	def getTechList(self,request):
		L.i("Entering in getTechList")
		technologyController = TechnologyController()
		return GDGPETecnologyListResponse(
			meta = self.getGDGPEMetaElementByCode( GDGPEEndpointStatus.CODE_OK ),
			technologies = list([x.asMessageElement() for x in technologyController.getList(request)])
		)
コード例 #2
0
ファイル: controllers.py プロジェクト: ozw1z5rd/gdg-pescara
    def openCapsule(TSCid=None, lat=None, lng=None, password=None, user=None):
        """
		openCapsule will assign the capsule is mode is not anonymous 
		and then will return to caller
		Is capsule is anonymous or already assigned, it will try to open it
		"""
        L.info("openCapsule Called")
        L.debug({
            'dumping parameters': '',
            'TSCid': TSCid,
            'lat': lat,
            'lng': lng,
            'pwd len': len(password) if password is not None else -1,
            'user': user
        })
        # capsule not found
        tsc = TimespaceCapsule.getByTSCid(TSCid)
        if tsc is None:
            return (TSCController.TSCCTRL_BADTSCID, None)
        # if not anonymous here we require a valid user.
        if not tsc.anonymous and tsc.user is None:
            if user is None:
                return (TSCController.TSCCTRL_BADUSER, None)
            L.info("TSC is not anonymous, binding ...")
            L.info(user)
            tsc.assignToUser(user)
            return (TSCController.TSCCTRL_ASSIGNED, None)

        # try to open
        L.info("try to disclose")
        response = tsc.disclose(lat=lat, lng=lng, user=user, password=password)
        return (TSCController.TSCCTRL_OK, response)
コード例 #3
0
def load_json(path):
    """ given a path, return a structure with the contained JSON """
    dirname = os.path.dirname(path)
    if not dirname:
        name = os.path.basename(path)
        thisdir = os.path.dirname(os.path.realpath(__file__))
        path = os.path.join(thisdir, name + '.json')

    filep = None
    try:
        filep = open(path)
    except IOError:
        L.warning("Can't open " + path + " for reading")
        return False

    data = {}
    filestr = filep.read()
    try:
        data = json.loads(filestr)
    except ValueError:
        L.error("Error: packet not valid json:" + filestr)
        filep.close()
        return False

    filep.close()
    return data
コード例 #4
0
ファイル: xresolv.py プロジェクト: gabriel4649/JMdictDB
def mkxref(v):
    # If there is no tsens, generate an xref to only the first
    # sense.  Rationale: Revs prior to ~2018-06-07 we generated
    # xrefs to all senses in this scenario.  When there were a
    # lot of reverse xrefs to a word from the Example sentences,
    # every sense of the target word would have them all repeated.
    # However unless there is only one target sense, we can be
    # sure we are wrong: if the senses were so similar to be
    # interchangable they wouldn't be separate senses.  Since
    # we'll be wrong either way and someone will need to manually
    # correct it later, choose the way that produces the least
    # amount of clutter in the entry.  Also, in many cases the
    # first *will* be the right sense.
    nosens = False
    if not v.tsens:
        if v.nsens != 1:
            L('multiple senses').warning("using sense 1: %s" % (fs(v)))
            nosens = True
        v.tsens = 1
    if v.tsens > v.nsens:
        L('sense number too big').error(fs(v))
        return None
    xref = jdb.Obj(entr=v.entr,
                   sens=v.sens,
                   xref=v.ord,
                   typ=v.typ,
                   xentr=v.targ,
                   xsens=v.tsens,
                   rdng=v.rdng,
                   kanj=v.kanj,
                   notes=v.notes,
                   nosens=nosens,
                   lowpri=not v.prio)
    return xref
コード例 #5
0
def save_json(path, data):
    """ given a path, and structure, save as JSON string """
    jsonstr = ""

    try:
        jsonstr = json.dumps(data)
    except TypeError:
        L.error("Error: data supplied can't be converted to JSON")
        return False

    dirname = os.path.dirname(path)
    if not dirname:
        name = os.path.basename(path)
        thisdir = os.path.dirname(os.path.realpath(__file__))
        path = os.path.join(thisdir, name + '.json')

    filep = None
    try:
        filep = open(path, "w")
    except IOError:
        L.error("Error: can't open " + path + " for writing")
        return False

    filep.write(jsonstr)
    filep.write("\n")
    filep.close()
    return True
コード例 #6
0
def reject(dbh, entr, edtree, errs, rejcnt=None):
    KW = jdb.KW
    L('cgi.edsubmit.reject').debug("rejecting entry id %s, rejcnt=%s" %
                                   (entr.dfrm, rejcnt))
    # rejectable() returns a list entr rows on the path to the edit
    # edit root, starting with the one closest to the root, and ending
    # with our entry's parent, that can be rejected.  If this is a new
    # entry, 'rejs' will be set to [].
    try:
        rejs = rejectable(edtree, entr.dfrm)
    except NonLeafError as e:
        L('cgi.edsubmit.reject').debug("NonLeafError")
        errs.append (jmcgi.Markup("Edits have been made to this entry.  "\
                "To reject entries, you must reject the version(s) most "
                "recently edited, which are: %s"\
                % ', '.join ("id="+url(x) for x in leafsn([e.args[0]]))))
        return
    except IsApprovedError as e:
        L('cgi.edsubmit.reject').debug("IsApprovedrror")
        errs.append("You can only reject unapproved entries.")
        return
    if not rejcnt or rejcnt > len(rejs): rejcnt = len(rejs)
    chhead = (rejs[-rejcnt]).id if rejcnt else None
    L('cgi.edsubmit.reject').debug("rejs=%r, rejcnt=%d, chhead=%s" %
                                   ([x.id for x in rejs], -rejcnt, chhead))
    entr.stat = KW.STAT['R'].id
    entr.dfrm = None
    entr.unap = False
    res = addentr(dbh, entr)
    if chhead: delentr(dbh, chhead)
    return res
コード例 #7
0
ファイル: webtail.py プロジェクト: amnond/mymon
 def process_message(self, user, msg):
     """ process a request from a client-side webtail component """
     reply_packet = {"status": ""}
     packet = {}
     try:
         packet = json.loads(msg)
     except Exception as ex:
         self.log_exeption(ex, "loading client request " + msg)
         reply_packet["status"] = "error"
         reply_packet["msg"] = "invalid request"
     if reply_packet["status"] == "error":
         return json.dumps(reply_packet)
     if "request" not in packet:
         reply_packet["status"] = "error"
         reply_packet["msg"] = "invalid request"
         L.error("webtail: no request in packet")
         return json.dumps(reply_packet)
     req = packet["request"]
     if req not in self.webtail_funcs:
         L.error("webtail: no handler for request")
         reply_packet["status"] = "error"
         reply_packet["msg"] = "invalid request"
         return json.dumps(reply_packet)
     reply_packet = self.webtail_funcs[req](user, packet)
     if "ctx" in packet:
         reply_packet["ctx"] = packet["ctx"]
     reply_packet["reply-to"] = req
     return json.dumps(reply_packet)
コード例 #8
0
ファイル: endpoint.py プロジェクト: ozw1z5rd/gdg-pescara
    def addCapsule(self, request):
        """add a new capsule, edit and delete is not allowed
		"""
        # probabilmente ci deve essere un sistema migliore di fare
        # questo passaggio dei parametri
        openingDate = request.openingDate
        closingDate = request.closingDate
        lat = request.lat
        lng = request.lng
        tll = request.tll
        anonymous = request.anonymous
        encrypt = request.encrypted
        content = request.content

        user = TSCEndpoint.get_current_user()
        TSCid = TSCController.addCapsule(openingDate, closingDate, \
         lat, lng, tll, anonymous, encrypt, user, content)
        if TSCid is None:
            response = TSCResponseMessage(TSCid=None,
                                          status=TSCController.TSCCTRL_KO,
                                          statusMessage='Capsule not created.',
                                          content='',
                                          items=[])
        else:
            L.info("Capsule created")
            response = TSCResponseMessage(
                TSCid=TSCid,
                status=TSCController.TSCCTRL_OK,
                statusMessage='Capsule correctly created',
                content='',
                items=[])

        return response
コード例 #9
0
ファイル: endpoint.py プロジェクト: ozw1z5rd/gdg-pescara
	def addCapsule(self, request):
		"""add a new capsule, edit and delete is not allowed
		"""
		# probabilmente ci deve essere un sistema migliore di fare
		# questo passaggio dei parametri
		openingDate = request.openingDate
		closingDate = request.closingDate
		lat = request.lat
		lng = request.lng
		tll = request.tll
		anonymous = request.anonymous
		encrypt = request.encrypted
		content = request.content

		user =  TSCEndpoint.get_current_user()
		TSCid = TSCController.addCapsule(openingDate, closingDate, \
			lat, lng, tll, anonymous, encrypt, user, content)
		if TSCid is None:
			response = TSCResponseMessage(
				TSCid = None,
				status = TSCController.TSCCTRL_KO,
				statusMessage = 'Capsule not created.',
				content = '',
				items = [] )
		else:
			L.info("Capsule created")
			response = TSCResponseMessage(
				TSCid = TSCid,
				status = TSCController.TSCCTRL_OK,
				statusMessage = 'Capsule correctly created',
				content = '',
				items = [] )

		return response
コード例 #10
0
ファイル: reqhandler.py プロジェクト: amnond/mymon
 def websock_new_connection(self, user, client, service):
     """ Notify handler of new client """
     if not service in self.websock_handlers:
         L.error("Error: service:" + service +
                 " not found for new connection")
         return False
     return self.websock_handlers[service]['new_client'](user, client)
コード例 #11
0
	def _distVincenty(self, lat1, lon1) :
		"""
		Return distance in meters beteewn 2 points.
		"""
		lat2 = self.positionLat
		lon2 = self.positionLng
		a = 6378137
		b = 6356752.3142
		f = 1/298.257223563  # WGS-84 ellipsiod

		L0 = math.radians(lon2-lon1)
		U1 = math.atan( (1-f) * math.tan(math.radians(lat1)) )
		U2 = math.atan( (1-f) * math.tan(math.radians(lat2)) )
		sinU1 = math.sin(U1)
		cosU1 = math.cos(U1)
		sinU2 = math.sin(U2)
		cosU2 = math.cos(U2)

		lambda1 = L0
		lambdaP = 0
		iterLimit = 100

		while True:
			L.info(iterLimit)
			sinLambda = math.sin(lambda1)
			cosLambda = math.cos(lambda1)
			sinSigma = math.sqrt((cosU2*sinLambda)
					   * (cosU2*sinLambda)
					   + (cosU1*sinU2-sinU1*cosU2*cosLambda)
					   * (cosU1*sinU2-sinU1*cosU2*cosLambda))
			if sinSigma==0 :
				return 0
			try:
				cosSigma = sinU1*sinU2 + cosU1*cosU2*cosLambda
				sigma = math.atan2(sinSigma, cosSigma)
				sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma
				cosSqAlpha = 1 - sinAlpha*sinAlpha
				cos2SigmaM = cosSigma - 2*sinU1*sinU2/cosSqAlpha
			except:
				cos2SigmaM = 0 # equatorial line: cosSqAlpha=0 (§6)
			C = f/16*cosSqAlpha*(4+f*(4-3*cosSqAlpha))
			lambdaP = lambda1
			lambda1 = L0 + (1-C) * f * sinAlpha *\
				(sigma + C*sinSigma*(cos2SigmaM+C*cosSigma*\
				(-1+2*cos2SigmaM*cos2SigmaM)))

			iterLimit = iterLimit - 1
			if abs(lambda1-lambdaP) > 1e-12 and iterLimit>0 :
				break
			if iterLimit==0 :
				return None # formula failed to converge
			uSq = cosSqAlpha * (a*a - b*b) / (b*b)
			A = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)))
			B = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq)))
			deltaSigma = B*sinSigma*(cos2SigmaM+B/4*(cosSigma*
					 (-1+2*cos2SigmaM*cos2SigmaM)-
					 B/6*cos2SigmaM*(-3+4*sinSigma*sinSigma)*
					 (-3+4*cos2SigmaM*cos2SigmaM)))
			s = b*A*(sigma-deltaSigma);
			return s
コード例 #12
0
ファイル: xresolv.py プロジェクト: gabriel4649/JMdictDB
def del_xresolv(dbconn,
                xref_src=[],
                targ_src=None,
                start=None,
                stop=None,
                active=False):
    # CAUTION: we assume here that xref.xref has the same value
    #  as xresolv.ord and thus we can use xref.xref to delete
    #  the corresponding xresolv row.  That is currently true but
    #  has not been true in past and could change in the future.
    #FIXME: this replicates same WHERE logic used in resolve();
    # should factor out to a single location, either in python
    # code or in a database view.
    c0 = "v.entr=x.entr AND v.sens=x.sens"\
         " AND v.typ=x.typ AND v.ord=x.xref"
    c1, args1 = src_clause(xref_src, targ_src)
    c2, args2 = idrange_clause(start, stop)
    c3 = "v.stat=2 AND NOT v.unapp" if active else ""
    c4 = "tstat=2"
    c5 = ""  #"NOT tunap" if appr_targ else "")
    whr = " AND ".join([c for c in [c0, c1, c2, c3, c4, c5] if c])
    if whr: whr = "WHERE " + whr
    args = args1 + args2
    sql = "DELETE FROM xresolv v"\
          " USING (SELECT x.entr, x.sens, x.xref, x.typ,"\
                        " ex.src, ex.stat, ex.unap,"\
                        " et.src as tsrc,et.stat AS tstat,et.unap AS tunap"\
                 " FROM xref x"\
                 " JOIN entr ex ON x.entr=ex.id"\
                 " JOIN entr et ON x.xentr=et.id) AS x"\
          " %s" % whr
    L('del_xresolv.sql').debug("sql: %s" % sql)
    L('del_xresolv.sql').debug("args: %r" % (args, ))
    cursor = db.ex(dbconn, sql, args)
    return cursor.rowcount
コード例 #13
0
ファイル: webtail.py プロジェクト: amnond/mymon
    def update_files_to_monitor(self, user, newclient):
        """ read user file monitor prefs and update monitoring paths if required """
        if user not in self.config:
            self.config[user] = {}
        user_config = self.config[user]
        if "monitored_files" not in user_config:
            user_config["monitored_files"] = {}
        if "regexes" not in user_config:
            user_config["regexes"] = []
        user_watched_files = user_config["monitored_files"]
        # L.info("==============")
        # L.info(user_watched_files)
        resave_config = False
        for filepath in user_watched_files:
            if filepath in self.path_filter and newclient:
                L.info(filepath +
                       ": file already being monitored by another client")
                self.path_filter[filepath] += 1  # increase reference count
                continue

            if not self.get_fp(filepath):
                L.error("Bad file path for:" + filepath)
                user_watched_files[filepath]['follow'] = 0
                resave_config = True
                continue

            # First subscription to monitor this file
            self.path_filter[filepath] = 1

        if resave_config:
            # Some bad file paths encountered and were marked. Resave users configurations
            # with the marked bad paths so that they can be displayed on the client side
            self.save_config()
コード例 #14
0
ファイル: webtail.py プロジェクト: amnond/mymon
 def new_client(self, user, client):
     """ invoked whenever a new client joins the service webtail"""
     L.info("received new client")
     self.listeners[client] = {"user": user}
     # new user means possibly more directories and files to monitor
     self.update_files_to_monitor(user, True)
     return True
コード例 #15
0
    def post(self):
        """ Tornado post authentication credentials """
        incorrect = self.get_secure_cookie("incorrect")
        if incorrect and int(incorrect) > 20:
            self.write('<center>blocked</center>')
            return

        getusername = tornado.escape.xhtml_escape(
            self.get_argument("username"))
        getpassword = tornado.escape.xhtml_escape(
            self.get_argument("password"))

        L.info("%s,%s\n" % (getusername, getpassword))

        if getusername == "demo" and getpassword == "demo":
            self.set_secure_cookie("user", self.get_argument("username"))
            self.set_secure_cookie("incorrect", "0")
            self.redirect(self.reverse_url("main"))
        else:
            incorrect = self.get_secure_cookie("incorrect") or 0
            increased = str(int(incorrect) + 1)
            self.set_secure_cookie("incorrect", increased)
            self.write("""<center>
                            Something Wrong With Your Data (%s)<br />
                            <a href="/">Go Home</a>
                          </center>""" % increased)
コード例 #16
0
ファイル: webtail.py プロジェクト: amnond/mymon
 def new_message(self, user, client, message):
     """ invoked whenever a client sends a new message to service webtail"""
     L.info("received new message:" + message)
     if client not in self.listeners:
         L.error("received message from unregiatered client")
         return
     reply_str = self.process_message(user, message)
     client.write_message(reply_str)
コード例 #17
0
ファイル: reqhandler.py プロジェクト: amnond/mymon
 def websock_close_connection(self, client):
     """ Notify handler of client closing a connection """
     service = client.service
     if not service in self.websock_handlers:
         L.error("Error: service:" + service +
                 " not found for close connection")
         return
     self.websock_handlers[service]['close_client'](client)
コード例 #18
0
ファイル: reqhandler.py プロジェクト: amnond/mymon
 def register_ajax_handler(self, request, function):
     """ component registers its ajax requests handlers via this method"""
     if request in self.ajax_handlers:
         L.error("Error: request:" + request + " is already registered")
         return False
     self.ajax_handlers[request] = function
     L.info("registered:" + request)
     return True
コード例 #19
0
ファイル: webtail.py プロジェクト: amnond/mymon
 def start(self, reqhandler, logger, timer):
     if self.started:
         L.error("WebTail plugin already started")
         return False
     webtail = WebTail()
     self.tail_timer = timer(webtail.follow, 1000)
     self.tail_timer.start()
     return True
コード例 #20
0
 def on_close_websock(self, client):
     """ existing websoock has been closed """
     self.listeners.remove(client)
     if len(self.listeners) == 0:
         pass
     L.info("websock closed")
     if hasattr(client, "service"):
         RH.websock_close_connection(client)
コード例 #21
0
def addentr (dbh, entr):
        entr._hist[-1].unap = entr.unap
        entr._hist[-1].stat = entr.stat
        L('edsubmit').debug("addentr(): adding entry to database")
        L('edsubmit').debug("addentr(): %d hists, last hist is %s [%s] %s" % (len(entr._hist),
              entr._hist[-1].dt, entr._hist[-1].userid, entr._hist[-1].name))
        res = jdb.addentr (dbh, entr)
        L('edsubmit').debug("addentr(): entry id=%s, seq=%s, src=%s added to database" % res)
        return res
コード例 #22
0
def read_text(path):
    L.debug("read_text" + os.path.abspath(path))
    f = open(path, "r")
    if f.mode == 'r':
        contents = f.read()
        f.close()
        return contents
    f.close()
    return ''
コード例 #23
0
ファイル: webtail.py プロジェクト: amnond/mymon
 def unfollow_file(self, fullpath):
     """ remove file from list of tracked files """
     if fullpath not in self.path_filter:
         return
     if fullpath not in self.tailed_file_ptrs:
         L.error("can't unfollow " + fullpath + " as it is not followed.")
         return
     self.tailed_file_ptrs[fullpath].close()
     del self.tailed_file_ptrs[fullpath]
コード例 #24
0
ファイル: controllers.py プロジェクト: ozw1z5rd/gdg-pescara
    def radar(TSCid=None, lat=None, lng=None):
        """
		Return how meters are we far away the capsule.
		"""
        L.info("radar Called")
        L.debug({'TSCid': TSCid, 'lat': lat, 'lng': lng})
        tsc = TimespaceCapsule.getByTSCid(TSCid)
        if tsc is None:
            return (TSCController.TSCCTRL_BADTSCID, None)
        return (TSCController.TSCCTRL_OK, tsc.distance(lat, lng))
コード例 #25
0
def gen_files(json_result, parent, name):
    file_name, file_extension = os.path.splitext(name)
    value = join_path(parent, name)
    key = normal_key(file_name)
    if valid_ext(file_extension):
        json_result[key] = value
        # L.info("+ %s = %s", key, value)
    else:
        L.warning("- %s = %s", key, value)
    return json_result
コード例 #26
0
def save(json_content, path):
    path = abs_path(path)
    # json_content = {}
    # for key, value in json_content.iteritems():
    #     print("key: {} | value: {}".format(key, value))
    # content = pattern_save.replace("@content", json.dumps(json_content, indent=4))

    content = pattern_save.replace("@content", json_stringify(json_content))
    write(path, content)
    L.debug("success => save to file:" + path)
コード例 #27
0
ファイル: endpoint.py プロジェクト: ozw1z5rd/gdg-pescara
	def searchPosts(self,request):
		author = request.author
		dateStart = request.dateStart
		ID = request.id
		sector = request.sector
		tags = request.tags
		
		L.i("Entering searchPost")
		L.i(request)
		
		return author + dateStart + ID + sector + tags
コード例 #28
0
def submit (dbh, entr, edtree, errs):
        KW = jdb.KW
        L('edsubmit').debug("submit(): submitting entry with parent id %s" % entr.dfrm)
        if not entr.dfrm and entr.stat != KW.STAT['A'].id:
            L('edsubmit').debug("submit(): bad url param exit")
            errs.append ("Bad url parameter, no dfrm");  return
        if entr.stat == jdb.KW.STAT['R'].id:
            L('edsubmit').debug("submit(): bad stat=R exit")
            errs.append ("Bad url parameter, stat=R");  return
        res = addentr (dbh, entr)
        return res
コード例 #29
0
ファイル: controllers.py プロジェクト: ozw1z5rd/gdg-pescara
	def addCapsule(
			openingDate=None,
			closingDate=None,
			lat=None,
			lng=None,
			tll=0, 
			anonymous=True, 
			encrypt=False, 
			user=None,
			content=None,
			password=None
		):
		"""
		Add a new capsule
		Create a new capsule and assign it to current user ( owner )
		content is uniencoded
		in : all the defining capsule parameters
		out : TSCid if ok, None otherwise
		"""
		L.info("addCapsule called")
		L.debug({
			'openingDate' : openingDate, 
			'closingDate' : closingDate, 
			'lat' : lat,
			'lng' : lng, 
			'ttl' : tll,
			'anonymous' : anonymous,
			'encrypt' : encrypt,
			'user' : user,
			'content' : content, 
			'pwd len' : len(password) if password is not None else -1
		})
		try:
			tsc = \
				TimespaceCapsule(
					openingDate = openingDate,
					closingDate = closingDate,
					content = content,
					positionLat = lat,
					positionLng = lng,
					positionTll = tll,
					anonymous = anonymous,
					owner = user,
					encrypt = encrypt,
					password = password 
				)
			tsc.put()
		except Exception as e:
			L.warning("Got exception!")
			L.exception(e)
			return None
		else:
			L.info("Capsule created")
			return tsc.TSCid
コード例 #30
0
ファイル: code.py プロジェクト: ozw1z5rd/gdg-pescara
 def t065_Image(self):
     """Immagini"""
     L.i("ImageTestData load start")
     for el in TestData.listImages:
         img = Image(description=el['description'],
                     link=el['link'],
                     type=el['type'],
                     blob=el['blob'])
         self.images.append(img)
         img.save()
     L.i("ImageTestData ended")
     return True
コード例 #31
0
ファイル: reqhandler.py プロジェクト: amnond/mymon
 def ajax_request(self, user, packet):
     """ invoke the appropriate method of the designated request handler """
     request = packet["request"]
     if not request in self.ajax_handlers:
         L.error("Error: request " + request + " does not have a handler")
         return {"status": "error", "msg": "no handler for " + request}
     reply = self.ajax_handlers[request](user, packet)
     reply['reply-to'] = request
     if 'ctx' in packet:
         # if context received with request, return it unchanged
         reply['ctx'] = packet['ctx']
     return reply
コード例 #32
0
ファイル: controllers.py プロジェクト: ozw1z5rd/gdg-pescara
    def addCapsule(openingDate=None,
                   closingDate=None,
                   lat=None,
                   lng=None,
                   tll=0,
                   anonymous=True,
                   encrypt=False,
                   user=None,
                   content=None,
                   password=None):
        """
		Add a new capsule
		Create a new capsule and assign it to current user ( owner )
		content is uniencoded
		in : all the defining capsule parameters
		out : TSCid if ok, None otherwise
		"""
        L.info("addCapsule called")
        L.debug({
            'openingDate': openingDate,
            'closingDate': closingDate,
            'lat': lat,
            'lng': lng,
            'ttl': tll,
            'anonymous': anonymous,
            'encrypt': encrypt,
            'user': user,
            'content': content,
            'pwd len': len(password) if password is not None else -1
        })
        try:
            tsc = \
             TimespaceCapsule(
              openingDate = openingDate,
              closingDate = closingDate,
              content = content,
              positionLat = lat,
              positionLng = lng,
              positionTll = tll,
              anonymous = anonymous,
              owner = user,
              encrypt = encrypt,
              password = password
             )
            tsc.put()
        except Exception as e:
            L.warning("Got exception!")
            L.exception(e)
            return None
        else:
            L.info("Capsule created")
            return tsc.TSCid
コード例 #33
0
ファイル: code.py プロジェクト: ozw1z5rd/gdg-pescara
	def t065_Image(self):
		"""Immagini"""
		L.i("ImageTestData load start")
		for el in TestData.listImages:
			img = Image(
				description = el['description'], 
				link = el['link'], 
				type = el['type'],
				blob = el['blob']
			)
			self.images.append(img)
			img.save()
		L.i("ImageTestData ended")
		return True
コード例 #34
0
ファイル: controllers.py プロジェクト: ozw1z5rd/gdg-pescara
	def radar( TSCid=None, lat=None, lng=None):
		"""
		Return how meters are we far away the capsule.
		"""
		L.info("radar Called")
		L.debug({
			'TSCid':TSCid, 
			'lat': lat, 
			'lng':lng
		})
		tsc = TimespaceCapsule.getByTSCid(TSCid)
		if tsc is None:
			return  (TSCController.TSCCTRL_BADTSCID, None)
		return (TSCController.TSCCTRL_OK, tsc.distance( lat, lng ))
コード例 #35
0
ファイル: reqhandler.py プロジェクト: amnond/mymon
 def register_websock_handlers(self, service, new_client, new_message,
                               close_client):
     """ component registers its websocket requests handlers via this method
         The new_client method should return False if there is a problem
         servicing a new client, otherwise True """
     if service in self.websock_handlers:
         L.error("Error: service:" + service + " is already registered")
         return False
     handlers = {
         "new_client": new_client,
         "new_message": new_message,
         "close_client": close_client
     }
     self.websock_handlers[service] = handlers
     return True
コード例 #36
0
ファイル: endpoint.py プロジェクト: ozw1z5rd/gdg-pescara
	def listCapsule(self, request):
		"""list capsule depending on search parameters
		This will be the most used api
		"""
		user = TSCEndpoint.get_current_user()

		( rc, items ) = TSCController.searchCapsule(
				TSCid = request.TSCid, \
				seen = request.seen, \
				anonymous = request.anonymous, \
				encrypt=request.encrypt, \
				user = user)

		L.info("Logging degli items")
		L.info(items)
		if not rc == TSCController.TSCCTRL_OK :
			raise endpoints.InternalServerErrorException("Something goes bad")
		return TSCResponseMessage( TSCid = None, status = TSCController.TSCCTRL_OK, \
			statusMessage = '', items = items )
コード例 #37
0
ファイル: controllers.py プロジェクト: ozw1z5rd/gdg-pescara
	def openCapsule(
			TSCid=None,
			lat=None,
			lng=None,
			password=None,
			user=None
		):
		"""
		openCapsule will assign the capsule is mode is not anonymous 
		and then will return to caller
		Is capsule is anonymous or already assigned, it will try to open it
		"""
		L.info("openCapsule Called")
		L.debug({
			'dumping parameters': '',
			'TSCid' : TSCid, 
			'lat' : lat,
			'lng' : lng, 
			'pwd len': len(password) if password is not None else -1,
			'user':user
		})
		# capsule not found
		tsc = TimespaceCapsule.getByTSCid(TSCid)
		if tsc is None:
			return (TSCController.TSCCTRL_BADTSCID, None)
		# if not anonymous here we require a valid user.
		if not tsc.anonymous and tsc.user is None:
			if user is None:
				return (TSCController.TSCCTRL_BADUSER, None)
			L.info("TSC is not anonymous, binding ...")
			L.info(user)
			tsc.assignToUser( user )
			return  (TSCController.TSCCTRL_ASSIGNED, None )
		
		# try to open
		L.info("try to disclose")
		response = tsc.disclose( 
						lat=lat,
						lng=lng,
						user=user,
						password=password
					)
		return ( TSCController.TSCCTRL_OK, response)
コード例 #38
0
ファイル: code.py プロジェクト: ozw1z5rd/gdg-pescara
	def t010_Sector(self):
		"""Settori di applicazione"""
		L.i("SectorTestData load start")
		c = 0 
		for el in TestData.listSectors:
			L.i("    Dataloaded #{0}".format(c)); c+=1;
			sector =  Sector( title = el['title'], description= el['description'])
			self.sectors.append(sector)
			sector.put()
		L.i("SectorTestData load ended")
		return True
コード例 #39
0
ファイル: controllers.py プロジェクト: ozw1z5rd/gdg-pescara
	def searchCapsule(
			TSCid=None,
			seen=False,
			anonymous=True,
			notified=False,
			assigned=False,
			encrypt=False,
			user=None
		):
		"""
		Search a TSC depending on the given parameters, if tscid is 
		provided extra parameters are ignored.
		"""
		L.info("searchCapsule called ")
		L.debug({
			'Dumping paramters' : '',
			'anonymous' : anonymous, 
			'notified' : notified, 
			'assigned' : assigned, 
			'encrypt' : encrypt, 
			'user' : user 
		})
		
		# if TSCid is provided SEARCH only by TSCid.
		if TSCid is not None:
			L.info("TSCid is not None")
			tsc = TimespaceCapsule.getByTSCid( TSCid )
			tscList = [tsc] if tsc is not None else [] 
		else:
			# more elements
			tscList = TimespaceCapsule.getList( 
						user=user, 
						seenFlag=seen,
						assignedFlag=assigned,
						notifiedFlag=notified,
						encryptFlag=encrypt
					)
			
		items = [ tsc.toEndPointMessage() for tsc in tscList ]
		if any(items): 
			L.info( "No capsule found!")
		return ( TSCController.TSCCTRL_OK, items )
コード例 #40
0
ファイル: code.py プロジェクト: ozw1z5rd/gdg-pescara
	def t000_Technology(self):
		"""Lista delle tecnologie"""
		L.i("TecnologyTestData load start")
		c = 0
		for el in TestData.listTechnologies:
			L.i("    Dataloaded #{0}".format(c)); c+=1;
			technology = Technology(
				title = el['title'],
				description=el['description'],
				icon="nunce")
			self.technologyEntity.append(technology)
			technology.put()
		L.i("TechnologyTestData load ended")
		return True
コード例 #41
0
ファイル: code.py プロジェクト: ozw1z5rd/gdg-pescara
	def t005_Link(self):
		"""lista dei link"""
		L.i("LinkTestData load start")
		c = 0 
		for el in TestData.listLinkProperty:
			L.i("    Dataloaded #{0}".format(c)); c+=1;
			link = Link(
					title = el['title'],
					url = el['url'],
					clicks = el['clicks']
				)
			link.save()
			self.links.append(link)
		L.i("LinkTestData load ended")
		return True
コード例 #42
0
ファイル: code.py プロジェクト: ozw1z5rd/gdg-pescara
	def t040_UserTechnology(self):
		"""tecnologie a cui un utente può essere associato"""
		L.i("UserTechnologyTestData load start")
		if len(self.technologyEntity) == 0:
			return False
		c = i = 0
		for el in TestData.listUserTecnology:
			L.i("    Dataloaded #{0}".format(c)); c+=1;
			UserTechnology(
				technology = self.technologyEntity[i], 
				rating = el['rating']
			).put()
			i += 1
		L.i("UserTechnologyTestData load ended")
		return True
コード例 #43
0
ファイル: code.py プロジェクト: ozw1z5rd/gdg-pescara
	def t080_Question(self):
		L.i("QuestionTestData load start")
		c = 0
		for el in TestData.listQuestion:
			q = Question(
				whoMadeTheQuestion = random.choice(self.users),
				body = el['body'],
				tags = el['tags'], 
				sector = list( [ x.key() for x in self.listOf(self.sectors,2)]),
				answer = [ random.choice(self.questionAnswers).key() ]
			)
			q.save()
			L.i("    Dataloaded #{0}".format(c)); c+=1;
		L.i("QuestionTestData load ended")
		return True
コード例 #44
0
ファイル: code.py プロジェクト: ozw1z5rd/gdg-pescara
	def t030_Quiz(self):
		"""Quiz, le domande a risposta multipla"""
		L.i("QuizTestData load start")
		c = 0
		for el in TestData.listQuiz:
			L.i("    Dataloaded #{0}".format(c)); c+=1;
			Quiz(
				title = el['title'],
				body = el['body'],
				dateStart = self.parseDate(el['dateStart']),
				dateEnd = self.parseDate(el['dateEnd']),
				answer= [ self.quizAnswerKeys[0] ], # todo -> deve recuperare i dati dal passo precedente
				user = el['user']
			)
		L.i("QuizTestData load ended")
		return True
コード例 #45
0
ファイル: code.py プロジェクト: ozw1z5rd/gdg-pescara
	def t045_User(self):
		"""Accounts"""
		L.i("UserTestData load start")
		c = 0
		for el in TestData.listUser:
			L.i("    Dataloaded #{0}".format(c)); c+=1;
			user = User(
				user_id = self.getRandomString(20),
				__email = el['__email'],
				__user = el['__user'], 
				federated_identity = None
			)
			self.users.append(user)
			user.put()
		L.i("UserTestData load ended")
		return True
コード例 #46
0
ファイル: code.py プロジェクト: ozw1z5rd/gdg-pescara
	def t020_QuizAnswer(self):
		"""Possibili risposte ai quiz"""
		L.i("QuizAnswerTestData load start")
		c= 0
		for el in TestData.listQuizAnswer:
			L.i("    Dataloaded #{0}".format(c)); c+=1;
			quizAnswer = QuizsAnswer( 
				text = el['text'],
				isCorrect=el['isCorrect'],
				click=el['click']
			)
			quizAnswer.put()
			self.quizAnswerKeys.append(
				quizAnswer.key()
			)
		L.i("QuizAnswerTestData load ended")
		return True
コード例 #47
0
ファイル: code.py プロジェクト: ozw1z5rd/gdg-pescara
	def get(self):
		L.i("Starting the TestData load")
		if self.t000_Technology() : 
			if self.t005_Link():
				if self.t010_Sector():
					if self.t020_QuizAnswer():
						if self.t030_Quiz():
							if self.t040_UserTechnology():
								if self.t045_User():
									if self.t050_Refer():
										if self.t065_Image():
											if self.t070_Post():
												if self.t075_QuestionAnswer():
													if self.t080_Question():
														L.i("Process completed")
														return self.response.write("Data Loaded")
		L.i("Process gone bad")
		return self.response.write("load error")
コード例 #48
0
	def put(self, *args, **dic):
		"""Store the TSC and before that does check, raise exception if something 
		is not correct.
		Failure reasons are
		1) closingDate < openingDate 
		2) encripted flag set and no password provided
		3) empty content """
	
		L.info("Storing the TSC")
		L.info("Dumping the anonymous " + str( self.anonymous ))
		L.info("Dumping the content " + str( self.content ))
		if self.encrypt and self.password is not None and len(self.password)==0:
			raise Exception("Can't store an encripted TSC with no password")
		if self.closingDate < self.openingDate: 
			raise Exception("closing date is before the opening date ")
		if len( self.content ) == 0:
			raise Exception("empty content ")
		
		return super( TimespaceCapsule, self).put(*args, **dic)
コード例 #49
0
ファイル: endpoint.py プロジェクト: ozw1z5rd/gdg-pescara
	def answerQuestion(self,request):
		L.i(request)
		return ""
コード例 #50
0
ファイル: endpoint.py プロジェクト: ozw1z5rd/gdg-pescara
	def rateQuestionAnswer(self,request):
		L.i(request)
		return
コード例 #51
0
ファイル: endpoint.py プロジェクト: ozw1z5rd/gdg-pescara
	def getQuiz(self,request):
		L.i(request)
		return ""
コード例 #52
0
ファイル: endpoint.py プロジェクト: ozw1z5rd/gdg-pescara
	def createQuestion(self,request):
		L.i(GDGPEQuestionCreateRequest)
		return ""
コード例 #53
0
ファイル: endpoint.py プロジェクト: ozw1z5rd/gdg-pescara
	def replyAnswer(self,request):
		L.i(request)
		return ""
コード例 #54
0
	def getCapsuleListForUser( user):
		L.info("Getting TSC list for user {0}".format(* user.get_email()))
		return TimespaceCapsule.all().filter("owner =",user )
コード例 #55
0
ファイル: main.py プロジェクト: ozw1z5rd/gdg-pescara
	def get(self):
		L.i("called Home")
		return self.response.write("It's Working! click here to load the data : <a href=\"/testData\">LOAD</a>")
コード例 #56
0
ファイル: endpoint.py プロジェクト: ozw1z5rd/gdg-pescara
	def createPost(self,request):
		L.i("Create Post Request")
		L.i(request)
		return ""
コード例 #57
0
ファイル: endpoint.py プロジェクト: ozw1z5rd/gdg-pescara
	def userInfo(self,request):
		L.i(request)
		return
コード例 #58
0
ファイル: endpoint.py プロジェクト: ozw1z5rd/gdg-pescara
	def unsubscribeUser(self,request):
		L.i(request)
		return ""