Print a list of available fields and works
    sort_by_date : boolean whether we print works by their due date
198972
def print_fields(fields, sort_by_date=False, sort_by_open_projects=False):
    
    if (not sort_by_date) and (not sort_by_open_projects):
        for (_, name, works) in fields:
            print(name)
            for work in works:
                print('- '+str(work))
    else:
        works = all_works
        # Sort works by due_date
        if sort_by_date:
            works.sort(key=lambda x: (not x.is_open, x.due_date), reverse=True)
        for work in works:
            if sort_by_open_projects:
                if not work.is_open:
                    continue
            # This is ugly, but there is no way to know the field name of a work without searching for it, at the moment
            field_name = [name for id, name, _ in fields if id == work.field][0]
            print(field_name)
            print('- '+str(work))
1133514
def include? date
      result = false
      walk { |elements|
        break result = true if elements.include? date 
      }

      return result if !result || date.class == Date || times.nil?

      times.include? date
    end
631757
def _print_tasks(env, tasks, mark_active=False):
    

    if env.task.active and mark_active:
        active_task = env.task.name
    else:
        active_task = None

    for task, options, blocks in tasks:
        # print heading
        invalid = False

        if task == active_task:
            method = 'success'
        else:
            if options is None and blocks is None:
                method = 'error'
                invalid = True

            else:
                method = 'write'

        opts = list(options or [])
        blks = list(blocks or [])

        write = getattr(env.io, method)
        write('~' * 80)
        write(' ' + task)
        write('~' * 80)
        env.io.write('')

        # non-block options
        if opts:
            for opt, values in opts:
                env.io.write('    {0}: {1}'.format(opt,
                             ', '.join(str(v) for v in values)))
            env.io.write('')

        # block options
        if blks:
            had_options = False

            for block, options in blks:
                if options:
                    had_options = True
                    env.io.write('    {{ {0} }}'.format(block))

                    for opt, values in options:
                        env.io.write('        {0}: {1}'.format(opt,
                                     ', '.join(str(v) for v in values)))
                    env.io.write('')

            if not had_options:
                blks = None

        if not opts and not blks:
            if invalid:
                env.io.write('  Invalid task.')
            else:
                env.io.write('  Empty task.')
            env.io.write('')
464798
def pending_work_items(self):
        ""
        pending = self._conn.execute(
            "SELECT * FROM work_items WHERE job_id NOT IN (SELECT job_id FROM results)"
        )
        return (_row_to_work_item(p) for p in pending)
775907
private void processCalendarData(ProjectCalendar calendar, List<ResultSetRow> calendarData)
   {
      for (ResultSetRow row : calendarData)
      {
         processCalendarData(calendar, row);
      }
   }
1020180
def filter_fields(self, fields=[], exclude=[], include_all_if_empty=True):
        
        if not include_all_if_empty and not fields:
            return []
        ret = []
        for f in self.visible_fields():
            if fields and f.name not in fields:
                continue
            if exclude and f.name in exclude:
                continue
            ret.append(f)
        return ret
20474
def GenerateCalendarDatesFieldValuesTuples(self):
    """"""
    for date, (exception_type, _) in self.date_exceptions.items():
      yield (self.service_id, date, unicode(exception_type))
404141
def pretty_print_user_list(list)
      total = 0
      data = []
      # Header row
      data.push('Asset', 'Total Value', 'Change % (Week)')
      list.user_pairs.each do |user_pair|
        data.push(user_pair.symbol)
        data.push(user_pair.valuation.format)
        data.push(user_pair.perchant_change_week.to_s)
        total += user_pair.valuation
      end

      data.push('', '', '')
      data.push('TOTAL:', total.format, '')
      data.push('', '', '')
      print_arrays(data, 3)
    end
1108802
def print_status(self, indent="", recurse=False):
        """"""
        print ("%s%30s : %15s : %20s" %
               (indent, "Linkname", "Link Status", "Jobs Status"))
        for link in self._links.values():
            if hasattr(link, 'check_status'):
                status_vect = link.check_status(
                    stream=sys.stdout, no_wait=True, do_print=False)
            else:
                status_vect = None
            key = JobDetails.make_fullkey(link.full_linkname)
            link_status = JOB_STATUS_STRINGS[link.check_job_status(key)]
            if status_vect is None:
                jobs_status = JOB_STATUS_STRINGS[link.check_jobs_status()]
            else:
                jobs_status = status_vect
            print ("%s%30s : %15s : %20s" %
                   (indent, link.linkname, link_status, jobs_status))
            if hasattr(link, 'print_status') and recurse:
                print ("----------   %30s    -----------" % link.linkname)
                link.print_status(indent + "  ", recurse=True)
                print ("------------------------------------------------")
578178
def render_queries(queries, sort):
    
    output = StringIO()
    if sort == 'order':
        print >>output, "     time query"
        for query in queries:
            print >>output, " %8s %s" % (query["time"], query["sql"])
        return output
    if sort == 'time':
        def sorter(x, y):
            return cmp(x[1][1], y[1][1])
    elif sort == 'queries':
        def sorter(x, y):
            return cmp(x[1][0], y[1][0])
    else:
        raise RuntimeError("Unknown sort: %s" % sort)
    print >>output, "  queries     time query"
    results = {}
    for query in queries:
        try:
            result = results[query["sql"]]
            result[0] += 1
            result[1] += Decimal(query["time"])
        except KeyError:
            results[query["sql"]] = [1, Decimal(query["time"])]
    results = sorted(results.iteritems(), cmp=sorter, reverse=True)
    for result in results:
        print >>output, " %8d %8.3f %s" % (
            result[1][0], result[1][1], result[0]
        )
    return output
