text:
<?php
$ft_messages['fi']['File Thingie Login'] = 'File Thingie - Sisäänkirjautuminen';
$ft_messages['fi']['Invalid username or password'] = 'Käyttäjätunnus tai salasana on virheellinen';
$ft_messages['fi']['Username:'] = 'Käyttäjätunnus:';
$ft_messages['fi']['Password:'] = 'Salasana:';
$ft_messages['fi']['Login'] = 'Kirjaudu';
$ft_messages['fi']['A new version of File Thingie (!version) is available.'] = 'Uusi versio File Thingie (!version) ohjelmasta on saatavilla';
$ft_messages['fi']['Download File Thingie !version directly'] = 'Lataa uusin versio (!version) nyt heti';
$ft_messages['fi']['No updates available.'] = 'Sinulla on jo uusin versio';
$ft_messages['fi']['Your version:'] = 'Sinun versio';
$ft_messages['fi']['Newest version:'] = 'Uusin versio';
$ft_messages['fi']['Newest version is:'] = 'Uusin versio on';
$ft_messages['fi']['Could not connect (possible error: URL wrappers not enabled).'] = 'Ei saada yhteyttä (mahdollinen syy: URL wrapperit eivät ole käytössä).';
$ft_messages['fi']['Highlight file in directory'] = 'Merkitse tiedosto päälleviivaustussilla';
$ft_messages['fi']['No files found'] = 'Yhtään tiedostoa ei löytynyt';
$ft_messages['fi']['Error.'] = 'Virhe.';
$ft_messages['fi']['Enter a search string.'] = 'Syötä haettava teksti';
$ft_messages['fi']['Go to home folder'] = 'Mene kotihakemistoon';
$ft_messages['fi']['Go to folder'] = 'Mene hakemistoon';
$ft_messages['fi']['[logout]'] = '[Kirjaudu ulos]';
$ft_messages['fi']['Logout of File Thingie'] = 'Kirjautuminen ulos ohjelmasta';
$ft_messages['fi']['Could not open directory.'] = 'Hakemistoa ei voi avata';
$ft_messages['fi']['Directory created.'] = 'Hakemisto on luotu.';
$ft_messages['fi']['Directory could not be created.'] = 'Hakemistoa ei voi luoda.';
$ft_messages['fi']['File created.'] = 'Tiedosto luotu.';
$ft_messages['fi']['File could not be created.'] = 'Tiedostoa ei voi luoda.';
$ft_messages['fi']['File could not be created. File already exists.'] = 'Tiedostoa ei voi luoda. Samanniminen tiedosto on jo olemassa,';
$ft_messages['fi']['Upload failed.'] = 'Tiedoston siirto epäonnistui.';
$ft_messages['fi']['!old was renamed to !new'] = '!old nimettiin uudelleen: !new';
$ft_messages['fi']['!old could not be renamed.'] = 'Uudelleen nimeäminen epäonnistui (!old).';
$ft_messages['fi']['!old could not be renamed (write failed).'] = 'Uudelleen nimeäminen epäonnistui (!old), virhe tiedostoa luotaessa.';
$ft_messages['fi']['!old was not renamed to !new (type not allowed).'] = 'Uudelleen nimeäminen epäonnistui (!old -> !new), uuden tiedoston tyyppi ei ole sallittu.';
$ft_messages['fi']['File could not be renamed since you didn\'t specify a new name.'] = 'Uudelleen nimeäminen epäonnistui, koska et antanut uutta nimeä.';
$ft_messages['fi']['File could not be renamed to !new since it already exists.'] = 'Uudelleen nimeäminen epäonnistui, samanniminen tiedosto on jo olemassa (!new).';
$ft_messages['fi']['!old was duplicated to !new'] = 'Kopioitu !old uudelle nimelle: !new';
$ft_messages['fi']['!old could not be duplicated.'] = 'Kopioiminen epäonnistui (!old)';
$ft_messages['fi']['!old could not be duplicated (write failed).'] = 'Kopioiminen epäonnistui (!old), virhe tiedostoa luotaessa.';
$ft_messages['fi']['!old was not duplicated to !new (type not allowed).'] = 'Kopioiminen epäonnistui (!old -> !new), uuden tiedoston tyyppi ei ole sallittu.';
$ft_messages['fi']['File could not be duplicated since you didn\'t specify a new name.'] = 'Kopioiminen epäonnistui, koska et antanut uutta nimeä.';
$ft_messages['fi']['File could not be duplicated to !new since it already exists.'] = 'Kopioiminen epäonnistui, samanniminen tiedosto on jo olemassa (!new).';
$ft_messages['fi']['!old deleted.'] = 'Poistettu tiedosto tai hakemisto !old ';
$ft_messages['fi']['!old could not be deleted.'] = 'Ei voitu poistaa tiedostoa tai hakemistoa !old';
$ft_messages['fi']['!old was moved to !new'] = '!old on siirretty uuteen paikkaan: !new';
$ft_messages['fi']['!old could not be moved.'] = 'Siirto epäonnistui (!old)';
$ft_messages['fi']['Could not move file. !old does not exist or is not a directory.'] = 'Tiedoston siirtäminen ei onnistunut. Sijaintia !old ei ole olemassa tai se ei ole hakemisto.';
$ft_messages['fi']['!old could not be moved. It doesn\'t exist.'] = 'Siirto epäonnistui. !old ei ole olemassa.';
$ft_messages['fi']['!old could not be moved outside the base directory.'] = 'Siirto epäonnistui. !old ei voi siirtää juurihakemiston ulkopuolelle.';
$ft_messages['fi']['!old was saved.'] = '!old on tallennettu';
$ft_messages['fi']['!old could not be edited.'] = '!old - muuttaminen ei onnistu';
$ft_messages['fi']['Could not edit file. This file type is not editable.'] = '!old - muuttaminen ei onnistu, kyseisen tiedostotyypin muuttaminen ei ole sallittua';
$ft_messages['fi']['!old unzipped.'] = 'paketti !old on purettu.';
$ft_messages['fi']['!old could not be unzipped.'] = 'paketin !old purkaminen epäonnistui.';
$ft_messages['fi']['Permissions changed for !old.'] = 'Muutettiin oikeuksia (!old).';
$ft_messages['fi']['Could not change permissions for !old.'] = 'Oikeuksien muuttaaminen ei onnistunut (!old)';
$ft_messages['fi']['File couldn\'t be moved'] = 'Tiedoston siirtäminen epäonnistui';
$ft_messages['fi']['File type not allowed'] = 'Tiedoston tyyppi ei ole sallittu';
$ft_messages['fi']['The file was too large'] = 'Tiedosto oli liian iso';
$ft_messages['fi']['Partial upload. Try again'] = 'Tiedosto siirrettiin vain osittain. Yritä uudestaan.';
$ft_messages['fi']['No file was uploaded. Please try again'] = 'Yhtään tiedostoa ei siirretty. Yritä uudestaan.';
$ft_messages['fi']['Unknown error'] = 'Tuntematon virhe';
$ft_messages['fi']['File already exists'] = 'Tiedosto on jo olemassa';
$ft_messages['fi']['The file was larger than MAXSIZE setting.'] = 'Tiedosto oli suurempi kuin muuttujassa MAXSIZE määritelty arvo';
$ft_messages['fi']['!file was uploaded.'] = 'Tiedosto !file vastaanotettu';
$ft_messages['fi']['!file was not uploaded.'] = 'Tiedostoa !file ei vastaanotettu';
$ft_messages['fi']['Files'] = 'Tiedostot';
$ft_messages['fi']['Directory is empty.'] = 'Hakemisto on tyhjä.';
$ft_messages['fi']['Show files in this directory'] = 'Näytä tämän hakemiston tiedostot';
$ft_messages['fi']['files'] = 'tiedostoa';
$ft_messages['fi']['Edit file:'] = 'Muuta tiedostoa:';
$ft_messages['fi']['Save'] = 'Tallenna';
$ft_messages['fi']['Save & exit'] = 'Tallenna ja poistu';
$ft_messages['fi']['Cancel'] = 'Hylkää';
$ft_messages['fi']['Convert spaces to tabs'] = 'Muuta välilyönnit tabuloinneiksi';
$ft_messages['fi']['Cannot edit file. This file type is not editable.'] = 'Tiedoston muuttaminen ei onnistu. Tämän tyyppistä tiedostoa ei voi muokata.';
$ft_messages['fi']['Cannot edit file. It either does not exist or is not writeable.'] = 'Tiedoston muuttaminen ei onnistu. Joko tiedostoa ei ole olemassa tai se on kirjoitussuojattu.';
$ft_messages['fi']['Results'] = 'Tulokset';
$ft_messages['fi']['Upload'] = 'Lähetä';
$ft_messages['fi']['Max:'] = 'Max:';
$ft_messages['fi']['Create folder'] = 'Luo tiedosto tai hakemisto';
$ft_messages['fi']['Folder'] = 'Hakemisto';
$ft_messages['fi']['File'] = 'Tiedosto';
$ft_messages['fi']['Ok'] = 'Ok';
$ft_messages['fi']['Search'] = 'Etsi';
$ft_messages['fi']['Search files & folders'] = 'Etsi tiedostoja tai kansioita';
$ft_messages['fi']['Search only this folder and below'] = 'Etsi vain tämän hetkisestä hakemistosta ja sen alihakemistoista';
$ft_messages['fi']['Login error.'] = 'Kirjautumisvirhe.';
$ft_messages['fi']['Online documentation'] = 'Ohjeet ohjelman kotisivulla';
$ft_messages['fi']['Check for new version'] = 'Tarkista onko ohjelmasta uudempi versio';
$ft_messages['fi']['Files for upload:'] = 'Siirrettävät tiedosto:';
$ft_messages['fi']['Rename'] = 'Nimeä uudelleen';
$ft_messages['fi']['Move'] = 'Siirrä';
$ft_messages['fi']['Delete'] = 'Tuhoa';
$ft_messages['fi']['Duplicate'] = 'Kopioi';
$ft_messages['fi']['Unzip'] = 'Pura paketti';
$ft_messages['fi']['chmod'] = 'Muuta oikeuksia';
$ft_messages['fi']['Rename to:'] = 'Uudelleennimeä:';
$ft_messages['fi']['Edit'] = 'Muokkaa';
$ft_messages['fi']['Fetching results…'] = 'Tiedonsiirron tulokset…';
$ft_messages['fi']['Dismiss'] = 'Dismiss';
$ft_messages['fi']['Saving file…'] = 'Tallennan tiedostoa…';
$ft_messages['fi']['Upload files'] = 'Lähetä tiedostoja';
$ft_messages['fi']['Move to folder:'] = 'Siirrä hakemistoon:';
$ft_messages['fi']['Duplicate to file:'] = 'Kopioi nimelle:';
$ft_messages['fi']['Set permissions to:'] = 'Aseta oikeudet:';
$ft_messages['fi']['Do you really want to delete file?'] = 'Haluatko varmasti poistaa tämän tiedoston tai hakemiston?';
$ft_messages['fi']['Yes, delete it'] = 'Kyllä, tuhoa se!';
$ft_messages['fi']['Do you want to edit this file?'] = 'Haluatko muokata tätä tiedostoa?';
$ft_messages['fi']['Yes, edit file'] = 'Kyllä, muokkaa tiedostoa';
$ft_messages['fi']['Do you really want to unzip file?'] = 'Haluatko purkaa tämän paketin?';
$ft_messages['fi']['Yes, unzip it'] = 'Kyllä, pura paketti';
$ft_messages['fi']['Cancel upload of this file'] = 'Peru tämän tiedoston siirtäminen';
$ft_messages['fi']['Logged in as !user '] = 'Olet kirjautuneena käyttäjätunnuksella !user';
$ft_messages['fi']['folders'] = 'hakemistoa';
$ft_messages['fi']['Remember me'] = 'Muista kirjautumiseni';
$ft_messages['fi']['Now uploading files. Please wait...'] = 'Siirrän tiedostoja. Odota...';
$ft_messages['fi']['Symlink'] = 'Symbolinen linkki';
$ft_messages['fi']['Create symlink called:'] = 'Luo symbolinen linkki nimeltä:';
$ft_messages['fi']['Created symlink !new'] = 'Luotu symbolinen linkki !new';
$ft_messages['fi']['Symlink to !old could not be created.'] = 'Symbolista linkkiä tiedostoon tai hakemistoon !old ei voitu luoda.';
$ft_messages['fi']['Could not create symlink to !old (write failed).'] = 'Symbolista linkkiä tiedostoon tai hakemistoon !old ei voitu luoda (kirjoittaminen epäonnistui)';
$ft_messages['fi']['Could not create symlink to !old (type not allowed).'] = 'Symbolista linkkiä tiedostoon tai hakemistoon !old ei voitu luodu, koska tiedoston tyyppi ei ole sallittu';
$ft_messages['fi']['Symlink could not be created since you didn\'t specify a name.'] = 'Symbolista linkkiä ei voitu luoda, koska et antanut sille nimeä.';
$ft_messages['fi']['Could not create symlink !new since it already exists.'] = 'Symbolista linkkiä ei voitu luoda, koska samanniminen (!new) tiedosto tai hakemisto on jo olemassa.';
$ft_messages['fi']['Sort by name'] = 'Järjestä nimen mukaan';
$ft_messages['fi']['Sort by size'] = 'Järjestä koon mukaan';
$ft_messages['fi']['Sort by type'] = 'Järjestä tiedostotyypin mukaan';
$ft_messages['fi']['Sort by date'] = 'Järjestä päivämäärän mukaan';
$ft_messages['fi']['Upload disabled. Total disk space use of !size exceeds the limit of !limit.'] = 'Tiedoston siirtäminen on estetty. Suurin sallitty tiedostojen koko (!limit) on ylittynyt. Tiedostojen koko on nyt !size.';
$ft_messages['fi']['Show files in !folder'] = 'Näytä tiedostot hakemistossa !folder';
$ft_messages['fi']['Show !file'] = 'Näytä !file';
$ft_messages['fi']['You can only delete empty folders.'] = 'Voit poistaa vain tyhjiä hakemistoja.';
$ft_messages['fi']['Home'] = 'Kotihakemisto';
$ft_messages['fi']['Cannot edit file. This file is currently being edited by !name'] = 'Tiedoston muuttaminen ei onnistu. Tiedostoa muokataan parhaillaan, käyttäjän !name toimesta.';
$ft_messages['fi']['From URL'] = 'Kopioi netistä (kirjoita koko osoite)';
$ft_messages['fi']['File could not be saved.'] = 'Tiedostoa ei voitu tallettaa.';
$ft_messages['fi']['Could not open URL. Possible reason: URL wrappers not enabled.'] = 'Internet-osoitteen avaaminen ei onnistunut (mahdollinen syy: URL wrapperit eivät ole käytössä).';
?>


