text:
from .controllers import retrieve_and_match_candidate_from_vote_smart, \
    retrieve_vote_smart_candidates_into_local_db, \
    retrieve_vote_smart_candidate_bio_into_local_db, \
    retrieve_vote_smart_position_categories_into_local_db, \
    retrieve_vote_smart_officials_into_local_db, retrieve_and_save_vote_smart_states, \
    retrieve_vote_smart_ratings_for_candidate_into_local_db, retrieve_vote_smart_ratings_by_group_into_local_db, \
    retrieve_vote_smart_special_interest_group_into_local_db, \
    retrieve_vote_smart_special_interest_groups_into_local_db, \
    transfer_vote_smart_special_interest_groups_to_we_vote_organizations, \
    transfer_vote_smart_ratings_to_positions_for_candidate, transfer_vote_smart_ratings_to_positions_for_politician
from .models import VoteSmartCandidate, VoteSmartCategory, VoteSmartRating, VoteSmartRatingOneCandidate, \
    VoteSmartSpecialInterestGroup, VoteSmartState
from .votesmart_local import VotesmartApiError
from admin_tools.views import redirect_to_sign_in_page
from candidate.models import CandidateCampaignManager, CandidateCampaign
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.contrib.messages import get_messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from exception.models import print_to_log
from voter.models import voter_has_authority
import wevote_functions.admin
from wevote_functions.functions import convert_to_int, positive_value_exists, STATE_CODE_MAP

logger = wevote_functions.admin.get_logger(__name__)

@login_required
def import_one_candidate_ratings_view(request, vote_smart_candidate_id):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    # retrieve_vote_smart_ratings_for_candidate_into_local_db can be used for both We Vote candidate or politician
    one_group_results = retrieve_vote_smart_ratings_for_candidate_into_local_db(vote_smart_candidate_id)

    if one_group_results['success']:
        messages.add_message(request, messages.INFO, "Ratings for one candidate retrieved. ")
    else:
        messages.add_message(request, messages.ERROR, "Ratings for one candidate NOT retrieved. "
                                                      "(error: {error_message})"
                                                      "".format(error_message=one_group_results['status']))

    candidate_manager = CandidateCampaignManager()
    results = candidate_manager.retrieve_candidate_campaign_from_vote_smart_id(vote_smart_candidate_id)
    if results['candidate_campaign_found']:
        candidate = results['candidate_campaign']
        candidate_campaign_id = candidate.id
        return HttpResponseRedirect(reverse('candidate:candidate_edit', args=(candidate_campaign_id,)))
    else:
        return HttpResponseRedirect(reverse('candidate:candidate_list', args=()))

