Example #1
0
    def _handle(self, args):
        if len(args) == 0:
            self._raise_omni_error('Insufficient number of arguments - Missing command to run')
        
        call = args[0].lower()
        # disallow calling private methods
        if call.startswith('_'):
            return
    
        if hasattr(self, call):
            return getattr(self, call)(args[1:])
        elif hasattr(self.chhandler, call):
            return getattr(self.chhandler, call)(args[1:])
        elif hasattr(self.amhandler, call):
            # Extract the slice name arg and put it in an option
            self.amhandler.opts.sliceName = self.amhandler._extractSliceArg(args)

            # Try to auto-correct API version
            msg = self.amhandler._correctAPIVersion(args)
            if msg is None:
                msg = ""

            (message, val) = getattr(self.amhandler,call)(args[1:])
            if message is None:
                message = ""
            return (msg+message, val)
        else:
            self._raise_omni_error('Unknown function: %s' % call)
def connectToDB():
    """
    _connectToDB_
    
    Connect to the database specified in the WMAgent config.
    """
    if not os.environ.has_key("WMAGENT_CONFIG"):
        print "Please set WMAGENT_CONFIG to point at your WMAgent configuration."
        sys.exit(1)
        
    if not os.path.exists(os.environ["WMAGENT_CONFIG"]):
        print "Can't find config: %s" % os.environ["WMAGENT_CONFIG"]
        sys.exit(1)

    wmAgentConfig = loadConfigurationFile(os.environ["WMAGENT_CONFIG"])
    
    if not hasattr(wmAgentConfig, "CoreDatabase"):
        print "Your config is missing the CoreDatabase section."

    socketLoc = getattr(wmAgentConfig.CoreDatabase, "socket", None)
    connectUrl = getattr(wmAgentConfig.CoreDatabase, "connectUrl", None)
    (dialect, junk) = connectUrl.split(":", 1)

    myWMInit = WMInit()
    myWMInit.setDatabaseConnection(dbConfig = connectUrl, dialect = dialect,
                                   socketLoc = socketLoc)
    return
Example #3
0
def event_update_participant_status(profile, event):
    if request.is_xhr:
        if profile.userid not in g.user.user_organizations_owned_ids():
            abort(403)
        participantid = int(request.form['participantid'])
        status = int(request.form['status'])
        participant = Participant.query.get(participantid)

        if participant.event != event:
            abort(403)
        if participant.status == PARTICIPANT_STATUS.WITHDRAWN:
            abort(403)
        if participant.status != status:
            participant.status = status
            try:
                text_message = unicode(getattr(event, (participants_email_attrs[status] + '_text')))
                text_message = text_message.replace("*|FULLNAME|*", participant.user.fullname)
                message = unicode(getattr(event, participants_email_attrs[status]))
                message = message.replace("*|FULLNAME|*", participant.user.fullname)
                if message and g.user.email:
                    send_email(sender=(g.user.fullname, g.user.email), to=participant.email,
                    subject="%s - Hacknight participation status" % event.title , body=text_message, html=message)
            except KeyError:
                pass
            db.session.commit()
        return "Done"
    abort(403)
Example #4
0
    def tohtml( self ) :
        etp = self.macronode.parser.etparser
        app = etp.app
        etp.dynamictext = True

        try :   # To handle test cases.
            p   = getattr( app.c, 'project', None )
        except :
            p   = None
        if self.project :
            p = app.projcomp.get_project( unicode(self.project ))

        cntnr = lhtml.Element(
                    'div',
                    { 'name' : 'projectvers',
                      'class': 'verdescr etmacro-projectversions',
                      'style' : self.style
                    }
                )
        e     = lhtml.Element( 'h3', { 'style' : "border-bottom : 1px solid cadetBlue; color: cadetBlue" })
        e.text= 'Versions'
        cntnr.append( e )
        versions = p and sorted( p.versions, key=lambda v : v.created_on ) or []
        for v in versions :
            e      = lhtml.Element( 'div', { 'style' : 'font-weight: bold' } ) 
            e.text = v.version_name or ' '  # Don't leave the text empty
            cntnr.append( e )
            e      = lhtml.Element( 'blockquote', {} )
            try :
                e.append( lhtml.fromstring( getattr( v, 'descriptionhtml', '<div> </div>' )))
            except :
                pass
            cntnr.append( e )
        return lhtml.tostring( cntnr )
