text:
//
// MainPage.xaml.h
// Declaration of the MainPage class.
//

#pragma once

#include "MainPage.g.h"

namespace CogniTest
{

	ref class ReencodeState sealed
	{
	internal:
		Windows::Graphics::Imaging::BitmapDecoder^ Decoder;
		Windows::Graphics::Imaging::BitmapEncoder^ Encoder;
		Windows::Storage::StorageFile^ File;
		Windows::Storage::FileProperties::PhotoOrientation Orientation;
	};

	/// <summary>
	/// An empty page that can be used on its own or navigated to within a Frame.
	/// </summary>
	public ref class MainPage sealed
	{
	private:
		CognitiveServicesLib::FaceClient^ m_FaceClient;
		Platform::Collections::Vector<CognitiveServicesLib::FaceAttributeOptions>^ m_FaceAttributeList;

	public:
		MainPage();

	private:
		void Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
		void BtnCamera_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);

		void PhotoButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);

	private:
		// Receive notifications about rotation of the device and UI and apply any necessary rotation to the preview stream and UI controls
		Windows::Devices::Sensors::SimpleOrientationSensor^ _orientationSensor;
		Windows::Graphics::Display::DisplayInformation^ _displayInformation;
		Windows::Devices::Sensors::SimpleOrientation _deviceOrientation;
		Windows::Graphics::Display::DisplayOrientations _displayOrientation;

		// Prevent the screen from sleeping while the camera is running
		Windows::System::Display::DisplayRequest^ _displayRequest;

		// For listening to media property changes
		Windows::Media::SystemMediaTransportControls^ _systemMediaControls;

		// MediaCapture and its state variables
		Platform::Agile<Windows::Media::Capture::MediaCapture^> _mediaCapture;
		Windows::Media::MediaProperties::IMediaEncodingProperties^ _previewProperties;
		bool _isInitialized;
		bool _isRecording;

		// Information about the camera device
		bool _externalCamera;
		bool _mirroringPreview;

		// CognitiveServicesLib members
		Windows::Media::Core::FaceDetectionEffect^ _faceDetectionEffect;
		CognitiveServicesLib::Speech::SpeechClient^ _speechClient;

		// Rotation metadata to apply to the preview stream and recorded videos (MF_MT_VIDEO_ROTATION)
		// Reference: http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868174.aspx
		const GUID RotationKey;

		// Folder in which the captures will be stored (availability check performed in SetupUiAsync)
		Windows::Storage::StorageFolder^ _captureFolder;

		// Event tokens
		Windows::Foundation::EventRegistrationToken _applicationSuspendingEventToken;
		Windows::Foundation::EventRegistrationToken _applicationResumingEventToken;
		Windows::Foundation::EventRegistrationToken _mediaControlPropChangedEventToken;
		Windows::Foundation::EventRegistrationToken _displayInformationEventToken;
		Windows::Foundation::EventRegistrationToken _recordLimitationExceededEventToken;
		Windows::Foundation::EventRegistrationToken _mediaCaptureFailedEventToken;
		Windows::Foundation::EventRegistrationToken _orientationChangedEventToken;
		Windows::Foundation::EventRegistrationToken _hardwareCameraButtonEventToken;
		Windows::Foundation::EventRegistrationToken _faceDetectedEventToken;

		// MediaCapture methods
		Concurrency::task<void> InitializeCameraAsync();
		Concurrency::task<void> CleanupCameraAsync();
		Concurrency::task<void> StartPreviewAsync();
		Concurrency::task<void> SetPreviewRotationAsync();
		Concurrency::task<void> StopPreviewAsync();
		Concurrency::task<void> TakePhotoAsync();
		void MediaCapture_Failed(Windows::Media::Capture::MediaCapture ^currentCaptureObject, Windows::Media::Capture::MediaCaptureFailedEventArgs^ errorEventArgs);

		// Rotation helpers
		Windows::Devices::Sensors::SimpleOrientation GetCameraOrientation();
		Windows::Storage::FileProperties::PhotoOrientation ConvertOrientationToPhotoOrientation(Windows::Devices::Sensors::SimpleOrientation orientation);
		int ConvertDeviceOrientationToDegrees(Windows::Devices::Sensors::SimpleOrientation orientation);
		int ConvertDisplayOrientationToDegrees(Windows::Graphics::Display::DisplayOrientations orientation);
		//void UpdateButtonOrientation();
		//void SetFacesCanvasRotation();

		// Helpers
		Concurrency::task<Windows::Devices::Enumeration::DeviceInformation^> FindCameraDeviceByPanelAsync(Windows::Devices::Enumeration::Panel panel);
		Concurrency::task<void> ReencodeAndSavePhotoAsync(Windows::Storage::Streams::IRandomAccessStream^ stream, Windows::Storage::StorageFile^ file, Windows::Storage::FileProperties::PhotoOrientation photoOrientation);
		void BtnJsonTest_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
		void BtnSpeak_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
	};
}


text:
module Background

end

ActionView::Base.send :include, FundoHelper

  #require File.join(File.dirname(__FILE__), "lib", "background")

#ActionView::Base.send :include, FundoHelper

redpajama_set_name: RedPajamaGithub


text:
A simplified version of this presentation follows.

For the best experience, please use one of the following browsers:

