text:
declare module 'eris' {
  import { EventEmitter } from 'events';
  import { Readable as ReadableStream } from 'stream';

  type WebhookPayload = {
    content?: string,
    file?: { file: Buffer, name: string } | Array<{ file: Buffer, name: string}>,
    embeds?: Array<EmbedOptions>,
    username?: string,
    avatarURL?: string,
    tts?: boolean,
    wait?: boolean,
    disableEveryone?: boolean
  }

  type EmbedBase = {
    title?: string,
    description?: string,
    url?: string,
    timestamp?: number,
    color?: number,
    footer?: { text: string, icon_url?: string, proxy_icon_url?: string },
    image?: { url?: string, proxy_url?: string, height?: number, width?: number },
    thumbnail?: { url?: string, proxy_url?: string, height?: number, width?: number },
    video?: { url: string, height?: number, width?: number },
    provider?: { name: string, url?: string },
    fields?: Array<{ name?: string, value?: string, inline?: boolean }>
  }
  type Embed = {
    type: string
  } & EmbedBase
  type EmbedOptions = {
    type?: string
  } & EmbedBase

  type Webhook = {
    name: string,
    channel_id: string,
    token: string,
    avatar?: string,
    guild_id: string,
    id: string,
    user: {
      username: string,
      discriminator: string,
      id: string,
      avatar?: string
    }
  }

  type GuildEmbed = {
    channel_id?: string,
    enabled: boolean
  }

  type Attachment = { url: string, proxy_url: string, size: number, id: string, filename: string };

  type VoiceRegion = {
    name: string,
    deprecated: boolean,
    custom: boolean,
    vip: boolean,
    optimal: boolean,
    id: string
  }

  type UserSettings = {
    theme: string,
    status: string,
    show_current_game: boolean,
    restricted_guilds: Array<string>,
    render_reactions: boolean,
    render_embeds: boolean,
    message_display_compact: boolean,
    locale: string,
    inline_embed_media: boolean,
    inline_attachment_media: boolean,
    guild_positions: Array<string>,
    friend_source_flags: {
      all: boolean // not sure about other keys, abal heeeelp
    },
    explicit_content_filter: number,
    enable_tts_command: boolean,
    developer_mode: boolean,
    detect_platform_accounts: boolean,
    default_guilds_restricted: boolean,
    convert_emojis: boolean,
    afk_timeout: number
  }

  type GuildSettings = {
    suppress_everyone: boolean,
    muted: boolean,
    mobile_push: boolean,
    message_notifications: number,
    guild_id: string,
    channel_override: Array<{
      muted: boolean,
      message_notifications: number,
      channel_id: string
    }>
  }

  type UserProfile = {
    premium_since?: number,
    mutual_guilds: Array<{ nick?: string, id: string }>,
    user: { username: string, discriminator: string, flags: number, id: string, avatar?: string },
    connected_accounts: Array<{ verified: boolean, type: string, id: string, name: string }>
  }

  type Connection = {
    verified: boolean,
    revoked: boolean,
    integrations: Array<any>, // TODO ????
    visibility: number,
    friend_sync: boolean,
    type: string,
    id: string,
    name: string
  }

  type GuildAuditLog = {
    users: Array<User>,
    entries: Array<GuildAuditLogEntry>
  }

  // TODO: Does this have more stuff?
  type BaseData = {
    id: string
  }

  type MessageContent = string | { content?: string, tts?: boolean, disableEveryone?: boolean, embed?: EmbedOptions };
  type MessageFile = { file: Buffer | string, name: string };
  type EmojiBase = {
    name: string,
    icon?: string
  }
  type EmojiOptions = {
    roles?: Array<string>
  } & EmojiBase
  type Emoji = {
    roles: Array<string>
  } & EmojiBase
  type IntegrationOptions = { expireBehavior: string, expireGracePeriod: string, enableEmoticons: string };
  type GuildOptions = {
    name?: string,
    region?: string,
    icon?: string,
    verificationLevel?: number,
    defaultNotifications?: number,
    afkChannelID?: string,
    afkTimeout?: number,
    ownerID?: string,
    splash?: string
  }
  type MemberOptions = { roles: Array<string>, nick: string, mute: boolean, deaf: boolean, channelID: string };
  type RoleOptions = { name: string, permissions: number, color: number, hoist: boolean, mentionable: boolean };
  type GamePresence = { name: string, type?: number, url?: string };
  type SearchOptions = {
    sortBy?: string,
    sortOrder?: string,
    content?: string,
    authorID?: string,
    minID?: string,
    maxID?: string,
    limit?: number,
    offset?: number,
    contextSize?: number,
    has?: string,
    embedProviders?: string,
    embedTypes?: string,
    attachmentExtensions?: string,
    attachmentFilename?: string,
    channelIDs: Array<string>
  }
  type SearchResults = { totalResults: number, results: Array<Array<Message & { hit?: boolean }>> };
  type VoiceResourceOptions = {
    inlineVolume?: boolean,
    voiceDataTimeout?: number,
    inputArgs?: Array<string>,
    encoderArgs?: Array<string>,
    format?: string,
    frameDuration?: number,
    frameSize?: number,
    sampleRate?: number
  }
  type PossiblyUncachedMessage = Message | { id: string, channel: Channel };
  type RawPacket = { op: number, t?: string, d?: any, s?: number };
  type ClientOptions = {
    autoreconnect?: boolean,
    compress?: boolean,
    connectionTimeout?: number,
    disableEvents?: { [s: string]: boolean },
    disableEveryone?: boolean,
    firstShardID?: number,
    getAllUsers?: boolean,
    guildCreateTimeout?: number,
    largeThreshold?: number,
    lastShardID?: number,
    maxShards?: number,
    messageLimit?: number,
    opusOnly?: boolean,
    restMode?: boolean,
    seedVoiceConnections?: boolean,
    sequencerWaiter?: number,
    defaultImageFormat?: string,
    defaultImageSize?: number
  }
  type CommandClientOptions = {
    defaultHelpCommand?: boolean,
    description?: string,
    ignoreBots?: boolean,
    ignoreSelf?: boolean,
    name?: string,
    owner?: string,
    prefix?: string,
    defaultCommandOptions?: CommandOptions
  }
  type CommandOptions = {
    aliases?: Array<string>,
    caseInsensitive?: boolean,
    deleteCommand?: boolean,
    argsRequired?: boolean,
    guildOnly?: boolean,
    dmOnly?: boolean,
    description?: string,
    fullDescription?: string,
    usage?: string,
    requirements?: {
      userIDs?: Array<string>,
      permissions?: { [s: string]: boolean }
    }
  }
  type CommandGeneratorFunction = (msg: Message, args: Array<string>) => string | void;
  type CommandGenerator = CommandGeneratorFunction | string | Array<string> | Array<CommandGeneratorFunction>;

