text:
"use strict";

import "es6-promise/auto";

import Vue from "vue/dist/vue.js";
import store from "./libs/store";

import * as Utility from "./libs/utility";

import * as capitalize from "vue2-filters/src/string/capitalize";

window.d3 = require("d3");

(() => {
	if(navigator.userAgent === 'jsdom'){ return; }

	window.socket = require("socket.io-client")(`http://${window.location.hostname}:8888`, { reconnection: false });

	Vue.filter('capitalize', capitalize.default);

	var app = new Vue({
		el: '#app',
		store: store,
		components: {
			'vchart': require('../vue/components/VChart/VChart.vue').default,
			'vfood': require('../vue/components/VFood/VFood.vue').default,
			'vshopping': require('../vue/components/VShopping/VShopping.vue').default,
			'vmacros': require('../vue/components/VMacros/VMacros.vue').default,
			'vstopwatch': require('../vue/components/VStopwatch/VStopwatch.vue').default,
			'vexercises': require('../vue/components/VExercises/VExercises.vue').default,
			'vworkout': require('../vue/components/VWorkout/VWorkout.vue').default
		}
	});

	var keys = Object.keys(store.state.exercises);
	Promise.all(keys.map(d => Utility.load(`media/data/${d.toLowerCase()}.json`)))
		.then((areas) => {
			store.commit('exercises', areas.reduce((prev, next, i) => {
				prev[keys[i]] = next;
				return prev;
			}, {}));
		});

	Utility.load("media/data/food.json").then(d => store.commit('foods', d));
	Utility.load("media/data/macros.json").then(d => store.commit('macros', d));
	Utility.load("media/data/weight.json").then((d) => store.commit('weight', d));

	Utility.toggles();

	if(window.socket){
		window.socket.on('closeWindow', function (data) {
			window.close();
		});
	}

	document.querySelector('html').classList.remove('loading');
	document.querySelector('html').classList.add('loaded');
})();


text:
// Copyright 2009-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0

#include "../common/tutorial/tutorial.h"
#include "../common/tutorial/benchmark_render.h"

namespace embree
{
  struct Tutorial : public TutorialApplication
  {
    Tutorial()
      : TutorialApplication("displacement_geometry",FEATURE_RTCORE)
    {
      /* set default camera */
      camera.from = Vec3fa(1.5f,1.5f,-1.5f);
      camera.to   = Vec3fa(0.0f,0.0f,0.0f);
    }
  };

}

int main(int argc, char** argv) {
  if (embree::TutorialBenchmark::benchmark(argc, argv)) {
    return embree::TutorialBenchmark(embree::renderBenchFunc<embree::Tutorial>).main(argc, argv, "displacement_geometry");
  }
  return embree::Tutorial().main(argc,argv);
}

redpajama_set_name: RedPajamaGithub


text:
<?php
declare(strict_types=1);

namespace Enm\JsonApi\Server\Tests;

use Enm\JsonApi\Model\Document\DocumentInterface;
use Enm\JsonApi\Serializer\DocumentDeserializerInterface;
use Enm\JsonApi\Serializer\DocumentSerializerInterface;
use Enm\JsonApi\Server\JsonApiServer;
use PHPUnit\Framework\TestCase;

/**
 * @author Philipp Marien <marien@eosnewmedia.de>
 */
class JsonApiServerTest extends TestCase
{
    public function testCreateEmptyRequestBody(): void
    {
        $body = $this->createJsonApiServer()->createRequestBody(null);
        $this->assertNull($body);
    }

    public function testCreateRequestBody(): void
    {
        $body = $this->createJsonApiServer()->createRequestBody('{"data":[]}');
        $this->assertInstanceOf(DocumentInterface::class, $body);
    }

    public function testHandleException(): void
    {
        $api = $this->createJsonApiServer();
        $e = $api->handleException(new \Exception('Test'));

        $this->assertEquals(500, $e->status());
        $this->assertEquals('application/vnd.api+json', $e->headers()->getOptional('Content-Type'));
        $this->assertEquals(1, $e->document()->errors()->count());
        $this->assertEquals('Test', $e->document()->errors()->all()[0]->title());
    }

    /**
     * @return JsonApiServer
     */
    protected function createJsonApiServer(): JsonApiServer
    {
        /** @var DocumentDeserializerInterface $deserializer */
        $deserializer = $this->createMock(DocumentDeserializerInterface::class);
        /** @var DocumentSerializerInterface $serializer */
        $serializer = $this->createMock(DocumentSerializerInterface::class);

        return new JsonApiServer($deserializer, $serializer);
    }
}


text:
/* Projects View - displays all projects active within the system */

var projectsTemplate = require('./projectListTemplate.hbs');

var ProjectCardView = require('../show/projectCardView.js');

module.exports = Backbone.Marionette.CompositeView.extend({
  tagName: 'div',
  template: projectsTemplate,
  itemView: ProjectCardView,
  itemViewContainer: 'ul.projects',

  initialize: function() {
    // Collection must be passed in by Controller
    this.listenTo(this.collection, 'sync', this.render);  // Without this, the collection doesn't render after it completes loading
    this.listenTo(this.collection, 'remove', this.render);   // Collection doesn't call sync when we add a new model.
  },

  events: {
    'click .project a': 'gotoProject',
    'click #createProject': 'createProject'
  },

  gotoProject: function(e) {
    // Navigate to a specific project
    e.preventDefault(); // Have to disable the default behavior of the anchor

    projectId = e.target.id;
    route = projectId;
    app.router.navigate(route, {trigger: true});
  },

  createProject: function(project) {
    if(app.user.get('loggedIn')) {
      var name = this.$el.find('#name');

      if(name.val()) {
        var input = {
          id: name.val(),
          user: app.user.get('username'),
          timestamp: Firebase.ServerValue.TIMESTAMP, // Tells the server to set a createdAt timestamp
        };

        this.collection.add(input);
        this.collection.trigger('sync');  // HACK - Marionette View normally places new models at the end of the collection

        mixpanel.track('Create Project', input);

        name.val('');
      }
    } else {
      this.showError('Sorry, you must be logged in');
    }
  },

  showError: function(message) {
    var error = this.$el.find('#projectsError');
    error.text(message);
    error.show();
  },
});


text:
package interfaz;

import javax.swing.JFrame;
import javax.swing.JButton;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
import java.util.LinkedList;

import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.JPanel;
import javax.swing.JTable;

import logica.Cuestionario;
import logica.GestorCuestionarios;

@SuppressWarnings("serial")
public class ConfiguracionCuestionario extends JFrame {

	private JFrame frmConfiguracinCuestionario;
	private JTable table;
	private String usuario;

	/*public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ConfiguracionCuestionario window = new ConfiguracionCuestionario(null);
					window.frmConfiguracinCuestionario.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}*/
	//Constructora
	public ConfiguracionCuestionario(String pUsuario) {
		usuario = pUsuario;
		initialize();
	}

	//Getter para llamar el frame desde otra ventana
	public JFrame getFrmConfiguracinCuestionario() {
		return frmConfiguracinCuestionario;
	}

	//Window
	private void initialize() {
		frmConfiguracinCuestionario = new JFrame();
		frmConfiguracinCuestionario.setTitle("Configuraci\u00F3n de Cuestionarios");
		frmConfiguracinCuestionario.setBounds(100, 100, 450, 300);
		frmConfiguracinCuestionario.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frmConfiguracinCuestionario.getContentPane().setLayout(new BorderLayout(0, 0));

		JPanel panel = new JPanel();
		frmConfiguracinCuestionario.getContentPane().add(panel, BorderLayout.SOUTH);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		frmConfiguracinCuestionario.getContentPane().add(scrollPane, BorderLayout.CENTER);

		//Tabla mas actualizarla
		final LinkedList<Cuestionario> listaCuestionarios = GestorCuestionarios.getGestorCuestionarios().obtenerCuestionariosUsuario(usuario);

		String[] columnNames = {"Cuestionarios", "Nº Preguntas"};
		Object[][] data = new Object[listaCuestionarios.size()][2];

		for (int i = 0; i < listaCuestionarios.size(); i++) {
			data[i][0]= listaCuestionarios.get(i).getNombre();
			data[i][1]= listaCuestionarios.get(i).getPreguntas().size();
		}

		table = new JTable(data, columnNames);
		scrollPane.setViewportView(table);

		JButton btnAadirCuestionario = new JButton("A\u00F1adir Cuestionario");
		btnAadirCuestionario.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				ModificarCrearCuestionario frame = new ModificarCrearCuestionario(usuario);
				frame.getFrmCreacionmodificacionCuestionario().setVisible(true);
				frmConfiguracinCuestionario.dispose();
			}
		});
		panel.add(btnAadirCuestionario);

		JButton btnModificarCuestionario = new JButton("Modificar Cuestionario");
		btnModificarCuestionario.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				//Know what cuestionary we are focusing
				int aux = table.getSelectedRow();
				int idCuestionario = listaCuestionarios.get(aux).getId();

				ModificarCrearCuestionario frame = new ModificarCrearCuestionario(usuario, idCuestionario);
				frame.getFrmCreacionmodificacionCuestionario().setVisible(true);
				frmConfiguracinCuestionario.dispose();
			}
		});
		panel.add(btnModificarCuestionario);

		JButton btnAtras = new JButton("      Atras       ");
		btnAtras.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				InicioSesion frame = new InicioSesion();
				frame.getFrmLogicgroup().setVisible(true);
				frmConfiguracinCuestionario.dispose();
			}
		});
		panel.add(btnAtras);

	}
}


text:
namespace NSubstitute.Core
{
    public interface ICallInfoFactory
    {
        CallInfo Create(ICall call);
    }
}


text:
package com.android.simone.github.marvelapp.presentation.ui;

/**
 * @author Simone Bellotti
 */

public interface BasePresenter {
    void start();

    void destroy();
}


text:
enum loglevel_e
{
	ERROR = 0,
	WARNING,
	INFO
};

class Log
{
public:
	static loglevel_e 		log_level;

	static void				write(loglevel_e level, std::string sender, std::string message);
	static void				warning(std::string sender, std::string message);
	static void				error(std::string sender, std::string message);
	static void				info(std::string sender, std::string message);
};

#endif // LOG_H


text:
<?php

class AC_Campaign extends ActiveCampaign {

	public $version;
	public $url_base;
	public $url;
	public $api_key;

	function __construct($version, $url_base, $url, $api_key) {
		$this->version = $version;
		$this->url_base = $url_base;
		$this->url = $url;
		$this->api_key = $api_key;
	}

	function create($params, $post_data) {
		$request_url = "{$this->url}&api_action=campaign_create&api_output={$this->output}";
		$response = $this->curl($request_url, $post_data);
		return $response;
	}

	function delete_list($params) {
		$request_url = "{$this->url}&api_action=campaign_delete_list&api_output={$this->output}&{$params}";
		$response = $this->curl($request_url);
		return $response;
	}

	function delete($params) {
		$request_url = "{$this->url}&api_action=campaign_delete&api_output={$this->output}&{$params}";
		$response = $this->curl($request_url);
		return $response;
	}

	function list_($params) {
		$request_url = "{$this->url}&api_action=campaign_list&api_output={$this->output}&{$params}";
		$response = $this->curl($request_url);
		return $response;
	}

	function paginator($params) {
		$request_url = "{$this->url}&api_action=campaign_paginator&api_output={$this->output}&{$params}";
		$response = $this->curl($request_url);
		return $response;
	}

	function report_bounce_list($params) {
		$request_url = "{$this->url}&api_action=campaign_report_bounce_list&api_output={$this->output}&{$params}";
		$response = $this->curl($request_url);
		return $response;
	}

	function report_bounce_totals($params) {
		$request_url = "{$this->url}&api_action=campaign_report_bounce_totals&api_output={$this->output}&{$params}";
		$response = $this->curl($request_url);
		return $response;
	}