- [Chrome](//www.google.com/chrome)
- [Safari](//www.apple.com/safari)
- [Firefox](//www.mozilla.org/firefox)


text:
require 'rails_helper'

RSpec.describe Admin::AnnouncementsController, :type => :controller do

end


text:
package org.kuali.kra.institutionalproposal.proposaladmindetails;

import org.kuali.coeus.sys.framework.model.KcPersistableBusinessObjectBase;
import org.kuali.kra.institutionalproposal.home.InstitutionalProposal;
import org.kuali.coeus.propdev.impl.core.DevelopmentProposal;
import org.kuali.coeus.instprop.api.admin.ProposalAdminDetailsContract;

import java.sql.Date;

public class ProposalAdminDetails extends KcPersistableBusinessObjectBase implements ProposalAdminDetailsContract {

    private static final long serialVersionUID = -277575593517810685L;

    private Long proposalAdminDetailId;

    private String devProposalNumber;

    private Long instProposalId;

    private Date dateSubmittedByDept;

    private Date dateReturnedToDept;

    private Date dateApprovedByOsp;

    private Date dateSubmittedToAgency;

    private Date instPropCreateDate;

    private String instPropCreateUser;

    private String signedBy;

    private boolean submissionType;

    private DevelopmentProposal developmentProposal;

    private InstitutionalProposal institutionalProposal;

    @Override
    public Date getDateSubmittedByDept() {
        return dateSubmittedByDept;
    }

    public void setDateSubmittedByDept(Date dateSubmittedByDept) {
        this.dateSubmittedByDept = dateSubmittedByDept;
    }

    @Override
    public Date getDateReturnedToDept() {
        return dateReturnedToDept;
    }

    public void setDateReturnedToDept(Date dateReturnedToDept) {
        this.dateReturnedToDept = dateReturnedToDept;
    }

    @Override
    public Date getDateApprovedByOsp() {
        return dateApprovedByOsp;
    }

    public void setDateApprovedByOsp(Date dateApprovedByOsp) {
        this.dateApprovedByOsp = dateApprovedByOsp;
    }

    @Override
    public Date getDateSubmittedToAgency() {
        return dateSubmittedToAgency;
    }

    public void setDateSubmittedToAgency(Date dateSubmittedToAgency) {
        this.dateSubmittedToAgency = dateSubmittedToAgency;
    }

    @Override
    public Date getInstPropCreateDate() {
        return instPropCreateDate;
    }

    public void setInstPropCreateDate(Date instPropCreateDate) {
        this.instPropCreateDate = instPropCreateDate;
    }

    @Override
    public String getInstPropCreateUser() {
        return instPropCreateUser;
    }

    public void setInstPropCreateUser(String instPropCreateUser) {
        this.instPropCreateUser = instPropCreateUser;
    }

    @Override
    public String getSignedBy() {
        return signedBy;
    }

    public void setSignedBy(String signedBy) {
        this.signedBy = signedBy;
    }

    @Override
    public boolean getSubmissionType() {
        return submissionType;
    }

    public void setSubmissionType(boolean submissionType) {
        this.submissionType = submissionType;
    }

    @Override
    public Long getProposalAdminDetailId() {
        return proposalAdminDetailId;
    }

    public void setProposalAdminDetailId(Long proposalAdminDetailId) {
        this.proposalAdminDetailId = proposalAdminDetailId;
    }

    @Override
    public String getDevProposalNumber() {
        return devProposalNumber;
    }

    public void setDevProposalNumber(String devProposalNumber) {
        this.devProposalNumber = devProposalNumber;
    }

    @Override
    public Long getInstProposalId() {
        return instProposalId;
    }

    public void setInstProposalId(Long instProposalId) {
        this.instProposalId = instProposalId;
    }

    public DevelopmentProposal getDevelopmentProposal() {
        return developmentProposal;
    }

    public void setDevelopmentProposal(DevelopmentProposal developmentProposal) {
        this.developmentProposal = developmentProposal;
    }

    public InstitutionalProposal getInstitutionalProposal() {
        return institutionalProposal;
    }

    public void setInstitutionalProposal(InstitutionalProposal institutionalProposal) {
        this.institutionalProposal = institutionalProposal;
    }
}


text:
import { defineExtension } from './defineExtension'
import { getExtensionContext } from './getExtensionContext'

export { defineExtension }
export { getExtensionContext }


text:
<?php

namespace common\models;

use Yii;

/**
 * This is the model class for collection "merchant_brand_contact".
 *
 * @property \MongoId|string $_id
 * @property mixed $merchant_brand_contact_name
 * @property mixed $merchant_brand_contact_title
 * @property mixed $merchant_brand_contact_mobile
 * @property mixed $merchant_brand_contact_email
 * @property mixed $merchant_brand_fk
 */
class MerchantBrandContact extends \yii\mongodb\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function collectionName()
    {
        return ['auctionDB', 'merchant_brand_contact'];
    }

    /**
     * @inheritdoc
     */
    public function attributes()
    {
        return [
            '_id',
            'merchant_brand_contact_name',
            'merchant_brand_contact_title',
            'merchant_brand_contact_mobile',
            'merchant_brand_contact_email',
            'merchant_brand_fk',
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['merchant_brand_contact_name', 'merchant_brand_contact_title', 'merchant_brand_contact_mobile', 'merchant_brand_contact_email', 'merchant_brand_fk'], 'safe']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            '_id' => 'ID',
            'merchant_brand_contact_name' => 'Merchant Brand Contact Name',
            'merchant_brand_contact_title' => 'Merchant Brand Contact Title',
            'merchant_brand_contact_mobile' => 'Merchant Brand Contact Mobile',
            'merchant_brand_contact_email' => 'Merchant Brand Contact Email',
            'merchant_brand_fk' => 'Merchant Brand Fk',
        ];
    }

    public function getMerchantBrand()
    {
		return $this->hasOne(MerchantBrand::className(),['_id' => 'merchant_brand_fk']);
	}
}


text:
module GitFit
  class GitLib

    def get_commit_statistics(commit)
      statistics = `git show -s --format="%an-%at" #{commit}`.strip.split('-')
      { :author => statistics[0], :commit_date => statistics[1].to_i } # TODO seems a bit eurgh
    end

    def get_revision_list(commit)
      `git rev-list #{commit}`.split("\n")
    end

    def get_commit_contents(treeish)
      contents       = `git ls-tree -zrl #{treeish}`.split("\0")
      split_contents = contents.map { |c| c.split(' ') }
      split_contents.map do |bits, type, sha, size, path|
        {
          :bits => bits.to_i,
          :type => type,
          :sha  => sha,
          :size => size.to_i,
          :path => path
        }
      end
    end

    def get_all_blobs
      output = {}

      get_revision_list('HEAD').each do |commit|
        get_commit_contents(commit).each do |commit_contents|
          if commit_contents.fetch(:type) == 'blob'
            output.merge!(commit_contents.fetch(:path) => commit_contents.fetch(:size))
          end
        end
      end

      output
    end

  end
end


text:
package nozzle

import (
	"context"
	"errors"
	"time"

	"code.cloudfoundry.org/lager"
	"github.com/cloudfoundry-community/stackdriver-tools/src/stackdriver-nozzle/cloudfoundry"
	"github.com/cloudfoundry-community/stackdriver-tools/src/stackdriver-nozzle/messages"
	"github.com/cloudfoundry-community/stackdriver-tools/src/stackdriver-nozzle/mocks"
	"github.com/cloudfoundry/sonde-go/events"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gstruct"
)

type mockUnitParser struct {
	lastInput string
}

func (m *mockUnitParser) Parse(unit string) string {
	m.lastInput = unit
	return "{foo}"
}

var _ = Describe("MetricSink", func() {
	var (
		subject        Sink
		metricBuffer   *mocks.MetricsBuffer
		unitParser     *mockUnitParser
		logger         *mocks.MockLogger
		labelMaker     LabelMaker
		counterTracker *CounterTracker
		err            error
	)

	BeforeEach(func() {
		appInfoRepository := &mocks.AppInfoRepository{AppInfoMap: map[string]cloudfoundry.AppInfo{}}
		labelMaker = NewLabelMaker(appInfoRepository, "foobar")
		metricBuffer = &mocks.MetricsBuffer{}
		unitParser = &mockUnitParser{}
		logger = &mocks.MockLogger{}

		subject, err = NewMetricSink(logger, "firehose", labelMaker, metricBuffer, counterTracker, unitParser, "^runtimeMetric\\..*")
		Expect(err).To(BeNil())
	})

	It("creates metric for ValueMetric", func() {
		eventTime := time.Now()

		origin := "origin"
		name := "valueMetricName"
		value := 123.456
		unit := "barUnit"
		event := events.ValueMetric{
			Name:  &name,
			Value: &value,
			Unit:  &unit,
		}

		eventType := events.Envelope_ValueMetric
		timeStamp := eventTime.UnixNano()
		envelope := &events.Envelope{
			Origin:      &origin,
			EventType:   &eventType,
			ValueMetric: &event,
			Timestamp:   &timeStamp,
		}

		subject.Receive(envelope)

		metrics := metricBuffer.PostedMetrics
		Expect(metrics).To(HaveLen(1))
		Expect(metrics[0]).To(MatchAllFields(Fields{
			"Name":      Equal("firehose/origin.valueMetricName"),
			"Labels":    Equal(map[string]string{"foundation": "foobar"}),
			"Value":     Equal(123.456),
			"IntValue":  BeNumerically("==", 0),
			"EventTime": BeTemporally("~", eventTime),
			"StartTime": BeTemporally("~", eventTime),
			"Unit":      Equal("{foo}"),
			"Type":      Equal(eventType),
		}))
		Expect(metrics[0].EventTime.UnixNano()).To(Equal(timeStamp))

		Expect(unitParser.lastInput).To(Equal("barUnit"))
	})

	It("handles runtime ValueMetric", func() {
		eventTime := time.Now()

		origin := "myOrigin"
		name := "runtimeMetric.foobar"
		value := 123.456
		event := events.ValueMetric{
			Name:  &name,
			Value: &value,
		}

		eventType := events.Envelope_ValueMetric
		timeStamp := eventTime.UnixNano()
		envelope := &events.Envelope{
			Origin:      &origin,
			EventType:   &eventType,
			ValueMetric: &event,
			Timestamp:   &timeStamp,
		}

		subject.Receive(envelope)

		metrics := metricBuffer.PostedMetrics
		Expect(metrics).To(HaveLen(1))
		Expect(metrics[0]).To(MatchAllFields(Fields{
			"Name":      Equal("firehose/runtimeMetric.foobar"),
			"Labels":    Equal(map[string]string{"foundation": "foobar", "origin": "myOrigin"}),
			"Value":     Equal(123.456),
			"IntValue":  BeNumerically("==", 0),
			"EventTime": BeTemporally("~", eventTime),
			"StartTime": BeTemporally("~", eventTime),
			"Unit":      Ignore(),
			"Type":      Ignore(),
		}))
		Expect(metrics[0].EventTime.UnixNano()).To(Equal(timeStamp))
	})

	It("creates the proper metrics for ContainerMetric", func() {
		eventTime := time.Now()

		origin := "origin"
		diskBytesQuota := uint64(1073741824)
		instanceIndex := int32(0)
		cpuPercentage := 0.061651273460637
		diskBytes := uint64(164634624)
		memoryBytes := uint64(16601088)
		memoryBytesQuota := uint64(33554432)
		applicationID := "ee2aa52e-3c8a-4851-b505-0cb9fe24806e"
		timeStamp := eventTime.UnixNano()

		metricType := events.Envelope_ContainerMetric
		containerMetric := events.ContainerMetric{
			DiskBytesQuota:   &diskBytesQuota,
			InstanceIndex:    &instanceIndex,
			CpuPercentage:    &cpuPercentage,
			DiskBytes:        &diskBytes,
			MemoryBytes:      &memoryBytes,
			MemoryBytesQuota: &memoryBytesQuota,
			ApplicationId:    &applicationID,
		}

		envelope := &events.Envelope{
			Origin:          &origin,
			EventType:       &metricType,
			ContainerMetric: &containerMetric,
			Timestamp:       &timeStamp,
		}

		subject.Receive(envelope)

		metrics := metricBuffer.PostedMetrics
		Expect(metrics).To(HaveLen(5))

		eventName := func(element interface{}) string {
			return element.(messages.Metric).Name
		}

		labels := map[string]string{"foundation": "foobar", "instanceIndex": "0"}
		Expect(metrics).To(MatchAllElements(eventName, Elements{
			"firehose/origin.diskBytesQuota":   MatchFields(IgnoreExtras, Fields{"Labels": Equal(labels), "Type": Equal(metricType), "Value": Equal(float64(1073741824)), "Unit": Equal("")}),
			"firehose/origin.cpuPercentage":    MatchFields(IgnoreExtras, Fields{"Labels": Equal(labels), "Type": Equal(metricType), "Value": Equal(float64(0.061651273460637)), "Unit": Equal("")}),
			"firehose/origin.diskBytes":        MatchFields(IgnoreExtras, Fields{"Labels": Equal(labels), "Type": Equal(metricType), "Value": Equal(float64(164634624)), "Unit": Equal("")}),
			"firehose/origin.memoryBytes":      MatchFields(IgnoreExtras, Fields{"Labels": Equal(labels), "Type": Equal(metricType), "Value": Equal(float64(16601088)), "Unit": Equal("")}),
			"firehose/origin.memoryBytesQuota": MatchFields(IgnoreExtras, Fields{"Labels": Equal(labels), "Type": Equal(metricType), "Value": Equal(float64(33554432)), "Unit": Equal("")}),
		}))
	})

	It("creates total and delta metrics for CounterEvent", func() {
		eventTime := time.Now()

		eventType := events.Envelope_CounterEvent
		origin := "origin"
		name := "counterName"
		delta := uint64(654321)
		total := uint64(123456)
		timeStamp := eventTime.UnixNano()

		event := events.CounterEvent{
			Name:  &name,
			Delta: &delta,
			Total: &total,
		}
		envelope := &events.Envelope{
			Origin:       &origin,
			EventType:    &eventType,
			CounterEvent: &event,
			Timestamp:    &timeStamp,
		}

		subject.Receive(envelope)

		metrics := metricBuffer.PostedMetrics

		eventName := func(element interface{}) string {
			return element.(messages.Metric).Name
		}
		Expect(metrics).To(MatchAllElements(eventName, Elements{
			"firehose/origin.counterName.delta": MatchAllFields(Fields{
				"Name":      Ignore(),
				"Labels":    Equal(map[string]string{"foundation": "foobar"}),
				"Value":     Equal(float64(654321)),
				"IntValue":  BeNumerically("==", 0),
				"EventTime": BeTemporally("~", eventTime),
				"StartTime": BeTemporally("~", eventTime),
				"Unit":      Equal(""),
				"Type":      Equal(events.Envelope_ValueMetric),
			}),
			"firehose/origin.counterName.total": MatchAllFields(Fields{
				"Name":      Ignore(),
				"Labels":    Equal(map[string]string{"foundation": "foobar"}),
				"Value":     Equal(float64(123456)),
				"IntValue":  BeNumerically("==", 0),
				"EventTime": BeTemporally("~", eventTime),
				"StartTime": BeTemporally("~", eventTime),
				"Unit":      Equal(""),
				"Type":      Equal(events.Envelope_ValueMetric),
			}),
		}))
	})

	Context("with CounterTracker enabled", func() {
		BeforeEach(func() {
			counterTracker = NewCounterTracker(context.TODO(), time.Duration(5)*time.Second, logger)
			subject, err = NewMetricSink(logger, "firehose", labelMaker, metricBuffer, counterTracker, unitParser, "^runtimeMetric\\..*")
			Expect(err).To(BeNil())
		})

		It("creates cumulative metrics for CounterEvent", func() {
			eventTime := time.Now()

			eventType := events.Envelope_CounterEvent
			origin := "origin"
			name := "counterName"

			// List of {delta, total} events to produce.
			eventValues := [][]uint64{
				{5, 105},
				{10, 115},
				{10, 125},
				{5, 5}, // counter reset
				{20, 25},
			}

			for idx, values := range eventValues {
				ts := eventTime.UnixNano() + int64(time.Second)*int64(idx) // Events are 1 second apart.
				delta := values[0]
				total := values[1]
				subject.Receive(&events.Envelope{
					Origin:    &origin,
					EventType: &eventType,
					Timestamp: &ts,
					CounterEvent: &events.CounterEvent{
						Name:  &name,
						Delta: &delta,
						Total: &total,
					},
				})
			}

			metrics := metricBuffer.PostedMetrics
			Expect(metrics).To(HaveLen(4))
			eventName := func(element interface{}) string {
				return element.(messages.Metric).Name
			}
			Expect(metrics).To(MatchElements(eventName, AllowDuplicates, Elements{
				"firehose/origin.counterName": MatchAllFields(Fields{
					"Name":      Ignore(),
					"Labels":    Equal(map[string]string{"foundation": "foobar"}),
					"Value":     BeNumerically("==", 0),
					"IntValue":  Ignore(),
					"EventTime": Ignore(),
					"StartTime": BeTemporally("~", eventTime),
					"Unit":      Equal(""),
					"Type":      Equal(eventType),
				}),
			}))
			expectedTotals := []float64{10, 20, 25, 45}
			for idx, total := range expectedTotals {
				Expect(metrics[idx]).To(MatchFields(IgnoreExtras, Fields{
					"IntValue":  BeNumerically("==", total),
					"EventTime": BeTemporally("~", eventTime.Add(time.Duration(idx+1)*time.Second)),
				}))
			}
		})
	})

	It("returns error when envelope contains unhandled event type", func() {
		eventType := events.Envelope_HttpStartStop
		envelope := &events.Envelope{
			EventType: &eventType,
		}

		subject.Receive(envelope)

		Expect(logger.Logs()).To(ContainElement(mocks.Log{
			Action: "metricSink.Receive",
			Level:  lager.ERROR,
			Err:    errors.New("unknown event type: HttpStartStop"),
		}))
	})
})


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
com.numericalmethod.suanshu.stats.dlm (SuanShu 1.3.1 API Documentation)
</TITLE>

<META NAME="date" CONTENT="2011-04-26">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

com.numericalmethod.suanshu.stats.dlm

Classes

Dlm

DlmSim

LinearKalmanFilter

ObservationEquation

StateEquation


text:
package com.intellij.java.codeInspection;

import com.intellij.codeInspection.dataFlow.NullityInference;
import com.intellij.codeInspection.dataFlow.Nullness;
import com.intellij.psi.PsiClass;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.psi.impl.source.PsiMethodImpl;
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;
import one.util.streamex.StreamEx;

public class ParameterNullityInferenceFromSourceTest extends LightCodeInsightFixtureTestCase {
  public void testSimpleDereference() {
    assertNullity("+", "String test(String s) { return s.trim(); }");
  }

  public void testReassign() {
    assertNullity("-+", "String test(String s, String s1) { s+=s1.trim();return s.trim(); }");
  }

  public void testNoDereference() {
    assertNullity("--", "String test(String s, int x) { return s == null ? null : s.trim(); }");
  }

  public void testSwitchPrimitive() {
    assertNullity("-", "String test(int x) { switch(x) {default:return null;} }");
  }

  public void testSwitchObject() {
    assertNullity("+", "String test(Integer x) { switch(x) {default:return null;} }");
  }

  public void testSynchronized() {
    assertNullity("++", "void test(Object lock, String s) {synchronized(lock) {;;System.out.println(s.trim());}}");
  }

  public void testArray() {
    assertNullity("++", "String test(int[] arr, int[] arr2) { System.out.println(arr2[0]);for(int a: arr) {} }");
  }

  public void testForInfiniteIf() {
    assertNullity("+-+",
                  "String test(String s, String s1, String s2) { for(;;) if(s.length()+s2.length() > 0) return s1.trim(); }");
  }

  public void testForFinite() {
    assertNullity("++",
                  "void test(Node n, Tree t) { for(Node x=n.firstChild();x!=t.getEnd();x=x.next()) System.out.println(x); }");
  }

  public void testForDerefAfterCondition() {
    assertNullity("-",
                  "void test(Node n) { for(;n != null;n=n.next()) System.out.println(n); }");
  }

  public void testForFiniteIf() {
    assertNullity("-+-",
                  "String test(String s, String s1, String s2) { for(;s1.length()>0;) if(s.length()+s2.length() > 0) return s1.trim(); }");
  }

  public void testWhileTrue() {
    assertNullity("+",
                  "String test(String s) { while(true) System.out.println(s.trim()); }");
  }

  public void testWhileOther() {
    assertNullity("-",
                  "String test(String s) { while(s != null) System.out.println(s.trim()); }");
  }

  public void testThrow() {
    assertNullity("+",
                  "String test(Object obj) { throw new RuntimeException(obj.toString()); }");
  }

  public void testThrowOk() {
    assertNullity("-",
                  "String test(Object obj) { throw new RuntimeException(String.valueOf(obj)); }");
  }

  public void testLambda() {
    assertNullity("-",
                  "String test(Object obj) { Runnable r = () -> obj.hashCode(); if(obj != null) r.run(); }");
  }

  public void testMethodRef() {
    assertNullity("+",
                  "String test(Object obj) { Runnable r = obj::hashCode; if(obj != null) r.run(); }");
  }

  public void testClass() {
    assertNullity("-+",
                  "String test(Object obj, String s) { class X { int i = obj.hashCode(); }\n" +
                  "if(!s.isEmpty() && obj != null) System.out.println(new X().i); }");
  }

  public void testAnonymousClass() {
    assertNullity("+-",
                  "String test(String s, String s1) { " +
                  "Object x = new Object(){" +
                  "String s1 = s.trim();" +
                  "{System.out.println(s1.trim());}}" +
                  "}");
  }

  public void testTryNPECaught() {
    assertNullity("-",
                  "String test(String s) {" +
                  "try {System.out.println(s.trim());}" +
                  "catch(RuntimeException ex) {}" +
                  "}");
  }

  public void testTryNPECaughtMultiCatch() {
    assertNullity("-",
                  "String test(String s) {" +
                  "try {System.out.println(s.trim());}" +
                  "catch(InternalError | NullPointerException ex) {}" +
                  "}");
  }

  public void testTryNPENotCaught() {
    assertNullity("+",
                  "String test(String s) {" +
                  "try {System.out.println(s.trim());}" +
                  "catch(InternalError ex) {}" +
                  "}");
  }

  public void testTryWithResources() {
    assertNullity("+",
                  "String test(String path) {" +
                  "try(java.io.FileReader fr = new java.io.FileReader(path.trim())) {System.out.println(fr.read());}" +
                  "catch(java.io.IOException ex) {}" +
                  "}");
  }

  // expected: + = notnull, - = unknown/nullable for each parameter
  private void assertNullity(String expected, String classBody) {
    PsiClass clazz = myFixture.addClass("final class Foo { " + classBody + " }");
    assertFalse(((PsiFileImpl)clazz.getContainingFile()).isContentsLoaded());
    PsiMethodImpl method = (PsiMethodImpl)clazz.getMethods()[0];
    String actual = StreamEx.of(method.getParameterList().getParameters())
      .map(NullityInference::inferNullity)
      .map(n -> n == Nullness.NOT_NULL ? "+" : "-")
      .joining();
    assertFalse(((PsiFileImpl)clazz.getContainingFile()).isContentsLoaded());
    assertEquals(expected, actual);
  }
}


text:
package com.facebook.buck.android;

import com.facebook.buck.android.apkmodule.APKModule;
import com.facebook.buck.android.apkmodule.APKModuleGraph;
import com.facebook.buck.android.packageable.AndroidPackageableCollection;
import com.facebook.buck.android.relinker.NativeRelinker;
import com.facebook.buck.android.toolchain.ndk.NdkCxxPlatform;
import com.facebook.buck.android.toolchain.ndk.NdkCxxPlatformsProvider;
import com.facebook.buck.android.toolchain.ndk.NdkCxxRuntime;
import com.facebook.buck.android.toolchain.ndk.TargetCpuType;
import com.facebook.buck.core.cell.CellPathResolver;
import com.facebook.buck.core.exceptions.HumanReadableException;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.Flavor;
import com.facebook.buck.core.model.InternalFlavor;
import com.facebook.buck.core.rules.ActionGraphBuilder;
import com.facebook.buck.core.rules.BuildRule;
import com.facebook.buck.core.rules.BuildRuleParams;
import com.facebook.buck.core.rules.SourcePathRuleFinder;
import com.facebook.buck.core.sourcepath.BuildTargetSourcePath;
import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.core.sourcepath.resolver.SourcePathResolver;
import com.facebook.buck.core.sourcepath.resolver.impl.DefaultSourcePathResolver;
import com.facebook.buck.core.toolchain.ToolchainProvider;
import com.facebook.buck.core.util.immutables.BuckStyleImmutable;
import com.facebook.buck.cxx.toolchain.CxxBuckConfig;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkable;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.util.RichStream;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;
import org.immutables.value.Value;

public class AndroidNativeLibsPackageableGraphEnhancer {

  private static final String COPY_NATIVE_LIBS = "copy_native_libs";

  private final ToolchainProvider toolchainProvider;
  private final ProjectFilesystem projectFilesystem;
  private final BuildTarget originalBuildTarget;
  private final BuildRuleParams buildRuleParams;
  private final ActionGraphBuilder graphBuilder;
  private final SourcePathResolver pathResolver;
  private final SourcePathRuleFinder ruleFinder;
  private final ImmutableSet<TargetCpuType> cpuFilters;
  private final CxxBuckConfig cxxBuckConfig;
  private final Optional<Map<String, List<Pattern>>> nativeLibraryMergeMap;
  private final Optional<BuildTarget> nativeLibraryMergeGlue;
  private final Optional<ImmutableSortedSet<String>> nativeLibraryMergeLocalizedSymbols;
  private final ImmutableList<Pattern> relinkerWhitelist;
  private final RelinkerMode relinkerMode;
  private final APKModuleGraph apkModuleGraph;

  private final CellPathResolver cellPathResolver;

  public AndroidNativeLibsPackageableGraphEnhancer(
      ToolchainProvider toolchainProvider,
      CellPathResolver cellPathResolver,
      ActionGraphBuilder graphBuilder,
      BuildTarget originalBuildTarget,
      ProjectFilesystem projectFilesystem,
      BuildRuleParams originalParams,
      ImmutableSet<TargetCpuType> cpuFilters,
      CxxBuckConfig cxxBuckConfig,
      Optional<Map<String, List<Pattern>>> nativeLibraryMergeMap,
      Optional<BuildTarget> nativeLibraryMergeGlue,
      Optional<ImmutableSortedSet<String>> nativeLibraryMergeLocalizedSymbols,
      RelinkerMode relinkerMode,
      ImmutableList<Pattern> relinkerWhitelist,
      APKModuleGraph apkModuleGraph) {
    this.toolchainProvider = toolchainProvider;
    this.cellPathResolver = cellPathResolver;
    this.projectFilesystem = projectFilesystem;
    this.originalBuildTarget = originalBuildTarget;
    this.ruleFinder = new SourcePathRuleFinder(graphBuilder);
    this.nativeLibraryMergeLocalizedSymbols = nativeLibraryMergeLocalizedSymbols;
    this.pathResolver = DefaultSourcePathResolver.from(ruleFinder);
    this.buildRuleParams = originalParams;
    this.graphBuilder = graphBuilder;
    this.cpuFilters = cpuFilters;
    this.cxxBuckConfig = cxxBuckConfig;
    this.nativeLibraryMergeMap = nativeLibraryMergeMap;
    this.nativeLibraryMergeGlue = nativeLibraryMergeGlue;
    this.relinkerMode = relinkerMode;
    this.relinkerWhitelist = relinkerWhitelist;
    this.apkModuleGraph = apkModuleGraph;
  }

  @Value.Immutable
  @BuckStyleImmutable
  interface AbstractAndroidNativeLibsGraphEnhancementResult {
    Optional<ImmutableMap<APKModule, CopyNativeLibraries>> getCopyNativeLibraries();

    Optional<ImmutableSortedSet<SourcePath>> getUnstrippedLibraries();

    Optional<ImmutableSortedMap<String, String>> getSonameMergeMap();

    Optional<ImmutableSortedMap<String, ImmutableSortedSet<String>>> getSharedObjectTargets();
  }

  // Populates an immutable map builder with all given linkables set to the given cpu type.
  // Returns true iff linkables is not empty.
  private boolean populateMapWithLinkables(
      ImmutableMultimap<APKModule, NativeLinkable> linkables,
      ImmutableMap.Builder<AndroidLinkableMetadata, SourcePath> builder,
      Map<AndroidLinkableMetadata, NativeLinkable> nativeLinkableMap,
      TargetCpuType targetCpuType,
      NdkCxxPlatform platform)
      throws HumanReadableException {

    boolean hasNativeLibs = false;

    for (Map.Entry<APKModule, NativeLinkable> linkableEntry : linkables.entries()) {
      NativeLinkable nativeLinkable = linkableEntry.getValue();
      if (nativeLinkable.getPreferredLinkage(platform.getCxxPlatform(), graphBuilder)
          != NativeLinkable.Linkage.STATIC) {
        ImmutableMap<String, SourcePath> solibs =
            nativeLinkable.getSharedLibraries(platform.getCxxPlatform(), graphBuilder);
        for (Map.Entry<String, SourcePath> entry : solibs.entrySet()) {
          AndroidLinkableMetadata metadata =
              AndroidLinkableMetadata.builder()
                  .setSoName(entry.getKey())
                  .setTargetCpuType(targetCpuType)
                  .setApkModule(linkableEntry.getKey())
                  .build();
          builder.put(metadata, entry.getValue());
          if (nativeLinkableMap.containsKey(metadata)) {
            throw new HumanReadableException(
                "Two libraries in the dependencies have the same output filename: %s:\n"
                    + "Those libraries are  %s and %s",
                metadata.getSoName(), nativeLinkable, nativeLinkableMap.get(metadata));
          }
          nativeLinkableMap.put(metadata, nativeLinkable);
          hasNativeLibs = true;
        }
      }
    }
    return hasNativeLibs;
  }

  public AndroidNativeLibsGraphEnhancementResult enhance(
      AndroidPackageableCollection packageableCollection) {
    @SuppressWarnings("PMD.PrematureDeclaration")
    AndroidNativeLibsGraphEnhancementResult.Builder resultBuilder =
        AndroidNativeLibsGraphEnhancementResult.builder();

    ImmutableMultimap<APKModule, NativeLinkable> nativeLinkables =
        packageableCollection.getNativeLinkables();
    ImmutableMultimap<APKModule, NativeLinkable> nativeLinkablesAssets =
        packageableCollection.getNativeLinkablesAssets();

    ImmutableMap<TargetCpuType, NdkCxxPlatform> nativePlatforms = ImmutableMap.of();

    if (!nativeLinkables.isEmpty() || !nativeLinkablesAssets.isEmpty()) {
      NdkCxxPlatformsProvider ndkCxxPlatformsProvider =
          toolchainProvider.getByName(
              NdkCxxPlatformsProvider.DEFAULT_NAME, NdkCxxPlatformsProvider.class);

      nativePlatforms = ndkCxxPlatformsProvider.getResolvedNdkCxxPlatforms(graphBuilder);

      if (nativePlatforms.isEmpty()) {
        throw new HumanReadableException(
            "No native platforms detected. Probably Android NDK is not configured properly.");
      }
    }

    if (nativeLibraryMergeMap.isPresent()
        && !nativeLibraryMergeMap.get().isEmpty()
        && !nativePlatforms.isEmpty()) {
      NativeLibraryMergeEnhancementResult enhancement =
          NativeLibraryMergeEnhancer.enhance(
              cellPathResolver,
              cxxBuckConfig,
              graphBuilder,
              pathResolver,
              ruleFinder,
              originalBuildTarget,
              projectFilesystem,
              nativePlatforms,
              nativeLibraryMergeMap.get(),
              nativeLibraryMergeGlue,
              nativeLibraryMergeLocalizedSymbols,
              nativeLinkables,
              nativeLinkablesAssets);
      nativeLinkables = enhancement.getMergedLinkables();
      nativeLinkablesAssets = enhancement.getMergedLinkablesAssets();
      resultBuilder.setSonameMergeMap(enhancement.getSonameMapping());
      resultBuilder.setSharedObjectTargets(enhancement.getSharedObjectTargets());
    }

    // Iterate over all the {@link AndroidNativeLinkable}s from the collector and grab the shared
    // libraries for all the {@link TargetCpuType}s that we care about.  We deposit them into a map
    // of CPU type and SONAME to the shared library path, which the {@link CopyNativeLibraries}
    // rule will use to compose the destination name.
    ImmutableMap.Builder<APKModule, CopyNativeLibraries> moduleMappedCopyNativeLibriesBuilder =
        ImmutableMap.builder();

    boolean hasCopyNativeLibraries = false;

    // Make sure we process the root module last so that we know if any of the module contain
    // libraries that depend on a non-system runtime and add it to the root module if needed.
    ImmutableSet<APKModule> apkModules =
        FluentIterable.from(apkModuleGraph.getAPKModules())
            .filter(input -> !input.isRootModule())
            .append(apkModuleGraph.getRootAPKModule())
            .toSet();

    ImmutableMap.Builder<AndroidLinkableMetadata, SourcePath> nativeLinkableLibsBuilder =
        ImmutableMap.builder();
    ImmutableMap.Builder<AndroidLinkableMetadata, SourcePath> nativeLinkableLibsAssetsBuilder =
        ImmutableMap.builder();

    Map<AndroidLinkableMetadata, NativeLinkable> nativeLinkableLibsMap = new HashMap<>();
    Map<AndroidLinkableMetadata, NativeLinkable> nativeLinkableLibsAssetsMap = new HashMap<>();

    if (!nativeLinkables.isEmpty() || !nativeLinkablesAssets.isEmpty()) {
      for (TargetCpuType targetCpuType : getFilteredPlatforms(nativePlatforms, cpuFilters)) {
        NdkCxxPlatform platform = nativePlatforms.get(targetCpuType);
        // Populate nativeLinkableLibs and nativeLinkableLibsAssets with the appropriate entries.
        populateMapWithLinkables(
            nativeLinkables,
            nativeLinkableLibsBuilder,
            nativeLinkableLibsMap,
            targetCpuType,
            platform);
        populateMapWithLinkables(
            nativeLinkablesAssets,
            nativeLinkableLibsAssetsBuilder,
            nativeLinkableLibsAssetsMap,
            targetCpuType,
            platform);
      }
    }
    // Adds a cxxruntime linkable to the nativeLinkableLibsBuilder for every platform that needs it.
    ImmutableMap<AndroidLinkableMetadata, SourcePath> nativeLinkableLibsAssets =
        nativeLinkableLibsAssetsBuilder.build();
    addCxxRuntimeLinkables(nativePlatforms, nativeLinkableLibsBuilder, nativeLinkableLibsAssets);

    ImmutableMap<AndroidLinkableMetadata, SourcePath> nativeLinkableLibs =
        nativeLinkableLibsBuilder.build();

    if (relinkerMode == RelinkerMode.ENABLED
        && (!nativeLinkableLibs.isEmpty() || !nativeLinkableLibsAssets.isEmpty())) {
      NativeRelinker relinker =
          new NativeRelinker(
              originalBuildTarget,
              projectFilesystem,
              buildRuleParams.withExtraDeps(
                  ImmutableSortedSet.<BuildRule>naturalOrder()
                      .addAll(ruleFinder.filterBuildRuleInputs(nativeLinkableLibs.values()))
                      .addAll(ruleFinder.filterBuildRuleInputs(nativeLinkableLibsAssets.values()))
                      .build()),
              cellPathResolver,
              pathResolver,
              ruleFinder,
              cxxBuckConfig,
              nativePlatforms,
              nativeLinkableLibs,
              nativeLinkableLibsAssets,
              relinkerWhitelist);

      nativeLinkableLibs = relinker.getRelinkedLibs();
      nativeLinkableLibsAssets = relinker.getRelinkedLibsAssets();
      for (BuildRule rule : relinker.getRules()) {
        graphBuilder.addToIndex(rule);
      }
    }

    ImmutableMap<StripLinkable, StrippedObjectDescription> strippedLibsMap =
        generateStripRules(nativePlatforms, nativeLinkableLibs);
    ImmutableMap<StripLinkable, StrippedObjectDescription> strippedLibsAssetsMap =
        generateStripRules(nativePlatforms, nativeLinkableLibsAssets);

    resultBuilder.setUnstrippedLibraries(
        RichStream.from(nativeLinkableLibs.values())
            .concat(nativeLinkableLibsAssets.values().stream())
            .toImmutableSortedSet(Ordering.natural()));

    for (APKModule module : apkModules) {
      ImmutableMap<StripLinkable, StrippedObjectDescription> filteredStrippedLibsMap =
          ImmutableMap.copyOf(
              FluentIterable.from(strippedLibsMap.entrySet())
                  .filter(entry -> module.equals(entry.getValue().getApkModule())));

      ImmutableMap<StripLinkable, StrippedObjectDescription> filteredStrippedLibsAssetsMap =
          ImmutableMap.copyOf(
              FluentIterable.from(strippedLibsAssetsMap.entrySet())
                  .filter(entry -> module.equals(entry.getValue().getApkModule())));

      ImmutableCollection<SourcePath> nativeLibsDirectories =
          packageableCollection.getNativeLibsDirectories().get(module);

      ImmutableCollection<SourcePath> nativeLibsAssetsDirectories =
          packageableCollection.getNativeLibAssetsDirectories().get(module);

      if (filteredStrippedLibsMap.isEmpty()
          && filteredStrippedLibsAssetsMap.isEmpty()
          && nativeLibsDirectories.isEmpty()
          && nativeLibsAssetsDirectories.isEmpty()) {
        continue;
      }

      moduleMappedCopyNativeLibriesBuilder.put(
          module,
          createCopyNativeLibraries(
              module,
              filteredStrippedLibsMap,
              filteredStrippedLibsAssetsMap,
              nativeLibsDirectories,
              nativeLibsAssetsDirectories));
      hasCopyNativeLibraries = true;
    }
    return resultBuilder
        .setCopyNativeLibraries(
            hasCopyNativeLibraries
                ? Optional.of(moduleMappedCopyNativeLibriesBuilder.build())
                : Optional.empty())
        .build();
  }

  private void addCxxRuntimeLinkables(
      ImmutableMap<TargetCpuType, NdkCxxPlatform> nativePlatforms,
      ImmutableMap.Builder<AndroidLinkableMetadata, SourcePath> nativeLinkableLibsBuilder,
      ImmutableMap<AndroidLinkableMetadata, SourcePath> nativeLinkableLibsAssets) {
    RichStream.from(nativeLinkableLibsBuilder.build().keySet())
        .concat(RichStream.from(nativeLinkableLibsAssets.keySet()))
        .map(AndroidLinkableMetadata::getTargetCpuType)
        .distinct()
        .forEach(
            targetCpuType -> {
              NdkCxxPlatform platform = Objects.requireNonNull(nativePlatforms.get(targetCpuType));
              NdkCxxRuntime cxxRuntime = platform.getCxxRuntime();
              Optional<SourcePath> cxxSharedRuntimePath = platform.getCxxSharedRuntimePath();
              if (!cxxSharedRuntimePath.isPresent()) {
                // Not all ndk cxx platforms require a packages c++ runtime.
                return;
              }
              AndroidLinkableMetadata runtimeLinkableMetadata =
                  AndroidLinkableMetadata.builder()
                      .setTargetCpuType(targetCpuType)
                      .setSoName(cxxRuntime.getSoname())
                      .setApkModule(apkModuleGraph.getRootAPKModule())
                      .build();
              nativeLinkableLibsBuilder.put(runtimeLinkableMetadata, cxxSharedRuntimePath.get());
            });
  }

  private CopyNativeLibraries createCopyNativeLibraries(
      APKModule module,
      ImmutableMap<StripLinkable, StrippedObjectDescription> filteredStrippedLibsMap,
      ImmutableMap<StripLinkable, StrippedObjectDescription> filteredStrippedLibsAssetsMap,
      ImmutableCollection<SourcePath> nativeLibsDirectories,
      ImmutableCollection<SourcePath> nativeLibAssetsDirectories) {
    return new CopyNativeLibraries(
        originalBuildTarget.withAppendedFlavors(
            InternalFlavor.of(COPY_NATIVE_LIBS + "_" + module.getName())),
        projectFilesystem,
        ruleFinder,
        ImmutableSet.copyOf(filteredStrippedLibsMap.values()),
        ImmutableSet.copyOf(filteredStrippedLibsAssetsMap.values()),
        ImmutableSet.copyOf(nativeLibsDirectories),
        ImmutableSet.copyOf(nativeLibAssetsDirectories),
        cpuFilters,
        module.getName());
  }

  private static Iterable<TargetCpuType> getFilteredPlatforms(
      ImmutableMap<TargetCpuType, ?> nativePlatforms, ImmutableSet<TargetCpuType> cpuFilters) {
    // TODO(agallagher): We currently treat an empty set of filters to mean to allow everything.
    // We should fix this by assigning a default list of CPU filters in the descriptions, but
    // until we do, if the set of filters is empty, just build for all available platforms.
    if (cpuFilters.isEmpty()) {
      return nativePlatforms.keySet();
    }
    Set<TargetCpuType> missing = Sets.difference(cpuFilters, nativePlatforms.keySet());
    Preconditions.checkState(
        missing.isEmpty(), "Unknown platform types <" + Joiner.on(",").join(missing) + ">");
    return cpuFilters;
  }

  private ImmutableMap<StripLinkable, StrippedObjectDescription> generateStripRules(
      ImmutableMap<TargetCpuType, NdkCxxPlatform> nativePlatforms,
      ImmutableMap<AndroidLinkableMetadata, SourcePath> libs) {
    ImmutableMap.Builder<StripLinkable, StrippedObjectDescription> result = ImmutableMap.builder();
    for (Map.Entry<AndroidLinkableMetadata, SourcePath> entry : libs.entrySet()) {
      SourcePath sourcePath = entry.getValue();
      TargetCpuType targetCpuType = entry.getKey().getTargetCpuType();
      APKModule apkModule = entry.getKey().getApkModule();

      NdkCxxPlatform platform = Objects.requireNonNull(nativePlatforms.get(targetCpuType));

      // To be safe, default to using the app rule target as the base for the strip rule.
      // This will be used for stripping the C++ runtime.  We could use something more easily
      // shareable (like just using the app's containing directory, or even the repo root),
      // but stripping the C++ runtime is pretty fast, so just keep the safe old behavior for now.
      BuildTarget baseBuildTarget = originalBuildTarget;
      // But if we're stripping a cxx_library, use that library as the base of the target
      // to allow sharing the rule between all apps that depend on it.
      if (sourcePath instanceof BuildTargetSourcePath) {
        baseBuildTarget = ((BuildTargetSourcePath) sourcePath).getTarget();
      }

      String sharedLibrarySoName = entry.getKey().getSoName();
      StripLinkable stripLinkable =
          requireStripLinkable(
              projectFilesystem,
              ruleFinder,
              graphBuilder,
              sourcePath,
              targetCpuType,
              platform,
              baseBuildTarget,
              sharedLibrarySoName);
      result.put(
          stripLinkable,
          StrippedObjectDescription.builder()
              .setSourcePath(stripLinkable.getSourcePathToOutput())
              .setStrippedObjectName(sharedLibrarySoName)
              .setTargetCpuType(targetCpuType)
              .setApkModule(apkModule)
              .build());
    }
    return result.build();
  }

  // Note: this method produces rules that will be shared between multiple apps,
  // so be careful not to let information about this particular app slip into the definitions.
  private static StripLinkable requireStripLinkable(
      ProjectFilesystem projectFilesystem,
      SourcePathRuleFinder ruleFinder,
      ActionGraphBuilder graphBuilder,
      SourcePath sourcePath,
      TargetCpuType targetCpuType,
      NdkCxxPlatform platform,
      BuildTarget baseBuildTarget,
      String sharedLibrarySoName) {
    BuildTarget targetForStripRule =
        baseBuildTarget.withAppendedFlavors(
            InternalFlavor.of("android-strip"),
            InternalFlavor.of(Flavor.replaceInvalidCharacters(sharedLibrarySoName)),
            InternalFlavor.of(Flavor.replaceInvalidCharacters(targetCpuType.name())));

    return (StripLinkable)
        graphBuilder.computeIfAbsent(
            targetForStripRule,
            (buildTarget) ->
                new StripLinkable(
                    targetForStripRule,
                    projectFilesystem,
                    ruleFinder,
                    platform.getCxxPlatform().getStrip(),
                    sourcePath,
                    sharedLibrarySoName));
  }
}


text:
function hasProperty(obj, prop) {
    for (var property in obj) {
        if(property == prop) {
            return true;
        }
    }

    return  false;
}

var person = {
    name: 'sasho',
    age: 22
};

console.log(hasProperty(person, 'pop'));
console.log(hasProperty(person, 'name'));


text:
from .profile import *
from .topic import *
from .tag import *
from .comment import *
from .relation import *


text:
package com.raoulvdberge.refinedstorage.tile;

import com.raoulvdberge.refinedstorage.apiimpl.network.node.NetworkNodeDestructor;
import com.raoulvdberge.refinedstorage.tile.config.IComparable;
import com.raoulvdberge.refinedstorage.tile.config.IFilterable;
import com.raoulvdberge.refinedstorage.tile.config.IType;
import com.raoulvdberge.refinedstorage.tile.data.TileDataParameter;
import net.minecraft.network.datasync.DataSerializers;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;

import javax.annotation.Nonnull;

public class TileDestructor extends TileNode<NetworkNodeDestructor> {
    public static final TileDataParameter<Integer, TileDestructor> COMPARE = IComparable.createParameter();
    public static final TileDataParameter<Integer, TileDestructor> MODE = IFilterable.createParameter();
    public static final TileDataParameter<Integer, TileDestructor> TYPE = IType.createParameter();
    public static final TileDataParameter<Boolean, TileDestructor> PICKUP = new TileDataParameter<>(DataSerializers.BOOLEAN, false, t -> t.getNode().isPickupItem(), (t, v) -> {
        t.getNode().setPickupItem(v);
        t.getNode().markDirty();
    });

    public TileDestructor() {
        dataManager.addWatchedParameter(COMPARE);
        dataManager.addWatchedParameter(MODE);
        dataManager.addWatchedParameter(TYPE);
        dataManager.addWatchedParameter(PICKUP);
    }

    @Override
    @Nonnull
    public NetworkNodeDestructor createNode(World world, BlockPos pos) {
        return new NetworkNodeDestructor(world, pos);
    }

    @Override
    public String getNodeId() {
        return NetworkNodeDestructor.ID;
    }
}


text:
using System.Collections.Generic;
using Build.DomainModel;
using Build.DomainModel.MSBuild;
using Build.IO;
using Build.Parser;

namespace Build.Watchdog
{
	public sealed class SolutionStore
		: FileStore<Solution>
	{
		public SolutionStore(IFileSystem fileSystem) : base(new SolutionParser(new ProjectParser(fileSystem)))
		{}

		public IEnumerable<Solution> CreateSolutions(IReadOnlyDictionary<string, Project> projects)
		{
			var solutions = new List<Solution>();
			foreach (Solution solution in Values)
			{
				solutions.Add(solution.Clone(projects));
			}
			return solutions;
		}
	}
}


text:
using System;

namespace SafeMapper.Tests.Model.ConvertClasses
{
    public class FakeConvertSingletonField
    {
        public static FakeConvertSingletonField Instance = new FakeConvertSingletonField();

        public int ToInt32(string value)
        {
            return 1337;
        }

        public string ToString(int value, IFormatProvider formatProvider)
        {
            return "1337";
        }
    }
}


text:
require 'set'

module Localizator
  class Key
    attr_accessor :name, :translations

    def initialize(attributes = {})
      @name = attributes[:name]
      @translations = Set.new
    end

    def add_translation(translation)
      translations.add(translation)
    end

    def category
      @category ||= name.split('.').first
    end

    def complete?
      translations.all? { |t| t.text.to_s !~ /\A\s*\z/ } || empty?
    end

    def empty?
      translations.all? { |t| t.text.to_s =~ /\A\s*\z/ }
    end
  end
end


text:
require 'open-uri'
require 'json'
require 'openssl'

require_relative 'PrecompiledDependency'
require_relative '../RubyCommon'

# Base database class
class BaseDatabase
  attr_reader :Name

  def initialize(name)
    @Name = name

    @Precompiled = {}
    @Data = nil
  end

  def base_url
    @Data['baseurl']
  end

  def handle_loaded_data
    @Data['precompiled'].each do |key, value|
      @Precompiled[key] = PrecompiledDependency.new key, base_url, value['hash']
    end
  end

  def info
    puts %(Base database "#{@Name}")
    common_info
  end

  def common_info
    puts %(has base url of "#{base_url}")
    puts %(contains #{@Precompiled.length} precompiled dependencies")
  end

  def getPrecompiled(name)
    get_precompiled name
  end

  def get_precompiled(name)
    @Precompiled[name]
  end

  def search(name)
    @Precompiled.select do |key, _value|
      key.include? name
    end.map { |_key, value| value }
  end

  def each
    @Precompiled.each do |key, value|
      yield key, value
    end
  end

  def add(dep)
    @Precompiled[dep.FullName] = dep
  end

  def write(file)
    File.open(file, 'wb') do |f|
      f.puts JSON.pretty_generate serialize
    end
  end

  def serialize
    precompiled = {}

    @Precompiled.each do |key, value|
      if key != value.FullName
        warning "Precompiled key doesn't match its name: #{key} != #{value.Fullname}"
      end

      precompiled[key] = { hash: value.Hash }
    end

    precompiled = precompiled.sort.to_h

    {
      baseurl: base_url,
      precompiled: precompiled
    }
  end
end

# Online database
class Database < BaseDatabase
  attr_reader :URL

  def initialize(name, url, keyFile)
    super name

    @URL = url
    @Key = loadKeyFromFile keyFile
    @KeyFile = keyFile

    puts "Downloading signature of #{@Name}"
    open(url + '.sha512', 'rb', read_timeout: 10) do |req|
      @Signature = req.read
    end

    puts "Downloading: #{@URL}"
    open(url, 'rb', read_timeout: 20) do |req|
      text = req.read

      # Verify signature
      puts 'Verifying download signature'

      unless @Key.verify OpenSSL::Digest::SHA512.new, @Signature, text
        raise 'Downloaded file/signature is not signed with the required key'
      end

      success 'Signature is good'

      @Data = JSON.parse(text)
    end

    handle_loaded_data
  end

  def info
    puts %(Database "#{@Name}" from #{@URL})
    puts %(verified by key "#{@KeyFile}")
    common_info
  end
end

# Local database
class LocalDatabase < BaseDatabase
  attr_reader :base_url

  def initialize(name, base_url: 'unset')
    super name

    @base_url = base_url

    @Data = {
      'baseurl' => base_url,
      'precompiled' => []
    }

    handle_loaded_data
  end

  def read_from_file(file)
    @Data = JSON.parse File.read(file)
    handle_loaded_data
    @base_url = @Data['baseurl']
  end

  def info
    puts %(Local database "#{@Name}")
    common_info
  end
end

def load_database(name, url, key)
  $remoteDatabases.push(Database.new(name, url, key))
  true
rescue StandardError => e
  warning "Failed to download database #{name}, error: #{e}"
  false
end

def load_local_database_from_file(name, file)
  db = LocalDatabase.new name
  db.read_from_file file
  db
end

def loadKeyFromFile(file)
  OpenSSL::X509::Certificate.new(File.read(file)).public_key
end

# Loads and returns all the default databases
def getDefaultDatabases
  unless $remoteDatabasesLoaded
    info 'Loading remote databases...'

    $remoteDatabases = []

    failures = false

    unless load_database 'boostslair',
                         'https://boostslair.com/rubysetupsystem/database.json',
                         File.expand_path('rubysetupsystem.cert', __dir__)
      failures = true
    end

    if failures
      warning 'One or more databases failed to download.'
      warning 'Precompiled and other features may be unavailable.'
    end

    $remoteDatabasesLoaded = true
    info "#{$remoteDatabases.length} remote databases loaded"
  end

  $remoteDatabases
end


text:
Clipper 1.2

This is a chrome unpacked extension.

To install goto:

   Chrome -> Window -> Extensions

   click on "Load unpacked extension"
   and select the directory where this extension is contained

Help Needed

This is just a beginning. Better analysis of the selection
is highly desirable.

Credits

The code in this extension is a modified version of
a chrome extension that I found on the net (and a blog)
article. The name of the extension was:

    "name": "Linx Bookmark 1.1",
    "description": "Adds the current page to the Linx bookmarking system.",
    "version": "1.1",

Unfortunately I cannot give a more precise reference, and
    have not been able to find the original. Mail my if you stumble over
    the origonal.

Some the code in content_script.js
came from
   http://dev.day.com/content/ddc/blog/2010/06.html


text:
// Copyright 2015 Georg-August-Universität Göttingen, Germany
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package de.ugoe.cs.cpdp.eval;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import de.ugoe.cs.cpdp.training.ITrainer;
import de.ugoe.cs.cpdp.training.IWekaCompatibleTrainer;
import de.ugoe.cs.cpdp.util.WekaUtils;
import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.core.Instance;
import weka.core.Instances;

/**
 * Base class for the evaluation of results of classifiers compatible with the {@link Classifier}
 * interface. For each classifier, the following metrics are calculated:
 *

 *
error

 *
recall

 *
precision

 *
fscore

 *
gscore

 *
MCC

 *
AUC

 *
balance

 *
AUCEC

 *
aucRoI

 *
NofB20

 *
RelB20

 *
NofI80

 *
RelI80

 *
RelE80

 *
NECM10

 *
NECM15

 *
NECM20

 *
NECM25

 *
cost

 *
tpr: true positive rate

 *
tnr: true negative rate

 *
fpr: false positive rate

 *
fnr: false negative rate

 *
tp: true positives

 *
fp: false positives

 *
tn: true negatives

 *
fn: false negatives

 *

 *
 * @author Steffen Herbold
 */
public abstract class AbstractWekaEvaluation implements IEvaluationStrategy {

    /**
     * writer for the evaluation results
     */
    private PrintWriter output = new PrintWriter(System.out);

    /**
     * flag that defines if the output is the system out
     */
    private boolean outputIsSystemOut = true;

    /**
     * name of the configuration
     */
    private String configurationName = "default";

    /**
     * Creates the Weka evaluator. Allows the creation of the evaluator in different ways, e.g., for
     * cross-validation or evaluation on the test data.
     *
     * @param testdata
     *            test data
     * @param classifier
     *            classifier used
     * @return evaluator
     */
    protected abstract Evaluation createEvaluator(Instances testdata, Classifier classifier);

    /*
     * (non-Javadoc)
     *
     * @see de.ugoe.cs.cpdp.eval.EvaluationStrategy#apply(weka.core.Instances, weka.core.Instances,
     * java.util.List, boolean)
     */
    @Override
    public void apply(Instances testdata,
                      Instances traindata,
                      Instances traindataOriginal,
                      List<ITrainer> trainers,
                      List<Double> efforts,
                      List<Double> numBugs,
                      Instances bugMatrix,
                      boolean writeHeader,
                      List<IResultStorage> storages)
    {
        final List<Classifier> classifiers = new LinkedList<>();
        final List<ExperimentResult> experimentResults = new LinkedList<>();
        String productName = testdata.relationName();

        for (ITrainer trainer : trainers) {
            if (trainer instanceof IWekaCompatibleTrainer) {
                classifiers.add(((IWekaCompatibleTrainer) trainer).getClassifier());
                experimentResults
                    .add(new ExperimentResult(this.configurationName, productName,
                                              ((IWekaCompatibleTrainer) trainer).getName()));
            }
            else {
                throw new RuntimeException("The selected evaluator only support Weka classifiers");
            }
        }

        if (writeHeader) {
            this.output.append("version,size_test,size_training,size_training_original");
            this.output.append(",bias_test,bias_training,bias_training_original,prop1_defect,prop1_clean");
            for (ITrainer trainer : trainers) {
                this.output.append(",error_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",recall_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",precision_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",fscore_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",gscore_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",mcc_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",auc_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",aucec_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",aucAlberg_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",aucRoI_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",balance_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",nofb20_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",nofi80_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",necm10_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",necm25_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",cost_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",tpr_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",tnr_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",fpr_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",fnr_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",tp_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",fn_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",tn_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",fp_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerConst1to1_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperConst1to1_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerConst1toM_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperConst1toM_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerConstNtoM_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperConstNtoM_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerSize1to1_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperSize1to1_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerSize1toM_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperSize1toM_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerSizeNtoM_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperSizeNtoM_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerConst1to1Imp10_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperConst1to1Imp10_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerConst1toMImp10_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperConst1toMImp10_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerConstNtoMImp10_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperConstNtoMImp10_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerSize1to1Imp10_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperSize1to1Imp10_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerSize1toMImp10_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperSize1toMImp10_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerSizeNtoMImp10_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperSizeNtoMImp10_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerConst1to1Imp20_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperConst1to1Imp20_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerConst1toMImp20_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperConst1toMImp20_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerConstNtoMImp20_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperConstNtoMImp20_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerSize1to1Imp20_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperSize1to1Imp20_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerSize1toMImp20_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperSize1toMImp20_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerSizeNtoMImp20_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperSizeNtoMImp20_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerConst1to1Imp30_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperConst1to1Imp30_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerConst1toMImp30_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperConst1toMImp30_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerConstNtoMImp30_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperConstNtoMImp30_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerSize1to1Imp30_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperSize1to1Imp30_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerSize1toMImp30_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperSize1toMImp30_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerSizeNtoMImp30_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperSizeNtoMImp30_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerConst1to1Imp40_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperConst1to1Imp40_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerConst1toMImp40_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperConst1toMImp40_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerConstNtoMImp40_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperConstNtoMImp40_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerSize1to1Imp40_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperSize1to1Imp40_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerSize1toMImp40_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperSize1toMImp40_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerSizeNtoMImp40_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperSizeNtoMImp40_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerConst1to1Imp50_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperConst1to1Imp50_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerConst1toMImp50_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperConst1toMImp50_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerConstNtoMImp50_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperConstNtoMImp50_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerSize1to1Imp50_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperSize1to1Imp50_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerSize1toMImp50_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperSize1toMImp50_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",lowerSizeNtoMImp50_" + ((IWekaCompatibleTrainer) trainer).getName());
                this.output.append(",upperSizeNtoMImp50_" + ((IWekaCompatibleTrainer) trainer).getName());
            }
            this.output.append(System.lineSeparator());
        }

        this.output.append(productName);
        this.output.append("," + testdata.numInstances());
        this.output.append("," + traindata.numInstances());
        this.output.append("," + traindataOriginal.numInstances());
        this.output.append("," + getBias(testdata));
        this.output.append("," + getBias(traindata));
        this.output.append("," + getBias(traindataOriginal));
        this.output.append("," + getProp1Defects(testdata, efforts));
        this.output.append("," + getProp1Clean(testdata, efforts));

        Evaluation eval = null;
        EffortMetricCalculator effortEval = null;
        CostBoundaryCalculator costBoundaryEval = null;
        CostBoundaryCalculator costBoundaryEvalImp10 = null;
        CostBoundaryCalculator costBoundaryEvalImp20 = null;
        CostBoundaryCalculator costBoundaryEvalImp30 = null;
        CostBoundaryCalculator costBoundaryEvalImp40 = null;
        CostBoundaryCalculator costBoundaryEvalImp50 = null;
        Iterator<Classifier> classifierIter = classifiers.iterator();
        Iterator<ExperimentResult> resultIter = experimentResults.iterator();
        while (classifierIter.hasNext()) {
            Classifier classifier = classifierIter.next();
            eval = createEvaluator(testdata, classifier);
            effortEval = new EffortMetricCalculator(testdata, classifier, efforts, numBugs);
            costBoundaryEval = new CostBoundaryCalculator(testdata, classifier, efforts, bugMatrix, eval, 0.0);
            costBoundaryEvalImp10 = new CostBoundaryCalculator(testdata, classifier, efforts, bugMatrix, eval, 0.1);
            costBoundaryEvalImp20 = new CostBoundaryCalculator(testdata, classifier, efforts, bugMatrix, eval, 0.2);
            costBoundaryEvalImp30 = new CostBoundaryCalculator(testdata, classifier, efforts, bugMatrix, eval, 0.3);
            costBoundaryEvalImp40 = new CostBoundaryCalculator(testdata, classifier, efforts, bugMatrix, eval, 0.4);
            costBoundaryEvalImp50 = new CostBoundaryCalculator(testdata, classifier, efforts, bugMatrix, eval, 0.5);

            double pf =
                eval.numFalsePositives(1) / (eval.numFalsePositives(1) + eval.numTrueNegatives(1));
            double gmeasure;
            if( eval.recall(1)==0.0 && pf==1.0 ) {
                gmeasure = 0.0;
            } else {
                gmeasure = 2 * eval.recall(1) * (1.0 - pf) / (eval.recall(1) + (1.0 - pf));
            }
            double balance = 1.0-Math.sqrt(Math.pow(1-eval.recall(1),2)+Math.pow(pf,2))/Math.sqrt(2);
            double aucec = effortEval.getAUCEC();
            double aucAlberg = effortEval.getAUCAlberg();
            double aucWithRoI = effortEval.getAUCwRoI();
            double nofb20 = effortEval.getNofb20();
            double relb20 = effortEval.getRelb20();
            double nofi80 = effortEval.getNofi80();
            double reli80 = effortEval.getReli80();
            double rele80 = effortEval.getRele80();

            double necm10 = getNECM(eval, 10.0);
            double necm15 = getNECM(eval, 15.0);
            double necm20 = getNECM(eval, 20.0);
            double necm25 = getNECM(eval, 25.0);

            double nofbPredicted = effortEval.getNofBPredicted();
            double nofbMissed = effortEval.getNofBMissed();
            double cost = effortEval.getCost();

            this.output.append("," + eval.errorRate());
            this.output.append("," + eval.recall(1));
            this.output.append("," + eval.precision(1));
            this.output.append("," + eval.fMeasure(1));
            this.output.append("," + gmeasure);
            this.output.append("," + eval.matthewsCorrelationCoefficient(1));
            this.output.append("," + eval.areaUnderROC(1));
            this.output.append("," + aucec);
            this.output.append("," + aucAlberg);
            this.output.append("," + aucWithRoI);
            this.output.append("," + balance);
            this.output.append("," + nofb20);
            this.output.append("," + nofi80);
            this.output.append("," + necm10);
            this.output.append("," + necm25);
            this.output.append("," + cost);
            this.output.append("," + eval.truePositiveRate(1));
            this.output.append("," + eval.trueNegativeRate(1));
            this.output.append("," + eval.falsePositiveRate(1));
            this.output.append("," + eval.falseNegativeRate(1));
            this.output.append("," + eval.numTruePositives(1));
            this.output.append("," + eval.numFalseNegatives(1));
            this.output.append("," + eval.numTrueNegatives(1));
            this.output.append("," + eval.numFalsePositives(1));
            this.output.append("," + costBoundaryEval.getLowerConst1to1());
            this.output.append("," + costBoundaryEval.getUpperConst1to1());
            this.output.append("," + costBoundaryEval.getLowerConst1toM());
            this.output.append("," + costBoundaryEval.getUpperConst1toM());
            this.output.append("," + costBoundaryEval.getLowerConstNtoM());
            this.output.append("," + costBoundaryEval.getUpperConstNtoM());
            this.output.append("," + costBoundaryEval.getLowerSize1to1());
            this.output.append("," + costBoundaryEval.getUpperSize1to1());
            this.output.append("," + costBoundaryEval.getLowerSize1toM());
            this.output.append("," + costBoundaryEval.getUpperSize1toM());
            this.output.append("," + costBoundaryEval.getLowerSizeNtoM());
            this.output.append("," + costBoundaryEval.getUpperSizeNtoM());
            this.output.append("," + costBoundaryEvalImp10.getLowerConst1to1());
            this.output.append("," + costBoundaryEvalImp10.getUpperConst1to1());
            this.output.append("," + costBoundaryEvalImp10.getLowerConst1toM());
            this.output.append("," + costBoundaryEvalImp10.getUpperConst1toM());
            this.output.append("," + costBoundaryEvalImp10.getLowerConstNtoM());
            this.output.append("," + costBoundaryEvalImp10.getUpperConstNtoM());
            this.output.append("," + costBoundaryEvalImp10.getLowerSize1to1());
            this.output.append("," + costBoundaryEvalImp10.getUpperSize1to1());
            this.output.append("," + costBoundaryEvalImp10.getLowerSize1toM());
            this.output.append("," + costBoundaryEvalImp10.getUpperSize1toM());
            this.output.append("," + costBoundaryEvalImp10.getLowerSizeNtoM());
            this.output.append("," + costBoundaryEvalImp10.getUpperSizeNtoM());
            this.output.append("," + costBoundaryEvalImp20.getLowerConst1to1());
            this.output.append("," + costBoundaryEvalImp20.getUpperConst1to1());
            this.output.append("," + costBoundaryEvalImp20.getLowerConst1toM());
            this.output.append("," + costBoundaryEvalImp20.getUpperConst1toM());
            this.output.append("," + costBoundaryEvalImp20.getLowerConstNtoM());
            this.output.append("," + costBoundaryEvalImp20.getUpperConstNtoM());
            this.output.append("," + costBoundaryEvalImp20.getLowerSize1to1());
            this.output.append("," + costBoundaryEvalImp20.getUpperSize1to1());
            this.output.append("," + costBoundaryEvalImp20.getLowerSize1toM());
            this.output.append("," + costBoundaryEvalImp20.getUpperSize1toM());
            this.output.append("," + costBoundaryEvalImp20.getLowerSizeNtoM());
            this.output.append("," + costBoundaryEvalImp20.getUpperSizeNtoM());
            this.output.append("," + costBoundaryEvalImp30.getLowerConst1to1());
            this.output.append("," + costBoundaryEvalImp30.getUpperConst1to1());
            this.output.append("," + costBoundaryEvalImp30.getLowerConst1toM());
            this.output.append("," + costBoundaryEvalImp30.getUpperConst1toM());
            this.output.append("," + costBoundaryEvalImp30.getLowerConstNtoM());
            this.output.append("," + costBoundaryEvalImp30.getUpperConstNtoM());
            this.output.append("," + costBoundaryEvalImp30.getLowerSize1to1());
            this.output.append("," + costBoundaryEvalImp30.getUpperSize1to1());
            this.output.append("," + costBoundaryEvalImp30.getLowerSize1toM());
            this.output.append("," + costBoundaryEvalImp30.getUpperSize1toM());
            this.output.append("," + costBoundaryEvalImp30.getLowerSizeNtoM());
            this.output.append("," + costBoundaryEvalImp30.getUpperSizeNtoM());
            this.output.append("," + costBoundaryEvalImp40.getLowerConst1to1());
            this.output.append("," + costBoundaryEvalImp40.getUpperConst1to1());
            this.output.append("," + costBoundaryEvalImp40.getLowerConst1toM());
            this.output.append("," + costBoundaryEvalImp40.getUpperConst1toM());
            this.output.append("," + costBoundaryEvalImp40.getLowerConstNtoM());
            this.output.append("," + costBoundaryEvalImp40.getUpperConstNtoM());
            this.output.append("," + costBoundaryEvalImp40.getLowerSize1to1());
            this.output.append("," + costBoundaryEvalImp40.getUpperSize1to1());
            this.output.append("," + costBoundaryEvalImp40.getLowerSize1toM());
            this.output.append("," + costBoundaryEvalImp40.getUpperSize1toM());
            this.output.append("," + costBoundaryEvalImp40.getLowerSizeNtoM());
            this.output.append("," + costBoundaryEvalImp40.getUpperSizeNtoM());
            this.output.append("," + costBoundaryEvalImp50.getLowerConst1to1());
            this.output.append("," + costBoundaryEvalImp50.getUpperConst1to1());
            this.output.append("," + costBoundaryEvalImp50.getLowerConst1toM());
            this.output.append("," + costBoundaryEvalImp50.getUpperConst1toM());
            this.output.append("," + costBoundaryEvalImp50.getLowerConstNtoM());
            this.output.append("," + costBoundaryEvalImp50.getUpperConstNtoM());
            this.output.append("," + costBoundaryEvalImp50.getLowerSize1to1());
            this.output.append("," + costBoundaryEvalImp50.getUpperSize1to1());
            this.output.append("," + costBoundaryEvalImp50.getLowerSize1toM());
            this.output.append("," + costBoundaryEvalImp50.getUpperSize1toM());
            this.output.append("," + costBoundaryEvalImp50.getLowerSizeNtoM());
            this.output.append("," + costBoundaryEvalImp50.getUpperSizeNtoM());

            ExperimentResult result = resultIter.next();
            result.setSizeTestData(testdata.numInstances());
            result.setSizeTrainingData(traindata.numInstances());
            result.setSizeTrainingOriginal(traindataOriginal.numInstances());
            result.setBiasTestData(getBias(testdata));
            result.setBiasTrainingData(getBias(traindata));
            result.setBiasTrainingOriginal(getBias(traindataOriginal));
            result.setProp1Defect(getProp1Defects(testdata, efforts));
            result.setProp1Clean(getProp1Clean(testdata, efforts));
            result.setError(eval.errorRate());
            result.setRecall(eval.recall(1));
            result.setPrecision(eval.precision(1));
            result.setFscore(eval.fMeasure(1));
            result.setGscore(gmeasure);
            result.setMcc(eval.matthewsCorrelationCoefficient(1));
            result.setBalance(balance);
            result.setAuc(eval.areaUnderROC(1));
            result.setAucec(aucec);
            result.setAucAlberg(aucAlberg);
            result.setAucRoI(aucWithRoI);
            result.setNofb20(nofb20);
            result.setRelb20(relb20);
            result.setNofi80(nofi80);
            result.setReli80(reli80);
            result.setRele80(rele80);
            result.setNecm10(necm10);
            result.setNecm15(necm15);
            result.setNecm20(necm20);
            result.setNecm25(necm25);
            result.setCost(cost);
            result.setNofbPredicted(nofbPredicted);
            result.setNofbMissed(nofbMissed);
            result.setTpr(eval.truePositiveRate(1));
            result.setTnr(eval.trueNegativeRate(1));
            result.setFpr(eval.falsePositiveRate(1));
            result.setFnr(eval.falseNegativeRate(1));
            result.setTp(eval.numTruePositives(1));
            result.setFn(eval.numFalseNegatives(1));
            result.setTn(eval.numTrueNegatives(1));
            result.setFp(eval.numFalsePositives(1));
            result.setLowerConst1to1(costBoundaryEval.getLowerConst1to1());
            result.setUpperConst1to1(costBoundaryEval.getUpperConst1to1());
            result.setLowerConst1toM(costBoundaryEval.getLowerConst1toM());
            result.setUpperConst1toM(costBoundaryEval.getUpperConst1toM());
            result.setLowerConstNtoM(costBoundaryEval.getLowerConstNtoM());
            result.setUpperConstNtoM(costBoundaryEval.getUpperConstNtoM());
            result.setLowerSize1to1(costBoundaryEval.getLowerSize1to1());
            result.setUpperSize1to1(costBoundaryEval.getUpperSize1to1());
            result.setLowerSize1toM(costBoundaryEval.getLowerSize1toM());
            result.setUpperSize1toM(costBoundaryEval.getUpperSize1toM());
            result.setLowerSizeNtoM(costBoundaryEval.getLowerSizeNtoM());
            result.setUpperSizeNtoM(costBoundaryEval.getUpperSizeNtoM());
            result.setLowerConst1to1Imp10(costBoundaryEvalImp10.getLowerConst1to1());
            result.setUpperConst1to1Imp10(costBoundaryEvalImp10.getUpperConst1to1());
            result.setLowerConst1toMImp10(costBoundaryEvalImp10.getLowerConst1toM());
            result.setUpperConst1toMImp10(costBoundaryEvalImp10.getUpperConst1toM());
            result.setLowerConstNtoMImp10(costBoundaryEvalImp10.getLowerConstNtoM());
            result.setUpperConstNtoMImp10(costBoundaryEvalImp10.getUpperConstNtoM());
            result.setLowerSize1to1Imp10(costBoundaryEvalImp10.getLowerSize1to1());
            result.setUpperSize1to1Imp10(costBoundaryEvalImp10.getUpperSize1to1());
            result.setLowerSize1toMImp10(costBoundaryEvalImp10.getLowerSize1toM());
            result.setUpperSize1toMImp10(costBoundaryEvalImp10.getUpperSize1toM());
            result.setLowerSizeNtoMImp10(costBoundaryEvalImp10.getLowerSizeNtoM());
            result.setUpperSizeNtoMImp10(costBoundaryEvalImp10.getUpperSizeNtoM());
            result.setLowerConst1to1Imp20(costBoundaryEvalImp20.getLowerConst1to1());
            result.setUpperConst1to1Imp20(costBoundaryEvalImp20.getUpperConst1to1());
            result.setLowerConst1toMImp20(costBoundaryEvalImp20.getLowerConst1toM());
            result.setUpperConst1toMImp20(costBoundaryEvalImp20.getUpperConst1toM());
            result.setLowerConstNtoMImp20(costBoundaryEvalImp20.getLowerConstNtoM());
            result.setUpperConstNtoMImp20(costBoundaryEvalImp20.getUpperConstNtoM());
            result.setLowerSize1to1Imp20(costBoundaryEvalImp20.getLowerSize1to1());
            result.setUpperSize1to1Imp20(costBoundaryEvalImp20.getUpperSize1to1());
            result.setLowerSize1toMImp20(costBoundaryEvalImp20.getLowerSize1toM());
            result.setUpperSize1toMImp20(costBoundaryEvalImp20.getUpperSize1toM());
            result.setLowerSizeNtoMImp20(costBoundaryEvalImp20.getLowerSizeNtoM());
            result.setUpperSizeNtoMImp20(costBoundaryEvalImp20.getUpperSizeNtoM());
            result.setLowerConst1to1Imp30(costBoundaryEvalImp30.getLowerConst1to1());
            result.setUpperConst1to1Imp30(costBoundaryEvalImp30.getUpperConst1to1());
            result.setLowerConst1toMImp30(costBoundaryEvalImp30.getLowerConst1toM());
            result.setUpperConst1toMImp30(costBoundaryEvalImp30.getUpperConst1toM());
            result.setLowerConstNtoMImp30(costBoundaryEvalImp30.getLowerConstNtoM());
            result.setUpperConstNtoMImp30(costBoundaryEvalImp30.getUpperConstNtoM());
            result.setLowerSize1to1Imp30(costBoundaryEvalImp30.getLowerSize1to1());
            result.setUpperSize1to1Imp30(costBoundaryEvalImp30.getUpperSize1to1());
            result.setLowerSize1toMImp30(costBoundaryEvalImp30.getLowerSize1toM());
            result.setUpperSize1toMImp30(costBoundaryEvalImp30.getUpperSize1toM());
            result.setLowerSizeNtoMImp30(costBoundaryEvalImp30.getLowerSizeNtoM());
            result.setUpperSizeNtoMImp30(costBoundaryEvalImp30.getUpperSizeNtoM());
            result.setLowerConst1to1Imp40(costBoundaryEvalImp40.getLowerConst1to1());
            result.setUpperConst1to1Imp40(costBoundaryEvalImp40.getUpperConst1to1());
            result.setLowerConst1toMImp40(costBoundaryEvalImp40.getLowerConst1toM());
            result.setUpperConst1toMImp40(costBoundaryEvalImp40.getUpperConst1toM());
            result.setLowerConstNtoMImp40(costBoundaryEvalImp40.getLowerConstNtoM());
            result.setUpperConstNtoMImp40(costBoundaryEvalImp40.getUpperConstNtoM());
            result.setLowerSize1to1Imp40(costBoundaryEvalImp40.getLowerSize1to1());
            result.setUpperSize1to1Imp40(costBoundaryEvalImp40.getUpperSize1to1());
            result.setLowerSize1toMImp40(costBoundaryEvalImp40.getLowerSize1toM());
            result.setUpperSize1toMImp40(costBoundaryEvalImp40.getUpperSize1toM());
            result.setLowerSizeNtoMImp40(costBoundaryEvalImp40.getLowerSizeNtoM());
            result.setUpperSizeNtoMImp40(costBoundaryEvalImp40.getUpperSizeNtoM());
            result.setLowerConst1to1Imp50(costBoundaryEvalImp50.getLowerConst1to1());
            result.setUpperConst1to1Imp50(costBoundaryEvalImp50.getUpperConst1to1());
            result.setLowerConst1toMImp50(costBoundaryEvalImp50.getLowerConst1toM());
            result.setUpperConst1toMImp50(costBoundaryEvalImp50.getUpperConst1toM());
            result.setLowerConstNtoMImp50(costBoundaryEvalImp50.getLowerConstNtoM());
            result.setUpperConstNtoMImp50(costBoundaryEvalImp50.getUpperConstNtoM());
            result.setLowerSize1to1Imp50(costBoundaryEvalImp50.getLowerSize1to1());
            result.setUpperSize1to1Imp50(costBoundaryEvalImp50.getUpperSize1to1());
            result.setLowerSize1toMImp50(costBoundaryEvalImp50.getLowerSize1toM());
            result.setUpperSize1toMImp50(costBoundaryEvalImp50.getUpperSize1toM());
            result.setLowerSizeNtoMImp50(costBoundaryEvalImp50.getLowerSizeNtoM());
            result.setUpperSizeNtoMImp50(costBoundaryEvalImp50.getUpperSizeNtoM());
            for (IResultStorage storage : storages) {
                storage.addResult(result);
            }
        }

        this.output.append(System.lineSeparator());
        this.output.flush();
    }

    /*
     * (non-Javadoc)
     *
     * @see de.ugoe.cs.cpdp.Parameterizable#setParameter(java.lang.String)
     */
    @Override
    public void setParameter(String parameters) {
        if (this.output != null && !this.outputIsSystemOut) {
            this.output.close();
        }
        if ("system.out".equals(parameters) || "".equals(parameters)) {
            this.output = new PrintWriter(System.out);
            this.outputIsSystemOut = true;
        }
        else {
            try {
                this.output = new PrintWriter(new FileOutputStream(parameters));
                this.outputIsSystemOut = false;
                int filenameStart = parameters.lastIndexOf('/') + 1;
                int filenameEnd = parameters.lastIndexOf('.');
                this.configurationName = parameters.substring(filenameStart, filenameEnd);
            }
            catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     *

     * Calculates the normalized expected cost of misclassification through a ratio
     * of the cost between the cost of false positives (unnecessary review effort) vs
     * the cost of false negatives (due to the bug introduced in the final product).
     *

     *
     * @param eval evaluator used
     * @param factor ratio between the costs as cost_fn/cost_fp
     * @return NECM value
     */
    public static double getNECM(Evaluation eval, double factor) {
        return (eval.numFalsePositives(1)+factor*eval.numFalseNegatives(1))/
                (eval.numInstances());
    }

    /**
     *

     * Calculates the bias of a data set. That means the percentage of instances in
     * the training data that are defective.
     *

     *
     * @param data data set to calculate the bias for
     * @return bias
     */
    public static double getBias(Instances data) {
        double count = 0.0;
        for (Instance instance : data) {
            if (instance.classValue() > 0.0) {
                count += 1.0;
            }
        }
        return (count / data.size());
    }

    /**
     *

     * Calculates ratio of the effort of the largest percentile of defect artifacts by
     * the overall amount of defect artifacts.
     *

     *
     * @param data test data set
     * @param efforts effort list from the test data set
     * @return Effort of the largest percentile of defect artifacts by overall amount of defect artifacts.
     */
    public static double getProp1Defects(Instances data, List<Double> efforts) {
        List<Double> effortDefect = new ArrayList<>();
        int amountDefectArtifacts = 0;
        for (int i = 0; i < data.size(); i++){
            if (data.get(i).classValue() > 0.0) {
                amountDefectArtifacts += 1;
                effortDefect.add(efforts.get(i));
            }
        }
        effortDefect.sort(Collections.reverseOrder());
        int percentileIndex = (int) Math.ceil(effortDefect.size() / 100.0);
        double largestPercentileEffort = 0.0;
        for (int i = 0; i < percentileIndex; i++){
            largestPercentileEffort += effortDefect.get(i);
        }
        return largestPercentileEffort / (double)amountDefectArtifacts;
    }

    /**
     *

     * Calculates ratio of the effort of the largest percentile of clean artifacts by
     * the overall amount of clean artifacts.
     *

     *
     * @param data test data set
     * @param efforts effort list from the test data set
     * @return Effort of the largest percentile of clean artifacts by overall amount of clean artifacts.
     */
    public static double getProp1Clean(Instances data, List<Double> efforts) {
        List<Double> effortClean = new ArrayList<>();
        int amountCleanArtifacts = 0;
        for (int i = 0; i < data.size(); i++){
            if (data.get(i).classValue() < 1.0) {
                amountCleanArtifacts += 1;
                effortClean.add(efforts.get(i));
            }
        }
        effortClean.sort(Collections.reverseOrder());
        int percentileIndex = (int)Math.ceil(effortClean.size() / 100.0);
        double largestPercentileEffort = 0.0;
        for (int i = 0; i < percentileIndex; i++){
            largestPercentileEffort += effortClean.get(i);
        }
        return largestPercentileEffort / (double)amountCleanArtifacts;
    }
}


text:
var Calendar = RightJS.Calendar = (function(document, parseInt, RightJS) {
%{source_code}

return Calendar;
})(document, parseInt, RightJS);


text:
#ifndef DANGERENGINE_SLSTRACKBALL_H
#define DANGERENGINE_SLSTRACKBALL_H

#include <kazmath/kazmath.h>
#include <math/math-types.h>

typedef struct slsTrackball slsTrackball;

struct slsTrackball {
  kmQuaternion rotation;
  float radius;
  float rotation_speed;

  kmMat4 rotation_mat;
};

kmQuaternion* sls_trackball_calc_quat(kmQuaternion* out,
                                      float trackball_radius,
                                      float trackball_speed,
                                      kmVec2 const* p1,
                                      kmVec2 const* p2);

void sls_trackball_set(slsTrackball* t, kmVec2 p1, kmVec2 p2);

slsTrackball* sls_trackball_init(slsTrackball* self,
                                 float radius,
                                 float rotation_speed);

static inline slsTrackball* sls_trackball_init_default(slsTrackball* self)
{
  return sls_trackball_init(self, 0.8, 2.0);
}

void sls_trackball_drag(slsTrackball* ball,
                        slsIPoint start_point,
                        slsIPoint second_point,
                        slsIPoint window_size);

#endif // DANGERENGINE_SLSTRACKBALL_H


text:
define(function () {
    var Util = {};

    Util.format = function (format) {
        var ret = format;
        for (var index in arguments) {
            if (index == 0) continue;
            ret = ret.replace("{" + (index - 1) + "}", arguments[index]);
        }
        return ret;
    };

    Util.startsWith = function (str, prefix) {
        return str.indexOf(prefix) === 0;
    };

    Util.endsWith = function (str, suffix) {
        return str.indexOf(suffix, str.length - suffix.length) !== -1;
    };

    Util.size = function (iterable) {
        if (iterable == null) return 0;
        if (iterable.length === parseInt(iterable.length)) return iterable.length;
        if (Object.keys) return Object.keys(iterable).length;

        var size = 0;
        for (var key in iterable) {
            if (iterable.hasOwnProperty(key)) size++;
        }
        return size;
    };

    Util.urlFor = function (source, dir) {
        var isAbsolutePath = Util.startsWith(source, "http") || Util.startsWith(source, "/");
        return isAbsolutePath ? source : (dir || ".") + "/" + source;
    }

    return Util;
});


text:
import base64
import json

from eventlet.green import urllib2
from celery import task

try:
    import celeryconfig
    token = celeryconfig.MIXPANEL_API_TOKEN
except:
    from django.conf import settings
    token = settings.MIXPANEL_API_TOKEN

@task(ignore_result=True)
def track(event, properties=None):
    if properties is None:
        properties = {}

    if 'token' not in properties:
        properties['token'] = token

    params = {'event': event, 'properties': properties}
    data = base64.b64encode(json.dumps(params))
    url = 'http://api.mixpanel.com/track/?data=' + data
    urllib2.urlopen(url)


text: google-site-verification: google143f61088b6c613f.html