text:
<mods xmlns="http://www.loc.gov/mods/v3" xmlns:exslt="http://exslt.org/common" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xsi:schemaLocation="http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-3.xsd" version="3.3" ID="P0b002ee18171d930">
<name type="corporate">
 <namePart>United States Government Printing Office</namePart>
 <role>
  <roleTerm type="text" authority="marcrelator">printer</roleTerm>
  <roleTerm type="code" authority="marcrelator">prt</roleTerm>
</role>
 <role>
  <roleTerm type="text" authority="marcrelator">distributor</roleTerm>
  <roleTerm type="code" authority="marcrelator">dst</roleTerm>
</role>
</name>
<name type="corporate">
 <namePart>United States</namePart>
 <namePart>United States District Court District of Kansas</namePart>
 <role>
  <roleTerm type="text" authority="marcrelator">author</roleTerm>
  <roleTerm type="code" authority="marcrelator">aut</roleTerm>
</role>
 <description>Government Organization</description>
</name>
<typeOfResource>text</typeOfResource>
<genre authority="marcgt">government publication</genre>
<language>
 <languageTerm authority="iso639-2b" type="code">eng</languageTerm>
</language>
<extension>
 <collectionCode>USCOURTS</collectionCode>
 <category>Judicial Publications</category>
 <branch>judicial</branch>
 <dateIngested>2012-01-11</dateIngested>
</extension>
<originInfo>
 <publisher>Administrative Office of the United States Courts</publisher>
 <dateIssued encoding="w3cdtf">2012-01-10</dateIssued>
 <issuance>monographic</issuance>
</originInfo>
<physicalDescription>
 <note type="source content type">deposited</note>
 <digitalOrigin>born digital</digitalOrigin>
</physicalDescription>
<classification authority="sudocs">JU 4.15</classification>
<identifier type="uri">http://www.gpo.gov/fdsys/pkg/USCOURTS-ksd-5_11-cv-04066</identifier>
<identifier type="local">P0b002ee18171d930</identifier>
<recordInfo>
 <recordContentSource authority="marcorg">DGPO</recordContentSource>
 <recordCreationDate encoding="w3cdtf">2012-01-11</recordCreationDate>
 <recordChangeDate encoding="w3cdtf">2012-01-11</recordChangeDate>
 <recordIdentifier source="DGPO">USCOURTS-ksd-5_11-cv-04066</recordIdentifier>
 <recordOrigin>machine generated</recordOrigin>
 <languageOfCataloging>
  <languageTerm authority="iso639-2b" type="code">eng</languageTerm>
</languageOfCataloging>
</recordInfo>
<accessCondition type="GPO scope determination">fdlp</accessCondition>
<extension>
 <docClass>USCOURTS</docClass>
 <accessId>USCOURTS-ksd-5_11-cv-04066</accessId>
 <courtType>District</courtType>
 <courtCode>ksd</courtCode>
 <courtCircuit>10th</courtCircuit>
 <courtState>Kansas</courtState>
 <courtSortOrder>2190</courtSortOrder>
 <caseNumber>5:11-cv-04066</caseNumber>
 <caseOffice>Topeka</caseOffice>
 <caseType>civil</caseType>
 <natureSuitCode>440</natureSuitCode>
 <natureSuit>Other Civil Rights</natureSuit>
 <party firstName="Marjorie" fullName="Marjorie A. Creamer" lastName="Creamer" middleName="A." role="Plaintiff"></party>
 <party fullName="Smith County Sheriff's Department" lastName="Smith County Sheriff's Department" role="Defendant"></party>
</extension>
<titleInfo>
 <title>Creamer v. Smith County Sheriff's Department</title>
 <partNumber>5:11-cv-04066</partNumber>
</titleInfo>
<location>
 <url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/pkg/USCOURTS-ksd-5_11-cv-04066/content-detail.html</url>
</location>
<classification authority="sudocs">JU 4.15</classification>
<identifier type="preferred citation">5:11-cv-04066;11-4066</identifier>
<name type="corporate">
 <namePart>United States District Court District of Kansas</namePart>
 <namePart>10th Circuit</namePart>
 <namePart>Topeka</namePart>
 <affiliation>U.S. Courts</affiliation>
 <role>
  <roleTerm authority="marcrelator" type="text">author</roleTerm>
  <roleTerm authority="marcrelator" type="code">aut</roleTerm>
</role>
</name>
<name type="personal">
 <displayForm>Marjorie A. Creamer</displayForm>
 <namePart type="family">Creamer</namePart>
 <namePart type="given">Marjorie</namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Plaintiff</description>
</name>
<name type="personal">
 <displayForm>Smith County Sheriff's Department</displayForm>
 <namePart type="family">Smith County Sheriff's Department</namePart>
 <namePart type="given"></namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Defendant</description>
</name>
<extension>
 <docClass>USCOURTS</docClass>
 <accessId>USCOURTS-ksd-5_11-cv-04066</accessId>
 <courtType>District</courtType>
 <courtCode>ksd</courtCode>
 <courtCircuit>10th</courtCircuit>
 <courtState>Kansas</courtState>
 <courtSortOrder>2190</courtSortOrder>
 <caseNumber>5:11-cv-04066</caseNumber>
 <caseOffice>Topeka</caseOffice>
 <caseType>civil</caseType>
 <natureSuitCode>440</natureSuitCode>
 <natureSuit>Other Civil Rights</natureSuit>
 <party firstName="Marjorie" fullName="Marjorie A. Creamer" lastName="Creamer" middleName="A." role="Plaintiff"></party>
 <party fullName="Smith County Sheriff's Department" lastName="Smith County Sheriff's Department" role="Defendant"></party>
 <state>Kansas</state>
</extension>
<relatedItem type="constituent" ID="id-USCOURTS-ksd-5_11-cv-04066-0" xlink:href="http://www.gpo.gov/fdsys/granule/USCOURTS-ksd-5_11-cv-04066/USCOURTS-ksd-5_11-cv-04066-0/mods.xml">
 <titleInfo>
  <title>Creamer v. Smith County Sheriff's Department</title>
  <subTitle>MEMORANDUM AND ORDER granting 8 Motion to Dismiss. Signed by District Judge Wesley E. Brown on 10/20/2011. (aa) Modified on 10/20/2011 (aa).</subTitle>
  <partNumber>0</partNumber>
</titleInfo>
 <originInfo>
  <dateIssued>2011-10-20</dateIssued>
</originInfo>
 <relatedItem xlink:href="http://www.gpo.gov/fdsys/pkg/pdf/USCOURTS-ksd-5_11-cv-04066-0.pdf" type="otherFormat">
  <identifier type="FDsys Unique ID">D09002ee18171dd90</identifier>
</relatedItem>
 <identifier type="uri">http://www.gpo.gov/fdsys/granule/USCOURTS-ksd-5_11-cv-04066/USCOURTS-ksd-5_11-cv-04066-0</identifier>
 <identifier type="former granule identifier">ksd-5_11-cv-04066_0.pdf</identifier>
 <location>
  <url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/granule/USCOURTS-ksd-5_11-cv-04066/USCOURTS-ksd-5_11-cv-04066-0/content-detail.html</url>
  <url access="raw object" displayLabel="PDF rendition">http://www.gpo.gov/fdsys/pkg/USCOURTS-ksd-5_11-cv-04066/pdf/USCOURTS-ksd-5_11-cv-04066-0.pdf</url>
</location>
 <extension>
  <searchTitle>USCOURTS 5:11-cv-04066; Creamer v. Smith County Sheriff's Department; </searchTitle>
  <courtName>United States District Court District of Kansas</courtName>
  <state>Kansas</state>
  <accessId>USCOURTS-ksd-5_11-cv-04066-0</accessId>
  <sequenceNumber>0</sequenceNumber>
  <dateIssued>2011-10-20</dateIssued>
  <docketText>MEMORANDUM AND ORDER granting 8 Motion to Dismiss. Signed by District Judge Wesley E. Brown on 10/20/2011. (aa) Modified on 10/20/2011 (aa).</docketText>
</extension>
</relatedItem>
<relatedItem type="constituent" ID="id-USCOURTS-ksd-5_11-cv-04066-1" xlink:href="http://www.gpo.gov/fdsys/granule/USCOURTS-ksd-5_11-cv-04066/USCOURTS-ksd-5_11-cv-04066-1/mods.xml">
 <titleInfo>
  <title>Creamer v. Smith County Sheriff's Department</title>
  <subTitle>MEMORANDUM AND ORDER denying 21 Motion for Reconsideration. Signed by District Judge Wesley E. Brown on 11/22/2011. Mailed to pro se party Marjorie A. Creamer by regular mail. (aa)</subTitle>
  <partNumber>1</partNumber>
</titleInfo>
 <originInfo>
  <dateIssued>2011-11-22</dateIssued>
</originInfo>
 <relatedItem xlink:href="http://www.gpo.gov/fdsys/pkg/pdf/USCOURTS-ksd-5_11-cv-04066-1.pdf" type="otherFormat">
  <identifier type="FDsys Unique ID">D09002ee18171dd92</identifier>
</relatedItem>
 <identifier type="uri">http://www.gpo.gov/fdsys/granule/USCOURTS-ksd-5_11-cv-04066/USCOURTS-ksd-5_11-cv-04066-1</identifier>
 <identifier type="former granule identifier">ksd-5_11-cv-04066_1.pdf</identifier>
 <location>
  <url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/granule/USCOURTS-ksd-5_11-cv-04066/USCOURTS-ksd-5_11-cv-04066-1/content-detail.html</url>
  <url access="raw object" displayLabel="PDF rendition">http://www.gpo.gov/fdsys/pkg/USCOURTS-ksd-5_11-cv-04066/pdf/USCOURTS-ksd-5_11-cv-04066-1.pdf</url>
</location>
 <extension>
  <searchTitle>USCOURTS 5:11-cv-04066; Creamer v. Smith County Sheriff's Department; </searchTitle>
  <courtName>United States District Court District of Kansas</courtName>
  <state>Kansas</state>
  <accessId>USCOURTS-ksd-5_11-cv-04066-1</accessId>
  <sequenceNumber>1</sequenceNumber>
  <dateIssued>2011-11-22</dateIssued>
  <docketText>MEMORANDUM AND ORDER denying 21 Motion for Reconsideration. Signed by District Judge Wesley E. Brown on 11/22/2011. Mailed to pro se party Marjorie A. Creamer by regular mail. (aa)</docketText>
</extension>
</relatedItem>
<relatedItem type="constituent" ID="id-USCOURTS-ksd-5_11-cv-04066-2" xlink:href="http://www.gpo.gov/fdsys/granule/USCOURTS-ksd-5_11-cv-04066/USCOURTS-ksd-5_11-cv-04066-2/mods.xml">
 <titleInfo>
  <title>Creamer v. Smith County Sheriff's Department</title>
  <subTitle>MEMORANDUM AND ORDER dismissing 26 Motion ; dismissing 27 Motion ; dismissing 28 Motion. See order for filing restriction details. Signed by District Judge Wesley E. Brown on 12/2/2011. (aa)</subTitle>
  <partNumber>2</partNumber>
</titleInfo>
 <originInfo>
  <dateIssued>2011-12-02</dateIssued>
</originInfo>
 <relatedItem xlink:href="http://www.gpo.gov/fdsys/pkg/pdf/USCOURTS-ksd-5_11-cv-04066-2.pdf" type="otherFormat">
  <identifier type="FDsys Unique ID">D09002ee18171dd8f</identifier>
</relatedItem>
 <identifier type="uri">http://www.gpo.gov/fdsys/granule/USCOURTS-ksd-5_11-cv-04066/USCOURTS-ksd-5_11-cv-04066-2</identifier>
 <identifier type="former granule identifier">ksd-5_11-cv-04066_2.pdf</identifier>
 <location>
  <url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/granule/USCOURTS-ksd-5_11-cv-04066/USCOURTS-ksd-5_11-cv-04066-2/content-detail.html</url>
  <url access="raw object" displayLabel="PDF rendition">http://www.gpo.gov/fdsys/pkg/USCOURTS-ksd-5_11-cv-04066/pdf/USCOURTS-ksd-5_11-cv-04066-2.pdf</url>
