text:
layout: manual
title: Motivation
date: 2015-07-04 10:00:00
nav: [ manual, motivation ]
---

# {{ page.title }}

This section describes the domain of system experiments, introduces a running example used throughout the rest of the manual, and discusses the problems Peel will solve for you.

## System Experiments Basics

The principle goal of a system experiment is to characterise the behavior of a particular *system under test (SUT)* for a specific set of values configured as *system and application parameters*. The usual way to achieve this goal is to

1. define a *workload application* which takes specific parameters (e.g., input and output path),
2. run it on top of the SUT with a specific configuration (e.g., allocated memory, <acronym title="degree of parallelism">DOP</acronym>), and
3. measure key performance characteristics (e.g., runtime, throughput, accuracy).

The basic layout of the execution environment observed when running a system experiment is depicted below.

Basic experiment environment layout

Modern data management, however, rarely relies on a single system running in isolation. Insead, current trends advocate an architecture based on interconnected systems (e.g.[ HDFS and Yarn](http://hadoop.apache.org),[ Spark](http://spark.apache.org/),[ Flink](http://flink.apache.org/),[ Storm](https://storm.apache.org/)), each maintaining its own configuration. A more realistic environment layout therefore looks as follows:

Experiment environment layout with multiple systems

Typically, one is not just interested in the insight obtained by a single experiment, but in trends highlighted by a suite of experiments where a certain SUT configuration or application parameter value is varied and everything else remains fixed.

A suite of experiments with varying SUT config

## Running Example

To illustrate the principles presented above, let us consider a scenario where we want to compare the scale-out characteristics of two parallel dataflow engines - [Apache Spark](http://spark.apache.org/) and [Apache Flink](http://flink.apache.org/) - based on their ability to count words.
The environment layout for a single run of the two applications looks like this:

Environment layout for "WordCount: Spark vs. Flink"

### Step 1: Defining a Workload Application

We start by coding two equivalent workload applications - *SparkWC* and *FlinkWC* - against the corresponding parallel dataflow APIs of the two systems. The applications

1. read a text corpus from HDFS,
2. compute the word frequencies within that corpus, and
3. store the resulting collection of (word, count) back in HDFS.

### Step 2: Defining the Input Data

In addition, we also write a parallel data generator that generates a random sequence of words to be used as input. To make the properties of the data realistic, the words are sampled i.i.d. out of a pre-defined dictionary following a Zipfian distribution.

### Step 3: Running the Experiments

We are now ready execute a series experiments on a cluster with varying capacity. In each step, we perform the following actions:

1. Setup the required systems, while doubling the number of DataNodes (HDFS) / TaskManagers (Flink) / Workers (Spark);
2. Generate and store input data in HDFS, while keeping the size/nodes ratio fixed;
3. Repeatedly execute the two applications and record key performance metrics for each experiment run.

The environment layout will look as follows:

Environment layouts for "Weak Scale-Out - Spark vs. Flink"

### Step 4: Result Analysis / Closing the Loop

The obtained data characterizes the so-called [weak-scaling](https://en.wikipedia.org/wiki/Scalability#Weak_versus_strong_scaling) behavior of the two systems for the word counting scenario. Upon running the experiments, the most common steps are:

1. Understand the experiment results (e.g., via visual exploration, statistical analysis);
2. Make hypotheses that explain the observed phenomenon;
3. Refine the old experiment or create a new one in order to verify them.

## Challenges

If you, as a practitioner, want to realize the steps outlined above, you will face the following challenges.

### Environment Configuration

Each system comes with its own installation and configuration manual. You need to have good prior knowledge or invest time reading these manuals in order to understand (i) which parameters work out of the box, (ii) which ones need to be tuned to your current execution environment, and (iii) which what values to chose for those.

### Execution Code

When you come to [Step 3](#step-3-running-the-experiments), you will have the option to either sit in front of the console and steer the experiment lifecycle (system setup & configuration, execution, cleanup) manually, or write a bunch of glue code that does this automatically for you. In a distributed setting, each of these phases is susceptible to occasional errors, so your glue code will need a couple of iterations until it becomes robust enough so you can rely on it.

### Analysis Code

When you come to [Step 4](#step-4-result-analysis--closing-the-loop), you will have to extract the data observed at execution time. Since every system has it's own logging format and specifics, you will have to write more glue code that deals with that, most likely handling the specific problem at hand.

### Packaging & Sharing

After fiddling around for some days, you will solve the problem at hand and produce some nice charts to share. [*Repeatability* and *reproducibility*, however, are important properties of any good experiment](http://www.tpc.org/tpctc/tpctc2009/tpctc2009-03.pdf), and you might be asked to package and share the experiments code with a skeptical third party. You will have to make sure that everything works well on another developer machine and another execution environment (e.g. EC2).

## Solution

Peel can help you solve all of the above problems. The remainder of this manual explains how by means of the running example presented above. To get the example, run the following code snippet:

```bash
cd "$BUNDLE_SRC"
mvn archetype:generate -B                         \
    -Dpackage="org.peelframework.wordcount"       \
    -DgroupId="org.peelframework"                 \
    -DartifactId="peel-wordcount"                 \
    -DarchetypeGroupId=org.peelframework          \
    -DarchetypeArtifactId=peel-flinkspark-bundle  \
    -DarchetypeVersion={{ site.current_version }}
cd "peel-wordcount"
mvn clean deploy
cd "$BUNDLE_BIN/peel-wordcount"
```


text:
require 'mongo'

class AppConfig

  attr_accessor :_id,:template_id_board, :template_id_message

  def initialize
    @_id = BSON::ObjectId.new
    @template_id_board = ""
    @template_id_message = ""
  end

  def to_array
    data = {}
    data["_id"] = @_id
    data["template_id_board"] = @template_id_board
    data["template_id_message"] = @template_id_message
    data
  end

  def self.create_new(data)
    obj = AppConfig.new
    obj._id = data["_id"]
    obj.template_id_board = data["template_id_board"]
    obj.template_id_message = data["template_id_message"]
    obj
  end

end

redpajama_set_name: RedPajamaGithub


text:
LegalPortal.controller('config.default.view.controller',
	['$scope', 'PORTLET',
    function ($scope, PORTLET) {
        'use strict';

        var init = function () {
          if(PORTLET.setup){

          } else {

          }
        };

        init();
    }
]);


text:
require_relative '../../../spec_helper'

describe BandCampBX::Entities::Order do
  subject{ described_class.new(order_hash) }

  context "a successful order" do
    let(:order_hash){
      {
        "id" => "1",
        "datetime" => 1234567,
        "type" => 0,
        "price" => "1.23",
        "amount" => "10"
      }
    }

    it "has an id" do
      expect(subject.id).to eq(1)
    end

    describe "type" do
      it "maps 0 to :buy" do
        expect(subject.type).to eq(:buy)
      end

      it "maps 1 to :sell" do
        order = described_class.new(order_hash.merge({"type" => 1}))
        expect(order.type).to eq(:sell)
      end

      it "raises InvalidTypeError for other values" do
        expect { described_class.new(order_hash.merge({"type" => 2})) }.to raise_error(BandCampBX::Entities::Order::InvalidTypeError)
      end
    end
  end

  context "an unsuccessful order" do
    context "with an __all__ key" do
      let(:order_hash){
        # Don't get mad at me, not my fault CampBX errors look like this
        {
          "error" => {
            "__all__" => ["Minimum order size is $1"]
          }
        }
      }

      it "raises an appropriate error" do
        expect{ subject }.to raise_error(BandCampBX::StandardError, "Minimum order size is $1")
      end
    end

    context "without an __all__ key" do
      let(:order_hash){
        # Don't get mad at me, not my fault CampBX errors look like this
        {
          "error" => {
            "neg" => ["Minimum order size is $1"]
          }
        }
      }

      it "raises an appropriate error" do
        expect{ subject }.to raise_error(BandCampBX::StandardError, "CampBX API Error #404")
      end
    end
  end
end


text:
require "google/cloud/logging/v2"

##
# Example demonstrating basic usage of
# Google::Cloud::Logging::V2::LoggingService::Client#delete_log
#
def delete_log
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::Logging::V2::LoggingService::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::Logging::V2::DeleteLogRequest.new

  # Call the delete_log method.
  result = client.delete_log request

  # The returned object is of type Google::Protobuf::Empty.
  p result
end
# [END logging_v2_generated_LoggingService_DeleteLog_sync]


text:
import Ember from 'ember';

export default Ember.Controller.extend({
	firstName: 'chen',
	lastName: 'ubuntuvim'
});


text:
from .base_object import BaseObject

class EmailAlias(BaseObject):
    """Represents a Box email alias."""

    _item_type = 'email_alias'


text:
<?php namespace Coreplex\Crumbs\Facades;

use Illuminate\Support\Facades\Facade;

class Crumbs extends Facade {

    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor() { return 'Coreplex\Crumbs\Contracts\Container'; }

}


text:
import { connect } from 'react-redux';
import { fetchGroupsIfNeeded } from '../actions';
import List from '../components/list';

const mapStateToProps = state => {
	return {
		items: state.customerGroups.items
	};
};

const mapDispatchToProps = dispatch => {
	return {
		onLoad: () => {
			dispatch(fetchGroupsIfNeeded());
		}
	};
};

export default connect(
	mapStateToProps,
	mapDispatchToProps
)(List);


text:
function random(min, max) {
  return Math.floor(Math.random() * (max - min) + min);
}

function release_key(bot, discord, moment, schedule, database, conf) {
  conf['daily-key-release'] = moment().format('LL');

  let release_hour = random(8, 22);
  let release_minute = random(1, 59);
  let release_date = `* ${release_minute} ${release_hour} * * *`;

  console.log(`[!] releasing key at ${release_hour}:${release_minute}`);

  var j = schedule.scheduleJob(release_date, function(){
    var collection = database.collection('release-keys');
    collection.find({}).toArray(function(err, table) {
      for (let row in table) {
        let embed = new discord.RichEmbed()
          .setColor('#0086AE')
          .setTitle(table[row]['key'])
          .setFooter('Give-Away')
          .setTimestamp();
        bot.channels.find('name', conf['release-channel']).send({embed});
        collection.deleteOne({'key': table[row]['key']}, function(err, result) {});
        return}
    });

    j.cancel();
  });
}

module.exports = {
  handler: (bot, discord, schedule, conf, moment, database) => {
    if (conf['daily-key-release'] !== moment().format('LL')) {release_key(bot, discord, moment, schedule, database, conf)}
  },

  add_release_key: (database, conf, message, key) => {
    if (message.channel.type === 'dm') {message.author.send({embed: {color: 3447003, title: 'Server commands must be used in the server.',}}); return}
    message.delete();
    if (message.member.roles.some(r=>[conf['admin-role']].includes(r.name)) === false) {return;}
    var collection = database.collection('release-keys');
    collection.insertMany([{'key': key}], function(err, result) {
      message.author.send({embed: {color: 3447003, description: `**${key}** was added to the release list!`,}})
    });
  }
}


text:
Puppet::Type.newtype(:neutron_plugin_cisco_credentials) do

  ensurable

  newparam(:name, :namevar => true) do
    desc 'Section/setting name to manage from credentials.ini'
    newvalues(/\S+\/\S+/)
  end

  newproperty(:value) do
    desc 'The value of the setting to be defined.'
    munge do |value|
      value = value.to_s.strip
      value.capitalize! if value =~ /^(true|false)$/i
      value
    end

    def is_to_s( currentvalue )
      if resource.secret?
        return '[old secret redacted]'
      else
        return currentvalue
      end
    end

    def should_to_s( newvalue )
      if resource.secret?
        return '[new secret redacted]'
      else
        return newvalue
      end
    end
  end

  newparam(:secret, :boolean => true) do
    desc 'Whether to hide the value from Puppet logs. Defaults to `false`.'

    newvalues(:true, :false)

    defaultto false

  end

  newparam(:ensure_absent_val) do
    desc 'A value that is specified as the value property will behave as if ensure => absent was specified'
    defaultto('<SERVICE DEFAULT>')
  end

  autorequire(:file) do
    ['/etc/neutron/plugins/cisco']
  end

  autorequire(:package) do
    'neutron-plugin-cisco'
  end

end


text:
package com.hudson.donglingmusic.ui.recyclerview.ViewHolder;

import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.hudson.donglingmusic.R;
import com.hudson.donglingmusic.bean.MyGedanBean;
import com.hudson.donglingmusic.ui.recyclerview.Adapter.MyLocalGedanListRecyclerViewAdapter;
import com.hudson.donglingmusic.utils.UIUtils;

/**
 * Created by Hudson on 2017/4/21.
 * 歌单详情页的头布局的ViewHolder
 */

public class MyGedanListHeaderViewHolder extends BaseRecyclerViewHolder<MyGedanBean> {
    private ImageView mListBg;
    private TextView mListTitle, mSongCount,mTag,mDesc;

    public MyGedanListHeaderViewHolder(View itemView, final MyLocalGedanListRecyclerViewAdapter.OnManageGedanClickListener listener) {
        super(itemView);
        itemView.findViewById(R.id.iv_manage_gedan).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(listener!=null){
                    listener.onManageGedanClick();
                }
            }
        });
        mListBg = (ImageView) itemView.findViewById(R.id.iv_gedan_list_bg);
        mListTitle = (TextView) itemView.findViewById(R.id.tv_gedan_name);
        mSongCount = (TextView) itemView.findViewById(R.id.tv_song_count);
        mTag = (TextView) itemView.findViewById(R.id.tv_tag);
        mDesc = (TextView) itemView.findViewById(R.id.tv_gedan_info);
    }

    @Override
    public void refreshView(MyGedanBean data) {
        String imagePath = data.getImagePath();
        if(TextUtils.isEmpty(imagePath)){
            mListBg.setImageResource(R.drawable.gedan_disk);
        }else{
            mListBg.setImageBitmap(BitmapFactory.decodeFile(imagePath));
        }
        mListTitle.setText(data.getTitle());
        mSongCount.setText(data.getSongCount()+"");
        mTag.setText(data.getTag());
        mDesc.setText(data.getDesc());
        mDesc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int maxLines = mDesc.getMaxLines();
                if(maxLines==3){
                    mDesc.setMaxLines(1000);
                    mDesc.setCompoundDrawablesWithIntrinsicBounds(null,null,null, UIUtils.getContext().getResources().getDrawable(R.drawable.up_arrow));
                }else{
                    mDesc.setMaxLines(3);
                    mDesc.setCompoundDrawablesWithIntrinsicBounds(null,null,null, UIUtils.getContext().getResources().getDrawable(R.drawable.down_arrow));
                }
                mDesc.invalidate();
            }
        });
    }
}


text:
import urllib2
import requests
import csv
import re
import time
import argparse
import json

from bs4 import BeautifulSoup
from pprint import pprint
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from elasticsearch import Elasticsearch
from elasticsearch.helpers import scan, streaming_bulk

from pyvirtualdisplay import Display

# --
# CLI

parser = argparse.ArgumentParser(description='ingest_otc_halts')
parser.add_argument("--config-path", type=str, action='store', default='../config.json')
args = parser.parse_args()

# --
# config

# config      = json.load(open(args.config_path))

config      = json.load(open('/home/ubuntu/ernest/config.json'))

# --
# connections

client = Elasticsearch([{"host" : config['es']['host'], "port" : config['es']['port']}])

INDEX  = config['otc_halts']['index']
TYPE   = config['otc_halts']['_type']

# display = Display(visible=0, size=(800, 600))
# display.start()

driver = webdriver.PhantomJS()
driver.get('http://otce.finra.org/TradeHaltsHistorical')

# --
# helpers

def sec_halt(facts):
    try:
        facts[6].find('a').get_text()
        sec_halt = True
    except:
        sec_halt = False
    return sec_halt

def build_date( date ):
    f = re.sub(r'/', '&', date)
    d = re.compile("\d{2}&\d{2}&\d{4}")
    c = re.findall(d, f)[0].split('&')
    out_d = c[2] + '-' + c[0] + '-' + c[1]
    return out_d

# --
# run

counter = 0
while True:
    try:
        time.sleep(6)
        posts = BeautifulSoup(driver.page_source).findAll("tr", {'class' : ['odd', 'even']})
        time.sleep(3)
        for post in posts:
            facts = post.findAll('td')
            out   = {
                'dateTime'      : build_date( facts[0].get_text() ),
                'ticker'        : facts[1].get_text().upper(),
                'issuerName'    : facts[2].get_text().upper(),
                'haltCode'      : facts[3].get_text(),
                'mktCtrOrigin'  : facts[4].get_text(),
                'Action'        : facts[5].get_text(),
                'secHalt'       : sec_halt(facts)
            }
            client.index(index=INDEX, doc_type=TYPE, body=out, id=out['dateTime'] + '_' + out['ticker'])

        counter += 1
        print(counter)

        try:
            driver.find_element_by_xpath("//*[contains(text(), 'Next')]").click()
        except:
            break
    except:
        driver.quit()
        raise

driver.quit()


text:
class CreateMessages < ActiveRecord::Migration
  def change
    create_table :messages do |t|
      t.belongs_to :user
      t.string :subject
      t.string :contents
      t.integer :receiver_id
      t.timestamps
    end
  end
end


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

/**
  * Entity Handler callback function
  */
var callbackFunction = function(flag, request) {
	console.log( "Entity handler called with flag = " + flag + " and the following request:" );
}

var intervalId,
	handleReceptacle = {},

	// This is the same value as server.get.js
	sampleUri = "/oic/graph",
	iotivity = require( "iotivity-node/lowlevel" );

console.log( "Starting OCF stack in server mode" );

// Start iotivity and set up the processing loop
iotivity.OCInit( null, 0, iotivity.OCMode.OC_SERVER );

iotivity.OCSetDeviceInfo( { deviceName: "server.get", types: [] } );
iotivity.OCSetPlatformInfo( {
	platformID: "server.get.sample",
	manufacturerName: "iotivity-node"
} );

intervalId = setInterval( function() {
	iotivity.OCProcess();
}, 1000 );

console.log( "Registering resource" );

// Create a new resource
iotivity.OCCreateResource(

	// The bindings fill in this object
	handleReceptacle,

	"oic.d.light",
	iotivity.OC_RSRVD_INTERFACE_DEFAULT,
	sampleUri,
	callbackFunction
	/*function( flag, request ) {
		console.log( "Entity handler called with flag = " + flag + " and the following request:" );
		console.log( JSON.stringify( request, null, 4 ) );

		// If we find the magic question in the request, we return the magic answer
		if ( request && request.payload && request.payload.values &&
				request.payload.values.question ===
				"How many angels can dance on the head of a pin?" ) {

			iotivity.OCDoResponse( {
				requestHandle: request.requestHandle,
				resourceHandle: request.resource,
				ehResult: iotivity.OCEntityHandlerResult.OC_EH_OK,
				payload: {
					type: iotivity.OCPayloadType.PAYLOAD_TYPE_REPRESENTATION,
					values: {
						"answer": "As many as wanting."
					}
				},
				resourceUri: sampleUri,
				sendVendorSpecificHeaderOptions: []
			} );

			return iotivity.OCEntityHandlerResult.OC_EH_OK;
		}

		// By default we error out
		return iotivity.OCEntityHandlerResult.OC_EH_ERROR;
	}*/,
	iotivity.OCResourceProperty.OC_DISCOVERABLE );

console.log( "Server ready" );

// Exit gracefully when interrupted
process.on( "SIGINT", function() {
	console.log( "SIGINT: Quitting..." );

	// Tear down the processing loop and stop iotivity
	clearInterval( intervalId );
	iotivity.OCDeleteResource( handleReceptacle.handle );
	iotivity.OCStop();

	// Exit
	process.exit( 0 );
} );


text:
require 'fog/core/collection'
require 'fog/opennebula/models/compute/server'

module Fog
  module Compute
    class OpenNebula

      class Servers < Fog::Collection

        model Fog::Compute::OpenNebula::Server

        def all(filter={})
          load(service.list_vms(filter))
        end

        def get(id)
          data = service.list_vms({:id => id})
          new data.first unless data.empty?
        end

        def shutdown(id)
          service.vm_shutdown(id)
        end

      end
    end
  end
end


text:
//
//  BRMenuUIControl.h
//  MenuKit
//
//  Created by Matt on 6/08/15.
//  Copyright (c) 2015 Blue Rocket. Distributable under the terms of the Apache License, Version 2.0.
//

#import <BRStyle/BRUIStylishControl.h>

/**
 A protocol for controls to conform to to pick up some common traits.
 */
@protocol BRMenuUIControl <BRUIStylishControl>

@end


text: Website (http://minio.io)


text:
package org.pentaho.di.trans.steps.addxml;

import org.pentaho.di.core.injection.Injection;
import org.pentaho.di.core.row.ValueMeta;

/**
 * Describes a single field in an XML output file
 *
 * @author Matt
 * @since 14-jan-2006
 *
 */
public class XMLField implements Cloneable {

  @Injection( name = "OUTPUT_FIELD_NAME", group = "OUTPUT_FIELDS" )
  private String fieldName;

  @Injection( name = "OUTPUT_ELEMENT_NAME", group = "OUTPUT_FIELDS" )
  private String elementName;

  private int type;

  @Injection( name = "OUTPUT_FORMAT", group = "OUTPUT_FIELDS" )
  private String format;

  @Injection( name = "OUTPUT_LENGTH", group = "OUTPUT_FIELDS" )
  private int length;

  @Injection( name = "OUTPUT_PRECISION", group = "OUTPUT_FIELDS" )
  private int precision;

  @Injection( name = "OUTPUT_CURRENCY_SYMBOL", group = "OUTPUT_FIELDS" )
  private String currencySymbol;

  @Injection( name = "OUTPUT_DECIMAL_SYMBOL", group = "OUTPUT_FIELDS" )
  private String decimalSymbol;

  @Injection( name = "OUTPUT_GROUPING_SYMBOL", group = "OUTPUT_FIELDS" )
  private String groupingSymbol;

  @Injection( name = "OUTPUT_ATTRIBUTE", group = "OUTPUT_FIELDS" )
  private boolean attribute;

  @Injection( name = "OUTPUT_ATTRIBUTE_PARENT_NAME", group = "OUTPUT_FIELDS" )
  private String attributeParentName;

  @Injection( name = "OUTPUT_NULL_STRING", group = "OUTPUT_FIELDS" )
  private String nullString;

  public XMLField( String fieldName, String elementName, int type, String format, int length, int precision,
      String currencySymbol, String decimalSymbol, String groupSymbol, String nullString, boolean attribute,
      String attributeParentName ) {
    this.fieldName = fieldName;
    this.elementName = elementName;
    this.type = type;
    this.format = format;
    this.length = length;
    this.precision = precision;
    this.currencySymbol = currencySymbol;
    this.decimalSymbol = decimalSymbol;
    this.groupingSymbol = groupSymbol;
    this.nullString = nullString;
    this.attribute = attribute;
    this.attributeParentName = attributeParentName;
  }

  public XMLField() {
  }

  public int compare( Object obj ) {
    XMLField field = (XMLField) obj;

    return fieldName.compareTo( field.getFieldName() );
  }

  public boolean equal( Object obj ) {
    XMLField field = (XMLField) obj;

    return fieldName.equals( field.getFieldName() );
  }

  public Object clone() {
    try {
      Object retval = super.clone();
      return retval;
    } catch ( CloneNotSupportedException e ) {
      return null;
    }
  }

  public int getLength() {
    return length;
  }

  public void setLength( int length ) {
    this.length = length;
  }

  public String getFieldName() {
    return fieldName;
  }

  public void setFieldName( String fieldname ) {
    this.fieldName = fieldname;
  }

  public int getType() {
    return type;
  }

  public String getTypeDesc() {
    return ValueMeta.getTypeDesc( type );
  }

  public void setType( int type ) {
    this.type = type;
  }

  @Injection( name = "OUTPUT_TYPE", group = "OUTPUT_FIELDS" )
  public void setType( String typeDesc ) {
    this.type = ValueMeta.getType( typeDesc );
  }

  public String getFormat() {
    return format;
  }

  public void setFormat( String format ) {
    this.format = format;
  }

  public String getGroupingSymbol() {
    return groupingSymbol;
  }

  public void setGroupingSymbol( String group_symbol ) {
    this.groupingSymbol = group_symbol;
  }

  public String getDecimalSymbol() {
    return decimalSymbol;
  }

  public void setDecimalSymbol( String decimal_symbol ) {
    this.decimalSymbol = decimal_symbol;
  }

  public String getCurrencySymbol() {
    return currencySymbol;
  }

  public void setCurrencySymbol( String currency_symbol ) {
    this.currencySymbol = currency_symbol;
  }

  public int getPrecision() {
    return precision;
  }

  public void setPrecision( int precision ) {
    this.precision = precision;
  }

  public String getNullString() {
    return nullString;
  }

  public void setNullString( String null_string ) {
    this.nullString = null_string;
  }

  public String toString() {
    return fieldName + ":" + getTypeDesc() + ":" + elementName;
  }

  /**
   * @return Returns the elementName.
   */
  public String getElementName() {
    return elementName;
  }

  /**
   * @param elementName
   *          The elementName to set.
   */
  public void setElementName( String elementName ) {
    this.elementName = elementName;
  }

  /**
   * @return true if the field should be encoded as attribute instead of a child node.
   */
  public boolean isAttribute() {
    return attribute;
  }

  /**
   * @param attribute
   *          set to true if the field should be encoded as attribute instead of a child node
   */
  public void setAttribute( boolean attribute ) {
    this.attribute = attribute;
  }

  /**
   * @return Returns the attributeParentName.
   */
  public String getAttributeParentName() {
    return attributeParentName;
  }

  /**
   * @param attributeParentName
   *          The attributeParentName to set.
   */
  public void setAttributeParentName( String attributeParentName ) {
    this.attributeParentName = attributeParentName;
  }
}


text:
<?php
/*
Plugin Name: XML Sitemap & Google News feeds
Plugin URI: http://status301.net/wordpress-plugins/xml-sitemap-feed/
Description: Feed the  hungry spiders in compliance with the XML Sitemap and Google News protocols. Happy with the results? Please leave me a tip for continued development and support. Thanks :)
Text Domain: xml-sitemap-feed
Version: 4.7.5
Author: RavanH
Author URI: http://status301.net/
*/

/*  Copyright 2016 RavanH
    http://status301.net/
    mailto: ravanhagen@gmail.com

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 3 as
    published by the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
*/

/* --------------------
 *  AVAILABLE HOOKS
 * --------------------
 *
 * FILTERS
 * 		xmlsf_defaults				-> Filters the default array values for different option groups.
 * 		xmlsf_allowed_domain	-> Filters the response when checking the url against allowed domains.
 *					Passes variable $url; must return true or false.
 * 		xmlsf_excluded				-> Filters the response when checking the post for exclusion flags.
 *					Passes variable $post_id; must return true or false.
 * 		the_title_xmlsitemap	-> Filters the Google News publication name, title and keywords
 *					plus the Image title and caption tags
 * 		xmlsf_custom_urls			-> Filters the custom urls array
 * 		xmlsf_custom_sitemaps	-> Filters the custom sitemaps array
 *
 * ACTIONS
 * 		xmlsf_news_tags_after	-> Fired inside the Google News Sitemap loop at the end of the news
 * 					tags, just before each closing </news:news> is generated. Can be used to
 * 					echo custom tags or trigger another action in the background.
 *
 * Feel free to request, suggest or submit more :)
 */

if ( ! defined( 'WPINC' ) ) die;

/* --------------------
 *      CONSTANTS
 * -------------------- */

	define('XMLSF_VERSION', '4.7.5');

	define('XMLSF_PLUGIN_BASENAME', plugin_basename(__FILE__));

/*
 * The following constants can be used to change plugin defaults
 * by defining them in wp-config.php
 */

/*
 * XMLSF_NAME
 *
 * Pretty permalink name for the main sitemap (index)
 */

if ( !defined('XMLSF_NAME') )

	define('XMLSF_NAME', 'sitemap.xml');

/*
 * XMLSF_NEWS_NAME
 *
 * Pretty permalink name for the news sitemap
 */

if ( !defined('XMLSF_NEWS_NAME') )

	define('XMLSF_NEWS_NAME', 'sitemap-news.xml');

/*
 * XMLSF_MULTISITE_UNINSTALL
 *
 * Set this constant in wp-config.php if you want to allow looping over each site
 * in the network to run XMLSitemapFeed_Uninstall->uninstall() defined in uninstall.php
 *
 * Be careful: There is NO batch-processing so it does not scale on large networks!
 *
 * example:
 * define('XMLSF_MULTISITE_UNINSTALL', true);
 */

/* -------------------------------------
 *      INCLUDE HACKS & CLASS
 * ------------------------------------- */

$xmlsf_dir = dirname(__FILE__);

if ( file_exists ( $xmlsf_dir.'/xml-sitemap-feed' ) )
	$xmlsf_dir .= '/xml-sitemap-feed';

include_once( $xmlsf_dir.'/hacks.php' );
include_once( $xmlsf_dir.'/includes/class-xmlsitemapfeed.php' );

/* ----------------------
 *     INSTANTIATE
 * ---------------------- */

$xmlsf = new XMLSitemapFeed();


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_encrypt"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="alexparunov.steganographer.MainActivity">

  <android.support.v7.widget.Toolbar
      android:id="@+id/toolbar"
      android:minHeight="?attr/actionBarSize"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:background="?attr/colorPrimary"
      android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
  </android.support.v7.widget.Toolbar>

  <LinearLayout android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:layout_gravity="center"
                android:paddingTop="@dimen/activity_vertical_margin">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/colorPrimaryBlack"
        android:text="@string/select_image_title"
        android:textSize="@dimen/medium_text_dim"
        android:layout_gravity="center"/>

    <ImageView
        android:layout_width="@dimen/large_image_square"
        android:layout_height="@dimen/large_image_square"
        android:layout_gravity="center"
        app:srcCompat="@mipmap/ic_launcher"
        android:contentDescription="@string/select_image_title"
        android:id="@+id/ivCoverImage"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/secret_message_title"
        android:textSize="@dimen/medium_text_dim"
        android:textColor="@color/colorPrimaryBlack"
        android:layout_gravity="center"/>

    <RadioGroup
        android:id="@+id/rgSecretMessageType"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

      <RadioButton
          android:id="@+id/rbText"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="@string/rb_secret_text"
          android:checked="true"/>

      <RadioButton
          android:id="@+id/rbImage"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="@string/rb_secret_image"/>
    </RadioGroup>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:ems="10"
        android:hint="@string/et_secret_text"
        android:id="@+id/etSecretMessage"/>

    <ImageView
        android:layout_width="@dimen/large_image_square"
        android:layout_height="@dimen/large_image_square"
        android:layout_gravity="center"
        app:srcCompat="@mipmap/ic_launcher"
        android:id="@+id/ivSecretImage"
        android:visibility="gone"/>

    <android.support.v7.widget.AppCompatButton
        android:text="@string/b_secret_text_encrypt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="@color/colorPrimaryWhite"
        app:backgroundTint="@color/colorBlueGreySecondary"
        android:id="@+id/bEncrypt"/>

  </LinearLayout>

</LinearLayout>


text:
package com.microsoft.azure.management.logic.v2016_06_01.implementation;

import com.microsoft.azure.management.logic.v2016_06_01.IntegrationAccountCertificate;
import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl;
import rx.Observable;
import java.util.Map;
import org.joda.time.DateTime;
import com.microsoft.azure.management.logic.v2016_06_01.KeyVaultKeyReference;

class IntegrationAccountCertificateImpl extends CreatableUpdatableImpl<IntegrationAccountCertificate, IntegrationAccountCertificateInner, IntegrationAccountCertificateImpl> implements IntegrationAccountCertificate, IntegrationAccountCertificate.Definition, IntegrationAccountCertificate.Update {
    private final LogicManager manager;
    private String resourceGroupName;
    private String integrationAccountName;
    private String certificateName;

    IntegrationAccountCertificateImpl(String name, LogicManager manager) {
        super(name, new IntegrationAccountCertificateInner());
        this.manager = manager;
        // Set resource name
        this.certificateName = name;
        //
    }

    IntegrationAccountCertificateImpl(IntegrationAccountCertificateInner inner, LogicManager manager) {
        super(inner.name(), inner);
        this.manager = manager;
        // Set resource name
        this.certificateName = inner.name();
        // resource ancestor names
        this.resourceGroupName = IdParsingUtils.getValueFromIdByName(inner.id(), "resourceGroups");
        this.integrationAccountName = IdParsingUtils.getValueFromIdByName(inner.id(), "integrationAccounts");
        this.certificateName = IdParsingUtils.getValueFromIdByName(inner.id(), "certificates");
        //
    }

    @Override
    public LogicManager manager() {
        return this.manager;
    }

    @Override
    public Observable<IntegrationAccountCertificate> createResourceAsync() {
        CertificatesInner client = this.manager().inner().certificates();
        return client.createOrUpdateAsync(this.resourceGroupName, this.integrationAccountName, this.certificateName, this.inner())
            .map(innerToFluentMap(this));
    }

    @Override
    public Observable<IntegrationAccountCertificate> updateResourceAsync() {
        CertificatesInner client = this.manager().inner().certificates();
        return client.createOrUpdateAsync(this.resourceGroupName, this.integrationAccountName, this.certificateName, this.inner())
            .map(innerToFluentMap(this));
    }

    @Override
    protected Observable<IntegrationAccountCertificateInner> getInnerAsync() {
        CertificatesInner client = this.manager().inner().certificates();
        return client.getAsync(this.resourceGroupName, this.integrationAccountName, this.certificateName);
    }

    @Override
    public boolean isInCreateMode() {
        return this.inner().id() == null;
    }

    @Override
    public DateTime changedTime() {
        return this.inner().changedTime();
    }

    @Override
    public DateTime createdTime() {
        return this.inner().createdTime();
    }

    @Override
    public String id() {
        return this.inner().id();
    }

    @Override
    public KeyVaultKeyReference keyVal() {
        return this.inner().key();
    }

    @Override
    public String location() {
        return this.inner().location();
    }

    @Override
    public Object metadata() {
        return this.inner().metadata();
    }

    @Override
    public String name() {
        return this.inner().name();
    }

    @Override
    public String publicCertificate() {
        return this.inner().publicCertificate();
    }

    @Override
    public Map<String, String> tags() {
        return this.inner().getTags();
    }

    @Override
    public String type() {
        return this.inner().type();
    }

    @Override
    public IntegrationAccountCertificateImpl withExistingIntegrationAccount(String resourceGroupName, String integrationAccountName) {
        this.resourceGroupName = resourceGroupName;
        this.integrationAccountName = integrationAccountName;
        return this;
    }

    @Override
    public IntegrationAccountCertificateImpl withKey(KeyVaultKeyReference key) {
        this.inner().withKey(key);
        return this;
    }

    @Override
    public IntegrationAccountCertificateImpl withLocation(String location) {
        this.inner().withLocation(location);
        return this;
    }

    @Override
    public IntegrationAccountCertificateImpl withMetadata(Object metadata) {
        this.inner().withMetadata(metadata);
        return this;
    }

    @Override
    public IntegrationAccountCertificateImpl withPublicCertificate(String publicCertificate) {
        this.inner().withPublicCertificate(publicCertificate);
        return this;
    }

    @Override
    public IntegrationAccountCertificateImpl withTags(Map<String, String> tags) {
        this.inner().withTags(tags);
        return this;
    }

}


text:
/* terminal.c -- controlling the terminal with termcap. */

/* Copyright (C) 1996 Free Software Foundation, Inc.

   This file is part of the GNU Readline Library, a library for
   reading lines of text with interactive input and history editing.

   The GNU Readline Library is free software; you can redistribute it
   and/or modify it under the terms of the GNU General Public License
   as published by the Free Software Foundation; either version 2, or
   (at your option) any later version.

   The GNU Readline Library is distributed in the hope that it will be
   useful, but WITHOUT ANY WARRANTY; without even the implied warranty
   of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   The GNU General Public License is often shipped with GNU software, and
   is generally kept in a file called COPYING or LICENSE.  If you do not
   have a copy of the license, write to the Free Software Foundation,
   59 Temple Place, Suite 330, Boston, MA 02111 USA. */
#define READLINE_LIBRARY

#if defined (HAVE_CONFIG_H)
#  include <config.h>
#endif

#include <sys/types.h>
#include "posixstat.h"
#include <fcntl.h>
#if defined (HAVE_SYS_FILE_H)
#  include <sys/file.h>
#endif /* HAVE_SYS_FILE_H */

#if defined (HAVE_UNISTD_H)
#  include <unistd.h>
#endif /* HAVE_UNISTD_H */

#if defined (HAVE_STDLIB_H)
#  include <stdlib.h>
#else
#  include "ansi_stdlib.h"
#endif /* HAVE_STDLIB_H */

#if defined (HAVE_LOCALE_H)
#  include <locale.h>
#endif

#include <stdio.h>

/* System-specific feature definitions and include files. */
#include "rldefs.h"

#if defined (GWINSZ_IN_SYS_IOCTL) && !defined (TIOCGWINSZ)
#  include <sys/ioctl.h>
#endif /* GWINSZ_IN_SYS_IOCTL && !TIOCGWINSZ */

#include "rltty.h"
#include "tcap.h"

/* Some standard library routines. */
#include "readline.h"
#include "history.h"

#include "rlprivate.h"
#include "rlshell.h"
#include "xmalloc.h"

/* **************************************************************** */
/*								    */
/*			Terminal and Termcap			    */
/*								    */
/* **************************************************************** */

static char *term_buffer = (char *)NULL;
static char *term_string_buffer = (char *)NULL;

static int tcap_initialized;

#if !defined (__linux__)
#  if defined (__EMX__) || defined (NEED_EXTERN_PC)
extern
#  endif /* __EMX__ || NEED_EXTERN_PC */
char PC, *BC, *UP;
#endif /* __linux__ */

/* Some strings to control terminal actions.  These are output by tputs (). */
char *_rl_term_clreol;
char *_rl_term_clrpag;
char *_rl_term_cr;
char *_rl_term_backspace;
char *_rl_term_goto;
char *_rl_term_pc;

/* Non-zero if we determine that the terminal can do character insertion. */
int _rl_terminal_can_insert = 0;

/* How to insert characters. */
char *_rl_term_im;
char *_rl_term_ei;
char *_rl_term_ic;
char *_rl_term_ip;
char *_rl_term_IC;

/* How to delete characters. */
char *_rl_term_dc;
char *_rl_term_DC;

#if defined (HACK_TERMCAP_MOTION)
char *_rl_term_forward_char;
#endif  /* HACK_TERMCAP_MOTION */

/* How to go up a line. */
char *_rl_term_up;

/* A visible bell; char if the terminal can be made to flash the screen. */
static char *_rl_visible_bell;

/* Non-zero means the terminal can auto-wrap lines. */
int _rl_term_autowrap;

/* Non-zero means that this terminal has a meta key. */
static int term_has_meta;

/* The sequences to write to turn on and off the meta key, if this
   terminal has one. */
static char *_rl_term_mm;
static char *_rl_term_mo;

/* The key sequences output by the arrow keys, if this terminal has any. */
static char *_rl_term_ku;
static char *_rl_term_kd;
static char *_rl_term_kr;
static char *_rl_term_kl;

/* How to initialize and reset the arrow keys, if this terminal has any. */
static char *_rl_term_ks;
static char *_rl_term_ke;

/* The key sequences sent by the Home and End keys, if any. */
static char *_rl_term_kh;
static char *_rl_term_kH;

/* Variables that hold the screen dimensions, used by the display code. */
int _rl_screenwidth, _rl_screenheight, _rl_screenchars;

/* Non-zero means the user wants to enable the keypad. */
int _rl_enable_keypad;

/* Non-zero means the user wants to enable a meta key. */
int _rl_enable_meta = 1;

#if defined (__EMX__)
static void
_emx_get_screensize (swp, shp)
     int *swp, *shp;
{
  int sz[2];

  _scrsize (sz);

  if (swp)
    *swp = sz[0];
  if (shp)
    *shp = sz[1];
}
#endif

/* Get readline's idea of the screen size.  TTY is a file descriptor open
   to the terminal.  If IGNORE_ENV is true, we do not pay attention to the
   values of $LINES and $COLUMNS.  The tests for TERM_STRING_BUFFER being
   non-null serve to check whether or not we have initialized termcap. */
void
_rl_get_screen_size (tty, ignore_env)
     int tty, ignore_env;
{
  char *ss;
#if defined (TIOCGWINSZ)
  struct winsize window_size;
#endif /* TIOCGWINSZ */

#if defined (TIOCGWINSZ)
  if (ioctl (tty, TIOCGWINSZ, &window_size) == 0)
    {
      _rl_screenwidth = (int) window_size.ws_col;
      _rl_screenheight = (int) window_size.ws_row;
    }
#endif /* TIOCGWINSZ */

#if defined (__EMX__)
  _emx_get_screensize (&_rl_screenwidth, &_rl_screenheight);
#endif

  /* Environment variable COLUMNS overrides setting of "co" if IGNORE_ENV
     is unset. */
  if (_rl_screenwidth <= 0)
    {
      if (ignore_env == 0 && (ss = sh_get_env_value ("COLUMNS")))
	_rl_screenwidth = atoi (ss);

#if !defined (__DJGPP__)
      if (_rl_screenwidth <= 0 && term_string_buffer)
	_rl_screenwidth = tgetnum ("co");
#endif
    }

  /* Environment variable LINES overrides setting of "li" if IGNORE_ENV
     is unset. */
  if (_rl_screenheight <= 0)
    {
      if (ignore_env == 0 && (ss = sh_get_env_value ("LINES")))
	_rl_screenheight = atoi (ss);

#if !defined (__DJGPP__)
      if (_rl_screenheight <= 0 && term_string_buffer)
	_rl_screenheight = tgetnum ("li");
#endif
    }

  /* If all else fails, default to 80x24 terminal. */
  if (_rl_screenwidth <= 1)
    _rl_screenwidth = 80;

  if (_rl_screenheight <= 0)
    _rl_screenheight = 24;

  /* If we're being compiled as part of bash, set the environment
     variables $LINES and $COLUMNS to new values.  Otherwise, just
     do a pair of putenv () or setenv () calls. */
  sh_set_lines_and_columns (_rl_screenheight, _rl_screenwidth);

  if (_rl_term_autowrap == 0)
    _rl_screenwidth--;

  _rl_screenchars = _rl_screenwidth * _rl_screenheight;
}

void
_rl_set_screen_size (rows, cols)
     int rows, cols;
{
  if (rows == 0 || cols == 0)
    return;

  _rl_screenheight = rows;
  _rl_screenwidth = cols;

  if (_rl_term_autowrap == 0)
    _rl_screenwidth--;

  _rl_screenchars = _rl_screenwidth * _rl_screenheight;
}

void
rl_set_screen_size (rows, cols)
     int rows, cols;
{
  _rl_set_screen_size (rows, cols);
}

void
rl_get_screen_size (rows, cols)
     int *rows, *cols;
{
  if (rows)
    *rows = _rl_screenheight;
  if (cols)
    *cols = _rl_screenwidth;
}

void
rl_resize_terminal ()
{
  if (readline_echoing_p)
    {
      _rl_get_screen_size (fileno (rl_instream), 1);
      _rl_redisplay_after_sigwinch ();
    }
}

struct _tc_string {
     const char *tc_var;
     char **tc_value;
};

/* This should be kept sorted, just in case we decide to change the
   search algorithm to something smarter. */
static struct _tc_string tc_strings[] =
{
  { "DC", &_rl_term_DC },
  { "IC", &_rl_term_IC },
  { "ce", &_rl_term_clreol },
  { "cl", &_rl_term_clrpag },
  { "cr", &_rl_term_cr },
  { "dc", &_rl_term_dc },
  { "ei", &_rl_term_ei },
  { "ic", &_rl_term_ic },
  { "im", &_rl_term_im },
  { "kd", &_rl_term_kd },
  { "kh", &_rl_term_kh },	/* home */
  { "kH", &_rl_term_kH },	/* end */
  { "kl", &_rl_term_kl },
  { "kr", &_rl_term_kr },
  { "ku", &_rl_term_ku },
  { "ks", &_rl_term_ks },
  { "ke", &_rl_term_ke },
  { "le", &_rl_term_backspace },
  { "mm", &_rl_term_mm },
  { "mo", &_rl_term_mo },
#if defined (HACK_TERMCAP_MOTION)
  { "nd", &_rl_term_forward_char },
#endif
  { "pc", &_rl_term_pc },
  { "up", &_rl_term_up },
  { "vb", &_rl_visible_bell },
};

#define NUM_TC_STRINGS (sizeof (tc_strings) / sizeof (struct _tc_string))

/* Read the desired terminal capability strings into BP.  The capabilities
   are described in the TC_STRINGS table. */
static void
get_term_capabilities (bp)
     char **bp;
{
#if !defined (__DJGPP__)	/* XXX - doesn't DJGPP have a termcap library? */
  register int i;

  for (i = 0; i < NUM_TC_STRINGS; i++)
#  ifdef __LCC__
    *(tc_strings[i].tc_value) = tgetstr ((char *)tc_strings[i].tc_var, bp);
#  else
    *(tc_strings[i].tc_value) = tgetstr (tc_strings[i].tc_var, bp);
#  endif
#endif
  tcap_initialized = 1;
}

#define CUSTOM_REDISPLAY_FUNC() (rl_redisplay_function != rl_redisplay)
#define CUSTOM_INPUT_FUNC() (rl_getc_function != rl_getc)

int
_rl_init_terminal_io (terminal_name)
     const char *terminal_name;
{
  const char *term;
  char *buffer;
  int tty, tgetent_ret;
  Keymap xkeymap;

  term = terminal_name ? terminal_name : sh_get_env_value ("TERM");
  _rl_term_clrpag = _rl_term_cr = _rl_term_clreol = (char *)NULL;
  tty = rl_instream ? fileno (rl_instream) : 0;
  _rl_screenwidth = _rl_screenheight = 0;

  if (term == 0)
    term = "dumb";

  /* I've separated this out for later work on not calling tgetent at all
     if the calling application has supplied a custom redisplay function,
     (and possibly if the application has supplied a custom input function). */
  if (CUSTOM_REDISPLAY_FUNC())
    {
      tgetent_ret = -1;
    }
  else
    {
      if (term_string_buffer == 0)
	term_string_buffer = (char *)xmalloc(2032);

      if (term_buffer == 0)
	term_buffer = (char *)xmalloc(4080);

      buffer = term_string_buffer;

      tgetent_ret = tgetent (term_buffer, term);
    }

  if (tgetent_ret <= 0)
    {
      FREE (term_string_buffer);
      FREE (term_buffer);
      buffer = term_buffer = term_string_buffer = (char *)NULL;

      _rl_term_autowrap = 0;	/* used by _rl_get_screen_size */

#if defined (__EMX__)
      _emx_get_screensize (&_rl_screenwidth, &_rl_screenheight);
      _rl_screenwidth--;
#else /* !__EMX__ */
      _rl_get_screen_size (tty, 0);
#endif /* !__EMX__ */

      /* Defaults. */
      if (_rl_screenwidth <= 0 || _rl_screenheight <= 0)
        {
	  _rl_screenwidth = 79;
	  _rl_screenheight = 24;
        }

      /* Everything below here is used by the redisplay code (tputs). */
      _rl_screenchars = _rl_screenwidth * _rl_screenheight;
      _rl_term_cr = "\r";
      _rl_term_im = _rl_term_ei = _rl_term_ic = _rl_term_IC = (char *)NULL;
      _rl_term_up = _rl_term_dc = _rl_term_DC = _rl_visible_bell = (char *)NULL;
      _rl_term_ku = _rl_term_kd = _rl_term_kl = _rl_term_kr = (char *)NULL;
      _rl_term_mm = _rl_term_mo = (char *)NULL;
#if defined (HACK_TERMCAP_MOTION)
      term_forward_char = (char *)NULL;
#endif
      _rl_terminal_can_insert = term_has_meta = 0;

      /* Reasonable defaults for tgoto().  Readline currently only uses
         tgoto if _rl_term_IC or _rl_term_DC is defined, but just in case we
         change that later... */
      PC = '\0';
      BC = _rl_term_backspace = "\b";
      UP = _rl_term_up;

      return 0;
    }

  get_term_capabilities (&buffer);

  /* Set up the variables that the termcap library expects the application
     to provide. */
  PC = _rl_term_pc ? *_rl_term_pc : 0;
  BC = _rl_term_backspace;
  UP = _rl_term_up;

  if (!_rl_term_cr)
    _rl_term_cr = "\r";

  _rl_term_autowrap = tgetflag ("am") && tgetflag ("xn");

  _rl_get_screen_size (tty, 0);

  /* "An application program can assume that the terminal can do
      character insertion if *any one of* the capabilities `IC',
      `im', `ic' or `ip' is provided."  But we can't do anything if
      only `ip' is provided, so... */
  _rl_terminal_can_insert = (_rl_term_IC || _rl_term_im || _rl_term_ic);

  /* Check to see if this terminal has a meta key and clear the capability
     variables if there is none. */
  term_has_meta = (tgetflag ("km") || tgetflag ("MT"));
  if (!term_has_meta)
    _rl_term_mm = _rl_term_mo = (char *)NULL;

  /* Attempt to find and bind the arrow keys.  Do not override already
     bound keys in an overzealous attempt, however. */
  xkeymap = _rl_keymap;

  _rl_keymap = emacs_standard_keymap;
  _rl_bind_if_unbound (_rl_term_ku, rl_get_previous_history);
  _rl_bind_if_unbound (_rl_term_kd, rl_get_next_history);
  _rl_bind_if_unbound (_rl_term_kr, rl_forward);
  _rl_bind_if_unbound (_rl_term_kl, rl_backward);

  _rl_bind_if_unbound (_rl_term_kh, rl_beg_of_line);	/* Home */
  _rl_bind_if_unbound (_rl_term_kH, rl_end_of_line);	/* End */

#if defined (VI_MODE)
  _rl_keymap = vi_movement_keymap;
  _rl_bind_if_unbound (_rl_term_ku, rl_get_previous_history);
  _rl_bind_if_unbound (_rl_term_kd, rl_get_next_history);
  _rl_bind_if_unbound (_rl_term_kr, rl_forward);
  _rl_bind_if_unbound (_rl_term_kl, rl_backward);

  _rl_bind_if_unbound (_rl_term_kh, rl_beg_of_line);	/* Home */
  _rl_bind_if_unbound (_rl_term_kH, rl_end_of_line);	/* End */
#endif /* VI_MODE */

  _rl_keymap = xkeymap;

  return 0;
}

char *
rl_get_termcap (cap)
     const char *cap;
{
  register int i;

  if (tcap_initialized == 0)
    return ((char *)NULL);
  for (i = 0; i < NUM_TC_STRINGS; i++)
    {
      if (tc_strings[i].tc_var[0] == cap[0] && strcmp (tc_strings[i].tc_var, cap) == 0)
        return *(tc_strings[i].tc_value);
    }
  return ((char *)NULL);
}

/* Re-initialize the terminal considering that the TERM/TERMCAP variable
   has changed. */
int
rl_reset_terminal (terminal_name)
     const char *terminal_name;
{
  _rl_init_terminal_io (terminal_name);
  return 0;
}

/* A function for the use of tputs () */
#ifdef _MINIX
void
_rl_output_character_function (c)
     int c;
{
  putc (c, _rl_out_stream);
}
#else /* !_MINIX */
int
_rl_output_character_function (c)
     int c;
{
  return putc (c, _rl_out_stream);
}
#endif /* !_MINIX */

/* Write COUNT characters from STRING to the output stream. */
void
_rl_output_some_chars (string, count)
     const char *string;
     int count;
{
  fwrite (string, 1, count, _rl_out_stream);
}

/* Move the cursor back. */
int
_rl_backspace (count)
     int count;
{
  register int i;

  if (_rl_term_backspace)
    for (i = 0; i < count; i++)
      tputs (_rl_term_backspace, 1, _rl_output_character_function);
  else
    for (i = 0; i < count; i++)
      putc ('\b', _rl_out_stream);
  return 0;
}

/* Move to the start of the next line. */
int
rl_crlf ()
{
#if defined (NEW_TTY_DRIVER)
  if (_rl_term_cr)
    tputs (_rl_term_cr, 1, _rl_output_character_function);
#endif /* NEW_TTY_DRIVER */
  putc ('\n', _rl_out_stream);
  return 0;
}

/* Ring the terminal bell. */
int
rl_ding ()
{
  if (readline_echoing_p)
    {
      switch (_rl_bell_preference)
        {
	case NO_BELL:
	default:
	  break;
	case VISIBLE_BELL:
	  if (_rl_visible_bell)
	    {
	      tputs (_rl_visible_bell, 1, _rl_output_character_function);
	      break;
	    }
	  /* FALLTHROUGH */
	case AUDIBLE_BELL:
	  fprintf (stderr, "\007");
	  fflush (stderr);
	  break;
        }
      return (0);
    }
  return (-1);
}

/* **************************************************************** */
/*								    */
/*	 	Controlling the Meta Key and Keypad		    */
/*								    */
/* **************************************************************** */

void
_rl_enable_meta_key ()
{
#if !defined (__DJGPP__)
  if (term_has_meta && _rl_term_mm)
    tputs (_rl_term_mm, 1, _rl_output_character_function);
#endif
}

void
_rl_control_keypad (on)
     int on;
{
#if !defined (__DJGPP__)
  if (on && _rl_term_ks)
    tputs (_rl_term_ks, 1, _rl_output_character_function);
  else if (!on && _rl_term_ke)
    tputs (_rl_term_ke, 1, _rl_output_character_function);
#endif
}


text:
#ifndef yyHEADER_H
#define yyHEADER_H 1
#define yyIN_HEADER 1

#line 6 "/Users/dracks/Documents/Programacio/Obj-Fenix/Obj-Fenix/compilador/build/flex.yy.h"

#line 8 "/Users/dracks/Documents/Programacio/Obj-Fenix/Obj-Fenix/compilador/build/flex.yy.h"

#define  YY_INT_ALIGNED short int

/* A lexical scanner generated by flex */

#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 5
#define YY_FLEX_SUBMINOR_VERSION 35
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif

/* First, we deal with  platform-specific or compiler-specific issues. */

/* begin standard C headers. */
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>

/* end standard C headers. */

/* flex integer type definitions */

#ifndef FLEXINT_H
#define FLEXINT_H

/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */

#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L

/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
 * if you want the limit (max/min) macros for int types.
 */
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS 1
#endif

#include <inttypes.h>
typedef int8_t flex_int8_t;
typedef uint8_t flex_uint8_t;
typedef int16_t flex_int16_t;
typedef uint16_t flex_uint16_t;
typedef int32_t flex_int32_t;
typedef uint32_t flex_uint32_t;
#else
typedef signed char flex_int8_t;
typedef short int flex_int16_t;
typedef int flex_int32_t;
typedef unsigned char flex_uint8_t;
typedef unsigned short int flex_uint16_t;
typedef unsigned int flex_uint32_t;
#endif /* ! C99 */

/* Limits of integral types. */
#ifndef INT8_MIN
#define INT8_MIN               (-128)
#endif
#ifndef INT16_MIN
#define INT16_MIN              (-32767-1)
#endif
#ifndef INT32_MIN
#define INT32_MIN              (-2147483647-1)
#endif
#ifndef INT8_MAX
#define INT8_MAX               (127)
#endif
#ifndef INT16_MAX
#define INT16_MAX              (32767)
#endif
#ifndef INT32_MAX
#define INT32_MAX              (2147483647)
#endif
#ifndef UINT8_MAX
#define UINT8_MAX              (255U)
#endif
#ifndef UINT16_MAX
#define UINT16_MAX             (65535U)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX             (4294967295U)
#endif

#endif /* ! FLEXINT_H */

#ifdef __cplusplus

/* The "const" storage-class-modifier is valid. */
#define YY_USE_CONST

#else	/* ! __cplusplus */

/* C99 requires __STDC__ to be defined as 1. */
#if defined (__STDC__)

#define YY_USE_CONST

#endif	/* defined (__STDC__) */
#endif	/* ! __cplusplus */

#ifdef YY_USE_CONST
#define yyconst const
#else
#define yyconst
#endif

/* Size of default input buffer. */
#ifndef YY_BUF_SIZE
#define YY_BUF_SIZE 16384
#endif

#ifndef YY_TYPEDEF_YY_BUFFER_STATE
#define YY_TYPEDEF_YY_BUFFER_STATE
typedef struct yy_buffer_state *YY_BUFFER_STATE;
#endif

#ifndef YY_TYPEDEF_YY_SIZE_T
#define YY_TYPEDEF_YY_SIZE_T
typedef size_t yy_size_t;
#endif

extern yy_size_t yyleng;

extern FILE *yyin, *yyout;

#ifndef YY_STRUCT_YY_BUFFER_STATE
#define YY_STRUCT_YY_BUFFER_STATE
struct yy_buffer_state
	{
	FILE *yy_input_file;

	char *yy_ch_buf;		/* input buffer */
	char *yy_buf_pos;		/* current position in input buffer */

	/* Size of input buffer in bytes, not including room for EOB
	 * characters.
	 */
	yy_size_t yy_buf_size;

	/* Number of characters read into yy_ch_buf, not including EOB
	 * characters.
	 */
	yy_size_t yy_n_chars;

	/* Whether we "own" the buffer - i.e., we know we created it,
	 * and can realloc() it to grow it, and should free() it to
	 * delete it.
	 */
	int yy_is_our_buffer;

	/* Whether this is an "interactive" input source; if so, and
	 * if we're using stdio for input, then we want to use getc()
	 * instead of fread(), to make sure we stop fetching input after
	 * each newline.
	 */
	int yy_is_interactive;

	/* Whether we're considered to be at the beginning of a line.
	 * If so, '^' rules will be active on the next match, otherwise
	 * not.
	 */
	int yy_at_bol;

    int yy_bs_lineno; /**< The line count. */
    int yy_bs_column; /**< The column count. */

	/* Whether to try to fill the input buffer when we reach the
	 * end of it.
	 */
	int yy_fill_buffer;

	int yy_buffer_status;

	};
#endif /* !YY_STRUCT_YY_BUFFER_STATE */

void yyrestart (FILE *input_file  );
void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer  );
YY_BUFFER_STATE yy_create_buffer (FILE *file,int size  );
void yy_delete_buffer (YY_BUFFER_STATE b  );
void yy_flush_buffer (YY_BUFFER_STATE b  );
void yypush_buffer_state (YY_BUFFER_STATE new_buffer  );
void yypop_buffer_state (void );

YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size  );
YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str  );
YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,yy_size_t len  );

