예제 #1
0
def renderAnchor(url,
                 text,
                 class_=None,
                 title=None,
                 target="_blank",
                 rel=None,
                 onClick=None):
    h = Html()
    h_html = h.tag(oohtml.HTML)
    h_body = h_html.tag(oohtml.BODY)
    h_Content = h_body.tag(oohtml.DIV)
    d = {}
    if (misc.isString(rel)):
        d['rel'] = rel
    if (misc.isString(onClick)):
        d['onClick'] = onClick
    if (misc.isString(class_)):
        d['class_'] = class_
    if (misc.isString(target)):
        d['target'] = target
    if (misc.isString(title)):
        d['title'] = title
    a = h_Content.tag(oohtml.A, href="%s" % (url), **d)
    a.text(text)
    return h_Content.toHtml().replace('<br>', '').replace('<BR>', '').replace(
        '<Br>', '').replace('<bR>', '').replace('\n', '').replace('\t', '')
예제 #2
0
def start_VyperProxy(server_version=None,version=None):
    global __server_version__, __version__
    if (misc.isString(server_version)):
        __server_version__ = server_version
    if (misc.isString(version)):
        __version__ = version
    BaseHTTPServer.test(VyperProxy, ThreadingHTTPServer, protocol="HTTP/1.1")
예제 #3
0
def http_post(url, parms, username=None, password=None, logging=None):
    import urllib, urllib2

    data = urllib.urlencode(parms)
    request = urllib2.Request(url, data)
    if (misc.isString(username)) and (misc.isString(password)):
        authenticate_request(request, username, password)
    return handle_response(request, logging=logging)
예제 #4
0
파일: CSV.py 프로젝트: raychorn/chrome_gui
 def fset(self, codec):
     if (not misc.isString(codec)):
         codec = self.__codec_name__(self.__codec__)
     if (misc.isString(codec)):
         import codecs
         try:
             self.__codec__ = codecs.getencoder(codec)
         except Exception as details:
             info_string = _utils.formattedException(details=details)
             print >>sys.stderr, info_string
예제 #5
0
 def __init__(self, title, items, orient, delim=' '):
     '''orient of True means '''
     self.lines = []
     if (not misc.isString(title)):
         print >> sys.stderr, '(PrettyPrint).ERROR :: title cannot be "%s", it must however be a string instance.' % str(
             title)
     else:
         if (not misc.isList(items)):
             print >> sys.stderr, '(PrettyPrint).ERROR :: items cannot be "%s", it must however be a list instance.' % str(
                 items)
         else:
             if (not isinstance(orient, bool)):
                 print >> sys.stderr, '(PrettyPrint).ERROR :: orient cannot be "%s", it must however be a bool instance.' % str(
                     orient)
             else:
                 if (not misc.isString(delim)):
                     print >> sys.stderr, '(PrettyPrint).ERROR :: delim cannot be "%s", it must however be a string instance.' % str(
                         delim)
                 else:
                     self.title = title
                     self.items = items
                     print title
                     n = 0
                     for p in items:
                         if (misc.isList(p)):
                             n = max(n, len(p))
                     stats = []
                     for i in xrange(len(items)):
                         stats.append(0)
                     for i in xrange(len(items)):
                         p = items[i]
                         if (misc.isList(p)):
                             for ii in xrange(len(p)):
                                 stats[i] = max(stats[i],
                                                len(p[ii]) + len(delim))
                     self.lines = []
                     for i in xrange(len(items)):
                         p = items[i]
                         if (misc.isList(p)):
                             aLine = []
                             for ii in xrange(len(p)):
                                 if (not orient):
                                     s = '%s%s' % (' ' *
                                                   (stats[ii] - len(p[ii])),
                                                   p[ii])
                                 else:
                                     s = '%s%s' % (p[ii], ' ' *
                                                   (stats[ii] - len(p[ii])))
                                 if (ii == (len(p) - 1)):
                                     s = s.rstrip()
                                 aLine.append(s)
                             self.lines.append(delim.join(aLine))
                         else:
                             self.lines.append(str(p))