@login_required
def import_one_politician_ratings_view(request, vote_smart_candidate_id):  # TODO DALE update to politician
    authority_required = {'admin'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    # retrieve_vote_smart_ratings_for_candidate_into_local_db can be used for both We Vote candidate or politician
    one_group_results = retrieve_vote_smart_ratings_for_candidate_into_local_db(vote_smart_candidate_id)

    if one_group_results['success']:
        messages.add_message(request, messages.INFO, "Ratings for one candidate retrieved. ")
    else:
        messages.add_message(request, messages.ERROR, "Ratings for one candidate NOT retrieved. "
                                                      "(error: {error_message})"
                                                      "".format(error_message=one_group_results['status']))

    candidate_manager = CandidateCampaignManager()
    results = candidate_manager.retrieve_candidate_campaign_from_vote_smart_id(vote_smart_candidate_id)
    if results['candidate_campaign_found']:
        candidate = results['candidate_campaign']
        candidate_campaign_id = candidate.id
        return HttpResponseRedirect(reverse('candidate:candidate_edit', args=(candidate_campaign_id,)))
    else:
        return HttpResponseRedirect(reverse('candidate:candidate_list', args=()))

@login_required
def import_group_ratings_view(request):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    # state_code = request.GET.get('state_code', 'NA')  # Default to national
    # category_id = request.GET.get('category_id', 0)

    # Retrieve each group so we can request the ratings for each group
    get_sig_group_count = 0
    get_sig_error_message_count = 0
    special_interest_group_list = VoteSmartSpecialInterestGroup.objects.order_by('name')
    for one_group in special_interest_group_list:
        special_interest_group_id = one_group.sigId
        one_group_results = retrieve_vote_smart_ratings_by_group_into_local_db(special_interest_group_id)

        if not one_group_results['success']:
            print_to_log(logger=logger, exception_message_optional=one_group_results['status'])
            get_sig_error_message_count += 1
        else:
            get_sig_group_count += 1

    messages.add_message(request, messages.INFO, "Ratings from {get_sig_group_count} "
                                                 "Special Interest Groups retrieved. "
                                                 "(errors: {get_sig_error_message_count})"
                                                 "".format(get_sig_group_count=get_sig_group_count,
                                                           get_sig_error_message_count=get_sig_error_message_count))

    return HttpResponseRedirect(reverse('import_export_vote_smart:vote_smart_rating_list', args=()))

@login_required
def import_one_group_ratings_view(request, special_interest_group_id):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    one_group_results = retrieve_vote_smart_ratings_by_group_into_local_db(special_interest_group_id)

    if one_group_results['success']:
        messages.add_message(request, messages.INFO, "Ratings from Special Interest Group retrieved. ")
    else:
        messages.add_message(request, messages.ERROR, "Ratings from Special Interest Group NOT retrieved. "
                                                      "(error: {error_message})"
                                                      "".format(error_message=one_group_results['status']))

    return HttpResponseRedirect(reverse('import_export_vote_smart:special_interest_group_rating_list',
                                        args=(special_interest_group_id,)))

@login_required
def import_states_view(request):
    """
    """
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    retrieve_and_save_vote_smart_states()

    template_values = {
        'state_list': VoteSmartState.objects.order_by('name'),
    }
    return render(request, 'import_export_vote_smart/vote_smart_import.html', template_values)

@login_required
def import_photo_view(request):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    # NOTE: This view is for testing purposes. For the operational "Import Vote Smart Images" view, see:
    #  "candidate_retrieve_photos_view" in candidate/views_admin.py
    last_name = "Trump"
    results = retrieve_vote_smart_candidates_into_local_db(last_name)
    if not results['success']:
        messages.add_message(request, messages.INFO, results['status'])
    else:
        messages.add_message(request, messages.INFO, "Photo retrieved.")

        # Now we can go on to make sure we have the right VoteSmartCandidate
        vote_smart_candidate_id = 15723
        # ...and then retrieve the photo
        results = retrieve_vote_smart_candidate_bio_into_local_db(vote_smart_candidate_id)

    last_name = "Pelosi"
    results = retrieve_vote_smart_officials_into_local_db(last_name)

    messages_on_stage = get_messages(request)

    template_values = {
        'messages_on_stage': messages_on_stage,
    }
    return render(request, 'import_export_vote_smart/vote_smart_import.html', template_values)

@login_required
def import_special_interest_groups_view(request):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    # state_code = request.GET.get('state_code', 'NA')  # Default to national
    # category_id = request.GET.get('category_id', 0)

    # First retrieve an index of all groups for each state and category
    group_count = 0
    error_message_count = 0
    position_category_list = VoteSmartCategory.objects.order_by('name')
    for position_category in position_category_list:
        category_id = position_category.categoryId

        for state_code, state_name in STATE_CODE_MAP.items():
            results = retrieve_vote_smart_special_interest_groups_into_local_db(category_id, state_code)

            if not results['success']:
                # messages.add_message(request, messages.INFO, results['status'])
                print_to_log(logger=logger, exception_message_optional=results['status'])
                error_message_count += 1
            else:
                group_count += 1

    messages.add_message(request, messages.INFO, "{group_count} Special Interest Groups retrieved. "
                                                 "(errors: {error_message_count})"
                                                 "".format(group_count=group_count,
                                                           error_message_count=error_message_count))

    # Then retrieve the details about each group
    get_sig_group_count = 0
    get_sig_error_message_count = 0
    special_interest_group_list = VoteSmartSpecialInterestGroup.objects.order_by('name')
    for one_group in special_interest_group_list:
        special_interest_group_id = one_group.sigId
        one_group_results = retrieve_vote_smart_special_interest_group_into_local_db(special_interest_group_id)

        if not one_group_results['success']:
            print_to_log(logger=logger, exception_message_optional=one_group_results['status'])
            get_sig_error_message_count += 1
        else:
            get_sig_group_count += 1

    messages.add_message(request, messages.INFO, "{get_sig_group_count} Special Interest Groups augmented. "
                                                 "(errors: {get_sig_error_message_count})"
                                                 "".format(get_sig_group_count=get_sig_group_count,
                                                           get_sig_error_message_count=get_sig_error_message_count))

    return HttpResponseRedirect(reverse('import_export_vote_smart:vote_smart_special_interest_group_list', args=()))

@login_required
def vote_smart_candidate_list_view(request):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    messages_on_stage = get_messages(request)
    candidate_list = []
    candidate_list_found = False
    try:
        candidate_list = VoteSmartCandidate.objects.order_by('lastName')[:1000]  # Descending order, and limited to 1000
        if len(candidate_list):
            candidate_list_found = True
    except VotesmartApiError as error_instance:
        # Catch the error message coming back from Vote Smart and pass it in the status
        error_message = error_instance.args
        status = "EXCEPTION_RAISED: {error_message}".format(error_message=error_message)
        print_to_log(logger=logger, exception_message_optional=status)

    # election_list = Election.objects.order_by('-election_day_text')

    if candidate_list_found:
        template_values = {
            'messages_on_stage': messages_on_stage,
            'candidate_list': candidate_list,
        }
    else:
        template_values = {
            'messages_on_stage': messages_on_stage,
        }
    return render(request, 'import_export_vote_smart/candidate_list.html', template_values)

@login_required
def vote_smart_rating_list_view(request):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    messages_on_stage = get_messages(request)
    rating_list = []
    rating_list_found = False
    try:
        rating_list = VoteSmartRating.objects.order_by('-timeSpan')[:1000]  # Descending order, and limited to 1000
        if len(rating_list):
            rating_list_found = True
    except VotesmartApiError as error_instance:
        # Catch the error message coming back from Vote Smart and pass it in the status
        error_message = error_instance.args
        status = "EXCEPTION_RAISED: {error_message}".format(error_message=error_message)
        print_to_log(logger=logger, exception_message_optional=status)

    # election_list = Election.objects.order_by('-election_day_text')

    if rating_list_found:
        template_values = {
            'messages_on_stage': messages_on_stage,
            'rating_list': rating_list,
            # 'election_list': election_list,
            # 'google_civic_election_id': google_civic_election_id,
        }
    else:
        template_values = {
            'messages_on_stage': messages_on_stage,
            # 'election_list': election_list,
            # 'google_civic_election_id': google_civic_election_id,
        }
    return render(request, 'import_export_vote_smart/rating_list.html', template_values)

@login_required
def special_interest_group_rating_list_view(request, special_interest_group_id):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    messages_on_stage = get_messages(request)
    special_interest_group_id = convert_to_int(special_interest_group_id)
    # google_civic_election_id = request.GET.get('google_civic_election_id', 0)
    special_interest_group = VoteSmartSpecialInterestGroup()
    special_interest_group_found = False
    try:
        special_interest_group_query = VoteSmartSpecialInterestGroup.objects.filter(sigId=special_interest_group_id)
        if special_interest_group_query.count():
            special_interest_group = special_interest_group_query[0]
            special_interest_group_found = True
    except VotesmartApiError as error_instance:
        # Catch the error message coming back from Vote Smart and pass it in the status
        error_message = error_instance.args
        status = "EXCEPTION_RAISED: {error_message}".format(error_message=error_message)
        print_to_log(logger=logger, exception_message_optional=status)
        special_interest_group_found = False

    if not special_interest_group_found:
        messages.add_message(request, messages.ERROR,
                             'Could not find special_interest_group when trying to retrieve ratings.')
        return HttpResponseRedirect(reverse('import_export_vote_smart:vote_smart_special_interest_group_list', args=()))
    else:
        rating_list = []
        rating_list_found = False
        try:
            rating_list = VoteSmartRatingOneCandidate.objects.order_by('-timeSpan')
            rating_list = rating_list.filter(sigId=special_interest_group_id)
            if len(rating_list):
                rating_list_found = True
        except VotesmartApiError as error_instance:
            # Catch the error message coming back from Vote Smart and pass it in the status
            error_message = error_instance.args
            status = "EXCEPTION_RAISED: {error_message}".format(error_message=error_message)
            print_to_log(logger=logger, exception_message_optional=status)

        # election_list = Election.objects.order_by('-election_day_text')

        if rating_list_found:
            template_values = {
                'messages_on_stage': messages_on_stage,
                'special_interest_group': special_interest_group,
                'rating_list': rating_list,
                # 'election_list': election_list,
                # 'google_civic_election_id': google_civic_election_id,
            }
        else:
            template_values = {
                'messages_on_stage': messages_on_stage,
                'special_interest_group': special_interest_group,
                # 'election_list': election_list,
                # 'google_civic_election_id': google_civic_election_id,
            }
    return render(request, 'import_export_vote_smart/group_rating_list.html', template_values)

@login_required
def vote_smart_special_interest_group_list_view(request):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    messages_on_stage = get_messages(request)

    special_interest_group_list = VoteSmartSpecialInterestGroup.objects.order_by('name')

    template_values = {
        'messages_on_stage': messages_on_stage,

        'special_interest_group_list': special_interest_group_list,
    }
    return render(request, 'import_export_vote_smart/special_interest_group_list.html', template_values)

@login_required
def import_vote_smart_position_categories_view(request):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    results = retrieve_vote_smart_position_categories_into_local_db()
    if not results['success']:
        messages.add_message(request, messages.INFO, results['status'])
    else:
        messages.add_message(request, messages.INFO, "Categories retrieved.")

    return HttpResponseRedirect(reverse('import_export_vote_smart:vote_smart_position_category_list', args=()))

def retrieve_positions_from_vote_smart_for_election_view(request):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    google_civic_election_id = convert_to_int(request.GET.get('google_civic_election_id', 0))

    try:
        candidate_list = CandidateCampaign.objects.all()
        if positive_value_exists(google_civic_election_id):
            candidate_list = candidate_list.filter(google_civic_election_id=google_civic_election_id)
        candidate_list = candidate_list.order_by('candidate_name')[:500]
    except CandidateCampaign.DoesNotExist:
        messages.add_message(request, messages.INFO, "Could not find any candidates for google_civic_election_id: "
                                                     "{google_civic_election_id}."
                                                     "".format(google_civic_election_id=google_civic_election_id))
        return HttpResponseRedirect(reverse('position:position_list', args=()))

    message = "Entering retrieve_positions_from_vote_smart_for_election."
    print_to_log(logger, exception_message_optional=message)

    vote_smart_candidates_that_exist = 0
    vote_smart_candidates_created = 0
    vote_smart_candidates_not_found = 0
    we_vote_organizations_created = 0
    organization_positions_that_exist = 0
    organization_positions_created = 0
    # Do a first pass through where we get positions for candidates for whom we already have an id
    for we_vote_candidate in candidate_list:
        if we_vote_candidate.vote_smart_id:
            retrieve_results = retrieve_vote_smart_ratings_for_candidate_into_local_db(we_vote_candidate.vote_smart_id)
            transfer_results = transfer_vote_smart_ratings_to_positions_for_candidate(we_vote_candidate.id)

            if retrieve_results['rating_one_candidate_exists']:
                vote_smart_candidates_that_exist += 1
            if retrieve_results['rating_one_candidate_created']:
                vote_smart_candidates_created += 1

            if transfer_results['we_vote_organizations_created']:
                we_vote_organizations_created += 1
            if transfer_results['organization_positions_that_exist']:
                organization_positions_that_exist += 1
            if transfer_results['organization_positions_created']:
                organization_positions_created += 1

    message = "About to cycle through candidates for whom we don't have Vote Smart IDs for."
    print_to_log(logger, exception_message_optional=message)

    # Then we cycle through again, reach out to Vote Smart to match the candidate if we did not have a vote_smart_id,
    # and if we find a new Vote Smart id, we get positions for that candidate
    for we_vote_candidate in candidate_list:
        if not we_vote_candidate.vote_smart_id:
            force_retrieve = False
            results = retrieve_and_match_candidate_from_vote_smart(we_vote_candidate, force_retrieve)
            if results['success'] and results['we_vote_candidate_id']:
                we_vote_candidate = results['we_vote_candidate']
                if we_vote_candidate.vote_smart_id:
                    retrieve_results = retrieve_vote_smart_ratings_for_candidate_into_local_db(
                        we_vote_candidate.vote_smart_id)
                    transfer_results = transfer_vote_smart_ratings_to_positions_for_candidate(we_vote_candidate.id)

                    if retrieve_results['rating_one_candidate_exists']:
                        vote_smart_candidates_that_exist += 1
                    if retrieve_results['rating_one_candidate_created']:
                        vote_smart_candidates_created += 1

                    if transfer_results['we_vote_organizations_created']:
                        we_vote_organizations_created += 1
                    if transfer_results['organization_positions_that_exist']:
                        organization_positions_that_exist += 1
                    if transfer_results['organization_positions_created']:
                        organization_positions_created += 1
            else:
                vote_smart_candidates_not_found += 1

    message = "Google Civic Election ID: {election_id}, " \
              "{vote_smart_candidates_that_exist} candidates from Vote Smart looked at, " \
              "{vote_smart_candidates_created} new candidates cached from Vote Smart, " \
              "{vote_smart_candidates_not_found} candidates not found in Vote Smart, " \
              "{we_vote_organizations_created} organizations created in We Vote, " \
              "{organization_positions_that_exist} positions from Vote Smart already exist locally, and " \
              "{organization_positions_created} positions from Vote Smart just created locally.".\
        format(election_id=google_civic_election_id,
               vote_smart_candidates_that_exist=vote_smart_candidates_that_exist,
               vote_smart_candidates_created=vote_smart_candidates_created,
               vote_smart_candidates_not_found=vote_smart_candidates_not_found,
               we_vote_organizations_created=we_vote_organizations_created,
               organization_positions_that_exist=organization_positions_that_exist,
               organization_positions_created=organization_positions_created)

    print_to_log(logger, exception_message_optional=message)
    messages.add_message(request, messages.INFO, message)

    return HttpResponseRedirect(reverse('position:position_list', args=()) +
                                "?google_civic_election_id=" + str(google_civic_election_id))

@login_required
def transfer_vote_smart_ratings_to_positions_for_candidate_view(request, candidate_campaign_id):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    results = transfer_vote_smart_ratings_to_positions_for_candidate(candidate_campaign_id)

    if results['success']:
        messages.add_message(request, messages.INFO, results['status'])
    else:
        messages.add_message(request, messages.ERROR, results['status'])

    return HttpResponseRedirect(reverse('candidate:candidate_edit', args=(candidate_campaign_id,)))

@login_required
def transfer_vote_smart_ratings_to_positions_for_politician_view(request, politician_id):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    results = transfer_vote_smart_ratings_to_positions_for_politician(politician_id)

    if results['success']:
        messages.add_message(request, messages.INFO, results['status'])
    else:
        messages.add_message(request, messages.ERROR, results['status'])

    return HttpResponseRedirect(reverse('candidate:candidate_edit', args=(politician_id,)))

@login_required
def transfer_vote_smart_sigs_to_we_vote_orgs_view(request):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    results = transfer_vote_smart_special_interest_groups_to_we_vote_organizations()

    if results['success']:
        messages.add_message(request, messages.INFO, results['status'])
    else:
        messages.add_message(request, messages.ERROR, results['status'])

    return HttpResponseRedirect(reverse('import_export_vote_smart:vote_smart_special_interest_group_list', args=()))

@login_required
def state_detail_view(request, pk):
    """
    """
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    state_id = pk

    template_values = {
        'state': VoteSmartState.objects.get(stateId=state_id),
    }
    return render(request, 'import_export_vote_smart/state_detail.html', template_values)

@login_required
def vote_smart_index_view(request):
    """
    """
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    template_values = {
    }
    return render(request, 'import_export_vote_smart/index.html', template_values)

@login_required
def vote_smart_position_category_list_view(request):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    messages_on_stage = get_messages(request)

    position_category_list = VoteSmartCategory.objects.order_by('name')

    template_values = {
        'messages_on_stage': messages_on_stage,
        'position_category_list': position_category_list,
    }
    return render(request, 'import_export_vote_smart/position_category_list.html', template_values)


text:
module PivotalCardChecker
  # Organizes the violations into a map of owner names -> card violations.
  class ViolationsOrganizer
    PROD_INFO_INDEX = 0
    SYS_LABEL_INDEX = 1
    ACCEPTANCE_CRIT_INDEX = 2
    OTHER_ISSUES_INDEX = 3
    UNASSIGNED_CARDS_INDEX = 4

    def initialize
      @bad_card_info = Hash.new { |hash, key| hash[key] = CardViolationsManager.new }
    end

    # Sends the cards to be processed, by type, then returns the resulting
    # info (@bad_card_info).
    def organize(results)
      [[PROD_INFO_ISSUE, results[PROD_INFO_INDEX]],
       [SYS_LABEL_ISSUE, results[SYS_LABEL_INDEX]],
       [ACCEPTANCE_CRIT_ISSUE, results[ACCEPTANCE_CRIT_INDEX]],
       [OTHER_ISSUE, results[OTHER_ISSUES_INDEX]],
       [UNASSIGNED_CARDS_ISSUE, results[UNASSIGNED_CARDS_INDEX]]].each do |type, violations|
        process_list(type, violations)
      end

      @bad_card_info
    end

    # Goes through the list of cards and places them into a Hash, which maps the
    # owner name(s) to a CardViolationsManager object.
    def process_list(type, list)
      unless list.nil?
        list.each do |story_card, message|
          card_owners = get_owners(story_card.owners)
          @bad_card_info[card_owners].add_violation(type, story_card, message)
        end
      end
    end

    # Returns a comma seperated list of all the story's owners. If a card has no
    # owners, then this method will return 'NOBODY??!?!'.
    def get_owners(owners)
      return 'NOBODY??!?!' if owners.empty?

      owner_names = []
      owners.each do |person|
        owner_names << person.name
      end

      owner_names.join(', ')
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
var Path = require('path')
var Hapi = require('hapi')
var NunjucksHapi = require('nunjucks-hapi')

// server
var server = new Hapi.Server()
server.connection({
  port: process.env.PORT || 4000,
  router: {
    isCaseSensitive: false,
    stripTrailingSlash: true
  }
})

// register views
var baseDir = Path.join(__dirname, 'app/views')
var env = NunjucksHapi.configure(baseDir)
server.views({
  engines: {
    nun: {
      module: NunjucksHapi
    }
  },
  path: baseDir,
  defaultExtension: 'nun',
  isCached: false,
  compileMode: 'sync'
})

// routes
server.route(require('./config/routes').routes)

// register plugins and start server
server.register(require('./config/plugins').plugins, function(err) {
  if (err) {
    throw err
  }

  // start server
  server.start(function() {
    console.info('Server started at ' + server.info.uri)
  })
})


text:
<?php

return [
    'database'      => 'Database',
    'administrator' => 'Administrator',
    'application'   => 'Application',
];


text:
#ifndef RMLUI_CORE_MATH_H
#define RMLUI_CORE_MATH_H

#include "Header.h"

namespace Rml {

template <typename Type> class Vector2;
using Vector2f = Vector2< float >;

namespace Math {

// The constant PI.
extern RMLUICORE_API const float RMLUI_PI;

template < typename Type >
Type Max(Type a, Type b)
{
	return (a > b) ? a : b;
}

template< typename Type >
Type Min(Type a, Type b)
{
	return (a < b) ? a : b;
}

template < typename Type >
Type ClampLower(Type value, Type min)
{
	return (value < min) ? min : value;
}

template < typename Type >
Type ClampUpper(Type value, Type max)
{
	return (value > max) ? max: value;
}

template< typename Type >
Type Clamp(Type value, Type min, Type max)
{
	return (value < min) ? min : (value > max) ? max : value;
}

template< typename Type >
Type Lerp(float t, Type v0, Type v1)
{
	return v0 * (1.0f - t) + v1 * t;
}

/// Evaluates if a number is, or close to, zero.
/// @param[in] value The number to compare to zero.
/// @return True if the number if zero or close to it, false otherwise.
RMLUICORE_API bool IsZero(float value);
/// Evaluates if two floating-point numbers are equal, or so similar that they could be considered
/// so.
/// @param[in] value_0 The first number to compare.
/// @param[in] value_1 The second number to compare.
/// @return True if the numbers are similar or equal.
RMLUICORE_API bool AreEqual(float value_0, float value_1);

/// Calculates the absolute value of a number.
/// @param[in] value The number of get the absolute value of.
/// @return The absolute value of the number.
RMLUICORE_API float AbsoluteValue(float value);

/// Calculates the cosine of an angle.
/// @param[in] angle The angle to calculate the cosine of, in radians.
/// @return The cosine of the angle.
RMLUICORE_API float Cos(float angle);
/// Calculates the arc-cosine of an value.
/// @param[in] angle The value to calculate the arc-cosine of.
/// @return The angle, in radians.
RMLUICORE_API float ACos(float value);
/// Calculates the sine of an angle.
/// @param[in] angle The angle to calculate the sine of, in radians.
/// @return The sine of the angle.
RMLUICORE_API float Sin(float angle);
/// Calculates the arc-sine of an value.
/// @param[in] angle The value to calculate the arc-sine of.
/// @return The angle, in radians.
RMLUICORE_API float ASin(float angle);
/// Calculates the tangent of an angle.
/// @param[in] angle The angle to calculate the tangent of, in radians.
/// @return The tanget of the angle.
RMLUICORE_API float Tan(float angle);
/// Calculates the angle of a two-dimensional line.
/// @param[in] y The y-component of the line.
/// @param[in] x The x-component of the line.
/// @return The angle of the line in radians.
RMLUICORE_API float ATan2(float y, float x);
/// Evaluates the natural exponential function on a value.
/// @param[in] value The value
/// @return e^(value)
RMLUICORE_API float Exp(float value);

/// Converts an angle from radians to degrees.
/// @param[in] The angle, in radians.
/// @return The angle converted to degrees.
RMLUICORE_API float RadiansToDegrees(float angle);
/// Converts an angle from degrees to radians.
/// @param[in] The angle, in degrees.
/// @return The angle converted to radians.
RMLUICORE_API float DegreesToRadians(float angle);
/// Normalises and angle in radians
/// @param[in] The angle, in randians
/// @return The normalised angle
RMLUICORE_API float NormaliseAngle(float angle);

/// Calculates the square root of a value.
/// @param[in] value The value to calculate the square root of. This must be above zero.
/// @return The square root of the value.
RMLUICORE_API float SquareRoot(float value);

/// Rounds a floating-point value to the nearest integer.
/// @param[in] value The value to round.
/// @return The rounded integer as float.
RMLUICORE_API float RoundFloat(float value);
/// Rounds a floating-point value to the nearest integer.
/// @param[in] value The value to round.
/// @return The rounded integer as double.
RMLUICORE_API double RoundFloat(double value);
/// Rounds a floating-point value up to the nearest integer.
/// @param[in] value The value to round.
/// @return The rounded integer as float.
RMLUICORE_API float RoundUpFloat(float value);
/// Rounds a floating-point value down to the nearest integer.
/// @param[in] value The value to round.
/// @return The rounded integer as float.
RMLUICORE_API float RoundDownFloat(float value);
/// Rounds a floating-point value to the nearest integer.
/// @param[in] value The value to round.
/// @return The rounded integer.
RMLUICORE_API int RoundToInteger(float value);
/// Rounds a floating-point value up to the nearest integer.
/// @param[in] value The value to round.
/// @return The rounded integer.
RMLUICORE_API int RoundUpToInteger(float value);
/// Rounds a floating-point value down to the nearest integer.
/// @param[in] value The value to round.
/// @return The rounded integer.
RMLUICORE_API int RoundDownToInteger(float value);

/// Efficiently truncates a floating-point value into an integer.
/// @param[in] value The value to truncate.
/// @return The truncated value as a signed integer.
RMLUICORE_API int RealToInteger(float value);

/// Round the position and width of a line segment to the pixel grid while minimizing movement of the edges.
/// @param[inout] x The position, which will use normal rounding.
/// @param[inout] width The width, which is rounded such that movement of the right edge is minimized.
RMLUICORE_API void SnapToPixelGrid(float& x, float& width);
/// Round the position and size of a rectangle to the pixel grid while minimizing movement of the edges.
/// @param[inout] position The position, which will use normal rounding.
/// @param[inout] size The size, which is rounded such that movement of the right and bottom edges is minimized.
RMLUICORE_API void SnapToPixelGrid(Vector2f& position, Vector2f& size);
/// Round the position and size of a rectangle to the pixel grid such that it fully covers the original rectangle.
/// @param[inout] position The position, which will be rounded down.
/// @param[inout] size The size, which is rounded such that the right and bottom edges are rounded up.
RMLUICORE_API void ExpandToPixelGrid(Vector2f& position, Vector2f& size);

/// Converts a number to the nearest power of two, rounding up if necessary.
/// @param[in] value The value to convert to a power-of-two.
/// @return The smallest power of two that is as least as big as the input value.
RMLUICORE_API int ToPowerOfTwo(int value);

/// Converts from the ASCII-representation of a hexadecimal digit to decimal.
/// @param[in] hex_digit The hexadecimal digit to convert to decimal.
/// @return The digit in decimal.
RMLUICORE_API int HexToDecimal(char hex_digit);

/// Generates a random floating-point value between 0 and a user-specified value.
/// @param[in] max_value The limit to random value. The generated value will be guaranteed to be below this limit.
/// @return The random value.
RMLUICORE_API float RandomReal(float max_value);
/// Generates a random integer value between 0 and a user-specified value.
/// @param[in] max_value The limit to random value. The generated value will be guaranteed to be below this limit.
/// @return The random value.
RMLUICORE_API int RandomInteger(int max_value);
/// Generates a random boolean value, with equal chance of true or false.
/// @return The random value.
RMLUICORE_API bool RandomBool();

}
} // namespace Rml
#endif


text:
from enum import Enum

from blinker import signal  # type: ignore

class SIGNAL(Enum):
    begin = "begin"
    end = "end"

    enter_state = "enter_state"
    exit_state = "exit_state"
    pause_state = "pause_state"
    resume_state = "resume_state"

    display_text = "display_text"

    begin_display_choices = "begin_display_choices"
    display_choice = "display_choice"
    end_display_choices = "end_display_choices"

    waiting_for_input = "waiting_for_input"

    quality_changed = "quality_changed"

class Signals:
    begin = signal(SIGNAL.begin.value)
    end = signal(SIGNAL.end.value)

    enter_state = signal(SIGNAL.enter_state.value)
    exit_state = signal(SIGNAL.exit_state.value)
    pause_state = signal(SIGNAL.pause_state.value)
    resume_state = signal(SIGNAL.resume_state.value)

    display_text = signal(SIGNAL.display_text.value)

    begin_display_choices = signal(SIGNAL.begin_display_choices.value)
    display_choice = signal(SIGNAL.display_choice.value)
    end_display_choices = signal(SIGNAL.end_display_choices.value)

    waiting_for_input = signal(SIGNAL.waiting_for_input.value)

    quality_changed = signal(SIGNAL.quality_changed.value)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>E-Index</title>
<meta name="date" content="2016-04-20">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C E F G H I K L M N O P R S T U V X

E

editIndexList(ArrayList<Index>) - Method in class struct.Trie

Entry - Class in struct

Entry(int, Lat_Attribute, String, int, int, int) - Constructor for class struct.Entry

entry - Variable in class struct.Table

EntryHandler - Class in handler

EntryHandler() - Constructor for class handler.EntryHandler

equals(Object) - Method in class struct.Lat_Attribute

extent - Variable in class struct.Lat_Concept

A B C E F G H I K L M N O P R S T U V X

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
using System.Linq;
using System.Web.Mvc;
using Abp.Authorization;
using Abp.Extensions;
using BodeAbp.Product.Products.Domain;
using Abp.Web.Mvc.Authorization;
using BodeAbp.Product.Attributes.Domain;
using Abp.Domain.Repositories;
using BodeAbp.Activity.Activities.Domain;
using BodeAbp.Zero.Users.Domain;
using System.Collections.Generic;

namespace WebDemo.Web.Areas.Admin.Controllers
{
    public class HomeController : Controller
    {
        private readonly IRepository<ProductClassify> _pclassifyRepository;
        private readonly IRepository<Classify> _classifyRepository;

        public HomeController(IRepository<ProductClassify> pclassifyRepository, IRepository<Classify> classifyRepository)
        {
            _pclassifyRepository = pclassifyRepository;
            _classifyRepository = classifyRepository;
        }

        #region 视图页

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Table()
        {
            ViewBag.Enums = new List<int>() { 1, 2 }.Select(p => new
            {
                value = p,
                text = "类型_" + p
            }).ToArray();
            return View();
        }

        public ActionResult Default()
        {
            //_pclassifyRepository.Insert(new ProductClassify() {Name="test" });
            //_classifyRepository.Insert(new Classify() { Name = "test" });
            return View();
        }

        #endregion
    }
}


text:
$(function() {
    $("#body_touch").swipe({
        swipeLeft: function (event, direction, distance, duration, fingerCount) {
            $(".cd-nav-trigger").click();
        }
    });
});

$(function() {
    $("#dept_body").swipe({
        swipeLeft: function (event, direction, distance, duration, fingerCount) {
            $('#dept_menu').prop('checked', true);
        }
    });
});

$(function() {
    $("#dept_body").swipe({
        tap: function (event,target) {
            $('#dept_menu').prop('checked', false);
        }
    });
});

$(function() {
    $("#header_touch").swipe({
        swipeUp: function (event, direction, distance, duration, fingerCount) {
            $("#down_arrow").click();
        }

    });
});


text:
package org.ladanse.persistence.entity.master;

import javax.persistence.*;

@Entity
@Table(name = "GameRace")
public class GameRace
{
    private Integer id;
    private String name;

    @Id
    @Column(name = "id", nullable = false)
    public Integer getId()
    {
        return id;
    }

    public GameRace setId(Integer id)
    {
        this.id = id;
        return this;
    }

    @Basic
    @Column(name = "name", nullable = false, length = 20)
    public String getName()
    {
        return name;
    }

    public GameRace setName(String name)
    {
        this.name = name;
        return this;
    }
}


text:
.. highlight:: bash

============
Command Line
============

When running ``vagga``, it  finds the ``vagga.yaml`` file in current working
directory or any of its parents and uses that as a project root directory
(alternative files are supported too, see below).

When running ``vagga`` without arguments it displays a short summary of which
commands are defined by ``vagga.yaml``, like this::

    $ vagga
    Available commands:
        run                 Run mysample project
        build-docs          Build documentation using sphinx

Refer to :ref:`commands` for more information of how to define commands for
vagga.

There are also builtin commands. All builtin commands start with underscore
``_`` character to be clearly distinguished from user-defined commands.

Full list of files that mark directory as vagga's project:

1. ``vagga.yaml`` primary and preferred one
2. ``.vagga/vagga.yaml`` as an alternative to ``vagga.yaml`` (useful if you
   don't want to commit it to a git)
3. ``vagga.local.yaml`` or ``.vagga.local.yaml`` or ``.vagga/local.yaml``
   which contain additional :opt:`mixins` also mark project directory even
   if no ``vagga.yaml`` is present (since vagga 0.8.1)

Multiple Commands
=================

Since vagga 0.6 there is a way to run multiple commands at once::

    $ vagga -m cmd1 cmd2

This is similar to running::

    $ vagga cmd1 && vagga cmd2

But there is one key difference: **containers needed to run all the commands
are built beforehand**. This has two consequences:

1. When containers need to be rebuilt, they are rebuilt first, then you see
   the output of both commands in sequence (no container build log in-between)
2. If container for command 2 depends on side-effects of running command 1
   (i.e. container contains a binary built by command 1), you will get wrong
   results. In that case you should rely on shell to do the work (for example
   in the repository of vagga itself ``vagga -m make test`` is **not** the
   right way, the right is ``vagga make && vagga test``)

Obviously you can't pass any arguments to either of commands when running
``vagga -m``, this is also the biggest reason of why you can't run built-in
commands (those starting with underscore) using the option. But you can use
global options, and they influence all the commands, for example::

    $ vagga --environ DISPLAY:0 -m clean_profile run_firefox

Builtin Commands
================

All commands have ``--help``, so we don't duplicate all command-line flags
here

vagga _run CONTAINER CMD ARG...
  run arbitrary command in container defined in vagga.yaml

vagga _build CONTAINER
  Builds container without running a command.

  More useful in the form::

      $ vagga _build --force container_name

  To rebuild a container that has previously been built.

vagga _clean
  Removes images and temporary files created by vagga.

  The following command removes containers that are not used by current vagga
  config (considering the state of all files that ``vagga.yaml`` depends on)::

      $ vagga _clean --unused

  Another for removes containers which were not uses for some time::

      $ vagga _clean --unused --at-least 10days

  This is faster as it only checks timestamps of the containers. Each time
  any command in a container is run, we update timestamp. This is generally
  more useful than bare ``--unused``, because it allows to keep multiple
  versions of same container, which means you can switch between branches
  rapidly.

  There an old and deprecated option for removing unused containers::

      $ vagga _clean --old

  This is different because it only looks at symlinks in ``.vagga/*``. So may
  be wrong (if you changed ``vagga.yaml`` and did not run the command(s)). It's
  faster because it doesn't calculate the hashsums. But the difference in
  speed usually not larger than a few seconds (on large configs). The existence
  of the two commands should probably be treated as a historical accident
  and ``--unused`` variant preferred.

  For other operations and parameters see ``vagga _clean --help``

vagga _list
  List of commands (similar to running vagga without command)

vagga _version_hash CONTAINER
  Prints version hash for the container. In case the image has not been built
  (or config has been updated since) it should return new hash. But sometimes
  it's not possible to determine the hash in advance. In this case command
  returns an error.

  Might be used in some automation scripts.

vagga _init_storage_dir
  **Deprecated**. Use :opt:`storage-subdir-from-env-var` instead.

  If you have configured a :opt:`storage-dir` in settings, say
  ``/vagga-storage``, when you run ``vagga _init_storage_dir abc`` will create
  a ``/vagga-storage/abc`` and ``.vagga`` with ``.vagga/.lnk`` pointing to
  the directory. The command ensures that the storage dir is not used for any
  other folder (unless ``--allow-multiple`` is specified).

  This is created for buildbots which tend to clean ``.vagga`` directory on
  every build (like gitlab-ci) or just very often.

  Since vagga 0.6 there is ``--allow-multiple`` flag, that allows to keep
  shared subdirectory for multiple source directories. This is useful for CI
  systems which use different build directories for different builds.

  .. warning:: While simultanenous builds of different source directories, with
     the same subdirectory should work most of the time, this functionality
     still considered exerimental and may have some edge cases.

vagga _pack_image IMAGE_NAME
  Pack image into the tar archive, optionally compressing and output it into
  stdout (use shell redirection ``> file.tar`` to store it into the file).

  It's very similar to ``tar -cC .vagga/IMAGE_NAME/root`` except it deals with
  file owners and permissions correctly. And similar to running
  ``vagga _run IMAGE_NAME tar -c /`` except it ignores mounted file systems.

.. _vagga_push_image:

vagga _push_image IMAGE_NAME
  Push container image ``IMAGE_NAME`` into the image cache.

  Actually it boils down to packing an image into tar (``vagga _pack_image``)
  and running :opt:`push-image-script`, see the documentation of the setting
  to find out how to configure image cache.

vagga _base_dir
  Displays (writes to stdout) directory where active ``vagga.yaml`` is.

vagga _relative_work_dir
  Displays (writes to stdout) current working directory relative to the
  base directory. Basically, this means that
  ``$(vagga _base_dir)/$(vagga _relative_work_dir)`` is current working
  directory.

  When current working directory contains ``vagga.yaml`` this command returns
  empty string (output still contains a newline), not a single dot, as one
  may expect.

.. _update_symlinks:

vagga _update_symlinks
  **This functionality is experimental**. Some details can change in future.

  Creates a set of symlinks in your home directory (`~/.vagga/cmd`) and in
  current vagga directory (`.vagga/.cmd`) which point to commands named in
  vagga. Symlinks are created to the current vagga binary (which is resolved
  using ``readlink /proc/self/exe`` not, ``argv[0]``).

  These directories can be added to ``PATH`` either in your shell or in
  your text editor, IDE, or any other kind of shell. Or you can pass them
  to scripts which allow customization
  (``make RSYNC=/myproj/.vagga/.cmd/rsync``).

  Only comands which have ``symlink-name`` are linked with the name specified
  in the parameter. So you make create a hidden (underscored) name for some
  public command.

  There are two directories, so basically two modes of operation:

  1. User home directory ``~/.vagga/cmd``. It meant to use for utilities
     you're going to use in multiple projects. When running such a command in
     some project dir, exact command from this project dir will be invoked. So
     if you run ``flake8`` (a linter for python), correct version of linter
     for this project will be run. If you ``cd`` to another project, correct
     version of the tool with specific plugins and python interpreter will be
     picked there immediately.

  2. Project directory ``proj/.vagga/.cmd``. This directory may be used to
     specify utility directly or to point your IDE to in project settings. It's
     not recommended to add this directory to your search ``PATH``.

  Note: for (1) it's expected that single version of vagga is used for all of
  the projects, which is usually the case.

  .. versionadded:: 0.7.1

vagga _verify <container-name>
  Checks checksums of the container files against an index. This is only
  useful if ``index-all-images`` is set to true.

  It's useful to find out if some container was modified by a mistake
  (container contents are not protected in the host system).

  .. versionadded:: 0.8.1

vagga _hardlink [--global]
  Scans all containers for identical files (using some heuristics) and
  hardlink matching files. See :opt:`hard-link-identical-files`
  for precautions.

  The ``--global`` flag allows to scan all projects. This works only if
  ``storage-dir`` is set.

  .. versionadded:: 0.8.1

Normal Commands
===============

If :ref:`command<commands>` declared as ``!Command`` you get a command
with the following usage::

    Usage:
        vagga [OPTIONS] some_command [ARGS ...]

    Runs a command in container, optionally builds container if that does not
    exists or outdated. Run `vagga` without arguments to see the list of
    commands.

    positional arguments:
      some_command          Your defined command
      args                  Arguments for the command

    optional arguments:
      -h,--help             show this help message and exit
      -E,--env,--environ NAME=VALUE
                            Set environment variable for running command
      -e,--use-env VAR      Propagate variable VAR into command environment
      --no-build            Do not build container even if it is out of date.
                            Return error code 29 if it's out of date.
      --no-version-check    Do not run versioning code, just pick whatever
                            container version with the name was run last (or
                            actually whatever is symlinked under
                            `.vagga/container_name`). Implies `--no-build`

All the  ``ARGS`` that follow command are passed to the command even if they
start with dash ``-``.

Supervise Commands
==================

If :ref:`command<commands>` declared as ``!Supervise`` you get a command
with the following usage::

    Usage:
        vagga run [OPTIONS]

    Run full server stack

    optional arguments:
      -h,--help             show this help message and exit
      --only PROCESS_NAME [...]
                            Only run specified processes
      --exclude PROCESS_NAME [...]
                            Don't run specified processes
      --no-build            Do not build container even if it is out of date.
                            Return error code 29 if it's out of date.
      --no-version-check    Do not run versioning code, just pick whatever
                            container version with the name was run last (or
                            actually whatever is symlinked under
                            `.vagga/container_name`). Implies `--no-build`

Currently there is no way to provide additional arguments to commands declared
with ``!Supervise``.

The ``--only`` and ``--exclude`` arguments are useful for isolating some
single app to a separate console. For example, if you have ``vagga run``
that runs full application stack including a database, cache, web-server
and your little django application, you might do the following::

    $ vagga run --exclude django

Then in another console::

    $ vagga run --only django

Now you have just a django app that you can observe logs from and restart
independently of other applications.


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Shared.Creature {
    public class Waypoint {
        public int StayTime { get; set; }
        public float X { get; set; }
        public float Y { get; set; }
        public float Z { get; set; }

        public Waypoint(int stayTime, float x, float y, float z) {
            StayTime = stayTime;
            X = x;
            Y = y;
            Z = z;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Diagnostics;

namespace Archimedes.Geometry.Rendering
{
    /// <summary>
    /// Threadsafe Renderer
    /// </summary>
    public class Renderer : IDisposable
    {
        #region Fields

        readonly List<DrawingGroup> _groups;
        readonly object _groupsSYNC = new object();

        readonly DrawingGroup _defaultGroup;

        Image _frame = null; // Internal Master Frame

        #endregion

        #region Events

        /// <summary>
        /// Raised before the Renderer draws its own content
        /// </summary>
        public event EventHandler<RenderEventArgs> OnPostRender;

        /// <summary>
        /// Raised after the Renderer has drawed its content
        /// </summary>
        public event EventHandler<RenderEventArgs> OnPastRender;

        #endregion

        #region Constructor

        public Renderer() {
            _groups = new List<DrawingGroup>();
            _defaultGroup = new DrawingGroup("default");
            _groups.Add(_defaultGroup);
        }

        #endregion

        #region Public Render Methods

        public void Render(int width, int height, double zoom = 1.0)
        {
            Render(new SizeD(width, height), zoom);
        }

        /// <summary>
        /// Render the IDrawable List to the master frame.
        /// </summary>
        /// <param name="frameSize"></param>
        /// <param name="zoom"></param>
        public void Render(SizeD frameSize, double zoom = 1.0) {
            if (zoom <= 0)
                throw new ArgumentException("zoom factor must not be negative!");

                Image _oldframe = _frame;
                _frame = new Bitmap(
                    (int)Math.Max(1, frameSize.Width * zoom),
                    (int)Math.Max(1, frameSize.Height * zoom));

                using (var G = Graphics.FromImage(_frame)) {
                    G.SmoothingMode = SmoothingMode.AntiAlias;
                    G.ScaleTransform((float)zoom, (float)zoom);

                    if (OnPostRender != null)
                        OnPostRender(this, new RenderEventArgs(G));

                    if (BackGroundColor.HasValue)
                        G.Clear(BackGroundColor.Value);

                    lock (_groupsSYNC) {
                        foreach (var group in _groups) {
                            group.Draw(G);
                        }
                    }

                    if (OnPastRender != null)
                        OnPastRender(this, new RenderEventArgs(G));

                if (_oldframe != null)
                    _oldframe.Dispose();
            }

        }

        /// <summary>
        /// Get Image from given ViewPort location/size
        /// </summary>
        /// <param name="viewPort"></param>
        /// <returns></returns>
        public Image GetViewPortFrame(Rectangle? viewPort = null) {

                Bitmap frame;

                if (_frame == null)
                    throw new NotSupportedException("Frame is null, can not get view-port!");

                if (viewPort.HasValue)
                {
                    var viewPortRect = viewPort.Value;

                    frame = new Bitmap(viewPortRect.Width, viewPortRect.Height);
                    using (Graphics g = Graphics.FromImage(frame))
                    {
                        try {
                            g.DrawImageUnscaled(_frame, viewPortRect.Location);
                        } catch(Exception e) {
                            Debug.Fail("Failed to draw image");
                        }
                    }
                } else {
                    frame = new Bitmap(_frame.Width, _frame.Height);
                    using (Graphics g = Graphics.FromImage(frame))
                    {
                        try {
                            g.DrawImageUnscaled(_frame, new Point(0, 0));
                        } catch(Exception e) {
                            Debug.Fail("Failed to draw image");
                        }
                    }
               }
                return frame;

        }

        #endregion

        #region Public List Handling IDrawable

        /// <summary>
        /// Clear all IDrawable Elements
        /// </summary>
        public void Clear() {
            lock (_groupsSYNC) {
                _groups.Clear();
            }
        }

        /// <summary>
        /// Add a IDrawable Element
        /// </summary>
        public void Add(IDrawable drawable, string groupname = "default") {
            GetGroupOrCreate(groupname).Add(drawable);
        }

        /// <summary>
        /// Add a range of IDrawable Elements
        /// </summary>
        public void AddRange(IEnumerable<IDrawable> udrawables, string groupname = "default") {
            GetGroupOrCreate(groupname).AddRange(udrawables);
        }

        public void Remove(IDrawable drawable, string groupname = "default") {
           //GetGroupOrDefault(groupname).Remove(drawable);
            throw new NotImplementedException();
        }

        #endregion

        public void GroupClear(string groupname) {
            lock (_groupsSYNC) {
                var grp = _groups.Find(x => x.Name.Equals(groupname));
                if (grp != null)
                    grp.Clear();
            }
        }

        private DrawingGroup GetGroupOrDefault(string groupname) {
            lock (_groupsSYNC) {
                return (from g in _groups
                        where g.Name == groupname
                        select g).DefaultIfEmpty(_defaultGroup).First();
            }
        }

        private DrawingGroup GetGroupOrCreate(string groupname) {
            lock (_groupsSYNC) {
                var grp = _groups.Find(x => x.Name.Equals(groupname));

                if (grp == null) {
                    grp = new DrawingGroup(groupname);
                    _groups.Add(grp);
                }
                return grp;
            }
        }

        #region Public Properties

        public Color? BackGroundColor {
            get;
            set;
        }

        #endregion

        public void Dispose() {
            if (_frame != null)
                _frame.Dispose();
        }
    }
}


text:
package user

import (
	"github.com/openshift/origin/pkg/user/api"
)

type Initializer interface {
	InitializeUser(identity *api.Identity, user *api.User) error
}


text:
package org.jkiss.dbeaver.ext.db2;

import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.ext.db2.model.DB2DataSource;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.DBPDataSourceContainer;
import org.jkiss.dbeaver.model.connection.DBPConnectionConfiguration;
import org.jkiss.dbeaver.model.connection.DBPDriver;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCDataSourceProvider;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.utils.CommonUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * DB2 DataSource provider ddd
 */
public class DB2DataSourceProvider extends JDBCDataSourceProvider {

    private static Map<String, String> connectionsProps = new HashMap<>();

    // ------------
    // Constructors
    // ------------

    public DB2DataSourceProvider()
    {
    }

    public static Map<String, String> getConnectionsProps()
    {
        return connectionsProps;
    }

    @Override
    protected String getConnectionPropertyDefaultValue(String name, String value)
    {
        String ovrValue = connectionsProps.get(name);
        return ovrValue != null ? ovrValue : super.getConnectionPropertyDefaultValue(name, value);
    }

    @Override
    public long getFeatures()
    {
        return FEATURE_SCHEMAS;
    }

    @Override
    public String getConnectionURL(DBPDriver driver, DBPConnectionConfiguration connectionInfo)
    {
        StringBuilder url = new StringBuilder(128);
        url.append("jdbc:db2://").append(connectionInfo.getHostName());
        if (!CommonUtils.isEmpty(connectionInfo.getHostPort())) {
            url.append(":").append(connectionInfo.getHostPort());
        }
        url.append("/");
        if (!CommonUtils.isEmpty(connectionInfo.getDatabaseName())) {
            url.append(connectionInfo.getDatabaseName());
        }
        Map<String, String> properties = connectionInfo.getProviderProperties();
        boolean traceEnabled = CommonUtils.getBoolean(properties.get(DB2Constants.PROP_TRACE_ENABLED), false);
        if (traceEnabled) {
            url.append(":traceDirectory=").append(CommonUtils.toString(properties.get(DB2Constants.PROP_TRACE_FOLDER)));
            url.append(";traceFile=")
                .append(CommonUtils.escapeFileName(CommonUtils.toString(properties.get(DB2Constants.PROP_TRACE_FILE))));
            url.append(";traceFileAppend=").append(CommonUtils.getBoolean(properties.get(DB2Constants.PROP_TRACE_APPEND), false));
            url.append(";traceLevel=")
                .append(CommonUtils.toInt(properties.get(DB2Constants.PROP_TRACE_LEVEL), DB2Constants.TRACE_ALL));
            url.append(";");
        }
        return url.toString();
    }

    @NotNull
    @Override
    public DBPDataSource openDataSource(@NotNull DBRProgressMonitor monitor, @NotNull DBPDataSourceContainer container)
        throws DBException
    {
        return new DB2DataSource(monitor, container);
    }

}


text:
var _ = require('underscore');
_.str = require('underscore.string');
_.mixin(_.str.exports());

var object = require('./object');
var array = require('./array');
var functional = require('./functional');
var string = require('./string');

_.mixin(object);
_.mixin(array);
_.mixin(functional);
_.mixin(string);

module.exports = _;


text:
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--]]

