If a sample session is available we include it in documentation
504179
def _include_query_example(self, f, method, path, api_version, server_type):
        """"""
        m = method["method"].lower()
        query_path = "{}_{}_{}.txt".format(server_type, m, self._file_path(path))
        if os.path.isfile(os.path.join(self._directory, "api", "examples", query_path)):
            f.write("Sample session\n***************\n")
            f.write("\n\n.. literalinclude:: ../../../examples/{}\n\n".format(query_path))
186965
def refresh_session_if_necessary(f):
    

    @functools.wraps(f)
    def wrapped(self, *args, **kwargs):
        try:
            result = f(self, *args, **kwargs)
        except Exception as ex:
            if hasattr(ex, 'code') and ex.code in (401, 403):
                self.refresh_session()
                # retry now
                result = f(self, *args, **kwargs)
            else:
                raise ex

        return result

    return wrapped
485574
def _get_samples_to_process(fn, out_dir, config, force_single, separators):
    """"""
    out_dir = os.path.abspath(out_dir)
    samples = defaultdict(list)
    with open(fn) as handle:
        for l in handle:
            if l.find("description") > 0:
                logger.info("Skipping header.")
                continue
            cols = l.strip().split(",")
            if len(cols) > 0:
                if len(cols) < 2:
                    raise ValueError("Line needs 2 values: file and name.")
                if utils.file_exists(cols[0]) or is_gsm(cols[0]) or is_srr(cols[0]):
                    if cols[0].find(" ") > -1:
                        new_name = os.path.abspath(cols[0].replace(" ", "_"))
                        logger.warning("Space finds in %s. Linked to %s." % (cols[0], new_name))
                        logger.warning("Please, avoid names with spaces in the future.")
                        utils.symlink_plus(os.path.abspath(cols[0]), new_name)
                        cols[0] = new_name
                    samples[cols[1]].append(cols)
                else:
                    logger.info("skipping %s, File doesn't exist." % cols[0])
    for sample, items in samples.items():
        if is_fastq(items[0][0], True):
            fn = "fq_merge"
            ext = ".fastq.gz"
        elif is_bam(items[0][0]):
            fn = "bam_merge"
            ext = ".bam"
        elif is_gsm(items[0][0]):
            fn = "query_gsm"
            ext = ".fastq.gz"
        elif is_srr(items[0][0]):
            fn = "query_srr"
            ext = ".fastq.gz"
        files = [os.path.abspath(fn_file[0]) if utils.file_exists(fn_file[0]) else fn_file[0] for fn_file in items]
        samples[sample] = [{'files': _check_paired(files, force_single, separators),
                            'out_file': os.path.join(out_dir, sample + ext),
                            'fn': fn, 'anno': items[0][2:], 'config': config,
                            'name': sample, 'out_dir': out_dir}]
    return [samples[sample] for sample in samples]
477803
def session_exist?
      sessions = Diplomat::Session.list
      sessions.any? { |s| s['ID'] == id }
    end
394553
def prepare_request(self, kwargs):
        
        if self.session_id is not None:
            actual = dt.datetime.now()

            if (self.last_activity + self.inactivity_limit) < actual:
                # session expired
                if self.persist:
                    # request new session
                    self.create_session()
                    actual = dt.datetime.now()
                else:
                    # raise error and recommend to manualy refresh session
                    raise RuntimeError('A non Persistent Session is expired. '
                                       'For consistency reasons this exception is raised. '
                                       'Please try again with manual refresh of the session ')
            self.last_activity = actual

            headers = kwargs.get('headers')
            if headers is None:
                kwargs['headers'] = headers = {}
            headers['workbook-session-id'] = self.session_id
1026631
def _show_documentation(self):
        
        documents = []
        for key, document in self.app.documents.get().items():
            if key != "main":
                documents.append((key, document))
        documents = sorted(documents, key=lambda x: x[0])
        main = self.app.documents.get("main")
        if main is not None:
            documents.insert(0, (main.name, main))

        user_answer = ""
        index = 0
        while user_answer != "X":
            if index < 0:
                index = 0
            if index > len(documents) - 1:
                index = len(documents) - 1
            document = documents[index][1]

            os.system('cls' if os.name == 'nt' else 'clear')
            echo(Environment().from_string(document.content).render(app=self.app, plugin=document.plugin))

            source = "This document is registered by '%s' under the name '%s'" % (document.plugin.name, document.name)
            echo("-" * len(source))
            echo(source)
            echo("-" * len(source))
            commands = "Actions: "
            if index < len(documents) - 1:
                commands += "[N]ext, "
            if index > 0:
                commands += "[P]revious, "
            commands += "E[x]it"
            echo(commands)

            if index < len(documents) - 1:
                default = "N"
            elif index > 0:
                default = "P"
            else:
                default = "X"
            user_answer = prompt("Select your action", default=default).upper()

            if user_answer == "N":
                index += 1
            elif user_answer == "P":
                index -= 1
284729
def save_session(self, outfolder, override=None):
        """"""
        filename = '%s_%s' % (self.protname.upper(), "_".join(
            [self.hetid, self.plcomplex.chain, self.plcomplex.position]))
        if override is not None:
            filename = override
        cmd.save("/".join([outfolder, "%s.pse" % filename]))
391328
function reporter(session) {
	Spec.call(this, session);

	var indents = 0;

	function indent() {
		return Array(indents).join('  ');
	}

	session.on('fail', function (test) {
		++indents;
		++indents;

		var plugin = test.plugin;
		var devices = plugin && test.ctx.plugins[plugin].devices;
		var prefix = indent();
		var fmt;

		if (devices) {
			devices.each(function (device, next) {
				fmt = prefix + color('fail', 'device: ' + device.uuid);
				next();
			});
		}
		/* eslint-disable */
		cursor.CR();
		/* eslint-enable */

		// console.log(fmt);

		--indents;
		--indents;
	});
}
779604
def get_documentation(self, request, *args, **kw):
        
        ret = dict()
        ret['resource'] = self.name()
        ret['urls'] = self._get_url_doc()
        ret['description'] = self.__doc__
        ret['representation'] = self._get_representation_doc()
        ret['methods'] = self._get_method_doc()
        return ret