Example #5
0
    def __new__(cls, name, bases, attrs):
        instance = super(OptionParserMeta, cls).__new__(cls, name, bases, attrs)
        if not hasattr(instance, '_mixin_setup_funcs'):
            instance._mixin_setup_funcs = []
        if not hasattr(instance, '_mixin_process_funcs'):
            instance._mixin_process_funcs = []
        if not hasattr(instance, '_mixin_after_parsed_funcs'):
            instance._mixin_after_parsed_funcs = []

        for base in _sorted(bases + (instance,)):
            func = getattr(base, '_mixin_setup', None)
            if func is not None and func not in instance._mixin_setup_funcs:
                instance._mixin_setup_funcs.append(func)

            func = getattr(base, '_mixin_after_parsed', None)
            if func is not None and func not in instance._mixin_after_parsed_funcs:
                instance._mixin_after_parsed_funcs.append(func)

            # Mark process_<opt> functions with the base priority for sorting
            for func in dir(base):
                if not func.startswith('process_'):
                    continue
                func = getattr(base, func)
                if getattr(func, '_mixin_prio_', None) is not None:
                    # Function already has the attribute set, don't override it
                    continue
                func.__func__._mixin_prio_ = getattr(base, '_mixin_prio_', 1000)

        return instance
Example #6
0
    def _read_file(self, file_type, record, options):
        # guess mimetype from file content
        mimetype = guess_mimetype(record.file)
        (file_extension, handler, req) = FILE_TYPE_DICT.get(mimetype, (None, None, None))
        if handler:
            try:
                return getattr(self, '_read_' + file_extension)(record, options)
            except Exception:
                _logger.warn("Failed to read file '%s' (transient id %d) using guessed mimetype %s",
                             record.file_name or '<unknown>', record.id, mimetype)

        # try reading with user-provided mimetype
        (file_extension, handler, req) = FILE_TYPE_DICT.get(file_type, (None, None, None))
        if handler:
            try:
                return getattr(self, '_read_' + file_extension)(record, options)
            except Exception:
                _logger.warn("Failed to read file '%s' (transient id %d) using user-provided mimetype %s",
                             record.file_name or '<unknown>', record.id, file_type)

        # fallback on file extensions as mime types can be unreliable (e.g.
        # software setting incorrect mime types, or non-installed software
        # leading to browser not sending mime types)
        if record.file_name:
            p, ext = os.path.splitext(record.file_name)
            if ext in EXTENSIONS:
                try:
                    return getattr(self, '_read_' + ext[1:])(record, options)
                except Exception:
                    _logger.warn("Failed to read file '%s' (transient id %s) using file extension",
                                 record.file_name, record.id)

        if req:
            raise ImportError(_("Unable to load \"{extension}\" file: requires Python module \"{modname}\"").format(extension=file_extension, modname=req))
        raise ValueError(_("Unsupported file format \"{}\", import only supports CSV, ODS, XLS and XLSX").format(file_type))
Example #7
0
    def set_proxy_server(
            self, server_obj, username=DEFAULT_USER, password=None):
        """
        Saves server model representing the proxy server (compute model)
        If obj does not contain the password, please provide it, it's difficult
        to connect otherwise...

        @param server_obj: compute model representation of server
        @param username: User to log into proxy
        @param password: password for compute VM

        @return: None

        """

        # Determine if the password is set
        if password is not None:
            server_obj.admin_pass = password

        if (not hasattr(server_obj, 'admin_pass') or
                getattr(server_obj, 'admin_pass', None) is None):
            raise NoPasswordProvided()

        server_obj.username = username

        self._proxy_svr = server_obj
        self._proxy_ip = getattr(self._proxy_svr.addresses.public,
                                 'ipv{ver}'.format(ver=self._ip_version))
