text:
<?php

namespace Sonata\AdminBundle\Mapper;

/**
 * This class is used to simulate the Form API
 *
 */
abstract class BaseGroupedMapper extends BaseMapper
{
    protected $currentGroup;
    protected $currentTab;

    protected $apply;

    abstract protected function getGroups();
    abstract protected function getTabs();

    abstract protected function setGroups(array $groups);
    abstract protected function setTabs(array $tabs);

    /**
     * Add new group or tab (if parameter "tab=true" is available in options)
     *
     * @param string $name
     * @param array  $options
     *
     * @return BaseGroupedMapper
     *
     * @throws \RuntimeException
     */
    public function with($name, array $options = array())
    {
        /**
         * The current implementation should work with the following workflow:
         *
         *     $formMapper
         *        ->with('group1')
         *            ->add('username')
         *            ->add('password')
         *        ->end()
         *        ->with('tab1', array('tab' => true))
         *            ->with('group1')
         *                ->add('username')
         *                ->add('password')
         *            ->end()
         *            ->with('group2', array('collapsed' => true))
         *                ->add('enabled')
         *                ->add('createdAt')
         *            ->end()
         *        ->end();
         *
         */
        $defaultOptions = array(
            'collapsed'          => false,
            'class'              => false,
            'description'        => false,
            'translation_domain' => null,
            'name'               => $name,
        );

        $code = $name;

        // Open
        if (array_key_exists('tab', $options) && $options['tab']) {
            $tabs = $this->getTabs();

            if ($this->currentTab) {
                if (isset($tabs[$this->currentTab]['auto_created']) && true === $tabs[$this->currentTab]['auto_created']) {
                    throw new \RuntimeException('New tab was added automatically when you have added field or group. You should close current tab before adding new one OR add tabs before adding groups and fields.');
                } else {
                    throw new \RuntimeException(sprintf('You should close previous tab "%s" with end() before adding new tab "%s".', $this->currentTab, $name));
                }
            } elseif ($this->currentGroup) {
                throw new \RuntimeException(sprintf('You should open tab before adding new group "%s".', $name));
            }

            if (!isset($tabs[$name])) {
                $tabs[$name] = array();
            }

            $tabs[$code] = array_merge($defaultOptions, array(
                'auto_created'       => false,
                'groups'             => array(),
            ), $tabs[$code], $options);

            $this->currentTab = $code;

        } else {

            if ($this->currentGroup) {
                throw new \RuntimeException(sprintf('You should close previous group "%s" with end() before adding new tab "%s".', $this->currentGroup, $name));
            }

            if (!$this->currentTab) {
                // no tab define
                $this->with('default', array(
                    'tab'                => true,
                    'auto_created'       => true,
                    'translation_domain' => isset($options['translation_domain']) ? $options['translation_domain'] : null
                )); // add new tab automatically
            }

            // if no tab is selected, we go the the main one named '_' ..
            if ($this->currentTab !== 'default') {
                $code = $this->currentTab.'.'.$name; // groups with the same name can be on different tabs, so we prefix them in order to make unique group name
            }

            $groups = $this->getGroups();
            if (!isset($groups[$code])) {
                $groups[$code] = array();
            }

            $groups[$code] = array_merge($defaultOptions, array(
                'fields' => array(),
            ), $groups[$code], $options);

            $this->currentGroup = $code;
            $this->setGroups($groups);
            $tabs = $this->getTabs();
        }

        if ($this->currentGroup && isset($tabs[$this->currentTab]) && !in_array($this->currentGroup, $tabs[$this->currentTab]['groups'])) {
            $tabs[$this->currentTab]['groups'][] = $this->currentGroup;
        }

        $this->setTabs($tabs);

        return $this;
    }

    /**
     * Only nested add if the condition match true
     *
     * @param boolean $bool
     *
     * @return BaseGroupedMapper
     *
     * @throws \RuntimeException
     */
    public function ifTrue($bool)
    {
        if ($this->apply !== null) {
            throw new \RuntimeException('Cannot nest ifTrue or ifFalse call');
        }

        $this->apply = ($bool === true);

        return $this;
    }

    /**
     * Only nested add if the condition match false
     *
     * @param boolean $bool
     *
     * @return BaseGroupedMapper
     *
     * @throws \RuntimeException
     */
    public function ifFalse($bool)
    {
        if ($this->apply !== null) {
            throw new \RuntimeException('Cannot nest ifTrue or ifFalse call');
        }

        $this->apply = ($bool === false);

        return $this;
    }

    /**
     * @return $this
     */
    public function ifEnd()
    {
        $this->apply = null;

        return $this;
    }

    /**
     * Add new tab
     *
     * @param string $name
     * @param array  $options
     *
     * @return BaseGroupedMapper
     */
    public function tab($name, array $options = array())
    {
        return $this->with($name, array_merge($options, array('tab' => true)));
    }

    /**
     * Close the current group or tab
     *
     * @return BaseGroupedMapper
     *
     * @throws \RuntimeException
     */
    public function end()
    {
        if ($this->currentGroup !== null) {
            $this->currentGroup = null;
        } elseif ($this->currentTab !== null) {
            $this->currentTab = null;
        } else {
            throw new \RuntimeException('No open tabs or groups, you cannot use end()');
        }

        return $this;
    }

    /**
     * Returns a boolean indicating if there is an open tab at the moment.
     *
     * @return boolean
     */
    public function hasOpenTab()
    {
        return null !== $this->currentTab;
    }

    /**
     * Add the fieldname to the current group
     *
     * @param string $fieldName
     */
    protected function addFieldToCurrentGroup($fieldName)
    {
        // Note this line must happen before the next line.
        // See https://github.com/sonata-project/SonataAdminBundle/pull/1351
        $currentGroup = $this->getCurrentGroupName();
        $groups = $this->getGroups();
        $groups[$currentGroup]['fields'][$fieldName] = $fieldName;
        $this->setGroups($groups);

        return $groups[$currentGroup];
    }

    /**
     * Return the name of the currently selected group. The method also makes
     * sure a valid group name is currently selected
     *
     * Note that this can have the side effect to change the 'group' value
     * returned by the getGroup function
     *
     * @return string
     */
    protected function getCurrentGroupName()
    {
        if (!$this->currentGroup) {
            $this->with($this->admin->getLabel(), array('auto_created' => true));
        }

        return $this->currentGroup;
    }
}


text:
package com.clujtracker.app;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import com.clujtracker.app.core.MapRefresher;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends ActionBarActivity {
    private GoogleMap map;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initUI();
    }

    public static final LatLng CLUJCENTER = new LatLng(46.772327, 23.595355);

    private void initUI() {
        map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();

        if (map != null) {
            map.addMarker(new MarkerOptions().position(CLUJCENTER)
                    .title("43B"));
            map.animateCamera(CameraUpdateFactory.newLatLngZoom(CLUJCENTER, 13));
        }

        new MapRefresher(map, this).start();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}

redpajama_set_name: RedPajamaGithub


text:
title: RemoteDebug and cross-browser DevTools. One year later. — Kenneth Auchenberg
author: azu
layout: post
itemUrl: 'https://kenneth.io/blog/2015/03/12/remotedebug-one-year-later'
editJSONPath: 'https://github.com/jser/jser.info/edit/gh-pages/data/2015/03/index.json'
date: '2015-03-16T15:20:02+00:00'
tags:
  - JavaScript
  - browser
  - debug
---
ブラウザ間の共通デバッグプロトコルを作るプロジェクトであるRemoteDebugを公開して1年経ってどのような変化があったかについて


text:
package com.gplucky;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gplucky.mybatis.dao.HolidayDataMapper;
import com.gplucky.mybatis.model.HolidayData;
import com.gplucky.schedule.TaskSwitchAop;
import com.gplucky.utils.DateUtils;
import com.gplucky.utils.RedisConstants;
import com.gplucky.utils.RedisUtils;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.ImportResource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.List;
import java.util.stream.Collectors;

@MapperScan("com.gplucky.mybatis.dao")
@ImportResource({"classpath:/common.xml"})
@EnableDiscoveryClient
@EnableScheduling
@SpringBootApplication
public class TaskApplication extends WebMvcConfigurerAdapter {

    @Autowired
    private TaskSwitchAop taskSwitchAop;

    /**
     * (1)在启动类App.java类中继承:WebMvcConfigurerAdapter
     *

     * (2)覆盖方法:configureContentNegotiation
     *

     *

     *

     * favorPathExtension表示支持后缀匹配,
     *

     * 属性ignoreAcceptHeader默认为fasle,表示accept-header匹配,defaultContentType开启默认匹配。
     *

     * 例如:请求aaa.xx,若设置<entry key="xx" value="application/xml"/> 也能匹配以xml返回。
     *

     * 根据以上条件进行一一匹配最终,得到相关并符合的策略初始化ContentNegotiationManager
     */

    @Override

    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {

        configurer.favorPathExtension(false);

    }

    public static void main(String[] args) {
        SpringApplication.run(TaskApplication.class, args);
    }

}


text:
pureEvil
========

My Hobby Evil code


text:
SELECT c.relname AS child, p.relname AS parent, tc.table_schema as schema
FROM pg_catalog.pg_inherits
    JOIN pg_catalog.pg_class AS c ON (inhrelid = c.oid)
    JOIN pg_catalog.pg_class AS p ON (inhparent = p.oid)
    JOIN information_schema.tables tc ON c.relname = tc.table_name
WHERE
    ((case -- allow specific schemas (none or '' assumes all):
      when $1 ='' then 1=1
      else tc.table_schema = any(string_to_array(replace($1, ' ', ''), ',')) end)
    and
    (case -- blacklist tables using LIKE by fully-qualified name (no schema assumes public):
      when $2 = '' then 1=1
      else replace((tc.table_schema || '.'|| tc.table_name), 'public.', '') not like all(string_to_array(replace($2, ' ', ''), ',')) end))
    or
    (case -- make exceptions for specific tables, with fully-qualified name or wildcard pattern (no schema assumes public).
      when $3 = '' then 1=0
      -- Below can use '%' as wildcard. Change 'like' to '=' to require exact names:
      else replace((tc.table_schema || '.'|| tc.table_name), 'public.', '') like any(string_to_array(replace($3, ' ', ''), ',')) end)
