Entry point.

    - Loads in Zeppelin notebook
    - Gets the version of the notebook
    - Converts it into markdown format
10987
def main():
    
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', dest='in_filename', required=True,
                        help='Zeppelin notebook input file (.json)')
    parser.add_argument('-o', dest='out_filename',
                        help='Markdown output file (.md) (optional)')
    args = parser.parse_args()
    directory = ''

    if args.out_filename:
        directory = os.path.dirname(args.out_filename)
        args.out_filename = os.path.basename(args.out_filename)
        args.out_filename = os.path.splitext(args.out_filename)[0]
        args.out_filename = args.out_filename if args.out_filename else 'knowledge'
    else:
        args.out_filename = 'knowledge'

    with open(args.in_filename, 'rb') as raw:
        try:
            t = json.load(raw)
            full_path = os.path.join(directory, args.out_filename + '.md')
        except ValueError:
            print('ERROR: Invalid JSON format')
            sys.exit(1)

    version = get_version(t)
    if version == '0.7.1':
        zeppelin_converter = NewConverter(args.in_filename, args.out_filename,
                                          directory)
    elif version == '0.6.2':
        zeppelin_converter = LegacyConverter(args.in_filename, args.out_filename,
                                             directory)

    with open(full_path, 'w') as fout:
        zeppelin_converter.convert(t, fout)
481693
def get_executed_notebook(self):
        """"""
        r = requests.get('http://{0}/api/notebook/{1}'.format(
                         self.zeppelin_url, self.notebook_id))
        if r.status_code == 200:
            return r.json()['body']
        else:
            print('ERROR: Could not get executed notebook.', file=sys.stderr)
            sys.exit(1)
320571
def main():
    """"""
    try:
        pkg_version = Update()
        if pkg_version.updatable():
            pkg_version.show_message()
        metadata = control.retreive_metadata()
        parser = parse_options(metadata)
        argvs = sys.argv
        if len(argvs) <= 1:
            parser.print_help()
            sys.exit(1)
        args = parser.parse_args()
        control.print_licences(args, metadata)
        control.check_repository_existence(args)
        control.check_package_existence(args)
        control.generate_package(args)
    except (RuntimeError, BackendFailure, Conflict) as exc:
        sys.stderr.write('{0}\n'.format(exc))
        sys.exit(1)
275592
def main():
    '''
    
    '''
    prog = 'latexmk.py'
    version = __version__
    usage = '%prog [options] [filename]'

    # Read description from doc
    doc_text = ''
    for line in __doc__.splitlines():
        if line.find('#') == 0:
            break
        doc_text += '  %s\n' % line

    parser = OptionParser(prog=prog, usage=usage, version=version)
    parser.add_option('-c', '--clean',
                      action='store_true', dest='clean', default=False,
                      help='clean all temporary files after converting')
    parser.add_option('-q', '--quiet',
                      action='store_false', dest='verbose', default=True,
                      help='don\'t print status messages to stdout')
    parser.add_option('-n', '--no-exit',
                      action='store_false', dest='exit_on_error', default=True,
                      help='don\'t exit if error occurs')
    parser.add_option('-p', '--preview',
                      action='store_true', dest='preview', default=False,
                      help='try to open preview of generated document')
    parser.add_option('--dvi', action='store_false', dest='pdf',
                      default=True, help='use "latex" instead of pdflatex')
    parser.add_option('--check-cite', action='store_true', dest='check_cite',
                      default=False,
                      help='check bibtex file for uncited entries')

    opt, args = parser.parse_args()
    if len(args) == 0:
        tex_files = fnmatch.filter(os.listdir(os.getcwd()), '*.tex')
        if len(tex_files) == 1:
            name = tex_files[0]
        else:
            parser.error('could not find a single *.tex file in current dir')
    elif len(args) == 1:
        name = args[0]
    else:
        parser.error('incorrect number of arguments')

    LatexMaker(name, opt).run()
