text:
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using AllReady.Models;

namespace AllReady.Migrations
{
    [DbContext(typeof(AllReadyContext))]
    partial class AllReadyContextModelSnapshot : ModelSnapshot
    {
        protected override void BuildModel(ModelBuilder modelBuilder)
        {
            modelBuilder
                .HasAnnotation("ProductVersion", "1.0.2")
                .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

            modelBuilder.Entity("AllReady.Models.ApplicationUser", b =>
                {
                    b.Property<string>("Id");

                    b.Property<int>("AccessFailedCount");

                    b.Property<string>("ConcurrencyStamp")
                        .IsConcurrencyToken();

                    b.Property<string>("Email")
                        .HasAnnotation("MaxLength", 256);

                    b.Property<bool>("EmailConfirmed");

                    b.Property<string>("FirstName");

                    b.Property<string>("LastName");

                    b.Property<bool>("LockoutEnabled");

                    b.Property<DateTimeOffset?>("LockoutEnd");

                    b.Property<string>("NormalizedEmail")
                        .HasAnnotation("MaxLength", 256);

                    b.Property<string>("NormalizedUserName")
                        .HasAnnotation("MaxLength", 256);

                    b.Property<int?>("OrganizationId");

                    b.Property<string>("PasswordHash");

                    b.Property<string>("PendingNewEmail");

                    b.Property<string>("PhoneNumber");

                    b.Property<bool>("PhoneNumberConfirmed");

                    b.Property<string>("SecurityStamp");

                    b.Property<string>("TimeZoneId")
                        .IsRequired();

                    b.Property<bool>("TwoFactorEnabled");

                    b.Property<string>("UserName")
                        .HasAnnotation("MaxLength", 256);

                    b.HasKey("Id");

                    b.HasIndex("NormalizedEmail")
                        .HasName("EmailIndex");

                    b.HasIndex("NormalizedUserName")
                        .IsUnique()
                        .HasName("UserNameIndex");

                    b.HasIndex("OrganizationId");

                    b.ToTable("ApplicationUser");
                });

            modelBuilder.Entity("AllReady.Models.Campaign", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("Description");

                    b.Property<DateTimeOffset>("EndDateTime");

                    b.Property<string>("ExternalUrl");

                    b.Property<string>("ExternalUrlText");

                    b.Property<bool>("Featured");

                    b.Property<string>("FullDescription");

                    b.Property<string>("Headline")
                        .HasAnnotation("MaxLength", 150);

                    b.Property<string>("ImageUrl");

                    b.Property<int?>("LocationId");

                    b.Property<bool>("Locked");

                    b.Property<int>("ManagingOrganizationId");

                    b.Property<string>("Name")
                        .IsRequired();

                    b.Property<string>("OrganizerId");

                    b.Property<bool>("Published");

                    b.Property<DateTimeOffset>("StartDateTime");

                    b.Property<string>("TimeZoneId")
                        .IsRequired();

                    b.HasKey("Id");

                    b.HasIndex("LocationId");

                    b.HasIndex("ManagingOrganizationId");

                    b.HasIndex("OrganizerId");

                    b.ToTable("Campaign");
                });

            modelBuilder.Entity("AllReady.Models.CampaignContact", b =>
                {
                    b.Property<int>("CampaignId");

                    b.Property<int>("ContactId");

                    b.Property<int>("ContactType");

                    b.Property<int?>("ContactId1");

                    b.HasKey("CampaignId", "ContactId", "ContactType");

                    b.HasIndex("CampaignId");

                    b.HasIndex("ContactId");

                    b.HasIndex("ContactId1");

                    b.ToTable("CampaignContact");
                });

            modelBuilder.Entity("AllReady.Models.CampaignGoal", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<int>("CampaignId");

                    b.Property<int>("CurrentGoalLevel");

                    b.Property<bool>("Display");

                    b.Property<int>("GoalType");

                    b.Property<int>("NumericGoal");

                    b.Property<string>("TextualGoal");

                    b.HasKey("Id");

                    b.HasIndex("CampaignId");

                    b.ToTable("CampaignGoal");
                });