예제 #6
0
def renderButton(value, title=None, onClick=None):
    h = Html()
    h_html = h.tag(oohtml.HTML)
    h_body = h_html.tag(oohtml.BODY)
    h_Content = h_body.tag(oohtml.DIV)
    d = {}
    if (misc.isString(onClick)):
        d['onClick'] = onClick
    if (misc.isString(title)):
        d['title'] = title
    value = value if (misc.isString(value)) else 'BUTTON'
    h_Content.tagINPUT(value=value, type_='button', **d)
    return h_Content.toHtml()
예제 #7
0
 def __init__(self, appName, publisherName='Vyper Logix Corp.'):
     self.__appName__ = '' if (appName is None) or (
         not misc.isString(appName)) else appName
     self.__publisherName__ = '' if (publisherName is None) or (
         not misc.isString(publisherName)) else publisherName
     self.__rootKeyName__ = '\\Software\\Digital River\\SoftwarePassport\\%s\\%s' % (
         self.publisherName, self.appName)
     self.__rootHKLM__ = winreg.get_key(winreg.HKEY.LOCAL_MACHINE,
                                        self.rootKeyName,
                                        winreg.KEY.ALL_ACCESS)
     self.__rootHKCU__ = winreg.get_key(winreg.HKEY.CURRENT_USER,
                                        self.rootKeyName,
                                        winreg.KEY.ALL_ACCESS)
예제 #8
0
def __makeWindowsShortcut(shortcut, targetPath, workingPath, description,
                          iconLocation):
    if (misc.isString(targetPath)):
        if (os.path.exists(targetPath)):
            shortcut.SetPath(targetPath)
    if (misc.isString(description)):
        if (len(description) > 0):
            shortcut.SetDescription(description)
    if (misc.isString(iconLocation)):
        if (os.path.exists(iconLocation)):
            shortcut.SetIconLocation(iconLocation, 0)
    if (misc.isString(workingPath)):
        if (os.path.exists(workingPath)):
            shortcut.SetWorkingDirectory(workingPath)
예제 #9
0
def dict2Obj(value):
    obj = value
    if (isinstance(value, dict)):
        if (value.has_key(const_class_symbol)):
            cname = value[const_class_symbol]
            try:
                toks = cname.split('.')
                s = 'from %s import %s\nobj=%s()' % (toks[0], '.'.join(
                    toks[1:-1]), '.'.join(toks[1:]))
                exec(s)
            except:
                obj = None
            if (obj):
                for k in [n for n in value.keys() if n != const_class_symbol]:
                    if not n.startswith('__'):
                        _k = '_%s' % toks[-1]
                    else:
                        _k = '%s' % (k)
                    try:
                        isQuoted = misc.isString(value[k])
                        _quote = '"' if isQuoted else ''
                        s = 'obj.%s=%s%s%s' % (_k.replace(
                            '__', ''), _quote, value[k], _quote)
                        exec(s)
                    except AttributeError:
                        pass
    return obj
예제 #10
0
def render_Button(id=None, src=None, title=None, onClick=None):
    h = Html()
    h_html = h.tag(oohtml.HTML)
    h_body = h_html.tag(oohtml.BODY)
    h_Content = h_body.tag(oohtml.DIV)
    d = {}
    if (misc.isString(onClick)):
        d['onClick'] = onClick
    if (misc.isString(title)):
        d['title'] = title
    if (misc.isString(id)):
        d['id'] = id
    d['type'] = 'button'
    btn = h_Content.tag(oohtml.BUTTON, **d)
    btn.tag_IMG(src=src, border=0)
    return h_Content.toHtml()
예제 #11
0
    def renderHTML(self, subj, body):
        from vyperlogix.html import myOOHTML as oohtml
        h_html = oohtml.Html()

        if (misc.isString(subj)) and (misc.isList(body)):
            h_html.text(oohtml.oohtml.DOCTYPE_40_TRANSITIONAL)

            html_html = h_html.tag(oohtml.oohtml.HTML)
            head_html = html_html.tag(oohtml.oohtml.HEAD)
            head_html.tagOp(oohtml.oohtml.META,
                            http_equiv=oohtml.oohtml.CONTENT_TYPE,
                            content=oohtml.oohtml.TEXT_HTML_CHARSET_ISO_8859_1)
            head_html.metas((
                oohtml.oohtml.AUTHOR, "Ray C Horn ([email protected])"
            ), (oohtml.oohtml.KEYWORDS, "SMTP Email Message"), (
                oohtml.oohtml.DESCRIPTION,
                "The contents of this email are considered to be confidential unless otherwise specified."
            ), (oohtml.oohtml.ROBOTS, oohtml.oohtml.ALL))
            head_html.tagTITLE('SMTP Email Message')
            body_html = html_html.tag(oohtml.oohtml.BODY)
            idContent = body_html.tag(oohtml.oohtml.DIV,
                                      id="content",
                                      style="background-color: white")

            idContent.html_simple_table(body)
            pass
        else:
            print >> sys.stderr, '%s :: "subj" parm must be of type str and "body" parm must be of type list rather than of types "%s" and "%s", respectively.' % (
                ObjectTypeName.objectSignature(self), type(subj), type(body))
        return h_html.toHtml()
