text:
package com.mcnallydevelopers.android.apps.encartelera;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.google.android.gms.ads.AdView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.nhaarman.listviewanimations.swinginadapters.AnimationAdapter;
import com.nhaarman.listviewanimations.swinginadapters.prepared.AlphaInAnimationAdapter;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;

public class HomeActivity extends ActionBarActivity {

    /**
     * API Url
     */
    private static final String API = "http://movies.apinic.org/v1/movie/all";

    private Helper helper = null;

    private AdView adView;
    private AdRequest adRequest;
    private String deviceid;

    private static final String AD_UNIT_ID = "ca-app-pub-2015513932539714/1102672624";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        helper = new Helper(this);

        if(helper.isConnected()){
            getMovies();

            // admob
            adMobInit();
        }
        else{
            Intent intent = new Intent(this, InternetRequireActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        }

    }

    private void adMobInit() {
        // Create an ad.
        adView = new AdView(this);
        adView.setAdSize(AdSize.SMART_BANNER);
        adView.setAdUnitId(AD_UNIT_ID);

        // Add the AdView to the view hierarchy. The view will have no size
        // until the ad is loaded.
        LinearLayout layout = (LinearLayout) findViewById(R.id.ad);
        layout.removeAllViews();

        if (helper.isConnected()) {
            layout.setVisibility(View.VISIBLE);
            layout.addView(adView);

            final TelephonyManager tm = (TelephonyManager) getBaseContext()
                    .getSystemService(Context.TELEPHONY_SERVICE);

            deviceid = tm.getDeviceId();

            // Create an ad request. Check logcat output for the hashed device
            // ID to
            // get test ads on a physical device.
            adRequest = new AdRequest.Builder()
                    .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                    .addTestDevice(deviceid).build();

            // Start loading the ad in the background.
            adView.loadAd(adRequest);
        } else {
            layout.setVisibility(View.GONE);
        }
    }

    private void getMovies() {
        AsyncHttpClient client = new AsyncHttpClient();
        client.get(API, new JsonHttpResponseHandler() {
            @Override
            public void onStart() {
                setProgressBarIndeterminateVisibility(Boolean.TRUE);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONArray response) {

                if (response.length() > 0) {

                    MoviesList[] moviesList = new MoviesList[response.length()];

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

                        try {

                            JSONObject movie = response.getJSONObject(i);

                            moviesList[i] = new MoviesList();
                            moviesList[i].setName(movie.getString("name"));
                            moviesList[i].setFront(movie.getString("front"));
                            moviesList[i].setSynopsis(movie.getString("synopsis"));
                            moviesList[i].setGenres(movie.getString("genres"));
                            moviesList[i].setClasification(movie.getString("clasification"));
                            moviesList[i].setDuration(movie.getString("duration"));

                        } catch (JSONException e) {

                            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();

                        }

                    }

                    ListView listView = (ListView) findViewById(R.id.listview_movies);

                    MoviesAdapter adapter = new MoviesAdapter(getApplicationContext(), moviesList);
                    AnimationAdapter animAdapter = new AlphaInAnimationAdapter(adapter);
                    animAdapter.setAbsListView(listView);
                    listView.setAdapter(animAdapter);
                    adapter.addAll(moviesList);

                }
                setProgressBarIndeterminateVisibility(Boolean.FALSE);

            }

        });
    }

    /*
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.home, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    */
}


text:
package net.canang.cfi.biz.ar.manager.history;

/**
 * @author rafizan.baharum
 * @since 10/3/13
 */
public class ReceiptRecord {
}

redpajama_set_name: RedPajamaGithub


text:
.class Lcom/htc/app/FilePickerRecentFragment$1;
.super Ljava/lang/Object;
.source "FilePickerRecentFragment.java"

# interfaces
.implements Lcom/htc/app/FilePickerListView$LayoutChangeListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/htc/app/FilePickerRecentFragment;->onCreateView(Landroid/view/LayoutInflater;Landroid/view/ViewGroup;Landroid/os/Bundle;)Landroid/view/View;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/htc/app/FilePickerRecentFragment;

# direct methods
.method constructor <init>(Lcom/htc/app/FilePickerRecentFragment;)V
    .locals 0
    .parameter

    .prologue
    .line 148
    iput-object p1, p0, Lcom/htc/app/FilePickerRecentFragment$1;->this$0:Lcom/htc/app/FilePickerRecentFragment;

    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onLayout()V
    .locals 1

    .prologue
    .line 150
    iget-object v0, p0, Lcom/htc/app/FilePickerRecentFragment$1;->this$0:Lcom/htc/app/FilePickerRecentFragment;

    #calls: Lcom/htc/app/FilePickerRecentFragment;->updateCountOfRecentListViewHeader()V
    invoke-static {v0}, Lcom/htc/app/FilePickerRecentFragment;->access$300(Lcom/htc/app/FilePickerRecentFragment;)V

    .line 151
    return-void
.end method


text:
define(["view/on-off-button"], function(OnOffButton){

  var MicButton = function(){
    this.initialize.apply(this, arguments);
  };

  MicButton.prototype = {
    initialize: function(config){
      this.mic = config.mic;
      this.el = new OnOffButton(config.el);

      this.el.addEventListener("on", function(){
        console.log("Enable the microphone");
        this.mic.enable();
      }.bind(this));
      this.el.addEventListener("off", function(){
        console.log("Disable the microphone");
        this.mic.disable();
      }.bind(this));
    }
  };

  return MicButton;
});


text:
package generator_test

import (
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"testing"

	"github.com/go-swagger/go-swagger/cmd/swagger/commands/generate"
	flags "github.com/jessevdk/go-flags"
)

func TestGenerateAndBuild(t *testing.T) {
	cases := map[string]struct {
		spec string
	}{
		"issue 844": {
			"../fixtures/bugs/844/swagger.json",
		},
	}

	for name, cas := range cases {
		t.Run(name, func(t *testing.T) {
			spec := filepath.FromSlash(cas.spec)

			generated, err := ioutil.TempDir(filepath.Dir(spec), "generated")
			if err != nil {
				t.Fatalf("TempDir()=%s", generated)
			}
			defer os.RemoveAll(generated)

			err = newTestClient(spec, generated).Execute(nil)
			if err != nil {
				t.Fatalf("Execute()=%s", err)
			}

			packages := filepath.Join(generated, "...")

			if p, err := exec.Command("go", "get", packages).CombinedOutput(); err != nil {
				t.Fatalf("go get %s: %s\n%s", packages, err, p)
			}

			if p, err := exec.Command("go", "build", packages).CombinedOutput(); err != nil {
				t.Fatalf("go build %s: %s\n%s", packages, err, p)
			}
		})
	}
}

func newTestClient(input, output string) *generate.Client {
	c := &generate.Client{
		DefaultScheme:   "http",
		DefaultProduces: "application/json",
	}
	c.Spec = flags.Filename(input)
	c.Target = flags.Filename(output)
	c.APIPackage = "operations"
	c.ModelPackage = "models"
	c.ServerPackage = "restapi"
	c.ClientPackage = "client"
	return c
}


text:
package com.microsoft.bingads.v12.adinsight;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="Keywords" type="{http://schemas.microsoft.com/2003/10/Serialization/Arrays}ArrayOfstring" minOccurs="0"/>
 *         <element name="MaxBid" type="{http://www.w3.org/2001/XMLSchema}double" minOccurs="0"/>
 *         <element name="Language" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="LocationIds" type="{http://schemas.microsoft.com/2003/10/Serialization/Arrays}ArrayOflong" minOccurs="0"/>
 *         <element name="CurrencyCode" type="{http://schemas.datacontract.org/2004/07/Microsoft.BingAds.Advertiser.AdInsight.Api.DataContract.V12.Entity}CurrencyCode" minOccurs="0"/>
 *         <element name="MatchTypes" type="{http://schemas.datacontract.org/2004/07/Microsoft.BingAds.Advertiser.AdInsight.Api.DataContract.V12.Entity}ArrayOfMatchType" minOccurs="0"/>
 *         <element name="CampaignId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
 *         <element name="AdGroupId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "keywords",
    "maxBid",
    "language",
    "locationIds",
    "currencyCode",
    "matchTypes",
    "campaignId",
    "adGroupId"
})
@XmlRootElement(name = "GetEstimatedPositionByKeywordsRequest", namespace = "Microsoft.Advertiser.AdInsight.Api.Service.V12")
public class GetEstimatedPositionByKeywordsRequest {

    @XmlElement(name = "Keywords", namespace = "Microsoft.Advertiser.AdInsight.Api.Service.V12", nillable = true)
    protected ArrayOfstring keywords;
    @XmlElement(name = "MaxBid", namespace = "Microsoft.Advertiser.AdInsight.Api.Service.V12")
    protected Double maxBid;
    @XmlElement(name = "Language", namespace = "Microsoft.Advertiser.AdInsight.Api.Service.V12", nillable = true)
    protected String language;
    @XmlElement(name = "LocationIds", namespace = "Microsoft.Advertiser.AdInsight.Api.Service.V12", nillable = true)
    protected ArrayOflong locationIds;
    @XmlElement(name = "CurrencyCode", namespace = "Microsoft.Advertiser.AdInsight.Api.Service.V12", nillable = true)
    @XmlSchemaType(name = "string")
    protected CurrencyCode currencyCode;
    @XmlElement(name = "MatchTypes", namespace = "Microsoft.Advertiser.AdInsight.Api.Service.V12", nillable = true)
    protected ArrayOfMatchType matchTypes;
    @XmlElement(name = "CampaignId", namespace = "Microsoft.Advertiser.AdInsight.Api.Service.V12", nillable = true)
    protected Long campaignId;
    @XmlElement(name = "AdGroupId", namespace = "Microsoft.Advertiser.AdInsight.Api.Service.V12", nillable = true)
    protected Long adGroupId;