</location>
 <extension>
  <searchTitle>USCOURTS 5:11-cv-04066; Creamer v. Smith County Sheriff's Department; </searchTitle>
  <courtName>United States District Court District of Kansas</courtName>
  <state>Kansas</state>
  <accessId>USCOURTS-ksd-5_11-cv-04066-2</accessId>
  <sequenceNumber>2</sequenceNumber>
  <dateIssued>2011-12-02</dateIssued>
  <docketText>MEMORANDUM AND ORDER dismissing 26 Motion ; dismissing 27 Motion ; dismissing 28 Motion. See order for filing restriction details. Signed by District Judge Wesley E. Brown on 12/2/2011. (aa)</docketText>
</extension>
</relatedItem>
<relatedItem type="constituent" ID="id-USCOURTS-ksd-5_11-cv-04066-3" xlink:href="http://www.gpo.gov/fdsys/granule/USCOURTS-ksd-5_11-cv-04066/USCOURTS-ksd-5_11-cv-04066-3/mods.xml">
 <titleInfo>
  <title>Creamer v. Smith County Sheriff's Department</title>
  <subTitle>MEMORANDUM AND ORDER denying 31 Motion for Leave to Proceed in forma pauperis on Appeal . Signed by District Judge Wesley E. Brown on 1/10/2012. (aa)</subTitle>
  <partNumber>3</partNumber>
</titleInfo>
 <originInfo>
  <dateIssued>2012-01-10</dateIssued>
</originInfo>
 <relatedItem xlink:href="http://www.gpo.gov/fdsys/pkg/pdf/USCOURTS-ksd-5_11-cv-04066-3.pdf" type="otherFormat">
  <identifier type="FDsys Unique ID">D09002ee18171dd91</identifier>
</relatedItem>
 <identifier type="uri">http://www.gpo.gov/fdsys/granule/USCOURTS-ksd-5_11-cv-04066/USCOURTS-ksd-5_11-cv-04066-3</identifier>
 <identifier type="former granule identifier">ksd-5_11-cv-04066_3.pdf</identifier>
 <location>
  <url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/granule/USCOURTS-ksd-5_11-cv-04066/USCOURTS-ksd-5_11-cv-04066-3/content-detail.html</url>
  <url access="raw object" displayLabel="PDF rendition">http://www.gpo.gov/fdsys/pkg/USCOURTS-ksd-5_11-cv-04066/pdf/USCOURTS-ksd-5_11-cv-04066-3.pdf</url>
</location>
 <extension>
  <searchTitle>USCOURTS 5:11-cv-04066; Creamer v. Smith County Sheriff's Department; </searchTitle>
  <courtName>United States District Court District of Kansas</courtName>
  <state>Kansas</state>
  <accessId>USCOURTS-ksd-5_11-cv-04066-3</accessId>
  <sequenceNumber>3</sequenceNumber>
  <dateIssued>2012-01-10</dateIssued>
  <docketText>MEMORANDUM AND ORDER denying 31 Motion for Leave to Proceed in forma pauperis on Appeal . Signed by District Judge Wesley E. Brown on 1/10/2012. (aa)</docketText>
</extension>
</relatedItem>
<relatedItem type="constituent" ID="id-USCOURTS-ksd-5_11-cv-04066-4" xlink:href="http://www.gpo.gov/fdsys/granule/USCOURTS-ksd-5_11-cv-04066/USCOURTS-ksd-5_11-cv-04066-4/mods.xml">
 <titleInfo>
  <title>Creamer v. Smith County Sheriff's Department</title>
  <subTitle>MEMORANDUM AND ORDER ON FILING RESTRICTIONS. Signed by District Judge Wesley E. Brown on 1/10/2012. See order for details. (aa)</subTitle>
  <partNumber>4</partNumber>
</titleInfo>
 <originInfo>
  <dateIssued>2012-01-10</dateIssued>
</originInfo>
 <relatedItem xlink:href="http://www.gpo.gov/fdsys/pkg/pdf/USCOURTS-ksd-5_11-cv-04066-4.pdf" type="otherFormat">
  <identifier type="FDsys Unique ID">D09002ee18171dd8e</identifier>
</relatedItem>
 <identifier type="uri">http://www.gpo.gov/fdsys/granule/USCOURTS-ksd-5_11-cv-04066/USCOURTS-ksd-5_11-cv-04066-4</identifier>
 <identifier type="former granule identifier">ksd-5_11-cv-04066_4.pdf</identifier>
 <location>
  <url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/granule/USCOURTS-ksd-5_11-cv-04066/USCOURTS-ksd-5_11-cv-04066-4/content-detail.html</url>
  <url access="raw object" displayLabel="PDF rendition">http://www.gpo.gov/fdsys/pkg/USCOURTS-ksd-5_11-cv-04066/pdf/USCOURTS-ksd-5_11-cv-04066-4.pdf</url>
</location>
 <extension>
  <searchTitle>USCOURTS 5:11-cv-04066; Creamer v. Smith County Sheriff's Department; </searchTitle>
  <courtName>United States District Court District of Kansas</courtName>
  <state>Kansas</state>
  <accessId>USCOURTS-ksd-5_11-cv-04066-4</accessId>
  <sequenceNumber>4</sequenceNumber>
  <dateIssued>2012-01-10</dateIssued>
  <docketText>MEMORANDUM AND ORDER ON FILING RESTRICTIONS. Signed by District Judge Wesley E. Brown on 1/10/2012. See order for details. (aa)</docketText>
</extension>
</relatedItem>
</mods>


text:
from slicc.symbols.Symbol import Symbol

class Var(Symbol):
    def __init__(self, symtab, ident, location, type, code, pairs,
                 machine=None, buffer_expr=""):
        super(Var, self).__init__(symtab, ident, location, pairs)

        self.buffer_expr = buffer_expr
        self.machine = machine
        self.type = type
        self.code = code

    def __repr__(self):
        return "[Var id: %s]" % (self.ident)

    def writeCodeFiles(self, path, includes):
        pass

__all__ = [ "Var" ]

redpajama_set_name: RedPajamaGithub


text:
\echo 'Creating Registries app tables...'

DROP TABLE IF EXISTS xform_registries_action_tracking_driller;
CREATE unlogged TABLE IF NOT EXISTS xform_registries_action_tracking_driller (
 trk_guid uuid DEFAULT gen_random_uuid()
,id integer
,registered_ind character varying(20)
,date_app_received date
,company_name character varying(80)
,name character varying(80)
,town_region character varying(80)
,date_gone_for_review date
,app_approval_date date
,date_approval_letter_card_sent date
,app_denial_date date
,comments character varying(200)
,date_denial_letter_sent date
,date_removed_from_register date
);

DROP TABLE IF EXISTS xform_registries_drillers_reg;
CREATE unlogged TABLE IF NOT EXISTS xform_registries_drillers_reg (
 reg_guid uuid DEFAULT gen_random_uuid()
,Name character varying(100)
,LastName character varying(20)
,FirstName character varying(20)
,BirthDate character varying(20)
,Welldrillerregno character varying(20)
,Registrationdate date
,CompanyName character varying(100)
,CompanyAddress character varying(100)
,CompanyCity character varying(20)
,CompanyProv character varying(20)
,CompanyPostalCode character varying(20)
,CompanyPhone  character varying(20)
,CompanyFax character varying(50)
,CompanyEmail  character varying(50)
,ClassofWellDriller  character varying(50) -- IGNORE for now
,TypeofCertificate  character varying(50)
--gwells=> select typeofcertificate, count(*) from public.xform_registries_drillers_reg group by typeofcertificate;
--           typeofcertificate            | count
----------------------------------------+-------
-- n/a                                    |    96
-- Ground Water Drilling Technician, CGWA |     2
-- Water Well Driller, Prov. Of BC        |    29
--(3 rows)
,ClassofWell  character varying(50)
,TypeofDrillRig  character varying(20) -- IGNORE no data
,MoERegion  character varying(40) -- IGNORE obsolete
,File_Number  character varying(20)
 );

DROP TABLE IF EXISTS xform_registries_removed_from;
CREATE unlogged TABLE IF NOT EXISTS xform_registries_removed_from (
 removed_guid uuid DEFAULT gen_random_uuid()
,Name character varying(100)
,LastName character varying(20)
,FirstName character varying(20)
,BirthDate character varying(20)
,RegistrationNumber character varying(20)
,Registrationdate character varying(20) -- should be date
,CompanyName character varying(100)
,CompanyAddress character varying(100)
,CompanyCity character varying(20)
,CompanyProv character varying(20)
,CompanyPostalCode character varying(20)
,CompanyPhone  character varying(20)
,CompanyFax character varying(50)
,CompanyEmail  character varying(50)
,ClassofWellDriller  character varying(50)
,Reason character varying(50)
,Removed_from_Registry date
 );

\echo 'Finished creating Registries app tables...'


text:
import { userMention } from "@discordjs/builders";
import {
  Guild,
  GuildMember,
  MessageOptions,
  PartialGuildMember,
} from "discord.js";
import config from "../config";
import { EventHandler, Module } from "../internal/types";
import { getGeneralMessageChannelForGuild } from "../utils/guilds";

const defaultJoinMessageBuilder = (
  guild: Guild,
  member: GuildMember
): MessageOptions => {
  return {
    content: `Welcome to ${guild.name}, ${userMention(member.user.id)}!`,
  };
};

const defaultLeaveMessageBuilder = (
  _: Guild,
  member: GuildMember | PartialGuildMember
): MessageOptions => {
  return {
    content: `Bye, ${member.user?.tag ?? member.displayName}!`,
  };
};

const handleGuildMemberAdd: EventHandler<"guildMemberAdd"> = async (member) => {
  if (!config.guilds[member.guild.id].joinLeaveMessages?.enabled) {
    return;
  }

  const channel = config.guilds[member.guild.id].joinLeaveMessages?.channelId
    ? await member.guild.channels.fetch(
        config.guilds[member.guild.id].joinLeaveMessages?.channelId as string
      )
    : await getGeneralMessageChannelForGuild(member.guild);

  if (channel === null) {
    throw Error(`Configured join/leave message channel not found.`);
  }

  if (!channel.isText()) {
    throw Error(`Configured join/leave message channel is not a text channel.`);
  }

  const builder =
    config.guilds[member.guild.id].joinLeaveMessages?.joinMessageBuilder ??
    defaultJoinMessageBuilder;

  const message = builder(member.guild, member);

  await channel.send(message);
};

const handleGuildMemberRemove: EventHandler<"guildMemberRemove"> = async (
  member
) => {
  if (!config.guilds[member.guild.id].joinLeaveMessages?.enabled) {
    return;
  }

  const channel = config.guilds[member.guild.id].joinLeaveMessages?.channelId
    ? await member.guild.channels.fetch(
        config.guilds[member.guild.id].joinLeaveMessages?.channelId as string
      )
    : await getGeneralMessageChannelForGuild(member.guild);

  if (channel === null) {
    throw Error(`Configured join/leave message channel not found.`);
  }

  if (!channel.isText()) {
    throw Error(`Configured join/leave message channel is not a text channel.`);
  }

  const builder =
    config.guilds[member.guild.id].joinLeaveMessages?.leaveMessageBuilder ??
    defaultLeaveMessageBuilder;

  const message = builder(member.guild, member);

  await channel.send(message);
};

const JoinLeaveMessagesModule: Module = {
  commands: [],
  handlers: {
    guildMemberAdd: [handleGuildMemberAdd],
    guildMemberRemove: [handleGuildMemberRemove],
  },
};

export default JoinLeaveMessagesModule;


text:
<?php

namespace Application\Cogito\BABBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Model as ORMBehaviors;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\Blameable\Traits\BlameableEntity;
use Gedmo\Timestampable\Traits\TimestampableEntity;