Example #8
0
    def _test_ranges(self, network, values):
        with getattr(Networks(), network) as n:
            n.ip_ranges[0].icon_plus.click()
            n.ip_ranges[0].start.clear()
            n.ip_ranges[0].start.send_keys(values[0][0])
            n.ip_ranges[0].end.clear()
            n.ip_ranges[0].end.send_keys(values[0][1])
            n.ip_ranges[1].start.send_keys(values[1][0])
            n.ip_ranges[1].end.send_keys(values[1][1])
        self._save_settings()
        with getattr(Networks(), network) as n:
            self.assertEqual(n.ip_ranges[0].start.get_attribute('value'),
                             values[0][0])
            self.assertEqual(n.ip_ranges[0].end.get_attribute('value'),
                             values[0][1])
            self.assertEqual(n.ip_ranges[1].start.get_attribute('value'),
                             values[1][0])
            self.assertEqual(n.ip_ranges[1].end.get_attribute('value'),
                             values[1][1])

            n.ip_ranges[0].start.clear()
            n.ip_ranges[0].start.send_keys(' ')
            self.assertIn('Invalid IP range start',
                          n.ip_ranges[0].start.
                          find_element_by_xpath('../../..').text)

            n.ip_ranges[1].end.clear()
            n.ip_ranges[1].end.send_keys(' ')
            self.assertIn('Invalid IP range end',
                          n.ip_ranges[1].end.
                          find_element_by_xpath('../../..').text)