;


text:
class AddIpToSignatures < ActiveRecord::Migration
  def change
    add_column :signatures, :ip, :inet
  end
end


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

namespace Verse.Tools
{
    internal class Walker<T> : IEnumerable<T>
    {
        #region Attributes

        private readonly IEnumerator<T> enumerator;

        #endregion

        #region Constructors

        public Walker(IEnumerator<T> enumerator)
        {
            this.enumerator = enumerator;
        }

        #endregion

        #region Methods / Public

        public IEnumerator<T> GetEnumerator()
        {
            return this.enumerator;
        }

        #endregion

        #region Methods / Explicit

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        #endregion
    }
}


text:
require 'spec_helper'

describe "User confirmation" do

  if User.confirmable?

    it "occurs after following the confirmation link" do
      register("user@example.com", "password")
      page.should have_content I18n.t('devise.registrations.signed_up_but_unconfirmed')
      @user = User.where(:email => "user@example.com").first
      visit user_confirmation_path(:confirmation_token => @user.confirmation_token)
      current_path.should == user_root_path
      page.should have_content I18n.t('devise.confirmations.confirmed')
    end

    describe "in beta", :beta do

      it "occurs after following the confirmation link" do
        register("user@example.com", "password", :invite_code => invite_code)
        page.should have_content I18n.t('devise.registrations.signed_up_but_unconfirmed')
        @user = User.where(:email => "user@example.com").first
        visit user_confirmation_path(:confirmation_token => @user.confirmation_token)
        current_path.should == user_root_path
        page.should have_content I18n.t('devise.confirmations.confirmed')
      end

    end

  end

end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Revue Mycol. , Paris 18: 105 (1953)

#### Original name
Patellaria rivularis P. Crouan & H. Crouan

### Remarks
null


text:
namespace Edustructures.Metadata
{
    using System;

    /// <summary>  Signals a parsing error.
    /// *
    /// </summary>
    /// <author>  Eric Petersen
    /// </author>
    /// <version>  1.0
    ///
    /// </version>
    public class ParseException : Exception
    {
        public ParseException()
            : base() {}

        public ParseException( String msg )
            : base( msg ) {}

        public ParseException( String msg,
                               Exception innerException )
            : base( msg, innerException ) {}
    }
}


text: fn main() { while main { } }


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<servico xmlns="http://servicos.gov.br/v3/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://servicos.gov.br/v3/schema ../servico.xsd">
    <nome>Serviços de CPF para Pessoas Físicas Residentes no Exterior</nome>
    <sigla/>
    <nomes-populares/>
    <descricao>Realizar nas Representações Diplomáticas pedido de inscrição, cancelamento, alteração de dados cadastrais ou regularização de inscrição no CPF.</descricao>
    <gratuito/>
    <solicitantes/>
    <tempo-total-estimado>
        <descricao/>
    </tempo-total-estimado>
    <etapas>
        <etapa>
            <titulo/>
            <descricao/>
            <documentos>
                <default/>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao tipo="web">
                        <descricao>http://www.receita.fazenda.gov.br/Aplicacoes/Atcta/cpfEstrangeiro/Fcpf.asp</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
    </etapas>
    <orgao id="http://estruturaorganizacional.dados.gov.br/id/unidade-organizacional/77"/>
    <segmentos-da-sociedade>
        <item>Cidadãos</item>
    </segmentos-da-sociedade>
    <areas-de-interesse>
        <item>Economia e Finanças</item>
    </areas-de-interesse>
    <palavras-chave/>
    <legislacoes/>
</servico>


text:
////////////////////////////////////////////////////////////////////////////////
package alma.ACSCOURSE_MOUNT;

////////////////////////////////////////////////////////////////////////////////
import alma.acs.component.client.ComponentClient;
import alma.acs.container.ContainerServices;
import alma.acs.nc.AcsEventPublisher;

////////////////////////////////////////////////////////////////////////////////
/**
 * MountSupplier is an event channel example that shows how to use the NCPublisher class
 * directly, without ContainerServices available.
 *
 * @author dfugate
 */
public class MountSupplier extends Thread
{
	// //////////////////////////////////////////////////////////////////////////
	/**
	 * In this example, the main function is all that is used.
	 *
	 * @param args
	 *            Not used!
	 */
	public static void main(String[] args) {
		try {
			// Setup an ACS Java client. This has little to do with the NC API
			String managerLoc = System.getProperty("ACS.manager");
			if (managerLoc == null) {
				System.out.println("Java property 'ACS.manager' must be set to the corbaloc of the ACS manager!");
				System.exit(-1);
			}
			String clientName = "MountSupplierClient";
			ComponentClient myClient = new ComponentClient(null, managerLoc, clientName);
			ContainerServices cs = myClient.getContainerServices();

			// Create and initialize the supplier
			AcsEventPublisher<MountEventData> joe = cs.createNotificationChannelPublisher(
					MOUNT_CHANNEL.value, // the channel's name
					MountEventData.class
				);

			// Create the event that will be published
			MountEventData t_block = new MountEventData(3.14F, 43.0F);

			// Publish the event 50 times int 50 seconds
			System.out.println("Now sending events...");
			for (int i = 0; i < 50; i++) {
				joe.publishEvent(t_block);
				sleep(1000);
			}

			// Must cleanly disconnect the supplier
			joe.disconnect();

			// Must cleanly disconnect the client
			myClient.tearDown();
		} catch (Exception e) {
			e.printStackTrace(System.err);
		}
	}
	// //////////////////////////////////////////////////////////////////////////
}


text:
package org.springframework.osgi.test.internal.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Utility class for IO operations.
 *
 * @author Costin Leau
 *
 */
public abstract class IOUtils {

	public static interface IOCallback {
		void doWithIO() throws IOException;
	}

	public static void doWithIO(IOCallback callback) {
		try {
			callback.doWithIO();
		}
		catch (IOException ioException) {

		}
	}

	public static void closeStream(InputStream stream) {
		if (stream != null)
			try {
				stream.close();
			}
			catch (IOException ex) {
				// ignore
			}
	}

	public static void closeStream(OutputStream stream) {
		if (stream != null)
			try {
				stream.close();
			}
			catch (IOException ex) {
				// ignore
			}
	}

	/**
	 * Delete the given file (can be a simple file or a folder).
	 *
	 * @param file the file to be deleted
	 * @return if the deletion succeded or not
	 */
	public static boolean delete(File file) {

		// bail out quickly
		if (file == null)
			return false;

		// recursively delete children file
		boolean success = true;

		if (file.isDirectory()) {
			String[] children = file.list();
			for (int i = 0; i < children.length; i++) {
				success &= delete(new File(file, children[i]));
			}
		}

		// The directory is now empty so delete it
		return (success &= file.delete());
	}
}


text:
import time

from zktraffic.base.sniffer import Sniffer, SnifferConfig
from zktraffic.stats.loaders import QueueStatsLoader
from zktraffic.stats.accumulators import PerPathStatsAccumulator

from .common import consume_packets

class TestablePerPathAccumulators(QueueStatsLoader):
  def __init__(self, aggregation_depth=0):
    self.processed_requests = 0
    super(TestablePerPathAccumulators, self).__init__()
    self.register_accumulator('0', PerPathStatsAccumulator(aggregation_depth))

  def cur_stats(self):
    return self._accumulators['0']._cur_stats

  def update_request_stats(self, request):
    self.processed_requests += 1
    self._accumulators['0'].update_request_stats(request)

NUMBER_OF_REQUESTS_SET_DATA = 30
NUMBER_OF_REQUESTS_WATCHES = 4
SLEEP_MAX = 2

def wait_for_stats(zkt, stats, pcap_file, expected_requests):
  consume_packets(pcap_file, zkt)
  slept = 0

  while stats.processed_requests < expected_requests:
    time.sleep(0.5)
    slept += 0.5
    if slept > SLEEP_MAX:
      break

  return stats.cur_stats()

def test_init_path_stats():
  stats = TestablePerPathAccumulators(aggregation_depth=1)
  stats.start()
  cur_stats = stats.cur_stats()
  assert "writes" in cur_stats
  assert "/" in cur_stats["writes"]
  assert "writesBytes" in cur_stats
  assert "/" in cur_stats["writesBytes"]
  assert "reads" in cur_stats
  assert "/" in cur_stats["reads"]
  assert "readsBytes" in cur_stats
  assert "/" in cur_stats["readsBytes"]
  assert "total" in cur_stats
  assert "/writes" in cur_stats["total"]
  assert "/writeBytes" in cur_stats["total"]
  assert "/reads" in cur_stats["total"]
  assert "/readBytes" in cur_stats["total"]

  #add some traffic
  zkt = Sniffer(SnifferConfig())
  zkt.add_request_handler(stats.handle_request)
  cur_stats = wait_for_stats(zkt, stats, "set_data", 1)

  #writes for / should stay 0
  assert cur_stats["writes"]["/"] == 0
  assert cur_stats["total"]["/writes"] == 20

  stats.stop()

def test_per_path_stats():
  stats = TestablePerPathAccumulators(aggregation_depth=1)
  stats.start()
  zkt = Sniffer(SnifferConfig())
  zkt.add_request_handler(stats.handle_request)

  cur_stats = wait_for_stats(zkt, stats, "set_data", NUMBER_OF_REQUESTS_SET_DATA)

  assert cur_stats["writes"]["/load-testing"] == 20
  assert cur_stats["SetDataRequest"]["/load-testing"] == 20

  stats.stop()

def test_per_path_stats_aggregated():
  stats = TestablePerPathAccumulators(aggregation_depth=2)
  stats.start()
  zkt = Sniffer(SnifferConfig())
  zkt.add_request_handler(stats.handle_request)

  cur_stats = wait_for_stats(zkt, stats, "set_data", NUMBER_OF_REQUESTS_SET_DATA)

  for i in range(0, 5):
    assert cur_stats["writes"]["/load-testing/%d" % (i)] == 4
    assert cur_stats["SetDataRequest"]["/load-testing/%d" % (i)] == 4

  assert cur_stats["total"]["/writes"] == 20
  assert cur_stats["total"]["/reads"] == 16

  stats.stop()