    /**
     * Gets the value of the keywords property.
     *
     * @return
     *     possible object is
     *     {@link ArrayOfstring }
     *
     */
    public ArrayOfstring getKeywords() {
        return keywords;
    }

    /**
     * Sets the value of the keywords property.
     *
     * @param value
     *     allowed object is
     *     {@link ArrayOfstring }
     *
     */
    public void setKeywords(ArrayOfstring value) {
        this.keywords = value;
    }

    /**
     * Gets the value of the maxBid property.
     *
     * @return
     *     possible object is
     *     {@link Double }
     *
     */
    public Double getMaxBid() {
        return maxBid;
    }

    /**
     * Sets the value of the maxBid property.
     *
     * @param value
     *     allowed object is
     *     {@link Double }
     *
     */
    public void setMaxBid(Double value) {
        this.maxBid = value;
    }

    /**
     * Gets the value of the language property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getLanguage() {
        return language;
    }

    /**
     * Sets the value of the language property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setLanguage(String value) {
        this.language = value;
    }

    /**
     * Gets the value of the locationIds property.
     *
     * @return
     *     possible object is
     *     {@link ArrayOflong }
     *
     */
    public ArrayOflong getLocationIds() {
        return locationIds;
    }

    /**
     * Sets the value of the locationIds property.
     *
     * @param value
     *     allowed object is
     *     {@link ArrayOflong }
     *
     */
    public void setLocationIds(ArrayOflong value) {
        this.locationIds = value;
    }

    /**
     * Gets the value of the currencyCode property.
     *
     * @return
     *     possible object is
     *     {@link CurrencyCode }
     *
     */
    public CurrencyCode getCurrencyCode() {
        return currencyCode;
    }

    /**
     * Sets the value of the currencyCode property.
     *
     * @param value
     *     allowed object is
     *     {@link CurrencyCode }
     *
     */
    public void setCurrencyCode(CurrencyCode value) {
        this.currencyCode = value;
    }

    /**
     * Gets the value of the matchTypes property.
     *
     * @return
     *     possible object is
     *     {@link ArrayOfMatchType }
     *
     */
    public ArrayOfMatchType getMatchTypes() {
        return matchTypes;
    }

    /**
     * Sets the value of the matchTypes property.
     *
     * @param value
     *     allowed object is
     *     {@link ArrayOfMatchType }
     *
     */
    public void setMatchTypes(ArrayOfMatchType value) {
        this.matchTypes = value;
    }

    /**
     * Gets the value of the campaignId property.
     *
     * @return
     *     possible object is
     *     {@link Long }
     *
     */
    public Long getCampaignId() {
        return campaignId;
    }

    /**
     * Sets the value of the campaignId property.
     *
     * @param value
     *     allowed object is
     *     {@link Long }
     *
     */
    public void setCampaignId(Long value) {
        this.campaignId = value;
    }

    /**
     * Gets the value of the adGroupId property.
     *
     * @return
     *     possible object is
     *     {@link Long }
     *
     */
    public Long getAdGroupId() {
        return adGroupId;
    }

    /**
     * Sets the value of the adGroupId property.
     *
     * @param value
     *     allowed object is
     *     {@link Long }
     *
     */
    public void setAdGroupId(Long value) {
        this.adGroupId = value;
    }

}


text:
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "..", "lib"))

require "rubygems"
require "test/unit"
require "json"
require "jsonschema"
require 'paypal_adaptive'
require 'active_support/core_ext/string'


text:
#include "id3_parser.h"

#include <vector>

//#define ID3_DEBUG 1

#if !defined ( ID3_DEBUG)
#define ID3_TRACE(...) do {} while (0)
#else
#define ID3_TRACE(...) printf(__VA_ARGS__)
#endif

namespace astreamer {

enum ID3_Parser_State {
    ID3_Parser_State_Initial = 0,
    ID3_Parser_State_Parse_Frames,
    ID3_Parser_State_Tag_Parsed,
    ID3_Parser_State_Not_Valid_Tag
};

/*
 * =======================================
 * Private class
 * =======================================
 */

class ID3_Parser_Private {
public:
    ID3_Parser_Private();
    ~ID3_Parser_Private();

    bool wantData();
    void feedData(UInt8 *data, UInt32 numBytes);
    void setState(ID3_Parser_State state);
    void reset();

    CFStringRef parseContent(UInt32 framesize, UInt32 pos, CFStringEncoding encoding, bool byteOrderMark);

    ID3_Parser *m_parser;
    ID3_Parser_State m_state;
    UInt32 m_bytesReceived;
    UInt32 m_tagSize;
    bool m_hasFooter;
    bool m_usesUnsynchronisation;
    bool m_usesExtendedHeader;
    CFStringRef m_title;
    CFStringRef m_performer;

    std::vector<UInt8> m_tagData;
};

/*
 * =======================================
 * Private class implementation
 * =======================================
 */

ID3_Parser_Private::ID3_Parser_Private() :
    m_parser(0),
    m_state(ID3_Parser_State_Initial),
    m_bytesReceived(0),
    m_tagSize(0),
    m_hasFooter(false),
    m_usesUnsynchronisation(false),
    m_usesExtendedHeader(false),
    m_title(NULL),
    m_performer(NULL)
{
}

ID3_Parser_Private::~ID3_Parser_Private()
{
    if (m_performer) {
        CFRelease(m_performer), m_performer = NULL;
    }
    if (m_title) {
        CFRelease(m_title), m_title = NULL;
    }
}

bool ID3_Parser_Private::wantData()
{
    if (m_state == ID3_Parser_State_Tag_Parsed) {
        return false;
    }
    if (m_state == ID3_Parser_State_Not_Valid_Tag) {
        return false;
    }

    return true;
}

void ID3_Parser_Private::feedData(UInt8 *data, UInt32 numBytes)
{
    if (!wantData()) {
        return;
    }

    m_bytesReceived += numBytes;

    ID3_TRACE("received %i bytes, total bytes %i\n", numBytes, m_bytesReceived);

    for (CFIndex i=0; i < numBytes; i++) {
        m_tagData.push_back(data[i]);
    }

    bool enoughBytesToParse = true;

    while (enoughBytesToParse) {
        switch (m_state) {
            case ID3_Parser_State_Initial: {
                // Do we have enough bytes to determine if this is an ID3 tag or not?
                if (m_bytesReceived <= 9) {
                    enoughBytesToParse = false;
                    break;
                }

                if (!(m_tagData[0] == 'I' &&
                    m_tagData[1] == 'D' &&
                    m_tagData[2] == '3')) {
                    ID3_TRACE("Not an ID3 tag, bailing out\n");

                    // Does not begin with the tag header; not an ID3 tag
                    setState(ID3_Parser_State_Not_Valid_Tag);
                    enoughBytesToParse = false;
                    break;
                }

                UInt8 majorVersion = m_tagData[3];
                // Currently support only id3v2.3
                if (majorVersion != 3) {
                    ID3_TRACE("ID3v2.%i not supported by the parser\n", majorVersion);

                    setState(ID3_Parser_State_Not_Valid_Tag);
                    enoughBytesToParse = false;
                    break;
                }

                // Ignore the revision

                // Parse the flags

                if ((m_tagData[5] & 0x80) != 0) {
                    m_usesUnsynchronisation = true;
                } else if ((m_tagData[5] & 0x40) != 0) {
                    m_usesExtendedHeader = true;
                } else if ((m_tagData[5] & 0x10) != 0) {
                    m_hasFooter = true;
                }

                m_tagSize = (m_tagData[6] << 21) + (m_tagData[7] << 14) + (m_tagData[8] << 7) + m_tagData[9];

                if (m_tagSize > 0) {
                    if (m_hasFooter) {
                        m_tagSize += 10;
                    }
                    m_tagSize += 10;

                    ID3_TRACE("tag size: %i\n", m_tagSize);

                    setState(ID3_Parser_State_Parse_Frames);
                    break;
                }

                setState(ID3_Parser_State_Not_Valid_Tag);
                enoughBytesToParse = false;
                break;
            }

            case ID3_Parser_State_Parse_Frames: {
                // Do we have enough data to parse the frames?
                if (m_tagData.size() < m_tagSize) {
                    ID3_TRACE("Not enough data received for parsing, have %lu bytes, need %i bytes\n",
                              m_tagData.size(),
                              m_tagSize);
                    enoughBytesToParse = false;
                    break;
                }

                UInt32 pos = 10;

                // Do we have an extended header? If we do, skip it
                if (m_usesExtendedHeader) {
                    UInt32 extendedHeaderSize = ((m_tagData[pos] << 21) |
                                                 (m_tagData[pos+1] << 14) |
                                                 (m_tagData[pos+2] << 7) |
                                                 m_tagData[pos+3]);

                    if (pos + extendedHeaderSize >= m_tagSize) {
                        setState(ID3_Parser_State_Not_Valid_Tag);
                        enoughBytesToParse = false;
                        break;
                    }

                    ID3_TRACE("Skipping extended header, size %i\n", extendedHeaderSize);

                    pos += extendedHeaderSize;
                }

                while (pos < m_tagSize) {
                    char frameName[5];
                    frameName[0] = m_tagData[pos];
                    frameName[1] = m_tagData[pos+1];
                    frameName[2] = m_tagData[pos+2];
                    frameName[3] = m_tagData[pos+3];
                    frameName[4] = 0;

                    pos += 4;

                    UInt32 framesize = ((m_tagData[pos] << 21) |
                                        (m_tagData[pos+1] << 14) |
                                        (m_tagData[pos+2] << 7) |
                                        m_tagData[pos+3]);
                    if (framesize == 0) {
                        setState(ID3_Parser_State_Not_Valid_Tag);
                        enoughBytesToParse = false;
                        break;
                    }

                    pos += 6;

                    CFStringEncoding encoding;
                    bool byteOrderMark = false;

                    if (m_tagData[pos] == 3) {
                        encoding = kCFStringEncodingUTF8;
                    } else if (m_tagData[pos] == 2) {
                        encoding = kCFStringEncodingUTF16BE;
                    } else if (m_tagData[pos] == 1) {
                        encoding = kCFStringEncodingUTF16;
                        byteOrderMark = true;
                    } else {
                        // ISO-8859-1 is the default encoding
                        encoding = kCFStringEncodingISOLatin1;
                    }

                    if (!strcmp(frameName, "TIT2")) {
                        if (m_title) {
                            CFRelease(m_title);
                        }
                        m_title = parseContent(framesize, pos + 1, encoding, byteOrderMark);

                        ID3_TRACE("ID3 title parsed: '%s'\n", CFStringGetCStringPtr(m_title, CFStringGetSystemEncoding()));
                    } else if (!strcmp(frameName, "TPE1")) {
                        if (m_performer) {
                            CFRelease(m_performer);
                        }
                        m_performer = parseContent(framesize, pos + 1, encoding, byteOrderMark);

                        ID3_TRACE("ID3 performer parsed: '%s'\n", CFStringGetCStringPtr(m_performer, CFStringGetSystemEncoding()));
                    } else {
                        // Unknown/unhandled frame
                        ID3_TRACE("Unknown/unhandled frame: %s, size %i\n", frameName, framesize);
                    }

                    pos += framesize;
                }

                // Push out the metadata
                if (m_parser->m_delegate) {
                    std::map<CFStringRef,CFStringRef> metadataMap;

                    if (m_performer && CFStringGetLength(m_performer) > 0) {
                        metadataMap[CFSTR("MPMediaItemPropertyArtist")] =
                            CFStringCreateCopy(kCFAllocatorDefault, m_performer);
                    }

                    if (m_title && CFStringGetLength(m_title) > 0) {
                        metadataMap[CFSTR("MPMediaItemPropertyTitle")] =
                            CFStringCreateCopy(kCFAllocatorDefault, m_title);
                    }

                    m_parser->m_delegate->id3metaDataAvailable(metadataMap);
                }

                setState(ID3_Parser_State_Tag_Parsed);
                enoughBytesToParse = false;
                break;
            }

            default:
                enoughBytesToParse = false;
                break;
        }
    }
}

void ID3_Parser_Private::setState(astreamer::ID3_Parser_State state)
{
    m_state = state;
}

void ID3_Parser_Private::reset()
{
    m_state = ID3_Parser_State_Initial;
    m_bytesReceived = 0;
    m_tagSize = 0;
    m_hasFooter = false;
    m_usesUnsynchronisation = false;
    m_usesExtendedHeader = false;

    if (m_title) {
        CFRelease(m_title), m_title = NULL;
    }
    if (m_performer) {
        CFRelease(m_performer), m_performer = NULL;
    }

    m_tagData.clear();
}

CFStringRef ID3_Parser_Private::parseContent(UInt32 framesize, UInt32 pos, CFStringEncoding encoding, bool byteOrderMark)
{
    CFStringRef content = CFStringCreateWithBytes(kCFAllocatorDefault,
                                                  &m_tagData[pos],
                                                  framesize - 1,
                                                  encoding,
                                                  byteOrderMark);

    return content;
}

/*
 * =======================================
 * ID3_Parser implementation
 * =======================================
 */

ID3_Parser::ID3_Parser() :
    m_delegate(0),
    m_private(new ID3_Parser_Private())
{
    m_private->m_parser = this;
}

ID3_Parser::~ID3_Parser()
{
    delete m_private, m_private = 0;
}

void ID3_Parser::reset()
{
    m_private->reset();
}

bool ID3_Parser::wantData()
{
    return m_private->wantData();
}

void ID3_Parser::feedData(UInt8 *data, UInt32 numBytes)
{
    m_private->feedData(data, numBytes);
}

}