Example #9
0
def orm_item_locator(orm_obj):
    """
    This function is called every time an object that will not be exported is required.
    Where orm_obj is the referred object.
    We postpone the lookup to locate_object() which will be run on the generated script

    """

    the_class = orm_obj._meta.object_name
    original_class = the_class
    pk_name = orm_obj._meta.pk.name
    original_pk_name = pk_name
    pk_value = getattr(orm_obj, pk_name)

    while hasattr(pk_value, "_meta") and hasattr(pk_value._meta, "pk") and hasattr(pk_value._meta.pk, "name"):
        the_class = pk_value._meta.object_name
        pk_name = pk_value._meta.pk.name
        pk_value = getattr(pk_value, pk_name)

    clean_dict = make_clean_dict(orm_obj.__dict__)

    for key in clean_dict:
        v = clean_dict[key]
        if v is not None and not isinstance(v, (six.string_types, six.integer_types, float, datetime.datetime)):
            clean_dict[key] = six.u("%s" % v)

    output = """ importer.locate_object(%s, "%s", %s, "%s", %s, %s ) """ % (
        original_class, original_pk_name,
        the_class, pk_name, pk_value, clean_dict
    )
    return output
    def get_previous_fitlered_sibling(self, **filters):
        """Very simillar to original mptt method, but adds support for filters.
        Returns this model instance's previous sibling in the tree, or
        ``None`` if it doesn't have a previous sibling.
        """
        opts = self._meta
        if self.is_root_node():
            filters.update({
                '%s__isnull' % opts.parent_attr: True,
                '%s__lt' % opts.tree_id_attr: getattr(self, opts.tree_id_attr),
            })
            order_by = '-%s' % opts.tree_id_attr
        else:
            filters.update({
                 opts.parent_attr: getattr(self, '%s_id' % opts.parent_attr),
                '%s__lt' % opts.right_attr: getattr(self, opts.left_attr),
            })
            order_by = '-%s' % opts.right_attr

        sibling = None
        try:
            sibling = self._tree_manager.filter(**filters).order_by(order_by)[0]
        except IndexError:
            pass
        return sibling
    def _collect_delete_marked_sub_objects(self, seen_objs, parent=None, nullable=False, excluded_models=None):
        if excluded_models is None:
            excluded_models = [self.__class__]
        elif not isinstance(self, Page) or self.__class__ in excluded_models:
            return

        pk_val = self._get_pk_val()
        if seen_objs.add(self.__class__, pk_val, self, parent, nullable):
            return

        for related in self._meta.get_all_related_objects():
            rel_opts_name = related.get_accessor_name()

            if not issubclass(related.model, Page) or related.model in excluded_models:
                continue

            if isinstance(related.field.rel, OneToOneRel):
                try:
                    sub_obj = getattr(self, rel_opts_name)
                except ObjectDoesNotExist:
                    pass
                else:
                    if sub_obj.publisher_is_draft:
                        continue
                    sub_obj._collect_delete_marked_sub_objects(seen_objs, self.__class__, related.field.null, excluded_models=excluded_models)
            else:
                # To make sure we can access all elements, we can't use the
                # normal manager on the related object. So we work directly
                # with the descriptor object.
                for cls in self.__class__.mro():
                    if rel_opts_name in cls.__dict__:
                        rel_descriptor = cls.__dict__[rel_opts_name]
                        break
                else:
                    raise AssertionError("Should never get here.")
                delete_qs = rel_descriptor.delete_manager(self).all()
                #filter(publisher_state=Publisher.PUBLISHER_STATE_DELETE)
                for sub_obj in delete_qs:
                    if not isinstance(sub_obj, Page) or sub_obj.__class__ in excluded_models:
                        continue
                    if sub_obj.publisher_is_draft:
                        continue
                    sub_obj._collect_delete_marked_sub_objects(seen_objs, self.__class__, related.field.null, excluded_models=excluded_models)

        # Handle any ancestors (for the model-inheritance case). We do this by
        # traversing to the most remote parent classes -- those with no parents
        # themselves -- and then adding those instances to the collection. That
        # will include all the child instances down to "self".
        parent_stack = [p for p in self._meta.parents.values() if p is not None]
        while parent_stack:
            link = parent_stack.pop()
            parent_obj = getattr(self, link.name)
            if parent_obj._meta.parents:
                parent_stack.extend(parent_obj._meta.parents.values())
                continue
            # At this point, parent_obj is base class (no ancestor models). So
            # delete it and all its descendents.
            if parent_obj.publisher_is_draft:
                continue
            parent_obj._collect_delete_marked_sub_objects(seen_objs, excluded_models=excluded_models)
Example #12
0
def start_services():
    if bokeh_app.backend['type'] == 'redis' and \
       bokeh_app.backend.get('start_redis', True):
        work_dir = getattr(bokeh_app, 'work_dir', os.getcwd())
        data_file = getattr(bokeh_app, 'data_file', 'redis.db')
        stdout = getattr(bokeh_app, 'stdout', sys.stdout)
        stderr = getattr(bokeh_app, 'stdout', sys.stderr)
        redis_save = getattr(bokeh_app, 'redis_save', True)
        mproc = services.start_redis(pidfilename=os.path.join(work_dir, "bokehpids.json"),
                                     port=bokeh_app.backend.get('redis_port', REDIS_PORT),
                                     data_dir=work_dir,
                                     data_file=data_file,
                                     stdout=stdout,
                                     stderr=stderr,
                                     save=redis_save)
        bokeh_app.redis_proc = mproc

    bokeh_app.publisher.start()
    if not bokeh_app.websocket_params['no_ws_start']:
        bokeh_app.subscriber = websocket.make_app(bokeh_app.url_prefix,
                                                  [bokeh_app.publisher.zmqaddr],
                                                  bokeh_app.websocket_params['ws_port']
        )
        bokeh_app.subscriber.start(thread=True)
    atexit.register(stop_services)