예제 #12
0
def deleteSalesForceObjects(sfdc, list_of_ids):
    import sys, traceback
    from vyperlogix import misc
    from vyperlogix.misc import ObjectTypeName
    deleted_ids = []
    t_sfdc = ObjectTypeName.typeName(sfdc)
    if (t_sfdc.find('.connection.Connection') > -1):
        if (all([misc.isString(id) for id in list_of_ids])):
            try:
                delete_result = sfdc.delete(list_of_ids)
                deleted_ids = sfdc.resultToIdList(delete_result,
                                                  success_status=True)
            except Exception as details:
                exc_info = sys.exc_info()
                info_string = '\n'.join(traceback.format_exception(*exc_info))
                info_string = '%s :: Cannot process, Reason: %s\n%s' % (
                    misc.funcName(), str(details), info_string)
                print >> sys.stderr, info_string
        else:
            info_string = '%s :: Cannot process, Reason: "%s" is not a list of id(s) each being a string.' % (
                misc.funcName(), str(list_of_ids))
            print >> sys.stderr, info_string
    else:
        info_string = '%s :: Cannot process, Reason: "%s" is not a valid connection object to pyax however it appears to be "%s".' % (
            misc.funcName(), str(sfdc), t_sfdc)
        print >> sys.stderr, info_string
    return deleted_ids
예제 #13
0
 def fset(self, object_name):
     if (misc.isString(object_name)):
         self.__object_name = object_name
         self.__description__ = self.__sfQuery__.sfdc.describeSObject(
             object_name)
         self.__factory = ClassFactory(self.__sfQuery__.sfdc,
                                       object_name)
예제 #14
0
 def __call__(self, *args, **kwargs):
     '''
     Automatically redirect all unknown methods to the underlying Pyro Proxy object.
     Builds a request in the format of: contacts.getPortalContactByEmail('*****@*****.**')
         that is turned into: request_objects('contacts.getPortalContactByEmail("%s")' % (contact_username))
     '''
     m = super(MagicObject2, self).__call__(*args, **kwargs)[1:]
     if (len(m[0]) > 1):
         isExecute = (m[0][-1] == 'execute') and (len(args)
                                                  == 0) and (len(kwargs)
                                                             == 0)
         if (isExecute):
             s = 'self.proxy.request_objects(\'%s.%s\')' % (m[0][0],
                                                            m[0][1])
         else:
             s = 'self.proxy.request_objects(\'%s.%s(%s)\')' % (
                 m[0][0], m[0][1], _utils.args(*args, **kwargs))
     else:
         s = 'self.proxy.%s(%s)' % (m[0][0], _utils.args(*args, **kwargs))
     lastError = 'n/a'
     objs = self.get_objects(s)
     if (isinstance(objs, tuple)):
         objs = list(objs)
         lastError = objs[-1]
         objs = objs[0]
     if (_isRunningLocal):
         print '"%s" --> %s' % (s, objs if
                                (not misc.isString(objs)) else '"%s"' %
                                (objs))
     self.__reset_magic__()
     if (not isinstance(objs, list)) and (not isinstance(
             objs, tuple)) and (not lists.isDict(objs)):
         return objs
     return self.asSmartObjects(objs), lastError