            modelBuilder.Entity("AllReady.Models.CampaignSponsors", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<int?>("CampaignId");

                    b.Property<int?>("OrganizationId");

                    b.HasKey("Id");

                    b.HasIndex("CampaignId");

                    b.HasIndex("OrganizationId");

                    b.ToTable("CampaignSponsors");
                });

            modelBuilder.Entity("AllReady.Models.ClosestLocation", b =>
                {
                    b.Property<string>("PostalCode");

                    b.Property<string>("City");

                    b.Property<double>("Distance");

                    b.Property<string>("State");

                    b.HasKey("PostalCode");

                    b.ToTable("ClosestLocation");
                });

            modelBuilder.Entity("AllReady.Models.Contact", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("Email");

                    b.Property<string>("FirstName");

                    b.Property<string>("LastName");

                    b.Property<string>("PhoneNumber");

                    b.HasKey("Id");

                    b.ToTable("Contact");
                });

            modelBuilder.Entity("AllReady.Models.Event", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<int>("CampaignId");

                    b.Property<string>("Description");

                    b.Property<DateTimeOffset>("EndDateTime");

                    b.Property<int>("EventType");

                    b.Property<string>("Headline")
                        .HasAnnotation("MaxLength", 150);

                    b.Property<string>("ImageUrl");

                    b.Property<bool>("IsAllowWaitList");

                    b.Property<bool>("IsLimitVolunteers");

                    b.Property<int?>("LocationId");

                    b.Property<string>("Name")
                        .IsRequired();

                    b.Property<string>("OrganizerId");

                    b.Property<DateTimeOffset>("StartDateTime");

                    b.Property<string>("TimeZoneId")
                        .IsRequired();

                    b.HasKey("Id");

                    b.HasIndex("CampaignId");

                    b.HasIndex("LocationId");

                    b.HasIndex("OrganizerId");

                    b.ToTable("Event");
                });

            modelBuilder.Entity("AllReady.Models.EventSkill", b =>
                {
                    b.Property<int>("EventId");

                    b.Property<int>("SkillId");

                    b.HasKey("EventId", "SkillId");

                    b.HasIndex("EventId");

                    b.HasIndex("SkillId");

                    b.ToTable("EventSkill");
                });

            modelBuilder.Entity("AllReady.Models.Itinerary", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<DateTime>("Date");

                    b.Property<double>("EndLatitude");

                    b.Property<int?>("EndLocationId");

                    b.Property<double>("EndLongitude");

                    b.Property<int>("EventId");

                    b.Property<string>("Name");

                    b.Property<double>("StartLatitude");

                    b.Property<int?>("StartLocationId");

                    b.Property<double>("StartLongitude");

                    b.Property<bool>("UseStartAddressAsEndAddress");

                    b.HasKey("Id");

                    b.HasIndex("EndLocationId");

                    b.HasIndex("EventId");

                    b.HasIndex("StartLocationId");

                    b.ToTable("Itinerary");
                });

            modelBuilder.Entity("AllReady.Models.ItineraryRequest", b =>
                {
                    b.Property<int>("ItineraryId");

                    b.Property<Guid>("RequestId");

                    b.Property<DateTime>("DateAssigned");

                    b.Property<int>("OrderIndex");

                    b.HasKey("ItineraryId", "RequestId");

                    b.HasIndex("ItineraryId");

                    b.HasIndex("RequestId")
                        .IsUnique();

                    b.ToTable("ItineraryRequest");
                });

            modelBuilder.Entity("AllReady.Models.Location", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("Address1");

                    b.Property<string>("Address2");

                    b.Property<string>("City");

                    b.Property<string>("Country");

                    b.Property<string>("Name");

                    b.Property<string>("PhoneNumber");

                    b.Property<string>("PostalCode");

                    b.Property<string>("State");

                    b.HasKey("Id");

                    b.ToTable("Location");
                });

            modelBuilder.Entity("AllReady.Models.Organization", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("DescriptionHtml");

                    b.Property<int?>("LocationId");

                    b.Property<string>("LogoUrl");

                    b.Property<string>("Name")
                        .IsRequired();

                    b.Property<string>("PrivacyPolicy");

                    b.Property<string>("PrivacyPolicyUrl");

                    b.Property<string>("Summary")
                        .HasAnnotation("MaxLength", 250);

                    b.Property<string>("WebUrl");

                    b.HasKey("Id");

                    b.HasIndex("LocationId");

                    b.ToTable("Organization");
                });

            modelBuilder.Entity("AllReady.Models.OrganizationContact", b =>
                {
                    b.Property<int>("OrganizationId");

                    b.Property<int>("ContactId");

                    b.Property<int>("ContactType");

                    b.Property<int?>("ContactId1");

                    b.HasKey("OrganizationId", "ContactId", "ContactType");

                    b.HasIndex("ContactId");

                    b.HasIndex("ContactId1");

                    b.HasIndex("OrganizationId");

                    b.ToTable("OrganizationContact");
                });

            modelBuilder.Entity("AllReady.Models.PostalCodeGeo", b =>
                {
                    b.Property<string>("PostalCode");

                    b.Property<string>("City");

                    b.Property<string>("State");

                    b.HasKey("PostalCode");

                    b.ToTable("PostalCodeGeo");
                });

            modelBuilder.Entity("AllReady.Models.PostalCodeGeoCoordinate", b =>
                {
                    b.Property<double>("Latitude");

                    b.Property<double>("Longitude");

                    b.HasKey("Latitude", "Longitude");

                    b.ToTable("PostalCodeGeoCoordinate");
                });

            modelBuilder.Entity("AllReady.Models.Request", b =>
                {
                    b.Property<Guid>("RequestId")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("Address");

                    b.Property<string>("City");

                    b.Property<DateTime>("DateAdded");

                    b.Property<string>("Email");

                    b.Property<int?>("EventId");

                    b.Property<int?>("ItineraryId");

                    b.Property<double>("Latitude");

                    b.Property<double>("Longitude");

                    b.Property<string>("Name");

                    b.Property<int?>("OrganizationId");

                    b.Property<string>("Phone");

                    b.Property<string>("PostalCode");

                    b.Property<string>("ProviderData");

                    b.Property<string>("ProviderRequestId");

                    b.Property<int>("Source");

                    b.Property<string>("State");

                    b.Property<int>("Status");

                    b.HasKey("RequestId");

                    b.HasIndex("EventId");

                    b.HasIndex("OrganizationId");

                    b.ToTable("Request");
                });

            modelBuilder.Entity("AllReady.Models.Resource", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("CategoryTag");

                    b.Property<string>("Description");

                    b.Property<string>("MediaUrl");

                    b.Property<string>("Name");

                    b.Property<DateTime>("PublishDateBegin");

                    b.Property<DateTime>("PublishDateEnd");

                    b.Property<string>("ResourceUrl");

                    b.HasKey("Id");

                    b.ToTable("Resource");
                });

            modelBuilder.Entity("AllReady.Models.Skill", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("Description");

                    b.Property<string>("Name")
                        .IsRequired();

                    b.Property<int?>("OwningOrganizationId");

                    b.Property<int?>("ParentSkillId");

                    b.HasKey("Id");

                    b.HasIndex("OwningOrganizationId");

                    b.HasIndex("ParentSkillId");

                    b.ToTable("Skill");
                });

            modelBuilder.Entity("AllReady.Models.UserSkill", b =>
                {
                    b.Property<string>("UserId");

                    b.Property<int>("SkillId");

                    b.HasKey("UserId", "SkillId");

                    b.HasIndex("SkillId");

                    b.HasIndex("UserId");

                    b.ToTable("UserSkill");
                });

            modelBuilder.Entity("AllReady.Models.VolunteerTask", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("Description");

                    b.Property<DateTimeOffset>("EndDateTime");

                    b.Property<int>("EventId");

                    b.Property<bool>("IsAllowWaitList");

                    b.Property<bool>("IsLimitVolunteers");

                    b.Property<string>("Name")
                        .IsRequired();

                    b.Property<int>("NumberOfVolunteersRequired");

                    b.Property<int?>("OrganizationId");

                    b.Property<DateTimeOffset>("StartDateTime");

                    b.HasKey("Id");

                    b.HasIndex("EventId");

                    b.HasIndex("OrganizationId");

                    b.ToTable("VolunteerTask");
                });

            modelBuilder.Entity("AllReady.Models.VolunteerTaskSignup", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("AdditionalInfo");

                    b.Property<bool>("IsTeamLead");

                    b.Property<int?>("ItineraryId");

                    b.Property<int>("Status");

                    b.Property<DateTime>("StatusDateTimeUtc");

                    b.Property<string>("StatusDescription");

                    b.Property<string>("UserId");

                    b.Property<int>("VolunteerTaskId");

                    b.HasKey("Id");

                    b.HasIndex("ItineraryId");

                    b.HasIndex("UserId");

                    b.HasIndex("VolunteerTaskId");

                    b.ToTable("VolunteerTaskSignup");
                });

            modelBuilder.Entity("AllReady.Models.VolunteerTaskSkill", b =>
                {
                    b.Property<int>("VolunteerTaskId");

                    b.Property<int>("SkillId");

                    b.HasKey("VolunteerTaskId", "SkillId");

                    b.HasIndex("SkillId");

                    b.HasIndex("VolunteerTaskId");

                    b.ToTable("VolunteerTaskSkill");
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b =>
                {
                    b.Property<string>("Id");

                    b.Property<string>("ConcurrencyStamp")
                        .IsConcurrencyToken();

                    b.Property<string>("Name")
                        .HasAnnotation("MaxLength", 256);

                    b.Property<string>("NormalizedName")
                        .HasAnnotation("MaxLength", 256);

                    b.HasKey("Id");

                    b.HasIndex("NormalizedName")
                        .HasName("RoleNameIndex");

                    b.ToTable("IdentityRole");
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("ClaimType");

                    b.Property<string>("ClaimValue");

                    b.Property<string>("RoleId")
                        .IsRequired();

                    b.HasKey("Id");

                    b.HasIndex("RoleId");

                    b.ToTable("IdentityRoleClaim<string>");
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("ClaimType");

                    b.Property<string>("ClaimValue");

                    b.Property<string>("UserId")
                        .IsRequired();

                    b.HasKey("Id");

                    b.HasIndex("UserId");

                    b.ToTable("IdentityUserClaim<string>");
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
                {
                    b.Property<string>("LoginProvider");

                    b.Property<string>("ProviderKey");

                    b.Property<string>("ProviderDisplayName");

                    b.Property<string>("UserId")
                        .IsRequired();

                    b.HasKey("LoginProvider", "ProviderKey");

                    b.HasIndex("UserId");

                    b.ToTable("IdentityUserLogin<string>");
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
                {
                    b.Property<string>("UserId");

                    b.Property<string>("RoleId");

                    b.HasKey("UserId", "RoleId");

                    b.HasIndex("RoleId");

                    b.HasIndex("UserId");

                    b.ToTable("IdentityUserRole<string>");
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b =>
                {
                    b.Property<string>("UserId");

                    b.Property<string>("LoginProvider");

                    b.Property<string>("Name");

                    b.Property<string>("Value");

                    b.HasKey("UserId", "LoginProvider", "Name");

                    b.ToTable("IdentityUserToken<string>");
                });

            modelBuilder.Entity("AllReady.Models.ApplicationUser", b =>
                {
                    b.HasOne("AllReady.Models.Organization")
                        .WithMany("Users")
                        .HasForeignKey("OrganizationId");
                });

            modelBuilder.Entity("AllReady.Models.Campaign", b =>
                {
                    b.HasOne("AllReady.Models.Location", "Location")
                        .WithMany()
                        .HasForeignKey("LocationId");

                    b.HasOne("AllReady.Models.Organization", "ManagingOrganization")
                        .WithMany("Campaigns")
                        .HasForeignKey("ManagingOrganizationId")
                        .OnDelete(DeleteBehavior.Cascade);

                    b.HasOne("AllReady.Models.ApplicationUser", "Organizer")
                        .WithMany()
                        .HasForeignKey("OrganizerId");
                });

            modelBuilder.Entity("AllReady.Models.CampaignContact", b =>
                {
                    b.HasOne("AllReady.Models.Campaign", "Campaign")
                        .WithMany("CampaignContacts")
                        .HasForeignKey("CampaignId")
                        .OnDelete(DeleteBehavior.Cascade);

                    b.HasOne("AllReady.Models.Contact", "Contact")
                        .WithMany()
                        .HasForeignKey("ContactId")
                        .OnDelete(DeleteBehavior.Cascade);

                    b.HasOne("AllReady.Models.Contact")
                        .WithMany("CampaignContacts")
                        .HasForeignKey("ContactId1");
                });

            modelBuilder.Entity("AllReady.Models.CampaignGoal", b =>
                {
                    b.HasOne("AllReady.Models.Campaign", "Campaign")
                        .WithMany("CampaignGoals")
                        .HasForeignKey("CampaignId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("AllReady.Models.CampaignSponsors", b =>
                {
                    b.HasOne("AllReady.Models.Campaign", "Campaign")
                        .WithMany("ParticipatingOrganizations")
                        .HasForeignKey("CampaignId");

                    b.HasOne("AllReady.Models.Organization", "Organization")
                        .WithMany()
                        .HasForeignKey("OrganizationId");
                });

            modelBuilder.Entity("AllReady.Models.Event", b =>
                {
                    b.HasOne("AllReady.Models.Campaign", "Campaign")
                        .WithMany("Events")
                        .HasForeignKey("CampaignId")
                        .OnDelete(DeleteBehavior.Cascade);

                    b.HasOne("AllReady.Models.Location", "Location")
                        .WithMany()
                        .HasForeignKey("LocationId");

                    b.HasOne("AllReady.Models.ApplicationUser", "Organizer")
                        .WithMany()
                        .HasForeignKey("OrganizerId");
                });

            modelBuilder.Entity("AllReady.Models.EventSkill", b =>
                {
                    b.HasOne("AllReady.Models.Event", "Event")
                        .WithMany("RequiredSkills")
                        .HasForeignKey("EventId")
                        .OnDelete(DeleteBehavior.Cascade);

                    b.HasOne("AllReady.Models.Skill", "Skill")
                        .WithMany()
                        .HasForeignKey("SkillId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("AllReady.Models.Itinerary", b =>
                {
                    b.HasOne("AllReady.Models.Location", "EndLocation")
                        .WithMany()
                        .HasForeignKey("EndLocationId");

                    b.HasOne("AllReady.Models.Event", "Event")
                        .WithMany("Itineraries")
                        .HasForeignKey("EventId")
                        .OnDelete(DeleteBehavior.Cascade);

                    b.HasOne("AllReady.Models.Location", "StartLocation")
                        .WithMany()
                        .HasForeignKey("StartLocationId");
                });

            modelBuilder.Entity("AllReady.Models.ItineraryRequest", b =>
                {
                    b.HasOne("AllReady.Models.Itinerary", "Itinerary")
                        .WithMany("Requests")
                        .HasForeignKey("ItineraryId")
                        .OnDelete(DeleteBehavior.Cascade);

                    b.HasOne("AllReady.Models.Request", "Request")
                        .WithOne("Itinerary")
                        .HasForeignKey("AllReady.Models.ItineraryRequest", "RequestId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("AllReady.Models.Organization", b =>
                {
                    b.HasOne("AllReady.Models.Location", "Location")
                        .WithMany()
                        .HasForeignKey("LocationId");
                });

            modelBuilder.Entity("AllReady.Models.OrganizationContact", b =>
                {
                    b.HasOne("AllReady.Models.Contact", "Contact")
                        .WithMany()
                        .HasForeignKey("ContactId")
                        .OnDelete(DeleteBehavior.Cascade);

                    b.HasOne("AllReady.Models.Contact")
                        .WithMany("OrganizationContacts")
                        .HasForeignKey("ContactId1");

                    b.HasOne("AllReady.Models.Organization", "Organization")
                        .WithMany("OrganizationContacts")
                        .HasForeignKey("OrganizationId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("AllReady.Models.Request", b =>
                {
                    b.HasOne("AllReady.Models.Event", "Event")
                        .WithMany("Requests")
                        .HasForeignKey("EventId")
                        .OnDelete(DeleteBehavior.SetNull);

                    b.HasOne("AllReady.Models.Organization", "Organization")
                        .WithMany("Requests")
                        .HasForeignKey("OrganizationId");
                });

            modelBuilder.Entity("AllReady.Models.Skill", b =>
                {
                    b.HasOne("AllReady.Models.Organization", "OwningOrganization")
                        .WithMany()
                        .HasForeignKey("OwningOrganizationId");

                    b.HasOne("AllReady.Models.Skill", "ParentSkill")
                        .WithMany("ChildSkills")
                        .HasForeignKey("ParentSkillId");
                });

            modelBuilder.Entity("AllReady.Models.UserSkill", b =>
                {
                    b.HasOne("AllReady.Models.Skill", "Skill")
                        .WithMany()
                        .HasForeignKey("SkillId")
                        .OnDelete(DeleteBehavior.Cascade);

                    b.HasOne("AllReady.Models.ApplicationUser", "User")
                        .WithMany("AssociatedSkills")
                        .HasForeignKey("UserId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("AllReady.Models.VolunteerTask", b =>
                {
                    b.HasOne("AllReady.Models.Event", "Event")
                        .WithMany("VolunteerTasks")
                        .HasForeignKey("EventId")
                        .OnDelete(DeleteBehavior.Cascade);

                    b.HasOne("AllReady.Models.Organization", "Organization")
                        .WithMany()
                        .HasForeignKey("OrganizationId");
                });

            modelBuilder.Entity("AllReady.Models.VolunteerTaskSignup", b =>
                {
                    b.HasOne("AllReady.Models.Itinerary", "Itinerary")
                        .WithMany("TeamMembers")
                        .HasForeignKey("ItineraryId");

                    b.HasOne("AllReady.Models.ApplicationUser", "User")
                        .WithMany()
                        .HasForeignKey("UserId");

                    b.HasOne("AllReady.Models.VolunteerTask", "VolunteerTask")
                        .WithMany("AssignedVolunteers")
                        .HasForeignKey("VolunteerTaskId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("AllReady.Models.VolunteerTaskSkill", b =>
                {
                    b.HasOne("AllReady.Models.Skill", "Skill")
                        .WithMany()
                        .HasForeignKey("SkillId")
                        .OnDelete(DeleteBehavior.Cascade);

                    b.HasOne("AllReady.Models.VolunteerTask", "VolunteerTask")
                        .WithMany("RequiredSkills")
                        .HasForeignKey("VolunteerTaskId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
                {
                    b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
                        .WithMany("Claims")
                        .HasForeignKey("RoleId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
                {
                    b.HasOne("AllReady.Models.ApplicationUser")
                        .WithMany("Claims")
                        .HasForeignKey("UserId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
                {
                    b.HasOne("AllReady.Models.ApplicationUser")
                        .WithMany("Logins")
                        .HasForeignKey("UserId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
                {
                    b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
                        .WithMany("Users")
                        .HasForeignKey("RoleId")
                        .OnDelete(DeleteBehavior.Cascade);

                    b.HasOne("AllReady.Models.ApplicationUser")
                        .WithMany("Roles")
                        .HasForeignKey("UserId")
                        .OnDelete(DeleteBehavior.Cascade);
                });
        }
    }
}


text:
define([
  'jquery',
  'backbone'
], function($, Backbone) {
  'use strict';

  var AppRouter = Backbone.Router.extend({

    routes: {
      '': 'index'
    },

    initialize: function() {
      console.log('Router Initialised!');
    },

    index: function() {
      console.log('Index function called!');
    },
  });

  return AppRouter;
});

redpajama_set_name: RedPajamaGithub


text:
package com.skubit.iab.provider.key;

import java.util.Date;

import android.database.Cursor;

import com.skubit.iab.provider.base.AbstractCursor;

/**
 * Cursor wrapper for the {@code key} table.
 */
public class KeyCursor extends AbstractCursor implements KeyModel {
    public KeyCursor(Cursor cursor) {
        super(cursor);
    }

    /**
     * Primary key.
     */
    public long getId() {
        Long res = getLongOrNull(KeyColumns._ID);
        if (res == null)
            throw new NullPointerException("The value of '_id' in the database was null, which is not allowed according to the model definition");
        return res;
    }

    /**
     * Get the {@code nickname} value.
     * Can be {@code null}.
     */
    public String getNickname() {
        String res = getStringOrNull(KeyColumns.NICKNAME);
        return res;
    }

    /**
     * Get the {@code pub} value.
     * Can be {@code null}.
     */
    public byte[] getPub() {
        byte[] res = getBlobOrNull(KeyColumns.PUB);
        return res;
    }

    /**
     * Get the {@code priv} value.
     * Can be {@code null}.
     */
    public byte[] getPriv() {
        byte[] res = getBlobOrNull(KeyColumns.PRIV);
        return res;
    }

    /**
     * Get the {@code address} value.
     * Can be {@code null}.
     */
    public String getAddress() {
        String res = getStringOrNull(KeyColumns.ADDRESS);
        return res;
    }
}


text:
title: Does VUX support weex
---

# Does VUX support weex

No, and not plan to support it.


text:
'use strict';

var Member = require('../membership/member');
var _ = require('underscore');

function StateTransitions(options) {
    this.ringpop = options.ringpop;

    var p = _.defaults({}, options.periods, StateTransitions.Defaults);
    this.suspectTimeout = p.suspect;
    this.faultyTimeout = p.faulty;
    this.tombstoneTimeout = p.tombstone;

    this.logger = this.ringpop.loggerFactory.getLogger('statetransitions');

    this.enabled = true;
    this.timers = {};
}

StateTransitions.prototype.enable = function enable() {
    if (this.enabled) {
        this.logger.error('ringpop cannot enable state transitions because it was never disabled', {
            local: this.ringpop.whoami()
        });
        return;
    }

    this.enabled = true;

    this.logger.debug('enabled state transitions protocol', {
        local: this.ringpop.whoami()
    });
};

StateTransitions.prototype.handleUpdate = function handleUpdate(update) {
    switch (update.status) {
        case Member.Status.alive:
        case Member.Status.leave:
            this.cancel(update);
            break;
        case Member.Status.suspect:
            this.scheduleSuspectToFaulty(update);
            break;
        case Member.Status.faulty:
            this.scheduleFaultyToTombstone(update);
            break;
        case Member.Status.tombstone:
            this.scheduleTombstoneToEvict(update);
            break;
    }
};

StateTransitions.prototype.scheduleSuspectToFaulty = function scheduleSuspectToFaulty(member) {
    var self = this;
    this.schedule(member, Member.Status.suspect, this.suspectTimeout, function suspectToFaulty() {
        self.ringpop.membership.makeFaulty(member.address,
            member.incarnationNumber);
    });
};

StateTransitions.prototype.scheduleFaultyToTombstone = function scheduleFaultyToTombstone(member) {
    var self = this;
    this.schedule(member, Member.Status.faulty, this.faultyTimeout, function faultyToTombstone() {
        self.ringpop.membership.makeTombstone(member.address,
            member.incarnationNumber);
    });
};

StateTransitions.prototype.scheduleTombstoneToEvict = function scheduleTombstoneToEvict(member) {
    var self = this;
    this.schedule(member, Member.Status.tombstone, this.tombstoneTimeout, function tombstoneToEvict() {
        self.ringpop.membership.evict(member.address);
    });
};

StateTransitions.prototype.schedule = function schedule(member, state, timeout, transition) {
    if (!this.enabled) {
        this.logger.error('cannot start a state transition because state transitions has not been enabled', {
            local: this.ringpop.whoami()
        });
        return;
    }

    if (member.address === this.ringpop.whoami()) {
        this.logger.debug('cannot start a state transition for the local member', {
            local: this.ringpop.whoami(),
            member: member.address
        });
        return;
    }

    var timer = this.timers[member.address];
    if (timer) {
        if (timer.state === state) {
            this.logger.warn('redundant call to schedule a state transition for member, ignored', {
                local: this.ringpop.whoami(),
                member: member.address,
                state: state,
            });
            return;
        }
        // cancel the previously scheduled transition for the member
        this.cancel(member);
    }

    this.timers[member.address] = {
        timer: setTimeout(transition, timeout),
        state: state
    };

    this.logger.debug('started state transition for member', {
        local: this.ringpop.whoami(),
        member: member.address,
        state: state
    });
};

StateTransitions.prototype.cancel = function cancel(member) {
    var timer = this.timers[member.address];
    if (!timer) {
        this.logger.warn('no state transition for member', {
            local: this.ringpop.whoami(),
            member: member.address
        });
        return;
    }
    clearTimeout(timer.timer);
    delete this.timers[member.address];
    this.logger.debug('cancelled state transition for member', {
        local: this.ringpop.whoami(),
        member: member.address,
        state: timer.state
    });
};

StateTransitions.prototype.disable = function disable() {
    this.enabled = false;

    var timerKeys = Object.keys(this.timers);

    if (timerKeys.length === 0) {
        this.logger.debug('no state transitions to cancel', {
            local: this.ringpop.whoami()
        });
        return;
    }

    timerKeys.forEach(function clearTimers(timerKey) {
        clearTimeout(this.timers[timerKey].timer);
        delete this.timers[timerKey];
    }, this);

    this.logger.debug('cancelled all state transitions', {
        local: this.ringpop.whoami(),
        numTimers: timerKeys.length
    });
};

StateTransitions.Defaults = {
    suspect: 5 * 1000, // 5s
    faulty: 24 * 60 * 60 * 1000, // 24h
    tombstone: 60 * 1000, // 60s
};

module.exports = StateTransitions;


text:
package edu.missouristate.mote.propertygrid;

import java.awt.Component;
import java.awt.Font;
import java.text.DecimalFormat;
import java.util.List;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.JFormattedTextField;
import javax.swing.border.EmptyBorder;
import edu.missouristate.mote.Constants;

/**
 * Renderer for cells in a PropertyTable.
 */
public final class PropertyCellRenderer extends DefaultTableCellRenderer {

    // *************************************************************************
    // FIELDS
    // *************************************************************************

    /** Table row data. */
    private final transient List<PropertyTableRow> tableRows;

    /** Text field backing this cell. */
    private final transient JFormattedTextField textField;

    // *************************************************************************
    // CONSTRUCTORS
    // *************************************************************************

    /**
     * Initialize a new instance of a PropertyCellRenderer.
     *
     * @param rows data for each row in the table
     */
    public PropertyCellRenderer(final List<PropertyTableRow> rows) {
        super();
        tableRows = rows;
        textField = new JFormattedTextField();
        textField.setBorder(new EmptyBorder(Constants.CELL_INSETS));
    }

    // *************************************************************************
    // PRIVATE METHODS
    // *************************************************************************

    /**
     * Return a formatted "value" given the cell's position in the grid.
     *
     * @param value cell value
     * @param column column number
     * @param isCategory true if the row is a category row
     * @return formatted value
     */
    private String formatValue(final Object value, final int column,
            final boolean isCategory) {
        String result;
        if (value == null) {
            result = "";
        } else if (isCategory || column != 1) {
            result = value.toString();
        } else {
            try {
                final double newDouble = Double.parseDouble(value.toString());
                final DecimalFormat format = new DecimalFormat(
                        Constants.DECIMAL_FORMAT);
                result = format.format(newDouble);
            } catch (ClassCastException | NumberFormatException e) {
                result = value.toString();
            }
        }
        return result;
    }

    // *************************************************************************
    // PUBLIC METHODS
    // *************************************************************************

    /**
     * Return the default table cell renderer.
     *
     * @param table the JTable
     * @param value the value to assign to the cell at [row, column]
     * @param isSelected true if cell is selected
     * @param hasFocus true if cell has focus
     * @param row the row of the cell to render
     * @param column the column of the cell to render
     * @return the default table cell renderer
     */
    @Override
    public Component getTableCellRendererComponent(final JTable table,
            final Object value, final boolean isSelected,
            final boolean hasFocus, final int row, final int column) {
        final PropertyTableRow tableRow = tableRows.get(row);
        textField.setText(formatValue(value, column, tableRow.isCategory()));

        if (tableRow.isCategory()) {
            // Category rows
            textField.setFont(textField.getFont().deriveFont(Font.BOLD));
            textField.setBackground(Constants.CATEGORY_BG_COLOR);
            textField.setForeground(Constants.CATEGORY_FG_COLOR);
        } else if (column == 0) {
            // Name column
            textField.setFont(textField.getFont().deriveFont(Font.BOLD));
            textField.setBackground(Constants.NAME_BG_COLOR);
            textField.setForeground(Constants.NAME_FG_COLOR);
        } else if (isSelected) {
            // Selected cell
            textField.setFont(textField.getFont().deriveFont(Font.BOLD));
            textField.setBackground(Constants.SELECT_BG_COLOR);
            textField.setForeground(Constants.SELECT_FG_COLOR);
        } else {
            // Value column
            textField.setFont(textField.getFont().deriveFont(Font.PLAIN));
            textField.setBackground(Constants.VALUE_BG_COLOR);
            textField.setForeground(Constants.VALUE_FG_COLOR);
        }
        return textField;
    }
}


text:
To use the Cloud Storage Android SDK with Kotlin Extensions, add the following
to your app's `build.gradle` file:

```groovy
// See maven.google.com for the latest versions
// This library transitively includes the firebase-storage library
implementation 'com.google.firebase:firebase-storage-ktx:$VERSION'
```

## Features

### Get an instance of FirebaseStorage

**Kotlin**
```kotlin
val storage = FirebaseStorage.getInstance()
val anotherStorage = FirebaseStorage.getInstance(FirebaseApp.getInstance("myApp"))
```

**Kotlin + KTX**
```kotlin
val storage = Firebase.storage
val anotherStorage = Firebase.storage(Firebase.app("myApp"))
```

### Get the FirebaseStorage for a custom storage bucket url

**Kotlin**
```kotlin
val storage = FirebaseStorage.getInstance("gs://my-custom-bucket")
val anotherStorage = FirebaseStorage.getInstance(FirebaseApp.getInstance("myApp"), "gs://my-custom-bucket")
```

**Kotlin + KTX**
```kotlin
val storage = Firebase.storage("gs://my-custom-bucket")
val anotherStorage = Firebase.storage(Firebase.app("myApp"), "gs://my-custom-bucket")
```

### Create file metadata

**Kotlin**
```kotlin
val metadata = StorageMetadata.Builder()
        .setContentType("image/jpg")
        .setContentDisposition("attachment")
        .setCustomMetadata("location", "Maputo, MOZ")
        .build()
```

**Kotlin + KTX**
```kotlin
val metadata = storageMetadata {
    contentType = "image/jpg"
    contentDisposition = "attachment"
    setCustomMetadata("location", "Maputo, MOZ")
}
```


text:
/*
 * Do not modify this file. This file is generated from the iot-data-2015-05-28.normal.json service model.
 */

using System;
using System.IO;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;

using Amazon.IotData;
using Amazon.IotData.Model;
using Amazon.IotData.Model.Internal.MarshallTransformations;
using Amazon.Runtime.Internal.Transform;
using Amazon.Util;
using ServiceClientGenerator;

using AWSSDK_DotNet35.UnitTests.TestTools;

namespace AWSSDK_DotNet35.UnitTests.Marshalling
{
    [TestClass]
    public partial class IotDataMarshallingTests
    {
        static readonly ServiceModel service_model = Utils.LoadServiceModel("iot-data-2015-05-28.normal.json", "");

        [TestMethod]
        [TestCategory("UnitTest")]
        [TestCategory("Rest_Json")]
        [TestCategory("IotData")]
        public void DeleteThingShadowMarshallTest()
        {
            var operation = service_model.FindOperation("DeleteThingShadow");

            var request = InstantiateClassGenerator.Execute<DeleteThingShadowRequest>();
            var marshaller = new DeleteThingShadowRequestMarshaller();

            var internalRequest = marshaller.Marshall(request);
            RequestValidator.Validate("DeleteThingShadow", request, internalRequest, service_model);

            var webResponse = new WebResponseData
            {
                Headers = {
                    {"x-amzn-RequestId", Guid.NewGuid().ToString()},
                    {"x-amz-crc32","0"}
                }
            };

            var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
            webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
            var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
            ResponseUnmarshaller unmarshaller = DeleteThingShadowResponseUnmarshaller.Instance;
            var response = unmarshaller.Unmarshall(context)
                as DeleteThingShadowResponse;
            InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
        }

        [TestMethod]
        [TestCategory("UnitTest")]
        [TestCategory("Rest_Json")]
        [TestCategory("IotData")]
        public void GetThingShadowMarshallTest()
        {
            var operation = service_model.FindOperation("GetThingShadow");

            var request = InstantiateClassGenerator.Execute<GetThingShadowRequest>();
            var marshaller = new GetThingShadowRequestMarshaller();

            var internalRequest = marshaller.Marshall(request);
            RequestValidator.Validate("GetThingShadow", request, internalRequest, service_model);

            var webResponse = new WebResponseData
            {
                Headers = {
                    {"x-amzn-RequestId", Guid.NewGuid().ToString()},
                    {"x-amz-crc32","0"}
                }
            };

            var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
            webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
            var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
            ResponseUnmarshaller unmarshaller = GetThingShadowResponseUnmarshaller.Instance;
            var response = unmarshaller.Unmarshall(context)
                as GetThingShadowResponse;
            InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
        }

        [TestMethod]
        [TestCategory("UnitTest")]
        [TestCategory("Rest_Json")]
        [TestCategory("IotData")]
        public void PublishMarshallTest()
        {
            var operation = service_model.FindOperation("Publish");

            var request = InstantiateClassGenerator.Execute<PublishRequest>();
            var marshaller = new PublishRequestMarshaller();

            var internalRequest = marshaller.Marshall(request);
            RequestValidator.Validate("Publish", request, internalRequest, service_model);

        }

        [TestMethod]
        [TestCategory("UnitTest")]
        [TestCategory("Rest_Json")]
        [TestCategory("IotData")]
        public void UpdateThingShadowMarshallTest()
        {
            var operation = service_model.FindOperation("UpdateThingShadow");

            var request = InstantiateClassGenerator.Execute<UpdateThingShadowRequest>();
            var marshaller = new UpdateThingShadowRequestMarshaller();

            var internalRequest = marshaller.Marshall(request);
            RequestValidator.Validate("UpdateThingShadow", request, internalRequest, service_model);

            var webResponse = new WebResponseData
            {
                Headers = {
                    {"x-amzn-RequestId", Guid.NewGuid().ToString()},
                    {"x-amz-crc32","0"}
                }
            };

            var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
            webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
            var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
            ResponseUnmarshaller unmarshaller = UpdateThingShadowResponseUnmarshaller.Instance;
            var response = unmarshaller.Unmarshall(context)
                as UpdateThingShadowResponse;
            InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
        }

            }
}


text:
// Copyright (c) Dapplo and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Dapplo.Windows.Shell32.Enums;

/// <summary>
/// A value that specifies an edge of the screen.
/// </summary>
public enum AppBarEdges : uint
{
    /// <summary>
    /// Left edge.
    /// </summary>
    Left = 0,
    /// <summary>
    /// Top edge.
    /// </summary>
    Top = 1,
    /// <summary>
    /// Right edge.
    /// </summary>
    Right = 2,
    /// <summary>
    /// Bottom edge.
    /// </summary>
    Bottom = 3
}


text:
package logray

import (
	"fmt"
	"strings"
)

// The type used to specify class for log functions.
type LogClass uint32

// Returns string representation of the given class.
func (l LogClass) String() string {
	switch l {
	case NONE:
		return "none"
	case TRACE:
		return "trace"
	case TRACEPLUS:
		return "trace+"
	case DEBUG:
		return "debug"
	case DEBUGPLUS:
		return "debug+"
	case INFO:
		return "info"
	case INFOPLUS:
		return "info+"
	case WARN:
		return "warn"
	case WARNPLUS:
		return "warn+"
	case ERROR:
		return "error"
	case ERRORPLUS:
		return "error+"
	case FATAL:
		return "fatal"
	case FATALPLUS:
		return "fatal+"
	case ALL:
		return "all"
	}

	// The consts do not match the class, so iterate over the base types and
	// generate a combination of the log classes.
	classes := make([]string, 0)
	for _, lc := range baseLogClasses {
		if l&lc == lc {
			classes = append(classes, lc.String())
		}
	}
	return strings.Join(classes, "|")
}

// Parses a logclass string into a LogClass object. This call is case
// insensitive. If the string is not recognised then an error will be returned
// and LogClass will be set to NONE.
func ParseLogClass(s string) (LogClass, error) {
	switch strings.ToLower(s) {
	case "none":
		return NONE, nil
	case "trace":
		return TRACE, nil
	case "trace+":
		return TRACEPLUS, nil
	case "debug":
		return DEBUG, nil
	case "debug+":
		return DEBUGPLUS, nil
	case "info":
		return INFO, nil
	case "info+":
		return INFOPLUS, nil
	case "warn":
		return WARN, nil
	case "warn+":
		return WARNPLUS, nil
	case "error":
		return ERROR, nil
	case "error+":
		return ERRORPLUS, nil
	case "fatal":
		return FATAL, nil
	case "fatal+":
		return FATALPLUS, nil
	case "all":
		return ALL, nil
	}
	return NONE, fmt.Errorf("Invalid LogClass string.")
}

// Returns true if the LogClass object is valid.
func (l LogClass) valid() bool {
	return l&(^(ALL | isPLUSDEF)) == 0
}

// Returns true if this log class includes the TRACE level.
func (l LogClass) includesTrace() bool { return l&TRACE != 0 }

// Returns true if this log class includes the DEBUG level.
func (l LogClass) includesDebug() bool { return l&DEBUG != 0 }

// Returns true if this log class includes the INFO level.
func (l LogClass) includesInfo() bool { return l&INFO != 0 }

// Returns true if this log class includes the WARN level.
func (l LogClass) includesWarn() bool { return l&WARN != 0 }

// Returns true if this log class includes the ERROR level.
func (l LogClass) includesError() bool { return l&ERROR != 0 }

// Returns true if this log class includes the FATAL level.
func (l LogClass) includesFatal() bool { return l&FATAL != 0 }

const (
	// Trace class logging.
	//
	// Logs in this class are typically dumping complete received message, etc. A
	// typical example of Tracing would be to dump the headers and POST data for a
	// request received via HTTP. Generally it should be expected that Trace class
	// calls will only be enabled when specific problems are being tracked.
	TRACE = LogClass(1)

	// Debug class logging.
	//
	// Debugging logging should show the general code path and should be used to
	// highlight edge case code deviations and such. This class will also not be
	// enabled by default.
	DEBUG = LogClass(TRACE << 1)

	// Info class logging.
	//
	// Info class logging is used to inform the admin of situations which are in
	// the normal code path. Examples of Info class logging include startup, shut
	// down notifications, or generalized query logs.
	INFO = LogClass(DEBUG << 1)

	// Warn class logging.
	//
	// Warnings are thrown when a problem happens that can be corrected.  Examples
	// of this type of logging include reconnect or disconnect notices. Logging
	// events in this class should not prevent anything from completing. For
	// example, if a query is delayed, but still completes then this is the right
	// class, but if the query fails then look at Error instead.
	WARN = LogClass(INFO << 1)

	// Error class logging.
	//
	// Error logging is for anything that impacts a query in a way that is
	// unrecoverable. Examples of this might be the inability to reconnect to a
	// backend, or a timeout on an operational call. Generally errors should be
	// reserved for specific failures which indicate that a request is failing.
	ERROR = LogClass(WARN << 1)

	// Fatal class logging.
	//
	// Fatal logs are used to report that something is wrong with the process
	// directly. A completely unexpected nil pointer, or a error writing to the
	// file system, etc. These are things for which recovery may not even be
	// possible and therefor further operation of the process is in question.
	FATAL = LogClass(ERROR << 1)

	// None, used to specify that no logging should be done.
	NONE = LogClass(0)

	// All, used when you want to change settings on all classes at once.
	ALL = (TRACE | DEBUG | INFO | WARN | ERROR | FATAL)

	// A bit that specifically marks the constant as being a plus definition.
	// This is used to ensure that ALL/TRACEPLUS and FATAL/FATALPLUS are different
	// numbers.
	isPLUSDEF = LogClass(FATAL << 1)

	// Trace+ is a set of TRACE, DEBUG, INFO, WARN, ERROR, FATAL and is used in
	// configuration to set all of those classes.
	TRACEPLUS = TRACE | DEBUG | INFO | WARN | ERROR | FATAL | isPLUSDEF

	// Debug+ is a set of DEBUG, INFO, WARN, ERROR, FATAL and is used in
	// configuration to set all of those classes.
	DEBUGPLUS = DEBUG | INFO | WARN | ERROR | FATAL | isPLUSDEF

	// Info+ is a set of INFO, WARN, ERROR, FATAL and is used in configuration to
	// set all of those classes.
	INFOPLUS = INFO | WARN | ERROR | FATAL | isPLUSDEF

	// WARN+ is a set of WARN, ERROR, FATAL and is used in configuration to set
	// all of those classes.
	WARNPLUS = WARN | ERROR | FATAL | isPLUSDEF

	// Trace+ is a set of ERROR, FATAL and is used in configuration to set all of
	// those classes.
	ERRORPLUS = ERROR | FATAL | isPLUSDEF

	// Fatal+ is a set of just FATAL. Its not expected to be used much however it
	// is provided to complete the API.
	FATALPLUS = FATAL | isPLUSDEF
)

var (
	// Defines the base log classes.
	baseLogClasses = []LogClass{
		TRACE, DEBUG, INFO, WARN, ERROR, FATAL,
	}
)


text:
setfenv(1, require'winapi')
require'winapi.winuser'

ffi.cdef[[
typedef struct tagACCEL {
    BYTE   fVirt;
    WORD   key;
    WORD   id;
} ACCEL, *LPACCEL;

HACCEL CreateAcceleratorTableW(LPACCEL paccel, int cAccel);
BOOL DestroyAcceleratorTable(HACCEL hAccel);
int CopyAcceleratorTableW(HACCEL hAccelSrc, LPACCEL lpAccelDst, int cAccelEntries);
]]

FVIRTKEY  = 0x01 --without this flag, FCONTROL doesn't work; with this flag, lowercase letters don't work.
FSHIFT    = 0x04
FCONTROL  = 0x08
FALT      = 0x10

function ACCEL(t)
	if type(t) == 'table' then
		local is_char = type(t.key) == 'string' and not t.key:find'^VK_'
		t = {
			key = is_char and wcs(t.key:upper())[0] or flags(t.key),
			fVirt = bit.bor(flags(t.modifiers), FVIRTKEY),
			id = t.id,
		}
	end
	return types.ACCEL(t)
end

function CreateAcceleratorTable(accel)
	local accel, sz = arrays.ACCEL(accel)
	return own(checkh(C.CreateAcceleratorTableW(accel, sz)), DestroyAcceleratorTable)
end

function DestroyAcceleratorTable(haccel)
	checknz(C.DestroyAcceleratorTable(haccel))
	disown(haccel)
end

function AcceleratorTableSize(haccel)
	return C.CopyAcceleratorTableW(haccel, nil, 0)
end

function CopyAcceleratorTable(haccel, buf)
	local buf, sz = arrays.ACCEL(buf or AcceleratorTableSize(haccel))
	C.CopyAcceleratorTableW(haccel, buf, sz)
	return buf
end


text:
require 'spec_helper'

# WebMock.disable!  # enable to re-record

describe PDC::V1::MultiDestination do
  before do
    VCR.insert_cassette fixture_name
  end

  after do
    VCR.eject_cassette
  end

  let(:multi_destinations) { PDC::V1::MultiDestination }

  describe 'simple test case' do
    it 'destination returns count' do
      count = multi_destinations.count
      count.must_equal 1
    end

    it 'destination works with where' do
      count = multi_destinations.where(active: false).count
      count.must_equal 0
    end

    it 'return empty data for specific global component and origin repo release' do
      multi_destinations.where(active: true, global_component: 'ceph', origin_repo_release_id: 'ceph-1.3').all!.must_equal []
    end

    it 'return real data with query params' do
      mappings = multi_destinations.where(active: true, global_component: 'ceph', origin_repo_release_id: 'rhceph-2.1@rhel-7').all!
      mappings.map(&:destination_repo).map(&:release_id).uniq.sort.must_equal ['ceph-2.0@rhel-7', 'rhceph-2.1-updates@rhel-7']
    end
  end
end


text:
package com.github.obullxl.lang.user;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.filter.OncePerRequestFilter;

/**
 * 用户上下文过滤器
 *
 * @author obullxl@gmail.com
 * @version $Id: UserContextFilter.java, V1.0.1 2013年12月12日 上午9:15:20 $
 */
public class UserContextFilter extends OncePerRequestFilter {

    /**
     * @see org.springframework.web.filter.OncePerRequestFilter#doFilterInternal(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, javax.servlet.FilterChain)
     */
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        try {
            // 设置
            HttpSession session = request.getSession(true);
            UserContext ctx = UserContextUtils.findSessionContext(session);
            if (ctx != null) {
                UserContextHolder.set(ctx);
            } else {
                UserContextHolder.set(UserContext.newMockContext());
            }

            // 过滤
            chain.doFilter(request, response);
        } finally {
            // 清理
            UserContextHolder.remove();
        }
    }

}


text:
// +build pkcs11

package pkcs11

import (
	"bytes"
	"crypto"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/sha256"
	"crypto/sha512"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/asn1"
	"fmt"
	"hash"
	"io/ioutil"
	"math/big"
	"net"
	"os"
	"strings"
	"testing"
	"time"

	"github.com/hyperledger/fabric/bccsp"
	"github.com/hyperledger/fabric/bccsp/signer"
	"github.com/hyperledger/fabric/bccsp/sw"
	"github.com/hyperledger/fabric/bccsp/utils"
	"github.com/stretchr/testify/assert"
	"golang.org/x/crypto/sha3"
)

var (
	currentKS         bccsp.KeyStore
	currentBCCSP      bccsp.BCCSP
	currentTestConfig testConfig
)

type testConfig struct {
	securityLevel int
	hashFamily    string
	softVerify    bool
	immutable     bool
}

func TestMain(m *testing.M) {
	os.Exit(testMain(m))
}

func testMain(m *testing.M) int {
	tmpDir, err := ioutil.TempDir("", "pkcs11_ks")
	if err != nil {
		fmt.Printf("Failed to create keystore directory [%s]\n", err)
		return -1
	}
	defer os.RemoveAll(tmpDir)

	keyStore, err := sw.NewFileBasedKeyStore(nil, tmpDir, false)
	if err != nil {
		fmt.Printf("Failed initiliazing KeyStore [%s]\n", err)
		return -1
	}
	currentKS = keyStore

	lib, pin, label := FindPKCS11Lib()
	tests := []testConfig{
		{256, "SHA2", true, false},
		{256, "SHA3", false, false},
		{384, "SHA2", false, false},
		{384, "SHA3", false, false},
		{384, "SHA3", true, false},
	}

	if strings.Contains(lib, "softhsm") {
		tests = append(tests, []testConfig{
			{256, "SHA2", true, false},
			{256, "SHA2", true, true},
		}...)
	}

	opts := PKCS11Opts{
		Library: lib,
		Label:   label,
		Pin:     pin,
	}

	for _, config := range tests {
		currentTestConfig = config

		opts.HashFamily = config.hashFamily
		opts.SecLevel = config.securityLevel
		opts.SoftVerify = config.softVerify
		opts.Immutable = config.immutable
		fmt.Printf("Immutable = [%v]\n", opts.Immutable)
		currentBCCSP, err = New(opts, keyStore)
		if err != nil {
			fmt.Printf("Failed initiliazing BCCSP at [%+v] \n%s\n", opts, err)
			return -1
		}

		ret := m.Run()
		if ret != 0 {
			fmt.Printf("Failed testing at [%+v]\n", opts)
			return -1
		}
	}
	return 0
}

func TestNew(t *testing.T) {
	opts := PKCS11Opts{
		HashFamily: "SHA2",
		SecLevel:   256,
		SoftVerify: false,
		Library:    "lib",
		Label:      "ForFabric",
		Pin:        "98765432",
	}

	// Setup PKCS11 library and provide initial set of values
	lib, _, _ := FindPKCS11Lib()
	opts.Library = lib

	// Test for nil keystore
	_, err := New(opts, nil)
	assert.Error(t, err)
	assert.Contains(t, err.Error(), "Invalid bccsp.KeyStore instance. It must be different from nil")

	// Test for invalid PKCS11 loadLib
	opts.Library = ""
	_, err = New(opts, currentKS)
	assert.Error(t, err)
	assert.Contains(t, err.Error(), "Failed initializing PKCS11 library")
}

func TestFindPKCS11LibEnvVars(t *testing.T) {
	const (
		dummy_PKCS11_LIB   = "/usr/lib/pkcs11"
		dummy_PKCS11_PIN   = "98765432"
		dummy_PKCS11_LABEL = "testing"
	)

	// Set environment variables used for test and preserve
	// original values for restoration after test completion
	orig_PKCS11_LIB := os.Getenv("PKCS11_LIB")
	os.Setenv("PKCS11_LIB", dummy_PKCS11_LIB)

	orig_PKCS11_PIN := os.Getenv("PKCS11_PIN")
	os.Setenv("PKCS11_PIN", dummy_PKCS11_PIN)

	orig_PKCS11_LABEL := os.Getenv("PKCS11_LABEL")
	os.Setenv("PKCS11_LABEL", dummy_PKCS11_LABEL)

	lib, pin, label := FindPKCS11Lib()
	assert.EqualValues(t, dummy_PKCS11_LIB, lib, "FindPKCS11Lib did not return expected library")
	assert.EqualValues(t, dummy_PKCS11_PIN, pin, "FindPKCS11Lib did not return expected pin")
	assert.EqualValues(t, dummy_PKCS11_LABEL, label, "FindPKCS11Lib did not return expected label")

	os.Setenv("PKCS11_LIB", orig_PKCS11_LIB)
	os.Setenv("PKCS11_PIN", orig_PKCS11_PIN)
	os.Setenv("PKCS11_LABEL", orig_PKCS11_LABEL)
}

func TestInvalidNewParameter(t *testing.T) {
	lib, pin, label := FindPKCS11Lib()
	opts := PKCS11Opts{
		Library:    lib,
		Label:      label,
		Pin:        pin,
		SoftVerify: true,
	}

	opts.HashFamily = "SHA2"
	opts.SecLevel = 0
	r, err := New(opts, currentKS)
	if err == nil {
		t.Fatal("Error should be different from nil in this case")
	}
	if r != nil {
		t.Fatal("Return value should be equal to nil in this case")
	}

	opts.HashFamily = "SHA8"
	opts.SecLevel = 256
	r, err = New(opts, currentKS)
	if err == nil {
		t.Fatal("Error should be different from nil in this case")
	}
	if r != nil {
		t.Fatal("Return value should be equal to nil in this case")
	}

	opts.HashFamily = "SHA2"
	opts.SecLevel = 256
	r, err = New(opts, nil)
	if err == nil {
		t.Fatal("Error should be different from nil in this case")
	}
	if r != nil {
		t.Fatal("Return value should be equal to nil in this case")
	}

	opts.HashFamily = "SHA3"
	opts.SecLevel = 0
	r, err = New(opts, nil)
	if err == nil {
		t.Fatal("Error should be different from nil in this case")
	}
	if r != nil {
		t.Fatal("Return value should be equal to nil in this case")
	}
}

func TestInvalidSKI(t *testing.T) {
	k, err := currentBCCSP.GetKey(nil)
	if err == nil {
		t.Fatal("Error should be different from nil in this case")
	}
	if k != nil {
		t.Fatal("Return value should be equal to nil in this case")
	}

	k, err = currentBCCSP.GetKey([]byte{0, 1, 2, 3, 4, 5, 6})
	if err == nil {
		t.Fatal("Error should be different from nil in this case")
	}
	if k != nil {
		t.Fatal("Return value should be equal to nil in this case")
	}
}

func TestKeyGenECDSAOpts(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestKeyGenECDSAOpts")
	}
	// Curve P256
	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAP256KeyGenOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed generating ECDSA P256 key [%s]", err)
	}
	if k == nil {
		t.Fatal("Failed generating ECDSA P256 key. Key must be different from nil")
	}
	if !k.Private() {
		t.Fatal("Failed generating ECDSA P256 key. Key should be private")
	}
	if k.Symmetric() {
		t.Fatal("Failed generating ECDSA P256 key. Key should be asymmetric")
	}

	ecdsaKey := k.(*ecdsaPrivateKey).pub
	if elliptic.P256() != ecdsaKey.pub.Curve {
		t.Fatal("P256 generated key in invalid. The curve must be P256.")
	}

	// Curve P384
	k, err = currentBCCSP.KeyGen(&bccsp.ECDSAP384KeyGenOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed generating ECDSA P384 key [%s]", err)
	}
	if k == nil {
		t.Fatal("Failed generating ECDSA P384 key. Key must be different from nil")
	}
	if !k.Private() {
		t.Fatal("Failed generating ECDSA P384 key. Key should be private")
	}
	if k.Symmetric() {
		t.Fatal("Failed generating ECDSA P384 key. Key should be asymmetric")
	}

	ecdsaKey = k.(*ecdsaPrivateKey).pub
	if elliptic.P384() != ecdsaKey.pub.Curve {
		t.Fatal("P256 generated key in invalid. The curve must be P384.")
	}
}

func TestKeyGenAESOpts(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestKeyGenAESOpts")
	}
	// AES 128
	k, err := currentBCCSP.KeyGen(&bccsp.AES128KeyGenOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed generating AES 128 key [%s]", err)
	}
	if k == nil {
		t.Fatal("Failed generating AES 128 key. Key must be different from nil")
	}
	if !k.Private() {
		t.Fatal("Failed generating AES 128 key. Key should be private")
	}
	if !k.Symmetric() {
		t.Fatal("Failed generating AES 128 key. Key should be symmetric")
	}

	// AES 192
	k, err = currentBCCSP.KeyGen(&bccsp.AES192KeyGenOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed generating AES 192 key [%s]", err)
	}
	if k == nil {
		t.Fatal("Failed generating AES 192 key. Key must be different from nil")
	}
	if !k.Private() {
		t.Fatal("Failed generating AES 192 key. Key should be private")
	}
	if !k.Symmetric() {
		t.Fatal("Failed generating AES 192 key. Key should be symmetric")
	}

	// AES 256
	k, err = currentBCCSP.KeyGen(&bccsp.AES256KeyGenOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed generating AES 256 key [%s]", err)
	}
	if k == nil {
		t.Fatal("Failed generating AES 256 key. Key must be different from nil")
	}
	if !k.Private() {
		t.Fatal("Failed generating AES 256 key. Key should be private")
	}
	if !k.Symmetric() {
		t.Fatal("Failed generating AES 256 key. Key should be symmetric")
	}
}

func TestHashOpts(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestHashOpts")
	}
	msg := []byte("abcd")

	// SHA256
	digest1, err := currentBCCSP.Hash(msg, &bccsp.SHA256Opts{})
	if err != nil {
		t.Fatalf("Failed computing SHA256 [%s]", err)
	}

	h := sha256.New()
	h.Write(msg)
	digest2 := h.Sum(nil)

	if !bytes.Equal(digest1, digest2) {
		t.Fatalf("Different SHA256 computed. [%x][%x]", digest1, digest2)
	}

	// SHA384
	digest1, err = currentBCCSP.Hash(msg, &bccsp.SHA384Opts{})
	if err != nil {
		t.Fatalf("Failed computing SHA384 [%s]", err)
	}

	h = sha512.New384()
	h.Write(msg)
	digest2 = h.Sum(nil)

	if !bytes.Equal(digest1, digest2) {
		t.Fatalf("Different SHA384 computed. [%x][%x]", digest1, digest2)
	}

	// SHA3_256O
	digest1, err = currentBCCSP.Hash(msg, &bccsp.SHA3_256Opts{})
	if err != nil {
		t.Fatalf("Failed computing SHA3_256 [%s]", err)
	}

	h = sha3.New256()
	h.Write(msg)
	digest2 = h.Sum(nil)

	if !bytes.Equal(digest1, digest2) {
		t.Fatalf("Different SHA3_256 computed. [%x][%x]", digest1, digest2)
	}

	// SHA3_384
	digest1, err = currentBCCSP.Hash(msg, &bccsp.SHA3_384Opts{})
	if err != nil {
		t.Fatalf("Failed computing SHA3_384 [%s]", err)
	}

	h = sha3.New384()
	h.Write(msg)
	digest2 = h.Sum(nil)

	if !bytes.Equal(digest1, digest2) {
		t.Fatalf("Different SHA3_384 computed. [%x][%x]", digest1, digest2)
	}
}

func TestECDSAKeyGenEphemeral(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestECDSAKeyGenEphemeral")
	}
	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: true})
	if err != nil {
		t.Fatalf("Failed generating ECDSA key [%s]", err)
	}
	if k == nil {
		t.Fatal("Failed generating ECDSA key. Key must be different from nil")
	}
	if !k.Private() {
		t.Fatal("Failed generating ECDSA key. Key should be private")
	}
	if k.Symmetric() {
		t.Fatal("Failed generating ECDSA key. Key should be asymmetric")
	}
	raw, err := k.Bytes()
	if err == nil {
		t.Fatal("Failed marshalling to bytes. Marshalling must fail.")
	}
	if len(raw) != 0 {
		t.Fatal("Failed marshalling to bytes. Output should be 0 bytes")
	}
	pk, err := k.PublicKey()
	if err != nil {
		t.Fatalf("Failed getting corresponding public key [%s]", err)
	}
	if pk == nil {
		t.Fatal("Public key must be different from nil.")
	}
}

func TestECDSAPrivateKeySKI(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestECDSAPrivateKeySKI")
	}
	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed generating ECDSA key [%s]", err)
	}

	ski := k.SKI()
	if len(ski) == 0 {
		t.Fatal("SKI not valid. Zero length.")
	}
}

func TestECDSAKeyGenNonEphemeral(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestECDSAKeyGenNonEphemeral")
	}
	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed generating ECDSA key [%s]", err)
	}
	if k == nil {
		t.Fatal("Failed generating ECDSA key. Key must be different from nil")
	}
	if !k.Private() {
		t.Fatal("Failed generating ECDSA key. Key should be private")
	}
	if k.Symmetric() {
		t.Fatal("Failed generating ECDSA key. Key should be asymmetric")
	}
}

func TestECDSAGetKeyBySKI(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestECDSAGetKeyBySKI")
	}
	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed generating ECDSA key [%s]", err)
	}

	k2, err := currentBCCSP.GetKey(k.SKI())
	if err != nil {
		t.Fatalf("Failed getting ECDSA key [%s]", err)
	}
	if k2 == nil {
		t.Fatal("Failed getting ECDSA key. Key must be different from nil")
	}
	if !k2.Private() {
		t.Fatal("Failed getting ECDSA key. Key should be private")
	}
	if k2.Symmetric() {
		t.Fatal("Failed getting ECDSA key. Key should be asymmetric")
	}

	// Check that the SKIs are the same
	if !bytes.Equal(k.SKI(), k2.SKI()) {
		t.Fatalf("SKIs are different [%x]!=[%x]", k.SKI(), k2.SKI())
	}
}

func TestECDSAPublicKeyFromPrivateKey(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestECDSAPublicKeyFromPrivateKey")
	}
	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed generating ECDSA key [%s]", err)
	}

	pk, err := k.PublicKey()
	if err != nil {
		t.Fatalf("Failed getting public key from private ECDSA key [%s]", err)
	}
	if pk == nil {
		t.Fatal("Failed getting public key from private ECDSA key. Key must be different from nil")
	}
	if pk.Private() {
		t.Fatal("Failed generating ECDSA key. Key should be public")
	}
	if pk.Symmetric() {
		t.Fatal("Failed generating ECDSA key. Key should be asymmetric")
	}
}

func TestECDSAPublicKeyBytes(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestECDSAPublicKeyBytes")
	}

	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed generating ECDSA key [%s]", err)
	}

	pk, err := k.PublicKey()
	if err != nil {
		t.Fatalf("Failed getting public key from private ECDSA key [%s]", err)
	}

	raw, err := pk.Bytes()
	if err != nil {
		t.Fatalf("Failed marshalling ECDSA public key [%s]", err)
	}
	if len(raw) == 0 {
		t.Fatal("Failed marshalling ECDSA public key. Zero length")
	}
}

func TestECDSAPublicKeySKI(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestECDSAPublicKeySKI")
	}
	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed generating ECDSA key [%s]", err)
	}

	pk, err := k.PublicKey()
	if err != nil {
		t.Fatalf("Failed getting public key from private ECDSA key [%s]", err)
	}

	ski := pk.SKI()
	if len(ski) == 0 {
		t.Fatal("SKI not valid. Zero length.")
	}
}

func TestECDSASign(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestECDSASign")
	}
	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed generating ECDSA key [%s]", err)
	}

	msg := []byte("Hello World")

	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
	if err != nil {
		t.Fatalf("Failed computing HASH [%s]", err)
	}

	signature, err := currentBCCSP.Sign(k, digest, nil)
	if err != nil {
		t.Fatalf("Failed generating ECDSA signature [%s]", err)
	}
	if len(signature) == 0 {
		t.Fatal("Failed generating ECDSA key. Signature must be different from nil")
	}

	_, err = currentBCCSP.Sign(nil, digest, nil)
	assert.Error(t, err)
	assert.Contains(t, err.Error(), "Invalid Key. It must not be nil")

	_, err = currentBCCSP.Sign(k, nil, nil)
	assert.Error(t, err)
	assert.Contains(t, err.Error(), "Invalid digest. Cannot be empty")
}