def test_watches():
  stats = TestablePerPathAccumulators(aggregation_depth=1)
  stats.start()
  zkt = Sniffer(SnifferConfig())
  zkt.add_request_handler(stats.handle_request)

  cur_stats = wait_for_stats(zkt, stats, "getdata_watches", NUMBER_OF_REQUESTS_WATCHES)

  assert cur_stats["watches"]["/test"] == 2
  assert cur_stats["GetDataRequest"]["/test"] == 2
  assert cur_stats["GetChildrenRequest"]["/test"] == 2

  stats.stop()


text:
package android.media.effect.effects;

public class LomoishEffect
  extends android.media.effect.SingleFilterEffect{
  // Constructors

  public LomoishEffect(android.media.effect.EffectContext arg1, java.lang.String arg2){
    super((android.media.effect.EffectContext) null, (java.lang.String) null, (java.lang.Class) null, (java.lang.String) null, (java.lang.String) null, (java.lang.Object []) null);
  }
}


text:
@class MISSING_TYPE;

__attribute__((visibility("hidden")))
@interface _TtC15IDESourceEditor21RefactoringController : NSObject
{
    MISSING_TYPE *gotAFailure;
    MISSING_TYPE *editor;
    MISSING_TYPE *updateTimer;
    MISSING_TYPE *changeCount;
    MISSING_TYPE *lastRefactoringRange;
    MISSING_TYPE *lastAvailableRefactoringsRequest;
    MISSING_TYPE *lastAvailableRefactorings;
    MISSING_TYPE *renameOperation;
}

- (void).cxx_destruct;
- (id)init;

@end


text:
/**
 * Exports under the tf.math.* namespace.
 */

import {confusionMatrix} from './ops/confusion_matrix';

export {confusionMatrix};


text:
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Practices.Unity;
using Microsoft.VisualStudio.TestTools.UnitTesting;

using MooveePicker;
using MoviePicker.Common;
using MoviePicker.Common.Interfaces;
using MoviePicker.Tests;

namespace MooviePicker.Tests
{
	[TestClass]
    [ExcludeFromCodeCoverage]
    public class MoviePickerTest_20170611 : MoviePickerTestBase
	{
		// Unity Reference: https://msdn.microsoft.com/en-us/library/ff648211.aspx
		private static IUnityContainer _unity;

		public override IUnityContainer UnityContainer => _unity;

		[ClassInitialize]
		public static void InitializeBeforeAllTests(TestContext context)
		{
			_unity = new UnityContainer();

			_unity.RegisterType<IMovie, Movie>();
			_unity.RegisterType<IMovieList, MovieList>();
			_unity.RegisterType<IMoviePicker, MooveePicker.MoviePicker>();
		}

		[TestMethod]
		public void MoviePicker_ChooseBest_Parker_20170611()
		{
			var test = ConstructTestObject();
			var movies = new List<IMovie>();
			int id = 1;

			movies.Add(ConstructMovie(id++, "Wonder Woman", 55m, 613));
			movies.Add(ConstructMovie(id++, "The Mummy", 38m, 526));
			movies.Add(ConstructMovie(id++, "It Comes at night", 11m, 150));
			movies.Add(ConstructMovie(id++, "Pirates of the caribbean", 12m, 143));
			movies.Add(ConstructMovie(id++, "Baywatch", 5m, 60));
			movies.Add(ConstructMovie(id++, "Megan Leavey", 3.3m, 59));
			movies.Add(ConstructMovie(id++, "Alien: Covenant", 2.1m, 26));
			movies.Add(ConstructMovie(id++, "My Cousin Rachel", 1m, 15));
			movies.Add(ConstructMovie(id++, "Diary of a wimpy Kid", 0.6m, 8));
			movies.Add(ConstructMovie(id++, "Captain Underpants", 12m, 198));
			movies.Add(ConstructMovie(id++, "Everything, Everything", 1.5m, 28));
			movies.Add(ConstructMovie(id++, "Guardians of the Galaxy", 5m, 70));
			movies.Add(ConstructMovie(id++, "King Arthur", 0.5m, 7));
			movies.Add(ConstructMovie(id++, "Snatched", 0.6m, 9));
			movies.Add(ConstructMovie(id++, "Best of the rest", 0.5m, 9));

			test.AddMovies(movies);

			var best = test.ChooseBest();

			WritePicker(test);
			WriteMovies(best);
		}

		[TestMethod]
		public void MoviePicker_ChooseBest_Debug_20170611()
		{
			var test = ConstructTestObject();
			var movies = new List<IMovie>();
			int id = 1;

			movies.Add(ConstructMovie(id++, "Wonder Woman", 55m, 613));
			movies.Add(ConstructMovie(id++, "Baywatch", 5m, 69));
			movies.Add(ConstructMovie(id++, "Pirates of the caribbean", 12m, 143));
			//movies.Add(ConstructMovie(id++, "Baywatch", 5m, 69));
			movies.Add(ConstructMovie(id++, "Alien: Covenant", 2.1m, 26));
			movies.Add(ConstructMovie(id++, "My Cousin Rachel", 1m, 15));
			movies.Add(ConstructMovie(id++, "Diary of a wimpy Kid", 0.6m, 8));

			test.AddMovies(movies);

			var best = test.ChooseBest();

			WritePicker(test);
			WriteMovies(best);

			Assert.AreEqual(86900000m, best.TotalEarnings);
		}

		[TestMethod]
		public void MoviePicker_ChooseBest_Doug_20170611()
		{
			var test = ConstructTestObject();
			var movies = new List<IMovie>();
			int id = 1;

			movies.Add(ConstructMovie(id++, "Wonder Woman", 55m, 613));
			movies.Add(ConstructMovie(id++, "The Mummy", 35m, 526));
			movies.Add(ConstructMovie(id++, "It Comes at night", 12m, 150));
			movies.Add(ConstructMovie(id++, "Pirates of the caribbean", 11m, 143));
			movies.Add(ConstructMovie(id++, "Baywatch", 4m, 60));
			movies.Add(ConstructMovie(id++, "Megan Leavey", 3m, 59));
			movies.Add(ConstructMovie(id++, "Alien: Covenant", 2m, 26));
			movies.Add(ConstructMovie(id++, "My Cousin Rachel", 2m, 15));
			movies.Add(ConstructMovie(id++, "Diary of a wimpy Kid", 0.5m, 8));
			movies.Add(ConstructMovie(id++, "Captain Underpants", 12m, 198));
			movies.Add(ConstructMovie(id++, "Everything, Everything", 1.5m, 28));
			movies.Add(ConstructMovie(id++, "Guardians of the Galaxy", 5m, 70));
			movies.Add(ConstructMovie(id++, "King Arthur", 0.5m, 7));
			movies.Add(ConstructMovie(id++, "Snatched", 0.5m, 9));
			movies.Add(ConstructMovie(id++, "Best of the rest", 0.5m, 9));

			test.AddMovies(movies);

			var best = test.ChooseBest();

			WritePicker(test);
			WriteMovies(best);
		}

		[TestMethod]
		public void MoviePicker_ChooseBest_Raj_20170611()
		{
			var test = ConstructTestObject();
			var movies = new List<IMovie>();
			int id = 1;

			movies.Add(ConstructMovie(id++, "Wonder Woman", 50m, 613));
			movies.Add(ConstructMovie(id++, "The Mummy", 32m, 526));
			movies.Add(ConstructMovie(id++, "It Comes at night", 10m, 150));
			movies.Add(ConstructMovie(id++, "Pirates of the caribbean", 10.5m, 143));
			movies.Add(ConstructMovie(id++, "Baywatch", 4m, 69));
			movies.Add(ConstructMovie(id++, "Megan Leavey", 2.4m, 59));
			movies.Add(ConstructMovie(id++, "Alien: Covenant", 2m, 26));
			movies.Add(ConstructMovie(id++, "My Cousin Rachel", 0.5m, 15));
			movies.Add(ConstructMovie(id++, "Diary of a wimpy Kid", 0.5m, 8));
			movies.Add(ConstructMovie(id++, "Captain Underpants", 13m, 198));
			movies.Add(ConstructMovie(id++, "Everything, Everything", 1.5m, 28));
			movies.Add(ConstructMovie(id++, "Guardians of the Galaxy", 4.5m, 70));
			movies.Add(ConstructMovie(id++, "King Arthur", 0.5m, 7));
			movies.Add(ConstructMovie(id++, "Snatched", 0.5m, 9));
			movies.Add(ConstructMovie(id++, "Best of the rest", 0.5m, 9));

			test.AddMovies(movies);

			var best = test.ChooseBest();

			WritePicker(test);
			WriteMovies(best);
		}

		[TestMethod]
		public void MoviePicker_ChooseBest_BoxOfficePro_20170611()
		{
			var test = ConstructTestObject();
			var movies = new List<IMovie>();
			int id = 1;

			movies.Add(ConstructMovie(id++, "Wonder Woman", 50m, 613));
			movies.Add(ConstructMovie(id++, "The Mummy", 32m, 526));
			movies.Add(ConstructMovie(id++, "It Comes at night", 11m, 150));
			movies.Add(ConstructMovie(id++, "Pirates of the caribbean", 10.4m, 143));
			movies.Add(ConstructMovie(id++, "Baywatch", 4.3m, 69));
			movies.Add(ConstructMovie(id++, "Megan Leavey", 2.4m, 59));
			movies.Add(ConstructMovie(id++, "Alien: Covenant", 1.86m, 26));
			movies.Add(ConstructMovie(id++, "My Cousin Rachel", 0m, 15));
			movies.Add(ConstructMovie(id++, "Diary of a wimpy Kid", 0m, 8));
			movies.Add(ConstructMovie(id++, "Captain Underpants", 13.35m, 198));
			movies.Add(ConstructMovie(id++, "Everything, Everything", 1.98m, 28));
			movies.Add(ConstructMovie(id++, "Guardians of the Galaxy", 4.7m, 70));
			movies.Add(ConstructMovie(id++, "King Arthur", 0m, 7));
			movies.Add(ConstructMovie(id++, "Snatched", 0m, 9));
			movies.Add(ConstructMovie(id++, "Best of the rest", 0m, 9));

			test.AddMovies(movies);

			var best = test.ChooseBest();

			WritePicker(test);
			WriteMovies(best);
		}