text:
namespace _10.Centuries_to_Nanoseconds
{
    using System;

    public class CenturiesNanoseconds
    {
        public static void Main()
        {
            //years = centuries * 100;
            //days = years * 365.2422;
            //hours = days * 24;
            //minutes = hours * 60;
            //seconds = minutes * 60;
            //milliseconds = seconds * 1000;
            //microseconds = milliseconds * 1000;
            //nanoseconds = microseconds * 1000;
            int centuries = int.Parse(Console.ReadLine());
            int years = centuries * 100;
            int days = (int)(years * 365.2422);
            int hours = days * 24;
            long minutes = hours * 60;
            ulong seconds = (ulong)minutes * 60;
            ulong milliseconds = seconds * 1000;
            decimal microseconds = milliseconds * 1000;
            decimal nanoseconds = microseconds * 1000;
            Console.Write($"{centuries} centuries = ");
            Console.Write($"{years} years = ");
            Console.Write($"{days} days = ");
            Console.Write($"{hours} hours = ");
            Console.Write($"{minutes} minutes = ");
            Console.Write($"{seconds} seconds = ");
            Console.Write($"{milliseconds} milliseconds = ");
            Console.Write($"{microseconds} microseconds = ");
            Console.Write($"{nanoseconds} nanoseconds");
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class AddForeignKeysToNotesTable extends Migration
{
    /**
     * Run the migrations.
     */
    public function up()
    {
        Schema::table('notes', function (Blueprint $table) {
            $table->foreign('user_id', 'fk_notes_user_id')->references('id')->on('users')->onUpdate('NO ACTION')->onDelete('NO ACTION');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down()
    {
        Schema::table('notes', function (Blueprint $table) {
            $table->dropForeign('fk_notes_user_id');
        });
    }
}


text:
package com.aorura.android.weather.app.utils;

import junit.framework.Assert;

import java.util.concurrent.Callable;

public abstract class PollingCheck {
    private static final long TIME_SLICE = 50;
    private long mTimeout = 3000;

    public PollingCheck() {
    }

    public PollingCheck(long timeout) {
        mTimeout = timeout;
    }

    protected abstract boolean check();

    public void run() {
        if (check()) {
            return;
        }

        long timeout = mTimeout;
        while (timeout > 0) {
            try {
                Thread.sleep(TIME_SLICE);
            } catch (InterruptedException e) {
                Assert.fail("unexpected InterruptedException");
            }

            if (check()) {
                return;
            }

            timeout -= TIME_SLICE;
        }

        Assert.fail("unexpected timeout");
    }

    public static void check(CharSequence message, long timeout, Callable<Boolean> condition)
            throws Exception {
        while (timeout > 0) {
            if (condition.call()) {
                return;
            }

            Thread.sleep(TIME_SLICE);
            timeout -= TIME_SLICE;
        }

        Assert.fail(message.toString());
    }
}


text:
package lppedd.j.api.files.device;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.ibm.as400.access.BinaryConverter;

import lppedd.j.api.JConnection;
import lppedd.j.api.JType;
import lppedd.j.api.ibm.JApi;
import lppedd.j.api.ibm.JApiResult;
import lppedd.j.api.misc.JUtil;

public class JSaveFile extends JAbstractDeviceFile
{
   public static class JSavedObject
   {
      private final String name;
      private final String library;
      private final JType type;
      private final String attribute;
      private final String text;
      private final List<String> members;

      private JSavedObject(final String name, final String library, final JType type, final String attribute, final String text, final List<String> members) {
         this.name = name;
         this.library = library;
         this.type = type;
         this.attribute = attribute;
         this.text = text;
         this.members = members;
      }

      public String getName() {
         return name;
      }

      public String getLibrary() {
         return library;
      }

      public JType getType() {
         return type;
      }

      public String getAttribute() {
         return attribute;
      }

      public String getText() {
         return text;
      }

      public List<String> getMembers() {
         return members;
      }
   }

   public JSaveFile(final JConnection connection, final String name, final String library) {
      super(connection, name, library);
   }

   public List<JSavedObject> getSavedObjects() {
      final JConnection connection = getConnection();

      // Recupero gli oggetti.
      JApiResult output = JApi.QSRLSAVF(connection, "SAVF0200", "*ALL", "*ALL", this);

      if (output.getMessages().length != 0) {
         return Collections.emptyList();
      }

      final byte[] objectsBytes = output.getValue();
      int objectsOffset = BinaryConverter.byteArrayToInt(objectsBytes, 124);
      int objectsCount = BinaryConverter.byteArrayToInt(objectsBytes, 132);
      final int objectEntrySize = BinaryConverter.byteArrayToInt(objectsBytes, 136);
      final List<JSavedObject> savedObjects = new ArrayList<>(objectsCount);

      for (; objectsCount > 0; --objectsCount, objectsOffset += objectEntrySize) {
         final String savedObjectName = ((String) CHAR10.toObject(objectsBytes, objectsOffset)).trim();
         final JType savedObjectType = JType.valueOf(((String) CHAR10.toObject(objectsBytes, objectsOffset + 20)).trim().substring(1));

         // Lista vuota, dato che l'oggetto potrebbe non essere un file, e quindi contenere membri.
         List<String> savedObjectMembers = Collections.emptyList();

         // Se l'oggetto e' un file, reperisco i suoi membri.
         if (JType.FILE == savedObjectType) {
            output = JApi.QSRLSAVF(connection, "SAVF0300", savedObjectName, "*ALL", this);

            if (output.getMessages().length != 0) {
               continue;
            }

            final byte[] membersBytes = output.getValue();
            int membersOffset = BinaryConverter.byteArrayToInt(membersBytes, 124);
            int membersCount = BinaryConverter.byteArrayToInt(membersBytes, 132);
            final int memberEntrySize = BinaryConverter.byteArrayToInt(membersBytes, 136);

            // Riassegno alla lista una nuova lista con dimensione iniziale uguale al numero di membri.
            savedObjectMembers = new ArrayList<>(membersCount);

            for (; membersCount > 0; --membersCount, membersOffset += memberEntrySize) {
               savedObjectMembers.add(((String) CHAR10.toObject(membersBytes, membersOffset + 20)).trim());
            }
         }

         savedObjects.add(new JSavedObject(
               savedObjectName,
               ((String) CHAR10.toObject(objectsBytes, objectsOffset + 10)).trim(),
               savedObjectType,
               ((String) CHAR10.toObject(objectsBytes, objectsOffset + 30)).trim(),
               ((String) CHAR50.toObject(objectsBytes, objectsOffset + 154)).trim(),
               savedObjectMembers));
      }

      return savedObjects;
   }

   @Override
   protected boolean performSetText() {
      final StringBuilder builder = new StringBuilder(144);
      builder.append("CHGSAVF FILE(");
      builder.append(library);
      builder.append("/");
      builder.append(name);
      builder.append(") TEXT('");
      builder.append(text);
      builder.append("')");

      return JUtil.checkForMessage("CPC7303", getConnection().executeCommand(builder.toString()));
   }
}


text:
<?php

if (!defined('PGV_PHPGEDVIEW')) {
	header('HTTP/1.0 403 Forbidden');
	exit;
}

$pgv_lang["batch_update"]="Küme Güncelle";
$pgv_lang["bu_update_chan"]="DEĞİŞEN kaydı güncelle";
$pgv_lang["bu_nothing"]="Hiç bir şey bulunamadı.";
$pgv_lang["bu__desc"]="Bu listeden küme güncelleştirilmesini seç";
$pgv_lang["bu_button_update"]="Güncelle";
$pgv_lang["bu_button_update_all"]="Tümü güncelle";
$pgv_lang["bu_button_delete"]="Sil";
$pgv_lang["bu_button_delete_all"]="Tümü sil";

$pgv_lang["bu_search_replace"]="Bul ve Değiştir";
$pgv_lang["bu_search_replace_desc"]="Basit arama veya gelişmiş aynısı eşlemesini kullanarak GEDCOM içindeki veriyi ara ve/veya değiştir yapabilirsiniz.";
$pgv_lang["bu_search"]="Aranacak metin/aynısı";
$pgv_lang["bu_replace"]="Yerine konacak metin";
$pgv_lang["bu_method"]="Arama Metodu";
$pgv_lang["bu_exact"]="Metin Çıkart";
$pgv_lang["bu_exact_desc"]="Eğer ki kelimenin ortasında gerçekleşse bile tam metni eşle.";
$pgv_lang["bu_words"]="Sadece tüm kelime";
$pgv_lang["bu_words_desc"]="Kelimenin ortasında gerçekleşmedikçe tam metni eşle.";
$pgv_lang["bu_wildcards"]="Özel karakter";
$pgv_lang["bu_wildcards_desc"]="Sıfır veya daha çok karakterleri eşlemek için «*» karakter kullanın, tek karakter eşlemek için «?» karakteri kullanın.";
$pgv_lang["bu_regex"]="Düzenli ifade";
$pgv_lang["bu_regex_desc"]="Düzenli ifade kullanımı ileri düzey kullanıcıları için tekniğidir.  Tekniğin detayını görmek için php.net/manual/en/regexp.reference.php tıklayın.";
$pgv_lang["bu_regex_bad"]="The regex Düzenli ifadede bir hata içerdiği belirlendi. Kullanamaz.";
$pgv_lang["bu_case"]="Duyarsız arama";
$pgv_lang["bu_case_desc"]="Aradığınız metin küçük ve büyük harf karakterleri ile eşlemek için bu kutuyu işaretleyin.";

$pgv_lang["bu_birth_y"]="Girilmemiş doğum kayıtları ekle";
$pgv_lang["bu_birth_y_desc"]="Tüm bireyler «yaşam olayının başlamasına» sahip olduğuna güvence vererek PGV performansını geliştirebilirsiniz.";

$pgv_lang["bu_death_y"]="Girilmemiş ölüm kayıtları ekle";
$pgv_lang["bu_death_y_desc"]="Tüm bireyler «yaşam olayının ölümüne» sahip olduğuna güvence vererek PGV performansını geliştirebilirsiniz.";

$pgv_lang["bu_married_names"]="Girilmemiş evli kadına soyadı ekle";
$pgv_lang["bu_married_names_desc"]="Evli kadınların soy adlarını kaydederek evli kadınları daha kolay arayabileceksiniz.
Yinede tüm kadınlar kocalarının soyadlarını almaz veya kullanmazlar bundan dolay GEDCOM da yanlış veri kaydetmekten sakının.";
$pgv_lang["bu_surname_option"]="Soyad Seçeneği";
$pgv_lang["bu_surname_replace"]="Hanımının soyadı kocasının soyadı ile yer değiştir";
$pgv_lang["bu_surname_add"]="Hanımının kızlık soyadı yeni soyadı olarak belirle";

$pgv_lang["bu_name_format"]="İsim kesikleri ve boşlukları ayarla";
$pgv_lang["bu_name_format_desc"]="Doğru İSİM kayıtları 'Adem/GENÇ' veya 'Adem /GENÇ' olarak formdan eski soyağaco programı tarafından üretilir.";

$pgv_lang["bu_duplicate_links"]="Kopya Linkleri Kaldır";
$pgv_lang["bu_duplicate_links_desc"]="Aynı kayıtta birden fazla linklere sahip olmak ortak bir gedcom hatasıdır, örnek bir çocuk birden fazla ailede kayıt edilip listelenmesi.";

?>


text:
* Last item in, first item out (LIFO)
  - `push(value)`
  - `pop()`
  - `size()`
  - compare to [queues](./queues.md)
* Call Stack (a list of Stack Frames)
  - Use a constructor function with inner functions to demonstrate call stack;
  - important for recursion; and
  - JS is single threaded - but there are web workers in the DOM to muddy this idea.

![Event Loop](/assets/concurrency_model_and_event_loop.png)

## String Stack
```JavaScript
"use strict";

// First one in, last one out...
// Compare a queue is first one in, first one out.
function Stack() {}

Stack.prototype = (function() {
  var publicAPI;
  var data = "";
  var delimiter = ",";
  var length = 0;

  function getItem(index) {
    if (index === -1) {
      return data;
    } else {
      return data.substr(0, index);
    }
  }

  function resetStack(index) {
    if (index === -1) {
      data = "";
      length = 0;
    } else {
      data = data.slice(index + 1, data.length);
      length -= 1;
    }
  }

  publicAPI = {
    peek: function peek() {
      var topItemIndex = data.indexOf(delimiter);

      return getItem(topItemIndex);
    },
    pop: function pop() {
      var topItemIndex = data.indexOf(delimiter);
      var topItem = getItem(topItemIndex);

      resetStack(topItemIndex);

      return topItem;
    },
    push: function push(value) {
      if (this.size() > 0) {
        data = value + delimiter + data;
      } else {
        data = value;
      }
      length += 1;
    },
    size: function size() {
      return length;
    }
  };

  return publicAPI;
}());

var stack = new Stack();

stack.push("foo");
stack.push("bar");
stack.peek(); // "bar"
stack.size(); // 2
stack.pop();  // "bar"
stack.size(); // 1
stack.pop();  // "foo"
```

## Object Stack
```JavaScript
"use strict";

// First one in, last one out...
// Compare a queue is first one in, first one out.
function Stack() {}

Stack.prototype = (function() {
  var publicAPI;
  var data = {};
  var length = 0;

  publicAPI = {
    peek: function() {
      return data[length];
    },
    pop: function pop() {
      if (length > 0) {
        var topItem = data[length]
        delete data[length];
        length -= 1;

        return topItem;
      }
    },
    push: function push(value) {
      data[length += 1] = value;
    },
    size: function size() {
      return length;
    }
  };

  return publicAPI;
}());

var stack = new Stack();

stack.push("foo");
stack.push("bar");
stack.peek(); // "foo"
stack.size(); // 2
stack.pop();  // "bar"
stack.size(); // 1
stack.pop();  // "foo"
```

## Minimum Stack

Implement a stack with a `minimum` method which returns the minimum element currently in the stack.
This method should have _O(1)_ time complexity.
Make sure your implementation handles duplicates.

```JavaScript
"use strict";

function miniStack() {
  var publicAPI;
  var data = {};
  var minimumData = {};
  var length = 0;

  function popFromMinimumStack(minimumData, length) {
    delete minimumData[length];
  }

  function pushOnMinimumStack(minimumData, length, value) {
    var previous = minimumData[length - 1];

    if (previous === undefined || value < previous) { // WOW!!
      minimumData[length] = value;
    } else {
      minimumData[length] = previous;
    }
  }

  publicAPI = {
    minimum: function minimum() {
      return minimumData[length];
    },
    peek: function() {
      return data[length];
    },
    pop: function pop() {
      if (length > 0) {
        var topItem = data[length];
        delete data[length];
        popFromMinimumStack(minimumData, length);
        length -= 1;

        return topItem;
      }
    },
    push: function push(value) {
      data[length += 1] = value;
      pushOnMinimumStack(minimumData, length, value);
    },
    size: function size() {
      return length;
    }
  };

  return publicAPI;
}

var stack = miniStack();

stack.push(4);
stack.minimum(); // 4
stack.push(3);
stack.minimum(); // 3
stack.push(3);
stack.minimum(); // 3
stack.push(8);
stack.minimum(); // 3
stack.push(2);
stack.minimum(); // 2
stack.peek();    // 2
stack.size();    // 5
stack.pop();     // 2
stack.minimum(); // 3
```


text:
/**
 * ColumnWidth mixin
 */

var columnWidth = function columnWidth(value) {
  value = value || 'auto';
  var numRegex = /\d/gi;
  var numWithoutValue = /(?:\s|^)(\.?\d+\.?\d*)(?![^(]*\)|\w|%|\.)/gi;

  if (numRegex.test(value)) {
    value = value.replace(numWithoutValue, function(match) {
      return match + 'px';
    });
  }

  return value;
};

/**
 * For which browsers is this mixin specified
 */

columnWidth.vendors = ['webkit', 'moz'];

/**
 * Export mixin
 */

module.exports = columnWidth;


text:
/**
 */
package org.mobadsl.semantic.model.moba;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.eclipse.emf.common.util.Enumerator;

/**
 *
 * A representation of the literals of the enumeration 'Constant Value Function',
 * and utility methods for working with them.
 *
 * @see org.mobadsl.semantic.model.moba.MobaPackage#getMobaConstantValueFunction()
 * @model
 * @generated
 */
public enum MobaConstantValueFunction implements Enumerator {
	/**
	 * The 'TO LOWER CASE' literal object.
	 *
	 *
	 * @see #TO_LOWER_CASE_VALUE
	 * @generated
	 * @ordered
	 */
	TO_LOWER_CASE(0, "TO_LOWER_CASE", "TO_LOWER_CASE"),

	/**
	 * The 'TO UPPER CASE' literal object.
	 *
	 *
	 * @see #TO_UPPER_CASE_VALUE
	 * @generated
	 * @ordered
	 */
	TO_UPPER_CASE(1, "TO_UPPER_CASE", "TO_UPPER_CASE"),

	/**
	 * The 'TO FIRST UPPER CASE' literal object.
	 *
	 *
	 * @see #TO_FIRST_UPPER_CASE_VALUE
	 * @generated
	 * @ordered
	 */
	TO_FIRST_UPPER_CASE(2, "TO_FIRST_UPPER_CASE", "TO_FIRST_UPPER_CASE"),

	/**
	 * The 'TO FIRST LOWER CASE' literal object.
	 *
	 *
	 * @see #TO_FIRST_LOWER_CASE_VALUE
	 * @generated
	 * @ordered
	 */
	TO_FIRST_LOWER_CASE(3, "TO_FIRST_LOWER_CASE", "TO_FIRST_LOWER_CASE");

	/**
	 * The 'TO LOWER CASE' literal value.
	 *
	 *

	 * If the meaning of 'TO LOWER CASE' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #TO_LOWER_CASE
	 * @model
	 * @generated
	 * @ordered
	 */
	public static final int TO_LOWER_CASE_VALUE = 0;

	/**
	 * The 'TO UPPER CASE' literal value.
	 *
	 *

	 * If the meaning of 'TO UPPER CASE' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #TO_UPPER_CASE
	 * @model
	 * @generated
	 * @ordered
	 */
	public static final int TO_UPPER_CASE_VALUE = 1;

	/**
	 * The 'TO FIRST UPPER CASE' literal value.
	 *
	 *

	 * If the meaning of 'TO FIRST UPPER CASE' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #TO_FIRST_UPPER_CASE
	 * @model
	 * @generated
	 * @ordered
	 */
	public static final int TO_FIRST_UPPER_CASE_VALUE = 2;

	/**
	 * The 'TO FIRST LOWER CASE' literal value.
	 *
	 *

	 * If the meaning of 'TO FIRST LOWER CASE' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #TO_FIRST_LOWER_CASE
	 * @model
	 * @generated
	 * @ordered
	 */
	public static final int TO_FIRST_LOWER_CASE_VALUE = 3;

	/**
	 * An array of all the 'Constant Value Function' enumerators.
	 *
	 *
	 * @generated
	 */
	private static final MobaConstantValueFunction[] VALUES_ARRAY =
		new MobaConstantValueFunction[] {
			TO_LOWER_CASE,
			TO_UPPER_CASE,
			TO_FIRST_UPPER_CASE,
			TO_FIRST_LOWER_CASE,
		};

	/**
	 * A public read-only list of all the 'Constant Value Function' enumerators.
	 *
	 *
	 * @generated
	 */
	public static final List<MobaConstantValueFunction> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));

	/**
	 * Returns the 'Constant Value Function' literal with the specified literal value.
	 *
	 *
	 * @param literal the literal.
	 * @return the matching enumerator or null.
	 * @generated
	 */
	public static MobaConstantValueFunction get(String literal) {
		for (int i = 0; i < VALUES_ARRAY.length; ++i) {
			MobaConstantValueFunction result = VALUES_ARRAY[i];
			if (result.toString().equals(literal)) {
				return result;
			}
		}
		return null;
	}

	/**
	 * Returns the 'Constant Value Function' literal with the specified name.
	 *
	 *
	 * @param name the name.
	 * @return the matching enumerator or null.
	 * @generated
	 */
	public static MobaConstantValueFunction getByName(String name) {
		for (int i = 0; i < VALUES_ARRAY.length; ++i) {
			MobaConstantValueFunction result = VALUES_ARRAY[i];
			if (result.getName().equals(name)) {
				return result;
			}
		}
		return null;
	}

	/**
	 * Returns the 'Constant Value Function' literal with the specified integer value.
	 *
	 *
	 * @param value the integer value.
	 * @return the matching enumerator or null.
	 * @generated
	 */
	public static MobaConstantValueFunction get(int value) {
		switch (value) {
			case TO_LOWER_CASE_VALUE: return TO_LOWER_CASE;
			case TO_UPPER_CASE_VALUE: return TO_UPPER_CASE;
			case TO_FIRST_UPPER_CASE_VALUE: return TO_FIRST_UPPER_CASE;
			case TO_FIRST_LOWER_CASE_VALUE: return TO_FIRST_LOWER_CASE;
		}
		return null;
	}

	/**
	 *
	 *
	 * @generated
	 */
	private final int value;

	/**
	 *
	 *
	 * @generated
	 */
	private final String name;

	/**
	 *
	 *
	 * @generated
	 */
	private final String literal;

	/**
	 * Only this class can construct instances.
	 *
	 *
	 * @generated
	 */
	private MobaConstantValueFunction(int value, String name, String literal) {
		this.value = value;
		this.name = name;
		this.literal = literal;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public int getValue() {
	  return value;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getName() {
	  return name;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getLiteral() {
	  return literal;
	}

	/**
	 * Returns the literal value of the enumerator, which is its string representation.
	 *
	 *
	 * @generated
	 */
	@Override
	public String toString() {
		return literal;
	}

} //MobaConstantValueFunction


text:
.class public Lcom/android/internal/os/storage/ExternalStorageFormatter;
.super Landroid/app/Service;
.source "ExternalStorageFormatter.java"

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/android/internal/os/storage/ExternalStorageFormatter$InternalStorageFormatterStringGetter;,
        Lcom/android/internal/os/storage/ExternalStorageFormatter$UsbStorageFormatterStringGetter;,
        Lcom/android/internal/os/storage/ExternalStorageFormatter$StorageFormatterStringGetter;
    }
.end annotation

# static fields
.field public static final COMPONENT_NAME:Landroid/content/ComponentName; = null

.field public static final EXTRA_ALWAYS_RESET:Ljava/lang/String; = "always_reset"

.field public static final FORMAT_AND_FACTORY_RESET:Ljava/lang/String; = "com.android.internal.os.storage.FORMAT_AND_FACTORY_RESET"

.field public static final FORMAT_ONLY:Ljava/lang/String; = "com.android.internal.os.storage.FORMAT_ONLY"

.field static final TAG:Ljava/lang/String; = "ExternalStorageFormatter"

# instance fields
.field private mAlwaysReset:Z

.field private mExtStoragePath:Ljava/lang/String;

.field private mFactoryReset:Z

.field private mIsStopped:Z

.field private mMountService:Landroid/os/storage/IMountService;

.field private mProgressDialog:Landroid/app/ProgressDialog;

.field mStorageListener:Landroid/os/storage/StorageEventListener;

.field private mStorageManager:Landroid/os/storage/StorageManager;

.field private mStorageVolume:Landroid/os/storage/StorageVolume;

.field mStringGetter:Lcom/android/internal/os/storage/ExternalStorageFormatter$StorageFormatterStringGetter;

.field private mWakeLock:Landroid/os/PowerManager$WakeLock;

# direct methods
.method static constructor <clinit>()V
    .locals 3

    .prologue
    .line 45
    new-instance v0, Landroid/content/ComponentName;

    const-string v1, "android"

    const-class v2, Lcom/android/internal/os/storage/ExternalStorageFormatter;

    invoke-virtual {v2}, Ljava/lang/Class;->getName()Ljava/lang/String;

    move-result-object v2

    invoke-direct {v0, v1, v2}, Landroid/content/ComponentName;-><init>(Ljava/lang/String;Ljava/lang/String;)V

    sput-object v0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->COMPONENT_NAME:Landroid/content/ComponentName;

    return-void
.end method

.method public constructor <init>()V
    .locals 2

    .prologue
    const/4 v0, 0x0

    const/4 v1, 0x0

    .line 32
    invoke-direct {p0}, Landroid/app/Service;-><init>()V

    .line 49
    iput-object v1, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mMountService:Landroid/os/storage/IMountService;

    .line 51
    iput-object v1, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mStorageManager:Landroid/os/storage/StorageManager;

    .line 55
    iput-object v1, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mProgressDialog:Landroid/app/ProgressDialog;

    .line 57
    iput-boolean v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mFactoryReset:Z

    .line 58
    iput-boolean v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mAlwaysReset:Z

    .line 59
    iput-boolean v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mIsStopped:Z

    .line 61
    new-instance v0, Lcom/android/internal/os/storage/ExternalStorageFormatter$StorageFormatterStringGetter;

    invoke-direct {v0, v1}, Lcom/android/internal/os/storage/ExternalStorageFormatter$StorageFormatterStringGetter;-><init>(Lcom/android/internal/os/storage/ExternalStorageFormatter$1;)V

    iput-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mStringGetter:Lcom/android/internal/os/storage/ExternalStorageFormatter$StorageFormatterStringGetter;

    .line 63
    new-instance v0, Lcom/android/internal/os/storage/ExternalStorageFormatter$1;

    invoke-direct {v0, p0}, Lcom/android/internal/os/storage/ExternalStorageFormatter$1;-><init>(Lcom/android/internal/os/storage/ExternalStorageFormatter;)V

    iput-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mStorageListener:Landroid/os/storage/StorageEventListener;

    .line 318
    return-void
.end method

.method static synthetic access$100(Lcom/android/internal/os/storage/ExternalStorageFormatter;)Ljava/lang/String;
    .locals 1
    .parameter "x0"

    .prologue
    .line 32
    iget-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mExtStoragePath:Ljava/lang/String;

    return-object v0
.end method

.method static synthetic access$200(Lcom/android/internal/os/storage/ExternalStorageFormatter;Ljava/lang/String;)Ljava/lang/String;
    .locals 1
    .parameter "x0"
    .parameter "x1"

    .prologue
    .line 32
    invoke-direct {p0, p1}, Lcom/android/internal/os/storage/ExternalStorageFormatter;->deleteLastSlash(Ljava/lang/String;)Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method

.method static synthetic access$300(Lcom/android/internal/os/storage/ExternalStorageFormatter;)Z
    .locals 1
    .parameter "x0"

    .prologue
    .line 32
    iget-boolean v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mFactoryReset:Z

    return v0
.end method

.method static synthetic access$400(Lcom/android/internal/os/storage/ExternalStorageFormatter;)V
    .locals 0
    .parameter "x0"

    .prologue
    .line 32
    invoke-direct {p0}, Lcom/android/internal/os/storage/ExternalStorageFormatter;->stopSelfInternal()V

    return-void
.end method

.method static synthetic access$500(Lcom/android/internal/os/storage/ExternalStorageFormatter;)Z
    .locals 1
    .parameter "x0"

    .prologue
    .line 32
    iget-boolean v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mAlwaysReset:Z

    return v0
.end method

.method static synthetic access$602(Lcom/android/internal/os/storage/ExternalStorageFormatter;Z)Z
    .locals 0
    .parameter "x0"
    .parameter "x1"

    .prologue
    .line 32
    iput-boolean p1, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mIsStopped:Z

    return p1
.end method

.method private deleteLastSlash(Ljava/lang/String;)Ljava/lang/String;
    .locals 2
    .parameter "path"

    .prologue
    .line 367
    if-eqz p1, :cond_0

    const-string v0, "/"

    invoke-virtual {p1, v0}, Ljava/lang/String;->endsWith(Ljava/lang/String;)Z

    move-result v0

    if-eqz v0, :cond_0

    .line 368
    const/4 v0, 0x0

    invoke-virtual {p1}, Ljava/lang/String;->length()I

    move-result v1

    add-int/lit8 v1, v1, -0x1

    invoke-virtual {p1, v0, v1}, Ljava/lang/String;->substring(II)Ljava/lang/String;

    move-result-object p1

    .line 370
    .end local p1
    :cond_0
    return-object p1
.end method

.method private getStringGetter(Ljava/lang/String;)Lcom/android/internal/os/storage/ExternalStorageFormatter$StorageFormatterStringGetter;
    .locals 6
    .parameter "path"

    .prologue
    const/4 v5, 0x0

    .line 343
    sget-object v1, Landroid/os/storage/StorageManager$StorageType;->EXTERNAL_CARD:Landroid/os/storage/StorageManager$StorageType;

    .line 345
    .local v1, storageType:Landroid/os/storage/StorageManager$StorageType;
    :try_start_0
    iget-object v2, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mStorageManager:Landroid/os/storage/StorageManager;

    invoke-virtual {v2, p1}, Landroid/os/storage/StorageManager;->getVolumeType(Ljava/lang/String;)Landroid/os/storage/StorageManager$StorageType;
    :try_end_0
    .catch Ljava/io/FileNotFoundException; {:try_start_0 .. :try_end_0} :catch_0

    move-result-object v1

    .line 350
    :goto_0
    sget-object v2, Landroid/os/storage/StorageManager$StorageType;->EXTERNAL_USB:Landroid/os/storage/StorageManager$StorageType;

    invoke-virtual {v2, v1}, Landroid/os/storage/StorageManager$StorageType;->equals(Ljava/lang/Object;)Z

    move-result v2

    if-eqz v2, :cond_0

    .line 351
    new-instance v2, Lcom/android/internal/os/storage/ExternalStorageFormatter$UsbStorageFormatterStringGetter;

    invoke-direct {v2, v5}, Lcom/android/internal/os/storage/ExternalStorageFormatter$UsbStorageFormatterStringGetter;-><init>(Lcom/android/internal/os/storage/ExternalStorageFormatter$1;)V

    .line 358
    :goto_1
    return-object v2

    .line 346
    :catch_0
    move-exception v0

    .line 347
    .local v0, e:Ljava/io/FileNotFoundException;
    const-string v2, "ExternalStorageFormatter"

    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    const-string v4, "Failed to get volume type, "

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v0}, Ljava/io/FileNotFoundException;->toString()Ljava/lang/String;

    move-result-object v4

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    invoke-static {v2, v3}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    goto :goto_0

    .line 352
    .end local v0           #e:Ljava/io/FileNotFoundException;
    :cond_0
    sget-object v2, Landroid/os/storage/StorageManager$StorageType;->INTERNAL:Landroid/os/storage/StorageManager$StorageType;

    invoke-virtual {v2, v1}, Landroid/os/storage/StorageManager$StorageType;->equals(Ljava/lang/Object;)Z

    move-result v2

    if-eqz v2, :cond_1

    .line 353
    new-instance v2, Lcom/android/internal/os/storage/ExternalStorageFormatter$InternalStorageFormatterStringGetter;

    invoke-direct {v2, v5}, Lcom/android/internal/os/storage/ExternalStorageFormatter$InternalStorageFormatterStringGetter;-><init>(Lcom/android/internal/os/storage/ExternalStorageFormatter$1;)V

    goto :goto_1

    .line 358
    :cond_1
    new-instance v2, Lcom/android/internal/os/storage/ExternalStorageFormatter$StorageFormatterStringGetter;

    invoke-direct {v2, v5}, Lcom/android/internal/os/storage/ExternalStorageFormatter$StorageFormatterStringGetter;-><init>(Lcom/android/internal/os/storage/ExternalStorageFormatter$1;)V

    goto :goto_1
.end method

.method private stopSelfInternal()V
    .locals 1

    .prologue
    .line 362
    const/4 v0, 0x1

    iput-boolean v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mIsStopped:Z

    .line 363
    invoke-virtual {p0}, Lcom/android/internal/os/storage/ExternalStorageFormatter;->stopSelf()V

    .line 364
    return-void
.end method

# virtual methods
.method fail(I)V
    .locals 2
    .parameter "msg"

    .prologue
    .line 143
    const/4 v0, 0x1

    invoke-static {p0, p1, v0}, Landroid/widget/Toast;->makeText(Landroid/content/Context;II)Landroid/widget/Toast;

    move-result-object v0

    invoke-virtual {v0}, Landroid/widget/Toast;->show()V

    .line 144
    iget-boolean v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mAlwaysReset:Z

    if-eqz v0, :cond_0

    .line 145
    new-instance v0, Landroid/content/Intent;

    const-string v1, "android.intent.action.MASTER_CLEAR"

    invoke-direct {v0, v1}, Landroid/content/Intent;-><init>(Ljava/lang/String;)V

    invoke-virtual {p0, v0}, Lcom/android/internal/os/storage/ExternalStorageFormatter;->sendBroadcast(Landroid/content/Intent;)V

    .line 147
    :cond_0
    invoke-direct {p0}, Lcom/android/internal/os/storage/ExternalStorageFormatter;->stopSelfInternal()V

    .line 148
    return-void
.end method

.method getMountService()Landroid/os/storage/IMountService;
    .locals 3

    .prologue
    .line 245
    iget-object v1, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mMountService:Landroid/os/storage/IMountService;

    if-nez v1, :cond_0

    .line 246
    const-string/jumbo v1, "mount"

    invoke-static {v1}, Landroid/os/ServiceManager;->getService(Ljava/lang/String;)Landroid/os/IBinder;

    move-result-object v0

    .line 247
    .local v0, service:Landroid/os/IBinder;
    if-eqz v0, :cond_1

    .line 248
    invoke-static {v0}, Landroid/os/storage/IMountService$Stub;->asInterface(Landroid/os/IBinder;)Landroid/os/storage/IMountService;

    move-result-object v1

    iput-object v1, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mMountService:Landroid/os/storage/IMountService;

    .line 253
    .end local v0           #service:Landroid/os/IBinder;
    :cond_0
    :goto_0
    iget-object v1, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mMountService:Landroid/os/storage/IMountService;

    return-object v1

    .line 250
    .restart local v0       #service:Landroid/os/IBinder;
    :cond_1
    const-string v1, "ExternalStorageFormatter"

    const-string v2, "Can\'t get mount service"

    invoke-static {v1, v2}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    goto :goto_0
.end method

.method public onBind(Landroid/content/Intent;)Landroid/os/IBinder;
    .locals 1
    .parameter "intent"

    .prologue
    .line 139
    const/4 v0, 0x0

    return-object v0
.end method

.method public onCreate()V
    .locals 3

    .prologue
    .line 86
    invoke-super {p0}, Landroid/app/Service;->onCreate()V

    .line 88
    iget-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mStorageManager:Landroid/os/storage/StorageManager;

    if-nez v0, :cond_0

    .line 89
    const-string/jumbo v0, "storage"

    invoke-virtual {p0, v0}, Lcom/android/internal/os/storage/ExternalStorageFormatter;->getSystemService(Ljava/lang/String;)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/os/storage/StorageManager;

    iput-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mStorageManager:Landroid/os/storage/StorageManager;

    .line 90
    iget-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mStorageManager:Landroid/os/storage/StorageManager;

    iget-object v1, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mStorageListener:Landroid/os/storage/StorageEventListener;

    invoke-virtual {v0, v1}, Landroid/os/storage/StorageManager;->registerListener(Landroid/os/storage/StorageEventListener;)V

    .line 93
    :cond_0
    const-string/jumbo v0, "power"

    invoke-virtual {p0, v0}, Lcom/android/internal/os/storage/ExternalStorageFormatter;->getSystemService(Ljava/lang/String;)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/os/PowerManager;

    const/4 v1, 0x1

    const-string v2, "ExternalStorageFormatter"

    invoke-virtual {v0, v1, v2}, Landroid/os/PowerManager;->newWakeLock(ILjava/lang/String;)Landroid/os/PowerManager$WakeLock;

    move-result-object v0

    iput-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mWakeLock:Landroid/os/PowerManager$WakeLock;

    .line 95
    iget-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mWakeLock:Landroid/os/PowerManager$WakeLock;

    invoke-virtual {v0}, Landroid/os/PowerManager$WakeLock;->acquire()V

    .line 96
    return-void
.end method

.method public onDestroy()V
    .locals 2

    .prologue
    .line 127
    iget-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mStorageManager:Landroid/os/storage/StorageManager;

    if-eqz v0, :cond_0

    .line 128
    iget-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mStorageManager:Landroid/os/storage/StorageManager;

    iget-object v1, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mStorageListener:Landroid/os/storage/StorageEventListener;

    invoke-virtual {v0, v1}, Landroid/os/storage/StorageManager;->unregisterListener(Landroid/os/storage/StorageEventListener;)V

    .line 130
    :cond_0
    iget-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mProgressDialog:Landroid/app/ProgressDialog;

    if-eqz v0, :cond_1

    .line 131
    iget-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mProgressDialog:Landroid/app/ProgressDialog;

    invoke-virtual {v0}, Landroid/app/ProgressDialog;->dismiss()V

    .line 133
    :cond_1
    iget-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mWakeLock:Landroid/os/PowerManager$WakeLock;

    invoke-virtual {v0}, Landroid/os/PowerManager$WakeLock;->release()V

    .line 134
    invoke-super {p0}, Landroid/app/Service;->onDestroy()V

    .line 135
    return-void
.end method

.method public onStartCommand(Landroid/content/Intent;II)I
    .locals 4
    .parameter "intent"
    .parameter "flags"
    .parameter "startId"

    .prologue
    const/4 v3, 0x0

    const/4 v2, 0x1

    .line 100
    const-string v0, "com.android.internal.os.storage.FORMAT_AND_FACTORY_RESET"

    invoke-virtual {p1}, Landroid/content/Intent;->getAction()Ljava/lang/String;

    move-result-object v1

    invoke-virtual {v0, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v0

    if-eqz v0, :cond_0

    .line 101
    iput-boolean v2, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mFactoryReset:Z

    .line 103
    :cond_0
    const-string v0, "always_reset"

    invoke-virtual {p1, v0, v3}, Landroid/content/Intent;->getBooleanExtra(Ljava/lang/String;Z)Z

    move-result v0

    if-eqz v0, :cond_1

    .line 104
    iput-boolean v2, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mAlwaysReset:Z

    .line 107
    :cond_1
    const-string/jumbo v0, "storage_volume"

    invoke-virtual {p1, v0}, Landroid/content/Intent;->getParcelableExtra(Ljava/lang/String;)Landroid/os/Parcelable;

    move-result-object v0

    check-cast v0, Landroid/os/storage/StorageVolume;

    iput-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mStorageVolume:Landroid/os/storage/StorageVolume;

    .line 108
    iget-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mStorageVolume:Landroid/os/storage/StorageVolume;

    if-nez v0, :cond_3

    invoke-static {}, Landroid/os/Environment;->getExternalStorageDirectory()Ljava/io/File;

    move-result-object v0

    invoke-virtual {v0}, Ljava/io/File;->getPath()Ljava/lang/String;

    move-result-object v0

    :goto_0
    iput-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mExtStoragePath:Ljava/lang/String;

    .line 111
    iget-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mExtStoragePath:Ljava/lang/String;

    invoke-direct {p0, v0}, Lcom/android/internal/os/storage/ExternalStorageFormatter;->getStringGetter(Ljava/lang/String;)Lcom/android/internal/os/storage/ExternalStorageFormatter$StorageFormatterStringGetter;

    move-result-object v0

    iput-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mStringGetter:Lcom/android/internal/os/storage/ExternalStorageFormatter$StorageFormatterStringGetter;

    .line 113
    iget-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mProgressDialog:Landroid/app/ProgressDialog;

    if-nez v0, :cond_2

    .line 114
    new-instance v0, Landroid/app/ProgressDialog;

    invoke-direct {v0, p0}, Landroid/app/ProgressDialog;-><init>(Landroid/content/Context;)V

    iput-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mProgressDialog:Landroid/app/ProgressDialog;

    .line 115
    iget-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mProgressDialog:Landroid/app/ProgressDialog;

    invoke-virtual {v0, v2}, Landroid/app/ProgressDialog;->setIndeterminate(Z)V

    .line 116
    iget-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mProgressDialog:Landroid/app/ProgressDialog;

    invoke-virtual {v0, v3}, Landroid/app/ProgressDialog;->setCancelable(Z)V

    .line 117
    iget-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mProgressDialog:Landroid/app/ProgressDialog;

    invoke-virtual {v0}, Landroid/app/ProgressDialog;->getWindow()Landroid/view/Window;

    move-result-object v0

    const/16 v1, 0x7d3

    invoke-virtual {v0, v1}, Landroid/view/Window;->setType(I)V

    .line 118
    invoke-virtual {p0}, Lcom/android/internal/os/storage/ExternalStorageFormatter;->updateProgressState()V

    .line 119
    iget-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mProgressDialog:Landroid/app/ProgressDialog;

    invoke-virtual {v0}, Landroid/app/ProgressDialog;->show()V

    .line 122
    :cond_2
    const/4 v0, 0x3

    return v0

    .line 108
    :cond_3
    iget-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mStorageVolume:Landroid/os/storage/StorageVolume;

    invoke-virtual {v0}, Landroid/os/storage/StorageVolume;->getPath()Ljava/lang/String;

    move-result-object v0

    goto :goto_0
.end method

.method public updateProgressDialog(I)V
    .locals 2
    .parameter "msg"

    .prologue
    .line 233
    iget-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mProgressDialog:Landroid/app/ProgressDialog;

    if-nez v0, :cond_0

    .line 234
    new-instance v0, Landroid/app/ProgressDialog;

    invoke-direct {v0, p0}, Landroid/app/ProgressDialog;-><init>(Landroid/content/Context;)V

    iput-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mProgressDialog:Landroid/app/ProgressDialog;

    .line 235
    iget-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mProgressDialog:Landroid/app/ProgressDialog;

    const/4 v1, 0x1

    invoke-virtual {v0, v1}, Landroid/app/ProgressDialog;->setIndeterminate(Z)V

    .line 236
    iget-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mProgressDialog:Landroid/app/ProgressDialog;

    const/4 v1, 0x0

    invoke-virtual {v0, v1}, Landroid/app/ProgressDialog;->setCancelable(Z)V

    .line 237
    iget-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mProgressDialog:Landroid/app/ProgressDialog;

    invoke-virtual {v0}, Landroid/app/ProgressDialog;->getWindow()Landroid/view/Window;

    move-result-object v0

    const/16 v1, 0x7d3

    invoke-virtual {v0, v1}, Landroid/view/Window;->setType(I)V

    .line 238
    iget-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mProgressDialog:Landroid/app/ProgressDialog;

    invoke-virtual {v0}, Landroid/app/ProgressDialog;->show()V

    .line 241
    :cond_0
    iget-object v0, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mProgressDialog:Landroid/app/ProgressDialog;

    invoke-virtual {p0, p1}, Lcom/android/internal/os/storage/ExternalStorageFormatter;->getText(I)Ljava/lang/CharSequence;

    move-result-object v1

    invoke-virtual {v0, v1}, Landroid/app/ProgressDialog;->setMessage(Ljava/lang/CharSequence;)V

    .line 242
    return-void
.end method

.method updateProgressState()V
    .locals 6

    .prologue
    .line 152
    iget-boolean v3, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mIsStopped:Z

    if-eqz v3, :cond_1

    .line 230
    :cond_0
    :goto_0
    return-void

    .line 156
    :cond_1
    iget-object v3, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mStorageManager:Landroid/os/storage/StorageManager;

    iget-object v4, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mExtStoragePath:Ljava/lang/String;

    invoke-virtual {v3, v4}, Landroid/os/storage/StorageManager;->getVolumeState(Ljava/lang/String;)Ljava/lang/String;

    move-result-object v2

    .line 157
    .local v2, status:Ljava/lang/String;
    const-string/jumbo v3, "mounted"

    invoke-virtual {v3, v2}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v3

    if-nez v3, :cond_2

    const-string/jumbo v3, "mounted_ro"

    invoke-virtual {v3, v2}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v3

    if-eqz v3, :cond_3

    .line 159
    :cond_2
    iget-object v3, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mStringGetter:Lcom/android/internal/os/storage/ExternalStorageFormatter$StorageFormatterStringGetter;

    invoke-virtual {v3}, Lcom/android/internal/os/storage/ExternalStorageFormatter$StorageFormatterStringGetter;->getStringProgressUnmounting()I

    move-result v3

    invoke-virtual {p0, v3}, Lcom/android/internal/os/storage/ExternalStorageFormatter;->updateProgressDialog(I)V

    .line 160
    invoke-virtual {p0}, Lcom/android/internal/os/storage/ExternalStorageFormatter;->getMountService()Landroid/os/storage/IMountService;

    move-result-object v1

    .line 163
    .local v1, mountService:Landroid/os/storage/IMountService;
    :try_start_0
    iget-object v3, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mExtStoragePath:Ljava/lang/String;

    const/4 v4, 0x1

    iget-boolean v5, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mFactoryReset:Z

    invoke-interface {v1, v3, v4, v5}, Landroid/os/storage/IMountService;->unmountVolume(Ljava/lang/String;ZZ)V
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    goto :goto_0

    .line 164
    :catch_0
    move-exception v0

    .line 165
    .local v0, e:Landroid/os/RemoteException;
    const-string v3, "ExternalStorageFormatter"

    const-string v4, "Failed talking with mount service"

    invoke-static {v3, v4, v0}, Landroid/util/Log;->w(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I

    .line 166
    invoke-direct {p0}, Lcom/android/internal/os/storage/ExternalStorageFormatter;->stopSelfInternal()V

    goto :goto_0

    .line 168
    .end local v0           #e:Landroid/os/RemoteException;
    .end local v1           #mountService:Landroid/os/storage/IMountService;
    :cond_3
    const-string/jumbo v3, "nofs"

    invoke-virtual {v3, v2}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v3

    if-nez v3, :cond_4

    const-string/jumbo v3, "unmounted"

    invoke-virtual {v3, v2}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v3

    if-nez v3, :cond_4

    const-string/jumbo v3, "unmountable"

    invoke-virtual {v3, v2}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v3

    if-eqz v3, :cond_6

    .line 171
    :cond_4
    iget-object v3, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mStringGetter:Lcom/android/internal/os/storage/ExternalStorageFormatter$StorageFormatterStringGetter;

    invoke-virtual {v3}, Lcom/android/internal/os/storage/ExternalStorageFormatter$StorageFormatterStringGetter;->getStringProgressErasing()I

    move-result v3

    invoke-virtual {p0, v3}, Lcom/android/internal/os/storage/ExternalStorageFormatter;->updateProgressDialog(I)V

    .line 172
    invoke-virtual {p0}, Lcom/android/internal/os/storage/ExternalStorageFormatter;->getMountService()Landroid/os/storage/IMountService;

    move-result-object v1

    .line 173
    .restart local v1       #mountService:Landroid/os/storage/IMountService;
    if-eqz v1, :cond_5

    .line 174
    new-instance v3, Lcom/android/internal/os/storage/ExternalStorageFormatter$2;

    invoke-direct {v3, p0, v1}, Lcom/android/internal/os/storage/ExternalStorageFormatter$2;-><init>(Lcom/android/internal/os/storage/ExternalStorageFormatter;Landroid/os/storage/IMountService;)V

    invoke-virtual {v3}, Lcom/android/internal/os/storage/ExternalStorageFormatter$2;->start()V

    goto :goto_0

    .line 212
    :cond_5
    const-string v3, "ExternalStorageFormatter"

    const-string v4, "Unable to locate IMountService"

    invoke-static {v3, v4}, Landroid/util/Log;->w(Ljava/lang/String;Ljava/lang/String;)I

    .line 213
    invoke-direct {p0}, Lcom/android/internal/os/storage/ExternalStorageFormatter;->stopSelfInternal()V

    goto :goto_0

    .line 215
    .end local v1           #mountService:Landroid/os/storage/IMountService;
    :cond_6
    const-string v3, "bad_removal"

    invoke-virtual {v3, v2}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v3

    if-eqz v3, :cond_7

    .line 216
    iget-object v3, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mStringGetter:Lcom/android/internal/os/storage/ExternalStorageFormatter$StorageFormatterStringGetter;

    invoke-virtual {v3}, Lcom/android/internal/os/storage/ExternalStorageFormatter$StorageFormatterStringGetter;->getStringBadRemoval()I

    move-result v3

    invoke-virtual {p0, v3}, Lcom/android/internal/os/storage/ExternalStorageFormatter;->fail(I)V

    goto/16 :goto_0

    .line 217
    :cond_7
    const-string v3, "checking"

    invoke-virtual {v3, v2}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v3

    if-nez v3, :cond_0

    .line 221
    const-string/jumbo v3, "removed"

    invoke-virtual {v3, v2}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v3

    if-eqz v3, :cond_8

    .line 222
    iget-object v3, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mStringGetter:Lcom/android/internal/os/storage/ExternalStorageFormatter$StorageFormatterStringGetter;

    invoke-virtual {v3}, Lcom/android/internal/os/storage/ExternalStorageFormatter$StorageFormatterStringGetter;->getStringMediaRemoved()I

    move-result v3

    invoke-virtual {p0, v3}, Lcom/android/internal/os/storage/ExternalStorageFormatter;->fail(I)V

    goto/16 :goto_0

    .line 223
    :cond_8
    const-string/jumbo v3, "shared"

    invoke-virtual {v3, v2}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v3

    if-eqz v3, :cond_9

    .line 224
    iget-object v3, p0, Lcom/android/internal/os/storage/ExternalStorageFormatter;->mStringGetter:Lcom/android/internal/os/storage/ExternalStorageFormatter$StorageFormatterStringGetter;

    invoke-virtual {v3}, Lcom/android/internal/os/storage/ExternalStorageFormatter$StorageFormatterStringGetter;->getStringMediaShared()I

    move-result v3

    invoke-virtual {p0, v3}, Lcom/android/internal/os/storage/ExternalStorageFormatter;->fail(I)V

    goto/16 :goto_0

    .line 226
    :cond_9
    const v3, 0x10404ba

    invoke-virtual {p0, v3}, Lcom/android/internal/os/storage/ExternalStorageFormatter;->fail(I)V

    .line 227
    const-string v3, "ExternalStorageFormatter"

    new-instance v4, Ljava/lang/StringBuilder;

    invoke-direct {v4}, Ljava/lang/StringBuilder;-><init>()V

    const-string v5, "Unknown storage state: "

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v4

    invoke-static {v3, v4}, Landroid/util/Log;->w(Ljava/lang/String;Ljava/lang/String;)I

    .line 228
    invoke-direct {p0}, Lcom/android/internal/os/storage/ExternalStorageFormatter;->stopSelfInternal()V

    goto/16 :goto_0
.end method


text:
#ifndef TUBA_INCLUDE
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/malloc.h>
#include <sys/mbuf.h>
#include <sys/socket.h>
#include <sys/socketvar.h>
#include <sys/protosw.h>
#include <sys/errno.h>

#include <net/if.h>
#include <net/route.h>

#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/in_pcb.h>
#include <netinet/ip_var.h>
#include <netinet/tcp.h>
#include <netinet/tcp_fsm.h>
#include <netinet/tcp_seq.h>
#include <netinet/tcp_timer.h>
#include <netinet/tcp_var.h>
#include <netinet/tcpip.h>

int	tcp_keepidle = TCPTV_KEEP_IDLE;
int	tcp_keepintvl = TCPTV_KEEPINTVL;
int	tcp_maxidle;
#endif /* TUBA_INCLUDE */
/*
 * Fast timeout routine for processing delayed acks
 */
void
tcp_fasttimo()
{
	register struct inpcb *inp;
	register struct tcpcb *tp;
	int s = splnet();

	inp = tcb.inp_next;
	if (inp)
	for (; inp != &tcb; inp = inp->inp_next)
		if ((tp = (struct tcpcb *)inp->inp_ppcb) &&
		    (tp->t_flags & TF_DELACK)) {
			tp->t_flags &= ~TF_DELACK;
			tp->t_flags |= TF_ACKNOW;
			tcpstat.tcps_delack++;
			(void) tcp_output(tp);
		}
	splx(s);
}

/*
 * Tcp protocol timeout routine called every 500 ms.
 * Updates the timers in all active tcb's and
 * causes finite state machine actions if timers expire.
 */
void
tcp_slowtimo()
{
	register struct inpcb *ip, *ipnxt;
	register struct tcpcb *tp;
	int s = splnet();
	register int i;

	tcp_maxidle = TCPTV_KEEPCNT * tcp_keepintvl;
	/*
	 * Search through tcb's and update active timers.
	 */
	ip = tcb.inp_next;
	if (ip == 0) {
		splx(s);
		return;
	}
	for (; ip != &tcb; ip = ipnxt) {
		ipnxt = ip->inp_next;
		tp = intotcpcb(ip);
		if (tp == 0)
			continue;
		for (i = 0; i < TCPT_NTIMERS; i++) {
			if (tp->t_timer[i] && --tp->t_timer[i] == 0) {
				(void) tcp_usrreq(tp->t_inpcb->inp_socket,
				    PRU_SLOWTIMO, (struct mbuf *)0,
				    (struct mbuf *)i, (struct mbuf *)0);
				if (ipnxt->inp_prev != ip)
					goto tpgone;
			}
		}
		tp->t_idle++;
		if (tp->t_rtt)
			tp->t_rtt++;
tpgone:
		;
	}
	tcp_iss += TCP_ISSINCR/PR_SLOWHZ;		/* increment iss */
#ifdef TCP_COMPAT_42
	if ((int)tcp_iss < 0)
		tcp_iss = 0;				/* XXX */
#endif
	tcp_now++;					/* for timestamps */
	splx(s);
}
#ifndef TUBA_INCLUDE

/*
 * Cancel all timers for TCP tp.
 */
void
tcp_canceltimers(tp)
	struct tcpcb *tp;
{
	register int i;

	for (i = 0; i < TCPT_NTIMERS; i++)
		tp->t_timer[i] = 0;
}

int	tcp_backoff[TCP_MAXRXTSHIFT + 1] =
    { 1, 2, 4, 8, 16, 32, 64, 64, 64, 64, 64, 64, 64 };

/*
 * TCP timer processing.
 */
struct tcpcb *
tcp_timers(tp, timer)
	register struct tcpcb *tp;
	int timer;
{
	register int rexmt;

	switch (timer) {

	/*
	 * 2 MSL timeout in shutdown went off.  If we're closed but
	 * still waiting for peer to close and connection has been idle
	 * too long, or if 2MSL time is up from TIME_WAIT, delete connection
	 * control block.  Otherwise, check again in a bit.
	 */
	case TCPT_2MSL:
		if (tp->t_state != TCPS_TIME_WAIT &&
		    tp->t_idle <= tcp_maxidle)
			tp->t_timer[TCPT_2MSL] = tcp_keepintvl;
		else
			tp = tcp_close(tp);
		break;

	/*
	 * Retransmission timer went off.  Message has not
	 * been acked within retransmit interval.  Back off
	 * to a longer retransmit interval and retransmit one segment.
	 */
	case TCPT_REXMT:
		if (++tp->t_rxtshift > TCP_MAXRXTSHIFT) {
			tp->t_rxtshift = TCP_MAXRXTSHIFT;
			tcpstat.tcps_timeoutdrop++;
			tp = tcp_drop(tp, tp->t_softerror ?
			    tp->t_softerror : ETIMEDOUT);
			break;
		}
		tcpstat.tcps_rexmttimeo++;
		rexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];
		TCPT_RANGESET(tp->t_rxtcur, rexmt,
		    tp->t_rttmin, TCPTV_REXMTMAX);
		tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
		/*
		 * If losing, let the lower level know and try for
		 * a better route.  Also, if we backed off this far,
		 * our srtt estimate is probably bogus.  Clobber it
		 * so we'll take the next rtt measurement as our srtt;
		 * move the current srtt into rttvar to keep the current
		 * retransmit times until then.
		 */
		if (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {
			in_losing(tp->t_inpcb);
			tp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);
			tp->t_srtt = 0;
		}
		tp->snd_nxt = tp->snd_una;
		/*
		 * If timing a segment in this window, stop the timer.
		 */
		tp->t_rtt = 0;
		/*
		 * Close the congestion window down to one segment
		 * (we'll open it by one segment for each ack we get).
		 * Since we probably have a window's worth of unacked
		 * data accumulated, this "slow start" keeps us from
		 * dumping all that data as back-to-back packets (which
		 * might overwhelm an intermediate gateway).
		 *
		 * There are two phases to the opening: Initially we
		 * open by one mss on each ack.  This makes the window
		 * size increase exponentially with time.  If the
		 * window is larger than the path can handle, this
		 * exponential growth results in dropped packet(s)
		 * almost immediately.  To get more time between
		 * drops but still "push" the network to take advantage
		 * of improving conditions, we switch from exponential
		 * to linear window opening at some threshhold size.
		 * For a threshhold, we use half the current window
		 * size, truncated to a multiple of the mss.
		 *
		 * (the minimum cwnd that will give us exponential
		 * growth is 2 mss.  We don't allow the threshhold
		 * to go below this.)
		 */
		{
		u_int win = min(tp->snd_wnd, tp->snd_cwnd) / 2 / tp->t_maxseg;
		if (win < 2)
			win = 2;
		tp->snd_cwnd = tp->t_maxseg;
		tp->snd_ssthresh = win * tp->t_maxseg;
		tp->t_dupacks = 0;
		}
		(void) tcp_output(tp);
		break;

	/*
	 * Persistance timer into zero window.
	 * Force a byte to be output, if possible.
	 */
	case TCPT_PERSIST:
		tcpstat.tcps_persisttimeo++;
		tcp_setpersist(tp);
		tp->t_force = 1;
		(void) tcp_output(tp);
		tp->t_force = 0;
		break;

	/*
	 * Keep-alive timer went off; send something
	 * or drop connection if idle for too long.
	 */
	case TCPT_KEEP:
		tcpstat.tcps_keeptimeo++;
		if (tp->t_state < TCPS_ESTABLISHED)
			goto dropit;
		if (tp->t_inpcb->inp_socket->so_options & SO_KEEPALIVE &&
		    tp->t_state <= TCPS_CLOSE_WAIT) {
		    	if (tp->t_idle >= tcp_keepidle + tcp_maxidle)
				goto dropit;
			/*
			 * Send a packet designed to force a response
			 * if the peer is up and reachable:
			 * either an ACK if the connection is still alive,
			 * or an RST if the peer has closed the connection
			 * due to timeout or reboot.
			 * Using sequence number tp->snd_una-1
			 * causes the transmitted zero-length segment
			 * to lie outside the receive window;
			 * by the protocol spec, this requires the
			 * correspondent TCP to respond.
			 */
			tcpstat.tcps_keepprobe++;
#ifdef TCP_COMPAT_42
			/*
			 * The keepalive packet must have nonzero length
			 * to get a 4.2 host to respond.
			 */
			tcp_respond(tp, tp->t_template, (struct mbuf *)NULL,
			    tp->rcv_nxt - 1, tp->snd_una - 1, 0);
#else
			tcp_respond(tp, tp->t_template, (struct mbuf *)NULL,
			    tp->rcv_nxt, tp->snd_una - 1, 0);
#endif
			tp->t_timer[TCPT_KEEP] = tcp_keepintvl;
		} else
			tp->t_timer[TCPT_KEEP] = tcp_keepidle;
		break;
	dropit:
		tcpstat.tcps_keepdrops++;
		tp = tcp_drop(tp, ETIMEDOUT);
		break;
	}
	return (tp);
}
#endif /* TUBA_INCLUDE */


text:
package main

import (
	"context"
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"strings"
	"time"

	compute "cloud.google.com/go/compute/apiv1"
	"google.golang.org/api/container/v1"
	computepb "google.golang.org/genproto/googleapis/cloud/compute/v1"
	"gopkg.in/yaml.v2"
)

// project_cleanup tool provides support to cleanup different resources insides a GCP project.
// Types of resources to be cleaned up in a single execution of the tool is specified as YAML file
// (run-time parameter flag) to the tool. Each GCP resource is associated with a handler function
// that performs cleanup. Adding a new resource for cleanup involves - adding a helper function to
// ProjectCleaner type and updating the switch condition in the CleanupProject method.

var (
	resourceSpec = flag.String("resource_spec", "", "resource spec yaml file")
)

// ResourceSpec is the top-level spec specifying GCP resources to be cleaned up in a project.
type ResourceSpec struct {
	// ProjectId - GCP Project Id
	ProjectId string `yaml:"project-id"`
	// Resources - Spec for each resource to be cleaned up by the tool.
	Resources []GCPResource `yaml:"resources"`
}

// GCPResource specifies an individual GCP resource to be cleaned up.
type GCPResource struct {
	// Resource - name of the resource is used as key to the handler function.
	Resource string `yaml:"resource"`
	// Zones - Multiple zones support.
	Zones []string `yaml:"zones"`
	// NamePrefixes - Only support for pre-fixed based filtering as go-client doesn't support regex
	// based filtering.
	NamePrefixes []string `yaml:"name-prefixes"`
	// TimeLapseInHours - Number of hours before the resource needs to be cleaned up.
	TimeLapseInHours int `yaml:"time-lapse-hours"`
}

// ProjectCleaner - top level type providing handlers for different GCP resources.
type ProjectCleaner struct {
	ProjectId string
	Resources []GCPResource
}

// GKEClusterHandler provides support to cleanup GCP resources within the project.
func (p *ProjectCleaner) GKEClusterHandler(resource GCPResource) {
	// See https://cloud.google.com/docs/authentication/.
	// Use GOOGLE_APPLICATION_CREDENTIALS environment variable to specify a service account key file
	// to authenticate to the API.
	ctx := context.Background()
	svc, err := container.NewService(ctx)
	if err != nil {
		log.Fatalf("Could not initialize gke client: %v", err)
	}

	elapsedTime := time.Now().Add(time.Hour * (-1) * time.Duration(resource.TimeLapseInHours))
	for _, zone := range resource.Zones {
		log.Printf("Listing gke clusters in zone: %v", zone)
		listResponse, err := svc.Projects.Zones.Clusters.List(p.ProjectId, zone).Do()
		if err != nil {
			log.Printf("Failed listing gke clusters in zone %v: %v", zone, err)
			continue
		}

		if listResponse == nil {
			log.Printf("Encountered nil listResponse gke clusters listing in zone: %v", zone)
			continue
		}

		for _, cluster := range listResponse.Clusters {
			createdTime, err := time.Parse(time.RFC3339, cluster.CreateTime)
			if err != nil {
				log.Printf("Unable to parse created time for cluster: %s. Ignoring cluster",
					cluster.Name)
				continue
			}

			if p.checkForPrefix(cluster.Name, resource.NamePrefixes) && createdTime.Before(elapsedTime) {
				log.Printf("Found cluster: %s for deletion", cluster.Name)
				if op, err := svc.Projects.Zones.Clusters.Delete(p.ProjectId, zone, cluster.Name).Do(); err != nil {
					log.Printf("Encountered error calling delete on cluster: %s Error: %v",
						cluster.Name, err)
				} else {
					log.Printf("Kicked off cluster delete : %v", op.TargetLink)
				}
			}
		}
	}
}

func (p *ProjectCleaner) PersistentDiskHandler(resource GCPResource) {
	// See https://cloud.google.com/docs/authentication/.
	// Use GOOGLE_APPLICATION_CREDENTIALS environment variable to specify a service account key file
	// to authenticate to the API.
	ctx := context.Background()
	c, err := compute.NewDisksRESTClient(ctx)
	if err != nil {
		log.Fatalf("Could not initialize perisistent disk client: %v", err)
	}
	defer c.Close()

	for _, zone := range resource.Zones {
		filter := `(lastDetachTimestamp != "")`
		// maxResults := uint32(5)
		// order := "creationTimestamp desc"
		req := &computepb.ListDisksRequest{
			Project: p.ProjectId,
			Zone:    zone,
			Filter:  &filter,
			// OrderBy:    &order,
			// MaxResults: &maxResults,
		}
		disk_list, listerr := c.List(ctx, req)
		if listerr != nil {
			log.Fatalf("Could not get perisistent disk list: %v, zone: %s", listerr, zone)
		}
		diskmarshal, _ := json.Marshal(disk_list)
		log.Printf("disk_list:%s", string(diskmarshal))
		log.Printf("disk_list size:%d", len(disk_list.GetItems()))

		for _, disk := range disk_list.GetItems() {
			// If the disk is not detached yet, do not delete the persistent disk.
			if len(disk.GetLastDetachTimestamp()) == 0 {
				log.Printf("disk: %s doesn't have last detach time, do not delete.", disk.GetName())
				continue
			}
			log.Printf("disk: %s last detach time: %s", disk.GetName(), disk.GetLastDetachTimestamp())

			// If the disk has users (attached instances) in form: projects/project/zones/zone/instances/instance, do not delete the persistent disk.
			if len(disk.GetUsers()) != 0 {
				log.Printf("disk: %s has users: %s, do not delete.", disk.GetName(), disk.GetUsers())
				continue
			}

			// Do not delete the persistent disk if this is less than specified hours old.
			creationTimestamp := disk.GetCreationTimestamp()
			createdTime, _ := time.Parse(time.RFC3339, creationTimestamp)
			duration := time.Since(createdTime)
			elapsedTime := time.Now().Add(time.Hour * (-1) * time.Duration(resource.TimeLapseInHours))
			if createdTime.After(elapsedTime) {
				log.Printf("disk: %s has been: %v old, do not delete.", disk.GetName(), duration)
				continue
			}
			log.Printf("disk: %s has been: %v old, should be deleted.", disk.GetName(), duration)
			log.Printf("Deleting disk: %s", disk.GetName())

			delete_req := &computepb.DeleteDiskRequest{
				Disk:    disk.GetName(),
				Project: p.ProjectId,
				Zone:    zone,
			}
			_, delete_err := c.Delete(ctx, delete_req)
			if delete_err != nil {
				log.Fatalf("Could not delete perisistent disk: %v", delete_err)
			}
			log.Printf("Deleted disk: %s", disk.GetName())
		}
	}
}

// checkForPrefix - helper function to check if testStr string has any of the prefix specified in
// prefixes
func (p *ProjectCleaner) checkForPrefix(testStr string, prefixes []string) bool {
	log.Printf("Performing prefix check for String: %s for Prefixes: %v", testStr, prefixes)
	for _, prefix := range prefixes {
		if strings.HasPrefix(testStr, prefix) {
			return true
		}
	}
	return false
}

// CleanupProject iterates over each resource specified in the spec and calls the corresponding
// cleanup handler method.
func (p *ProjectCleaner) CleanupProject() {
	for _, resource := range p.Resources {
		switch resource.Resource {
		case "gke-cluster":
			p.GKEClusterHandler(resource)
		case "disk":
			p.PersistentDiskHandler(resource)
		default:
			log.Printf("Un-identified resource: %v found in spec. Ignoring", resource.Resource)
		}
	}
}

func main() {
	flag.Parse()
	log.SetOutput(os.Stdout)

	if *resourceSpec == "" {
		fmt.Fprintln(os.Stderr, "missing resource_spec parameter")
		flag.Usage()
		os.Exit(2)
	}

	if _, err := os.Stat(*resourceSpec); err != nil {
		log.Fatalf("missing resource spec file")
	}

	var r ResourceSpec
	yamlFile, err := ioutil.ReadFile(*resourceSpec)
	if err != nil {
		log.Fatalf("Error reading yaml file")
	}

	err = yaml.Unmarshal(yamlFile, &r)
	if err != nil {
		log.Fatalf("Unmarshal: %v", err)
	}

	p := ProjectCleaner{
		ProjectId: r.ProjectId,
		Resources: r.Resources,
	}
	p.CleanupProject()
}


text:
package ast

import (
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/issue9/version"

	"github.com/caixw/apidoc/v7/internal/locale"
	"github.com/caixw/apidoc/v7/internal/xmlenc"
)

const dateFormat = time.RFC3339

type (
	// Attribute 表示 XML 属性
	Attribute struct {
		xmlenc.BaseAttribute
		Value    xmlenc.String `apidoc:"-"`
		RootName struct{}      `apidoc:"string,meta,usage-string"`
	}

	// NumberAttribute 表示数值类型的属性
	NumberAttribute struct {
		xmlenc.BaseAttribute
		Value    Number   `apidoc:"-"`
		RootName struct{} `apidoc:"number,meta,usage-number"`
	}

	// BoolAttribute 表示布尔值类型的属性
	BoolAttribute struct {
		xmlenc.BaseAttribute
		Value    Bool     `apidoc:"-"`
		RootName struct{} `apidoc:"bool,meta,usage-bool"`
	}

	// VersionAttribute 表示版本号属性
	VersionAttribute struct {
		xmlenc.BaseAttribute
		Value    xmlenc.String `apidoc:"-"`
		RootName struct{}      `apidoc:"version,meta,usage-version"`
	}

	// DateAttribute 日期属性
	DateAttribute struct {
		xmlenc.BaseAttribute
		Value    Date     `apidoc:"-"`
		RootName struct{} `apidoc:"date,meta,usage-date"`
	}

	// MethodAttribute 表示请求方法
	MethodAttribute Attribute

	// StatusAttribute 状态码的 XML 属性
	StatusAttribute NumberAttribute

	// TypeAttribute 表示方法类型属性
	TypeAttribute struct {
		xmlenc.BaseAttribute
		Value    xmlenc.String `apidoc:"-"`
		RootName struct{}      `apidoc:"type,meta,usage-type"`
	}

	// APIDocVersionAttribute 版本号属性,同时对版本号进行比较
	APIDocVersionAttribute Attribute
)

// DecodeXMLAttr AttrDecoder.DecodeXMLAttr
func (a *Attribute) DecodeXMLAttr(p *xmlenc.Parser, attr *xmlenc.Attribute) error {
	a.Value = attr.Value
	return nil
}

// EncodeXMLAttr AttrEncoder.EncodeXMLAttr
func (a *Attribute) EncodeXMLAttr() (string, error) {
	return a.V(), nil
}

// V 返回当前属性实际表示的值
func (a *Attribute) V() string {
	if a == nil {
		return ""
	}
	return a.Value.Value
}

// DecodeXMLAttr AttrDecoder.DecodeXMLAttr
func (num *NumberAttribute) DecodeXMLAttr(p *xmlenc.Parser, attr *xmlenc.Attribute) error {
	if v, err := strconv.Atoi(attr.Value.Value); err == nil {
		num.Value = Number{
			Range: attr.Value.Range,
			Int:   v,
		}
		return nil
	}

	v, err := strconv.ParseFloat(attr.Value.Value, 64)
	if err != nil {
		return attr.Value.WithError(err).WithField(attr.Name.String())
	}
	num.Value = Number{
		Range:   attr.Value.Range,
		Float:   v,
		IsFloat: true,
	}
	return nil
}

// EncodeXMLAttr AttrEncoder.EncodeXMLAttr
func (num *NumberAttribute) EncodeXMLAttr() (string, error) {
	if num.IsFloat() {
		return strconv.FormatFloat(num.FloatValue(), 'f', -1, 64), nil
	}
	return strconv.Itoa(num.IntValue()), nil
}

// IntValue 返回当前属性实际表示的值
func (num *NumberAttribute) IntValue() int {
	if num == nil {
		return 0
	}
	return num.Value.Int
}

// FloatValue 返回当前属性实际表示的值
func (num *NumberAttribute) FloatValue() float64 {
	if num == nil {
		return 0
	}
	return num.Value.Float
}

// IsFloat 当前的数值类型是否为浮点型
func (num *NumberAttribute) IsFloat() bool {
	return num.Value.IsFloat
}

// DecodeXMLAttr AttrDecoder.DecodeXMLAttr
func (b *BoolAttribute) DecodeXMLAttr(p *xmlenc.Parser, attr *xmlenc.Attribute) error {
	v, err := strconv.ParseBool(attr.Value.Value)
	if err != nil {
		return attr.Value.WithError(err).WithField(attr.Name.String())
	}

	b.Value = Bool{
		Range: attr.Value.Range,
		Value: v,
	}
	return nil
}

// EncodeXMLAttr AttrEncoder.EncodeXMLAttr
func (b *BoolAttribute) EncodeXMLAttr() (string, error) {
	return strconv.FormatBool(b.V()), nil
}

// V 返回当前属性实际表示的值
func (b *BoolAttribute) V() bool {
	if b == nil {
		return false
	}
	return b.Value.Value
}

// DecodeXMLAttr AttrDecoder.DecodeXMLAttr
func (a *MethodAttribute) DecodeXMLAttr(p *xmlenc.Parser, attr *xmlenc.Attribute) error {
	a.Value = attr.Value
	a.Value.Value = strings.ToUpper(a.V())
	if !isValidMethod(a.V()) {
		return attr.Value.NewError(locale.ErrInvalidValue).WithField(attr.Name.String())
	}
	return nil
}

// EncodeXMLAttr AttrEncoder.EncodeXMLAttr
func (a *MethodAttribute) EncodeXMLAttr() (string, error) {
	return a.V(), nil
}

// V 返回当前属性实际表示的值
func (a *MethodAttribute) V() string {
	return (*Attribute)(a).V()
}

// DecodeXMLAttr AttrDecoder.DecodeXMLAttr
func (a *StatusAttribute) DecodeXMLAttr(p *xmlenc.Parser, attr *xmlenc.Attribute) error {
	v := NumberAttribute{}
	if err := v.DecodeXMLAttr(p, attr); err != nil {
		return err
	}

	if !isValidStatus(v.Value.Int) {
		return attr.Value.NewError(locale.ErrInvalidValue).WithField(attr.Name.String())
	}

	*a = StatusAttribute(v)
	return nil
}

// EncodeXMLAttr AttrEncoder.EncodeXMLAttr
func (a *StatusAttribute) EncodeXMLAttr() (string, error) {
	return strconv.Itoa(a.V()), nil
}

// V 返回当前属性实际表示的值
func (a *StatusAttribute) V() int {
	return (*NumberAttribute)(a).IntValue()
}

// DecodeXMLAttr AttrDecoder.DecodeXMLAttr
func (a *TypeAttribute) DecodeXMLAttr(p *xmlenc.Parser, attr *xmlenc.Attribute) error {
	a.Value = attr.Value
	if !isValidType(a.V()) {
		return attr.Value.NewError(locale.ErrInvalidValue).WithField(attr.Name.String())
	}
	return nil
}

// EncodeXMLAttr AttrEncoder.EncodeXMLAttr
func (a *TypeAttribute) EncodeXMLAttr() (string, error) {
	return a.V(), nil
}

// V 返回当前属性实际表示的值
func (a *TypeAttribute) V() string {
	if a == nil {
		return ""
	}
	return a.Value.Value
}

// DecodeXMLAttr AttrDecoder.DecodeXMLAttr
func (a *VersionAttribute) DecodeXMLAttr(p *xmlenc.Parser, attr *xmlenc.Attribute) error {
	a.Value = attr.Value
	if !isValidVersion(a.V()) {
		return attr.Value.NewError(locale.ErrInvalidValue).WithField(attr.Name.String())
	}
	return nil
}

// EncodeXMLAttr AttrEncoder.EncodeXMLAttr
func (a *VersionAttribute) EncodeXMLAttr() (string, error) {
	return a.V(), nil
}

// V 返回当前属性实际表示的值
func (a *VersionAttribute) V() string {
	return a.Value.Value
}

// DecodeXMLAttr AttrDecoder.DecodeXMLAttr
func (d *DateAttribute) DecodeXMLAttr(p *xmlenc.Parser, attr *xmlenc.Attribute) error {
	t, err := time.Parse(dateFormat, attr.Value.Value)
	if err != nil {
		return attr.Value.WithError(err).WithField(attr.Name.String())
	}

	d.Value = Date{
		Range: attr.Value.Range,
		Value: t,
	}
	return nil
}

// EncodeXMLAttr AttrEncoder.EncodeXMLAttr
func (d *DateAttribute) EncodeXMLAttr() (string, error) {
	return d.V().Format(dateFormat), nil
}

// V 返回当前属性实际表示的值
func (d *DateAttribute) V() time.Time {
	return d.Value.Value
}

// DecodeXMLAttr AttrDecoder.DecodeXMLAttr
func (a *APIDocVersionAttribute) DecodeXMLAttr(p *xmlenc.Parser, attr *xmlenc.Attribute) error {
	a.Value = attr.Value

	ok, err := version.SemVerCompatible(Version, attr.Value.Value)
	if err != nil {
		return attr.Value.WithError(err).WithField(attr.Name.String())
	}

	if !ok {
		return attr.Value.NewError(locale.ErrInvalidValue).WithField(attr.Name.String())
	}

	return nil
}

// EncodeXMLAttr AttrEncoder.EncodeXMLAttr
func (a *APIDocVersionAttribute) EncodeXMLAttr() (string, error) {
	return a.V(), nil
}

// V 返回当前属性实际表示的值
func (a *APIDocVersionAttribute) V() string {
	return (*Attribute)(a).V()
}

var validMethods = []string{
	http.MethodGet,
	http.MethodPost,
	http.MethodPut,
	http.MethodPatch,
	http.MethodDelete,
	http.MethodHead,
	http.MethodOptions,
}

func isValidMethod(method string) bool {
	for _, m := range validMethods {
		if m == method {
			return true
		}
	}

	return false
}

func isValidStatus(status int) bool {
	return (status >= http.StatusContinue) &&
		(status <= http.StatusNetworkAuthenticationRequired)
}

func isValidType(t string) bool {
	return t == TypeBool ||
		t == TypeObject ||
		t == TypeNumber ||
		t == TypeInt ||
		t == TypeFloat ||
		t == TypeString ||
		t == TypeURL ||
		t == TypeEmail ||
		t == TypeImage ||
		t == TypeDate ||
		t == TypeTime ||
		t == TypeDateTime ||
		t == TypeNone
}

func isValidVersion(v string) bool {
	return version.SemVerValid(v)
}


text:
#ifndef TENSORFLOW_COMPILER_XLA_PYTHON_PJRT_IFRT_PJRT_COMPILER_H_
#define TENSORFLOW_COMPILER_XLA_PYTHON_PJRT_IFRT_PJRT_COMPILER_H_

#include <functional>
#include <memory>
#include <optional>
#include <utility>

#include "llvm/Support/ExtensibleRTTI.h"
#include "tensorflow/compiler/xla/python/ifrt/compiler.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"

namespace xla {
namespace ifrt {

class PjRtClient;

class XlaCompatibleCompiler
    : public llvm::RTTIExtends<XlaCompatibleCompiler, Compiler> {
 public:
  virtual StatusOr<std::unique_ptr<LoadedExecutable>> CompileXla(
      const XlaComputation& computation, CompileOptions options) = 0;

  static char ID;  // NOLINT
};

class PjRtCompiler final
    : public llvm::RTTIExtends<PjRtCompiler, XlaCompatibleCompiler> {
 public:
  explicit PjRtCompiler(PjRtClient* client) : client_(client) {}
  ~PjRtCompiler() override = default;

  StatusOr<std::unique_ptr<LoadedExecutable>> Compile(
      mlir::ModuleOp mlir_module, CompileOptions options) override;
  StatusOr<std::unique_ptr<LoadedExecutable>> CompileXla(
      const XlaComputation& computation, CompileOptions options) override;

  StatusOr<std::unique_ptr<LoadedExecutable>> DeserializeLoadedExecutable(
      absl::string_view serialized, CompileOptions options) override;

  static char ID;  // NOLINT

 private:
  PjRtClient* client_;
};

}  // namespace ifrt
}  // namespace xla

#endif  // TENSORFLOW_COMPILER_XLA_PYTHON_PJRT_IFRT_PJRT_COMPILER_H_


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

'''
This module provides a python-land multithreaded mechanism for executing work.

Basic usage is as follows:
   coordinator = parallel_workers.init_workers(
      my_worker_fun,
      worker_name="train"
   )
   ...
   coordinator.start()

First argument is the function to run in a loop on potentially multiple threads.
It has the call signature
    worker_fun(worker_id)

Argument 'worker_name' is used to distinguish different workers,
such as workers processing train data or workers processing test data.

Optionally, one can define an "init function" that is called once before
threads start, and has call signature:
   my_init_fun(worker_coordinator, global_coordinator)

Note that for data_parallel_models, init_workers will be called
for each GPU. Note that the 'coordinator' returned by the function is same
each time.
'''

import logging
import threading
import atexit
import time
import collections
import six
import traceback

from abc import ABCMeta, abstractmethod

log = logging.getLogger("parallel_workers")
log.setLevel(logging.INFO)
LOG_INT_SECS = 60

def init_workers(
    worker_fun,
    num_worker_threads=2,
    worker_name="train",
    init_fun=None,
    external_loggers=None,
    shutdown_fun=None,
):
    global global_coordinator

    metrics = Metrics(external_loggers)

    # Create coordinator object
    coordinator = WorkerCoordinator(
        worker_name, init_fun, shutdown_fun=shutdown_fun)

    # Launch fetch worker threads
    worker_ids = [
        global_coordinator.get_new_worker_id()
        for i in range(num_worker_threads)
    ]
    workers = [
        threading.Thread(
            target=run_worker,
            name="parallel_workers worker id {}".format(worker_id),
            args=[coordinator,
                  Worker(coordinator, worker_id, worker_fun, metrics)],
        ) for worker_id in worker_ids
    ]

    coordinator._workers = workers
    global_coordinator.add(coordinator)

    return global_coordinator

class Metrics(object):
    def __init__(self, external_loggers):
        self._metrics = collections.defaultdict(lambda: 0)
        self._external_loggers = external_loggers

    def reset_metrics(self):
        self._metrics = collections.defaultdict(lambda: 0)

    def log_metrics(self):
        if not self._external_loggers:
            return
        for logger in self._external_loggers:
            try:
                logger.log(self._metrics)
            except Exception as e:
                print("Failed to call ExternalLogger: {}".format(e))

    def put_metric(self, key, value, count=True):
        self._metrics[key] += value
        if count:
            count_key = '{}_count'.format(key)
            self._metrics[count_key] += 1

class State():
    six.add_metaclass(ABCMeta)

    @abstractmethod
    def start(self):
        pass

    @abstractmethod
    def stop(self):
        pass

    @abstractmethod
    def cleanup(self):
        pass

class WorkerCoordinator(object):
    def __init__(self, worker_name, init_fun, state=None, shutdown_fun=None):
        self._active = True
        self._started = False
        self._workers = []
        self._worker_name = worker_name
        self._init_fun = init_fun
        self._state = state
        self._shutdown_fun = shutdown_fun

    def is_active(self):
        return self._active

    def init(self, global_coordinator):
        if self._init_fun and not self._started:
            data_coordinator = self
            self._init_fun(data_coordinator, global_coordinator)

    def _start(self):
        if self._started:
            return
        self._active = True
        self._started = True
        if self._state:
            self._state.start()

        for w in self._workers:
            w.daemon = True
            w.start()

    def _stop(self, reason=None):
        self._active = False
        if reason is not None:
            log.error("Data input failed due to an error: {}".format(reason))
        if self._shutdown_fun and self._started:
            self._shutdown_fun()
        if self._state:
            self._state.stop()

        self._started = False

    def _wait_finish(self, cleanup=None):
        print("Wait for workers to die: {}".format(self._worker_name))
        for w in self._workers:
            if w != threading.current_thread():
                w.join(5.0)  # don't wait forever, thread may be blocked in i/o
        success = True
        for w in self._workers:
            if w.isAlive():
                print("Worker {} failed to close while waiting".format(w))
                success = False

        # Release memory for the scratch blobs
        if success and self._state:
            self._state.cleanup()

        print("All workers terminated: {}".format(success))
        return success

class GlobalWorkerCoordinator(object):
    def __init__(self):
        self._coordinators = []
        self._fetcher_id_seq = 0
        self._worker_ids = []
        self.register_shutdown_handler()

    def add(self, coordinator):
        self._coordinators.append(coordinator)

    def get_new_worker_id(self):
        worker_id = self._fetcher_id_seq
        self._worker_ids.append(worker_id)
        self._fetcher_id_seq += 1
        return worker_id

    def get_worker_ids(self):
        return self._worker_ids

    def start(self):
        # run init and start in separate for loop to
        # ensure init happens serially before threads are spawn.
        for c in self._coordinators:
            c.init(self)
        for c in self._coordinators:
            c._start()

    def stop(self):
        all_success = True
        for c in self._coordinators:
            c._stop()
        for c in self._coordinators:
            success = c._wait_finish()
            all_success = all_success and success
        self._coordinators = []
        return all_success

    def stop_coordinator(self, worker_name):
        '''
        Stop a specific coordinator
        '''
        for c in self._coordinators:
            if c._worker_name == worker_name:
                c._stop()
                c._wait_finish()
        self._coordinators = [
            c for c in self._coordinators
            if c._worker_name != worker_name
        ]

    def register_shutdown_handler(self):
        def cleanup():
            self.stop()

        atexit.register(cleanup)

class Worker(object):
    def __init__(
        self,
        coordinator,
        worker_id,
        worker_fun=None,
        metrics=None
    ):
        self._coordinator = coordinator
        self._worker_id = worker_id
        self._worker_fun = worker_fun
        self._metrics = metrics

    def start(self):
        self._start_time = time.time()

    def run(self):
        self._worker_fun(self._worker_id)

    def handle_exception(self, e):
        traceback.print_exc()
        logging.exception("Exception in worker", e)
        self._coordinator._stop("Exception in worker {}: {}".format(
            self._worker_id, e
        ))

    def finish(self):
        self._metrics.put_metric(
            'worker_time', time.time() - self._start_time)
        self._metrics.log_metrics()

global_coordinator = GlobalWorkerCoordinator()

def run_worker(coordinator, worker):
    while coordinator.is_active():
        worker.start()
        try:
            worker.run()
        except Exception as e:
            worker.handle_exception(e)
        finally:
            worker.finish()