Example #13
0
 def _get_protocol_attrs(cls):
     # Get all Protocol base classes.
     protocol_bases = []
     for c in cls.__mro__:
         if getattr(c, '_is_protocol', False) and c.__name__ != 'Protocol':
             protocol_bases.append(c)
     
     # Get attributes included in protocol.
     attrs = set()
     for base in protocol_bases:
         for attr in base.__dict__.keys():
             # Include attributes not defined in any non-protocol bases.
             for c in cls.__mro__:
                 if (c is not base and attr in c.__dict__ and
                         not getattr(c, '_is_protocol', False)):
                     break
             else:
                 if (not attr.startswith(u'_abc_') and
                     attr != '__abstractmethods__' and
                     attr != '_is_protocol' and
                     attr != '__dict__' and
                     attr != '_get_protocol_attrs' and
                     attr != '__module__'):
                     attrs.add(attr)
     
     return attrs
 def recordMatches(record):
     if operand == "and":
         for fieldName, value, caseless, matchType in fields:
             try:
                 fieldValue = getattr(record, fieldName)
                 if not fieldMatches(fieldValue, value, caseless,
                     matchType):
                     return False
             except AttributeError:
                 # No property => no match
                 return False
         # we hit on every property
         return True
     else: # "or"
         for fieldName, value, caseless, matchType in fields:
             try:
                 fieldValue = getattr(record, fieldName)
                 if fieldMatches(fieldValue, value, caseless,
                     matchType):
                     return True
             except AttributeError:
                 # No value
                 pass
         # we didn't hit any
         return False
Example #15
0
def lookup_field(name, obj, model_admin=None):
    opts = obj._meta
    try:
        f = opts.get_field(name)
    except models.FieldDoesNotExist:
        # For non-field values, the value is either a method, property or
        # returned via a callable.
        if callable(name):
            attr = name
            value = attr(obj)
        elif (model_admin is not None and hasattr(model_admin, name) and
              not name == '__str__' and not name == '__unicode__'):
            attr = getattr(model_admin, name)
            value = attr(obj)
        else:
            if is_rel_field(name,obj):
                parts = name.split("__")
                rel_name,sub_rel_name = parts[0],"__".join(parts[1:])
                rel_obj =  getattr(obj,rel_name)
                if rel_obj is not None:
                    return lookup_field(sub_rel_name,rel_obj,model_admin)
            attr = getattr(obj, name)
            if callable(attr):
                value = attr()
            else:
                value = attr
        f = None
    else:
        attr = None
        value = getattr(obj, name)
    return f, attr, value
Example #16
0
def eq(a, b):
    if isinstance(a, Array):
        adt = a._dtype
        a = a.compute(get=dask.get)
    else:
        adt = getattr(a, 'dtype', None)
    if isinstance(b, Array):
        bdt = b._dtype
        b = b.compute(get=dask.get)
    else:
        bdt = getattr(b, 'dtype', None)

    if not str(adt) == str(bdt):
        return False

    try:
        return np.allclose(a, b)
    except TypeError:
        pass

    c = a == b

    if isinstance(c, np.ndarray):
        return c.all()
    else:
        return c
Example #17
0
    def object_to_flat_dict(cls, inst_cls, value, hier_delim="_", retval=None, prefix=None, parent=None):
        """Converts a native python object to a flat dict.

        See :func:`spyne.model.complex.ComplexModelBase.get_flat_type_info`.
        """

        if retval is None:
            retval = {}
        if prefix is None:
            prefix = []

        fti = inst_cls.get_flat_type_info(inst_cls)
        for k, v in fti.items():
            new_prefix = list(prefix)
            new_prefix.append(k)
            subvalue = getattr(value, k, None)
            if getattr(v, "get_flat_type_info", None) is None:  # Not a ComplexModel
                key = hier_delim.join(new_prefix)

                if retval.get(key, None) is not None:
                    raise ValueError("%r.%s conflicts with previous value %r" % (inst_cls, k, retval[key]))

                try:
                    retval[key] = subvalue
                except:
                    retval[key] = None

            else:
                cls.object_to_flat_dict(fti[k], subvalue, hier_delim, retval, new_prefix, parent=inst_cls)

        return retval