func TestECDSAVerify(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestECDSAVerify")
	}
	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed generating ECDSA key [%s]", err)
	}

	msg := []byte("Hello World")

	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
	if err != nil {
		t.Fatalf("Failed computing HASH [%s]", err)
	}

	signature, err := currentBCCSP.Sign(k, digest, nil)
	if err != nil {
		t.Fatalf("Failed generating ECDSA signature  [%s]", err)
	}

	valid, err := currentBCCSP.Verify(k, signature, digest, nil)
	if err != nil {
		t.Fatalf("Failed verifying ECDSA signature [%s]", err)
	}
	if !valid {
		t.Fatal("Failed verifying ECDSA signature. Signature not valid.")
	}

	pk, err := k.PublicKey()
	if err != nil {
		t.Fatalf("Failed getting corresponding public key [%s]", err)
	}

	valid, err = currentBCCSP.Verify(pk, signature, digest, nil)
	if err != nil {
		t.Fatalf("Failed verifying ECDSA signature [%s]", err)
	}
	if !valid {
		t.Fatal("Failed verifying ECDSA signature. Signature not valid.")
	}

	_, err = currentBCCSP.Verify(nil, signature, digest, nil)
	assert.Error(t, err)
	assert.Contains(t, err.Error(), "Invalid Key. It must not be nil")

	_, err = currentBCCSP.Verify(pk, nil, digest, nil)
	assert.Error(t, err)
	assert.Contains(t, err.Error(), "Invalid signature. Cannot be empty")

	_, err = currentBCCSP.Verify(pk, signature, nil, nil)
	assert.Error(t, err)
	assert.Contains(t, err.Error(), "Invalid digest. Cannot be empty")

	// Import the exported public key
	pkRaw, err := pk.Bytes()
	if err != nil {
		t.Fatalf("Failed getting ECDSA raw public key [%s]", err)
	}

	// Store public key
	_, err = currentBCCSP.KeyImport(pkRaw, &bccsp.ECDSAPKIXPublicKeyImportOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed storing corresponding public key [%s]", err)
	}

	pk2, err := currentBCCSP.GetKey(pk.SKI())
	if err != nil {
		t.Fatalf("Failed retrieving corresponding public key [%s]", err)
	}

	valid, err = currentBCCSP.Verify(pk2, signature, digest, nil)
	if err != nil {
		t.Fatalf("Failed verifying ECDSA signature [%s]", err)
	}
	if !valid {
		t.Fatal("Failed verifying ECDSA signature. Signature not valid.")
	}
}