		[TestMethod]
		public void MoviePicker_ChooseBest_Cinefiles_20170611()
		{
			var test = ConstructTestObject();
			var movies = new List<IMovie>();
			int id = 1;

			// https://cinefilesreviews.com/2017/06/07/weekend-box-office-predictions-june-9-june-11/

			movies.Add(ConstructMovie(id++, "Wonder Woman", 83m, 613));
			movies.Add(ConstructMovie(id++, "The Mummy", 65m, 526));
			movies.Add(ConstructMovie(id++, "It Comes at night", 20m, 150));
			movies.Add(ConstructMovie(id++, "Captain Underpants", 16m, 198));
			movies.Add(ConstructMovie(id++, "Pirates of the caribbean", 10m, 143));

			// End of picks, using Parker's data for the rest.
			movies.Add(ConstructMovie(id++, "Megan Leavey", 3.3m, 59));
			movies.Add(ConstructMovie(id++, "Baywatch", 5m, 69));
			movies.Add(ConstructMovie(id++, "Alien: Covenant", 2.1m, 26));
			movies.Add(ConstructMovie(id++, "My Cousin Rachel", 1m, 15));
			movies.Add(ConstructMovie(id++, "Diary of a wimpy Kid", 0.6m, 8));
			movies.Add(ConstructMovie(id++, "Everything, Everything", 1.5m, 28));
			movies.Add(ConstructMovie(id++, "Guardians of the Galaxy", 5m, 70));
			movies.Add(ConstructMovie(id++, "King Arthur", 0.5m, 7));
			movies.Add(ConstructMovie(id++, "Snatched", 0.6m, 9));
			movies.Add(ConstructMovie(id++, "Best of the rest", 0.5m, 9));

			test.AddMovies(movies);

			var best = test.ChooseBest();

			WritePicker(test);
			WriteMovies(best);
		}

		[TestMethod]
		public void MoviePicker_ChooseBest_TheNumbers_20170611()
		{
			var test = ConstructTestObject();
			var movies = new List<IMovie>();
			int id = 1;

			// http://www.the-numbers.com/news/222490830-Weekend-Predictions-Can-Mummy-Bury-the-Competition

			movies.Add(ConstructMovie(id++, "Wonder Woman", 47m, 613));
			movies.Add(ConstructMovie(id++, "The Mummy", 34m, 526));
			movies.Add(ConstructMovie(id++, "Captain Underpants", 12m, 198));
			movies.Add(ConstructMovie(id++, "It Comes at night", 12m, 150));
			movies.Add(ConstructMovie(id++, "Pirates of the caribbean", 10m, 143));
			movies.Add(ConstructMovie(id++, "Megan Leavey", 3m, 59));

			// End of picks, using Parker's data for the rest.
			movies.Add(ConstructMovie(id++, "Baywatch", 5m, 69));
			movies.Add(ConstructMovie(id++, "Alien: Covenant", 2.1m, 26));
			movies.Add(ConstructMovie(id++, "My Cousin Rachel", 1m, 15));
			movies.Add(ConstructMovie(id++, "Diary of a wimpy Kid", 0.6m, 8));
			movies.Add(ConstructMovie(id++, "Everything, Everything", 1.5m, 28));
			movies.Add(ConstructMovie(id++, "Guardians of the Galaxy", 5m, 70));
			movies.Add(ConstructMovie(id++, "King Arthur", 0.5m, 7));
			movies.Add(ConstructMovie(id++, "Snatched", 0.6m, 9));
			movies.Add(ConstructMovie(id++, "Best of the rest", 0.5m, 9));

			test.AddMovies(movies);

			var best = test.ChooseBest();

			WritePicker(test);
			WriteMovies(best);
		}

		[TestMethod]
		public void MoviePicker_ChooseBest_ToddMThatcher_20170611()
		{
			var test = ConstructTestObject();
			var movies = new List<IMovie>();
			int id = 1;

			movies.Add(ConstructMovie(id++, "Wonder Woman", 49.5m, 613));
			movies.Add(ConstructMovie(id++, "The Mummy", 38.7m, 526));
			movies.Add(ConstructMovie(id++, "It Comes at night", 9.5m, 150));
			movies.Add(ConstructMovie(id++, "Pirates of the caribbean", 12m, 143));
			movies.Add(ConstructMovie(id++, "Baywatch", 4m, 69));
			movies.Add(ConstructMovie(id++, "Megan Leavey", 3.3m, 59));
			movies.Add(ConstructMovie(id++, "Alien: Covenant", 2m, 26));
			movies.Add(ConstructMovie(id++, "My Cousin Rachel", 0m, 15));
			movies.Add(ConstructMovie(id++, "Diary of a wimpy Kid", 1m, 8));
			movies.Add(ConstructMovie(id++, "Captain Underpants", 7.18m, 198));
			movies.Add(ConstructMovie(id++, "Everything, Everything", 1.39m, 28));
			movies.Add(ConstructMovie(id++, "Guardians of the Galaxy", 4.5m, 70));
			movies.Add(ConstructMovie(id++, "King Arthur", 0.72m, 7));
			movies.Add(ConstructMovie(id++, "Snatched", 0.87m, 9));
			movies.Add(ConstructMovie(id++, "Best of the rest", 0m, 9));

			test.AddMovies(movies);

			var best = test.ChooseBest();

			WritePicker(test);
			WriteMovies(best);
		}

		//----==== PRIVATE ====---------------------------------------------------------
	}
}


text:
class Rosemary::Permissions
  include Enumerable

  attr_reader :raw

  def initialize
    @raw = []
  end

  # make sure we can add permissions and are "Enumerable" via delegation to the permissions array
  delegate :<<, :each, :to => :raw

  # some convenience helpers for permissions we already know:
  %w(allow_read_prefs allow_write_prefs allow_write_diary
     allow_write_api allow_read_gpx allow_write_gpx).each do |name|
    define_method("#{name}?") { raw.include?(name) }
  end
end


text:
namespace gpu {

class IdAllocatorInterface;
class TransferBufferManagerInterface;

namespace gles2 {

class ProgramCache;
class BufferManager;
class GLES2Decoder;
class FramebufferManager;
class MailboxManager;
class RenderbufferManager;
class ProgramManager;
class ShaderManager;
class TextureManager;
class MemoryTracker;
struct DisallowedFeatures;

// A Context Group helps manage multiple GLES2Decoders that share
// resources.
class GPU_EXPORT ContextGroup : public base::RefCounted<ContextGroup> {
 public:
  ContextGroup(
      const scoped_refptr<MailboxManager>& mailbox_manager,
      const scoped_refptr<MemoryTracker>& memory_tracker,
      const scoped_refptr<ShaderTranslatorCache>& shader_translator_cache,
      const scoped_refptr<FeatureInfo>& feature_info,
      bool bind_generates_resource);

  // This should only be called by GLES2Decoder. This must be paired with a
  // call to destroy if it succeeds.
  bool Initialize(
      GLES2Decoder* decoder,
      const DisallowedFeatures& disallowed_features);

  // Destroys all the resources when called for the last context in the group.
  // It should only be called by GLES2Decoder.
  void Destroy(GLES2Decoder* decoder, bool have_context);

  MailboxManager* mailbox_manager() const {
    return mailbox_manager_.get();
  }

  MemoryTracker* memory_tracker() const {
    return memory_tracker_.get();
  }

  ShaderTranslatorCache* shader_translator_cache() const {
    return shader_translator_cache_.get();
  }

  bool bind_generates_resource() {
    return bind_generates_resource_;
  }

  uint32 max_vertex_attribs() const {
    return max_vertex_attribs_;
  }

  uint32 max_texture_units() const {
    return max_texture_units_;
  }

  uint32 max_texture_image_units() const {
    return max_texture_image_units_;
  }

  uint32 max_vertex_texture_image_units() const {
    return max_vertex_texture_image_units_;
  }

  uint32 max_fragment_uniform_vectors() const {
    return max_fragment_uniform_vectors_;
  }

  uint32 max_varying_vectors() const {
    return max_varying_vectors_;
  }

  uint32 max_vertex_uniform_vectors() const {
    return max_vertex_uniform_vectors_;
  }

  uint32 max_color_attachments() const {
    return max_color_attachments_;
  }

  uint32 max_draw_buffers() const {
    return max_draw_buffers_;
  }

  FeatureInfo* feature_info() {
    return feature_info_.get();
  }

  BufferManager* buffer_manager() const {
    return buffer_manager_.get();
  }

  FramebufferManager* framebuffer_manager() const {
    return framebuffer_manager_.get();
  }

  RenderbufferManager* renderbuffer_manager() const {
    return renderbuffer_manager_.get();
  }

  TextureManager* texture_manager() const {
    return texture_manager_.get();
  }

  ProgramManager* program_manager() const {
    return program_manager_.get();
  }

  bool has_program_cache() const {
    return program_cache_ != NULL;
  }

  void set_program_cache(ProgramCache* program_cache) {
    program_cache_ = program_cache;
  }

  ShaderManager* shader_manager() const {
    return shader_manager_.get();
  }

  TransferBufferManagerInterface* transfer_buffer_manager() const {
    return transfer_buffer_manager_.get();
  }

  IdAllocatorInterface* GetIdAllocator(unsigned namespace_id);

  uint32 GetMemRepresented() const;

  // Loses all the context associated with this group.
  void LoseContexts(GLenum reset_status);

  // EXT_draw_buffer related states for backbuffer.
  GLenum draw_buffer() const {
    return draw_buffer_;
  }
  void set_draw_buffer(GLenum buf) {
    draw_buffer_ = buf;
  }

 private:
  friend class base::RefCounted<ContextGroup>;
  ~ContextGroup();

  bool CheckGLFeature(GLint min_required, GLint* v);
  bool CheckGLFeatureU(GLint min_required, uint32* v);
  bool QueryGLFeature(GLenum pname, GLint min_required, GLint* v);
  bool QueryGLFeatureU(GLenum pname, GLint min_required, uint32* v);
  bool HaveContexts();