	function report_forward_list($params) {
		$request_url = "{$this->url}&api_action=campaign_report_forward_list&api_output={$this->output}&{$params}";
		$response = $this->curl($request_url);
		return $response;
	}

	function report_forward_totals($params) {
		$request_url = "{$this->url}&api_action=campaign_report_forward_totals&api_output={$this->output}&{$params}";
		$response = $this->curl($request_url);
		return $response;
	}

	function report_link_list($params) {
		$request_url = "{$this->url}&api_action=campaign_report_link_list&api_output={$this->output}&{$params}";
		$response = $this->curl($request_url);
		return $response;
	}

	function report_link_totals($params) {
		$request_url = "{$this->url}&api_action=campaign_report_link_totals&api_output={$this->output}&{$params}";
		$response = $this->curl($request_url);
		return $response;
	}

	function report_open_list($params) {
		$request_url = "{$this->url}&api_action=campaign_report_open_list&api_output={$this->output}&{$params}";
		$response = $this->curl($request_url);
		return $response;
	}

	function report_open_totals($params) {
		$request_url = "{$this->url}&api_action=campaign_report_open_totals&api_output={$this->output}&{$params}";
		$response = $this->curl($request_url);
		return $response;
	}

	function report_totals($params) {
		$request_url = "{$this->url}&api_action=campaign_report_totals&api_output={$this->output}&{$params}";
		$response = $this->curl($request_url);
		return $response;
	}

	function report_unopen_list($params) {
		$request_url = "{$this->url}&api_action=campaign_report_unopen_list&api_output={$this->output}&{$params}";
		$response = $this->curl($request_url);
		return $response;
	}

	function report_unsubscription_list($params) {
		$request_url = "{$this->url}&api_action=campaign_report_unsubscription_list&api_output={$this->output}&{$params}";
		$response = $this->curl($request_url);
		return $response;
	}

	function report_unsubscription_totals($params) {
		$request_url = "{$this->url}&api_action=campaign_report_unsubscription_totals&api_output={$this->output}&{$params}";
		$response = $this->curl($request_url);
		return $response;
	}

	function send($params) {
		$request_url = "{$this->url}&api_action=campaign_send&api_output={$this->output}&{$params}";
		$response = $this->curl($request_url);
		return $response;
	}

	function status($params) {
		$request_url = "{$this->url}&api_action=campaign_status&api_output={$this->output}&{$params}";
		$response = $this->curl($request_url);
		return $response;
	}

}

?>


text:
BOOST_AUTO_TEST_CASE(checking_empty_html)
{
	std::string html_generated;
	auto erased_html_sink = Si::Sink<char, Si::success>::erase(
	    Si::make_container_sink(html_generated));

	auto content =
	    tags::menu(tags::p("Content")) + tags::footer(tags::p("Copyright"));
	tags::html(tags::head(tags::title("Title")) +
	           tags::body(std::move(content)))
	    .generate(erased_html_sink);
	BOOST_CHECK_EQUAL("<title>Title</title></"
	                  "head><menu>
Content
</"
	                  "menu>
Copyright
",
	                  html_generated);
}

BOOST_AUTO_TEST_CASE(tags_link)
{
	std::string html_generated;
	auto erased_html_sink = Si::Sink<char, Si::success>::erase(
	    Si::make_container_sink(html_generated));
	tags::link("https://", "google.com").generate(erased_html_sink);
	BOOST_CHECK_EQUAL(
	    "google.com",
	    html_generated);
}

BOOST_AUTO_TEST_CASE(paragraph)
{
	std::string html_generated;
	auto erased_html_sink = Si::Sink<char, Si::success>::erase(
	    Si::make_container_sink(html_generated));
	tags::p(tags::cl("someclass"), Si::html::text("Testing p tag"))
	    .generate(erased_html_sink);
	BOOST_CHECK_EQUAL("
Testing p tag
",
	                  html_generated);
}

