text:
<?php

namespace Rhubarb\Crown\Exceptions;

class DeploymentException extends RhubarbException
{
    public function __construct($message = "")
    {
        parent::__construct($message);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.opentele.server.dgks.monitoringdataset.version1_0_1.generated;

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

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

 * <complexType name="FaultType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="Code" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="Cause" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="Detail" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="System" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "FaultType", propOrder = {
    "code",
    "cause",
    "detail",
    "system"
})
public class FaultType {

    @XmlElement(name = "Code")
    protected String code;
    @XmlElement(name = "Cause")
    protected String cause;
    @XmlElement(name = "Detail")
    protected String detail;
    @XmlElement(name = "System")
    protected String system;

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

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

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

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

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

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

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

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

}


text:
package models.hbase092

import models.LogFile
import java.util.regex._
import java.util.Date
import models.hbase.LogFileParser

class LogFileParser092 extends LogFileParser {

  val COMPACTION = Pattern.compile(
    """^(.*) INFO (.*)\.CompactionRequest: completed compaction: regionName=(.*\.), storeName=(.*), fileCount=(.*), fileSize=(.*), priority=(.*), time=(.*); duration=(.*)$""",
    Pattern.MULTILINE
  )
  val DATE_GROUP = 1
  val REGION_GROUP = 3
  val DURATION_GROUP = 9

  override def eachCompaction(logFile: LogFile, functionBlock: (String, Date, Long) => Unit) = {
    val m = COMPACTION.matcher(logFile.tail())
    while(m.find()) {
      val date = m.group(DATE_GROUP)
      val region = m.group(REGION_GROUP)
      val duration = m.group(DURATION_GROUP)

      val end = LogFile.dateFormat.parse(date)
      val durationMsec = parseDuration(duration)

      functionBlock(region, end, durationMsec)
    }
  }

}


text:
package com.deleidos.rtws.commons.util;

/**
 * This class is made up of constants used in various mathematical conversions.
 * All class members are accessible via public static final keywords to ensure
 * that their usage in the software generates the highest performing
 * calculations possible based on compiler optimizations.  These constants also
 * ensure a common set of values are used throughout the application.
 *
 * @see java.lang.StrictMath StrictMath
 */
public final class Constant {

	/** Constructor. */
	protected Constant() { }

	/** 1.5 .*/
	private static final double MAGIC_NUMBER_ONE_POINT_FIVE = 1.5;
	/** 1.943846 .*/
	private static final double MAGIC_NUMBER_ONE_TO_NMPH = 1.943846;
	/** 2.0 .*/
	private static final double MAGIC_NUMBER_TWO = 2.0;
	/** 4.0 .*/
	private static final double MAGIC_NUMBER_FOUR = 4.0;
	/** 8.0 .*/
	private static final double MAGIC_NUMBER_EIGHT = 8.0;
	/** 60.0 .*/
	private static final double MAGIC_NUMBER_SIXTY = 60.0;
	/** 180.0 .*/
	private static final double MAGIC_NUMBER_ONE_HUNDRED_EIGHTY = 180.0;
	/** 10800.0 .*/
	private static final double MAGIC_NUMBER_TEN_THOUSAND_EIGHT_HUNDRED = 10800.0;
	/** 20001600.0 .*/
	private static final double MAGIC_NUMBER_TWENTY_MILLION_SIXTEEN_HUNDRED = 20001600.0;

    /** Conversion factor from Hours to Minutes (minutes/hour). */
    public static final double MINUTES_PER_HOUR = 60.0;

    /** Conversion factor from Days to Hours (hours/day). */
    public static final double HOURS_PER_DAY = 24.0;

    /** Conversion factor from Hours to Seconds (seconds/hour). */
    public static final double SECONDS_PER_HOUR = 3600.0;

    /** Conversion factor from Days to Seconds (seconds/day). */
    public static final double SECONDS_PER_DAY = 86400.0;

    /** Closest double to {@link java.lang.StrictMath#PI PI} times 8. */
    public static final double PIx8 = (StrictMath.PI * MAGIC_NUMBER_EIGHT);

    /** Closest double to {@link java.lang.StrictMath#PI PI} times 4. */
    public static final double PIx4 = (StrictMath.PI * MAGIC_NUMBER_FOUR);

    /** Closest double to {@link java.lang.StrictMath#PI PI} times 2. */
    public static final double PIx2 = (StrictMath.PI * MAGIC_NUMBER_TWO);

    /** Closest double to {@link java.lang.StrictMath#PI PI} times 1.5. */
    public static final double PIx3_2 = (StrictMath.PI * MAGIC_NUMBER_ONE_POINT_FIVE);

    /** Closest double to {@link java.lang.StrictMath#PI PI}. */
    public static final double PI = StrictMath.PI;    //  3.141592653589793

    /** Closest double to negative {@link java.lang.StrictMath#PI PI}. */
    public static final double NEGATIVE_PI = -(StrictMath.PI); // -3.141592653589793

    /** Closest double to {@link java.lang.StrictMath#PI PI} divided by 2. */
    public static final double PI_2 = (StrictMath.PI / MAGIC_NUMBER_FOUR);

    /** Closest double to negative {@link java.lang.StrictMath#PI PI} divided
     *  by 2. */
    public static final double NEGATIVE_PI_2 = -(StrictMath.PI / MAGIC_NUMBER_TWO);

    /** Closest double to {@link java.lang.StrictMath#PI PI} divided by 4. */
    public static final double PI_4 = (StrictMath.PI / MAGIC_NUMBER_FOUR);

    /** Closest double to negative {@link java.lang.StrictMath#PI PI} divided by
     *  4. */
    public static final double NEGATIVE_PI_4 = -(StrictMath.PI / MAGIC_NUMBER_FOUR);

    /** Closest double to {@link java.lang.StrictMath#PI PI} divided by 8. */
    public static final double PI_8 = (StrictMath.PI / MAGIC_NUMBER_EIGHT);

    /** Closest double to negative {@link java.lang.StrictMath#PI PI} divided by
     *  8. */
    public static final double NEGATIVE_PI_8 = -(StrictMath.PI / MAGIC_NUMBER_EIGHT);

    /** Closest double to the square root of 2. */
    public static final double SQRT_2 = StrictMath.sqrt(2.0);

    /** Conversion factor from Radians to Degrees (degrees/radian). */
    public static final double DEG_PER_RAD = MAGIC_NUMBER_ONE_HUNDRED_EIGHTY / Constant.PI;

    /** Conversion factor from Degrees to Radians (radians/degree). */
    public static final double RAD_PER_DEG = Constant.PI / MAGIC_NUMBER_ONE_HUNDRED_EIGHTY;

    /** Minimum non-sumberged land elevation on the Earth (meters). */
    public static final double MIN_EARTH_ELEVATION = -1000.0;

    /** Maximum land elevation on the Earth (meters). */
    public static final double MAX_EARTH_ELEVATION = 8850.0; //Mt. Everest, Asia

    /** Minimum submerged land elevation (meters). */
    public static final double BOTTOM_OF_OCEAN = -10924.0; //Pacific Ocean

    /** Mean radius of the earth (meters). */
    public static final double EARTH_RADIUS = 6378137.0;

    /** Mean radius of the earth multiplied by 2 (meters). */
    public static final double EARTH_RADIUSx2 = Constant.EARTH_RADIUS * MAGIC_NUMBER_TWO;

    /** Conversion factor from Nautical Miles to Meters (meters/nautical mile). */
    public static final double METERS_PER_NAUTMILE = 1852.0;

    /** Conversion factor from Meters to Nautical Miles (nautical miles/meter). */
    public static final double NAUTMILES_PER_METER = 1 / METERS_PER_NAUTMILE; //0.00054;

    /** Conversion factor from Meters to Radians (radians/meter). */
    public static final double RADIANS_PER_METER = Constant.PI / MAGIC_NUMBER_TWENTY_MILLION_SIXTEEN_HUNDRED;

    /** Conversion factor from Radians to Meters (meters/radian). */
    public static final double METERS_PER_RADIAN = MAGIC_NUMBER_TWENTY_MILLION_SIXTEEN_HUNDRED / Constant.PI;

    /** Conversion factor from Kilometers to Radians (radians/kilometer). */
    public static final double RADIANS_PER_KILOMETER =
            Constant.RADIANS_PER_METER * Constant.METERS_PER_KILOMETER;

    /** Conversion factor from Nautical Miles to Degrees (degrees/nautical
     *  mile). */
    public static final double DEGREES_PER_NAUTMILE = 1.0 / MAGIC_NUMBER_SIXTY;

    /** Conversion factor from Nautical Miles to Radians (radians/nautical
     *  mile). */
    public static final double RADIANS_PER_NAUTMILE = Constant.PI / MAGIC_NUMBER_TEN_THOUSAND_EIGHT_HUNDRED;

    /** Conversion factor from Nautical Miles to Kilometers
     *  (kilometers/nautical mile). */
    public static final double KILOMETERS_PER_NAUTMILE = 1.852;

    /** Conversion factor from Kilometers to Nautical Miles
     *  (nautical miles/kilometer). */
    public static final double NAUTMILES_PER_KILOMETER = 0.53996;

    /** Conversion factor from Feet to Meters (meters/foot). */
    public static final double METERS_PER_FOOT = 0.3048;

    /** Conversion factor from data mile to feet. */
    public static final double FEET_PER_DATA_MILE = 6000.0;

    /** Conversion factor from Meters to Feet (feet/meter). */
    public static final double FEET_PER_METER = 3.28084;

    /** Conversion factor from Nautical Miles to Feet (feet/nautical mile). */
    public static final double FEET_PER_NAUTMILE = 6076.11549;

    /** Conversion factor from Feet to Nautical Miles (nautical miles/foot). */
    public static final double NAUTMILES_PER_FOOT = 0.00016;

    /** Conversion factor from Feet to Kilometers (kilometers/foot). */
    public static final double KILOMETERS_PER_FOOT = 0.0003;

    /** Conversion factor from Kilometers to Feet (feet/kilometer). */
    public static final double FEET_PER_KILOMETER = 3280.8399;

    /** Conversion factor from Kilometers to Meters (meters/kilometer). */
    public static final double METERS_PER_KILOMETER = 1000.0;

    /** Conversion factor from Meters to Kilometers (kilometers/meter). */
    public static final double KILOMETERS_PER_METER = 0.001;

    /** Conversion factor from Miles to Feet. */
    public static final double FEET_PER_MILE = 5280.0;

    /** Speed of light in a vacuum (meters per second). */
    public static final double LIGHTSPEED = 299792458;

    /** Conversion factor from Meters per Second to Knots
     *  knots/meter per second). */
    public static final double KNOTS_PER_MPS = 1.94385;

    /** Conversion factor from Knots to Meters per Second
     *  (meters per second/knot). */
    public static final double MPS_PER_KNOT = 1 / KNOTS_PER_MPS;
    //public static final double MPS_PER_KNOT = 0.51444;