text:
package com.nike.cerberus.auth.connector.okta;

import com.google.common.base.Preconditions;
import com.nike.cerberus.auth.connector.AuthConnector;
import com.nike.cerberus.auth.connector.AuthData;
import com.nike.cerberus.auth.connector.AuthMfaDevice;
import com.nike.cerberus.auth.connector.AuthResponse;
import com.nike.cerberus.auth.connector.AuthStatus;
import com.okta.sdk.models.auth.AuthResult;
import com.okta.sdk.models.factors.Factor;
import com.okta.sdk.models.usergroups.UserGroup;
import org.apache.commons.lang3.StringUtils;

import javax.inject.Inject;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Okta version 1 API implementation of the AuthConnector interface.
 */
public class OktaAuthConnector implements AuthConnector {

    private final OktaApiClientHelper oktaApiClientHelper;

    private final OktaClientResponseUtils oktaClientResponseUtils;

    @Inject
    public OktaAuthConnector(final OktaApiClientHelper oktaApiClientHelper,
                             final OktaClientResponseUtils oktaClientResponseUtils) {

        this.oktaApiClientHelper = oktaApiClientHelper;
        this.oktaClientResponseUtils = oktaClientResponseUtils;
    }

    @Override
    public AuthResponse authenticate(String username, String password) {

        final AuthResult authResult = oktaApiClientHelper.authenticateUser(username, password, null);
        final String userId = oktaClientResponseUtils.getUserIdFromAuthResult(authResult);
        final String userLogin = oktaClientResponseUtils.getUserLoginFromAuthResult(authResult);

        final AuthData authData = new AuthData()
                .setUserId(userId)
                .setUsername(userLogin);
        final AuthResponse authResponse = new AuthResponse().setData(authData);

        final List<Factor> factors;
        if (StringUtils.equals(authResult.getStatus(), OktaClientResponseUtils.AUTHENTICATION_MFA_REQUIRED_STATUS) ||
                StringUtils.equals(authResult.getStatus(), OktaClientResponseUtils.AUTHENTICATION_MFA_ENROLL_STATUS)) {

            authData.setStateToken(authResult.getStateToken());
            authResponse.setStatus(AuthStatus.MFA_REQUIRED);

            factors = oktaClientResponseUtils.getUserFactorsFromAuthResult(authResult);
            oktaClientResponseUtils.validateUserFactors(factors);

            factors.forEach(factor -> authData.getDevices().add(new AuthMfaDevice()
                    .setId(factor.getId())
                    .setName(oktaClientResponseUtils.getDeviceName(factor))));
        }
        else {
            authResponse.setStatus(AuthStatus.SUCCESS);
        }

        return authResponse;
    }

    @Override
    public AuthResponse mfaCheck(String stateToken, String deviceId, String otpToken) {

        final AuthResult authResult = oktaApiClientHelper.verifyFactor(deviceId, stateToken, otpToken);
        final String userId = oktaClientResponseUtils.getUserIdFromAuthResult(authResult);
        final String userLogin = oktaClientResponseUtils.getUserLoginFromAuthResult(authResult);

        final AuthData authData = new AuthData()
                .setUserId(userId)
                .setUsername(userLogin);
        final AuthResponse authResponse = new AuthResponse()
                .setData(authData)
                .setStatus(AuthStatus.SUCCESS);

        return authResponse;
    }

    @Override
    public Set<String> getGroups(AuthData authData) {

        Preconditions.checkNotNull(authData, "auth data cannot be null.");

        final List<UserGroup> userGroups = oktaApiClientHelper.getUserGroups(authData.getUserId());

        final Set<String> groups = new HashSet<>();
        if (userGroups.isEmpty()) {
            return groups;
        }

        userGroups.forEach(group -> groups.add(group.getProfile().getName()));

        return groups;
    }

}


text:
    <meta http-equiv="refresh" content="0; url=http://github.com/nickmeessen/" />
    <meta name="author" content="Nick Meessen">

    Redirecting to: Nick Meessen's Github Profile.


text:
package expr

import (
	"strings"
)

type (
	// MappedAttributeExpr is an attribute expression of type object that map the
	// object keys to external names (e.g. HTTP header names).
	MappedAttributeExpr struct {
		*AttributeExpr
		nameMap    map[string]string
		reverseMap map[string]string
	}

	// MappedAttributeWalker is the type of functions given to WalkMappedAttr.
	//
	// name is the name of the attribute
	// elem the name of the corresponding transport element
	// a is the corresponding attribute expression
	//
	MappedAttributeWalker func(name, elem string, a *AttributeExpr) error
)

// NewEmptyMappedAttributeExpr creates an empty mapped attribute expression.
func NewEmptyMappedAttributeExpr() *MappedAttributeExpr {
	return NewMappedAttributeExpr(&AttributeExpr{Type: &Object{}})
}

// NewMappedAttributeExpr instantiates a mapped attribute expression for the
// given attribute. The type of att must be Object.
func NewMappedAttributeExpr(att *AttributeExpr) *MappedAttributeExpr {
	if att == nil {
		return NewEmptyMappedAttributeExpr()
	}
	if !IsObject(att.Type) {
		panic("cannot create a mapped attribute with a non object attribute") // bug
	}
	var (
		nameMap    = make(map[string]string)
		reverseMap = make(map[string]string)
		validation *ValidationExpr
	)
	if att.Validation != nil {
		validation = att.Validation.Dup()
	} else if ut, ok := att.Type.(UserType); ok {
		if val := ut.Attribute().Validation; val != nil {
			validation = val.Dup()
		}
	}
	attr := DupAtt(att)
	attr.Validation = validation
	ma := &MappedAttributeExpr{
		AttributeExpr: attr,
		nameMap:       nameMap,
		reverseMap:    reverseMap,
	}
	ma.Remap()
	return ma
}

