Example #1
    def _prepare_json_kwargs(self, dumps=False, loads=False):
        assert dumps or loads, "Please, supply ``dumps`` or ``loads`` " "keyword argument first."

        if dumps:
            args = (
            args = ("encoding", "cls", "object_hook", "parse_float", "parse_int", "parse_constant", "object_paris_hook")

        kwargs = {}

        for arg in args:
            cls_arg = "cls"

            if arg == "cls":
                cls_arg = "encoder_cls" if dumps else "decoder_cls"

            if not hasattr(self, arg) and not hasattr(self, cls_arg):

            value = getattr(self, cls_arg) if hasattr(self, cls_arg) else getattr(self, arg)
            kwargs.update({arg: value})

        return kwargs
Example #2
 def __call__(self):
     uid = self.request.get("Sample_uid", False)
     if not uid:
         return []
     uc = getToolByName(self.context, "uid_catalog")
     proxies = uc(UID=uid)
     if not proxies:
         return []
     sample = proxies[0].getObject()
     sample_schema = sample.Schema()
     sample_fields = dict([(f.getName(), f) for f in sample_schema.fields()])
     ar_schema = self.context.Schema()
     ar_fields = [
         f.getName() for f in ar_schema.fields() if f.widget.isVisible(self.context, "secondary") == "disabled"
     ret = []
     for fieldname in ar_fields:
         if fieldname in sample_fields:
             fieldvalue = sample_fields[fieldname].getAccessor(sample)()
             if fieldvalue is None:
                 fieldvalue = ""
             if hasattr(fieldvalue, "Title"):
                 # Must store UID for referencefields.
                 ret.append([fieldname + "_uid", fieldvalue.UID()])
                 fieldvalue = fieldvalue.Title()
             if hasattr(fieldvalue, "year"):
                 fieldvalue = fieldvalue.strftime(self.date_format_short)
             fieldvalue = ""
         ret.append([fieldname, fieldvalue])
     return json.dumps(ret)
Example #3
    def post_validate(self):
        xmlText = []
        xmlChildren = []
        for child in self.children:
            if isinstance(child, xmlbase.XMLText):

        if len(xmlText) == 0 and hasattr(self, "n_to_v"):

        elif not hasattr(self, "n_to_v"):
            self.n_to_v = dict(
                [(i, x) for i, x in enumerate("".join([str(x) for x in xmlText]).split(self.attrib["delimiter"]))]
            self.children = xmlChildren

        if "n" in self.attrib:
            if self.attrib["n"] != len(self.n_to_v):
                raise XMLValidationError(
                    'LookupTable["n"] (%d) should be equal to len(LookupTable.n_to_v) (%d)'
                    % (self.attrib["n"], len(self.n_to_v))
            self.attrib["n"] = len(self.n_to_v)
    def get_attribute(self, instance):
        # Can't have any relationships if not created
        if hasattr(instance, "pk") and instance.pk is None:
            return []

        relationship = get_attribute(instance, self.source_attrs)
        return relationship.all() if (hasattr(relationship, "all")) else relationship
Example #5
    def scaffold_list_columns(self):
            Return a list of columns from the model.
        columns = []

        for p in self._get_model_iterator():
            # Verify type
            if hasattr(p, "direction"):
                if self.column_display_all_relations or p.direction.name == "MANYTOONE":
            elif hasattr(p, "columns"):
                column_inherited_primary_key = False
                if len(p.columns) != 1:
                    if is_inherited_primary_key(p):
                        column = get_column_for_current_model(p)
                        raise TypeError("Can not convert multiple-column properties (%s.%s)" % (self.model, p.key))
                    # Grab column
                    column = p.columns[0]

                # An inherited primary key has a foreign key as well
                if column.foreign_keys and not is_inherited_primary_key(p):

                if not self.column_display_pk and column.primary_key:


        return columns
    def process_request(self, request):
        __traceback_hide__ = True
        if self.show_toolbar(request):

            urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
            if isinstance(urlconf, basestring):
                urlconf = import_module(getattr(request, "urlconf", settings.ROOT_URLCONF))

            if urlconf not in self._urlconfs:
                new_urlconf = imp.new_module("urlconf")
                new_urlconf.urlpatterns = debug_toolbar.urls.urlpatterns + patterns("", ("", include(urlconf)))

                if hasattr(urlconf, "handler404"):
                    new_urlconf.handler404 = urlconf.handler404
                if hasattr(urlconf, "handler500"):
                    new_urlconf.handler500 = urlconf.handler500

                self._urlconfs[urlconf] = new_urlconf

            request.urlconf = self._urlconfs[urlconf]

            toolbar = DebugToolbar(request)
            for panel in toolbar.panels:
            self.__class__.debug_toolbars[thread.get_ident()] = toolbar
Example #7
    def test_smart_strings(self):
        """Lxml smart strings return values"""

        class SmartStringsSelector(Selector):
            _lxml_smart_strings = True

        body = """<body>
                    <div class='one'>
                    <div class='two'>

        response = HtmlResponse(url="http://example.com", body=body)

        # .getparent() is available for text nodes and attributes
        # only when smart_strings are on
        x = self.sscls(response)
        li_text = x.xpath("//li/text()")
        self.assertFalse(any(map(lambda e: hasattr(e._root, "getparent"), li_text)))
        div_class = x.xpath("//div/@class")
        self.assertFalse(any(map(lambda e: hasattr(e._root, "getparent"), div_class)))

        x = SmartStringsSelector(response)
        li_text = x.xpath("//li/text()")
        self.assertTrue(all(map(lambda e: hasattr(e._root, "getparent"), li_text)))
        div_class = x.xpath("//div/@class")
        self.assertTrue(all(map(lambda e: hasattr(e._root, "getparent"), div_class)))
Example #8
def get_file(fileorpath):
    """Get a file-like object, whether given a FileUpload object or a path."""
    if hasattr(fileorpath, "path"):  # FileUpload
        return storage.open(fileorpath.path)
    if hasattr(fileorpath, "name"):
        return fileorpath
    return storage.open(fileorpath)
Example #9
    def templates(self, template=None, **kwargs):
        scene = kwargs.get("handler", user.ui.scene)
        actors = scene.cast.actors
        items = scene.data.sprites
        # Cast
        if actors:
            tgt = kwargs.get("target", self.target)
            if not tgt in actors:
                tgt = actors[0]
            castinf = [i for i in tgt.dft if hasattr(tgt, i)]
            castopt = ()
            if self.info in castinf:
                inf = getattr(tgt, self.info)
                keyget = None
                if hasattr(inf, "keys") and inf:
                        if inf.keys()[0].type == "actor":
                            keyget = ("key", "arrowsel", {"values": actors})
                        elif inf.keys()[0].type == "node":
                            keyget = ("key", "extsel", {"val": items[0], "values": items, "selsource": scene})
                if keyget is None and hasattr(inf, "__iter__"):
                    keyget = ("key", "input", {"legend": "Key"})
                if keyget:
                    castopt += (keyget,)
            templatelist = self.templatelist(scene, items, actors, (castinf, castopt))
            templatelist = self.templatelist(scene, items)

        if template is None:
            return templatelist
            return templatelist[template]
Example #10
 def getvalue(x):
     if hasattr(x, "file") and hasattr(x, "value"):
         return x.value
     elif hasattr(x, "value"):
         return unicodify(x.value)
         return unicodify(x)
Example #11
def set_target(obj_id_src, obj_id_target):
    obj = get_object(obj_id_src)
    target = get_object(obj_id_target)
    for obj in physics.body_update_list:
        if hasattr(obj, "obj_id"):
            if obj.obj_id == obj_id_src and hasattr(obj, "target"):
                obj.target = target
def model_post_save(sender, **kwargs):
    A signal handler to run any model presave activities and trigger the built-in
    pre save signals
    1. Detect if the model has been changed and appy these changes to the db
    2. Trigger the pre creation signal
    3. Trigger the pre update signal

    MetaModel = sender
    meta_model = kwargs["instance"]
    update = hasattr(meta_model, "_update")
    creation = hasattr(meta_model, "_creation")

    if update or creation:
        DynamicModel = meta_model.get_model()
        # Create a new table if it's missing

    if creation:
        post_model_creation.send(sender=MetaModel, new_model=DynamicModel)
        del meta_model._creation

    if update:
        post_model_update.send(sender=MetaModel, old_model=meta_model._update, new_model=DynamicModel)
        del meta_model._update
def get_bitno_lin_comb(bloom_filter, key):
    """Apply num_probes_k hash functions to key.  Generate the array index and bitmask corresponding to each result"""

    # This one assumes key is either bytes or str (or other list of integers)

    # I'd love to check for long too, but that doesn't exist in 3.2, and 2.5 doesn't have the numbers.Integral base type
    if hasattr(key, "__divmod__"):
        int_list = []
        temp = key
        while temp:
            quotient, remainder = divmod(temp, 256)
            temp = quotient
    elif hasattr(key[0], "__divmod__"):
        int_list = key
    elif isinstance(key[0], str):
        int_list = [ord(char) for char in key]
        raise TypeError("Sorry, I do not know how to hash this type")

    hash_value1 = hash1(int_list)
    hash_value2 = hash2(int_list)

    # We're using linear combinations of hash_value1 and hash_value2 to obtain num_probes_k hash functions
    for probeno in range(1, bloom_filter.num_probes_k + 1):
        bit_index = hash_value1 + probeno * hash_value2
        yield bit_index % bloom_filter.num_bits_m
Example #14
 def validate(self):
         if self.diagnoseId is None:
             return FAILURE
         diagnose = Diagnose.getDiagnoseById(self.diagnoseId)
         if diagnose is None:
             return FAILURE
         if diagnose.doctorId and hasattr(diagnose, "doctor") and diagnose.doctor and diagnose.doctor.userId:
             self.receiverId = diagnose.doctor.userId
             return FAILURE
         if diagnose.patientId and hasattr(diagnose, "patient") and diagnose.patient and diagnose.patient.userID:
             self.userId = diagnose.patient.userID
             return FAILURE
         # if self.title is None:
         #     return FAILURE
         if self.content is None or len(self.content) < 10:
             failure = ResultStatus(FAILURE.status, "输入的内容长度必须大于等于10")
             return failure
         if self.score is None or self.score == u"":
             return FAILURE
             self.score = string.atoi(self.score)
     except Exception, e:
         return FAILURE
Example #15
 def put(self, url, body="", headers={}):
     headers = copy.deepcopy(headers)
     if "content-length" not in headers:
             {"content-length": (hasattr(body, "read") and hasattr(body, "len")) and body.len or str(len(body))}
     return self.request("PUT", url, body, headers)
Example #16
def _register_model(admin, model):
    if not hasattr(admin, "revision_manager"):
        admin.revision_manager = default_revision_manager
    if not hasattr(admin, "reversion_format"):
        admin.reversion_format = "json"

    if not admin.revision_manager.is_registered(model):
        inline_fields = []
        for inline in getattr(admin, "inlines", []):
            inline_model = inline.model
            if getattr(inline, "generic_inline", False):
                ct_field = getattr(inline, "ct_field", "content_type")
                ct_fk_field = getattr(inline, "ct_fk_field", "object_id")
                for field in model._meta.many_to_many:
                    if (
                        isinstance(field, GenericRelation)
                        and field.rel.to == inline_model
                        and field.object_id_field_name == ct_fk_field
                        and field.content_type_field_name == ct_field
                _autoregister(admin, inline_model)
                fk_name = getattr(inline, "fk_name", None)
                if not fk_name:
                    for field in inline_model._meta.fields:
                        if isinstance(field, (models.ForeignKey, models.OneToOneField)) and issubclass(
                            model, field.rel.to
                            fk_name = field.name
                _autoregister(admin, inline_model, follow=[fk_name])
                if not inline_model._meta.get_field(fk_name).rel.is_hidden():
                    accessor = inline_model._meta.get_field(fk_name).related.get_accessor_name()
        _autoregister(admin, model, inline_fields)
Example #17
    def __init__(self, param, cursor, strings_only=False):
        # With raw SQL queries, datetimes can reach this function
        # without being converted by DateTimeField.get_db_prep_value.
        if settings.USE_TZ and isinstance(param, datetime.datetime):
            if timezone.is_naive(param):
                    "Oracle received a naive datetime (%s)" " while time zone support is active." % param,
                default_timezone = timezone.get_default_timezone()
                param = timezone.make_aware(param, default_timezone)
            param = param.astimezone(timezone.utc).replace(tzinfo=None)

        # Oracle doesn't recognize True and False correctly in Python 3.
        # The conversion done below works both in 2 and 3.
        if param is True:
            param = "1"
        elif param is False:
            param = "0"
        if hasattr(param, "bind_parameter"):
            self.force_bytes = param.bind_parameter(cursor)
            self.force_bytes = convert_unicode(param, cursor.charset, strings_only)
        if hasattr(param, "input_size"):
            # If parameter has `input_size` attribute, use that.
            self.input_size = param.input_size
        elif isinstance(param, six.string_types) and len(param) > 4000:
            # Mark any string param greater than 4000 characters as a CLOB.
            self.input_size = Database.CLOB
            self.input_size = None
Example #18
    def test_localtime_timezone(self):

        # Get the localtime and examine it for the offset and zone.
        lt = time.localtime()
        self.assertTrue(hasattr(lt, "tm_gmtoff"))
        self.assertTrue(hasattr(lt, "tm_zone"))

        # See if the offset and zone are similar to the module
        # attributes.
        if lt.tm_gmtoff is None:
            self.assertTrue(not hasattr(time, "timezone"))
            self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst])
        if lt.tm_zone is None:
            self.assertTrue(not hasattr(time, "tzname"))
            self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst])

        # Try and make UNIX times from the localtime and a 9-tuple
        # created from the localtime. Test to see that the times are
        # the same.
        t = time.mktime(lt)
        t9 = time.mktime(lt[:9])
        self.assertEqual(t, t9)

        # Make localtimes from the UNIX times and compare them to
        # the original localtime, thus making a round trip.
        new_lt = time.localtime(t)
        new_lt9 = time.localtime(t9)
        self.assertEqual(new_lt, lt)
        self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
        self.assertEqual(new_lt.tm_zone, lt.tm_zone)
        self.assertEqual(new_lt9, lt)
        self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
        self.assertEqual(new_lt9.tm_zone, lt.tm_zone)
Example #19
 def check_server_disallowed(self):
     Check if server domain name or IP is disallowed in settings.py.
     hostname = self.netloc_parts[2].lower()
     if (hasattr(settings, 'DISALLOWED_DOMAIN_LIST') and
         for domain in settings.DISALLOWED_DOMAIN_LIST:
             if hostname == domain or hostname.endswith('.' + domain):
                 raise ValidationError(unicode(
                     _("Domain name %(domain)s is disallowed.") % locals()))
         ip = socket.gethostbyname(hostname)
     except socket.error:
         raise ValidationError(unicode(
             _("Could not resolve IP address for %(hostname)s.") %
     if (not hasattr(settings, 'DISALLOWED_SERVER_IP_LIST') or
         not settings.DISALLOWED_SERVER_IP_LIST):
     server = long_ip(ip)
     # print 'server', server, dotted_ip(server), ip
     for disallowed in settings.DISALLOWED_SERVER_IP_LIST:
         disallowed = disallowed.strip()
         if disallowed == '' or disallowed.startswith('#'):
         mask = bit_mask(32)
         if '/' in disallowed:
             disallowed, bits = disallowed.split('/', 1)
             mask = slash_mask(int(bits))
         identifier = long_ip(disallowed) & mask
         masked = server & mask
         if masked == identifier:
             raise ValidationError(unicode(
                 _("Server IP address %(ip)s is disallowed.") % locals()))
Example #20
File: tabgroup.py Project: Reve/eve
 def OnDropData(self, dragObj, nodes):
     if hasattr(self, 'OnTabDropData'):
         if self.OnTabDropData(dragObj, nodes):
     elif isinstance(self.sr.panel, uicls.DragDropObject) and hasattr(self.sr.panel, 'OnDropData'):
         if self.sr.panel.OnDropData(dragObj, nodes):
Example #21
    def add_update_fields(self, values_seq):
        Turn a sequence of (field, model, value) triples into an update query.
        Used by add_update_values() as well as the "fast" update path when
        saving models.
        from django.db.models.base import Model

        for field, model, val in values_seq:
            # FIXME: Some sort of db_prep_* is probably more appropriate here.
            if field.rel and isinstance(val, Model):
                val = val.pk

            # Getting the placeholder for the field.
            if hasattr(field, "get_placeholder"):
                placeholder = field.get_placeholder(val)
                placeholder = "%s"

            if hasattr(val, "evaluate"):
                val = SQLEvaluator(val, self, allow_joins=False)
            if model:
                self.add_related_update(model, field.column, val, placeholder)
                self.values.append((field.column, val, placeholder))
Example #22
def build_suite(app_module):
    Create a complete Django test suite for the provided application module.
    suite = unittest.TestSuite()

    # Load unit and doctests in the models.py module. If module has
    # a suite() method, use it. Otherwise build the test suite ourselves.
    if hasattr(app_module, "suite"):
            suite.addTest(doctest.DocTestSuite(app_module, checker=doctestOutputChecker, runner=DocTestRunner))
        except ValueError:
            # No doc tests in models.py

    # Check to see if a separate 'tests' module exists parallel to the
    # models module
    test_module = get_tests(app_module)
    if test_module:
        # Load unit and doctests in the tests.py module. If module has
        # a suite() method, use it. Otherwise build the test suite ourselves.
        if hasattr(test_module, "suite"):
                suite.addTest(doctest.DocTestSuite(test_module, checker=doctestOutputChecker, runner=DocTestRunner))
            except ValueError:
                # No doc tests in tests.py
    return suite
Example #23
    def pre(self, emulator=None):

        Pre execution checks

        if emulator is not None:
            return emulator.emulatePre(self.step)
        logging.info("Pre-executing CMSSW step")
        if hasattr(self.step.application.configuration, "configCacheUrl"):
            # means we have a configuration & tweak in the sandbox
            psetFile = self.step.application.command.configuration
            psetTweak = self.step.application.command.psetTweak

            if psetTweak:

        if hasattr(self.step, "pileup"):

        # add in ths scram env PSet manip script whatever happens
        return None
    def sql_indexes_for_model(self, model, *args, **kwargs):
        """Creates ``model`` indexes.

        :param model: The model containing the fields inside group.
        :param \*args: Extra args not used in this engine.
        :param \*\*kwargs: Extra kwargs not used in this engine.
        if not model._meta.managed or model._meta.proxy:
            return []
        fields = [f for f in model._meta.local_fields if f.db_index]
        if not fields and not hasattr(model._meta, "index_together") and not hasattr(model._meta, "unique_together"):
            return []
        print "Installing index for %s.%s model" % (model._meta.app_label, model._meta.object_name)
        for field in fields:
            self.sql_indexes_for_field(model, field)
        for group in getattr(model._meta, "index_together", []):
            self.index_fields_group(model, group)

        # unique_together support
        unique_together = getattr(model._meta, "unique_together", [])
        # Django should do this, I just wanted to be REALLY sure.
        if len(unique_together) > 0 and isinstance(unique_together[0], basestring):
            unique_together = (unique_together,)
        for fields in unique_together:
            group = {"fields": fields, "unique": True}
            self.index_fields_group(model, group)
        return []
Example #25
File: sql.py Project: Will-So/blaze
def lower_column(col):
    """ Return column from lower level tables if possible

    >>> metadata = sa.MetaData()

    >>> s = sa.Table('accounts', metadata,
    ...              sa.Column('name', sa.String),
    ...              sa.Column('amount', sa.Integer),
    ...              sa.Column('id', sa.Integer, primary_key=True),
    ...              )

    >>> s2 = select([s])
    >>> s2.c.amount is s.c.amount

    >>> lower_column(s2.c.amount) is s.c.amount

    >>> lower_column(s2.c.amount)
    Column('amount', Integer(), table=<accounts>)

    old = None
    while col is not None and col is not old:
        old = col
        if not hasattr(col, "table") or not hasattr(col.table, "froms"):
            return col
        for f in col.table.froms:
            if f.corresponding_column(col) is not None:
                col = f.corresponding_column(col)

    return old
    def sql_create_model(self, model, *args, **kwargs):
        """Creates the collection for model. Mostly used for capped collections.

        :param model: The model that should be created.
        :param \*args: Extra args not used in this engine.
        :param \*\*kwargs: Extra kwargs not used in this engine.


            >>> class TestFieldModel(Task):
            ...     class MongoMeta:
            ...         capped = True
            ...         collection_max = 100000
            ...         collection_size = 10
        opts = model._meta
        kwargs = {}
        kwargs["capped"] = getattr(opts, "capped", False)
        if hasattr(opts, "collection_max") and opts.collection_max:
            kwargs["max"] = opts.collection_max
        if hasattr(opts, "collection_size") and opts.collection_size:
            kwargs["size"] = opts.collection_size
        col = Collection(self.connection.db_connection, model._meta.db_table, **kwargs)
        return [], {}
Example #27
    def __get__(self, instance, owner):
        if not instance:
            return self

        if self.name in instance.__dict__:
            # This condition has already been processed, so don't try getting it again
            return None

        # Customizes the field for this particular instance
        # Use field instead of self for the rest of the method
        with self.for_instance(instance):

            a = self.a
            if hasattr(a, "resolve"):
                a = a.resolve(instance)

            b = self.b
            if hasattr(b, "resolve"):
                b = b.resolve(instance)

            if self.compare(a, b):
                # The comparison succeeded, so the fields should be processed

                raw_bytes = b""
                for f in self.fields:
                    with f.for_instance(instance):
                        bytes, value = f.read_value(instance)
                        raw_bytes += bytes
                        instance.__dict__[f.name] = value
                        f.after_decode.apply(instance, value)
                instance._raw_values[self.name] = raw_bytes

        return None
Example #28
    def adjust_for_viewer(self, X):
        .. todo::

        # assumes no preprocessing. need to make preprocessors mark the new
        # ranges
        rval = X.copy()

        # patch old pkl files
        if not hasattr(self, "center"):
            self.center = False
        if not hasattr(self, "gcn"):
            self.gcn = False

        if self.gcn is not None:
            rval = X.copy()
            for i in xrange(rval.shape[0]):
                rval[i, :] /= np.abs(rval[i, :]).max()
            return rval

        if not self.center:
            rval -= 127.5

        rval /= 127.5
        rval = np.clip(rval, -1.0, 1.0)

        return rval
Example #29
def get_gravatar_url(request, user, size=None):
    from django.conf import settings

    if user.is_anonymous() or not user.email:
        return ""

    email = user.email.strip().lower()
    email_hash = md5(email).hexdigest()

    if request.is_secure():
        url_base = "https://secure.gravatar.com"
        url_base = "http://www.gravatar.com"

    url = "%s/avatar/%s" % (url_base, email_hash)
    params = []

    if not size and hasattr(settings, "GRAVATAR_SIZE"):
        size = settings.GRAVATAR_SIZE

    if size:
        params.append("s=%s" % size)

    if hasattr(settings, "GRAVATAR_RATING"):
        params.append("r=%s" % settings.GRAVATAR_RATING)

    if hasattr(settings, "GRAVATAR_DEFAULT"):
        params.append("d=%s" % settings.GRAVATAR_DEFAULT)

    if params:
        url += "?" + "&".join(params)

    return url
Example #30
        def proxy(**forgettable_view_args):
            # Always use the global request object's view_args, because they
            # can be modified by intervening function before an endpoint or
            # wrapper gets called. This matches Flask's behavior.
            del forgettable_view_args

            if hasattr(i, "before_request"):
                response = i.before_request(name, **request.view_args)
                if response is not None:
                    return response

            before_view_name = "before_" + name
            if hasattr(i, before_view_name):
                before_view = getattr(i, before_view_name)
                response = before_view(**request.view_args)
                if response is not None:
                    return response

            response = view(**request.view_args)
            if not isinstance(response, Response):
                response = make_response(response)

            after_view_name = "after_" + name
            if hasattr(i, after_view_name):
                after_view = getattr(i, after_view_name)
                response = after_view(response)

            if hasattr(i, "after_request"):
                response = i.after_request(name, response)

            return response