  scoped_refptr<MailboxManager> mailbox_manager_;
  scoped_refptr<MemoryTracker> memory_tracker_;
  scoped_refptr<ShaderTranslatorCache> shader_translator_cache_;
  scoped_ptr<TransferBufferManagerInterface> transfer_buffer_manager_;

  bool enforce_gl_minimums_;
  bool bind_generates_resource_;

  uint32 max_vertex_attribs_;
  uint32 max_texture_units_;
  uint32 max_texture_image_units_;
  uint32 max_vertex_texture_image_units_;
  uint32 max_fragment_uniform_vectors_;
  uint32 max_varying_vectors_;
  uint32 max_vertex_uniform_vectors_;
  uint32 max_color_attachments_;
  uint32 max_draw_buffers_;

  ProgramCache* program_cache_;

  scoped_ptr<BufferManager> buffer_manager_;

  scoped_ptr<FramebufferManager> framebuffer_manager_;

  scoped_ptr<RenderbufferManager> renderbuffer_manager_;

  scoped_ptr<TextureManager> texture_manager_;

  scoped_ptr<ProgramManager> program_manager_;

  scoped_ptr<ShaderManager> shader_manager_;

  linked_ptr<IdAllocatorInterface>
      id_namespaces_[id_namespaces::kNumIdNamespaces];

  scoped_refptr<FeatureInfo> feature_info_;

  std::vector<base::WeakPtr<gles2::GLES2Decoder> > decoders_;

  GLenum draw_buffer_;

  DISALLOW_COPY_AND_ASSIGN(ContextGroup);
};

}  // namespace gles2
}  // namespace gpu

#endif  // GPU_COMMAND_BUFFER_SERVICE_CONTEXT_GROUP_H_


text:
<?php

