text:
<?php

namespace Johnnymn\Sim\Roles\Contracts;

interface PermissionHasRelations
{
    /**
     * Permission belongs to many roles.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function roles();

    /**
     * Permission belongs to many users.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function users();
}

redpajama_set_name: RedPajamaGithub


text:
#include <inviwo/core/datastructures/representationutil.h>

#include <inviwo/core/datastructures/buffer/buffer.h>
#include <inviwo/core/datastructures/image/layer.h>
#include <inviwo/core/datastructures/volume/volume.h>
#include <inviwo/core/datastructures/volume/volumeramprecision.h>
#include <inviwo/core/datastructures/volume/volumeramconverter.h>
#include <inviwo/core/datastructures/image/layerramprecision.h>
#include <inviwo/core/datastructures/image/layerramconverter.h>
#include <inviwo/core/datastructures/buffer/bufferramprecision.h>

#include <inviwo/core/datastructures/representationfactory.h>
#include <inviwo/core/datastructures/representationfactoryobject.h>
#include <inviwo/core/datastructures/representationconverterfactory.h>

#include <inviwo/core/common/inviwomodule.h>
#include <inviwo/core/datastructures/representationfactorymanager.h>

namespace inviwo {

namespace util {

namespace {

class BufferRAMFactoryObject
    : public RepresentationFactoryObjectTemplate<BufferRepresentation, BufferRAM> {
public:
    virtual std::unique_ptr<BufferRepresentation> create(
        const typename BufferRepresentation::ReprOwner* buffer) {
        return dispatching::dispatch<std::unique_ptr<BufferRepresentation>,
                                     dispatching::filter::All>(buffer->getDataFormat()->getId(),
                                                               Dispatcher{}, buffer);
    }

private:
    struct Dispatcher {
        template <typename Result, typename Format>
        Result operator()(const BufferBase* buffer) {
            switch (buffer->getBufferTarget()) {
                case BufferTarget::Index:
                    return std::make_unique<
                        BufferRAMPrecision<typename Format::type, BufferTarget::Index>>(
                        buffer->getSize(), buffer->getBufferUsage());

                case BufferTarget::Data:
                default:
                    return std::make_unique<
                        BufferRAMPrecision<typename Format::type, BufferTarget::Data>>(
                        buffer->getSize(), buffer->getBufferUsage());
            }
        }
    };
};

class LayerRAMFactoryObject
    : public RepresentationFactoryObjectTemplate<LayerRepresentation, LayerRAM> {
public:
    virtual std::unique_ptr<LayerRepresentation> create(
        const typename LayerRepresentation::ReprOwner* layer) {
        return dispatching::dispatch<std::unique_ptr<LayerRepresentation>,
                                     dispatching::filter::All>(layer->getDataFormat()->getId(),
                                                               Dispatcher{}, layer);
    }

private:
    struct Dispatcher {
        template <typename Result, typename Format>
        Result operator()(const Layer* layer) {
            return std::make_unique<LayerRAMPrecision<typename Format::type>>(
                layer->getDimensions(), layer->getLayerType(), layer->getSwizzleMask(),
                layer->getInterpolation(), layer->getWrapping());
        }
    };
};

class VolumeRAMFactoryObject
    : public RepresentationFactoryObjectTemplate<VolumeRepresentation, VolumeRAM> {
public:
    virtual std::unique_ptr<VolumeRepresentation> create(
        const typename VolumeRepresentation::ReprOwner* volume) {
        return dispatching::dispatch<std::unique_ptr<VolumeRepresentation>,
                                     dispatching::filter::All>(volume->getDataFormat()->getId(),
                                                               Dispatcher{}, volume);
    }

private:
    struct Dispatcher {
        template <typename Result, typename Format>
        Result operator()(const Volume* volume) {
            return std::make_unique<VolumeRAMPrecision<typename Format::type>>(
                volume->getDimensions(), volume->getSwizzleMask(), volume->getInterpolation(),
                volume->getWrapping());
        }
    };
};

template <typename T>
void registerCoreRepresentationsHelper(T& obj) {

    // Register representation Factories
    obj.registerRepresentationFactory(
        std::make_unique<RepresentationFactory<BufferRepresentation>>(typeid(BufferRAM)));
    obj.registerRepresentationFactory(
        std::make_unique<RepresentationFactory<LayerRepresentation>>(typeid(LayerRAM)));
    obj.registerRepresentationFactory(
        std::make_unique<RepresentationFactory<VolumeRepresentation>>(typeid(VolumeRAM)));

    // Register RAM Representations
    obj.template registerRepresentationFactoryObject<BufferRepresentation>(
        std::make_unique<BufferRAMFactoryObject>());
    obj.template registerRepresentationFactoryObject<LayerRepresentation>(
        std::make_unique<LayerRAMFactoryObject>());
    obj.template registerRepresentationFactoryObject<VolumeRepresentation>(
        std::make_unique<VolumeRAMFactoryObject>());

    // Register Converter Factories
    obj.registerRepresentationConverterFactory(
        std::make_unique<RepresentationConverterFactory<VolumeRepresentation>>());
    obj.registerRepresentationConverterFactory(
        std::make_unique<RepresentationConverterFactory<LayerRepresentation>>());
    obj.registerRepresentationConverterFactory(
        std::make_unique<RepresentationConverterFactory<BufferRepresentation>>());

    // Register Converters
    obj.template registerRepresentationConverter<VolumeRepresentation>(
        std::make_unique<VolumeDisk2RAMConverter>());
    obj.template registerRepresentationConverter<LayerRepresentation>(
        std::make_unique<LayerDisk2RAMConverter>());
}

}  // namespace

void registerCoreRepresentations(InviwoModule& obj) { registerCoreRepresentationsHelper(obj); }

void registerCoreRepresentations(RepresentationFactoryManager& obj) {
    registerCoreRepresentationsHelper(obj);
}

}  // namespace util

}  // namespace inviwo


text:
ALTER TABLE worker_resource_caches
    DROP CONSTRAINT worker_resource_caches_worker_base_resource_type_id_fkey;

ALTER TABLE worker_resource_caches
    ADD CONSTRAINT worker_resource_caches_worker_base_resource_type_id_fkey
        FOREIGN KEY (worker_base_resource_type_id) REFERENCES worker_base_resource_types(id)
            ON DELETE CASCADE;


text:
module SeedSnapshot
  class TestCase < Minitest::Test
    def setup
    end

    def teardown
      SQLCounter.clear_log
    end

    def capture_sql
      SQLCounter.clear_log
      yield
      SQLCounter.log_all.dup
    end
  end

  class SQLCounter
    class << self
      attr_accessor :ignored_sql, :log, :log_all
      def clear_log; self.log = []; self.log_all = []; end
    end

    self.clear_log

    self.ignored_sql = [/^PRAGMA/, /^SELECT currval/, /^SELECT CAST/, /^SELECT @@IDENTITY/, /^SELECT @@ROWCOUNT/, /^SAVEPOINT/, /^ROLLBACK TO SAVEPOINT/, /^RELEASE SAVEPOINT/, /^SHOW max_identifier_length/, /^BEGIN/, /^COMMIT/]

    # FIXME: this needs to be refactored so specific database can add their own
    # ignored SQL, or better yet, use a different notification for the queries
    # instead examining the SQL content.
    oracle_ignored     = [/^select .*nextval/i, /^SAVEPOINT/, /^ROLLBACK TO/, /^\s*select .* from all_triggers/im, /^\s*select .* from all_constraints/im, /^\s*select .* from all_tab_cols/im]
    mysql_ignored      = [/^SHOW TABLES/i, /^SHOW FULL FIELDS/, /^SHOW CREATE TABLE /i, /^SHOW VARIABLES /]
    postgresql_ignored = [/^\s*select\b.*\bfrom\b.*pg_namespace\b/im, /^\s*select tablename\b.*from pg_tables\b/im, /^\s*select\b.*\battname\b.*\bfrom\b.*\bpg_attribute\b/im, /^SHOW search_path/i]
    sqlite3_ignored =    [/^\s*SELECT name\b.*\bFROM sqlite_master/im]

    [oracle_ignored, mysql_ignored, postgresql_ignored, sqlite3_ignored].each do |db_ignored_sql|
      ignored_sql.concat db_ignored_sql
    end

    attr_reader :ignore

    def initialize(ignore = Regexp.union(self.class.ignored_sql))
      @ignore = ignore
    end

    def call(name, start, finish, message_id, values)
      sql = values[:sql]

      # FIXME: this seems bad. we should probably have a better way to indicate
      # the query was cached
      return if 'CACHE' == values[:name]

      self.class.log_all << sql
      self.class.log << sql unless ignore =~ sql
    end
  end

  ActiveSupport::Notifications.subscribe('sql.active_record', SQLCounter.new)
end


text:
package tr.edu.firat.ceng.aml.assignments.decisiontree.tree.impl;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;

/**
 *
 * @author Muhammed Olgun <141129113@ogrenci.firat.edu.tr>
 */
public class GiniGainImplTest {

    public GiniGainImplTest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    /**
     * Test of getGain method, of class GiniGainImpl.
     */
    @org.junit.Test
    public void testGetGain() {

    }
}


text: #import "PineBoard-Structs.h"


text:
"""
             LUFA Library
     Copyright (C) Dean Camera, 2014.

  dean [at] fourwalledcubicle [dot] com
           www.lufa-lib.org
"""

"""
    Front-end configuration app for the TempDataLogger project. This script
    configures the logger to the current system time and date, with a user
    defined logging interval.

    The logging interval should be specified in milliseconds and is rounded to
    a multiple of 500ms.

    Usage:
        python temp_log_config.py <Log_Interval>

    Example:
        python temp_log_config.py 500

    Requires the pywinusb library (https://pypi.python.org/pypi/pywinusb/).
"""

import sys
from datetime import datetime
import pywinusb.hid as hid

# Generic HID device VID, PID and report payload length (length is increased
# by one to account for the Report ID byte that must be pre-pended)
device_vid = 0x03EB
device_pid = 0x2063
report_length = 1 + 7

def get_hid_device_handle():
    hid_device_filter = hid.HidDeviceFilter(vendor_id=device_vid,
                                            product_id=device_pid)