/**
 * Description
 *
 * @ORM\Table(name="description")
 * @ORM\Entity
 * @Gedmo\Loggable
 */
class Description extends \Application\Cogito\TemplateBundle\Entity\BaseTranslatedEntity
{
    use ORMBehaviors\Translatable\Translatable;
    use BlameableEntity;
    use TimestampableEntity;

    public function __call($method, $arguments)
    {
        return $this->proxyCurrentLocaleTranslation($method, $arguments);
    }
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var \Application\Cogito\BABBundle\Entity\Descrtype
     *
     * @ORM\ManyToOne(targetEntity="Application\Cogito\BABBundle\Entity\Descrtype")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="descrtype_id", referencedColumnName="id", nullable=false)
     * })
     */
    private $descrtype;

    /**
     * @var \Application\Sonata\MediaBundle\Entity\Media
     *
     * @ORM\ManyToOne(targetEntity="Application\Sonata\MediaBundle\Entity\Media")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="media_id", referencedColumnName="id", nullable=false)
     * })
     */
    private $media;

    /**
     * @ORM\OrderBy({"position" = "ASC"})
     * @ORM\OneToMany(targetEntity="Application\Cogito\BABBundle\Entity\CardHasDescription", mappedBy="description", cascade={"persist", "remove"}, orphanRemoval=true)
     */
    private $cards;

    public function __construct() {
        $this->cards = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set descrtype
     *
     * @param \stdClass $descrtype
     * @return Description
     */
    public function setDescrtype($descrtype)
    {
        $this->descrtype = $descrtype;

        return $this;
    }

    /**
     * Get descrtype
     *
     * @return \stdClass
     */
    public function getDescrtype()
    {
        return $this->descrtype;
    }

    /**
     * Set media
     *
     * @param \stdClass $media
     * @return Description
     */
    public function setMedia($media)
    {
        $this->media = $media;

        return $this;
    }

    /**
     * Get media
     *
     * @return \stdClass
     */
    public function getMedia()
    {
        return $this->media;
    }

    /**
     *
     * @param \Doctrine\Common\Collections\ArrayCollection $descriptions
     * @return \Application\Cogito\BABBundle\Entity\Description
     */
    public function setCards($cards) {
        if (count($cards) > 0) {
            foreach ($dcards as $i) {
                $this->addCard($i);
            }
        }

        return $this;
    }

    /**
     *
     * @param \Application\Cogito\BABBundle\Entity\CardHasDescription $tse
     */
    public function addCard(\Application\Cogito\BABBundle\Entity\CardHasDescription $tse) {
        $tse->setDescription($this);

        $this->cards->add($tse);
    }

    /**
     *
     * @param \Application\Cogito\BABBundle\Entity\CardHasDescription $ts
     */
    public function removeCard(\Application\Cogito\BABBundle\Entity\CardHasDescription $tse) {
        $this->cards->removeElement($tse);
    }

    /**
     *
     * @return \Doctrine\Common\Collections\ArrayCollection()
     */
    public function getCards() {
        return $this->cards;
    }

    public function __toString() {

      if(!$this->getId()) return '-';

        if($this->getTitle()){
          return $this->getTitle();
        }
        else{
          if($this->translate($this->getMyDefaultLocale())->getTitle()){
            return $this->translate($this->getMyDefaultLocale())->getTitle();
          }
          else{
            return (string) $this->getId();
          }
        }
    }
}


text:
from django.db import models
from django.conf import settings
# Create your models here.
User = settings.AUTH_USER_MODEL

class Genre(models.Model):
    genre = models.CharField(max_length=30)

    def __unicode__(self):
        return self.genre

class Movie(models.Model):
    name = models.CharField(max_length=255)
    director = models.CharField(max_length=255)
    genre = models.ManyToManyField(Genre, null=False, blank=False)
    release = models.DateField(editable=True)
    imdb_score = models.FloatField()
    popularity = models.IntegerField()
    owner = models.ForeignKey(User, related_name='movies', null=False, blank=False,on_delete=models.CASCADE)

    def __unicode__(self):
        return self.name


text:
A collection of samples that demonstrate how to call the
[Google Cloud DLP API](https://cloud.google.com/dlp/) from C#.

## Build and Run

1.  **Follow the set-up instructions in [the documentation](https://cloud.google.com/dotnet/docs/setup).**

4.  Enable APIs for your project.
    [Click here](https://console.cloud.google.com/flows/enableapi?apiid=dlp.googleapis.com&showconfirmation=true)
    to visit Cloud Platform Console and enable the Google Cloud Translation API.

5.  Set the environment variable `GOOGLE_PROJECT_ID` to your Google Cloud
    Project Id.

    ```ps1
    PS > $env:GOOGLE_PROJECT_ID = 'YOUR-GOOGLE-PROJECT-ID'
    ```

9.  Run the test:
    ```ps1
    PS >  dotnet test
    Build started, please wait...
    Build completed.

    Test run for /usr/local/google/home/rennie/gitrepos/dds2/dlp/api/Snippets/bin/Debug/netcoreapp2.1/DlpSnippets.dll(.NETCoreApp,Version=v2.1)
    Microsoft (R) Test Execution Command Line Tool Version 15.7.0
    Copyright (c) Microsoft Corporation.  All rights reserved.

    Starting test execution, please wait...
    Deidentified content: My SSN is *****9127.

    Total tests: 1. Passed: 1. Failed: 0. Skipped: 0.
    Test Run Successful.
    Test execution time: 2.7392 Seconds
    ```

## Designed to demonstrate Google APIs

These code samples are designed to demonstrate simple code that calls Google
APIs.  They're optimized for being embedded into documentation on
[https://cloud.google.com/docs](https://cloud.google.com/docs).
So sometimes, they don't conform to engineering best practices like
"don't copy and paste code."

## Contributing changes

* See [CONTRIBUTING.md](../../../CONTRIBUTING.md)

## Licensing

* See [LICENSE](../../../LICENSE)

## Testing

* See [TESTING.md](../../../TESTING.md)


text:
void CVarStore::initDefaultVars () {

	CDictValue *sys = new CDictValue ();

	sys -> append ("platform", shared_ptr<CValueRef> (new CValueRef (shared_ptr<CValue> (new CStringValue (getPlatform ())))));
	sys -> append ("hostname", shared_ptr<CValueRef> (new CValueRef (shared_ptr<CValue> (new CStringValue (getComputerName ())))));
	sys -> append ("username", shared_ptr<CValueRef> (new CValueRef (shared_ptr<CValue> (new CStringValue (getUserName ())))));
	sys -> append ("bits", shared_ptr<CValueRef> (new CValueRef (shared_ptr<CValue> (new CIntValue (getBitness ())))));

	CDictValue *env = new CDictValue ();
	CArrayValue *path = new CArrayValue ();

	map<string,string> envmap;
	getEnvironment (envmap);

	for (map<string,string>::iterator it = envmap.begin (); it != envmap.end (); it++) {

		string key = it -> first;
		string value = it -> second;

		if (equalsIgnoreCase (key, "path")) {
			size_t pos = 0;
			size_t nextSep;

			while (pos < value.length()) {
				nextSep = value.find (ENV_PATH_SEPARATOR, pos);
				if (nextSep == string::npos)
					nextSep = value.length ();

				string pathComp = value.substr (pos, nextSep - pos);
				path -> append (shared_ptr<CValueRef> (new CValueRef (shared_ptr<CValue> (new CStringValue (pathComp)))));
				pos = nextSep + 1;
			}

		} else {
			env -> append (key, shared_ptr<CValueRef> (new CValueRef (shared_ptr<CValue> (new CStringValue (value)))));
		}

	}

	sys -> append ("env", shared_ptr<CValueRef> (new CValueRef (shared_ptr<CValue> (env))));
	sys -> append ("path", shared_ptr<CValueRef> (new CValueRef (shared_ptr<CValue> (path))));
	sys -> append ("include_path", shared_ptr<CValueRef> (new CValueRef (shared_ptr<CValue> (new CArrayValue ()))));

	setVar ("sys", shared_ptr<CValue> (sys));

}

shared_ptr<CValue> CVarStore::getVar (const string& varName) {

	map<string, shared_ptr<CValueRef>>::iterator it = variables.find (varName);
	if (it == variables.end ()) {
		if (baseStore)
			return baseStore -> getVar (varName);
		else
			return shared_ptr<CValue> (new CVoidValue ());
	}

	return it -> second -> getValue ();
}

shared_ptr<CValueRef> CVarStore::getVarRef (const string& varName) {

	map<string, shared_ptr<CValueRef>>::iterator it = variables.find (varName);

	if (it == variables.end ()) {

		shared_ptr<CValue> newValue = getVar (varName);
		shared_ptr<CValueRef> newRef = shared_ptr<CValueRef> (new CValueRef (newValue));
		variables.insert (pair<string, shared_ptr<CValueRef>> (varName, newRef));

		return newRef;
	}

	return it -> second;

}

void CVarStore::setVar (const string& varName, shared_ptr<CValue> value) {

	map<string, shared_ptr<CValueRef>>::iterator it = variables.find (varName);

	if (it == variables.end ()) {

		shared_ptr<CValue> newValue = value;
		shared_ptr<CValueRef> newRef = shared_ptr<CValueRef> (new CValueRef (newValue));
		variables.insert (pair<string, shared_ptr<CValueRef>> (varName, newRef));

	} else

		it -> second -> setValue (value);

}

void CBaseExecutionContext::addFunctions (const map<string,shared_ptr<CUserFunction>>& moreFunctions) {

	for (map<string,shared_ptr<CUserFunction>>::const_iterator it = moreFunctions.begin (); it != moreFunctions.end (); it++) {
		map<string,shared_ptr<CUserFunction>>::iterator old = userFunctions.find (it -> first);
		if (old != userFunctions.end ())
			throw runtime_error ("Function name conflict");
		userFunctions.insert (*it);
	}

}

shared_ptr<CUserFunction> CBaseExecutionContext::getFunction (const string& name) {

	map<string,shared_ptr<CUserFunction>>::iterator it = userFunctions.find (name);
	if (it == userFunctions.end ())
		throw runtime_error ("Function does not exist");

	return it -> second;

}

bool CBaseExecutionContext::hasIncludedModule (const string& path) {

	set<string>::iterator it = includedModules.find (path);
	return (it != includedModules.end ());

}

void CBaseExecutionContext::addIncludedModule (const string& path) {

	includedModules.insert (path);

}

shared_ptr<CValue> CUserFunction::execute (shared_ptr<CExecutionContext> ctx, const vector<shared_ptr<CExpression>>& invoke_args) {

	if (args.size() != invoke_args.size ())
		throw runtime_error ("Invalid number of arguments");

	shared_ptr<CExecutionContext> newCtx (ctx -> enterFunction (functionName, isTarget));

	list<string>::iterator it_names = args.begin ();
	vector<shared_ptr<CExpression>>::const_iterator it_exprs = invoke_args.begin ();

	while (it_names != args.end () && it_exprs != invoke_args.end ()) {

		shared_ptr<CValue> argValue = (*it_exprs) -> evaluate (ctx);
		newCtx -> getVarStore () -> setVar (*it_names, argValue);

		it_names ++;
		it_exprs ++;

	}

	stmt -> execute (newCtx);

	return newCtx -> getReturnValue ();

}

void CUserFunction::updateHash (shared_ptr<CExecutionContext> ctx, SHA1& hash) {

	for (list<string>::iterator it = args.begin (); it != args.end (); it ++) {
		hash.update (":arg:");
		hash.update (*it);
	}

	hash.update (":body:");
	stmt -> updateHash (ctx, hash);

}


text:
package com.hack23.cia.service.data.impl;

import java.util.Locale;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.PhysicalNamingStrategy;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;

/**
 * The Class LegacyNamingStrategy.
 */
public final class LegacyNamingStrategy implements PhysicalNamingStrategy {

    private static final String REG_EXPR = "([a-z])([A-Z])";
    private static final String REPLACEMENT_PATTERN = "$1_$2";

    /**
	 * Instantiates a new legacy naming strategy.
	 */
    public LegacyNamingStrategy() {
		super();
	}

    /**
	 * Convert.
	 *
	 * @param identifier
	 *            the identifier
	 * @return the identifier
	 */
    private static Identifier convert(final Identifier identifier) {
    	if (identifier == null || StringUtils.isBlank(identifier.getText())) {
            return identifier;
        } else {
        	return Identifier.toIdentifier(identifier.getText().replaceAll(REG_EXPR, REPLACEMENT_PATTERN).toLowerCase(Locale.ENGLISH));
        }
    }

    @Override
    public Identifier toPhysicalCatalogName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
        return convert(identifier);
    }

    @Override
    public Identifier toPhysicalColumnName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
        return convert(identifier);
    }

    @Override
    public Identifier toPhysicalSchemaName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
        return convert(identifier);
    }

    @Override
    public Identifier toPhysicalSequenceName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
        return convert(identifier);
    }

    @Override
    public Identifier toPhysicalTableName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
        return convert(identifier);
    }

}