368948
function getInitialModel(routeInfo, page) {
    var initModelDeps = {
        appName:    routeInfo.appName,
        tokens:     routeInfo.tokens,
        routeInfo:  routeInfo,
        defaults:   page.defaults,
        activeUser: routeInfo.activeUser || {},
        currentScope: {}
    };

    // if no model, just return empty object
    if (!page.model) {
        return Q.when({});
    }
    // if function, inject and the returned value is the model
    else if (_.isFunction(page.model)) {
        return Q.when(injector.loadModule(page.model, null, { dependencies: initModelDeps }));
    }
    else {
        throw new Error(routeInfo.name + ' page invalid model() format: ' + page.model);
    }
}
39001
def main(md=None, filename=None, cols=None, theme=None, c_theme=None, bg=None,
         c_no_guess=None, display_links=None, from_txt=None, do_html=None,
         no_colors=None, **kw):
    

    args = locals()
    if not md:
        if not filename:
            print 'Using sample markdown:'
            make_sample()
            md = args['md'] = md_sample
            print md
            print
            print 'Styling Result'
        else:
            with open(filename) as f:
                md = f.read()

    global term_columns
    # style rolers requested?
    if c_theme == 'all' or theme == 'all':
        args.pop('kw')
        themes = read_themes()
        for k, v in themes.items():
            if not filename:
                yl = 'You like *%s*, *%s*?' % (k, v['name'])
                args['md'] = md_sample.replace(you_like, yl)
            print col('%s%s%s' % ('\n\n', '=' * term_columns,'\n'), L)
            # should really create an iterator here:
            if theme == 'all':
                args['theme'] = k
            else:
                args['c_theme'] = k
            print main(**args)
        return ''

    if cols:
        term_columns = int(cols)

    global show_links
    show_links = display_links

    if bg and bg == 'light':
        # not in use rite now:
        global background, color
        background = BGL
        color = T

    set_theme(theme)

    global guess_lexer
    guess_lexer = not c_no_guess

    if not c_theme:
        c_theme = theme or 'default'

    if c_theme == 'None':
        c_theme = None

    if c_theme:
        set_theme(c_theme, for_code=1)

    if c_theme or c_guess:
        # info:
        if not have_pygments:
            print col('No pygments, can not analyze code for hilite', R)


    # Create an instance of the Markdown class with the new extension
    MD = markdown.Markdown(extensions=[AnsiPrintExtension(),
                                       TableExtension(),
                                       fenced_code.FencedCodeExtension()])
    # html?
    the_html = MD.convert(md)
    if do_html:
        return the_html

    # who wants html, here is our result:
    try:
        ansi = MD.ansi
    except:
        if html:
            # can this happen? At least show:
            print "we have markdown result but no ansi."
            print html
        else:
            ansi = 'n.a. (no parsing result)'

    # The RAW html within source, incl. fenced code blocks:
    # phs are numbered like this in the md, we replace back:
    PH = markdown.util.HTML_PLACEHOLDER
    stash = MD.htmlStash
    nr = -1
    tags = Tags()
    for ph in stash.rawHtmlBlocks:
        nr += 1
        raw = html_parser.unescape(ph[0])
        pre = '<pre><code'
        if raw.startswith(pre):
            pre, raw = raw.split(pre, 1)
            raw = raw.split('>', 1)[1].rsplit('</code>', 1)[0]
            if 'class="' in pre:
                # language:
                lang = pre.split('class="', 1)[1].split('"')[0]
            else:
                lang = ''
            raw = tags.code(raw.strip(), from_fenced_block=1, lang=lang)
        ansi = ansi.replace(PH % nr, raw)

    # don't want these: gone through the extension now:
    # ansi = ansi.replace('```', '')

    # sub part display (the -f feature)
    if from_txt:
        if not from_txt.split(':', 1)[0] in ansi:
            # display from top then:
            from_txt = ansi.strip()[1]
        from_txt, mon_lines = (from_txt + ':%s' % (term_rows-6)).split(':')[:2]
        mon_lines = int(mon_lines)
        pre, post = ansi.split(from_txt, 1)
        post = '\n'.join(post.split('\n')[:mon_lines])
        ansi = '\n(...)%s%s%s' % (
               '\n'.join(pre.rsplit('\n', 2)[-2:]), from_txt, post)

    ansi = set_hr_widths(ansi) + '\n'
    if no_colors:
        return clean_ansi(ansi)
    return ansi + '\n'
196592
def main(model=None, output_dir=None, n_iter=15):
    """"""
    if model is not None:
        nlp = spacy.load(model)  # load existing spaCy model
        print("Loaded model '%s'" % model)
    else:
        nlp = spacy.blank("en")  # create blank Language class
        print("Created blank 'en' model")

    # We'll use the built-in dependency parser class, but we want to create a
    # fresh instance – just in case.
    if "parser" in nlp.pipe_names:
        nlp.remove_pipe("parser")
    parser = nlp.create_pipe("parser")
    nlp.add_pipe(parser, first=True)

    for text, annotations in TRAIN_DATA:
        for dep in annotations.get("deps", []):
            parser.add_label(dep)

    other_pipes = [pipe for pipe in nlp.pipe_names if pipe != "parser"]
    with nlp.disable_pipes(*other_pipes):  # only train parser
        optimizer = nlp.begin_training()
        for itn in range(n_iter):
            random.shuffle(TRAIN_DATA)
            losses = {}
            # batch up the examples using spaCy's minibatch
            batches = minibatch(TRAIN_DATA, size=compounding(4.0, 32.0, 1.001))
            for batch in batches:
                texts, annotations = zip(*batch)
                nlp.update(texts, annotations, sgd=optimizer, losses=losses)
            print("Losses", losses)

    # test the trained model
    test_model(nlp)

    # save model to output directory
    if output_dir is not None:
        output_dir = Path(output_dir)
        if not output_dir.exists():
            output_dir.mkdir()
        nlp.to_disk(output_dir)
        print("Saved model to", output_dir)

        # test the saved model
        print("Loading from", output_dir)
        nlp2 = spacy.load(output_dir)
        test_model(nlp2)