// Remap recomputes the name mappings from the inner attribute. Use this if
// the underlying attribute is modified after the mapped attribute has been
// initially created.
func (ma *MappedAttributeExpr) Remap() {
	var (
		n = &Object{}
		o = AsObject(ma.Type)
	)
	for _, nat := range *o {
		elems := strings.Split(nat.Name, ":")
		n.Set(elems[0], nat.Attribute)
		if len(elems) > 1 {
			ma.nameMap[elems[0]] = elems[1]
			ma.reverseMap[elems[1]] = elems[0]
		}
	}

	// Conserve examples defined on user type
	ma.AttributeExpr.UserExamples = ma.ExtractUserExamples()

	ma.Type = n
}

// DupMappedAtt creates a deep copy of ma.
func DupMappedAtt(ma *MappedAttributeExpr) *MappedAttributeExpr {
	nameMap := make(map[string]string, len(ma.nameMap))
	reverseMap := make(map[string]string, len(ma.reverseMap))
	for k, v := range ma.nameMap {
		nameMap[k] = v
	}
	for k, v := range ma.reverseMap {
		reverseMap[k] = v
	}
	return &MappedAttributeExpr{
		AttributeExpr: DupAtt(ma.AttributeExpr),
		nameMap:       nameMap,
		reverseMap:    reverseMap,
	}
}

// WalkMappedAttr iterates over the mapped attributes. It calls the given
// function giving each attribute as it iterates. WalkMappedAttr stops if there
// is no more attribute to iterate over or if the iterator function returns an
// error in which case it returns the error.
func WalkMappedAttr(ma *MappedAttributeExpr, it MappedAttributeWalker) error {
	o := AsObject(ma.Type)
	for _, nat := range *o {
		if err := it(nat.Name, ma.ElemName(nat.Name), nat.Attribute); err != nil {
			return err
		}
	}
	return nil
}

// Map records the element name of one of the child attributes.
// Map panics if attName is not the name of a child attribute.
func (ma *MappedAttributeExpr) Map(elemName, attName string) {
	if att := AsObject(ma.Type).Attribute(attName); att == nil {
		panic(attName + " is not the name of a child of the mapped attribute") // bug
	}
	ma.nameMap[attName] = elemName
	ma.reverseMap[elemName] = attName
}

// Delete removes a child attribute given its name.
func (ma *MappedAttributeExpr) Delete(attName string) {
	delete(ma.nameMap, attName)
	for k, v := range ma.reverseMap {
		if v == attName {
			delete(ma.reverseMap, k)
			break
		}
	}
	ma.Type.(*Object).Delete(attName)
	if ma.Validation != nil {
		ma.Validation.RemoveRequired(attName)
	}
}

// Attribute returns the original attribute using "att:elem" format for the keys.
func (ma *MappedAttributeExpr) Attribute() *AttributeExpr {
	att := DupAtt(ma.AttributeExpr)
	obj := AsObject(att.Type)
	for _, nat := range *obj {
		if elem := ma.ElemName(nat.Name); elem != nat.Name {
			obj.Rename(nat.Name, nat.Name+":"+elem)
		}
	}
	return att
}

// ElemName returns the transport element name of the given object key. It
// returns keyName if it's a key of the mapped attribute object type. It panics
// if there is no mapping and keyName is not a key.
func (ma *MappedAttributeExpr) ElemName(keyName string) string {
	if n, ok := ma.nameMap[keyName]; ok {
		return n
	}
	if att := AsObject(ma.Type).Attribute(keyName); att != nil {
		return keyName
	}
	panic("Key " + keyName + " is not defined") // bug
}

// KeyName returns the object key of the given transport element name. It
// returns elemName if it's a key of the mapped attribute object type. It panics
// if there is no mapping and elemName is not a key.
func (ma *MappedAttributeExpr) KeyName(elemName string) string {
	if n, ok := ma.reverseMap[elemName]; ok {
		return n
	}
	if att := AsObject(ma.Type).Attribute(elemName); att != nil {
		return elemName
	}
	panic("transport element " + elemName + " is not defined and is not a key") // bug
}

// Merge merges other's attributes into a overriding attributes of a with
// attributes of other with identical names.
func (ma *MappedAttributeExpr) Merge(other *MappedAttributeExpr) {
	if other == nil {
		return
	}
	ma.AttributeExpr.Merge(other.Attribute())
	ma.Remap()
}

// FindKey finds the given key in the mapped attribute expression.
// If key is found, it returns the transport element name of the key and true.
// Otherwise, it returns an empty string and false.
func (ma *MappedAttributeExpr) FindKey(keyName string) (string, bool) {
	obj := AsObject(ma.Type)
	for _, nat := range *obj {
		if nat.Name == keyName {
			return ma.ElemName(keyName), true
		}
	}
	return "", false
}

// IsEmpty returns true if the mapped attribute contains no key.
func (ma *MappedAttributeExpr) IsEmpty() bool {
	return len(*ma.Type.(*Object)) == 0
}