void *yyalloc (yy_size_t  );
void *yyrealloc (void *,yy_size_t  );
void yyfree (void *  );

/* Begin user sect3 */

extern int yylineno;

extern char *yytext;
#define yytext_ptr yytext

#ifdef YY_HEADER_EXPORT_START_CONDITIONS
#define INITIAL 0
#define comments 1

#endif

#ifndef YY_NO_UNISTD_H
/* Special case for "unistd.h", since it is non-ANSI. We include it way
 * down here because we want the user's section 1 to have been scanned first.
 * The user has a chance to override it with an option.
 */
#include <unistd.h>
#endif

#ifndef YY_EXTRA_TYPE
#define YY_EXTRA_TYPE void *
#endif

/* Accessor methods to globals.
   These are made visible to non-reentrant scanners for convenience. */

int yylex_destroy (void );

int yyget_debug (void );

void yyset_debug (int debug_flag  );

YY_EXTRA_TYPE yyget_extra (void );

void yyset_extra (YY_EXTRA_TYPE user_defined  );

FILE *yyget_in (void );

void yyset_in  (FILE * in_str  );

FILE *yyget_out (void );

void yyset_out  (FILE * out_str  );

yy_size_t yyget_leng (void );

char *yyget_text (void );

int yyget_lineno (void );

