Example #1
0
 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
         settings.DISALLOWED_DOMAIN_LIST):
         for domain in settings.DISALLOWED_DOMAIN_LIST:
             if hostname == domain or hostname.endswith('.' + domain):
                 raise ValidationError(unicode(
                     _("Domain name %(domain)s is disallowed.") % locals()))
     try:
         ip = socket.gethostbyname(hostname)
     except socket.error:
         raise ValidationError(unicode(
             _("Could not resolve IP address for %(hostname)s.") %
             locals()))
     if (not hasattr(settings, 'DISALLOWED_SERVER_IP_LIST') or
         not settings.DISALLOWED_SERVER_IP_LIST):
         return
     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('#'):
             continue
         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 #2
0
 def convert(ctx, x):
     if isinstance(x, (ctx.mpf, ctx.mpc)):
         return x
     if isinstance(x, ctx._constant):
         return +x
     if isinstance(x, complex) or hasattr(x, "_mpc_"):
         re = ctx.convert(x.real)
         im = ctx.convert(x.imag)
         return ctx.mpc(re,im)
     if isinstance(x, basestring):
         v = mpi_from_str(x, ctx.prec)
         return ctx.make_mpf(v)
     if hasattr(x, "_mpi_"):
         a, b = x._mpi_
     else:
         try:
             a, b = x
         except (TypeError, ValueError):
             a = b = x
         if hasattr(a, "_mpi_"):
             a = a._mpi_[0]
         else:
             a = convert_mpf_(a, ctx.prec, round_floor)
         if hasattr(b, "_mpi_"):
             b = b._mpi_[1]
         else:
             b = convert_mpf_(b, ctx.prec, round_ceiling)
     if a == fnan or b == fnan:
         a = fninf
         b = finf
     assert mpf_le(a, b), "endpoints must be properly ordered"
     return ctx.make_mpf((a, b))
Example #3
0
    def cursor(self, function, return_pages=False, **params):
        """Returns a generator for results that match a specified query.

        :param function: Instance of a Twython function
        (Twython.get_home_timeline, Twython.search)
        :param \*\*params: Extra parameters to send with your request
        (usually parameters accepted by the Twitter API endpoint)
        :rtype: generator

        Usage::

          >>> from twython import Twython
          >>> twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN,
          OAUTH_TOKEN_SECRET)

          >>> results = twitter.cursor(twitter.search, q='python')
          >>> for result in results:
          >>>   print result

        """
        if not hasattr(function, 'iter_mode'):
            raise TwythonError('Unable to create generator for Twython \
                               method "%s"' % function.__name__)

        while True:
            content = function(**params)

            if not content:
                raise StopIteration

            if hasattr(function, 'iter_key'):
                results = content.get(function.iter_key)
            else:
                results = content

            if return_pages:
                yield results
            else:
                for result in results:
                    yield result

            if function.iter_mode == 'cursor' and \
               content['next_cursor_str'] == '0':
                raise StopIteration

            try:
                if function.iter_mode == 'id':
                    if 'max_id' not in params:
                        # Add 1 to the id because since_id and
                        # max_id are inclusive
                        if hasattr(function, 'iter_metadata'):
                            since_id = content[function.iter_metadata].get('since_id_str')
                        else:
                            since_id = content[0]['id_str']
                        params['since_id'] = (int(since_id) - 1)
                elif function.iter_mode == 'cursor':
                    params['cursor'] = content['next_cursor_str']
            except (TypeError, ValueError):  # pragma: no cover
                raise TwythonError('Unable to generate next page of search \
                                   results, `page` is not a number.')