예제 #15
0
    def __handleConnection__(self, connHandle):
        try:
            if (connHandle.channel):
                val = connHandle.server.__callback__(connHandle, None)
                if ((val) and (misc.isString(val)) and (len(val) > 0)):
                    if (connHandle.server.__send__(connHandle, val)):
                        #connHandle.server.shutdown(connHandle)
                        print >> sys.stderr, '(handleConnection).1 __Q__.isRunning=(%s).' % (
                            SocketServer.__Q__.isRunning)

                while SocketServer.__Q__.isRunning:
                    print >> sys.stderr, '(handleConnection).2 __Q__.isRunning=(%s)' % (
                        SocketServer.__Q__.isRunning)
                    data = connHandle.channel.recv(connHandle.server.iBufSize)
                    print '%s --> (%s) "%s"' % (misc.callersName(), 'NOT' if
                                                (not data) else 'DATA', data)
                    if not data:
                        if (connHandle.dropConnectionOnErrors):
                            connHandle.server.shutdown(connHandle)
                            break
                    connHandle.server.processData(connHandle, data)
                print >> sys.stderr, '(handleConnection).3 __Q__.isRunning=(%s)' % (
                    SocketServer.__Q__.isRunning)
                connHandle.channel.close()
        except Exception as details:
            print >> sys.stderr, '(handleConnection).Error "%s".' % (
                str(details))
            ex = str(details)
            if (ex.find('Connection reset by peer') > -1) or (
                    ex.find('forcibly closed by the remote host') > -1):
                connHandle.server.shutdown(connHandle)
예제 #16
0
def rewrite_anchor(_url, params='', callback=None, isDebug=False):
    from vyperlogix import misc
    from vyperlogix.misc import _utils
    _url = _url.lower()
    subject = _url
    if (_url.find('.php') > -1):
        toks2 = _url.split('"')
        toks2_3 = (len(toks2) == 3)
        if (len(toks2) == 1) or (toks2_3):
            toks3 = toks2[1 if (toks2_3) else 0].split('?')
            if (len(toks3) == 2):
                try:
                    toks4 = [
                        tuple(t.split('='))
                        for t in toks3[-1].replace('&&', '&').split('&')
                    ]
                    d_toks4 = dict([t for t in toks4 if (len(t) == 2)])
                    if (len(params) > 0):
                        d_toks4[
                            'params'] = _utils.parse_key_value_pairs_as_dict(
                                params) if (misc.isString(params)) else ''
                    if (callable(callback)):
                        try:
                            if (isDebug):
                                print '%s :: %s' % (misc.funcName(),
                                                    str(d_toks4))
                            href = callback(d_toks4)
                        except:
                            href = _url  # do nothing if there is not a callback...
                    return href
                except Exception as details:
                    print >> sys.stderr, _utils.formattedException(
                        details=details)
    return _url
예제 #17
0
 def __init__(self, sleepy_mongoose):
     '''
     See also: https://github.com/kchodorow/sleepy.mongoose/wiki/
     '''
     toks = sleepy_mongoose.split(':')
     try:
         self.__sleepy_mongoose__ = sleepy_mongoose if (misc.isString(
             toks[0]) and misc.isInteger(int(toks[-1]))) else None
     except:
         self.__sleepy_mongoose__ = None
     self.__database__ = None
     self.__collection__ = None
     self.__server__ = None
     self.__server_name__ = None
     self.__last_exception__ = None
     self.__n__ = None
     self.__docs__ = None
     self.__criteria__ = None
     self.__newobj__ = None
     self.__fields__ = None
     self.__sort__ = None
     self.__skip__ = None
     self.__limit__ = None
     self.__explain__ = None
     self.__batch_size__ = None
     self.__id__ = None