text:
package com.mopub.mraid;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.view.WindowManager;
import android.webkit.ConsoleMessage;
import android.webkit.JsResult;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;

import com.mopub.common.AdReport;
import com.mopub.common.CloseableLayout;
import com.mopub.common.CloseableLayout.ClosePosition;
import com.mopub.common.CloseableLayout.OnCloseListener;
import com.mopub.common.MoPubBrowser;
import com.mopub.common.Preconditions;
import com.mopub.common.VisibleForTesting;
import com.mopub.common.logging.MoPubLog;
import com.mopub.common.util.DeviceUtils;
import com.mopub.common.util.Dips;
import com.mopub.common.util.Intents;
import com.mopub.common.util.Views;
import com.mopub.exceptions.IntentNotResolvableException;
import com.mopub.exceptions.UrlParseException;
import com.mopub.mobileads.MraidVideoPlayerActivity;
import com.mopub.mobileads.util.WebViews;
import com.mopub.mraid.MraidBridge.MraidBridgeListener;
import com.mopub.mraid.MraidBridge.MraidWebView;

import java.lang.ref.WeakReference;
import java.net.URI;

import static android.content.pm.ActivityInfo.CONFIG_ORIENTATION;
import static android.content.pm.ActivityInfo.CONFIG_SCREEN_SIZE;
import static com.mopub.common.util.Utils.bitMaskContainsFlag;

public class MraidController {
    private final AdReport mAdReport;

    public interface MraidListener {
        public void onLoaded(View view);
        public void onFailedToLoad();
        public void onExpand();
        public void onOpen();
        public void onClose();
    }

    public interface UseCustomCloseListener {
        public void useCustomCloseChanged(boolean useCustomClose);
    }

    /**
     * Holds a weak reference to the activity if the context that is passed in is an activity.
     * While this field is never null, the reference could become null. This reference starts out
     * null if the passed-in context is not an activity.
     */
    @NonNull private final WeakReference<Activity> mWeakActivity;
    @NonNull private final Context mContext;
    @NonNull private final PlacementType mPlacementType;

    // An ad container, which contains the ad web view in default state, but is empty when expanded.
    @NonNull private final FrameLayout mDefaultAdContainer;

    // Ad ad container which contains the ad view in expanded state.
    @NonNull private final CloseableLayout mCloseableAdContainer;

    // Root view, where we'll add the expanded ad
    @Nullable private ViewGroup mRootView;

    // Helper classes for updating screen values
    @NonNull private final ScreenMetricsWaiter mScreenMetricsWaiter;
    @NonNull private final MraidScreenMetrics mScreenMetrics;

    // Current view state
    @NonNull private ViewState mViewState = ViewState.LOADING;

    // Listeners
    @Nullable private MraidListener mMraidListener;
    @Nullable private UseCustomCloseListener mOnCloseButtonListener;
    @Nullable private MraidWebViewDebugListener mDebugListener;

    // The WebView which will display the ad. "Two part" creatives, loaded via handleExpand(URL)
    // are shown in a separate web view
    @Nullable private MraidWebView mMraidWebView;
    @Nullable private MraidWebView mTwoPartWebView;

    // A bridge to handle all interactions with the WebView HTML and Javascript.
    @NonNull private final MraidBridge mMraidBridge;
    @NonNull private final MraidBridge mTwoPartBridge;

    @NonNull private OrientationBroadcastReceiver mOrientationBroadcastReceiver =
            new OrientationBroadcastReceiver();

    // Stores the requested orientation for the Activity to which this controller's view belongs.
    // This is needed to restore the Activity's requested orientation in the event that the view
    // itself requires an orientation lock.
    @Nullable private Integer mOriginalActivityOrientation;

    private boolean mAllowOrientationChange = true;
    private MraidOrientation mForceOrientation = MraidOrientation.NONE;

    private final MraidNativeCommandHandler mMraidNativeCommandHandler;

    private boolean mIsPaused;

    public MraidController(@NonNull Context context, @Nullable AdReport adReport,
            @NonNull PlacementType placementType) {
        this(context, adReport, placementType,
                new MraidBridge(adReport, placementType),
                new MraidBridge(adReport, PlacementType.INTERSTITIAL),
                new ScreenMetricsWaiter());
    }