  export class Client extends EventEmitter {
    token: string;
    bot?: boolean;
    options: ClientOptions;
    channelGuildMap: { [s: string]: string };
    shards: Collection<Shard>;
    guilds: Collection<Guild>;
    privateChannelMap: { [s: string]: string };
    privateChannels: Collection<PrivateChannel>;
    groupChannels: Collection<GroupChannel>;
    voiceConnections: Collection<VoiceConnection>;
    retryAfters: { [s: string]: number };
    guildShardMap: { [s: string]: number };
    startTime: number;
    unavailableGuilds: Collection<UnavailableGuild>;
    uptime: number;
    user: ExtendedUser;
    users: Collection<User>;
    relationships: Collection<Relationship>;
    userGuildSettings: { [s: string]: GuildSettings };
    userSettings: UserSettings;
    notes: { [s: string]: string };
    constructor(token: string, options?: ClientOptions);
    connect(): Promise<void>;
    getGateway(): Promise<string>;
    getBotGateway(): Promise<{ url: string, shards: number }>;
    disconnect(options: { reconnect: boolean }): void;
    joinVoiceChannel(channelID: string, options?: { shared?: boolean, opusOnly?: boolean }): Promise<VoiceConnection>;
    leaveVoiceChannel(channelID: string): void;
    editAFK(afk: boolean): void;
    editStatus(status?: string, game?: GamePresence): void;
    getChannel(channelID: string): Promise<Channel>;
    createChannel(guildID: string, name: string, type?: number, reason?: string): Promise<GuildChannel>;
    editChannel(channelID: string, options: {
      name?: string,
      icon?: string,
      ownerID?: string,
      topic?: string,
      bitrate?: number,
      userLimit?: number
    }, reason?: string): Promise<GroupChannel | GuildChannel>;
    editChannelPosition(channelID: string, position: number): Promise<void>;
    deleteChannel(channelID: string, reason?: string): Promise<void>;
    sendChannelTyping(channelID: string): Promise<void>;
    editChannelPermission(channelID: string, overwriteID: string, allow: number, deny: number, type: string, reason?:string): Promise<void>;
    deleteChannelPermission(channelID: string, overwriteID: string, reason?: string): Promise<void>;
    getChannelInvites(channelID: string): Promise<Array<Invite>>;
    createChannelInvite(channelID: string, options?: { maxAge?: number, maxUses?: number, temporary?: boolean, unique?: boolean }, reason?: string): Promise<Invite>;
    getChannelWebhooks(channelID: string): Promise<Array<Webhook>>;
    getWebhook(webhookID: string, token?: string): Promise<Webhook>;
    createChannelWebhook(channelID: string, options: { name: string, avatar: string }, reason?: string): Promise<Webhook>;
    editWebhook(webhookID: string, options: { name?: string, avatar?: string }, token?: string, reason?: string): Promise<Webhook>;
    executeWebhook(webhookID: string, token: string, options: WebhookPayload): Promise<void>;
    executeSlackWebhook(webhookID: string, token: string, options?: { wait?: boolean }): Promise<void>;
    deleteWebhook(webhookID: string, token?: string, reason?: string): Promise<void>;
    getGuildWebhooks(guildID: string): Promise<Array<Webhook>>;
    getGuildAuditLogs(guildID: string, limit?: number, before?: string, actionType?: number): Promise<GuildAuditLog>;
    createGuildEmoji(guildID: string, options: EmojiOptions, reason?: string): Promise<Emoji>;
    editGuildEmoji(guildID: string, emojiID: string, options: { name?: string, roles?: Array<string> }, reason?: string): Promise<Emoji>;
    deleteGuildEmoji(guildID: string, emojiID: string, reason?: string): Promise<void>;
    createRole(guildID: string, options?: RoleOptions, reason?: string): Promise<Role>;
    editRole(guildID: string, roleID: string, options: RoleOptions, reason?: string): Promise<Role>; // TODO not all options are available?
    editRolePosition(guildID: string, roleID: string, position: number): Promise<void>;
    deleteRole(guildID: string, roleID: string, reason?: string): Promise<void>;
    getPruneCount(guildID: string, days: number): Promise<number>;
    pruneMembers(guildID: string, days: number, reason?: string): Promise<number>;
    getVoiceRegions(guildID: string): Promise<Array<VoiceRegion>>;
    getInvite(inviteID: string, withCounts?: boolean): Promise<Invite>;
    acceptInvite(inviteID: string): Promise<Invite>;
    deleteInvite(inviteID: string, reason?: string): Promise<void>;
    getSelf(): Promise<ExtendedUser>;
    editSelf(options: { username?: string, avatar?: string }): Promise<ExtendedUser>;
    getDMChannel(userID: string): Promise<PrivateChannel>;
    createGroupChannel(userIDs: Array<string>): Promise<GroupChannel>;
    getMessage(channelID: string, messageID: string): Promise<Message>;
    getMessages(channelID: string, limit?: number, before?: string, after?: string, around?: string): Promise<Array<Message>>;
    getPins(channelID: string): Promise<Array<Message>>;
    createMessage(channelID: string, content: MessageContent, file: MessageFile): Promise<Message>;
    editMessage(channelID: string, messageID: string, content: MessageContent): Promise<Message>;
    pinMessage(channelID: string, messageID: string): Promise<void>;
    unpinMessage(channelID: string, messageID: string): Promise<void>;
    getMessageReaction(channelID: string, messageID: string, reaction: string, limit?: number): Promise<Array<User>>;
    addMessageReaction(channelID: string, messageID: string, reaction: string, userID?: string): Promise<void>;
    removeMessageReaction(channelID: string, messageID: string, reaction: string, userID?: string): Promise<void>;
    removeMessageReactions(channelID: string, messageID: string): Promise<void>;
    deleteMessage(channelID: string, messageID: string, reason?: string): Promise<void>;
    deleteMessages(channelID: string, messageIDs: Array<string>, reason?: string): Promise<void>;
    purgeChannel(channelID: string, limit?: number, filter?: (m: Message) => boolean, before?: string, after?: string): Promise<number>;
    getGuildEmbed(guildID: string): Promise<GuildEmbed>;
    getGuildIntegrations(guildID: string): Promise<Array<GuildIntegration>>;
    editGuildIntegration(guildID: string, integrationID: string, options: IntegrationOptions): Promise<void>;
    deleteGuildIntegration(guildID: string, integrationID: string): Promise<void>;
    syncGuildIntegration(guildID: string, integrationID: string): Promise<void>;
    getGuildInvites(guildID: string): Promise<Array<Invite>>;
    banGuildMember(guildID: string, userID: string, deleteMessageDays?: number, reason?: string): Promise<void>;
    unbanGuildMember(guildID: string, userID: string, reason?: string): Promise<void>;
    createGuild(name: string, region: string, icon?: string): Promise<Guild>;
    editGuild(guildID: string, options: GuildOptions, reason?: string): Promise<Guild>;
    getGuildBans(guildID: string): Promise<Array<{ reason?: string, user: User }>>;
    editGuildMember(guildID: string, memberID: string, options: MemberOptions, reason?: string): Promise<void>;
    addGuildMemberRole(guildID: string, memberID: string, roleID: string, reason?: string): Promise<void>;
    removeGuildMemberRole(guildID: string, memberID: string, roleID: string, reason?: string): Promise<void>;
    editNickname(guildID: string, nick: string, reason?: string): Promise<void>;
    kickGuildMember(guildID: string, userID: string, reason?: string): Promise<void>;
    deleteGuild(guildID: string): Promise<void>;
    leaveGuild(guildID: string): Promise<void>;
    getOAuthApplication(appID?: string): Promise<{
      description: string,
      name: string,
      owner: {
        username: string,
        discriminator: string,
        id: string,
        avatar?: string
      },
      bot_public: boolean,
      bot_require_code_grant: boolean,
      id: string,
      icon?: string
    }>;
    addRelationship(userID: string, block?: boolean): Promise<void>;
    removeRelationship(userID: string): Promise<void>;
    addGroupRecipient(groupID: string, userID: string): Promise<void>;
    removeGroupRecipient(groupID: string, userID: string): Promise<void>;
    getUserProfile(userID: string): Promise<UserProfile>;
    editUserNote(userID: string, note: string): Promise<void>;
    deleteUserNote(userID: string): Promise<void>;
    getSelfConnections(): Promise<Array<Connection>>;
    editSelfConnection(platform: string, id: string, data: { friendSync: boolean, visibility: number }): Promise<Connection>;
    deleteSelfConnection(platform: string, id: string): Promise<void>;
    getSelfSettings(): Promise<UserSettings>;
    editSelfSettings(data: UserSettings): Promise<UserSettings>;
    getSelfMFACodes(password: string, regenerate?: boolean): Promise<{ backup_codes: Array<{ code: string, consumed: boolean }> }>;
    enableSelfMFATOTP(secret: string, code: string): Promise<{ token: string, backup_codes: Array<{ code: string, consumed: boolean }> }>;
    disableSelfMFATOTP(code: string): Promise<{ token: string }>;
    getSelfBilling(): Promise<{
      premium_subscription?: {
        status: number,
        ended_at?: string,
        canceled_at?: string,
        created_at: string,
        current_period_end?: string,
        current_period_start?: string,
        plan: string
      },
      payment_source?: {
        type: string,
        brand: string,
        invalid: boolean,
        last_4: number,
        expires_year: number,
        expires_month: number
      },
      payment_gateway?: string
    }>;
    getSelfPayments(): Promise<Array<{
      status: number,
      amount_refunded: number,
      description: string,
      created_at: string, // date
      currency: string,
      amount: number
    }>>;
    addSelfPremiumSubscription(token: string, plan: string): Promise<void>;
    deleteSelfPremiumSubscription(): Promise<void>;
    getRESTChannel(channelID: string): Promise<Channel>;
    getRESTGuild(guildID: string): Promise<Guild>;
    getRESTGuilds(limit?: number, before?: string, after?: string): Promise<Array<Guild>>;
    getRESTGuildChannels(guildID: string): Promise<Array<GuildChannel>>;
    getRESTGuildEmojis(guildID: string): Promise<Array<Emoji>>;
    getRESTGuildEmoji(guildID: string, emojiID: string): Promise<Emoji>;
    getRESTGuildMembers(guildID: string, limit?: number, after?: string): Promise<Array<Member>>;
    getRESTGuildMember(guildID: string, memberID: string): Promise<Member>;
    getRESTGuildRoles(guildID: string): Promise<Array<Role>>;
    getRESTUser(userID: string): Promise<User>;
    searchChannelMessages(channelID: string, query: SearchOptions): Promise<SearchResults>;
    searchGuildMessages(guildID: string, query: SearchOptions): Promise<SearchResults>;
    on(event: string, listener: Function): this;
    on(event: "callCreate", listener: (call: Call) => void): this;
    on(event: "callDelete", listener: (call: Call) => void): this;
    on(event: "callRing", listener: (call: Call) => void): this;
    on(event: "callUpdate", listener: (call: Call, oldCall: { participants: Array<string>, endedTimestamp?: number, ringing: Array<string>, region: string, unavailable: boolean }) => void): this;
    on(event: "channelCreate", listener: (channel: Channel) => void): this;
    on(event: "channelDelete", listener: (channel: Channel) => void): this;
    on(event: "channelPinUpdate", listener: (channel: Channel, timestamp: number, oldTimestamp: number) => void): this;
    on(event: "channelRecipientAdd", listener: (channel: GroupChannel, user: User) => void): this;
    on(event: "channelRecipientRemove", listener: (channel: GroupChannel, user: User) => void): this;
    on(event: "channelUpdate", listener: (channel: Channel, oldChannel: { name: string, position: string, topic?: string, bitrate?: number, permissionOverwrites: Collection<PermissionOverwrite> }) => void): this;
    on(event: "connect", listener: (id: number) => void): this;
    on(event: "debug", listener: (message: string, id: number) => void): this;
    on(event: "error", listener: (err: Error, id: number) => void): this;
    on(event: "friendSuggestionCreate", listener: (user: User, reasons: Array<{ type: number, platform_type: string, name: string }>) => void): this;
    on(event: "friendSuggestionDelete", listener: (user: User) => void): this;
    on(event: "guildAvailable", listener: (guild: Guild) => void): this;
    on(event: "guildBanAdd", listener: (guild: Guild, user: User) => void): this;
    on(event: "guildBanRemove", listener: (guild: Guild, user: User) => void): this;
    on(event: "guildCreate", listener: (guild: Guild) => void): this;
    on(event: "guildDelete", listener: (guild: Guild) => void): this;
    on(event: "guildEmojisUpdate", listener: (guild: Guild, emojis: Array<Emoji>, oldEmojis: Array<Emoji>) => void): this;
    on(event: "guildMemberAdd", listener: (guild: Guild, member: Member) => void): this;
    on(event: "guildMemberChunk", listener: (guild: Guild, members: Array<Member>) => void): this;
    on(event: "guildMemberRemove", listener: (guild: Guild, member: Member | { id: string, user: User }) => void): this;
    on(event: "guildMemberUpdate", listener: (guild: Guild, member: Member, oldMember: { roles: Array<string>, nick?: string }) => void): this;
    on(event: "guildRoleCreate", listener: (guild: Guild, role: Role) => void): this;
    on(event: "guildRoleDelete", listener: (guild: Guild, role: Role) => void): this;
    on(event: "guildRoleUpdate", listener: (guild: Guild, role: Role, oldRole: RoleOptions) => void): this;
    on(event: "guildUnavailable", listener: (guild: Guild) => void): this;
    on(event: "guildUpdate", listener: (guild: Guild, oldGuild: GuildOptions) => void): this;
    on(event: "messageCreate", listener: (message: Message) => void): this;
    on(event: "messageDelete", listener: (message: PossiblyUncachedMessage) => void): this;
    on(event: "messageDeleteBulk", listener: (messages: Array<PossiblyUncachedMessage>) => void): this;
    on(event: "messageReactionAdd", listener: (message: PossiblyUncachedMessage, emoji: Emoji, userID: string) => void): this;
    on(event: "messageReactionRemove", listener: (message: PossiblyUncachedMessage, emoji: Emoji, userID: string) => void): this;
    on(event: "messageReactionRemoveAll", listener: (message: PossiblyUncachedMessage) => void): this;
    on(event: "messageUpdate", listener: (message: Message, oldMessage?: {
      attachments: Array<Attachment>,
      embeds: Array<Embed>,
      content: string,
      editedTimestamp?: number,
      mentionedBy?: any,
      tts: boolean,
      mentions: Array<string>,
      roleMentions: Array<string>,
      channelMentions: Array<string>
    }) => void): this;
    on(event: "presenceUpdate", listener: (other: Member | Relationship, oldPresence?: {
      status: string,
      game?: {
        name: string,
        type: number,
        url?: string
      }
    }) => void): this;
    on(event: "rawWS", listener: (packet: RawPacket, id: number) => void): this;
    on(event: "relationshipAdd", listener: (relationship: Relationship) => void): this;
    on(event: "relationshipRemove", listener: (relationship: Relationship) => void): this;
    on(event: "relationshipUpdate", listener: (relationship: Relationship, oldRelationship: { type: number } ) => void): this;
    on(event: "shardDisconnect", listener: (err: Error, id: number) => void): this;
    on(event: "shardPreReady", listener: (id: number) => void): this;
    on(event: "shardReady", listener: (id: number) => void): this;
    on(event: "shardResume", listener: (id: number) => void): this;
    on(event: "typingStart", listener: (channel: Channel, user: User) => void): this;
    on(event: "unavailableGuildCreate", listener: (guild: UnavailableGuild) => void): this;
    on(event: "unknown", listener: (packet: RawPacket, id: number) => void): this;
    on(event: "userUpdate", listener: (user: User, oldUser: { username: string, discriminator: string, avatar?: string }) => void): this;
    on(event: "voiceChannelJoin", listener: (member: Member, newChannel: GuildChannel) => void): this;
    on(event: "voiceChannelLeave", listener: (member: Member, oldChannel: GuildChannel) => void): this;
    on(event: "voiceChannelSwitch", listener: (member: Member, newChannel: GuildChannel, oldChannel: GuildChannel) => void): this;
    on(event: "voiceStateUpdate", listener: (member: Member, oldState: { mute: boolean, deaf: boolean, selfMute: boolean, selfDeaf: boolean }) => void): this;
    on(event: "warn", listener: (message: string, id: number) => void): this;
  }