void yyset_lineno (int line_number  );

/* Macros after this point can all be overridden by user definitions in
 * section 1.
 */

#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
extern "C" int yywrap (void );
#else
extern int yywrap (void );
#endif
#endif

#ifndef yytext_ptr
static void yy_flex_strncpy (char *,yyconst char *,int );
#endif

#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * );
#endif

#ifndef YY_NO_INPUT

#endif

/* Amount of stuff to slurp up with each read. */
#ifndef YY_READ_BUF_SIZE
#define YY_READ_BUF_SIZE 8192
#endif

/* Number of entries by which start-condition stack grows. */
#ifndef YY_START_STACK_INCR
#define YY_START_STACK_INCR 25
#endif

/* Default declaration of generated scanner - a define so the user can
 * easily add parameters.
 */
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1

extern int yylex (void);

#define YY_DECL int yylex (void)
#endif /* !YY_DECL */

/* yy_get_previous_state - get the state just before the EOB char was reached */

#undef YY_NEW_FILE
#undef YY_FLUSH_BUFFER
#undef yy_set_bol
#undef yy_new_buffer
#undef yy_set_interactive
#undef YY_DO_BEFORE_ACTION

#ifdef YY_DECL_IS_OURS
#undef YY_DECL_IS_OURS
#undef YY_DECL
#endif