예제 #18
0
    def __setitem__(self, key, value):
        from vyperlogix.crypto.Encryptors import Encryptors
        from vyperlogix.misc import GenPasswd

        key = key if (misc.isString(key)) else str(key)
        if (self.has_key(key)) and (value == None):
            self.__delitem__(key)
        else:
            if (misc.isList(value)):
                value = [
                    v if (not lists.can_asDict(v)) else v.asDict()
                    for v in value
                ]
            else:
                value = value if (
                    not lists.can_asDict(value)) else value.asDict()
            if (self.isPickleMethodUseStrings):
                if (not misc.isString(value)):
                    if not misc.isList(value):
                        value = list(value) if (not isinstance(
                            value, dict)) else [(k, v)
                                                for k, v in value.iteritems()]
                    val = [
                        '|'.join([str(x) for x in v])
                        if isinstance(v, tuple) else str(v) for v in value
                    ]
                    if (len(val) > 0):
                        value = ','.join(val) if (len(val) > 1) else val[0]
                    else:
                        value = ''
            elif (self.isPickleMethodUseMarshal):
                value = strToHex(marshal.dumps(value, 2))
            elif (self.isPickleMethodUseBsdDbShelf):
                value = self.pickleItem(value)
            elif (self.isPickleMethodUseSafeSerializer):
                value = dumps(value, CompressionOption.compression)
            elif (self.isPickleMethodUseCerealizer):
                #cls = eval(ObjectTypeName.typeClassName(value))
                #if (not cerealizer.isRegistered(cls)):
                #cerealizer.register(cls)
                value = cerealizer.dumps(value)
            if (not self.isPickleMethodUseSafeSerializer):
                if (self.isPickleMethodUseZLIB):
                    value = zlib.compress(value, zlib.Z_BEST_COMPRESSION)
                elif (self.isPickleMethodUseLZMA):
                    value = pylzma.compress(value, eos=1)
            self.__db[key] = value
예제 #19
0
파일: QIF.py 프로젝트: raychorn/chrome_gui
 def dateSpecToFloat(self, date_or_toks):
     _date = 0.0
     toks = date_or_toks
     if (misc.isString(date_or_toks)):
         toks = self.parseDate(date_or_toks)
     if (len(toks) == 3):
         _date = julian.Julian(int(toks[0]), int(toks[1]), int(toks[2]))
     return _date
예제 #20
0
 def __str__(self):
     ascii_only = lambda s: ''.join(
         [ch for ch in s if (ord(ch) >= 32) and (ord(ch) <= 127)])
     _vars = []
     for k, v in self.__dict__.iteritems():
         _vars.append('%s="%s"' % (real_k(k), ascii_only(v) if
                                   (misc.isString(v)) else str(v)))
     return '(%s) %s' % (str(self.__class__), ', '.join(_vars))
예제 #21
0
파일: QIF.py 프로젝트: raychorn/chrome_gui
 def set_date(self, dt):
     if (misc.isList(dt)):
         dt = '/'.join([str(n) for n in dt])
     self.__date = [
         int(n) if misc.isString(n) else n for n in self.parseDate(dt)
     ]
     self.__mm, self.__dd, self.__yyyy = self.__date
     self.__julianDate = julian.Julian(self.__mm, self.__dd, self.__yyyy)
예제 #22
0
 def __getitem__(self, key):
     lower = lambda value: value.lower() if (misc.isString(value)
                                             ) else value
     _key = lower(key)
     for k in self.keys():
         if (lower(k) == _key):
             val = super(HashedFuzzyLists, self).__getitem__(k)
             return val
     return None
예제 #23
0
파일: QIF.py 프로젝트: raychorn/chrome_gui
 def __init__(self, fname=None, dateSpec=None):
     self.__items = []
     self.fileName = fname if (misc.isString(fname)) and (os.path.exists(
         fname)) else 'Z:/#zDisk/#IRS/Microsoft Money (1996-2007).qif'
     self.dateSpec = dateSpec
     if (self.dateSpec):
         if (misc.isList(self.dateSpec)):
             if (len(self.dateSpec) >= 1):
                 if (misc.isString(self.dateSpec[0])):
                     self.dateSpec[0] = self.dateSpecToFloat(
                         self.dateSpec[0])
             if (len(self.dateSpec) > 1):
                 if (misc.isString(self.dateSpec[-1])):
                     self.dateSpec[-1] = self.dateSpecToFloat(
                         self.dateSpec[-1])
         elif (misc.isString(self.dateSpec)):
             self.dateSpec = [self.dateSpecToFloat(self.dateSpec)]
         else:
             self.dateSpec = [self.dateSpec]
예제 #24
0
 def __setitem__(self, key, value):
     key = key if (misc.isString(key)) else str(key)
     if (self.has_key(key)):
         bucket = super(PickledHash2, self).__getitem__(key)
         if (misc.isList(bucket)):
             bucket.append(value)
             super(PickledHash2, self).__setitem__(key, bucket)
         else:
             super(PickledHash2, self).__setitem__(key, [value])
     else:
         super(PickledHash2, self).__setitem__(key, value)