text:
module Shipit
  class Task < Record
    include DeferredTouch

    ConcurrentTaskRunning = Class.new(StandardError)

    PRESENCE_CHECK_TIMEOUT = 30
    ACTIVE_STATUSES = %w(pending running aborting).freeze
    COMPLETED_STATUSES = %w(success flapping faulty validating).freeze
    UNSUCCESSFUL_STATUSES = %w(error failed aborted flapping timedout faulty).freeze
    OUTPUT_SIZE_LIMIT = 16.megabytes # A MySQL mediumblob
    HUMAN_READABLE_OUTPUT_LIMIT = ActionController::Base.helpers.number_to_human_size(OUTPUT_SIZE_LIMIT)
    OUTPUT_TRUNCATED_MESSAGE = "Output exceeded the limit of #{HUMAN_READABLE_OUTPUT_LIMIT} and was truncated\n"

    attr_accessor :pid

    belongs_to :deploy, foreign_key: :parent_id, required: false, inverse_of: false # required for fixtures

    belongs_to :user, optional: true
    belongs_to :aborted_by, class_name: 'User', optional: true
    belongs_to :stack, counter_cache: true
    belongs_to :until_commit, class_name: 'Commit', required: false
    belongs_to :since_commit, class_name: 'Commit', required: false

    belongs_to :rollback_once_aborted_to, class_name: 'Task', optional: true

    deferred_touch stack: :updated_at

    module EnvHash
      class << self
        def dump(hash)
          raise TypeError, "Task#env should be a Hash[String => String]" unless hash.is_a?(Hash)
          hash = hash.to_h.stringify_keys
          hash.transform_values! do |value|
            case value
            when String, Symbol, Numeric
              value.to_s
            else
              raise TypeError, "Task#env should be a Hash[String => String]" unless hash.is_a?(Hash)
            end
          end

          hash unless hash.empty?
        end

        def load(hash)
          hash&.to_h || {} # cast back to a real hash
        end

        def new
          nil
        end
      end
    end

    serialize :definition, TaskDefinition
    serialize :env, Shipit.serialized_column(:env, coder: EnvHash)

    scope :success, -> { where(status: 'success') }
    scope :completed, -> { where(status: COMPLETED_STATUSES) }
    scope :active, -> { where(status: ACTIVE_STATUSES) }
    scope :not_active, -> { where(status: COMPLETED_STATUSES + UNSUCCESSFUL_STATUSES) }
    scope :exclusive, -> { where(allow_concurrency: false) }
    scope :unsuccessful, -> { where(status: UNSUCCESSFUL_STATUSES) }
    scope :last_seven_days, -> { where("created_at > ?", 7.days.ago) }
    scope :previous_seven_days, -> { where(created_at: 14.days.ago..7.days.ago) }

    scope :due_for_rollup, -> { not_active.where(rolled_up: false).where('created_at <= ?', 1.hour.ago) }

    after_save :record_status_change
    after_create :prevent_concurrency, unless: :allow_concurrency?
    after_commit :emit_hooks, on: :create
    after_commit :emit_hooks_if_status_changed, on: :update

    class << self
      def durations
        pluck(:started_at, :ended_at).select { |s, e| s && e }.map { |s, e| e - s }
      end

      def last_completed
        completed.last
      end

      def last_successful
        success.last
      end

      def current
        active.exclusive.last
      end
    end

    state_machine :status, initial: :pending do
      before_transition any => :running do |task|
        task.started_at ||= Time.now.utc
      end

      before_transition running: any do |task|
        task.ended_at ||= Time.now.utc
      end

      after_transition any => %i(success failed error timedout) do |task|
        task.async_refresh_deployed_revision
      end

      after_transition any => %i(aborted success failed error timedout) do |task|
        task.schedule_rollup_chunks
      end

      after_transition any => :flapping do |task|
        task.update!(confirmations: 0)
      end

      after_transition any => :success do |task|
        task.async_update_estimated_deploy_duration
      end

      after_transition any => %i(failed error timedout) do |task|
        task.retry_if_necessary
      end

      event :run do
        transition pending: :running
      end

      event :failure do
        transition %i(running flapping) => :failed
      end

      event :complete do
        transition %i(running flapping validating faulty) => :success
      end

      event :enter_validation do
        transition %i(running flapping) => :validating
      end

      event :mark_faulty do
        transition %i(validating success) => :faulty
      end

      event :error do
        transition all => :error
      end

      event :giveup do # :timeout would cause a name clash
        transition all => :timedout
      end

      event :aborting do
        transition all - %i(aborted) => :aborting
      end

      event :aborted do
        transition aborting: :aborted
      end

      event :flap do
        transition %i(failed error timedout success) => :flapping
      end

      state :pending
      state :running
      state :validating
      state :faulty
      state :failed
      state :success
      state :error
      state :timedout
      state :aborting
      state :aborted
      state :flapping
    end

    def active?
      status.in?(ACTIVE_STATUSES)
    end

    def report_complete!
      complete!
    end

    def report_failure!(error)
      reload
      if aborting?
        aborted!
      elsif error.respond_to?(:exit_code) && Shipit.timeout_exit_codes.include?(error.exit_code)
        giveup!
      else
        failure!
      end
    end

    def report_timeout!(_error)
      giveup!
    end

    def report_error!(error)
      write("#{error.class}: #{error.message}\n\t#{error.backtrace.join("\n\t")}\n")
      error!
    end

    delegate :acquire_git_cache_lock, :async_refresh_deployed_revision, :async_update_estimated_deploy_duration,
      to: :stack

    delegate :checklist, to: :definition

    def duration?
      started_at? && ended_at?
    end

    def duration
      Duration.new(ended_at - started_at) if duration?
    end

    def spec
      @spec ||= DeploySpec::FileSystem.new(working_directory, stack.environment)
    end

    def enqueue
      raise "only persisted jobs can be enqueued" unless persisted?
      PerformTaskJob.perform_later(self)
    end

    def run_now!
      raise "only persisted jobs can be run" unless persisted?
      PerformTaskJob.perform_now(self)
    end

    def write(text)
      log_output(text)
      Shipit.redis.append(output_key, text)
    end

    def chunk_output
      if rolled_up?
        output
      else
        blob = Shipit.redis.get(output_key)

        if blob && blob.size > OUTPUT_SIZE_LIMIT
          Rails.logger.warn("Task #{id} output exceeds limit of #{HUMAN_READABLE_OUTPUT_LIMIT}, and will be truncated.")
          blob = blob.last(OUTPUT_SIZE_LIMIT - OUTPUT_TRUNCATED_MESSAGE.size)
          blob = OUTPUT_TRUNCATED_MESSAGE + blob
        end

        blob
      end
    end

    def chunk_output_size
      return 0 if rolled_up?

      Shipit.redis.strlen(output_key)
    end

    def tail_output(range_start)
      Shipit.redis.getrange(output_key, range_start || 0, -1)
    end

    def schedule_rollup_chunks
      ChunkRollupJob.perform_later(self)
    end

    def rollup_chunks
      ActiveRecord::Base.transaction do
        chunks = Shipit::OutputChunk.where(task: self).pluck(:text)
        chunks << chunk_output
        self.output = chunks.join("\n")

        update_attribute(:rolled_up, true)

        Shipit.redis.del(output_key)
        Shipit::OutputChunk.where(task: self).delete_all
      end
    end

    def output
      gzip = self[:gzip_output]

      if gzip.blank?
        ''
      else
        ActiveSupport::Gzip.decompress(gzip)
      end
    end

    def output=(string)
      self[:gzip_output] = ActiveSupport::Gzip.compress(string)
    end

    def rollback?
      false
    end

    def rollbackable?
      false
    end

    def supports_rollback?
      false
    end

    def title
      definition.render_title(env)
    end

    def author
      user || AnonymousUser.new
    end

    def author=(user)
      super(user.presence)
    end

    def finished?
      !pending? && !running? && !aborting?
    end

    def ping
      Shipit.redis.set(status_key, 'alive', ex: PRESENCE_CHECK_TIMEOUT)
    end

    def alive?
      Shipit.redis.get(status_key) == 'alive'
    end

    def report_dead!
      write("ERROR: Background job hasn't reported back in #{PRESENCE_CHECK_TIMEOUT} seconds.")
      error!
    end

    def should_abort?
      @last_abort_count ||= 1
      (@last_abort_count..Shipit.redis.get(abort_key).to_i).each do |count|
        @last_abort_count = count + 1
        yield count
      end
    end

    def request_abort
      Shipit.redis.pipelined do |pipeline|
        pipeline.incr(abort_key)
        pipeline.expire(abort_key, 1.month.to_i)
      end
    end

    def abort!(rollback_once_aborted: false, rollback_once_aborted_to: nil, aborted_by:)
      update!(
        rollback_once_aborted: rollback_once_aborted,
        rollback_once_aborted_to: rollback_once_aborted_to,
        aborted_by_id: aborted_by.id
      )

      if alive?
        aborting
        request_abort
      elsif aborting? || aborted?
        aborted
      elsif !finished?
        report_dead!
      end
    end

    def working_directory
      File.join(stack.deploys_path, id.to_s)
    end

    if Rails.gem_version >= Gem::Version.new('5.1.0.beta1')
      def record_status_change
        @status_changed ||= saved_change_to_attribute?(:status)
      end
    else
      def record_status_change
        @status_changed ||= status_changed?
      end
    end

    def emit_hooks_if_status_changed
      return unless @status_changed
      @status_changed = nil
      emit_hooks
    end

    def emit_hooks
      Hook.emit(hook_event, stack, hook_event => self, status: status, stack: stack)
    end

    def hook_event
      self.class.name.demodulize.underscore.to_sym
    end

    def permalink
      Shipit::Engine.routes.url_helpers.stack_task_url(stack, self)
    end

    def commit_to_rollback_to
      previous_deployed_commit = stack.previous_successful_deploy_commit(id)

      if previous_deployed_commit == Shipit::Stack::NoDeployedCommit
        since_commit
      else
        previous_deployed_commit
      end
    end

    def commit_range?
      since_commit && until_commit
    end

    def includes_commit?(commit)
      return false unless commit_range?

      if since_commit == until_commit
        commit.id == since_commit.id
      else
        commit.id > since_commit.id && commit.id <= until_commit.id
      end
    end

    def self.recently_created_at
      5.minutes.ago
    end

    ZOMBIE_STATES = %w(running aborting).freeze
    private_constant :ZOMBIE_STATES
    def self.zombies
      where(status: ZOMBIE_STATES)
        .where(
          "created_at <= :recently",
          recently: recently_created_at,
        )
        .reject(&:alive?)
    end

    def retry_if_necessary
      return unless retries_configured? && !stack.reload.locked?

      if retry_attempt < max_retries
        retry_task = duplicate_task
        retry_task.retry_attempt = duplicate_task.retry_attempt + 1
        retry_task.save!

        retry_task.enqueue
      end
    end

    def retries_configured?
      !max_retries.nil? && max_retries > 0
    end

    private

    def prevent_concurrency
      raise ConcurrentTaskRunning if stack.tasks.active.exclusive.count > 1
    end

    def output_key
      "#{status_key}:output"
    end

    def status_key
      "shipit:task:#{id}"
    end

    def abort_key
      "#{status_key}:aborting"
    end

    def log_output(text)
      output_line_buffer.buffer(text) do |line|
        Shipit.task_logger.info("[#{stack.repo_name}##{id}] #{line}")
      end
    end

    def output_line_buffer
      @output_line_buffer ||= LineBuffer.new
    end

    def duplicate_task
      copy_task = dup
      copy_task.status = 'pending'
      copy_task.started_at = nil
      copy_task.ended_at = nil
      copy_task
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <groupId>edu.bu.android_mitm</groupId>
  <artifactId>soot-infoflow</artifactId>
  <versioning>
    <release>1.0-16062015</release>
    <versions>
      <version>1.0-16062015</version>
    </versions>
    <lastUpdated>20151115201852</lastUpdated>
  </versioning>
</metadata>


text:
package io.gpm.viadisable.listeners;

import io.gpm.viadisable.ViaDisable;
import io.gpm.viadisable.impl.PotionConsumeEvent;
import io.gpm.viadisable.utils.ConfigMessageHandler;
import org.bukkit.entity.Player;
import org.bukkit.entity.ShulkerBullet;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.inventory.ItemStack;

/***
 * @author George
 * @since 29-Oct-17
 */
public class CancelEffects implements Listener {

    @EventHandler(priority = EventPriority.LOW)
    public void onLevitate(EntityDamageByEntityEvent event){
        if(ViaDisable.instance.getConfig().getBoolean("cancel-levitate",true)){
            if(event.getEntity() instanceof Player && event.getDamager() instanceof ShulkerBullet){
                event.setCancelled(true);
            }
        }
    }

    @EventHandler(priority = EventPriority.NORMAL)
    public void potionConsume(PotionConsumeEvent event){

        ItemStack item = event.getPlayer().getInventory().getItemInMainHand();
        if(ViaDisable.instance.getConfig().getBoolean("cancel-1.9-potions", true)) {
            if (item.getItemMeta().getDisplayName().toUpperCase().contains("LINGERING")
                    || item.getItemMeta().getDisplayName().toUpperCase().contains("LEAP")) {
                event.setCancelled(true);
                item.setAmount(0);
                ConfigMessageHandler.sendToPlayer(event.getPlayer());
            }
        }
    }
}


text:
// The MIT License (MIT)
//
// CoreTweet - A .NET Twitter Library supporting Twitter API 1.1
// Copyright (c) 2013-2015 CoreTweet Development Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#if !NET35
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

#if WIN_RT
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.Web.Http;
using Windows.Web.Http.Filters;
using Windows.Web.Http.Headers;
#endif

#if PCL
using System.Net.Http;
using System.Net.Http.Headers;
#endif

namespace CoreTweet
{
    /// <summary>
    /// Represents an asynchronous response.
    /// </summary>
    public class AsyncResponse : IDisposable
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="AsyncResponse"/> class with a specified source.
        /// </summary>
        /// <param name="source"></param>
#if WIN_RT
        public AsyncResponse(HttpResponseMessage source)
#elif PCL
        internal AsyncResponse(HttpResponseMessage source)
#else
        public AsyncResponse(HttpWebResponse source)
#endif
        {
            this.Source = source;
            this.StatusCode = (int)source.StatusCode;
#if WIN_RT
            this.Headers = source.Headers;
#elif PCL
            this.Headers = source.Headers.ToDictionary(x => x.Key, x => x.Value.FirstOrDefault());
#else
            this.Headers = source.Headers.AllKeys.ToDictionary(k => k.ToLowerInvariant(), k => source.Headers[k]);
#endif
        }