#line 99 "/Users/dracks/Documents/Programacio/Obj-Fenix/Obj-Fenix/compilador/src/lexical_analyzer.l"

#line 318 "/Users/dracks/Documents/Programacio/Obj-Fenix/Obj-Fenix/compilador/build/flex.yy.h"
#undef yyIN_HEADER
#endif /* yyHEADER_H */


text:
"""
Skinnable web apps.

The most important requirement for this all is that the content pages
must not inherit the skin. This ensures the content need not know
about the used skin.
"""


text:
package ru.aveselov.lesson5.refbook;

/**
 * Interface for reference book's element.
 *
 * @author Veselov Alexey.
 * @version 1.00
 * @since 27.12.2016
 * @param <K> - type of KEY.
 * @param <V> - type of VALUE.
 */
public interface RefBookElement<K, V> {

    /**
     * Get key from element.
     * @return key.
     */
    K getKey();

    /**
     * Get value from element.
     * @return value.
     */
    V getValue();
}


text:
require 'spec_helper'

describe Server do
  it "is valid with just a name" do
    Server.new.should_not be_valid
    Server.new(name: "my-server").should be_valid
  end

  describe "#processor_*" do
    it "has a intelligent default value for #processor_system_count" do
      Server.new(name: "srv-01", processor_system_count: 36).processor_system_count.should == 36
      Server.new(name: "srv-01", processor_physical_count: 5).processor_system_count.should == 5
      Server.new(name: "srv-01", processor_physical_count: 5, processor_cores_per_cpu: 3).processor_system_count.should == 15
      Server.new(name: "srv-01").processor_system_count.should == 1
    end
  end

  describe "#ipaddresses" do
    let(:server) { FactoryGirl.create(:server) }

    it "updates with an address as a string" do
      server.ipaddresses = [ Ipaddress.new(address: "192.168.99.99", main: true) ]
      server.save
      server.reload
      server.read_attribute(:ipaddress).should eq 3232260963
      server.ipaddress.should eq "192.168.99.99"
    end

    it "updates with an address as a number between 1 and 32" do
      server.ipaddresses = [ Ipaddress.new(address: "24", main: true) ]
      server.save
      server.reload.should have(1).ipaddresses
      server.ipaddresses.first.address.should eq "255.255.255.0"
      server.read_attribute(:ipaddress).should eq 4294967040
      server.ipaddress.should eq "255.255.255.0"
    end

    it "leaves ip empty if no main ipaddress" do
      server.ipaddresses = [ Ipaddress.new(address: "10.0.0.1", main: true) ]
      server.save
      server.reload.ipaddress.should == "10.0.0.1"
      server.ipaddresses = [ Ipaddress.new(address: "24") ]
      server.save
      server.reload.ipaddress.should be_nil
      server.ipaddresses = [ ]
      server.save
      server.reload.ipaddress.should be_nil
    end
  end

  describe "#to_param" do
    it "outputs name if name is alphanum" do
      m = Server.create(name: "blah")
      m.to_param.should eq "blah"
      m = Server.create(name: "Test-3")
      m.to_param.should eq "Test-3"
    end

    it "outpus mongodb's id if not" do
      m = Server.create(name: "( bizarr# n@me )")
      m.to_param.should eq m.id.to_s
    end
  end

  describe "#find" do
    let(:server) { FactoryGirl.create(:server) }

    it "works normally with ids" do
      Server.find(server.id).should eq server
      Server.find(server.id.to_s).should eq server
    end

    it "works with identifiers too" do
      Server.find(server.to_param).should eq server
    end

    it "raises an exception if no existing record with this identifier" do
      lambda { Server.find(0) }.should raise_error Mongoid::Errors::DocumentNotFound
      lambda { Server.find("non-existent") }.should raise_error Mongoid::Errors::DocumentNotFound #new with mongoid 3
    end

    it "doesn't care if a server was previously named with identifier" do
      old_server = FactoryGirl.create(:server, name: "www")
      old_server.update_attribute(:name, "www-old")
      new_server = FactoryGirl.create(:server, name: "www")
      Server.find("www").should == new_server
    end
  end

  describe "scopes" do
    let!(:site1) { Site.create!(name: "eu-west") }
    let!(:site2) { Site.create!(name: "us-east") }
    let!(:rack1) { PhysicalRack.create!(name: "rack-1-eu", site_id: site1.id.to_s) }
    let!(:rack2) { PhysicalRack.create!(name: "rack-2-us", site_id: site2.id.to_s) }
    let!(:maint) { Company.create!(name: "Computer shop", is_maintainer: true,
                                   email_infos: [EmailInfo.new(value: "blah@example.net")],
                                   phone_infos: [PhoneInfo.new(value: "555-123456")]) }
    let!(:os)    { OperatingSystem.create!(name: "Linux") }
    let!(:s1)    { Server.create!(name: "srv-app-01", physical_rack_id: rack1.id.to_s,
                                       maintainer_id: maint.id.to_s,
                                       operating_system_id: os.id.to_s) }
    let!(:s2)    { Server.create!(name: "srv-app-02", physical_rack_id: rack2.id.to_s,
                                       virtual: true, puppetversion: nil) }
    let!(:s3)    { Server.create!(name: "srv-db-01", physical_rack_id: rack1.id.to_s,
                                       puppetversion: "0.24.5") }

    it "filters servers by rack" do
      Server.count.should eq 3
      Server.by_rack(rack1.id.to_s).count.should eq 2
      Server.by_rack(rack2.id.to_s).count.should eq 1
    end

    it "filters servers by site" do
      Server.count.should eq 3
      Server.by_site(site1.id.to_s).count.should eq 2
      Server.by_site(site2.id.to_s).count.should eq 1
    end

    it "filters servers by location" do
      Server.by_location("site-#{site1.id}").should eq Server.by_site(site1.id.to_s)
      Server.by_location("site-0").should eq []
      Server.by_location("rack-#{rack1.id}").should eq Server.by_rack(rack1.id.to_s)
      Server.by_location("rack-0").should eq []
    end

    it "ignores the filter by location if the parameter is invalid" do
      invalid_result = Server.by_location("invalid location")
      invalid_result.should eq Server.scoped
      invalid_result.count.should eq 3
    end

    it "filters servers by maintainer" do
      Server.by_maintainer(maint.id.to_s).should eq [s1]
    end

    it "filters servers by system" do
      Server.by_system(os.id.to_s).to_a.should eq [s1]
    end

    it "filters servers by virtual" do
      Server.by_virtual(1).to_a.should eq [s2]
    end

    it "returns server with puppet installed" do
      Server.by_puppet(1).to_a.should eq [s3]
    end

    it "returns real servers only" do
      s4 = Server.create!(name: "just-a-name")
      s5 = Server.create!(name: "switch-01", network_device: true)
      s6 = Server.create!(name: "fw-01", network_device: false)
      Server.real_servers.to_a.should =~ [s1, s2, s3, s4, s6]
    end

    it "denormalizes phone_info_value" do
      s1.maintainer_phone.should == "555-123456"
    end

    it "denormalizes email_info_value" do
      s1.maintainer_email.should == "blah@example.net"
    end

    describe "#find_or_generate" do
      let!(:server) { Server.create(name: "rake-server") }

      it "finds server by name in priority" do
        srv = Server.find_or_generate("rake-server")
        srv.should eq server
        srv.just_created.should be_false
      end

      it "generates a new server if no match with name and identifier" do
        server = Server.where(name: "rake-server3").first
        server.should be_nil
        lambda { server = Server.find_or_generate("rake-server3") }.should change(Server, :count).by(+1)
        server.should be_persisted
        server.just_created.should be_true
      end
    end
  end

  describe "#stock?" do
    it "is truthy only if it's in a rack that is marked as stock" do
      server = FactoryGirl.create(:server)
      rack = FactoryGirl.create(:rack1)
      server.stock?.should be_false
      server.physical_rack = rack
      rack.stock?.should be_false
      server.stock?.should be_false
      rack.status = PhysicalRack::STATUS_STOCK
      rack.stock?.should be_true
      server.stock?.should be_true
    end
  end

  describe ".not_backuped" do
    let!(:server) { FactoryGirl.create(:server) }
    let!(:vm)     { FactoryGirl.create(:virtual) }

    it "includes everything by default" do
      Server.not_backuped.should include(server)
      Server.not_backuped.should include(vm)
    end

    it "does not include active servers which have an associated backup job" do
      Server.not_backuped.should include(server)
      server.backup_jobs << BackupJob.create(hierarchy: "/")
      Server.not_backuped.should_not include(server)
    end

    it "does not include servers which have a backup_exclusion" do
      Server.not_backuped.should include(server)
      BackupExclusion.create!(reason: "backuped an other way", servers: [server])
      Server.not_backuped.to_a.should_not include(server)
    end

    it "does not include net devices" do
      Server.not_backuped.should include(server)
      server.update_attribute(:network_device, true)
      Server.not_backuped.should_not include(server)
    end

    it "does not include stock servers" do
      Server.not_backuped.should include(server)
      rack = PhysicalRack.create!(name: "rack-1", site_id: FactoryGirl.create(:room).id.to_s, status: PhysicalRack::STATUS_STOCK)
      server.physical_rack = rack
      server.save
      Server.not_backuped.should_not include(server)
    end
  end

  describe "#can_be_managed_with_puppet?" do
    it "requires having an compatible os defined" do
      srv = FactoryGirl.create(:server)
      srv.operating_system.should be_blank
      srv.can_be_managed_with_puppet?.should be_false
      sys = OperatingSystem.create(name: "Ubuntu 11.10")
      srv.update_attribute(:operating_system_id, sys.id.to_s)
      srv.reload.can_be_managed_with_puppet?.should be_false
      sys.update_attribute(:managed_with_puppet, true)
      srv.reload.can_be_managed_with_puppet?.should be_true
    end
  end

  describe "#application_instances" do
    it "can have many application instance ids" do
      srv = FactoryGirl.create(:server)
      srv.application_instance_ids.should eq []
      srv.application_instances.should eq []
    end
  end

  describe "#hardware_model" do
    it "gets #model (but model is a reserved word for draper)" do
      srv = Server.create!(name: "srv-01", model: "Dell PE 2950")
      srv.hardware_model.should == "Dell PE 2950"
    end
  end

  describe "mongoid_denormalized" do
    it "updates #physical_rack_full_name correctly" do
      srv = Server.find_or_create_by(name: "srv-01")
      rack = PhysicalRack.create!(name: "Rack-01", site: Site.create!(name: "Room-A"))
      rack2 = PhysicalRack.create!(name: "Rack-02")
      srv.physical_rack_full_name.should be_blank

      srv.update_attributes(physical_rack_id: rack2.id)
      srv.reload.physical_rack_full_name.should == "Rack-02"

      srv.update_attributes(physical_rack_id: rack.id)
      srv.reload.physical_rack_full_name.should == "Room-A - Rack-01"

      rack.reload.update_attributes(name: "RCK01")
      srv.reload.physical_rack_full_name.should == "Room-A - RCK01"

      rack.destroy
      srv.reload.physical_rack_full_name.should be_blank
    end

    it "updates #operating_system_name correctly" do
      srv = Server.find_or_create_by(name: "srv-01")
      sys = OperatingSystem.create!(name: "Linux")
      srv.operating_system_name.should be_blank

      srv.update_attributes(operating_system_id: sys.id)
      srv.reload.operating_system_name.should == "Linux"

      sys.reload.update_attributes(name: "GNU/Linux")
      srv.reload.operating_system_name.should == "GNU/Linux"

      sys.destroy
      srv.reload.operating_system_name.should be_blank
    end
  end