Example #18
0
    def onSuccess(self, fields, request):
        """
        saves data.
        """
        # if LP_SAVE_TO_CANONICAL and not loopstop:
        # LinguaPlone functionality:
        # check to see if we're in a translated
        # form folder, but not the canonical version.
        # parent = self.aq_parent
        # if safe_hasattr(parent, 'isTranslation') and \
        # parent.isTranslation() and not parent.isCanonical():
        # look in the canonical version to see if there is
        # a matching (by id) save-data adapter.
        # If so, call its onSuccess method
        # cf = parent.getCanonical()
        # target = cf.get(self.getId())
        # if target is not None and target.meta_type == 'FormSaveDataAdapter':
        # target.onSuccess(fields, request, loopstop=True)
        # return
        data = {}
        showFields = getattr(self, 'showFields', []) or self.getColumnNames()
        for f in fields:
            if f not in showFields:
                continue
            data[f] = fields[f]

        if self.ExtraData:
            for f in self.ExtraData:
                if f == 'dt':
                    data[f] = str(DateTime())
                else:
                    data[f] = getattr(request, f, '')

        self.addDataRow(data)
Example #19
0
    def manage_addFolder( self
                        , id
                        , title=''
                        , REQUEST=None
                        ):
        """ Add a new folder-like object with id *id*.

        IF present, use the parent object's 'mkdir' alias; otherwise, just add
        a PortalFolder.
        """
        ti = self.getTypeInfo()
        method_id = ti and ti.queryMethodID('mkdir', context=self)
        if method_id:
            # call it
            getattr(self, method_id)(id=id)
        else:
            self.invokeFactory( type_name='Folder', id=id )

        ob = self._getOb( id )
        ob.setTitle( title )
        try:
            ob.reindexObject()
        except AttributeError:
            pass

        if REQUEST is not None:
            return self.manage_main(self, REQUEST, update_menu=1)
Example #20
0
    def get(self, year, query):
        # if searching in the current year, access the Profile model
        if year == self.application.options.current_year:
            model = Profile
            results = s.query(model)
        # otherwise we're going old school with the Archives
        else:
            model = globals()['Archive'+str(year)]
            results = archive_s.query(model)

        # break up the query <-- expected to be a standard URIEncodedComponent
        fields = [q.split("=") for q in query.split(";")]
        for f in fields:
            if len(f) == 1:
                # throw %'s around everything to make the search relative
                # e.g. searching for "b" will return anything that has b *somewhere* in it
                v = '%'+f[0].replace(' ','%').replace('.','%')+'%'
                results = results.filter(or_(model.username.ilike(v), model.full_name.ilike(v)))
            else:
                # we want these queries to matche exactly
                # e.g. "%male%" would also return "female"
                if f[0] in ['gender']:
                    results = results.filter(getattr(model,f[0]).ilike(f[1]))
                else:
                    results = results.filter(getattr(model,f[0]).ilike('%'+f[1]+'%'))
        self.write({'results': [r.base_info() for r in results]})
Example #21
0
def decrement_counter_post_save(sender, instance, **kwargs):
    if getattr(instance, "is_public", True) and not getattr(instance, "is_removed", False):
        key = get_cache_key_from_comment(instance)
        try:
            cache.decr(key)
        except ValueError:
            pass