  export class VoiceConnection extends EventEmitter {
    id: string;
    channelID: string;
    connecting: boolean;
    ready: boolean;
    playing: boolean;
    paused: boolean;
    volume: number;
    current?: {
      startTime: number,
      playTime: number,
      pausedTimestamp?: number,
      pausedTime?: number,
      options: VoiceResourceOptions
    }
    constructor(id: string, options?: { shard?: Shard, shared?: boolean, opusOnly?: boolean });
    pause(): void;
    play(resource: ReadableStream | string, options: VoiceResourceOptions): void;
    receive(type: string): VoiceDataStream;
    resume(): void;
    setVolume(volume: number): void;
    stopPlaying(): void;
    switchChannel(channelID: string): void;
    updateVoiceState(selfMute: boolean, selfDeaf: boolean): void;
    on(event: string, listener: Function): this;
    on(event: "debug", listener: (message: string) => void): this;
    on(event: "disconnect", listener: (err: Error) => void): this;
    on(event: "error", listener: (err: Error) => void): this;
    on(event: "pong", listener: (latency: number) => void): this;
    on(event: "speakingStart", listener: (userID: string) => void): this;
    on(event: "warn", listener: (message: string) => void): this;
  }

  export class SharedStream extends EventEmitter {
    add(connection: VoiceConnection): void;
    play(resource: ReadableStream | string, options: VoiceResourceOptions): void;
    remove(connection: VoiceConnection): void;
    stopPlaying(): void;
  }

  class VoiceDataStream {
    type: string;
    constructor(type: string);
  }

  export class VoiceConnectionManager<T extends VoiceConnection> extends Collection<T> { // owo an undocumented class
    constructor(vcObject: new () => T);
    join(guildID: string, channelID: string, options: VoiceResourceOptions): Promise<VoiceConnection>;
    leave(guildID: string): void;
    switch(guildID: string, channelID: string): void;
  }

  class Base {
    id: string;
    createdAt: number;
    constructor(id: string);
    toJSON(arg: any, cache: Array<string | any>): { [s: string]: any }; // TODO is `arg` even used
    inspect(): this;
  }

  export class Bucket {
    tokens: number;
    lastReset: number;
    lastSend: number;
    tokenLimit: number;
    interval: number;
    constructor(tokenLimit: number, interval: number, latencyRef: { latency: number });
    queue(func: Function): void;
  }

  export class Collection<T extends { id: string }> extends Map<string, T> {
    baseObject: new () => T;
    limit?: number;
    constructor(baseObject: new () => T, limit?: number);
    add(obj: T, extra?: any, replace?: boolean): T;
    find(func: (i: T) => boolean): T;
    random(): T;
    filter(func: (i: T) => boolean): Array<T>;
    map<R>(func: (i: T) => R): Array<R>;
    update(obj: T, extra?: any, replace?: boolean): T;
    remove(obj: T | { id: string }): T;
  }

  export class Call extends Base {
    id: string;
    createdAt: number;
    channel: GroupChannel;
    voiceStates: Collection<VoiceState>;
    participants: Array<string>;
    endedTimestamp?: number;
    ringing?: Array<string>;
    region?: string;
    unavailable: boolean;
    constructor(data: BaseData, channel: GroupChannel);
  }

  export class Channel extends Base {
    id: string;
    createdAt: number;
    constructor(data: BaseData);
    sentTyping(): Promise<void>;
    getMessage(messageID: string): Promise<Message>;
    getMessages(limit?: number, before?: string, after?: string, around?: string): Promise<Array<Message>>;
    getPins(): Promise<Array<Message>>;
    createMessage(
      content: MessageContent,
      file?: MessageFile
    ): Promise<Message>;
    editMessage(messageID: string, content: MessageContent): Promise<Message>;
    pinMessage(messageID: string): Promise<void>;
    unpinMessage(messageID: string): Promise<void>;
    getMessageReaction(messageID: string, reaction: string, limit?: number): Promise<Array<User>>;
    addMessageReaction(messageID: string, reaction: string, userID?: string): Promise<void>;
    removeMessageReaction(messageID: string, reaction: string, userID?: string): Promise<void>;
    removeMessageReactions(messageID: string): Promise<void>;
    deleteMessage(messageID: string, reason?: string): Promise<void>;
    unsendMessage(messageID: string): Promise<void>;
  }

  export class ExtendedUser extends User {
    email: string;
    verified: boolean;
    mfaEnabled: boolean;
  }

  export class GroupChannel extends PrivateChannel {
    recipients: Collection<User>;
    name: string;
    icon?: string;
    iconURL?: string;
    ownerID: string;
    edit(options: { name?: string, icon?: string, ownerID?: string }): Promise<GroupChannel>;
    addRecipient(userID: string): Promise<void>;
    removeRecipient(userID: string): Promise<void>;
    dynamicIconURL(format: string, size: number): string;
  }

  export class Guild extends Base {
    id: string;
    createdAt: number;
    name: string;
    verificationLevel: number;
    region: string;
    defaultChannel: GuildChannel;
    icon?: string;
    afkChannelID: string;
    afkTimeout: number;
    defaultNotifications: number;
    mfaLevel: number;
    joinedAt: number;
    ownerID: string;
    splash?: string;
    unavailable: boolean;
    large: boolean;
    maxPresences: number;
    channels: Collection<GuildChannel>;
    members: Collection<Member>;
    memberCount: number;
    roles: Collection<Role>;
    shard: Shard;
    features: Array<string>;
    emojis: Array<Emoji>;
    iconURL?: string;
    explicitContentFilter: number;
    constructor(data: BaseData, client: Client);
    fetchAllMembers(): void;
    dynamicIconURL(format: string, size: number): string;
    createChannel(name: string, type: string): Promise<GuildChannel>;
    createEmoji(options: { name: string, image: string, roles?: Array<string> }, reason?: string): Promise<EmojiOptions>;
    editEmoji(emojiID: string, options: { name: string, roles?: Array<string> }, reason?: string): Promise<EmojiOptions>;
    deleteEmoji(emojiID: string, reason?: string): Promise<void>;
    createRole(options: RoleOptions, reason?: string): Promise<Role>;
    getPruneCount(days: number): Promise<number>;
    pruneMembers(days: number, reason?: string): Promise<number>;
    getRESTChannels(): Promise<Array<GuildChannel>>;
    getRESTEmojis(): Promise<Array<Emoji>>;
    getRESTEmoji(emojiID: string): Promise<Emoji>;
    getRESTMembers(limit?: number, after?: string): Promise<Array<Member>>;
    getRESTMember(memberID: string): Promise<Member>;
    getRESTRoles(): Promise<Array<Role>>;
    getEmbed(): Promise<GuildEmbed>;
    getVoiceRegions(): Promise<Array<VoiceRegion>>;
    editRole(roleID: string, options: RoleOptions): Promise<Role>;
    deleteRole(roleID: string): Promise<void>;
    getAuditLogs(limit?: number, before?: string, actionType?: number): Promise<GuildAuditLog>;
    getIntegrations(): Promise<GuildIntegration>;
    editIntegration(integrationID: string, options: IntegrationOptions): Promise<void>;
    syncIntegration(integrationID: string): Promise<void>;
    deleteIntegration(integrationID: string): Promise<void>;
    getInvites(): Promise<Array<Invite>>;
    editMember(memberID: string, options: MemberOptions, reason?: string): Promise<void>;
    addMemberRole(memberID: string, roleID: string, reason?: string): Promise<void>;
    removeMemberRole(memberID: string, roleID: string, reason?: string): Promise<void>;
    kickMember(userID: string, reason?: string): Promise<void>;
    banMember(userID: string, deleteMessageDays?: number, reason?: string): Promise<void>;
    unbanMember(userID: string, reason?: string): Promise<void>;
    edit(
      options: GuildOptions, reason?: string
    ): Promise<Guild>;
    delete(): Promise<void>;
    leave(): Promise<void>;
    getBans(): Promise<Array<User>>;
    editNickname(nick: string): Promise<void>;
    getWebhooks(): Promise<Array<Webhook>>;
  }