/*
 * This file is part of php-cache organization.
 *
 * (c) 2015 Aaron Scherer <aequasi@gmail.com>, Tobias Nyholm <tobias.nyholm@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Cache\Adapter\Void\Tests;

use Cache\Adapter\Void\VoidCachePool;
use Cache\IntegrationTests\CachePoolTest as BaseTest;

class IntegrationPoolTest extends BaseTest
{
    protected $skippedTests = [
        'testBasicUsage'                     => 'Void adapter does not save,',
        'testGetItem'                        => 'Void adapter does not save,',
        'testGetItems'                       => 'Void adapter does not save,',
        'testHasItem'                        => 'Void adapter does not save,',
        'testDeleteItems'                    => 'Void adapter does not save,',
        'testSave'                           => 'Void adapter does not save,',
        'testSaveWithoutExpire'              => 'Void adapter does not save,',
        'testDataTypeFloat'                  => 'Void adapter only outputs boolean,',
        'testDataTypeBoolean'                => 'Void adapter only outputs boolean,',
        'testDataTypeArray'                  => 'Void adapter only outputs boolean,',
        'testDataTypeObject'                 => 'Void adapter only outputs boolean,',
        'testBinaryData'                     => 'Void adapter only outputs boolean,',
        'testDeferredSave'                   => 'Void adapter does not save,',
        'testDeferredSaveWithoutCommit'      => 'Void adapter does not save,',
        'testCommit'                         => 'Void adapter does not save,',
        'testExpiresAt'                      => 'Void adapter does not save,',
        'testExpiresAtWithNull'              => 'Void adapter does not save,',
        'testExpiresAfterWithNull'           => 'Void adapter does not save,',
        'testKeyLength'                      => 'Void adapter does not save,',
        'testDataTypeString'                 => 'Void adapter does not save,',
        'testDataTypeInteger'                => 'Void adapter does not save,',
        'testDataTypeNull'                   => 'Void adapter does not save,',
        'testIsHit'                          => 'Void adapter does not save,',
        'testIsHitDeferred'                  => 'Void adapter does not save,',
        'testSaveDeferredWhenChangingValues' => 'Void adapter does not save,',
        'testSavingObject'                   => 'Void adapter does not save,',
        'testSaveDeferredOverwrite'          => 'Void adapter does not save,',
    ];

    public function createCachePool()
    {
        return new VoidCachePool();
    }
}


text:
package org.cbioportal.genome_nexus.persistence.internal;

import org.cbioportal.genome_nexus.model.PdbHeader;
import org.cbioportal.genome_nexus.model.SimpleCacheEntity;
import org.cbioportal.genome_nexus.util.PdbHeaderParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public class PdbHeaderRepositoryImpl
    extends PlainTextMongoRepositoryImpl // this allows us to save the string value into the simple cache collection
    implements PdbHeaderRepositoryCustom<PdbHeader, String>
{
    public static final String COLLECTION = "pdb.header";

    private final PdbHeaderParser parser;

    @Autowired
    public PdbHeaderRepositoryImpl(MongoTemplate mongoTemplate, PdbHeaderParser parser)
    {
        super(mongoTemplate);
        this.parser = parser;
    }

    @Override
    public Optional<PdbHeader> findById(String id)
    {
        SimpleCacheEntity entity = this.mongoTemplate.findById(id, SimpleCacheEntity.class, COLLECTION);
        PdbHeader instance = null;

        // and then map it to a PdbHeader instance to return
        if (entity != null) {
            instance = this.parser.convertToInstance(entity.getValue());
        }

        return Optional.ofNullable(instance);
    }
}


text:
@implementation NSString (SSAddition)

- (BOOL)ss_containsString:(NSString *)string {
    return !NSEqualRanges([self rangeOfString:string], NSMakeRange(NSNotFound, 0));
}

- (NSString *)ss_md5 {
    if(self == nil || [self length] == 0)
        return nil;

    const char *value = [self UTF8String];

    unsigned char outputBuffer[CC_MD5_DIGEST_LENGTH];
    CC_MD5(value, (CC_LONG)strlen(value), outputBuffer);

    NSMutableString *outputString = [[NSMutableString alloc] initWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(NSInteger count = 0; count < CC_MD5_DIGEST_LENGTH; count++){
        [outputString appendFormat:@"%02x",outputBuffer[count]];
    }

    return outputString;
}

- (NSString *)reversedString {
    NSMutableString *reverseString = [[NSMutableString alloc] init];
    NSInteger charIndex = [self length];
    while (charIndex > 0) {
        charIndex --;
        NSRange subStrRange = NSMakeRange(charIndex, 1);
        [reverseString appendString:[self substringWithRange:subStrRange]];
    }
    return reverseString;
}

- (NSString *)trimmingWhitespace {
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}

- (NSString *)trimmingWhitespaceAndNewlines {
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

//Unicode编码的字符串转成NSString
- (NSString *)makeUnicodeToString {
    NSString *tempStr1 = [self stringByReplacingOccurrencesOfString:@"\\u"withString:@"\\U"];
    NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\""withString:@"\\\""];
    NSString *tempStr3 = [[@"\""stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    //NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData mutabilityOption:NSPropertyListImmutable format:NULL errorDescription:NULL];

    NSString *returnStr = [NSPropertyListSerialization propertyListWithData:tempData options:NSPropertyListMutableContainersAndLeaves format:NULL error:NULL];

    return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n"withString:@"\n"];
}

- (NSString *)capitalizedSentence {
    return [self stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[self substringToIndex:1] capitalizedString]];
}

- (NSInteger)numberOfLineBreaks {
    NSInteger numberOfBreaks = [self componentsSeparatedByString:@"\n"].count;
    if (numberOfBreaks > 1) return numberOfBreaks-1;
    else return 0;
}

- (NSString *)stringByStrippingHTML {
    return [self stringByReplacingOccurrencesOfString:@"<[^>]+>" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, self.length)];
}

- (NSString *)stringByRemovingScriptsAndStrippingHTML {
    NSMutableString *mString = [self mutableCopy];
    NSError *error;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<script[^>]*>[\\w\\W]*</script>" options:NSRegularExpressionCaseInsensitive error:&error];
    NSArray *matches = [regex matchesInString:mString options:NSMatchingReportProgress range:NSMakeRange(0, [mString length])];
    for (NSTextCheckingResult *match in [matches reverseObjectEnumerator]) {
        [mString replaceCharactersInRange:match.range withString:@""];
    }
    return [mString stringByStrippingHTML];
}

#pragma mark - Working with Ranges

- (NSRange)ss_composedRangeWithRange:(NSRange)range {
    // We're going to make a new range that takes into account surrogate unicode pairs (composed characters)
    __block NSRange adjustedRange = NSMakeRange(range.location, range.length);
    NSUInteger length = self.length;

    // Adjust range location for composed characters that appear before the original range.
    [self enumerateSubstringsInRange:NSMakeRange(0, length) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        // Stop if we've past the end of the range to be adjusted
        if (substringRange.location >= adjustedRange.location) {
            *stop = YES;
            return;
        }

        adjustedRange.location += (substringRange.length - 1);
    }];

    // Adjust range length for composed characters that appear within the original range.
    [self enumerateSubstringsInRange:NSMakeRange(adjustedRange.location, length - adjustedRange.location) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        adjustedRange.length += (substringRange.length - 1);

        // Stop if we're finished
        if (NSMaxRange(substringRange) >= NSMaxRange(adjustedRange)) {
            *stop = YES;
        }
    }];

    // Return the adjusted range
    return adjustedRange;
}

- (NSString *)ss_composedSubstringWithRange:(NSRange)range {
    // Return a substring using a composed range so surrogate unicode pairs (composed characters) count as 1 in the
    // range instead of however many unichars they actually are.
    return [self substringWithRange:[self ss_composedRangeWithRange:range]];
}

- (NSRange)ss_wordRangeAtIndex:(NSUInteger)index {
    NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
    NSInteger beginIndex = index;
    while(beginIndex > 0 && ![whitespace characterIsMember:[self characterAtIndex:beginIndex - 1]]) {
        beginIndex--;
    }

    NSInteger endIndex = index;
    NSInteger lenght = [self length];
    while (endIndex < lenght && ![whitespace characterIsMember:[self characterAtIndex:endIndex]]) {
        endIndex++;
    }
    return NSMakeRange(beginIndex, endIndex - beginIndex);
}

@end


text:
This document provides a guide for installing AWX.

## Table of contents

- [Getting started](#getting-started)
  - [Clone the repo](#clone-the-repo)
  - [AWX branding](#awx-branding)
  - [Prerequisites](#prerequisites)
  - [System Requirements](#system-requirements)
  - [AWX Tunables](#awx-tunables)
  - [Choose a deployment platform](#choose-a-deployment-platform)
  - [Official vs Building Images](#official-vs-building-images)
- [OpenShift](#openshift)
  - [Prerequisites](#prerequisites-1)
    - [Deploying to Minishift](#deploying-to-minishift)
  - [Pre-build steps](#pre-build-steps)
  - [PostgreSQL](#postgresql)
  - [Start the build](#start-the-build)
  - [Post build](#post-build)
  - [Accessing AWX](#accessing-awx)
- [Kubernetes](#kubernetes)
  - [Prerequisites](#prerequisites-2)
  - [Pre-build steps](#pre-build-steps-1)
  - [Configuring Helm](#configuring-helm)
  - [Start the build](#start-the-build-1)
  - [Accessing AWX](#accessing-awx-1)
  - [SSL Termination](#ssl-termination)
- [Docker or Docker Compose](#docker-or-docker-compose)
  - [Prerequisites](#prerequisites-3)
  - [Pre-build steps](#pre-build-steps-2)
    - [Deploying to a remote host](#deploying-to-a-remote-host)
    - [Inventory variables](#inventory-variables)
      - [Docker registry](#docker-registry)
      - [PostgreSQL](#postgresql-1)
      - [Proxy settings](#proxy-settings)
  - [Start the build](#start-the-build-2)
  - [Post build](#post-build-1)
  - [Accessing AWX](#accessing-awx-2)

## Getting started

### Clone the repo

If you have not already done so, you will need to clone, or create a local copy, of the [AWX repo](https://github.com/ansible/awx). For more on how to clone the repo, view [git clone help](https://git-scm.com/docs/git-clone).

Once you have a local copy, run commands within the root of the project tree.

### AWX branding

You can optionally install the AWX branding assets from the [awx-logos repo](https://github.com/ansible/awx-logos). Prior to installing, please review and agree to the [trademark guidelines](https://github.com/ansible/awx-logos/blob/master/TRADEMARKS.md).

To install the assets, clone the `awx-logos` repo so that it is next to your `awx` clone. As you progress through the installation steps, you'll be setting variables in the [inventory](./installer/inventory) file. To include the assets in the build, set `awx_official=true`.

### Prerequisites

Before you can run a deployment, you'll need the following installed in your local environment:

- [Ansible](http://docs.ansible.com/ansible/latest/intro_installation.html) Requires Version 2.4+
- [Docker](https://docs.docker.com/engine/installation/)
- [docker-py](https://github.com/docker/docker-py) Python module
- [GNU Make](https://www.gnu.org/software/make/)
- [Git](https://git-scm.com/) Requires Version 1.8.4+
- [Node 8.x LTS version](https://nodejs.org/en/download/)
- [NPM 6.x LTS](https://docs.npmjs.com/)

### System Requirements

The system that runs the AWX service will need to satisfy the following requirements

- At leasts 4GB of memory
- At least 2 cpu cores
- At least 20GB of space
- Running Docker, Openshift, or Kubernetes
- If you choose to use an external PostgreSQL database, please note that the minimum version is 9.4.

### AWX Tunables

**TODO** add tunable bits

### Choose a deployment platform

We currently support running AWX as a containerized application using Docker images deployed to either an OpenShift cluster, docker-compose or a standalone Docker daemon. The remainder of this document will walk you through the process of building the images, and deploying them to either platform.

The [installer](./installer) directory contains an [inventory](./installer/inventory) file, and a playbook, [install.yml](./installer/install.yml). You'll begin by setting variables in the inventory file according to the platform you wish to use, and then you'll start the image build and deployment process by running the playbook.

In the sections below, you'll find deployment details and instructions for each platform:
- [OpenShift](#openshift)
- [Kubernetes](#kubernetes)
- [Docker or Docker Compose](#docker-or-docker-compose).

### Official vs Building Images

When installing AWX you have the option of building your own images or using the images provided on DockerHub (see [awx_web](https://hub.docker.com/r/ansible/awx_web/) and [awx_task](https://hub.docker.com/r/ansible/awx_task/))

This is controlled by the following variables in the `inventory` file

```
dockerhub_base=ansible
dockerhub_version=latest
```

If these variables are present then all deployments will use these hosted images. If the variables are not present then the images will be built during the install.

*dockerhub_base*

> The base location on DockerHub where the images are hosted (by default this pulls container images named `ansible/awx_web:tag` and `ansible/awx_task:tag`)

*dockerhub_version*

> Multiple versions are provided. `latest` always pulls the most recent. You may also select version numbers at different granularities: 1, 1.0, 1.0.1, 1.0.0.123

## OpenShift

### Prerequisites

To complete a deployment to OpenShift, you will obviously need access to an OpenShift cluster. For demo and testing purposes, you can use [Minishift](https://github.com/minishift/minishift) to create a single node cluster running inside a virtual machine.

You will also need to have the `oc` command in your PATH. The `install.yml` playbook will call out to `oc` when logging into, and creating objects on the cluster.

The default resource requests per-deployment requires:

> Memory: 6GB
> CPU: 3 cores

This can be tuned by overriding the variables found in [/installer/roles/kubernetes/defaults/main.yml](/installer/roles/kubernetes/defaults/main.yml). Special care should be taken when doing this as undersized instances will experience crashes and resource exhaustion.

For more detail on how resource requests are formed see: [https://docs.openshift.com/container-platform/latest/dev_guide/compute_resources.html#dev-compute-resources](https://docs.openshift.com/container-platform/latest/dev_guide/compute_resources.html#dev-compute-resources)

### Pre-build steps

Before starting the build process, review the [inventory](./installer/inventory) file, and uncomment and provide values for the following variables found in the `[all:vars]` section:

*openshift_host*

> IP address or hostname of the OpenShift cluster. If you're using Minishift, this will be the value returned by `minishift ip`.

*openshift_skip_tls_verify*

> Boolean. Set to True if using self-signed certs.

*openshift_project*

> Name of the OpenShift project that will be created, and used as the namespace for the AWX app. Defaults to *awx*.

*openshift_user*

> Username of the OpenShift user that will create the project, and deploy the application. Defaults to *developer*.

*openshift_pg_emptydir*

> Boolean. Set to True to use an emptyDir volume when deploying the PostgreSQL pod. Note: This should only be used for demo and testing purposes.

*docker_registry*

> IP address and port, or URL, for accessing a registry that the OpenShift cluster can access. Defaults to *172.30.1.1:5000*, the internal registry delivered with Minishift. This is not needed if you are using official hosted images.

*docker_registry_repository*

> Namespace to use when pushing and pulling images to and from the registry. Generally this will match the project name. It defaults to *awx*. This is not needed if you are using official hosted images.

*docker_registry_username*

> Username of the user that will push images to the registry. Will generally match the *openshift_user* value. Defaults to *developer*. This is not needed if you are using official hosted images.

#### Deploying to Minishift

Install Minishift by following the [installation guide](https://docs.openshift.org/latest/minishift/getting-started/installing.html).

The recommended minimum resources for your Minishift VM:

```bash
$ minishift start --cpus=4 --memory=8GB
```

The Minishift VM contains a Docker daemon, which you can use to build the AWX images. This is generally the approach you should take, and we recommend doing so. To use this instance, run the following command to setup your environment:

```bash
# Set DOCKER environment variable to point to the Minishift VM
$ eval $(minishift docker-env)
```

**Note**

> If you choose to not use the Docker instance running inside the VM, and build the images externally, you will have to enable the OpenShift cluster to access the images. This involves pushing the images to an external Docker registry, and granting the cluster access to it, or exposing the internal registry, and pushing the images into it.

#### PostgreSQL

By default, AWX will deploy a PostgreSQL pod inside of your cluster. You will need to create a [Persistent Volume Claim](https://docs.openshift.org/latest/dev_guide/persistent_volumes.html) which is named `postgresql` by default, and can be overridden by setting the `openshift_pg_pvc_name` variable. For testing and demo purposes, you may set `openshift_pg_emptydir=yes`.

If you wish to use an external database, in the inventory file, set the value of `pg_hostname`, and update `pg_username`, `pg_password`, `pg_database`, and `pg_port` with the connection information. When setting `pg_hostname` the installer will assume you have configured the database in that location and will not launch the postgresql pod.

### Start the build

To start the build, you will pass two *extra* variables on the command line. The first is *openshift_password*, which is the password for the *openshift_user*, and the second is *docker_registry_password*, which is the password associated with *docker_registry_username*.

If you're using the OpenShift internal registry, then you'll pass an access token for the *docker_registry_password* value, rather than a password. The `oc whoami -t` command will generate the required token, as long as you're logged into the cluster via `oc cluster login`.

To start the build and deployment, run the following (docker_registry_password is optional if using official images):

```bash
# Start the build and deployment
$ ansible-playbook -i inventory install.yml -e openshift_password=developer  -e docker_registry_password=$(oc whoami -t)
```

### Post build

After the playbook run completes, check the status of the deployment by running `oc get pods`:

```bash
# View the running pods
$ oc get pods

NAME                   READY     STATUS    RESTARTS   AGE
awx-3886581826-5mv0l   4/4       Running   0          8s
postgresql-1-l85fh     1/1       Running   0          20m

```

In the above example, the name of the AWX pod is `awx-3886581826-5mv0l`. Before accessing the AWX web interface, setup tasks and database migrations need to complete. These tasks are running in the `awx_task` container inside the AWX pod. To monitor their status, tail the container's STDOUT by running the following command, replacing the AWX pod name with the pod name from your environment:

```bash
# Follow the awx_task log output
$ oc logs -f awx-3886581826-5mv0l -c awx-celery
```

You will see the following indicating that database migrations are running:

```bash
Using /etc/ansible/ansible.cfg as config file
127.0.0.1 | SUCCESS => {
    "changed": false,
    "db": "awx"
}
Operations to perform:
  Synchronize unmigrated apps: solo, api, staticfiles, messages, channels, django_extensions, ui, rest_framework, polymorphic
  Apply all migrations: sso, taggit, sessions, sites, kombu_transport_django, social_auth, contenttypes, auth, conf, main
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying contenttypes.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0001_initial... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying taggit.0001_initial... OK
  Applying taggit.0002_auto_20150616_2121... OK
  ...
```

When you see output similar to the following, you'll know that database migrations have completed, and you can access the web interface:

```bash
Python 2.7.5 (default, Nov  6 2016, 00:28:07)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)

>>> <User: admin>
>>> Default organization added.
Demo Credential, Inventory, and Job Template added.
Successfully registered instance awx-3886581826-5mv0l
(changed: True)
Creating instance group tower
Added instance awx-3886581826-5mv0l to tower
```

Once database migrations complete, the web interface will be accessible.

### Accessing AWX

The AWX web interface is running in the AWX pod, behind the `awx-web-svc` service. To view the service, and its port value, run the following command:

```bash
# View available services
$ oc get services

NAME          CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE
awx-web-svc   172.30.111.74   <nodes>       8052:30083/TCP   37m
postgresql    172.30.102.9    <none>        5432/TCP         38m
```

The deployment process creates a route, `awx-web-svc`, to expose the service. How the ingres is actually created will vary depending on your environment, and how the cluster is configured. You can view the route, and the external IP address and hostname assigned to it, by running the following command:

```bash
# View available routes
$ oc get routes

NAME          HOST/PORT                             PATH      SERVICES      PORT      TERMINATION   WILDCARD
awx-web-svc   awx-web-svc-awx.192.168.64.2.nip.io             awx-web-svc   http      edge/Allow    None
```

The above example is taken from a Minishift instance. From a web browser, use `https` to access the `HOST/PORT` value from your environment. Using the above example, the URL to access the server would be [https://awx-web-svc-awx.192.168.64.2.nip.io](https://awx-web-svc-awx.192.168.64.2.nip.io).

Once you access the AWX server, you will be prompted with a login dialog. The default administrator username is `admin`, and the password is `password`.

## Kubernetes

### Prerequisites

A Kubernetes deployment will require you to have access to a Kubernetes cluster as well as the following tools:

- [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/)
- [helm](https://docs.helm.sh/using_helm/#quickstart-guide)

The installation program will reference `kubectl` directly. `helm` is only necessary if you are letting the installer configure PostgreSQL for you.

The default resource requests per-pod requires:

> Memory: 6GB
> CPU: 3 cores

This can be tuned by overriding the variables found in [/installer/roles/kubernetes/defaults/main.yml](/installer/roles/kubernetes/defaults/main.yml). Special care should be taken when doing this as undersized instances will experience crashes and resource exhaustion.

For more detail on how resource requests are formed see: [https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/](https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/)

### Pre-build steps

Before starting the build process, review the [inventory](./installer/inventory) file, and uncomment and provide values for the following variables found in the `[all:vars]` section uncommenting when necessary. Make sure the openshift and standalone docker sections are commented out:

*kubernetes_context*

> Prior to running the installer, make sure you've configured the context for the cluster you'll be installing to. This is how the installer knows which cluster to connect to and what authentication to use

*kubernetes_namespace*

> Name of the Kubernetes namespace where the AWX resources will be installed. This will be created if it doesn't exist

*docker_registry_*

> These settings should be used if building your own base images. You'll need access to an external registry and are responsible for making sure your kube cluster can talk to it and use it. If these are undefined and the dockerhub_ configuration settings are uncommented then the images will be pulled from dockerhub instead

### Configuring Helm

If you want the AWX installer to manage creating the database pod (rather than installing and configuring postgres on your own). Then you will need to have a working `helm` installation, you can find details here: [https://docs.helm.sh/using_helm/#quickstart-guide](https://docs.helm.sh/using_helm/#quickstart-guide).

Newer Kubernetes clusters with RBAC enabled will need to make sure a service account is created, make sure to follow the instructions here [https://docs.helm.sh/using_helm/#role-based-access-control](https://docs.helm.sh/using_helm/#role-based-access-control)

### Start the build

After making changes to the `inventory` file use `ansible-playbook` to begin the install

```bash
$ ansible-playbook -i inventory install.yml
```

### Post build

After the playbook run completes, check the status of the deployment by running `kubectl get pods --namespace awx` (replace awx with the namespace you used):

```bash
# View the running pods, it may take a few minutes for everything to be marked in the Running state
$ kubectl get pods --namespace awx
NAME                             READY     STATUS    RESTARTS   AGE
awx-2558692395-2r8ss             4/4       Running   0          29s
awx-postgresql-355348841-kltkn   1/1       Running   0          1m
```

### Accessing AWX

The AWX web interface is running in the AWX pod behind the `awx-web-svc` service:

```bash
# View available services
$ kubectl get svc --namespace awx
NAME             TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)        AGE
awx-postgresql   ClusterIP   10.7.250.208   <none>        5432/TCP       2m
awx-web-svc      NodePort    10.7.241.35    <none>        80:30177/TCP   1m
```

The deployment process creates an `Ingress` named `awx-web-svc` also. Some kubernetes cloud providers will automatically handle routing configuration when an Ingress is created others may require that you more explicitly configure it. You can see what kubernetes knows about things with:

```bash
 kubectl get ing --namespace awx
NAME          HOSTS     ADDRESS          PORTS     AGE
awx-web-svc   *         35.227.x.y       80        3m
```

If your provider is able to allocate an IP Address from the Ingress controller then you can navigate to the address and access the AWX interface. For some providers it can take a few minutes to allocate and make this accessible. For other providers it may require you to manually intervene.

### SSL Termination

Unlike Openshift's `Route` the Kubernetes `Ingress` doesn't yet handle SSL termination. As such the default configuration will only expose AWX through HTTP on port 80. You are responsible for configuring SSL support until support is added (either to Kubernetes or AWX itself).

## Docker or Docker-Compose

### Prerequisites

- [Docker](https://docs.docker.com/engine/installation/) on the host where AWX will be deployed. After installing Docker, the Docker service must be started (depending on your OS, you may have to add the local user that uses Docker to the ``docker`` group, refer to the documentation for details)
- [docker-py](https://github.com/docker/docker-py) Python module.

If you're installing using Docker Compose, you'll need [Docker Compose](https://docs.docker.com/compose/install/).

### Pre-build steps

#### Deploying to a remote host

By default, the delivered [installer/inventory](./installer/inventory) file will deploy AWX to the local host. It is possible, however, to deploy to a remote host. The [installer/install.yml](./installer/install.yml) playbook can be used to build images on the local host, and ship the built images to, and run deployment tasks on, a remote host. To do this, modify the [installer/inventory](./installer/inventory) file, by commenting out `localhost`, and adding the remote host.

For example, suppose you wish to build images locally on your CI/CD host, and deploy them to a remote host named *awx-server*. To do this, add *awx-server* to the [installer/inventory](./installer/inventory) file, and comment out or remove `localhost`, as demonstrated by the following:

```yaml
# localhost ansible_connection=local
awx-server

[all:vars]
...
```

In the above example, image build tasks will be delegated to `localhost`, which is typically where the clone of the AWX project exists. Built images will be archived, copied to remote host, and imported into the remote Docker image cache. Tasks to start the AWX containers will then execute on the remote host.

If you choose to use the official images then the remote host will be the one to pull those images.

**Note**

> You may also want to set additional variables to control how Ansible connects to the host. For more information about this, view [Behavioral Inventory Parameters](http://docs.ansible.com/ansible/latest/intro_inventory.html#id12).

> As mentioned above, in [Prerequisites](#prerequisites-1), the prerequisites are required on the remote host.

> When deploying to a remote host, the playbook does not execute tasks with the `become` option. For this reason, make sure the user that connects to the remote host has privileges to run the `docker` command. This typically means that non-privileged users need to be part of the `docker` group.

#### Inventory variables

Before starting the build process, review the [inventory](./installer/inventory) file, and uncomment and provide values for the following variables found in the `[all:vars]` section:

*postgres_data_dir*

> If you're using the default PostgreSQL container (see [PostgreSQL](#postgresql-1) below), provide a path that can be mounted to the container, and where the database can be persisted.

*host_port*

> Provide a port number that can be mapped from the Docker daemon host to the web server running inside the AWX container. Defaults to *80*.

*use_docker_compose*

> Switch to ``true`` to use Docker Compose instead of the standalone Docker install.

*docker_compose_dir*

When using docker-compose, the `docker-compose.yml` file will be created there (default `/var/lib/awx`).

*ca_trust_dir*

> If you're using a non trusted CA, provide a path where the untrusted Certs are stored on your Host.

#### Docker registry

If you wish to tag and push built images to a Docker registry, set the following variables in the inventory file:

*docker_registry*

> IP address and port, or URL, for accessing a registry.

*docker_registry_repository*

> Namespace to use when pushing and pulling images to and from the registry. Defaults to *awx*.

*docker_registry_username*

> Username of the user that will push images to the registry. Defaults to *developer*.

*docker_remove_local_images*

> Due to the way that the docker_image module behaves, images will not be pushed to a remote repository if they are present locally.  Set this to delete local versions of the images that will be pushed to the remote.  This will fail if containers are currently running from those images.

**Note**

> These settings are ignored if using official images

#### Proxy settings

*http_proxy*

> IP address and port, or URL, for using an http_proxy.

*https_proxy*

> IP address and port, or URL, for using an https_proxy.

*no_proxy*

> Exclude IP address or URL from the proxy.

#### PostgreSQL

AWX requires access to a PostgreSQL database, and by default, one will be created and deployed in a container, and data will be persisted to a host volume. In this scenario, you must set the value of `postgres_data_dir` to a path that can be mounted to the container. When the container is stopped, the database files will still exist in the specified path.

If you wish to use an external database, in the inventory file, set the value of `pg_hostname`, and update `pg_username`, `pg_password`, `pg_database`, and `pg_port` with the connection information.

### Start the build

If you are not pushing images to a Docker registry, start the build by running the following:

```bash
# Set the working directory to installer
$ cd installer

# Run the Ansible playbook
$ ansible-playbook -i inventory install.yml
```

If you're pushing built images to a repository, then use the `-e` option to pass the registry password as follows, replacing *password* with the password of the username assigned to `docker_registry_username` (note that you will also need to remove `dockerhub_base` and `dockerhub_version` from the inventory file):

```bash
# Set the working directory to installer
$ cd installer

# Run the Ansible playbook
$ ansible-playbook -i inventory -e docker_registry_password=password install.yml
```

### Post build

After the playbook run completes, Docker will report up to 5 running containers. If you chose to use an existing PostgresSQL database, then it will report 4. You can view the running containers using the `docker ps` command, as follows:

```bash
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                NAMES
e240ed8209cd        awx_task:1.0.0.8    "/tini -- /bin/sh ..."   2 minutes ago       Up About a minute   8052/tcp                             awx_task
1cfd02601690        awx_web:1.0.0.8     "/tini -- /bin/sh ..."   2 minutes ago       Up About a minute   0.0.0.0:80->8052/tcp                 awx_web
55a552142bcd        memcached:alpine    "docker-entrypoint..."   2 minutes ago       Up 2 minutes        11211/tcp                            memcached
84011c072aad        rabbitmq:3          "docker-entrypoint..."   2 minutes ago       Up 2 minutes        4369/tcp, 5671-5672/tcp, 25672/tcp   rabbitmq
97e196120ab3        postgres:9.6        "docker-entrypoint..."   2 minutes ago       Up 2 minutes        5432/tcp                             postgres
```

If you're deploying using Docker Compose, container names will be prefixed by the name of the folder where the docker-compose.yml file is created (by default, `awx`).

Immediately after the containers start, the *awx_task* container will perform required setup tasks, including database migrations. These tasks need to complete before the web interface can be accessed. To monitor the progress, you can follow the container's STDOUT by running the following:

```bash
# Tail the the awx_task log
$ docker logs -f awx_task
```

You will see output similar to the following:

```bash
Using /etc/ansible/ansible.cfg as config file
127.0.0.1 | SUCCESS => {
    "changed": false,
    "db": "awx"
}
Operations to perform:
  Synchronize unmigrated apps: solo, api, staticfiles, messages, channels, django_extensions, ui, rest_framework, polymorphic
  Apply all migrations: sso, taggit, sessions, sites, kombu_transport_django, social_auth, contenttypes, auth, conf, main
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying contenttypes.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0001_initial... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying taggit.0001_initial... OK
  Applying taggit.0002_auto_20150616_2121... OK
  Applying main.0001_initial... OK
...
```

Once migrations complete, you will see the following log output, indicating that migrations have completed:

```bash
Python 2.7.5 (default, Nov  6 2016, 00:28:07)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)

>>> <User: admin>
>>> Default organization added.
Demo Credential, Inventory, and Job Template added.
Successfully registered instance awx
(changed: True)
Creating instance group tower
Added instance awx to tower
(changed: True)
...
```

### Accessing AWX

The AWX web server is accessible on the deployment host, using the *host_port* value set in the *inventory* file. The default URL is [http://localhost](http://localhost).

You will prompted with a login dialog. The default administrator username is `admin`, and the password is `password`.

### Maintenance using docker-compose

After the installation, maintenance operations with docker-compose can be done by using the  `docker-compose.yml` file created at the location pointed by `docker_compose_dir`.

Among the possible operations, you may:

- Stop AWX : `docker-compose stop`
- Upgrade AWX : `docker-compose pull && docker-compose up --force-recreate`

See the [docker-compose documentation](https://docs.docker.com/compose/) for details.


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of PaymentController
 *
 * @author anurartkae
 */