Example #4
0
 def getContextMenu(self, priority=QAction.NormalPriority):
     ''' Insert the subwidgets' contextMenus between double separators '''
     contextMenu = None
     if hasattr(self, 'actions'):
         if hasattr(self.actions, 'contextMenu'):
             contextMenu = self.actions.getContextMenu()
             lastActionWasASeparator = False
             menusWereInserted = False
             for action in contextMenu.actions():
                 if menusWereInserted == True:
                     debug(self, "Menus were already inserted...", 5)
                 else:
                     if lastActionWasASeparator == False:
                         if action.isSeparator(): 
                             debug(self, "Found a separator...", 5)
                             lastActionWasASeparator = True
                         else:
                             debug(self, "Not a separator...", 5)
                             lastActionWasASeparator = False
                     else:
                         if not(action.isSeparator()):
                             debug(self, "Not a double separator...", 5)
                             lastActionWasASeparator = False
                         else:
                             debug(self, "Found a double separator...", 5)
                             for widget in self.getLWidgets() :
                                 widgetMenu = widget.getContextMenu(priority)
                                 if not(widgetMenu.isEmpty()):
                                     debug(self, "Inserting %d entries in '%s'..." % (len(widgetMenu.actions()), widgetMenu.title()))
                                     contextMenu.insertMenu(action, widgetMenu)
                             menusWereInserted = True
                             lastActionWasASeparator = True
     return contextMenu
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 _extend(self, json, site):
		self.id = json.question_id

		self.creation_date = datetime.datetime.fromtimestamp(json.creation_date)
		self.vote_count = self.up_vote_count - self.down_vote_count 

		self.timeline = StackExchangeLazySequence(TimelineEvent, None, site, json.question_timeline_url, self._up('timeline'))
		self.revisions = StackExchangeLazySequence(PostRevision, None, site, 'revisions/%s' % self.id, self._up('revisions'), 'revisions')

		self.comments_url = json.question_comments_url
		self.comments = StackExchangeLazySequence(Comment, None, site, self.comments_url, self._up('comments'))

		self.answers_url = json.question_answers_url
		if hasattr(json, 'answers'):
			self.answers = [Answer(x, site) for x in json.answers]
		else:
			self.answers = []

		if hasattr(json, 'owner'):
			self.owner_id = json.owner['user_id']

			owner_dict = dict(json.owner)
			owner_dict['id'] = self.owner_id
			del owner_dict['user_id']
			owner_dict['user_type'] = UserType.from_string(owner_dict['user_type'])

			self.owner = User.partial(lambda self: self.site.user(self.id), site, owner_dict)

		self.url = 'http://' + self.site.root_domain + '/questions/' + str(self.id)
Example #7
0
    def _build_conch_options(self):
        """Verify and construct the ssh (conch) option object
        
        This is just a dictionary like object that options the twisted ssh implementation uses.
        """
        ssh_options = options.ConchOptions()
        if not hasattr(self, 'agent'):
            ssh_options['noagent'] = True
        else:
            if 'SSH_AUTH_SOCK' in os.environ:
                ssh_options['agent'] = True
            else:
                raise Error("No SSH Agent available ($SSH_AUTH_SOCK)")

        if hasattr(self, "identities"):
            for file_name in self.identities:
                file_path = os.path.expanduser(file_name)
                if not os.path.exists(file_path):
                    raise Error("Private key file %s doesn't exist" % file_name)
                if not os.path.exists(file_path + ".pub"):
                    raise Error("Public key %s doesn't exist" % (file_name + ".pub"))
            
                ssh_options.opt_identity(file_name)
        
        return ssh_options
Example #8
0
    def process(self, formdata=None, obj=None, **kwargs):
        """
        Take form, object data, and keyword arg input and have the fields
        process them.

        :param formdata:
            Used to pass data coming from the enduser, usually `request.POST` or
            equivalent.
        :param obj:
            If `formdata` has no data for a field, the form will try to get it
            from the passed object.
        :param `**kwargs`:
            If neither `formdata` or `obj` contains a value for a field, the
            form will assign the value of a matching keyword argument to the
            field, if provided.
        """
        if formdata is not None and not hasattr(formdata, 'getlist'):
            if hasattr(formdata, 'getall'):
                formdata = WebobInputWrapper(formdata)
            else:
                raise TypeError("formdata should be a multidict-type wrapper that supports the 'getlist' method")

        for name, field, in self._fields.iteritems():
            if obj is not None and hasattr(obj, name):
                field.process(formdata, getattr(obj, name))
            elif name in kwargs:
                field.process(formdata, kwargs[name])
            else:
                field.process(formdata)
Example #9
0
    def test_custom_lookup_ns_fallback(self):
        class TestElement1(etree.ElementBase):
            FIND_ME = "custom"

        class TestElement2(etree.ElementBase):
            FIND_ME = "nsclasses"

        class MyLookup(etree.CustomElementClassLookup):
            def lookup(self, t, d, ns, name):
                if name == 'c1':
                    return TestElement1

        lookup = etree.ElementNamespaceClassLookup( MyLookup() )
        etree.set_element_class_lookup(lookup)

        ns = lookup.get_namespace("otherNS")
        ns[None] = TestElement2

        root = etree.XML(xml_str)
        self.assertFalse(hasattr(root, 'FIND_ME'))
        self.assertEqual(root[0].FIND_ME,
                          TestElement1.FIND_ME)
        self.assertFalse(hasattr(root[0][1], 'FIND_ME'))
        self.assertEqual(root[0][-1].FIND_ME,
                          TestElement2.FIND_ME)