end


text:
package net.nogotofail.mitmtester;

import android.content.Context;
import android.location.Location;
import com.google.android.gms.ads.identifier.AdvertisingIdClient;
import net.nogotofail.mitmtester.util.ClientProperties;

/**
 * Extension of BackgroundTest class with awareness of application context.
 * Note. Application context is needed to access system resources (Device IDs &
 * location) and application resources (strings.xml).
 */
public abstract class BackgroundTestForHttpPii extends BackgroundTest {

    protected static final String HTTP_TARGET = "http://android.com/";
    protected static final String HTTPS_TARGET = "https://google.com/";
    protected static final int CONNECTION_TIMEOUT = 10000;

    protected String android_id, google_ad_id;
    protected AdvertisingIdClient.Info advertising_info;
    protected Location client_location;
    protected String location_longitude, location_latitude;
    protected String email;

    private Context mContext;

    protected BackgroundTestForHttpPii(Context app_context) {
        mContext = app_context;
    }

    protected abstract void runTest() throws Exception;

    protected Context getContext(){
        return this.mContext;
    }

    protected void FetchPIITestData() {
        android_id = ClientProperties.getAndroidId(mContext);
        advertising_info = ClientProperties.getAdvertisingId(mContext);
        google_ad_id = advertising_info.getId();
        client_location = ClientProperties.getDeviceLocation(mContext);
        location_longitude = String.valueOf(client_location.getLongitude());
        location_latitude = String.valueOf(client_location.getLatitude());
        email = mContext.getString(R.string.pii_detail_email);
    }
}