  export class GuildAuditLogEntry extends Base {
    id: string;
    guild: Guild;
    actionType: number;
    reason?: string;
    user: User;
    targetID: string;
    target?: Guild | GuildChannel | Member | Invite | Role | any;
    before?: any;
    after?: any;
    count?: number;
    channel?: GuildChannel;
    deleteMemberDays?: number;
    membersRemoved?: number;
    member?: Member | any;
    role?: Role | any;
    constructor(data: BaseData, guild: Guild);
  }

  export class GuildChannel extends Channel {
    mention: string;
    guild: Guild;
    messages: Collection<Message>;
    lastMessageID: string;
    lastPinTimestamp: number;
    permissionOverwrites: Collection<PermissionOverwrite>;
    type: number;
    name: string;
    position: number;
    topic?: string;
    bitrate?: number;
    userLimit?: number;
    nsfw: boolean;
    voiceMembers?: Collection<Member>;
    constructor(data: BaseData, guild: Guild, messageLimit: number);
    permissionsOf(memberID: string): Permission;
    edit(
      options: {
        name: string,
        topic: string,
        bitrate: number,
        userLimit: number
      }, reason?: string
    ): Promise<GuildChannel>;
    editPosition(position: number): Promise<void>;
    delete(reason?: string): Promise<void>;
    editPermission(overwriteID: string, allow: number, deny: number, type: string, reason?: string): Promise<PermissionOverwrite>;
    deletePermission(overwriteID: string, reason?: string): Promise<void>;
    getInvites(): Promise<Array<Invite>>;
    createInvite(options: { maxAge: number, maxUses: number, temporary: boolean }, reason?: string): Promise<Invite>;
    getWebhooks(): Promise<Array<Webhook>>;
    createWebhook(options: { name: string, avatar: string }, reason?: string): Promise<Webhook>;
    deleteMessages(messageIDs: Array<string>): Promise<void>;
    purge(limit?: number, filter?: (m: Message) => boolean, before?: string, after?: string): Promise<number>;
  }

  export class GuildIntegration extends Base {
    id: string;
    createdAt: number;
    name: string;
    type: string;
    roleID: string;
    user: User;
    account: { id: string, name: string };
    enabled: boolean;
    syncing: boolean;
    expireBehavior: number;
    expireGracePeriod: number;
    enableEmoticons: boolean;
    subscriberCount: number;
    syncedAt: number;
    constructor(data: BaseData, guild: Guild);
    edit(options: { expireBehavior: string, expireGracePeriod: string, enableEmoticons: string }): Promise<void>;
    delete(): Promise<void>;
    sync(): Promise<void>;
  }

  export class Invite {
    code: string;
    channel: { id: string, name: string };
    guild: { id: string, name: string, splash?: string, icon?: string, textChannelCount?: number, voiceChannelCount?: number };
    inviter?: User;
    uses?: number;
    maxUses?: number;
    maxAge?: number;
    temporary?: boolean;
    createdAt?: number;
    revoked?: boolean;
    presenceCount?: number;
    memberCount?: number;
    constructor(data: BaseData, client: Client);
    delete(reason?: string): Promise<void>;
  }

  export class Member extends Base {
    id: string;
    mention: string;
    guild: Guild;
    joinedAt: number;
    status: string;
    game?: GamePresence;
    voiceState: VoiceState;
    nick?: string;
    roles: Array<string>;
    user: User;
    permission: Permission;
    defaultAvatar: string;
    createdAt: number;
    bot: boolean;
    username: string;
    discriminator: string;
    avatar?: string;
    defaultAvatarURL: string;
    avatarURL: string;
    staticAvatarURL: string;
    constructor(data: BaseData, guild: Guild);
    edit(
      options: MemberOptions, reason?: string
    ): Promise<void>;
    addRole(roleID: string, reason?: string): Promise<void>;
    removeRole(roleID: string, reason?: string): Promise<void>;
    kick(reason?: string): Promise<void>;
    ban(deleteMessageDays?: number, reason?: string): Promise<void>;
    unban(reason?: string): Promise<void>;
  }

  export class Message extends Base {
    id: string;
    createdAt: number;
    channel: Channel;
    guild?: Guild;
    timestamp: number;
    type: number;
    author: User;
    member?: Member;
    mentions: Array<User>;
    content: string;
    cleanContent?: string;
    roleMentions: Array<string>;
    channelMentions?: Array<string>;
    editedTimestamp?: number;
    tts: boolean;
    mentionEveryone: boolean;
    attachments: Array<Attachment>;
    embeds: Array<Embed>;
    reactions: { [s: string]: any, count: number, me: boolean };
    command: Command;
    constructor(data: BaseData, client: Client);
    edit(content: MessageContent): Promise<Message>;
    pin(): Promise<void>;
    unpin(): Promise<void>;
    getReaction(reaction: string, limit?: number): Promise<Array<User>>;
    addReaction(reaction: string, userID?: string): Promise<void>;
    removeReaction(reaction: string, userID?: string): Promise<void>;
    removeReactions(): Promise<void>;
    delete(reason?: string): Promise<void>;
  }

  export class Permission {
    allow: number;
    deny: number;
    json: { [s: string]: boolean };
    constructor(allow: number, deny: number);
    has(permission: string): boolean;
  }

  export class PermissionOverwrite extends Permission {
    id: string;
    createdAt: number;
    type: string;
    constructor(data: { allow: number, deny: number });
  }

  export class PrivateChannel extends Channel {
    lastMessageID: string;
    recipient: User;
    messages: Collection<Message>;
    ring(recipient: Array<string>): void;
    syncCall(): void;
    leave(): Promise<void>;
  }

  export class Relationship {
    id: string;
    user: User;
    type: number;
    status: string;
    game?: GamePresence;
    constructor(data: BaseData, client: Client);
  }

  export class Role extends Base {
    id: string;
    createdAt: number;
    guild: Guild;
    mention: string;
    name: string;
    mentionable: boolean;
    managed: boolean;
    hoist: boolean;
    color: number;
    position: number;
    permissions: Permission;
    json: { [s: string]: boolean };
    constructor(data: BaseData, guild: Guild);
    edit(options: RoleOptions, reason?: string): Promise<Role>;
    editPosition(position: number): Promise<void>;
    delete(reason?: string): Promise<void>;
  }

  export class UnavailableGuild extends Base {
    id: string;
    createdAt: number;
    unavailable: boolean;
    shard: Shard;
    constructor(data: BaseData, client: Client);
  }

  export class User extends Base {
    id: string;
    mention: string;
    defaultAvatar: string;
    createdAt: number;
    bot: boolean;
    username: string;
    discriminator: string;
    avatar?: string;
    defaultAvatarURL: string;
    avatarURL: string;
    staticAvatarURL: string;
    constructor(data: BaseData, client: Client);
    dynamicIconURL(format?: string, size?: number): string;
    getDMChannel(): Promise<PrivateChannel>;
    addRelationship(block?: boolean): Promise<void>;
    removeRelationship(): Promise<void>;
    getProfile(): Promise<UserProfile>;
    editNote(note: string): Promise<void>;
    deleteNote(): Promise<void>;
  }

  export class VoiceState extends Base {
    id: string;
    createdAt: number;
    sessionID?: string;
    channelID?: string;
    mute: boolean;
    deaf: boolean;
    suppress: boolean;
    selfMute: boolean;
    selfDeaf: boolean;
    constructor(data: BaseData);
  }

  export class Shard extends EventEmitter {
    id: string;
    connecting: boolean;
    ready: boolean;
    discordServerTrace?: Array<string>;
    status: string;
    lastHeartbeatReceived: number;
    lastHeartbeatSent: number;
    latency: number;
    constructor(id: number, client: Client);
    connect(): void;
    disconnect(options?: { reconnect: boolean }): void;
    editAFK(afk: boolean): void;
    editStatus(status?: string, game?: GamePresence): void;
    on(event: string, listener: Function): this;
    on(event: "disconnect", listener: (err: Error) => void): this;
  }

  // TODO: Do we need all properties of Command, as it has a lot of stuff
  export class Command {
    subcommands: { [s: string]: Command };
    constructor(label: string, generate: CommandGenerator, options?: CommandOptions);
    registerSubcommandAlias(alias: string, label: string): void;
    registerSubcommand(label: string, generator: CommandGenerator, options?: CommandOptions): void;
    unregisterSubcommand(label: string): void;
  }

  export class CommandClient extends Client {
    commands: { [s: string]: Command };
    constructor(token: string, options?: ClientOptions, commandOptions?: CommandClientOptions);
    onMessageCreate(msg: Message): void;
    registerGuildPrefix(guildID: string, prefix: Array<string> | string): void;
    registerCommandAlias(alias: string, label: string): void;
    registerCommand(label: string, generator: CommandGenerator, options?: CommandOptions): void;
    unregisterCommand(label: string): void;
  }
}


text:
<?php

namespace Jaguar\Tests\Action;

use Jaguar\Action\Sharpen;

class SharpenTest extends AbstractActionTest
{

    public function getAction()
    {
        return new Sharpen();
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testSetTypeThrowInvalidArgumentException()
    {
        $this->getAction()->setType('Foo Type');
    }

    public function testApply()
    {
        $this->assertInstanceOf(
                '\Jaguar\Action\Sharpen'
                , $this->getAction()->apply($this->getCanvas())
        );
    }

}

redpajama_set_name: RedPajamaGithub


text:
import React from "react";
import styled from "styled-components";
import PropTypes from "prop-types";

import IconDelete from "./icon-delete.svg?inline";
import Button from "components/Button";
import IconText from "components/IconText";
import Tooltip from "components/Tooltip";

const DeleteButton = styled(Button).attrs({
  variant: "tertiary",
  small: true
})`
  .lid {
    transform-origin: 50% 50%;
    transition: all 200ms ease-out;
  }

  &:focus,
  &:hover {
    .lid {
      transform: translateY(-1px) rotate(6deg);
    }
  }
`;

const DeleteTooltip = ({ children }) => (
  <Tooltip content="Delete" place="top" offset={{ top: 0, bottom: 10 }}>
    {children}
  </Tooltip>
);

const IconButtonDelete = ({ hideText, iconText = "Delete", ...otherProps }) => {
  const Wrapper = hideText ? DeleteTooltip : React.Fragment;
  return (
    <Wrapper>
      <DeleteButton title="Delete" {...otherProps}>
        <IconText icon={IconDelete} hideText={hideText}>
          {iconText}
        </IconText>
      </DeleteButton>
    </Wrapper>
  );
};
DeleteTooltip.propTypes = {
  children: PropTypes.node.isRequired
};

IconButtonDelete.propTypes = {
  hideText: PropTypes.bool
};

IconButtonDelete.defaultProps = {
  hideText: false
};

export default IconButtonDelete;


text:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Nest.Litterateur.Documentation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Nest.Litterateur.Documentation.Blocks;

namespace Nest.Litterateur.Walkers
{
	class CodeWithDocumentationWalker : CSharpSyntaxWalker
	{
		public List<IDocumentationBlock> Blocks { get; } = new List<IDocumentationBlock>();
		public List<TextBlock> TextBlocks { get; } = new List<TextBlock>();