Example #10
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)
Example #11
0
def overload(func):
    """Function decorator for defining overloaded functions."""
    frame = sys._getframe(1)
    locals = frame.f_locals
    # See if there is a previous overload variant available.  Also verify
    # that the existing function really is overloaded: otherwise, replace
    # the definition.  The latter is actually important if we want to reload
    # a library module such as genericpath with a custom one that uses
    # overloading in the implementation.
    if func.__name__ in locals and hasattr(locals[func.__name__], 'dispatch'):
        orig_func = locals[func.__name__]
        
        def wrapper(*args, **kwargs):
            ret, ok = orig_func.dispatch(*args, **kwargs)
            if ok:
                return ret
            return func(*args, **kwargs)
        wrapper.isoverload = True
        wrapper.dispatch = make_dispatcher(func, orig_func.dispatch)
        wrapper.next = orig_func
        wrapper.__name__ = func.__name__
        if hasattr(func, '__isabstractmethod__'):
            # Note that we can't reliably check that abstractmethod is
            # used consistently across overload variants, so we let a
            # static checker do it.
            wrapper.__isabstractmethod__ = func.__isabstractmethod__
        return wrapper
    else:
        # Return the initial overload variant.
        func.isoverload = True
        func.dispatch = make_dispatcher(func)
        func.next = None
        return func
Example #12
0
def _enterRawMode():
    global _inRawMode, _savedRawMode
    if _inRawMode:
        return
    fd = sys.stdin.fileno()
    try:
        old = tty.tcgetattr(fd)
        new = old[:]
    except:
        log.msg('not a typewriter!')
    else:
        # iflage
        new[0] = new[0] | tty.IGNPAR
        new[0] = new[0] & ~(tty.ISTRIP | tty.INLCR | tty.IGNCR | tty.ICRNL |
                            tty.IXON | tty.IXANY | tty.IXOFF)
        if hasattr(tty, 'IUCLC'):
            new[0] = new[0] & ~tty.IUCLC

        # lflag
        new[3] = new[3] & ~(tty.ISIG | tty.ICANON | tty.ECHO | tty.ECHO |
                            tty.ECHOE | tty.ECHOK | tty.ECHONL)
        if hasattr(tty, 'IEXTEN'):
            new[3] = new[3] & ~tty.IEXTEN

        #oflag
        new[1] = new[1] & ~tty.OPOST

        new[6][tty.VMIN] = 1
        new[6][tty.VTIME] = 0

        _savedRawMode = old
        tty.tcsetattr(fd, tty.TCSANOW, new)
        #tty.setraw(fd)
        _inRawMode = 1
Example #13
0
    def destroy(self):
        self.disable()
        if hasattr(self, 'wrongWaySeq'):
            self.wrongWaySeq.finish()
            self.wrongWaySeq = None
        taskMgr.removeTasksMatching('removeIt')
        taskMgr.removeTasksMatching('removeCam*')
        taskMgr.removeTasksMatching('clearRaceEndPanel')
        for obj in self.directObjList:
            obj.destroy()

        if hasattr(self, 'mapScene'):
            self.mapScene.removeNode()
            self.mapScene = None
        self.aspect2dRoot.removeNode()
        self.aspect2dRoot = None
        self.raceModeRoot.removeNode()
        self.raceModeRoot = None
        self.render2dRoot.removeNode()
        self.render2dRoot = None
        self.closeButton = None
        self.gag = None
        self.lapLabel = None
        self.timeLabels = None
        self.placeLabelStr = None
        self.placeLabelNum = None
        self.photoFinishLabel = None
        self.mapScene = None
        self.race = None
        return
Example #14
0
 def create(cls, **kwargs):
     instance = cls(**kwargs)
     if hasattr(instance, 'created_at'):
         setattr(instance, 'created_at', datetime.datetime.utcnow())
     if hasattr(instance, 'modified_at'):
         setattr(instance, 'modified_at', datetime.datetime.utcnow())
     return instance
    def highlightBlock(self, qstring):
        """ Highlight a block of text.
        """
        qstring = compat.unicode(qstring)
        prev_data = self.previous_block_data()

        if prev_data is not None:
            self._lexer._epd_state_stack = prev_data.syntax_stack
        elif hasattr(self._lexer, '_epd_state_stack'):
            del self._lexer._epd_state_stack

        index = 0
        # Lex the text using Pygments
        for token, text in self._lexer.get_tokens(qstring):
            l = len(text)
            format = self._get_format(token)
            if format is not None:
                self.setFormat(index, l, format)
            index += l

        if hasattr(self._lexer, '_epd_state_stack'):
            data = BlockUserData(syntax_stack=self._lexer._epd_state_stack)
            self.currentBlock().setUserData(data)

            # there is a bug in pyside and it will crash unless we
            # hold on to the reference a little longer
            data = self.currentBlock().userData()

            # Clean up for the next go-round.
            del self._lexer._epd_state_stack