class PaymentController  extends CI_Controller{
    function __construct() {
        parent::__construct();
        $this->load->library('cart');
    }
    public function index(){

        $this->load->view('frontend/payment');

    }
}


text:
package org.xbib.catalog.entities.mab;

import org.xbib.catalog.entities.CatalogEntity;

import java.util.Map;

/**
 *
 */
public class SourceIdentifier extends CatalogEntity {

    public SourceIdentifier(Map<String, Object> params) {
        super(params);
    }
}


text:
package mesos

import (
	"log"
	"net"
	"regexp"
	"strconv"
	"strings"
)

func cleanName(name string) string {
	reg, err := regexp.Compile("[^\\w-.\\.]")
	if err != nil {
		log.Print("[WARN] ", err)
		return name
	}

	s := reg.ReplaceAllString(name, "")

	return strings.ToLower(strings.Replace(s, "_", "", -1))
}

// The PID has a specific format:
// type@host:port
func parsePID(pid string) (string, string) {
	host := strings.Split(strings.Split(pid, ":")[0], "@")[1]
	port := strings.Split(pid, ":")[1]

	return toIP(host), port
}

func leaderIP(leader string) string {
	host := strings.Split(leader, "@")[1]
	host = strings.Split(host, ":")[0]

	return toIP(host)
}