예제 #25
0
파일: QIF.py 프로젝트: raychorn/chrome_gui
 def parseDate(self, dt):
     if (misc.isString(dt)):
         toks = dt.split('/')
         if (len(toks) == 1):
             toks = dt.split('-')
         if (len(toks) == 2):
             _toks = toks[-1].split("'")
             del toks[-1]
             for t in _toks:
                 toks.append(t)
         dt = toks
     return dt
예제 #26
0
 def encode(self, codec_name):
     '''encodes the contents of the object using the named codec'''
     if (isDict(self)):
         for k, v in self.iteritems():
             self[k] = v.encode(codec_name)
     elif (isinstance(self, list)):
         for i in xrange(len(self)):
             self[i] = self[i].encode(codec_name)
     elif (misc.isString(self)):
         self = self.encode(codec_name)
     else:
         self = str(self).encode(codec_name)
예제 #27
0
def render_captcha_form(request,
                        form_name=None,
                        font_name=None,
                        font_size=18,
                        choices='QWERTYPASDFGHJKLZXCVBNM23456789',
                        fill=(255, 255, 255),
                        bgImage='bg.jpg'):
    try:
        imghash = ''
        tempname = ''
        imgtext = ''
        try:
            from random import choice
            import Image, ImageDraw, ImageFont, sha
            _settings = django_utils.get_from_session(
                request, 'settings', default=lists.HashedLists2())
            if (not _settings.has_key('SECRET_KEY')):
                from django.conf import settings as _settings
            SALT = _settings.SECRET_KEY[:20]
            imgtext = ''.join([choice(choices) for i in range(5)])
            imghash = sha.new(SALT + imgtext).hexdigest()
            image_fname = os.path.join(_settings.MEDIA_ROOT, bgImage)
            im = Image.open(image_fname)
            draw = ImageDraw.Draw(im)
            font_fname = os.path.join(_settings.MEDIA_ROOT, font_name)
            font = ImageFont.truetype(font_fname, font_size)
            draw.text((10, 10), imgtext, font=font, fill=fill)
            _captcha_symbol = 'captcha'
            image_name = '%s.jpg' % (imgtext)
            temp = os.path.join(_settings.MEDIA_ROOT, _captcha_symbol,
                                image_name)
            _utils._makeDirs(os.path.dirname(temp))
            tempname = '/'.join(
                [_settings.MEDIA_URL, _captcha_symbol, image_name])
            if (os.path.exists(tempname)):
                os.remove(tempname)
            im.save(temp, "JPEG")
        except:
            imghash = ''
            tempname = ''
            imgtext = ''
    except Exception as e:
        return _utils.formattedException(details=e)

    if (misc.isString(form_name)):
        c = {'hash': imghash, 'tempname': tempname}
        http_host = django_utils.get_http_host(request).split(':')[0]
        if (django_utils.isBeingDebugged(http_host)):
            c['imgtext'] = imgtext
        ctx = Context(c, autoescape=False)
        return render_to_string(form_name, context_instance=ctx)
    else:
        return render_to_string('405.html', {})
예제 #28
0
파일: QIF.py 프로젝트: raychorn/chrome_gui
 def getDatabaseFileNameFor(self, yyyy):
     toks = self.fileName.split('.')
     if (misc.isString(yyyy)):
         toks[0] += '_%s' % yyyy
     else:
         toks[0] += '_%d' % yyyy
     toks[-1] = 'db'
     fname = '.'.join(toks)
     dname = os.sep.join([self.filepath, const_money_symbol])
     bname = os.path.basename(fname)
     fname = os.sep.join([dname, bname])
     if (not os.path.exists(dname)):
         os.mkdir(dname)
     return fname
예제 #29
0
파일: views.py 프로젝트: raychorn/knowu
def create_data(request):
    from g import states, fetch_data_for
    items = JsonData.objects.all()
    for item in items:
        item.delete()
    for statename in states:
        __json__ = fetch_data_for(statename)
        item = JsonData()
        item.statename = statename
        if (misc.isString(__json__)):
            item.data = json.dumps(json.loads(__json__),indent=4)
        else:
            item.data = json.dumps(__json__,indent=4)
        item.save()
    return HttpResponseRedirect('/data/')
예제 #30
0
 def encoder(value):
     if isinstance(value, unicode):
         value = value.strip()
         if len(value) == 0:
             return None
         else:
             return value.encode(encoding)
     elif misc.isString(value):
         value = str(value).strip()
         if len(value) == 0:
             return None
         else:
             return value
     else:
         return value
