Watches and progressively outputs information
    about a given Travis build
175983
def _watch_travis_build(build_id):
    
    import requests
    try:
        build_size = None  # type: int
        running = True
        while running:
            with requests.get('https://api.travis-ci.org/builds/%d' % build_id,
                              headers=_travis_headers()) as r:
                json = r.json()

                if build_size is not None:
                    if build_size > 1:
                        sys.stdout.write('\r\x1b[%dA' % build_size)
                    else:
                        sys.stdout.write('\r')

                build_size = len(json['jobs'])
                running = False
                current_number = 1
                for job in json['jobs']:  # pragma: no coverage
                    color, state, is_running = _travis_job_state(job['state'])
                    if is_running:
                        running = True

                    platform = job['config']['os']
                    if platform == 'osx':
                        platform = ' osx '

                    env = job['config'].get('env', '')
                    sudo = 's' if job['config'].get('sudo', True) else 'c'
                    lang = job['config'].get('language', 'generic')

                    padding = ' ' * (len(str(build_size)) -
                                     len(str(current_number)))
                    number = str(current_number) + padding
                    current_number += 1
                    job_display = '#' + ' '.join([number,
                                                  state,
                                                  platform,
                                                  sudo,
                                                  lang,
                                                  env])

                    print(color + job_display + colorama.Style.RESET_ALL)

            time.sleep(3.0)
    except KeyboardInterrupt:
        pass
1084265
function beginWatch() {
    let watchPaths = []
    let outputs = []

    util.each(cfgArr, function(config) {
      outputs = outputs.concat(config.output)
      watchPaths = watchPaths.concat(config.files)
      watchPaths = watchPaths.concat(config.libPaths)
    })

    chokidar
      .watch(watchPaths, {
        persistent: true,
        ignored: outputs,
        ignoreInitial: true,
        followSymlinks: true,
        usePolling: true,
        alwaysStat: false,
        interval: 100,
        atomic: true,
        ignorePermissionErrors: false
      })
      .on('change', function() {
        i = 0
        build(cfgArr[i], true)
      })
  }
928619
function readme(worker, watcher, done) {
    var cb = done;
    if (gutil.env.watch || gutil.env.w) {
      cb = function (err) {
        if (err) {
          done(err);
        } else {
          watcher(done);
        }
      };
    }

    worker(cb);
  }
1268036
function watchChanges() {
  function buildChange(file) {
    log.info('File changed:', file);
    try {
      siteBuilder.buildChange(file);
    } catch (e) {
      log.error('Error building site:', e);
    }
  }

  // TODO: What happens when files/dirs are added?
  var dirs = [];
  siteBuilder.fileMap.files.forEach(function(file) {
    if (file.type === 'dir') {
      dirs.push(file.name);
    }
  });

  watch(dirs, buildChange);
}
476257
def get_build_info(api_instance, build_id=None,
                   keys=DEFAULT_BUILD_KEYS, wait=False):
    
    build = (api_instance.get_build(build_id) if build_id
             else api_instance.get_last_build())
    output = ""

    if wait:
        build.block_until_complete()

    if 'timestamp' in keys:
        output += str(build.get_timestamp()) + '\n'

    if 'console' in keys:
        output += build.get_console() + '\n'

    if 'scm' in keys:
        # https://github.com/salimfadhley/jenkinsapi/pull/250
        # try/except while this is still occuring
        try:
            output += build.get_revision() + '\n'
        except IndexError:
            pass

    return output
661203
function watch() {
  gulp.watch([appSrc + '/app/**/*.ts', '!' + appSrc + '/app/**/*.spec.ts']).on('change', function (e) {
    console.log('TypeScript file ' + e.path + ' has been changed. Compiling.');
  });
  gulp.watch([appSrc + '/app/**/*.less']).on('change', function (e) {
    console.log(e.path + ' has been changed. Updating.');
    transpileLESS(e.path);
    updateWatchDist();
  });
  gulp.watch([appSrc + '/app/**/*.html']).on('change', function (e) {
    console.log(e.path + ' has been changed. Updating.');
    copyToDist(e.path);
    updateWatchDist();
  });
}
1121862
function watch() {
  gulp.watch([appSrc + '/app/**/*.ts', '!' + appSrc + '/app/**/*.spec.ts']).on('change', function (path) {
    console.log('TypeScript file ' + path + ' has been changed. Compiling.');
    gulp.series(inlineTemplate, transpile, updateWatchDist)();
  });
  gulp.watch([appSrc + '/app/**/*.less', appSrc + '/assets/**/*.less']).on('change', function (path) {
    console.log(path + ' has been changed. Updating.');
    gulp.series(() => transpileMinifyLESS(path), updateWatchDist)();
  });
  gulp.watch([appSrc + '/app/**/*.html']).on('change', function (path) {
    console.log(path + ' has been changed. Updating.');
    gulp.series(inlineTemplate, transpile, updateWatchDist)();
  });
}
1031065
def monitor(i):
    """"""
    count = 0
    for x in i:
        count+=1
        if count % 10000 == 0:
            logger.info("%d records so far, current record is %s",
                count, x["idx"])
        yield x