text:
package dberror

import (
	"fmt"
	"regexp"
	"strings"
	"unicode"
	"unicode/utf8"

	"github.com/lib/pq"
)

// See http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html for
// a full listing of the error codes present here.
const (
	CodeNumericValueOutOfRange    = "22003"
	CodeInvalidTextRepresentation = "22P02"
	CodeNotNullViolation          = "23502"
	CodeForeignKeyViolation       = "23503"
	CodeUniqueViolation           = "23505"
	CodeCheckViolation            = "23514"
	CodeLockNotAvailable          = "55P03"
)

// Error is a human-readable database error. Message should always be a
// non-empty, readable string, and is returned when you call err.Error(). The
// other fields may or may not be empty.
type Error struct {
	Message    string
	Code       string
	Constraint string
	Severity   string
	Routine    string
	Table      string
	Detail     string
	Column     string
}

func (dbe *Error) Error() string {
	return dbe.Message
}

// Constraint is a custom database check constraint you've defined, like "CHECK
// balance > 0". Postgres doesn't define a very useful message for constraint
// failures (new row for relation "accounts" violates check constraint), so you
// can define your own. The Name should be the name of the constraint in the
// database. Define GetError to provide your own custom error handler for this
// constraint failure, with a custom message.
type Constraint struct {
	Name     string
	GetError func(*pq.Error) *Error
}