func TestECDSAKeyImportFromExportedKey(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestECDSAKeyImportFromExportedKey")
	}
	// Generate an ECDSA key
	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed generating ECDSA key [%s]", err)
	}

	// Export the public key
	pk, err := k.PublicKey()
	if err != nil {
		t.Fatalf("Failed getting ECDSA public key [%s]", err)
	}

	pkRaw, err := pk.Bytes()
	if err != nil {
		t.Fatalf("Failed getting ECDSA raw public key [%s]", err)
	}

	// Import the exported public key
	pk2, err := currentBCCSP.KeyImport(pkRaw, &bccsp.ECDSAPKIXPublicKeyImportOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed importing ECDSA public key [%s]", err)
	}
	if pk2 == nil {
		t.Fatal("Failed importing ECDSA public key. Return BCCSP key cannot be nil.")
	}

	// Sign and verify with the imported public key
	msg := []byte("Hello World")

	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
	if err != nil {
		t.Fatalf("Failed computing HASH [%s]", err)
	}

	signature, err := currentBCCSP.Sign(k, digest, nil)
	if err != nil {
		t.Fatalf("Failed generating ECDSA signature [%s]", err)
	}

	valid, err := currentBCCSP.Verify(pk2, signature, digest, nil)
	if err != nil {
		t.Fatalf("Failed verifying ECDSA signature [%s]", err)
	}
	if !valid {
		t.Fatal("Failed verifying ECDSA signature. Signature not valid.")
	}
}