396871
def main():
    
    import jsonschema
    parser = argparse.ArgumentParser(version=__version__)
    parser.add_argument(
        '--verbose', action='store_true', default=False,
        help='Turn on verbose output.')
    parser.add_argument(
        '--header', action='store_true', default=False,
        help='Turn on header.')
    parser.add_argument(
        'playbooks', metavar='PLAYBOOKS', type=str, nargs='+',
        help='The playbook(s) to lint.')

    args = parser.parse_args()

    validation_results = {}
    all_valid = True
    # Load the playbook schema
    with open(resource_filename(
            'relent', 'schemas/playbook_schema.json'), 'r') as schema_fp:
        schema = json.load(schema_fp)
        # Do checks against playbooks
        for playbook in args.playbooks:
            try:
                with open(playbook, 'r') as pb:
                    # Schema check
                    jsonschema.validate(json.load(pb), schema)
            except jsonschema.ValidationError, e:
                all_valid = False
                validation_results[playbook] = (
                    False, e.message, list(e.schema_path), str(e))
            except ValueError, e:
                all_valid = False
                validation_results[playbook] = (
                    False, 'JSON is invalid.', str(e), str(e))

    # If all_valid is True then return back happy results
    if all_valid is True:
        if args.verbose or args.header:
            parser._print_message('Found 0 issues.\n')
        raise SystemExit(0)
    else:
        if args.verbose or args.header:
            parser._print_message('Found %s issues.\n\n' % len(
                validation_results))
        for problem_playbook in validation_results.keys():
            parser._print_message('%s: E: %s %s\n' % (
                problem_playbook,
                validation_results[problem_playbook][1],
                validation_results[problem_playbook][2]))
            if args.verbose:
                parser._print_message(
                    validation_results[problem_playbook][3] + '\n--\n')
        raise SystemExit(1)
821635
def main():
    

    # Parse arguments and configure application instance.
    arguments, parser = parse_arguments()

    # Start iterating
    store = RevisionStore()
    sys.stdout.write("Iterating over %d items.\n" % arguments.number)

    for i in xrange(arguments.number):
        key = chr(65 + (i % 26))
        value = [key * (i % 26), key * (i % 13), key * (i % 5)]

        store.add(key, value)

    # Wait for an enter
    if arguments.pause:
        sys.stdout.write("Done!")
        sys.stdin.readline()
376098
def main():
    
    from os import path as op
    from inspect import getfile, currentframe
    from setuptools import setup, find_packages
    from niworkflows.__about__ import (
        __packagename__,
        __author__,
        __email__,
        __maintainer__,
        __license__,
        __description__,
        __longdesc__,
        __url__,
        DOWNLOAD_URL,
        CLASSIFIERS,
        REQUIRES,
        SETUP_REQUIRES,
        LINKS_REQUIRES,
        TESTS_REQUIRES,
        EXTRA_REQUIRES,
    )

    pkg_data = {
        'niworkflows': [
            'data/t1-mni_registration*.json',
            'data/bold-mni_registration*.json',
            'reports/figures.json',
            'reports/fmriprep.yml',
            'reports/report.tpl',
        ]}

    root_dir = op.dirname(op.abspath(getfile(currentframe())))
    version = None
    cmdclass = {}
    if op.isfile(op.join(root_dir, __packagename__, 'VERSION')):
        with open(op.join(root_dir, __packagename__, 'VERSION')) as vfile:
            version = vfile.readline().strip()
        pkg_data[__packagename__].insert(0, 'VERSION')

    if version is None:
        import versioneer
        version = versioneer.get_version()
        cmdclass = versioneer.get_cmdclass()

    setup(
        name=__packagename__,
        version=version,
        description=__description__,
        long_description=__longdesc__,
        author=__author__,
        author_email=__email__,
        maintainer=__maintainer__,
        maintainer_email=__email__,
        license=__license__,
        url=__url__,
        download_url=DOWNLOAD_URL,
        classifiers=CLASSIFIERS,
        packages=find_packages(exclude=['*.tests']),
        zip_safe=False,
        # Dependencies handling
        setup_requires=SETUP_REQUIRES,
        install_requires=list(set(REQUIRES)),
        dependency_links=LINKS_REQUIRES,
        tests_require=TESTS_REQUIRES,
        extras_require=EXTRA_REQUIRES,
        # Data
        package_data=pkg_data,
        include_package_data=True,
        cmdclass=cmdclass,
    )