-- Internalization
local sqrt = math.sqrt
local abs = math.abs
local floor = math.floor
local tonumber = tonumber
local ipairs = ipairs
local setmetatable = setmetatable
local error = error
local type = type
local _VERSION = "0.2"

-- Normalizes a colon-vector
-- See http://en.wikipedia.org/wiki/Normalized_vector
local function Normalize(_M)
  local n = 0
  for i,v in ipairs(_M) do
    n = n + (v*v)
  end
  return sqrt(n)
end

-- Checks if v is an integer
local function isInteger(v)
  return tonumber(v) and floor(v)==v or false
end

-- Checks if the given matrix is symmetric
-- See http://en.wikipedia.org/wiki/Symmetric_matrix
local function isSymmetric(_M)
  local i
  for x = 1,#_M[1]-1 do
    i = x
    for y = 1,#_M do
      i = i+1
      if not (_M[i]) then  break end
      if (_M[i][x] ~= _M[x][i]) then return false end
    end
  end
  return true
end

-- Checks if the given matrix is diagonally dominant
-- See http://en.wikipedia.org/wiki/Diagonally_dominant_matrix
local function isDiagonallyDominant(_M)
  local s
  for i = 1,#_M do
    s = 0
    for j = 1,#_M[i]-1 do
      s = (i~=j) and (s + abs(_M[i][j])) or s
    end
    if abs(_M[i][i]) < s then return false end
  end
  return true
