text:
I denna lektion så är målet att skapa ett spel där en drake/fågel flyger igenom portar.

## Skapa happy

Först behöver vi ladda sprites för vår drake som jag kallar happy

```
sprites = {}
spelarkostymer = {
    "resources/player/frame-1.png",
    "resources/player/frame-2.png",
    "resources/player/frame-3.png",
    "resources/player/frame-4.png",
}

function love.load()
    bas.starta(bas.hanteraSignaler)
    bas.starta(bas.uppdateraGrafik)
    bas.starta(bas.repeteraAlla)
    happy = Sprite(125, 250, 0, 0, 0.14, spelarkostymer) -- Skapar en sprite på x=125, y=250, 14% av orginalstorleken
    table.insert(sprites, happy)
end

function love.update()
    bas.tick() -- Berättar för basmodulen att tid har passerat
end

function love.draw()
    for _, sprite in pairs(sprites) do
        sprite:rita()
    end
end

function love.keypressed(key)
    if key == "escape" then
        love.event.quit()
    end
end
```

Nu borde spelet rita en drake på svart bakgrund

## Animera happy

För att animera happy så behöver vi lägga till en rad som byter kostym i love.load() och en funktion som byter kostym.

Lägg till en funktion som byter kostym
```
function animera(sprite)
    sprite:bytKostym()
end
```
Lägg till i love.load()
```
bas.repetera(animera, 0.15, true, happy)
```

## Få happy att dyka

Ett sätt att få happy att dyka är att flytta i en riktning. När en sprite skapas är vinkeln noll. Så en negativ vinkel kommer att få happy att titta uppåt och en positiv vinkel får happy att titta nedåt. Om y är en funktion av vinkeln så kommer happy flytta sig uppåt med en negativ vinkel och tvärt om.

Lägg till

Denna kod får det att se ut som att happy dyker.
```
function uppdateraHappy(happy)
    -- Öka y fart med vinkeln gånger 15
    happy.yfart = happy.vinkel * 15
    if happy.vinkel < 1.0 then -- Bestäm en max vinkel
        happy.vinkel = happy.vinkel + 0.05
    end
    -- Stoppa happy från att ramla ur bild (valfritt)
    if (happy.y + happy.hojd < 600 or happy.yfart < 0) and (happy.y > 0 or happy.yfart > 0) then
        happy.y = happy.y + happy.yfart
    end
end
```
Lägg till denna rad i love.load() för att köra uppdateraHappy varje gång love.update() kör
```
bas.startaGrafik(happy, uppdateraHappy)
```

## Få happy att flyga

Eftersom happy nu faller beroende av vinkeln så kan vi koppla en knapp till att återställa vinkeln. Då kommer happy att röra sig uppåt om vinkeln sätts till att vara negativ

Skapa funktionen flyg
```
function flyg(sprite)
    sprite.vinkel = -0.55
end
```
Lägg sedan till tre rader i love.keypressed(key)
```
if key == " " then
    bas.skickaSignal(flyg, happy)
end
```
Nu borde happy flyga varje gång man trycker på mellanslag

## Skapa torn

För att spelet ska vara intressant så behöver vi hinder som happy måste passera. Börja med att skapa en tabell med grafik för hindren.

Först måste vi skapa två stycken torn som vi kommer att klona i love.load()
```
golvtorn = Sprite(850, 100, -5, 0, 0.14, tornkostymer)
taktorn = Sprite(940, -100, -5, 0, -0.14, tornkostymer)
bas.repetera(skapaTorn, 1.5, true) -- Skapa torn med 1.5 sekunders mellanrum
```

För att klona tornen och få dom att röra sig

```
hinder = {} --En tom tabell för alla hinder som finns på banan
-- Alla hinder är torn och kan ha olika färger
tornkostymer = {
    "resources/towers/Green-tower.png",
    "resources/towers/Icy-tower.png",
    "resources/towers/Pink-tower.png",
    "resources/towers/Yellow-tower.png",
}

-- Kopierar golvtorn och taktorn från love.load och får dom att uppdatera sig hela tiden
function skapaTorn()
    golvtornkopia = golvtorn:kopiera()
    taktornkopia = taktorn:kopiera()
    golvtornkopia.y = 300
    taktornkopia.y = 100
    table.insert(hinder, golvtornkopia)
    table.insert(hinder, taktornkopia)
    bas.startaGrafik(golvtornkopia, uppdateraTorn)
    bas.startaGrafik(taktornkopia, uppdateraTorn)
end

function uppdateraTorn(torn)
    torn.x = torn.x + torn.xfart --torn.xfart är -5
end
```
För att rita tornen så behöver vi ändra på love.draw(). Lägg till dessa fyra rader för att rita alla torn
```
-- För varje torn i tabellen hinder så anropa funktionen rita
for _, torn in pairs(hinder) do
    torn:rita()
end
```

Om man kör spelet nu så kommer det likadana torn på samma plats hela tiden

## Slumpa färg och plats på tornen

För att få tornen att vara olika höga varje gång som de klonas så kan vi använda ett slumptal. Ändra på funktionen skapa torn så att den ser ut som nedan.
```
function skapaTorn()
    slump = math.random(100, 500) -- Slumpa ett tal mellan 100 och 500
    golvtornkopia = golvtorn:kopiera()
    taktornkopia = taktorn:kopiera()
    golvtornkopia.y = slump + 100 -- Lägg till 100 för att tornet ska hamna lägre ner
    taktornkopia.y = slump - 100 -- Ta bort 100 för att tornet ska hamna högre upp
    -- Ändra slumptalet så att det är mellan 0 och 3 och lägg till 1, tornen har 4 olika kostymer
    taktornkopia.kostym = slump % table.getn(taktornkopia.kostymer) + 1
    -- Ge golvtornet samma kostym som taktornet
    golvtornkopia.kostym = taktornkopia.kostym
    table.insert(hinder, golvtornkopia) --Lägg till tornen bland hinder
    table.insert(hinder, taktornkopia)
    bas.startaGrafik(golvtornkopia, uppdateraTorn) -- Få tornen att uppdatera sig
    bas.startaGrafik(taktornkopia, uppdateraTorn)
end
```

Nu bör tornen inte vara likadana hela tiden. Men happy kan inte krocka med dom

## Få happy att krocka med tornen

Först skapar vi en funktion som vi kallar reset. Syftet är att återställa spelet till startpunkten.

```
function reset()
    sprites = {}
    hinder = {}
    table.insert(sprites, happy)
    happy.y = 250
    happy.vinkel = 0
end
```

För att upptäcka när happy krockar med torn så kan man lägga till kod i love.update()

```
for _, torn in pairs(hinder) do
    if happy:krock(torn) then
        reset()
    end
end
```
Med denna kod så kommer spelet återställas till startpunkten varje gång happy krockar med ett torn.

## Lägg till en bakgrund

För att spelet ska se lite snyggare ut så kan vi lägga till en bakgrund

Ladda in bakgrunden i love.load()

```
bakgrund = love.graphics.newImage( "resources/background.png" )
```

Visa bakgrunden genom att rita den först av allt i love.draw()

```
love.graphics.draw(bakgrund, 0, 0, 0, 1.2)
```

## Utmaningar

