text:
**Panduan BlankOn 6**

Bab ini membahas cara memasang BlankOn di komputer. Pemasangan BlankOn sangat
mudah dilakukan jika Anda sudah memahami persiapan dan langkah-langkah apa saja
yang perlu dilakukan. Pada bab ini, dibahas mengenai persiapan dan langkah-
langkah melakukan pemasangan BlankOn.
### Kebutuhan sistem
Sebelum melakukan pemasangan, terlebih dahulu komputer Anda harus memenuhi
syarat spesifikasi minimal agar BlankOn bisa berjalan dengan lancar. Berikut
adalah syarat spesifikasi minimal untuk BlankOn 6.0 :
  * Prosesor setara Pentium IV atau Celeron,
  * Memori RAM 256 MB,
  * Kartu Video atau VGA minimal memiliki memori 64 MB untuk efek desktop,
      dan
  * Harddisk dengan ukuran 6 GB.
### Cara Mendapatkan CD BlankOn
Untuk mendapatkan CD BlankOn, Anda bisa mengunduh image atau cetakan CD-nya
dari situs http://cdimage.blankonlinux.or.id. Berkas cetakan tersebut
selanjutnya dibakar ke CD kosong menggunakan aplikasi pembakar CD seperti
Brasero, K3b, Nero, Roxio, dsb.
     TIP: Jika mengunduh terasa lambat, Anda bisa memanfaatkan situs
     cermin (mirror) sebagai sumber mengunduh berikut ini :
  * http://kambing.ui.ac.id/iso/blankon
  * http://mirror.unej.ac.id/blankon-cd
  * ftp://dl2.foss-id.web.id/iso/blankon
  * http://buaya.klas.or.id/pub/blankon
  * http://pandawa.ipb.ac.id/iso/blankon/
  * http://repo.ugm.ac.id/iso/blankon
  * http://jaran.undip.ac.id/public/ISO/
  * http://mugos.ums.ac.id/iso/Blankon