537406
function() {
            if (observed.size) {
                observed.forEach(performPropertyChecks);
                handlers.forEach(deliverHandlerRecords);
                nextFrame(runGlobalLoop);
            }
        }
239131
def commit_docs(*, added, removed):
    
    TRAVIS_BUILD_NUMBER = os.environ.get("TRAVIS_BUILD_NUMBER", "<unknown>")
    TRAVIS_BRANCH = os.environ.get("TRAVIS_BRANCH", "<unknown>")
    TRAVIS_COMMIT = os.environ.get("TRAVIS_COMMIT", "<unknown>")
    TRAVIS_REPO_SLUG = os.environ.get("TRAVIS_REPO_SLUG", "<unknown>")
    TRAVIS_JOB_WEB_URL = os.environ.get("TRAVIS_JOB_WEB_URL", "<unknown>")
    TRAVIS_TAG = os.environ.get("TRAVIS_TAG", "")
    branch = "tag" if TRAVIS_TAG else "branch"

    DOCTR_COMMAND = ' '.join(map(shlex.quote, sys.argv))


    if added:
        run(['git', 'add', *added])
    if removed:
        run(['git', 'rm', *removed])

    commit_message = """\
Update docs after building Travis build {TRAVIS_BUILD_NUMBER} of
{TRAVIS_REPO_SLUG}

The docs were built from the {branch} '{TRAVIS_BRANCH}' against the commit
{TRAVIS_COMMIT}.

The Travis build that generated this commit is at
{TRAVIS_JOB_WEB_URL}.

The doctr command that was run is

    {DOCTR_COMMAND}
""".format(
    branch=branch,
    TRAVIS_BUILD_NUMBER=TRAVIS_BUILD_NUMBER,
    TRAVIS_BRANCH=TRAVIS_BRANCH,
    TRAVIS_COMMIT=TRAVIS_COMMIT,
    TRAVIS_REPO_SLUG=TRAVIS_REPO_SLUG,
    TRAVIS_JOB_WEB_URL=TRAVIS_JOB_WEB_URL,
    DOCTR_COMMAND=DOCTR_COMMAND,
    )

    # Only commit if there were changes
    if run(['git', 'diff-index', '--exit-code', '--cached', '--quiet', 'HEAD', '--'], exit=False) != 0:
        print("Committing")
        run(['git', 'commit', '-am', commit_message])
        return True

    return False
1094546
def run():
    """"""
    import json
    import os
    import sys
    from . import coverage, report

    args = coverage.create_args(sys.argv[1:])

    if args.verbose:
        print('encodings: {}'.format(args.encodings))

    yml = parse_yaml_config(args)

    if not args.repo_token:
        # try get token from yaml first
        args.repo_token = yml.get('repo_token', '')
    if not args.repo_token:
        # use environment COVERALLS_REPO_TOKEN as a fallback
        args.repo_token = os.environ.get('COVERALLS_REPO_TOKEN')

    args.service_name = yml.get('service_name', 'travis-ci')

    if not args.gcov_options:
        args.gcov_options = yml.get('gcov_options', '')
    if not args.root:
        args.root = yml.get('root', '.')
    if not args.build_root:
        args.build_root = yml.get('build_root', '')

    args.exclude.extend(yml.get('exclude', []))
    args.include.extend(yml.get('include', []))
    args.exclude_lines_pattern.extend(yml.get('exclude_lines_pattern', []))

    args.service_job_id = os.environ.get('TRAVIS_JOB_ID', '')

    if args.repo_token == '' and args.service_job_id == '':
        raise ValueError("\nno coveralls.io token specified and no travis job id found\n"
                         "see --help for examples on how to specify a token\n")

    if not args.no_gcov:
        coverage.run_gcov(args)
    cov_report = coverage.collect(args)
    if args.verbose:
        print(cov_report)
    if args.dryrun:
        return 0
    if args.dump:
        args.dump.write(json.dumps(cov_report))
        return 0

    return report.post_report(cov_report, args)