		private bool _firstVisit = true;
		private string _code;
		public int ClassDepth { get; }
		private readonly int? _lineNumberOverride;

		/// <summary>
		/// We want to support inlining /** */ documentations because its super handy
		/// to document fluent code, what ensues is total hackery
		/// </summary>
		/// <param name="classDepth"></param>
		/// <param name="lineNumber">line number used for sorting</param>
		public CodeWithDocumentationWalker(int classDepth = 1, int? lineNumber = null) : base(SyntaxWalkerDepth.StructuredTrivia)
		{
			ClassDepth = classDepth;
			_lineNumberOverride = lineNumber;
		}

		public override void Visit(SyntaxNode node)
		{
			if (_firstVisit)
			{
				_firstVisit = false;

				var repeatedTabs = 2 + ClassDepth;
				_code = node.WithoutLeadingTrivia().WithTrailingTrivia().ToFullString();

				// find x or more repeated tabs and trim x number of tabs from the start
				_code = Regex.Replace(_code, $"\t{{{repeatedTabs},}}", match => match.Value.Substring(repeatedTabs));

				var nodeLine = node.SyntaxTree.GetLineSpan(node.Span).StartLinePosition.Line;

				var line = _lineNumberOverride ?? nodeLine;

				var codeBlocks = Regex.Split(_code, @"\/\*\*.*?\*\/", RegexOptions.Singleline)
					.Select(b => b.TrimStart('\r', '\n').TrimEnd('\r', '\n', '\t'))
					.Where(b => !string.IsNullOrEmpty(b) && b != ";")
					.Select(b=>new CodeBlock(b, line))
					.ToList();

				base.Visit(node);

				var nodeHasLeadingTriva = node.HasLeadingTrivia && node.GetLeadingTrivia()
					.Any(c=>c.Kind() == SyntaxKind.MultiLineDocumentationCommentTrivia);
				var blocks = codeBlocks.Intertwine<IDocumentationBlock>(this.TextBlocks, swap: nodeHasLeadingTriva);
				this.Blocks.Add(new CombinedBlock(blocks, line));
				return;
			}

			base.Visit(node);
		}

		public override void VisitBlock(BlockSyntax node)
		{
			if (_firstVisit)
			{
				_firstVisit = false;
				foreach (var statement in node.Statements)
				{
					var leadingTabs = new string('\t', 3 + ClassDepth);
					SyntaxNode formattedStatement = statement;

					_code = formattedStatement.WithoutLeadingTrivia().WithTrailingTrivia().ToFullString().Replace(leadingTabs, string.Empty);

					var nodeLine = formattedStatement.SyntaxTree.GetLineSpan(node.Span).StartLinePosition.Line;

					var line = _lineNumberOverride ?? nodeLine;

					var codeBlocks = Regex.Split(_code, @"\/\*\*.*?\*\/", RegexOptions.Singleline)
						.Select(b => b.TrimStart('\r', '\n').TrimEnd('\r', '\n', '\t'))
						.Where(b => !string.IsNullOrEmpty(b) && b != ";")
						.Select(b => new CodeBlock(b, line))
						.ToList();

					this.Blocks.AddRange(codeBlocks);
				}

				base.Visit(node);
			}
		}

		public override void VisitXmlText(XmlTextSyntax node)
		{
			var nodeLine = node.SyntaxTree.GetLineSpan(node.Span).StartLinePosition.Line;
			var line = _lineNumberOverride ?? nodeLine;
			var text = node.TextTokens
				.Where(n => n.Kind() == SyntaxKind.XmlTextLiteralToken)
				.Aggregate(new StringBuilder(), (a, t) => a.AppendLine(t.Text.TrimStart()), a => a.ToString());

			this.TextBlocks.Add(new TextBlock(text, line));

			base.VisitXmlText(node);
		}

	}
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package rlVizLib.general;

/**
 *
 * @author btanner
 */
public interface hasVersionDetails {
    public String getName();
    public String getShortName();
    public String getAuthors();
    public String getInfoUrl();
    public String getDescription();

}


text:
<?php

namespace Loevgaard\DandomainAltapayBundle\Entity;

class WebhookExchangeRepository extends EntityRepository
{
    /**
     * This method will find the webhook exchange with the given URL
     * If it doesn't exist it will create it.
     *
     * @param string $url
     *
     * @return WebhookExchange
     */
    public function findByUrlOrCreate(string $url): WebhookExchange
    {
        /** @var WebhookExchange $obj */
        $obj = $this->findOneBy([
            'url' => $url,
        ]);

        if (!$obj) {
            $obj = new WebhookExchange($url);
            $this->save($obj);
        }

        return $obj;
    }
}


text:
package org.ajprax.serialization.schema.impl;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import com.google.common.base.MoreObjects;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.ajprax.serialization.schema.Schema;

/** Helper methods for recursive Schema operations. */
public final class SchemaRecursionHelpers {

  /** Unordered pair of Schemas. Equality is tested by reference rather than value. */
  private static final class SchemaPair {
    private final Schema mLeft;
    private final Schema mRight;

    private SchemaPair(
        final Schema left,
        final Schema right
    ) {
      mLeft = left;
      mRight = right;
    }

    @Override
    public String toString() {
      return MoreObjects.toStringHelper(getClass())
          .add("left", mLeft)
          .add("right", mRight)
          .toString();
    }

    @Override
    public int hashCode() {
      return Objects.hash(mLeft, mRight);
    }

    @Override
    public boolean equals(
        final Object obj
    ) {
      // TODO: Consider removing these safety checks to improve performance.
      // This is a private class which is never called with null values or values of other types.
      if (obj == null || !obj.getClass().equals(getClass())) {
        return false;
      } else {
        final SchemaPair that = (SchemaPair) obj;
        return (this.mLeft == that.mLeft && this.mRight == that.mRight)
            || (this.mLeft == that.mRight && this.mRight == that.mLeft);
      }
    }
  }

  private SchemaRecursionHelpers() { }

  private static boolean equals(
      final Schema left,
      final Schema right,
      final Map<SchemaPair, Optional<Boolean>> knownPairs
  ) {
    if (left == right) {
      return true;
    } else if (left == null || right == null || !Objects.equals(left.getType(), right.getType())) {
      return false;
    } else {
      final SchemaPair pair = new SchemaPair(left, right);
      final Optional<Boolean> knownEquals = knownPairs.get(pair);
      if (knownEquals != null) {
        // TODO is it ever possible to get into a situation where we are comparing two schemas we
        // know to be unequal within a single schema graph comparison? Should a single false
        // short circuit the entire process? In other words, can knownEquals ever contain false?
        // if absent, recursive comparison in progress, break recursion.
        return knownEquals.orElse(true);
      } else {
        switch(left.getType()) {
          case UNSIGNED_8:
          case UNSIGNED_16:
          case UNSIGNED_32:
          case UNSIGNED_64:
          case UNSIGNED_BIG:
          case SIGNED_8:
          case SIGNED_16:
          case SIGNED_32:
          case SIGNED_64:
          case SIGNED_BIG:
          case FLOAT_32:
          case FLOAT_64:
          case FLOAT_BIG:
          case BOOLEAN:
          case STRING: {
            // primitive schemas are equal if their types are equal.
            knownPairs.put(pair, Optional.of(true));
            return true;
          }
          case ENUM: {
            // enum schemas are equal if their name and value sets are equal.
            final boolean equal = Objects.equals(left.getName(), right.getName())
                && Objects.equals(left.getEnumSymbols(), right.getEnumSymbols());
            knownPairs.put(pair, Optional.of(equal));
            return equal;
          }
          case EXTENSION: {
            // extension schemas are equal if their tag schemas are equal.
            knownPairs.put(pair, Optional.empty());
            final boolean equal = equals(left.getTagSchema(), right.getTagSchema(), knownPairs);
            knownPairs.put(pair, Optional.of(equal));
            return equal;
          }
          case ARRAY: {
            // array schemas are equal if their element schemas are equal.
            knownPairs.put(pair, Optional.empty());
            final boolean equal = equals(left.getElementSchema(), right.getElementSchema(), knownPairs);
            knownPairs.put(pair, Optional.of(equal));
            return equal;
          }
          case FIXED_SIZE_ARRAY: {
            // fixed size array schema are equal if their size and element schemas are equal.
            knownPairs.put(pair, Optional.empty());
            final boolean equal = left.getSize() == right.getSize()
                && equals(left.getElementSchema(), right.getElementSchema(), knownPairs);
            knownPairs.put(pair, Optional.of(equal));
            return equal;
          }
          case SET: {
            // set schemas are equal if their element schemas are equal.
            knownPairs.put(pair, Optional.empty());
            final boolean equal = equals(left.getElementSchema(), right.getElementSchema(), knownPairs);
            knownPairs.put(pair, Optional.of(equal));
            return equal;
          }
          case MAP: {
            // map schemas are equal if the key and value schemas are equal.
            knownPairs.put(pair, Optional.empty());
            final boolean equal = equals(left.getKeySchema(), right.getKeySchema(), knownPairs)
                && equals(left.getValueSchema(), right.getValueSchema(), knownPairs);
            knownPairs.put(pair, Optional.of(equal));
            return equal;
          }
          case UNION: {
            // union schemas are equal if their branch schemas are equal.
            knownPairs.put(pair, Optional.empty());
            final List<Schema> leftBranchSchemas = left.getBranchSchemas();
            final List<Schema> rightBranchSchemas = right.getBranchSchemas();
            boolean equal = leftBranchSchemas.size() == rightBranchSchemas.size();
            for (int i = 0; i < leftBranchSchemas.size(); i++) {
              equal = equal && equals(leftBranchSchemas.get(i), rightBranchSchemas.get(i), knownPairs);
            }
            knownPairs.put(pair, Optional.of(equal));
            return equal;
          }
          case OPTIONAL: {
            // optional schemas are equal if their element schemas are equal.
            knownPairs.put(pair, Optional.empty());
            final boolean equal = equals(left.getElementSchema(), right.getElementSchema(), knownPairs);
            knownPairs.put(pair, Optional.of(equal));
            return equal;
          }
          case RECORD: {
            // record schemas are equal if their names are equal and their field names and schemas are equal.
            knownPairs.put(pair, Optional.empty());
            final Map<String, Schema> leftFieldSchemas = left.getFieldSchemas();
            final Map<String, Schema> rightFieldSchemas = right.getFieldSchemas();
            boolean equal = Objects.equals(leftFieldSchemas.keySet(), rightFieldSchemas.keySet());
            for (String fieldName : leftFieldSchemas.keySet()) {
              equal = equal && equals(leftFieldSchemas.get(fieldName), rightFieldSchemas.get(fieldName), knownPairs);
            }
            knownPairs.put(pair, Optional.of(equal));
            return equal;
          }
          default: throw new RuntimeException(String.format("Unknown schema type: '%s'", left.getType()));
        }
      }
    }
  }