예제 #31
0
 def func(*args, **kwargs):
     kw = kwargs.items()
     kw.sort()
     key = (tuple([arg for arg in list(args) if (misc.isString(arg))]), tuple(kw))
     try:
         v = _cache[key]
         et = time.time() - v[1]
         if (self.isDebugging):
             print '\n%s :: cache :: "%s"' % (ObjectTypeName.objectSignature(self),key)
         if (et) > self.timeout:
             raise KeyError
     except KeyError:
         v = _cache[key] = f(*args,**kwargs),time.time()
         if (self.isDebugging):
             print '\n%s :: new (%d) :: "%s"' % (ObjectTypeName.objectSignature(self),len(_cache),key)
     return v[0]
예제 #32
0
IS_NOT_PRODUCTION_WEB_SERVER = not IS_PRODUCTION_WEB_SERVER
print '2.DEBUG=%s' % (DEBUG)
print '3.DATABASES=%s' % (DATABASES)
print '4.IS_PRODUCTION_SERVER=%s' % (IS_PRODUCTION_SERVER)
print '5.IS_PRODUCTION_WEB_SERVER=%s' % (IS_PRODUCTION_WEB_SERVER)
print '5a.IS_NOT_PRODUCTION_WEB_SERVER=%s' % (IS_NOT_PRODUCTION_WEB_SERVER)
TEMPLATE_DEBUG = DEBUG

IS_HTTPS_REQUIRED = False

MONGODBS = 'gps_1M'
MONGODB_COLLECTION = 'num_connections'

MONGODB_TEST = None
print '6.MONGODB_ENDPOINT=%s' % (MONGODB_ENDPOINT)
if (misc.isString(MONGODB_ENDPOINT)):
    MONGODB_TEST = 'http://%s/test' % (MONGODB_ENDPOINT)
    s = _urllib2.get(MONGODB_TEST)
    if (len(s) == 0):
        MONGODB_TEST = MONGODB_ENDPOINT= None
print '7.MONGODB_ENDPOINT=%s' % (MONGODB_ENDPOINT)

print '8.SLEEPY_MONGOOSE=%s' % (SLEEPY_MONGOOSE)
if (misc.isString(SLEEPY_MONGOOSE)):
    u = 'http://%s/' % (SLEEPY_MONGOOSE)
    s = _urllib2.get(u)
    if (len(s) == 0):
        SLEEPY_MONGOOSE = None
print '9.SLEEPY_MONGOOSE=%s' % (SLEEPY_MONGOOSE)