end

-- Inits a zero-column vector
local function init1DVector(len)
  local x = {}
  for i = 1,len do x[i] = 0 end
  return x
end

-- Checks matrix validity before SOR processing
local function checkMatrix(_M,level)
  if type(_M)~='table' then
    return error('Argument is not a table!',level)
  end
  if (#_M<=1) then
    return error('Matrix should be at least 2x2!',level)
  end
  for i = 1,#_M do
    if _M[i+1] then
      if (#_M[i] ~= #_M[i+1]) then
        return error('Wrong matrix dimensions!',level)
      end
    end
    for j = 1,#_M[i] do
      if not (type(_M[i][j]) == 'number') then
        return error('Maxtrix should contains only numbers!',level)
      end
    end
  end
  if (#_M ~= #_M[1]-1) then
    return error('Column missing!',level)
  end
end

-- Checks matrix peoperties before SOR processing
local function checkMatrixProperties(_M,level)
  if not (isSymmetric(_M)) then
    return error('Matrix is not symmetric!',level)
  end
  if not (isDiagonallyDominant(_M)) then
    return error('Matrix should be diagonal dominant!',level)
  end
end

-- SOR solver Metatable
local SOR_mt = { __call = function(self,...) return self.solve(...) end,
         __newindex = function(self,key,value)
          return error ('Cannot write data inside SOR table',2)
         end,
        }

-- SOR solver
local SOR = {
        MAX_ITERATIONS = 1E4,
        W = 1.86,
        ACCURACY = 1E-6,
      }

-- Sets MAX_ITERATIONS
function SOR.setMaxIterations(I)
  if not (I>0) or not isInteger(I) then
    return error('Argument must positive integer',2)
  end
  SOR.MAX_ITERATIONS = I
end

-- Gets MAX_ITERATIONS
function SOR.getMaxIterations() return SOR.MAX_ITERATIONS end

-- Sets relaxation parameter
function SOR.SetRelaxationParameter(W)
  if not tonumber(W) or not (W>0 and W<2) then
    return error('Relaxation parameter must be a number between 0 and 2 excluded for convergence',2)
  end
  SOR.W = W
end

-- Gets relaxation parameter
function SOR.GetRelaxationParameter() return SOR.W end

-- Sets solver accuracy
function SOR.setAccuracy(Acc)
  if not tonumber(Acc) or (Acc <=0) then
    return error('Accuracy must be a positive number greather but near to 0. The lower, the better.',2)
  end
  SOR.ACCURACY = Acc
end

-- Gets Accuracy parameter
function SOR.getAccuracy() return SOR.ACCURACY end

-- Solves the given Marix
function SOR.solve(Matrix)
  checkMatrix(Matrix,3)
  checkMatrixProperties(Matrix,3)

  local n = #Matrix
  local x = init1DVector(n)
  local w = SOR.W
  local Acc = SOR.ACCURACY
  local q, p, sum
  local t = 0
  repeat
  t = t+1
  q = Normalize(x)
    for i=1,n do
    sum = Matrix[i][n+1]
      for j=1,n do
        if (i~=j) then
          sum = sum - Matrix[i][j]*x[j]
        end
      end
    x[i] = (1-w) * x[i] + w * sum/Matrix[i][i]
    end
  p = Normalize(x)
  local d = abs(p-q)
  until (d<Acc) or (t>=SOR.MAX_ITERATIONS)

  return x, t
end

return setmetatable(SOR,SOR_mt)


text:
<?php
class Product extends AppModel {
	var $name='Product';

	 public $belongsTo = array(
        'Category' => array(
            'className' => 'Category',
			'foreignKey' => 'category_id'
        )

    );

	/*public $hasOne = array(
        'Price' => array(
            'className' => 'Price',
            'foreignKey' => 'products_id'
        )
    );*/

	public $hasMany = array(
        'Cart_detail' => array(
            'className' => 'Cart_detail',
            'foreignKey' => 'product_id'
        ),

<<<<<<< HEAD
		'Product_gallery' => array(
            'className' => 'Product_gallery',
            'foreignKey' => 'products_id'
=======
		'Gallery' => array(
            'className' => 'Gallery',
            'foreignKey' => 'product_id'
>>>>>>> develop
        )

    );
	}
?>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>Ignite Tools: Shared/Airship/External/UA_json-framework/UA_SBJsonBase.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css"/>

Ignite Tools

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

Shared/Airship/External/UA_json-framework/UA_SBJsonBase.h

00001
00029
00030 #import <Foundation/Foundation.h>
00031
00032 extern NSString * UA_SBJSONErrorDomain;
00033
00034
00035 enum {
00036     UA_EUNSUPPORTED = 1,
00037     UA_EPARSENUM,
00038     UA_EPARSE,
00039     UA_EFRAGMENT,
00040     UA_ECTRL,
00041     UA_EUNICODE,
00042     UA_EDEPTH,
00043     UA_EESCAPE,
00044     UA_ETRAILCOMMA,
00045     UA_ETRAILGARBAGE,
00046     UA_EEOF,
00047     UA_EINPUT
00048 };
00049
00055 @interface UA_SBJsonBase : NSObject {
00056     NSMutableArray *errorTrace;
00057 }
00058
00066  @property(copy,readonly) NSArray* errorTrace;
00067
00069 - (void)addErrorWithCode:(NSUInteger)code description:(NSString*)str;
00070
00072 - (void)clearErrorTrace;
00073
00074 @end

 All Classes Functions Variables Properties

<address class="footer">Generated on Tue Aug 30 2011 10:11:53 for Ignite Tools by

 1.7.4 </address>


text:
<?php

/**
 * Custom Post Type
 */
class MBDL_Post_Type {

	/**
	 * @access protected
	 *
	 * @see register_post_type()
	 */
	protected $post_type;

	/**
	 * @access	protected
	 *
	 * @see		register_post_type()
	 * @link	https://codex.wordpress.org/Function_Reference/register_post_type
	 */
	protected $args;

	/**
	 * @access protected
	 *
	 * @see register_post_type()
	 */
	public function __construct( $post_type, $args ) {
		$this->post_type = $post_type;
		$this->args		 = $args;

		// register post type
		add_action( 'init', array( $this, 'register' ) );

		// add instance to global variable
		$GLOBALS[ 'mbdl_post_types' ][ $this->post_type ] = $this;

	}

	/**
	 * Register post type
	 *
	 * @uses register_post_type()
	 */
	public function register() {
		register_post_type( $this->post_type, $this->args );
	}

	/**
	 * Get posts
	 *
	 * @param array $args WP_Query args
	 *
	 * @link https://codex.wordpress.org/Template_Tags/get_posts
	 *
	 * @return array Array of posts
	 */
	public function getPosts( $args ) {
		$default = array(
			'post_type' => $this->post_type
		);
		$args	 = wp_parse_args( $args, $default );

		return get_posts( $args );
	}

	/**
	 * get post
	 *
	 * @param int | WP_Post $post Post ID or post object
	 *
	 * @return object WP_Post
	 */
	public function getPost( $post = null ) {
		return get_post( $post );
	}

	/**
	 * Get array of post titles,
	 *
	 * @return array Collection of IDs and Titles
	 */
	public function getTitles( $args = array() ) {
		global $post;

		$default = array(
			'numberposts'	 => -1,
			'order'			 => 'ASC',
			'orderby'		 => 'title',
		);

		$args = wp_parse_args( $args, $default );

		$titles = array();

		$posts = $this->getPosts( $args );
		if ( $posts ) {
			foreach ( $posts as $post ) {
				setup_postdata( $post );
				$titles[ get_the_ID() ] = get_the_title();
			}
			wp_reset_postdata();
		}
		return $titles;
	}

}


text:
package sink

import (
	"context"
	"encoding/hex"
	"fmt"
	"path"
	"strings"
	"sync"
	"sync/atomic"

	"github.com/golang/protobuf/proto"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/durationpb"
	"google.golang.org/protobuf/types/known/emptypb"

	"go.chromium.org/luci/common/clock"
	"go.chromium.org/luci/common/data/rand/mathrand"
	"go.chromium.org/luci/common/data/stringset"
	"go.chromium.org/luci/common/errors"
	"go.chromium.org/luci/common/logging"
	"go.chromium.org/luci/common/sync/parallel"

	"go.chromium.org/luci/resultdb/pbutil"
	pb "go.chromium.org/luci/resultdb/proto/v1"
	sinkpb "go.chromium.org/luci/resultdb/sink/proto/v1"
)

var zeroDuration = durationpb.New(0)

// sinkServer implements sinkpb.SinkServer.
type sinkServer struct {
	cfg           ServerConfig
	ac            *artifactChannel
	tc            *testResultChannel
	ec            *unexpectedPassChannel
	resultIDBase  string
	resultCounter uint32

	// A set of invocation-level artifact IDs that have been uploaded.
	// If an artifact is uploaded again, server should reject the request with
	// error AlreadyExists.
	invocationArtifactIDs stringset.Set
	mu                    sync.Mutex
}

func newSinkServer(ctx context.Context, cfg ServerConfig) (sinkpb.SinkServer, error) {
	// random bytes to generate a ResultID when ResultID unspecified in
	// a TestResult.
	bytes := make([]byte, 4)
	if _, err := mathrand.Read(ctx, bytes); err != nil {
		return nil, err
	}

	ctx = metadata.AppendToOutgoingContext(ctx, pb.UpdateTokenMetadataKey, cfg.UpdateToken)
	ss := &sinkServer{
		cfg:                   cfg,
		ac:                    newArtifactChannel(ctx, &cfg),
		tc:                    newTestResultChannel(ctx, &cfg),
		resultIDBase:          hex.EncodeToString(bytes),
		invocationArtifactIDs: stringset.New(0),
	}

	if cfg.ExonerateUnexpectedPass {
		ss.ec = newTestExonerationChannel(ctx, &cfg)
	}

	return &sinkpb.DecoratedSink{
		Service: ss,
		Prelude: authTokenPrelude(cfg.AuthToken),
	}, nil
}

// closeSinkServer closes the dispatcher channels and blocks until they are fully drained,
// or the context is cancelled.
func closeSinkServer(ctx context.Context, s sinkpb.SinkServer) {
	ss := s.(*sinkpb.DecoratedSink).Service.(*sinkServer)

	logging.Infof(ctx, "SinkServer: draining TestResult channel started")
	ss.tc.closeAndDrain(ctx)
	logging.Infof(ctx, "SinkServer: draining TestResult channel ended")

	logging.Infof(ctx, "SinkServer: draining Artifact channel started")
	ss.ac.closeAndDrain(ctx)
	logging.Infof(ctx, "SinkServer: draining Artifact channel ended")

	if ss.ec != nil {
		logging.Infof(ctx, "SinkServer: draining TestExoneration channel started")
		ss.ec.closeAndDrain(ctx)
		logging.Infof(ctx, "SinkServer: draining TestExoneration channel ended")
	}
}

// authTokenValue returns the value of the Authorization HTTP header that all requests must
// have.
func authTokenValue(authToken string) string {
	return fmt.Sprintf("%s %s", AuthTokenPrefix, authToken)
}

// authTokenValidator is a factory function generating a pRPC prelude that validates
// a given HTTP request with the auth key.
func authTokenPrelude(authToken string) func(context.Context, string, proto.Message) (context.Context, error) {
	expected := authTokenValue(authToken)
	missingKeyErr := status.Errorf(codes.Unauthenticated, "Authorization header is missing")

	return func(ctx context.Context, _ string, _ proto.Message) (context.Context, error) {
		md, ok := metadata.FromIncomingContext(ctx)
		if !ok {
			return nil, missingKeyErr
		}
		tks := md.Get(AuthTokenKey)
		if len(tks) == 0 {
			return nil, missingKeyErr
		}
		for _, tk := range tks {
			if tk == expected {
				return ctx, nil
			}
		}
		return nil, status.Errorf(codes.PermissionDenied, "no valid auth_token found")
	}
}

// ReportTestResults implement sinkpb.SinkServer.
func (s *sinkServer) ReportTestResults(ctx context.Context, in *sinkpb.ReportTestResultsRequest) (*sinkpb.ReportTestResultsResponse, error) {
	now := clock.Now(ctx).UTC()

	// create a slice with a rough estimate.
	uts := make([]*uploadTask, 0, len(in.TestResults)*4)
	// Unexpected passed test results that need to be exonerated.
	trsForExo := make([]*sinkpb.TestResult, 0, len(in.TestResults))
	for _, tr := range in.TestResults {
		tr.TestId = s.cfg.TestIDPrefix + tr.GetTestId()

		// assign a random, unique ID if resultID omitted.
		if tr.ResultId == "" {
			tr.ResultId = fmt.Sprintf("%s-%.5d", s.resultIDBase, atomic.AddUint32(&s.resultCounter, 1))
		}

		if s.cfg.TestLocationBase != "" {
			locFn := tr.GetTestMetadata().GetLocation().GetFileName()
			// path.Join converts the leading double slashes to a single slash.
			// Add a slash to keep the double slashes.
			if locFn != "" && !strings.HasPrefix(locFn, "//") {
				tr.TestMetadata.Location.FileName = "/" + path.Join(s.cfg.TestLocationBase, locFn)
			}
		}
		// The system-clock of GCE machines may get updated by ntp while a test is running.
		// It can possibly cause a negative duration produced, because most test harnesses
		// use system-clock to calculate the run time of a test. For more info, visit
		// crbug.com/1135892.
		if duration := tr.GetDuration(); duration != nil && s.cfg.CoerceNegativeDuration {
			// If a negative duration was reported, remove the duration.
			if d := duration.AsDuration(); d < 0 {
				logging.Warningf(ctx, "TestResult(%s) has a negative duration(%s); coercing it to 0", tr.TestId, d)
				tr.Duration = zeroDuration
			}
		}

		if err := validateTestResult(now, tr); err != nil {
			return nil, status.Errorf(codes.InvalidArgument, "%s", err)
		}

		for id, a := range tr.GetArtifacts() {
			updateArtifactContentType(a)
			n := pbutil.TestResultArtifactName(s.cfg.invocationID, tr.TestId, tr.ResultId, id)
			t, err := newUploadTask(n, a)

			// newUploadTask can return an error if os.Stat() fails.
			if err != nil {
				// TODO(crbug.com/1124868) - once all test harnesses are fixed, return 4xx on
				// newUploadTask failures instead of dropping the artifact silently.
				logging.Warningf(ctx, "Dropping an artifact request; failed to create a new Uploadtask: %s",
					errors.Annotate(err, "artifact %q: %s", id, err).Err())
				continue
			}
			uts = append(uts, t)
		}

		if s.ec != nil && !tr.Expected && tr.Status == pb.TestStatus_PASS {
			trsForExo = append(trsForExo, tr)
		}
	}

	parallel.FanOutIn(func(work chan<- func() error) {
		work <- func() error {
			s.ac.schedule(uts...)
			return nil
		}
		work <- func() error {
			s.tc.schedule(in.TestResults...)
			return nil
		}
		if s.ec != nil {
			work <- func() error {
				s.ec.schedule(trsForExo...)
				return nil
			}
		}
	})

	// TODO(1017288) - set `TestResultNames` in the response
	return &sinkpb.ReportTestResultsResponse{}, nil
}

// ReportInvocationLevelArtifacts implement sinkpb.SinkServer.
func (s *sinkServer) ReportInvocationLevelArtifacts(ctx context.Context, in *sinkpb.ReportInvocationLevelArtifactsRequest) (*emptypb.Empty, error) {
	uts := make([]*uploadTask, 0, len(in.Artifacts))
	for id, a := range in.Artifacts {
		updateArtifactContentType(a)
		if err := validateArtifact(a); err != nil {
			return nil, status.Errorf(codes.InvalidArgument, "bad request for artifact %q: %s", id, err)
		}
		t, err := newUploadTask(pbutil.InvocationArtifactName(s.cfg.invocationID, id), a)
		// newUploadTask can return an error if os.Stat() fails.
		if err != nil {
			// TODO(crbug.com/1124868) - once all test harnesses are fixed, return 4xx on
			// newUploadTask failures instead of dropping the artifact silently.
			logging.Warningf(ctx, "Dropping an artifact request; failed to create a new Uploadtask: %s",
				errors.Annotate(err, "artifact %q: %s", id, err).Err())
			continue
		}
		s.mu.Lock()
		if added := s.invocationArtifactIDs.Add(id); !added {
			s.mu.Unlock()
			return nil, status.Errorf(codes.AlreadyExists, "artifact %q has already been uploaded", id)
		}
		s.mu.Unlock()
		uts = append(uts, t)
	}
	s.ac.schedule(uts...)

	return &emptypb.Empty{}, nil
}

func updateArtifactContentType(a *sinkpb.Artifact) {
	if a.GetFilePath() == "" || a.GetContentType() != "" {
		return
	}

	switch path.Ext(a.GetFilePath()) {
	case ".txt":
		a.ContentType = "text/plain"
	case ".html":
		a.ContentType = "text/html"
	case ".png":
		a.ContentType = "image/png"
	}
}


text:
<TITLE>Review for Beverly Hills Cop III (1994)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Beverly Hills Cop III (1994)

reviewed by
Scott Renshaw

                            BEVERLY HILLS COP III
                       A film review by Scott Renshaw
                        Copyright 1994 Scott Renshaw

Starring:  Eddie Murphy, Judge Reinhold, Hector Elizondo, Timothy
Carhart, Theresa Randle, Bronson Pinchot.
Screenplay:  Steven E. de Souza.
Director:  John Landis.

     It's hard to believe that it's been ten years since the original
BEVERLY HILLS COP turned Eddie Murphy into the biggest star in
Hollywood, for two very different reasons.  On the one hand, it doesn't
seem like that long since I saw it in a theater for the first time.  On
the other hand, it seems like twice that long since Murphy has had a
hit.  It certainly must seem like an eternity to Murphy; he is proved
consistently unable in the last few years to recapture the COP audience
without returning to Beverly Hills.  So at something of a crossroads in
his career, he again dons the Detroit Lions jacket for BEVERLY HILLS
COP III.  And what a lifeless outing it is--slow, unfunny and lacking
even Murphy's cocky charm.

     COP III opens back in Detroit, where Axel Foley is in the process
of leading a raid on a stolen car chop shop.  The raid goes sour when
big guns turn out to be on the scene, and in the ensuing battle Axel's
boss is killed.  The killer's trail, naturally, leads back to
California, where Axel enlists the aid of old friend Billy Rosewood
(Judge Reinhold) and newcomer Det. Flint (Hector Elizondo).  Their
investigation leads to the WonderWorld amusement park, whose chief of
security Ellis DeWald (Timothy Carhart) is behind the dirty dealings.
Unfortunately, no one believes Axel except a park technician (Theresa
Randle) and WonderWorld patriarch Uncle Dave (Alan Young), leaving Axel
more or less alone to figure out what's rotten at WonderWorld.

     Give Steven E. de Souza credit for not deciding simply to rehash
BEVERLY HILLS COP.  COP III is more of a pure action film, which makes
it exactly the wrong kind of film for John Landis to direct.  Landis'
sense of pacing has always been suspect to say the least, tending
towards manic spurts interrupted by long, surrealistic comic passages,
and that package is on display here.  For no apparent reason, Landis
interrupts his establishing sequence in the chop shop to bring us a
production number featuring two corpulent gentlemen performing "Come
See About Me."  Later, in the middle of a chase, Axel stops to join a
group of costumed characters in a stage show.  COP III is filled with
decisions like these which bring the film to a grinding halt.  Bronson
Pinchot's scene-stealing Serge from COP I returns as a personal
security-device peddler in a scene which takes far too long to
introduce a single plot element.  Ditto for the scene in which we sit
through an entire park attraction, because we know it's going to show
up later.  There is no economy to the screenwriting or the direction,
and Landis has simply gotten too predictable in his shot selection.  In
one scene in a restaurant bar, I anticipated the conclusion of the
scene two minutes before it happened.

     It's also extremely unfortunate that in addition to abandoning the
COP I formula, de Souza has also decided to abandon the characters.  He
seems to have forgotten completely about Billy Rosewood's fascination
with big guns from COP II, missing a wonderful opportunity.  He also
seems to have forgotten that Axel is supposed to be smart; how else to
explain running from park security into a ride from which escape is not
extremely likely.  Perhaps to set up an action sequence.  Murphy gets
to fire a lot of bullets, but gets painfully few opportunities to show
that Axel's greatest weapon is his wits.

     Of course, it would have been difficult for any wit to come
through when Murphy sleepwalks through his performance.  Perhaps he
senses what the audience does, that a thirty-something Axel Foley isn't
nearly as interesting as a twenty-something Axel Foley.  What made COP
I click was Murphy as the streetwise loose cannon, aggravating uptight
veteran Taggart even while he was teaching him.  Now, Axel _is_ the
veteran, going about his business methodically and rarely thinking on
his feet.  There is some good action to be found in BEVERLY HILLS COP
III, particularly a rescue on a runaway park ride, and one very funny
sequence involving a multi-faceted gun.  But there is none of the
irreverent edge that made the young Murphy so appealing.  Maybe that's
what depressed me most about COP III:  considering the possibility that
we might never see that Eddie Murphy again.

     On the Renshaw scale of 0 to 10 Beverly Hills cops:  3.

--
Scott Renshaw
Stanford University
Office of the General Counsel

.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
var _ = require('underscore');

var tick = Ticker(function (){
	console.info('Finished');
});

tick.add(5);
tick.done();
tick.done();
tick.done();
tick.done();
tick.done();


text:
Tube
====

A 3D tunnelracing game for Android and PC


text:
'''
	extract top taxons for each user:
	movies
	music
	sex
	humor
	school
'''
import codecs
from collections import defaultdict, OrderedDict
import json
import glob, os

f_in = "tweets_taxonomy_clean.JSON"
f_in_user_ids = "user_IDs.dat"
IN_DIR = "../../../DATA/taxonomy_stats/"
OUT_DIR = "user_taxons/"
f_out_sent = "user_sent.tab"
f_out_taxon = "user_taxons.tab"
f_out_concepts = "user_concepts.tab"
f_out_entities = "user_entities.tab"
##################################################
# read in a map for the twitter username --> id
##################################################
def read_user_IDs():

	user_ids = defaultdict(str)

	with codecs.open(f_in_user_ids,'r', encoding='utf8') as f:
		for line in f:
			line = line.split()
			user_id = line[0]
			user =  line[1]
			user_ids[user] = user_id

	return user_ids

##################################################
# the main function
##################################################
"""
	go through taxon file and extract and save user sent
"""
def extract_usr_sentiment():

	os.chdir(IN_DIR)

	# resulting dictionary in which the counts and tfidf relevance are collected
	docSentiment_sum = defaultdict(int)
	# holds all the user ids
	user_ids = read_user_IDs()

	output_file = codecs.open(OUT_DIR+f_out_sent, 'w', encoding='utf8')

	cnt = 0
	with codecs.open(f_in,'r', encoding='utf8') as input_file:
		for line7s in input_file:
			try:
				line = json.loads(line7s)
				taxonomy_all = line["taxonomy"]
				user_name = line["_id"]
				user_id = user_ids[user_name]
				taxonomy = taxonomy_all["taxonomy"]
				docSentiment = taxonomy_all["docSentiment"]
				# the user we analyze
				user_name = line["_id"]
				user_id = user_ids[user_name]

				# procedure for extracting the taxons
				for el in taxonomy:
					try:
						if el["confident"] == "no":
							continue
					except: KeyError
					taxonomy_tree = el["label"]
					taxonomy_tree = taxonomy_tree.split("/")
					taxonomy_tree.pop(0)
					levels = len(taxonomy_tree)

					s = taxonomies_sum
					# go until the last element; on the last, we will not create a dict NONO
					for tax_class in taxonomy_tree:
						#print tax_class
						if tax_class not in s.keys():
							s[tax_class] = defaultdict(int)
							#print taxonomies_sum
							#return
						s = s[tax_class]
					#last_tax_class = taxonomy_tree[levels-1]
					#s = s[last_tax_class]

					old_score = s["size"]
					#old_cnt = s[tax_class][1]
					#old_sent = s[tax_class][2]
					new_score = old_score + float(el["score"])
					s["size"] = new_score
					# this shows that it takes as confident only those above 0.4
					if float(el["score"]) < 0.4:
						print float(el["score"])
					output_file.write(str(user_id) + '\t' + str(snt) + '\t' + str(score) +  '\n')

					cnt += 1

			except KeyError:
				#print line7s
				# we don't print since it is tested, there some 10% users for whom
				# the taxonomy was not successfuly downloaded and they would be listed here
				continue

	print "Saved sentiment for %d users " % (cnt)

###############################################################################

"""
	go through taxon file and extract and save user taxons: diversity 1
	number of top level taxons in user tweets
"""
def extract_usr_taxonomies():
	os.chdir(IN_DIR)
	# resulting dictionary in which the counts and tfidf relevance are collected
	res = defaultdict(int)
	# holds all the user ids
	user_ids = read_user_IDs()

	output_file = codecs.open(OUT_DIR+f_out_taxon, 'w', encoding='utf8')

	cnt = 0
	with codecs.open(f_in,'r', encoding='utf8') as input_file:
		for line7s in input_file:
			try:
				line = json.loads(line7s)
				taxonomy_all = line["taxonomy"]
				user_name = line["_id"]
				user_id = user_ids[user_name]
				taxonomy = taxonomy_all["taxonomy"]
				docSentiment = taxonomy_all["docSentiment"]
				# the user we analyze
				user_name = line["_id"]
				user_id = user_ids[user_name]
				res[user_id] = defaultdict(int)
				# procedure for extracting the taxons
				for el in taxonomy:
					try:
						if el["confident"] == "no":
							continue
					except: KeyError
					taxonomy_tree = el["label"]
					taxonomy_tree = taxonomy_tree.split("/")
					taxonomy_tree.pop(0)
					levels = len(taxonomy_tree)

					res[user_id][taxonomy_tree[0]] = 1

				output_file.write(str(user_id) + '\t' + str(len(res[user_id])) + '\n')

				cnt += 1

			except KeyError:
				#print line7s
				# we don't print since it is tested, there some 10% users for whom
				# the taxonomy was not successfuly downloaded and they would be listed here
				continue

	print "Taxon saved for %d users " % (cnt)
###############################################################################

"""
	go through taxon file and extract and save user concepts
"""
def extract_usr_concepts():
	os.chdir(IN_DIR)
	# resulting dictionary in which the counts and tfidf relevance are collected
	res = defaultdict(int)
	# holds all the user ids
	user_ids = read_user_IDs()

	output_file = codecs.open(OUT_DIR+f_out_concepts, 'w', encoding='utf8')

	cnt = 0
	with codecs.open(f_in,'r', encoding='utf8') as input_file:
		for line7s in input_file:
			try:
				line = json.loads(line7s)
				taxonomy_all = line["taxonomy"]
				user_name = line["_id"]
				user_id = user_ids[user_name]
				concepts = taxonomy_all["concepts"]
				docSentiment = taxonomy_all["docSentiment"]
				# the user we analyze
				user_name = line["_id"]
				user_id = user_ids[user_name]
				res[user_id] = defaultdict(int)
				# procedure for extracting the concepts

				for el in concepts:
					concept = el["text"]
					res[user_id][concept] = 1

				output_file.write(str(user_id) + '\t' + str(len(res[user_id])) + '\n')

				cnt += 1

			except KeyError:
				#print line7s
				# we don't print since it is tested, there some 10% users for whom
				# the taxonomy was not successfuly downloaded and they would be listed here
				continue

	print "Concepts saved for %d users " % (cnt)

"""
	go through taxon file and extract and save user entities
"""
def extract_usr_entities():
	os.chdir(IN_DIR)
	# resulting dictionary in which the counts and tfidf relevance are collected
	res = defaultdict(int)
	# holds all the user ids
	user_ids = read_user_IDs()

	output_file = codecs.open(OUT_DIR+f_out_entities, 'w', encoding='utf8')

	cnt = 0
	with codecs.open(f_in,'r', encoding='utf8') as input_file:
		for line7s in input_file:
			try:
				line = json.loads(line7s)
				taxonomy_all = line["taxonomy"]
				user_name = line["_id"]
				user_id = user_ids[user_name]
				entities = taxonomy_all["entities"]
				docSentiment = taxonomy_all["docSentiment"]
				# the user we analyze
				user_name = line["_id"]
				user_id = user_ids[user_name]
				res[user_id] = defaultdict(int)
				# procedure for extracting the entities
				for el in entities:
					entity = el["text"]
					res[user_id][entity] = 1

				output_file.write(str(user_id) + '\t' + str(len(res[user_id])) + '\n')

				cnt += 1

			except KeyError:
				#print line7s
				# we don't print since it is tested, there some 10% users for whom
				# the taxonomy was not successfuly downloaded and they would be listed here
				continue

	print "Concepts saved for %d users " % (cnt)

#extract_usr_taxonomies()
#extract_usr_concepts()
extract_usr_entities()


text:
import type { ReactElement } from 'react';

export function intersperse(
  items?: Array<ReactElement | string>,
  toInject?: string
): Array<ReactElement | string> {
  if (!items || !items.length) {
    return [];
  }
  if (!toInject) {
    return items;
  }

  const start = items[0];
  if (!start) {
    return [];
  }

  return items
    .slice(1)
    .reduce((result, item) => result.concat([toInject, item]), [start]);
}