var constraintMap = map[string]*Constraint{}

// RegisterConstraint tells dberror about your custom constraint and its error
// handling.
func RegisterConstraint(c *Constraint) {
	constraintMap[c.Name] = c
}

// capitalize the first letter in the string
func capitalize(s string) string {
	r, size := utf8.DecodeRuneInString(s)
	return fmt.Sprintf("%c", unicode.ToTitle(r)) + s[size:]
}

var columnFinder *regexp.Regexp
var valueFinder *regexp.Regexp
var foreignKeyFinder *regexp.Regexp

func init() {
	columnFinder = regexp.MustCompile(`Key \((.+)\)=`)
	valueFinder = regexp.MustCompile(`Key \(.+\)=\((.+)\)`)
	foreignKeyFinder = regexp.MustCompile(`not present in table "(.+)"`)
}

// findColumn finds the column in the given pq Detail error string. If the
// column does not exist, the empty string is returned.
//
// detail can look like this:
//    Key (id)=(3c7d2b4a-3fc8-4782-a518-4ce9efef51e7) already exists.
func findColumn(detail string) string {
	results := columnFinder.FindStringSubmatch(detail)
	if len(results) < 2 {
		return ""
	} else {
		return results[1]
	}
}

// findColumn finds the column in the given pq Detail error string. If the
// column does not exist, the empty string is returned.
//
// detail can look like this:
//    Key (id)=(3c7d2b4a-3fc8-4782-a518-4ce9efef51e7) already exists.
func findValue(detail string) string {
	results := valueFinder.FindStringSubmatch(detail)
	if len(results) < 2 {
		return ""
	} else {
		return results[1]
	}
}

// findColumn finds the referenced table in the given pq Detail error string.
// If we can't find the table, we return the empty string.
//
// detail can look like this:
//    Key (account_id)=(91f47e99-d616-4d8c-9c02-cbd13bceac60) is not present in table "accounts"
func findForeignKeyTable(detail string) string {
	results := foreignKeyFinder.FindStringSubmatch(detail)
	if len(results) < 2 {
		return ""
	} else {
		return results[1]
	}
}

// GetError parses a given database error and returns a human-readable
// version of that error. If the error is unknown, it's returned as is,
// however, all errors of type `pq.Error` are re-thrown as an Error, so it's
// impossible to get a `pq.Error` back from this function.
func GetError(err error) error {
	if err == nil {
		return nil
	}
	switch pqerr := err.(type) {
	case *pq.Error:
		switch pqerr.Code {
		case CodeUniqueViolation:
			columnName := findColumn(pqerr.Detail)
			if columnName == "" {
				columnName = "value"
			}
			valueName := findValue(pqerr.Detail)
			var msg string
			if valueName == "" {
				msg = fmt.Sprintf("A %s already exists with that value", columnName)
			} else {
				msg = fmt.Sprintf("A %s already exists with this value (%s)", columnName, valueName)
			}
			dbe := &Error{
				Message:    msg,
				Code:       string(pqerr.Code),
				Severity:   pqerr.Severity,
				Constraint: pqerr.Constraint,
				Table:      pqerr.Table,
				Detail:     pqerr.Detail,
			}
			if columnName != "value" {
				dbe.Column = columnName
			}
			return dbe
		case CodeForeignKeyViolation:
			columnName := findColumn(pqerr.Detail)
			if columnName == "" {
				columnName = "value"
			}
			foreignKeyTable := findForeignKeyTable(pqerr.Detail)
			var tablePart string
			if foreignKeyTable == "" {
				tablePart = "in the parent table"
			} else {
				tablePart = fmt.Sprintf("in the %s table", foreignKeyTable)
			}
			valueName := findValue(pqerr.Detail)
			var msg string
			if valueName == "" {
				msg = fmt.Sprintf("Can't save to %s because the %s isn't present %s", pqerr.Table, columnName, tablePart)
			} else {
				msg = fmt.Sprintf("Can't save to %s because the %s (%s) isn't present %s", pqerr.Table, columnName, valueName, tablePart)
			}
			return &Error{
				Message:    msg,
				Code:       string(pqerr.Code),
				Column:     pqerr.Column,
				Constraint: pqerr.Constraint,
				Table:      pqerr.Table,
				Routine:    pqerr.Routine,
				Severity:   pqerr.Severity,
			}
		case CodeNumericValueOutOfRange:
			msg := strings.Replace(pqerr.Message, "out of range", "too large or too small", 1)
			return &Error{
				Message:  capitalize(msg),
				Code:     string(pqerr.Code),
				Severity: pqerr.Severity,
			}
		case CodeInvalidTextRepresentation:
			msg := pqerr.Message
			// Postgres tweaks with the message, play whack-a-mole until we
			// figure out a better method of dealing with these.
			if !strings.Contains(pqerr.Message, "invalid input syntax for type") {
				msg = strings.Replace(pqerr.Message, "input syntax for", "input syntax for type", 1)
			}
			msg = strings.Replace(msg, "input value for enum ", "", 1)
			msg = strings.Replace(msg, "invalid", "Invalid", 1)
			return &Error{
				Message:  msg,
				Code:     string(pqerr.Code),
				Severity: pqerr.Severity,
			}
		case CodeNotNullViolation:
			msg := fmt.Sprintf("No %[1]s was provided. Please provide a %[1]s", pqerr.Column)
			return &Error{
				Message:  msg,
				Code:     string(pqerr.Code),
				Column:   pqerr.Column,
				Table:    pqerr.Table,
				Severity: pqerr.Severity,
			}
		case CodeCheckViolation:
			c, ok := constraintMap[pqerr.Constraint]
			if ok {
				return c.GetError(pqerr)
			} else {
				return &Error{
					Message:    pqerr.Message,
					Code:       string(pqerr.Code),
					Column:     pqerr.Column,
					Table:      pqerr.Table,
					Severity:   pqerr.Severity,
					Constraint: pqerr.Constraint,
				}
			}
		default:
			return &Error{
				Message:    pqerr.Message,
				Code:       string(pqerr.Code),
				Column:     pqerr.Column,
				Constraint: pqerr.Constraint,
				Table:      pqerr.Table,
				Routine:    pqerr.Routine,
				Severity:   pqerr.Severity,
			}
		}
	default:
		return pqerr
	}
}


text:
CreationTool.prototype = new AbstractTool();