func TestECDSAKeyImportFromECDSAPublicKey(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestECDSAKeyImportFromECDSAPublicKey")
	}
	// Generate an ECDSA key
	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed generating ECDSA key [%s]", err)
	}

	// Export the public key
	pk, err := k.PublicKey()
	if err != nil {
		t.Fatalf("Failed getting ECDSA public key [%s]", err)
	}

	pkRaw, err := pk.Bytes()
	if err != nil {
		t.Fatalf("Failed getting ECDSA raw public key [%s]", err)
	}

	pub, err := utils.DERToPublicKey(pkRaw)
	if err != nil {
		t.Fatalf("Failed converting raw to ecdsa.PublicKey [%s]", err)
	}

	// Import the ecdsa.PublicKey
	pk2, err := currentBCCSP.KeyImport(pub, &bccsp.ECDSAGoPublicKeyImportOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed importing ECDSA public key [%s]", err)
	}
	if pk2 == nil {
		t.Fatal("Failed importing ECDSA public key. Return BCCSP key cannot be nil.")
	}

	// Sign and verify with the imported public key
	msg := []byte("Hello World")

	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
	if err != nil {
		t.Fatalf("Failed computing HASH [%s]", err)
	}

	signature, err := currentBCCSP.Sign(k, digest, nil)
	if err != nil {
		t.Fatalf("Failed generating ECDSA signature [%s]", err)
	}

	valid, err := currentBCCSP.Verify(pk2, signature, digest, nil)
	if err != nil {
		t.Fatalf("Failed verifying ECDSA signature [%s]", err)
	}
	if !valid {
		t.Fatal("Failed verifying ECDSA signature. Signature not valid.")
	}
}