  private static String toString(
      final Schema schema,
      final Map<Schema, Optional<String>> knownSchemas
  ) {
    final Optional<String> knownToString = knownSchemas.get(schema);
    if (knownToString != null) {
      // if absent, recursive toString in progress, break recursion.
      return knownToString.orElse(schema.getName());
    } else {
      knownSchemas.put(schema, Optional.empty());
      switch (schema.getType()) {
        case UNSIGNED_8:
        case UNSIGNED_16:
        case UNSIGNED_32:
        case UNSIGNED_64:
        case UNSIGNED_BIG:
        case SIGNED_8:
        case SIGNED_16:
        case SIGNED_32:
        case SIGNED_64:
        case SIGNED_BIG:
        case FLOAT_32:
        case FLOAT_64:
        case FLOAT_BIG:
        case BOOLEAN:
        case STRING: {
          final String toString = MoreObjects.toStringHelper(schema.getClass())
              .add("type", schema.getType())
              .toString();
          knownSchemas.put(schema, Optional.of(toString));
          return toString;
        }
        case ENUM: {
          final String toString = MoreObjects.toStringHelper(schema.getClass())
              .add("type", schema.getType())
              .add("name", schema.getName())
              .add("values", schema.getEnumSymbols())
              .toString();
          knownSchemas.put(schema, Optional.of(toString));
          return toString;
        }
        case EXTENSION: {
          final String toString = MoreObjects.toStringHelper(schema.getClass())
              .add("type", schema.getType())
              .add("tag_schema", toString(schema.getTagSchema(), knownSchemas))
              .toString();
          knownSchemas.put(schema, Optional.of(toString));
          return toString;
        }
        case ARRAY: {
          final String toString = MoreObjects.toStringHelper(schema.getClass())
              .add("type", schema.getType())
              .add("element_schema", toString(schema.getElementSchema(), knownSchemas))
              .toString();
          knownSchemas.put(schema, Optional.of(toString));
          return toString;
        }
        case FIXED_SIZE_ARRAY: {
          final String toString = MoreObjects.toStringHelper(schema.getClass())
              .add("type", schema.getType())
              .add("size", schema.getSize())
              .add("element_schema", toString(schema.getElementSchema(), knownSchemas))
              .toString();
          knownSchemas.put(schema, Optional.of(toString));
          return toString;
        }
        case SET: {
          final String toString = MoreObjects.toStringHelper(schema.getClass())
              .add("type", schema.getType())
              .add("element_schema", toString(schema.getElementSchema(), knownSchemas))
              .toString();
          knownSchemas.put(schema, Optional.of(toString));
          return toString;
        }
        case MAP: {
          final String toString = MoreObjects.toStringHelper(schema.getClass())
              .add("type", schema.getType())
              .add("key_schema", toString(schema.getKeySchema(), knownSchemas))
              .add("value_schema", toString(schema.getValueSchema(), knownSchemas))
              .toString();
          knownSchemas.put(schema, Optional.of(toString));
          return toString;
        }
        case UNION: {
          final String toString = MoreObjects.toStringHelper(schema.getClass())
              .add("type", schema.getType())
              .add(
                  "branch_schemas",
                  Lists.transform(
                      schema.getBranchSchemas(),
                      (Schema branchSchema) -> toString(branchSchema, knownSchemas)
                  )
              )
              .toString();
          knownSchemas.put(schema, Optional.of(toString));
          return toString;
        }
        case OPTIONAL: {
          final String toString = MoreObjects.toStringHelper(schema.getClass())
              .add("type", schema.getType())
              .add("element_schema", toString(schema.getElementSchema(), knownSchemas))
              .toString();
          knownSchemas.put(schema, Optional.of(toString));
          return toString;
        }
        case RECORD: {
          final String toString = MoreObjects.toStringHelper(schema.getClass())
              .add("type", schema.getType())
              .add("name", schema.getName())
              .add(
                  "field_schemas",
                  Maps.transformValues(
                      schema.getFieldSchemas(),
                      (Schema fieldSchema) -> toString(fieldSchema, knownSchemas)
                  )
              )
              .toString();
          knownSchemas.put(schema, Optional.of(toString));
          return toString;
        }
        default: throw new RuntimeException(String.format("Unknown schema type: '%s'.", schema.getType()));
      }
    }
  }

  private static int hashCode(
      final Schema schema,
      final Map<Schema, Optional<Integer>> knownSchemas
  ) {
    final Optional<Integer> knownHashCode = knownSchemas.get(schema);
    if (knownHashCode != null) {
      // if absent, recursive hashCode in progress, break recursion.
      return knownHashCode.orElse(0);
    } else {
      knownSchemas.put(schema, Optional.empty());
      switch (schema.getType()) {
        case UNSIGNED_8:
        case UNSIGNED_16:
        case UNSIGNED_32:
        case UNSIGNED_64:
        case UNSIGNED_BIG:
        case SIGNED_8:
        case SIGNED_16:
        case SIGNED_32:
        case SIGNED_64:
        case SIGNED_BIG:
        case FLOAT_32:
        case FLOAT_64:
        case FLOAT_BIG:
        case BOOLEAN:
        case STRING: {
          final int hashCode = Objects.hashCode(schema.getType());
          knownSchemas.put(schema, Optional.of(hashCode));
          return hashCode;
        }
        case ENUM: {
          final int hashCode = Objects.hash(schema.getType(), schema.getName(), schema.getEnumSymbols());
          knownSchemas.put(schema, Optional.of(hashCode));
          return hashCode;
        }
        case EXTENSION: {
          final int hashCode = Objects.hash(schema.getType(), hashCode(schema.getTagSchema(), knownSchemas));
          knownSchemas.put(schema, Optional.of(hashCode));
          return hashCode;
        }
        case ARRAY: {
          final int hashCode = Objects.hash(schema.getType(), hashCode(schema.getElementSchema(), knownSchemas));
          knownSchemas.put(schema, Optional.of(hashCode));
          return hashCode;
        }
        case FIXED_SIZE_ARRAY: {
          final int hashCode = Objects.hash(schema.getType(), schema.getSize(), hashCode(schema.getElementSchema(), knownSchemas));
          knownSchemas.put(schema, Optional.of(hashCode));
          return hashCode;
        }
        case SET: {
          final int hashCode = Objects.hash(schema.getType(), hashCode(schema.getElementSchema(), knownSchemas));
          knownSchemas.put(schema, Optional.of(hashCode));
          return hashCode;
        }
        case MAP: {
          final int hashCode = Objects.hash(schema.getType(), hashCode(schema.getKeySchema(), knownSchemas), hashCode(schema.getValueSchema()));
          knownSchemas.put(schema, Optional.of(hashCode));
          return hashCode;
        }
        case UNION: {
          final int hashCode = Objects.hash(schema.getType(), Lists.transform(schema.getBranchSchemas(), (Schema branchSchema) -> hashCode(branchSchema, knownSchemas)));
          knownSchemas.put(schema, Optional.of(hashCode));
          return hashCode;
        }
        case OPTIONAL: {
          final int hashCode = Objects.hash(schema.getType(), hashCode(schema.getElementSchema(), knownSchemas));
          knownSchemas.put(schema, Optional.of(hashCode));
          return hashCode;
        }
        case RECORD: {
          final int hashCode = Objects.hash(schema.getType(), schema.getName(), Maps.transformValues(schema.getFieldSchemas(), (Schema fieldSchema) -> hashCode(fieldSchema, knownSchemas)));
          knownSchemas.put(schema, Optional.of(hashCode));
          return hashCode;
        }
        default: throw new RuntimeException(String.format("Unknown schema type: '%s'", schema.getType()));
      }
    }
  }

  /**
   * Create a String representation of a Schema.
   *
   * If the Schema contains a recursive reference, the recursion is broken and a token is included
   * in its place that indicates a loop. Recursive loops are identified according to the rules
   * defined by {@link #equals(org.ajprax.serialization.schema.Schema,
   * org.ajprax.serialization.schema.Schema)}.
   *
   * @param schema Schema for which to get a String representation.
   * @return The given Schema represented as a String.
   */
  public static String toString(
      final Schema schema
  ) {
    return toString(schema, Maps.newHashMap());
  }

  /**
   * Hash a Schema to an integer.
   *
   * If the Schema contains a recursive reference, the recursion is broken and the hash value up to
   * that point is returned. Recursive loops are identified by reference equality. This recursive
   * check may require a deeper traversal than the one defined by
   * {@link #equals(org.ajprax.serialization.schema.Schema, org.ajprax.serialization.schema.Schema)}
   * but equals relies on hashCode to break recursion so that it may use a hash map internally. As a
   * result, `hashCode` must use a more fundamental system to break recursion.
   *
   * @param schema Schema to hash to an integer.
   * @return An integer reduction of the given Schema.
   */
  public static int hashCode(
      final Schema schema
  ) {
    return hashCode(schema, Maps.newIdentityHashMap());
  }