    @VisibleForTesting
    MraidController(@NonNull Context context, @Nullable AdReport adReport,
            @NonNull PlacementType placementType,
            @NonNull MraidBridge bridge, @NonNull MraidBridge twoPartBridge,
            @NonNull ScreenMetricsWaiter screenMetricsWaiter) {
        mContext = context.getApplicationContext();
        Preconditions.checkNotNull(mContext);
        mAdReport = adReport;
        if (context instanceof Activity) {
            mWeakActivity = new WeakReference<Activity>((Activity) context);
        } else {
            // Make sure mWeakActivity itself is never null, though the reference
            // it's pointing to could be null.
            mWeakActivity = new WeakReference<Activity>(null);
        }

        mPlacementType = placementType;
        mMraidBridge = bridge;
        mTwoPartBridge = twoPartBridge;
        mScreenMetricsWaiter = screenMetricsWaiter;

        mViewState = ViewState.LOADING;

        DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
        mScreenMetrics = new MraidScreenMetrics(mContext, displayMetrics.density);
        mDefaultAdContainer = new FrameLayout(mContext);
        mCloseableAdContainer = new CloseableLayout(mContext);
        mCloseableAdContainer.setOnCloseListener(new OnCloseListener() {
            @Override
            public void onClose() {
                handleClose();
            }
        });

        View dimmingView = new View(mContext);
        dimmingView.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        mCloseableAdContainer.addView(dimmingView,
                new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

        mOrientationBroadcastReceiver.register(mContext);

        mMraidBridge.setMraidBridgeListener(mMraidBridgeListener);
        mTwoPartBridge.setMraidBridgeListener(mTwoPartBridgeListener);
        mMraidNativeCommandHandler = new MraidNativeCommandHandler();
    }

    @SuppressWarnings("FieldCanBeLocal")
    private final MraidBridgeListener mMraidBridgeListener = new MraidBridgeListener() {
        @Override
        public void onPageLoaded() {
            handlePageLoad();
        }

        @Override
        public void onPageFailedToLoad() {
            if (mMraidListener != null) {
                mMraidListener.onFailedToLoad();
            }
        }

        @Override
        public void onVisibilityChanged(final boolean isVisible) {
            // The bridge only receives visibility events if there is no 2 part covering it
            if (!mTwoPartBridge.isAttached()) {
                mMraidBridge.notifyViewability(isVisible);
            }
        }

        @Override
        public boolean onJsAlert(@NonNull final String message, @NonNull final JsResult result) {
            return handleJsAlert(message, result);
        }

        @Override
        public boolean onConsoleMessage(@NonNull final ConsoleMessage consoleMessage) {
            return handleConsoleMessage(consoleMessage);
        }

        @Override
        public void onClose() {
            handleClose();
        }

        @Override
        public void onResize(final int width, final int height, final int offsetX,
                final int offsetY, @NonNull final ClosePosition closePosition,
                final boolean allowOffscreen) throws MraidCommandException {
            handleResize(width, height, offsetX, offsetY, closePosition, allowOffscreen);
        }

        public void onExpand(@Nullable final URI uri, final boolean shouldUseCustomClose)
                throws MraidCommandException {
            handleExpand(uri, shouldUseCustomClose);
        }

        @Override
        public void onUseCustomClose(final boolean shouldUseCustomClose) {
            handleCustomClose(shouldUseCustomClose);
        }

        @Override
        public void onSetOrientationProperties(final boolean allowOrientationChange,
                final MraidOrientation forceOrientation) throws MraidCommandException {
            handleSetOrientationProperties(allowOrientationChange, forceOrientation);
        }

        @Override
        public void onOpen(@NonNull final URI uri) {
            handleOpen(uri.toString());
        }

        @Override
        public void onPlayVideo(@NonNull final URI uri) {
            handleShowVideo(uri.toString());
        }
    };

    @SuppressWarnings("FieldCanBeLocal")
    private final MraidBridgeListener mTwoPartBridgeListener = new MraidBridgeListener() {
        @Override
        public void onPageLoaded() {
            handleTwoPartPageLoad();
        }

        @Override
        public void onPageFailedToLoad() {
            // no-op for two-part expandables. An expandable failing to load should not trigger failover.
        }

        @Override
        public void onVisibilityChanged(final boolean isVisible) {
            // The original web view must see the 2-part bridges visibility
            mMraidBridge.notifyViewability(isVisible);
            mTwoPartBridge.notifyViewability(isVisible);
        }

        @Override
        public boolean onJsAlert(@NonNull final String message, @NonNull final JsResult result) {
            return handleJsAlert(message, result);
        }

        @Override
        public boolean onConsoleMessage(@NonNull final ConsoleMessage consoleMessage) {
            return handleConsoleMessage(consoleMessage);
        }

        @Override
        public void onResize(final int width, final int height, final int offsetX,
                final int offsetY, @NonNull final ClosePosition closePosition,
                final boolean allowOffscreen) throws MraidCommandException {
            throw new MraidCommandException("Not allowed to resize from an expanded state");
        }

        @Override
        public void onExpand(@Nullable final URI uri, final boolean shouldUseCustomClose) {
            // The MRAID spec dictates that this is ignored rather than firing an error
        }

        @Override
        public void onClose() {
            handleClose();
        }

        @Override
        public void onUseCustomClose(final boolean shouldUseCustomClose) {
            handleCustomClose(shouldUseCustomClose);
        }

        @Override
        public void onSetOrientationProperties(final boolean allowOrientationChange,
                final MraidOrientation forceOrientation) throws MraidCommandException {
            handleSetOrientationProperties(allowOrientationChange, forceOrientation);
        }

        @Override
        public void onOpen(final URI uri) {
            handleOpen(uri.toString());
        }

        @Override
        public void onPlayVideo(@NonNull final URI uri) {
            handleShowVideo(uri.toString());
        }
    };

    public void setMraidListener(@Nullable MraidListener mraidListener) {
        mMraidListener = mraidListener;
    }

    public void setUseCustomCloseListener(@Nullable UseCustomCloseListener listener) {
        mOnCloseButtonListener = listener;
    }

    public void setDebugListener(@Nullable MraidWebViewDebugListener debugListener) {
        mDebugListener = debugListener;
    }

    public void loadContent(@NonNull String htmlData) {
        Preconditions.checkState(mMraidWebView == null, "loadContent should only be called once");

        mMraidWebView = new MraidWebView(mContext);
        mMraidBridge.attachView(mMraidWebView);
        mDefaultAdContainer.addView(mMraidWebView,
                new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

        // onPageLoaded gets fired once the html is loaded into the webView
        mMraidBridge.setContentHtml(htmlData);
    }

    // onPageLoaded gets fired once the html is loaded into the webView.
    private int getDisplayRotation() {
        WindowManager wm = (WindowManager) mContext
                .getSystemService(Context.WINDOW_SERVICE);
        return wm.getDefaultDisplay().getRotation();
    }

    @VisibleForTesting
    boolean handleConsoleMessage(@NonNull final ConsoleMessage consoleMessage) {
        //noinspection SimplifiableIfStatement
        if (mDebugListener != null) {
            return mDebugListener.onConsoleMessage(consoleMessage);
        }
        return true;
    }

    @VisibleForTesting
    boolean handleJsAlert(@NonNull final String message, @NonNull final JsResult result) {
        if (mDebugListener != null) {
            return mDebugListener.onJsAlert(message, result);
        }
        result.confirm();
        return true;
    }

    @VisibleForTesting
    static class ScreenMetricsWaiter {
        static class WaitRequest {
            @NonNull private final View[] mViews;
            @NonNull private final Handler mHandler;
            @Nullable private Runnable mSuccessRunnable;
            int mWaitCount;

            private WaitRequest(@NonNull Handler handler, @NonNull final View[] views) {
                mHandler = handler;
                mViews = views;
            }

            private void countDown() {
                mWaitCount--;
                if (mWaitCount == 0 && mSuccessRunnable != null) {
                    mSuccessRunnable.run();
                    mSuccessRunnable = null;
                }
            }

            private final Runnable mWaitingRunnable = new Runnable() {
                @Override
                public void run() {
                    for (final View view : mViews) {
                        // Immediately count down for any views that already have a size
                        if (view.getHeight() > 0 || view.getWidth() > 0) {
                            countDown();
                            continue;
                        }

                        // For views that didn't have a size, listen (once) for a preDraw. Note
                        // that this doesn't leak because the ViewTreeObserver gets detached when
                        // the view is no longer part of the view hierarchy.
                        view.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {
                            @Override
                            public boolean onPreDraw() {
                                view.getViewTreeObserver().removeOnPreDrawListener(this);
                                countDown();
                                return true;
                            }
                        });
                    }
                }
            };

            void start(@NonNull Runnable successRunnable) {
                mSuccessRunnable = successRunnable;
                mWaitCount = mViews.length;
                mHandler.post(mWaitingRunnable);
            }

            void cancel() {
                mHandler.removeCallbacks(mWaitingRunnable);
                mSuccessRunnable = null;
            }
        }

        @NonNull private final Handler mHandler = new Handler();
        @Nullable private WaitRequest mLastWaitRequest;

        WaitRequest waitFor(@NonNull View... views) {
            mLastWaitRequest = new WaitRequest(mHandler, views);
            return mLastWaitRequest;
        }

        void cancelLastRequest() {
            if (mLastWaitRequest != null) {
                mLastWaitRequest.cancel();
                mLastWaitRequest = null;
            }
        }
    }

    @Nullable
    private View getCurrentWebView() {
        return mTwoPartBridge.isAttached() ? mTwoPartWebView : mMraidWebView;
    }

    private boolean isInlineVideoAvailable() {
        //noinspection SimplifiableIfStatement
        final Activity activity = mWeakActivity.get();
        if (activity == null || getCurrentWebView() == null) {
            return false;
        }

        return mMraidNativeCommandHandler.isInlineVideoAvailable(activity, getCurrentWebView());
    }

    @VisibleForTesting
    void handlePageLoad() {
        setViewState(ViewState.DEFAULT, new Runnable() {
            @Override
            public void run() {
                mMraidBridge.notifySupports(
                        mMraidNativeCommandHandler.isSmsAvailable(mContext),
                        mMraidNativeCommandHandler.isTelAvailable(mContext),
                        MraidNativeCommandHandler.isCalendarAvailable(mContext),
                        MraidNativeCommandHandler.isStorePictureSupported(mContext),
                        isInlineVideoAvailable());
                mMraidBridge.notifyPlacementType(mPlacementType);
                mMraidBridge.notifyViewability(mMraidBridge.isVisible());
                mMraidBridge.notifyReady();
            }
        });

        // Call onLoaded immediately. This causes the container to get added to the view hierarchy
        if (mMraidListener != null) {
            mMraidListener.onLoaded(mDefaultAdContainer);
        }
    }

    @VisibleForTesting
    void handleTwoPartPageLoad() {
        updateScreenMetricsAsync(new Runnable() {
            @Override
            public void run() {
                mTwoPartBridge.notifySupports(
                        mMraidNativeCommandHandler.isSmsAvailable(mContext),
                        mMraidNativeCommandHandler.isTelAvailable(mContext),
                        mMraidNativeCommandHandler.isCalendarAvailable(mContext),
                        mMraidNativeCommandHandler.isStorePictureSupported(mContext),
                        isInlineVideoAvailable());
                mTwoPartBridge.notifyViewState(mViewState);
                mTwoPartBridge.notifyPlacementType(mPlacementType);
                mTwoPartBridge.notifyViewability(mTwoPartBridge.isVisible());
                mTwoPartBridge.notifyReady();
            }
        });
    }

    /**
     * Updates screen metrics, calling the successRunnable once they are available. The
     * successRunnable will always be called asynchronously, ie on the next main thread loop.
     */
    private void updateScreenMetricsAsync(@Nullable final Runnable successRunnable) {
        // Don't allow multiple metrics wait requests at once
        mScreenMetricsWaiter.cancelLastRequest();

        // Determine which web view should be used for the current ad position
        final View currentWebView = getCurrentWebView();
        if (currentWebView == null) {
            return;
        }

        // Wait for the next draw pass on the default ad container and current web view
        mScreenMetricsWaiter.waitFor(mDefaultAdContainer, currentWebView).start(
                new Runnable() {
                    @Override
                    public void run() {
                        DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
                        mScreenMetrics.setScreenSize(
                                displayMetrics.widthPixels, displayMetrics.heightPixels);

                        int[] location = new int[2];
                        View rootView = getRootView();
                        rootView.getLocationOnScreen(location);
                        mScreenMetrics.setRootViewPosition(location[0], location[1],
                                rootView.getWidth(),
                                rootView.getHeight());

                        mDefaultAdContainer.getLocationOnScreen(location);
                        mScreenMetrics.setDefaultAdPosition(location[0], location[1],
                                mDefaultAdContainer.getWidth(),
                                mDefaultAdContainer.getHeight());

                        currentWebView.getLocationOnScreen(location);
                        mScreenMetrics.setCurrentAdPosition(location[0], location[1],
                                currentWebView.getWidth(),
                                currentWebView.getHeight());

                        // Always notify both bridges of the new metrics
                        mMraidBridge.notifyScreenMetrics(mScreenMetrics);
                        if (mTwoPartBridge.isAttached()) {
                            mTwoPartBridge.notifyScreenMetrics(mScreenMetrics);
                        }

                        if (successRunnable != null) {
                            successRunnable.run();
                        }
                    }
                });
    }

    void handleOrientationChange(int currentRotation) {
        updateScreenMetricsAsync(null);
    }

    public void pause(boolean isFinishing) {
        mIsPaused = true;

        // This causes an inline video to pause if there is one playing
        if (mMraidWebView != null) {
            WebViews.onPause(mMraidWebView, isFinishing);
        }
        if (mTwoPartWebView != null) {
            WebViews.onPause(mTwoPartWebView, isFinishing);
        }
    }

    public void resume() {
        mIsPaused = false;

        // This causes an inline video to resume if it was playing previously
        if (mMraidWebView != null) {
            WebViews.onResume(mMraidWebView);
        }
        if (mTwoPartWebView != null) {
            WebViews.onResume(mTwoPartWebView);
        }
    }

    public void destroy() {
        mScreenMetricsWaiter.cancelLastRequest();

        try {
            mOrientationBroadcastReceiver.unregister();
        } catch (IllegalArgumentException e) {
            if (!e.getMessage().contains("Receiver not registered")) {
                throw e;
            } // Else ignore this exception.
        }

        // Pause the controller to make sure the video gets stopped.
        if (!mIsPaused) {
            pause(true);
        }

        // Remove the closeable ad container from the view hierarchy, if necessary
        Views.removeFromParent(mCloseableAdContainer);

        // Calling destroy eliminates a memory leak on Gingerbread devices
        mMraidBridge.detach();
        if (mMraidWebView != null) {
            mMraidWebView.destroy();
            mMraidWebView = null;
        }
        mTwoPartBridge.detach();
        if (mTwoPartWebView != null) {
            mTwoPartWebView.destroy();
            mTwoPartWebView = null;
        }
    }

    private void setViewState(@NonNull ViewState viewState) {
        setViewState(viewState, null);
    }

    private void setViewState(@NonNull ViewState viewState, @Nullable Runnable successRunnable) {
        // Make sure this is a valid transition.
        MoPubLog.d("MRAID state set to " + viewState);
        mViewState = viewState;
        mMraidBridge.notifyViewState(viewState);

        // Changing state notifies the two part view, but only if it's loaded
        if (mTwoPartBridge.isLoaded()) {
            mTwoPartBridge.notifyViewState(viewState);
        }

        if (mMraidListener != null) {
            if (viewState == ViewState.EXPANDED) {
                mMraidListener.onExpand();
            } else if (viewState == ViewState.HIDDEN) {
                mMraidListener.onClose();
            }
        }

        updateScreenMetricsAsync(successRunnable);
    }

    int clampInt(int min, int target, int max) {
        return Math.max(min, Math.min(target, max));
    }

    @VisibleForTesting
    void handleResize(final int widthDips, final int heightDips, final int offsetXDips,
            final int offsetYDips, @NonNull final ClosePosition closePosition,
            final boolean allowOffscreen)
            throws MraidCommandException {
        if (mMraidWebView == null) {
            throw new MraidCommandException("Unable to resize after the WebView is destroyed");
        }

        // The spec says that there is no effect calling resize from loaded or hidden, but that
        // calling it from expanded should raise an error.
        if (mViewState == ViewState.LOADING
                || mViewState == ViewState.HIDDEN) {
            return;
        } else if (mViewState == ViewState.EXPANDED) {
            throw new MraidCommandException("Not allowed to resize from an already expanded ad");
        }

        if (mPlacementType == PlacementType.INTERSTITIAL) {
            throw new MraidCommandException("Not allowed to resize from an interstitial ad");
        }

        // Translate coordinates to px and get the resize rect
        int width = Dips.dipsToIntPixels(widthDips, mContext);
        int height = Dips.dipsToIntPixels(heightDips, mContext);
        int offsetX = Dips.dipsToIntPixels(offsetXDips, mContext);
        int offsetY = Dips.dipsToIntPixels(offsetYDips, mContext);
        int left = mScreenMetrics.getDefaultAdRect().left + offsetX;
        int top = mScreenMetrics.getDefaultAdRect().top + offsetY;
        Rect resizeRect = new Rect(left, top, left + width, top + height);

        if (!allowOffscreen) {
            // Require the entire ad to be on-screen.
            Rect bounds = mScreenMetrics.getRootViewRect();
            if (resizeRect.width() > bounds.width() || resizeRect.height() > bounds.height()) {
                throw new MraidCommandException("resizeProperties specified a size ("
                        + widthDips + ", " + heightDips + ") and offset ("
                        + offsetXDips + ", " + offsetYDips + ") that doesn't allow the ad to"
                        + " appear within the max allowed size ("
                        + mScreenMetrics.getRootViewRectDips().width() + ", "
                        + mScreenMetrics.getRootViewRectDips().height() + ")");
            }

            // Offset the resize rect so that it displays on the screen
            int newLeft = clampInt(bounds.left, resizeRect.left, bounds.right - resizeRect.width());
            int newTop = clampInt(bounds.top, resizeRect.top, bounds.bottom - resizeRect.height());
            resizeRect.offsetTo(newLeft, newTop);
        }

        // The entire close region must always be visible.
        Rect closeRect = new Rect();
        mCloseableAdContainer.applyCloseRegionBounds(closePosition, resizeRect, closeRect);
        if (!mScreenMetrics.getRootViewRect().contains(closeRect)) {
            throw new MraidCommandException("resizeProperties specified a size ("
                    + widthDips + ", " + heightDips + ") and offset ("
                    + offsetXDips + ", " + offsetYDips + ") that doesn't allow the close"
                    + " region to appear within the max allowed size ("
                    + mScreenMetrics.getRootViewRectDips().width() + ", "
                    + mScreenMetrics.getRootViewRectDips().height() + ")");
        }

        if (!resizeRect.contains(closeRect)) {
            throw new MraidCommandException("resizeProperties specified a size ("
                    + widthDips + ", " + height + ") and offset ("
                    + offsetXDips + ", " + offsetYDips + ") that don't allow the close region to appear "
                    + "within the resized ad.");
        }

        // Resized ads always rely on the creative's close button (as if useCustomClose were true)
        mCloseableAdContainer.setCloseVisible(false);
        mCloseableAdContainer.setClosePosition(closePosition);

        // Put the ad in the closeable container and resize it
        LayoutParams layoutParams = new LayoutParams(resizeRect.width(), resizeRect.height());
        layoutParams.leftMargin = resizeRect.left - mScreenMetrics.getRootViewRect().left;
        layoutParams.topMargin = resizeRect.top - mScreenMetrics.getRootViewRect().top;
        if (mViewState == ViewState.DEFAULT) {
            mDefaultAdContainer.removeView(mMraidWebView);
            mDefaultAdContainer.setVisibility(View.INVISIBLE);
            mCloseableAdContainer.addView(mMraidWebView,
                    new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            getRootView().addView(mCloseableAdContainer, layoutParams);
        } else if (mViewState == ViewState.RESIZED) {
            mCloseableAdContainer.setLayoutParams(layoutParams);
        }
        mCloseableAdContainer.setClosePosition(closePosition);

        setViewState(ViewState.RESIZED);
    }

    void handleExpand(@Nullable URI uri, boolean shouldUseCustomClose)
            throws MraidCommandException {
        if (mMraidWebView == null) {
            throw new MraidCommandException("Unable to expand after the WebView is destroyed");
        }

        if (mPlacementType == PlacementType.INTERSTITIAL) {
            return;
        }

        if (mViewState != ViewState.DEFAULT && mViewState != ViewState.RESIZED) {
            return;
        }

        applyOrientation();

        // For two part expands, create a new web view
        boolean isTwoPart = (uri != null);
        if (isTwoPart) {
            // Of note: the two part ad will start off with its view state as LOADING, and will
            // transition to EXPANDED once the page is fully loaded
            mTwoPartWebView = new MraidWebView(mContext);
            mTwoPartBridge.attachView(mTwoPartWebView);

            // onPageLoaded gets fired once the html is loaded into the two part webView
            mTwoPartBridge.setContentUrl(uri.toString());
        }

        // Make sure the correct webView is in the closeable  container and make it full screen
        LayoutParams layoutParams = new LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        if (mViewState == ViewState.DEFAULT) {
            if (isTwoPart) {
                mCloseableAdContainer.addView(mTwoPartWebView, layoutParams);
            } else {
                mDefaultAdContainer.removeView(mMraidWebView);
                mDefaultAdContainer.setVisibility(View.INVISIBLE);
                mCloseableAdContainer.addView(mMraidWebView, layoutParams);
            }
            getRootView().addView(mCloseableAdContainer,
                    new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        } else if (mViewState == ViewState.RESIZED) {
            if (isTwoPart) {
                // Move the ad back to the original container so that when we close the
                // resized ad, it will be in the correct place
                mCloseableAdContainer.removeView(mMraidWebView);
                mDefaultAdContainer.addView(mMraidWebView, layoutParams);
                mDefaultAdContainer.setVisibility(View.INVISIBLE);
                mCloseableAdContainer.addView(mTwoPartWebView, layoutParams);
            }
            // If we were resized and not 2 part, nothing to do.
        }
        mCloseableAdContainer.setLayoutParams(layoutParams);
        handleCustomClose(shouldUseCustomClose);

        // Update to expanded once we have new screen metrics. This won't update the two-part ad,
        // because it is not yet loaded.
        setViewState(ViewState.EXPANDED);
    }

    @VisibleForTesting
    void handleClose() {
        if (mMraidWebView == null) {
            // Doesn't throw an exception because the ad has been destroyed
            return;
        }

        if (mViewState == ViewState.LOADING || mViewState == ViewState.HIDDEN) {
            return;
        }

        // Unlock the orientation before changing the view hierarchy.
        if (mViewState == ViewState.EXPANDED || mPlacementType == PlacementType.INTERSTITIAL) {
            unApplyOrientation();
        }

        if (mViewState == ViewState.RESIZED || mViewState == ViewState.EXPANDED) {
            if (mTwoPartBridge.isAttached() && mTwoPartWebView != null) {
                // If we have a two part web view, simply remove it from the closeable container
                mCloseableAdContainer.removeView(mTwoPartWebView);
                mTwoPartBridge.detach();
            } else {
                // Move the web view from the closeable container back to the default container
                mCloseableAdContainer.removeView(mMraidWebView);
                mDefaultAdContainer.addView(mMraidWebView, new LayoutParams(
                        LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
                mDefaultAdContainer.setVisibility(View.VISIBLE);
            }
            getRootView().removeView(mCloseableAdContainer);

            // Set the view state to default
            setViewState(ViewState.DEFAULT);
        } else if (mViewState == ViewState.DEFAULT) {
            mDefaultAdContainer.setVisibility(View.INVISIBLE);
            setViewState(ViewState.HIDDEN);
        }
    }

    @NonNull
    @TargetApi(VERSION_CODES.KITKAT)
    private ViewGroup getRootView() {
        if (mRootView == null) {
            // This method should never be called this method before the container is ready, ie before
            // handlePageLoad.
            if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
                Preconditions.checkState(mDefaultAdContainer.isAttachedToWindow());
            }

            mRootView = (ViewGroup) mDefaultAdContainer.getRootView().findViewById(
                    android.R.id.content);
        }

        return mRootView;
    }

    @VisibleForTesting
    void handleShowVideo(@NonNull String videoUrl) {
        MraidVideoPlayerActivity.startMraid(mContext, videoUrl);
    }

    @VisibleForTesting
    void lockOrientation(final int screenOrientation) throws MraidCommandException {
        final Activity activity = mWeakActivity.get();
        if (activity == null || !shouldAllowForceOrientation(mForceOrientation)) {
            throw new MraidCommandException("Attempted to lock orientation to unsupported value: " +
                    mForceOrientation.name());
        }

        if (mOriginalActivityOrientation == null) {
            mOriginalActivityOrientation = activity.getRequestedOrientation();
        }

        activity.setRequestedOrientation(screenOrientation);
    }

    @VisibleForTesting
    void applyOrientation() throws MraidCommandException {
        if (mForceOrientation == MraidOrientation.NONE) {
            if (mAllowOrientationChange) {
                // If screen orientation can be changed, an orientation of NONE means that any
                // orientation lock should be removed
                unApplyOrientation();
            } else {
                final Activity activity = mWeakActivity.get();
                if (activity == null) {
                    throw new MraidCommandException("Unable to set MRAID expand orientation to " +
                            "'none'; expected passed in Activity Context.");
                }

                // If screen orientation cannot be changed and we can obtain the current
                // screen orientation, locking it to the current orientation is a best effort
                lockOrientation(DeviceUtils.getScreenOrientation(activity));
            }
        } else {
            // Otherwise, we have a valid, non-NONE orientation. Lock the screen based on this value
            lockOrientation(mForceOrientation.getActivityInfoOrientation());
        }
    }

    @VisibleForTesting
    void unApplyOrientation() {
        final Activity activity = mWeakActivity.get();
        if (activity != null && mOriginalActivityOrientation != null) {
            activity.setRequestedOrientation(mOriginalActivityOrientation);
        }
        mOriginalActivityOrientation = null;
    }

    @TargetApi(VERSION_CODES.HONEYCOMB_MR2)
    @VisibleForTesting
    boolean shouldAllowForceOrientation(final MraidOrientation newOrientation) {
        // NONE is the default and always allowed
        if (newOrientation == MraidOrientation.NONE) {
            return true;
        }

        final Activity activity = mWeakActivity.get();
        // If we can't obtain an Activity, return false
        if (activity == null) {
            return false;
        }

        final ActivityInfo activityInfo;
        try {
            activityInfo = activity.getPackageManager().getActivityInfo(
                    new ComponentName(activity, activity.getClass()), 0);
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }

        // If an orientation is explicitly declared in the manifest, allow forcing this orientation
        final int activityOrientation = activityInfo.screenOrientation;
        if (activityOrientation != ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) {
            return activityOrientation == newOrientation.getActivityInfoOrientation();
        }

        // Make sure the config changes won't tear down the activity when moving to this orientation
        // The necessary configChanges must always include "orientation"
        boolean containsNecessaryConfigChanges =
                bitMaskContainsFlag(activityInfo.configChanges, CONFIG_ORIENTATION);

        // And on API 13+, configChanges must also include "screenSize"
        if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB_MR2) {
            containsNecessaryConfigChanges = containsNecessaryConfigChanges
                    && bitMaskContainsFlag(activityInfo.configChanges, CONFIG_SCREEN_SIZE);
        }

        return containsNecessaryConfigChanges;
    }

    @VisibleForTesting
    void handleCustomClose(boolean useCustomClose) {
        boolean wasUsingCustomClose = !mCloseableAdContainer.isCloseVisible();
        if (useCustomClose == wasUsingCustomClose) {
            return;
        }

        mCloseableAdContainer.setCloseVisible(!useCustomClose);
        if (mOnCloseButtonListener != null) {
            mOnCloseButtonListener.useCustomCloseChanged(useCustomClose);
        }
    }

    @NonNull
    public FrameLayout getAdContainer() {
        return mDefaultAdContainer;
    }

    /**
     * Loads a javascript URL. Useful for running callbacks, such as javascript:webviewDidClose()
     */
    public void loadJavascript(@NonNull String javascript) {
        mMraidBridge.injectJavaScript(javascript);
    }

    @VisibleForTesting
    class OrientationBroadcastReceiver extends BroadcastReceiver {
        @Nullable private Context mContext;

        // -1 until this gets set at least once
        private int mLastRotation = -1;

        @Override
        public void onReceive(Context context, Intent intent) {
            if (mContext == null) {
                return;
            }

            if (Intent.ACTION_CONFIGURATION_CHANGED.equals(intent.getAction())) {
                int orientation = getDisplayRotation();

                if (orientation != mLastRotation) {
                    mLastRotation = orientation;
                    handleOrientationChange(mLastRotation);
                }
            }
        }

        public void register(@NonNull final Context context) {
            Preconditions.checkNotNull(context);
            mContext = context.getApplicationContext();
            if (mContext != null) {
                mContext.registerReceiver(this,
                        new IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED));
            }
        }

        public void unregister() {
            if (mContext != null) {
                mContext.unregisterReceiver(this);
                mContext = null;
            }
        }
    }

    @NonNull
    public Context getContext() {
        return mContext;
    }

    @VisibleForTesting
    void handleSetOrientationProperties(final boolean allowOrientationChange,
            final MraidOrientation forceOrientation) throws MraidCommandException {
        if (!shouldAllowForceOrientation(forceOrientation)) {
            throw new MraidCommandException(
                    "Unable to force orientation to " + forceOrientation);
        }

        mAllowOrientationChange = allowOrientationChange;
        mForceOrientation = forceOrientation;

        if (mViewState == ViewState.EXPANDED || mPlacementType == PlacementType.INTERSTITIAL) {
            applyOrientation();
        }
    }

    /**
     * Attempts to handle mopubnativebrowser links in the device browser, deep-links in the
     * corresponding application, and all other links in the MoPub in-app browser.
     */
    @VisibleForTesting
    void handleOpen(@NonNull final String url) {
        MoPubLog.d("Opening url: " + url);

        if (mMraidListener != null) {
            mMraidListener.onOpen();
        }

        if (Intents.isAboutScheme(url)) {
            MoPubLog.d("Link to about page ignored.");
            return;
        }

        // MoPubNativeBrowser URLs
        if (Intents.isNativeBrowserScheme(url)) {
            try {
                final Intent intent = Intents.intentForNativeBrowserScheme(url);
                Intents.startActivity(mContext, intent);
            } catch (UrlParseException e) {
                MoPubLog.d("Unable to load mopub native browser url: " + url + ". "
                        + e.getMessage());
            } catch (IntentNotResolvableException e) {
                MoPubLog.d("Unable to load mopub native browser url: " + url + ". "
                        + e.getMessage());
            }

            return;
        }

        if (Intents.isHttpUrl(url)) {
            final Bundle extras = new Bundle();
            extras.putString(MoPubBrowser.DESTINATION_URL_KEY, url);

            final Intent intent = Intents.getStartActivityIntent(mContext, MoPubBrowser.class,
                    extras);
            try {
                Intents.startActivity(mContext, intent);
            } catch (IntentNotResolvableException e) {
                MoPubLog.d("Unable to launch intent for URL: " + url + ".");
            }
            return;
        }

        // Non-http(s) URLs like app deep links
        if (Intents.canHandleApplicationUrl(mContext, url)) {
            final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));

            try {
                Intents.startActivity(mContext, intent);
            } catch (IntentNotResolvableException e) {
                MoPubLog.d("Unable to resolve application url: " + url);
            }
            return;
        }

        MoPubLog.d("Link ignored. Unable to handle url: " + url);
    }