928487
def OrderFields(fields):
    
    fields = list(fields)

    @use_context
    @use_raw_input
    def _OrderFields(context, row):
        nonlocal fields
        context.setdefault("remaining", None)
        if not context.output_type:
            context.remaining = list(sorted(set(context.get_input_fields()) - set(fields)))
            context.set_output_fields(fields + context.remaining)

        yield tuple(row.get(field) for field in context.get_output_fields())

    return _OrderFields
23591
def print_results_adj(results, indent=False, prt=sys.stdout):
        """"""
        # Print column headers if there are results to be printed
        if results:
            prt.write("{R}\n".format(R="\t".join(GOEnrichmentStudy.get_prtflds_default(results))))
        # Print the GOEA results
        for rec in results:
            prt.write("{R}\n".format(R=rec.__str__(indent=indent)))
888768
def sorted_by_field(issues, field='closed_at', reverse=False):
    """"""
    return sorted(issues, key = lambda i:i[field], reverse=reverse)
256662
def status():
    
    import pdb; pdb.set_trace()
    branch = git.branch
    issue = jira.get_issue(branch)
    if not issue:
        return

    # Print the title
    title = issue.fields.summary
    print "(%s) %s" % (branch, title)

    # Print the status
    status = issue.fields.status.name
    assignee = issue.fields.assignee.name
    in_progress = jira.get_datetime_issue_in_progress(issue)

    if in_progress:
        in_progress_string = in_progress.strftime("%a %x %I:%M %p")
        print '  Status: %s as of %s' % (status, in_progress_string)
    else:
        print '  Status: %s' % status

    print '  Assignee: %s' % assignee

    # Print the worklogs

    # Get the timespent and return 0m if it does not exist
    time_spent = '0m'
    try:
        time_spent = issue.fields.timetracking.timeSpent
    except:
        pass

    worklogs = jira.get_worklog(issue)
    print "\nTime logged (%s):" % time_spent
    if worklogs:
        for worklog in worklogs:
            worklog_hash = worklog.raw

            author = worklog_hash['author']['name']

            time_spent = worklog_hash.get('timeSpent', '0m')

            created = dateutil.parser.parse(worklog_hash['started'])
            created_pattern = '%a %x         '  # Adding extra space for formatting
            if not created.hour == created.minute == created.second == 0:
                created = created.astimezone(tzlocal())
                created_pattern = '%a %x %I:%M %p'
            comment = worklog_hash.get('comment', '<no comment>')

            updated_string = created.strftime(created_pattern)
            print "  %s - %s (%s): %s" % (updated_string, author, time_spent, comment)
    else:
        print "  No worklogs"

    cycle_time = jira.get_cycle_time(issue)
    if cycle_time:
        print '\nCycle Time: %.1f days' % cycle_time

    # Print the time elapsed since the last mark
    elapsed_time = jira.get_elapsed_time(issue)
    if elapsed_time:
        print '\n\033[0;32m%s elapsed\033[00m (use "jtime log ." to log elapsed time or "jtime log <duration> (ex. 30m, 1h etc.)" to log a specific amount of time)' % (elapsed_time)
    else:
        print '\n\033[0;32m0m elapsed\033[00m'
496912
private void printDeliverables() {
        final List<Map.Entry<String, String>> pairs = readProjectFile().deliverables.stream()
                .filter(deliverable -> deliverable.id != null)
                .map(deliverable -> new AbstractMap.SimpleEntry<String, String>(deliverable.id, deliverable.name))
                .collect(Collectors.toList());
        final int length = pairs.stream()
                .map(p -> p.getKey())
                .map(String::length)
                .reduce(Integer::max)
                .orElse(0);
        for (Map.Entry<String, String> pair : pairs) {
            System.out.println(Strings.padEnd(pair.getKey(), length, ' ')
                    + (pair.getValue() != null ? ("  " + pair.getValue()) : ""));
        }
    }
322179
private static void listTasks(ProjectFile file)
   {
      SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm z");

      for (Task task : file.getTasks())
      {
         Date date = task.getStart();
         String text = task.getStartText();
         String startDate = text != null ? text : (date != null ? df.format(date) : "(no start date supplied)");

         date = task.getFinish();
         text = task.getFinishText();
         String finishDate = text != null ? text : (date != null ? df.format(date) : "(no finish date supplied)");

         Duration dur = task.getDuration();
         text = task.getDurationText();
         String duration = text != null ? text : (dur != null ? dur.toString() : "(no duration supplied)");

         dur = task.getActualDuration();
         String actualDuration = dur != null ? dur.toString() : "(no actual duration supplied)";

         String baselineDuration = task.getBaselineDurationText();
         if (baselineDuration == null)
         {
            dur = task.getBaselineDuration();
            if (dur != null)
            {
               baselineDuration = dur.toString();
            }
            else
            {
               baselineDuration = "(no duration supplied)";
            }
         }

         System.out.println("Task: " + task.getName() + " ID=" + task.getID() + " Unique ID=" + task.getUniqueID() + " (Start Date=" + startDate + " Finish Date=" + finishDate + " Duration=" + duration + " Actual Duration" + actualDuration + " Baseline Duration=" + baselineDuration + " Outline Level=" + task.getOutlineLevel() + " Outline Number=" + task.getOutlineNumber() + " Recurring=" + task.getRecurring() + ")");
      }
      System.out.println();
   }
697911
def isworkday(self, date):
        
        date = parsefun(date)
        return self.weekdaymap[date.weekday()].isworkday