  /**
   * Compare two Schemas for equality.
   *
   * Two Schemas are considered equal if neither contains a recursive reference and their type trees
   * are equal or if both contain recursive references at the same place in their respective type
   * graphs and the graphs are otherwise equal.
   *
   * @param left Left Schema to compare.
   * @param right Right Schema to compare.
   * @return Whether the two Schemas are equal.
   */
  public static boolean equals(
      final Schema left,
      final Schema right
  ) {
    return equals(left, right, Maps.newHashMap());
  }
}


text:
from tournament import *

def test_delete_all_event(test_num):
    delete_all_events()
    c = count_events()
    if type(c) is not long:
        raise TypeError(
            "count_events() should return long value.")
    if c != 0:
        raise ValueError("After deleting, count_events should return zero.")
    print ("{}. All events can be deleted.").format(test_num)

def test_delete_one_event(test_num):
    delete_all_events()
    event_id = register_event("Blitz Tournament", "2015/12/30")
    delete_event(event_id)
    event_id = register_event("Blitz Tournament2", "2015/12/30")
    c = count_events()
    if type(c) is not long:
        raise TypeError(
            "count_events() should return long value.")
    if c != 1:
        raise ValueError("After deleting, count_events should return one.")
    print ("{}. One event can be deleted.").format(test_num)

def test_register_event(test_num):
    delete_all_events()
    register_event("Blitz Tournament", "2015/12/30")
    c = count_events()
    if type(c) is not long:
        raise TypeError(
            "count_events() should return a long value.")
    if c != 1:
        raise ValueError("After one event registered, count_events should \
            return one.")
    print ("{}. After registering an event, count_events() returns 1.")\
            .format(test_num)

def test_delete_players(test_num):
    delete_all_events()
    delete_players()
    c = count_players()
    if type(c) is not long:
        raise TypeError(
            "count_players() should return long value.")
    if c != 0:
        raise ValueError("After deleting, count_players should return zero.")
    print ("{}. All players can be deleted.").format(test_num)

def test_register_player(test_num):
    delete_all_events()
    delete_players()
    register_player("Aristoteles", "Nunez")
    c = count_players()
    if type(c) is not long:
        raise TypeError(
            "count_players() should return long value.")
    if c != 1:
        raise ValueError(
            "After one player registers, count_players() should be 1.")
    print ("{}. After registering a player, count_players() returns 1.")\
            .format(test_num)

def test_add_player_to_event(test_num):
    delete_all_events()
    delete_players()
    event_id = register_event("Blitz Tournament", "2015/12/30")
    player_id = register_player("Aristoteles", "Nunez")
    add_player_to_event(event_id, player_id)
    c = count_players_in_event(event_id)
    if type(c) is not long:
        raise TypeError(
            "count_players() should return long value.")
    if c != 1:
        raise ValueError(
            "After one player adds to an event, count_players_in_event() should be 1.")
    print ("{}. After adding a player, count_players_in_event() returns 1.")\
            .format(test_num)

def test_remove_player_from_event(test_num):
    delete_all_events()
    delete_players()
    event_id = register_event("Blitz Tournament", "2015/12/30")
    player_id = register_player("Aristoteles", "Nunez")
    add_player_to_event(event_id, player_id)
    remove_player_from_event(event_id, player_id)
    c = count_players_in_event(event_id)
    if type(c) is not long:
        raise TypeError(
            "count_players() should return long value.")
    if c != 0:
        raise ValueError(
            "count_players_in_event() should be 0.")
    print ("{}. After removing a player, count_players_in_event() returns 0.")\
            .format(test_num)

def test_delete_all_matches(test_num):
    delete_all_events()
    delete_all_matches()
    print ("{}. All matches can be deleted.").format(test_num)

def test_delete_matches_from_event(test_num):
    delete_all_events()
    event_id = register_event("Blitz Tournament", "2015/12/30")
    delete_matches_from_event(event_id)
    print ("{}. All matches from event can be deleted.").format(test_num)

def test_register_count_delete(test_num):
    delete_all_events()
    delete_all_matches()
    delete_players()
    register_player("Markov", "Chaney")
    register_player("Joe", "Malik")
    register_player("Mao", "Tsu-hsi")
    register_player("Atlanta", "Hope")
    c = count_players()
    if c != 4:
        raise ValueError(
            "After registering four players, count_players should be 4.")
    delete_players()
    c = count_players()
    if c != 0:
        raise ValueError("After deleting, count_players should return zero.")
    print ("{}. Players can be registered and deleted.").format(test_num)

def test_standings_before_matches(test_num):
    delete_all_events()
    delete_all_matches()
    delete_players()
    event_id = register_event("Blitz Tournament", "2015/12/30")
    player1_id = register_player("Melpomene", "Murray")
    player2_id = register_player("Randy", "Schwartz")
    player3_id = register_player("Aristoteles", "Nunez")
    player4_id = register_player("Gary", "Nunez")
    add_player_to_event(event_id, player1_id)
    add_player_to_event(event_id, player4_id)
    standings = player_standings(event_id)
    if len(standings) < 2:
        raise ValueError("Players should appear in player_standings even before "
                         "they have played any matches.")
    elif len(standings) > 2:
        raise ValueError("Only registered players should appear in standings.")
    if len(standings[0]) != 4:
        raise ValueError("Each player_standings row should have four columns.")
    [(id1, name1, wins1, matches1), (id2, name2, wins2, matches2)] = standings
    if matches1 != 0 or matches2 != 0 or wins1 != 0 or wins2 != 0:
        raise ValueError(
            "Newly registered players should have no matches or wins.")
    if set([name1, name2]) != set(["Melpomene Murray", "Gary Nunez"]):
        raise ValueError("Registered players' names should appear in standings, "
                         "even if they have no matches played.")
    print ("{}. Newly registered players appear in the standings with no matches.")\
            .format(test_num)

def test_report_matches(test_num):
    delete_all_events()
    delete_all_matches()
    delete_players()
    event_id = register_event("Blitz Tournament", "2015/12/30")
    player1_id = register_player("Melpomene", "Murray")
    player2_id = register_player("Randy", "Schwartz")
    player3_id = register_player("Aristoteles", "Nunez")
    player4_id = register_player("Gary", "Nunez")
    add_player_to_event(event_id, player1_id)
    add_player_to_event(event_id, player2_id)
    add_player_to_event(event_id, player3_id)
    add_player_to_event(event_id, player4_id)
    standings = player_standings(event_id)
    [id1, id2, id3, id4] = [row[0] for row in standings]
    report_match(event_id, 1, id1, 1.0, id2, 0.0)
    report_match(event_id, 1, id3, 0.0, id4, 1.0)
    standings = player_standings(event_id)
    for (i, n, w, m) in standings:
        if m != 1:
            raise ValueError("Each player should have one match recorded.")
        if i in (id1, id4) and w < 1:
            raise ValueError("Each match winner should have one win recorded.")
        elif i in (id2, id3) and w > 0:
            raise ValueError("Each match loser should have zero wins recorded.")
    print ("{}. After a match, players have updated standings.")\
            .format(test_num)

def test_pairings(test_num):
    delete_all_events()
    delete_all_matches()
    delete_players()
    event_id = register_event("Blitz Tournament", "2015/12/30")
    player1_id = register_player("Twilight", "Sparkle")
    player2_id = register_player("Flutter", "Shy")
    player3_id = register_player("Aristoteles", "Nunez")
    player4_id = register_player("Gary", "Nunez")
    add_player_to_event(event_id, player1_id)
    add_player_to_event(event_id, player2_id)
    add_player_to_event(event_id, player3_id)
    add_player_to_event(event_id, player4_id)
    standings = player_standings(event_id)
    [id1, id2, id3, id4] = [row[0] for row in standings]
    report_match(event_id, 1, id1, 1.0, id2, 0.0)
    report_match(event_id, 1, id3, 1.0, id4, 0.0)
    pairings = swiss_pairings(event_id, 1)
    if len(pairings) != 2:
        raise ValueError(
            "For four players, swissPairings should return two pairs.")
    [(pid1, pname1, pid2, pname2), (pid3, pname3, pid4, pname4)] = pairings
    correct_pairs = set([frozenset([id1, id3]), frozenset([id2, id4])])
    actual_pairs = set([frozenset([pid1, pid2]), frozenset([pid3, pid4])])
    if correct_pairs != actual_pairs:
        raise ValueError(
            "After one match, players with one win should be paired.")
    print ("{}. After one match, players with one win are paired.")\
            .format(test_num)

def test_tournament (test_num):
    delete_all_events()
    delete_all_matches()
    delete_players()
    event_id = register_event("Blitz Tournament", "2015/12/30")
    player1_id = register_player("Twilight", "Sparkle")
    player2_id = register_player("Flutter", "Shy")
    player3_id = register_player("Aristoteles", "Nunez")
    player4_id = register_player("Gary", "Nunez")
    player5_id = register_player("Federico", "Juarez")
    player6_id = register_player("Sahadi", "Urbina")
    player7_id = register_player("Itzel", "Lopez")
    player8_id = register_player("Vladimir", "Kramnik")
    player9_id = register_player("Bobby", "Fisher")
    player10_id = register_player("Magnus", "Carlsen")
    player11_id = register_player("Emanuel", "Lasker")
    player12_id = register_player("Raul", "Capablanca")
    player13_id = register_player("Boris", "Spasky")
    player14_id = register_player("Anand", "Viswanathan")
    player15_id = register_player("Gary", "Kasparov")
    player16_id = register_player("Anatoli", "Karpov")
    add_player_to_event(event_id, player1_id)
    add_player_to_event(event_id, player2_id)
    add_player_to_event(event_id, player3_id)
    add_player_to_event(event_id, player4_id)
    add_player_to_event(event_id, player5_id)
    add_player_to_event(event_id, player6_id)
    add_player_to_event(event_id, player7_id)
    add_player_to_event(event_id, player8_id)
    add_player_to_event(event_id, player9_id)
    add_player_to_event(event_id, player10_id)
    add_player_to_event(event_id, player11_id)
    add_player_to_event(event_id, player12_id)
    add_player_to_event(event_id, player13_id)
    add_player_to_event(event_id, player14_id)
    add_player_to_event(event_id, player15_id)
    add_player_to_event(event_id, player16_id)
    standings = player_standings(event_id)
    #print ("\n{}\n".format(standings))
    pairings = swiss_pairings(event_id, 1)
    for pair in pairings:
        (id1, name1, id2, name2) = pair
        report_match(event_id, 1, id1, 1.0, id2, 0.0)
    standings = player_standings(event_id)
    #print ("\n{}\n".format(standings))
    pairings = swiss_pairings(event_id, 2)
    for pair in pairings:
        (id1, name1, id2, name2) = pair
        report_match(event_id, 2, id1, 1.0, id2, 0.0)
    standings = player_standings(event_id)
    #print ("\n{}\n".format(standings))
    pairings = swiss_pairings(event_id, 3)
    for pair in pairings:
        (id1, name1, id2, name2) = pair
        report_match(event_id, 3, id1, 1.0, id2, 0.0)
    standings = player_standings(event_id)
    #print ("\n{}\n".format(standings))
    pairings = swiss_pairings(event_id, 4)
    for pair in pairings:
        (id1, name1, id2, name2) = pair
        report_match(event_id, 4, id1, 0.0, id2, 1.0)
    standings = player_standings(event_id)
    #print ("\n{}\n".format(standings))
    for (i, n, p, m) in standings:
        if m != 4:
            raise ValueError("Each player should have 4 matches recorded.")
    (i1, n1, p1, m1) = standings[0]
    (i16, n16, p16, m16) = standings[len(standings)-1]
    if p1 < 4.0:
        raise ValueError("In this case winner must have 4 points")
    if p16 > 0.0:
        raise ValueError("In this case the last player must have 0 points")
    print ("{}. After 4 rounds we have a winner")\
            .format(test_num)

def test_prevent_rematches (test_num):
    delete_all_events()
    delete_all_matches()
    delete_players()
    event_id = register_event("Blitz Tournament", "2015/12/30")
    player1_id = register_player("Twilight", "Sparkle")
    player2_id = register_player("Flutter", "Shy")
    player3_id = register_player("Aristoteles", "Nunez")
    player4_id = register_player("Gary", "Nunez")
    player5_id = register_player("Vladimir", "Kramnik")
    player6_id = register_player("Sahadi", "Urbina")
    player7_id = register_player("Itzel", "Lopez")
    player8_id = register_player("Vladimir", "Kramnik")
    add_player_to_event(event_id, player1_id)
    add_player_to_event(event_id, player2_id)
    add_player_to_event(event_id, player3_id)
    add_player_to_event(event_id, player4_id)
    add_player_to_event(event_id, player5_id)
    add_player_to_event(event_id, player6_id)
    add_player_to_event(event_id, player7_id)
    add_player_to_event(event_id, player8_id)
    standings = player_standings(event_id)
    #print ("\n{}\n".format(standings))
    # Pairings with score 0
    pairings = swiss_pairings(event_id, 1)
    (p1id1, p1name1, p1id2, p1name2) = pairings[0]
    for pair in pairings:
        (id1, name1, id2, name2) = pair
        report_match(event_id, 1, id1, 0.5, id2, 0.5)
    standings = player_standings(event_id)
    #print ("\n{}\n".format(standings))
    # After everybody ties, the pairings must prevent rematches
    pairings = swiss_pairings(event_id, 2)
    #print ("\n{}\n".format(pairings))
    (p2id1, p2name1, p2id2, p2name2) = pairings[0]
    round_one = set([p1id1, p1id2])
    round_two = set([p2id1, p2id2])
    if round_one == round_two:
        raise ValueError(
            "After one match players do not rematch.")
    print ("{}. Preventing rematches between players")\
            .format(test_num)

def test_odd_players (test_num):
    delete_all_events()
    delete_all_matches()
    delete_players()
    event_id = register_event("Blitz Tournament", "2015/12/30")
    player1_id = register_player("Twilight", "Sparkle")
    player2_id = register_player("Flutter", "Shy")
    player3_id = register_player("Aristoteles", "Nunez")
    add_player_to_event(event_id, player1_id)
    add_player_to_event(event_id, player2_id)
    add_player_to_event(event_id, player3_id)
    standings = player_standings(event_id)
    pairings = swiss_pairings(event_id, 1)
    #print ("\n{}\n".format(pairings))
    standings = player_standings(event_id)
    #print ("\n{}\n".format(standings))
    if len(standings) < 4:
        raise ValueError("In this case there must be 4 players")
    print ("{}. Player Bye Added when odd number of players")\
            .format(test_num)

if __name__ == '__main__':
    test_delete_all_event(1)
    test_delete_one_event(2)
    test_register_event(3)
    test_delete_players(4)
    test_register_player(5)
    test_add_player_to_event(6)
    test_remove_player_from_event(7)
    test_delete_all_matches(8)
    test_delete_matches_from_event(9)
    test_register_count_delete(10)
    test_standings_before_matches(11)
    test_report_matches(12)
    test_pairings(13)
    test_tournament (14)
    test_prevent_rematches(15)
    test_odd_players(16)
    print ("Success!  All tests pass!")


text:
function Find-LatestWindowsUpdates {

    <#
    .SYNOPSIS
    Get the latest Cumulative update for Windows

    .DESCRIPTION
    This script will return the list of Cumulative updates for Windows 10 and Windows Server 2016 from the Microsoft Update Catalog.

    .NOTES
    Copyright Keith Garner (KeithGa@DeploymentLive.com), All rights reserved.

    .LINK
    https://support.microsoft.com/en-us/help/4000823

    .EXAMPLE
    Get the latest Cumulative Update for Windows 10 x64

    .\Get-LatestUpdate.ps1

    .PARAMETER Build
    Windows 10 Build Number used to filter avaible Downloads

        10240 - Windows 10 Version 1507
        10586 - Windows 10 Version 1511
        14393 - Windows 10 Version 1607 and Windows Server 2016
        15063 - Windows 10 Version 1703

    .PARAMETER Filter
    Specify a specific search filter to change the target update behaviour. The default will only Cumulative updates for x86 and x64.

    If Mulitple Filters are specified, only string that match *ALL* filters will be selected.

        Cumulative - Download Cumulative updates.
        Delta - Download Delta updates.
        x86 - Download x86
        x64 - Download x64

    .EXAMPLE
    Get the latest Cumulative Update for Windows 10 x86

    .\Get-LatestUpdate.ps1 -Filter 'Cumulative','x86'

    .EXAMPLE

    Get the latest Cumulative Update for Windows Server 2016

    .\Get-LatestUpdate.ps1 -Filter 'Cumulative','x64' -Build 14393

    .EXAMPLE

    Get the latest Cumulative Updates for Windows 10 (both x86 and x64) and download to the %TEMP% directory.

    .\Get-LatestUpdate.ps1 | Start-BitsTransfer -Destination $env:Temp

    #>

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$False, HelpMessage="JSON source for the update KB articles.")]
        [string] $StartKB = 'https://support.microsoft.com/api/content/asset/4000816',