Bagi Anda yang memiliki koneksi internet terbatas atau bahkan tidak memiliki
koneksi internet sama sekali, jangan khawatir. Anda bisa membeli CD BlankOn
melalui toko penjual CD/DVD Linux atau meminjamnya dari teman yang telah
memilikinya. Berikut adalah beberapa Toko penjual CD/DVD Linux yang ada di
Indonesia :
  * Juragan Kambing (http://juragan.kambing.ui.ac.id)
  * Toko Baliwae (http://toko.baliwae.com)
  * Gudanglinux (http://gudanglinux.com)
  * Toko Ku Online (http://tokoku-online.com/)
  * dll.
### Persiapan menjelang pemasangan
Sebelum melakukan pemasangan BlankOn, lakukan beberapa persiapan seperti
berikut:
   1. Persiapkan CD BlankOn sebagai bekal untuk proses pemasangan, baca kembali
      subbab sebelumnya untuk mengetahui cara mendapatkan CD BlankOn, pastikan
      CD dalam keadaan baik agar proses pemasangan lancar.
   1. Backup atau buat cadangan dari data penting Anda ke media penyimpanan
      cadangan (seperti Flash Disk, Harddisk lain, CD/DVD) agar data Anda aman
      dan terhindar dari resiko kehilangan data.
   1. Tentukan skema partisi harddisk yang Anda inginkan. Partisi merupakan
      bagian ruang-ruang data yang terdapat di harddisk. Jika Anda ingin
      melakukan dual-boot (terdapat dua sistem operasi dalam satu komputer),
      Anda harus membuat partisi baru pada harddisk komputer yang nantinya akan
      digunakan sebagai tempat pemasangan BlankOn. Pembahasan lebih lanjut
      dijelaskan pada subbab tentang langkah pemasangan.
   1. Pastikan untuk menjaga kestabilan tegangan listrik. Hal ini untuk
      menghindari listrik yang tiba-tiba padam saat pemasangan dan menyebabkan
      terjadinya kerusakan fisik pada komputer (terutama harddisk).
   1. Lakukan penyetelan BIOS agar komputer membaca CD terlebih dahulu untuk
      proses booting. Silahkan merujuk ke manual komputer atau motherboard Anda
      mengenai cara melakukan penyetelan ini.
### Persiapan Partisi
Sebelum memulai pemasangan, terlebih dahulu persiapkan partisi kosong untuk
yang akan digunakan sebagai tempat pemasangan BlankOn. Misal di Windows, Anda
mempunyai drive C dan D. Salin data yang ada di Drive D ke media lain
(flashdisk, eksternal harddisk, atau harddisk lain). Drive D akan kita gunakan
sebagai tempat instalasi BlankOn. Jika Anda mempunyai drive C, D, dan E. Anda
bisa memindahkan data di drive E ke drive D, lalu drive E yang akan kita
gunakan untuk instalasi BlankOn. Jika semua bagian harddisk sudah terpartisi,
Anda bisa memotong partisi harddisk terakhir dengan langkah berikut ini:
     PERINGATAN! Jika partisi tersebut merupakan partisi Windows, lakukan
     terlebih dahulu Defragmenting melalui tools "Disk Defragmenter" yang
     terdapat di sistem operasi Microsoft Windows. Hal ini untuk
     menghindari partisi yang rusak pada saat melakukan pemotongan
     partisi.
   1. Buka aplikasi Editor Partisi melalui menu Sistem > Administrasi > Gparted
      (Editor Partisi).
   1. Pada baris partisi yang ditampilkan, klik kanan pada partisi terakhir
      (yang paling kanan), lalu pilih menu [>Ubah Ukuran/Pindahkan?<].
   1. Tentukan ukuran baru dari partisi yang Anda potong pada opsi [>Ukuran
      Baru (MiB)<]. Kemudian, klik tombol [>Ubah Ukuran/Pindahkan?<].
   1. Terakhir, klik tombol [>Terapkan<] pada toolbar untuk menerapkan
      perubahan yang dilakukan.
Sekarang, Anda sudah memiliki partisi kosong yang bisa Anda manfaatkan untuk
pemasangan BlankOn.
### Memasang BlankOn melalui Live CD
Untuk pemasangan melalui Live CD, Anda harus mempersiapkan Live CD dari BlankOn
6.0 Ombilin. Masukkan CD tersebut ke dalam CD/DVD-ROM drive pada komputer Anda.
Restart komputer Anda dan Anda akan melihat menu awal dari Live CD BlankOn 6.0
Ombilin, tekan tombol Enter untuk masuk ke modus Live CD, maka sistem operasi
BlankOn 6.0 Ombilin akan mulai dijalankan melalui CD. Tunggu sebentar sampai
desktop BlankOn 6.0 Ombilin muncul. Proses booting memakan waktu sekitar 1
menit lamanya.
[menu_awal]
     TIP: Jika terdapat masalah pada saat menampilkan antarmuka grafis,
     Anda bisa restart komputer dan memilih menu [>Coba BlankOn 6.0
     Ombilin (darurat)<] pada menu awal Live CD BlankOn.
[sedang_booting]
Setelah proses booting selesai, maka Anda akan melihat desktop BlankOn 6.0
Ombilin yang sangat cantik. Anda bisa mencobanya terlebih dahulu sebelum
memasangnya ke harddisk.
Untuk melakukan pemasangan BlankOn, klik ganda ikon [>Pasang<] pada Desktop.
Maka akan muncul sebuah wahana pandu yang membantu Anda dalam pemasangan
BlankOn. Berikut uraian setiap langkahnya :
  * [Selamat Datang]
      Pada langkah ini, pilih bahasa pengantar yang ingin Anda gunakan dalam
      proses pemasangan. Setelah itu, klik tombol [>Maju<].
[instalasi_blankon]
  * [Memilih Lokasi Anda]
      Pilih lokasi tempat tinggal Anda pada peta yang disediakan. Kemudian,
      klik tombol [>Maju<].
[instalasi_blankon_-_lokasi]
  * [Susunan Papan Tik]
      Pilih jenis papan tik (keyboard) yang Anda gunakan. Jenis papan tik yang
      umum digunakan di Indonesia adalah jenis Amerika Serikat (USA). Kemudian,
      klik tombol [>Maju<].
[instalasi_blankon_-_keyboard]
  * [Mempersiapkan ruang (partisi) Harddisk]
      Disini, Anda akan memilih skema tata ruang partisi harddisk yang Anda
      inginkan. Jika Anda ingin menghapus semua isi data dan partisi yang ada
      di harddisk, pilih mode [>Hapus dan gunakan seluruh cakram<]. Karena kita
      sudah mempersiapkan paritisi kosong, kita akan membuat partisi manual.
      Setelah itu, klik tombol [>Maju<].
[instalasi_blankon_-_buat_partisi]
  * [Titik kait root (/)]
      Pilih ruang atau partisi kosong, lalu klik tombol Tambah, isi paramater
      seperti gambar. Ukuran partisi / bisa disesuaikan dengan kapasitas
      harddisk yang Anda miliki. Jangan lupa memilih Titik kait /. Titik kait /
      merupakan partisi sistem.
[buat_partisi]
  * [Swap]
      Pilih ruang atau partisi kosong, lalu klik tombol Tambah, isi paramater
      seperti gambar. Ukuran partisi swap ini disesuai dengan memori komputer
      Anda. Biasanya 2 kali kapasitas memori. Misal Anda mempunyai memori 512
      MB, ukuran partisi swap 1024 MB.
[buat_partisi_swap]
  * [Titik kait beranda (home)]
      Pilih ruang atau partisi kosong, lalu klik tombol Tambah, isi paramater
      seperti gambar. Sisa kapasitas harddisk digunakan untuk partisi home ini.
[buat_partisi_home]
  * [Isi data diri]
      Isi nama lengkap anda, nama akun pengguna, dan sandi sesuai dengan yang
      Anda inginkan. Nama akun pengguna dan sandi akan Anda gunakan pada saat
      masuk ke sistem (login). Nama akun pengguna dan sandi ini juga akan
      memiliki hak administratif untuk melakukan pengaturan sistem secara
      mendalam. Jika Anda ingin masuk otomatis ke sistem tanpa perlu memasukkan
      id pengguna dan password, klik pada opsi [>Masuk secara otomatis<].
      Selanjutnya, klik tombol [>Maju<].
[instalasi_blankon_-_pengguna_dan_sandi]
  * [Migrasi data dan dokumen]
      Jika Anda ingin memigrasikan data Anda dari sistem operasi lain yang
      sudah terinstal ke sistem operasi BlankOn yang akan di-instal, beri tanda
      centang pada nama sistem operasi yang ingin Anda migrasikan datanya,
      kemudian klik tombol [>Maju<].
[instalasi_blankon_-_informasi_instalasi]
  * [Proses pemasangan]
      Jika Anda siap untuk melakukan pemasangan, klik tombol [>Maju<]. Maka
    akan dipasang ke partisi harddisk yang telah Anda tentukan.
      Proses pemasangan memakan waktu sekitar 5 sampai 30 menit, tergantung
      dari kecepatan komputer Anda. Sembari menunggu pemasangan, Anda bisa
      membuka berbagai permainan kecil yang ada di menu BlankOn > Permainan.
[instalasi_blankon_-_informasi_instalasi]
  * [Pemasangan berhasil]
      Selamat! Proses pemasangan telah berhasil dilakukan. Jika Anda ingin
      tetap lanjut menggunakan Live CD, klik tombol [>Lanjut Pengecekan<]. Jika
      tidak, klik tombol [>Restart sekarang<] untuk menghidupkan ulang
      komputer.
Pada saat pertama kali menghidupkan komputer, Anda akan melihat menu sistem
operasi yang bisa Anda jalankan. Jika Anda ingin menggunakan BlankOn, Anda bisa
memilih pilihan paling atas menggunakan tombol arah panah, dan tekan tombol
Enter. Jika Anda tidak memilih sistem operasi apapun, 5 detik kemudian otomatis
komputer melakukan booting ke sistem operasi BlankOn 6.0 Ombilin.
[boot_loader]
Layar boot ganda
Setelah proses booting, Anda akan melihat layar login BlankOn. Tik nama akun
pengguna Anda lalu tekan enter, lalu tik sandi Anda dan tekan tombol enter
lagi. Maka Anda akan masuk ke desktop BlankOn.
### Mengatasi masalah boot ganda
Pada saat panduan ini ditulis, instalasi dua OS Windows XP dan BlankOn, akan
membuat Windows tidak muncul pada daftar pilihan sistem operasi. Untuk
mengatasinya, pada saat boot loader (pilihan sistem operasi) muncul, gunakan
pilihan kedua yakni [>BlankOn (recovery mode)<] dengan menggunakan tombol panah
bawah, lalu tekan enter. Tunggu sebentar sampai muncul berikut.
[memutahirkan_boot_loader]
Memulihkan sistem
Pilihlah [>grub - Update grub loader<] dengan tombol panah bawah lalu tekan
Enter. Blankon akan memutahirkan grub boot loader, sehingga sistem operasi
Windows muncul pada boot loader. Setelah pemutahiran grub bootloader sukses,
pilih Lanjutkan boot normal. Anda akan dibawa mode teks.
blankon login :
Password
Tikkan nama pengguna tekan enter, tik password Anda lalu tekan enter
Setelah masuk BlankOn, restart komputer, gunakan perintah:
blankon@blankon:~$sudo reboot
[sudo] Password for blankon :
tik sandi Anda lalu tekan enter. Komputer akan restart. Windows XP sudah
terdaftar di bootloader. Sekarang Anda bisa berpindah sistem operasi.
Last modified on 06/26/2010 04:47:29 PM
#### Attachments (16)
  * menu_awal.png (174.1 KB) - added by hanafi 7 years ago. menu awal
  * live-booting.png (121.8 KB) - added by hanafi 7 years ago. sedang
      booting
  * Gambar-Layar-Buat-partisi.png (23.2 KB) - added by hanafi 7 years ago.
      buat partisi
  * Gambar-Layar-Buat-partisi-home.png (23.7 KB) - added by hanafi 7 years
      ago. buat partisi home
  * Gambar-Layar-Buat-partisi-swap.png (21.8 KB) - added by hanafi 7 years
      ago. buat partisi swap
  * Gambar-Layar-Instal.png (47.3 KB) - added by hanafi 7 years ago.
      instalasi blankon
  * Gambar-Layar-Instal-1.png (120.9 KB) - added by hanafi 7 years ago.
      instalasi blankon - lokasi
  * Gambar-Layar-Instal-2.png (58.2 KB) - added by hanafi 7 years ago.
      instalasi blankon - keyboard
  * Gambar-Layar-Instal-3.png (61.9 KB) - added by hanafi 7 years ago.
      instalasi blankon - buat partisi
  * Gambar-Layar-Instal-4.png (54.2 KB) - added by hanafi 7 years ago.
      instalasi blankon - buat partisi selesai
  * Gambar-Layar-Instal-5.png (51.5 KB) - added by hanafi 7 years ago.
      instalasi blankon - pengguna dan sandi
  * Gambar-Layar-Instal-6.png (37.3 KB) - added by hanafi 7 years ago.
      instalasi blankon - informasi instalasi
  * Gambar-Layar-Instal-7.png (57.2 KB) - added by hanafi 7 years ago.
      instalasi blankon - informasi instalasi
  * Gambar-Layar-Meng-install-sistem.png (7.6 KB) - added by hanafi 7 years
      ago. instalasi blankon - instalasi sedang berjalan
  * dual-booting.png (7.1 KB) - added by hanafi 7 years ago. boot loader
  * mode-pemulihan.png (4.4 KB) - added by hanafi 7 years ago. memutahirkan
      boot loader
####

---


text:
package org.wikidata.wdtk.datamodel.implementation;

import static org.junit.Assert.*;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.wikidata.wdtk.datamodel.helpers.Datamodel;
import org.wikidata.wdtk.datamodel.helpers.DatamodelMapper;
import org.wikidata.wdtk.datamodel.interfaces.EntityIdValue;

import java.io.IOException;

public class PropertyIdValueImplTest {

	private final ObjectMapper mapper = new DatamodelMapper(Datamodel.SITE_WIKIDATA);

	private final PropertyIdValueImpl prop1 = new PropertyIdValueImpl("P42", "http://www.wikidata.org/entity/");
	private final PropertyIdValueImpl prop2 = new PropertyIdValueImpl("P42", "http://www.wikidata.org/entity/");
	private final PropertyIdValueImpl prop3 = new PropertyIdValueImpl("P57",	 "http://www.wikidata.org/entity/");
	private final PropertyIdValueImpl prop4 = new PropertyIdValueImpl("P42", "http://www.example.org/entity/");
	private final String JSON_PROPERTY_ID_VALUE = "{\"type\":\"wikibase-entityid\",\"value\":{\"entity-type\":\"property\",\"numeric-id\":42,\"id\":\"P42\"}}";
	private final String JSON_PROPERTY_ID_VALUE_WITHOUT_NUMERICAL_ID = "{\"type\":\"wikibase-entityid\",\"value\":{\"id\":\"P42\"}}";

	@Test
	public void entityTypeIsProperty() {
		assertEquals(prop1.getEntityType(), EntityIdValue.ET_PROPERTY);
	}

	@Test
	public void iriIsCorrect() {
		assertEquals(prop1.getIri(), "http://www.wikidata.org/entity/P42");
		assertEquals(prop4.getIri(), "http://www.example.org/entity/P42");
	}

	@Test
	public void idIsCorrect() {
		assertEquals(prop1.getId(), "P42");
	}

	@Test
	public void equalityBasedOnContent() {
		assertEquals(prop1, prop1);
		assertEquals(prop1, prop2);
		assertNotEquals(prop1, prop3);
		assertNotEquals(prop1, prop4);
		assertNotEquals(prop1, null);
		assertNotEquals(prop1, this);
	}

	@Test
	public void hashBasedOnContent() {
		assertEquals(prop1.hashCode(), prop2.hashCode());
	}

	@Test(expected = RuntimeException.class)
	public void idValidatedForFirstLetter() {
		new PropertyIdValueImpl("Q12345", "http://www.wikidata.org/entity/");
	}

	@Test(expected = IllegalArgumentException.class)
	public void idValidatedForLength() {
		new ItemIdValueImpl("P", "http://www.wikidata.org/entity/");
	}

	@Test(expected = IllegalArgumentException.class)
	public void idValidatedForNumber() {
		new PropertyIdValueImpl("P34d23", "http://www.wikidata.org/entity/");
	}

	@Test
	public void testToJson() throws JsonProcessingException {
		JsonComparator.compareJsonStrings(JSON_PROPERTY_ID_VALUE, mapper.writeValueAsString(prop1));
	}

	@Test
	public void testToJava() throws
			IOException {
		assertEquals(prop1, mapper.readValue(JSON_PROPERTY_ID_VALUE, ValueImpl.class));
	}

	@Test
	public void testToJavaWithoutNumericalID() throws IOException {
		assertEquals(prop1, mapper.readValue(JSON_PROPERTY_ID_VALUE_WITHOUT_NUMERICAL_ID, ValueImpl.class));
	}

	@Test
	public void testIsPlaceholder() {
		assertFalse(prop1.isPlaceholder());
	}

}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

		<title>nw.js + pdf.js example</title>
		<meta charset="utf-8">


text:
"""
Utilities for ratelimiting a command.
"""
import time
from typing import Any, Callable, List, Tuple

from curious.commands import Context
from curious.commands.exc import CommandRateLimited

class BucketNamer:
    """
    A simple namespace for storing bucket functions.
    """

    def __new__(cls):
        raise NotImplementedError("Don't make an instance of this class")

    @staticmethod
    def GUILD(ctx: Context) -> str:
        """
        A bucket namer that uses the guild ID as the bucket.
        """
        return str(ctx.guild.id)

    @staticmethod
    def CHANNEL(ctx: Context) -> str:
        """
        A bucket namer that uses the channel ID as the bucket.
        """
        return str(ctx.channel.id)

    @staticmethod
    def AUTHOR(ctx: Context) -> str:
        """
        A bucket namer that uses the author ID as the bucket.
        """
        return str(ctx.author.id)

    @staticmethod
    def GLOBAL(ctx: Context) -> str:
        """
        A bucket namer that is global.
        """
        return "GLOBAL"

class CommandRateLimit(object):
    """
    Represents a ratelimit for a command.
    """

    def __init__(self, *, limit: int, time: float,
                 bucket_namer: Callable[[Context], str] = BucketNamer.AUTHOR):
        """
        :param limit: The number of times a command can be called in the specified limit.
        :param time: The time (in seconds) this ratelimit lasts.
        :param bucket_namer: A callable that gets the ratelimit bucket name.
        """
        self.limit = limit
        self.time = time
        self.bucket_namer = bucket_namer

        #: The command function being used.
        self.command = None

    def get_full_bucket_key(self, ctx: Context) -> Tuple[str, str]:
        """
        Gets the full bucket key for this ratelimit.
        """
        return self.command.cmd_name, self.bucket_namer(ctx)

class RateLimiter(object):
    """
    Represents a ratelimiter. This ensures that commands meet the ratelimit before being ran.
    """

    def __init__(self):
        self._ratelimit_buckets = {}

    async def update_bucket(self, key: Any, current_uses: int, expiration: float):
        """
        Updates a ratelimit bucket.

        :param key: The ratelimit key to use.
        :param current_uses: The current uses for the key.
        :param expiration: When the ratelimit expires.
        """
        self._ratelimit_buckets[key] = (current_uses, expiration)

    async def get_bucket(self, key: Any) -> Tuple[int, float]:
        """
        Gets the ratelimit bucket for the specified key.

        :param key: The key to use.
        :return: A two-item tuple of (uses, expiration), or None if no bucket was found.
        """
        return self._ratelimit_buckets.get(key)

    async def ensure_ratelimits(self, ctx: Context, cmd):
        """
        Ensures the ratelimits for a command.
        """
        ratelimits: List[CommandRateLimit] = cmd.cmd_ratelimits
        for limit in ratelimits:
            bucket_key = limit.get_full_bucket_key(ctx)
            bucket = await self.get_bucket(key=bucket_key)
            if not bucket:
                await self.update_bucket(bucket_key, 1, time.monotonic() + limit.time)
                continue

            # check if we've hit the limit
            if bucket[0] == limit.limit:
                # we have, but that might be okay if the timer has expired
                if time.monotonic() > bucket[1]:
                    # we're good, so we can just reset the bucket and continue on our way
                    await self.update_bucket(bucket_key, 1, time.monotonic() + limit.time)
                else:
                    raise CommandRateLimited(ctx, cmd, limit, bucket)
            else:
                # we haven't, but we need to up the number anyway
                await self.update_bucket(bucket_key, bucket[0] + 1, bucket[1])


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<LEOSimulation version="2.5.0">
	<STELAVersion>2.5.1</STELAVersion>
	<SpaceObject>
		<mass unit="kg">4.0</mass>
		<dragArea>0.055</dragArea>
		<reflectingArea>0.22</reflectingArea>
		<reflectivityCoefficient>1.5</reflectivityCoefficient>
		<orbitType>LEO</orbitType>
		<ConstantDragCoef>
			<cstDragCoef>2.1</cstDragCoef>
		</ConstantDragCoef>
		<name>WC997P2N</name>
	</SpaceObject>
	<EphemerisManager version="2.5.0">
		<initState>
			<bulletin version="2.5.0">
				<date>2014-07-14T14:55:16.000</date>
				<Type2PosVel>
					<frame>CELESTIAL_MEAN_OF_DATE</frame>
					<nature>MEAN</nature>
					<semiMajorAxis unit="m">7000000.0</semiMajorAxis>
					<eccentricity>0.001</eccentricity>
					<inclination unit="rad">1.69296937443</inclination>
					<rAAN unit="rad">0.0</rAAN>
					<argOfPerigee unit="rad">0.0</argOfPerigee>
					<meanAnomaly unit="rad">0.0</meanAnomaly>
				</Type2PosVel>
			</bulletin>
		</initState>
		<finalState>
			<bulletin version="2.5.0">
				<date>2032-04-15T15:56:48.749</date>
				<Type2PosVel>
					<frame>CELESTIAL_MEAN_OF_DATE</frame>
					<nature>MEAN</nature>
					<semiMajorAxis unit="m">6493036.081327666</semiMajorAxis>
					<eccentricity>2.1983612987409957E-4</eccentricity>
					<inclination unit="rad">1.6909241153215513</inclination>
					<rAAN unit="rad">2.1754966634655553</rAAN>
					<argOfPerigee unit="rad">6.1497284491446935</argOfPerigee>
					<meanAnomaly unit="rad">1.9379533112671359</meanAnomaly>
				</Type2PosVel>
			</bulletin>
		</finalState>
	</EphemerisManager>
	<author>CNES</author>
	<comment>LEO example simulation</comment>
	<simulationDuration unit="years">100.0</simulationDuration>
	<ephemerisStep unit="s">86400.0</ephemerisStep>
	<ttMinusUT1 unit="s">67.184</ttMinusUT1>
	<srpSwitch>true</srpSwitch>
	<sunSwitch>true</sunSwitch>
	<moonSwitch>true</moonSwitch>
	<extrapolationDuration>14725</extrapolationDuration>
	<warningFlag>false</warningFlag>
	<iterativeMode>false</iterativeMode>
	<GTOIntegrator>
		<Integrator>
			<effective_duration unit="years">17.756448296131516</effective_duration>
			<LOSCriteria1 version="2.5.0">
				<status_criteria1>1</status_criteria1>
				<comment_criteria1>Lifetime :17.76 years</comment_criteria1>
			</LOSCriteria1>
			<LOSCriteria2 version="2.5.0">
				<status_criteria2>3</status_criteria2>
			</LOSCriteria2>
			<LOSCriteria3 version="2.5.0">
				<status_criteria3>3</status_criteria3>
			</LOSCriteria3>
			<LOSCriteria4 version="2.5.0">
				<status_criteria4>3</status_criteria4>
			</LOSCriteria4>
		</Integrator>
	</GTOIntegrator>
	<modelType>GTO</modelType>
	<atmosModel>NRLMSISE-00</atmosModel>
	<VariableSolarActivity>
		<solActType>VARIABLE</solActType>
	</VariableSolarActivity>
	<integrationStep unit="s">86400.0</integrationStep>
	<dragSwitch>true</dragSwitch>
	<dragQuadPoints>33</dragQuadPoints>
	<atmosDragRecomputeStep>1</atmosDragRecomputeStep>
	<srpQuadPoints>11</srpQuadPoints>
	<reentryAltitude unit="m">120000.0</reentryAltitude>
	<iterationData>
		<funcValueAccuracy unit="days">10.0</funcValueAccuracy>
		<expDuration unit="years">24.75</expDuration>
		<simMinusExpDuration unit="years">75.25</simMinusExpDuration>
		<iterationMethod>FrozenOrbit</iterationMethod>
	</iterationData>
	<nbIntegrationStepTesseral>5.0</nbIntegrationStepTesseral>
	<zonalOrder>7</zonalOrder>
</LEOSimulation>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd">

<meta name="generator" content="JDiff v1.0.9">

<meta name="description" content="JDiff is a Javadoc doclet which generates an HTML report of all the packages, classes, constructors, methods, and fields which have been removed, added or changed in any way, including their documentation, when two APIs are compared.">
<meta name="keywords" content="diff, jdiff, javadiff, java diff, java difference, API difference, difference between two APIs, API diff, Javadoc, doclet">
<TITLE>
org.apache.hadoop.mapred.lib.MultipleOutputs
</TITLE>
<LINK REL="stylesheet" TYPE="text/css" HREF="../stylesheet-jdiff.css" TITLE="Style">

       <tt>hadoop 0.20.2-cdh3u0</tt>
       Overview
       Package
        Class
       Statistics
       Help

  Generated by
JDiff

 PREV CLASS
 NEXT CLASS

  FRAMES
   NO FRAMES
   DETAIL:
CONSTRUCTORS |
METHODS |
FIELDS

Class org.apache.hadoop.mapred.lib.<tt>MultipleOutputs</tt>

Now deprecated.

  Changed Methods

  <nobr>void <tt>addMultiNamedOutput</tt>(JobConf,</nobr> String<nobr>,</nobr> Class<nobr>,</nobr> Class<nobr>,</nobr> Class<nobr><nobr>)  </nobr>

Change in signature from (JobConf, String, Class<?, extends, OutputFormat>, Class<?>, Class<?>) to (JobConf, String, Class, Class, Class).

  Adds a multi named output for the job.

  <nobr>void <tt>addNamedOutput</tt>(JobConf,</nobr> String<nobr>,</nobr> Class<nobr>,</nobr> Class<nobr>,</nobr> Class<nobr><nobr>)  </nobr>

Change in signature from (JobConf, String, Class<?, extends, OutputFormat>, Class<?>, Class<?>) to (JobConf, String, Class, Class, Class).

  Adds a named output for the job.

  <nobr>Class <tt>getNamedOutputFormatClass</tt>(JobConf,</nobr> String<nobr><nobr>)  </nobr>

Change in return type from (Class<?, extends, OutputFormat>) to Class.

  Returns the named output OutputFormat.

  <nobr>Class <tt>getNamedOutputKeyClass</tt>(JobConf,</nobr> String<nobr><nobr>)  </nobr>

Change in return type from (Class<?, extends, WritableComparable>) to Class.

  Returns the key class for a named output.

  <nobr>Class <tt>getNamedOutputValueClass</tt>(JobConf,</nobr> String<nobr><nobr>)  </nobr>

Change in return type from (Class<?, extends, Writable>) to Class.

  Returns the value class for a named output.

  <nobr>Iterator <tt>getNamedOutputs</tt>()  </nobr>

Change in return type from String> to Iterator.

  Returns iterator with the defined name outputs.

  <nobr>List <tt>getNamedOutputsList</tt>(JobConf)  </nobr>

Change in return type from String> to List.

  Returns list of channel names.

       <tt>hadoop 0.20.2-cdh3u0</tt>
       Overview
       Package
        Class
       Statistics
       Help

 PREV CLASS
 NEXT CLASS

  FRAMES
   NO FRAMES


text:
/*$Id: ManagePatternsPopupDialog.java,v 1.1.2.4.2.15 2008/07/17 19:16:32 christianfoltin Exp $*/

package accessories.plugins.dialogs;

import java.awt.CardLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.util.logging.Logger;

import javax.swing.AbstractAction;
import javax.swing.AbstractListModel;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import com.jgoodies.forms.factories.ButtonBarFactory;

import freemind.common.TextTranslator;
import freemind.controller.StructuredMenuHolder;
import freemind.controller.actions.generated.instance.ManageStyleEditorWindowConfigurationStorage;
import freemind.controller.actions.generated.instance.Pattern;
import freemind.main.Tools;
import freemind.modes.MindMapNode;
import freemind.modes.StylePatternFactory;
import freemind.modes.mindmapmode.MindMapController;
import freemind.modes.mindmapmode.dialogs.StylePatternFrame;
import freemind.modes.mindmapmode.dialogs.StylePatternFrame.StylePatternFrameType;

/** */
public class ManagePatternsPopupDialog extends JDialog implements
		TextTranslator, KeyListener {
	private static Pattern sLastSelectedPattern = null;

	private static final String STACK_PATTERN_FRAME = "PATTERN";

	private static final String EMPTY_FRAME = "EMPTY_FRAME";

	private Pattern mLastSelectedPattern = null;

	private final class PatternListSelectionListener implements
			ListSelectionListener {

		public void valueChanged(ListSelectionEvent e) {
			if (e.getValueIsAdjusting() || mIsDragging)
				return;
			// save old list:
			writePatternBackToModel();
			JList theList = (JList) e.getSource();
			if (theList.isSelectionEmpty()) {
				mCardLayout.show(mRightStack, EMPTY_FRAME);
			} else {
				int index = theList.getSelectedIndex();
				Pattern p = mPatternListModel.getPatternAt(index);
				setLastSelectedPattern(p);
				// write pattern:
				mStylePatternFrame.setPatternList(mPatternListModel
						.getPatternList());
				mStylePatternFrame.setPattern(p);
				mCardLayout.show(mRightStack, STACK_PATTERN_FRAME);
			}
		}
	}

	protected final class PatternListModel extends AbstractListModel {
		private final List mPatternList;

		// private final List mListeners;

		public PatternListModel(List patternList) {
			// we take a copy of the list as it may came from the patterns xml
			// element and would be read-only
			this.mPatternList = new Vector(patternList);
			// this.mListeners = new Vector();
		}

		public int getSize() {
			return mPatternList.size();
		}

		/**
		 * @return the name of the pattern belonging to index.
		 */
		public Object getElementAt(int index) {
			return getPatternAt(index).getName();
			// return
			// "

"+getPatternAt(index).getName()+"	TEST

";
		}

		/**
		 * @return the pattern belonging to index.
		 */
		public Pattern getPatternAt(int index) {
			return ((Pattern) mPatternList.get(index));
		}

		public List getPatternList() {
			return Collections.unmodifiableList(mPatternList);
		}

		public void removePattern(int index) {
			if (index < 0 || index >= mPatternList.size()) {
				throw new IllegalArgumentException(
						"try to delete in pattern list with an index out of range: "
								+ index);
			}
			logger.info("Pattern "
					+ ((Pattern) mPatternList.get(index)).getName()
					+ " should be removed at " + index);
			mPatternList.remove(index);
			fireIntervalRemoved(mList, index, index);
		}

		public void addPattern(Pattern newPattern, int selectedIndex) {
			logger.info("Pattern " + newPattern.getName()
					+ " should be added at " + selectedIndex);
			mPatternList.add(selectedIndex, newPattern);
			fireIntervalAdded(mList, selectedIndex, selectedIndex);
		}

		private void printPatterns() {
			int i = 0;
			for (Iterator iter = mPatternList.iterator(); iter.hasNext();) {
				Pattern pattern = (Pattern) iter.next();
				logger.info("Pattern " + i + " = " + pattern.getName());
				i++;
			}
		}

		public Pattern getPatternByName(String name) {
			for (Iterator iter = mPatternList.iterator(); iter.hasNext();) {
				Pattern pattern = (Pattern) iter.next();
				if (pattern.getName().equals(name)) {
					return pattern;
				}
			}
			return null;
		}

		public void add(int i, Object object) {
			if (object instanceof String) {
				String patternName = (String) object;
				Pattern correspondingPattern = getPatternByName(patternName);
				if (correspondingPattern != null) {
					addPattern(correspondingPattern, i);
				}
			}
		}

		public void remove(int i) {
			removePattern(i);
		}
	}

	private static final String WINDOW_PREFERENCE_STORAGE_PROPERTY = "accessories.plugins.dialogs.ManagePatternsPopupDialog/window_positions";

	public static final int CANCEL = -1;

	public static final int OK = 1;

	private int result = CANCEL;

	private javax.swing.JPanel jContentPane = null;

	private MindMapController mController;

	private JButton jCancelButton;

	private JButton jOKButton;

	private CardLayout mCardLayout;

	private JPanel mRightStack;

	private PatternListModel mPatternListModel;

	private JPopupMenu popupMenu;

	private StylePatternFrame mStylePatternFrame;

	private JList mList;

	private boolean mIsDragging = false;

	private accessories.plugins.dialogs.ArrayListTransferHandler mArrayListHandler;

	private JSplitPane mSplitPane;

	private static Logger logger = null;

	/**
	 * This is the default constructor
	 */
	public ManagePatternsPopupDialog(JFrame caller, MindMapController controller) {
		super(caller);
		this.mController = controller;
		if (logger == null) {
			logger = mController.getFrame()
					.getLogger(this.getClass().getName());
		}
		List patternList = new Vector();
		try {
			patternList = StylePatternFactory.loadPatterns(controller
					.getPatternReader());
		} catch (Exception e) {
			freemind.main.Resources.getInstance().logException(e);
			JOptionPane.showMessageDialog(this, getDialogTitle(), controller
					.getText("accessories/plugins/ManagePatterns.not_found"),
					JOptionPane.ERROR_MESSAGE);
		}
		initialize(patternList);
	}

	/**
	 * This method initializes this
	 *
	 *
	 * @return void
	 */
	private void initialize(List patternList) {
		this.setTitle(getDialogTitle());
		JPanel contentPane = getJContentPane(patternList);
		this.setContentPane(contentPane);
		setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent we) {
				cancelPressed();
			}
		});
		Action cancelAction = new AbstractAction() {

			public void actionPerformed(ActionEvent arg0) {
				cancelPressed();
			}
		};
		Tools.addEscapeActionToDialog(this, cancelAction);
		// // recover latest pattern:
		int i = 0;
		if (sLastSelectedPattern != null) {
			for (Iterator iterator = mPatternListModel.getPatternList()
					.iterator(); iterator.hasNext();) {
				Pattern pattern = (Pattern) iterator.next();
				if (pattern.getName().equals(sLastSelectedPattern.getName())) {
					mList.setSelectedIndex(i);
					break;
				}
				++i;
			}
		}
		this.pack();
		ManageStyleEditorWindowConfigurationStorage decorateDialog = (ManageStyleEditorWindowConfigurationStorage) mController
				.decorateDialog(this, WINDOW_PREFERENCE_STORAGE_PROPERTY);
		if (decorateDialog != null) {
			mSplitPane.setDividerLocation(decorateDialog.getDividerPosition());
		}
	}

	/**
	 */
	private String getDialogTitle() {
		return mController
				.getText("accessories/plugins/ManagePatterns.dialog.title");
	}

	private void close() {
		ManageStyleEditorWindowConfigurationStorage storage = new ManageStyleEditorWindowConfigurationStorage();
		storage.setDividerPosition(mSplitPane.getDividerLocation());
		mController.storeDialogPositions(this, storage,
				WINDOW_PREFERENCE_STORAGE_PROPERTY);
		this.dispose();

	}

	private void okPressed() {
		result = OK;
		writePatternBackToModel();
		close();
	}

	private void cancelPressed() {
		result = CANCEL;
		close();
	}

	/**
	 * This method initializes jContentPane
	 *
	 *
	 * @return javax.swing.JPanel
	 */
	private javax.swing.JPanel getJContentPane(List patternList) {
		if (jContentPane == null) {
			jContentPane = new javax.swing.JPanel();
			jContentPane.setLayout(new GridBagLayout());
			mList = new JList();
			mArrayListHandler = new ArrayListTransferHandler();
			mList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			mPatternListModel = new PatternListModel(patternList);
			mList.setModel(mPatternListModel);
			mList.setTransferHandler(mArrayListHandler);
			mList.setDragEnabled(true);
			mList.addListSelectionListener(new PatternListSelectionListener());
			mList.addMouseMotionListener(new MouseMotionListener() {

				public void mouseDragged(MouseEvent pE) {
					// TODO Auto-generated method stub
					mIsDragging = true;
				}

				public void mouseMoved(MouseEvent pE) {
					// TODO Auto-generated method stub
					mIsDragging = false;
				}
			});
			/* Some common action listeners */
			ActionListener addPatternActionListener = new ActionListener() {
				public void actionPerformed(ActionEvent actionEvent) {
					addPattern(actionEvent);
				}
			};
			ActionListener fromNodesActionListener = new ActionListener() {
				public void actionPerformed(ActionEvent actionEvent) {
					insertPatternFromNode(actionEvent);
				}
			};
			ActionListener applyActionListener = new ActionListener() {
				public void actionPerformed(ActionEvent actionEvent) {
					applyToNode(actionEvent);
				}
			};
			/** Menu **/
			JMenuBar menu = new JMenuBar();
			StructuredMenuHolder menuHolder = new StructuredMenuHolder();
			JMenu mainItem = new JMenu(
					mController.getText("ManagePatternsPopupDialog.Actions"));
			menuHolder.addMenu(mainItem, "main/actions/.");
			JMenuItem menuItemApplyPattern = new JMenuItem(
					mController.getText("ManagePatternsPopupDialog.apply"));
			menuItemApplyPattern.addActionListener(applyActionListener);
			menuHolder.addMenuItem(menuItemApplyPattern, "main/actions/apply");
			JMenuItem menuItemAddPattern = new JMenuItem(
					mController.getText("ManagePatternsPopupDialog.add"));
			menuItemAddPattern.addActionListener(addPatternActionListener);
			menuHolder.addMenuItem(menuItemAddPattern, "main/actions/add");
			JMenuItem menuItemPatternFromNodes = new JMenuItem(
					mController.getText("ManagePatternsPopupDialog.from_nodes"));
			menuItemPatternFromNodes.addActionListener(fromNodesActionListener);
			menuHolder.addMenuItem(menuItemPatternFromNodes,
					"main/actions/from_nodes");
			menuHolder.updateMenus(menu, "main/");
			this.setJMenuBar(menu);
			/* Popup menu */
			popupMenu = new JPopupMenu();
			// menuHolder.addMenuItem(new JPopupMenu.Separator());
			JMenuItem menuItemApply = new JMenuItem(
					mController.getText("ManagePatternsPopupDialog.apply"));
			menuHolder.addMenuItem(menuItemApply, "popup/apply");
			menuItemApply.addActionListener(applyActionListener);
			JMenuItem menuItemAdd = new JMenuItem(
					mController.getText("ManagePatternsPopupDialog.add"));
			menuHolder.addMenuItem(menuItemAdd, "popup/add");
			menuItemAdd.addActionListener(addPatternActionListener);
			JMenuItem menuItemDuplicate = new JMenuItem(
					mController.getText("ManagePatternsPopupDialog.duplicate"));
			menuHolder.addMenuItem(menuItemDuplicate, "popup/duplicate");
			menuItemDuplicate.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent actionEvent) {
					duplicatePattern(actionEvent);
				}
			});
			JMenuItem menuItemFromNodes = new JMenuItem(
					mController.getText("ManagePatternsPopupDialog.from_nodes"));
			menuHolder.addMenuItem(menuItemFromNodes, "popup/from_nodes");
			menuItemFromNodes.addActionListener(fromNodesActionListener);
			menuHolder.addSeparator("popup/sep");
			JMenuItem menuItemRemove = new JMenuItem(
					mController.getText("ManagePatternsPopupDialog.remove"));
			menuItemRemove.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent actionEvent) {
					removePattern(actionEvent);
				}
			});
			menuHolder.addMenuItem(menuItemRemove, "popup/remove");
			menuHolder.updateMenus(popupMenu, "popup/");
			mList.addMouseListener(new MouseAdapter() {
				public void mouseReleased(MouseEvent me) {
					showPopup(mList, me);
				}

				/** For Linux */
				public void mousePressed(MouseEvent me) {
					showPopup(mList, me);
				}

				private void showPopup(final JList mList, MouseEvent me) {
					// if right mouse button clicked (or me.isPopupTrigger())
					if (me.isPopupTrigger()
							&& !mList.isSelectionEmpty()
							&& mList.locationToIndex(me.getPoint()) == mList
									.getSelectedIndex()) {
						popupMenu.show(mList, me.getX(), me.getY());
					}
				}
			});

			mCardLayout = new CardLayout();
			mRightStack = new JPanel(mCardLayout);
			mRightStack.add(new JPanel(), EMPTY_FRAME);
			mStylePatternFrame = new StylePatternFrame(this, mController,
					StylePatternFrameType.WITH_NAME_AND_CHILDS);
			mStylePatternFrame.init();
			mStylePatternFrame.addListeners();
			mRightStack.add(new JScrollPane(mStylePatternFrame),
					STACK_PATTERN_FRAME);
			JScrollPane leftPane = new JScrollPane(mList);
			mSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true,
					leftPane, mRightStack);
			jContentPane.add(mSplitPane, new GridBagConstraints(0, 0, 2, 1,
					1.0, 8.0, GridBagConstraints.WEST, GridBagConstraints.BOTH,
					new Insets(0, 0, 0, 0), 0, 0));
			jContentPane.add(ButtonBarFactory.buildOKCancelBar(
					getJCancelButton(), getJOKButton()),
					new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0,
							GridBagConstraints.EAST, GridBagConstraints.NONE,
							new Insets(0, 0, 0, 0), 0, 0));
			// jContentPane.add(getJOKButton(), new GridBagConstraints(1, 1, 1,
			// 1,
			// 1.0, 1.0, GridBagConstraints.EAST, GridBagConstraints.NONE,
			// new Insets(0, 0, 0, 0), 0, 0));
			// jContentPane.add(getJCancelButton(), new GridBagConstraints(2, 1,
			// 1, 1, 1.0, 1.0, GridBagConstraints.EAST,
			// GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
			getRootPane().setDefaultButton(getJOKButton());
		}
		return jContentPane;
	}

	private void addPattern(ActionEvent actionEvent) {
		writePatternBackToModel();
		setLastSelectedPattern(null);
		Pattern newPattern = new Pattern();
		newPattern.setName(searchForNameForNewPattern());
		int selectedIndex = mList.getSelectedIndex();
		if (selectedIndex < 0) {
			selectedIndex = mList.getModel().getSize();
		}
		mPatternListModel.addPattern(newPattern, selectedIndex);
		mList.setSelectedIndex(selectedIndex);
	}

	private void duplicatePattern(ActionEvent actionEvent) {
		int selectedIndex = mList.getSelectedIndex();
		writePatternBackToModel();
		setLastSelectedPattern(null);
		Pattern oldPattern = mPatternListModel.getPatternAt(selectedIndex);
		// deep copy:
		Pattern newPattern = (Pattern) Tools.deepCopy(oldPattern);
		newPattern.setName(searchForNameForNewPattern());
		mPatternListModel.addPattern(newPattern, selectedIndex);
		mList.setSelectedIndex(selectedIndex);
	}

	private void insertPatternFromNode(ActionEvent actionEvent) {
		writePatternBackToModel();
		setLastSelectedPattern(null);
		Pattern newPattern = StylePatternFactory.createPatternFromSelected(
				mController.getSelected(), mController.getSelecteds());
		newPattern.setName(searchForNameForNewPattern());
		int selectedIndex = mList.getSelectedIndex();
		if (selectedIndex < 0) {
			selectedIndex = mList.getModel().getSize();
		}
		mPatternListModel.addPattern(newPattern, selectedIndex);
		mList.setSelectedIndex(selectedIndex);
	}

	private void applyToNode(ActionEvent actionEvent) {
		int selectedIndex = mList.getSelectedIndex();
		if (selectedIndex < 0)
			return;
		writePatternBackToModel();
		setLastSelectedPattern(null);
		Pattern pattern = mPatternListModel.getPatternAt(selectedIndex);
		for (Iterator iterator = mController.getSelecteds().iterator(); iterator
				.hasNext();) {
			MindMapNode node = (MindMapNode) iterator.next();
			mController.applyPattern(node, pattern);
		}
	}

	private String searchForNameForNewPattern() {
		// give it a good name:
		String newName = mController.getText("PatternNewNameProperty");
		// collect names:
		Vector allNames = new Vector();
		for (Iterator iter = mPatternListModel.getPatternList().iterator(); iter
				.hasNext();) {
			Pattern p = (Pattern) iter.next();
			allNames.add(p.getName());
		}
		String toGiveName = newName;
		int i = 1;
		while (allNames.contains(toGiveName)) {
			toGiveName = newName + i;
			++i;
		}
		return toGiveName;
	}

	private void removePattern(ActionEvent actionEvent) {
		int selectedIndex = mList.getSelectedIndex();
		setLastSelectedPattern(null);
		mPatternListModel.removePattern(selectedIndex);
		if (mPatternListModel.getSize() > selectedIndex) {
			mList.setSelectedIndex(selectedIndex);
		} else if (mPatternListModel.getSize() > 0 && selectedIndex >= 0) {
			mList.setSelectedIndex(selectedIndex - 1);
		} else {
			// empty
			mList.clearSelection();
		}
	}

	/**
	 * This method initializes jButton
	 *
	 * @return javax.swing.JButton
	 */
	private JButton getJOKButton() {
		if (jOKButton == null) {
			jOKButton = new JButton();

			jOKButton.setAction(new AbstractAction() {

				public void actionPerformed(ActionEvent e) {
					okPressed();
				}

			});

			jOKButton.setText(mController
					.getText("ManagePatternsPopupDialog.Save"));
		}
		return jOKButton;
	}

	/**
	 * This method initializes jButton1
	 *
	 * @return javax.swing.JButton
	 */
	private JButton getJCancelButton() {
		if (jCancelButton == null) {
			jCancelButton = new JButton();
			jCancelButton.setAction(new AbstractAction() {

				public void actionPerformed(ActionEvent e) {
					cancelPressed();
				}
			});
			Tools.setLabelAndMnemonic(jCancelButton, getText("cancel"));
		}
		return jCancelButton;
	}

	/**
	 * @return Returns the result.
	 */
	public int getResult() {
		return result;
	}

	public String getText(String pKey) {
		return mController.getText(pKey);
	}

	public List getPatternList() {
		return mPatternListModel.getPatternList();
	}

	private void writePatternBackToModel() {
		if (getLastSelectedPattern() != null) {
			// save pattern:
			Pattern pattern = getLastSelectedPattern();
			Pattern resultPatternCopy = mStylePatternFrame.getResultPattern();
			// check for name change:
			String oldPatternName = pattern.getName();
			String newPatternName = resultPatternCopy.getName();
			if (!(oldPatternName.equals(newPatternName))) {
				// now, let's check, whether or not it is still unique:
				for (Iterator iter = mPatternListModel.getPatternList()
						.iterator(); iter.hasNext();) {
					Pattern otherPattern = (Pattern) iter.next();
					if (otherPattern == pattern) {
						// myself is not regarded:
						continue;
					}
					if (otherPattern.getName().equals(newPatternName)) {
						// duplicate found. What now?
						JOptionPane
								.showMessageDialog(
										this,
										mController
												.getText("ManagePatternsPopupDialog.DuplicateNameMessage"));
					}
				}
			}
			// no duplicates. We search for uses of the old name:
			for (Iterator iter = mPatternListModel.getPatternList().iterator(); iter
					.hasNext();) {
				Pattern otherPattern = (Pattern) iter.next();
				if (otherPattern.getPatternChild() != null
						&& oldPatternName.equals(otherPattern.getPatternChild()
								.getValue())) {
					// change to new name
					otherPattern.getPatternChild().setValue(newPatternName);
				}
			}
			mStylePatternFrame.getResultPattern(pattern);
			// Special case that a pattern that points to itself is renamed:
			if (pattern.getPatternChild() != null
					&& oldPatternName.equals(pattern.getPatternChild()
							.getValue())) {
				pattern.getPatternChild().setValue(newPatternName);
			}
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent)
	 */
	public void keyPressed(KeyEvent keyEvent) {
		// System.out.println("key pressed: " + keyEvent);
		switch (keyEvent.getKeyCode()) {
		case KeyEvent.VK_ESCAPE:
			keyEvent.consume();
			cancelPressed();
			break;
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
	 */
	public void keyReleased(KeyEvent keyEvent) {
		// System.out.println("keyReleased: " + keyEvent);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent)
	 */
	public void keyTyped(KeyEvent keyEvent) {
		// System.out.println("keyTyped: " + keyEvent);
	}

	public Pattern getLastSelectedPattern() {
		return mLastSelectedPattern;
	}

	public void setLastSelectedPattern(Pattern pLastSelectedPattern) {
		mLastSelectedPattern = pLastSelectedPattern;
		sLastSelectedPattern = pLastSelectedPattern;
	}

}


text:
package com.mobilejazz.coltrane.provider.filesystem;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.net.Uri;
import android.os.CancellationSignal;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.provider.BaseColumns;
import android.util.Base64;

import com.mobilejazz.coltrane.library.DocumentsProvider;
import com.mobilejazz.coltrane.library.DocumentsProviderRegistry;
import com.mobilejazz.coltrane.library.Root;
import com.mobilejazz.coltrane.library.UserRecoverableException;
import com.mobilejazz.coltrane.library.compatibility.DocumentsContract;
import com.mobilejazz.coltrane.library.utils.DocumentCursor;
import com.mobilejazz.coltrane.library.utils.ListCursor;
import com.mobilejazz.coltrane.library.utils.thumbnail.Thumbnail;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import timber.log.Timber;

public class FileSystemProvider extends DocumentsProvider {

    public static final String ID = "com.mobilejazz.coltrane.provider.filesystem";

    /**
     * Default document projection: everything but Document.COLUMN_ICON and
     * Document.COLUMN_SUMMARY
     */
    private final static String[] DEFAULT_DOCUMENT_PROJECTION = new String[] {
            BaseColumns._ID,
            DocumentsContract.Document.COLUMN_DOCUMENT_ID,
            DocumentsContract.Document.COLUMN_DISPLAY_NAME, DocumentsContract.Document.COLUMN_FLAGS, DocumentsContract.Document.COLUMN_MIME_TYPE,
            DocumentsContract.Document.COLUMN_SIZE,
            DocumentsContract.Document.COLUMN_LAST_MODIFIED
    };

    private FileAccessor mAccessor = new FileAccessor();

    public FileSystemProvider(Context context) {
        super(context);
    }

    @Override
    public List<Root> getRoots() throws FileNotFoundException {
        // Add Home directory
        File homeDir = Environment.getExternalStorageDirectory();

        String state = Environment.getExternalStorageState();

        if (Environment.MEDIA_MOUNTED.equals(state)) {

            Root root = new Root(this,
                    homeDir.getAbsolutePath(),
                    homeDir.getAbsolutePath(),
                    getContext().getString(R.string.internal_storage),
                    R.drawable.ic_provider_filesystem,
                    homeDir.getFreeSpace(),
                    DocumentsContract.Root.FLAG_LOCAL_ONLY | DocumentsContract.Root.FLAG_SUPPORTS_CREATE);

            return Collections.singletonList(root);

        } else {
            return Collections.emptyList();
        }
    }

    @Override
    public String getName() {
        return getContext().getString(R.string.filesystem_name);
    }

    @Override
    public int getIcon() {
        return R.drawable.ic_provider_filesystem;
    }

    @Override
    public Cursor queryChildDocuments(String parentDocumentId, String[] projection, String sortOrder, String mimeFilter) throws FileNotFoundException {
        final File parent = new File(parentDocumentId);
        List<File> files = new ArrayList<File>();
        for (File file : parent.listFiles()) {
            // Don't show hidden files/folders
            if (!file.getName().startsWith(".")) {
                // Adds the file's display name, MIME type, size, and so on.
                files.add(file);
            }
        }
        return new ListCursor<File>(files, mAccessor, projection, sortOrder, mimeFilter);
    }

    @Override
    public Cursor queryDocument(String documentId, String[] projection) throws FileNotFoundException {
        return new ListCursor<File>(Collections.singletonList(new File(documentId)), mAccessor, projection, null, null);
    }

    @Override
    public ParcelFileDescriptor openDocument(String documentId, String mode, CancellationSignal signal) throws FileNotFoundException {
        File file = new File(documentId);
        return descriptorFromFile(file, mode);
    }

    @Override
    public Uri getDocumentThumbnailUri(String documentId, Point sizeHint, CancellationSignal signal) throws FileNotFoundException, UserRecoverableException {
        File f = new File(documentId);
        return Thumbnail.getDocumentThumbnailUri(getContext(), f, documentId, mAccessor.getMimeType(f), sizeHint);
    }

    @Override
    public String createDocument(String parentDocumentId, String mimeType, String displayName) throws FileNotFoundException {
        File newFile = new File(parentDocumentId, displayName);
        try {
            newFile.createNewFile();
            return newFile.getAbsolutePath();
        } catch (IOException e) {
            Timber.e("Error creating new file " + newFile);
        }
        return null;
    }

    @Override
    public String getId() {
        return ID;
    }

    public static void register(Context context) {
        DocumentsProviderRegistry.get().register(ID, new FileSystemProvider(context));
    }

//    private void includeFile(final MatrixCursor result, final File file, long id)
//            throws FileNotFoundException {
//        final MatrixCursor.RowBuilder row = result.newRow();
//        // These columns are required
//        row.add(BaseColumns._ID, id); // for supporting CursorAdapter
//        row.add(DocumentsContract.Document.COLUMN_DOCUMENT_ID, file.getAbsolutePath());
//        row.add(DocumentsContract.Document.COLUMN_DISPLAY_NAME, file.getName());
//        String mimeType = getDocumentType(file.getAbsolutePath());
//        row.add(DocumentsContract.Document.COLUMN_MIME_TYPE, mimeType);
//        int flags = file.canWrite() ? DocumentsContract.Document.FLAG_SUPPORTS_DELETE | DocumentsContract.Document.FLAG_SUPPORTS_WRITE
//                : 0;
//        // We only show thumbnails for image files - expect a call to
//        // openDocumentThumbnail for each file that has
//        // this flag set
//        if (mimeType.startsWith("image/"))
//            flags |= DocumentsContract.Document.FLAG_SUPPORTS_THUMBNAIL;
//        row.add(DocumentsContract.Document.COLUMN_FLAGS, flags);
//        // COLUMN_SIZE is required, but can be null
//        row.add(DocumentsContract.Document.COLUMN_SIZE, file.length());
//        // These columns are optional
//        row.add(DocumentsContract.Document.COLUMN_LAST_MODIFIED, file.lastModified());
//        // Document.COLUMN_ICON can be a resource id identifying a custom icon.
//        // The system provides default icons
//        // based on mime type
//        // Document.COLUMN_SUMMARY is optional additional information about the
//        // file
//    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ProviderHostedAppPartsWeb.Controllers {
  public class AppPart3Controller : Controller {
    public ActionResult Index() {
      return View();
    }
  }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Xml;

namespace Vuzit
{
    /// <summary>
    /// Vuzit library exception handler class.
    /// </summary>
    public class ClientException : System.Exception
    {
        #region Public properties
        /// <summary>
        /// The error message.
        /// </summary>
        public override string Message
        {
            get { return message; }
        }

        /// <summary>
        /// The Vuzit error code.
        /// </summary>
        public int Code
        {
            get { return code; }
        }
        #endregion

        #region Private variables
        string message = null;
        int code = -1;
        #endregion

        #region Constructors
        /// <summary>
        /// Creates a new exception from a WebException instance.
        /// </summary>
        /// <param name="message"></param>
        /// <param name="ex">The WebException returned. </param>
        public ClientException(string message, WebException ex)
        {
            HttpWebResponse response = (HttpWebResponse)ex.Response;

            XmlDocument doc = new XmlDocument();
            try
            {
                doc.LoadXml(Base.ReadHttpResponse(response));

                XmlNode node = doc.SelectSingleNode("/err/code");
                if (node != null)
                {
                    string code = doc.SelectSingleNode("/err/code").InnerText;
                    string msg = doc.SelectSingleNode("/err/msg").InnerText;

                    this.code = Convert.ToInt32(code);
                    this.message = msg;
                }
            }
            catch
            {
                // There was invalid XML so default to the base error
                Stream errorStream = ex.Response.GetResponseStream();
                StreamReader errorReader = new StreamReader(errorStream);
                string responseText = errorReader.ReadToEnd();
                errorStream.Close();

                this.message = responseText;
                this.code = 0;
            }
        }

        /// <summary>
        /// Creates a new exception instance.
        /// </summary>
        /// <param name="message">Error message. </param>
        public ClientException(string message)
        {
            this.message = message;
        }

        /// <summary>
        /// Creates a new exception instance.
        /// </summary>
        /// <param name="message">Error message. </param>
        /// <param name="code">Error code. </param>
        public ClientException(string message, int code)
        {
            this.message = message;
            this.code = code;
        }

        /// <summary>
        /// Creates a new exception instance.
        /// </summary>
        /// <param name="message">Error message. </param>
        /// <param name="code">Error code. </param>
        public ClientException(string message, string code)
        {
            this.message = message;
            this.code = Convert.ToInt32(code);
        }
        #endregion
    }
}


text: Tests Components.Spectrum


text:
;(function(win, analytics, ch){
	'use strict';

	win.setTracker = function(resolve)
	{
		win.trackerService = analytics.getService('jira-extras');
		win.trackerService.getConfig().addCallback(
			function(config)
			{
				win.tracker = config.isTrackingPermitted() ? win.trackerService.getTracker('UA-73823583-1') : win.fakeTracker;
				win.tracker.trackEvent = function(sCategory, sAction)
				{
					win.tracker.sendEvent(sCategory, sAction, win.JSON.stringify({
						extension : {
							version : ch.app.getDetails().version,
							id : ch.app.getDetails().id
						},
						useragent : win.navigator.userAgent
					}));
				};

				resolve();
			}
		);
	}
}(window, analytics, chrome));


text:
from django.apps import AppConfig

class FooappConfig(AppConfig):
    name = 'fooapp'


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="broadcasts">Overføringar</string>
  <string name="liveBroadcasts">Direktesende turneringar</string>
  <string name="newBroadcast">Ny direktesending</string>
  <string name="addRound">Legg til ein runde</string>
  <string name="ongoing">Pågåande</string>
  <string name="upcoming">Kommande</string>
  <string name="completed">Fullførde</string>
  <string name="roundName">Rundenamn</string>
  <string name="roundNumber">Rundenummer</string>
  <string name="tournamentName">Turneringsnamn</string>
  <string name="tournamentDescription">Kortfatta skildring av turneringa</string>
  <string name="fullDescription">Full omtale av arrangementet</string>
  <string name="fullDescriptionHelp">Valfri lang omtale av overføringa. %1$s er tilgjengeleg. Omtalen må vera kortare enn %2$s teikn.</string>
  <string name="sourceUrlOrGameIds">Kjelde-URL eller parti-ID-ar</string>
  <string name="sourceUrlHelp">Lenke som Lichess vil hente PGN-oppdateringar frå. Den må vera offentleg tilgjengeleg på internett.</string>
  <string name="gameIdsHelp">Som eit alternativ kan du skriva opp til 64 Lichess-ID\'ar, skilde frå kvarandre med eit mellomrom.</string>
  <string name="startDate">Startdato i di eiga tidssone</string>
  <string name="startDateHelp">Valfritt, om du veit når arrangementet startar</string>
  <string name="credits">Kreditér kjelda</string>
  <string name="resetRound">Tilbakestill denne runden</string>
  <string name="deleteRound">Slett denne runden</string>
  <string name="broadcastUrl">Kunngjerings-URL</string>
  <string name="currentRoundUrl">URL til noverande runde</string>
  <string name="currentGameUrl">URL til pågåande parti</string>
  <string name="downloadAllRounds">Last ned alle rundene</string>
</resources>


text:
#pragma once

enum	{	kLexPlus, kLexMinus, kLexAbs,
			kLexMultiply, kLexDivide, kLexModulo, kLexPower,
			kLexLt, kLexGt, kLexEq,
			kLexLtEq, kLexGtEq,
			kLexStore,
			kLexMin, kLexMax,
			kLexOpenParen, kLexCloseParen,
			kLexRowOffset, kLexConstant,
			kUnaryMinus, kLexVariable,
			kLexFun0, kLexFun1,
			kLexEnum,
			kLexUnique,
			kLexEnd,
			kLexAdjust,
			kLexObject,
			kAssignment,
			kParseError, kLexEof	};

enum	{	kMinKey, kMaxKey,
			kRandomKey, kSinKey, kCosKey,
			kIntKey, kRoundKey,
			kEnumKey,
			kUniqueKey,
			kEndKey,
			kAdjustKey,
			kObjectKey, firstVariable };

typedef struct
{
	short	kind;			//	Determines what this lexical symbol is.

	union
	{	double	floating;		//	Used for numeric constants.
		long	offset;			//	Used as offset into datacube.
		long	token;			//	Token for variable
		long	level;			//	Level number from level statement
	}	value;
}	LexSymbol;

typedef	struct
{
	StringPtr	input;
	Handle		output;
	long		realSize;
	long		logicalSize;

	LexSymbol	lookahead;

	short		stackDepth;
	short		stackMax;
}	ParserVariables;

void		CreateVariable(long token);
void		ParseCompare();
void		ParseExpr();
void		LexRead(LexSymbol *theSymbol);
void		EmitInstruction(LexSymbol *theOperation,short stackChange);
void		LoadLevel(short whichLevel);
double		EvalVariable(long token, Boolean forceCalc);
void		WriteVariable(long token, double value);

void		RunThis(StringPtr theScript);
void		AllocParser();
void		DeallocParser();
void		InitParser();
void		FreshCalc();


text:
/*
*  author: amit tank
*  module : network traffic analyzer
*  file :  common util routines.
*/

#define PARTITION_SIZE 10000
#define MAX_PARTITION_NUMBERS 20

INT PacketPosition[MAX_PARTITION_NUMBERS];
INT PacketIndex[MAX_PARTITION_NUMBERS];
INT PartionPositionArray[20];
INT CurrentPartition=0;

ULONG TotalPacketCount=0;

INT GetSearchPartition(INT PacketIndex);
INT GetSearchPosition(INT PacketIndex);
INT GetSearchIndex(INT PacketIndex);

struct PktHeader {
	ULARGE_INTEGER PktTimeStamp;
	UINT PktPacketSize;
};

/*
void CloseDumpFile();
BOOLEAN OpenDumpFile();
void DumpPacketContent(PUCHAR,ULONG);
BOOLEAN bDumpFlag = FALSE;
*/

HANDLE hPktDumpFile = NULL;
BOOLEAN DUMPFILEOPEN = FALSE;
DWORD dwFileSizeHigh;
DWORD BytesWritten;
char DumpFilePath[256];

void ErrorCheck(){

LPVOID lpMsgBuf;

FormatMessage(
    FORMAT_MESSAGE_ALLOCATE_BUFFER |
    FORMAT_MESSAGE_FROM_SYSTEM |
    FORMAT_MESSAGE_IGNORE_INSERTS,
    NULL,
    GetLastError(),
    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
    (LPTSTR) &lpMsgBuf,
    0,
    NULL
);
// Display the string.
MessageBox( NULL, (LPCTSTR)lpMsgBuf, "Error", MB_OK | MB_ICONINFORMATION );
// Free the buffer.
LocalFree( lpMsgBuf );

}

void PacketToHex(PCHAR PacketHoldBuffer,PUCHAR BytesReadFromFile,LONG BytesRead) {

		char TempStr[15];
		int Count=0;
		int PrintBufferLength=0;//16;//1514;
		int nCounter=0;

		lstrcpy(PacketHoldBuffer,"\0");

		PrintBufferLength = BytesRead;
		while(nCounter<PrintBufferLength){

				if((nCounter%16)==0){
					wsprintf(TempStr,"\r\n %08d :  ",Count);
					lstrcat(PacketHoldBuffer,TempStr);
					Count++;
				}

				if((nCounter%8)==0)
						lstrcat(PacketHoldBuffer,"    ");
			wsprintf(TempStr," %02x",(BYTE)*(BytesReadFromFile+nCounter));
			//wsprintf(TempStr,"%c",(unsigned char)*(BytesReadFromFile+nCounter));
			//wsprintf(TempStr,"0E ");
			lstrcat(PacketHoldBuffer,TempStr);
			nCounter++;
			}

		//wsprintf(TempStr,"******%d",lstrlen(buffer));
		//lstrcat(buffer,TempStr);
		lstrcat(PacketHoldBuffer,"\0");

		return;
}

void CopyPacketContent(char * str) {
char buffer[8000];
char TempStr[15];
int Count=0;
int PrintBufferLength=1514;
int nCounter=0;

lstrcpy(buffer,"\0");

while(nCounter<PrintBufferLength){

		if((nCounter%16)==0){
			wsprintf(TempStr,"\r\n %08d :  ",Count);
			lstrcat(buffer,TempStr);
			Count++;
		}

		if((nCounter%8)==0)
				lstrcat(buffer," ");
	//wsprintf(TempStr," %02x",(BYTE)*(PrintBuffer+nCounter));
	wsprintf(TempStr,"0E ");
	lstrcat(buffer,TempStr);
	nCounter++;
	}

//wsprintf(TempStr,"******%d",lstrlen(buffer));
//lstrcat(buffer,TempStr);
lstrcat(buffer,"\0");

strcpy(str,buffer);
return;
}

BOOLEAN OpenDumpFile() {

	PCHAR SummaryFileName = DumpFilePath;//"e:\\pktdump.txt";

//	char  lpFileBuffer[600];
//	char TempBuffer[20];

	hPktDumpFile = CreateFile(
					SummaryFileName,
					GENERIC_READ,
					FILE_SHARE_READ,
					NULL,
					OPEN_EXISTING,
					FILE_ATTRIBUTE_NORMAL,
					NULL
					);

	if(hPktDumpFile == INVALID_HANDLE_VALUE)
				return FALSE;

	SetFilePointer(
		hPktDumpFile,
		0,//GetFileSize(hPktDumpFile,&dwFileSizeHigh),
		NULL,
		FILE_BEGIN
	);

//WriteFile(hPktDumpFile,lpFileBuffer,lstrlen(lpFileBuffer),&BytesWritten,NULL);//strlen(lpFileBuffer),NULL,NULL);
//ErrorCheck();

	return TRUE;
}

ULONG GetDumpContent(int Index,PCHAR PacketHoldBuffer, PUCHAR tmpRawPktFrame, PUINT tmpRawPktFrameLength) {

ULONG BytesToRead,BytesRead;
char str[50];
UCHAR FileHoldBuffer[MAX_PANE_SIZE];
struct PktHeader *PacketHeader;
int PacketCounter=0;
INT StartSearchIndex =0;
INT StartSearchPosition =0;

//StartSearchIndex = GetSearchIndex(Index);
//StartSearchPosition = GetSearchPosition(Index);
//PacketCounter = StartSearchIndex;

	SetFilePointer(
		hPktDumpFile,
		StartSearchPosition,//GetFileSize(hPktDumpFile,&dwFileSizeHigh),
		NULL,
		FILE_BEGIN
	);

		do {
			BytesToRead = sizeof(struct PktHeader);
			ReadFile(hPktDumpFile,FileHoldBuffer,BytesToRead,&BytesRead,NULL);
			//ErrorCheck();

			PacketHeader = (struct PktHeader*)FileHoldBuffer;

			BytesToRead = PacketHeader->PktPacketSize;

			ReadFile(hPktDumpFile,FileHoldBuffer,BytesToRead,&BytesRead,NULL);

			//SetFilePointer(hPktDumpFile,(long)BytesToRead,NULL,FILE_CURRENT);

			PacketCounter++;
		}
		while(PacketCounter <= Index);

	/***********************************/
	//lstrcpy((LPSTR)tmpRawPktFrame,(LPSTR)FileHoldBuffer);
	memcpy(tmpRawPktFrame,FileHoldBuffer,BytesRead);
	*tmpRawPktFrameLength = BytesRead;

	/***********************************/

	PacketToHex(PacketHoldBuffer,FileHoldBuffer,BytesRead);

	wsprintf(str,"\r\n\r\n\r\n");
	lstrcat(PacketHoldBuffer,str);
	wsprintf(str,"Total Packet Size : %d",BytesRead);
	lstrcat(PacketHoldBuffer,str);

//	wsprintf(str,"\nPane Buffer Size : %d",lstrlen(PacketHoldBuffer));
//	lstrcat(PacketHoldBuffer,str);

	return -1;
}

		ULONG GetDumpPacketCount() {

			ULONG BytesToRead,BytesRead,TotalBytesRead=0;
			char FileHoldBuffer[8000];
			struct PktHeader *PacketHeader;
			int TempPacketCount=0;
			int nLower, nUpper;
			UINT ONE_TENTH;
			UINT nLoop=1;
			UINT TotalFileSize=0;
			CWinApp * tmpWinApp = AfxGetApp();

			CDialog *tmpMainWnd = (CDialog*)tmpWinApp->GetMainWnd();
			CProgressCtrl *tmpProgBar = (CProgressCtrl*)tmpMainWnd->GetDlgItem(IDC_PROGRESS);

			TotalFileSize = GetFileSize(hPktDumpFile,&dwFileSizeHigh);

			ONE_TENTH = (TotalFileSize)/1000;
			tmpProgBar->SetRange32(0,TotalFileSize);
			tmpProgBar->GetRange( nLower, nUpper );
			//tmpProgBar->SetStep((TotalFileSize)/10);
			tmpProgBar->SetStep(ONE_TENTH);

				SetFilePointer(
					hPktDumpFile,
					0,//GetFileSize(hPktDumpFile,&dwFileSizeHigh),
					NULL,
					FILE_BEGIN
				);

					do {
						BytesToRead = sizeof(struct PktHeader);
						ReadFile(hPktDumpFile,FileHoldBuffer,BytesToRead,&BytesRead,NULL);
						//ErrorCheck();
						if(BytesRead == 0)
							break;

						TotalBytesRead = TotalBytesRead + BytesRead;

						PacketHeader = (struct PktHeader*)FileHoldBuffer;

						BytesToRead = PacketHeader->PktPacketSize;

						ReadFile(hPktDumpFile,FileHoldBuffer,BytesToRead,&BytesRead,NULL);
						TempPacketCount++;

						TotalBytesRead = TotalBytesRead + BytesRead;

						if(TempPacketCount == ( PARTITION_SIZE * (CurrentPartition+1)) )
						{
							CurrentPartition++;
							PacketIndex[CurrentPartition] = TempPacketCount+1;
							PacketPosition[CurrentPartition] = TotalBytesRead;
							PartionPositionArray[CurrentPartition] = TotalBytesRead;
						}

						if(TotalBytesRead >= (ONE_TENTH * nLoop))
						{
							tmpProgBar->StepIt();
							nLoop++;
						}

					}
					while(BytesRead != 0);

			//tmpProgBar->SetPos(0);

			return TempPacketCount;
		}

INT GetSearchPartition(INT PacketIndex)
{

	return ((PacketIndex) / PARTITION_SIZE);
}

INT GetSearchPosition(INT PacketIndex)
{
INT TmpIndex = GetSearchPartition(PacketIndex);

return PacketPosition[TmpIndex];
}

INT GetSearchIndex(INT PacketIndex)
{

INT TmpIndex = GetSearchPartition(PacketIndex);

//PacketIndex[0] =0;
//PacketIndex[CurrentPartition] = TmpIndex;

return PartionPositionArray[TmpIndex];
}


text:
require 'electric_sheep/commands/database/mongodb_dump'
require 'electric_sheep/commands/database/sql_dump'
require 'electric_sheep/commands/database/mysql_dump'
require 'electric_sheep/commands/database/postgresql_dump'

module ElectricSheep
  module Commands
    module Database
    end
  end
end


text:
import * as nls from 'vs/nls';
import { Registry } from 'vs/platform/registry/common/platform';
import { Action } from 'vs/base/common/actions';
import { IEditorGroupsService, GroupDirection, GroupLocation, IFindGroupScope } from 'vs/workbench/services/editor/common/editorGroupsService';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IWorkbenchLayoutService, Parts, Position as PartPosition } from 'vs/workbench/services/layout/browser/layoutService';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
import { IViewlet } from 'vs/workbench/common/viewlet';
import { IPanel } from 'vs/workbench/common/panel';
import { SyncActionDescriptor } from 'vs/platform/actions/common/actions';
import { IWorkbenchActionRegistry, Extensions } from 'vs/workbench/common/actions';

abstract class BaseNavigationAction extends Action {

	constructor(
		id: string,
		label: string,
		@IEditorGroupsService protected editorGroupService: IEditorGroupsService,
		@IPanelService protected panelService: IPanelService,
		@IWorkbenchLayoutService protected layoutService: IWorkbenchLayoutService,
		@IViewletService protected viewletService: IViewletService
	) {
		super(id, label);
	}

	run(): Promise<any> {
		const isEditorFocus = this.layoutService.hasFocus(Parts.EDITOR_PART);
		const isPanelFocus = this.layoutService.hasFocus(Parts.PANEL_PART);
		const isSidebarFocus = this.layoutService.hasFocus(Parts.SIDEBAR_PART);

		const isSidebarPositionLeft = this.layoutService.getSideBarPosition() === PartPosition.LEFT;
		const isPanelPositionDown = this.layoutService.getPanelPosition() === PartPosition.BOTTOM;

		if (isEditorFocus) {
			return this.navigateOnEditorFocus(isSidebarPositionLeft, isPanelPositionDown);
		}

		if (isPanelFocus) {
			return this.navigateOnPanelFocus(isSidebarPositionLeft, isPanelPositionDown);
		}

		if (isSidebarFocus) {
			return Promise.resolve(this.navigateOnSidebarFocus(isSidebarPositionLeft, isPanelPositionDown));
		}

		return Promise.resolve(false);
	}

	protected navigateOnEditorFocus(_isSidebarPositionLeft: boolean, _isPanelPositionDown: boolean): Promise<boolean | IViewlet | IPanel> {
		return Promise.resolve(true);
	}

	protected navigateOnPanelFocus(_isSidebarPositionLeft: boolean, _isPanelPositionDown: boolean): Promise<boolean | IPanel> {
		return Promise.resolve(true);
	}

	protected navigateOnSidebarFocus(_isSidebarPositionLeft: boolean, _isPanelPositionDown: boolean): boolean | IViewlet {
		return true;
	}

	protected navigateToPanel(): IPanel | boolean {
		if (!this.layoutService.isVisible(Parts.PANEL_PART)) {
			return false;
		}

		const activePanelId = this.panelService.getActivePanel()!.getId();

		return this.panelService.openPanel(activePanelId, true)!;
	}

	protected async navigateToSidebar(): Promise<IViewlet | boolean> {
		if (!this.layoutService.isVisible(Parts.SIDEBAR_PART)) {
			return Promise.resolve(false);
		}

		const activeViewlet = this.viewletService.getActiveViewlet();
		if (!activeViewlet) {
			return Promise.resolve(false);
		}
		const activeViewletId = activeViewlet.getId();

		const value = await this.viewletService.openViewlet(activeViewletId, true);
		return value === null ? false : value;
	}

	protected navigateAcrossEditorGroup(direction: GroupDirection): boolean {
		return this.doNavigateToEditorGroup({ direction });
	}

	protected navigateToEditorGroup(location: GroupLocation): boolean {
		return this.doNavigateToEditorGroup({ location });
	}

	private doNavigateToEditorGroup(scope: IFindGroupScope): boolean {
		const targetGroup = this.editorGroupService.findGroup(scope, this.editorGroupService.activeGroup);
		if (targetGroup) {
			targetGroup.focus();

			return true;
		}

		return false;
	}
}

class NavigateLeftAction extends BaseNavigationAction {

	static readonly ID = 'workbench.action.navigateLeft';
	static readonly LABEL = nls.localize('navigateLeft', "Navigate to the View on the Left");

	constructor(
		id: string,
		label: string,
		@IEditorGroupsService editorGroupService: IEditorGroupsService,
		@IPanelService panelService: IPanelService,
		@IWorkbenchLayoutService layoutService: IWorkbenchLayoutService,
		@IViewletService viewletService: IViewletService
	) {
		super(id, label, editorGroupService, panelService, layoutService, viewletService);
	}

	protected navigateOnEditorFocus(isSidebarPositionLeft: boolean, _isPanelPositionDown: boolean): Promise<boolean | IViewlet> {
		const didNavigate = this.navigateAcrossEditorGroup(GroupDirection.LEFT);
		if (didNavigate) {
			return Promise.resolve(true);
		}

		if (isSidebarPositionLeft) {
			return this.navigateToSidebar();
		}

		return Promise.resolve(false);
	}

	protected navigateOnPanelFocus(isSidebarPositionLeft: boolean, isPanelPositionDown: boolean): Promise<boolean | IViewlet> {
		if (isPanelPositionDown && isSidebarPositionLeft) {
			return this.navigateToSidebar();
		}

		if (!isPanelPositionDown) {
			return Promise.resolve(this.navigateToEditorGroup(GroupLocation.LAST));
		}

		return Promise.resolve(false);
	}

	protected navigateOnSidebarFocus(isSidebarPositionLeft: boolean, _isPanelPositionDown: boolean): boolean {
		if (!isSidebarPositionLeft) {
			return this.navigateToEditorGroup(GroupLocation.LAST);
		}

		return false;
	}
}

class NavigateRightAction extends BaseNavigationAction {

	static readonly ID = 'workbench.action.navigateRight';
	static readonly LABEL = nls.localize('navigateRight', "Navigate to the View on the Right");

	constructor(
		id: string,
		label: string,
		@IEditorGroupsService editorGroupService: IEditorGroupsService,
		@IPanelService panelService: IPanelService,
		@IWorkbenchLayoutService layoutService: IWorkbenchLayoutService,
		@IViewletService viewletService: IViewletService
	) {
		super(id, label, editorGroupService, panelService, layoutService, viewletService);
	}

	protected navigateOnEditorFocus(isSidebarPositionLeft: boolean, isPanelPositionDown: boolean): Promise<boolean | IViewlet | IPanel> {
		const didNavigate = this.navigateAcrossEditorGroup(GroupDirection.RIGHT);
		if (didNavigate) {
			return Promise.resolve(true);
		}

		if (!isPanelPositionDown) {
			return Promise.resolve(this.navigateToPanel());
		}

		if (!isSidebarPositionLeft) {
			return this.navigateToSidebar();
		}

		return Promise.resolve(false);
	}

	protected navigateOnPanelFocus(isSidebarPositionLeft: boolean, _isPanelPositionDown: boolean): Promise<boolean | IViewlet> {
		if (!isSidebarPositionLeft) {
			return this.navigateToSidebar();
		}

		return Promise.resolve(false);
	}

	protected navigateOnSidebarFocus(isSidebarPositionLeft: boolean, _isPanelPositionDown: boolean): boolean {
		if (isSidebarPositionLeft) {
			return this.navigateToEditorGroup(GroupLocation.FIRST);
		}

		return false;
	}
}

class NavigateUpAction extends BaseNavigationAction {

	static readonly ID = 'workbench.action.navigateUp';
	static readonly LABEL = nls.localize('navigateUp', "Navigate to the View Above");

	constructor(
		id: string,
		label: string,
		@IEditorGroupsService editorGroupService: IEditorGroupsService,
		@IPanelService panelService: IPanelService,
		@IWorkbenchLayoutService layoutService: IWorkbenchLayoutService,
		@IViewletService viewletService: IViewletService
	) {
		super(id, label, editorGroupService, panelService, layoutService, viewletService);
	}

	protected navigateOnEditorFocus(_isSidebarPositionLeft: boolean, _isPanelPositionDown: boolean): Promise<boolean> {
		return Promise.resolve(this.navigateAcrossEditorGroup(GroupDirection.UP));
	}

	protected navigateOnPanelFocus(_isSidebarPositionLeft: boolean, isPanelPositionDown: boolean): Promise<boolean> {
		if (isPanelPositionDown) {
			return Promise.resolve(this.navigateToEditorGroup(GroupLocation.LAST));
		}

		return Promise.resolve(false);
	}
}

class NavigateDownAction extends BaseNavigationAction {

	static readonly ID = 'workbench.action.navigateDown';
	static readonly LABEL = nls.localize('navigateDown', "Navigate to the View Below");

	constructor(
		id: string,
		label: string,
		@IEditorGroupsService editorGroupService: IEditorGroupsService,
		@IPanelService panelService: IPanelService,
		@IWorkbenchLayoutService layoutService: IWorkbenchLayoutService,
		@IViewletService viewletService: IViewletService
	) {
		super(id, label, editorGroupService, panelService, layoutService, viewletService);
	}

	protected navigateOnEditorFocus(_isSidebarPositionLeft: boolean, isPanelPositionDown: boolean): Promise<boolean | IPanel> {
		const didNavigate = this.navigateAcrossEditorGroup(GroupDirection.DOWN);
		if (didNavigate) {
			return Promise.resolve(true);
		}

		if (isPanelPositionDown) {
			return Promise.resolve(this.navigateToPanel());
		}

		return Promise.resolve(false);
	}
}

const registry = Registry.as<IWorkbenchActionRegistry>(Extensions.WorkbenchActions);
const viewCategory = nls.localize('view', "View");

registry.registerWorkbenchAction(new SyncActionDescriptor(NavigateUpAction, NavigateUpAction.ID, NavigateUpAction.LABEL, undefined), 'View: Navigate to the View Above', viewCategory);
registry.registerWorkbenchAction(new SyncActionDescriptor(NavigateDownAction, NavigateDownAction.ID, NavigateDownAction.LABEL, undefined), 'View: Navigate to the View Below', viewCategory);
registry.registerWorkbenchAction(new SyncActionDescriptor(NavigateLeftAction, NavigateLeftAction.ID, NavigateLeftAction.LABEL, undefined), 'View: Navigate to the View on the Left', viewCategory);
registry.registerWorkbenchAction(new SyncActionDescriptor(NavigateRightAction, NavigateRightAction.ID, NavigateRightAction.LABEL, undefined), 'View: Navigate to the View on the Right', viewCategory);


text:
from nose.tools import *
from unittest import TestCase
import repo_test_utils

import os
from shutil import rmtree
from tempfile import mkdtemp
from datetime import datetime

from repo.git_repository import GitRepository, GitRepositoryException

class GitRepositoryTests(TestCase):
    def setUp(self):
        self.directory = mkdtemp('-caboose-git-repo-tests')
        self.rmtree = True

    def tearDown(self):
        if self.rmtree:
            rmtree(self.directory)

    @raises(GitRepositoryException)
    def test_init_raises_with_non_git_directory(self):
        gitrepo = GitRepository(self.directory)

    def test_init_creates_repo_when_init_set_to_true(self):
        ok_(not os.path.isdir(os.path.join(self.directory, '.git')))
        gitrepo = GitRepository(self.directory, init=True)
        ok_(os.path.isdir(os.path.join(self.directory, '.git')))

    def test_adding_a_file_adds_it_to_the_git_index(self):
        gitrepo = GitRepository(self.directory, init=True)
        filename = repo_test_utils._create_random_file(self.directory)
        gitrepo.add(filename)
        status = gitrepo.run_git("status --porcelain")
        eq_("A  %s\n" % (os.path.basename(filename),), status)

    def test_commiting_actually_creates_a_new_commit(self):
        #create repo and add file
        gitrepo = GitRepository(self.directory, init=True)
        self.create_single_file_and_add_to_repository(gitrepo)

        #commit and verify commit was created
        gitrepo.commit(message='testmessage')
        message = gitrepo.run_git("log --format=%s")
        eq_("testmessage\n", message)

    def test_set_date_on_git_commit(self):
        gitrepo = GitRepository(self.directory, init=True)
        self.create_single_file_and_add_to_repository(gitrepo)

        expected_date = datetime(2011, 10, 28, 8, 0, 0)
        gitrepo.commit(message='testmessage', date=expected_date)
        actual_date = gitrepo.run_git("log --format=%cd --date=iso")
        actual_date = gitrepo.convert_git_date_to_datetime(actual_date)
        eq_(expected_date, actual_date)

    def test_convert_git_date_to_datetime(self):
        gitrepo = GitRepository(self.directory, init=True)
        gitdate = '2011-10-23 17:35:20 -0400'
        dt = gitrepo.convert_git_date_to_datetime(gitdate)
        eq_(datetime(2011, 10, 23, 17, 35, 20), dt)

    def test_get_date_of_earliest_commit(self):
        #create repo and add file
        gitrepo = GitRepository(self.directory, init=True)
        expected_date = datetime(2011, 10, 28, 8, 4, 0)
        self.create_single_file_add_and_commit_it(gitrepo, date=expected_date)

        #make a few more commits
        self.create_single_file_add_and_commit_it(gitrepo, date=datetime(2011, 10, 28, 8, 5, 0))
        self.create_single_file_add_and_commit_it(gitrepo, date=datetime(2011, 10, 28, 8, 6, 0))
        self.create_single_file_add_and_commit_it(gitrepo, date=datetime(2011, 10, 28, 8, 7, 0))

        #make sure when we ask for the earliest date, we get the first one
        earliest = gitrepo.get_date_of_earliest_commit()
        eq_(expected_date, earliest)

    def test_get_revision_before_date(self):
        #create repo
        gitrepo = GitRepository(self.directory, init=True)

        #make a few commits
        date_of_target_commit = datetime(2011, 10, 28, 8, 5, 0)
        self.create_single_file_add_and_commit_it(gitrepo, date=datetime(2011, 10, 28, 8, 4, 0))
        self.create_single_file_add_and_commit_it(gitrepo, date=date_of_target_commit)
        self.create_single_file_add_and_commit_it(gitrepo, date=datetime(2011, 10, 28, 8, 6, 0))
        self.create_single_file_add_and_commit_it(gitrepo, date=datetime(2011, 10, 28, 8, 7, 0))

        #get sha1 of target commit (since we know it is the second commit)
        target_sha1 = gitrepo.run_git("log --format=%H --skip=2 -1")
        target_sha1 = target_sha1.strip()

        #make sure when we ask for sha1 of the commit before a date we get the right one
        actual_sha1 = gitrepo.get_revision_before_date(datetime(2011, 10, 28, 8, 5, 45))
        eq_(target_sha1, actual_sha1)

    def test_get_revision_before_date_stays_on_current_branch(self):
        #create repo
        gitrepo = GitRepository(self.directory, init=True)

        #make a few commits
        date_of_target_commit = datetime(2011, 10, 28, 8, 5, 0)
        self.create_single_file_add_and_commit_it(gitrepo, date=datetime(2011, 10, 28, 8, 4, 0))
        self.create_single_file_add_and_commit_it(gitrepo, date=date_of_target_commit)
        self.create_single_file_add_and_commit_it(gitrepo, date=datetime(2011, 10, 28, 8, 6, 0))
        self.create_single_file_add_and_commit_it(gitrepo, date=datetime(2011, 10, 28, 8, 7, 0))

        #get sha1 of target commit (since we know it is the second commit)
        target_sha1 = gitrepo.run_git("log --format=%H --skip=2 -1")
        target_sha1 = target_sha1.strip()

        #create a new branch and commits on it, with one commit that would be
        #a better match for the requested date, except it is on a different branch
        gitrepo.create_branch("newbranch")
        gitrepo.switch_to_revision("newbranch")
        self.create_single_file_add_and_commit_it(gitrepo, date=datetime(2011, 10, 28, 8, 4, 0))
        self.create_single_file_add_and_commit_it(gitrepo, date=datetime(2011, 10, 28, 8, 5, 30))
        self.create_single_file_add_and_commit_it(gitrepo, date=datetime(2011, 10, 28, 8, 6, 0))

        #make sure when we ask for sha1 of the commit before a date we get the right one
        gitrepo.switch_to_revision("master")
        actual_sha1 = gitrepo.get_revision_before_date(datetime(2011, 10, 28, 8, 5, 45))
        eq_(target_sha1, actual_sha1)

    def test_get_revision_before_date_can_find_commits_later_than_current_working_directory(self):
        #create repo
        gitrepo = GitRepository(self.directory, init=True)

        #make a few commits
        target_date = datetime(2011, 11, 1, 20, 38, 0)
        self.create_single_file_add_and_commit_it(gitrepo, date=datetime(2011, 11, 1, 20, 35, 0))
        self.create_single_file_add_and_commit_it(gitrepo, date=datetime(2011, 11, 1, 20, 36, 0))
        self.create_single_file_add_and_commit_it(gitrepo, date=datetime(2011, 11, 1, 20, 37, 0))
        self.create_single_file_add_and_commit_it(gitrepo, date=target_date)

        #get sha1 of an early and a late commit
        early_sha1 = gitrepo.run_git("log --format=%H --skip=2 -1").strip()
        late_sha1 = gitrepo.run_git("log --format=%H -1").strip()

        #switch to early_sha1
        gitrepo.switch_to_revision(early_sha1)

        #make sure when we ask for sha1 of the commit before a date we get the right one
        actual_sha1 = gitrepo.get_revision_before_date(datetime(2011, 11, 1, 20, 38, 30))
        eq_(late_sha1, actual_sha1)

    def test_switch_to_revision(self):
        #create repo
        gitrepo = GitRepository(self.directory, init=True)

        #make a few commits
        date_of_target_commit = datetime(2011, 11, 1, 7, 25, 0)
        self.create_single_file_add_and_commit_it(gitrepo, date=datetime(2011, 11, 1, 7, 24, 0))
        self.create_single_file_add_and_commit_it(gitrepo, date=date_of_target_commit)
        self.create_single_file_add_and_commit_it(gitrepo, date=datetime(2011, 11, 1, 7, 26, 0))
        self.create_single_file_add_and_commit_it(gitrepo, date=datetime(2011, 11, 1, 7, 27, 0))

        #get sha1 of target commit (since we know it is the second commit)
        target_sha1 = gitrepo.run_git("log --format=%H --skip=2 -1")
        target_sha1 = target_sha1.strip()

        #switch to target commit
        gitrepo.switch_to_revision(target_sha1)

        #make sure we are on the target commit
        result = gitrepo.run_git("rev-parse HEAD").strip()
        eq_(target_sha1, result)

    def test_get_base_directory(self):
        gitrepo = GitRepository(self.directory, init=True)
        eq_(self.directory, gitrepo.get_base_directory())

    @nottest
    def create_single_file_add_and_commit_it(self, gitrepo, date=None):
        self.create_single_file_and_add_to_repository(gitrepo)
        gitrepo.commit(message='testmessage', date=date)

    @nottest
    def create_single_file_and_add_to_repository(self, gitrepo):
        filename = repo_test_utils._create_random_file(self.directory)
        gitrepo.add(filename)

        #verify the file is not committed
        status = gitrepo.run_git("status --porcelain")
        eq_("A  %s\n" % (os.path.basename(filename),), status)

    @nottest
    def create_test_changesets(self, repo, count=1, dates=[]):
        for i in range(count):
            filename = repo_test_utils._create_random_file(self.directory)
            commands.add(repo.get_ui(), repo.get_repo(), filename)

            date=None
            if i < len(dates):
                date=dates[i]
            commands.commit(repo.get_ui(), repo.get_repo(), date=date, message="creating test commit", user='Test Runner <trunner@domain.com>')


text:
// Copyright (C) 2017 Calin Cruceru <calin.cruceru@stud.acs.upb.ro>.
//
// See the LICENCE file distributed with this work for additional
// information regarding copyright ownership.

package org.symnet
package models.iptables.core

// scala
import org.junit.runner.RunWith
import org.scalatest.{FunSuite, Matchers}
import org.scalatest.junit.JUnitRunner

// 3rd party:
// -> scalaz
import scalaz.Maybe._

// -> Symnet
import org.change.v2.analysis.processingmodels.Instruction

// project
import types.net.Ipv4
import Policy._

@RunWith(classOf[JUnitRunner])
class CoreValidationSuite extends FunSuite with Matchers {

  private val emptyCtx = ValidationContext.empty

  test("simple table validation") {
    // Success
    {
      val filterTable = Table("filter", Nil)
      filterTable.validate(emptyCtx) shouldBe Just(filterTable)
    }
    {
      val natTable = Table("nat", Nil)
      natTable.validate(emptyCtx) shouldBe Just(natTable)
    }
    {
      val mangleTable = Table("mangle", Nil)
      mangleTable.validate(emptyCtx) shouldBe Just(mangleTable)
    }
    {
      val rawTable = Table("raw", Nil)
      rawTable.validate(emptyCtx) shouldBe Just(rawTable)
    }

    // Failure
    {
      val almostFilterTable = Table("filtre", Nil)
      almostFilterTable.validate(emptyCtx) shouldBe empty
    }
  }

  test("table with chains validation") {
    // Success
    {
      val chains = List(
        BuiltinChain("FORWARD", Nil, Drop),
        BuiltinChain("INPUT", Nil, Drop)
      )
      val table = Table("filter", chains)

      table.validate(emptyCtx) shouldBe Just(table)
    }
    {
      // Capitalization matters.
      val chains = List(
        BuiltinChain("FORWARD", Nil, Drop),
        UserChain("forward", Nil)
      )
      val table = Table("filter", chains)

      table.validate(emptyCtx) shouldBe Just(table)
    }
    {
      // Order of chains in the list doesn't matter.
      val chains = List(
        UserChain("MY_CHAIN1", Nil),
        UserChain("MY_CHAIN3", Nil),
        BuiltinChain("OUTPUT", Nil, Return),
        BuiltinChain("POSTROUTING", Nil, Accept),
        UserChain("MY_CHAIN2", Nil)
      )
      val table = Table("nat", chains)

      table.validate(emptyCtx) shouldBe Just(table)
    }

    // Failure
    {
      // The 'POSTROUTING' chain cannot be part of the filter table.
      val chains = List(
        BuiltinChain("FORWARD", Nil, Drop),
        BuiltinChain("INPUT", Nil, Drop),
        BuiltinChain("POSTROUTING", Nil, Drop)
      )
      val table = Table("filter", chains)

      table.validate(emptyCtx) shouldBe empty
    }
    {
      // A (builtin) chain cannot appear multiple times in the same table.
      val chains = List(
        BuiltinChain("INPUT", Nil, Drop),
        BuiltinChain("INPUT", Nil, Drop)
      )
      val table = Table("filter", chains)

      table.validate(emptyCtx) shouldBe empty
    }
    {
      // A (user-defined) chain cannot appear multiple times in the same table.
      val chains = List(
        UserChain("MY_CHAIN", Nil),
        UserChain("MY_CHAIN", Nil)
      )
      val table = Table("filter", chains)

      table.validate(emptyCtx) shouldBe empty
    }
    {
      // We cannot name a user-defined chain using one of the reserved names for
      // builtin chains.
      val chains = List(
        BuiltinChain("FORWARD", Nil, Drop),
        UserChain("INPUT", Nil)
      )
      val table = Table("mangle", chains)

      table.validate(emptyCtx) shouldBe empty
    }
  }

  // is always valid
  object validMatch extends Match {
    type Self = this.type

    // this is not used here
    override def seflCondition(options: SeflGenOptions): SeflCondition =
      SeflCondition.empty
  }
  // is always valid
  object validTarget extends Target {
    type Self = this.type

    // this is not used here
    override def seflCode(options: SeflGenOptions): Instruction = null
  }
  // is never valid
  object invalidMatch extends Match {
    type Self = this.type

    override protected def validateIf(context: ValidationContext): Boolean =
      false

    // this is not used here
    override def seflCondition(options: SeflGenOptions): SeflCondition =
      SeflCondition.empty
  }
  // is never valid
  object invalidTarget extends Target {
    type Self = this.type

    override protected def validateIf(context: ValidationContext): Boolean =
      false

    // this is not used here
    override def seflCode(options: SeflGenOptions): Instruction = null
  }

  test("1 table/1 chain/1 rule") {
    // Success
    {
      val rule = Rule(List(NegatedMatch(validMatch)), validTarget)
      val chain = BuiltinChain("FORWARD", List(rule), Drop)
      val table = Table("filter", List(chain))

      table.validate(emptyCtx) shouldBe Just(table)
    }
    {
      val rule  = Rule(List(validMatch), PlaceholderTarget("MY_CHAIN"))
      val myChain = UserChain("MY_CHAIN", Nil)
      val chain = BuiltinChain("FORWARD", List(rule), Drop)
      val table = Table("filter", List(chain, myChain))

      // The model after the rule is validate(emptyCtx)d.
      val vRule = Rule(List(validMatch), myChain)
      val vChain = BuiltinChain("FORWARD", List(vRule), Drop)
      val vTable = Table("filter", List(vChain, myChain))

      table.validate(emptyCtx) shouldBe Just(vTable)
      vTable should not equal (table)
    }

    // Failure
    {
      // Jumps to builtin chains are not allowed.
      val rule  = Rule(List(validMatch), PlaceholderTarget("FORWARD"))
      val myChain = UserChain("MY_CHAIN", List(rule))
      val chain = BuiltinChain("FORWARD", Nil, Drop)
      val table = Table("filter", List(chain, myChain))

      table.validate(emptyCtx) shouldBe empty
    }
    {
      // Recursive jumps are not allowed.
      val rule  = Rule(List(validMatch), PlaceholderTarget("MY_CHAIN"))
      val chain = UserChain("MY_CHAIN", List(rule))
      val table = Table("filter", List(chain))

      table.validate(emptyCtx) shouldBe empty
    }
    {
      // Invalid match.
      val rule = Rule(List(invalidMatch), validTarget)
      val chain = BuiltinChain("FORWARD", List(rule), Drop)
      val table = Table("filter", List(chain))

      table.validate(emptyCtx) shouldBe empty
    }
    {
      // Invalid target.
      val rule = Rule(List(NegatedMatch(validMatch)), invalidTarget)
      val chain = BuiltinChain("FORWARD", List(rule), Drop)
      val table = Table("filter", List(chain))

      table.validate(emptyCtx) shouldBe empty
    }
  }

  test("jump to user-defined chain") {
    // Success
    {
      val dstChain = UserChain("MY_CHAIN", Nil)
      val rule = Rule(List(validMatch), /* the target */ dstChain)
      val chain = BuiltinChain("PREROUTING", List(rule), Accept)

      // The order of chains is not important.
      val table1 = Table("nat", List(chain, dstChain))
      table1.validate(emptyCtx) shouldBe Just(table1)

      val table2 = Table("nat", List(dstChain, chain))
      table2.validate(emptyCtx) shouldBe Just(table2)
    }

    // Failure
    {
      // The destination chain is not part of the table.
      val dstChain = UserChain("MY_CHAIN", Nil)
      val rule = Rule(List(validMatch), /* the target */ dstChain)
      val chain = BuiltinChain("INPUT", List(rule), Accept)
      val table = Table("nat", List(chain))

      table.validate(emptyCtx) shouldBe empty
    }
  }

  test("prerouting chain in filter table is invalid") {
    val table = Table("filter", List(BuiltinChain("PREROUTING", Nil, Drop)))
    table.validate(emptyCtx) shouldBe empty
  }

  test("indirected jump should still replace PlaceholderTarget") {
    val rule1 = Rule(List(validMatch), PlaceholderTarget("CHAIN2"))
    val rule2 = Rule(List(validMatch), PlaceholderTarget("CHAIN3"))
    val chain1 = UserChain("CHAIN1", List(rule1))
    val chain2 = UserChain("CHAIN2", List(rule2))
    val chain3 = UserChain("CHAIN3", Nil)
    val table = Table("filter", List(chain1, chain2, chain3))

    val maybeValidTable = table.validate(emptyCtx)
    maybeValidTable shouldBe a [Just[_]]

    val validTable = maybeValidTable.toOption.get
    validTable.chains(0).name shouldBe "CHAIN1"
    validTable.chains(0).rules(0).target shouldBe a [UserChain]

    val ucTarget = validTable.chains(0).rules(0).target.asInstanceOf[UserChain]
    ucTarget.rules(0).target shouldBe a [UserChain]
  }

  test("negation is kept after validation too") {
    val rule = Rule(List(NegatedMatch(validMatch)), validTarget)
    val chain = BuiltinChain("FORWARD", List(rule), Drop)
    val table = Table("filter", List(chain))

    table.validate(emptyCtx) shouldBe Just(table)
  }

  test("raw validation") {
    val tableStr = """
      <<raw>>
      <PREROUTING:ACCEPT>
      -j neutron-l3-agent-PREROUTING
      <OUTPUT:ACCEPT>
      -j neutron-l3-agent-OUTPUT
      <neutron-l3-agent-OUTPUT>
      <neutron-l3-agent-PREROUTING>
    """
    implicit val context = ParsingContext.default

    val maybeTable = iptParsers.tableParser.eval(tableStr)
    maybeTable shouldBe a [Just[_]]

    val table = maybeTable.toOption.get
    val maybeVTable = table.validate(ValidationContext.empty)
    maybeVTable shouldBe a [Just[_]]
  }

  test("mangle validation") {
    val tableStr = """
      <<mangle>>
      <PREROUTING:ACCEPT>
      -j neutron-l3-agent-PREROUTING
      <INPUT:ACCEPT>
      -j neutron-l3-agent-INPUT
      <FORWARD:ACCEPT>
      -j neutron-l3-agent-FORWARD
      <OUTPUT:ACCEPT>
      -j neutron-l3-agent-OUTPUT
      <POSTROUTING:ACCEPT>
      -j neutron-l3-agent-POSTROUTING
      <neutron-l3-agent-FORWARD>
      <neutron-l3-agent-INPUT>
      <neutron-l3-agent-OUTPUT>
      <neutron-l3-agent-POSTROUTING>
      -o qg-09d66f0a-46 -m connmark --mark 0x0/0xffff0000 -j CONNMARK --save-mark --nfmask 0xffff0000 --ctmask 0xffff0000
      <neutron-l3-agent-PREROUTING>
      -j neutron-l3-agent-mark
      -j neutron-l3-agent-scope
      -m connmark ! --mark 0x0/0xffff0000 -j CONNMARK --restore-mark --nfmask 0xffff0000 --ctmask 0xffff0000
      -j neutron-l3-agent-floatingip
      -d 169.254.169.254/32 -i qr-+ -p tcp -m tcp --dport 80 -j MARK --set-xmark 0x1/0xffff
      <neutron-l3-agent-float-snat>
      -m connmark --mark 0x0/0xffff0000 -j CONNMARK --save-mark --nfmask 0xffff0000 --ctmask 0xffff0000
      <neutron-l3-agent-floatingip>
      <neutron-l3-agent-mark>
      -i qg-09d66f0a-46 -j MARK --set-xmark 0x2/0xffff
      <neutron-l3-agent-scope>
      -i qr-6a98a347-87 -j MARK --set-xmark 0x4000000/0xffff0000
      -i qg-09d66f0a-46 -j MARK --set-xmark 0x4000000/0xffff0000
    """
    implicit val context = ParsingContext.default

    val maybeTable = iptParsers.tableParser.eval(tableStr)
    maybeTable shouldBe a [Just[_]]

    val table = maybeTable.toOption.get
    val maybeVTable = table.validate(ValidationContext.empty)
    maybeVTable shouldBe a [Just[_]]
  }

  test("nat validation") {
    val tableStr = """
      <<nat>>
      <PREROUTING:ACCEPT>
      -j neutron-l3-agent-PREROUTING
      <INPUT:ACCEPT>
      <OUTPUT:ACCEPT>
      -j neutron-l3-agent-OUTPUT
      <POSTROUTING:ACCEPT>
      -j neutron-l3-agent-POSTROUTING
      -j neutron-postrouting-bottom
      <neutron-l3-agent-OUTPUT>
      <neutron-l3-agent-POSTROUTING>
      <neutron-l3-agent-PREROUTING>
      <neutron-l3-agent-float-snat>
      <neutron-l3-agent-snat>
      <neutron-postrouting-bottom>
    """
    implicit val context = ParsingContext.default

    val maybeTable = iptParsers.tableParser.eval(tableStr)
    maybeTable shouldBe a [Just[_]]

    val table = maybeTable.toOption.get
    val maybeVTable = table.validate(ValidationContext.empty)
    maybeVTable shouldBe a [Just[_]]
  }
}