# Local time zone for this installation. Choices can be found here:
예제 #33
0
    def startup(self):
	# When ReverseProxy is used the asyncore.loop() handles this part of the process...
	mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
	if (logger):
	    logger.info('%s.startup() :: self.ipAddr=[%s], self.port=[%s]' % (self.__class__,self.ipAddr,self.port))
	mySocket.bind ( ( self.ipAddr, self.port) )
	mySocket.listen ( 1 )
	channel, details = mySocket.accept()
	if (logger):
	    logger.info('(%s) Opened a connection with "%s".' % (self.port,details))
	__data__ = ''
	__filename__ = None
	__fOut__ = None
	__chunk_count__ = 0
	__re1__ = re.compile("@@@filename=(?P<filename>.*)@@@", re.DOTALL | re.MULTILINE)
	__re2__ = re.compile("@@@address=(?P<address>.*)@@@", re.DOTALL | re.MULTILINE)
	while True:
	    try:
		data = channel.recv(8192)
		if (data) and (len(data) > 0):
		    for ch in data:
			if (not __filename__) and (ord(ch) == 0):
			    if (__data__) and (misc.isString(__data__)) and (len(__data__) > 0) and (callable(self.callback)):
				self.__handler__(__data__)
			    __data__ = ''
			else:
			    __data__ += ch
			    matches1 = __re1__.search(__data__)
			    matches2 = __re2__.search(__data__)
			    if (matches1):
				f = matches1.groupdict().get('filename',None)
				if (f):
				    __filename__ = f
				    dirname = os.path.dirname(__filename__)
				    if (callable(self.callback)):
					dirname2 = self.__handler__(dirname)
					if (misc.isIterable(dirname2) and (len(dirname2) > 0)):
					    dirname2 = dirname2[0]
					if (dirname != dirname2):
					    __filename__ = __filename__.replace(dirname,dirname2)
					    dirname = dirname2
				    if (not os.path.exists(dirname)):
					os.makedirs(dirname)
				    __fOut__ = open(__filename__,'wb')
				    __data__ = ''
			    elif (matches2):
				f = matches2.groupdict().get('address',None)
				if (f):
				    self.address = f
				    if (logger):
					logger.debug('Address is "%s".' % (self.address))
				    __data__ = ''
			    else:
				i = __data__.find(self.eof)
				if (__filename__) and (i > -1):
				    __data__ = [ch for ch in __data__]
				    del __data__[i:]
				    __data__ = ''.join(__data__)
				    __fOut__.write(__data__)
				    __fOut__.flush()
				    __fOut__.close()
				    if (callable(self.callback)):
					self.__handler__(__filename__)
				    if (_utils.is_valid_ip_and_port(self.address)):
					connect_to_ip,connect_to_port = parse_ip_address_and_port(self.address, default_ip='0.0.0.0', default_port=51555)
					__writer__ = SocketWriter(connect_to_ip, connect_to_port,retry=True)
					__writer__.send('@@@delete=%s@@@' % (os.path.basename(__filename__)))
					__writer__.close()
				    __filename__ = None
				    __fOut__ = None
				    __data__ = ''
		    if (__filename__):
			__chunk_count__ += 1
			if (logger):
			    logger.debug('DEBUG: writing (%s bytes) x (%s) --> "%s"' % (len(__data__),__chunk_count__,__fOut__.name))
			__fOut__.write(__data__)
			__data__ = ''
	    except socket.error:
		mySocket.close()
		mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
		if (logger):
		    logger.info('%s.reconnect() :: self.ipAddr=[%s], self.port=[%s]' % (self.__class__,self.ipAddr,self.port))
		mySocket.bind ( ( self.ipAddr, self.port) )
		mySocket.listen ( 1 )
		channel, details = mySocket.accept()
		if (logger):
		    logger.info('(%s) Reopened a connection with "%s".' % (self.port,details))
		__data__ = ''
		__filename__ = None
		__fOut__ = None
		__chunk_count__ = 0
	    except Exception, details:
		info_string = _utils.formattedException(details=details)
		if (logger):
		    logger.exception('EXCEPTION: %s\n%s' % (details,info_string))
예제 #34
0
    def send_activation_email(self,new_user,password,registration_profile,air_id='',domain_override='',prefix='',reason='',data={},error_symbol=None):
        from vyperlogix.products import keys
        _current_site_ = domain_override if (domain_override and len(domain_override) > 0) else settings.CURRENT_SITE
        _current_site = '.'.join([t.capitalize() for t in _current_site_.split('.')])
        
        subject = django_utils.render_from_string(__registration_activation_email_subject__,context=Context({ 'site': _current_site },autoescape=False))
        subject = ''.join(subject.splitlines()) # Email subject *must not* contain newlines

        c = { 'activation_key': keys.encode('%s;%s;%s'%(registration_profile.user.email,password,registration_profile.activation_key)),
              'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
              'site': _current_site if (settings.IS_PRODUCTION_WEB_SERVER) else settings.LOCALHOST,
              'site_name': _current_site,
              'ssl':'s' if (settings.IS_PRODUCTION_SERVER) else '',
              }
        c['activation_symbol'] = '%sactivation/' % ('' if _current_site.endswith('/') else '/')
        message = django_utils.render_from_string(__registration_activation_email__,context=c)
        message_html = django_utils.render_from_string(__registration_activation_email_html__,context=c)

        try:
	    logging.log(logging.INFO,'sender="%s Support <%s>"' % (air_sender(air_id),air_sender(air_id)))
	    queue_email(air_sender(air_id),new_user.email,"Your User Account %sActivation%s for %s" % (prefix,' (%s)'%(reason) if (reason and misc.isString(reason) and (len(reason) > 0)) else '',air_site(air_id)),message,message_html,air_id,is_html=True,data=data,error_symbol=error_symbol)
        except Exception, e:
            info_string = _utils.formattedException(details=e)
            logging.error('RegistrationManager.create_inactive_user.ERROR --> %s' % (info_string))