    valid_hid_devices = hid_device_filter.get_devices()

    if len(valid_hid_devices) is 0:
        return None
    else:
        return valid_hid_devices[0]

def configure_temp_log_device(device, time_date, log_interval_500ms):
    # Report data for the demo is the report ID (always zero)
    report_data = [0]

    # Followed by the time/date data
    report_data.extend([time_date.hour, time_date.minute,
                        time_date.second, time_date.day,
                        time_date.month, time_date.year - 2000])

    # Lastly the log interval in 500ms units of time
    report_data.extend([log_interval_500ms])

    # Zero-extend the array to the length the report should be
    report_data.extend([0] * (report_length - len(report_data)))

    # Send the generated report to the device
    device.send_output_report(report_data)

def main(time_date, log_interval_500ms):
    hid_device = get_hid_device_handle()

    if hid_device is None:
        print("No valid HID device found.")
        sys.exit(1)

    try:
        hid_device.open()

        print("Connected to device 0x%04X/0x%04X - %s [%s]" %
              (hid_device.vendor_id, hid_device.product_id,
               hid_device.product_name, hid_device.vendor_name))

        configure_temp_log_device(hid_device, time_date, log_interval_500ms)

        print("Time/Date is now set to %s" % time_date)
        print("Log interval is now set to every %0.1fs" % (log_interval_500ms * (500.0 / 1000.0)))

    finally:
        hid_device.close()

if __name__ == '__main__':
    time_date = datetime.now()
    log_interval_500ms = (int(sys.argv[1]) / 500) if len(sys.argv) > 1 else 2

    # Clamp the log interval to the allowable range
    log_interval_500ms = max(log_interval_500ms, 0x01)
    log_interval_500ms = min(log_interval_500ms, 0xFF)

    main(time_date, log_interval_500ms)


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.gudnam.bringluck.util.AnimatedExpandableListView
        android:id="@+id/lv_mypage"
		android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="9"
		android:layout_gravity="left"
		android:dividerHeight="0dp"
		android:divider="@android:color/transparent" />

    <com.google.android.gms.ads.AdView
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/ad_mypage"
        android:layout_width="match_parent"
        android:layout_height="0dip"
		android:layout_weight="1"
        ads:adSize="SMART_BANNER"
        ads:adUnitId="ca-app-pub-8412113653981763/7149818335" />
</LinearLayout>


text:
using System;
using Microsoft.Reactive.Testing;

namespace Shoutr.Tests
{
    public static class TestSchedulerExtensions
    {
        public static void AdvanceBy(this TestScheduler testScheduler, TimeSpan timeSpan)
        {
            testScheduler.AdvanceBy(timeSpan.Ticks);
        }
    }
}


text:
package influent.server.clustering;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.avro.AvroRemoteException;

import com.oculusinfo.ml.DataSet;
import com.oculusinfo.ml.Instance;
import com.oculusinfo.ml.feature.spatial.GeoSpatialFeature;
import com.oculusinfo.ml.feature.spatial.centroid.FastGeoSpatialCentroid;
import com.oculusinfo.ml.feature.spatial.distance.HaversineDistance;
import com.oculusinfo.ml.unsupervised.cluster.BaseClusterer;
import com.oculusinfo.ml.unsupervised.cluster.Cluster;
import com.oculusinfo.ml.unsupervised.cluster.ClusterResult;
import com.oculusinfo.ml.unsupervised.cluster.dpmeans.DPMeans;
import influent.idl.FL_Cluster;
import influent.idl.FL_ContinentCode;
import influent.idl.FL_Country;
import influent.idl.FL_DistributionRange;
import influent.idl.FL_Entity;
import influent.idl.FL_Frequency;
import influent.idl.FL_GeoData;
import influent.idl.FL_Geocoding;
import influent.idl.FL_PropertyTag;
import influent.idl.FL_PropertyType;
import influent.idlhelper.ClusterHelper;
import influent.idlhelper.EntityHelper;
import influent.idlhelper.PropertyHelper;
import influent.server.clustering.utils.EntityClusterFactory;

public class GeoEntityClusterer extends BaseEntityClusterer {
	private FL_Geocoding geoCoder;
	private GEO_LEVEL level;

	public enum GEO_LEVEL {
		Continent,
		Region,
		Country,
		LatLon
	}

	@Override
	public void init(Object[] args) {
		try {
			clusterFactory = (EntityClusterFactory)args[0];
			clusterField = (String)args[1];
			geoCoder = (FL_Geocoding)args[2];
			level = (GEO_LEVEL)args[3];
		 }
		 catch (Exception e) {
			 throw new IllegalArgumentException("Invalid initialization parameters.", e);
		 }
	}

	private String toGeoKey(FL_GeoData geo) {
		String key = "Unknown";

		try {
			List<FL_Country> country = null;
			switch (level) {
			case Continent:
				country = geoCoder.getCountries(Collections.singletonList(geo));
				if (country != null && !country.isEmpty() && country.get(0) != null) {
					FL_ContinentCode continent = country.get(0).getContinent();
					if (continent != null && !continent.name().isEmpty()) {
						key = continent.name();
					}
				}
				break;
			case Region:
				country = geoCoder.getCountries(Collections.singletonList(geo));
				if (country != null && !country.isEmpty() && country.get(0) != null) {
					String region = country.get(0).getRegion();
					if (region != null && !region.isEmpty()) {
						key = country.get(0).getRegion();
					}
				}
				break;
			case Country:
				String cc = geo.getCc();
				if (cc != null && !cc.isEmpty()) {
					key = cc;
				}
				break;
			default:
				break;
			}
		} catch (AvroRemoteException e) {
			log.error("Cluster geo field is not a valid FL_GeoData object! Ignoring.");
		}
		return key;
	}

	@Override
	protected String getBucketKey(FL_Cluster cluster, ClusterContext context) {
		String key = "Unknown";

		PropertyHelper prop = getFirstProperty(cluster, FL_PropertyType.GEO.name());
		if (prop != null) {
			@SuppressWarnings("unchecked")
			List<FL_Frequency> dist = (List<FL_Frequency>)prop.getValue();
			if (!dist.isEmpty()) {
				FL_Frequency freq = dist.get(0);
				FL_GeoData geo = (FL_GeoData)freq.getRange();
				key = toGeoKey(geo);
			}
		}
		return key;
	}

	@Override
	protected String getBucketKey(FL_Entity entity) {
		String key = "UNKNOWN";

		PropertyHelper prop = getFirstProperty(entity, clusterField);
		if (prop != null) {
			FL_GeoData geo = (FL_GeoData)prop.getValue();
			key = toGeoKey(geo);
		}
		return key;
	}

	private Instance createInstance(String id, FL_GeoData geo) {
		Instance inst = new Instance(id);

		double lat = 0.0, lon = 0.0;

		// sanity check
		if (geo != null && geo.getLat() != null && geo.getLon() != null) {
			lat = geo.getLat();
			lon = geo.getLon();
		}

		GeoSpatialFeature feature = new GeoSpatialFeature("geo");
		feature.setValue(lat, lon);
		inst.addFeature( feature );

		return inst;
	}

	private FL_GeoData getGeoValue(PropertyHelper property) {
		FL_GeoData geo = null;

		// try to read the latitude and longitude of the entity
		if (property != null && property.getRange() != null) {
			if (property.getRange() instanceof FL_DistributionRange) {
				@SuppressWarnings("unchecked")
				List<FL_Frequency> dist = (List<FL_Frequency>)property.getValue();
				if (!dist.isEmpty()) {
					FL_Frequency freq = dist.get(0);
					geo = (FL_GeoData) freq.getRange();
				}
			}
			else {
				geo = (FL_GeoData) property.getValue();
			}

			// if the geo property is missing valid lat/long try to use the latitude and longitude of the country
			if (geo == null || geo.getLat() == null || geo.getLon() == null || (geo.getLat() == 0 && geo.getLon() == 0)) {
				try {
					List<FL_Country> countries = geoCoder.getCountries(Collections.singletonList(geo));
					if (!countries.isEmpty()) {
						FL_Country country = countries.get(0);
						if (country != null) {
							geo = country.getCountry();
						}
					}
				} catch (AvroRemoteException e) { /* ignore */ }
			}
		}

		// No valid geo info could be found - dummy in a default to cluster this entity
		if (geo == null) {
			geo = new FL_GeoData("Unknown", 0.0, 0.0, "");
		}
		return geo;
	}

	private DataSet createDataSet(Collection<FL_Entity> entities,
								  Collection<FL_Cluster> immutableClusters) {
		DataSet ds = new DataSet();

		for (FL_Entity entity : entities) {
			PropertyHelper prop = EntityHelper.getFirstPropertyByTag(entity, FL_PropertyTag.GEO);
			FL_GeoData geo = getGeoValue(prop);

			if (geo != null) {
				Instance inst = createInstance(entity.getUid(), geo);
				ds.add(inst);
			}
		}
		for (FL_Cluster immutableCluster : immutableClusters) {
			PropertyHelper prop = getFirstProperty(immutableCluster, FL_PropertyType.GEO.name());
			FL_GeoData geo = getGeoValue(prop);

			if (geo != null) {
				Instance inst = createInstance(immutableCluster.getUid(), geo);
				ds.add(inst);
			}
		}
		return ds;
	}