    @VisibleForTesting
    @Deprecated // for testing
    @NonNull
    ViewState getViewState() {
        return mViewState;
    }

    @VisibleForTesting
    @Deprecated // for testing
    void setViewStateForTesting(@NonNull ViewState viewState) {
        mViewState = viewState;
    }

    @VisibleForTesting
    @Deprecated // for testing
    @NonNull
    CloseableLayout getExpandedAdContainer() {
        return mCloseableAdContainer;
    }

    @VisibleForTesting
    @Deprecated // for testing
    void setRootView(FrameLayout rootView) {
        mRootView = rootView;
    }

    @VisibleForTesting
    @Deprecated // for testing
    void setRootViewSize(int width, int height) {
        mScreenMetrics.setRootViewPosition(0, 0, width, height);
    }

    @VisibleForTesting
    @Deprecated // for testing
    Integer getOriginalActivityOrientation() {
        return mOriginalActivityOrientation;
    }

    @VisibleForTesting
    @Deprecated // for testing
    boolean getAllowOrientationChange() {
        return mAllowOrientationChange;
    }

    @VisibleForTesting
    @Deprecated // for testing
    MraidOrientation getForceOrientation() {
        return mForceOrientation;
    }

    @VisibleForTesting
    @Deprecated // for testing
    void setOrientationBroadcastReceiver(OrientationBroadcastReceiver receiver) {
        mOrientationBroadcastReceiver = receiver;
    }