func TestKeyImportFromX509ECDSAPublicKey(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestKeyImportFromX509ECDSAPublicKey")
	}
	// Generate an ECDSA key
	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed generating ECDSA key [%s]", err)
	}

	// Generate a self-signed certificate
	testExtKeyUsage := []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}
	testUnknownExtKeyUsage := []asn1.ObjectIdentifier{[]int{1, 2, 3}, []int{2, 59, 1}}
	extraExtensionData := []byte("extra extension")
	commonName := "test.example.com"
	template := x509.Certificate{
		SerialNumber: big.NewInt(1),
		Subject: pkix.Name{
			CommonName:   commonName,
			Organization: []string{"Σ Acme Co"},
			Country:      []string{"US"},
			ExtraNames: []pkix.AttributeTypeAndValue{
				{
					Type:  []int{2, 5, 4, 42},
					Value: "Gopher",
				},
				// This should override the Country, above.
				{
					Type:  []int{2, 5, 4, 6},
					Value: "NL",
				},
			},
		},
		NotBefore: time.Now().Add(-1 * time.Hour),
		NotAfter:  time.Now().Add(1 * time.Hour),

		SignatureAlgorithm: x509.ECDSAWithSHA256,

		SubjectKeyId: []byte{1, 2, 3, 4},
		KeyUsage:     x509.KeyUsageCertSign,

		ExtKeyUsage:        testExtKeyUsage,
		UnknownExtKeyUsage: testUnknownExtKeyUsage,

		BasicConstraintsValid: true,
		IsCA:                  true,

		OCSPServer:            []string{"http://ocurrentBCCSP.example.com"},
		IssuingCertificateURL: []string{"http://crt.example.com/ca1.crt"},

		DNSNames:       []string{"test.example.com"},
		EmailAddresses: []string{"gopher@golang.org"},
		IPAddresses:    []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")},

		PolicyIdentifiers:   []asn1.ObjectIdentifier{[]int{1, 2, 3}},
		PermittedDNSDomains: []string{".example.com", "example.com"},

		CRLDistributionPoints: []string{"http://crl1.example.com/ca1.crl", "http://crl2.example.com/ca1.crl"},

		ExtraExtensions: []pkix.Extension{
			{
				Id:    []int{1, 2, 3, 4},
				Value: extraExtensionData,
			},
		},
	}

	cryptoSigner, err := signer.New(currentBCCSP, k)
	if err != nil {
		t.Fatalf("Failed initializing CyrptoSigner [%s]", err)
	}

	// Export the public key
	pk, err := k.PublicKey()
	if err != nil {
		t.Fatalf("Failed getting ECDSA public key [%s]", err)
	}

	pkRaw, err := pk.Bytes()
	if err != nil {
		t.Fatalf("Failed getting ECDSA raw public key [%s]", err)
	}

	pub, err := utils.DERToPublicKey(pkRaw)
	if err != nil {
		t.Fatalf("Failed converting raw to ECDSA.PublicKey [%s]", err)
	}

	certRaw, err := x509.CreateCertificate(rand.Reader, &template, &template, pub, cryptoSigner)
	if err != nil {
		t.Fatalf("Failed generating self-signed certificate [%s]", err)
	}

	cert, err := utils.DERToX509Certificate(certRaw)
	if err != nil {
		t.Fatalf("Failed generating X509 certificate object from raw [%s]", err)
	}

	// Import the certificate's public key
	pk2, err := currentBCCSP.KeyImport(cert, &bccsp.X509PublicKeyImportOpts{Temporary: false})

	if err != nil {
		t.Fatalf("Failed importing ECDSA public key [%s]", err)
	}
	if pk2 == nil {
		t.Fatal("Failed importing ECDSA public key. Return BCCSP key cannot be nil.")
	}

	// Sign and verify with the imported public key
	msg := []byte("Hello World")

	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
	if err != nil {
		t.Fatalf("Failed computing HASH [%s]", err)
	}

	signature, err := currentBCCSP.Sign(k, digest, nil)
	if err != nil {
		t.Fatalf("Failed generating ECDSA signature [%s]", err)
	}

	valid, err := currentBCCSP.Verify(pk2, signature, digest, nil)
	if err != nil {
		t.Fatalf("Failed verifying ECDSA signature [%s]", err)
	}
	if !valid {
		t.Fatal("Failed verifying ECDSA signature. Signature not valid.")
	}
}