	private BaseClusterer createGeoClusterer() {
		DPMeans clusterer = new DPMeans(3, true);
		clusterer.setThreshold(0.01);
		clusterer.registerFeatureType("geo", FastGeoSpatialCentroid.class, new HaversineDistance(1.0));
		return clusterer;
	}

	@SuppressWarnings("unchecked")
	private Map<String, FL_Cluster> clusterByLatLon(Collection<FL_Entity> entities,
													Collection<FL_Cluster> immutableClusters,
													Collection<FL_Cluster> clusters) {
		// Haversine clustering
		Map<String, FL_Entity> entityIndex = createEntityIndex(entities);
		Map<String, FL_Cluster> immutableClusterIndex = createClusterIndex(immutableClusters);
		Map<String, FL_Cluster> clusterIndex = createClusterIndex(clusters);

		DataSet ds = createDataSet(entities, immutableClusters);

		BaseClusterer clusterer = createGeoClusterer();

		List<Cluster> existingClusters = new LinkedList<Cluster>();

		for (FL_Cluster cluster : clusters) {
			PropertyHelper prop = getFirstProperty(cluster, FL_PropertyType.GEO.name());
			if (prop != null) {
				List<FL_Frequency> dist = (List<FL_Frequency>)prop.getValue();

				double lat = 0, lon = 0;
				for (FL_Frequency freq : dist) {
					FL_GeoData geo = (FL_GeoData)freq.getRange();
					lat += geo.getLat();
					lon += geo.getLon();
				}
				lat /= dist.size();
				lon /= dist.size();

				Cluster c = clusterer.createCluster();
				c.setId(cluster.getUid());
				GeoSpatialFeature feature = new GeoSpatialFeature("geo");
				feature.setValue(lat, lon);
				c.addFeature(feature);
				existingClusters.add(c);
			}
		}

		ClusterResult rs = clusterer.doIncrementalCluster(ds, existingClusters);

		// clean up
		clusterer.terminate();

		Map<String, FL_Cluster> modifiedClusters = new HashMap<String, FL_Cluster>();

		for (Cluster c : rs) {
			List<FL_Cluster> subClusters = new LinkedList<FL_Cluster>();
			List<FL_Entity> members = new LinkedList<FL_Entity>();

			for (Instance inst : c.getMembers()) {
				String id = inst.getId();
				if (entityIndex.containsKey(id)) {
					members.add( entityIndex.get(inst.getId()) );
				}
				else if (immutableClusterIndex.containsKey(id)){
					subClusters.add( immutableClusterIndex.get(id) );
				}
			}
			FL_Cluster cluster = clusterIndex.get(c.getId());
			if (cluster == null) {
				cluster = clusterFactory.toCluster(members, subClusters);
			}
			else {
				ClusterHelper.addMembers(cluster, members);
				EntityClusterFactory.setEntityCluster(members, cluster);

				for (FL_Cluster subCluster : subClusters) {
					ClusterHelper.addSubCluster(cluster, subCluster);
					subCluster.setParent(cluster.getUid());
				}
			}
			modifiedClusters.put(cluster.getUid(), cluster);
		}
		return modifiedClusters;
	}