BOOST_AUTO_TEST_CASE(div_box)
{
	std::string html_generated;
	auto erased_html_sink = Si::Sink<char, Si::success>::erase(
	    Si::make_container_sink(html_generated));
	tags::div(tags::cl(""), Si::html::text("Testing div tag"))
	    .generate(erased_html_sink);
	BOOST_CHECK_EQUAL("
Testing div tag
", html_generated);
}

BOOST_AUTO_TEST_CASE(span)
{
	std::string html_generated;
	auto erased_html_sink = Si::Sink<char, Si::success>::erase(
	    Si::make_container_sink(html_generated));
	tags::span(tags::cl(""), Si::html::text("Testing span tag"))
	    .generate(erased_html_sink);
	BOOST_CHECK_EQUAL("Testing span tag",
	                  html_generated);
}

BOOST_AUTO_TEST_CASE(break_row)
{
	std::string html_generated;
	auto erased_html_sink = Si::Sink<char, Si::success>::erase(
	    Si::make_container_sink(html_generated));
	tags::br(tags::cl("clear")).generate(erased_html_sink);
	BOOST_CHECK_EQUAL("
", html_generated);
}

BOOST_AUTO_TEST_CASE(h1)
{
	std::string html_generated;
	auto erased_html_sink = Si::Sink<char, Si::success>::erase(
	    Si::make_container_sink(html_generated));
	tags::h1(Si::html::text("Test heading")).generate(erased_html_sink);
	BOOST_CHECK_EQUAL("
Test heading
", html_generated);
}

BOOST_AUTO_TEST_CASE(h2)
{
	std::string html_generated;
	auto erased_html_sink = Si::Sink<char, Si::success>::erase(
	    Si::make_container_sink(html_generated));
	tags::h2(Si::html::text("Test heading")).generate(erased_html_sink);
	BOOST_CHECK_EQUAL("
Test heading
", html_generated);
}

BOOST_AUTO_TEST_CASE(h3)
{
	std::string html_generated;
	auto erased_html_sink = Si::Sink<char, Si::success>::erase(
	    Si::make_container_sink(html_generated));
	tags::h3(Si::html::text("Test heading")).generate(erased_html_sink);
	BOOST_CHECK_EQUAL("
Test heading
", html_generated);
}

BOOST_AUTO_TEST_CASE(h4)
{
	std::string html_generated;
	auto erased_html_sink = Si::Sink<char, Si::success>::erase(
	    Si::make_container_sink(html_generated));
	tags::h4(Si::html::text("Test heading")).generate(erased_html_sink);
	BOOST_CHECK_EQUAL("
Test heading
", html_generated);
}

BOOST_AUTO_TEST_CASE(pre_tag)
{
	std::string html_generated;
	auto erased_html_sink = Si::Sink<char, Si::success>::erase(
	    Si::make_container_sink(html_generated));
	tags::pre(Si::html::text("Test heading")).generate(erased_html_sink);
	BOOST_CHECK_EQUAL("
Test heading
", html_generated);
}

BOOST_AUTO_TEST_CASE(ul)
{
	std::string html_generated;
	auto erased_html_sink = Si::Sink<char, Si::success>::erase(
	    Si::make_container_sink(html_generated));
	tags::ul(tags::li(Si::html::text("Test heading")))
	    .generate(erased_html_sink);
	BOOST_CHECK_EQUAL("

Test heading

", html_generated);
}


text:
<script>
// These are the cookies we expect to see along the way.
var SET_REMOVE_COOKIE = {
  name: 'testSetRemove',
  value: '42',
  domain: 'a.com',
  hostOnly: true,
  path: '/',
  secure: false,
  httpOnly: false,
  session: false,
  expirationDate: 12345678900,
  storeId: "0"
};

var OVERWRITE_COOKIE_PRE = {
  name: 'testOverwrite',
  value: '42',
  domain: 'a.com',
  hostOnly: true,
  path: '/',
  secure: false,
  httpOnly: false,
  session: false,
  expirationDate: 12345678900,
  storeId: "0"
};

var OVERWRITE_COOKIE_POST = {
  name: 'testOverwrite',
  value: '43',
  domain: 'a.com',
  hostOnly: true,
  path: '/',
  secure: false,
  httpOnly: false,
  session: false,
  expirationDate: 12345678900,
  storeId: "0"
};

chrome.test.runTests([
  function testSet() {
    var testCompleted = chrome.test.callbackAdded();
    var listener = function (info) {
      chrome.test.assertFalse(info.removed);
      chrome.test.assertEq('explicit', info.cause);
      chrome.test.assertEq(SET_REMOVE_COOKIE, info.cookie);
      testCompleted();
    };

    chrome.cookies.onChanged.addListener(listener);
    chrome.cookies.set({
      url: 'http://a.com/path',
      name: 'testSetRemove',
      value: '42',
      expirationDate: 12345678900
    }, function () {
      chrome.cookies.onChanged.removeListener(listener);
    });
  },
  function testRemove() {
    var testCompleted = chrome.test.callbackAdded();
    var listener = function (info) {
      chrome.test.assertTrue(info.removed);
      chrome.test.assertEq('explicit', info.cause);
      chrome.test.assertEq(SET_REMOVE_COOKIE, info.cookie);
      testCompleted();
    };

    chrome.cookies.onChanged.addListener(listener);
    chrome.cookies.remove({
      url: 'http://a.com/path',
      name: 'testSetRemove'
    }, function () {
      chrome.cookies.onChanged.removeListener(listener);
    });
  },
  function overwriteFirstSet() {
    var testCompleted = chrome.test.callbackAdded();
    var listener = function (info) {
      chrome.test.assertFalse(info.removed);
      chrome.test.assertEq('explicit', info.cause);
      chrome.test.assertEq(OVERWRITE_COOKIE_PRE, info.cookie);
      testCompleted();
    };

    chrome.cookies.onChanged.addListener(listener);
    chrome.cookies.set({
      url: 'http://a.com/path',
      name: 'testOverwrite',
      value: '42',
      expirationDate: 12345678900
    }, function () {
      chrome.cookies.onChanged.removeListener(listener);
    });
  },
  function overwriteSecondSet() {
    var removeCompleted = chrome.test.callbackAdded();
    var setCompleted = chrome.test.callbackAdded();
    var listenerRemove = function (info) {
      if (info.removed) {
        chrome.test.assertEq('overwrite', info.cause);
        chrome.test.assertEq(OVERWRITE_COOKIE_PRE, info.cookie);
        removeCompleted();
      }
    };
    var listenerSet = function (info) {
      if (!info.removed) {
        chrome.test.assertEq('explicit', info.cause);
        chrome.test.assertEq(OVERWRITE_COOKIE_POST, info.cookie);
        setCompleted();
      }
    };
    chrome.cookies.onChanged.addListener(listenerRemove);
    chrome.cookies.onChanged.addListener(listenerSet);
    chrome.cookies.set({
      url: 'http://a.com/path',
      name: 'testOverwrite',
      value: '43',
      expirationDate: 12345678900
    }, function () {
      chrome.cookies.onChanged.removeListener(listenerRemove);
      chrome.cookies.onChanged.removeListener(listenerSet);
    });
  },
  function overwriteExpired() {
    var setCompleted = chrome.test.callbackAdded();
    var listener = function (info) {
      chrome.test.assertTrue(info.removed);
      chrome.test.assertEq('expired_overwrite', info.cause);
      chrome.test.assertEq(OVERWRITE_COOKIE_POST, info.cookie);
      setCompleted();
    };
    chrome.cookies.onChanged.addListener(listener);
    chrome.cookies.set({
      url: 'http://a.com/path',
      name: 'testOverwrite',
      value: '43',
      expirationDate: 1
    }, function () {
      chrome.cookies.onChanged.removeListener(listener);
    });
  }
]);
</script>


text:
from django.core.management.base import BaseCommand

from apostello.models import Recipient
from apostello.tasks import update_msgs_name

class Command(BaseCommand):
    """Updates names on messages for all existing contacts."""

    args = ""
    help = "Update from_name fields"

    def handle(self, *args, **options):
        """Handle the command."""
        for c in Recipient.objects.all():
            update_msgs_name(c.id)


text:
require 'minitest_helper'

class ColumnTest < Minitest::Test

  def setup
    @x = 2
    @products = [
      PrimeNumbers::Product.new(@x, 2),
      PrimeNumbers::Product.new(@x, 3),
      PrimeNumbers::Product.new(@x, 5)
    ]
    @column = PrimeNumbers::Column.new @x, @products
  end

  def test_attribute_header
    assert_equal @x, @column.header
  end

  def test_attribute_products
    assert_instance_of Array, @column.products
    assert_equal @products, @column.products
  end

  def test_column_is_sorted
    assert_equal @column.products, @column.products.sort

    unsorted_list = @products.dup
    unsorted_list.push(unsorted_list.shift)
    refute_equal @products, unsorted_list

    column = PrimeNumbers::Column.new @x, unsorted_list
    assert_equal column.products, column.products.sort
  end

  def test_array_access
    assert_instance_of PrimeNumbers::Product, @column[0]
    assert_equal @products[0], @column[0]
    assert_equal @products[-1], @column[-1]
  end

  def test_width
    assert_instance_of Fixnum, @column.width

    expected = @column.products.last.width
    assert_equal expected, @column.width

    more_products = [
      *@products,
      PrimeNumbers::Product.new(@x, 1000),
      PrimeNumbers::Product.new(@x, 10000)
    ]
    column = PrimeNumbers::Column.new @x, more_products
    assert_equal 5, column.width
  end
end


text:
Command line interface and library for the smoothing of probability mass functions

[Library API documentation](https://josellarena.github.io/goodturingjs/module-goodturing.html)

## Getting Started

### Prerequisites

[nodejs](https://nodejs.org/en/download/), for the node CLI/library

### Installing the CLI

globally:

```
npm i -g goodturing
```
locally:

```
npm i goodturing
```
#### Usage

global:

```
goodturing -h
```

local:

```
./node_modules/.bin/goodturing -h
```

```

  Usage: goodturing <input file> <output file> [options]

  recalculates counts and count probabilities of a probability mass distribution using good-turing smoothing
  <input file> should contain two whitespace-separated columns, the first being the raw count and the secound its frequency
  <output file> will be created/overwritten with two tab-separated columnns, the first being the input raw count and the second
  the smoothed count or its smoothed probability; for zero raw counts, the smooth count and its probability are aggregated over
  all symbols with zero counts

  Options:

    -h, --help           output usage information
    -V, --version        output the version number
    -t, --type [c|p]     output type: smoothed counts [c] or smoothed probability of counts [p], defaults to [c]
    -a, --algo [s|m]     smoothing algorithm: simple [s] or minmax [m], defaults to [s]
    -c, --crit <number>  critical value for Turing/Linear-Good-Turing switch for Simple Good-Turing, defaults to 1.96
```

### Installing the library

#### In node

```
git clone git@github.com:josellarena/goodturingjs.git
```
```
const goodturing = require('./good-turing.js');
```
or if cli  has been installed locally:
```
const goodturing = require('goodturing');
```
if globally, first do:

```
npm ln goodturing
```

#### In the browser

`good-turing.min.js` is an uglified es5-babelised version of `good-turing.js`

```
<script src='good-turing.min.js'></script>
```
`goodturing` will be available as a global

### Uninstalling

globally:

```
npm un -g goodturing
```
locally:

```
npm un goodturing
```

## Running the tests

Only for the library:
```
npm test
```
if mocha and chai not installed, first do:
```
npm i mocha chai
```
## License

This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details


text:
/***********************************************************
* Developer: Minhas Kamal (minhaskamal024@gmail.com)       *
* Date: 18-Apr-2016                                        *
* License: MIT License                                     *
***********************************************************/

package com.minhaskamal.egami.utilityAlgorithms;

public class GlobalThresholdCalculator {

	public static int getOtsuThreshold(int[] values){

		int sumValue = 0,
			sumValueThreshold = 0;
		for(int i=0; i<values.length; i++){
			sumValue += values[i];
			sumValueThreshold += i*values[i];
		}

		int weightB = 0,
			weightF = 0;
		int sumB = 0,
			sumF = 0;
		double meanB = 0,
			meanF = 0;
		double betweenClassVariance = 0;

		double maxBetweenClassVariance = -999;
		int threshold = -999;
		for(int i=0; i<values.length; i++){
			weightB += values[i];
			weightF = sumValue - weightB;

			if(weightB==0) continue;
			if(weightF==0) break;

			sumB += i*values[i];
			sumF = sumValueThreshold-sumB;

			meanB = (double) sumB/weightB;
			meanF = (double) sumF/weightF;

			betweenClassVariance = weightB * weightF * (meanB-meanF)*(meanB-meanF);

			if(betweenClassVariance>maxBetweenClassVariance){
				maxBetweenClassVariance = betweenClassVariance;
				threshold = i;
			}
		}

		return threshold;
	}

	public static int getKnownDistributionThreshold(int[] values, int percentage){

		int threshold = -999;

		int sumValue = 0;
		for(int i=0; i<values.length; i++){
			sumValue += values[i];
		}

		int sumB = 0;
		for(int i=0; i<values.length; i++){
			sumB += values[i];

			if((sumB*100/sumValue) > percentage){
				threshold = i;
				break;
			}
		}

		return threshold;
	}
}


text:
<script type="text/javascript" src="/site_media/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="/site_media/js/jstree/jquery.jstree.js"></script>
<script type="text/javascript" src="/site_media/js/jquery-ui-1.8.6.custom.min.js"></script>
<script type="text/javascript" src="/site_media/js/jquery.autocomplete.min.js"></script>
<script type="text/javascript" src="/site_media/js/jquery.cookie.js"></script>
<script type="text/javascript" src="/site_media/js/jqmodal.js"></script>
<script type="text/javascript" src="/site_media/js/flash_detect_min.js"></script>
<link href="/site_media/css/jqmodal.css" rel="stylesheet" type="text/css" media="screen">
<link type="text/css" href="/site_media/css/autocomplete/jquery.autocomplete.css" rel="stylesheet" />
<link type="text/css" href="/site_media/css/theme/ui.all.css" rel="Stylesheet" />
<link type="text/css" href="/site_media/css/smoothness/jquery-ui-1.7.2.custom.css" rel="stylesheet" />


text:
<?xml version='1.0' encoding='UTF-8'?>
<project>
  <actions/>
  <description>"All in one" standalone openstack installation and running tempest on it.
AIO on VM
Tempest on node</description>
  <keepDependencies>false</keepDependencies>
  <properties/>
  <scm class="org.jenkinsci.plugins.multiplescms.MultiSCM" plugin="multiple-scms@0.3">
    <scms>
      <hudson.plugins.git.GitSCM plugin="git@2.2.1">
        <configVersion>2</configVersion>
        <userRemoteConfigs>
          <hudson.plugins.git.UserRemoteConfig>
            <url>https://git.openstack.org/stackforge/rally</url>
          </hudson.plugins.git.UserRemoteConfig>
        </userRemoteConfigs>
        <branches>
          <hudson.plugins.git.BranchSpec>
            <name>*/master</name>
          </hudson.plugins.git.BranchSpec>
        </branches>
        <doGenerateSubmoduleConfigurations>false</doGenerateSubmoduleConfigurations>
        <submoduleCfg class="list"/>
        <extensions>
          <hudson.plugins.git.extensions.impl.RelativeTargetDirectory>
            <relativeTargetDir>rally</relativeTargetDir>
          </hudson.plugins.git.extensions.impl.RelativeTargetDirectory>
        </extensions>
      </hudson.plugins.git.GitSCM>
      <hudson.plugins.git.GitSCM plugin="git@2.2.1">
        <configVersion>2</configVersion>
        <userRemoteConfigs>
          <hudson.plugins.git.UserRemoteConfig>
            <url>https://github.com/CiscoSystems/openstack-sqe.git</url>
          </hudson.plugins.git.UserRemoteConfig>
        </userRemoteConfigs>
        <branches>
          <hudson.plugins.git.BranchSpec>
            <name>*/master</name>
          </hudson.plugins.git.BranchSpec>
        </branches>
        <doGenerateSubmoduleConfigurations>false</doGenerateSubmoduleConfigurations>
        <submoduleCfg class="list"/>
        <extensions>
          <hudson.plugins.git.extensions.impl.RelativeTargetDirectory>
            <relativeTargetDir>openstack-sqe</relativeTargetDir>
          </hudson.plugins.git.extensions.impl.RelativeTargetDirectory>
          <hudson.plugins.git.extensions.impl.WipeWorkspace/>
        </extensions>
      </hudson.plugins.git.GitSCM>
      <hudson.plugins.git.GitSCM plugin="git@2.2.1">
        <configVersion>2</configVersion>
        <userRemoteConfigs>
          <hudson.plugins.git.UserRemoteConfig>
            <url>https://github.com/CiscoSystems/puppet_openstack_builder</url>
          </hudson.plugins.git.UserRemoteConfig>
        </userRemoteConfigs>
        <branches>
          <hudson.plugins.git.BranchSpec>
            <name>*/icehouse</name>
          </hudson.plugins.git.BranchSpec>
        </branches>
        <doGenerateSubmoduleConfigurations>false</doGenerateSubmoduleConfigurations>
        <submoduleCfg class="list"/>
        <extensions>
          <hudson.plugins.git.extensions.impl.RelativeTargetDirectory>
            <relativeTargetDir>puppet_openstack_builder</relativeTargetDir>
          </hudson.plugins.git.extensions.impl.RelativeTargetDirectory>
          <hudson.plugins.git.extensions.impl.WipeWorkspace/>
        </extensions>
      </hudson.plugins.git.GitSCM>
    </scms>
  </scm>
  <assignedNode>jvnode2</assignedNode>
  <canRoam>false</canRoam>
  <disabled>false</disabled>
  <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
  <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
  <triggers/>
  <concurrentBuild>false</concurrentBuild>
  <builders>
    <hudson.tasks.Shell>
      <command># Reverting to initial snapshot
#virsh -c qemu+ssh://localadmin@vhost/system snapshot-revert $BOX before_os
#sleep 10</command>
    </hudson.tasks.Shell>
    <org.jvnet.hudson.plugins.SSHBuilder plugin="ssh@2.4">
      <siteName>root@aio4:22</siteName>
      <command>echo<<EOF
curl https://gist.githubusercontent.com/rickerc/9836426/raw/7f5d2ba507d99134e280f5118f588687146701f4/install_icehouse_cisco.sh > install_icehouse_cisco.sh
sed -i "s@\./install.sh@ls ~/puppet_openstack_builder/install-scripts/install.sh; sed -i 's/install.log 2>\&1/install.log/g' install.sh\n./install.sh@g" install_icehouse_cisco.sh
echo -e "\npuppet apply /etc/puppet/manifests/site.pp\n" >> install_icehouse_cisco.sh
nohup /bin/bash /root/install_icehouse_cisco.sh 2>&1 | tee ./install.log
sed -i "s/virt_type=kvm/virt_type=qemu/g" /etc/nova/nova-compute.conf
service nova-compute restart
sed -i "s/allow_versions = false/allow_versions = true/g" /etc/swift/container-server.conf
swift-init container-server restart
EOF</command>
    </org.jvnet.hudson.plugins.SSHBuilder>
    <hudson.tasks.Shell>
      <command>scp root@$BOX:/root/openrc .
source ./openrc

#python $WORKSPACE/tempest/tools/install_venv.py
#source $WORKSPACE/tempest/.venv/bin/activate
#pip install junitxml python-ceilometerclient

#/bin/bash $WORKSPACE/openstack-sqe/tools/tempest-scripts/tempest_unconfig.sh
#/bin/bash $WORKSPACE/openstack-sqe/tools/tempest-scripts/tempest_configurator.sh
#/bin/bash $WORKSPACE/openstack-sqe/tools/tempest-scripts/config_creator.sh $IP1

#mv $WORKSPACE/tempest.conf.jenkins $WORKSPACE/tempest/etc/tempest.conf

#cd $WORKSPACE/tempest/
#testr init || :
#testr run --subunit | subunit-2to1 | tools/colorizer.py || :
#testr last --subunit | subunit-1to2 | subunit2junitxml --output-to="${WORKSPACE}/nosetests.xml" || :
/bin/bash $WORKSPACE/rally/install_rally.sh -v</command>
    </hudson.tasks.Shell>
  </builders>
  <publishers>
    <hudson.plugins.chucknorris.CordellWalkerRecorder plugin="chucknorris@0.5">
      <factGenerator/>
    </hudson.plugins.chucknorris.CordellWalkerRecorder>
    <hudson.plugins.logparser.LogParserPublisher plugin="log-parser@1.0.8">
      <unstableOnWarning>false</unstableOnWarning>
      <failBuildOnError>false</failBuildOnError>
      <parsingRulesPath>/var/lib/jenkins/custom_configs/parsing_rules</parsingRulesPath>
    </hudson.plugins.logparser.LogParserPublisher>
  </publishers>
  <buildWrappers>
    <hudson.plugins.ansicolor.AnsiColorBuildWrapper plugin="ansicolor@0.4.0">
      <colorMapName>xterm</colorMapName>
    </hudson.plugins.ansicolor.AnsiColorBuildWrapper>
    <com.lookout.jenkins.EnvironmentScript plugin="environment-script@1.1.2">
      <script>echo BOX=aio4
echo IP1=$(getent hosts aio4 | awk {'print $1'})</script>
      <onlyRunOnParent>false</onlyRunOnParent>
    </com.lookout.jenkins.EnvironmentScript>
  </buildWrappers>
</project>


text:
package com.globo.globodns.client.api;

import java.lang.reflect.Type;
import java.util.List;

import com.fasterxml.jackson.core.type.TypeReference;
import com.globo.globodns.client.AbstractAPI;
import com.globo.globodns.client.GloboDns;
import com.globo.globodns.client.GloboDnsException;
import com.globo.globodns.client.model.GloboDnsRoot;
import com.globo.globodns.client.model.Domain;
import com.newrelic.api.agent.NewRelic;
import com.newrelic.api.agent.Trace;

public class DomainAPI extends AbstractAPI<Domain> {

	public DomainAPI(GloboDns transport) {
		super(transport);
	}

	@Override
	protected Type getType() {
		return new TypeReference<Domain>() {}.getType();
	}

	@Override
	protected Type getListType() {
		return new TypeReference<List<Domain>>() {}.getType();
	}

	//////////////////
	// Domain calls //
	//////////////////
	@Trace(dispatcher = true)
	public Domain createDomain(String name, Long templateId, String authorityType) throws GloboDnsException {
		NewRelic.setTransactionName(null, "/globodns/createDomain");
		return this.createDomain(name, templateId, authorityType, false);
	}

	@Trace(dispatcher = true)
	public List<Domain> listAll() throws GloboDnsException {
		NewRelic.setTransactionName(null, "/globodns/listDomains");
		return this.listAll(false);
	}

	@Trace(dispatcher = true)
	public List<Domain> listByQuery(String query) throws GloboDnsException {
		NewRelic.setTransactionName(null, "/globodns/listDomainsByQuery");
		return this.listByQuery(query, false);
	}

	@Trace(dispatcher = true)
	public Domain getById(Long domainId) throws GloboDnsException {
		NewRelic.setTransactionName(null, "/globodns/getDomainById");
		return this.getById(domainId, false);
	}

	@Trace(dispatcher = true)
	public void updateDomain(Long domainId, String name, String authorityType, String ttl) throws GloboDnsException {
		NewRelic.setTransactionName(null, "/globodns/updateDomain");
		this.updateDomain(domainId, name, authorityType, ttl, false);
	}

	@Trace(dispatcher = true)
	public void removeDomain(Long domainId) throws GloboDnsException {
		NewRelic.setTransactionName(null, "/globodns/removeDomain");
		this.removeDomain(domainId, false);
	}

	//////////////////////////
	// Reverse domain calls //
	//////////////////////////
	@Trace(dispatcher = true)
	public Domain createReverseDomain(String name, Long templateId, String authorityType) throws GloboDnsException {
		NewRelic.setTransactionName(null, "/globodns/createReverseDomain");
		return this.createDomain(name, templateId, authorityType, true);
	}

	@Trace(dispatcher = true)
	public List<Domain> listAllReverse() throws GloboDnsException {
		NewRelic.setTransactionName(null, "/globodns/listAllReverseDomains");
		return this.listAll(true);
	}

	@Trace(dispatcher = true)
	public List<Domain> listReverseByQuery(String query) throws GloboDnsException {
		NewRelic.setTransactionName(null, "/globodns/listReverseDomainsByQuery");
		return this.listByQuery(query, true);
	}

	@Trace(dispatcher = true)
	public Domain getReverseById(Long domainId) throws GloboDnsException {
		NewRelic.setTransactionName(null, "/globodns/getReverseDomainById");
		return this.getById(domainId, true);
	}

	@Trace(dispatcher = true)
	public void updateReverseDomain(Long domainId, String name, String authorityType, String ttl) throws GloboDnsException {
		NewRelic.setTransactionName(null, "/globodns/updateReverseDomain");
		this.updateDomain(domainId, name, authorityType, ttl, true);
	}

	@Trace(dispatcher = true)
	public void removeReverseDomain(Long domainId) throws GloboDnsException {
		NewRelic.setTransactionName(null, "/globodns/removeReverseDomain");
		this.removeDomain(domainId, true);
	}

	////////////////////
	// Implementation //
	////////////////////
	/*
	 * Creating features
	 */
	private Domain createDomain(String name, Long templateId, String authorityType, boolean reverse) throws GloboDnsException {
		Domain domain = new Domain();
		domain.getDomainAttributes().setName(name);
		domain.getDomainAttributes().setTemplateId(templateId);
		domain.getDomainAttributes().setAuthorityType(authorityType);

		GloboDnsRoot<Domain> globoDnsRoot = this.post("/domains.json" + (reverse ? "?reverse=true" : ""), domain, false);
		if (globoDnsRoot == null) {
			throw new GloboDnsException("Invalid response");
		}
		return globoDnsRoot.getFirstObject();
	}

	/*
	 * Recovering features
	 */
	private List<Domain> listAll(boolean reverse) throws GloboDnsException {
		GloboDnsRoot<Domain> globoDnsRoot = this.get("/domains.json" + (reverse ? "?reverse=true" : ""), true);
		if (globoDnsRoot == null) {
			throw new GloboDnsException("Invalid response");
		}
		return globoDnsRoot.getObjectList();
	}

	private List<Domain> listByQuery(String query, boolean reverse) throws GloboDnsException {
		if (query == null) {
			throw new GloboDnsException("Query cannot be null");
		}

		GloboDnsRoot<Domain> globoDnsRoot = this.get("/domains.json?query=" + query + (reverse ? "&reverse=true" : ""), true);
		if (globoDnsRoot == null) {
			throw new GloboDnsException("Invalid response");
		}
		return globoDnsRoot.getObjectList();
	}

	private Domain getById(Long domainId, boolean reverse) throws GloboDnsException {
		if (domainId == null) {
			throw new GloboDnsException("Domain id cannot be null");
		}

		GloboDnsRoot<Domain> globoDnsRoot = this.get("/domains/" + domainId + ".json" + (reverse ? "?reverse=true" : ""), false);
		if (globoDnsRoot == null) {
			throw new GloboDnsException("Invalid response");
		}
		return globoDnsRoot.getFirstObject();
	}

	/*
	 * Updating features
	 */
	private void updateDomain(Long domainId, String name, String authorityType, String ttl, boolean reverse) throws GloboDnsException {
		if (domainId == null) {
			throw new GloboDnsException("Domain id cannot be null");
		}

		Domain domain = new Domain();
		if (name != null)
			domain.getDomainAttributes().setName(name);
		if (authorityType != null)
			domain.getDomainAttributes().setAuthorityType(authorityType);
		if (ttl != null)
			domain.getDomainAttributes().setTTL(ttl);

		GloboDnsRoot<Domain> globoDnsRoot = this.put("/domains/" + domainId + ".json" + (reverse ? "?reverse=true" : ""), domain, false);
		if (globoDnsRoot == null) {
			throw new GloboDnsException("Invalid response");
		}
		return;
	}

	/*
	 * Removing features
	 */
	private void removeDomain(Long domainId, boolean reverse) throws GloboDnsException {
		if (domainId == null) {
			throw new GloboDnsException("Domain id cannot be null");
		}

		GloboDnsRoot<Domain> globoDnsRoot = this.delete("/domains/" + domainId + ".json" + (reverse ? "?reverse=true" : ""), false);
		if (globoDnsRoot == null) {
			throw new GloboDnsException("Invalid response");
		}
		return;
	}
}


text:
expose your app with `module.exports`

``` js
module.exports = function (db) {
  db.on('connection', function (ws) {
    //handle websocket stream
  })
  db.on('http_connection', function (req, res) {
    //handle http request
  })
}
```

`db` is a [levelup](https://github.com/rvagg/node-levelup) instance.

### on("connection", function (stream){...})

emitted on a websocket connection to tacodb.

### on("http_connection", function (req, res) {...})

emitted on a http connection to tacodb.

## Routes

When `tacodb` is run globally, with `tacodb start`
each service is prefixed with /http/NAME/

When `tacodb` is run locally, with `tacodb local file --name foo`
then routes are unprefixed.


text:
<?php

namespace Blackfire\Player\Step;

/**
 * @author Fabien Potencier <fabien@blackfire.io>
 */
class ClickStep extends Step
{
    private $selector;

    public function __construct($selector, $file = null, $line = null)
    {
        $this->selector = $selector;

        parent::__construct($file, $line);
    }

    public function __toString()
    {
        return sprintf("└ %s: %s\n", get_class($this), $this->selector);
    }

    public function getSelector()
    {
        return $this->selector;
    }
}


text:
package nonewvars_test

import (
	"testing"

	"golang.org/x/tools/go/analysis/analysistest"
	"golang.org/x/tools/gopls/internal/lsp/analysis/nonewvars"
	"golang.org/x/tools/internal/typeparams"
)

func Test(t *testing.T) {
	testdata := analysistest.TestData()
	tests := []string{"a"}
	if typeparams.Enabled {
		tests = append(tests, "typeparams")
	}
	analysistest.RunWithSuggestedFixes(t, testdata, nonewvars.Analyzer, tests...)
}


text:
package scrupal.api

import scrupal.storage.api.Storable
import scrupal.utils.{Enablee, Registrable}

import scala.concurrent.Future
import scala.language.implicitConversions

/** The fundamental unit of storage, behavior and interaction in Scrupal.
  *
  * An Entity brings together several things:The BundleType of an Instance's  payload,
  * definitions of the RESTful methods, security constraints, and extension actions for the REST API.
  * This is the key abstraction for Modules. Entities have a public REST API that is served by Scrupal. Entities
  * should represent some concept that is stored by Scrupal and delivered to the user interface via the REST API.
  */
abstract class Entity(sym : Symbol)(implicit scrpl : Scrupal) extends {
  val id : Symbol = sym
  val segment : String = id.name
  implicit val scrupal: Scrupal = scrpl
} with EntityProvider with Storable with Registrable[Entity] with ModuleOwned with Authorable
  with Describable with Enablee with Bootstrappable {
  def moduleOf = { scrupal.Modules.values.find(mod ⇒ mod.entities.contains(this)) }

  override def parent = moduleOf

  def instanceType : BundleType

  def registry = scrupal.Entities

  /*
  def toMap(mt : Map[String,Any]) : Map[String, Any] = mt

  def validateElement(ref : SelectedLocation, k: String, v : Any) : Results[Any] = {

  }

  override def validate(ref : Location, value : Map[String,Any] ) : VResult = instanceType.validate(ref, value)
*/

  def create(details: String) : EntityCreate = {
    NoOpEntityCreate(details)
  }

  def retrieve(instance_id: String, details: String) : EntityRetrieve = {
    NoOpEntityRetrieve(instance_id, details)
  }

  def retrieve(instance_id: Long, details: String) : EntityRetrieve = {
    retrieve (instance_id.toString, details)
  }

  def info(instance_id: String, details: String) : EntityInfo = {
    NoOpEntityInfo(instance_id, details)
  }

  def info(instance_id: Long, details: String) : EntityInfo = {
    info (instance_id.toString, details)
  }

  def update(instance_id: String, details: String) : EntityUpdate = {
    NoOpEntityUpdate(instance_id, details)
  }
  def update(instance_id: Long, details: String) : EntityUpdate = {
    update(instance_id.toString, details)
  }

  def delete(instance_id: String, details: String) : EntityDelete = {
    NoOpEntityDelete(instance_id, details)
  }
  def delete(instance_id: Long, details: String) : EntityDelete = {
    delete(instance_id.toString, details)
  }

  def query(details: String) : EntityQuery = {
    NoOpEntityQuery(details)
  }

  def add(instance_id: String, facet: String, details: String) : EntityAdd = {
    NoOpEntityAdd(instance_id, facet, details)
  }
  def add(instance_id: Long, facet: String, details: String) : EntityAdd = {
    add(instance_id.toString, facet, details)
  }

  def get(instance_id: String, facet: String, facet_id: String, details: String) : EntityGet = {
    NoOpEntityGet(instance_id, facet, facet_id, details)
  }
  def get(instance_id: Long, facet: String, facet_id: String, details: String) : EntityGet = {
    get(instance_id.toString, facet, facet_id, details)
  }

  def facetInfo(instance_id: String, facet: String, facet_id: String, details: String) : EntityFacetInfo = {
    NoOpEntityFacetInfo(instance_id, facet, facet_id, details)
  }
  def facetInfo(instance_id: Long, facet: String, facet_id: String, details: String) : EntityFacetInfo = {
    facetInfo(instance_id.toString, facet, facet_id, details)
  }

  def set(instance_id: String, facet: String, facet_id: String, details: String) : EntitySet = {
    NoOpEntitySet(instance_id, facet, facet_id, details)
  }
  def set(instance_id: Long, facet: String, facet_id: String, details: String) : EntitySet = {
    set(instance_id.toString, facet, facet_id, details)
  }

  def remove(instance_id: String, facet: String, facet_id: String, details: String) : EntityRemove = {
    NoOpEntityRemove(instance_id, facet, facet_id, details)
  }
  def remove(instance_id: Long, facet: String, facet_id: String, details: String) : EntityRemove = {
    remove(instance_id.toString, facet, facet_id, details)
  }

  def find(instance_id: String, facet: String, details: String) : EntityFind = {
    NoOpEntityFind(instance_id, facet, details)
  }
  def find(instance_id: Long, facet: String, details: String) : EntityFind = {
    find(instance_id.toString, facet, details)
  }

}

/** The registry of Entities for this Scrupal.
  *
  * This object is the registry of Entity objects. When a [[scrupal.api.Entity]] is instantiated, it will register
  * itself with this object. The object is located in [[scrupal.api.Scrupal]]
  */
case class EntitiesRegistry() extends scrupal.utils.Registry[Entity] {
  val registrantsName : String = "entity"
  val registryName : String = "Entities"
}

trait NoOpReactor extends Reactor with Describable {
  def apply(request: Stimulus) : Future[Response] = Future.successful( NoopResponse )
}

case class NoOpEntityCreate(details: String)
  extends EntityCreate with NoOpReactor
case class NoOpEntityRetrieve(instance_id: String, details: String)
  extends EntityRetrieve with NoOpReactor
case class NoOpEntityInfo(instance_id: String, details: String)
  extends EntityInfo with NoOpReactor
case class NoOpEntityUpdate(instance_id: String, details: String)
  extends EntityUpdate with NoOpReactor
case class NoOpEntityDelete(instance_id: String, details: String)
  extends EntityDelete with NoOpReactor
case class NoOpEntityQuery(details: String)
  extends EntityQuery with NoOpReactor
case class NoOpEntityAdd(instance_id: String, facet: String, details: String)
  extends EntityAdd with NoOpReactor
case class NoOpEntityGet(instance_id: String, facet: String, facet_id: String, details: String)
  extends EntityGet with NoOpReactor
case class NoOpEntityFacetInfo(instance_id: String, facet: String, facet_id: String, details: String)
  extends EntityFacetInfo with NoOpReactor
case class NoOpEntitySet(instance_id: String, facet: String, facet_id: String, details: String)
  extends EntitySet with NoOpReactor
case class NoOpEntityRemove(instance_id: String, facet: String, facet_id: String, details: String)
  extends EntityRemove with NoOpReactor
case class NoOpEntityFind(instance_id: String, facet: String, details: String)
  extends EntityFind with NoOpReactor


text:
[![Build Status](https://travis-ci.org/pahnev/KPFontPicker.svg?branch=master)](https://travis-ci.org/pahnev/KPFontPicker)

# KPFontPicker
Simple container view for a `UIPicker`.

![Demo](https://raw.github.com/pahnev/KPFontPicker/master/README%20images/demo.gif)

# How to use
Just add KPFontPicker into your project and implement delegate method.

```objc
- (void)pickerDidSelectFont:(NSString *)font withSize:(CGFloat)fontSize color:(UIColor *)fontColor
```
Check demo for details

# Todo
- Landscape support
- iPad support?

# Licence
This project is released under MIT License. Feel free to fork and stuff.


text:
<?php

namespace Lobama\Social2PrintBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Lobama\Social2PrintBundle\Entity\Score
 */
class Score
{
    /**
     * @var integer $id
     */
    private $id;

    /**
     * @var string $origin_object_id
     */
    private $origin_object_id;

    /**
     * @var Lobama\Social2PrintBundle\Entity\ScoreType
     */
    private $ScoreType;

    /**
     * @var Lobama\Social2PrintBundle\Entity\Photo
     */
    private $Photo;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set origin_object_id
     *
     * @param string $originObjectId
     */
    public function setOriginObjectId($originObjectId)
    {
        $this->origin_object_id = $originObjectId;
    }

    /**
     * Get origin_object_id
     *
     * @return string
     */
    public function getOriginObjectId()
    {
        return $this->origin_object_id;
    }

    /**
     * Set ScoreType
     *
     * @param Lobama\Social2PrintBundle\Entity\ScoreType $scoreType
     */
    public function setScoreType(\Lobama\Social2PrintBundle\Entity\ScoreType $scoreType)
    {
        $this->ScoreType = $scoreType;
    }

    /**
     * Get ScoreType
     *
     * @return Lobama\Social2PrintBundle\Entity\ScoreType
     */
    public function getScoreType()
    {
        return $this->ScoreType;
    }

    /**
     * Set Photo
     *
     * @param Lobama\Social2PrintBundle\Entity\Photo $photo
     */
    public function setPhoto(\Lobama\Social2PrintBundle\Entity\Photo $photo)
    {
        $this->Photo = $photo;
    }

    /**
     * Get Photo
     *
     * @return Lobama\Social2PrintBundle\Entity\Photo
     */
    public function getPhoto()
    {
        return $this->Photo;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.toy.data.extend.UserMapper">
  <resultMap id="BaseResultMap" type="com.toy.model.generate.User">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 07 22:17:15 CST 2015.
    -->
    <id column="user_id" jdbcType="VARCHAR" property="userId" />
    <result column="username" jdbcType="VARCHAR" property="username" />
    <result column="password" jdbcType="VARCHAR" property="password" />
    <result column="salt" jdbcType="VARCHAR" property="salt" />
    <result column="email" jdbcType="VARCHAR" property="email" />
    <result column="mobile" jdbcType="VARCHAR" property="mobile" />
    <result column="role" jdbcType="VARCHAR" property="role" />
    <result column="state" jdbcType="VARCHAR" property="state" />
    <result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
  </resultMap>
  <sql id="Example_Where_Clause">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 07 22:17:15 CST 2015.
    -->
    <where>
      <foreach collection="oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue">
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue">
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue">
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue">
                  and ${criterion.condition}
                  <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 07 22:17:15 CST 2015.
    -->
    <where>
      <foreach collection="example.oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue">
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue">
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue">
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue">
                  and ${criterion.condition}
                  <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 07 22:17:15 CST 2015.
    -->
    user_id, username, password, salt, email, mobile, role, state, create_time
  </sql>
  <select id="selectByExample" parameterType="com.toy.model.generate.UserExample" resultMap="BaseResultMap">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 07 22:17:15 CST 2015.
    -->
    select
    <if test="distinct">
      distinct
    </if>
    <include refid="Base_Column_List" />
    from user
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null">
      order by ${orderByClause}
    </if>
  </select>
  <select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 07 22:17:15 CST 2015.
    -->
    select
    <include refid="Base_Column_List" />
    from user
    where user_id = #{userId,jdbcType=VARCHAR}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.String">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 07 22:17:15 CST 2015.
    -->
    delete from user
    where user_id = #{userId,jdbcType=VARCHAR}
  </delete>
  <delete id="deleteByExample" parameterType="com.toy.model.generate.UserExample">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 07 22:17:15 CST 2015.
    -->
    delete from user
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="com.toy.model.generate.User">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 07 22:17:15 CST 2015.
    -->
    insert into user (user_id, username, password,
      salt, email, mobile,
      role, state, create_time
      )
    values (#{userId,jdbcType=VARCHAR}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
      #{salt,jdbcType=VARCHAR}, #{email,jdbcType=VARCHAR}, #{mobile,jdbcType=VARCHAR},
      #{role,jdbcType=VARCHAR}, #{state,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.toy.model.generate.User">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 07 22:17:15 CST 2015.
    -->
    insert into user
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="userId != null">
        user_id,
      </if>
      <if test="username != null">
        username,
      </if>
      <if test="password != null">
        password,
      </if>
      <if test="salt != null">
        salt,
      </if>
      <if test="email != null">
        email,
      </if>
      <if test="mobile != null">
        mobile,
      </if>
      <if test="role != null">
        role,
      </if>
      <if test="state != null">
        state,
      </if>
      <if test="createTime != null">
        create_time,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="userId != null">
        #{userId,jdbcType=VARCHAR},
      </if>
      <if test="username != null">
        #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        #{password,jdbcType=VARCHAR},
      </if>
      <if test="salt != null">
        #{salt,jdbcType=VARCHAR},
      </if>
      <if test="email != null">
        #{email,jdbcType=VARCHAR},
      </if>
      <if test="mobile != null">
        #{mobile,jdbcType=VARCHAR},
      </if>
      <if test="role != null">
        #{role,jdbcType=VARCHAR},
      </if>
      <if test="state != null">
        #{state,jdbcType=VARCHAR},
      </if>
      <if test="createTime != null">
        #{createTime,jdbcType=TIMESTAMP},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.toy.model.generate.UserExample" resultType="java.lang.Integer">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 07 22:17:15 CST 2015.
    -->
    select count(*) from user
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 07 22:17:15 CST 2015.
    -->
    update user
    <set>
      <if test="record.userId != null">
        user_id = #{record.userId,jdbcType=VARCHAR},
      </if>
      <if test="record.username != null">
        username = #{record.username,jdbcType=VARCHAR},
      </if>
      <if test="record.password != null">
        password = #{record.password,jdbcType=VARCHAR},
      </if>
      <if test="record.salt != null">
        salt = #{record.salt,jdbcType=VARCHAR},
      </if>
      <if test="record.email != null">
        email = #{record.email,jdbcType=VARCHAR},
      </if>
      <if test="record.mobile != null">
        mobile = #{record.mobile,jdbcType=VARCHAR},
      </if>
      <if test="record.role != null">
        role = #{record.role,jdbcType=VARCHAR},
      </if>
      <if test="record.state != null">
        state = #{record.state,jdbcType=VARCHAR},
      </if>
      <if test="record.createTime != null">
        create_time = #{record.createTime,jdbcType=TIMESTAMP},
      </if>
    </set>
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 07 22:17:15 CST 2015.
    -->
    update user
    set user_id = #{record.userId,jdbcType=VARCHAR},
      username = #{record.username,jdbcType=VARCHAR},
      password = #{record.password,jdbcType=VARCHAR},
      salt = #{record.salt,jdbcType=VARCHAR},
      email = #{record.email,jdbcType=VARCHAR},
      mobile = #{record.mobile,jdbcType=VARCHAR},
      role = #{record.role,jdbcType=VARCHAR},
      state = #{record.state,jdbcType=VARCHAR},
      create_time = #{record.createTime,jdbcType=TIMESTAMP}
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="com.toy.model.generate.User">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 07 22:17:15 CST 2015.
    -->
    update user
    <set>
      <if test="username != null">
        username = #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        password = #{password,jdbcType=VARCHAR},
      </if>
      <if test="salt != null">
        salt = #{salt,jdbcType=VARCHAR},
      </if>
      <if test="email != null">
        email = #{email,jdbcType=VARCHAR},
      </if>
      <if test="mobile != null">
        mobile = #{mobile,jdbcType=VARCHAR},
      </if>
      <if test="role != null">
        role = #{role,jdbcType=VARCHAR},
      </if>
      <if test="state != null">
        state = #{state,jdbcType=VARCHAR},
      </if>
      <if test="createTime != null">
        create_time = #{createTime,jdbcType=TIMESTAMP},
      </if>
    </set>
    where user_id = #{userId,jdbcType=VARCHAR}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.toy.model.generate.User">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 07 22:17:15 CST 2015.
    -->
    update user
    set username = #{username,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR},
      salt = #{salt,jdbcType=VARCHAR},
      email = #{email,jdbcType=VARCHAR},
      mobile = #{mobile,jdbcType=VARCHAR},
      role = #{role,jdbcType=VARCHAR},
      state = #{state,jdbcType=VARCHAR},
      create_time = #{createTime,jdbcType=TIMESTAMP}
    where user_id = #{userId,jdbcType=VARCHAR}
  </update>
</mapper>


text: module.exports = require('./lib/compile-module');


text:
namespace swift {
namespace syntax {

class Syntax;

/// The base class for holding parented syntax.
///
/// This structure and subclasses thereof should not contain significant public
/// API or internal modification API.
///
/// This is only for holding a strong reference to the RawSyntax, a weak
/// reference to the parent, and, in subclasses, lazily created strong
/// references to non-terminal child nodes.
class SyntaxData : public llvm::ThreadSafeRefCountedBase<SyntaxData> {
  friend struct SyntaxFactory;
#define SYNTAX(Id, Parent) friend class Id##Syntax;
#include "swift/Syntax/SyntaxKinds.def"
public:
  /// The shared raw syntax representing this syntax data node.
  const RC<RawSyntax> Raw;

  /// The parent of this syntax.
  ///
  /// WARNING! Do not access this directly. Use getParent(),
  /// which enforces nullptr checking.
  const SyntaxData *Parent;

  /// The index into the parent's child layout.
  ///
  /// If there is no parent, this is 0.
  const CursorIndex IndexInParent;

  SyntaxData(RC<RawSyntax> Raw, const SyntaxData *Parent = nullptr,
             CursorIndex IndexInParent = 0)
    : Raw(Raw), Parent(Parent), IndexInParent(IndexInParent) {}

  /// With a new RawSyntax node, create a new node from this one and
  /// recursively rebuild the parental chain up to the root.
  ///
  /// DO NOT expose this as public API.
  template <typename SyntaxNode>
  SyntaxNode replaceSelf(RC<RawSyntax> NewRaw) const {
    auto NewMe = SyntaxNode::DataType::make(NewRaw, nullptr, IndexInParent);
    if (hasParent()) {
      auto NewRootAndParent = getParent().getValue()
        ->replaceChild<Syntax>(NewRaw, IndexInParent);
      NewMe->Parent = NewRootAndParent.Data;
      return SyntaxNode {
        NewRootAndParent.Root,
        cast<typename SyntaxNode::DataType>(NewMe.get())
      };
    } else {
      return SyntaxNode {
        NewMe,
        cast<typename SyntaxNode::DataType>(NewMe.get())
      };
    }
  }

  /// Unsafely instantiate a child within another node.
  ///
  /// DANGER!
  ///
  /// Scary thread-safe code here. This should only be used for internally
  /// mutating cached children!
  ///
  /// Why do we need this?
  /// - ___SyntaxData nodes should have pointer identity.
  /// - We only want to construct parented, realized child nodes as
  /// ___SyntaxData when asked.
  ///
  /// For example, if we have a ReturnStmtSyntax, and ask for its returned
  /// expression for the first time with getExpression(), two nodes can race
  /// to create and set the cached expression.
  ///
  ///
  /// Looking at an example - say we have a ReturnStmtSyntaxData.
  ///
  /// ReturnStmtSyntaxData = {
  ///   RC<RawSyntax> Raw = {
  ///     RC<TokenSyntax { SyntaxKind::Token, tok::return_kw, "return" },
  ///     RC<RawSyntax> { SyntaxKind::SomeExpression, ... }
  ///   }
  ///   RC<ExprSyntaxData> CachedExpression = { 0 };
  /// }
  ///
  /// We pretend that `CachedExpression` is a std::atomic<uintptr_t> &, so that
  /// we can safely instantiate that field using the RawSyntax for the
  /// expression, i.e. getRaw()->getChild(ReturnStmtSyntax::Cursor::Expression))
  template <typename SyntaxNode>
  static
  void realizeSyntaxNode(std::atomic<uintptr_t> &Child,
                         RC<RawSyntax> RawChild,
                         const SyntaxData *Parent,
                         CursorIndex IndexInParent) {
    // We rely on the fact that an RC<___SyntaxData> is pointer-sized, which
    // means we can atomically compare-exchange the child field.
    // If we can't do that, we can't pretend it's a uintptr_t and use its
    // compare_exchange_strong.
    static_assert(
      sizeof(uintptr_t) == sizeof(RC<typename SyntaxNode::DataType>),
      "Can't safely atomically replace a child SyntaxData node "
      "for caching! This is the end of the world!");

    if (Child == 0) {
      // We expect the uncached value to wrap a nullptr. If another thread
      // beats us to caching the child, it'll be non-null, so we would
      // leave it alone.
      uintptr_t Expected = 0;

      // Make a RC<SyntaxNode::DataType> at RefCount == 1, which we'll try to
      // atomically swap in.
      RC<typename SyntaxNode::DataType> Data =
        cast<typename SyntaxNode::DataType>(
          SyntaxData::makeDataFromRaw(RawChild, Parent, IndexInParent));

      // Try to swap in raw pointer value.
      auto SuccessfullySwapped =
        Child.compare_exchange_strong(Expected,
                                      reinterpret_cast<uintptr_t>(Data.get()));

      // If we won, then leave the RefCount == 1.
      if (SuccessfullySwapped) {
        Data.resetWithoutRelease();
      }

      // Otherwise, the Data we just made is unfortunately useless.
      // Let it die on this scope exit after its terminal release.
    }
  }

  /// Replace a child in the raw syntax and recursively rebuild the
  /// parental chain up to the root.
  ///
  /// This is the effective private implementation of all setters in
  /// subclasses of `SyntaxData`.
  ///
  /// DO NOT expose this as public API.
  template <typename SyntaxNode, typename CursorType>
  SyntaxNode replaceChild(RC<RawSyntax> RawChild,
                          CursorType ChildCursor) const {
    auto NewRaw = Raw->replaceChild(ChildCursor, RawChild);
    return replaceSelf<SyntaxNode>(NewRaw);
  }

public:

  static RC<SyntaxData> makeDataFromRaw(RC<RawSyntax> Raw,
                                        const SyntaxData *Parent,
                                        CursorIndex IndexInParent);

  static RC<SyntaxData> make(RC<RawSyntax> Raw,
                             const SyntaxData *Parent = nullptr,
                             CursorIndex IndexInParent = 0);

  /// Returns the raw syntax node for this syntax node.
  const RC<RawSyntax> getRaw() const {
    return Raw;
  }

  /// Returns the kind of syntax node this is.
  SyntaxKind getKind() const {
    return Raw->Kind;
  }

  /// Return the parent syntax if there is one.
  llvm::Optional<const SyntaxData *> getParent() const {
    if (Parent != nullptr) {
      return Parent;
    }
    return NoParent;
  }

  /// Returns true if this syntax node has a parent.
  bool hasParent() const {
    return Parent != nullptr;
  }

  /// Returns the child index of this node in its parent, if it has a parent,
  /// otherwise 0.
  size_t getIndexInParent() const {
    return IndexInParent;
  }

  /// Returns true if the data node represents type syntax.
  bool isType() const;

  /// Returns true if the data node represents statement syntax.
  bool isStmt() const;

  /// Returns true if the data node represents declaration syntax.
  bool isDecl() const;

  /// Returns true if the data node represents expression syntax.
  bool isExpr() const;

  /// Returns true if this syntax is of some "unknown" kind.
  bool isUnknown() const;

  /// Dump a debug description of the syntax data for debugging to
  /// standard error.
  void dump(llvm::raw_ostream &OS) const;
};

} // end namespace syntax
} // end namespace swift

// DenseMapInfo for RC<SyntaxData>, used for a Syntax Node -> lib/AST mapping.
namespace llvm {
  using SD = swift::syntax::SyntaxData;
  using RCSD = swift::RC<SD>;
  template <> struct llvm::DenseMapInfo<RCSD> {
    static inline RCSD getEmptyKey() {
      return SD::make(nullptr, nullptr, 0);
    }
    static inline RCSD getTombstoneKey() {
        return SD::make(nullptr, nullptr, 0);
    }
    static unsigned getHashValue(const RCSD Value) {
      unsigned H = 0;
      H ^= DenseMapInfo<uintptr_t>::getHashValue(reinterpret_cast<const uintptr_t>(Value->Raw.get()));
      H ^= DenseMapInfo<uintptr_t>::getHashValue(reinterpret_cast<const uintptr_t>(Value->Parent));
      H ^= DenseMapInfo<swift::syntax::CursorIndex>::getHashValue(Value->getIndexInParent());
      return H;
    }
    static bool isEqual(const RCSD LHS, const RCSD RHS) {
      return LHS->getRaw().get() == RHS->getRaw().get() &&
             LHS->getParent() == RHS->getParent() &&
             LHS->getIndexInParent() == RHS->getIndexInParent();
    }
  };
}

#endif // SWIFT_SYNTAX_SYNTAXDATA_H


text:
<?php
    /**
     * @var $MODEL \App\Scaffold\Installer\Model\ModelDefinition
     * @var $field  \App\Scaffold\Installer\Model\Field
     */
    $middleWare = $MODEL->getMiddleware();
    echo '<?php' ?> namespace {{$NAME_SPACE}}\Controllers;

use {{$NAME_SPACE}}\Requests\Create{{$MODEL_NAME}}Request;
use {{$NAME_SPACE}}\Requests\Update{{$MODEL_NAME}}Request;
use {{$NAME_SPACE}}\Repositories\{{$MODEL_NAME}}Repository;
use App\Http\Requests\IndexRequest;
use App\Http\Requests\ShowRequest;
use Illuminate\Http\JsonResponse;
use App\Scaffold\AppBaseController;

class {{$MODEL_NAME}}Controller extends AppBaseController
{

    public function __construct({{$MODEL_NAME}}Repository $repository)
    {
        $this->repository = $repository;
@if($middleWare)
        $this->middleware("{{$middleWare}}");
@endif
        $this->middleware("permission.auto");
    }

    /**
     * Display a listing of the {{$MODEL_NAME}}.
     *
     * @param IndexRequest $request
     * @return JsonResponse|\Illuminate\Http\Response|\Symfony\Component\HttpFoundation\BinaryFileResponse
     * @throws \Exception
     */
    public function index(IndexRequest $request)
    {
        $data = $this->repository->datatables(null, $request->getWith())
        ->search($request->getColumns(), null)
        ->result($request->getExportFileName());

        return $data;
    }

    /**
     * Store a newly created {{$MODEL_NAME}} in storage.
     *
     * @param Create{{$MODEL_NAME}}Request $request
     * @return JsonResponse
     */
    public function store(Create{{$MODEL_NAME}}Request $request)
    {
        $input = $request->all();

        $item = $this->repository->create($input);
        $item->load($request->getWith());

        return $this->sendResponse($item, '{{$MODEL_NAME}} saved successfully.');
    }

    /**
     * Display the specified {{$MODEL_NAME}}.
     *
     * @param  int $id
     *
     * @return JsonResponse
     */
    public function show($id, ShowRequest $request)
    {
        $item = $this->repository->findWithoutFail($id);
        if (empty($item)) {
            return $this->sendError('{{$MODEL_NAME}} not found');
        }
        $item->load($request->getWith());

        return $this->sendResponse($item, '');
    }

    /**
     * Update the specified {{$MODEL_NAME}} in storage.
     *
     * @param  int $id
     * @param Update{{$MODEL_NAME}}Request $request
     *
     * @return JsonResponse
     */
    public function update($id, Update{{$MODEL_NAME}}Request $request)
    {
        $item = $this->repository->findWithoutFail($id);

        if (empty($item)) {
            return $this->sendError('{{$MODEL_NAME}} not found');
        }

        $item = $this->repository->update($request->all(), $id);
        $item->load($request->getWith());

        return $this->sendResponse($item, '{{$MODEL_NAME}} updated successfully.');
    }

    /**
     * Remove the specified {{$MODEL_NAME}} from storage.
     *
     * @param  int $id
     *
     * @return JsonResponse
     */
    public function destroy($id)
    {
        $item = $this->repository->findWithoutFail($id);

        if (empty($item)) {
            return $this->sendError('{{$MODEL_NAME}} not found');
        }

        $this->repository->delete($id);

        return $this->sendResponse($item, '{{$MODEL_NAME}} deleted successfully.');
    }
}


text: "use strict";var app=angular.module("hosonto",["infinite-scroll","ngFileUpload"]);


text:
RASlideInViewController
=======================

#### RASlideInViewController has an transition effect expressing the depth, and you can dismiss it by draging.

### Screen shots
![screen shot1](https://github.com/ra1028/RASlideInViewController/raw/master/Assets/screenshot1.png)
![screen shot2](https://github.com/ra1028/RASlideInViewController/raw/master/Assets/screenshot2.png)
![screen shot3](https://github.com/ra1028/RASlideInViewController/raw/master/Assets/screenshot3.png)

### Example animation
![animated gif](https://github.com/ra1028/RASlideInViewController/raw/master/Assets/animation.gif)

### Usage

Please add the library into your project, and create subclass of this class.

#### Example
```Objective-C
    UIStoryboard *storyboard = self.storyboard;
    RANewSlideInViewController *slideViewController = [storyboard instantiateViewControllerWithIdentifier:NSStringFromClass([RANewSlideInViewController class])];

    self.modalPresentationStyle = UIModalPresentationCurrentContext;  //***

    [self presentViewController:slideViewController animated:NO completion:nil];
```

```Objective-C
    UIStoryboard *storyboard = self.storyboard;
    RANewSlideInViewController *slideViewController = [storyboard instantiateViewControllerWithIdentifier:NSStringFromClass([RANewSlideInViewController class])];
    slideViewController.slideInDirection = RASlideInDirectionLeftToRight;

    _subWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _subWindow.windowLevel = UIWindowLevelStatusBar;
    _subWindow.rootViewController = slideViewController;
    [_subWindow makeKeyAndVisible];
```

#### Option
```Objective-C
typedef NS_ENUM(NSInteger, RASlideViewSlideInDirection){
    RASlideInDirectionBottomToTop,
    RASlideInDirectionRightToLeft,
    RASlideInDirectionTopToBottom,
    RASlideInDirectionLeftToRight
};

@interface RASlideInViewController : UIViewController

@property (nonatomic, assign) RASlideViewSlideInDirection slideInDirection; //default RASlideInDirectionBottomToTop;
@property (nonatomic, assign) BOOL shiftBackDropView; //default NO
@property (nonatomic, assign) CGFloat animationDuration; //default .3f
@property (nonatomic, assign) CGFloat backdropViewScaleReductionRatio; //default .9f
@property (nonatomic, assign) CGFloat shiftBackDropViewValue; //default 100.f
@property (nonatomic, assign) CGFloat backDropViewAlpha; //default 0

@end
```

### License
RASlideInViewController is released under the MIT License, see LICENSE.txt.


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>net.dvt32.javabrains</groupId>
  <artifactId>advanced-jaxrs-01</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>advanced-jaxrs-01 Maven Webapp</name>
  <url>http://maven.apache.org</url>

  <dependencies>
    <dependency>
      <groupId>org.glassfish.jersey.bundles</groupId>
      <artifactId>jaxrs-ri</artifactId>
      <version>2.16</version>
    </dependency>
    <dependency>
      <groupId>org.glassfish.jersey.media</groupId>
      <artifactId>jersey-media-moxy</artifactId>
      <version>2.16</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>advanced-jaxrs-01</finalName>
    <plugins>
    	<plugin>
    		<groupId>org.apache.maven.plugins</groupId>
    		<artifactId>maven-compiler-plugin</artifactId>
    		<version>2.5.1</version>
    		<inherited>true</inherited>
    		<configuration>
    			<source>1.7</source>
    			<target>1.7</target>
    		</configuration>
    	</plugin>
    </plugins>
  </build>

  <properties>
  	<jersey.version>2.16</jersey.version>
  	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

</project>


text:
```php
<?php
namespace Models;

use AdjutantHandlers\Time\Occurrences\Inventory\OccurrencesModel;

class ExtendedOccurrencesModel extends OccurrencesModel
{
    protected $mysqli;

    public function __construct()
    {
        $this->mysqli = MySQLConnection::getConnection();
    }

    public function checkDateIsWorkWeekend($weekendDate)
    {
        $query = parent::checkDateIsWorkWeekend($weekendDate);
        return $this->mysqli->query($query)->fetch_object();
    }

    public function checkDateIsNotNormalLengthDay($notNormalLengthDay)
    {
        $query = parent::checkDateIsNotNormalLengthDay($notNormalLengthDay);
        return $this->mysqli->query($query)->fetch_object();
    }

    public function checkDateIsHoliday($day, $month)
    {
        $query = parent::checkDateIsHoliday($day, $month);
        return $this->mysqli->query($query)->fetch_object();
    }

}

```


text:
import argparse
import sys
import os
import re
from pathlib import Path

def convertFile(file_path):
    contents = Path(file_path).read_text()
    # print(contents)
    # find $ $ and replace
    line_matches = re.findall(r'\$([^$]+)?\$', contents)
    for formula in line_matches:
        if len(formula) == 0:
            continue
        new_formula = formula.replace('_', '\_')
        new_formula = new_formula.replace('*', '\*')
        res = re.findall(r"P(x_\{t\+1\} \\vert x_t)", contents)
        print(repr(formula), res)
        break
    print(line_matches)
    # Path(file_path).write_text(contents)
    # write_text
    return

def main():
    parser = argparse.ArgumentParser(description='Give file path')
    parser.add_argument('-f', nargs='+',
                       help='the file to convert')

    args = parser.parse_args()
    try:
        for file_path in vars(args)['f']:
            convertFile(file_path)
    except:
        print("file list error")
        raise

if __name__ == '__main__':
    main()


text:
package rxmongo.bson

import scala.annotation.switch

/** Base class of the case objects for BSON code values
  *
  * Byte code identifiers from here: [[http://docs.mongodb.org/manual/reference/bson-types/]]
  */
sealed trait TypeCode {
  val code : Byte
  val typeName : String
}

case object NotACode extends { val code : Byte = 0; val typeName = "Not_A_BSONValue" } with TypeCode
case object DoubleCode extends { val code : Byte = 1; val typeName = "BSONDouble" } with TypeCode
case object StringCode extends { val code : Byte = 2; val typeName = "BSONString" } with TypeCode
case object ObjectCode extends { val code : Byte = 3; val typeName = "BSONObject" } with TypeCode
case object ArrayCode extends { val code : Byte = 4; val typeName = "BSONArray" } with TypeCode
case object BinaryCode extends { val code : Byte = 5; val typeName = "BSONBinary" } with TypeCode
/** @deprecated */
case object UndefinedCode extends { val code : Byte = 6; val typeName = "BSONUndefinede" } with TypeCode
case object ObjectIDCode extends { val code : Byte = 7; val typeName = "BSONObjectID" } with TypeCode
case object BooleanCode extends { val code : Byte = 8; val typeName = "BSONBoolean" } with TypeCode
case object DateCode extends { val code : Byte = 9; val typeName = "BSONDate" } with TypeCode
case object NullCode extends { val code : Byte = 10; val typeName = "BSONNull" } with TypeCode
case object RegexCode extends { val code : Byte = 11; val typeName = "BSONRegex" } with TypeCode
/** @deprecated */
case object DBPointerCode extends { val code : Byte = 12; val typeName = "BSONDBPointer" } with TypeCode
case object JavaScriptCode extends { val code : Byte = 13; val typeName = "BSONJavaScript" } with TypeCode
/** @deprecated */
case object SymbolCode extends { val code : Byte = 14; val typeName = "BSONSymbol" } with TypeCode
case object ScopedJSCode extends { val code : Byte = 15; val typeName = "BSONScopedJSCode" } with TypeCode
case object IntegerCode extends { val code : Byte = 16; val typeName = "BSONInteger" } with TypeCode
case object TimestampCode extends { val code : Byte = 17; val typeName = "BSONTimestamp" } with TypeCode
case object LongCode extends { val code : Byte = 18; val typeName = "BSONLong" } with TypeCode
case object MinKey extends { val code : Byte = 255.toByte; val typeName = "MinKey" } with TypeCode
case object MaxKey extends { val code : Byte = 127; val typeName = "MaxKey" } with TypeCode

object TypeCode {
  def apply(code : Byte) : TypeCode = {
    (code : @switch) match {
      case 1   ⇒ DoubleCode
      case 2   ⇒ StringCode
      case 3   ⇒ ObjectCode
      case 4   ⇒ ArrayCode
      case 5   ⇒ BinaryCode
      case 6   ⇒ UndefinedCode
      case 7   ⇒ ObjectIDCode
      case 8   ⇒ BooleanCode
      case 9   ⇒ DateCode
      case 10  ⇒ NullCode
      case 11  ⇒ RegexCode
      case 12  ⇒ DBPointerCode
      case 13  ⇒ JavaScriptCode
      case 14  ⇒ SymbolCode
      case 15  ⇒ ScopedJSCode
      case 16  ⇒ IntegerCode
      case 17  ⇒ TimestampCode
      case 18  ⇒ LongCode
      case -1  ⇒ MinKey
      case 127 ⇒ MaxKey
      case _ ⇒
        throw new NoSuchElementException(s"BSON TypeCode($code)")
    }
  }
  def apply(v : BSONValue) : TypeCode = v.code
}


text:
package kieker.analysis.plugin.filter.forward;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import kieker.analysis.IProjectContext;
import kieker.analysis.plugin.annotation.InputPort;
import kieker.analysis.plugin.annotation.OutputPort;
import kieker.analysis.plugin.annotation.Plugin;
import kieker.analysis.plugin.annotation.Property;
import kieker.analysis.plugin.filter.AbstractFilterPlugin;
import kieker.common.configuration.Configuration;

/**
 * This filter has exactly one input port and one output port.
 *
 * A simple message is printed to a configurable stream and all objects are
 * forwarded to the output port.
 *
 * @author Matthias Rohr, Jan Waller
 *
 * @since 1.2
 * @deprecated since 1.15 ported to teetime kieker.analysis.stage.forward.TeeFilter
 */
@Deprecated
@Plugin(description = "A filter to print the object to a configured stream",
		outputPorts = @OutputPort(name = TeeFilter.OUTPUT_PORT_NAME_RELAYED_EVENTS, description = "Provides each incoming object",
				eventTypes = Object.class),
		configuration = {
			@Property(name = TeeFilter.CONFIG_PROPERTY_NAME_STREAM, defaultValue = TeeFilter.CONFIG_PROPERTY_VALUE_STREAM_STDOUT,
					description = "The name of the stream used to print the incoming data (special values are STDOUT, STDERR, STDlog, and NULL; "
							+ "other values are interpreted as filenames)."),
			@Property(name = TeeFilter.CONFIG_PROPERTY_NAME_ENCODING, defaultValue = TeeFilter.CONFIG_PROPERTY_VALUE_DEFAULT_ENCODING,
					description = "The used encoding for the selected stream."),
			@Property(name = TeeFilter.CONFIG_PROPERTY_NAME_APPEND, defaultValue = TeeFilter.CONFIG_PROPERTY_VALUE_STREAM_APPEND,
					description = "Decides whether the filter appends to the stream in the case of a file or not.") })
public final class TeeFilter extends AbstractFilterPlugin {

	/** The name of the input port for incoming events. */
	public static final String INPUT_PORT_NAME_EVENTS = "receivedEvents";
	/** The name of the output port delivering the incoming events. */
	public static final String OUTPUT_PORT_NAME_RELAYED_EVENTS = "relayedEvents";
	/**
	 * The name of the property determining the stream in which the incoming data
	 * will be printed.
	 */
	public static final String CONFIG_PROPERTY_NAME_STREAM = "stream";
	/** The name of the property determining the used encoding. */
	public static final String CONFIG_PROPERTY_NAME_ENCODING = "characterEncoding";
	/**
	 * The name of the property determining whether or not the stream appends or
	 * overwrites to files.
	 */
	public static final String CONFIG_PROPERTY_NAME_APPEND = "append";

	/**
	 * The value of the stream property which determines that the filter uses the
	 * standard output.
	 */
	public static final String CONFIG_PROPERTY_VALUE_STREAM_STDOUT = "STDOUT";
	/**
	 * The value of the stream property which determines that the filter uses the
	 * standard error output.
	 */
	public static final String CONFIG_PROPERTY_VALUE_STREAM_STDERR = "STDERR";
	/**
	 * The value of the stream property which determines that the filter uses the
	 * standard log.
	 */
	public static final String CONFIG_PROPERTY_VALUE_STREAM_STDLOG = "STDlog";
	/**
	 * The value of the stream property which determines that the filter doesn't
	 * print anything.
	 */
	public static final String CONFIG_PROPERTY_VALUE_STREAM_NULL = "NULL";
	/**
	 * The default value of the encoding property which determines that the filter
	 * uses utf-8.
	 */
	public static final String CONFIG_PROPERTY_VALUE_DEFAULT_ENCODING = "UTF-8";
	/**
	 * The default value of the stream property which determines that the filter
	 * appends or overwrites a file.
	 */
	public static final String CONFIG_PROPERTY_VALUE_STREAM_APPEND = "true";

	private final PrintStream printStream;
	private final String printStreamName;
	private final boolean active;
	private final boolean append;
	private final String encoding;

	/**
	 * Creates a new instance of this class using the given parameters.
	 *
	 * @param configuration
	 *            The configuration for this component.
	 * @param projectContext
	 *            The project context for this component.
	 */
	public TeeFilter(final Configuration configuration, final IProjectContext projectContext) {
		super(configuration, projectContext);

		// Get the name of the stream.
		final String printStreamNameConfig = this.configuration.getStringProperty(CONFIG_PROPERTY_NAME_STREAM);
		// Get the encoding.
		this.encoding = this.configuration.getStringProperty(CONFIG_PROPERTY_NAME_ENCODING);

		// Decide which stream to be used - but remember the name!
		if (CONFIG_PROPERTY_VALUE_STREAM_STDLOG.equals(printStreamNameConfig)) {
			this.printStream = null; // NOPMD (null)
			this.printStreamName = null; // NOPMD (null)
			this.active = true;
			this.append = false;
		} else if (CONFIG_PROPERTY_VALUE_STREAM_STDOUT.equals(printStreamNameConfig)) {
			this.printStream = System.out;
			this.printStreamName = null; // NOPMD (null)
			this.active = true;
			this.append = false;
		} else if (CONFIG_PROPERTY_VALUE_STREAM_STDERR.equals(printStreamNameConfig)) {
			this.printStream = System.err;
			this.printStreamName = null; // NOPMD (null)
			this.active = true;
			this.append = false;
		} else if (CONFIG_PROPERTY_VALUE_STREAM_NULL.equals(printStreamNameConfig)) {
			this.printStream = null; // NOPMD (null)
			this.printStreamName = null; // NOPMD (null)
			this.active = false;
			this.append = false;
		} else {
			this.append = configuration.getBooleanProperty(CONFIG_PROPERTY_NAME_APPEND);
			PrintStream tmpPrintStream;
			try {
				final OutputStream stream = Files.newOutputStream(Paths.get(printStreamNameConfig), StandardOpenOption.CREATE,
						this.append ? StandardOpenOption.APPEND : StandardOpenOption.WRITE); // NOCS
				tmpPrintStream = new PrintStream(stream, false, this.encoding);
			} catch (final UnsupportedEncodingException ex) {
				this.logger.error("Failed to initialize {}", printStreamNameConfig, ex);
				tmpPrintStream = null; // NOPMD (null)
			} catch (final FileNotFoundException ex) {
				this.logger.error("Failed to initialize {}", printStreamNameConfig, ex);
				tmpPrintStream = null; // NOPMD (null)
			} catch (final IOException ex) {
				this.logger.error("Failed to initialize {}", printStreamNameConfig, ex);
				tmpPrintStream = null; // NOPMD (null)
			}
			this.printStream = tmpPrintStream;
			this.printStreamName = printStreamNameConfig;
			this.active = true;
		}
	}

	@Override
	public final void terminate(final boolean error) {
		if ((this.printStream != null) && (this.printStream != System.out) && (this.printStream != System.err)) {
			this.printStream.close();
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public final Configuration getCurrentConfiguration() {
		final Configuration configuration = new Configuration();
		configuration.setProperty(CONFIG_PROPERTY_NAME_ENCODING, this.encoding);
		configuration.setProperty(CONFIG_PROPERTY_NAME_APPEND, Boolean.toString(this.append));
		// We reverse the if-decisions within the constructor.
		if (this.printStream == null) {
			if (this.active) {
				configuration.setProperty(CONFIG_PROPERTY_NAME_STREAM, CONFIG_PROPERTY_VALUE_STREAM_STDLOG);
			} else {
				configuration.setProperty(CONFIG_PROPERTY_NAME_STREAM, CONFIG_PROPERTY_VALUE_STREAM_NULL);
			}
		} else if (this.printStream == System.out) {
			configuration.setProperty(CONFIG_PROPERTY_NAME_STREAM, CONFIG_PROPERTY_VALUE_STREAM_STDOUT);
		} else if (this.printStream == System.err) {
			configuration.setProperty(CONFIG_PROPERTY_NAME_STREAM, CONFIG_PROPERTY_VALUE_STREAM_STDERR);
		} else {
			configuration.setProperty(CONFIG_PROPERTY_NAME_STREAM, this.printStreamName);
		}
		return configuration;
	}

	/**
	 * This method is the input port of the filter receiving incoming objects. Every
	 * object will be printed into a stream (based on the configuration) before the
	 * filter sends it to the output port.
	 *
	 * @param object
	 *            The new object.
	 */
	@InputPort(name = INPUT_PORT_NAME_EVENTS, description = "Receives incoming objects to be logged and forwarded",
			eventTypes = Object.class)
	public final void inputEvent(final Object object) {
		if (this.active) {
			final StringBuilder sb = new StringBuilder(128);
			sb.append(this.getName()).append('(').append(object.getClass().getSimpleName()).append(") ")
					.append(object.toString());
			final String record = sb.toString();
			if (this.printStream != null) {
				this.printStream.println(record);
			} else {
				this.logger.info(record);
			}
		}
		super.deliver(OUTPUT_PORT_NAME_RELAYED_EVENTS, object);
	}
}


text:
import os
import shutil
import pwd
import sys
import inspect

from setuptools import setup, find_packages

###############################################################################
# CONSTANTS
###############################################################################

SAMPLE_CONF_FILE_NAMES = ["mongoctl.config",
                          "servers.config",
                          "clusters.config"]

###############################################################################
# Calculating sample_conf_files
###############################################################################
def get_sample_conf_dir():
    this_dir = os.path.dirname(
        inspect.getfile(inspect.currentframe()))
    return os.path.join(this_dir, "mongoctl/sample_conf")

###############################################################################
def copy_sample_configs():

    # create the dot_mongoctl_dir if it does not exist
    # mode of folder is user RW and R for group and others
    try:
        login = os.getlogin()
        home_dir = os.path.expanduser( "~%s" % login)
        dot_mongoctl_dir = os.path.join(home_dir, ".mongoctl")
        owner = pwd.getpwnam(login)
        owner_uid = owner[2]
        owner_gid = owner[3]

        if not os.path.exists(dot_mongoctl_dir):
            os.makedirs(dot_mongoctl_dir)
        else:
            return True

        os.chown(dot_mongoctl_dir, owner_uid, owner_gid)
        os.chmod(dot_mongoctl_dir, 00755)

        sample_conf_dir = get_sample_conf_dir()

        for fname in SAMPLE_CONF_FILE_NAMES:
            data_file_path = os.path.join(dot_mongoctl_dir, fname)
            if not os.path.exists(data_file_path):
                src_file = os.path.join(sample_conf_dir, fname)
                # copy file
                print ("Creating sample configuration file '%s' in '%s' " %
                       (fname,dot_mongoctl_dir))
                shutil.copyfile(src_file, data_file_path)
                # make file writable
                os.chown(data_file_path, owner_uid, owner_gid)
                os.chmod(data_file_path, 00644)
    except Exception, e:
        print ("Error while copying sample config files. "
               "This is not harmful. The error happened while trying to "
               "determine owner/mode of sample config files: %s" % e)

version_str = "0.7.0"

def install_latest_mongodb():
    try:
        from mongoctl.commands.misc.install import install_mongodb
        install_mongodb(version_str)
    except Exception, e:
        #print "Unable to install latest mongodb. Cause: '%s' " % e
        pass

###############################################################################
# mongoct post install
def mongoctl_post_install():
    configs_exists = copy_sample_configs()
    if not configs_exists:
        install_latest_mongodb()

###############################################################################
# Setup
###############################################################################
setup(
    name='mongoctl',
    version=version_str,
    author='richardxx',
    author_email='richardxx@cse.ust.hk',
    description='MongoDB command line utility',
    long_description="mongoctl is a lightweight command line utility that simplifies the"
                     " installation of MongoDB and management of MongoDB servers and replica set clusters. It is"
                     " particularly useful if you maintain many MongoDB environments with"
                     " lots of configurations to manage.",
    packages=find_packages(),

    package_data = {'mongoctl.tests.testing_conf':
                        ['*.config'],
                    'mongoctl.sample_conf':
                        ['*.config']},
    test_suite="mongoctl.tests.test_suite",
    include_package_data=True,
    scripts=['bin/mongoctl'],
    url='https://github.com/mongolab/mongoctl',
    license='MIT',
    install_requires=[
        'dargparse',
        'pymongo>=2.4.2',
        'verlib==0.1']

)

### execute this block after setup "install" command is complete
if "install" in sys.argv:
    mongoctl_post_install()