        /// <summary>
        /// Gets the source of the response.
        /// </summary>
#if WIN_RT
        public HttpResponseMessage Source { get; }
#elif PCL
        internal HttpResponseMessage Source { get; }
#else
        public HttpWebResponse Source { get; }
#endif

        /// <summary>
        /// Gets the status code of the response.
        /// </summary>
        public int StatusCode { get; }

        /// <summary>
        /// Gets the headers of the response.
        /// </summary>
        public IDictionary<string, string> Headers { get; }

        /// <summary>
        /// Gets the stream that is used to read the body of the response from the server as an asynchronous operation.
        /// </summary>
        /// <returns>
        /// <para>The task object representing the asynchronous operation.</para>
        /// <para>The Result property on the task object returns the <see cref="System.IO.Stream"/> containing the body of the response.</para>
        /// </returns>
        public
#if WIN_RT
        async
#endif
        Task<Stream> GetResponseStreamAsync()
        {
#if WIN_RT
            return (await this.Source.Content.ReadAsInputStreamAsync()).AsStreamForRead(0);
#elif PCL
            return this.Source.Content.ReadAsStreamAsync();
#else
            var t = new TaskCompletionSource<Stream>();
            try
            {
                t.SetResult(this.Source.GetResponseStream());
            }
            catch(Exception ex)
            {
                t.TrySetException(ex);
            }
            return t.Task;
#endif
        }

        /// <summary>
        /// Closes the stream and releases all the resources.
        /// </summary>
        protected virtual void Dispose(bool disposing)
        {
            if(disposing)
            {
#if PCL || WIN_RT
                this.Source?.Dispose();
#else
                this.Source?.Close();
#endif
            }
        }

        /// <summary>
        /// Closes the stream and releases all the resources.
        /// </summary>
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }
    }

    partial class Request
    {
#if !(PCL || WIN_RT)
        private static void DelayAction(int timeout, CancellationToken cancellationToken, Action action)
        {
            if(timeout == Timeout.Infinite) return;

#if !NET40
            Task.Delay(timeout, cancellationToken).ContinueWith(_ => action(), cancellationToken);
#else
            var reg = default(CancellationTokenRegistration);
            var timer = new Timer(
                _ =>
                {
                    reg.Dispose();
                    action();
                },
                null, timeout, Timeout.Infinite
            );
            reg = cancellationToken.Register(timer.Dispose);
#endif
        }
#endif

#if WIN_RT || PCL
        private static async Task<AsyncResponse> ExecuteRequest(HttpRequestMessage req, string authorizationHeader, ConnectionOptions options, CancellationToken cancellationToken)
        {
            var splitAuth = authorizationHeader.Split(new[] { ' ' }, 2);
#if WIN_RT
            req.Headers.Add("User-Agent", options.UserAgent);
            req.Headers.Expect.Clear();
            req.Headers.Authorization = new HttpCredentialsHeaderValue(splitAuth[0], splitAuth[1]);
            if(options.DisableKeepAlive)
            {
                req.Headers.Connection.Clear();
                req.Headers.Connection.Add(new HttpConnectionOptionHeaderValue("close"));
            }
            options.BeforeRequestAction?.Invoke(req);
            var handler = new HttpBaseProtocolFilter();
            handler.AutomaticDecompression = options.UseCompression;
            var cancellation = new CancellationTokenSource();
            cancellationToken.Register(cancellation.Cancel);
            cancellation.CancelAfter(options.Timeout);
            var client = new HttpClient(handler);
            var task = client.SendRequestAsync(req, HttpCompletionOption.ResponseHeadersRead).AsTask(cancellation.Token);
            return new AsyncResponse(await task.ConfigureAwait(false));
#else
            req.Headers.TryAddWithoutValidation("User-Agent", options.UserAgent);
            req.Headers.ExpectContinue = false;
            req.Headers.Authorization = new AuthenticationHeaderValue(splitAuth[0], splitAuth[1]);
            req.Headers.ConnectionClose = options.DisableKeepAlive;
            var handler = new HttpClientHandler();
            if(options.UseCompression)
                handler.AutomaticDecompression = CompressionType;
            var client = new HttpClient(handler) { Timeout = new TimeSpan(TimeSpan.TicksPerMillisecond * options.Timeout) };
            return new AsyncResponse(await client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false));
#endif
        }
#endif

        /// <summary>
        /// Sends a GET request as an asynchronous operation.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="authorizationHeader">The OAuth header.</param>
        /// <param name="options">The connection options for the request.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// <para>The task object representing the asynchronous operation.</para>
        /// <para>The Result property on the task object returns the response.</para>
        /// </returns>
        internal static Task<AsyncResponse> HttpGetAsync(Uri url, string authorizationHeader, ConnectionOptions options, CancellationToken cancellationToken)
        {
            if(options == null) options = new ConnectionOptions();

#if WIN_RT || PCL
            var req = new HttpRequestMessage(HttpMethod.Get, url);
            return ExecuteRequest(req, authorizationHeader, options, cancellationToken);
#else
            var task = new TaskCompletionSource<AsyncResponse>();
            if(cancellationToken.IsCancellationRequested)
            {
                task.TrySetCanceled();
                return task.Task;
            }

            try
            {
                var req = (HttpWebRequest)WebRequest.Create(url);

                var reg = cancellationToken.Register(() =>
                {
                    task.TrySetCanceled();
                    req.Abort();
                });

#if !WP
                req.ReadWriteTimeout = options.ReadWriteTimeout;
                req.Proxy = options.Proxy;
                if(options.UseCompression)
                    req.AutomaticDecompression = CompressionType;
                if (options.DisableKeepAlive)
                    req.KeepAlive = false;
#endif
                req.Headers[HttpRequestHeader.Authorization] = authorizationHeader;
                req.UserAgent = options.UserAgent;
                options.BeforeRequestAction?.Invoke(req);

                var result = req.BeginGetResponse(ar =>
                {
                    reg.Dispose();
                    try
                    {
                        task.TrySetResult(new AsyncResponse((HttpWebResponse)req.EndGetResponse(ar)));
                    }
                    catch(Exception ex)
                    {
                        task.TrySetException(ex);
                    }
                }, null);

                ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, (_, timeout) =>
                {
                    if (!timeout) return;
                    task.TrySetCanceled();
                    req.Abort();
                }, null, options.Timeout, true);
            }
            catch(Exception ex)
            {
                task.TrySetException(ex);
            }

            return task.Task;