        [Parameter(Mandatory=$False, HelpMessage="Windows build number.")]
        [ValidateSet('15063','14393','10586','10240')]
        [string] $BUild = '15063',

        [Parameter(Mandatory=$False, HelpMessage="Windows update Catalog Search Filter.")]
        [ValidateSet('x64','x86','Cumulative','Delta',$null)]
        [string[]] $Filter = @( "Cumulative" )

    )

    #region Support Routine

    Function Select-LatestUpdate {
        [CmdletBinding(SupportsShouldProcess=$True)]
        Param(
            [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
            $Updates
        )
        Begin {
            $MaxObject = $null
            $MaxValue = [version]::new("0.0")
        }
        Process {
            ForEach ( $Update in $updates ) {
                Select-String -InputObject $Update -AllMatches -Pattern "(\d+\.)?(\d+\.)?(\d+\.)?(\*|\d+)" |
                ForEach-Object { $_.matches.value } |
                ForEach-Object { $_ -as [version] } |
                ForEach-Object {
                    if ( $_ -gt $MaxValue ) { $MaxObject = $Update; $MaxValue = $_ }
                }
            }
        }
        End {
            $MaxObject | Write-Output
        }
    }

    #endregion

    #region Find the KB Article Number

    Write-Verbose "Downloading $StartKB to retrieve the list of updates."
    $kbID = Invoke-WebRequest -Uri $StartKB |
        Select-Object -ExpandProperty Content |
        ConvertFrom-Json |
        Select-Object -ExpandProperty Links |
        Where-Object level -eq 2 |
        Where-Object text -match $BUild |
        Select-LatestUpdate |
        Select-Object -First 1

    #endregion

    #region get the download link from Windows Update

    Write-Verbose "Found ID: KB$($kbID.articleID)"
    $kbObj = Invoke-WebRequest -Uri "http://www.catalog.update.microsoft.com/Search.aspx?q=KB$($KBID.articleID)"

    $Available_KBIDs = $kbObj.InputFields |
        Where-Object { $_.type -eq 'Button' -and $_.Value -eq 'Download' } |
        Select-Object -ExpandProperty  ID

    $Available_KBIDs | out-string | write-verbose

    $kbGUIDs = $kbObj.Links |
        Where-Object ID -match '_link' |
        Where-Object { $_.OuterHTML -match ( "(?=.*" + ( $Filter -join ")(?=.*" ) + ")" ) } |
        ForEach-Object { $_.id.replace('_link','') } |
        Where-Object { $_ -in $Available_KBIDs }

    foreach ( $kbGUID in $kbGUIDs )
    {
        Write-Verbose "`t`tDownload $kbGUID"
        $Post = @{ size = 0; updateID = $kbGUID; uidInfo = $kbGUID } | ConvertTo-Json -Compress
        $PostBody = @{ updateIDs = "[$Post]" }
        Invoke-WebRequest -Uri 'http://www.catalog.update.microsoft.com/DownloadDialog.aspx' -Method Post -Body $postBody |
            Select-Object -ExpandProperty Content |
            Select-String -AllMatches -Pattern "(http[s]?\://download\.windowsupdate\.com\/[^\'\""]*)" |
            Select-Object -Unique |
            ForEach-Object { [PSCustomObject] @{ Source = $_.matches.value } }  # Output for BITS
    }

    #endregion

}


text:
package imagesignature

import (
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/util/validation/field"
	apirequest "k8s.io/apiserver/pkg/endpoints/request"
	kapi "k8s.io/kubernetes/pkg/api"

	imageapi "github.com/openshift/origin/pkg/image/apis/image"
	"github.com/openshift/origin/pkg/image/apis/image/validation"
)

// strategy implements behavior for ImageStreamTags.
type strategy struct {
	runtime.ObjectTyper
}

var Strategy = &strategy{
	ObjectTyper: kapi.Scheme,
}

func (s *strategy) NamespaceScoped() bool {
	return false
}

func (s *strategy) PrepareForCreate(ctx apirequest.Context, obj runtime.Object) {
	signature := obj.(*imageapi.ImageSignature)

	signature.Conditions = nil
	signature.ImageIdentity = ""
	signature.SignedClaims = nil
	signature.Created = nil
	signature.IssuedBy = nil
	signature.IssuedTo = nil
}

func (s *strategy) GenerateName(base string) string {
	return base
}

func (s *strategy) Validate(ctx apirequest.Context, obj runtime.Object) field.ErrorList {
	signature := obj.(*imageapi.ImageSignature)

	return validation.ValidateImageSignature(signature)
}

func (s *strategy) AllowCreateOnUpdate() bool {
	return false
}

func (*strategy) AllowUnconditionalUpdate() bool {
	return false
}

// Canonicalize normalizes the object after validation.
func (strategy) Canonicalize(obj runtime.Object) {
}