    @VisibleForTesting
    @Deprecated // for testing
    MraidWebView getMraidWebView() {
        return mMraidWebView;
    }

    @VisibleForTesting
    @Deprecated // for testing
    MraidWebView getTwoPartWebView() {
        return mTwoPartWebView;
    }
}


text:
kuvauksen kirjoitti: Mikko Huuhka
## Lyhyt määritelmä
Rational unified process tai RUP on iteratiivinen ohjelmistonkehitysmalli. RUP sisältää 4 eri vaihetta, jossa jokaisessa on omat tehtävät jotka pitäisi toteuttaa.
* **Voimaantulovaihe** _Projektin arviointi, Riskiarviointi ja projektisuunnitelma_. Voidaan siis myös sanoa että tämä vaihe on pääosin bisnesvaihe. Mietitään onko mitään järkeä edes alkaa tekemään suunniteltua projektia. Mietitään mahdolliset riskit ja aletaan luomaan projektisuunnitelmaa.
* **Kehittelyvaihe** _Riskienkarsinta, use-caset ja kehityssuunnitelma_. Tässä vaiheessa aiemmin todetut riskit otetaan tarkempaan tarkasteluun ja koitetaan karsia niitä. Mietitään projektin kehityssuunnitelmaa ja aletaan tuottamaan use-caseja jotta saadaan mahdollisimman hyvä kuva projektista. Tehdään mahdollinen prototyyppi.
* **Rakennusvaihe** _Koodaus, kehitys ja viimeistely_. Tässä vaiheessa alkaa ohjelmiston varsinainen koodaus ja tuottaminen. Aletaan kehittämään projektia valmiiksi, ja voidaan myös alkaa miettimään lopullista tuotetta.
* **Muutosvaihe** _Päivitys, Ylläpito, Laadunvarmistus_. Viimeisessä vaiheessa aletaan tekemään kehitysvaiheessa olevasta tuotteesta valmista tuotetta. Koulutetaan tarvittavat henkilöt ylläpitämään valmista ohjelmistoa. Ohjelmiston päivittäminen ja testaaminen myös kuuluvat tähän viimeiseen vaiheeseen.