func TestECDSASignatureEncoding(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestECDSASignatureEncoding")
	}
	v := []byte{0x30, 0x07, 0x02, 0x01, 0x8F, 0x02, 0x02, 0xff, 0xf1}
	_, err := asn1.Unmarshal(v, &utils.ECDSASignature{})
	if err == nil {
		t.Fatalf("Unmarshalling should fail for [% x]", v)
	}
	t.Logf("Unmarshalling correctly failed for [% x] [%s]", v, err)

	v = []byte{0x30, 0x07, 0x02, 0x01, 0x8F, 0x02, 0x02, 0x00, 0x01}
	_, err = asn1.Unmarshal(v, &utils.ECDSASignature{})
	if err == nil {
		t.Fatalf("Unmarshalling should fail for [% x]", v)
	}
	t.Logf("Unmarshalling correctly failed for [% x] [%s]", v, err)

	v = []byte{0x30, 0x07, 0x02, 0x01, 0x8F, 0x02, 0x81, 0x01, 0x01}
	_, err = asn1.Unmarshal(v, &utils.ECDSASignature{})
	if err == nil {
		t.Fatalf("Unmarshalling should fail for [% x]", v)
	}
	t.Logf("Unmarshalling correctly failed for [% x] [%s]", v, err)

	v = []byte{0x30, 0x07, 0x02, 0x01, 0x8F, 0x02, 0x81, 0x01, 0x8F}
	_, err = asn1.Unmarshal(v, &utils.ECDSASignature{})
	if err == nil {
		t.Fatalf("Unmarshalling should fail for [% x]", v)
	}
	t.Logf("Unmarshalling correctly failed for [% x] [%s]", v, err)

	v = []byte{0x30, 0x0A, 0x02, 0x01, 0x8F, 0x02, 0x05, 0x00, 0x00, 0x00, 0x00, 0x8F}
	_, err = asn1.Unmarshal(v, &utils.ECDSASignature{})
	if err == nil {
		t.Fatalf("Unmarshalling should fail for [% x]", v)
	}
	t.Logf("Unmarshalling correctly failed for [% x] [%s]", v, err)

}