1213128
def build_srpm(specfile, save_dir):
    
    logger.info('Starting rpmbuild to build: {0} SRPM.'.format(specfile))
    if save_dir != get_default_save_path():
        try:
            msg = subprocess.Popen(
                ['rpmbuild',
                 '--define', '_sourcedir {0}'.format(save_dir),
                 '--define', '_builddir {0}'.format(save_dir),
                 '--define', '_srcrpmdir {0}'.format(save_dir),
                 '--define', '_rpmdir {0}'.format(save_dir),
                 '-bs', specfile], stdout=subprocess.PIPE).communicate(
                 )[0].strip()
        except OSError:
            logger.error(
                "Rpmbuild failed for specfile: {0} and save_dir: {1}".format(
                    specfile, save_dir), exc_info=True)
            msg = 'Rpmbuild failed. See log for more info.'
        return msg
    else:
        if not os.path.exists(save_dir):
            raise IOError("Specify folder to store a file (SAVE_DIR) "
                          "or install rpmdevtools.")
        try:
            msg = subprocess.Popen(
                ['rpmbuild',
                 '--define', '_sourcedir {0}'.format(save_dir + '/SOURCES'),
                 '--define', '_builddir {0}'.format(save_dir + '/BUILD'),
                 '--define', '_srcrpmdir {0}'.format(save_dir + '/SRPMS'),
                 '--define', '_rpmdir {0}'.format(save_dir + '/RPMS'),
                 '-bs', specfile], stdout=subprocess.PIPE).communicate(
                )[0].strip()
        except OSError:
            logger.error("Rpmbuild failed for specfile: {0} and save_dir: "
                         "{1}".format(specfile, save_dir), exc_info=True)
            msg = 'Rpmbuild failed. See log for more info.'
        return msg
1097876
function scripts (src, dest, watch) {
  var bundleOpts = _.extend({}, watchify.args)
  if (watch) bundleOpts.debug = true

  var bundle = browserify(src, bundleOpts)

  if (watch) {
    bundle = watchify(bundle)

    bundle.on('update', function () { compileBundle(bundle, dest) }) // when a dependency changes, recompile
    bundle.on('log', gutil.log) // output build logs to terminal
  } else {
    bundle.transform({ global: true }, 'uglifyify')
  }

  return compileBundle(bundle, dest)
}
1305475
function build(projectInfo, backendProject, callback){
    if(isNewBuildNeeded(projectInfo)){
        console.log('   generating backend project content')
        backendContentManager.generateContents(projectInfo, backendProject, function(){
            console.log('   done')
            if(callback){
                callback(true)
            }
        })
    }else{
        if(callback){
            callback(false)
        }
    }
}
1163268
def wait_for_build(version)
      # Attempt to find the build. Re-attempt if the build can not
      # be found on travis yet.
      retry_opts = {
        tries: MAX_BUILD_FIND_ATTEMPTS,
        base_interval: 10
      }
      job_number = nil
      sh_retry("bundle exec travis show #{@cli_args} #{version}",
               opts: retry_opts) do |build_out|
        raise CommandError, "Build for #{version} not found.\n#{build_out}" \
          unless (job_number = build_out.match(/^#(\d+\.\d+) .+BUILD=1.+/)[1])
      end
      job_number
    end
107610
function watchjs(sources, outdir, outfile, opt_options) {
  var bundler = watchify(browserify({
    entries: sources,
    debug: false,
    // Watchify options:
    cache: {},
    packageCache: {},
    fullPaths: true
  }));

  bundler.on('update', function() {
    gutil.log('recompiling js...');
    rebundle_(bundler, outdir, outfile, opt_options);
    gutil.log('finished recompiling js');
  });
  return rebundle_(bundler, outdir, outfile, opt_options);
}
111354
def view_build():
    """"""
    build = g.build
    page_size = min(request.args.get('page_size', 10, type=int), 50)
    offset = request.args.get('offset', 0, type=int)

    ops = operations.BuildOps(build.id)
    has_next_page, candidate_list, stats_counts = ops.get_candidates(
        page_size, offset)

    # Collate by release name, order releases by latest creation. Init stats.
    release_dict = {}
    created_dict = {}
    run_stats_dict = {}
    for candidate in candidate_list:
        release_list = release_dict.setdefault(candidate.name, [])
        release_list.append(candidate)
        max_created = created_dict.get(candidate.name, candidate.created)
        created_dict[candidate.name] = max(candidate.created, max_created)
        run_stats_dict[candidate.id] = dict(
            runs_total=0,
            runs_complete=0,
            runs_successful=0,
            runs_failed=0,
            runs_baseline=0,
            runs_pending=0)

    # Sort each release by candidate number descending
    for release_list in release_dict.itervalues():
        release_list.sort(key=lambda x: x.number, reverse=True)

    # Sort all releases by created time descending
    release_age_list = [
        (value, key) for key, value in created_dict.iteritems()]
    release_age_list.sort(reverse=True)
    release_name_list = [key for _, key in release_age_list]

    # Count totals for each run state within that release.
    for candidate_id, status, count in stats_counts:
        stats_dict = run_stats_dict[candidate_id]
        for key in ops.get_stats_keys(status):
            stats_dict[key] += count

    return render_template(
        'view_build.html',
        build=build,
        release_name_list=release_name_list,
        release_dict=release_dict,
        run_stats_dict=run_stats_dict,
        has_next_page=has_next_page,
        current_offset=offset,
        next_offset=offset + page_size,
        last_offset=max(0, offset - page_size),
        page_size=page_size)