![RUP](https://upload.wikimedia.org/wikipedia/commons/1/19/Development-iterative.png)
##

## Lähteitä liittyen aiheeseen
* [agilemodeling.com](http://www.agilemodeling.com/essays/agileModelingRUP.htm)
* [RUP methodology](http://www.my-project-management-expert.com/rup-methodology.html)

## Linkit wikin muihin sivuihin
[Ketterä kehittäminen](https://github.com/JAMK-IT/IIO12110-harjoitus-gt0/wiki/aihe%20ketter%C3%A4%20kehitt%C3%A4minen)


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project default="create_run_jar" name="Create Runnable Jar for Project JavaFXExample">
    <!--this file was created by Eclipse Runnable JAR Export Wizard-->
    <!--ANT 1.7 is required                                        -->
    <!--define folder properties-->
    <property name="dir.buildfile" value="."/>
    <property name="dir.workspace" value="${dir.buildfile}/.."/>
    <property name="dir.jarfile" value="/builds/Talonite/"/>
    <target name="create_run_jar">
        <jar destfile="${dir.jarfile}/Talonite_ClientServer.jar" filesetmanifest="mergewithoutmain">
            <manifest>
                <attribute name="Main-Class" value="com.evanrobertcampbell.impl.main.Main"/>
                <attribute name="Class-Path" value="."/>
            </manifest>
            <fileset dir="${dir.buildfile}/bin"/>
        </jar>
    </target>
</project>


text:
@interface TYPeoplePickerController() <ABPeoplePickerNavigationControllerDelegate,CNContactPickerDelegate>

@end

@implementation TYPeoplePickerController

- (void)show {

    if (IOS9) {

        CNContactPickerViewController *picker = [CNContactPickerViewController new];
        picker.delegate = self;
        picker.displayedPropertyKeys = @[CNContactPhoneNumbersKey,CNContactEmailAddressesKey];

        [tp_topMostViewController() presentViewController:picker animated:YES completion:nil];

    } else {

        ABPeoplePickerNavigationController *picker = [ABPeoplePickerNavigationController new];
        picker.peoplePickerDelegate = self;

        picker.displayedProperties = @[@(kABPersonPhoneProperty),@(kABPersonEmailProperty)];
        picker.predicateForSelectionOfPerson = [NSPredicate predicateWithValue:false];

        [tp_topMostViewController() presentViewController:picker animated:YES completion:nil];

    }
}

//iOS9 iOS10
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty {
    NSLog(@"sss %@",contactProperty.contact.familyName);

    id contactPropertyValue = contactProperty.value;

    if ([contactPropertyValue isKindOfClass:[NSString class]]) {

        [self.delegate peoplePickerController:self didselectCountryModel:nil phoneNumber:contactPropertyValue];

    } else if ([contactPropertyValue isKindOfClass:[CNPhoneNumber class]])  {

        CNPhoneNumber *phoneNumberValue = contactProperty.value;

        NSString *phone = phoneNumberValue.stringValue;

        NBPhoneNumberUtil *phoneUtil = [[NBPhoneNumberUtil alloc] init];
        NSError *anError = nil;
        NBPhoneNumber *myNumber = [phoneUtil parse:phone
                                     defaultRegion:[TPUtils getISOcountryCode]
                                             error:&anError];
        if (anError) {
            NSLog(@"Error : %@", [anError localizedDescription]);
            return;
        }

        NSString *nationalNumber = @"";
        NSString *phoneNumber = [phoneUtil format:myNumber
                                     numberFormat:NBEPhoneNumberFormatE164
                                            error:&anError];
        NSNumber *countryCode = [phoneUtil extractCountryCode:phoneNumber nationalNumber:&nationalNumber];
        NSString *regionCode = [phoneUtil getRegionCodeForCountryCode:countryCode];

        TPCountryModel *countryCodeModel = [TPCountryService getCountryModel:regionCode];

        [self.delegate peoplePickerController:self didselectCountryModel:countryCodeModel phoneNumber:nationalNumber];

    }
}

#pragma mark - ABPeoplePickerNavigationControllerDelegate
//iOS8
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {

    ABMultiValueRef emailMulti = ABRecordCopyValue(person, kABPersonEmailProperty);

    if (emailMulti) {

        long index = ABMultiValueGetIndexForIdentifier(emailMulti, identifier);
        if (index < 0) {
            CFRelease(emailMulti);
            return;
        }

        NSString *email = (NSString *)CFBridgingRelease(ABMultiValueCopyValueAtIndex(emailMulti, index));

        CFRelease(emailMulti);

        [self.delegate peoplePickerController:self didselectCountryModel:nil phoneNumber:email];

        return;

    }

    ABMultiValueRef phoneMulti = ABRecordCopyValue(person, kABPersonPhoneProperty);
    if (!phoneMulti) {
        return;
    }

    long index = ABMultiValueGetIndexForIdentifier(phoneMulti, identifier);
    if (index < 0) {
        CFRelease(phoneMulti);
        return;
    }

//    NSString *name = (NSString *)CFBridgingRelease(ABRecordCopyCompositeName(person));
    NSString *phone = (NSString *)CFBridgingRelease(ABMultiValueCopyValueAtIndex(phoneMulti, index));

    CFRelease(phoneMulti);

    NBPhoneNumberUtil *phoneUtil = [[NBPhoneNumberUtil alloc] init];
    NSError *anError = nil;
    NBPhoneNumber *myNumber = [phoneUtil parse:phone
                                 defaultRegion:[TPUtils getISOcountryCode]
                                         error:&anError];
    if (anError) {
        NSLog(@"Error : %@", [anError localizedDescription]);
        return;
    }

    NSString *nationalNumber = @"";
    NSString *phoneNumber = [phoneUtil format:myNumber
                                 numberFormat:NBEPhoneNumberFormatE164
                                        error:&anError];
    NSNumber *countryCode = [phoneUtil extractCountryCode:phoneNumber nationalNumber:&nationalNumber];
    NSString *regionCode = [phoneUtil getRegionCodeForCountryCode:countryCode];

    TPCountryModel *countryCodeModel = [TPCountryService getCountryModel:regionCode];

    //15088667998 / 150-8866-7998 / 8615088667998 / +86 150-8866-7998
    //0571-87150683 / +86 (0)571-87150683
//    NSLog(@"name:%@ countryCode:%@ nationalNumber:%@", name, countryCode, nationalNumber);

    if ([self.delegate respondsToSelector:@selector(peoplePickerController:didselectCountryModel:phoneNumber:)]) {
        [self.delegate peoplePickerController:self didselectCountryModel:countryCodeModel phoneNumber:nationalNumber];
    }
}

- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker {
}

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HIO_Backup.Interface;
using Alphaleonis.Win32.Filesystem;
using Newtonsoft.Json;

namespace HIO_Backup.Persistence
{
    class DirectoryListDiskRepository : IDirectoryListRepository
    {
        private string FilePath;

        //-Constructor
        public async Task<DirectoryListDiskRepository> InitializeAsync(string configDir)
        {
            await Task.Run(() => Directory.CreateDirectory(configDir));
            this.FilePath = Path.Combine(configDir, "directories.json");

            if(false == await Task.Run(() => File.Exists(this.FilePath)))
            {
                await this.WriteJsonAsync(new List<string>());
            }

            return this;
        }

        public static async Task<DirectoryListDiskRepository> CreateAsync(string configDir)
        {
            DirectoryListDiskRepository instance = new DirectoryListDiskRepository();
            return await instance.InitializeAsync(configDir);
        }

        //-Read
        private async Task<List<string>> ReadJsonAsync()
        {
            string json;

            using (System.IO.StreamReader reader = new System.IO.StreamReader(this.FilePath))
            {
                json = await reader.ReadToEndAsync();
            }

            return await Task.Run(() => JsonConvert.DeserializeObject<List<string>>(json));
        }

        //-Write
        private async Task WriteJsonAsync(List<string> list)
        {
            string json = await Task.Run(() => JsonConvert.SerializeObject(list));
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(this.FilePath))
            {
                await writer.WriteAsync(json);
            }
        }

        //-Add
        public async Task AddAsync(string path)
        {
            List<string> diskList = await this.ReadJsonAsync();

            if (!diskList.Contains(path))
            {
                diskList.Add(path);
                await this.WriteJsonAsync(diskList);
            }
        }

        //-Remove
        public async Task DeleteAsync(string path)
        {
            List<string> diskList = await this.ReadJsonAsync();

            if (diskList.Contains(path))
            {
                diskList.Remove(path);
                await this.WriteJsonAsync(diskList);
            }
        }

        //-Get
        public async Task<List<string>> GetAsync()
        {
            return await this.ReadJsonAsync();
        }

    }
}


text:
package chandu0101.scalajs.react.components.materialui

import scala.scalajs.js

@js.native
trait MuiUtil extends js.Object {
  val CssEvent:         js.Dynamic       = js.native
  val Dom:              js.Dynamic       = js.native
  val Events:           js.Dynamic       = js.native
  val KeyCode:          js.Dynamic       = js.native
  val KeyLine:          js.Dynamic       = js.native
  val ColorManipulator: ColorManipulator = js.native
  val Extend:           js.Dynamic       = js.native
  val UniqueId:         js.Dynamic       = js.native
}

@js.native
trait ColorManipulator extends js.Object {
  def fade(color: MuiColor, amount: Double): MuiColor = js.native
  def lighten(color: MuiColor, amount: Double): MuiColor = js.native
  def darken(color: MuiColor, amount: Double): MuiColor = js.native
  def contrastRatio(background: MuiColor, foreground: MuiColor): Double = js.native
  def contrastRatioLevel(background: MuiColor, foreground: MuiColor): String = js.native
}


text:
"use strict";

var sphero = require("../");
var orb = sphero(process.env.PORT);

orb.connect(function() {
  // sets color to the provided r/g/b values
  orb.color({ red: 255, green: 0, blue: 255 });

  setTimeout(function() {
    console.log("color 1 -50% luminance");
    // sets color to the provided hex value, at -50% luminance
    orb.color(0xcc0000, -0.5);
  }, 1000);

  setTimeout(function() {
    console.log("color 1 normal% luminance");
    // sets color to the same hex value, at +50% luminance
    orb.color(0xcc0000, 0);
  }, 2000);

  setTimeout(function() {
    console.log("color 1 +50% luminance");
    // sets color to the same hex value, at +50% luminance
    orb.color(0xcc0000, 0.5);
  }, 3000);

  setTimeout(function() {
    console.log("color 2 -50% luminance");
    // hex numbers can also be passed in strings
    orb.color("00cc00", -0.5);
  }, 4000);

  setTimeout(function() {
    console.log("color 2 normal% luminance");
    // hex numbers can also be passed in strings
    orb.color("00cc00", 0);
  }, 5000);

  setTimeout(function() {
    console.log("color 2 +50% luminance");
    // hex numbers can also be passed in strings
    orb.color("00cc00", 0.5);
  }, 6000);

  setTimeout(function() {
    console.log("color 3 -50% luminance");
    // sets color to the provided color name
    orb.color("magenta", -0.5);
  }, 7000);

  setTimeout(function() {
    console.log("color 3 normal% luminance");
    // sets color to the provided color name
    orb.color("magenta", 0);
  }, 8000);

  setTimeout(function() {
    console.log("color 3 +50% luminance");
    // sets color to the provided color name
    orb.color("magenta", 0.5);
  }, 9000);
});


text:
package in.co.madhur.dashclock.dashanalytics;

import android.content.Context;
import in.co.madhur.dashclock.AppPreferences;
import in.co.madhur.dashclock.Consts;

public class AnalyticsPreferences extends AppPreferences
{

	public AnalyticsPreferences(Context context)
	{
		this.context = context;
		this.sharedPreferences = context.getSharedPreferences(Consts.ANALYTICS_PREFERENCE_NAME, Context.MODE_PRIVATE);

	}

}


text:
module GhostWriter
  VERSION = "0.5.0"
end


text:
namespace cc {
namespace {
// These constants were chosen empirically for their visually pleasant behavior.
// Contact tedchoc@chromium.org for questions about changing these values.
const int64 kShowHideMaxDurationMs = 175;
}

// static
scoped_ptr<TopControlsManager> TopControlsManager::Create(
    TopControlsManagerClient* client,
    float top_controls_height,
    float top_controls_show_threshold,
    float top_controls_hide_threshold) {
  return make_scoped_ptr(new TopControlsManager(client,
                                                top_controls_height,
                                                top_controls_show_threshold,
                                                top_controls_hide_threshold));
}

TopControlsManager::TopControlsManager(TopControlsManagerClient* client,
                                       float top_controls_height,
                                       float top_controls_show_threshold,
                                       float top_controls_hide_threshold)
    : client_(client),
      animation_direction_(NO_ANIMATION),
      visibility_restriction_(NONE),
      controls_top_offset_(0.f),
      top_controls_height_(top_controls_height),
      current_scroll_delta_(0.f),
      controls_scroll_begin_offset_(0.f),
      top_controls_show_height_(
          top_controls_height * top_controls_hide_threshold),
      top_controls_hide_height_(
          top_controls_height * (1.f - top_controls_show_threshold)) {
  CHECK(client_);
}

TopControlsManager::~TopControlsManager() {
}

void TopControlsManager::UpdateTopControlsState(bool enable_hiding,
                                                bool enable_showing,
                                                bool animate) {
  float final_controls_position = 0.f;

  if (enable_hiding && enable_showing) {
    visibility_restriction_ = NONE;
  } else if (enable_showing || !enable_hiding) {
    visibility_restriction_ = ALWAYS_SHOWN;
  } else {
    visibility_restriction_ = ALWAYS_HIDDEN;
    final_controls_position = -top_controls_height_;
  }

  if (visibility_restriction_ != NONE &&
      final_controls_position != controls_top_offset_) {
    ResetAnimations();
    if (animate) {
      SetupAnimation(visibility_restriction_ == ALWAYS_SHOWN ?
          SHOWING_CONTROLS : HIDING_CONTROLS);
    } else {
      controls_top_offset_ = final_controls_position;
    }
    client_->DidChangeTopControlsPosition();
  }
}

void TopControlsManager::ScrollBegin() {
  ResetAnimations();
  current_scroll_delta_ = 0.f;
  controls_scroll_begin_offset_ = controls_top_offset_;
}

gfx::Vector2dF TopControlsManager::ScrollBy(
    const gfx::Vector2dF pending_delta) {
  if (visibility_restriction_ == ALWAYS_SHOWN && pending_delta.y() > 0)
    return pending_delta;
  else if (visibility_restriction_ == ALWAYS_HIDDEN && pending_delta.y() < 0)
    return pending_delta;

  current_scroll_delta_ += pending_delta.y();

  float old_offset = controls_top_offset_;
  SetControlsTopOffset(controls_scroll_begin_offset_ - current_scroll_delta_);

  // If the controls are fully visible, treat the current position as the
  // new baseline even if the gesture didn't end.
  if (controls_top_offset_ == 0.f) {
    current_scroll_delta_ = 0.f;
    controls_scroll_begin_offset_ = 0.f;
  }

  ResetAnimations();

  gfx::Vector2dF applied_delta(0.f, old_offset - controls_top_offset_);
  return pending_delta - applied_delta;
}

void TopControlsManager::ScrollEnd() {
  StartAnimationIfNecessary();
}

void TopControlsManager::SetControlsTopOffset(float controls_top_offset) {
  controls_top_offset = std::max(controls_top_offset, -top_controls_height_);
  controls_top_offset = std::min(controls_top_offset, 0.f);

  if (controls_top_offset_ == controls_top_offset)
    return;

  controls_top_offset_ = controls_top_offset;

  client_->DidChangeTopControlsPosition();
}

gfx::Vector2dF TopControlsManager::Animate(base::TimeTicks monotonic_time) {
  if (!top_controls_animation_ || !client_->HaveRootScrollLayer())
    return gfx::Vector2dF();

  double time = (monotonic_time - base::TimeTicks()).InMillisecondsF();

  float old_offset = controls_top_offset_;
  SetControlsTopOffset(top_controls_animation_->GetValue(time));

  if (IsAnimationCompleteAtTime(monotonic_time))
    ResetAnimations();

  gfx::Vector2dF scroll_delta(0.f, controls_top_offset_ - old_offset);
  return scroll_delta;
}

void TopControlsManager::ResetAnimations() {
  if (top_controls_animation_)
    top_controls_animation_.reset();

  animation_direction_ = NO_ANIMATION;
}

void TopControlsManager::SetupAnimation(AnimationDirection direction) {
  top_controls_animation_ = KeyframedFloatAnimationCurve::Create();
  double start_time =
      (base::TimeTicks::Now() - base::TimeTicks()).InMillisecondsF();
  top_controls_animation_->AddKeyframe(
      FloatKeyframe::Create(start_time, controls_top_offset_,
                            scoped_ptr<TimingFunction>()));
  float max_ending_offset =
      (direction == SHOWING_CONTROLS ? 1 : -1) * top_controls_height_;
  top_controls_animation_->AddKeyframe(
      FloatKeyframe::Create(start_time + kShowHideMaxDurationMs,
                            controls_top_offset_ + max_ending_offset,
                            EaseTimingFunction::Create()));
  animation_direction_ = direction;
}

void TopControlsManager::StartAnimationIfNecessary() {
  if (controls_top_offset_ != 0
      && controls_top_offset_ != -top_controls_height_) {
    AnimationDirection show_controls = NO_ANIMATION;

    if (controls_top_offset_ >= -top_controls_show_height_) {
      // If we're showing so much that the hide threshold won't trigger, show.
      show_controls = SHOWING_CONTROLS;
    } else if (controls_top_offset_ <= -top_controls_hide_height_) {
      // If we're showing so little that the show threshold won't trigger, hide.
      show_controls = HIDING_CONTROLS;
    } else {
      // If we could be either showing or hiding, we determine which one to
      // do based on whether or not the total scroll delta was moving up or
      // down.
      show_controls = current_scroll_delta_ <= 0.f ?
          SHOWING_CONTROLS : HIDING_CONTROLS;
    }

    if (show_controls != NO_ANIMATION &&
        (!top_controls_animation_ || animation_direction_ != show_controls)) {
      SetupAnimation(show_controls);
      client_->DidChangeTopControlsPosition();
    }
  }
}

bool TopControlsManager::IsAnimationCompleteAtTime(base::TimeTicks time) {
  if (!top_controls_animation_)
    return true;

  double time_ms = (time - base::TimeTicks()).InMillisecondsF();
  float new_offset = top_controls_animation_->GetValue(time_ms);

  if ((animation_direction_ == SHOWING_CONTROLS && new_offset >= 0) ||
      (animation_direction_ == HIDING_CONTROLS
          && new_offset <= -top_controls_height_)) {
    return true;
  }
  return false;
}

}  // namespace cc