Example #16
0
def netflix_solve(i_stream, o_stream):
    """Creates prediction output for any valid input for the Netflix Prize
    problem.

    Args:
        i_stream: The input stream.
        o_stream: The output stream.
    """
    # pre-conditions
    assert hasattr(i_stream, 'read')
    assert hasattr(o_stream, 'write')

    customer_ids = []
    movie_data, cust_data, answers = load_data()
    # parse input
    for line in i_stream:
        line = line.strip()
        if line[-1] == ':':
            if len(customer_ids) > 0:
                # see the future (or the past, actually)
                predictions = netflix_predict(movie_id, customer_ids,
                                              movie_data, cust_data)
                # print current movie's output
                netflix_print(movie_id, customer_ids, predictions, o_stream)
            movie_id = int(line[:-1])
            customer_ids = []
        else:
            customer_ids.append(int(line))
    # predict ratings for final movie
    predictions = netflix_predict(movie_id, customer_ids,
                                  movie_data, cust_data)
    # print final movie's output
    netflix_print(movie_id, customer_ids, predictions, o_stream)
    print_rmse(o_stream, calculated_ratings, answers)
Example #17
0
	def _extend(self, json, site):
		self.id = json.comment_id

		self.creation_date = datetime.datetime.fromtimestamp(json.creation_date)

		if hasattr(json, 'owner'):
			self.owner_id = json.owner['owner_id'] if 'owner_id' in json.owner else json.owner['user_id']
			self.owner = User.partial(lambda self: self.site.user(self.id), site, {
				'id': self.owner_id,
				'user_type': Enumeration.from_string(json.owner['user_type'], UserType),
				'display_name': json.owner['display_name'],
				'reputation': json.owner['reputation'],
				'email_hash': json.owner['email_hash']})
		else:
			self.owner = None

		if hasattr(json, 'reply_to'):
			self.reply_to_user_id = json.reply_to['user_id']
			self.reply_to = User.partial(lambda self: self.site.user(self.id), site, {
				'id': self.reply_to_user_id,
				'user_type': Enumeration.from_string(json.reply_to['user_type'], UserType),
				'display_name': json.reply_to['display_name'],
				'reputation': json.reply_to['reputation'],
				'email_hash': json.reply_to['email_hash']})

		self.post_type = PostType.from_string(json.post_type)