func TestECDSALowS(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestECDSALowS")
	}
	// Ensure that signature with low-S are generated
	k, err := currentBCCSP.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed generating ECDSA key [%s]", err)
	}

	msg := []byte("Hello World")

	digest, err := currentBCCSP.Hash(msg, &bccsp.SHAOpts{})
	if err != nil {
		t.Fatalf("Failed computing HASH [%s]", err)
	}

	signature, err := currentBCCSP.Sign(k, digest, nil)
	if err != nil {
		t.Fatalf("Failed generating ECDSA signature [%s]", err)
	}

	R, S, err := utils.UnmarshalECDSASignature(signature)
	if err != nil {
		t.Fatalf("Failed unmarshalling signature [%s]", err)
	}

	if S.Cmp(utils.GetCurveHalfOrdersAt(k.(*ecdsaPrivateKey).pub.pub.Curve)) >= 0 {
		t.Fatal("Invalid signature. It must have low-S")
	}

	valid, err := currentBCCSP.Verify(k, signature, digest, nil)
	if err != nil {
		t.Fatalf("Failed verifying ECDSA signature [%s]", err)
	}
	if !valid {
		t.Fatal("Failed verifying ECDSA signature. Signature not valid.")
	}

	// Ensure that signature with high-S are rejected.
	for {
		R, S, err = currentBCCSP.(*impl).signP11ECDSA(k.SKI(), digest)
		if err != nil {
			t.Fatalf("Failed generating signature [%s]", err)
		}

		if S.Cmp(utils.GetCurveHalfOrdersAt(k.(*ecdsaPrivateKey).pub.pub.Curve)) > 0 {
			break
		}
	}

	sig, err := utils.MarshalECDSASignature(R, S)
	if err != nil {
		t.Fatalf("Failing unmarshalling signature [%s]", err)
	}

	valid, err = currentBCCSP.Verify(k, sig, digest, nil)
	if err == nil {
		t.Fatal("Failed verifying ECDSA signature. It must fail for a signature with high-S")
	}
	if valid {
		t.Fatal("Failed verifying ECDSA signature. It must fail for a signature with high-S")
	}
}

func TestAESKeyGen(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestAESKeyGen")
	}
	k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed generating AES_256 key [%s]", err)
	}
	if k == nil {
		t.Fatal("Failed generating AES_256 key. Key must be different from nil")
	}
	if !k.Private() {
		t.Fatal("Failed generating AES_256 key. Key should be private")
	}
	if !k.Symmetric() {
		t.Fatal("Failed generating AES_256 key. Key should be symmetric")
	}

	pk, err := k.PublicKey()
	if err == nil {
		t.Fatal("Error should be different from nil in this case")
	}
	if pk != nil {
		t.Fatal("Return value should be equal to nil in this case")
	}
}

func TestAESEncrypt(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestAESEncrypt")
	}
	k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed generating AES_256 key [%s]", err)
	}

	ct, err := currentBCCSP.Encrypt(k, []byte("Hello World"), &bccsp.AESCBCPKCS7ModeOpts{})
	if err != nil {
		t.Fatalf("Failed encrypting [%s]", err)
	}
	if len(ct) == 0 {
		t.Fatal("Failed encrypting. Nil ciphertext")
	}
}

func TestAESDecrypt(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestAESDecrypt")
	}
	k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed generating AES_256 key [%s]", err)
	}

	msg := []byte("Hello World")

	ct, err := currentBCCSP.Encrypt(k, msg, &bccsp.AESCBCPKCS7ModeOpts{})
	if err != nil {
		t.Fatalf("Failed encrypting [%s]", err)
	}

	pt, err := currentBCCSP.Decrypt(k, ct, bccsp.AESCBCPKCS7ModeOpts{})
	if err != nil {
		t.Fatalf("Failed decrypting [%s]", err)
	}
	if len(ct) == 0 {
		t.Fatal("Failed decrypting. Nil plaintext")
	}

	if !bytes.Equal(msg, pt) {
		t.Fatalf("Failed decrypting. Decrypted plaintext is different from the original. [%x][%x]", msg, pt)
	}
}

func TestHMACTruncated256KeyDerivOverAES256Key(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestHMACTruncated256KeyDerivOverAES256Key")
	}
	k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed generating AES_256 key [%s]", err)
	}

	hmcaedKey, err := currentBCCSP.KeyDeriv(k, &bccsp.HMACTruncated256AESDeriveKeyOpts{Temporary: false, Arg: []byte{1}})
	if err != nil {
		t.Fatalf("Failed HMACing AES_256 key [%s]", err)
	}
	if k == nil {
		t.Fatal("Failed HMACing AES_256 key. HMACed Key must be different from nil")
	}
	if !hmcaedKey.Private() {
		t.Fatal("Failed HMACing AES_256 key. HMACed Key should be private")
	}
	if !hmcaedKey.Symmetric() {
		t.Fatal("Failed HMACing AES_256 key. HMACed Key should be asymmetric")
	}
	raw, err := hmcaedKey.Bytes()
	if err == nil {
		t.Fatal("Failed marshalling to bytes. Operation must be forbidden")
	}
	if len(raw) != 0 {
		t.Fatal("Failed marshalling to bytes. Operation must return 0 bytes")
	}

	msg := []byte("Hello World")

	ct, err := currentBCCSP.Encrypt(hmcaedKey, msg, &bccsp.AESCBCPKCS7ModeOpts{})
	if err != nil {
		t.Fatalf("Failed encrypting [%s]", err)
	}

	pt, err := currentBCCSP.Decrypt(hmcaedKey, ct, bccsp.AESCBCPKCS7ModeOpts{})
	if err != nil {
		t.Fatalf("Failed decrypting [%s]", err)
	}
	if len(ct) == 0 {
		t.Fatal("Failed decrypting. Nil plaintext")
	}

	if !bytes.Equal(msg, pt) {
		t.Fatalf("Failed decrypting. Decrypted plaintext is different from the original. [%x][%x]", msg, pt)
	}

}

func TestHMACKeyDerivOverAES256Key(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestHMACKeyDerivOverAES256Key")
	}
	k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed generating AES_256 key [%s]", err)
	}

	hmcaedKey, err := currentBCCSP.KeyDeriv(k, &bccsp.HMACDeriveKeyOpts{Temporary: false, Arg: []byte{1}})

	if err != nil {
		t.Fatalf("Failed HMACing AES_256 key [%s]", err)
	}
	if k == nil {
		t.Fatal("Failed HMACing AES_256 key. HMACed Key must be different from nil")
	}
	if !hmcaedKey.Private() {
		t.Fatal("Failed HMACing AES_256 key. HMACed Key should be private")
	}
	if !hmcaedKey.Symmetric() {
		t.Fatal("Failed HMACing AES_256 key. HMACed Key should be asymmetric")
	}
	raw, err := hmcaedKey.Bytes()
	if err != nil {
		t.Fatalf("Failed marshalling to bytes [%s]", err)
	}
	if len(raw) == 0 {
		t.Fatal("Failed marshalling to bytes. 0 bytes")
	}
}

func TestAES256KeyImport(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestAES256KeyImport")
	}
	raw, err := sw.GetRandomBytes(32)
	if err != nil {
		t.Fatalf("Failed generating AES key [%s]", err)
	}

	k, err := currentBCCSP.KeyImport(raw, &bccsp.AES256ImportKeyOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed importing AES_256 key [%s]", err)
	}
	if k == nil {
		t.Fatal("Failed importing AES_256 key. Imported Key must be different from nil")
	}
	if !k.Private() {
		t.Fatal("Failed HMACing AES_256 key. Imported Key should be private")
	}
	if !k.Symmetric() {
		t.Fatal("Failed HMACing AES_256 key. Imported Key should be asymmetric")
	}
	raw, err = k.Bytes()
	if err == nil {
		t.Fatal("Failed marshalling to bytes. Marshalling must fail.")
	}
	if len(raw) != 0 {
		t.Fatal("Failed marshalling to bytes. Output should be 0 bytes")
	}

	msg := []byte("Hello World")

	ct, err := currentBCCSP.Encrypt(k, msg, &bccsp.AESCBCPKCS7ModeOpts{})
	if err != nil {
		t.Fatalf("Failed encrypting [%s]", err)
	}

	pt, err := currentBCCSP.Decrypt(k, ct, bccsp.AESCBCPKCS7ModeOpts{})
	if err != nil {
		t.Fatalf("Failed decrypting [%s]", err)
	}
	if len(ct) == 0 {
		t.Fatal("Failed decrypting. Nil plaintext")
	}

	if !bytes.Equal(msg, pt) {
		t.Fatalf("Failed decrypting. Decrypted plaintext is different from the original. [%x][%x]", msg, pt)
	}
}

func TestAES256KeyImportBadPaths(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestAES256KeyImportBadPaths")
	}
	_, err := currentBCCSP.KeyImport(nil, &bccsp.AES256ImportKeyOpts{Temporary: false})
	if err == nil {
		t.Fatal("Failed importing key. Must fail on importing nil key")
	}

	_, err = currentBCCSP.KeyImport([]byte{1}, &bccsp.AES256ImportKeyOpts{Temporary: false})
	if err == nil {
		t.Fatal("Failed importing key. Must fail on importing a key with an invalid length")
	}
}

func TestAES256KeyGenSKI(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestAES256KeyGenSKI")
	}
	k, err := currentBCCSP.KeyGen(&bccsp.AESKeyGenOpts{Temporary: false})
	if err != nil {
		t.Fatalf("Failed generating AES_256 key [%s]", err)
	}

	k2, err := currentBCCSP.GetKey(k.SKI())
	if err != nil {
		t.Fatalf("Failed getting AES_256 key [%s]", err)
	}
	if k2 == nil {
		t.Fatal("Failed getting AES_256 key. Key must be different from nil")
	}
	if !k2.Private() {
		t.Fatal("Failed getting AES_256 key. Key should be private")
	}
	if !k2.Symmetric() {
		t.Fatal("Failed getting AES_256 key. Key should be symmetric")
	}

	// Check that the SKIs are the same
	if !bytes.Equal(k.SKI(), k2.SKI()) {
		t.Fatalf("SKIs are different [%x]!=[%x]", k.SKI(), k2.SKI())
	}

}

func TestSHA(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestSHA")
	}
	for i := 0; i < 100; i++ {
		b, err := sw.GetRandomBytes(i)
		if err != nil {
			t.Fatalf("Failed getting random bytes [%s]", err)
		}

		h1, err := currentBCCSP.Hash(b, &bccsp.SHAOpts{})
		if err != nil {
			t.Fatalf("Failed computing SHA [%s]", err)
		}

		var h hash.Hash
		switch currentTestConfig.hashFamily {
		case "SHA2":
			switch currentTestConfig.securityLevel {
			case 256:
				h = sha256.New()
			case 384:
				h = sha512.New384()
			default:
				t.Fatalf("Invalid security level [%d]", currentTestConfig.securityLevel)
			}
		case "SHA3":
			switch currentTestConfig.securityLevel {
			case 256:
				h = sha3.New256()
			case 384:
				h = sha3.New384()
			default:
				t.Fatalf("Invalid security level [%d]", currentTestConfig.securityLevel)
			}
		default:
			t.Fatalf("Invalid hash family [%s]", currentTestConfig.hashFamily)
		}

		h.Write(b)
		h2 := h.Sum(nil)
		if !bytes.Equal(h1, h2) {
			t.Fatalf("Discrempancy found in HASH result [%x], [%x]!=[%x]", b, h1, h2)
		}
	}
}

func getCryptoHashIndex(t *testing.T) crypto.Hash {
	switch currentTestConfig.hashFamily {
	case "SHA2":
		switch currentTestConfig.securityLevel {
		case 256:
			return crypto.SHA256
		case 384:
			return crypto.SHA384
		default:
			t.Fatalf("Invalid security level [%d]", currentTestConfig.securityLevel)
		}
	case "SHA3":
		switch currentTestConfig.securityLevel {
		case 256:
			return crypto.SHA3_256
		case 384:
			return crypto.SHA3_384
		default:
			t.Fatalf("Invalid security level [%d]", currentTestConfig.securityLevel)
		}
	default:
		t.Fatalf("Invalid hash family [%s]", currentTestConfig.hashFamily)
	}

	return crypto.SHA3_256
}