* Gör så att övre och undre tornet inte alltid har samma färg
* Gör en poängräknare med love.graphics.print("Text", x, y)
* Gör att spelet stannar och visar game over i 2 sekunder och sen byter till get ready


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace AsymmetricCrypt
{
    class Program
    {
        static readonly string HEADER = "ASCR";
        const int KEY_SIZE = 4096;
        const int MODULUS_SIZE = KEY_SIZE / 8;

        SymmetricAlgorithm AES = new RijndaelManaged();

        static RSACryptoServiceProvider NewAsymmetricAlgorithm(bool forExport = false)
        {
            const int PROV_RSA_FULL = 1;

            var cspParams = new CspParameters()
            {
                ProviderType = PROV_RSA_FULL,
                Flags = forExport ? CspProviderFlags.UseArchivableKey : 0,
                KeyNumber = (int)KeyNumber.Exchange,
            };
            var rsaProvider = new RSACryptoServiceProvider(4096, cspParams);
            return rsaProvider;
        }

        static void Encrypt(Stream input, Stream output, RSACryptoServiceProvider asymmetricAlg)
        {
            var header = Encoding.ASCII.GetBytes(HEADER);
            output.Write(header, 0, header.Length);

            var aes = new RijndaelManaged() { KeySize = 256 };
            aes.GenerateIV();
            output.Write(aes.IV, 0, aes.IV.Length);

            aes.GenerateKey();
            var key = asymmetricAlg.Encrypt(aes.Key, false);
            if (key.Length != MODULUS_SIZE)
            {
                throw new InvalidOperationException();
            }
            output.Write(key, 0, key.Length);

            using (var cs = new CryptoStream(output, aes.CreateEncryptor(), CryptoStreamMode.Write))
            {
                byte[] buffer = new byte[1024 * 16];
                int count;
                while ((count = input.Read(buffer, 0, buffer.Length)) != 0)
                {
                    cs.Write(buffer, 0, count);
                }
            }
        }

        static void Decrypt(Stream input, Stream output, RSACryptoServiceProvider asymmetricAlg)
        {
            var header = new byte[HEADER.Length];
            input.Read(header, 0, header.Length);
            if (Encoding.ASCII.GetString(header) != HEADER)
            {
                throw new InvalidOperationException();
            }

            var aes = new RijndaelManaged() { KeySize = 256 };
            var iv = new byte[aes.IV.Length];
            input.Read(iv, 0, iv.Length);
            aes.IV = iv;

            var key = new byte[MODULUS_SIZE];
            input.Read(key, 0, key.Length);
            aes.Key = asymmetricAlg.Decrypt(key, false);

            using (var cs = new CryptoStream(input, aes.CreateDecryptor(), CryptoStreamMode.Read))
            {
                byte[] buffer = new byte[1024 * 16];
                int count;
                while ((count = cs.Read(buffer, 0, buffer.Length)) != 0)
                {
                    output.Write(buffer, 0, count);
                }
            }
        }

        static int Main(string[] args)
        {
            try
            {
                if (args.Length == 0)
                {
                    throw new ArgumentException();
                }

                if (args[0] == "--genkey")
                {
                    Console.Error.WriteLine("Generating 4096 bit keypair. This could take a little bit of time...");

                    var pk = NewAsymmetricAlgorithm(true);
                    var xml = pk.ToXmlString(true);
                    using (var stream = (args.Length >= 2) ? new StreamWriter(args[1]) : Console.Out)
                    {
                        stream.WriteLine(xml);
                    }
                }
                else if (args[0] == "--publickey")
                {
                    var pk = NewAsymmetricAlgorithm();
                    using (var keyStream = (args.Length >= 2) ? new StreamReader(args[1]) : Console.In)
                    {
                        var privateKey = keyStream.ReadToEnd();
                        pk.FromXmlString(privateKey);
                    }
                    var xml = pk.ToXmlString(false);
                    using (var stream = (args.Length >= 3) ? new StreamWriter(args[2]) : Console.Out)
                    {
                        stream.WriteLine(xml);
                    }
                }
                else if (args[0] == "--encrypt")
                {
                    if (args.Length < 2)
                    {
                        throw new ArgumentException();
                    }

                    var pk = NewAsymmetricAlgorithm();

                    using (var keyStream = new StreamReader(args[1]))
                    {
                        var privateKey = keyStream.ReadToEnd();
                        pk.FromXmlString(privateKey);
                    }

                    using (var input = (args.Length >= 3) ? new FileStream(args[2], FileMode.Open) : Console.OpenStandardInput())
                    using (var output = (args.Length >= 4) ? new FileStream(args[3], FileMode.Create) : Console.OpenStandardOutput())
                    {
                        Encrypt(input, output, pk);
                    }
                }
                else if (args[0] == "--decrypt")
                {
                    if (args.Length < 2)
                    {
                        throw new ArgumentException();
                    }

                    var pk = NewAsymmetricAlgorithm();

                    using (var keyStream = new StreamReader(args[1]))
                    {
                        var privateKey = keyStream.ReadToEnd();
                        pk.FromXmlString(privateKey);
                    }

                    using (var input = (args.Length >= 3) ? new FileStream(args[2], FileMode.Open) : Console.OpenStandardInput())
                    using (var output = (args.Length >= 4) ? new FileStream(args[3], FileMode.Create) : Console.OpenStandardOutput())
                    {
                        Decrypt(input, output, pk);
                    }
                }
                else
                {
                    throw new ArgumentException();
                }
            }
            catch (ArgumentException)
            {
                Console.Error.WriteLine("Usage:");
                Console.Error.WriteLine("   AsymmetricCrypt [--encrypt|--decrypt|--genkey|--publickey]");
                Console.Error.WriteLine("Example:");
                Console.Error.WriteLine("   AsymmetricCrypt --genkey private.key");
                Console.Error.WriteLine("   AsymmetricCrypt --publickey [private.key [public.key]]");
                Console.Error.WriteLine("   AsymmetricCrypt --encrypt public.key [plaintext.txt [encrypted.ascr]]");
                Console.Error.WriteLine("   AsymmetricCrypt --decrypt private.key [encrypted.ascr [plaintext.txt]]");
                return 1;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
            }

            return 0;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package za.org.grassroot.core.domain.livewire;

import org.hibernate.annotations.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import za.org.grassroot.core.domain.User;
import za.org.grassroot.core.domain.geo.GeoLocation;
import za.org.grassroot.core.domain.geo.LocationHolder;
import za.org.grassroot.core.domain.group.Group;
import za.org.grassroot.core.domain.media.MediaFileRecord;
import za.org.grassroot.core.domain.task.Meeting;
import za.org.grassroot.core.enums.LiveWireAlertDestType;
import za.org.grassroot.core.enums.LiveWireAlertType;
import za.org.grassroot.core.enums.LocationSource;
import za.org.grassroot.core.util.DateTimeUtil;
import za.org.grassroot.core.util.PhoneNumberUtil;
import za.org.grassroot.core.util.StringArrayUtil;
import za.org.grassroot.core.util.UIDGenerator;

import javax.persistence.*;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.*;

/**
 * Created by luke on 2017/05/07.
 * Creating a request entity to handle partials would be heavy compared to frequency of use case
 * (different to events in this regard), hence using booleans to flag
 */
@Entity
@Table(name = "live_wire_alert")
public class LiveWireAlert implements LocationHolder {

    private static final Logger logger = LoggerFactory.getLogger(LiveWireAlert.class);

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false, updatable = false)
    private Long id;

    @Basic
    @Column(name = "uid", unique = true, nullable = false, updatable = false)
    private String uid;

    @Column(name = "creation_time", nullable = false, updatable = false)
    private Instant creationTime;

    @ManyToOne
    @JoinColumn(name = "created_by_user", nullable = false, updatable = false)
    private User creatingUser;

    @Enumerated(EnumType.STRING)
    @Column(name = "type", length = 50, nullable = false)
    private LiveWireAlertType type;

    @ManyToOne
    @JoinColumn(name = "meeting_id")
    private Meeting meeting;

    @ManyToOne
    @JoinColumn(name = "group_id")
    private Group group;

    @ManyToOne
    @JoinColumn(name = "contact_user_id")
    private User contactUser;

    // since can over-ride the display name used in Grassroot (if non null)
    @Basic
    @Column(name = "contact_name")
    private String contactName;

    @Basic
    @Column(name = "headline")
    private String headline;

    @Basic
    @Column(name = "description")
    private String description;

    @Basic
    @Column(name = "send_time")
    private Instant sendTime;

    @Basic
    @Column(name = "complete")
    private boolean complete;

    @Basic
    @Column(name = "reviewed")
    private boolean reviewed;

    @ManyToOne
    @JoinColumn(name = "reviewed_by_user_id")
    private User reviewedByUser;

    @Basic
    @Column(name = "sent")
    private boolean sent;

    @Column(name = "tags")
    @Type(type = "za.org.grassroot.core.util.StringArrayUserType")
    private String[] tags;

    @Enumerated(EnumType.STRING)
    @Column(name = "destination_type", length = 50)
    private LiveWireAlertDestType destinationType;

    // this is the private list of the user, if they have one
    @ManyToOne
    @JoinColumn(name = "subscriber_id")
    private DataSubscriber targetSubscriber;

    // these are the public lists selected by reviewer
    @Column(name = "public_list_uids")
    @Type(type = "za.org.grassroot.core.util.StringArrayUserType")
    private String[] publicLists;

    @Embedded
    @AttributeOverrides({
            @AttributeOverride(name="latitude", column = @Column(nullable = true)),
            @AttributeOverride(name="longitude", column = @Column(nullable = true))
    })
    private GeoLocation location;

    @Enumerated(EnumType.STRING)
    @Column(name = "location_source", length = 50, nullable = true)
    private LocationSource locationSource;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "live_wire_media_files",
            joinColumns = @JoinColumn(name = "live_wire_alert_id", nullable = false),
            inverseJoinColumns = @JoinColumn(name = "media_file_id", nullable = false))
    private Set<MediaFileRecord> mediaFiles = new HashSet<>();

    @Version
    private Integer version;

    public static Builder newBuilder() {
        return new Builder();
    }

    public static final class Builder {
        private User creatingUser;
        private LiveWireAlertType type;
        private User contactUser;
        private String contactName;
        private String contactNumber;
        private Meeting meeting;
        private Group group;
        private String headline;
        private String description;
        private Instant sendTime;
        private boolean complete;
        private LiveWireAlertDestType destType;

        private DataSubscriber destSubscriber;
        private Set<MediaFileRecord> mediaFiles;
        private GeoLocation location;
        private LocationSource locationSource;

        public Builder creatingUser(User creatingUser) {
            this.creatingUser = creatingUser;
            return this;
        }

        public Builder type(LiveWireAlertType type) {
            this.type = type;
            return this;
        }

        public Builder meeting(Meeting meeting) {
            this.meeting = meeting;
            return this;
        }

        public Builder group(Group group) {
            this.group = group;
            return this;
        }

        public Builder contactUser(User user) {
            logger.debug("setting contact user to: {}", user);
            this.contactUser = user;
            return this;
        }

        public Builder contactName(String contactName) {
            this.contactName = contactName;
            return this;
        }

        public Builder contactNumber(String contactNumber) {
            this.contactNumber = contactNumber;
            return this;
        }

        public Builder headline(String headline) {
            this.headline = headline;
            return this;
        }

        public Builder description(String description) {
            this.description = description;
            return this;
        }

        public Builder sendTime(Instant sendTime) {
            this.sendTime = sendTime;
            return this;
        }

        public Builder complete(boolean complete) {
            this.complete = complete;
            return this;
        }

        public Builder destType(LiveWireAlertDestType destType) {
            this.destType = destType;
            return this;
        }

        public Builder destSubscriber(DataSubscriber destSubscriber) {
            this.destSubscriber = destSubscriber;
            return this;
        }

        public Builder mediaFiles(Set<MediaFileRecord> mediaFiles) {
            this.mediaFiles = mediaFiles;
            return this;
        }

        public Builder addMediaFiles(Set<MediaFileRecord> mediaFiles) {
            if (this.mediaFiles == null) {
                this.mediaFiles = new HashSet<>();
            }
            this.mediaFiles.addAll(mediaFiles);
            return this;
        }

        public Builder location(GeoLocation location, LocationSource locationSource) {
            this.location = location;
            this.locationSource = locationSource;
            return this;
        }

        // checks if we have enough for a _complete_ alert (not called when generating via USSD, just Android/Web
        public void validateSufficientFields() {
            Objects.requireNonNull(creatingUser);
            Objects.requireNonNull(type);
            Objects.requireNonNull(destType);
            Objects.requireNonNull(headline);

            if (LiveWireAlertType.MEETING.equals(type)) {
                Objects.requireNonNull(meeting);
            } else {
                Objects.requireNonNull(group);
            }
        }

        public LiveWireAlert build() {
            LiveWireAlert alert = new LiveWireAlert(
                    Objects.requireNonNull(creatingUser),
                    Objects.requireNonNull(type),
                    Objects.requireNonNull(destType),
                    meeting, group, description, headline);

            if (sendTime != null) {
                alert.setSendTime(sendTime);
            }

            if (contactUser != null) {
                logger.info("setting contact user in build to = {}", contactUser);
                alert.setContactUser(contactUser);
                alert.setContactName(contactName);
            }

            if (mediaFiles != null) {
                alert.setMediaFiles(mediaFiles);
            }

            if (location != null) {
                alert.setLocation(location);
                alert.setLocationSource(locationSource == null ? LocationSource.UNKNOWN : locationSource);
            }

            if (destSubscriber != null) {
                alert.setTargetSubscriber(destSubscriber);
            }

            alert.setComplete(complete);

            return alert;
        }
    }

    private LiveWireAlert() {
        // for JPA
    }

    private LiveWireAlert(User creatingUser, LiveWireAlertType type, LiveWireAlertDestType destType,
                          Meeting meeting, Group group, String description, String headline) {
        this.uid = UIDGenerator.generateId();
        this.creationTime = Instant.now();
        this.creatingUser = creatingUser;
        this.type = type;
        this.meeting = meeting;
        this.group = group;
        this.headline = headline;
        this.description = description;
        this.complete = false;
        this.sent = false;
        this.destinationType = destType;
    }

    public Long getId() {
        return id;
    }

    public String getUid() {
        return uid;
    }

    public Instant getCreationTime() {
        return creationTime;
    }

    public ZonedDateTime getCreationTimeAtSAST() {
        return DateTimeUtil.convertToUserTimeZone(creationTime, DateTimeUtil.getSAST());
    }

    public User getCreatingUser() {
        return creatingUser;
    }

    public LiveWireAlertType getType() {
        return type;
    }

    public User getContactUser() {
        return contactUser;
    }

    public String getContactNumberFormatted() {
        return contactUser == null ? "" : PhoneNumberUtil.invertPhoneNumber(contactUser.getPhoneNumber());
    }

    public String getContactName() {
        return contactName;
    }

    public String getContactNameNullSafe() {
        return !StringUtils.isEmpty(contactName) ? contactName :
                contactUser != null ? contactUser.getName() : creatingUser.getName();
    }

    public Meeting getMeeting() {
        return meeting;
    }

    public Group getGroup() {
        return group;
    }

    public String getHeadline() {
        return headline;
    }

    public String getDescription() {
        return description;
    }

    public Instant getSendTime() {
        return sendTime;
    }

    public boolean isSent() {
        return sent;
    }

    public void setType(LiveWireAlertType type) {
        this.type = type;
    }

    public void setMeeting(Meeting meeting) {
        this.meeting = meeting;
    }

    public void setGroup(Group group) {
        this.group = group;
    }

    public void setContactUser(User contactUser) {
        this.contactUser = contactUser;
    }

    public void setContactName(String contactName) {
        this.contactName = contactName;
    }

    public void setHeadline(String headline) {
        this.headline = headline;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public boolean isComplete() {
        return complete;
    }

    public void setComplete(boolean complete) {
        this.complete = complete;
    }

    public boolean isReviewed() {
        return reviewed;
    }

    public void setReviewed(boolean reviewed) {
        this.reviewed = reviewed;
    }

    public boolean isInstant() {
        return LiveWireAlertType.INSTANT.equals(type);
    }

    public User getReviewedByUser() {
        return reviewedByUser;
    }

    public void setReviewedByUser(User reviewedByUser) {
        this.reviewedByUser = reviewedByUser;
    }

    public String[] getTags() {
        return tags;
    }

    public List<String> getTagList() {
        logger.debug("getting ... tags = {}", Arrays.toString(tags));
        return tags == null ? new ArrayList<>() : new ArrayList<>(Arrays.asList(tags));
    }

    public String printTags() {
        return String.join(", ", getTagList());
    }

    public void setTags(String[] tags) {
        this.tags = tags;
    }

    public void addTags(List<String> tagsToAdd) {
        List<String> currentTags = new ArrayList<>(StringArrayUtil.arrayToList(tags));
        currentTags.addAll(tagsToAdd);
        tags = StringArrayUtil.listToArrayRemoveDuplicates(currentTags);
    }

    public void reviseTags(List<String> tags) {
        Objects.requireNonNull(tags);
        this.tags = StringArrayUtil.listToArrayRemoveDuplicates(tags);
    }

    public List<String> getPublicListsUids() {
        logger.debug("getting ... public lists = {}", Arrays.toString(publicLists));
        return publicLists == null ? new ArrayList<>() : new ArrayList<>(Arrays.asList(publicLists));
    }

    public void revisePublicLists(List<String> listsToAdd) {
        Objects.requireNonNull(tags);
        this.publicLists = StringArrayUtil.listToArrayRemoveDuplicates(listsToAdd);
    }

    public void setSendTime(Instant sendTime) {
        this.sendTime = sendTime;
    }

    public void setSent(boolean sent) {
        this.sent = sent;
    }

    @Override
    public GeoLocation getLocation() {
        return location;
    }

    @Override
    public boolean hasLocation() {
        return location != null;
    }

    @Override
    public LocationSource getSource() {
        return locationSource;
    }

    public void setLocation(GeoLocation location) {
        this.location = location;
    }

    public LocationSource getLocationSource() {
        return locationSource;
    }

    public void setLocationSource(LocationSource locationSource) {
        this.locationSource = locationSource;
    }

    public Integer getVersion() {
        return version;
    }

    public LiveWireAlertDestType getDestinationType() {
        return destinationType;
    }

    public void setDestinationType(LiveWireAlertDestType destinationType) {
        this.destinationType = destinationType;
    }

    public DataSubscriber getTargetSubscriber() {
        return targetSubscriber;
    }

    public void setTargetSubscriber(DataSubscriber targetSubscriber) {
        this.targetSubscriber = targetSubscriber;
    }

    public Set<MediaFileRecord> getMediaFiles() {
        if (mediaFiles == null) {
            mediaFiles = new HashSet<>();
        }
        return mediaFiles;
    }

    public void setMediaFiles(Set<MediaFileRecord> mediaFiles) {
        this.mediaFiles = mediaFiles;
    }

    public void addMediaFile(MediaFileRecord mediaFileRecord) {
        getMediaFiles().add(mediaFileRecord);
    }

    public boolean hasMediaFiles() {
        return !getMediaFiles().isEmpty();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        LiveWireAlert alert = (LiveWireAlert) o;

        return uid.equals(alert.uid);
    }

    @Override
    public int hashCode() {
        return uid.hashCode();
    }

    @Override
    public String toString() {
        return "LiveWireAlert{" +
                "type=" + type +
                ", meeting=" + meeting +
                ", group=" + group +
                ", description='" + description + '\'' +
                ", sendTime=" + sendTime +
                ", sent=" + sent +
                '}';
    }
}


text:
require_relative "test_helper"

class FakedTest < Test::Unit::TestCase
  def test_something
    assert_equal "bar", FakedProject.foo
  end

  def test_framework_specific
    assert_equal "Only tested in Test/Unit", FrameworkSpecific.test_unit
  end
end


text:
/**
 * Adapts the service worker to its runtime environment.
 *
 * Mostly, this is used to mock out identifiers which are otherwise read
 * from the global scope.
 */
export class Adapter {
  readonly cacheNamePrefix: string;

  constructor(scope: ServiceWorkerGlobalScope) {
    // Suffixing `ngsw` with the baseHref to avoid clash of cache names
    // for SWs with different scopes on the same domain.
    const baseHref = this.parseUrl(scope.registration.scope).path;
    this.cacheNamePrefix = 'ngsw:' + baseHref;
  }

  /**
   * Wrapper around the `Request` constructor.
   */
  newRequest(input: string|Request, init?: RequestInit): Request {
    return new Request(input, init);
  }

  /**
   * Wrapper around the `Response` constructor.
   */
  newResponse(body: any, init?: ResponseInit) { return new Response(body, init); }

  /**
   * Wrapper around the `Headers` constructor.
   */
  newHeaders(headers: {[name: string]: string}): Headers { return new Headers(headers); }

  /**
   * Test if a given object is an instance of `Client`.
   */
  isClient(source: any): source is Client { return (source instanceof Client); }

  /**
   * Read the current UNIX time in milliseconds.
   */
  get time(): number { return Date.now(); }

  /**
   * Extract the pathname of a URL.
   */
  parseUrl(url: string, relativeTo?: string): {origin: string, path: string} {
    const parsed = new URL(url, relativeTo);
    return {origin: parsed.origin, path: parsed.pathname};
  }

  /**
   * Wait for a given amount of time before completing a Promise.
   */
  timeout(ms: number): Promise<void> {
    return new Promise<void>(resolve => { setTimeout(() => resolve(), ms); });
  }
}

/**
 * An event context in which an operation is taking place, which allows
 * the delaying of Service Worker shutdown until certain triggers occur.
 */
export interface Context {
  /**
   * Delay shutdown of the Service Worker until the given promise resolves.
   */
  waitUntil(fn: Promise<any>): void;
}


text:
<?php

namespace Cocoders\CityBike;

interface DockingStations
{
    /**
     * @param DockingStation $dockingStation
     * @return null
     */
    public function add(DockingStation $dockingStation);

    /**
     * @return DockingStation[]
     */
    public function findAll();

    /**
     * @return DockingStation
     */
    public function find($id);
}


text:
export enum OriginalPositionMode {
    /**
     * Original positions are hidden.
     */
    Hidden,

    /**
     * Visualize original positions with altitude change.
     */
    Altitude,

    /**
     * Visualize original positions without altitude change,
     * i.e. as flat lines from the camera origin.
     */
    Flat,
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:drawable="@drawable/toolbar_icon_more_sel" />
    <item android:state_checked="true" android:drawable="@drawable/toolbar_icon_more_sel" />
    <item android:drawable="@drawable/toolbar_icon_more_nor" />
</selector>


text:
package org.conscrypt;

/**
 * A provider for the peer host and port information.
 */
abstract class PeerInfoProvider {
    private static final PeerInfoProvider NULL_PEER_INFO_PROVIDER = new PeerInfoProvider() {
        @Override
        String getHostname() {
            return null;
        }

        @Override
        public String getHostnameOrIP() {
            return null;
        }

        @Override
        public int getPort() {
            return -1;
        }
    };

    /**
     * Returns the hostname supplied during engine/socket creation. No DNS resolution is
     * attempted before returning the hostname.
     */
    abstract String getHostname();

    /**
     * This method attempts to create a textual representation of the peer host or IP. Does
     * not perform a reverse DNS lookup. This is typically used during session creation.
     */
    abstract String getHostnameOrIP();

    /**
     * Gets the port of the peer.
     */
    abstract int getPort();

    static PeerInfoProvider nullProvider() {
        return NULL_PEER_INFO_PROVIDER;
    }

    static PeerInfoProvider forHostAndPort(final String host, final int port) {
        return new PeerInfoProvider() {
            @Override
            String getHostname() {
                return host;
            }

            @Override
            public String getHostnameOrIP() {
                return host;
            }

            @Override
            public int getPort() {
                return port;
            }
        };
    }
}


text: Created with the help of [Jekyll Now](https://github.com/barryclark/jekyll-now)!


text:
using AzureRepositories.LykkeRepositories;
using AzureStorage.Tables;
using AzureStorage.Tables.Templates.Index;
using Common.IocContainer;
using Common.Log;
using Core;
using Core.LykkeIntegration.Repositories;
using Core.LykkeIntegration.Services;

namespace AzureRepositories
{
    public static class AzureRepoBinder
    {
        public static void BindAzureRepositories(this IoC ioc, DbSettings dbSettings, ILog log)
        {
            ioc.Register<IBitCoinTransactionsRepository>(
                new BitCoinTransactionsRepository(
                    new AzureTableStorage<BitCoinTransactionEntity>(dbSettings.BitCoinQueueConnectionString,
                        "BitCoinTransactions", log)));

            ioc.Register<ICashOperationsRepository>(
                new CashOperationsRepository(
                    new AzureTableStorage<CashInOutOperationEntity>(dbSettings.ClientPersonalInfoConnString,
                        "OperationsCash", log),
                    new AzureTableStorage<AzureIndex>(dbSettings.ClientPersonalInfoConnString, "OperationsCash", log))
                );

            ioc.Register<IClientTradesRepository>(
                new ClientTradesRepository(
                    new AzureTableStorage<ClientTradeEntity>(dbSettings.HTradesConnString, "Trades", log),
                    new AzureTableStorage<AzureIndex>(dbSettings.ClientPersonalInfoConnString, "Trades", log)));

            ioc.Register<ITransferEventsRepository>(
                new TransferEventsRepository(
                    new AzureTableStorage<TransferEventEntity>(dbSettings.ClientPersonalInfoConnString, "Transfers", log),
                    new AzureTableStorage<AzureIndex>(dbSettings.ClientPersonalInfoConnString, "Transfers", log)));
        }
    }
}


text:
package com.intellij.ide.impl;

import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.KeyedLazyInstanceEP;
import com.intellij.util.containers.HashMap;
import org.jetbrains.annotations.Nullable;

import java.lang.reflect.Array;
import java.util.Map;

public abstract class DataValidator<T> {
  private static boolean ourExtensionsLoaded;

  public static final ExtensionPointName<KeyedLazyInstanceEP<DataValidator>> EP_NAME =
    ExtensionPointName.create("com.intellij.dataValidator");

  Logger LOG = Logger.getInstance("#com.intellij.ide.impl.DataValidator");

  private static final Map<String, DataValidator> ourValidators = new HashMap<>();
  private static final DataValidator<VirtualFile> VIRTUAL_FILE_VALIDATOR = new DataValidator<VirtualFile>() {
    public VirtualFile findInvalid(final String dataId, VirtualFile file, final Object dataSource) {
      return file.isValid() ? null : file;
    }
  };
  private static final DataValidator<Project> PROJECT_VALIDATOR = new DataValidator<Project>() {
    @Override
    public Project findInvalid(final String dataId, final Project project, final Object dataSource) {
      return project.isDisposed() ? project : null;
    }
  };
  private static final DataValidator<Editor> EDITOR_VALIDATOR = new DataValidator<Editor>() {
    @Override
    public Editor findInvalid(final String dataId, final Editor editor, final Object dataSource) {
      return editor.isDisposed() ? editor : null;
    }
  };

  @Nullable
  public abstract T findInvalid(final String dataId, T data, final Object dataSource);

  private static <T> DataValidator<T> getValidator(String dataId) {
    if (!ourExtensionsLoaded) {
      ourExtensionsLoaded = true;
      for (KeyedLazyInstanceEP<DataValidator> ep : Extensions.getExtensions(EP_NAME)) {
        ourValidators.put(ep.key, ep.getInstance());
      }
    }
    return ourValidators.get(dataId);
  }

  public static <T> T findInvalidData(String dataId, Object data, final Object dataSource) {
    if (data == null) return null;
    DataValidator<T> validator = getValidator(dataId);
    if (validator != null) return validator.findInvalid(dataId, (T)data, dataSource);
    return null;
  }

  static {
    ourValidators.put(CommonDataKeys.VIRTUAL_FILE.getName(), VIRTUAL_FILE_VALIDATOR);
    ourValidators.put(CommonDataKeys.VIRTUAL_FILE_ARRAY.getName(), new ArrayValidator<>(VIRTUAL_FILE_VALIDATOR));
    ourValidators.put(CommonDataKeys.PROJECT.getName(), PROJECT_VALIDATOR);
    ourValidators.put(CommonDataKeys.EDITOR.getName(), EDITOR_VALIDATOR);
  }

  public static class ArrayValidator<T> extends DataValidator<T[]> {
    private final DataValidator<T> myElementValidator;

    public ArrayValidator(DataValidator<T> elementValidator) {
      myElementValidator = elementValidator;
    }

    public T[] findInvalid(final String dataId, T[] array, final Object dataSource) {
      for (T element : array) {
        if (element == null) {
          LOG.error(
            "Data isn't valid. " + dataId + "=null Provided by: " + dataSource.getClass().getName() + " (" + dataSource.toString() + ")");
        }
        T invalid = myElementValidator.findInvalid(dataId, element, dataSource);
        if (invalid != null) {
          T[] result = (T[])Array.newInstance(array.getClass().getComponentType(), 1);
          result[0] = invalid;
          return result;
        }
      }
      return null;
    }
  }

}


text:
var express = require('express');
var exphbs  = require('express-handlebars');
var app = express();
var os = require("os");
var morgan  = require('morgan');

app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
app.use(express.static('static'));
app.use(morgan('combined'));

// Configuration
var port = process.env.PORT || 8080;
var message = process.env.MESSAGE || "Hello world!";

app.get('/', function (req, res) {
    res.render('home', {
      message: message,
      platform: os.type(),
      release: os.release(),
      hostName: os.hostname()
    });
});

// Set up listener
app.listen(port, function () {
  console.log("Listening on: http://%s:%s", os.hostname(), port);
});


text:
<?php
// Get the PHP helper library from https://twilio.com/docs/libraries/php
require_once '/path/to/vendor/autoload.php'; // Loads the library

use Twilio\Rest\Client;

// To set up environmental variables, see http://twil.io/secure
$account_sid = getenv('TWILIO_ACCOUNT_SID');
$auth_token = getenv('TWILIO_AUTH_TOKEN');
$twilio = new Client($account_sid, $auth_token);

$shortCodes = $twilio->messaging->v1->services("MG2172dd2db502e20dd981ef0d67850e1a")
                                      ->shortCodes("SC3f94c94562ac88dccf16f8859a1a8b25")->delete();


text:
package com.whoshuu.artbox.system;

public interface TouchListener {
    public void onDown(int xd, int yd);
    public void onUp(int xu, int yu);
    public void onMove(int x, int y);
}


text:
source "$(dirname "${BASH_SOURCE}")/../../hack/lib/init.sh"
trap os::test::junit::reconcile_output EXIT

# Cleanup cluster resources created by this test
(
  set +e
  oc delete all,templates --all
  exit 0
) &>/dev/null

url=":${API_PORT:-8443}"
project="$(oc project -q)"

os::test::junit::declare_suite_start "cmd/builds"
# This test validates builds and build related commands

os::cmd::expect_success 'oc new-build centos/ruby-22-centos7 https://github.com/openshift/ruby-hello-world.git'
os::cmd::expect_success 'oc get bc/ruby-hello-world'

os::cmd::expect_success "cat '${OS_ROOT}/images/origin/Dockerfile' | oc new-build -D - --name=test"
os::cmd::expect_success 'oc get bc/test'

template='{{with .spec.output.to}}{{.kind}} {{.name}}{{end}}'

# Build from Dockerfile with output to ImageStreamTag
os::cmd::expect_success "oc new-build --dockerfile=\$'FROM centos:7\nRUN yum install -y httpd'"
os::cmd::expect_success_and_text "oc get bc/centos --template '${template}'" '^ImageStreamTag centos:latest$'

# Build from a binary with no inputs requires name
os::cmd::expect_failure_and_text "oc new-build --binary" "you must provide a --name"

# Build from a binary with inputs creates a binary build
os::cmd::expect_success "oc new-build --binary --name=binary-test"
os::cmd::expect_success_and_text "oc get bc/binary-test" 'Binary'

os::cmd::expect_success 'oc delete is/binary-test bc/binary-test'

# Build from Dockerfile with output to DockerImage
os::cmd::expect_success "oc new-build -D \$'FROM openshift/origin:v1.1' --to-docker"
os::cmd::expect_success_and_text "oc get bc/origin --template '${template}'" '^DockerImage origin:latest$'

os::cmd::expect_success 'oc delete is/origin'

# Build from Dockerfile with given output ImageStreamTag spec
os::cmd::expect_success "oc new-build -D \$'FROM openshift/origin:v1.1\nENV ok=1' --to origin-test:v1.1"
os::cmd::expect_success_and_text "oc get bc/origin-test --template '${template}'" '^ImageStreamTag origin-test:v1.1$'

os::cmd::expect_success 'oc delete is/origin bc/origin'

# Build from Dockerfile with given output DockerImage spec
os::cmd::expect_success "oc new-build -D \$'FROM openshift/origin:v1.1\nENV ok=1' --to-docker --to openshift/origin:v1.1-test"
os::cmd::expect_success_and_text "oc get bc/origin --template '${template}'" '^DockerImage openshift/origin:v1.1-test$'

os::cmd::expect_success 'oc delete is/origin'

# Build from Dockerfile with custom name and given output ImageStreamTag spec
os::cmd::expect_success "oc new-build -D \$'FROM openshift/origin:v1.1\nENV ok=1' --to origin-name-test --name origin-test2"
os::cmd::expect_success_and_text "oc get bc/origin-test2 --template '${template}'" '^ImageStreamTag origin-name-test:latest$'

os::cmd::try_until_text 'oc get is ruby-22-centos7' 'latest'
os::cmd::expect_failure_and_text 'oc new-build ruby-22-centos7~https://github.com/openshift/ruby-ex ruby-22-centos7~https://github.com/openshift/ruby-ex --to invalid/argument' 'error: only one component with source can be used when specifying an output image reference'

os::cmd::expect_success 'oc delete all --all'

os::cmd::expect_success "oc new-build -D \$'FROM centos:7' --no-output"
os::cmd::expect_success_and_not_text 'oc get bc/centos -o=jsonpath="{.spec.output.to}"' '.'

# Ensure output is valid JSON
os::cmd::expect_success 'oc new-build -D "FROM centos:7" -o json | python -m json.tool'

os::cmd::expect_success 'oc delete all --all'
os::cmd::expect_success 'oc process -f examples/sample-app/application-template-dockerbuild.json -l build=docker | oc create -f -'
os::cmd::expect_success 'oc get buildConfigs'
os::cmd::expect_success 'oc get bc'
os::cmd::expect_success 'oc get builds'

# make sure the imagestream has the latest tag before trying to test it or start a build with it
os::cmd::try_until_text 'oc get is ruby-22-centos7' 'latest'

os::test::junit::declare_suite_start "cmd/builds/patch-anon-fields"
REAL_OUTPUT_TO=$(oc get bc/ruby-sample-build --template='{{ .spec.output.to.name }}')
os::cmd::expect_success "oc patch bc/ruby-sample-build -p '{\"spec\":{\"output\":{\"to\":{\"name\":\"different:tag1\"}}}}'"
os::cmd::expect_success_and_text "oc get bc/ruby-sample-build --template='{{ .spec.output.to.name }}'" 'different'
os::cmd::expect_success "oc patch bc/ruby-sample-build -p '{\"spec\":{\"output\":{\"to\":{\"name\":\"${REAL_OUTPUT_TO}\"}}}}'"
echo "patchAnonFields: ok"
os::test::junit::declare_suite_end

os::test::junit::declare_suite_start "cmd/builds/config"
os::cmd::expect_success_and_text 'oc describe buildConfigs ruby-sample-build' "${url}/oapi/v1/namespaces/${project}/buildconfigs/ruby-sample-build/webhooks/secret101/github"
os::cmd::expect_success_and_text 'oc describe buildConfigs ruby-sample-build' "Webhook GitHub"
os::cmd::expect_success_and_text 'oc describe buildConfigs ruby-sample-build' "${url}/oapi/v1/namespaces/${project}/buildconfigs/ruby-sample-build/webhooks/secret101/generic"
os::cmd::expect_success_and_text 'oc describe buildConfigs ruby-sample-build' "Webhook Generic"
os::cmd::expect_success 'oc start-build --list-webhooks=all ruby-sample-build'
os::cmd::expect_success_and_text 'oc start-build --list-webhooks=all bc/ruby-sample-build' 'generic'
os::cmd::expect_success_and_text 'oc start-build --list-webhooks=all ruby-sample-build' 'github'
os::cmd::expect_success_and_text 'oc start-build --list-webhooks=github ruby-sample-build' 'secret101'
os::cmd::expect_failure 'oc start-build --list-webhooks=blah'
os::cmd::expect_success "oc start-build --from-webhook='$(oc start-build --list-webhooks='generic' ruby-sample-build --api-version=v1 | head -n 1)'"
os::cmd::expect_success 'oc get builds'
os::cmd::expect_success 'oc delete all -l build=docker'
echo "buildConfig: ok"
os::test::junit::declare_suite_end

os::test::junit::declare_suite_start "cmd/builds/start-build"
os::cmd::expect_success 'oc create -f test/integration/testdata/test-buildcli.json'
# a build for which there is not an upstream tag in the corresponding imagerepo, so
# the build should use the image field as defined in the buildconfig
# Use basename to transform "build/build-name" into "build-name"
started="$(basename $(oc start-build -o=name ruby-sample-build-invalidtag))"
os::cmd::expect_success_and_text "oc describe build ${started}" 'centos/ruby-22-centos7$'
frombuild="$(basename $(oc start-build -o=name --from-build="${started}"))"
os::cmd::expect_success_and_text "oc describe build ${frombuild}" 'centos/ruby-22-centos7$'
os::cmd::expect_failure_and_text "oc start-build ruby-sample-build-invalid-tag --from-dir=. --from-build=${started}" "Cannot use '--from-build' flag with binary builds"
os::cmd::expect_failure_and_text "oc start-build ruby-sample-build-invalid-tag --from-file=. --from-build=${started}" "Cannot use '--from-build' flag with binary builds"
os::cmd::expect_failure_and_text "oc start-build ruby-sample-build-invalid-tag --from-repo=. --from-build=${started}" "Cannot use '--from-build' flag with binary builds"
echo "start-build: ok"
os::test::junit::declare_suite_end

os::test::junit::declare_suite_start "cmd/builds/cancel-build"
os::cmd::expect_success_and_text "oc cancel-build ${started} --dump-logs --restart" "restarted build \"${started}\""
os::cmd::expect_success 'oc delete all --all'
os::cmd::expect_success 'oc delete secret dbsecret'
os::cmd::expect_success 'oc process -f examples/sample-app/application-template-dockerbuild.json -l build=docker | oc create -f -'
os::cmd::try_until_success 'oc get build/ruby-sample-build-1'
# Uses type/name resource syntax to cancel the build and check for proper message
os::cmd::expect_success_and_text 'oc cancel-build build/ruby-sample-build-1' 'build "ruby-sample-build-1" cancelled'
# Make sure canceling already cancelled build returns proper message
os::cmd::expect_success 'oc cancel-build build/ruby-sample-build-1'
# Cancel all builds from a build configuration
os::cmd::expect_success "oc start-build bc/ruby-sample-build"
os::cmd::expect_success "oc start-build bc/ruby-sample-build"
lastbuild="$(basename $(oc start-build -o=name bc/ruby-sample-build))"
os::cmd::expect_success_and_text 'oc cancel-build bc/ruby-sample-build', "\"${lastbuild}\" cancelled"
os::cmd::expect_success_and_text "oc get build ${lastbuild} -o template --template '{{.status.phase}}'", 'Cancelled'
builds=$(oc get builds -o template --template '{{range .items}}{{ .status.phase }} {{end}}')
for state in $builds; do
  os::cmd::expect_success "[ \"${state}\" == \"Cancelled\" ]"
done
# Running this command again when all builds are cancelled should be no-op.
os::cmd::expect_success 'oc cancel-build bc/ruby-sample-build'
os::cmd::expect_success 'oc delete all --all'
os::cmd::expect_success 'oc delete secret dbsecret'
echo "cancel-build: ok"
os::test::junit::declare_suite_end

os::test::junit::declare_suite_end


text:
function mostrarTabela()
{
	var radioTodos = document.getElementById("Todos");
	var radioPintura = document.getElementById("Pintura");
	var radioFunilaria = document.getElementById("Funilaria");
	var radioMecanica = document.getElementById("Mecanica");

	var linhaPintura = document.getElementsByClassName("TipoPintura");
	var linhaFunilaria = document.getElementsByClassName("TipoFunilaria");
	var linhaMecanica = document.getElementsByClassName("TipoMecanica");

	var colunaVeiculo = document.getElementsByClassName("ColunaVeiculo");
	var colunaTipoServico = document.getElementsByClassName("ColunaTipoServico");
	var colunaServico = document.getElementsByClassName("ColunaServico");
	var colunaCor = document.getElementsByClassName("ColunaCor");
	var colunaPeca = document.getElementsByClassName("ColunaPeca");
	var colunaPreco = document.getElementsByClassName("ColunaPreco");

	if(radioTodos.checked == true)
	{
		for(i=0; i<linhaPintura.length; i++)
		{
			linhaPintura.item(i).setAttribute("style","display:");
		}
		for(i=0; i<linhaFunilaria.length; i++)
		{
			linhaFunilaria.item(i).setAttribute("style","display:");
		}
		for(i=0; i<linhaMecanica.length; i++)
		{
			linhaMecanica.item(i).setAttribute("style","display:");
		}

		for(i=0; i<colunaVeiculo.length; i++)
		{
			colunaVeiculo.item(i).setAttribute("style","display:");
		}
		for(i=0; i<colunaTipoServico.length; i++)
		{
			colunaTipoServico.item(i).setAttribute("style","display:");
		}
		for(i=0; i<colunaServico.length; i++)
		{
			colunaServico.item(i).setAttribute("style","display:");
		}
		for(i=0; i<colunaCor.length; i++)
		{
			colunaCor.item(i).setAttribute("style","display:");
		}
		for(i=0; i<colunaPeca.length; i++)
		{
			colunaPeca.item(i).setAttribute("style","display:");
		}
		for(i=0; i<colunaPreco.length; i++)
		{
			colunaPreco.item(i).setAttribute("style","display:");
		}
	}
	else if(radioPintura.checked == true)
	{
		for(i=0; i<linhaPintura.length; i++)
		{
			linhaPintura.item(i).setAttribute("style","display:");
		}
		for(i=0; i<linhaFunilaria.length; i++)
		{
			linhaFunilaria.item(i).setAttribute("style","display:none");
		}
		for(i=0; i<linhaMecanica.length; i++)
		{
			linhaMecanica.item(i).setAttribute("style","display:none");
		}

		for(i=0; i<colunaVeiculo.length; i++)
		{
			colunaVeiculo.item(i).setAttribute("style","display:");
		}
		for(i=0; i<colunaTipoServico.length; i++)
		{
			colunaTipoServico.item(i).setAttribute("style","display:");
		}
		for(i=0; i<colunaServico.length; i++)
		{
			colunaServico.item(i).setAttribute("style","display:");
		}
		for(i=0; i<colunaCor.length; i++)
		{
			colunaCor.item(i).setAttribute("style","display:");
		}
		for(i=0; i<colunaPeca.length; i++)
		{
			colunaPeca.item(i).setAttribute("style","display:");
		}
		for(i=0; i<colunaPreco.length; i++)
		{
			colunaPreco.item(i).setAttribute("style","display:");
		}
	}
	else if(radioFunilaria.checked == true)
	{
		for(i=0; i<linhaPintura.length; i++)
		{
			linhaPintura.item(i).setAttribute("style","display:none");
		}
		for(i=0; i<linhaFunilaria.length; i++)
		{
			linhaFunilaria.item(i).setAttribute("style","display:");
		}
		for(i=0; i<linhaMecanica.length; i++)
		{
			linhaMecanica.item(i).setAttribute("style","display:none");
		}

		for(i=0; i<colunaVeiculo.length; i++)
		{
			colunaVeiculo.item(i).setAttribute("style","display:");
		}
		for(i=0; i<colunaTipoServico.length; i++)
		{
			colunaTipoServico.item(i).setAttribute("style","display:");
		}
		for(i=0; i<colunaServico.length; i++)
		{
			colunaServico.item(i).setAttribute("style","display:");
		}
		for(i=0; i<colunaCor.length; i++)
		{
			colunaCor.item(i).setAttribute("style","display:none");
		}
		for(i=0; i<colunaPeca.length; i++)
		{
			colunaPeca.item(i).setAttribute("style","display:");
		}
		for(i=0; i<colunaPreco.length; i++)
		{
			colunaPreco.item(i).setAttribute("style","display:");
		}
	}
	else if(radioMecanica.checked == true)
	{

		for(i=0; i<linhaPintura.length; i++)
		{
			linhaPintura.item(i).setAttribute("style","display:none");
		}
		for(i=0; i<linhaFunilaria.length; i++)
		{
			linhaFunilaria.item(i).setAttribute("style","display:none");
		}
		for(i=0; i<linhaMecanica.length; i++)
		{
			linhaMecanica.item(i).setAttribute("style","display:");
		}

		for(i=0; i<colunaVeiculo.length; i++)
		{
			colunaVeiculo.item(i).setAttribute("style","display:");
		}
		for(i=0; i<colunaTipoServico.length; i++)
		{
			colunaTipoServico.item(i).setAttribute("style","display:");
		}
		for(i=0; i<colunaServico.length; i++)
		{
			colunaServico.item(i).setAttribute("style","display:");
		}
		for(i=0; i<colunaCor.length; i++)
		{
			colunaCor.item(i).setAttribute("style","display:none");
		}
		for(i=0; i<colunaPeca.length; i++)
		{
			colunaPeca.item(i).setAttribute("style","display:none");
		}
		for(i=0; i<colunaPreco.length; i++)
		{
			colunaPreco.item(i).setAttribute("style","display:");
		}
	}
}
function swapPlaceholder() {
	var TipoDePesquisa = document.getElementById("TipoDePesquisa");
	var CampoDePesquisa = document.getElementById("CampoDePesquisa");

	switch (TipoDePesquisa.value) {
	case "":
		CampoDePesquisa.setAttribute("placeholder",
				"Selecione uma opção...");
		break;
	case "Codigo":
		CampoDePesquisa.setAttribute("placeholder", "SERV####");
		break;
	case "TipoVeiculo":
		CampoDePesquisa.setAttribute("placeholder", "Carro ou Moto");
		break;
	case "TipoServico":
		CampoDePesquisa.setAttribute("placeholder",
				"Pintura, Mecanica ou Funilaria");
		break;
	case "Servico":
		CampoDePesquisa.setAttribute("placeholder", "Descrição do serviço");
		break;
	case "Preco":
		CampoDePesquisa.setAttribute("placeholder", "Preço Máximo");
		break;
	case "Cor":
		CampoDePesquisa.setAttribute("placeholder",
				"Informe a Cor da Pintura");
		break;
	case "Peca":
		CampoDePesquisa.setAttribute("placeholder", "Informe a Peça");
		break;
	}
}


text:
module JsonifiedForms
  VERSION = "0.0.1"
end


text:
<?php

/**
 * Author	: Praveen Kumar Pendyala (m@praveen.xyz)
 * Created	: 21.08.2015
 *
 * These are the list of actions / api calls for a teacher or course instructor
 */

$app->group('/teacher', function () use ($app, $db, $checkToken) {

    //################## Add Teacher  ##################
    $app->map('/add', $checkToken, function () use ($app, $db) {
        $userid = $app->request->headers->get("studentid");
        $name = $app->request->get('name');
        $website = $app->request->get('website');

        try {
            // Check duplicate
            $stmt0 = $db->prepare('SELECT teacherid FROM teachers WHERE name=?');
            $stmt0->execute(array($name));
            if($stmt0->rowCount() != 0){
                // Teacher already exists. So stop.
                $teacher = $stmt0->fetch(PDO::FETCH_ASSOC);
                ApiResponse::success(200, "success", "teacherid", $teacher['teacherid']);
                $app->stop();
            }

            $stmt = $db->prepare('INSERT INTO teachers (name, website, addedby) VALUES (?, ?, ?)');
            $stmt->execute(array(utf8_encode($name), utf8_encode($website), $userid));
            ApiResponse::success(200, "success", "teacherid", $db->lastInsertId());
        } catch (PDOException $ex) {
            ApiResponse::error(500, "Internal server error");
        }
    })->via('GET', 'POST');

    //################# Teachers  ##################
    $app->map('/list', function() use ($app, $db) {
        try{
            $stmt = $db->prepare('SELECT * FROM teachers LIMIT 50');
            $stmt->execute();
            ApiResponse::success(200, "success", "teachers", $stmt->fetchAll(PDO::FETCH_ASSOC));
        } catch(PDOException $ex){
            ApiResponse::error(500, "Internal server error");
        }
    })->via('GET', 'POST');

    //################## Search Teachers  ##################
    $app->map('/search', function() use ($app, $db) {
        $query = $app->request->get('q');
        try{
            $stmt = $db->prepare('SELECT * FROM teachers WHERE name LIKE ? LIMIT 10');
            $stmt->execute(array("%$query%"));
            ApiResponse::success(200, "success", "teachers", $stmt->fetchAll(PDO::FETCH_ASSOC));
        } catch(PDOException $ex){
            ApiResponse::error(500, "Internal server error");
        }
    })->via('GET', 'POST');

});


text:
package wave.caribe.dashboard;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.support.design.widget.FloatingActionButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.HashSet;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;

import android.graphics.RectF;
import com.mapbox.mapboxsdk.camera.CameraPosition;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;

import com.mapbox.mapboxsdk.annotations.Icon;
import com.mapbox.mapboxsdk.annotations.IconFactory;
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
import com.mapbox.mapboxsdk.constants.MyBearingTracking;
import com.mapbox.mapboxsdk.constants.MyLocationTracking;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.views.MapView;

import wave.caribe.dashboard.MQTT.MQTTCallbackInterface;
import wave.caribe.dashboard.MQTT.MQTTClient;
import wave.caribe.dashboard.model.Sensor;
import wave.caribe.dashboard.services.AsyncHttpTask;
import wave.caribe.dashboard.services.RegistrationIntentService;

/**
 * Caribe Wave Android App
 *
 * Main entry point
 *
 * Created by tchap on 14/03/16.
 */
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    private static final String TAG = "CW:MAIN ACTIVITY";

    private MQTTClient mMQTTClient;
    private GoogleApiClient mGoogleApiClient;
    private Location mCurrentLocation;
    private LocationRequest mLocationRequest;

    private final int REQUEST_LOCATION = 1;
    private final String LOCATION_FILTER_KEY = "location.request.caribe.wave";

    private MapView mapView = null;
    private TextView msg;
    private LinearLayout msgbox;
    private FloatingActionButton mLocationButton;

    // Timers for display
    private Timer resetMarkerTimer = new Timer();
    private Timer resetAlertTimer = new Timer();

    private boolean alert_in_progress = false;
    private static final int WARNING_DISPLAY_TIME_IN_S = 5;
    private static final int ALERT_DISPLAY_TIME_IN_S = 120;

    private final ArrayList<Sensor> sensors = new ArrayList<>();
    private final ArrayList<Marker> listOfMarkers = new ArrayList<>();

    private static final int DEFAULT_ZOOM = 10;
    private final float default_lat = 15.9369587f; // Marie Galante
    private final float default_lon = -61.301064f;
    private final int LOCATION_INTERVAL = 2000;

    private Date mLastActive;

    private SharedPreferences sharedPref;

    // GCM
    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    public static final String SENT_TOKEN_TO_SERVER = "sentTokenToServer";
    public static final String REGISTRATION_COMPLETE = "registrationComplete";

    // Do we have location permissions or not ?
    private boolean isLocationPermissionGranted() {
        return ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
    }
    private void askPermissionForLocation() {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                REQUEST_LOCATION);
    }

    private boolean isLocationServiceEnabled() {
        LocationManager locationManager;
        boolean gps_enabled= false,network_enabled = false;

        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

        try{
            gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        }catch(Exception ex){
            //do nothing...
        }

        try{
            network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        }catch(Exception ex){
            //do nothing...
        }

        return gps_enabled || network_enabled;

    }

    @Override
    protected void onCreate(final Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Force values (we hide the preference screen for now)
        PreferenceManager.setDefaultValues(this, R.xml.preferences, true);

        sharedPref = PreferenceManager.getDefaultSharedPreferences(this);

        // Request fine location (Android > 6.0)
        if (!isLocationPermissionGranted()) {
            Log.i(TAG, "Asking for permissions (Location)");
            askPermissionForLocation();
        }

        // Check if we have Play Services for GCM
        if (checkPlayServices()) {
            Log.i(TAG, "Play Services are OK");
            // Start IntentService to register this application with GCM.
            Intent intent = new Intent(this, RegistrationIntentService.class);
            startService(intent);
        } else {
            Log.i(TAG, "Play Services are NOT ok");
        }

        msg = (TextView) findViewById(R.id.msg);
        msgbox = (LinearLayout) findViewById(R.id.msgbox);
        mLocationButton = (FloatingActionButton) findViewById(R.id.location);
        if (isLocationPermissionGranted() && isLocationServiceEnabled()) {
            mLocationButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Toggle GPS position updates
                    if (mCurrentLocation != null) {
                        CameraPosition cameraPosition = new CameraPosition.Builder()
                                .target(new LatLng(mCurrentLocation))
                                .build();
                        mapView.easeCamera(CameraUpdateFactory.newCameraPosition(cameraPosition), 1000, null);
                    }
                }
            });
        }

        mapView = (MapView) findViewById(R.id.map);
        mapView.setAccessToken(getString(R.string.mapbox_id));

        //Handling tasks dispatching across 3 threads
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        Set<Callable<Boolean>> callables = new HashSet<>();

        callables.add(new Callable<Boolean>() {
            public Boolean call() throws Exception {

                // Instantiate map
                Log.i(TAG, "Instantiating map");

                mapView.setStyleUrl("mapbox://styles/anthill/ciltunikq00eya2kq6s5nk85k");
                mapView.setCenterCoordinate(new LatLng(default_lat, default_lon));
                mapView.setZoomLevel(DEFAULT_ZOOM);
                mapView.setRotateEnabled(false);
                mapView.onCreate(savedInstanceState);

                if (isLocationPermissionGranted() && isLocationServiceEnabled()) {
                    //noinspection ResourceType
                    mapView.setMyLocationEnabled(true);
                    //noinspection ResourceType
                    mapView.setMyLocationTrackingMode(MyLocationTracking.TRACKING_NONE);
                    //noinspection ResourceType
                    mapView.setMyBearingTrackingMode(MyBearingTracking.GPS);

                    mapView.setOnMyLocationChangeListener(new MapView.OnMyLocationChangeListener() {
                        @Override
                        public void onMyLocationChange(@Nullable Location location) {
                            if (location != null) {
                                CameraPosition cameraPosition = new CameraPosition.Builder()
                                        .target(new LatLng(location))
                                        .zoom(DEFAULT_ZOOM)
                                        .build();
                                mapView.easeCamera(CameraUpdateFactory.newCameraPosition(cameraPosition), 1000, null);
                                mapView.setOnMyLocationChangeListener(null);
                            }
                        }
                    });

                    mLocationButton.setVisibility(View.VISIBLE);

                } else if (isLocationPermissionGranted()) {
                    mLocationButton.setVisibility(View.VISIBLE);
                    mLocationButton.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.text)));
                    mLocationButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Toast.makeText(getApplicationContext(), R.string.error_location, Toast.LENGTH_LONG).show();
                        }
                    });
                }

                // Msg Box
                msg.setText(R.string.no_event);

                return true;

            }
        });

        callables.add(new Callable<Boolean>() {
            public Boolean call() throws Exception {
                // Build the Google API client for location requests
                Log.i(TAG, "Building Google API Client");
                buildGoogleApiClient();
                return true;
            }
        });

        callables.add(new Callable<Boolean>() {
            public Boolean call() throws Exception {
                // Retrieve sensor list
                Log.i(TAG, "Retrieving Sensor list");
                getSensorList();
                return true;
            }
        });

        try {

            executorService.invokeAll(callables);
        } catch (Exception ignored) {}
        finally {
            executorService.shutdown();
        }

        // Build the MQTT Client
        Log.i(TAG, "Creating MQTT Client");
        mMQTTClient = new MQTTClient(this);

    }

    private void getSensorList()
    {

        String api_url = sharedPref.getString("pref_sensor_api", "");

        if (api_url.equals("")) {
            Log.i(TAG, "Bad sensor list URL");
        } else {
            AsyncHttpTask task = new AsyncHttpTask(new AsyncHttpTask.TaskListener() {
                @Override
                public void onFinished(JSONArray result) {
                    // Translate to sensor ArrayList
                    Sensor current;
                    ArrayList<LatLng> coordinates = new ArrayList<>();

                    for (int i = 0; i < result.length(); i++) {
                        try {

                            JSONObject place = result.getJSONObject(i);
                            JSONArray sensor_uids = place.getJSONArray("sensor_uids");
                            LatLng c = new LatLng(Double.parseDouble(place.getString("lat")), Double.parseDouble(place.getString("lon")));

                            if (sensor_uids.length() > 0 && !sensor_uids.get(0).toString().equals("null")) {
                                current = new Sensor(sensor_uids.get(0).toString(), place.getString("name"), c);
                            } else {
                                current = new Sensor(null,place.getString("name"), c);
                            }
                            coordinates.add(c);
                            sensors.add(current);

                        } catch(JSONException ignored) {}
                    }

                    LatLng[] arr = coordinates.toArray(new LatLng[coordinates.size()]);
                    mapView.setVisibleCoordinateBounds(arr, new RectF(100, 100, 100, 100), true);

                    resetStillMarkers();
                }
            });
            task.execute(api_url);
        }

    }

    private void resetStillMarkers()
    {

        Log.i(TAG, "Resetting markers.");

        runOnUiThread(new Runnable() {
            @SuppressLint("PrivateResource")
            @Override
            public void run() {
                mapView.removeAllAnnotations();
                listOfMarkers.clear();
                msg.setText(R.string.no_event);
                msg.setTextColor(getResources().getColor(R.color.black));
                msgbox.setBackgroundColor(getResources().getColor(R.color.safe));
            }
        });

        IconFactory mIconFactory = IconFactory.getInstance(this);
        Drawable mIconDrawableDisabled = ContextCompat.getDrawable(this, R.drawable.map_grey);
        Icon disabled_icon = mIconFactory.fromDrawable(mIconDrawableDisabled);

        Drawable mIconDrawableActive = ContextCompat.getDrawable(this, R.drawable.map_green);
        Icon active_icon = mIconFactory.fromDrawable(mIconDrawableActive);

        for (int i = 0; i < sensors.size(); i++)
        {
            listOfMarkers.add(
                mapView.addMarker(new MarkerOptions()
                        .position(sensors.get(i).getLatLng())
                        .title(sensors.get(i).getName())
                        .icon(sensors.get(i).hasUid() ? active_icon : disabled_icon)
                        .snippet(sensors.get(i).getUid())));
        }

    }

    private synchronized void buildGoogleApiClient()
    {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();

        if (isLocationPermissionGranted()) {
            createLocationRequest();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {

        switch (item.getItemId()) {
            case R.id.action_retry:
                Toast.makeText(getApplicationContext(), R.string.msg_reconnecting, Toast.LENGTH_LONG).show();

                // Retrieve sensor list
                Log.i(TAG, "Retrieving Sensor list");
                getSensorList();
                Log.i(TAG, "Reconnecting MQTT");
                reconnect();
                return true;
            case R.id.action_settings:
                getFragmentManager().beginTransaction()
                    .replace(android.R.id.content, new SettingsFragment())
                    .addToBackStack("settings")
                    .commit();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public void reconnect()
    {

        // In case of reconnection, make sure that everything comes
        // back to normal before reconnecting
        resetStillMarkers();

        HandlerThread handlerThread = new HandlerThread("MQTTHandler");
        handlerThread.start();
        Handler handler = new Handler(handlerThread.getLooper());
        Runnable r = new Runnable() {
            @Override
            public void run() {
                Log.i(TAG, "Connecting MQTT Client");
                mMQTTClient.reconnect(new MQTTCallbackInterface() {
                    public void newMeasurement(String uid, JSONArray measurement) {
                        updateMap(uid, measurement);
                    }
                    public void alert(JSONObject alert) {
                        showAlert(alert);
                    }
                });
            }
        };

        handler.post(r);

    }

    private void updateMap(String uid, JSONArray measurement)
    {
        if (alert_in_progress) {
            // We don't want to interfere with a general alert
            return;
        }

        // A new event is coming
        resetMarkerTimer.cancel();

        updateLastActive();

        final ArrayList<String> places = new ArrayList<>();

        IconFactory mIconFactory = IconFactory.getInstance(this);
        Drawable mIconDrawableDanger = ContextCompat.getDrawable(this, R.drawable.map_yellow);
        Icon warning_icon = mIconFactory.fromDrawable(mIconDrawableDanger);

        for (final Marker marker : listOfMarkers) {
            if (marker.getSnippet().equals(uid)) {
                places.add(marker.getTitle());
                marker.setIcon(warning_icon);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mapView.removeMarker(marker);
                        mapView.addMarker(new MarkerOptions()
                                .position(marker.getPosition())
                                .title(marker.getTitle())
                                .icon(marker.getIcon())
                                .snippet(marker.getSnippet()));
                    }
                });

            }
        }

        // Update msg box
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                msg.setText(String.format(getString(R.string.measurement_event), TextUtils.join(", ", places)));
                msgbox.setBackgroundColor(getResources().getColor(R.color.warning));
            }
        });

        // Run for 2 seconds
        resetMarkerTimer = new Timer();
        resetMarkerTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (!alert_in_progress) {
                    resetStillMarkers();
                }
                resetMarkerTimer.cancel();
            }
        }, WARNING_DISPLAY_TIME_IN_S*1000);

    }

    private void showAlert(JSONObject alert)
    {
        // A new event is coming
        resetMarkerTimer.cancel();
        alert_in_progress = true;

        String tmp;
        JSONArray sensor_uids;
        List<String> uids_list = new ArrayList<>();
        updateLastActive();

        try {
            tmp = alert.get("message").toString();
        } catch(Exception e) {
            tmp = getString(R.string.general_alert);
        }

        try {
            sensor_uids = (JSONArray) alert.get("sensors_uids");
            //noinspection StatementWithEmptyBody
            for (int i = 0; i < sensor_uids.length();uids_list.add(sensor_uids.get(i++).toString()));
        } catch(Exception ignored) {
        }

        IconFactory mIconFactory = IconFactory.getInstance(this);
        Drawable mIconDrawableDanger = ContextCompat.getDrawable(this, R.drawable.map_red);
        Icon danger_icon = mIconFactory.fromDrawable(mIconDrawableDanger);

        for (final Marker marker : listOfMarkers) {
            if (uids_list.contains(marker.getSnippet())) {
                marker.setIcon(danger_icon);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mapView.removeMarker(marker);
                        mapView.addMarker(new MarkerOptions()
                                .position(marker.getPosition())
                                .title(marker.getTitle())
                                .icon(marker.getIcon())
                                .snippet(marker.getSnippet()));
                            }
                });
            }
        }

        final String message = tmp;
        // Update msg box with alert
        runOnUiThread(new Runnable() {
            @SuppressLint("PrivateResource")
            @Override
            public void run() {
                msg.setText(message);
                msg.setTextColor(getResources().getColor(R.color.white));
                msgbox.setBackgroundColor(getResources().getColor(R.color.danger));
            }
        });

        // Run for 2 seconds
        resetAlertTimer = new Timer();
        resetAlertTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                resetStillMarkers();
                resetAlertTimer.cancel();
                alert_in_progress = false;
            }
        }, ALERT_DISPLAY_TIME_IN_S*1000);
    }

    private void updateLastActive()
    {
        mLastActive = new Date();
        //Log.i(TAG, "Data received at " + mLastActive.toString());
    }

    /*
    * Manages the back button in fragments stacks
    * */
    @Override
    public void onBackPressed()
    {
        if (getFragmentManager().getBackStackEntryCount() > 0) {
            getFragmentManager().popBackStack();
            getFragmentManager().beginTransaction().commit();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onResume()
    {
        super.onResume();
        mapView.onResume();
        reconnect(); // Reconnect MQTT
        // Within {@code onPause()}, we pause location updates, but leave the
        // connection to GoogleApiClient intact.
        startLocationUpdates();

    }

    @Override
    public void onPause()
    {
        super.onPause();
        mapView.onPause();
        // Stop location updates to save battery, but don't disconnect the GoogleApiClient object.
        stopLocationUpdates();
        if (mMQTTClient != null) {
            try {
                mMQTTClient.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onStop()
    {
        super.onStop();
        mapView.onStop();
        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
        super.onStop();
    }

    @Override
    protected void onStart()
    {
        super.onStart();
        mapView.onStart();
        if (mGoogleApiClient != null && !mGoogleApiClient.isConnected() && !mGoogleApiClient.isConnecting()) {
            mGoogleApiClient.connect();
        }
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String permissions[], @NonNull int[] grantResults)
    {
        switch (requestCode) {
            case REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay
                    createLocationRequest();
                    startLocationUpdates();
                }
            }
        }
    }

    private void createLocationRequest()
    {
        if (mLocationRequest == null) { // Do not recreate it
            mLocationRequest = new LocationRequest();
            mLocationRequest.setInterval(LOCATION_INTERVAL);
            mLocationRequest.setFastestInterval(3000);
            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        }
    }

    private void stopLocationUpdates()
    {
        if (mGoogleApiClient != null && mGoogleApiClient.isConnected() && isLocationPermissionGranted()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }

    private void startLocationUpdates()
    {
        if (mGoogleApiClient != null && mGoogleApiClient.isConnected() && isLocationPermissionGranted()) {
            //noinspection ResourceType
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
    }
    @Override
    public void onLocationChanged(Location location)
    {
        // We can set the flag back to true since this method is only
        // called when we have a new "real" location
        mCurrentLocation = location;
        //Log.i("  MAIN LOCATION UPDATE", mCurrentLocation.toString());

        Intent intent = new Intent(LOCATION_FILTER_KEY);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

    /**
     * Runs when a GoogleApiClient object successfully connects.
     */
    @Override
    public void onConnected(Bundle connectionHint)
    {

        // If the initial location was never previously requested, we use
        // FusedLocationApi.getLastLocation() to get it. If it was previously requested, we store
        // its value in the Bundle and check for it in onCreate()
        //
        // Because we cache the value of the initial location in the Bundle, it means that if the
        // user launches the activity,
        // moves to a new location, and then changes the device orientation, the original location
        // is displayed as the activity is re-created.
        if (mCurrentLocation == null && isLocationPermissionGranted()) {
            //noinspection ResourceType
            mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        }

        startLocationUpdates();
    }

    @Override
    public void onConnectionSuspended(int cause)
    {
        // The connection to Google Play services was lost for some reason. We call connect() to
        // attempt to re-establish the connection.
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult result)
    {
        // Refer to the javadoc for ConnectionResult to see what error codes might be returned in
        // onConnectionFailed.
    }

    /**
     * Check the device to make sure it has the Google Play Services APK. If
     * it doesn't, display a dialog that allows users to download the APK from
     * the Google Play Store or enable it in the device's system settings.
     */
    private boolean checkPlayServices()
    {
        GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
        int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            Log.i(TAG, "GCM Error : " + resultCode);
            if (apiAvailability.isUserResolvableError(resultCode)) {
                apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
                        .show();
            } else {
                Log.i(TAG, "GCM Error : This device is not supported.");
                finish();
            }
            return false;
        }
        return true;
    }
}


text:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>MianIO</title>
    <script src="https://use.fontawesome.com/00501ef61b.js"></script>
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
  </head>
  <body>
    <div id="app" />
    <script src="public/bundle.js" type="text/javascript"></script>
  </body>
</html>


text:
package com.fulin.TwoPointer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Given two arrays, write a function to compute their intersection.
 * Example:
 * Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
 * Note:
 * Each element in the result should appear as many times as it shows in both arrays.
 * The result can be in any order.
 *
 * Created by fulin on 17-2-14.
 */
public class IntersectionofTwoArraysII {
    public static void main(String[] args){

    }

    public int[] intersect(int[] nums1, int[] nums2) {
        if(nums1 == null || nums2 == null ){
            return null;
        }
        int[] result = null;
        List<Integer> list = new ArrayList<Integer>();
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int index1 = 0;
        int index2 = 0;
        while(index1 < nums1.length && index2 < nums2.length){
            if(nums1[index1] == nums2[index2]){
                list.add(nums1[index1]);
                index1 ++;
                index2 ++;
            }else if(nums1[index1] > nums2[index2]){
                index2 ++;
            }else{
                index1 ++;
            }
        }

        result = new int[list.size()];
        for(int i=0;i<list.size();i++){
            result[i] = list.get(i);
        }
        return result;
    }

}


text:
class SoftmaxTester {
public:
	SoftmaxTester() :
		iterations_(1),
		errorLimit_(1.0e-5),
		multithreading_(false),
		batchSize_(1),
		channels_(1)
	{
		this->threadpool = nullptr;
	}

	SoftmaxTester(const SoftmaxTester&) = delete;

	inline SoftmaxTester(SoftmaxTester&& tester) :
		iterations_(tester.iterations_),
		errorLimit_(tester.errorLimit_),
		multithreading_(tester.multithreading_),
		batchSize_(tester.batchSize_),
		channels_(tester.channels_),
		threadpool(tester.threadpool)
	{
		tester.threadpool = nullptr;
	}

	SoftmaxTester& operator=(const SoftmaxTester&) = delete;

	~SoftmaxTester() {
		if (this->threadpool != nullptr) {
			pthreadpool_destroy(this->threadpool);
			this->threadpool = nullptr;
		}
	}

	inline SoftmaxTester& iterations(size_t iterations) {
		this->iterations_ = iterations;
		return *this;
	}

	inline size_t iterations() const {
		return this->iterations_;
	}

	inline SoftmaxTester& errorLimit(float errorLimit) {
		this->errorLimit_ = errorLimit;
		return *this;
	}

	inline float errorLimit() const {
		return this->errorLimit_;
	}

	inline SoftmaxTester& multithreading(bool multithreading) {
		this->multithreading_ = multithreading;
		if (multithreading && this->threadpool == nullptr) {
			this->threadpool = pthreadpool_create(0);
		} else if (!multithreading && this->threadpool != nullptr) {
			pthreadpool_destroy(this->threadpool);
			this->threadpool = nullptr;
		}
		return *this;
	}

	inline bool multithreading() const {
		return this->multithreading_;
	}

	inline SoftmaxTester& batchSize(size_t batchSize) {
		this->batchSize_ = batchSize;
		return *this;
	}

	inline size_t batchSize() const {
		return this->batchSize_;
	}

	inline SoftmaxTester& channels(size_t channels) {
		this->channels_ = channels;
		return *this;
	}

	inline size_t channels() const {
		return this->channels_;
	}

	void testOutput() const {
		const uint_fast32_t seed = std::chrono::system_clock::now().time_since_epoch().count();
		auto rng = std::bind(std::uniform_real_distribution<float>(-1.0f, +1.0f), std::mt19937(seed));

		std::vector<float> input(batchSize() * channels());
		std::vector<float> output(batchSize() * channels());
		std::vector<float> referenceOutput(batchSize() * channels());

		for (size_t iteration = 0; iteration < iterations(); iteration++) {
			std::generate(input.begin(), input.end(), std::ref(rng));
			std::fill(output.begin(), output.end(), nanf(""));

			nnp_softmax_output__reference(
				batchSize(), channels(),
				input.data(), referenceOutput.data(),
				this->threadpool);

			enum nnp_status status = nnp_softmax_output(
				batchSize(), channels(),
				input.data(), output.data(),
				this->threadpool);
			ASSERT_EQ(nnp_status_success, status);

			const float maxError = std::inner_product(referenceOutput.cbegin(), referenceOutput.cend(), output.cbegin(), 0.0f,
				[](float x, float y)->float { return std::max<float>(y, x); }, relativeError);
			EXPECT_LT(maxError, errorLimit());
		}
	}

	void testOutputInplace() const {
		const uint_fast32_t seed = std::chrono::system_clock::now().time_since_epoch().count();
		auto rng = std::bind(std::uniform_real_distribution<float>(-1.0f, +1.0f), std::mt19937(seed));

		std::vector<float> data(batchSize() * channels());
		std::vector<float> referenceData(batchSize() * channels());
		const float negativeSlope = 0.2f;

		for (size_t iteration = 0; iteration < iterations(); iteration++) {
			std::generate(data.begin(), data.end(), std::ref(rng));
			std::copy(data.cbegin(), data.cend(), referenceData.begin());

			nnp_softmax_output__reference(
				batchSize(), channels(),
				referenceData.data(), referenceData.data(),
				this->threadpool);

			enum nnp_status status = nnp_softmax_output(
				batchSize(), channels(),
				data.data(), data.data(),
				this->threadpool);
			ASSERT_EQ(nnp_status_success, status);

			const float maxError = std::inner_product(referenceData.cbegin(), referenceData.cend(), data.cbegin(), 0.0f,
				[](float x, float y)->float { return std::max<float>(y, x); }, relativeError);
			EXPECT_LT(maxError, errorLimit());
		}
	}

protected:
	pthreadpool_t threadpool;

private:
	inline static float relativeError(float reference, float actual) {
		return std::abs(reference - actual) / std::max(FLT_MIN, std::abs(reference));
	}

	size_t iterations_;
	float errorLimit_;
	bool multithreading_;

	size_t batchSize_;
	size_t channels_;
};


text:
package org.sleuthkit.autopsy.communications;

import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.ChildFactory;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.python.google.common.collect.Iterables;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.datamodel.AccountDeviceInstance;
import org.sleuthkit.datamodel.BlackboardArtifact;
import org.sleuthkit.datamodel.CommunicationsFilter;
import org.sleuthkit.datamodel.CommunicationsManager;
import org.sleuthkit.datamodel.Content;
import org.sleuthkit.datamodel.TskCoreException;

/**
 * 'Root' Node for the Account/Messages area. Has children which are all the
 * relationships of all the accounts in this node.
 *
 */
final class AccountDetailsNode extends AbstractNode {

    private final static Logger logger = Logger.getLogger(AccountDetailsNode.class.getName());

    AccountDetailsNode(Set<AccountDeviceInstance> accountDeviceInstances, CommunicationsFilter filter, CommunicationsManager commsManager) {
        super(Children.create(new AccountRelationshipChildren(accountDeviceInstances, commsManager, filter), true));
        String displayName = (accountDeviceInstances.size() == 1)
                ? Iterables.getOnlyElement(accountDeviceInstances).getAccount().getTypeSpecificID()
                : accountDeviceInstances.size() + " accounts";
        setDisplayName(displayName);
    }

    /**
     * Children object for the relationships that the accounts are part of.
     */
    private static class AccountRelationshipChildren extends ChildFactory<Content> {

        private final Set<AccountDeviceInstance> accountDeviceInstances;
        private final CommunicationsManager commsManager;
        private final CommunicationsFilter filter;

        private AccountRelationshipChildren(Set<AccountDeviceInstance> accountDeviceInstances, CommunicationsManager commsManager, CommunicationsFilter filter) {
            this.accountDeviceInstances = accountDeviceInstances;
            this.commsManager = commsManager;
            this.filter = filter;
        }

        @Override
        protected boolean createKeys(List<Content> list) {
            try {
                list.addAll(commsManager.getRelationshipSources(accountDeviceInstances, filter));
            } catch (TskCoreException ex) {
                logger.log(Level.SEVERE, "Error getting communications", ex);
            }
            return true;
        }

        @Override
        protected Node createNodeForKey(Content t) {
            if (t instanceof BlackboardArtifact) {
                return new RelationshipNode((BlackboardArtifact) t);
            } else {
                throw new UnsupportedOperationException("Cannot create a RelationshipNode for non BlackboardArtifact content.");
            }
        }
    }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MainWindow.xaml.cs" company="Helix Toolkit">
//   Copyright (c) 2014 Helix Toolkit contributors
// </copyright>
// <summary>
//   Interaction logic for MainWindow.xaml
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace TubeDemo
{
    using System;
    using System.Windows;
    using System.Windows.Media.Media3D;

    using ExampleBrowser;

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    [Example(null, "Shows Borromean rings using the TubeVisual3D.")]
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            // http://en.wikipedia.org/wiki/Borromean_rings
            // http://paulbourke.net/geometry/borromean/

            int n = 180;
            double r = Math.Sqrt(3) / 3;
            Ring1 = this.CreatePath(0, Math.PI * 2, n, u => Math.Cos(u), u => Math.Sin(u) + r, u => Math.Cos(3 * u) / 3);
            Ring2 = this.CreatePath(0, Math.PI * 2, n, u => Math.Cos(u) + 0.5, u => Math.Sin(u) - r / 2, u => Math.Cos(3 * u) / 3);
            Ring3 = this.CreatePath(0, Math.PI * 2, n, u => Math.Cos(u) - 0.5, u => Math.Sin(u) - r / 2, u => Math.Cos(3 * u) / 3);

            DataContext = this;
        }

        private Point3DCollection CreatePath(double min, double max, int n, Func<double, double> fx, Func<double, double> fy, Func<double, double> fz)
        {
            var list = new Point3DCollection(n);
            for (int i = 0; i < n; i++)
            {
                double u = min + (max - min) * i / n;
                list.Add(new Point3D(fx(u), fy(u), fz(u)));
            }
            return list;
        }

        public Point3DCollection Ring1 { get; set; }
        public Point3DCollection Ring2 { get; set; }
        public Point3DCollection Ring3 { get; set; }
    }
}