#endif
        }

        /// <summary>
        /// Sends a POST request as an asynchronous operation.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="prm">The parameters.</param>
        /// <param name="authorizationHeader">The OAuth header.</param>
        /// <param name="options">The connection options for the request.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// <para>The task object representing the asynchronous operation.</para>
        /// <para>The Result property on the task object returns the response.</para>
        /// </returns>
        internal static Task<AsyncResponse> HttpPostAsync(Uri url, IEnumerable<KeyValuePair<string, object>> prm, string authorizationHeader, ConnectionOptions options, CancellationToken cancellationToken)
        {
            if(options == null) options = new ConnectionOptions();
            if(prm == null) prm = new Dictionary<string, object>();

#if WIN_RT || PCL
            var req = new HttpRequestMessage(HttpMethod.Post, url);
            req.Content =
#if WIN_RT
                new HttpFormUrlEncodedContent(
#else
                new FormUrlEncodedContent(
#endif
                    prm.Select(kvp => new KeyValuePair<string, string>(kvp.Key, kvp.Value.ToString()))
                );
            return ExecuteRequest(req, authorizationHeader, options, cancellationToken);
#else
            var task = new TaskCompletionSource<AsyncResponse>();
            if(cancellationToken.IsCancellationRequested)
            {
                task.TrySetCanceled();
                return task.Task;
            }

            try
            {
                var req = (HttpWebRequest)WebRequest.Create(url);

                var reg = cancellationToken.Register(() =>
                {
                    task.TrySetCanceled();
                    req.Abort();
                });

                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.Headers[HttpRequestHeader.Authorization] = authorizationHeader;
#if !WP
                req.ServicePoint.Expect100Continue = false;
                req.ReadWriteTimeout = options.ReadWriteTimeout;
                req.Proxy = options.Proxy;
                if(options.UseCompression)
                    req.AutomaticDecompression = CompressionType;
                if (options.DisableKeepAlive)
                    req.KeepAlive = false;
#endif
                req.UserAgent = options.UserAgent;
                options.BeforeRequestAction?.Invoke(req);

                var timeoutCancellation = new CancellationTokenSource();
                DelayAction(options.Timeout, timeoutCancellation.Token, () =>
                {
                    task.TrySetCanceled();
                    req.Abort();
                });
                req.BeginGetRequestStream(reqStrAr =>
                {
                    try
                    {
                        var data = Encoding.UTF8.GetBytes(CreateQueryString(prm));
                        using(var stream = req.EndGetRequestStream(reqStrAr))
                            stream.Write(data, 0, data.Length);

                        req.BeginGetResponse(resAr =>
                        {
                            timeoutCancellation.Cancel();
                            reg.Dispose();
                            try
                            {
                                task.TrySetResult(new AsyncResponse((HttpWebResponse)req.EndGetResponse(resAr)));
                            }
                            catch(Exception ex)
                            {
                                task.TrySetException(ex);
                            }
                        }, null);
                    }
                    catch(Exception ex)
                    {
                        task.TrySetException(ex);
                    }
                }, null);
            }
            catch(Exception ex)
            {
                task.TrySetException(ex);
            }

            return task.Task;
#endif
        }

        /// <summary>
        /// Sends a POST request with multipart/form-data as an asynchronous operation.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="prm">The parameters.</param>
        /// <param name="authorizationHeader">The OAuth header.</param>
        /// <param name="options">The connection options for the request.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// <para>The task object representing the asynchronous operation.</para>
        /// <para>The Result property on the task object returns the response.</para>
        /// </returns>
        internal static
#if WIN_RT
        async
#endif
        Task<AsyncResponse> HttpPostWithMultipartFormDataAsync(Uri url, IEnumerable<KeyValuePair<string, object>> prm, string authorizationHeader, ConnectionOptions options, CancellationToken cancellationToken)
        {
            if(options == null) options = new ConnectionOptions();

#if WIN_RT || PCL
            var req = new HttpRequestMessage(HttpMethod.Post, url);
#endif
#if WIN_RT
            var content = new HttpMultipartFormDataContent();
            foreach(var x in prm)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var valueStream = x.Value as Stream;
                var valueInputStream = x.Value as IInputStream;
                var valueBytes = x.Value as IEnumerable<byte>;
                var valueBuffer = x.Value as IBuffer;
                var valueInputStreamReference = x.Value as IInputStreamReference;
                var valueStorageItem = x.Value as IStorageItem;

                if(valueInputStreamReference != null)
                    valueInputStream = await valueInputStreamReference.OpenSequentialReadAsync();

                if(valueStream != null)
                    valueInputStream = valueStream.AsInputStream();
                if(valueBytes != null)
                {
                    var valueByteArray = valueBytes as byte[] ?? valueBytes.ToArray();
                    valueBuffer = valueByteArray.AsBuffer();
                }

                if(valueInputStream != null)
                    content.Add(new HttpStreamContent(valueInputStream), x.Key, valueStorageItem?.Name ?? "file");
                else if(valueBuffer != null)
                    content.Add(new HttpBufferContent(valueBuffer), x.Key, valueStorageItem?.Name ?? "file");
                else
                    content.Add(new HttpStringContent(x.Value.ToString()), x.Key);
            }
            cancellationToken.ThrowIfCancellationRequested();
            req.Content = content;
            return await ExecuteRequest(req, authorizationHeader, options, cancellationToken).ConfigureAwait(false);
#elif PCL
            var content = new MultipartFormDataContent();
            foreach (var x in prm)
            {
                var valueStream = x.Value as Stream;
                var valueBytes = x.Value as IEnumerable<byte>;

                if(valueStream != null)
                    content.Add(new StreamContent(valueStream), x.Key, "file");
                else if(valueBytes != null)
                    content.Add(new ByteArrayContent(valueBytes as byte[] ?? valueBytes.ToArray()), x.Key, "file");
                else
                    content.Add(new StringContent(x.Value.ToString()), x.Key);
            }
            req.Content = content;
            return ExecuteRequest(req, authorizationHeader, options, cancellationToken);
#else
            var task = new TaskCompletionSource<AsyncResponse>();
            if(cancellationToken.IsCancellationRequested)
            {
                task.TrySetCanceled();
                return task.Task;
            }

            try
            {
                var boundary = Guid.NewGuid().ToString();
                var req = (HttpWebRequest)WebRequest.Create(url);

                var reg = cancellationToken.Register(() =>
                {
                    task.TrySetCanceled();
                    req.Abort();
                });

                req.Method = "POST";
#if !WP
                req.ServicePoint.Expect100Continue = false;
                req.ReadWriteTimeout = options.ReadWriteTimeout;
                req.Proxy = options.Proxy;
                req.SendChunked = true;
                if(options.UseCompression)
                    req.AutomaticDecompression = CompressionType;
                if (options.DisableKeepAlive)
                    req.KeepAlive = false;
#endif
                req.UserAgent = options.UserAgent;
                req.ContentType = "multipart/form-data;boundary=" + boundary;
                req.Headers[HttpRequestHeader.Authorization] = authorizationHeader;
                options.BeforeRequestAction?.Invoke(req);

                var timeoutCancellation = new CancellationTokenSource();
                DelayAction(options.Timeout, timeoutCancellation.Token, () =>
                {
                    task.TrySetCanceled();
                    req.Abort();
                });
                req.BeginGetRequestStream(reqStrAr =>
                {
                    try
                    {
                        using(var stream = req.EndGetRequestStream(reqStrAr))
                            WriteMultipartFormData(stream, boundary, prm);

                        req.BeginGetResponse(resAr =>
                        {
                            timeoutCancellation.Cancel();
                            reg.Dispose();
                            try
                            {
                                task.TrySetResult(new AsyncResponse((HttpWebResponse)req.EndGetResponse(resAr)));
                            }
                            catch(Exception ex)
                            {
                                task.TrySetException(ex);
                            }
                        }, null);
                    }
                    catch(Exception ex)
                    {
                        task.TrySetException(ex);
                    }
                }, null);
            }
            catch(Exception ex)
            {
                task.TrySetException(ex);
            }

            return task.Task;
#endif
        }
    }
}
#endif


text:
<?php

namespace Admin\Controllers;

use Admin\Classes\AdminController;
use Admin\Facades\AdminMenu;
use Admin\Models\Menu_options_model;
use Igniter\Flame\Exception\ApplicationException;

class Menus extends AdminController
{
    public $implement = [
        'Admin\Actions\ListController',
        'Admin\Actions\FormController',
        'Admin\Actions\LocationAwareController',
    ];

    public $listConfig = [
        'list' => [
            'model' => 'Admin\Models\Menus_model',
            'title' => 'lang:admin::lang.menus.text_title',
            'emptyMessage' => 'lang:admin::lang.menus.text_empty',
            'defaultSort' => ['menu_id', 'DESC'],
            'configFile' => 'menus_model',
        ],
    ];

    public $formConfig = [
        'name' => 'lang:admin::lang.menus.text_form_name',
        'model' => 'Admin\Models\Menus_model',
        'request' => 'Admin\Requests\Menu',
        'create' => [
            'title' => 'lang:admin::lang.form.create_title',
            'redirect' => 'menus/edit/{menu_id}',
            'redirectClose' => 'menus',
            'redirectNew' => 'menus/create',
        ],
        'edit' => [
            'title' => 'lang:admin::lang.form.edit_title',
            'redirect' => 'menus/edit/{menu_id}',
            'redirectClose' => 'menus',
            'redirectNew' => 'menus/create',
        ],
        'preview' => [
            'title' => 'lang:admin::lang.form.preview_title',
            'redirect' => 'menus',
        ],
        'delete' => [
            'redirect' => 'menus',
        ],
        'configFile' => 'menus_model',
    ];

    protected $requiredPermissions = 'Admin.Menus';

    public function __construct()
    {
        parent::__construct();

        AdminMenu::setContext('menus', 'restaurant');
    }

    public function edit_onChooseMenuOption($context, $recordId)
    {
        $menuOptionId = post('Menu._options');
        if (!$menuOption = Menu_options_model::find($menuOptionId))
            throw new ApplicationException(lang('admin::lang.menus.alert_menu_option_not_attached'));

        $model = $this->asExtension('FormController')->formFindModelObject($recordId);

        $menuOption->attachToMenu($model);

        $model->reload();
        $this->asExtension('FormController')->initForm($model, $context);

        flash()->success(sprintf(lang('admin::lang.alert_success'), 'Menu item option attached'))->now();

        $formField = $this->widgets['form']->getField('menu_options');

        return [
            '#notification' => $this->makePartial('flash'),
            '#'.$formField->getId('group') => $this->widgets['form']->renderField($formField, [
                'useContainer' => false,
            ]),
        ];
    }
}


text:
<?php
class Page_model extends CI_Model
{
    function __construct()
    {
        parent::__construct();
        $this->table = 'pages';
    }

    // Get list of pages
    public function get_list()
    {
        $query = $this->db->get($this->table);
        return $query->result();
    }

    // Get single page
    public function get($id)
    {
        $this->db->where('id',$id);
        $query =  $this->db->get($this->table);
        return $query->row();
    }

    // Add single page
    public function add($data)
    {
        $this->db->insert($this->table,$data);
        return true;
    }

    // Update single page
    public function update($id,$data)
    {
        $this->db->where('id',$id);
        $this->db->update($this->table,$data);
        return true;
    }

    // Delete single page
    public function delete_page($id)
    {
        $this->db->where('id',$id);
        $this->db->delete($this->table);
        return true;
    }

    public function get_featured()
    {
        $this->db->select('*');
        $this->db->from($this->table);
        $this->db->where('is_featured', 1);
        $this->db->where('is_published', 1);

        $query = $this->db->get();
        if($query->num_rows() >= 1)
        {
            return $query->result();
        } else {
            return false;
        }
    }

    // Get pages for the menu
    public function get_menu_pages()
    {
        $this->db->select('*');
        $this->db->from($this->table);
        $this->db->where('in_menu', 1);
        $this->db->where('is_published', 1);
        $this->db->order_by('order_menu', 'ASC');

        $query = $this->db->get();

        return $query->result();
    }

    // Get page by slug
    public function get_by_slug($slug)
    {
        $this->db->where('slug',$slug);
        $this->db->where('is_published', 1);
        $this->db->limit(1);
        $query = $this->db->get($this->table);

        return $query->row();
    }

}