func toIP(host string) string {
	// Check if host string is already an IP address
	ip := net.ParseIP(host)
	if ip != nil {
		return host
	}

	// Try to resolve host
	ips, err := net.LookupIP(host)
	if err != nil {
		// Return the hostname if unable to resolve
		return host
	}

	return ips[0].String()
}

func toPort(p string) int {
	ps, err := strconv.Atoi(p)
	if err != nil {
		log.Printf("[ERROR] Invalid port number: %s", p)
	}

	return ps
}


text:
export function SayHello() {
  return true;
}


text:
using System;
using System.Runtime.InteropServices;

namespace Noesis
{

public class QuarticEase : EasingFunctionBase {
  internal new static QuarticEase CreateProxy(IntPtr cPtr, bool cMemoryOwn) {
    return new QuarticEase(cPtr, cMemoryOwn);
  }

  internal QuarticEase(IntPtr cPtr, bool cMemoryOwn) : base(cPtr, cMemoryOwn) {
  }

  internal static HandleRef getCPtr(QuarticEase obj) {
    return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
  }

  public QuarticEase() {
  }

  protected override IntPtr CreateCPtr(Type type, out bool registerExtend) {
    registerExtend = false;
    return NoesisGUI_PINVOKE.new_QuarticEase();
  }

  new internal static IntPtr GetStaticType() {
    IntPtr ret = NoesisGUI_PINVOKE.QuarticEase_GetStaticType();
    if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
    return ret;
  }

}

}


text:
namespace ai
{
	namespace bt
	{
        #pragma region IComposite

        class IComposite
        : public Behaviour
        {
        public:
            virtual ~IComposite(){};

            virtual void addChild(Behaviour* child_) = 0;
            virtual void removeChild(Behaviour* child_) =0;
            virtual void removeAllChildren() = 0;
        };

        #pragma endregion

		#pragma region Composite

		template<template<class>class _ContainerType>
		class Composite
		: public IComposite
		{
		public:

			#pragma region Typedefs

			typedef _ContainerType<Behaviour*>	Container;
			typedef typename Container::iterator	Container_it;

			#pragma endregion

			virtual ~Composite();

			#pragma region Accessors

			inline Container& children();
            inline size_t childrenCount() const;

			#pragma endregion

			#pragma region Children List Mutation

			inline virtual void addChild(Behaviour* child_) override;
			// insert before
			inline virtual void insertChild(Container_it loc_, Behaviour* child_);
            inline virtual void removeChild(Behaviour* child_) override;
			inline virtual void removeChild(Container_it loc_);
            inline virtual void removeAllChildren() override;

			#pragma endregion

		private:

            inline static bool remove(Behaviour* child_);

			Container m_children;
		};

		#pragma endregion
	}
}

#include "BTComposite_impl.hpp"

#endif //AI_BT_Composite_hpp


text:
<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="2.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="
      http://java.sun.com/xml/ns/javaee
      http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd">

	<!-- Login Inicio -->
	<navigation-rule>
		<from-view-id>/pages/login/login.xhtml</from-view-id>
		<navigation-case>
			<from-outcome>sucesso</from-outcome>
			<to-view-id>/pages/usuario/telaPrincipal.xhtml</to-view-id>
		</navigation-case>
		<navigation-case>
			<from-outcome>fracasso</from-outcome>
			<to-view-id>/pages/login/login.xhtml</to-view-id>
		</navigation-case>
		<navigation-case>
			<from-outcome>cadastro</from-outcome>
			<to-view-id>/pages/usuario/cadastro-usuario.xhtml</to-view-id>
		</navigation-case>
	</navigation-rule>
	<!-- Login Fim -->

	<!-- Usuarios Inicio -->
	<navigation-rule>
		<from-view-id>*</from-view-id>
		<navigation-case>
			<from-outcome>sucesso</from-outcome>
			<to-view-id>/pages/usuario/cadastro-usuario.xhtml</to-view-id>
		</navigation-case>
	</navigation-rule>

	<navigation-rule>
		<from-view-id>/pages/usuario/cadastro-usuario.xhtml</from-view-id>
		<navigation-case>
			<from-outcome>sucesso</from-outcome>
			<to-view-id>/pages/usuario/lista-usuario.xhtml</to-view-id>
		</navigation-case>
	</navigation-rule>

	<navigation-rule>
		<from-view-id>/pages/usuario/lista-usuario.xhtml</from-view-id>
		<navigation-case>
			<from-outcome>atualiza</from-outcome>
			<to-view-id>/pages/usuario/atualizaUsuario.xhtml</to-view-id>
		</navigation-case>
	</navigation-rule>

	<navigation-rule>
		<from-view-id>/pages/usuario/cadastro-usuario.xhtml</from-view-id>
		<navigation-case>
			<from-outcome>voltar</from-outcome>
			<to-view-id>/pages/login/login.xhtml</to-view-id>
		</navigation-case>
		<navigation-case>
			<from-outcome>sucesso</from-outcome>
			<to-view-id>/pages/login/login.xhtml</to-view-id>
		</navigation-case>
	</navigation-rule>

	<navigation-rule>
		<from-view-id>/pages/usuario/atualizaUsuario.xhtml</from-view-id>
		<navigation-case>
			<from-outcome>sucesso</from-outcome>
			<to-view-id>/pages/usuario/listUsuario.xhtml</to-view-id>
		</navigation-case>
	</navigation-rule>
	<!-- Usuarios Fim -->

	<application>
		<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
		<locale-config>
		</locale-config>
		<resource-bundle>
			<base-name>MessageResources</base-name>
			<var>messages</var>
		</resource-bundle>
	</application>
</faces-config>