244985
def __extract_help(method):
        
        if method is None:
            return "(No associated method)"

        # Get the arguments
        arg_spec = get_method_arguments(method)

        # Ignore the session argument
        start_arg = 1

        # Compute the number of arguments with default value
        if arg_spec.defaults is not None:
            nb_optional = len(arg_spec.defaults)

            # Let the mandatory arguments as they are
            args = [
                "<{0}>".format(arg)
                for arg in arg_spec.args[start_arg:-nb_optional]
            ]

            # Add the other arguments
            for name, value in zip(
                arg_spec.args[-nb_optional:], arg_spec.defaults[-nb_optional:]
            ):
                if value is not None:
                    args.append("[<{0}>={1}]".format(name, value))
                else:
                    args.append("[<{0}>]".format(name))
        else:
            # All arguments are mandatory
            args = ["<{0}>".format(arg) for arg in arg_spec.args[start_arg:]]

        # Extra arguments
        if arg_spec.keywords:
            args.append("[<property=value> ...]")

        if arg_spec.varargs:
            args.append("[<{0} ...>]".format(arg_spec.varargs))

        # Get the documentation string
        doc = inspect.getdoc(method) or "(Documentation missing)"
        return " ".join(args), " ".join(doc.split())
896800
def get_current_session(request, hproPk):
    """"""

    retour = {}

    base_key = 'plugit_' + str(hproPk) + '_'

    for key, value in request.session.iteritems():
        if key.startswith(base_key):
            retour[key[len(base_key):]] = value

    return retour
4727
def in_interactive_session():
    
    from pandas import get_option

    def check_main():
        try:
            import __main__ as main
        except ModuleNotFoundError:
            return get_option('mode.sim_interactive')
        return (not hasattr(main, '__file__') or
                get_option('mode.sim_interactive'))

    try:
        return __IPYTHON__ or check_main()  # noqa
    except NameError:
        return check_main()
393497
def use_plenary_assessment_offered_view(self):
        """"""
        self._object_views['assessment_offered'] = PLENARY
        # self._get_provider_session('assessment_offered_lookup_session') # To make sure the session is tracked
        for session in self._get_provider_sessions():
            try:
                session.use_plenary_assessment_offered_view()
            except AttributeError:
                pass
653926
def init_session(self):
        
        # Clear out previous session's restoration files
        for status in Status:
            path = self.get_restore_path(status)
            if os.path.isfile(path):
                os.remove(path)

        self.__record_progress()
        self.__record_progress(Status.CONSTRUCT_CHANNEL)
1046742
def documentation(self, add_to=None, version=None, prefix="", base_url="", url=""):
        """"""
        doc = OrderedDict() if add_to is None else add_to

        usage = self.interface.spec.__doc__
        if usage:
            doc['usage'] = usage

        for example in self.examples:
            example_text = "{0}{1}{2}{3}".format(prefix, base_url, '/v{0}'.format(version) if version else '', url)
            if isinstance(example, str):
                example_text += "?{0}".format(example)
            doc_examples = doc.setdefault('examples', [])
            if not example_text in doc_examples:
                doc_examples.append(example_text)

        doc = super().documentation(doc)

        if getattr(self, 'output_doc', ''):
            doc['outputs']['type'] = self.output_doc

        return doc
586590
function checkVersionAndSession(config, setSessionTime, callback) {

  var currentTime = (new Date).getTime();

  if(!config){
    writeToConfig({
      checkVersion: currentTime,
      checkSession: currentTime
    }, function(err) {

      return callback(err);
    });
  }

  // console.log(config.checkVersion);

  //config file exists
  // config = JSON.parse(config);
  var itIsCheckVersionTime = currentTime - config.checkVersion > 86400000; // check if module is up-to-date every day
  var itIsCheckSessionTime = currentTime - config.checkSession > 604800000; // refresh session every 7 days

  // console.log(itIsCheckVersionTime, itIsCheckSessionTime, config.checkVersion, config);
  if (itIsCheckVersionTime || typeof(config.checkVersion) === 'undefined') {

    config.checkVersion = currentTime;
    writeToConfig(config, function(err) {


      checkNPMVersion(function(outOfDate, LatestnpmVersion) {

        callback(outOfDate, LatestnpmVersion);
      });

    });

  } else if (itIsCheckSessionTime || typeof(config.checkSession) === 'undefined') {
    // getNewSessionAuth()
    config.checkSession = currentTime;
    writeToConfig(config, function(err) {

      callback();
    });
  }
  callback();

}
259159
def get_session(*args, **kwargs):
    
    if 'config' not in kwargs:
        kwargs['config'] = tf.ConfigProto(**settings.session)
    if settings.profiling.dump_timeline:
        def fill_kwargs(key, value):
            """
            Internal function for filling default None values with meaningful
            values from gpflow settings.
            """
            if kwargs.get(key) is None:
                kwargs[key] = value
        fill_kwargs('output_file_name', settings.profiling.output_file_name)
        fill_kwargs('output_directory', settings.profiling.output_directory)
        fill_kwargs('each_time', settings.profiling.each_time)
        return TracerSession(*args, **kwargs)
    kwargs.pop("output_file_name", None)
    kwargs.pop("output_directory", None)
    kwargs.pop("each_time", None)
    return tf.Session(*args, **kwargs)