	@Override
	public ClusterContext clusterEntities(Collection<FL_Entity> entities,
										  Collection<FL_Cluster> immutableClusters,
										  Collection<FL_Cluster> clusters,
										  ClusterContext context) {

		if (level != GEO_LEVEL.LatLon) {
			return super.clusterEntities(entities, immutableClusters, clusters, context);
		}

		// Cluster by latitude and longitude
		Map<String, FL_Cluster> modifiedClusters = clusterByLatLon(entities, immutableClusters, clusters);

		ClusterContext result = new ClusterContext();
		result.roots.putAll(modifiedClusters);
		result.clusters.putAll(modifiedClusters);

		return result;
	}
}


text:
Code sample for post about custom segues in iOS from [http://beardforhire.com/blog/super-simple-custom-segues](http://beardforhire.com/blog/super-simple-custom-segues).

Comments? Questions? Contact me on Twitter [@beardforhire](http://twitter.com/beardforhire).


text:
layout: page
title: Introduction
description: "The introduction to the first project"
image:
  feature: abstract-10.jpg
  credit: dargadgetz
  creditlink: http://www.dargadgetz.com/ios-7-abstract-wallpaper-pack-for-iphone-5-and-ipod-touch-retina/
share: true
comments: true
---
Lorem ipsum

dolor sit amet, consectetur adipiscing elit. Suspendisse in fringilla purus. Phasellus quis ultrices mauris, ac condimentum tellus. Vestibulum condimentum tristique erat, eget ullamcorper enim. Praesent ante ante, placerat a venenatis a, dictum at ipsum. Nam vitae sodales lorem, vitae congue lacus. Sed pellentesque, eros sit amet tristique molestie, tellus quam congue risus, rhoncus dictum nibh orci ut massa. Vivamus interdum erat ipsum, sit amet vulputate risus semper at. Vestibulum odio arcu, scelerisque id eros in, elementum ornare felis. Integer nec lectus et turpis ultricies gravida vitae nec est. Nulla non aliquam arcu, id vehicula dolor. Cras vitae dolor tortor. Curabitur dapibus auctor dolor, eget feugiat ligula vulputate eget.

Go to task


text:
package net.sansa_stack.inference.utils

/**
  * A 0-tuple.
  *
  * @author Lorenz Buehmann
  */
object Tuple0 extends AnyRef with Product with Serializable{
  def productArity: Int = 0

  def productElement(n: Int): Any = throw new IllegalStateException("No element")

  def canEqual(that: Any): Boolean = false

  override def toString: String = "(_)"
}


text:
package com.intellij.codeInsight.daemon.quickFix;

import com.intellij.codeInsight.daemon.impl.HighlightInfo;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.ide.highlighter.XmlFileType;
import com.intellij.javaee.ExternalResourceManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase;
import com.intellij.xml.XmlBundle;

import java.util.List;

/**
 * @author Dmitry Avdeev
 */
public class RealFetchTest extends LightPlatformCodeInsightFixtureTestCase {

  public void testFetchDtd() throws Exception {

    final String url = "http://helpserver.labs.intellij.net/help/images.dtd";
    assertEquals(url, ExternalResourceManager.getInstance().getResourceLocation(url, getProject()));
    myFixture.configureByText(XmlFileType.INSTANCE, "<!DOCTYPE images SYSTEM \"http://helpserver.labs.intellij.net/help/ima<caret>ges.dtd\">");
    IntentionAction intention = myFixture.getAvailableIntention(XmlBundle.message("fetch.external.resource"));
    assertNotNull(intention);
    intention.invoke(getProject(), myFixture.getEditor(), myFixture.getFile());
    assertNotSame(url, ExternalResourceManager.getInstance().getResourceLocation(url, getProject()));
    ApplicationManager.getApplication().runWriteAction(() -> ExternalResourceManager.getInstance().removeResource(url));
  }

  public void testOverwriteFetchDtd() throws Exception {

    final String url = "http://helpserver.labs.intellij.net/help/images.dtd";
    VirtualFile virtualFile = myFixture.getTempDirFixture().createFile("images.dtd", "");
    ApplicationManager.getApplication().runWriteAction(() -> ExternalResourceManager.getInstance().addResource(url, virtualFile.getPath()));

    myFixture.configureByText(XmlFileType.INSTANCE, "<!DOCTYPE images SYSTEM \"<error descr=\"Resource registered by this uri is not recognized (Settings | Languages & Frameworks | Schemas and DTDs)\">http://helpserver.labs.intellij.net/help/ima<caret>ges.dtd</error>\"><images> </images>");
    myFixture.testHighlighting();
    IntentionAction intention = myFixture.getAvailableIntention(XmlBundle.message("fetch.external.resource"));
    assertNotNull(intention);
    intention.invoke(getProject(), myFixture.getEditor(), myFixture.getFile());
    List<HighlightInfo> infos = myFixture.doHighlighting();
    assertEmpty(infos);
    ApplicationManager.getApplication().runWriteAction(() -> ExternalResourceManager.getInstance().removeResource(url));
  }
}


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class org.apache.http.cookie.MalformedCookieException (HttpComponents Client 4.1.1 API)
</TITLE>

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

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.http.cookie.MalformedCookieException

Packages that use MalformedCookieException

org.apache.http.cookie
The API for client-side state management via cookies.

org.apache.http.impl.cookie
Default implementations for interfaces in
org.apache.http.cookie.

Uses of MalformedCookieException in org.apache.http.cookie

Subclasses of MalformedCookieException in org.apache.http.cookie

 class
CookieRestrictionViolationException

          Signals that a cookie violates a restriction imposed by the cookie
 specification.

Methods in org.apache.http.cookie that throw MalformedCookieException

 List<Cookie>
CookieSpec.parse(Header header,
      CookieOrigin origin)

          Parse the <tt>"Set-Cookie"</tt> Header into an array of Cookies.

 void
CookieAttributeHandler.parse(SetCookie cookie,
      String value)

          Parse the given cookie attribute value and update the corresponding
 Cookie property.

 void
CookieAttributeHandler.validate(Cookie cookie,
         CookieOrigin origin)

          Peforms cookie validation for the given attribute value.

 void
CookieSpec.validate(Cookie cookie,
         CookieOrigin origin)

          Validate the cookie according to validation rules defined by the
  cookie specification.

Uses of MalformedCookieException in org.apache.http.impl.cookie

Methods in org.apache.http.impl.cookie that throw MalformedCookieException

 List<Cookie>
BestMatchSpec.parse(Header header,
      CookieOrigin origin)

 List<Cookie>
BrowserCompatSpec.parse(Header header,
      CookieOrigin origin)

 List<Cookie>
IgnoreSpec.parse(Header header,
      CookieOrigin origin)

 List<Cookie>
RFC2109Spec.parse(Header header,
      CookieOrigin origin)

 List<Cookie>
RFC2965Spec.parse(Header header,
      CookieOrigin origin)

 List<Cookie>
NetscapeDraftSpec.parse(Header header,
      CookieOrigin origin)

          Parses the Set-Cookie value into an array of <tt>Cookie</tt>s.

protected  List<Cookie>
CookieSpecBase.parse(HeaderElement[] elems,
      CookieOrigin origin)

protected  List<Cookie>
RFC2965Spec.parse(HeaderElement[] elems,
      CookieOrigin origin)

 void
BasicCommentHandler.parse(SetCookie cookie,
      String value)

 void
RFC2965PortAttributeHandler.parse(SetCookie cookie,
      String portValue)

          Parse cookie port attribute.

 void
BasicSecureHandler.parse(SetCookie cookie,
      String value)

 void
RFC2965DomainAttributeHandler.parse(SetCookie cookie,
      String domain)

          Parse cookie domain attribute.

 void
BasicMaxAgeHandler.parse(SetCookie cookie,
      String value)

 void
RFC2965CommentUrlAttributeHandler.parse(SetCookie cookie,
      String commenturl)

 void
RFC2109DomainHandler.parse(SetCookie cookie,
      String value)

 void
RFC2109VersionHandler.parse(SetCookie cookie,
      String value)

 void
PublicSuffixFilter.parse(SetCookie cookie,
      String value)

 void
BasicDomainHandler.parse(SetCookie cookie,
      String value)

 void
BasicPathHandler.parse(SetCookie cookie,
      String value)

 void
RFC2965VersionAttributeHandler.parse(SetCookie cookie,
      String value)

          Parse cookie version attribute.

 void
RFC2965DiscardAttributeHandler.parse(SetCookie cookie,
      String commenturl)

 void
BasicExpiresHandler.parse(SetCookie cookie,
      String value)

 void
BestMatchSpec.validate(Cookie cookie,
         CookieOrigin origin)

 void
RFC2965PortAttributeHandler.validate(Cookie cookie,
         CookieOrigin origin)

          Validate cookie port attribute.

 void
RFC2965DomainAttributeHandler.validate(Cookie cookie,
         CookieOrigin origin)

          Validate cookie domain attribute.

 void
RFC2965CommentUrlAttributeHandler.validate(Cookie cookie,
         CookieOrigin origin)

 void
RFC2109DomainHandler.validate(Cookie cookie,
         CookieOrigin origin)

 void
RFC2109VersionHandler.validate(Cookie cookie,
         CookieOrigin origin)

 void
NetscapeDomainHandler.validate(Cookie cookie,
         CookieOrigin origin)

 void
PublicSuffixFilter.validate(Cookie cookie,
         CookieOrigin origin)

 void
RFC2109Spec.validate(Cookie cookie,
         CookieOrigin origin)

 void
CookieSpecBase.validate(Cookie cookie,
         CookieOrigin origin)

 void
BasicDomainHandler.validate(Cookie cookie,
         CookieOrigin origin)

 void
RFC2965Spec.validate(Cookie cookie,
         CookieOrigin origin)

 void
BasicPathHandler.validate(Cookie cookie,
         CookieOrigin origin)

 void
RFC2965VersionAttributeHandler.validate(Cookie cookie,
         CookieOrigin origin)

          validate cookie version attribute.

 void
RFC2965DiscardAttributeHandler.validate(Cookie cookie,
         CookieOrigin origin)

 void
AbstractCookieAttributeHandler.validate(Cookie cookie,
         CookieOrigin origin)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 1999-2011 The Apache Software Foundation. All Rights Reserved.


text:
package org.jboss.resteasy.test.providers.multipart;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataOutput;
import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
import org.jboss.resteasy.test.providers.multipart.resource.HeaderFlushedOutputStreamBean;
import org.jboss.resteasy.test.providers.multipart.resource.HeaderFlushedOutputStreamService;
import org.jboss.resteasy.utils.PortProviderUtil;
import org.jboss.resteasy.utils.TestUtil;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;

import javax.mail.BodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;

/**
 * @tpSubChapter Multipart provider
 * @tpChapter Integration tests
 * @tpTestCaseDetails Regression test for RESTEASY-190
 * @tpSince RESTEasy 3.0.16
 */
@RunWith(Arquillian.class)
@RunAsClient
public class HeaderFlushedOutputStreamTest {
    static Client client;

    @BeforeClass
    public static void before() throws Exception {
        client = ClientBuilder.newClient();
    }

    @AfterClass
    public static void after() throws Exception {
        client.close();
    }

    static final String testFilePath;

    static {
        testFilePath = TestUtil.getResourcePath(HeaderFlushedOutputStreamTest.class,
                "HeaderFlushedOutputStreamTestData.txt");
    }

    @Deployment
    public static Archive<?> deploy() {
        WebArchive war = TestUtil.prepareArchive(HeaderFlushedOutputStreamTest.class.getSimpleName());
        war.addClass(HeaderFlushedOutputStreamBean.class);
        return TestUtil.finishContainerPrepare(war, null, HeaderFlushedOutputStreamService.class);
    }

    private static String generateURL(String path) {
        return PortProviderUtil.generateURL(path, HeaderFlushedOutputStreamTest.class.getSimpleName());
    }

    private static final String TEST_URI = generateURL("/mime");

    /**
     * @tpTestDetails Loopback to examine form-data
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testPost() throws Exception {
        // prepare file
        File file = new File(testFilePath);
        Assert.assertTrue("File " + testFilePath + " doesn't exists", file.exists());
        // test logic
        MultipartOutput mpo = new MultipartOutput();
        mpo.addPart("This is Value 1", MediaType.TEXT_PLAIN_TYPE);
        mpo.addPart("This is Value 2", MediaType.TEXT_PLAIN_TYPE);
        mpo.addPart(file, MediaType.TEXT_PLAIN_TYPE);
        Response response = client.target(TEST_URI).request().post(Entity.entity(mpo, MediaType.MULTIPART_FORM_DATA_TYPE));
        BufferedInputStream in = new BufferedInputStream(response.readEntity(InputStream.class));
        String contentType = response.getHeaderString("content-type");
        ByteArrayDataSource ds = new ByteArrayDataSource(in, contentType);
        MimeMultipart mimeMultipart = new MimeMultipart(ds);
        Assert.assertEquals("Wrong count of parts of response", mimeMultipart.getCount(), 3);
        response.close();
    }

    /**
     * @tpTestDetails Test post method
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testPostForm() throws Exception {
        // prepare file
        File file = new File(testFilePath);
        Assert.assertTrue("File " + testFilePath + " doesn't exists", file.exists());
        // test logic
        MultipartFormDataOutput mpfdo = new MultipartFormDataOutput();
        mpfdo.addFormData("part1", "This is Value 1", MediaType.TEXT_PLAIN_TYPE);
        mpfdo.addFormData("part2", "This is Value 2", MediaType.TEXT_PLAIN_TYPE);
        mpfdo.addFormData("data.txt", file, MediaType.TEXT_PLAIN_TYPE);

        Response response = client.target(TEST_URI).request().post(Entity.entity(mpfdo, MediaType.MULTIPART_FORM_DATA_TYPE));
        BufferedInputStream in = new BufferedInputStream(response.readEntity(InputStream.class));

        String contentType = response.getHeaderString("content-type");
        ByteArrayDataSource ds = new ByteArrayDataSource(in, contentType);
        MimeMultipart mimeMultipart = new MimeMultipart(ds);
        Assert.assertEquals("Wrong count of parts of response", mimeMultipart.getCount(), 3);
        response.close();
    }

    /**
     * @tpTestDetails Test get method
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testGet() throws Exception {

        Response response = client.target(TEST_URI).request().get();

        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
        BufferedInputStream in = new BufferedInputStream(response.readEntity(InputStream.class));
        String contentType = response.getHeaderString("content-type");
        ByteArrayDataSource ds = new ByteArrayDataSource(in, contentType);
        MimeMultipart mimeMultipart = new MimeMultipart(ds);
        Assert.assertEquals("Wrong count of parts of response", mimeMultipart.getCount(), 1);

        BodyPart part = mimeMultipart.getBodyPart(0);
        InputStream is = part.getInputStream();

        Assert.assertEquals("Wrong count of parts of response", 3, part.getSize());

        char[] output = new char[3];
        output[0] = (char) is.read();
        output[1] = (char) is.read();
        output[2] = (char) is.read();
        String str = new String(output);
        Assert.assertEquals("Wrong content of first part of response", "bla", str);
    }
}


text:
"""Test the Plugwise config flow."""
from plugwise.exceptions import (
    ConnectionFailedError,
    InvalidAuthentication,
    PlugwiseException,
)
import pytest

from homeassistant import config_entries, data_entry_flow, setup
from homeassistant.components.plugwise.const import (
    DEFAULT_PORT,
    DEFAULT_SCAN_INTERVAL,
    DOMAIN,
)
from homeassistant.config_entries import SOURCE_USER, SOURCE_ZEROCONF
from homeassistant.const import (
    CONF_HOST,
    CONF_NAME,
    CONF_PASSWORD,
    CONF_PORT,
    CONF_SCAN_INTERVAL,
    CONF_USERNAME,
)

from tests.async_mock import MagicMock, patch
from tests.common import MockConfigEntry

TEST_HOST = "1.1.1.1"
TEST_HOSTNAME = "smileabcdef"
TEST_PASSWORD = "test_password"
TEST_PORT = 81
TEST_USERNAME = "smile"
TEST_USERNAME2 = "stretch"

TEST_DISCOVERY = {
    "host": TEST_HOST,
    "port": DEFAULT_PORT,
    "hostname": f"{TEST_HOSTNAME}.local.",
    "server": f"{TEST_HOSTNAME}.local.",
    "properties": {
        "product": "smile",
        "version": "1.2.3",
        "hostname": f"{TEST_HOSTNAME}.local.",
    },
}

@pytest.fixture(name="mock_smile")
def mock_smile():
    """Create a Mock Smile for testing exceptions."""
    with patch(
        "homeassistant.components.plugwise.config_flow.Smile",
    ) as smile_mock:
        smile_mock.PlugwiseError = PlugwiseException
        smile_mock.InvalidAuthentication = InvalidAuthentication
        smile_mock.ConnectionFailedError = ConnectionFailedError
        smile_mock.return_value.connect.return_value = True
        yield smile_mock.return_value

async def test_form(hass):
    """Test we get the form."""
    await setup.async_setup_component(hass, "persistent_notification", {})
    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": SOURCE_USER}
    )
    assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
    assert result["errors"] == {}

    with patch(
        "homeassistant.components.plugwise.config_flow.Smile.connect",
        return_value=True,
    ), patch(
        "homeassistant.components.plugwise.async_setup",
        return_value=True,
    ) as mock_setup, patch(
        "homeassistant.components.plugwise.async_setup_entry",
        return_value=True,
    ) as mock_setup_entry:
        result2 = await hass.config_entries.flow.async_configure(
            result["flow_id"],
            {CONF_HOST: TEST_HOST, CONF_PASSWORD: TEST_PASSWORD},
        )

    await hass.async_block_till_done()

    assert result2["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
    assert result2["data"] == {
        CONF_HOST: TEST_HOST,
        CONF_PASSWORD: TEST_PASSWORD,
        CONF_PORT: DEFAULT_PORT,
        CONF_USERNAME: TEST_USERNAME,
    }

    assert len(mock_setup.mock_calls) == 1
    assert len(mock_setup_entry.mock_calls) == 1

async def test_zeroconf_form(hass):
    """Test we get the form."""
    await setup.async_setup_component(hass, "persistent_notification", {})
    result = await hass.config_entries.flow.async_init(
        DOMAIN,
        context={"source": SOURCE_ZEROCONF},
        data=TEST_DISCOVERY,
    )
    assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
    assert result["errors"] == {}

    with patch(
        "homeassistant.components.plugwise.config_flow.Smile.connect",
        return_value=True,
    ), patch(
        "homeassistant.components.plugwise.async_setup",
        return_value=True,
    ) as mock_setup, patch(
        "homeassistant.components.plugwise.async_setup_entry",
        return_value=True,
    ) as mock_setup_entry:
        result2 = await hass.config_entries.flow.async_configure(
            result["flow_id"],
            {CONF_PASSWORD: TEST_PASSWORD},
        )

    await hass.async_block_till_done()

    assert result2["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
    assert result2["data"] == {
        CONF_HOST: TEST_HOST,
        CONF_PASSWORD: TEST_PASSWORD,
        CONF_PORT: DEFAULT_PORT,
        CONF_USERNAME: TEST_USERNAME,
    }

    assert len(mock_setup.mock_calls) == 1
    assert len(mock_setup_entry.mock_calls) == 1

async def test_form_username(hass):
    """Test we get the username data back."""
    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": SOURCE_USER}
    )
    assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
    assert result["errors"] == {}

    with patch(
        "homeassistant.components.plugwise.config_flow.Smile.connect",
        return_value=True,
    ), patch(
        "homeassistant.components.plugwise.async_setup",
        return_value=True,
    ) as mock_setup, patch(
        "homeassistant.components.plugwise.async_setup_entry",
        return_value=True,
    ) as mock_setup_entry:
        result2 = await hass.config_entries.flow.async_configure(
            result["flow_id"],
            {
                CONF_HOST: TEST_HOST,
                CONF_PASSWORD: TEST_PASSWORD,
                CONF_USERNAME: TEST_USERNAME2,
            },
        )

    await hass.async_block_till_done()

    assert result2["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
    assert result2["data"] == {
        CONF_HOST: TEST_HOST,
        CONF_PASSWORD: TEST_PASSWORD,
        CONF_PORT: DEFAULT_PORT,
        CONF_USERNAME: TEST_USERNAME2,
    }

    assert len(mock_setup.mock_calls) == 1
    assert len(mock_setup_entry.mock_calls) == 1

    result3 = await hass.config_entries.flow.async_init(
        DOMAIN,
        context={"source": SOURCE_ZEROCONF},
        data=TEST_DISCOVERY,
    )
    assert result3["type"] == data_entry_flow.RESULT_TYPE_FORM
    assert result3["errors"] == {}

    with patch(
        "homeassistant.components.plugwise.config_flow.Smile.connect",
        return_value=True,
    ), patch(
        "homeassistant.components.plugwise.async_setup",
        return_value=True,
    ) as mock_setup, patch(
        "homeassistant.components.plugwise.async_setup_entry",
        return_value=True,
    ) as mock_setup_entry:
        result4 = await hass.config_entries.flow.async_configure(
            result3["flow_id"],
            {CONF_PASSWORD: TEST_PASSWORD},
        )

    await hass.async_block_till_done()

    assert result4["type"] == "abort"
    assert result4["reason"] == "already_configured"

async def test_form_invalid_auth(hass, mock_smile):
    """Test we handle invalid auth."""
    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER}
    )

    mock_smile.connect.side_effect = InvalidAuthentication
    mock_smile.gateway_id = "0a636a4fc1704ab4a24e4f7e37fb187a"

    result2 = await hass.config_entries.flow.async_configure(
        result["flow_id"],
        {CONF_HOST: TEST_HOST, CONF_PASSWORD: TEST_PASSWORD},
    )

    assert result2["type"] == data_entry_flow.RESULT_TYPE_FORM
    assert result2["errors"] == {"base": "invalid_auth"}

async def test_form_cannot_connect(hass, mock_smile):
    """Test we handle cannot connect error."""
    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER}
    )

    mock_smile.connect.side_effect = ConnectionFailedError
    mock_smile.gateway_id = "0a636a4fc1704ab4a24e4f7e37fb187a"

    result2 = await hass.config_entries.flow.async_configure(
        result["flow_id"],
        {CONF_HOST: TEST_HOST, CONF_PASSWORD: TEST_PASSWORD},
    )

    assert result2["type"] == data_entry_flow.RESULT_TYPE_FORM
    assert result2["errors"] == {"base": "cannot_connect"}

async def test_form_cannot_connect_port(hass, mock_smile):
    """Test we handle cannot connect to port error."""
    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER}
    )

    mock_smile.connect.side_effect = ConnectionFailedError
    mock_smile.gateway_id = "0a636a4fc1704ab4a24e4f7e37fb187a"

    result2 = await hass.config_entries.flow.async_configure(
        result["flow_id"],
        {CONF_HOST: TEST_HOST, CONF_PASSWORD: TEST_PASSWORD, CONF_PORT: TEST_PORT},
    )

    assert result2["type"] == data_entry_flow.RESULT_TYPE_FORM
    assert result2["errors"] == {"base": "cannot_connect"}

async def test_form_other_problem(hass, mock_smile):
    """Test we handle cannot connect error."""
    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER}
    )

    mock_smile.connect.side_effect = TimeoutError
    mock_smile.gateway_id = "0a636a4fc1704ab4a24e4f7e37fb187a"

    result2 = await hass.config_entries.flow.async_configure(
        result["flow_id"],
        {CONF_HOST: TEST_HOST, CONF_PASSWORD: TEST_PASSWORD},
    )

    assert result2["type"] == data_entry_flow.RESULT_TYPE_FORM
    assert result2["errors"] == {"base": "unknown"}

async def test_options_flow_power(hass, mock_smile) -> None:
    """Test config flow options DSMR environments."""
    entry = MockConfigEntry(
        domain=DOMAIN,
        title=CONF_NAME,
        data={CONF_HOST: TEST_HOST, CONF_PASSWORD: TEST_PASSWORD},
        options={CONF_SCAN_INTERVAL: DEFAULT_SCAN_INTERVAL},
    )

    hass.data[DOMAIN] = {entry.entry_id: {"api": MagicMock(smile_type="power")}}
    entry.add_to_hass(hass)

    with patch(
        "homeassistant.components.plugwise.async_setup_entry", return_value=True
    ):
        assert await hass.config_entries.async_setup(entry.entry_id)
        await hass.async_block_till_done()

        result = await hass.config_entries.options.async_init(entry.entry_id)

        assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
        assert result["step_id"] == "init"

        result = await hass.config_entries.options.async_configure(
            result["flow_id"], user_input={CONF_SCAN_INTERVAL: 10}
        )
        assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
        assert result["data"] == {
            CONF_SCAN_INTERVAL: 10,
        }

async def test_options_flow_thermo(hass, mock_smile) -> None:
    """Test config flow options for thermostatic environments."""
    entry = MockConfigEntry(
        domain=DOMAIN,
        title=CONF_NAME,
        data={CONF_HOST: TEST_HOST, CONF_PASSWORD: TEST_PASSWORD},
        options={CONF_SCAN_INTERVAL: DEFAULT_SCAN_INTERVAL},
    )

    hass.data[DOMAIN] = {entry.entry_id: {"api": MagicMock(smile_type="thermostat")}}
    entry.add_to_hass(hass)

    with patch(
        "homeassistant.components.plugwise.async_setup_entry", return_value=True
    ):
        assert await hass.config_entries.async_setup(entry.entry_id)
        await hass.async_block_till_done()

        result = await hass.config_entries.options.async_init(entry.entry_id)

        assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
        assert result["step_id"] == "init"

        result = await hass.config_entries.options.async_configure(
            result["flow_id"], user_input={CONF_SCAN_INTERVAL: 60}
        )

        assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
        assert result["data"] == {
            CONF_SCAN_INTERVAL: 60,
        }


text:
@interface YSActionSheetCell ()

@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicatorView;

@end

@implementation YSActionSheetCell

+ (UINib*)nib
{
    return [UINib nibWithNibName:NSStringFromClass([self class]) bundle:nil];
}

- (void)awakeFromNib
{
    self.textLabel.minimumScaleFactor = 0.5;
    self.textLabel.adjustsFontSizeToFitWidth = YES;

    self.backgroundColor = [UIColor clearColor];
    self.contentView.backgroundColor = [UIColor clearColor];
}

- (void)configureWithItem:(YSActionSheetItem *)item
{
    self.textLabel.attributedText = [item attributedText];
    self.textLabel.textAlignment = item.textAlignment;

    self.imageView.image = item.image;

    self.accessoryView = item.accessoryView;

    [self activityIndicatorShown:item.activityIndicatorShown];

    [self setNeedsDisplay];
}

- (void)activityIndicatorShown:(BOOL)shown
{
    self.textLabel.alpha = !shown;
    self.detailTextLabel.alpha = !shown;

    self.activityIndicatorView.alpha = shown;
    if (shown) {
        [self.activityIndicatorView startAnimating];
    } else {
        [self.activityIndicatorView stopAnimating];
    }
}

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated
{
    [super setHighlighted:highlighted animated:animated];
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];

    if (self.highlighted) {
        [[YSActionSheetUtility highlightedContentBackgroundColor] set];
    } else {
        [[YSActionSheetUtility contentBackgroundColor] set];
    }

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextFillRect(context, CGRectMake(rect.origin.x,
                                          rect.origin.y,
                                          rect.size.width,
                                          rect.size.height - 1.f/[UIScreen mainScreen].scale));
}

@end


text:
// Spline.cpp

#include "Spline.h"

using namespace _3DMath;

//------------------------------------------------------------------------------------
//                                      Spline
//------------------------------------------------------------------------------------

Spline::Spline( void )
{
}

/*virtual*/ Spline::~Spline( void )
{
}

/*virtual*/ bool Spline::Evaluate( double input, Vector& output ) const
{
	return false;
}

/*virtual*/ double Spline::CalcLength( double maxSegmentLength ) const
{
	double totalLength = 0.0;
	VectorArray pointArray;
	CalcSplinePolyline( maxSegmentLength, pointArray );
	for( int i = 0; i < ( signed )pointArray.size(); i++ )
		totalLength += pointArray[i].Distance( pointArray[ i + 1 ] );
	return totalLength;
}

/*virtual*/ void Spline::CalcSplinePolyline( double maxSegmentLength, VectorArray& pointArray ) const
{
	Vector p0, p1;
	Evaluate( 0.0, p0 );
	Evaluate( 1.0, p1 );

	CalcSplinePolylineRecursively( maxSegmentLength, 0.0, 1.0, p0, p1, pointArray );
	pointArray.push_back( p1 );
}

void Spline::CalcSplinePolylineRecursively( double maxSegmentLength, double t0, double t1, const Vector& p0, const Vector& p1, VectorArray& pointArray, int maxDepth /*= 5*/, int depth /*= 1*/ ) const
{
	if( ( p0 - p1 ).Length() <= maxSegmentLength || depth >= maxDepth )
		pointArray.push_back( p0 );
	else
	{
		double t = ( t0 + t1 ) / 2.0;
		Vector p;
		Evaluate( t, p );
		CalcSplinePolylineRecursively( maxSegmentLength, t0, t, p0, p, pointArray, maxDepth, depth + 1 );
		CalcSplinePolylineRecursively( maxSegmentLength, t, t1, p, p1, pointArray, maxDepth, depth + 1 );
	}
}

//------------------------------------------------------------------------------------
//                                   BezierSpline
//------------------------------------------------------------------------------------

BezierSpline::BezierSpline( void )
{
}

/*virtual*/ BezierSpline::~BezierSpline( void )
{
}

/*virtual*/ bool BezierSpline::Evaluate( double input, Vector& output ) const
{
	if( controlPointList.size() < 2 )
		return false;

	VectorArray pointArray;
	for( VectorList::const_iterator iter = controlPointList.cbegin(); iter != controlPointList.cend(); iter++ )
		pointArray.push_back( *iter );

	for( int i = 1; i < ( signed )pointArray.size(); i++ )
		for( int j = 0; j < ( signed )pointArray.size() - i; j++ )
			pointArray[j].Lerp( pointArray[j], pointArray[ j + 1 ], input );

	output = pointArray[0];
	return true;
}

// Spline.cpp


text:
namespace AutoResponse.WebApi2.IntegrationTests.Tests
{
    using System.Net;
    using System.Threading.Tasks;
    using AutoFixture.Xunit2;
    using AutoResponse.Sample.Domain.Exceptions;
    using AutoResponse.Sample.Domain.Repositories;
    using AutoResponse.Sample.Domain.Services;
    using AutoResponse.WebApi2.IntegrationTests.Helpers;
    using Moq;
    using Xunit;

    // ReSharper disable StyleCop.SA1600
    #pragma warning disable SA1600
    #pragma warning disable 1591

    public class DomainExceptionTests
    {
        [Theory]
        [AutoData]
        public async Task DomainValidationExceptionInOwinShouldReturn422(
            SampleServerFactory serverFactory,
            Mock<IExceptionService> exceptionService,
            DomainValidationException exception)
        {
            exceptionService.Setup(s => s.Execute()).Throws(exception);
            using (var server = serverFactory.With<IExceptionService>(exceptionService.Object).Create())
            {
                var response = await server.HttpClient.GetAsync("/");
                Assert.Equal((HttpStatusCode)422, response.StatusCode);
            }
        }

        [Theory]
        [AutoData]
        public async Task DomainValidationExceptionInWebApiShouldReturn422(
             SampleServerFactory serverFactory,
             Mock<IValuesRepository> valuesRepository,
             DomainValidationException exception,
             int entityId)
        {
            valuesRepository.Setup(r => r.GetValue(It.IsAny<int>())).Throws(exception);

            using (var server = serverFactory.With<IValuesRepository>(valuesRepository.Object).Create())
            {
                var response = await server.HttpClient.GetAsync($"/api/values/{entityId}");
                Assert.Equal((HttpStatusCode)422, response.StatusCode);
            }
        }
    }
}


text:
"""
Skeleton example of a Ginga global plugin called 'MyGlobalPlugin'

To enable it, run ginga with the command
    $ ginga --modules=MyLocalPlugin

it should become active in the right panel.
"""

from ginga import GingaPlugin
from ginga.gw import Widgets

# import any other modules you want here--it's a python world!

class MyGlobalPlugin(GingaPlugin.GlobalPlugin):

    def __init__(self, fv):
        """
        This method is called when the plugin is loaded for the  first
        time.  ``fv`` is a reference to the Ginga (reference viewer) shell.

        You need to call the superclass initializer and then do any local
        initialization.
        """
        super(MyGlobalPlugin, self).__init__(fv)

        # Your initialization here

        # Create some variables to keep track of what is happening
        # with which channel
        self.active = None

        # Subscribe to some interesting callbacks that will inform us
        # of channel events.  You may not need these depending on what
        # your plugin does
        fv.set_callback('add-channel', self.add_channel)
        fv.set_callback('delete-channel', self.delete_channel)
        fv.set_callback('active-image', self.focus_cb)

    def build_gui(self, container):
        """
        This method is called when the plugin is invoked.  It builds the
        GUI used by the plugin into the widget layout passed as
        ``container``.
        This method could be called several times if the plugin is opened
        and closed.  The method may be omitted if there is no GUI for the
        plugin.

        This specific example uses the GUI widget set agnostic wrappers
        to build the GUI, but you can also just as easily use explicit
        toolkit calls here if you only want to support one widget set.
        """
        top = Widgets.VBox()
        top.set_border_width(4)

        # this is a little trick for making plugins that work either in
        # a vertical or horizontal orientation.  It returns a box container,
        # a scroll widget and an orientation ('vertical', 'horizontal')
        vbox, sw, orientation = Widgets.get_oriented_box(container)
        vbox.set_border_width(4)
        vbox.set_spacing(2)

        # Take a text widget to show some instructions
        self.msgFont = self.fv.getFont("sansFont", 12)
        tw = Widgets.TextArea(wrap=True, editable=False)
        tw.set_font(self.msgFont)
        self.tw = tw

        # Frame for instructions and add the text widget with another
        # blank widget to stretch as needed to fill emp
        fr = Widgets.Frame("Status")
        fr.set_widget(tw)
        vbox.add_widget(fr, stretch=0)

        # Add a spacer to stretch the rest of the way to the end of the
        # plugin space
        spacer = Widgets.Label('')
        vbox.add_widget(spacer, stretch=1)

        # scroll bars will allow lots of content to be accessed
        top.add_widget(sw, stretch=1)

        # A button box that is always visible at the bottom
        btns = Widgets.HBox()
        btns.set_spacing(3)

        # Add a close button for the convenience of the user
        btn = Widgets.Button("Close")
        btn.add_callback('activated', lambda w: self.close())
        btns.add_widget(btn, stretch=0)
        btns.add_widget(Widgets.Label(''), stretch=1)
        top.add_widget(btns, stretch=0)

        # Add our GUI to the container
        container.add_widget(top, stretch=1)
        # NOTE: if you are building a GUI using a specific widget toolkit
        # (e.g. Qt) GUI calls, you need to extract the widget or layout
        # from the non-toolkit specific container wrapper and call on that
        # to pack your widget, e.g.:
        #cw = container.get_widget()
        #cw.addWidget(widget, stretch=1)

    def get_channel_info(self, fitsimage):
        chname = self.fv.get_channelName(fitsimage)
        chinfo = self.fv.get_channelInfo(chname)
        return chinfo

    def set_info(self, text):
        self.tw.set_text(text)

    # CALLBACKS

    def add_channel(self, viewer, chinfo):
        """
        Callback from the reference viewer shell when a channel is added.
        """
        self.set_info("Channel '%s' has been added" % (
                chinfo.name))
        # Register for new image callbacks on this channel's canvas
        fitsimage = chinfo.fitsimage
        fitsimage.set_callback('image-set', self.new_image_cb)

    def delete_channel(self, viewer, chinfo):
        """
        Callback from the reference viewer shell when a channel is deleted.
        """
        self.set_info("Channel '%s' has been deleted" % (
                chinfo.name))
        return True

    def focus_cb(self, viewer, fitsimage):
        """
        Callback from the reference viewer shell when the focus changes
        between channels.
        """
        chinfo = self.get_channel_info(fitsimage)
        chname = chinfo.name

        if self.active != chname:
            # focus has shifted to a different channel than our idea
            # of the active one
            self.active = chname
            self.set_info("Focus is now in channel '%s'" % (
                self.active))
        return True

    def new_image_cb(self, fitsimage, image):
        """
        Callback from the reference viewer shell when a new image has
        been added to a channel.
        """
        chinfo = self.get_channel_info(fitsimage)
        chname = chinfo.name

        # Only update our GUI if the activity is in the focused
        # channel
        if self.active == chname:
            imname = image.get('name', 'NONAME')
            self.set_info("A new image '%s' has been added to channel %s" % (
                imname, chname))
        return True

    def start(self):
        """
        This method is called just after ``build_gui()`` when the plugin
        is invoked.  This method could be called more than once if the
        plugin is opened and closed.  This method may be omitted
        in many cases.
        """
        pass

    def stop(self):
        """
        This method is called when the plugin is stopped.
        It should perform any special clean up necessary to terminate
        the operation.  This method could be called more than once if
        the plugin is opened and closed, and may be omitted if there is no
        special cleanup required when stopping.
        """
        pass

    def close(self):
        self.fv.stop_global_plugin(str(self))
        return True

    def __str__(self):
        """
        This method should be provided and should return the lower case
        name of the plugin.
        """
        return 'myglobalplugin'


text:
<?php

namespace Phalcon\Mvc\Model {

	/**
	 * Phalcon\Mvc\Model\ResultInterface initializer
	 */

	interface ResultInterface {

		/**
		 * Sets the object's state
		 *
		 * @param boolean $dirtyState
		 */
		public function setDirtyState($dirtyState);

	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true">
    <LinearLayout android:orientation="vertical"
        android:id="@+id/tab_container"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <FrameLayout
            android:id="@+id/dict_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <!--
        <fragment class="org.nick.wwwjdic.DictionaryFragment"
            android:id="@+id/dictionary_fragment"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
        -->
        <org.nick.wwwjdic.history.FavoritesAndHistorySummaryView
            android:id="@+id/dict_history_summary"
            android:layout_width="fill_parent"
            android:layout_height="120dp"
            android:paddingLeft="15dip"
            android:paddingRight="15dip" />
    </LinearLayout>
</ScrollView>


text:
var courseR = '75%';

var coursePage = Ti.UI.currentWindow;

//Views included
var headView = Ti.UI.createView({
	backgroundColor: '#b18e5f',
	top: 0,
	bottom: '90%'
});

var addCourse = Ti.UI.createButton({
	top:0,
	left:0,
	title:'Add a course'
});

var back = Ti.UI.createButton({
	top:0,
	right:0,
	title:'Back'
});

back.addEventListener('click',function(e){
	var newWin = Ti.UI.createWindow({
		url:'homePage.js',
		backgroundColor: '#b18e5f'
	});
	newWin.open();
});

var courseView1 = Ti.UI.createView({
	backgroundColor: 'white',
	borderColor:'#585858',
	borderWidth:1,
	top: '10%',
	bottom: '80%',
	right: courseR
});

var course1 = Ti.UI.createLabel({
	text:'Course 1',
	color:'#585858'
});

var sectionView = Ti.UI.createView({
	backgroundColor: 'white',
	borderColor:'#585858',
	borderWidth:1,
	top: '20%',
	bottom: '30%',
	right: courseR
});

var section1 = Ti.UI.createLabel({
	text:'Section 1',
	color:'#585858',
	top:3,
	font:{fontSize:11}
});

var section2 = Ti.UI.createLabel({
	text:'Section 2',
	color:'#585858',
	top: 20,
	font:{fontSize:11}
});

var tutor = Ti.UI.createLabel({
	text:'Tutor',
	color:'#585858',
	top: 37,
	font:{fontSize:11}
});

var courseView2 = Ti.UI.createView({
	backgroundColor: 'white',
	borderColor:'#585858',
	borderWidth:1,
	top:'70%',
	bottom: '20%',
	right: courseR
});

var course2 = Ti.UI.createLabel({
	text:'Course 2',
	color:'#585858'
});

var courseView3 = Ti.UI.createView({
	backgroundColor: 'white',
	borderColor:'#585858',
	borderWidth:1,
	top: '80%',
	bottom: '10%',
	right: courseR
});

var course3 = Ti.UI.createLabel({
	text:'Course 3',
	color:'#585858'
});

var courseView4 = Ti.UI.createView({
	backgroundColor: 'white',
	borderColor:'#585858',
	borderWidth:1,
	top: '90%',
	bottom: '0%',
	right: courseR
});

var course4 = Ti.UI.createLabel({
	text:'Course 4',
	color:'#585858'
});

var buttonView = Ti.UI.createView ({
	backgroundColor: '#9f9d9d',
	borderColor:'#585858',
	borderWidth:1,
	top: '10%',
	bottom: '80%',
	left:'25%'
});

var createGroup = Ti.UI.createButton({
	title:'Create A Group',
	left:0
});

createGroup.addEventListener('click',function(e){
	var newWin = Ti.UI.createWindow({
		url:'coursePageDetails.js',
		backgroundColor:'white',
		title:'Create a Group'
	});
	newWin.open();
});

var post = Ti.UI.createButton({
	title:'Post',
	right:0
});

var forumView = Ti.UI.createView ({
	top:'20%',
	left:'25%',
	backgroundColor:'white',
	borderColor:'#585858',
	scrollable:true,
	borderWidth:1
});

var groupView1 = Ti.UI.createView ({
	top:'5%',
	left:'5%',
	right:'5%',
	height:150,
	backgroundColor:'white',
	borderColor:'#585858',
	scrollable:true,
	borderWidth:1
});

var name = Ti.UI.createLabel({
	text:'Group A',
	top:'5%',
	left:'5%',
	font:{fontSize:12,fontFamily:'Helvetica Neue'}
});

var date = Ti.UI.createLabel({
	text:'4/13 5:30pm',
	top:'5%',
	right:'5%',
	font:{fontSize:12,fontFamily:'Helvetica Neue'}
});

var place = Ti.UI.createLabel({
	text:'Place: Library 1st Floor',
	top:'15%',
	left:'5%',
	font:{fontSize:12,fontFamily:'Helvetica Neue'}
});

var enroll = Ti.UI.createLabel({
	text:'Enroll: 4/10',
	top:'25%',
	left:'5%',
	font:{fontSize:12,fontFamily:'Helvetica Neue'}
});

var detail = Ti.UI.createLabel({
	text:'Bus353, study for final exam!',
	top:'35%',
	left:'5%',
	font:{fontSize:12,fontFamily:'Helvetica Neue'}
});

var joinButton = Ti.UI.createButton({
	title:'Join',
	left:'5%',
	bottom:5
});

joinButton.addEventListener('click',function(e){
	if (joinButton.getTitle() === 'Join'){
		joinButton.title = 'Cancel';
	} else {
		joinButton.title = 'Join';
	}
});

var groupView2 = Ti.UI.createView ({
	top:'50%',
	left:'5%',
	right:'5%',
	height:150,
	backgroundColor:'white',
	borderColor:'#585858',
	scrollable:true,
	borderWidth:1
});

var name2 = Ti.UI.createLabel({
	text:'Group B',
	top:'5%',
	left:'5%',
	font:{fontSize:12,fontFamily:'Helvetica Neue'}
});

var date2 = Ti.UI.createLabel({
	text:'4/13 5:30pm',
	top:'5%',
	right:'5%',
	font:{fontSize:12,fontFamily:'Helvetica Neue'}
});

var place2 = Ti.UI.createLabel({
	text:'Place: ALB 1st Floor',
	top:'15%',
	left:'5%',
	font:{fontSize:12,fontFamily:'Helvetica Neue'}
});

var enroll2 = Ti.UI.createLabel({
	text:'Enroll: 6/10',
	top:'25%',
	left:'5%',
	font:{fontSize:12,fontFamily:'Helvetica Neue'}
});

var detail2 = Ti.UI.createLabel({
	text:'Bus390,Project study!',
	top:'35%',
	left:'5%',
	font:{fontSize:12,fontFamily:'Helvetica Neue'}
});

var joinButton2 = Ti.UI.createButton({
	title:'Join',
	left:'5%',
	bottom:5
});

joinButton2.addEventListener('click',function(e){
	if (joinButton2.getTitle() === 'Join'){
		joinButton2.title = 'Cancel';
	} else {
		joinButton2.title = 'Join';
	}
});

headView.add(addCourse);
headView.add(back);

courseView1.add(course1);
courseView2.add(course2);
courseView3.add(course3);
courseView4.add(course4);
sectionView.add(section1);
sectionView.add(section2);
sectionView.add(tutor);

buttonView.add(createGroup);
buttonView.add(post);

groupView1.add(name);
groupView1.add(date);
groupView1.add(place);
groupView1.add(detail);
groupView1.add(enroll);
groupView1.add(joinButton);
groupView2.add(name2);
groupView2.add(date2);
groupView2.add(place2);
groupView2.add(detail2);
groupView2.add(enroll2);
groupView2.add(joinButton2);

forumView.add(groupView1);
forumView.add(groupView2);

coursePage.add(headView);
coursePage.add(sectionView);
coursePage.add(courseView1);
coursePage.add(courseView2);
coursePage.add(courseView3);
coursePage.add(courseView4);
coursePage.add(buttonView);
coursePage.add(forumView);
coursePage.open();


text:
@implementation NYPLMenuViewController

@synthesize backgroundImageView;
@synthesize backFlag;

- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        navigationMenuObjects=[[NSMutableArray alloc]init];
    }
    return self;
}

#pragma mark addViewControllers

- (void)addViewControllers:(NSArray*)menuArray
{
	id appDelegate = [[UIApplication sharedApplication]delegate];
	totalBtnsWidth = 0.0;
	totalMenuBtn = 1;
	BOOL isScalingNotRequired = FALSE;

	for (int menuIndex = 0; menuIndex < [menuArray count]; menuIndex++) {

		MenuObject *menuObject = (MenuObject*)[menuArray objectAtIndex:menuIndex];
		UINavigationController *viewNavigationController = [[UINavigationController alloc]initWithRootViewController:menuObject.viewController];
		[navigationMenuObjects addObject:viewNavigationController];
        viewNavigationController.navigationBar.hidden = YES;
		UIButton *menuBtn = nil;

		if(menuObject.normalBtnImage) {
			if(menuObject.buttonFrame.size.width > 0) {
				menuBtn = [[UIButton alloc]initWithFrame:CGRectMake(menuObject.buttonFrame.origin.x, menuObject.buttonFrame.origin.y, menuObject.buttonFrame.size.width, menuObject.buttonFrame.size.height)] ;
				isScalingNotRequired = TRUE;

			} else {
				if(isScalingNotRequired) {
					UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"CustomTabBar" message:[NSString stringWithFormat:@"You must have to provide frame of tab %i.",menuIndex] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
					[alertView show];
                    alertView = nil;
				}

				menuBtn = [[UIButton alloc]initWithFrame:CGRectMake(0.0, 0.0, menuObject.normalBtnImage.size.width, menuObject.normalBtnImage.size.height)];
			}

			[menuBtn setImage:menuObject.normalBtnImage forState:UIControlStateNormal];
			[menuBtn setImage:menuObject.selectedBtnImage forState:UIControlStateSelected];
			[menuBtn setTag:menuIndex];
			[menuBtn addTarget:self action:@selector(menuBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
			[self addSubview:menuBtn];

			if(menuIndex < 1) {
				[menuBtn setHidden:YES];
            }
			totalBtnsWidth += menuBtn.frame.size.width;
			totalMenuBtn++;
		}

		if(menuIndex == 0) {
			[viewNavigationController.view addSubview:self];
            [[appDelegate window] setRootViewController:viewNavigationController];
			previousNavigationView = viewNavigationController;
			[[appDelegate window] bringSubviewToFront:self];
			previousSelectedBtn = menuBtn;
			[menuBtn setSelected:TRUE];
		}
	}

	if(!isScalingNotRequired)
		[self addjustMenuBtn];
}

- (void)addjustMenuBtn
{
	float viewHorizontalSpacing = (self.frame.size.width-totalBtnsWidth)/totalMenuBtn;
	float xOffset = 0.0;

	for (UIView *view in self.subviews) {
		if([view isKindOfClass:[UIButton class]]) {
			xOffset += viewHorizontalSpacing;
			view.frame=CGRectMake(xOffset, (self.frame.size.height-view.frame.size.height)/2, view.frame.size.width, view.frame.size.height);
			xOffset += view.frame.size.width;
		}
	}
}

#pragma mark menuBtnClickedAction

- (IBAction)menuBtnClicked:(id)sender
{
	tempBtn = (UIButton *)sender;

    if(tempBtn.tag < [navigationMenuObjects count]) {

        [previousSelectedBtn setSelected:FALSE];
        [tempBtn setSelected:TRUE];
        previousSelectedBtn = tempBtn;
        id appDelegate = [[UIApplication sharedApplication]delegate];
        UINavigationController *currentNavigationController = [navigationMenuObjects objectAtIndex:tempBtn.tag];
        id obj = [currentNavigationController.viewControllers objectAtIndex:0];

        if([obj isKindOfClass:[PlayViewController class]]) {
            PlayViewController* objPlay = (PlayViewController*)obj;
            [objPlay.playTableView reloadData];
        }

        if([obj isKindOfClass:[AnnotateViewController class]]) {
            AnnotateViewController* objAno = (AnnotateViewController*)obj;
            [objAno.noteTableView reloadData];
        }

        if([obj isKindOfClass:[BookmarkViewController class]]) {
            BookmarkViewController* objBok = (BookmarkViewController*)obj;
            [objBok.bookmarkTableView reloadData];
        }
        [previousNavigationView.view removeFromSuperview];
        [currentNavigationController.view addSubview:self];
        [[appDelegate window] setRootViewController:currentNavigationController];
        previousNavigationView = currentNavigationController;
        [[appDelegate window] bringSubviewToFront:self];
    }
}

#pragma mark -
#pragma mark showRequiredController
- (void)showRequiredController:(HighlightedTab)requiredTab
{
	for (UIView *view in self.subviews) {
		if([view isKindOfClass:[UIButton class]]) {
			if(view.tag == requiredTab) {
                [self menuBtnClicked:view];
                break;
            }
		}
	}
}
@end


text:
package com.agup.gps;

import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;

public class SettingsActivity extends PreferenceActivity {

	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		//addPreferencesFromResource(R.xml.preferences); //deprecated in v1.3
		getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();
	}

	public static class SettingsFragment extends PreferenceFragment{

		@Override
		public void onCreate(final Bundle savedInstanceState){
			super.onCreate(savedInstanceState);
			addPreferencesFromResource(R.xml.preferences);
		}
	}
}


text:
package org.apache.directmemory.serialization;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import java.io.IOException;

import org.apache.directmemory.measures.Monitor;
import org.apache.directmemory.measures.MonitorService;
import org.apache.directmemory.measures.Ram;
import org.apache.directmemory.misc.DummyPojo;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.carrotsearch.junitbenchmarks.AbstractBenchmark;
import com.carrotsearch.junitbenchmarks.BenchmarkOptions;
import com.carrotsearch.junitbenchmarks.annotation.AxisRange;
import com.carrotsearch.junitbenchmarks.annotation.BenchmarkHistoryChart;
import com.carrotsearch.junitbenchmarks.annotation.BenchmarkMethodChart;
import com.carrotsearch.junitbenchmarks.annotation.LabelType;

@AxisRange( min = 0, max = 1 )
@BenchmarkMethodChart()
@BenchmarkHistoryChart( labelWith = LabelType.CUSTOM_KEY, maxRuns = 5 )
@BenchmarkOptions( benchmarkRounds = 2, warmupRounds = 1, concurrency = 1 )

public class SerializerTest
    extends AbstractBenchmark
{

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

    private void testSerializer( String name, Serializer serializer, int size, int howMany )
        throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException
    {
        logger.info( "begin " + serializer.getClass().toString() );
        MonitorService stopWatch = Monitor.get( "serializer." + name + "." + size + "bytes" );
        MonitorService stopWatch2 = Monitor.get( "deserializer." + name + "." + size + "bytes" );
        DummyPojo pojo = new DummyPojo( "test", size );
        for ( int i = 0; i < howMany; i++ )
        {
            long split = stopWatch.start();
            final byte[] array = serializer.serialize( pojo );
            stopWatch.stop( split );
            long split2 = stopWatch2.start();
            DummyPojo check = (DummyPojo) serializer.deserialize( array, pojo.getClass() );
            stopWatch2.stop( split2 );
            assertNotNull( "object has not been serialized", check );
            assertEquals( pojo.name, check.name );
        }
        logger.info( "end serialize " + serializer.getClass().toString() + "\r\n" + stopWatch.toString() );
        logger.info( "end deserialize " + serializer.getClass().toString() + "\r\n" + stopWatch2.toString() );
    }

    @Test
    public void StandardTest()
        throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException
    {
        testSerializer( "java-serialization", new StandardSerializer(), Ram.Kb( 1 ), 20000 );
        testSerializer( "java-serialization", new StandardSerializer(), Ram.Kb( 2 ), 20000 );
        testSerializer( "java-serialization", new StandardSerializer(), Ram.Kb( 3 ), 20000 );
        testSerializer( "java-serialization", new StandardSerializer(), Ram.Kb( 4 ), 20000 );
    }

}