    /** Conversion factor from Meters per Second to Kilometers per Hour
     *  (kilometer per hour/meter per second). */
    public static final double KPH_PER_MPS = 3.6;

    /** Conversion factor from Kilometers per Hour to Meters per Second
     *  (meters per second/kilometer per hour). */
    //public static final double MPS_PER_KPH = 0.27778;
    public static final double MPS_PER_KPH = 1 / KPH_PER_MPS;

    /** Conversion factor from Knots to Kilometers per Hour
     *  (kilometer per hour/knot). */
    public static final double KPH_PER_KNOT = 1.852;

    /** Conversion factor from Kilometers per Hour to Knots
     *  (knots/kilometer per hour). */
    public static final double KNOTS_PER_KPH = 0.53996;

    /** Conversion factor from Miles per Hour to Kilometers per Hour. */
    public static final double KPH_PER_MPH = 1.609344;

    /** Conversion factor from Date Miles per Hour to Kilometers per Hour. */
    public static final double KPH_PER_DMPH = 1.8288;

    /** Conversion factor from Feet per Second to Meters per Second (meters per
     *  second / foot per second). */
    public static final double MPS_PER_FPS = 0.3048;

    /** Conversion factor from Data Miles per Hour to Meters per Second. */
    public static final double FPS_PER_DATA_MPH = FEET_PER_DATA_MILE / SECONDS_PER_HOUR;

    /** Conversion factor from MPS to DMPH. */
    public static final double DATA_MPH_PER_FPS = 1 / FPS_PER_DATA_MPH;

    /** Conversion factor from Nautical Miles per Hour to Meters per Second
     * (meters per second / nautical miles per hour). */
    public static final double MPS_PER_NMPH = 1.0 / MAGIC_NUMBER_ONE_TO_NMPH;

    /** Conversion factor from Minutes to Seconds (seconds/minute). */
    public static final double SECONDS_PER_MINUTE = 60.0;

    /** Constant definition of Success. */
    public static final boolean SUCCESS = true;

    /** Constant definition of Failure. */
    public static final boolean FAILURE = false;

    /** Closest double to the mathematical constant.
     *  {@link java.lang.StrictMath#E E}*/
    public static final double E = StrictMath.E; // 2.718281828459045

    /** Two doubles differing by less than EPSILON are considered equivalent.*/
    public static final double EPSILON = 0.0000001;

    /** Two angles differing by less than DEG_EPSILON are considered
        equivalent.*/
    public static final double DEG_EPSILON = 0.0000573; // (EPSILON*10)*180/PI
                                     // Don't need as much precision as above
    /** 2 degrees in radians. */
    public static final double TWO_DEG_IN_RAD = MAGIC_NUMBER_TWO * Constant.RAD_PER_DEG;

    /** Integer used for specifying right side.*/
    public static final int RIGHT_SIDE = 1;

    /** Integer used for specifying left side.*/
    public static final int LEFT_SIDE = -1;
}


text:
export * from './headers-extract.service';
export * from './headers-get-cookie.service';


text:
import styled from 'styled-components'

// import Img from '@/Img'
import css, { theme } from '@/utils/css'

export const Wrapper = styled.div`
  ${css.flexColumn()};
  padding: 10px 0;
  background: ${theme('modal.subPanel')};
  min-height: 300px;
  height: auto;
  border-bottom: 3px solid;
  border-color: #00424f;
  transition: all 0.2s;
`

export const Header = styled.div`
  ${css.flexColumn()};
  height: 68px;
  padding: 0 28px;
  padding-bottom: 8px;
  width: 100%;
  color: ${theme('thread.articleDigest')};
  font-size: 16px;
`
export const ReplyToHint = styled.div`
  ${css.flex('align-center')};
  margin-bottom: 6px;
`
export const ReplyToContent = styled.div`
  ${css.lineClamp(1)}
  color: ${theme('thread.articleDigest')};
  font-size: 14px;
`
export const ReplyToAuthor = styled.div`
  color: ${theme('thread.articleTitle')};
  margin-left: 5px;
`
export const EditorWrapper = styled.div`
  overflow-x: hidden;
  padding-top: 10px;
  background: #002a34;
  min-height: 320px;
`
export const FooterWrapper = styled.div`
  width: 100%;
  padding-top: 16px;
`


text:
package main

import (
	"github.com/docker/machine/drivers/amazonec2"
	"github.com/docker/machine/libmachine/drivers/plugin"
)

func main() {
	plugin.RegisterDriver(amazonec2.NewDriver("", ""))
}


text:
<?php

use Phinx\Migration\AbstractMigration;

class AddMoreTxnStatus extends AbstractMigration
{
    public function change()
    {
      $table= $this->table('txn');
      $table
        ->changeColumn('status', 'enum', [
          'values' => [
            'new',
            'filled',
            'paid',
            'processing',
            'waitingforitems',
            'readyforpickup',
            'shipping',
            'shipped',
            'complete',
            'template',
          ],
          'default' => 'new',
          'null' => false,
          'after' => 'number',
        ])
        ->addIndex([ 'status' ])
        ->save();

    }
}


text:
module TurkishBanks
  class BankNotFoundError < StandardError
    def message
      'Banka bulunamadı.'
    end
  end

  BANKS_URL = 'http://eftemkt.tcmb.gov.tr/bankasubelistesi/bankaSubeTumListe.xml'
  DOC = Nokogiri
        .XML(::OpenURI.open_uri(BANKS_URL), nil, 'UTF-8')
        .remove_namespaces!.freeze
  LAST_UPDATE = DOC.at_xpath('//bankaSubeTumListe')['tarih'].freeze

  def self.get_bank_params(bank_name)
    node = DOC.at_xpath("//banka[bAd= '#{bank_name.upcase(:turkic)}']")
    raise BankNotFoundError if node.nil?

    Hash.from_xml(node.to_s)['banka']
  end

  def self.banks
    nodes = DOC.xpath('//banka')
    nodes.each.map { |node| Hash.from_xml(node.to_s)['banka'] }
  end
end


text:
layout: post
title: "Seputar Pertalite Bahan Bakar Minyak Non Subsidi"
image-post : /images/Seputar-Pertalite-BBM-Non-Subsidi.jpg
excerpt: "Tepat hari ini senin 27 Juli 2015 aku mencoba untuk menggunakan BBM baru dari Pertamina yang bernama Pertalite. Seperti yang diberitakan di media masa, bahwasanya Pertalite merupakan bahan bakar minyak yang nantinya akan menggantikan keberadaan Premium. Nah, untuk dua bulan kedepan Pertamina mengadakan uji coba terkait penjualan serta kualitas dari Pertalite."
tags: [andhikamaheva, ngeblog, cerita, tentang saya, andhika maheva wicaksono, programmer indonesia, pertalite, harga pertalite, andhikamaheva.com]
comments: true
image:
  thumb : Seputar-Pertalite-BBM-Non-Subsidi.jpg
  feature:
  credit:
  creditlink:
---

Ilustrasi Penjualan Pertalite

Tepat hari ini senin 27 Juli 2015 aku mencoba untuk menggunakan BBM baru dari Pertamina yang bernama Pertalite. Seperti yang diberitakan di media masa, bahwasanya Pertalite merupakan bahan bakar minyak yang nantinya akan menggantikan keberadaan Premium. Nah, untuk dua bulan kedepan Pertamina mengadakan uji coba terkait penjualan serta kualitas dari Pertalite.

Kebetulan di Jawa Timur terdapat beberapa SPBU yang telah tersedia bahan bakar ini khususnya di daerah Sidoarjo ada sekitar 9 SPBU yang menyediakannya. Beruntung sekali, SPBU di dekat rumahku menyediakan Pertalite. Tidak seperti yang diberitakan sebelumnya bahwa terjadi antrean panjang pada bahan bakar jenis ini. Mungkin karena aku berangkat agak pagian kali ya, jadi antrian biasa - biasa saja. Pertalite memiliki RON antara 90 - 91 jadi hampir mendekati Pertamax 92.