Example #22
0
    def gen_code(self, phase):
        self.add_init(1, """
    def __init__(self, weight_file):
        super(KitModel, self).__init__()
        global __weights_dict
        __weights_dict = load_weights(weight_file)
""")

        self.add_body(1, "def forward(self, x):")

        for layer in self.IR_graph.topological_sort:
            current_node = self.IR_graph.get_node(layer)
            node_type = current_node.type

            if hasattr(self, "emit_" + node_type):
                func = getattr(self, "emit_" + node_type)
                line = func(current_node)

            else:
                print("Pytorch Emitter has not supported operator [%s]." % (node_type))
                self.emit_UNKNOWN(current_node)

        self.add_body(2, "return {}".format(
            ','.join([self.IR_graph.get_node(name).real_variable_name for name in self.IR_graph.output_layers])))

        self.add_body(0, "")
        for i in self.used_layers:
            func = getattr(self, "_layer_" + i)
            func()

        return self.header_code + '\n' + self.init_code + '\n' + self.body_code
Example #23
0
    def get_config_params(self):
        """Get configuration parameters to be rendered into the conf file."""
        # TODO this should be handled better in the theme
        conf_py_path = os.path.join(os.path.sep,
                                    self.version.get_conf_py_path(),
                                    '')
        remote_version = self.version.commit_name

        github_user, github_repo = version_utils.get_github_username_repo(
            url=self.project.repo)
        github_version_is_editable = (self.version.type == 'branch')
        display_github = github_user is not None

        bitbucket_user, bitbucket_repo = version_utils.get_bitbucket_username_repo(
            url=self.project.repo)
        bitbucket_version_is_editable = (self.version.type == 'branch')
        display_bitbucket = bitbucket_user is not None

        # Avoid hitting database and API if using Docker build environment
        if getattr(settings, 'DONT_HIT_API', False):
            versions = self.project.active_versions()
            downloads = self.version.get_downloads(pretty=True)
        else:
            versions = self.project.api_versions()
            downloads = api.version(self.version.pk).get()['downloads']

        data = {
            'current_version': self.version.verbose_name,
            'project': self.project,
            'settings': settings,
            'static_path': SPHINX_STATIC_DIR,
            'template_path': SPHINX_TEMPLATE_DIR,
            'conf_py_path': conf_py_path,
            'api_host': getattr(settings, 'PUBLIC_API_URL', 'https://readthedocs.org'),
            'commit': self.project.vcs_repo(self.version.slug).commit,
            'versions': versions,
            'downloads': downloads,

            # GitHub
            'github_user': github_user,
            'github_repo': github_repo,
            'github_version': remote_version,
            'github_version_is_editable': github_version_is_editable,
            'display_github': display_github,

            # BitBucket
            'bitbucket_user': bitbucket_user,
            'bitbucket_repo': bitbucket_repo,
            'bitbucket_version': remote_version,
            'bitbucket_version_is_editable': bitbucket_version_is_editable,
            'display_bitbucket': display_bitbucket,
        }

        finalize_sphinx_context_data.send(
            sender=self.__class__,
            build_env=self.build_env,
            data=data,
        )

        return data
Example #24
0
def _getLastOkDefines(options):
    p = getattr(options, 'poker_path', None)
    if not p :
        p = getattr(options, 'pokerpath', None)
    lastfile = p + '/._service_.json'
    datas = fsutils.readJsonFile(lastfile)
    return datas
Example #25
0
 def _loadEntry(self):
     if not hasattr(self, '_flags'):
         info = self._pts._ListEntry(self._id)
         for field in self._attrs:
             setattr(self, '_%s' % field, getattr(info, field))
         for field in self._entry_attrs:
             setattr(self, '_%s' % field, self._pts.getEntry(getattr(info, field)))
Example #26
0
 def post(self):
     table = self.get_argument("module")
     data = str(self.get_argument("data"))
     data = json.loads(data)
     date = self.parse_date(self.get_argument("date", None))
     getattr(db, table).load_report(data, date)
     self.set_status(204)