Example #18
0
    def pre(self, emulator=None):
        """
        _pre_

        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
            self.stepSpace.getFromSandbox(psetFile)

            if psetTweak:
                self.stepSpace.getFromSandbox(psetTweak)

        if hasattr(self.step, "pileup"):
            self.stepSpace.getFromSandbox("pileupconf.json")

        # add in ths scram env PSet manip script whatever happens
        self.step.runtime.scramPreScripts.append("SetupCMSSWPset")
        return None
Example #19
0
    def apply(self, mcp):
        """Apply the configuration to the specified master control program"""
        working_dir = self._get_working_dir(mcp)
        if not os.path.isdir(working_dir):
            raise ConfigError("Specified working directory \'%s\' is not a directory" % working_dir)
        if not os.access(working_dir, os.W_OK):
            raise ConfigError("Specified working directory \'%s\' is not writable" % working_dir)
        
        mcp.state_handler.working_dir = working_dir

        if hasattr(self, 'command_context'):
            if mcp.context:
                mcp.context.base = self.command_context
            else:
                mcp.context = command_context.CommandContext(self.command_context)
        
        self._apply_nodes(mcp)

        if hasattr(self, 'ssh_options'):
            self.ssh_options = default_or_from_tag(self.ssh_options, SSHOptions)
            self.ssh_options._apply(mcp)
        
        self._apply_jobs(mcp)
        self._apply_services(mcp)

        if hasattr(self, 'notification_options'):
            self.notification_options = default_or_from_tag(self.notification_options, NotificationOptions)
            self.notification_options._apply(mcp)
Example #20
0
    def scaffold_list_columns(self):
        """
            Return a list of columns from the model.
        """
        columns = []

        for p in self._get_model_iterator():
            if hasattr(p, 'direction'):
                if self.column_display_all_relations or p.direction.name == 'MANYTOONE':
                    columns.append(p.key)
            elif hasattr(p, 'columns'):
                if len(p.columns) > 1:
                    filtered = tools.filter_foreign_columns(self.model.__table__, p.columns)

                    if len(filtered) > 1:
                        warnings.warn('Can not convert multiple-column properties (%s.%s)' % (self.model, p.key))
                        continue

                    column = filtered[0]
                else:
                    column = p.columns[0]

                if column.foreign_keys:
                    continue

                if not self.column_display_pk and column.primary_key:
                    continue

                columns.append(p.key)

        return columns
Example #21
0
    def _set_model(self, model):
        import tensorflow as tf
        import keras.backend.tensorflow_backend as KTF

        self.model = model
        self.sess = KTF.get_session()
        if self.histogram_freq and not self.merged:
            mod_type = self.model.get_config()['name']
            if mod_type == 'Sequential':
                layers = {l.get_config()['name']: l for l in self.model.layers}
            elif mod_type == 'Graph':
                layers = self.model.nodes
            else:
                raise Exception('Unrecognized model:',
                                self.model.get_config()['name'])
            for l in layers:
                cur_layer = layers[l]
                if hasattr(cur_layer, 'W'):
                    tf.histogram_summary('{}_W'.format(l), cur_layer.W)
                if hasattr(cur_layer, 'b'):
                    tf.histogram_summary('{}_b'.format(l), cur_layer.b)
                if hasattr(cur_layer, 'get_output'):
                    tf.histogram_summary('{}_out'.format(l),
                                         cur_layer.get_output())
        self.merged = tf.merge_all_summaries()
        self.writer = tf.train.SummaryWriter(self.log_dir,
                                             self.sess.graph_def)
Example #22
0
def time_column(table, ifo=None):
    """Extract the 'time' column from the given table.

    This function uses time_func to determine the correct column to
    use as a proxy for 'time' and returns that column.
    The following mappings are used:
    - `sngl_inspiral` -> 'end' time
    - `sngl_burst` -> 'peak' time
    - `sngl_ringdown` -> 'start' time

    @param table
        any `LIGO_LW` table
    @param ifo
        an interferometer prefix if you want single-detector times

    @returns a numpy array object with a 'time' element for each row in
    the table
    """
    if hasattr(table, "get_time"):
        return numpy.asarray(table.get_time())
    func_name = time_func(ligolw_table.StripTableName(table.tableName)).__name__
    if hasattr(table, func_name):
        return numpy.asarray(getattr(table, func_name)())
    else:
        return numpy.asarray(map(func_name, table))
Example #23
0
def get_img(doc, page_num, thumbnail, format_):
    """
    Convert doc to img if not already done. Given doc is updated with new img
    if created.
    :param doc: :class:`labresult.model.Document`
    :param page_num: int, desired page number
    :param thumbnail: bool, thumbnail or not
    :param format_: str, "svg" pr "png"
    :rtype: bytes, img data
    """
    imgobj = get_existing_img_or_new_one(doc, page_num, thumbnail, format_)
    img_data= None
    if thumbnail and hasattr(imgobj.thumbnail,'_id'):
        img_data = imgobj.thumbnail.read()
    elif not thumbnail and hasattr(imgobj.data,'_id'):
        img_data = imgobj.data.read()
    if not img_data :
        if not hasattr(doc.pdf, '_id'):
            doc.pdf = get_pdf(doc)
        doc.pdf.seek(0)
        pdf_data = doc.pdf.read()
        img_data = tasks.pdf2img.delay(pdf_data, page_num, thumbnail, format_).get()
        tasks.save_img(img_data, doc.id, page_num, thumbnail, format_)

    return img_data
Example #24
0
 def emit(self, record):
     try:
         msg = self.format(record)
         stream = self.stream
         isBuffer = hasattr(record, 'filebuffer')
         toSort = hasattr(record,  'filesort')
         if toSort:
             self.toSort = True
         if isBuffer:
             #toggle buffer switcch
             self.isBuffer = not self.isBuffer
         if self.isBuffer or isBuffer:
             if len(msg):
                  self.logBuffer.append(msg.replace(". Test:",". Case:"))
         else:
             if len(self.logBuffer):
                 if self.toSort:
                     self.logBuffer.sort()
                 for item in self.logBuffer:
                     item = item.replace(". Case:",". Test:")
                     stream.write(item)
                     stream.write(self.terminator)
                 self.logBuffer = []
                 self.toSort = False
             if  len(msg):
                 stream.write(msg)
                 stream.write(self.terminator)
             self.flush()
     except (KeyboardInterrupt, SystemExit):
         raise
     except:
         self.handleError(record)
  def __init__(self, args, output_manager, _error_func):
    super(LocalDeviceEnvironment, self).__init__(output_manager)
    self._blacklist = (device_blacklist.Blacklist(args.blacklist_file)
                       if args.blacklist_file
                       else None)
    self._device_serials = args.test_devices
    self._devices_lock = threading.Lock()
    self._devices = None
    self._concurrent_adb = args.enable_concurrent_adb
    self._enable_device_cache = args.enable_device_cache
    self._logcat_monitors = []
    self._logcat_output_dir = args.logcat_output_dir
    self._logcat_output_file = args.logcat_output_file
    self._max_tries = 1 + args.num_retries
    self._skip_clear_data = args.skip_clear_data
    self._tool_name = args.tool
    self._trace_output = None
    if hasattr(args, 'trace_output'):
      self._trace_output = args.trace_output
    self._trace_all = None
    if hasattr(args, 'trace_all'):
      self._trace_all = args.trace_all

    devil_chromium.Initialize(
        output_directory=constants.GetOutDirectory(),
        adb_path=args.adb_path)

    # Some things such as Forwarder require ADB to be in the environment path.
    adb_dir = os.path.dirname(adb_wrapper.AdbWrapper.GetAdbPath())
    if adb_dir and adb_dir not in os.environ['PATH'].split(os.pathsep):
      os.environ['PATH'] = adb_dir + os.pathsep + os.environ['PATH']
Example #26
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
Example #27
0
def _toPNG(mol):
  if hasattr(mol, '__sssAtoms'):
    highlightAtoms = mol.__sssAtoms
  else:
    highlightAtoms = []
  try:
    mol.GetAtomWithIdx(0).GetExplicitValence()
  except RuntimeError:
    mol.UpdatePropertyCache(False)

  if not hasattr(rdMolDraw2D, 'MolDraw2DCairo'):
    mc = copy.deepcopy(mol)
    try:
      img = Draw.MolToImage(mc, size=molSize, kekulize=kekulizeStructures,
                            highlightAtoms=highlightAtoms)
    except ValueError:  # <- can happen on a kekulization failure
      mc = copy.deepcopy(mol)
      img = Draw.MolToImage(mc, size=molSize, kekulize=False, highlightAtoms=highlightAtoms)
    bio = BytesIO()
    img.save(bio, format='PNG')
    return bio.getvalue()
  else:
    nmol = rdMolDraw2D.PrepareMolForDrawing(mol, kekulize=kekulizeStructures)
    d2d = rdMolDraw2D.MolDraw2DCairo(molSize[0], molSize[1])
    d2d.DrawMolecule(nmol, highlightAtoms=highlightAtoms)
    d2d.FinishDrawing()
    return d2d.GetDrawingText()
def clone_request(request, method):
    """
    Internal helper method to clone a request, replacing with a different
    HTTP method.  Used for checking permissions against other methods.
    """
    ret = Request(request=request._request,
                  parsers=request.parsers,
                  authenticators=request.authenticators,
                  negotiator=request.negotiator,
                  parser_context=request.parser_context)
    ret._data = request._data
    ret._files = request._files
    ret._full_data = request._full_data
    ret._content_type = request._content_type
    ret._stream = request._stream
    ret._method = method
    if hasattr(request, '_user'):
        ret._user = request._user
    if hasattr(request, '_auth'):
        ret._auth = request._auth
    if hasattr(request, '_authenticator'):
        ret._authenticator = request._authenticator
    if hasattr(request, 'accepted_renderer'):
        ret.accepted_renderer = request.accepted_renderer
    if hasattr(request, 'accepted_media_type'):
        ret.accepted_media_type = request.accepted_media_type
    return ret
    def to_dict(self):
        """
        Returns the model properties as a dict
        """
        result = {}

        for attr, _ in iteritems(self.swagger_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value

        return result
Example #30
0
 def __setattr__(self, name, value):
     if hasattr(self, name):
         object.__setattr__(self, name, value)
     elif name != "_impl" and hasattr(self._impl, name):
         self._impl.__setattr__(name, value)
     else:
         self.__dict__[name] = value