> Nilai oktan sebuah bahan bakar yang paling umum di seluruh dunia adalah nilai Research Octane Number (RON). RON ditentukan dengan mengisi bahan bakar ke dalam mesin uji dengan rasio kompresi variabel dengan kondisi yang teratur. Nilai RON diambil dengan membandingkan campuran antara iso-oktana dan n-heptana. Misalnya, sebuah bahan bakar dengan RON 88 berarti 88% kandungan bahan bakar itu adalah iso-oktana dan 12%-nya n-heptana.
Source by [wikipedia](https://id.wikipedia.org/wiki/Oktan)

Berikut ini table perbandingan Bahan Bakar Minyak (BBM) yang dijual Pertamina :

| Jenis Bahan Bakar | Octan |
|:--------|:-------:|
| Premium   | 88   |
|----
| Pertalite   | 90   |
|----
| Pertamax   | 92   |
|----
| Pertamax Plus   | 95   |
|=====
{: rules="groups"}

## Hitung Biaya Pemakaian

Untuk harganya sendiri, dalam dua bulan ke depan Pertalite dibandrol dengan harga Rp 8.400 / liter. Nggak terlalu mahal juga ya ? Khususnya untuk kantong Mahasiswa. Iseng - iseng, aku coba membandingkan biaya konsumsi bahan bakar selama satu bulan. Oh iya, kendaraan yang aku pakai adalah New Vixion Lightning yang merupakan kendaraan dengan sistem injeksi. Berikut perhitungannya :

Kondisi saat pengisian bensin yaitu pada saat bar penunjuk bahan bakar berkurang satu  bar (sebelumnya dalam keadaan penuh), biasanya terjadi pada Kilometer ke 115 dan melakukan pengisian bensin sebanyak Rp 20.000 dengan kecepatan rata - rata 65 Km / Jam.

Jarak Rumah - Kampus : 20 Km x 2 (pulang pergi) = 40 Km / hari.

Jumlah Hari Efektif (Kuliah) : Senin - Jum'at (5 Hari) x 4 Minggu = 20 Hari efektif dalam sebulan.

Harga Pertalite : Rp 8.400 / liter

Harga Premium : Rp 7.400 / liter

Perhitungan Pertalite dalam Sebulan :

Jumlah Pengisian : 40 Km / Hari x 20 Hari = 800 Km (Jarak Total) / 115 Km (Jumlah Kilometer tiap pengisian) = +- 7 Kali dalam Sebulan

Jumlah Pembelian (liter) : Rp 20.000 / Rp 8.400 = 2.4 liter

Jumlah Km / liter  : 115 Km / 2.4 liter = 47 Km / liter

Jumlah Km selama sebulan : (40 Km x 20 Hari) = 800 Km.

Total Biaya : (Jumlah Km sebulan  / Jumlah Km per liter) x Harga Pertalite = (800 / 47) x Rp 8.400 = Rp 142.800 / Bulan

Perhitungan Premium dalam Sebulan :

Jumlah Pengisian : 40 Km / Hari x 20 Hari = 800 Km (Jarak Total) / 115 Km (Jumlah Kilometer tiap pengisian) = +- 7 Kali dalam Sebulan

Jumlah Pembelian (liter) : Rp 20.000 / Rp 7.400 = 2.7 liter

Jumlah Km / liter  : 115 Km / 2.7 liter = 43 Km / liter

Jumlah Km selama sebulan : (40 Km x 20 Hari) = 800 Km.

Total Biaya : (Jumlah Km sebulan  / Jumlah Km per liter) x Harga Premium = (800 / 43) x Rp 7.400 = Rp 137.640 / Bulan

Jadi setelah dihitung total biaya Pertalite dalam sebulan adalah Rp 142.800 dan Premium adalah Rp 137.640 selisihnya hanya Rp 5.160 loh :D

Itu hanya perhitungan sederhana saja, jadi kalau kamu punya perhitungan lebih rinci mungkin bisa dibagi pada kolom komentar.

Dari informasi yang aku dapat, pertalite ini sangat cocok untuk kendaraan jaman sekarang terutama untuk kendaraan injeksi karena menghasilkan pembakaran yang lebih baik dari pada Premium.

## Kesimpulan

Untuk dua bulan ke depan harga untuk Pertalite adalah Rp 8.400 / liter. Nah untuk bulan berikutnya mungkin harga bisa berubah bisa juga tetap, ini mengikuti perkembangan minyak dunia. Ada juga nih yang ngomong kalau menggunakan bahan bakar dengan RON yang semakin tinggi akan menghasilkan sensasi yang nyaman untuk kendaraan. Menurutku itu tidak dapat dipungkiri, akan tetapi percuma saja kendaraan yang memakai bahan bakar RON tinggi tetapi tidak pernah melakukan perawatan atau service hasilnya ya biasa saja. Tidak hanya itu, mencuci kendaraan bermotor juga tentunya akan menghasilkan kenyamanan saat berkendara. Jadi ada baiknya kendaraan selalu diservice dan dibersihkan tak lain tak bukan agar lebih nyaman dalam penggunaannya.

Yuk, cobain Pertalite itung - itung membiasakan untuk menggunakannya sebelum Premium benar - benar dihapus nantinya dan jangan lupa lakukan perawatan secara berkala untuk kendaraanmu. Semoga bermanfaat!

#### Sumber :

http://www.merdeka.com/otomotif/ini-mobil-dan-motor-yang-cocok-gunakan-pertalite.html

http://otomotif.news.viva.co.id/news/read/594720-cara-mudah-hitung-konsumsi-bahan-bakar-mobil

http://www.harjasaputra.com/opini/iptek/perbandingan-premium-pertamax-pertamax-plus-dan-shell-v-power.html

http://infobandung.co.id/mengenal-lebih-dekat-tentang-pertalite/


text:
<?php namespace Tsi\Lutetium\Updates;

use Schema;
use October\Rain\Database\Updates\Migration;

class BuilderTableCreateTsiLutetiumOrganization extends Migration
{
    public function up()
    {
        Schema::create('tsi_lutetium_organization', function($table)
        {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('name');
            $table->text('description')->nullable();
            $table->timestamp('created_at')->nullable();
            $table->timestamp('updated_at')->nullable();
            $table->text('remark')->nullable();
        });
    }

    public function down()
    {
        Schema::dropIfExists('tsi_lutetium_organization');
    }
}


text:
import os
import psutil
import random
import socket
import subprocess
import sys
import time
import requests
# noinspection PyPackageRequirements
import bs4

def executable(binary='python'):
    candidates = [
        os.path.join(sys.exec_prefix, 'bin', binary),
        os.path.join(sys.exec_prefix, 'local', 'bin', binary),
    ]
    for candidate in candidates:
        if os.path.exists(candidate):
            return candidate
    raise ValueError("Can't find location of {}".format(binary))

def get_free_port():
    # There is a potential for a race condition here, but I think it works ok in practice.
    port_used = True
    while port_used:
        port = random.randrange(4545, 9999)
        port_used = port in [x.laddr[1] for x in psutil.net_connections()]
    # noinspection PyUnboundLocalVariable
    return port

def text_from_html(html):
    soap = bs4.BeautifulSoup(html, 'lxml')
    text = soap.get_text("\n", strip=True)
    return text

def start_servers(gocd_dash_path):
    application_port = get_free_port()
    print("starting server, application on port {}, using checkout {}".format(application_port, gocd_dash_path))

    application_process = start_application(application_port)

    return application_port, application_process

def dump_database(file_name):
    with open(file_name, 'w') as output:
        data = subprocess.check_output(
            ['sqlite3', 'gocddash.sqlite3'],
            input=b'.dump')
        output.write(data.decode('utf-8'))

# noinspection PyUnusedLocal
def do_get(url, data):
    try:
        # noinspection PyUnresolvedReferences
        return subprocess.check_output(["/usr/bin/lynx", "-dump", url], stderr=subprocess.STDOUT).decode('utf-8')
    except subprocess.CalledProcessError as error:
        print(error)
        print(error.output)
        raise

def do_post(url, data):
    response = requests.post(url, data)
    return text_from_html(response.text)

def run_shell_script(script, _):
    # noinspection PyUnresolvedReferences
    return subprocess.check_output([script], stderr=subprocess.STDOUT).decode('utf-8')

def perform_testcase(port):
    action = {
        'GET': do_get,
        'POST': do_post,
        'SHELL': run_shell_script,
    }
    print("Starting test workflow for GO CD Dashboard")
    with open("gui_log.txt", "w", encoding="utf-8") as log:
        with open("actions.txt") as rows:

            coverage_url = "http://127.0.0.1:{}/dash/coverage/".format(port)

            for row in rows:
                if not row.strip():
                    continue
                verb, url, *raw_data = row.split()
                data = dict(pair.split('=') for pair in raw_data)
                url = url.format(port=port)
                log.write("{} {}\ndata: {{{}}}\n".format(verb, url,
                                                         ", ".join("%s='%s'" % tup for tup in sorted(data.items()))))
                out = action[verb](url, data)
                try:
                    log.write(out)
                except TypeError as err:
                    print("Got '{}' on log.write()".format(err))
                    print("What I had:", verb, url, data, type(out))
                    print("What I got back:", out.decode('utf-8'))
                    raise

            requests.get(coverage_url)

def stop_servers(application):
    application.kill()

def main():
    python_version = sys.version_info.major
    if not (3 == python_version):
        print("This code requires Python 3. Instead found version {}. Exiting.".format(python_version))
        sys.exit(-1)
    gocd_dash_path = os.environ['TEXTTEST_CHECKOUT']
    app_port, application = start_servers(gocd_dash_path)
    try:
        sync_pipelines()
        dump_database('db_after_sync')
        perform_testcase(app_port)
        dump_database('db_after_test')
    finally:
        stop_servers(application)

def start_application(application_port):
    application_process = subprocess.Popen([executable(),
                                            executable("gocddash_app.py"),
                                            "-b", str(application_port),
                                            "--file-client", os.getcwd()])

    _wait_for_app_to_start(application_port)
    return application_process

def _wait_for_app_to_start(application_port):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def can_connect():
        try:
            s.connect(('localhost', application_port))
            return True
        except socket.error:
            return False

    i = 0
    while i < 10 and not can_connect():
        time.sleep(.5)
        i += 1
    s.close()
    print("application is started")

def sync_pipelines():
    os.makedirs('/tmp/gocddash-cover/', exist_ok=True)
    subprocess.check_call([executable('coverage'),
                           "run",
                           "--branch",
                           "--parallel-mode",
                           "--source=gocddash",
                           executable("gocddash_sync.py"),
                           "-a", os.getcwd() + "/application.cfg",
                           "-f", os.getcwd()])
    print("pipelines are synced")

if __name__ == "__main__":
    main()


text:
layout: page
title: The Server Couldn't Find What You Were Looking For.
class: errorpage
---


text:
Les icônes augmentent la clarté d'une interface en donnant des repères visuels et en résumant des notions complexes. Pour être efficaces, les icônes doivent être significatives, reconnaissables et comprises rapidement par tout utilisateur. Pour cela, les icônes utilisent des symboles reconnus. Par exemple, la loupe suggère la recherche et la poubelle suggère la suppression.

<modul-do>

Utiliser une icône pour attirer l'attention, sur un message important par exemple.

Utiliser une icône pour résumer une notion complexe comme un panier d'achats.

Utiliser une icône pour donner des repères intuitifs, un crayon pour modifier, une poubelle pour supprimer, etc.

Toujours utiliser la même icône pour représenter une même notion.

</modul-do>

## Caractéristiques

### Choix
La <m-link mode="link" url='/normes/normes-graphiques/iconographie'>librairie d'icônes</m-link> met à votre disposition un ensemble d'icônes communément utilisées dans la conception d'une interface. Dans un même écosytème, une icône devrait être utilisée pour représenter la même notion. Afin d'encourager cette pratique, chaque icône est nommée en fonction de l'action ou la notion qu'elle représente. Par exemple, l'icône de poubelle est nommée Supprimer.

#### Icônes de fichier
Pour illustrer le type d'un fichier, il est recommandé d'utiliser le composant <modul-go name="m-icon-file"></modul-go>, qui associe la bonne icône automatiquement en fonction de l'extension du fichier.

#### Icônes personnalisées
Bien qu'il soit recommandé d'utiliser le plus plus possible les icônes de <m-link mode="link" url='/normes/normes-graphiques/iconographie'>la librairie existante</m-link>, il est possible de créer une nouvelle icône pour un besoin spécifique. La marche à suivre est décrite à la page <m-link mode="link" url='/normes/normes-graphiques/iconographie'>icône personnalisée</m-link>.

### Taille
La taille d'une icône n'est pas normée. Sa valeur par défaut de 18px peut être ajustée en fonction du contexte. Pour des tailles inférieures à 18px, assurez-vous cependant de préserver la lisibilité de l'icône.

### Couleur
La couleur par défaut des icônes est le gris. Lorsqu'elles sont utilisées avec du texte, elles héritent de la couleur de la police de caractères. Par exemple, une icône qui accompagne un lien cliquable sera de la couleur de la police appliquée aux liens. Certaines icônes possèdent couleur propre, comme les icônes de fichiers qui représentent une marque déposée (documents PDF ou Word). Dans ce cas, la couleur originale doit être conservée car elle constitue l'identité de l'icône.

<modul-demo>

```html
<a name="demo-colored-icon"></a>
<m-link class="m-u--margin-top m--is-unvisited" mode="link"  icon="true" icon-name="file-audio" iconPosition="left" icon-size="24px" url="#demo-colored-icon">Balado de la semaine 2</m-link><br/>
<m-link class="m--is-unvisited" mode="link"  icon="true" icon-name="file-pdf" iconPosition="left" icon-size="24px"url="#demo-colored-icon">Règlement des études</m-link><br/>

```
</modul-demo>

### Pastilles
Une pastille est un petit disque de couleur que l'on superpose à une icône pour illustrer un état parmi les suivants :

#### États d'une pastille
* **complété/succès** (cercle vert avec crochet)
* **avertissement** (triangle jaune avec un point d'exclamation)
* **erreur** (cercle rouge avec un point d'exclamation)

<modul-demo>

```html
<m-icon name="m-svg__calendar" v-m-badge="{ state: 'completed'}" size="30px"></m-icon>
<m-icon name="m-svg__calendar" v-m-badge="{ state: 'warning'}" size="30px" class="m-u--margin-left"></m-icon>
<m-icon name="m-svg__calendar" v-m-badge="{ state: 'error'}" size="30px" class="m-u--margin-left"></m-icon>

```

</modul-demo>

Les états suivants sont également prévus, mais pas encore réalisés :

* **publié** (cercle vert)
* **partiellement publié** (cercle orange avec point d'exclamation)
* **non publié** (cercle rouge)
* **nouveauté/nouvel item** (pastille orange avec un chiffre)

#### Positionnement de la pastille
Par défaut, la pastille est positionnée automatiquement à l'emplacement désigné par son concepteur. Si cette position ne convient pas, il est possible de l'ajuster.

<modul-demo>

```html
<h5>Position par défaut</h5>
<m-icon name="m-svg__clock" v-m-badge="{ state: 'completed'}" size="48px"></m-icon>
<h5>Après ajustement</h5>
<m-icon name="m-svg__clock" v-m-badge="{ state: 'completed', offsetX: '-4px', offsetY: '-2px'}" size="48px"></m-icon>

```

</modul-demo>


text:
<?php

namespace ICanBoogie\Mailer\Header;

class ContentType
{
	public $type = 'text/plain';
	public $charset = 'UTF-8';

	static public function from()
	{
		return new static;
	}

	public function __toString()
	{
		return "{$this->type}; charset={$this->charset}";
	}
}


text:
'''
User event notifications endpoints (for Alerts & Alarms Notification process)

'''
__author__ = 'Edna Donoughe'

from flask import (current_app)
from ooiservices.app import db
#from ooiservices.app.decorators import scope_required
#from ooiservices.app.main.authentication import auth
from ooiservices.app.models import (UserEventNotification, User, SystemEvent, SystemEventDefinition, TicketSystemEventLink)
from ooiservices.app.main.errors import bad_request
from ooiservices.app.redmine.routes import (create_redmine_ticket_for_notification, get_redmine_users_by_project,
                                            update_redmine_ticket_for_notification, get_redmine_ticket_for_notification)
import datetime as dt
from sqlalchemy import desc

# todo - discuss scope_required for 'notifications'
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Notification processing - notification of Alerts/Alarms from ooi-ui-notifications service
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Begin notification process for an alert or an alarm
def begin_notification_process(id):
    """
    Initiate the escalation process for an alert or an alarm (id provided)
    Process:
    - Get alert_alarm
    - Get alert_alarm_definition
    - Get user_event_notification information
    * Create initial [red mine] ticket, get ticket id
    - if successful creating ticket, then:
        alert_alarm.escalated =True;
        alert_alarms_escalated = dt.datetime.strftime(dt.datetime.now(), "%Y-%m-%dT%H:%M:%S")
        alert_alarm.ticket_id = ticket_id
        persist escalation field changes with update_alert_alarm
    """
    debug = False
    #log = False
    result = None
    try:
        # Get alert_alarm, alert_alarm_definition and user_event_notification to update redmine ticket
        alert_alarm, alert_alarm_definition, user_event_notification = get_redmine_info_from_alert(id)
        if alert_alarm is None or alert_alarm_definition is None or user_event_notification is None:
            message = 'Failed to retrieve alert, definition or notification for update_notification_ticket. (id: %d)' % id
            current_app.logger.exception('[update_notification_ticket] %s ' % message)
            raise Exception(message)

        # Populate required fields to create a redmine ticket
        project = current_app.config['REDMINE_PROJECT_ID']

        if debug: print '\n \t(debug) ---- Get targeted user for redmine assignment using user_event_notification...'
        # Use user_event_notification for determining assigned user's redmine id
        redmine_id = 1  # this assumes Redmine ADmin is assigned to redmine user id 1; should lookup 'Redmine Admin' todo
        name = None
        assigned_user = User.query.get(user_event_notification.user_id)
        if assigned_user is not None:
            name = assigned_user.first_name + ' ' + assigned_user.last_name
            tmp_id = get_user_redmine_id(project, name)
            if tmp_id is not None:
                redmine_id = tmp_id

        if debug: print '\n \t(debug) -- Creating redmine ticket for \'%s\' (project: %s), get ticket_id...' % \
                        (name, project)

        # Create redmine ticket
        prefix = (alert_alarm.event_type).upper() + ': '
        subject = prefix + alert_alarm.event_response
        description = alert_alarm.event_response
        priority = alert_alarm_definition.severity
        ticket_id = create_redmine_ticket_for_notification(project, subject, description, priority, redmine_id)
        if ticket_id is None:
            message = 'Failed to create_redmine_ticket.'
            print'\n \t-- message: ', message
            current_app.logger.exception('[begin_notification_process] %s ' % message)
            return result

        # If successful creating redmine ticket, update escalate fields
        escalated = True
        ts_escalated = dt.datetime.strftime(dt.datetime.now(), "%Y-%m-%dT%H:%M:%S") # should this be event_time?
        SystemEvent.update_alert_alarm_escalation(id=alert_alarm.id, ticket_id=ticket_id,
                                                  escalated=escalated, ts_escalated=ts_escalated)

        if debug: print '\n \t(debug) -- updated alert_alarm: ', alert_alarm.to_json()
        ticket_link_id = TicketSystemEventLink.insert_ticket_link(system_event_id=alert_alarm.id, ticket_id=ticket_id)
        if debug: print '\n \t(debug) -- [begin_notification_process] \'%s\' has been escalated!' % alert_alarm.event_type
        if debug: print '\n \tbegin_notification_process - ticket_id: ', ticket_id
        result = ticket_id

    except Exception as err:
        current_app.logger.exception('[begin_notification_process] %s ' % err.message)
    finally:
        return result

def get_redmine_info_from_alert(id):
    """ Get information necessary to create or update a redmine ticket.
    """
    alert_alarm = None
    alert_alarm_definition = None
    user_event_notification = None
    #debug = False
    #log = False
    try:
        if id is None:
            raise Exception('No alert id provided (None).')

        # Get alert_alarm
        alert_alarm = SystemEvent.query.get(id)
        if alert_alarm is None:
            message = 'Failed to identify system_event with id: %d' % id
            #if log: print '\n (debug) -- get_redmine_info_from_alert - message: ', message
            current_app.logger.exception('[get_redmine_info_from_alert] %s ' % message)
            raise Exception(message)

        #if debug: print '\n (debug) -- get_redmine_info_from_alert - processing event_type: ', alert_alarm.event_type

        # Get alert_alarm_definition
        alert_alarm_definition = SystemEventDefinition.query.get(alert_alarm.system_event_definition_id)
        if alert_alarm_definition is None:
            message = 'Failed to identify system_event_definition with id: %d' % alert_alarm.system_event_definition_id
            current_app.logger.exception('[get_redmine_info_from_alert] %s ' % message)
            raise Exception(message)

        # Get user_event_notification by filter on alert alarm definition value
        user_event_notification = UserEventNotification.query.filter_by(system_event_definition_id=alert_alarm_definition.id).first()
        if user_event_notification is None:
            message = 'Failed to identify user_event_notification with id: %d' % alert_alarm_definition.id
            current_app.logger.exception('[get_redmine_info_from_alert] %s ' % message)
            raise Exception(message)

    except Exception as err:
        current_app.logger.exception('[get_redmine_info_from_alert] %s ' % err.message)
    finally:
        return alert_alarm, alert_alarm_definition, user_event_notification

def alert_escalation_state(id):
    """ (Alerts only) Determine alert escalation state, return action.

    valid_actions = ['begin_notification_process', 'update_notification_ticket', 'reissue_notification_ticket', None]

    Responds by indicating one of three actions to be taken:
        - if a new ticket is to be created,           ('begin_notification_process') or
        - if an existing ticket needs to be updated   ('update_notification_ticket') or
        - if another new ticket must be issued ticket ('reissue_notification_ticket') or
        - None                                        (pass)
    """
    action = None
    try:
        valid_actions = ['begin_notification_process', 'update_notification_ticket', 'reissue_notification_ticket', None]
        action = determine_action(id)          # actual alert escalation state review to determine action goes here
        '''
        if action not in valid_actions:
            message = 'Invalid action \'%s\' situation, failure to process alert (id:%d) escalation.' % (action, id)
            if log: print '\n (log) [alert_escalation_state] - message: ', message
            current_app.logger.exception('[alert_escalation_state] %s ' % message)
        '''
    except Exception as err:
        message = err.message
        current_app.logger.exception('[alert_escalation_state] %s ' % message)
    finally:
        return action

def determine_action(id):
    """
    For alert id, determine which valid action (or None) is next; return action. If exception, log exception.

    Note on log, debug and verbose (please leave in for now):
        log is used to enable or disable development debug when exceptions are raised, generally written to log file.
        debug is used for development debugging.
        verbose is used specifically in this method for display the list of alerts being reviewed/processed for definition.
    """
    #log = False
    debug = False
    #verbose = False
    action = None
    previous_alert = None
    previously_escalated = False
    try:
        # Get alert
        alert = SystemEvent.query.get(id)
        if alert is None:
            message = 'Failed to retrieve alert record for id provided (id:%d).' % id
            raise Exception(message)

        # Get alert_alarm_definition
        alert_alarm_definition = SystemEventDefinition.query.get(alert.system_event_definition_id)
        if alert_alarm_definition is None:
            message = 'Failed to identify system_event_definition with id: %d' % alert.system_event_definition_id
            current_app.logger.exception('[begin_notification_process] %s ' % message)
            return action

        # Get associated alerts back to when ts_start is not None (ts_start set to timestamp when this alert first arrived).
        alerts = SystemEvent.query.filter_by(system_event_definition_id=alert.system_event_definition_id).order_by(desc(SystemEvent.id)).all()

        # Determine whether additional alerts have arrived since first alert
        found_alerts = False
        if alerts is not None:
            for item in alerts:
                if item.id == alert.id:
                    pass
                else:
                    found_alerts = True

        # If this is the FIRST alert for this definition, set ts_start to current datetime, return None
        if not found_alerts:
            #if debug: print '\n (debug) -- (determine_action) alerts is None, set ts_start!!! \n'
            alert.ts_start = alert.event_time
            try:
                db.session.add(alert)
                db.session.commit()
            except Exception as err:
                # todo review exception handling
                current_app.logger.exception('[determine_action] %s ' % err.message)
            #if debug: print '\n (debug) -- ***** set alert.ts_start: ', alert.to_json()
            return action

        # Not the first alert received for this definition, evaluate this alert to determine whether to escalate.
        # Or if escalated == True, then have we exceeded the escalate boundary (if so, re-issue ticket)
        else:
            # Determine if previously escalated, review previous alert to see if escalated is True. Save previous_alert.
            previously_escalated = False
            inx = 1
            for item in alerts:
                if inx > 1:
                    if item.escalated == True:
                        previously_escalated = True
                        previous_alert = item
                        #if debug: print '\n (debug) -- ***** alert -- previously_escalated !'
                        break
                inx += 1

            # Determine start_alert (ts_start is not None)
            #if debug: print '\n (debug) -- (determine_action) have alerts...get start alert...'
            '''
            inx = 1
            if verbose:
                for item in alerts:
                    print '\n (verbose) alert -- %d: %s' % (inx, item.to_json())
                    inx += 1
            '''
            start_alert = None
            for item in alerts:
                if item.ts_start is not None:
                    start_alert = item
                    break
            #if debug: print '\n (debug) -- Found start_alert: ', start_alert.to_json()
            #if debug: print '\n (debug) -- type(start_alert): ', type(start_alert)

            # Now have initial alert which kicked off (start_alert)
            # Evaluate time delta (event_time) of this alert versus start_alert
            delta = (alert.event_time - start_alert.ts_start).total_seconds()
            #if debug: print '\n (debug) -- delta: ', delta
            #if debug: print '\n (debug) -- alert_alarm_definition.escalate_on: ', alert_alarm_definition.escalate_on

            # if delta is greater than escalate_on value (from definition), has alert been previously escalated?
            if delta <= alert_alarm_definition.escalate_on:
                #if debug: print '\n (debug) -- have not reached escalate on!  Keep going....no ticket yet....'
                pass
            elif delta > alert_alarm_definition.escalate_on:

                # if alert hasn't been previously escalated, begin escalation
                #if debug: print '\n (debug) -- delta > alert_alarm_definition.escalate_on'
                if not previously_escalated: #alert.escalated:
                    #if debug: print '\n (debug) -- not previously_escalated - begin_notification_process', alert.to_json()
                    action = 'begin_notification_process'
                    return action

                else:
                    #if debug: print '\n (debug) -- previously escalated'
                    # if alert previously escalated, determine if we have crossed escalate_boundary.
                    # If escalate boundary is crossed:
                    #     First:
                    #        reset start_alert.ts_start - None
                    #        alert.ts_start - event_time
                    #     Proceed to reissue ticket where:
                    #      escalated True, timestamp None
                    #      update ticket_id to be for new ticket_id created
                    # Carry forward some escalation data from previous alert...
                    try:
                        alert.escalated = previous_alert.escalated
                        alert.ts_escalated = previous_alert.ts_escalated
                        alert.ticket_id = previous_alert.ticket_id
                        db.session.add(alert)
                        db.session.commit()
                    except Exception as err:
                        message = '[determine_action] (Escalate boundary has been crossed) %s ' % err.message
                        current_app.logger.exception(message)
                    # If boundary has not been crossed, update existing ticket
                    if delta <= alert_alarm_definition.escalate_boundary:
                        # Escalate boundary has not been crossed, update existing ticket
                        #if debug: print '\n (debug) -- Escalate boundary has not been crossed, update existing ticket (ticket_id: %d) \n' % alert.ticket_id
                        action = 'update_notification_ticket'
                        return action

                    elif delta > alert_alarm_definition.escalate_boundary:
                        # Escalate boundary has been crossed, issue new ticket 'reissue_notification_ticket'
                        #if debug: print '\n (debug) -- Escalate boundary has been crossed, reissue ticket (current ticket_id: %d) \n' % alert.ticket_id
                        #if debug: print '\n (debug) -- delta > alert_alarm_definition.escalate_boundary'
                        action = 'reissue_notification_ticket'
                        start_alert.ts_start = None
                        try:
                            db.session.add(start_alert)
                            db.session.commit()
                        except Exception as err:
                            # todo review exception handling
                            if debug: print '\n (debug) -- (Escalate boundary has been crossed) (1) exception: ', err.message

                        #if debug: print '\n (debug) -- ***** start_alert.ts_start (should be None): ', start_alert.to_json()

                        alert.ts_start = alert.event_time
                        try:
                            db.session.add(alert)
                            db.session.commit()
                        except Exception as err:
                            # todo review exception handling
                            if debug: print '\n (debug) -- (Escalate boundary has been crossed) (2) exception: ', err.message

                        return action

        return action

    except Exception as err:
        message = err.message
        #if log: print'\n (debug) -- (determine_action) exception: ', err.message
        current_app.logger.exception('[determine_action] %s ' % message)
        return action

def update_notification_ticket(id):
    """ Update redmine ticket as a part of notification process (for alerts only)
    """
    debug = False
    #log = False
    result = None
    try:
        # Get alert, definition and notification to update redmine ticket
        alert, definition, notification = get_redmine_info_from_alert(id)
        if alert is None or definition is None or notification is None:
            message = 'Failed to retrieve alert, definition or notification for update_notification_ticket. (id: %d)' % id
            raise Exception(message)

        # Populate required fields to create a redmine ticket
        project = current_app.config['REDMINE_PROJECT_ID']

        # Use user_event_notification for determining assigned user's redmine id
        redmine_id = 1
        name = None
        assigned_user = User.query.get(notification.user_id)
        if assigned_user is not None:
            name = assigned_user.first_name + ' ' + assigned_user.last_name
            tmp_id = get_user_redmine_id(project, name)
            if tmp_id is not None:
                redmine_id = tmp_id
        else:
            # todo issue - assigned_user is None
            message = "Invalid User ID, User record not found."
            #if log: print '\n message: ', message
            return bad_request(message)

        # Get alert ticket id
        ticket_id = alert.ticket_id

        #if debug: print '\n (debug) update_notification_ticket id: ', ticket_id
        ts_updated = dt.datetime.strftime(dt.datetime.now(), "%Y-%m-%dT%H:%M:%S")
        update_info = '\nUpdated: %s ' % ts_updated

        # Get current redmine ticket
        redmine_ticket = get_redmine_ticket_for_notification(ticket_id)

        # Set fields for update
        project = redmine_ticket['project']
        subject = redmine_ticket['subject']
        description = redmine_ticket['description']
        priority = redmine_ticket['priority']
        if 'assigned_to' in redmine_ticket:
            assigned_id = redmine_ticket['assigned_to']
        else:
            # Use user_event_notification for determining assigned user's redmine id
            redmine_id = 1
            name = None
            assigned_user = User.query.get(notification.user_id)
            if assigned_user is not None:
                name = assigned_user.first_name + ' ' + assigned_user.last_name
                tmp_id = get_user_redmine_id(project, name)
                if tmp_id is not None:
                    redmine_id = tmp_id
            else:
                # todo issue - assigned_user is None
                message = "Invalid User ID, User record not found."
                #if log: print '\n message: ', message
                return bad_request(message)
            assigned_id = redmine_id

        # Update subject for recent receipt of alert (not past escalate boundary yet)
        description += update_info
        result = update_redmine_ticket_for_notification(ticket_id, project, subject, description, priority, assigned_id)
        if result is None:
            message = 'Failed to update redmine ticket (ticket_id: %d' % ticket_id
            raise Exception(message)

        if debug: print '\n \tupdate_notification_ticket - ticket_id: ', ticket_id
        return ticket_id

    except Exception as err:
        message = err.message
        current_app.logger.exception('[update_notification_ticket] %s ' % message)
        return result

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Private Methods for notification service routes
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def get_user_redmine_id(project_name, name):
    """Get the redmine id for the user assigned to this alert.
    The assigned user is defined in the UserEventNotification associated with the alert_alarm definition
    (class SystemEventDefinition).
    """
    redmine_id = None
    try:
        if name is None:
            message = 'User name is None; unable to get redmine id for user assigned to alert or alarm.'
            current_app.logger.exception('[get_user_redmine_id] %s ' % message)
            return redmine_id
        list_redmine_users = get_redmine_users_by_project(project_name)
        if len(list_redmine_users) == 0:
            message = 'No redmine user for this project (%s)' % project_name
            raise Exception(message)
        redmine_users = list_redmine_users['users']
        for user_tuple in redmine_users:
            if str(user_tuple[0]) == name:
                redmine_id = user_tuple[1]
                break
        return redmine_id
    except Exception as err:
        current_app.logger.exception('[get_user_redmine_id] %s ' % err.message)
        return redmine_id

def reissue_notification_ticket(id):
    """ Create another (re-issue) redmine ticket as a part of notification process (for alerts only)
    """
    debug = False   # development debug
    #log = False     # used in except blocks
    result = None
    try:
        if debug: print '\n \t(debug) entered reissue_notification_ticket, id: ', id

        # Get alert, definition and notification to update redmine ticket
        alert, definition, notification = get_redmine_info_from_alert(id)
        if alert is None or definition is None or notification is None:
            message = 'Failed to retrieve alert, definition or notification for update_notification_ticket. (id: %d)' % id
            current_app.logger.exception('[update_notification_ticket] %s ' % message)
            raise Exception(message)

        # Populate required fields to create a redmine ticket
        project = current_app.config['REDMINE_PROJECT_ID']

        if debug:
            print '\n \t(debug) -- Reissue redmine ticket (project: %s), get ticket_id...' % project
            print'\n \t(debug) -- Current ticket id: ', alert.ticket_id

        # Get current redmine ticket
        redmine_ticket = get_redmine_ticket_for_notification(alert.ticket_id)
        if debug: print '\n \t(debug) -- Current redmine ticket: ', redmine_ticket

        # Set assigned id to reflect update to user currently assigned to alert.ticket_id
        #assigned_id = redmine_ticket['assigned_to']
        if 'assigned_to' in redmine_ticket:
            assigned_id = redmine_ticket['assigned_to']
        else:
            # Use user_event_notification for determining assigned user's redmine id
            redmine_id = 1
            name = None
            assigned_user = User.query.get(notification.user_id)
            if assigned_user is not None:
                name = assigned_user.first_name + ' ' + assigned_user.last_name
                tmp_id = get_user_redmine_id(project, name)
                if tmp_id is not None:
                    redmine_id = tmp_id
            else:
                # todo issue - assigned_user is None
                message = "Invalid User ID, User record not found."
                #if log: print '\n message: ', message
                return bad_request(message)
            assigned_id = redmine_id

        # Update description to indicate previously issued ticket id for this alert.
        update_info = '\n* Associated with previously issued ticket: %d' % alert.ticket_id
        if debug: print '\n \t(debug) -- New reissued ticket update_info: ', update_info

        # Create new redmine ticket
        prefix = (alert.event_type).upper() + '*: '
        subject = prefix + alert.event_response
        description = alert.event_response + update_info
        priority = definition.severity
        if debug: print '\n \t(debug) New ticket subject: ', subject
        if debug: print '\n \t(debug) New ticket description: ', description

        ticket_id = create_redmine_ticket_for_notification(project, subject, description, priority, assigned_id)
        if ticket_id is None:
            message = 'Failed to reissue (create another new)_redmine_ticket.'
            current_app.logger.exception('[reissue_notification_ticket] %s ' % message)
            return result

        # update escalate fields if successful creating the redmine ticket
        escalated = True
        ts_escalated = dt.datetime.strftime(dt.datetime.now(), "%Y-%m-%dT%H:%M:%S") # should this be event_time?
        SystemEvent.update_alert_alarm_escalation(id=alert.id, ticket_id=ticket_id,
                                                  escalated=escalated, ts_escalated=ts_escalated)

        if debug: print '\n \t(debug) reissue_notification_ticket -- updated alert_alarm: ', alert.to_json()
        ticket_link_id = TicketSystemEventLink.insert_ticket_link(system_event_id=alert.id, ticket_id=ticket_id)
        if debug: print '\n \t(debug) -- (notifications) ticket_link_id: ', ticket_link_id
        '''
        # debug - view contents of alert_alarm escalation fields; verify changes have been persisted
        escalated_alert_alarm = SystemEvent.query.get(alert_alarm.id)
        print '\n (debug) *** escalated alert_alarm.to_json(): ', escalated_alert_alarm.to_json()
        '''

        result = ticket_id
        if debug: print '\n \treissue_notification_ticket - ticket_id: ', ticket_id

    except Exception as err:
        message = err.message
        current_app.logger.exception('[reissue_notification_ticket] %s ' % message)
    finally:
        return result


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.08.30 at 10:54:58 오전 KST
//

package com.athena.chameleon.engine.entity.xml.ejbjar.v2_1;

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

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

/**
 *
 *
 * 	The relationship-role-sourceType designates the source of a
 * 	role that participates in a relationship. A
 * 	relationship-role-sourceType is used by
 * 	relationship-role-source elements to uniquely identify an
 * 	entity bean.
 *
 *
 *
 *
Java class for relationship-role-sourceType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="relationship-role-sourceType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="description" type="{http://java.sun.com/xml/ns/j2ee}descriptionType" maxOccurs="unbounded" minOccurs="0"/>
 *         <element name="ejb-name" type="{http://java.sun.com/xml/ns/j2ee}ejb-nameType"/>
 *       </sequence>
 *       <attribute name="id" type="{http://www.w3.org/2001/XMLSchema}ID" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "relationship-role-sourceType", propOrder = {
    "description",
    "ejbName"
})
public class RelationshipRoleSourceType {

    protected List<DescriptionType> description;
    @XmlElement(name = "ejb-name", required = true)
    protected EjbNameType ejbName;
    @XmlAttribute(name = "id")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlID
    @XmlSchemaType(name = "ID")
    protected java.lang.String id;

    /**
     * Gets the value of the description property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the description property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getDescription().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link DescriptionType }
     *
     *
     */
    public List<DescriptionType> getDescription() {
        if (description == null) {
            description = new ArrayList<DescriptionType>();
        }
        return this.description;
    }

    /**
     * Gets the value of the ejbName property.
     *
     * @return
     *     possible object is
     *     {@link EjbNameType }
     *
     */
    public EjbNameType getEjbName() {
        return ejbName;
    }

    /**
     * Sets the value of the ejbName property.
     *
     * @param value
     *     allowed object is
     *     {@link EjbNameType }
     *
     */
    public void setEjbName(EjbNameType value) {
        this.ejbName = value;
    }

    /**
     * Gets the value of the id property.
     *
     * @return
     *     possible object is
     *     {@link java.lang.String }
     *
     */
    public java.lang.String getId() {
        return id;
    }

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

}


text:
namespace Cocos2D
{
    internal class CCSpriteLoader : CCNodeLoader
    {
        private const string PROPERTY_FLIP = "flip";
        private const string PROPERTY_DISPLAYFRAME = "displayFrame";
        private const string PROPERTY_COLOR = "color";
        private const string PROPERTY_OPACITY = "opacity";
        private const string PROPERTY_BLENDFUNC = "blendFunc";

        public override CCNode CreateCCNode()
        {
            return new CCSprite();
        }

        protected override void OnHandlePropTypeSpriteFrame(CCNode node, CCNode parent, string propertyName, CCSpriteFrame spriteFrame,
                                                            CCBReader reader)
        {
            if (propertyName == PROPERTY_DISPLAYFRAME)
            {
                if (spriteFrame != null)
                {
                    ((CCSprite) node).DisplayFrame = spriteFrame;
                }
                else
                {
                    CCLog.Log("ERROR: SpriteFrame NULL");
                }
            }
            else
            {
                base.OnHandlePropTypeSpriteFrame(node, parent, propertyName, spriteFrame, reader);
            }
        }

        protected override void OnHandlePropTypeFlip(CCNode node, CCNode parent, string propertyName, bool[] pFlip, CCBReader reader)
        {
            if (propertyName == PROPERTY_FLIP)
            {
                ((CCSprite) node).FlipX = pFlip[0];
                ((CCSprite) node).FlipY = pFlip[1];
            }
            else
            {
                base.OnHandlePropTypeFlip(node, parent, propertyName, pFlip, reader);
            }
        }

        protected override void OnHandlePropTypeColor3(CCNode node, CCNode parent, string propertyName, CCColor3B color, CCBReader reader)
        {
            if (propertyName == PROPERTY_COLOR)
            {
                ((CCSprite) node).Color = color;
            }
            else
            {
                base.OnHandlePropTypeColor3(node, parent, propertyName, color, reader);
            }
        }

        protected override void OnHandlePropTypeByte(CCNode node, CCNode parent, string propertyName, byte pByte, CCBReader reader)
        {
            if (propertyName == PROPERTY_OPACITY)
            {
                ((CCSprite) node).Opacity = pByte;
            }
            else
            {
                base.OnHandlePropTypeByte(node, parent, propertyName, pByte, reader);
            }
        }

        protected override void OnHandlePropTypeBlendFunc(CCNode node, CCNode parent, string propertyName, CCBlendFunc blendFunc,
                                                          CCBReader reader)
        {
            if (propertyName == PROPERTY_BLENDFUNC)
            {
                ((CCSprite) node).BlendFunc = blendFunc;
            }
            else
            {
                base.OnHandlePropTypeBlendFunc(node, parent, propertyName, blendFunc, reader);
            }
        }
    }
}


text:
require File.join(File.dirname(__FILE__), 'spec_helper')

describe String do
  deprec_specify "#camelize and #camelcase should transform the word to CamelCase" do
    "egg_and_hams".camelize.should == "EggAndHams"
    "egg_and_hams".camelize(false).should == "eggAndHams"
    "post".camelize.should == "Post"
    "post".camelcase.should == "Post"
  end

  deprec_specify "#constantize should eval the string to get a constant" do
    "String".constantize.should == String
    "String::Inflections".constantize.should == String::Inflections
    proc{"BKSDDF".constantize}.should raise_error
    proc{"++A++".constantize}.should raise_error
  end

  deprec_specify "#dasherize should transform underscores to dashes" do
    "egg_and_hams".dasherize.should == "egg-and-hams"
    "post".dasherize.should == "post"
  end

  deprec_specify "#demodulize should remove any preceding modules" do
    "String::Inflections::Blah".demodulize.should == "Blah"
    "String::Inflections".demodulize.should == "Inflections"
    "String".demodulize.should == "String"
  end

  deprec_specify "#humanize should remove _i, transform underscore to spaces, and capitalize" do
    "egg_and_hams".humanize.should == "Egg and hams"
    "post".humanize.should == "Post"
    "post_id".humanize.should == "Post"
  end

  deprec_specify "#titleize and #titlecase should underscore, humanize, and capitalize all words" do
    "egg-and: hams".titleize.should == "Egg And: Hams"
    "post".titleize.should == "Post"
    "post".titlecase.should == "Post"
  end

  deprec_specify "#underscore should add underscores between CamelCased words, change :: to / and - to _, and downcase" do
    "EggAndHams".underscore.should == "egg_and_hams"
    "EGGAndHams".underscore.should == "egg_and_hams"
    "Egg::And::Hams".underscore.should == "egg/and/hams"
    "post".underscore.should == "post"
    "post-id".underscore.should == "post_id"
  end

  deprec_specify "#pluralize should transform words from singular to plural" do
    "post".pluralize.should == "posts"
    "octopus".pluralize.should =="octopi"
    "the blue mailman".pluralize.should == "the blue mailmen"
    "CamelOctopus".pluralize.should == "CamelOctopi"
  end

  deprec_specify "#singularize should transform words from plural to singular" do
    "posts".singularize.should == "post"
    "octopi".singularize.should == "octopus"
    "the blue mailmen".singularize.should == "the blue mailman"
    "CamelOctopi".singularize.should == "CamelOctopus"
  end

  deprec_specify "#tableize should transform class names to table names" do
    "RawScaledScorer".tableize.should == "raw_scaled_scorers"
    "egg_and_ham".tableize.should == "egg_and_hams"
    "fancyCategory".tableize.should == "fancy_categories"
  end

  deprec_specify "#classify should tranform table names to class names" do
    "egg_and_hams".classify.should == "EggAndHam"
    "post".classify.should == "Post"
  end

  deprec_specify "#foreign_key should create a foreign key name from a class name" do
    "Message".foreign_key.should == "message_id"
    "Message".foreign_key(false).should == "messageid"
    "Admin::Post".foreign_key.should == "post_id"
  end
end

describe String::Inflections do
  before do
    deprec do
      @plurals, @singulars, @uncountables = String.inflections.plurals.dup, String.inflections.singulars.dup, String.inflections.uncountables.dup
    end
  end
  after do
    deprec do
      String.inflections.plurals.replace(@plurals)
      String.inflections.singulars.replace(@singulars)
      String.inflections.uncountables.replace(@uncountables)
      Sequel.inflections.plurals.replace(@plurals)
      Sequel.inflections.singulars.replace(@singulars)
      Sequel.inflections.uncountables.replace(@uncountables)
    end
  end

  deprec_specify "should be possible to clear the list of singulars, plurals, and uncountables" do
    String.inflections.clear(:plurals)
    String.inflections.plurals.should == []
    String.inflections.plural('blah', 'blahs')
    String.inflections.clear
    String.inflections.plurals.should == []
    String.inflections.singulars.should == []
    String.inflections.uncountables.should == []
  end

  deprec_specify "should be able to specify new inflection rules" do
    String.inflections do |i|
      i.plural(/xx$/i, 'xxx')
      i.singular(/ttt$/i, 'tt')
      i.irregular('yy', 'yyy')
      i.uncountable(%w'zz')
    end
    'roxx'.pluralize.should == 'roxxx'
    'rottt'.singularize.should == 'rott'
    'yy'.pluralize.should == 'yyy'
    'yyy'.singularize.should == 'yy'
    'zz'.pluralize.should == 'zz'
    'zz'.singularize.should == 'zz'
  end

  deprec_specify "should be yielded and returned by String.inflections" do
    String.inflections{|i| i.should == String::Inflections}.should == String::Inflections
  end
end


text:
class MigrateDataToGeolocation < ActiveRecord::Migration
  def self.up

    #move places into new Geolocation table
    StashDatacite::GeolocationPlace.where('resource_id IS NOT NULL').each do |place|
      point = nil
      if place.latitude && place.longitude
        point = StashDatacite::GeolocationPoint.create(latitude: place.latitude, longitude: place.longitude)
      end
      StashDatacite::Geolocation.create(resource_id: place.resource_id, place_id: place.id, point_id: point.try(:id))
    end

    # move points into Geolocation table
    StashDatacite::GeolocationPoint.where('resource_id IS NOT NULL').each do |point|
      StashDatacite::Geolocation.create(resource_id: point.resource_id, point_id: point.id)
    end

    #move boxes into Geolocation table
    StashDatacite::GeolocationBox.where('resource_id IS NOT NULL').each do |box|
      StashDatacite::Geolocation.create(resource_id: box.resource_id, box_id: box.id)
    end

    remove_column :dcs_geo_location_places, :resource_id
    remove_column :dcs_geo_location_places, :latitude
    remove_column :dcs_geo_location_places, :longitude
    remove_column :dcs_geo_location_points, :resource_id
    remove_column :dcs_geo_location_boxes, :resource_id

  end
  def self.down
    raise ActiveRecord::IrreversibleMigration
  end
end


text:
package microsoft.exchange.webservices.data.property.complex;

import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.internal.matchers.NotNull.NOT_NULL;

import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.enumeration.misc.error.ServiceError;
import microsoft.exchange.webservices.data.core.exception.service.remote.ServiceResponseException;
import microsoft.exchange.webservices.data.core.service.item.Item;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Test class for the FileAttachment methods that were added to support streaming of large
 * FileAttachments at the XML response level so that we don't throw an OutOfMemoryError.
 */
public class FileAttachmentTest {

  @Test
  public void testParseResponse() throws Exception {
    verifyRepeatingResponse("Empty0", "".getBytes("UTF-8"), 0);
    verifyRepeatingResponse("Tiny1", "Tiny".getBytes("UTF-8"), 1);
    verifyRepeatingResponse("NineChars2", "NineChars".getBytes("UTF-8"), 2);
    verifyRepeatingResponse("NineChars10", "NineChars".getBytes("UTF-8"), 10);
    verifyRepeatingResponse("NineChars128k", "NineChars".getBytes("UTF-8"), 128 * 1024);
  }

  @Test
  public void testParseResponseBinary() throws Exception {
    verifyBinaryContent("Image1", ".jpg");
  }

  @Test
  public void testBadResponse() throws Exception {
    String xmlFilename = this.getClass().getSimpleName() + "BadResponseMissingContent.xml";
    InputStream is = ClassLoader.getSystemResourceAsStream(xmlFilename);
    try {
      // passing null for the OutputStream argument to prove that it will never get to it.

      FileAttachment.writeContentFromResponseFile(is, null);
      throw new RuntimeException("Should have thrown an exception when no Content element was found");
    } catch (IOException ex) {
      if (!ex.getMessage().contains("never found pattern")) {
        throw new RuntimeException("unexpected Exception", ex);
      }
    } finally {
      is.close();
    }
  }

  @Test
  public void testErrorResponse() throws Exception {
    final String xmlFilename = this.getClass().getSimpleName() + "ErrorResponse.xml";

    Item parent = mock(Item.class);
    ExchangeService exchangeService = mock(ExchangeService.class);
    FileAttachment fileAttachment = new FileAttachment(parent, false);

    when(parent.getService()).thenReturn(exchangeService);
    when(exchangeService.getRequestedServerVersion()).thenReturn(ExchangeVersion.Exchange2010_SP1);
    doAnswer(new Answer() {
      @Override
      public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
        // Read test test xml file into the responseFile OutputStream.
        OutputStream os = (OutputStream)invocationOnMock.getArguments()[1];
        InputStream is = null;
        try {
          is = ClassLoader.getSystemResourceAsStream(xmlFilename);
          byte[] buffer = new byte[is.available()];
          // Read test file into buffer
          is.read(buffer);
          // Dump buffer into OutputStream
          os.write(buffer);
        } finally {
          if (is != null) {
            is.close();
          }
        }
        return null;
      }
    }).when(exchangeService).streamAttachment(eq(fileAttachment), any(OutputStream.class));

    try {
      fileAttachment.streamContent(new ByteArrayOutputStream());
      fail("ServiceResponseException expected.");
    } catch (ServiceResponseException e) {
      assertThat(e, NOT_NULL);
      assertThat(e.getMessage(), equalTo("The attachment could not be opened."));
      assertThat(e.getErrorCode(), equalTo(ServiceError.ErrorCannotOpenFileAttachment));
    }
  }

  void verifyRepeatingResponse(String name, byte[] pattern, int repeated) throws Exception {

    String filename = this.getClass().getSimpleName() + name + ".xml";
    File content = File.createTempFile("content", ".tmp");
    OutputStream os = new BufferedOutputStream(new FileOutputStream(content));
    try {
      System.out.println(String.format("filename [%s], repeated [%s], content [%s]",
          filename, repeated, content.getAbsolutePath()));
      FileAttachment.writeContentFromResponseFile(ClassLoader.getSystemResourceAsStream(filename), os);
      content.deleteOnExit();
    } finally {
      os.close();
    }

    if (pattern.length == 0) {
      if (content.length() != 0) {
        throw new RuntimeException("Expected empty content file");
      }
      return;
    }
    // Now use an InputStream to read 'content' and verify we read the pattern the correct number of times.
    int byteCount;
    int readCount = 0;
    byte[] buffer = new byte[pattern.length];
    InputStream is = new BufferedInputStream(new FileInputStream(content));
    try {
      while (-1 != (byteCount = is.read(buffer))) {
        if (byteCount != buffer.length) {
          throw new RuntimeException(String.format(
              "expected to read %s bytes, actual %s bytes after %s reads",
              buffer.length, byteCount, readCount));
        }
        readCount++;
        if (readCount > repeated) {
          throw new RuntimeException(String.format(
              "pattern.length=%s, readCount=%s, should have been done after %s",
              pattern.length, readCount, repeated));
        }
        for (int i = 0; i < buffer.length; i++) {
          if (buffer[i] != pattern[i]) {
            throw new RuntimeException(String.format(
                "pattern.length=%s, after %s repeats, index %s mismatch: expected [%s], got [%s]",
                pattern.length, readCount, i, pattern[i], buffer[i]));
          }
        }
      }
      if (readCount != repeated) {
        throw new RuntimeException(String.format(
            "expected to read %s times, read %s times",
            repeated, readCount));
      }
    } finally {
      is.close();
    }
    content.delete();
  }

  void verifyBinaryContent(String name, String suffix) throws Exception {
    String xmlFilename = this.getClass().getSimpleName() + name + ".xml";
    File content = File.createTempFile("content", ".tmp");
    OutputStream os = new BufferedOutputStream(new FileOutputStream(content));
    try {
      System.out.println(String.format("filename [%s], content [%s]",
          xmlFilename, content.getAbsolutePath()));
      FileAttachment.writeContentFromResponseFile(ClassLoader.getSystemResourceAsStream(xmlFilename), os);
      content.deleteOnExit();
    } finally {
      os.close();
    }

    // Now an "expected" and "actual" InputStream to verify the content file.
    String expectedFilename = this.getClass().getSimpleName() + name + suffix;
    InputStream isExpected = ClassLoader.getSystemResourceAsStream(expectedFilename);
    InputStream isActual = new FileInputStream(content);
    try {
      long total = 0;
      int bExpected;
      int bActual;
      do {
        bExpected = isExpected.read();
        bActual = isActual.read();
        if (bExpected != bActual) {
          throw new RuntimeException(String.format("total=%s, bExpected=%s, bActual=%s",
              total, bExpected, bActual));
        }
      } while (bExpected != -1);
    } finally {
      isExpected.close();
      isActual.close();
    }
    content.delete();
  }

}


text:
require 'spec_helper'

describe PresetSerializer do
  let(:preset) { Preset.new }
  let(:serializer) { PresetSerializer.new(preset) }

  describe '#as_json' do
    let(:subject) { serializer.as_json[:preset] }
    its([:name]) { should == preset.name }
    its([:id]) { should == preset.id }
  end

end


text:
using System;
using System.Collections.Generic;

namespace Otter {
    /// <summary>
    /// A base class for Movement Components to extend.
    /// </summary>
    public abstract class Movement : Component {

        #region Private Fields

        protected int
            MoveBufferX = 0,
            MoveBufferY = 0;

        #endregion

        #region Public Fields

        /// <summary>
        /// An action triggered after movement as been applied. Up to subclasses to implement.
        /// </summary>
        public Action OnMove;

        /// <summary>
        /// Determines how many units represent 1 pixel. Default is 100. Example: A speed of 100 would
        /// move the object 1 pixel per update.
        /// </summary>
        public int SpeedScale = 100;

        /// <summary>
        /// The main Collider to use for detecting collisions. If this is not set, no collisions will
        /// register at all!
        /// </summary>
        public Collider Collider;

        /// <summary>
        /// An action triggered when there is a collision in the X axis.
        /// </summary>
        public Action OnCollideX;

        /// <summary>
        /// An action triggered when there is a collision in the Y axis.
        /// </summary>
        public Action OnCollideY;

        #endregion

        #region Public Properties

        /// <summary>
        /// The list of types that the Collider should check for collisions for when moving.
        /// </summary>
        public List<int> CollisionsSolid { get; private set; }

        #endregion

        #region Constructors

        public Movement() {
            CollisionsSolid = new List<int>();
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Register a tag that the Collider should check for collisions with.
        /// </summary>
        /// <param name="tags">The tags to collide with.</param>
        public void AddCollision(params int[] tags) {
            foreach (var t in tags) {
                CollisionsSolid.Add(t);
            }
        }

        /// <summary>
        /// Register a tag that the Collider should check for collisions with.
        /// </summary>
        /// <param name="tags">The tags to collide with.</param>
        public void AddCollision(params Enum[] tags) {
            AddCollision(Util.EnumToIntArray(tags));
        }

        /// <summary>
        /// Remove a tag from the collision checking.
        /// </summary>
        /// <param name="tags"></param>
        public void RemoveCollision(params int[] tags) {
            foreach (int t in tags) {
                if (CollisionsSolid.Contains(t)) {
                    CollisionsSolid.Remove(t);
                }
            }
        }

        /// <summary>
        /// Move the object in the X axis by the value of speed. Sweeping collision test.
        /// </summary>
        /// <param name="speed">The speed to move by (remember SpeedScale is applied.)</param>
        /// <param name="collider">The Collider to use when moving.</param>
        public virtual void MoveX(int speed, Collider collider = null) {
            MoveBufferX += speed;

            while (Math.Abs(MoveBufferX) >= SpeedScale) {
                int move = Math.Sign(MoveBufferX);
                if (collider != null) {
                    Collider c = collider.Collide(Entity.X + move, Entity.Y, CollisionsSolid);
                    if (c == null) {
                        Entity.X += move;
                        MoveBufferX = (int)Util.Approach(MoveBufferX, 0, SpeedScale);
                    }
                    else {
                        MoveBufferX = 0;
                        MoveCollideX(c);
                    }
                }
                if (collider == null || CollisionsSolid.Count == 0) {
                    Entity.X += move;
                    MoveBufferX = (int)Util.Approach(MoveBufferX, 0, SpeedScale);
                }

            }
        }

        /// <summary>
        /// Move the object in the Y axis by the value of speed. Sweeping collision test.
        /// </summary>
        /// <param name="speed">The speed to move by (remember SpeedScale is applied.)</param>
        /// <param name="collider">The Collider to use when moving.</param>
        public virtual void MoveY(int speed, Collider collider = null) {
            MoveBufferY += speed;

            while (Math.Abs(MoveBufferY) >= SpeedScale) {
                int move = Math.Sign(MoveBufferY);
                if (collider != null) {
                    Collider c = collider.Collide(Entity.X, Entity.Y + move, CollisionsSolid);
                    if (c == null) {
                        Entity.Y += move;
                        MoveBufferY = (int)Util.Approach(MoveBufferY, 0, SpeedScale);
                    }
                    else {
                        MoveBufferY = 0;
                        MoveCollideY(c);
                    }
                }
                if (collider == null || CollisionsSolid.Count == 0) {
                    Entity.Y += move;
                    MoveBufferY = (int)Util.Approach(MoveBufferY, 0, SpeedScale);
                }
            }
        }

        /// <summary>
        /// Called when MoveX collides with a collider.
        /// </summary>
        /// <param name="collider">The collider that was hit.</param>
        public virtual void MoveCollideX(Collider collider) {
            if (OnCollideX != null) {
                OnCollideX();
            }
        }

        /// <summary>
        /// Called when MoveY collides with a collider.
        /// </summary>
        /// <param name="collider">The collider that was hit.</param>
        public virtual void MoveCollideY(Collider collider) {
            if (OnCollideY != null) {
                OnCollideY();
            }
        }

        /// <summary>
        /// Shortcut to call both move x and move y.
        /// </summary>
        /// <param name="speedX"></param>
        /// <param name="speedY"></param>
        /// <param name="collider"></param>
        public void MoveXY(int speedX, int speedY, Collider collider = null) {
            MoveX(speedX, collider);
            MoveY(speedY, collider);
        }

        #endregion
    }
}


text:
.dashboard .container {
	width: 2000px;
}

.package .about .name {
	font-size: 18px;
}

.package .badges {
	position: relative;
	list-style-type: none;
}

.package .package-badge {
	float: left;
	margin-right: 10px;
}


text:
package com.novoda.downloadmanager.demo.extended;

import android.app.Application;
import android.hardware.SensorManager;

import com.novoda.downloadmanager.Download;
import com.novoda.downloadmanager.lib.DownloadClientReadyChecker;

public class DemoApplication extends Application implements DownloadClientReadyChecker {

    private OneRuleToBindThem oneRuleToBindThem;

    @Override
    public void onCreate() {
        super.onCreate();
        oneRuleToBindThem = new OneRuleToBindThem();
    }

    @Override
    public boolean isAllowedToDownload(Download download) {
        // Here you would add any reasons you may not want to download
        // For instance if you have some type of geo-location lock on your download capability
        return oneRuleToBindThem.shouldWeDownload(download);
    }

    private static final class OneRuleToBindThem {

        /**
         * @return for our demo we expect always to return true ... unless you want to conquer the galaxy
         */
        public boolean shouldWeDownload(Download download) {
            return download.getTotalSize() > SensorManager.GRAVITY_DEATH_STAR_I;
        }
    }
}


text:
<?php
// set the models directory if needed
$modelsdir = '/var/www/yvytu/models';
$title = $_GET['q'];

$tmpfname = tempnam("/tmp", "yvy.");
$handle = fopen($tmpfname, "w");
fwrite($handle, "$title\n");
fclose($handle);

// use base2 or base 3
$predicted =`cat $tmpfname | /usr/bin/dbacl -v -c $modelsdir/granizo -c $modelsdir/base1`;

if($predicted == "granizo\n"){
  echo $predicted;
}

unlink($tmpfname);


text:
package com.intellij.openapi.externalSystem.settings;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.util.containers.ContainerUtilRt;
import com.intellij.util.messages.Topic;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.*;

/**
 * Common base class for external system settings. Defines a minimal api which is necessary for the common external system
 * support codebase.
 *

 * Note: non-abstract sub-classes of this class are expected to be marked by {@link State} annotation configured as necessary.
 *
 * @author Denis Zhdanov
 * @since 4/3/13 4:04 PM
 */
public abstract class AbstractExternalSystemSettings<
  SS extends AbstractExternalSystemSettings<SS, PS, L>,
  PS extends ExternalProjectSettings,
  L extends ExternalSystemSettingsListener<PS>>
  implements Disposable
{

  @NotNull private final Topic<L> myChangesTopic;

  private Project  myProject;

  @NotNull private final Map<String/* project path */, PS> myLinkedProjectsSettings = ContainerUtilRt.newHashMap();

  @NotNull private final Map<String/* project path */, PS> myLinkedProjectsSettingsView
    = Collections.unmodifiableMap(myLinkedProjectsSettings);

  protected AbstractExternalSystemSettings(@NotNull Topic<L> topic, @NotNull Project project) {
    myChangesTopic = topic;
    myProject = project;
    Disposer.register(project, this);
  }

  @Override
  public void dispose() {
    myProject = null;
  }

  @NotNull
  public Project getProject() {
    return myProject;
  }

  /**
   * Every time particular external system setting is changed corresponding message is sent via ide
   * messaging sub-system.
   * The problem is that every external system implementation defines it's own topic/listener pair. Listener interface is derived
   * from the common {@link ExternalSystemSettingsListener} interface and is specific to external sub-system implementation.
   * However, it's possible that a client wants to perform particular actions based only on {@link ExternalSystemSettingsListener}
   * facilities. There is no way for such external system-agnostic client to create external system-specific listener
   * implementation then.
   *

   * That's why this method allows to wrap given 'generic listener' into external system-specific one.
   *
   * @param listener  target generic listener to wrap to external system-specific implementation
   */
  public abstract void subscribe(@NotNull ExternalSystemSettingsListener<PS> listener);

  public void copyFrom(@NotNull SS settings) {
    myLinkedProjectsSettings.clear();
    for (PS projectSettings : settings.getLinkedProjectsSettings()) {
      myLinkedProjectsSettings.put(projectSettings.getExternalProjectPath(), projectSettings);
    }
    copyExtraSettingsFrom(settings);
  }

  protected abstract void copyExtraSettingsFrom(@NotNull SS settings);

  @SuppressWarnings("unchecked")
  @NotNull
  public Collection<PS> getLinkedProjectsSettings() {
    return myLinkedProjectsSettingsView.values();
  }

  @Nullable
  public PS getLinkedProjectSettings(@NotNull String linkedProjectPath) {
    PS ps = myLinkedProjectsSettings.get(linkedProjectPath);
    if(ps == null) {
      for (PS ps1 : myLinkedProjectsSettings.values()) {
        for (String modulePath : ps1.getModules()) {
          if(linkedProjectPath.equals(modulePath)) return ps1;
        }
      }
    }
    return ps;
  }

  public void linkProject(@NotNull PS settings) throws IllegalArgumentException {
    PS existing = getLinkedProjectSettings(settings.getExternalProjectPath());
    if (existing != null) {
      throw new IllegalArgumentException(String.format(
        "Can't link external project '%s'. Reason: it's already registered at the current ide project",
        settings.getExternalProjectPath()
      ));
    }
    myLinkedProjectsSettings.put(settings.getExternalProjectPath(), settings);
    getPublisher().onProjectsLinked(Collections.singleton(settings));
  }

  /**
   * Un-links given external project from the current ide project.
   *
   * @param linkedProjectPath  path of external project to be unlinked
   * @return                   true if there was an external project with the given config path linked to the current
   *                           ide project;
   *                           false otherwise
   */
  public boolean unlinkExternalProject(@NotNull String linkedProjectPath) {
    PS removed = myLinkedProjectsSettings.remove(linkedProjectPath);
    if (removed == null) {
      return false;
    }

    getPublisher().onProjectsUnlinked(Collections.singleton(linkedProjectPath));
    return true;
  }

  public void setLinkedProjectsSettings(@NotNull Collection<PS> settings) {
    List<PS> added = ContainerUtilRt.newArrayList();
    Map<String, PS> removed = ContainerUtilRt.newHashMap(myLinkedProjectsSettings);
    myLinkedProjectsSettings.clear();
    for (PS current : settings) {
      myLinkedProjectsSettings.put(current.getExternalProjectPath(), current);
    }

    for (PS current : settings) {
      PS old = removed.remove(current.getExternalProjectPath());
      if (old == null) {
        added.add(current);
      }
      else {
        if (current.isUseAutoImport() != old.isUseAutoImport()) {
          getPublisher().onUseAutoImportChange(current.isUseAutoImport(), current.getExternalProjectPath());
        }
        checkSettings(old, current);
      }
    }
    if (!added.isEmpty()) {
      getPublisher().onProjectsLinked(added);
    }
    if (!removed.isEmpty()) {
      getPublisher().onProjectsUnlinked(removed.keySet());
    }
  }

  /**
   * Is assumed to check if given old settings external system-specific state differs from the given new one
   * and {@link #getPublisher() notify} listeners in case of the positive answer.
   *
   * @param old      old settings state
   * @param current  current settings state
   */
  protected abstract void checkSettings(@NotNull PS old, @NotNull PS current);

  @NotNull
  public Topic<L> getChangesTopic() {
    return myChangesTopic;
  }

  @NotNull
  public L getPublisher() {
    return myProject.getMessageBus().syncPublisher(myChangesTopic);
  }

  protected void fillState(@NotNull State<PS> state) {
    state.setLinkedExternalProjectsSettings(ContainerUtilRt.newTreeSet(myLinkedProjectsSettings.values()));
  }

  @SuppressWarnings("unchecked")
  protected void loadState(@NotNull State<PS> state) {
    Set<PS> settings = state.getLinkedExternalProjectsSettings();
    if (settings != null) {
      myLinkedProjectsSettings.clear();
      for (PS projectSettings : settings) {
        myLinkedProjectsSettings.put(projectSettings.getExternalProjectPath(), projectSettings);
      }
    }
  }

  public interface State<S> {

    Set<S> getLinkedExternalProjectsSettings();

    void setLinkedExternalProjectsSettings(Set<S> settings);
  }
}