Example #27
0
def _get_plugins_from_settings():
    plugins = (list(getattr(settings, 'NOSE_PLUGINS', [])) +
               ['django_nose.plugin.TestReorderer'])
    for plug_path in plugins:
        try:
            dot = plug_path.rindex('.')
        except ValueError:
            raise exceptions.ImproperlyConfigured(
                    "%s isn't a Nose plugin module" % plug_path)
        p_mod, p_classname = plug_path[:dot], plug_path[dot + 1:]

        try:
            mod = import_module(p_mod)
        except ImportError as e:
            raise exceptions.ImproperlyConfigured(
                    'Error importing Nose plugin module %s: "%s"' % (p_mod, e))

        try:
            p_class = getattr(mod, p_classname)
        except AttributeError:
            raise exceptions.ImproperlyConfigured(
                    'Nose plugin module "%s" does not define a "%s"' %
                    (p_mod, p_classname))

        yield p_class()
Example #28
0
def _ordered_dict(loader: SafeLineLoader,
                  node: yaml.nodes.MappingNode) -> OrderedDict:
    """Load YAML mappings into an ordered dictionary to preserve key order."""
    loader.flatten_mapping(node)
    nodes = loader.construct_pairs(node)

    seen = {}  # type: Dict
    min_line = None
    for (key, _), (node, _) in zip(nodes, node.value):
        line = getattr(node, '__line__', 'unknown')
        if line != 'unknown' and (min_line is None or line < min_line):
            min_line = line
        if key in seen:
            fname = getattr(loader.stream, 'name', '')
            first_mark = yaml.Mark(fname, 0, seen[key], -1, None, None)
            second_mark = yaml.Mark(fname, 0, line, -1, None, None)
            raise yaml.MarkedYAMLError(
                context="duplicate key: \"{}\"".format(key),
                context_mark=first_mark, problem_mark=second_mark,
            )
        seen[key] = line

    processed = OrderedDict(nodes)
    setattr(processed, '__config_file__', loader.name)
    setattr(processed, '__line__', min_line)
    return processed
Example #29
0
def main():
    if len(sys.argv) == 2:
        filename = sys.argv[1]
    else:
        error('no filename passed')

    filename = os.path.abspath(filename)
    nex, ext = os.path.splitext(filename)

    if not os.path.exists(filename):
        error('cannot find file %s' % (filename,))

    if ext == ".swf":
        abcs = SwfData.from_filename(filename).read_tags((DoABC, DoABCDefine))
    else:
        error('cannot parse a %s file' % (ext,))

    for i, abc in enumerate(abcs):
        name = getattr(abc, "name", None) or "%s_%d" % (nex, i)
        abc  = getattr(abc, "abc", abc)
        data = abc.serialize(optimize=False)
        f = open(name+".abc", "w")
        f.write(data)
        f.close()
        print "wrote %s.abc, %s" % (name, sizeof_fmt(len(data)))
Example #30
0
    def save(self, force_insert=False, force_update=False):
        if getattr(settings, 'DPP_IE_COMPATIBLE_PDF_VIEWER', True) and self.old_document != self.document:
            self.pdf_images_generated = False
        else:
            self.pdf_images_generated = True
        super(Document, self).save(force_insert, force_update)
        #print "pdf_images_generated set to: " + str(self.pdf_images_generated)

        # Delete old document
        if self.old_document and self.old_document != self.document:
            if os.path.exists(self.old_document.path):
                os.remove(self.old_document.path)
                #print "Old document deleted from path: " + self.old_document.path
        
        if self.old_document != self.document:
            cmd = u"python manage.py createpages " + str(self.id) + " --settings=" + settings.SETTINGS_MODULE
            subprocess.Popen(cmd, shell=True)
            #print "New page creation process started..."
        
        # Creating images when DPP_IE_COMPATIBLE_PDF_VIEWER=True in settings.py    
        if getattr(settings, 'DPP_IE_COMPATIBLE_PDF_VIEWER', True) and self.old_document != self.document:
            cmd = u"python manage.py generatepdfimages " + str(self.id) + " --settings=" + settings.SETTINGS_MODULE
            subprocess.Popen(cmd, shell=True)
            #print "Image generation process started..."
        
        self.old_document = self.document