878723
def main():
    ''''''
    arguments = docopt(__doc__, version=__version__)
    if arguments['ls']:
        _pull_all('ls')
    elif arguments['list']:
        _pull_all('list')
    elif arguments['<PACKAGE>']:
		try:
			if arguments['<VERSION>']:
				_construct(arguments['<PACKAGE>'],arguments['<VERSION>'])
			else:
				_construct(arguments['<PACKAGE>'],None)
		except ValueError:
			print "\033[91m\033[1mError: package not found try.. \033[0m\033[1m\n$ cheese ls \nto view pacakages"
    else:
        print(__doc__)
507663
def main():
  
  args = docopt(__doc__)
  if args['--version']:
    print(__version__)
    sys.exit()

  result = parse(
      args['<source>'],
      segmenter=args['--segmenter'],
      language=args['--language'],
      classname=args['--classname'])
  print(result['html_code'])
  sys.exit()
1010097
def main():
    
    arguments = docopt(main.__doc__)

    if arguments.get('--version'):
        print('with {}'.format(withtool.__version__))
        sys.exit()

    while True:
        sub = yield from get_prompt(arguments['<command>'])
        call = '{cmd} {sub}'.format(cmd=arguments['<command>'], sub=sub)
        run(call)
576597
def init():
    

    mochapyfile = os.path.join(os.path.join(CWD, "brew.py"))

    header("Initializing Mocha ...")
    if os.path.isfile(mochapyfile):
        print("WARNING: It seems like Mocha is already setup!")
        print("*" * 80)
    else:
        print("")
        print("Copying files to the current directory...")
        copy_resource_dir(SKELETON_DIR + "/create/", CWD)
        print("")

        _npm_install_static()
        print("")
        print("----- Your Mocha is ready! ----")
        print("")
        print("> What's next?")
        print("- Edit the config [ application/config.py ] ")
        print("- If necessary setup your model database [ mocha :initdb ]")
        print("- Launch app on development mode, run [ mocha :serve ]")
        print("")
        print("*" * 80)
693777
def main():
    
    # Try parsing command line args and flags with docopt
    args = docopt(__doc__, version="cdk")
    # Am I going to need validation? No Schema for the moment...
    if args['FILE']:
        out = output_file(args['FILE'])
        # Great! Run asciidoc with appropriate flags
        theme = pick_theme(args['--theme'])
        if theme not in listdir(THEMES_DIR):
            exit('Selected theme "%s" not found. Check ~/.cdk/prefs' % theme)
        cmd = create_command(theme, args['--bare'], args['--toc'], args['--notransition'],
                             args['--logo'])
        run_command(cmd, args)
        if args['--toc']:
            add_css(out, '.deck-container .deck-toc li a span{color: #888;display:inline;}')
        if args['--custom-css']:
            add_css_file(out, args['--custom-css'])
        if args['--open']:
            webbrowser.open("file://" + abspath(out))

    # other commands
    elif args['--generate']:
        if isfile(args['--generate']):
            exit("%s already exists!" % args['--generate'])
        with open(args['--generate'], "w") as fp:
            sample = join(LOCATION,  "custom", "sample.asc")
            fp.write(open(sample).read())
            print("Created sample slide deck in %s..." % args['--generate'])
        exit()

    elif args['--install-theme']:
        path = args['--install-theme']
        if not isfile(path):
            exit("Theme file not found.")
        if not path.endswith(".zip"):
            exit("Theme installation currently only supports theme install from "
                 ".zip files.")
        install_theme(path)
    elif args['--default-theme']:
        set_default_theme(args['--default-theme'])
929273
def show_entry_points(self):
        
        found = False
        for entry_point in \
                pkg_resources.iter_entry_points(self.options.show_entry_points):
            found = True
            try:
                plugin = entry_point.load()
                print(plugin.__module__)
                print("   %s" % entry_point)
                if plugin.__doc__:
                    print(plugin.__doc__)
                print
            except ImportError:
                pass
        if not found:
            self.logger.error("No entry points found for %s" \
                    % self.options.show_entry_points)
            return 1
        return 0
1210907
def get_version():
    
    version_regex = re.compile(
        '__version__\\s*=\\s*(?P<q>[\'"])(?P<version>\\d+(\\.\\d+)*(-(alpha|beta|rc)(\\.\\d+)?)?)(?P=q)'
    )
    here = path.abspath(path.dirname(__file__))
    init_location = path.join(here, "CHAID/__init__.py")

    with open(init_location) as init_file:
        for line in init_file:
            match = version_regex.search(line)

    if not match:
        raise Exception(
            "Couldn't read version information from '{0}'".format(init_location)
        )

    return match.group('version')