text:
class Users::RegistrationsController < Devise::RegistrationsController
# before_filter :configure_sign_up_params, only: [:create]
# before_filter :configure_account_update_params, only: [:update]

  before_filter :check_permissions, :only => [ :new, :create, :cancel ]
  skip_before_filter :require_no_authentication

  def check_permissions
    authorize! :create, resource
  end

  # GET /resource/sign_up
  def new
    build_resource({})
    self.resource.membro = Membro.new
    respond_with self.resource
  end

  # POST /resource
  # def create
  #    super
  # end

  # GET /resource/edit
  # def edit
  #   super
  # end

  # PUT /resource
  # def update
  #   super
  # end

  # DELETE /resource
  # def destroy
  #   super
  # end

  # GET /resource/cancel
  # Forces the session data which is usually expired after sign
  # in to be expired now. This is useful if the user wants to
  # cancel oauth signing in/up in the middle of the process,
  # removing all OAuth session data.
  # def cancel
  #   super
  # end

  protected

  # You can put the params you want to permit in the empty array.
  def configure_sign_up_params
    devise_parameter_sanitizer.for(:sign_up) << :role
  end

  # You can put the params you want to permit in the empty array.
  # def configure_account_update_params
  #   devise_parameter_sanitizer.for(:account_update) << :attribute
  # end

  # The path used after sign up.
  def after_sign_up_path_for(resource)
    return url_for(:controller => parse_role(resource), :action => 'new', :user_id => resource.id)
  end

  def sign_up(resource_name, resource)
    true
  end

  # The path used after sign up for inactive accounts.
  # def after_inactive_sign_up_path_for(resource)
  #   super(resource)
  # end

  def parse_role(resource)
    role_name = resource.role_ids[0]
    return '/' + I18n.transliterate(Role.find(resource.role_ids[0]).name) + 's'
  end

end


text:
package ro.nextreports.server.exception;

/**
 * Created by IntelliJ IDEA.
 * User: mihai.panaitescu
 * Date: Feb 14, 2008
 * Time: 10:54:35 AM
 */
public class ReportEngineException extends Exception {

    public ReportEngineException() {
        super();
    }

    public ReportEngineException(String message, Throwable cause) {
        super(message, cause);
    }

    public ReportEngineException(String message) {
        super(message);
    }

    public ReportEngineException(Throwable cause) {
        super(cause);
    }

}


text:
const net   = require('net'),
      utils = require('./utils');

var client, callbacks, lines;

function _connect_to_host(host, port, timeout, callback) {
    var started_time = new Date().getTime();

    client = net.connect({ host:host, port:port }, function() {
         callback();
    });

    client.on('error', function(error) {
        timeout = Math.max(timeout - (new Date().getTime() - started_time), 0);

        if (timeout > 0) {
            setTimeout(function() {
                _connect_to_host(host, port, timeout - 100, callback);
            }, 100);
        } else {
            console.log("ERROR: Failed to establish connection!");
        }
    });
};

module.exports = {
    ready: function(host, port, timeout) {
        return new Promise(function(resolve, reject) {
            _connect_to_host(host, port, timeout, function() {
                resolve();
            });
        });
    },

    open: function() {
        return new Promise(function(resolve, reject) {
            callbacks = new Array();
            lines = '';

            callbacks.push(resolve);

            client.on('data', function(data) {
                lines += data.toString('utf-8');

                if (lines.match(/(.|\n)*\$ $/)) {
                    (lines.match(/(.|\n)*\$ ?/g)||[]).forEach(function(line) {
                        callbacks.shift()(line.replace('$ ', '').trimEnd());
                    });

                    lines = '';

                    return;
                }

                if (lines.match(/(DEBUG: .*\n)+/)) {
                    (lines.match(/DEBUG: .*\n/g)||[]).forEach(function(line) {
                        console.log(line.replace('DEBUG: ', '').trimEnd());
                    });

                    lines = '';

                    return;
                }
            });
        });
    },

    execute: function(command) {
        return new Promise(function(resolve, reject) {
            callbacks.push(resolve);

            client.write(command);
            client.write('\r\n');
        });
    },

    close: function() {
        client.end();
    }
}


text:
Circlo
======

Circlo is an ambient audiovisual clock for iPhone and iPad. Design and programming by Johan Halin. Sound by Hannu Kuosmanen.

Circlo is mostly an experiment in doing an atypical user experience with UIKit. There are definitely some questionable (and outright stupid) code design decisions in Circlo, but I've learned to forgive myself about that.

The project uses ARC and requires Xcode 4.4 or newer.

Circlo uses [CocosDenshion](https://github.com/cocos2d/cocos2d-iphone) for playing audio, and the [Sniglet](http://www.theleagueofmoveabletype.com/sniglet) typeface by Haley Fiege. I've included these directly in the repository. If this is a problem, please contact me.

Links
=====

[Circlo on the App Store](http://itunes.apple.com/us/app/circlo-ambient-audiovisual/id523405247?ls=1&mt=8)

[Aero Deko](http://aerodeko.com)

[Johan (@suprjohan) on Twitter](http://twitter.com/suprjohan)


text:
import {Action} from "../action/Action";
import {EventEmitter} from "../ioc/wrapper/EventEmitter";
import {ConfigStore} from "../config/ConfigStore";
import {UtilConfig} from "../util/UtilConfig";
import {ActionPayload} from "../action/ActionPayload";
import {State} from "../State";
//
export interface Store extends EventEmitter {
	processAction(action: Action<ActionPayload>): void;
	getConfig(): UtilConfig<ConfigStore>;
	getState(): State;
}


text:
#include "config.h"

#if USE(COREAUDIO)

#include "PlatformClockCA.h"

#include <AudioToolbox/CoreAudioClock.h>
#include <CoreAudio/AudioHardware.h>

using namespace WebCore;

PlatformClockCA::PlatformClockCA()
    : m_clock(0)
    , m_running(false)
{
    CAClockNew(0, &m_clock);
    UInt32 timebase = kCAClockTimebase_AudioDevice;
    UInt32 timebaseSize = sizeof(timebase);
    CAClockSetProperty(m_clock, kCAClockProperty_InternalTimebase, timebaseSize, &timebase);

    AudioObjectID defaultAudioOutput = 0;
    UInt32 defaultAudioOutputSize = sizeof(defaultAudioOutput);

    AudioObjectPropertyAddress address;
    address.mSelector = kAudioHardwarePropertyDefaultOutputDevice;
    address.mScope    = kAudioObjectPropertyScopeGlobal;
    address.mElement  = kAudioObjectPropertyElementMaster;

    AudioObjectGetPropertyData(kAudioObjectSystemObject, &address, 0, 0, &defaultAudioOutputSize, &defaultAudioOutput);
    CAClockSetProperty(m_clock, kCAClockProperty_TimebaseSource, defaultAudioOutputSize, &defaultAudioOutput);
}

PlatformClockCA::~PlatformClockCA()
{
    CAClockDispose(m_clock);
}

void PlatformClockCA::setCurrentTime(double time)
{
    if (m_running)
        CAClockStop(m_clock);
    CAClockTime caTime;
    caTime.format = kCAClockTimeFormat_Seconds;
    caTime.time.seconds = time;
    CAClockSetCurrentTime(m_clock, &caTime);
    if (m_running)
        CAClockStart(m_clock);
}

double PlatformClockCA::currentTime() const
{
    CAClockTime caTime;

    // CAClock does not return the correct current time when stopped. Instead, query for
    // what is the start time, i.e. what the current time will be when started.
    if (m_running) {
        if (CAClockGetCurrentTime(m_clock, kCAClockTimeFormat_Seconds, &caTime) == noErr)
            return caTime.time.seconds;
    } else {
        if (CAClockGetStartTime(m_clock, kCAClockTimeFormat_Seconds, &caTime) == noErr)
            return caTime.time.seconds;
    }
    return 0;
}

void PlatformClockCA::setPlayRate(double rate)
{
    CAClockSetPlayRate(m_clock, rate);
}

double PlatformClockCA::PlatformClockCA::playRate() const
{
    double rate = 0;
    if (CAClockGetPlayRate(m_clock, &rate) == noErr)
        return rate;
    return 0;
}

void PlatformClockCA::start()
{
    if (m_running)
        return;
    m_running = true;
    CAClockStart(m_clock);
}

void PlatformClockCA::stop()
{
    if (!m_running)
        return;
    m_running = false;
    CAClockStop(m_clock);
}

#endif


text:
using System.Web.Mvc;
using System.Web.Routing;

namespace Mvc.Helper
{
    public static class RouteExtension
    {
        public static Route MapRouteLowerCase(this RouteCollection routes, string name, string url, object defaults)
        {
            return routes.MapRouteLowerCase(name, url, defaults, null);
        }

        public static Route MapRouteLowerCase(this RouteCollection routes, string name, string url, object defaults,
            string constraints)
        {
            Route route = new LowercaseRoute(url, new MvcRouteHandler())
            {
                Defaults = new RouteValueDictionary(defaults),
                Constraints = new RouteValueDictionary(constraints)
            };

            routes.Add(name, route);

            return route;
        }
    }

    public class LowercaseRoute : Route
    {
        public LowercaseRoute(string url, IRouteHandler routeHandler)
            : base(url, routeHandler)
        {
        }

        public LowercaseRoute(string url, RouteValueDictionary defaults, IRouteHandler routeHandler)
            : base(url, defaults, routeHandler)
        {
        }

        public LowercaseRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints,
            IRouteHandler routeHandler)
            : base(url, defaults, constraints, routeHandler)
        {
        }

        public LowercaseRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints,
            RouteValueDictionary dataTokens, IRouteHandler routeHandler)
            : base(url, defaults, constraints, dataTokens, routeHandler)
        {
        }

        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
        {
            VirtualPathData path = base.GetVirtualPath(requestContext, values);

            if (path != null)
                path.VirtualPath = path.VirtualPath.ToLowerInvariant();

            return path;
        }
    }
}