function CreationTool( /* DrawingView */ view, /* Figure */ prototypeFig) {
    var argv = CreationTool.arguments;
    var argc = CreationTool.length;
    this.className = "CreationTool";
    /* Point */
    this.fAnchorPoint = null; // the anchor point of the interaction
    /* Figure */
    this.fCreatedFigure = null; // the currently created figure
    /* Figure */
    this.fPrototype = null; //the prototypical figure that is used to create new figures.
    if (argv.length > 0) this.initCreationTool(view, prototypeFig);
}
//*************
// Initializes a CreationTool with the given prototype.
//*************
CreationTool.prototype.initCreationTool = function(view, prototypeFig) {
    this.initAbstractTool(view);
    if (prototypeFig != undefined) this.fPrototype = prototypeFig;
}
//*************
// Sets the cross hair cursor.
//*************
CreationTool.prototype.activate = function() {
    this.activateCreationTool();
}
CreationTool.prototype.activateCreationTool = function() {
    this.activateAbstractTool();
    this.view().setCursor("crosshair");
}
//*************
// deactivate
//*************
CreationTool.prototype.deactivate = function() {
    this.deactivateCreationTool();
}
CreationTool.prototype.deactivateCreationTool = function() {
    this.deactivateAbstractTool();
}
//*************
// Creates a new figure by cloning the prototype.
//*************
/* Figure */
CreationTool.prototype.createFigure = function(p) {
    if (this.fPrototype == null) {
        alert("No protoype defined");
        return;
    }
    return this.fPrototype.clone();
}
//*************
// Gets the currently created figure
//*************
/* Figure */
CreationTool.prototype.createdFigure = function() {
    return this.fCreatedFigure;
}
//*************
// Creates a new figure by cloning the prototype.
//*************
CreationTool.prototype.mouseDown = function( /* MouseEvent */ e, /* int */ x, /* int */ y) {
    this.creationToolMouseDown(e, x, y);
}
//*************
// Creates a new figure by cloning the prototype.
//*************
CreationTool.prototype.creationToolMouseDown = function( /* MouseEvent */ e, /* int */ x, /* int */ y) {
    this.fAnchorPoint = new Point(x, y);
    this.fCreatedFigure = this.createFigure();
    this.fCreatedFigure.displayBox(this.fAnchorPoint, new Point(x + 1, y + 1));
    this.view().add(this.fCreatedFigure);
    this.view().drawDrawing();
}
//*************
// Adjusts the extent of the created figure
//*************
CreationTool.prototype.mouseDrag = function( /* MouseEvent */ e, /* int */ x, /* int */ y) {
    this.fCreatedFigure.displayBox(this.fAnchorPoint, new Point(x, y));
    // Refresh the figure,...
    if (this.fCreatedFigure.getShape()) {
        this.fCreatedFigure.draw();
    }
}
//*************
// Checks if the created figure is empty. If it is, the figure is removed from the drawing.
//*************
CreationTool.prototype.mouseUp = function( /* MouseEvent */ e, /* int */ x, /* int */ y) {
    if (this.fCreatedFigure == null) return;
    var create = true;
    if (this.fCreatedFigure.isEmpty()) {
        this.drawing().remove(this.fCreatedFigure);
        create = false;
    }
    this.view().drawDrawing();
    this.editor().toolDone();
    if (create) this.fireViewEvent(this.fCreatedFigure, "Create"); // <======================= [ Create View Event]
    this.fCreatedFigure = null;
}


text:
import json
import mock
import os
import re
import traceback

import yaml

from rally import api
from rally.task import scenario
from rally.task import engine
from tests.unit import test

class TaskSampleTestCase(test.TestCase):
    samples_path = os.path.join(
        os.path.dirname(__file__),
        os.pardir, os.pardir, os.pardir,
        "samples", "tasks")

    @mock.patch("rally.task.engine.TaskEngine"
                "._validate_config_semantic")
    def test_schema_is_valid(self,
                             mock_task_engine__validate_config_semantic):
        scenarios = set()

        for dirname, dirnames, filenames in os.walk(self.samples_path):
            for filename in filenames:
                full_path = os.path.join(dirname, filename)

                # NOTE(hughsaunders): Skip non config files
                # (bug https://bugs.launchpad.net/rally/+bug/1314369)
                if not re.search("\.(ya?ml|json)$", filename, flags=re.I):
                    continue

                with open(full_path) as task_file:
                    try:
                        task_config = yaml.safe_load(api.Task.render_template
                                                     (task_file.read()))
                        eng = engine.TaskEngine(task_config,
                                                     mock.MagicMock())
                        eng.validate()
                    except Exception:
                        print(traceback.format_exc())
                        self.fail("Invalid task file: %s" % full_path)
                    else:
                        scenarios.update(task_config.keys())

        missing = set(s.get_name() for s in scenario.Scenario.get_all())
        missing -= scenarios
        # check missing scenario is not from plugin
        missing = [s for s in list(missing)
                   if scenario.Scenario.get(s).__module__.startswith("rally")]
        self.assertEqual(missing, [],
                         "These scenarios don't have samples: %s" % missing)

    def test_json_correct_syntax(self):
        for dirname, dirnames, filenames in os.walk(self.samples_path):
            for filename in filenames:
                if not filename.endswith(".json"):
                    continue
                full_path = os.path.join(dirname, filename)
                with open(full_path) as task_file:
                    try:
                        json.loads(api.Task.render_template(task_file.read()))
                    except Exception:
                        print(traceback.format_exc())
                        self.fail("Invalid JSON file: %s" % full_path)

    def test_task_config_pair_existance(self):
        inexistent_paths = []

        for dirname, dirnames, filenames in os.walk(self.samples_path):
            # iterate over unique config names
            for sample_name in set(
                    f[:-5] for f in filenames
                    if f.endswith(".json") or f.endswith(".yaml")):

                partial_path = os.path.join(dirname, sample_name)
                yaml_path = partial_path + ".yaml"
                json_path = partial_path + ".json"

                if not os.path.exists(yaml_path):
                    inexistent_paths.append(yaml_path)
                elif not os.path.exists(json_path):
                    inexistent_paths.append(json_path)

        if inexistent_paths:
            self.fail("Sample task configs are missing:\n%r"
                      % inexistent_paths)

    def test_task_config_pairs_equality(self):
        for dirname, dirnames, filenames in os.walk(self.samples_path):
            # iterate over unique config names
            for sample_name in set(
                    f[:-5] for f in filenames
                    if f.endswith(".json") or f.endswith(".yaml")):

                partial_path = os.path.join(dirname, sample_name)
                yaml_path = partial_path + ".yaml"
                json_path = partial_path + ".json"

                if os.path.exists(yaml_path) and os.path.exists(json_path):
                    with open(json_path) as json_file:
                        json_config = yaml.safe_load(api.Task.render_template
                                                     (json_file.read()))
                    with open(yaml_path) as yaml_file:
                        yaml_config = yaml.safe_load(api.Task.render_template
                                                     (yaml_file.read()))
                    self.assertEqual(json_config, yaml_config,
                                     "Sample task configs are not equal:"
                                     "\n%s\n%s" % (yaml_path, json_path))

    def test_no_underscores_in_filename(self):
        bad_filenames = []

        for dirname, dirnames, filenames in os.walk(self.samples_path):
            for filename in filenames:
                if "_" in filename and (filename.endswith(".yaml") or
                                        filename.endswith(".json")):
                    full_path = os.path.join(dirname, filename)
                    bad_filenames.append(full_path)

        self.assertEqual([], bad_filenames,
                         "Following sample task filenames contain "
                         "underscores (_) but must use dashes (-) instead: "
                         "{}".format(bad_filenames))


text:
import { Column, Entity, Index, PrimaryGeneratedColumn } from "typeorm";

@Index(
  "index_sections_on_activity_id_and_position",
  ["activityId", "position"],
  {}
)
@Index("index_sections_on_position", ["position"], {})
@Entity("sections", { schema: "portal_development" })
export class Sections {
  @PrimaryGeneratedColumn({ type: "int", name: "id" })
  id: number;

  @Column("int", { name: "user_id", nullable: true })
  userId: number | null;

  @Column("int", { name: "activity_id", nullable: true })
  activityId: number | null;

  @Column("varchar", { name: "uuid", nullable: true, length: 36 })
  uuid: string | null;

  @Column("varchar", { name: "name", nullable: true, length: 255 })
  name: string | null;

  @Column("mediumtext", { name: "description", nullable: true })
  description: string | null;

  @Column("int", { name: "position", nullable: true })
  position: number | null;

  @Column("datetime", { name: "created_at" })
  createdAt: Date;

  @Column("datetime", { name: "updated_at" })
  updatedAt: Date;

  @Column("tinyint", {
    name: "teacher_only",
    nullable: true,
    width: 1,
    default: () => "'0'",
  })
  teacherOnly: boolean | null;

  @Column("varchar", {
    name: "publication_status",
    nullable: true,
    length: 255,
  })
  publicationStatus: string | null;
}


text:
<?php
    // configuration
    require("../includes/config.php");

    // Get the current cash information:
    $cash = query("SELECT cash FROM `users` WHERE id = ?", $_SESSION["id"]);
    if ($cash === false) {
        apologize ("Cannot retrieve cash information");
    }

    // Check if form was submitted:
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // validate submission
        if (empty($_POST["symbol"])){
            apologize("Quote cannot be empty");
        }
        if (empty($_POST["shares"])) {
            apologize("Shares value cannot be empty");
        }

        // Get the quote:
        $quote = lookup($_POST["symbol"]);

        // Check if not found:
        if (empty($quote)) {
            apologize("Quote Symbol \"" . $_POST["symbol"] . "\" not found");
        }

        // Check if enough money to buy the shares:
        if ($cash[0]["cash"] < $quote["price"]*$_POST["shares"]) {
            apologize (
                "Not enough cash to buy "
                . number_format($_POST["shares"], 0) . "@$" . number_format($quote["price"], 2)
                . " (CASH: $" . number_format($cash[0]["cash"], 2)
                . " NEED: $"  . number_format($quote["price"]*$_POST["shares"], 2) .")"
            );
        } else {
            // Buy the shares:
            if ( (query("INSERT INTO `portfolio` (id, symbol, shares) VALUES(?, ?, ?) ON DUPLICATE KEY UPDATE shares = shares + VALUES(shares)", $_SESSION["id"], strtoupper($_POST["symbol"]), $_POST["shares"]) === false) ||
                 (query("UPDATE `users` SET cash = cash - ? where id = ?", $quote["price"]*$_POST["shares"], $_SESSION["id"]) === false) ) {
                apologize("Something went wrong. CANNOT BUY SHARES OR CANNOT UPDATE CASH!!!");
            }
            // Create a history item:
            query("INSERT INTO `history` (id, transaction, datetime, symbol, shares, price) " .
                "VALUES(?, 'BUY', NOW(), ?, ?, ?)",
                $_SESSION["id"], $_POST["symbol"], $_POST["shares"], $quote["price"]);
            redirect(HOME);
        }

    } else { // Request the form
        // dump($names);
        render("buy_form.php", array("title" => "Buy"));
    }

?>


text:
package org.onecmdb.core;

import java.io.OutputStream;
import java.util.Comparator;

public interface IValue {

    /**
     *
A simple, basic, comparator, which can be used whenever value items
     * are to be compared.

     *
     *
The comparison is based on the value's
     * {@link IValue#getDisplayName}.

     */
    public static final Comparator<IValue> VALUE_COMPARATOR
        = new Comparator<IValue>() {

            public int compare(IValue o1, IValue o2) {
                String n1 = (o1 != null) ? o1.getDisplayName() : null;
                String n2 = (o2 != null) ? o2.getDisplayName() : null;
                if (n1 == n2)
                    return 0;
                if (n1 != null)
                    return n2 != null ? +n1.compareTo(n2) : 1;

                if (n2 != null) {
                     return n1 != null ? -n2.compareTo(n1) : -1;
                }
                return 0;

            }
    };

	/** The type of this value */
	IType getValueType();

	/**
	 * The string representation of this value.
	 *
	 * @return A string representing this value. The empty string may be
	 *         returned when there is no actualvalue set--never
	 *         null!
	 */
	String getAsString();

	OutputStream asOutputStream();

	/**
	 * Returns a string representation of the value held by this
	 * value.
	 *
	 * @return
	 */
	String getDisplayName();

    /**
     *
Query if this value represents the null value, according
     * to the the type backed by this value.

     *
     * @return A boolean indicating if the this value actually should be
     * interpreted as the null value.
     */
    boolean isNullValue();

    /**
     * Check if a IValue is a ICi.
     *
     * @return true if the Value is a ICi
     */
    boolean isComplex();

	String getIcon();

	/**
	 * The java object representation of this value if there exists any.
	 * If no correct java object represetation exists null is retured.
	 *
	 * @return a java object representaion of this value. null if no such exists.
	 */
	Object getAsJavaObject();
}