text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Navigation;
using GraphX.Controls;
using GraphX.Controls.Animations;
using GraphX.Controls.Models;
using GraphX.PCL.Common.Enums;
using GraphX.PCL.Logic.Algorithms.LayoutAlgorithms;
using GraphX.PCL.Logic.Algorithms.OverlapRemoval;
using METRO.SimpleGraph.Models;
using QuickGraph.Graphviz.Dot;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace METRO.SimpleGraph
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            InitializeComponent();

            cboxLayout.ItemsSource = Enum.GetValues(typeof(LayoutAlgorithmTypeEnum)).Cast<LayoutAlgorithmTypeEnum>();//.Where(a=> a != LayoutAlgorithmTypeEnum.FR && a != LayoutAlgorithmTypeEnum.BoundedFR).ToArray();
            cboxOverlap.ItemsSource = Enum.GetValues(typeof(OverlapRemovalAlgorithmTypeEnum)).Cast<OverlapRemovalAlgorithmTypeEnum>();
            cboxEdgeRouting.ItemsSource = Enum.GetValues(typeof(EdgeRoutingAlgorithmTypeEnum)).Cast<EdgeRoutingAlgorithmTypeEnum>();

            cboxLayout.SelectedItem = LayoutAlgorithmTypeEnum.LinLog;
            cboxOverlap.SelectedItem = OverlapRemovalAlgorithmTypeEnum.FSA;
            cboxEdgeRouting.SelectedItem = EdgeRoutingAlgorithmTypeEnum.None;

            cboxLayout.SelectionChanged += cboxLayout_SelectionChanged;
            cboxOverlap.SelectionChanged += cboxOverlap_SelectionChanged;
            cboxEdgeRouting.SelectionChanged += cboxEdgeRouting_SelectionChanged;

            butRelayout.Click += butRelayout_Click;
            butGenerate.Click += butGenerate_Click;
            graph.GenerateGraphFinished += OnFinishedLayout;
            graph.RelayoutFinished += OnFinishedLayout;
            graph.AlignAllEdgesLabels();
            graph.ControlsDrawOrder = ControlDrawOrder.VerticesOnTop;
            Loaded += MainPage_Loaded;
        }

        void OnFinishedLayout(object sender, EventArgs e)
        {
            zc.ZoomToFill();
        }

        private async void butGenerate_Click(object sender, RoutedEventArgs e)
        {
            GraphAreaExample_Setup();
            try
            {
                await graph.GenerateGraphAsync();
            }
            catch (OperationCanceledException)
            {
                // User may have canceled
            }
        }

        async void butRelayout_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                await graph.RelayoutGraphAsync();
            }
            catch (OperationCanceledException)
            {
                // User may have canceled
            }
        }

        void cboxEdgeRouting_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (graph.LogicCore == null) return;
            graph.LogicCore.DefaultEdgeRoutingAlgorithm = (EdgeRoutingAlgorithmTypeEnum)cboxEdgeRouting.SelectedItem;
        }

        void cboxOverlap_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (graph.LogicCore == null) return;
            graph.LogicCore.DefaultOverlapRemovalAlgorithm = (OverlapRemovalAlgorithmTypeEnum)cboxOverlap.SelectedItem;
        }

        void cboxLayout_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(graph.LogicCore == null) return;
            var late = (LayoutAlgorithmTypeEnum) cboxLayout.SelectedItem;
            graph.LogicCore.DefaultLayoutAlgorithm = late;
            if (late == LayoutAlgorithmTypeEnum.BoundedFR)
                graph.LogicCore.DefaultLayoutAlgorithmParams
                    = graph.LogicCore.AlgorithmFactory.CreateLayoutParameters(LayoutAlgorithmTypeEnum.BoundedFR);
            if (late == LayoutAlgorithmTypeEnum.FR)
                graph.LogicCore.DefaultLayoutAlgorithmParams
                    = graph.LogicCore.AlgorithmFactory.CreateLayoutParameters(LayoutAlgorithmTypeEnum.FR);
        }

        async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            InitialSetup();
            GraphAreaExample_Setup();

            try
            {
                await graph.GenerateGraphAsync();
            }
            catch (OperationCanceledException)
            {
                // User may have canceled
            }

            //graph.RelayoutGraph(true);
            //zc.ZoomToFill();
            //graph.VertexList.Values.ToList()[0].SetPosition(new Point(0, 0));
            //graph.VertexList.Values.ToList()[1].SetPosition(new Point(100, 0));
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void AddEdge(GraphExample igraph, int index1, int index2, IReadOnlyList<DataVertex> vlist)
        {
            var dataEdge = new DataEdge(vlist[index1], vlist[index2])
            {
                Text = string.Format("Edge {0}{1}", vlist[index1].ID, vlist[index2].ID),
                VisualEdgeThickness = _rnd.Next(1, 4),
                VisualEdgeTransparency = 1.0,
                VisualColor = "#ffffff"
            };
            igraph.AddEdge(dataEdge);
        }

        private readonly Random _rnd = new Random();
        private GraphExample GraphExample_Setup()
        {
            var dataGraph = new GraphExample();
            var vlist = new List<DataVertex>();;

            //debug
           /* dataGraph.AddVertex(new DataVertex("MyVertex " + 1) { ID = 1, VisualDiameter = 10, VisualInnerDiameter = 10 });
            dataGraph.AddVertex(new DataVertex("MyVertex " + 2) { ID = 2, VisualDiameter = 10, VisualInnerDiameter = 10 });
            vlist = dataGraph.Vertices.ToList();
            AddEdge(dataGraph, 0, 1, vlist);
            return dataGraph;*/

            switch ((LayoutAlgorithmTypeEnum)cboxLayout.SelectedItem)
            {
                case LayoutAlgorithmTypeEnum.EfficientSugiyama:
                case LayoutAlgorithmTypeEnum.Sugiyama:
                case LayoutAlgorithmTypeEnum.BoundedFR:
                case LayoutAlgorithmTypeEnum.FR:
                case LayoutAlgorithmTypeEnum.Tree:
                    for (int i = 1; i < 14; i++)
                    {
                        var dataVertex = new DataVertex("MyVertex " + i) { ID = i, VisualDiameter = _rnd.Next(25, 50), VisualInnerDiameter = _rnd.Next(10, 22) };
                        dataGraph.AddVertex(dataVertex);
                    }
                    vlist = dataGraph.Vertices.ToList();
                    AddEdge(dataGraph, 0, 1, vlist);
                    AddEdge(dataGraph, 0, 0, vlist);

                    AddEdge(dataGraph, 0, 2, vlist);
                    AddEdge(dataGraph, 1, 3, vlist);
                    AddEdge(dataGraph, 1, 4, vlist);
                    AddEdge(dataGraph, 2, 5, vlist);
                    AddEdge(dataGraph, 2, 6, vlist);
                    AddEdge(dataGraph, 2, 7, vlist);

                    AddEdge(dataGraph, 8, 9, vlist);
                    AddEdge(dataGraph, 9, 10, vlist);
                    AddEdge(dataGraph, 10, 7, vlist);
                    AddEdge(dataGraph, 10, 11, vlist);
                    AddEdge(dataGraph, 10, 12, vlist);

                    break;
                default:
                     for (var i = 1; i < 11; i++)
                    {
                        var dataVertex = new DataVertex("MyVertex " + i) { ID = i, VisualDiameter = _rnd.Next(50, 100), VisualInnerDiameter = _rnd.Next(20, 45) };
                        if (i == 2)
                            dataVertex.LabelText += "\nMultiline!";
                        dataGraph.AddVertex(dataVertex);
                    }
                     vlist = dataGraph.Vertices.ToList();
                    AddEdge(dataGraph, 0, 1, vlist);

                    AddEdge(dataGraph, 1, 2, vlist);
                    AddEdge(dataGraph, 1, 3, vlist);
                    AddEdge(dataGraph, 1, 4, vlist);

                    AddEdge(dataGraph, 4, 5, vlist);
                    AddEdge(dataGraph, 4, 6, vlist);

                    AddEdge(dataGraph, 2, 7, vlist);
                    AddEdge(dataGraph, 2, 8, vlist);

                    AddEdge(dataGraph, 8, 9, vlist);

                    //add some cross references
                    AddEdge(dataGraph, 4, 2, vlist);
                    AddEdge(dataGraph, 4, 8, vlist);
                    AddEdge(dataGraph, 9, 2, vlist);

                    break;
            }

           /* foreach (var item in graph.EdgesList)
            {
                //item.Value.LabelVerticalOffset = -40;
                item.Value.LabelAngle = 45;
            }*/

            return dataGraph;

            /*ManipulationDelta += MainPage_ManipulationDelta;
            ManipulationMode = ManipulationModes.Scale;

            for (int i = 1; i < 10; i++)
            {
                var dataVertex = new DataVertex("MyVertex " + i) { ID = i };
                dataGraph.AddVertex(dataVertex);
            }

            var vlist = dataGraph.Vertices.ToList();
            //var dataEdge = new DataEdge(vlist[0], vlist[1]) { Text = string.Format("{0} -> {1}", vlist[0], vlist[1]) };
            //dataGraph.AddEdge(dataEdge);
            var dataEdge = new DataEdge(vlist[2], vlist[3]) { Text = "23" };
            dataGraph.AddEdge(dataEdge);
            dataEdge = new DataEdge(vlist[3], vlist[2]) { Text = "32" };
            dataGraph.AddEdge(dataEdge);

            return dataGraph;*/
        }

        void MainPage_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
        {

        }

        private void InitialSetup()
        {
            var logicCore = new GXLogicCoreExample();
            graph.LogicCore = logicCore;

            var layParams = new LinLogLayoutParameters { IterationCount = 100 };
            logicCore.DefaultLayoutAlgorithm = LayoutAlgorithmTypeEnum.LinLog;
            logicCore.DefaultLayoutAlgorithmParams = layParams;

            logicCore.DefaultOverlapRemovalAlgorithmParams = logicCore.AlgorithmFactory.CreateOverlapRemovalParameters(OverlapRemovalAlgorithmTypeEnum.FSA);
            ((OverlapRemovalParameters)logicCore.DefaultOverlapRemovalAlgorithmParams).HorizontalGap = 50;
            ((OverlapRemovalParameters)logicCore.DefaultOverlapRemovalAlgorithmParams).VerticalGap = 50;

            graph.MoveAnimation = AnimationFactory.CreateMoveAnimation(MoveAnimation.Move, TimeSpan.FromMilliseconds(500));
            graph.MoveAnimation.Completed += MoveAnimation_Completed;
        }

        private void GraphAreaExample_Setup()
        {

            var logicCore = graph.GetLogicCore<GXLogicCoreExample>();
            logicCore.Graph = GraphExample_Setup();

            switch ((LayoutAlgorithmTypeEnum) cboxLayout.SelectedItem)
            {
                case LayoutAlgorithmTypeEnum.EfficientSugiyama:
                    logicCore.DefaultLayoutAlgorithmParams = new EfficientSugiyamaLayoutParameters { VertexDistance = 50 };
                    break;
            }

            switch ((LayoutAlgorithmTypeEnum)cboxLayout.SelectedItem)
            {
                case LayoutAlgorithmTypeEnum.EfficientSugiyama:
                case LayoutAlgorithmTypeEnum.Sugiyama:
                case LayoutAlgorithmTypeEnum.BoundedFR:
                case LayoutAlgorithmTypeEnum.FR:
                case LayoutAlgorithmTypeEnum.Tree:
                    cboxEdgeRouting.SelectedItem = EdgeRoutingAlgorithmTypeEnum.SimpleER;
                    break;
                default:
                    cboxEdgeRouting.SelectedItem = EdgeRoutingAlgorithmTypeEnum.SimpleER;
                    break;
            }

            logicCore.EnableParallelEdges = true;
            logicCore.ParallelEdgeDistance = 25;
            logicCore.EdgeCurvingEnabled = true;

            graph.SetVerticesDrag(true, true);
            graph.SetVerticesMathShape(VertexShape.Circle);
            graph.ShowAllVerticesLabels();
            graph.ShowAllEdgesLabels();
        }

        void MoveAnimation_Completed(object sender, EventArgs e)
        {
            zc.ZoomToFill();
        }
    }
}


text:
var relativePath =
    '/extensions/api_test/executescript/run_at/test.html';
var testUrl = 'http://b.com:PORT' + relativePath;

chrome.test.getConfig(function(config) {
  testUrl = testUrl.replace(/PORT/, config.testServer.port);
  chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    if (changeInfo.status != 'complete')
      return;
    chrome.tabs.onUpdated.removeListener(arguments.callee);
    chrome.test.runTests([
      function executeAtStartShouldSucceed() {
        var scriptDetails = {};
        scriptDetails.code = "document.title = 'Injected';";
        scriptDetails.runAt = "document_start";
        chrome.tabs.executeScript(tabId, scriptDetails, function() {
          chrome.tabs.get(tabId, chrome.test.callbackPass(function(tab) {
            chrome.test.assertEq('Injected', tab.title);
          }));
        });
      },
    ]);
  });
  chrome.tabs.create({ url: testUrl });
});

redpajama_set_name: RedPajamaGithub


text:
namespace SuperMap.Web.iServerJava2
{
    ///
    /// <para>${iServer2_DatasetType_Title}</para>
    /// <para>${iServer2_DatasetType_Description}</para>
    ///
    public enum DatasetType
    {
        /// ${iServer2_JoinType_attribute_undefined_D}
        Undefined=-1,
        /// ${iServer2_Entity_attribute_point_D}
        Point=1,
        /// ${iServer2_Entity_attribute_line_D}
        Line=3,
        /// ${iServer2_Entity_attribute_region_D}
        Region=5,
        /// ${iServer2_Entity_attribute_text_D}
        Text=7,
        /// ${iServer2_Entity_attribute_network_D}
        Network=4,
        /// ${iServer2_Entity_attribute_grid_D}
        Grid=83,
        /// ${iServer2_Entity_attribute_image_D}
        Image=81,
        /// ${iServer2_Entity_attribute_CAD_D}
        CAD=149,
        /// ${iServer2_Entity_attribute_lineM_D}
        LineM=35,
        /// ${iServer2_Entity_attribute_tabular_D}
        Tabular=0,
        /// ${iServer2_Entity_attribute_networkpoint_D}
        Networkpoint=-2,
        /// ${iServer2_Entity_attribute_linktable_D}
        Linktable=153,
        /// ${iServer2_Entity_attribute_wcs_D}
        WCS= 87,
        /// ${iServer2_Entity_attribute_wms_D}
        WMS=86
    }
}


text:
import Phaser from 'phaser'

export default class extends Phaser.Group {
  constructor ({game, name, x, y, font, size}) {
    super(game)
    this.game = game;

    this.font = font;
    this.size = size;
    this.x = x;
    this.y = y;

    this.playertime = [];
    this.playerorder = [];

    this.bmtext = [];

    this.game.add.existing(this);

  }

  recordTime(id, ms){
    if(this.playerorder.indexOf(id) === -1){
      this.playerorder.push(id);
      this.playertime.push(ms);
    }
  }

  formatText(rank, id, time){
    return(id + " - " + time);
  }

  viewTimes(){
    let ctext, s1;
    //Phaser.GameObjectCreator.bitmapText(x, y, font, text, size) : Phaser.BitmapText;
    for(let i = 0; i < this.playerorder.length; i++){
      s1 = this.formatText((i+1),this.playerorder[i],  this.formatMilliseconds(this.playertime[i]));
      ctext = this.game.add.bitmapText(this.x, this.y + (this.size *i) + (5 *(i>0)), this.font, s1, this.size);
      this.bmtext.push(ctext);
    }
  }

  formatMilliseconds(ms) {
    let minutes, seconds, milliseconds;
    if(ms < 0) return("0:00:00");

    minutes = Math.floor(ms / 60000) % 60;
    seconds = Math.floor(ms / 1000) % 60;
    milliseconds = Math.floor(ms) % 100;
    //If any of the digits becomes a single digit number, pad it with a zero    if (milliseconds < 10)        milliseconds = '0' + milliseconds;
    if (seconds < 10)        seconds = '0' + seconds;
    if (minutes < 10)        minutes = '0' + minutes;
    return(minutes + ':'+ seconds + ':' + milliseconds);
  }
}


text:
template <class T>
class Vector
{
public:
    Vector(std::size_t size = 0);
    Vector(const Vector& v);
    Vector(Vector&& v) noexcept;
    Vector(const std::initializer_list<T>& l);

    template <class It>
    Vector(It begin, It end);

    ~Vector();

    Vector& operator=(const Vector& v);
    Vector& operator=(Vector&& v) noexcept;
    Vector& operator=(const std::initializer_list<T>& l);

    template <class It>
    void assign(It begin, It end);

    bool empty() const;
    std::size_t size() const;

    T* data() noexcept;
    const T* data() const noexcept;

    T& operator[](std::size_t i);
    const T& operator[](std::size_t i) const;

private:
    std::size_t size_;
    std::size_t reserve_;
    T* data_;

    static std::size_t reserve_len_(std::size_t size);
    void resize_(std::size_t new_size, std::size_t new_reserve);
};

template <class T>
std::ostream& operator<<(std::ostream& os, const Vector<T>& v);

#include "vector.hxx"


text:
#include "config.h"
#include "BooleanObject.h"

#include "JSScope.h"
#include "Operations.h"

namespace JSC {

STATIC_ASSERT_IS_TRIVIALLY_DESTRUCTIBLE(BooleanObject);

const ClassInfo BooleanObject::s_info = { "Boolean", &JSWrapperObject::s_info, 0, 0, CREATE_METHOD_TABLE(BooleanObject) };

BooleanObject::BooleanObject(VM& vm, Structure* structure)
    : JSWrapperObject(vm, structure)
{
}

void BooleanObject::finishCreation(VM& vm)
{
    Base::finishCreation(vm);
    ASSERT(inherits(info()));
}

} // namespace JSC


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

var log = log4javascript.getLogger('gpxViewer.models');

function mergeStats(s1, s2) {
	log.debug("_compareStats");
	var s = {};

	s.eleMin = nullableMin(s1.eleMin, s2.eleMin);
	s.eleMax = nullableMax(s1.eleMax, s2.eleMax);

	if (!s1.eleRise) {
		s1.eleRise = 0;
	}
	s.eleRise = s1.eleRise + s2.eleRise;

	s.timeMin = nullableMin(s1.timeMin, s2.timeMin);
	s.timeMax = nullableMax(s1.timeMax, s2.timeMax);

	if (s1.distance && s2.distance) {
		s.distance = s1.distance + s2.distance;
	}
	else if (s1.distance) {
		s.distance = s1.distance;
	}
	else if (s2.distance) {
		s.distance = s2.distance;
	}

	return s;
}

function Point(lat, lon, ele) {
	this.lat = lat || 0;
	this.lon = lon || 0;
	this.ele = ele || 0;
	this.time;

	this.toString = function() {
		return "Point: lat=" + this.lat + ", lon=" + this.lon + ", ele=" + this.ele;
	};
}

function TrackSegment(name) {

	var log = log4javascript.getLogger('gpxViewer.models.TrackSegment');
	log.debug('TrackSegment created');

	this.name = name;
	this.points = new Array();

	this.calcStats = function() {
		log.debug('TrackSegment: calcStats()');
		var statsResult = {distance: 0, eleRise: 0};	// Initialise distance as number!
		var lastPoint;
		this.points.forEach(function(obj) {
			statsResult.eleMin = nullableMin(obj.ele, statsResult.eleMin);
			statsResult.eleMax = nullableMax(obj.ele, statsResult.eleMax);

			statsResult.latMin = nullableMin(obj.lat, statsResult.latMin);
			statsResult.latMax = nullableMax(obj.lat, statsResult.latMax);
			statsResult.lonMin = nullableMin(obj.lon, statsResult.lonMin);
			statsResult.lonMax = nullableMax(obj.lon, statsResult.lonMax);

			statsResult.timeMin = nullableMin(obj.time, statsResult.timeMin);
			statsResult.timeMax = nullableMax(obj.time, statsResult.timeMax);

			if (lastPoint) {
				statsResult.distance += calcDistance(lastPoint, obj);
				var dif = obj.ele - lastPoint.ele;
				if (dif > 0) {
					statsResult.eleRise += dif;
				}
			}
			lastPoint = obj;
		});
		return statsResult;
	};

	this.toString = function() {
		var text = "TrackSegment - Anzahl Punkte: " + this.points.length;
//		this.points.forEach(function(n) {
//			text += n.toString() + "\n";
//		});
		return text;
	};
}

function Track(name) {
	this.name = name || '';
	this.segments = new Array();

	this.calcStats = function() {
		log.debug('track: calcStats()');
		var statsResult = {};
		this.segments.forEach(function(obj) {
			statsResult = mergeStats(statsResult, obj.calcStats());
		});
		return statsResult;
	};

	this.toString = function() {
		var text = "Gpx.Track\n";
		text += "Anzahl Segmente: " + this.segments.length + "\n";
		this.segments.forEeach(function(n) {
			text += n.toString();
		});
		return text;
	};
}

function Tour(id, name) {
	this.id = id;
	this.name = name || '';
	this.path = '';
	this.tracks = new Array();
	this.stats = {};
	this.color;

	this.calcStats = function() {
		log.debug('container: calcStats()');
		var statsResult = {};
		this.tracks.forEach(function(obj) {
			statsResult = mergeStats(statsResult, obj.calcStats());
		});
		this.stats = statsResult;

		if (statsResult.timeMin && statsResult.timeMax) {
			this.stats.duration = new Date(statsResult.timeMax - statsResult.timeMin);
		}
		if (statsResult.timeMin) {
			this.stats.date = new Date(statsResult.timeMin);
		}
	};

}


text:
import _ from '../wrap/lodash'
import stringifyAnything from './anything'

export default (args, joiner = ', ', wrapper = '') =>
  _.map(args, arg =>
    `${wrapper}${stringifyAnything(arg)}${wrapper}`
  ).join(joiner)


text:
import json
import os

import solnlib.utils as utils

from splunktaucclib.global_config import GlobalConfig, GlobalConfigSchema

'''
Usage Examples:
setup_util = Setup_Util(uri, session_key)
setup_util.get_log_level()
setup_util.get_proxy_settings()
setup_util.get_credential_account("my_account_name")
setup_util.get_customized_setting("my_customized_field_name")
'''

'''
setting object structure.
It is stored in self.__cached_global_settings
Note, this structure is only maintained in this util.
setup_util transforms global settings in os environment or from ucc into this structure.
{
    "proxy_settings": {
    "proxy_enabled": False/True,
    "proxy_url": "example.com",
    "proxy_port": "1234",
    "proxy_username": "",
    "proxy_password": "",
    "proxy_type": "http",
    "proxy_rdns": False/True
    },
    "log_settings": {
        "loglevel": "DEBUG"
    },
    "credential_settings": [{
        "name": "account_id",
        "username": "example_account",
        "password": "example_password"
    }, { # supported by ucc, not seen any usage in AoB
        "api_key": "admin",
        "api_uuid": "admin",
        "endpoint": "some url",
        "name": "account1"
    }],
    "customized_settings": {
        "text_name": "content",
        "pass_name": "password",
        "checkbox": 0/1
    }
}
'''

GLOBAL_SETTING_KEY = "global_settings"
AOB_TEST_FLAG = 'AOB_TEST'

PROXY_SETTINGS = "proxy_settings"
LOG_SETTINGS = "log_settings"
CREDENTIAL_SETTINGS = "credential_settings"
CUSTOMIZED_SETTINGS = "customized_settings"

UCC_PROXY = "proxy"
UCC_LOGGING = "logging"
UCC_CUSTOMIZED = "additional_parameters"
UCC_CREDENTIAL = "account"

CONFIGS = [CREDENTIAL_SETTINGS]
SETTINGS = [PROXY_SETTINGS, LOG_SETTINGS, CUSTOMIZED_SETTINGS]

PROXY_ENABLE_KEY = 'proxy_enabled'
PROXY_RDNS_KEY = 'proxy_rdns'
LOG_LEVEL_KEY = 'loglevel'
LOG_LEVEL_KEY_ENV = 'log_level'

TYPE_CHECKBOX = "checkbox"
ALL_SETTING_TYPES = ['text', 'password', 'checkbox', 'dropdownlist', 'multi_dropdownlist', 'radiogroup']

def get_schema_path():
    dirname = os.path.dirname
    basedir = dirname(dirname(dirname((dirname(__file__)))))
    return os.path.join(basedir, 'appserver', 'static', 'js', 'build', 'globalConfig.json')

class Setup_Util(object):
    def __init__(self, uri, session_key, logger=None):
        self.__uri = uri
        self.__session_key = session_key
        self.__logger = logger
        self.scheme, self.host, self.port = utils.extract_http_scheme_host_port(
            self.__uri)
        self.__cached_global_settings = {}
        self.__global_config = None

    def init_global_config(self):
        if self.__global_config is not None:
            return
        schema_file = get_schema_path()
        if not os.path.isfile(schema_file):
            self.log_error("Global config JSON file not found!")
            self.__global_config = None
        else:
            with open(get_schema_path()) as f:
                json_schema = ''.join([l for l in f])
            self.__global_config = GlobalConfig(self.__uri, self.__session_key,
                                                GlobalConfigSchema(json.loads(json_schema)))

    def log_error(self, msg):
        if self.__logger:
            self.__logger.error(msg)

    def log_info(self, msg):
        if self.__logger:
            self.__logger.info(msg)

    def log_debug(self, msg):
        if self.__logger:
            self.__logger.debug(msg)

    def _parse_conf(self, key):
        if os.environ.get(AOB_TEST_FLAG, 'false') == 'true':
            global_settings = self._parse_conf_from_env(json.loads(os.environ.get(GLOBAL_SETTING_KEY, '{}')))
            return global_settings.get(key)
        else:
            return self._parse_conf_from_global_config(key)

    def _parse_conf_from_env(self, global_settings):
        '''
        this is run in test env
        '''
        if not self.__cached_global_settings:
            # format the settings, the setting from env is from global_setting
            # meta
            self.__cached_global_settings = {}
            for s_k, s_v in global_settings.iteritems():
                if s_k == PROXY_SETTINGS:
                    proxy_enabled = s_v.get(PROXY_ENABLE_KEY)
                    proxy_rdns = s_v.get(PROXY_RDNS_KEY)
                    if type(proxy_enabled) != bool:
                        s_v[PROXY_ENABLE_KEY] = utils.is_true(proxy_enabled)
                    if type(proxy_rdns) != bool:
                        s_v[PROXY_RDNS_KEY] = utils.is_true(proxy_rdns)
                    self.__cached_global_settings[PROXY_SETTINGS] = s_v
                elif s_k == LOG_SETTINGS:
                    self.__cached_global_settings[LOG_SETTINGS] = {
                        LOG_LEVEL_KEY: s_v.get(LOG_LEVEL_KEY_ENV)
                    }
                elif s_k == CREDENTIAL_SETTINGS:
                    # add account id to accounts
                    for i in range(0, len(s_v)):
                        s_v[i]['name'] = 'account' + str(i)
                    self.__cached_global_settings[CREDENTIAL_SETTINGS] = s_v
                else:  # should be customized settings
                    self.__cached_global_settings[CUSTOMIZED_SETTINGS] = {}
                    for s in s_v:
                        field_type = s.get('type')
                        if not field_type:
                            self.log_error(
                                'unknown type for customized var:{}'.format(s))
                            continue
                        self.__cached_global_settings['customized_settings'][s.get('name', '')] = self._transform(
                            s.get("value", ""), field_type)

        return self.__cached_global_settings

    def _parse_conf_from_global_config(self, key):
        if self.__cached_global_settings and key in self.__cached_global_settings:
            return self.__cached_global_settings.get(key)
        self.init_global_config()
        if self.__global_config is None:
            return None
        if key in CONFIGS:
            accounts = self.__global_config.configs.load().get(UCC_CREDENTIAL, [])
            if accounts:
                for account in accounts:
                    if 'disabled' in account:
                        del account['disabled']
            self.__cached_global_settings[CREDENTIAL_SETTINGS] = accounts
        elif key in SETTINGS:
            settings = self.__global_config.settings.load()
            self.__cached_global_settings.update({UCC_PROXY: None, UCC_LOGGING: None, UCC_CUSTOMIZED: None})
            customized_setting = {}
            for setting in settings.get('settings', []):
                # filter out disabled setting page and 'disabled' field
                if setting.get('disabled', False):
                    continue
                if setting['name'] == UCC_LOGGING:
                    self.__cached_global_settings[LOG_SETTINGS] = {
                        LOG_LEVEL_KEY: setting.get(LOG_LEVEL_KEY)
                    }
                elif setting['name'] == UCC_PROXY:
                    if 'disabled' in setting:
                        del setting['disabled']
                    setting[PROXY_ENABLE_KEY] = utils.is_true(setting.get(PROXY_ENABLE_KEY, '0'))
                    setting[PROXY_RDNS_KEY] = utils.is_true(setting.get(PROXY_RDNS_KEY, '0'))
                    self.__cached_global_settings[PROXY_SETTINGS] = setting
                else:  # should be customized settings
                    if 'disabled' in setting:
                        del setting['disabled']
                    customized_setting.update(setting)
            self.__cached_global_settings[CUSTOMIZED_SETTINGS] = customized_setting

        return self.__cached_global_settings.get(key)

    def get_log_level(self):
        log_level = "INFO"
        log_settings = self._parse_conf(LOG_SETTINGS)
        if log_settings is None:
            self.log_info("Log level is not set, use default INFO")
        else:
            log_level = log_settings.get(LOG_LEVEL_KEY, None)
            if not log_level:
                self.log_info("Log level is not set, use default INFO")
                log_level = "INFO"
        return log_level

    def get_proxy_settings(self):
        proxy_settings = self._parse_conf(PROXY_SETTINGS)
        if proxy_settings is None:
            self.log_info("Proxy is not set!")
            return {}
        proxy_enabled = proxy_settings.get(PROXY_ENABLE_KEY)
        if not proxy_enabled:
            self.log_info("Proxy is not enabled!")
            return {}
        proxy_settings = {
            "proxy_url": proxy_settings.get("proxy_url", ""),
            "proxy_port": proxy_settings.get("proxy_port", None),
            "proxy_username": proxy_settings.get("proxy_username", ""),
            "proxy_password": proxy_settings.get("proxy_password", ""),
            "proxy_type": proxy_settings.get("proxy_type", ""),
            "proxy_rdns": proxy_settings.get("proxy_rdns")
        }
        self._validate_proxy_settings(proxy_settings)
        return proxy_settings

    def get_credential_by_id(self, account_id):
        credential_settings = self._parse_conf(CREDENTIAL_SETTINGS)
        for account in credential_settings:
            if account.get('name', None) == account_id:
                return account
        self.log_error("Credential account with account id {} can not be found".format(account_id))
        return None

    def get_credential_by_username(self, username):
        credential_settings = self._parse_conf(CREDENTIAL_SETTINGS)
        for account in credential_settings:
            if account.get('username', None) == username:
                return account
        self.log_error("Credential account with username {} can not be found".format(username))
        return None

    def get_customized_setting(self, key):
        customized_settings = self._parse_conf(CUSTOMIZED_SETTINGS)
        if customized_settings is None:
            self.log_info("Customized setting is not set")
            return None
        if key not in customized_settings:
            self.log_info("Customized key can not be found")
            return None
        customized_setting = customized_settings.get(key, None)
        if customized_setting is None:
            self.log_error("Cannot find customized setting with key %s" % key)
        return customized_setting

    def _validate_proxy_settings(self, proxy_settings):
        if proxy_settings:
            if proxy_settings.get('proxy_url') == "":
                raise Exception("Proxy host must not be empty!")
            proxy_port = proxy_settings.get('proxy_port')
            if proxy_port is None or not proxy_port.isdigit():
                raise Exception("Proxy port must be a number!")

    def _transform(self, value, field_type):
        '''
        This is method is only used when parsing customized global params from env.
        Only checkbox type needs transform. Other types will be extracted automatically when apply json.loads.
        :param value:
        :param field_type: can be checkbox, text, password, dropdownlist, multi_dropdownlist, radiogroup
        :return:
        '''
        if field_type == TYPE_CHECKBOX:
            return utils.is_true(value)
        elif field_type in ALL_SETTING_TYPES:
            return value
        else:
            raise Exception("Type of this customized setting is corrupted. Value: {}, type: {}"
                            .format(value, field_type))

    '''
    # the following methods is used by AoB internally
    # user should not use this
    # These methods returns the similiar structure like ucc libs

    the output of config is like
{
  "account": [
    {
      "username": "admin",
      "credential": "a",
      "name": "ddddd",
      "disabled": false
    }
  ]
}

    the output of settings is like
{
  "settings": [
    {
      "additional_parameters": {
        "checkbox": "1",
        "text": "msn",
        "disabled": false
      }
    },
    {
      "proxy": {
        "proxy_type": "http",
        "proxy_port": "9999",
        "proxy_url": "localhost",
        "proxy_rdns": "1",
        "disabled": false,
        "proxy_password": "a",
        "proxy_username": "admin",
        "proxy_enabled": "1"
      }
    },
    {
      "logging": {
        "loglevel": "ERROR",
        "disabled": false
      }
    }
  ]
}
    '''
    def get_ucc_log_setting(self):
        return {UCC_LOGGING: self._parse_conf(LOG_SETTINGS)}

    def get_ucc_proxy_setting(self):
        p = dict(self.get_proxy_settings())
        p[PROXY_ENABLE_KEY] = True if p else False
        return {
            UCC_PROXY: p
        }

    def get_ucc_customized_setting(self):
        customized_settings = self._parse_conf(CUSTOMIZED_SETTINGS)
        if customized_settings:
            return {
                UCC_CUSTOMIZED: customized_settings
            }
        else:
            return {}

    # account belongs to the configs
    def get_ucc_account_config(self):
        return {
            UCC_CREDENTIAL: self._parse_conf(CREDENTIAL_SETTINGS)
        }


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>Verbi/Substantiivi/Adjektiivi-taivutin</title>

Tervetuloa taivuttamaan!

        Taivuttimelle


text:
package org.apache.commons.cli;

import junit.framework.TestCase;

/**
 * @author John Keyes (john at integralsource.com)
 * @version $Revision: 678662 $
 */
public class ParseRequiredTest extends TestCase
{
    private Options _options = null;
    private CommandLineParser parser = new PosixParser();

    public void setUp()
    {
        _options = new Options()
            .addOption("a",
                       "enable-a",
                       false,
                       "turn [a] on or off")
            .addOption( OptionBuilder.withLongOpt( "bfile" )
                                     .hasArg()
                                     .isRequired()
                                     .withDescription( "set the value of [b]" )
                                     .create( 'b' ) );
    }

    public void testWithRequiredOption() throws Exception
    {
        String[] args = new String[] {  "-b", "file" };

        CommandLine cl = parser.parse(_options,args);

        assertTrue( "Confirm -a is NOT set", !cl.hasOption("a") );
        assertTrue( "Confirm -b is set", cl.hasOption("b") );
        assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("file") );
        assertTrue( "Confirm NO of extra args", cl.getArgList().size() == 0);
    }

    public void testOptionAndRequiredOption() throws Exception
    {
        String[] args = new String[] {  "-a", "-b", "file" };

        CommandLine cl = parser.parse(_options,args);

        assertTrue( "Confirm -a is set", cl.hasOption("a") );
        assertTrue( "Confirm -b is set", cl.hasOption("b") );
        assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("file") );
        assertTrue( "Confirm NO of extra args", cl.getArgList().size() == 0);
    }

    public void testMissingRequiredOption()
    {
        String[] args = new String[] { "-a" };

        try
        {
            CommandLine cl = parser.parse(_options,args);
            fail( "exception should have been thrown" );
        }
        catch (MissingOptionException e)
        {
            assertEquals( "Incorrect exception message", "Missing required option: b", e.getMessage() );
            assertTrue(e.getMissingOptions().contains("b"));
        }
        catch (ParseException e)
        {
            fail( "expected to catch MissingOptionException" );
        }
    }

    public void testMissingRequiredOptions()
    {
        String[] args = new String[] { "-a" };

        _options.addOption( OptionBuilder.withLongOpt( "cfile" )
                                     .hasArg()
                                     .isRequired()
                                     .withDescription( "set the value of [c]" )
                                     .create( 'c' ) );

        try
        {
            CommandLine cl = parser.parse(_options,args);
            fail( "exception should have been thrown" );
        }
        catch (MissingOptionException e)
        {
            assertEquals( "Incorrect exception message", "Missing required options: b, c", e.getMessage() );
            assertTrue(e.getMissingOptions().contains("b"));
            assertTrue(e.getMissingOptions().contains("c"));
        }
        catch (ParseException e)
        {
            fail( "expected to catch MissingOptionException" );
        }
    }

    public void testReuseOptionsTwice() throws Exception
    {
        Options opts = new Options();
		opts.addOption(OptionBuilder.isRequired().create('v'));

		GnuParser parser = new GnuParser();

        // first parsing
        parser.parse(opts, new String[] { "-v" });

        try
        {
            // second parsing, with the same Options instance and an invalid command line
            parser.parse(opts, new String[0]);
            fail("MissingOptionException not thrown");
        }
        catch (MissingOptionException e)
        {
            // expected
        }
    }

}


text:
package com.agapsys.web.toolkit.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HttpUtils {

    protected HttpUtils() {}

    public static class MissingParameterException extends Exception {

        private MissingParameterException(String message, Object...msgArgs) {
            super(msgArgs.length > 0 ? String.format(message, msgArgs) : message);
        }
    }

    /**
     * @return request origin IP.
     *
     * @param req HTTP request.
     */
    public static String getOriginIp(HttpServletRequest req) {
        return req.getRemoteAddr();
    }

    /**
     * @return origin user-agent.
     *
     * @param req HTTP request.
     */
    public static String getOriginUserAgent(HttpServletRequest req) {
        return req.getHeader("user-agent");
    }

    /**
     * @return request URI.
     *
     * @param req HTTP request.
     */
    public static String getRequestUri(HttpServletRequest req) {
        StringBuffer requestUrl = req.getRequestURL();
        if (req.getQueryString() != null) {
            requestUrl.append("?").append(req.getQueryString());
        }

        return String.format("%s %s %s", req.getMethod(), requestUrl.toString(), req.getProtocol());
    }

    /**
     * @return cookie value. If there is no such cookie, returns null.
     *
     * @param request HTTP request.
     * @param name cookie name.
     */
    public static String getCookieValue(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (name.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    /**
     * Adds a cookie.
     *
     * @param resp HTTP response.
     * @param name cookie name.
     * @param value cookie value.
     * @param maxAge an integer specifying the maximum age of the cookie in seconds; if negative, means the cookie is not stored; if zero, deletes the cookie.
     * @param path cookie path (usually {@linkplain HttpServletRequest#getContextPath()}).
     */
    public static void addCookie(HttpServletResponse resp, String name, String value, int maxAge, String path) {
        if (path == null || !path.startsWith("/"))
            throw new IllegalArgumentException("Invalid path: " + path);

        Cookie cookie = new Cookie(name, value);
        cookie.setPath(path);
        cookie.setMaxAge(maxAge);
        resp.addCookie(cookie);
    }

    /**
     * Adds a cookie for request context path.
     *
     * @param req  HTTP request.
     * @param resp HTTP response.
     * @param name cookie name.
     * @param value cookie value.
     * @param maxAge an integer specifying the maximum age of the cookie in seconds; if negative, means the cookie is not stored; if zero, deletes the cookie.
     */
    public static void addCookie(HttpServletRequest req, HttpServletResponse resp, String name, String value, int maxAge) {
        addCookie(resp, name, value, maxAge, req.getContextPath());
    }

    /**
     * Removes a cookie.
     *
     * @param resp HTTP response.
     * @param name name of the cookie to be removed.
     * @param path cookie path ((usually {@linkplain HttpServletRequest#getContextPath()}).
     */
    public static void removeCookie(HttpServletResponse resp, String name, String path) {
        addCookie(resp, name, null, 0, path);
    }

    /**
     * Removes a cookie for request context path.
     *
     * @param req  HTTP request.
     * @param resp HTTP response.
     * @param name name of the cookie to be removed.
     */
    public static void removeCookie(HttpServletRequest req, HttpServletResponse resp, String name) {
        removeCookie(resp, name, req.getContextPath());
    }

    /**
     * @return an optional parameter contained in the request.
     *
     * @param req          HTTP request.
     * @param paramName    parameter name.
     * @param defaultValue default value if given parameter is not contained in the request.
     */
    public static String getOptionalParameter(HttpServletRequest req, String paramName, String defaultValue) {

        String val = req.getParameter(paramName);
        if (val == null || val.trim().isEmpty())
            val = defaultValue;

        if (val != null)
            val = val.trim();

        return val;
    }

    /**
     * Returns a mandatory parameter contained in the request.
     *
     * @param req  HTTP request.
     * @param paramName parameter name.
     * @return parameter value.
     * @throws MissingParameterException if parameter is not contained in given request.
     */
    public static String getMandatoryParameter(HttpServletRequest req, String paramName) throws MissingParameterException {
        return getMandatoryParameter(req, paramName, "Missing parameter: %s", paramName);
    }

    /**
     * Returns a mandatory parameter contained in the request.
     *
     * @param req  HTTP request.
     * @param paramName parameter name.
     * @param errorMessage error message used by thrown exception.
     * @param errMsgArgs optional error message args if error message is a formatted string.
     * @return parameter value.
     * @throws MissingParameterException if parameter is not contained in given request.
     */
    public static String getMandatoryParameter(HttpServletRequest req, String paramName, String errorMessage, Object...errMsgArgs) throws MissingParameterException {
        String val = getOptionalParameter(req, paramName, "");
        if (val.trim().isEmpty())
            throw new MissingParameterException(errorMessage, errMsgArgs);

        return val;
    }

}


text:
'use strict';
angular
.module( 'app.controller.navigation', [
                                      'ngMaterial',
                                      'ngMessages',
                                      'ngRoute'
                                    ] )

// constants
.constant('MODULE_VERSION', '0.0.1')

.config(['$routeProvider', function($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: '../templates/timeline.html',
        controller: 'TimelineController'
      })
      .when('/timeline', {
        templateUrl: '../templates/timeline.html',
        controller: 'TimelineController'
      })
      .when('/editor', {
        templateUrl: '../templates/editor.html',
        controller: 'EditorController'
      })
      // .when('/dashboard', {
      //   templateUrl: '../templates/dashboard.html',
      //   controller: 'DashboardController'
      // })
      .when('/control', {
        templateUrl: '../templates/control.html',
        controller: 'ControlController'
      })
      .when('/api', {
        templateUrl: '../templates/api.html',
        controller: 'ApiBrowserController'
      })
      .when('/devices', {
        templateUrl: '../templates/devices.html',
        controller: 'DevicesController'
      })
      // .when('/settings', {
      //   templateUrl: '../templates/settings.html',
      //   controller: 'SettingsController'
      // })
      // .when('/help', {
      //   templateUrl: '../templates/help.html',
      //   controller: 'HelpController'
      // })
      // .when('/share', {
      //   templateUrl: '../templates/share.html',
      //   controller: 'ShareController'
      // })
      .otherwise({ redirectTo: '/' });
  }])

// // // // // // // // // // // // // // // // // // // // // // // // //
.controller('MenuController', function ($scope, $timeout, $mdSidenav, $log, $location, $rootScope) {

   $rootScope.mainPages = [
     {
       icon : 'schedule',
       text: 'Timeline',
       path: '#/timeline'
     },
    //  {
    //    icon : 'dashboard',
    //    text: 'Dashboard',
    //    path: '#/dashboard'
    //  },
     {
       icon : 'code',
       text: 'Sequence Editor',
       path: '#/editor'
     },
     {
       icon : 'pan_tool',
       text: 'Control',
       path: '#/control'
     },
     {
       icon : 'chrome_reader_mode',
       text: 'API',
       path: '#/api'
     },
   ];

   $rootScope.subPages = [
     {
       icon : 'devices_other',
       text: 'My devices',
       path: '#/devices'
     },
    //  {
    //    icon : 'help',
    //    text: 'Help',
    //    path: '#/help'
    //  },
    //  {
    //    icon : 'share',
    //    text: 'Share',
    //    path: '#/share'
    //  },
    //  {
    //    icon : 'settings',
    //    text: 'Settings',
    //    path: '#/settings'
    //  },
   ];

    $rootScope.currentPage = $scope.mainPages[0];

    $scope.navigateTo =   function navigateTo(page) {

       $scope.currentPage = page;
       $log.debug("Page: " + page.path + " selected");

      //  $location.url('templates/timeline.html'); // path not hash

      // close sidenav after interaction
      $mdSidenav('left').close()
        .then(function () {
          $log.debug("close LEFT is done");
        });
    };

  $scope.toggleLeft = buildDelayedToggler('left');

  $scope.isOpenRight = function(){
    return $mdSidenav('right').isOpen();
  };

  function debounce(func, wait, context) {
    var timer;

    return function debounced() {
      var context = $scope,
          args = Array.prototype.slice.call(arguments);
      $timeout.cancel(timer);
      timer = $timeout(function() {
        timer = undefined;
        func.apply(context, args);
      }, wait || 10);
    };
  }

  function buildDelayedToggler(navID) {
    return debounce(function() {
      $mdSidenav(navID)
        .toggle()
        .then(function () {
          $log.debug("toggle " + navID + " is done");
        });
    }, 200);
  }

  function buildToggler(navID) {
    return function() {
      $mdSidenav(navID)
        .toggle()
        .then(function () {
          $log.debug("toggle " + navID + " is done");
        });
    }
  }
})

// SideNav Controller
.controller('LeftCtrl', function ($scope, $timeout, $mdSidenav, $log) {
  $scope.close = function () {
    $mdSidenav('left').close()
      .then(function () {
        $log.debug("close LEFT is done");
      });

  };
});


text:
<?php

class smintbackConfiguration extends sfApplicationConfiguration
{
  public function configure()
  {
  }
}


text:
package org.dhis2.mobile.utils.date;

public class DateConstants {
    public static final String PERIOD_YEARLY = "Yearly";
    public static final String PERIOD_FINANCIAL_APRIL = "FinancialApril";
    public static final String PERIOD_FINANCIAL_JULY = "FinancialJuly";
    public static final String PERIOD_FINANCIAL_OCT = "FinancialOct";
    public static final String PERIOD_SIX_MONTHLY = "SixMonthly";
    public static final String PERIOD_SIX_MONTHLY_APRIL = "SixMonthlyApril";
    public static final String PERIOD_QUARTERLY = "Quarterly";
    public static final String PERIOD_BIMONTHLY = "BiMonthly";
    public static final String PERIOD_MONTHLY = "Monthly";
    public static final String PERIOD_WEEKLY = "Weekly";
    public static final String PERIOD_BIWEEKLY = "BiWeekly";
    public static final String PERIOD_DAILY = "Daily";
    public static final String PERIOD_WEEKLY_WEDNESDAY = "WeeklyWednesday";
    public static final String PERIOD_WEEKLY_THURSDAY = "WeeklyThursday";
    public static final String PERIOD_WEEKLY_SATURDAY = "WeeklySaturday";
    public static final String PERIOD_WEEKLY_SUNDAY = "WeeklySunday";
}


text:
using Chloe.Core;
using Chloe.Core.Visitors;
using Chloe.DbExpressions;
using Chloe.Descriptors;
using Chloe.Exceptions;
using Chloe.Infrastructure;
using Chloe.RDBMS;
using Chloe.Utility;
using System.Data;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;

namespace Chloe.Oracle
{
    public partial class OracleContextProvider : DbContextProvider
    {
        DatabaseProvider _databaseProvider;
        public OracleContextProvider(IDbConnectionFactory dbConnectionFactory)
        {
            PublicHelper.CheckNull(dbConnectionFactory);
            this._databaseProvider = new DatabaseProvider(dbConnectionFactory, this);
        }
        public OracleContextProvider(Func<IDbConnection> dbConnectionFactory) : this(new DbConnectionFactory(dbConnectionFactory))
        {
        }

        /// <summary>
        /// 设置方法解析器。
        /// </summary>
        /// <param name="methodName"></param>
        /// <param name="handler"></param>
        public static void SetMethodHandler(string methodName, IMethodHandler handler)
        {
            PublicHelper.CheckNull(methodName, nameof(methodName));
            PublicHelper.CheckNull(handler, nameof(handler));
            lock (SqlGenerator.MethodHandlers)
            {
                SqlGenerator.MethodHandlers[methodName] = handler;
            }
        }

        /// <summary>
        /// 是否将 sql 中的表名/字段名转成大写。默认为 true。
        /// </summary>
        public bool ConvertToUppercase { get; set; } = true;
        public override IDatabaseProvider DatabaseProvider
        {
            get { return this._databaseProvider; }
        }

        protected override async Task<TEntity> Insert<TEntity>(TEntity entity, string table, bool @async)
        {
            PublicHelper.CheckNull(entity);

            TypeDescriptor typeDescriptor = EntityTypeContainer.GetDescriptor(typeof(TEntity));

            DbTable dbTable = PublicHelper.CreateDbTable(typeDescriptor, table);

            List<PrimitivePropertyDescriptor> outputColumns = new List<PrimitivePropertyDescriptor>();
            Dictionary<PrimitivePropertyDescriptor, DbExpression> insertColumns = new Dictionary<PrimitivePropertyDescriptor, DbExpression>();
            foreach (PrimitivePropertyDescriptor propertyDescriptor in typeDescriptor.PrimitivePropertyDescriptors)
            {
                if (propertyDescriptor.IsAutoIncrement)
                {
                    outputColumns.Add(propertyDescriptor);
                    continue;
                }

                if (propertyDescriptor.HasSequence())
                {
                    DbMethodCallExpression getNextValueForSequenceExp = PublicHelper.MakeNextValueForSequenceDbExpression(propertyDescriptor, dbTable.Schema);
                    insertColumns.Add(propertyDescriptor, getNextValueForSequenceExp);
                    outputColumns.Add(propertyDescriptor);
                    continue;
                }

                object val = propertyDescriptor.GetValue(entity);

                PublicHelper.NotNullCheck(propertyDescriptor, val);

                DbExpression valExp = DbExpression.Parameter(val, propertyDescriptor.PropertyType, propertyDescriptor.Column.DbType);
                insertColumns.Add(propertyDescriptor, valExp);
            }

            DbInsertExpression e = new DbInsertExpression(dbTable);

            foreach (var kv in insertColumns)
            {
                e.InsertColumns.Add(kv.Key.Column, kv.Value);
            }

            e.Returns.AddRange(outputColumns.Select(a => a.Column));

            DbCommandInfo dbCommandInfo = this.Translate(e);
            await this.ExecuteNonQuery(dbCommandInfo, @async);

            List<DbParam> outputParams = dbCommandInfo.Parameters.Where(a => a.Direction == ParamDirection.Output).ToList();

            for (int i = 0; i < outputColumns.Count; i++)
            {
                PrimitivePropertyDescriptor propertyDescriptor = outputColumns[i];
                string putputColumnName = Utils.GenOutputColumnParameterName(propertyDescriptor.Column.Name);
                DbParam outputParam = outputParams.Where(a => a.Name == putputColumnName).First();
                var outputValue = PublicHelper.ConvertObjectType(outputParam.Value, propertyDescriptor.PropertyType);
                outputColumns[i].SetValue(entity, outputValue);
            }

            return entity;
        }
        protected override async Task<object> Insert<TEntity>(Expression<Func<TEntity>> content, string table, bool @async)
        {
            PublicHelper.CheckNull(content);

            TypeDescriptor typeDescriptor = EntityTypeContainer.GetDescriptor(typeof(TEntity));

            if (typeDescriptor.PrimaryKeys.Count > 1)
            {
                /* 对于多主键的实体,暂时不支持调用这个方法进行插入 */
                throw new NotSupportedException(string.Format("Can not call this method because entity '{0}' has multiple keys.", typeDescriptor.Definition.Type.FullName));
            }

            PrimitivePropertyDescriptor keyPropertyDescriptor = typeDescriptor.PrimaryKeys.FirstOrDefault();

            Dictionary<MemberInfo, Expression> insertColumns = InitMemberExtractor.Extract(content);

            DbTable dbTable = PublicHelper.CreateDbTable(typeDescriptor, table);

            DefaultExpressionParser expressionParser = typeDescriptor.GetExpressionParser(dbTable);
            DbInsertExpression insertExp = new DbInsertExpression(dbTable);

            object keyVal = null;

            foreach (var kv in insertColumns)
            {
                MemberInfo key = kv.Key;
                PrimitivePropertyDescriptor propertyDescriptor = typeDescriptor.GetPrimitivePropertyDescriptor(key);

                if (propertyDescriptor.IsAutoIncrement)
                    throw new ChloeException(string.Format("Could not insert value into the auto increment column '{0}'.", propertyDescriptor.Column.Name));

                if (propertyDescriptor.HasSequence())
                    throw new ChloeException(string.Format("Can not insert value into the column '{0}', because it's mapping member has define a sequence.", propertyDescriptor.Column.Name));

                if (propertyDescriptor.IsPrimaryKey)
                {
                    object val = ExpressionEvaluator.Evaluate(kv.Value);
                    if (val == null)
                        throw new ChloeException(string.Format("The primary key '{0}' could not be null.", propertyDescriptor.Property.Name));
                    else
                    {
                        keyVal = val;
                        insertExp.InsertColumns.Add(propertyDescriptor.Column, DbExpression.Parameter(keyVal, propertyDescriptor.PropertyType, propertyDescriptor.Column.DbType));
                        continue;
                    }
                }

                insertExp.InsertColumns.Add(propertyDescriptor.Column, expressionParser.Parse(kv.Value));
            }

            foreach (PrimitivePropertyDescriptor propertyDescriptor in typeDescriptor.PrimitivePropertyDescriptors)
            {
                if (propertyDescriptor.IsAutoIncrement && propertyDescriptor.IsPrimaryKey)
                {
                    insertExp.Returns.Add(propertyDescriptor.Column);
                    continue;
                }

                if (propertyDescriptor.HasSequence())
                {
                    DbMethodCallExpression getNextValueForSequenceExp = PublicHelper.MakeNextValueForSequenceDbExpression(propertyDescriptor, dbTable.Schema);
                    insertExp.InsertColumns.Add(propertyDescriptor.Column, getNextValueForSequenceExp);

                    if (propertyDescriptor.IsPrimaryKey)
                    {
                        insertExp.Returns.Add(propertyDescriptor.Column);
                    }

                    continue;
                }
            }

            if (keyPropertyDescriptor != null)
            {
                //主键为空并且主键又不是自增列
                if (keyVal == null && !keyPropertyDescriptor.IsAutoIncrement && !keyPropertyDescriptor.HasSequence())
                {
                    throw new ChloeException(string.Format("The primary key '{0}' could not be null.", keyPropertyDescriptor.Property.Name));
                }
            }

            DbCommandInfo dbCommandInfo = this.Translate(insertExp);
            await this.ExecuteNonQuery(dbCommandInfo, @async);

            if (keyPropertyDescriptor != null && (keyPropertyDescriptor.IsAutoIncrement || keyPropertyDescriptor.HasSequence()))
            {
                string outputColumnName = Utils.GenOutputColumnParameterName(keyPropertyDescriptor.Column.Name);
                DbParam outputParam = dbCommandInfo.Parameters.Where(a => a.Direction == ParamDirection.Output && a.Name == outputColumnName).First();
                keyVal = PublicHelper.ConvertObjectType(outputParam.Value, keyPropertyDescriptor.PropertyType);
            }

            return keyVal; /* It will return null if an entity does not define primary key. */
        }
        protected override async Task InsertRange<TEntity>(List<TEntity> entities, string table, bool @async)
        {
            /*
             * 将 entities 分批插入数据库
             * 每批生成 insert into TableName(...) select ... from dual union all select ... from dual...
             * 对于 oracle,貌似速度提升不了...- -
             * #期待各码友的优化建议#
             */

            PublicHelper.CheckNull(entities);
            if (entities.Count == 0)
                return;

            int maxParameters = 1000;
            int batchSize = 40; /* 每批实体大小,此值通过测试得出相对插入速度比较快的一个值 */

            TypeDescriptor typeDescriptor = EntityTypeContainer.GetDescriptor(typeof(TEntity));

            List<PrimitivePropertyDescriptor> mappingPropertyDescriptors = typeDescriptor.PrimitivePropertyDescriptors.Where(a => a.IsAutoIncrement == false).ToList();
            int maxDbParamsCount = maxParameters - mappingPropertyDescriptors.Count; /* 控制一个 sql 的参数个数 */

            DbTable dbTable = PublicHelper.CreateDbTable(typeDescriptor, table);
            string sqlTemplate = AppendInsertRangeSqlTemplate(dbTable, mappingPropertyDescriptors);

            Func<Task> insertAction = async () =>
            {
                int batchCount = 0;
                List<DbParam> dbParams = new List<DbParam>();
                StringBuilder sqlBuilder = new StringBuilder();
                for (int i = 0; i < entities.Count; i++)
                {
                    var entity = entities[i];

                    if (batchCount > 0)
                        sqlBuilder.Append(" UNION ALL ");

                    sqlBuilder.Append("SELECT ");
                    for (int j = 0; j < mappingPropertyDescriptors.Count; j++)
                    {
                        if (j > 0)
                            sqlBuilder.Append(",");

                        PrimitivePropertyDescriptor mappingPropertyDescriptor = mappingPropertyDescriptors[j];

                        object val = mappingPropertyDescriptor.GetValue(entity);

                        PublicHelper.NotNullCheck(mappingPropertyDescriptor, val);

                        if (val == null)
                        {
                            sqlBuilder.Append("NULL");
                            sqlBuilder.Append(" C").Append(j.ToString());
                            continue;
                        }

                        Type valType = val.GetType();
                        if (valType.IsEnum)
                        {
                            val = Convert.ChangeType(val, Enum.GetUnderlyingType(valType));
                            valType = val.GetType();
                        }

                        if (Utils.IsToStringableNumericType(valType))
                        {
                            sqlBuilder.Append(val.ToString());
                        }
                        else if (val is bool)
                        {
                            if ((bool)val == true)
                                sqlBuilder.AppendFormat("1");
                            else
                                sqlBuilder.AppendFormat("0");
                        }
                        else
                        {
                            string paramName = UtilConstants.ParameterNamePrefix + dbParams.Count.ToString();
                            DbParam dbParam = new DbParam(paramName, val) { DbType = mappingPropertyDescriptor.Column.DbType };
                            dbParams.Add(dbParam);
                            sqlBuilder.Append(paramName);
                        }

                        sqlBuilder.Append(" C").Append(j.ToString());
                    }

                    sqlBuilder.Append(" FROM DUAL");

                    batchCount++;

                    if ((batchCount >= 20 && dbParams.Count >= 400/*参数个数太多也会影响速度*/) || dbParams.Count >= maxDbParamsCount || batchCount >= batchSize || (i + 1) == entities.Count)
                    {
                        sqlBuilder.Insert(0, sqlTemplate);
                        sqlBuilder.Append(") T");

                        string sql = sqlBuilder.ToString();
                        await this.Session.ExecuteNonQuery(sql, dbParams.ToArray(), @async);

                        sqlBuilder.Clear();
                        dbParams.Clear();
                        batchCount = 0;
                    }
                }
            };

            Func<Task> fAction = insertAction;

            if (this.Session.IsInTransaction)
            {
                await fAction();
                return;
            }

            /* 因为分批插入,所以需要开启事务保证数据一致性 */
            this.Session.BeginTransaction();
            try
            {
                await fAction();
                this.Session.CommitTransaction();
            }
            catch
            {
                this.Session.RollbackTransaction();
                throw;
            }
        }

        protected override async Task<int> Update<TEntity>(TEntity entity, string table, bool @async)
        {
            PublicHelper.CheckNull(entity);

            TypeDescriptor typeDescriptor = EntityTypeContainer.GetDescriptor(typeof(TEntity));
            PublicHelper.EnsureHasPrimaryKey(typeDescriptor);

            PairList<PrimitivePropertyDescriptor, object> keyValues = new PairList<PrimitivePropertyDescriptor, object>(typeDescriptor.PrimaryKeys.Count);

            IEntityState entityState = this.TryGetTrackedEntityState(entity);
            Dictionary<PrimitivePropertyDescriptor, DbExpression> updateColumns = new Dictionary<PrimitivePropertyDescriptor, DbExpression>();
            foreach (PrimitivePropertyDescriptor propertyDescriptor in typeDescriptor.PrimitivePropertyDescriptors)
            {
                if (propertyDescriptor.IsPrimaryKey)
                {
                    var keyValue = propertyDescriptor.GetValue(entity);
                    PrimaryKeyHelper.KeyValueNotNull(propertyDescriptor, keyValue);
                    keyValues.Add(propertyDescriptor, keyValue);
                    continue;
                }

                if (propertyDescriptor.CannotUpdate())
                    continue;

                object val = propertyDescriptor.GetValue(entity);
                PublicHelper.NotNullCheck(propertyDescriptor, val);

                if (entityState != null && !entityState.HasChanged(propertyDescriptor, val))
                    continue;

                DbExpression valExp = DbExpression.Parameter(val, propertyDescriptor.PropertyType, propertyDescriptor.Column.DbType);
                updateColumns.Add(propertyDescriptor, valExp);
            }

            object rowVersionNewValue = null;
            if (typeDescriptor.HasRowVersion())
            {
                var rowVersionDescriptor = typeDescriptor.RowVersion;
                var rowVersionOldValue = rowVersionDescriptor.GetValue(entity);
                rowVersionNewValue = PublicHelper.IncreaseRowVersionNumber(rowVersionOldValue);
                updateColumns.Add(rowVersionDescriptor, DbExpression.Parameter(rowVersionNewValue, rowVersionDescriptor.PropertyType, rowVersionDescriptor.Column.DbType));
                keyValues.Add(rowVersionDescriptor, rowVersionOldValue);
            }

            if (updateColumns.Count == 0)
                return 0;

            DbTable dbTable = PublicHelper.CreateDbTable(typeDescriptor, table);
            DbExpression conditionExp = PublicHelper.MakeCondition(keyValues, dbTable);
            DbUpdateExpression e = new DbUpdateExpression(dbTable, conditionExp);

            foreach (var item in updateColumns)
            {
                e.UpdateColumns.Add(item.Key.Column, item.Value);
            }

            int rowsAffected = await this.ExecuteNonQuery(e, @async);

            if (typeDescriptor.HasRowVersion())
            {
                PublicHelper.CauseErrorIfOptimisticUpdateFailed(rowsAffected);
                typeDescriptor.RowVersion.SetValue(entity, rowVersionNewValue);
            }

            if (entityState != null)
                entityState.Refresh();

            return rowsAffected;
        }

        string AppendInsertRangeSqlTemplate(DbTable table, List<PrimitivePropertyDescriptor> mappingPropertyDescriptors)
        {
            StringBuilder sqlBuilder = new StringBuilder();

            sqlBuilder.Append("INSERT INTO ");
            sqlBuilder.Append(this.AppendTableName(table));
            sqlBuilder.Append("(");

            for (int i = 0; i < mappingPropertyDescriptors.Count; i++)
            {
                PrimitivePropertyDescriptor mappingPropertyDescriptor = mappingPropertyDescriptors[i];
                if (i > 0)
                    sqlBuilder.Append(",");
                sqlBuilder.Append(this.QuoteName(mappingPropertyDescriptor.Column.Name));
            }

            sqlBuilder.Append(")");

            sqlBuilder.Append(" SELECT ");
            for (int i = 0; i < mappingPropertyDescriptors.Count; i++)
            {
                PrimitivePropertyDescriptor mappingPropertyDescriptor = mappingPropertyDescriptors[i];
                if (i > 0)
                    sqlBuilder.Append(",");

                if (mappingPropertyDescriptor.HasSequence())
                    sqlBuilder.AppendFormat("{0}.{1}", this.QuoteName(mappingPropertyDescriptor.Definition.SequenceName), this.QuoteName("NEXTVAL"));
                else
                {
                    sqlBuilder.Append("C").Append(i.ToString());
                }
            }
            sqlBuilder.Append(" FROM (");

            string sqlTemplate = sqlBuilder.ToString();
            return sqlTemplate;
        }

        string AppendTableName(DbTable table)
        {
            if (string.IsNullOrEmpty(table.Schema))
                return this.QuoteName(table.Name);

            return string.Format("{0}.{1}", this.QuoteName(table.Schema), this.QuoteName(table.Name));
        }
        string QuoteName(string name)
        {
            if (this.ConvertToUppercase)
                return string.Concat("\"", name.ToUpper(), "\"");

            return string.Concat("\"", name, "\"");
        }
    }
}


text:
/**
* Author: DevChache (Yang Zhongdong)
* Date: July 1st, 2017
* Description: This is the mixed file of stylesheets from different domains.
*/

@-moz-document url-prefix("http://12306.cn"), url-prefix("http://www.12306.cn"), url-prefix("https://www.12306.cn"), url-prefix("https://12306.cn") {
@font-face {
	font-family: 'Material Icons';
	font-style: normal;
	font-weight: 400;
	src: local('Material Icons'), local('MaterialIcons-Regular'), url(https://fonts.gstatic.com/s/materialicons/v22/2fcrYFNaTjcS6g4U3t-Y5ZjZjT5FdEJ140U2DJYC3mY.woff2) format('woff2');
}
* {
	font-family: "Microsoft YaHei", "Roboto", sans-serif !important;
	font-size: 16px;
}
body {
	background-color: #f7f7f7;
}
div#top.flash-update,div#top.flash-replaced {
	display: none;
}
#page {
	margin-top: 72px;
	background:none;
	background-color:transparent;
}
#menu {
	width: 100%;
	position: fixed;
	left: 0;
	top: 0;
	display: block;
	height: 48px;
	background: none;
	background-color: #2196f3;
	box-shadow: 0 0 5px 2px rgba(0, 0, 0, .3);
	z-index: 99999;
}
#menu > ul.menubg {
	width: 960px;
	height: 48px;
	position: absolute;
	left: 50%;
	margin-left: -480px;
	background: none;
	background-color: transparent;
	padding-left: 16px;
}
#menu > ul.menubg li {
	text-align: left;
	line-height: 48px;
	background: none;
	background-color: transparent;
}
#menu > ul.menubg li#currentDate {
	display: none;
}
#menu > ul.menubg li a {
	color: #ffffff;
	font-size: 1em;
}
#menu > ul.menubg li a:hover {
	color: #e0e0e0;
	text-decoration: none;
}
div#appDown {
	display: none;
}
div#newLeft {
	display: none;
}
div#indexLeft {
	width: 100%;
}
div#indexRight {
	display: none;
}
div#newContent {
	width: 100%;
	float: none;
	padding: 32px;
	box-sizing: border-box;
	background-color: #fff;
	box-shadow: 3px 4px 6px 0px rgba(0, 0, 0, .1),-1px -1px 6px 0px rgba(0, 0, 0, .1);
	border-radius: 2px;
	height: auto;
}
div#newContent div.newsTitle {
	background: none;
	font-size: 1.5em;
	font-weight:normal;
	margin-bottom: .25em;
	color: #424242;
	padding: 0;
}
div#newContent div.newH2#newContent2 > div:first-child {
	margin-bottom: 0.75em;
}
div#newContent div.newH2#newContent2 > div:first-child > span {
	font-size: 14px !important;
	color: #aeaeae !important;
	margin-left: -8px;
}
div#newContent div.newH2#newContent2 > div:first-child > span > a u {
	font-size: 14px !important;
	text-decoration: none;
	margin: 0 4px;
}
div#newContent div.newH2#newContent2 > div:first-child > marquee {
	display: none;
}
div#newContent div#zxdt {
	padding: 0;
	height: auto;
}
div#newContent div#zxdt ul {
	margin: 0;
	padding: 0;
}
div#newContent div#zxdt ul li {
	list-style: none;
	margin: 0;
	padding: 0;
	background: none;
	height: 32px;
	line-height: 32px;
}
div#newContent div#zxdt ul li span.zxdt_time {
	font-size: 0.85em;
	color: #aeaeae;
}
div#newContent div#zxdt ul li a {
	font-size: 1em;
	background: none;
	margin: 0;
	padding: 0;
	color: #757575;
}
#newContent2 > div.textRight > a {
	font-size: 0.85em;
	color: #aeaeae;
}
#newContent2 > div.textRight > a:hover {
	text-decoration: none;
	color: #757575;
}
div#indexLeft div#indexLeftB div#indexLeftBL {
	display: block;
	box-shadow: 3px 4px 6px 0px rgba(0, 0, 0, .1),-1px -1px 6px 0px rgba(0, 0, 0, .1);
	border-radius: 5px;
	width: 216px;
	padding: 32px;
	box-sizing: border-box;
	float: left;
	margin: 32px 0;
	background-color:#FFFFFF;
}
div#indexLeft div#indexLeftB div#indexLeftBR {
	display: block;
	box-shadow: 3px 4px 6px 0px rgba(0, 0, 0, .1),-1px -1px 6px 0px rgba(0, 0, 0, .1);
	border-radius: 5px;
	width: 728px;
	padding: 32px;
	box-sizing: border-box;
	float: left;
	background-color:#FFFFFF;
	margin: 32px 0 0 16px;
}
div#indexLeft div#indexLeftB div#indexLeftBL ul.leftItem {
	padding: 0;
	margin: 0;
}
div#indexLeft div#indexLeftB div#indexLeftBL ul.leftItem li {
	height: 32px;
}
div#indexLeft div#indexLeftB div#indexLeftBL ul.leftItem li a:hover {
	color: #757575;
}
div#indexLeft div#indexLeftB div#indexLeftBL ul.leftItem li:first-child a img {
	display: none;
}
div#indexLeft div#indexLeftB div#indexLeftBL ul.leftItem li:first-child {
	height: 32px;
}
div#indexLeft div#indexLeftB div#indexLeftBL ul.leftItem li:first-child a::before {
	float: left;
	font-family: 'Material Icons';
	font-size: 30px;
	display: block;
	content: "\E570";
	line-height: 32px;
	color: #757575;
}
div#indexLeft div#indexLeftB div#indexLeftBL ul.leftItem li:first-child a {
	width: 100%;
	display: block;
	height: 32px;
	line-height: 32px;
}
div#indexLeft div#indexLeftB div#indexLeftBL ul.leftItem li:first-child a::after {
	margin-left: 8px;
	content: "购票入口";
	font-size: 16px;
	height: 32px;
	display: block;
	float: left;
	line-height: 32px;
}
div#indexLeft div#indexLeftB div#indexLeftBL ul.leftItem {
	width: auto;
}
div#indexLeft div#indexLeftB div#indexLeftBL ul.leftItem li {
	background: none;
	background-color: transparent;
}
div#indexLeft div#indexLeftB div#indexLeftBL ul.leftItem li a {
	background-image: none;
	background-color: transparent;
	padding: 0;
	border: none;
	font-size: 16px;
}
div#indexLeft div#indexLeftB div#indexLeftBL ul.leftItem li a:hover {
	text-decoration: none;
}
div#indexLeft div#indexLeftB div#indexLeftBL ul.leftItem li:last-child {
	display: none;
}

div#indexLeft div#indexLeftB div#indexLeftBR div#search{
	border:none;
	background:none;
	text-align:left;
	height:48px;
	line-height:48px;
	font-size:16px;
}
div#indexLeft div#indexLeftB div#indexLeftBR div#search form#fmsearch{
	width:560px;
}

div#indexLeft div#indexLeftB div#indexLeftBR div#search form#fmsearch::before{
	content:"全文搜索:";
	display:block;
	float:left;
}

div#indexLeft div#indexLeftB div#indexLeftBR div#search form#fmsearch::after{
	content:"\E8B6";
	font-family: 'Material Icons';
	font-size: 30px;
	width:30px;
	float:right;
	height:48px;
	margin-top:-46px;
	margin-right:24px;
	display: block;
	line-height: 48px;
	color: #757575;
}
div#indexLeft div#indexLeftB div#indexLeftBR div#search form#fmsearch lable,div#indexLeft div#indexLeftB div#indexLeftBR div#search form#fmsearch label{
	display:none;
}
div#indexLeft div#indexLeftB div#indexLeftBR div#search form#fmsearch input#searchwordl{
	border:none;
	margin:0;
	border-bottom:1px solid #e0e0e0;
	transition:border-bottom-width ease 300ms,border-bottom-color ease 300ms;
}
div#indexLeft div#indexLeftB div#indexLeftBR div#search form#fmsearch input#searchwordl:focus{
	outline:none;
	border-bottom:2px solid #757575;
}
div#indexLeft div#indexLeftB div#indexLeftBR div#search form#fmsearch input[type=image]{
	opacity:0;
	width:60px;
}

#indexLeftBR > div.margin_top3px.clearfix{
	display:none;
}
#indexLeftBR > div.slideTxtBox{
	border:none;
	padding:0;
	width:100%;
	margin-top:16px;
}
#indexLeftBR > div.slideTxtBox > div.hd {
	background:none;
	padding:0;
	height:32px;
	line-height:32px;
	border:none;
}

#indexLeftBR > div.slideTxtBox > div.hd > ul{
	float:none;
	position:static;
	top:0;
	left:0;
}
#indexLeftBR > div.slideTxtBox > div.hd > ul li{
	font-size:16px;
	height:32px;
	line-height:32px;
	border:none;
	text-align:left;
	padding:0 16px;
	width:auto;
	box-sizing:border-box;
	user-select:none;
}
#indexLeftBR > div.slideTxtBox > div.hd > ul li.on{
/* 	background-color:#f3f3f3; */
	box-shadow:1px -2px 2px 1px rgba(0,0,0,.2);
	border-top-left-radius:2px;
	border-top-right-radius:2px;
}
#indexLeftBR > div.slideTxtBox > div.tempWrap > div > ul{
	padding:0 20px 20px 0;
}
#indexLeftBR > div.slideTxtBox > div.tempWrap > div > ul li{
	height:32px;
	line-height:32px;
}
#indexLeftBR > div.slideTxtBox > div.tempWrap > div > ul li.info_item > a{
	background:none;
	padding-left:0;
	font-size:12px;
}

#indexRight > #slideRBox.slideRBox,
#indexRight > div.slideRTxt {
	display: none !important;
}
#indexLeftBR > div.slideTxtBox > div.tempWrap > div > ul:nth-child(1) > li{
	height:auto;
}
#indexLeftBR > div.slideTxtBox > div.tempWrap > div > ul:nth-child(1) > li > iframe{
	min-height:356px;
}

div.bottom_copy {
	width: 960px;
	height: 24px;
	display: block;
	overflow: hidden;
	transition: height ease 300ms, margin-top ease 300ms;
	margin-top: 24px;
	background-color:transparent;
	color:#757575;
}
div.bottom_copy:hover {
	height: 128px;
	margin-top: 0;
}
div.bottom_copy div.bottom_line1,
div.bottom_copy div.bottom_line2 {
	display: none;
}
div.bottom_copy div:nth-child(2) {
	transition: margin-top ease 300ms;
	margin-top: -52px;
	user-select: none;
	cursor: default;
}
div.bottom_copy:hover div:nth-child(2) {
	margin-top: 0px;
}
}

@-moz-document url-prefix("http://dynamic.12306.cn"), url-prefix("https://dynamic.12306.cn") {
@font-face {
	font-family: 'Material Icons';
	font-style: normal;
	font-weight: 400;
	src: local('Material Icons'), local('MaterialIcons-Regular'), url(https://fonts.gstatic.com/s/materialicons/v22/2fcrYFNaTjcS6g4U3t-Y5ZjZjT5FdEJ140U2DJYC3mY.woff2) format('woff2');
}
* {
	font-family: "Microsoft YaHei", "Roboto", sans-serif !important;
	font-size: 16px;
}

body table#board_table.ypxx-con th,table#board_table.ypxx-con td{
	padding:0 16px;
	height:32px !important;
	line-height:32px;
	text-align:left;
	font-size:14px;
	width:auto!important;
}

body > div.ypxx-box > div.ypxx-page {
	height:24px;
	line-height:24px;
	text-align:left;
}

body > div.ypxx-box > div.ypxx-page a#board_gotoMore{
	color:#757575;
}

body > div.ypxx-box > div.ypxx-page a#board_gotoMore:hover{
	color:#aeaeae;
}
body > div.ypxx-box > div.ypxx-page span#leftTicketTip{
	padding-left:16px;
	color:#aeaeae;
	font-size:12px;
}
body > div.ypxx-box > div.ypxx-page #board_gotoMore{
	font-size:14px;
}
}


text:
package de.learnlib.alex.websocket.message;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.jayway.jsonpath.JsonPath;
import de.learnlib.alex.security.AuthContext;
import de.learnlib.alex.websocket.entities.WebSocketMessage;
import de.learnlib.alex.websocket.services.WebSocketService;
import de.learnlib.alex.websocket.services.enums.WebSocketServiceEnum;
import java.io.IOException;
import java.security.Principal;
import javax.ws.rs.core.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpAttributesContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@Controller
public class WebSocketController {

    private final WebSocketService webSocketService;

    private final AuthContext authContext;

    private final ObjectMapper objectMapper;

    @Autowired
    public WebSocketController(WebSocketService webSocketService, AuthContext authContext, ObjectMapper objectMapper) {
        this.webSocketService = webSocketService;
        this.authContext = authContext;
        this.objectMapper = objectMapper;
    }

    @MessageMapping("/send/event")
    public void onIncomingEvent(@Payload String event, Principal userPrincipal) {
        WebSocketMessage msg;

        try {
            msg = objectMapper.readValue(event, WebSocketMessage.class);
            if (msg.getEntity() == null || msg.getType() == null) {
                throw new IOException();
            }
            webSocketService.processIncomingMessage(msg, userPrincipal);
        } catch (IOException e) {
            final WebSocketMessage error = new WebSocketMessage();
            error.setEntity(WebSocketServiceEnum.WEBSOCKET_SERVICE.name());
            error.setType(WebSocketServiceEnum.ERROR.name());

            final ObjectNode content = objectMapper.createObjectNode();
            content.put("description", "Received malformed WebSocketMessage.");
            content.put("message", event);
            error.setContent(content.toString());

            this.webSocketService.sendError(SimpAttributesContextHolder.currentAttributes().getSessionId(), error);
        }
    }

    @ResponseStatus(code = HttpStatus.NO_CONTENT)
    @PostMapping(
            value = "/rest/ws/disconnect",
            consumes = MediaType.APPLICATION_JSON
    )
    public void onDisconnect(@RequestBody String data) {
        final String sessionId = JsonPath.read(data, "$.sessionId");
        final long userId = this.webSocketService.getUserIdBySessionId(sessionId);

        if (authContext.getUser().getId() == userId) {
            this.webSocketService.closeSession(sessionId);
        }
    }

}


text:
import java.util.HashMap;

public interface Consumer {
    public void consume(HashMap message);
}


text:
package ch.bfh.entities;

public abstract class TwitterEntity {
}


text:
from pants.backend.codegen.wire.java.java_wire_library import JavaWireLibrary
from pants.backend.codegen.wire.java.wire_gen import WireGen
from pants.build_graph.build_file_aliases import BuildFileAliases
from pants.goal.task_registrar import TaskRegistrar as task

def build_file_aliases():
    return BuildFileAliases(targets={"java_wire_library": JavaWireLibrary,})

def register_goals():
    task(name="wire", action=WireGen).install("gen")


text:
/**
 *
 */
package org.apache.geode.demo.fastfootshoes.model;

import java.util.Date;

import org.springframework.data.annotation.Id;
import org.springframework.data.gemfire.mapping.Region;

/**
 * This class contains all the details around a transaction.
 * Rather than nesting Product and Customer objects, they are referenced by Id.
 * This approach allows for easier querying of Transactions in Geode as well as reduces the
 * memory foot print.
 * @author lshannon
 */

//Spring Data Repositories will be used to populate the data into the cluster. This must map exactly to a region name in the cluster
@Region("Transaction")
public class Transaction {

	private String customerId;
	private Date transactionDate;
	private String productId;
	private int quantity;
	private double retailPrice;
	private String orderStatus;
	@Id
	private String id;
	private double markUp;
	public static String ORDER_COMPLETED = "shipped";
	public static String ORDER_CANCELLED = "cancelled";
	public static String ORDER_OPEN = "open";

	public Date getTransactionDate() {
		return transactionDate;
	}

	public void setTransactionDate(Date transactionDate) {
		this.transactionDate = transactionDate;
	}

	public String getProductId() {
		return productId;
	}

	public void setProductId(String productId) {
		this.productId = productId;
	}

	public int getQuantity() {
		return quantity;
	}

	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}

	public double getRetailPrice() {
		return retailPrice;
	}

	public void setRetailPrice(double retailPrice) {
		this.retailPrice = retailPrice;
	}

	public String getOrderStatus() {
		return orderStatus;
	}

	public void setOrderStatus(String orderStatus) {
		this.orderStatus = orderStatus;
	}

	public double getMarkUp() {
		return markUp;
	}

	public void setMarkUp(double markUp) {
		this.markUp = markUp;
	}

	public String getCustomerId() {
		return customerId;
	}

	public void setCustomerId(String customerId) {
		this.customerId = customerId;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	@Override
	public String toString() {
		return "Transaction [customerId=" + customerId + ", transactionDate="
				+ transactionDate + ", productId=" + productId + ", quantity="
				+ quantity + ", retailPrice=" + retailPrice + ", orderStatus="
				+ orderStatus + ", id=" + id + ", markUp=" + markUp + "]";
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Transaction other = (Transaction) obj;
		if (customerId == null) {
			if (other.customerId != null)
				return false;
		} else if (!customerId.equals(other.customerId))
			return false;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		if (Double.doubleToLongBits(markUp) != Double
				.doubleToLongBits(other.markUp))
			return false;
		if (orderStatus == null) {
			if (other.orderStatus != null)
				return false;
		} else if (!orderStatus.equals(other.orderStatus))
			return false;
		if (productId == null) {
			if (other.productId != null)
				return false;
		} else if (!productId.equals(other.productId))
			return false;
		if (quantity != other.quantity)
			return false;
		if (Double.doubleToLongBits(retailPrice) != Double
				.doubleToLongBits(other.retailPrice))
			return false;
		if (transactionDate == null) {
			if (other.transactionDate != null)
				return false;
		} else if (!transactionDate.equals(other.transactionDate))
			return false;
		return true;
	}

}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Aleurodiscus macrosporus f. polyphysa Pilát

### Remarks
null


text:
Notes

				Posted on

				by

    	No Notes yet, why don't you create one?


text:
(function() {
  var CommandProcess, Icommand, formatMemory, padding,
    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    hasProp = {}.hasOwnProperty,
    indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

  Icommand = require('../icommand.js');

  formatMemory = function(num, type, showType) {
    var output;
    if (type == null) {
      type = 'auto';
    }
    if (showType == null) {
      showType = 'show';
    }
    if (type === 'auto') {
      type = 'mb';
      if (num > 1024 * 1024 * 1024 * 0.9) {
        type = 'gb';
      }
    }
    output = '';
    if (type === 'mb') {
      output += (num / 1024 / 1024).toFixed(1);
    } else {
      output += (num / 1024 / 1024 / 1024).toFixed(1);
    }
    if (showType === 'show') {
      output += type;
    }
    return output;
  };

  padding = function(str, fill, len) {
    str = str.toString();
    while (str.length < len) {
      str = fill + str;
    }
    return str;
  };

  CommandProcess = (function(superClass) {
    extend(CommandProcess, superClass);

    function CommandProcess() {
      this.displayed = ['pid', 'memoryUsage', 'uptime'];
    }

    CommandProcess.prototype.handle = function(sender, text, args, storage, textRouter, commandManager) {
      var i, len1, output, ref, ref1, type;
      if (args.length === 1) {
        args.push('all');
      }
      if (args.length > 2) {
        return false;
      }
      if (0 > (['all'].concat(this.displayed)).indexOf(args[1])) {
        return false;
      }
      output = [];
      if (args[1] === 'all') {
        ref = this.displayed;
        for (i = 0, len1 = ref.length; i < len1; i++) {
          type = ref[i];
          output.push(type + " : " + (this._getValue(type)));
        }
      } else if (ref1 = args[1], indexOf.call(this.displayed, ref1) >= 0) {
        output.push(this._getValue(args[1]));
      } else {
        return false;
      }
      commandManager.send(sender, textRouter, output.join(', '));
      return true;
    };

    CommandProcess.prototype._getValue = function(type) {
      var result;
      if ('function' === typeof process[type]) {
        result = process[type]();
      } else {
        result = process[type];
      }
      result = this._mapper(result, type);
      return result;
    };

    CommandProcess.prototype._mapper = function(val, type) {
      var day, hour, minute, name, res, second, value;
      if (type === 'uptime') {
        val = Math.floor(val / 1);
        second = val % 60;
        minute = (Math.floor(val / 60)) % 60;
        hour = (Math.floor(val / (60 * 60))) % 24;
        day = Math.floor(val / (60 * 60 * 24));
        return "" + (day > 1 ? day + ' days, ' : day > 0 ? '1 day, ' : '') + (padding(hour, "0", 2)) + ":" + (padding(minute, "0", 2)) + ":" + (padding(second, "0", 2));
      }
      if (type === 'memoryUsage') {
        res = [];
        for (name in val) {
          value = val[name];
          res.push(name + " : " + (formatMemory(value)));
        }
        return res.join(', ');
      }
      return val.toString();
    };

    CommandProcess.prototype.help = function(commandPrefix) {
      return ["Show process info of this bot, Usage: ", commandPrefix + " [all|pid|memoryUsage|uptime]."];
    };

    CommandProcess.prototype.hasPermission = function(sender, text, args, storage, textRouter, commandManager, fromBinding) {
      return true;
    };

    return CommandProcess;

  })(Icommand);

  module.exports = CommandProcess;

}).call(this);


text:
""" This is the entry point for the Planteur application."""
import json
import logging
from collections import namedtuple

import serial

import adapters
import database
import plant
import watering

def _configure_logging(config_pathname):
    logging.info('Loading configuration...')

    with open(config_pathname) as file:
        # Load JSON content
        json_dict = json.load(file)

        # Log level
        level_str = json_dict['log']['level']
        level = getattr(logging, level_str.upper())
        logging.info('Changing log level to %s', level)
        logging.getLogger().setLevel(level)

        # XBee port

def _start_xbee_adapter(config_pathname, plants):
    # Check that there if there is at least one network plant
    xbee_ids_to_uids = dict()
    for plant_ in plants:
        if plant_.connection is plant.ConnectionType.xbee:
            xbee_ids_to_uids[plant_.xbee_id] = plant_.uid

    logging.debug('XBee ID <==> UID: %s', xbee_ids_to_uids)

    if len(xbee_ids_to_uids) != 0:
        # Get XBee port from configuration
        with open(config_pathname) as file:
            json_dict = json.load(file)
            xbee_port = json_dict['xbee']['serial_port']

        # Open port
        ser = serial.Serial(xbee_port)

        # Start adapter
        xbee_adapter = adapters.XbeeAdapter(ser, xbee_ids_to_uids)
        xbee_adapter.start()

def planteur(config_pathname, plant_pathname):
    """Run the Planteur :)

    :param config_pathname: the pathname to the configuration file
    :type config_pathname: str
    :param plant_pathname: the pathname to the plant description file
    :type plant_pathname: str
    """
    logging.info('Planteur application starts')
    _configure_logging(config_pathname)

    # Load plants
    logging.info('Loading plants...')
    plants = plant.load_plants_from(plant_pathname)
    if len(plants) == 0:
        logging.warning('No plant has been loaded, plants.json may be empty')

    # Start database logger
    db_logger = database.DatabaseLogger('planteur.db')
    db_logger.start()

    # Start sprinkler
    sprinkler = watering.Sprinkler(plants)
    sprinkler.start()

    # TODO create watering planner if at least one plant as 'planned' as it's watering method

    # Start adapters
    _start_xbee_adapter(config_pathname, plants)

    # TODO create and start custom adapters

    # Startup complete
    logging.debug('Application startup is complete')

if __name__ == '__main__':
    # Configure logging
    logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.DEBUG)

    # Run Planteur
    planteur('config.json', 'plants.json')


text:
from sys import stdout
from time import gmtime, strftime

try:
    from django.core.management.base import NoArgsCommand
except ImportError:
    from django.core.management import BaseCommand as NoArgsCommand

from searchv2.builders import build_1

class Command(NoArgsCommand):

    help = "Constructs the search results for the system"

    def handle(self, *args, **options):

        print("Commencing search result building now %s " % strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()), file=stdout)
        build_1()
        print("Finished at %s" % strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()), file=stdout)


text:
package com.aqnote.app.barcode.result.supplement;

import android.text.Html;
import android.widget.TextView;
import com.aqnote.app.barcode.HttpHelper;
import com.aqnote.app.barcode.history.HistoryManager;
import com.aqnote.app.barcode.core.client.result.URIParsedResult;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Retrieves the title of a web page as supplemental info.
 *
 * @author Sean Owen
 */
final class TitleRetriever extends SupplementalInfoRetriever {

  private static final Pattern TITLE_PATTERN = Pattern.compile("<title>([^<]+)");
  private static final int MAX_TITLE_LEN = 100;

  private final String httpUrl;

  TitleRetriever(TextView textView, URIParsedResult result, HistoryManager historyManager) {
    super(textView, historyManager);
    this.httpUrl = result.getURI();
  }

  @Override
  void retrieveSupplementalInfo() {
    CharSequence contents;
    try {
      contents = HttpHelper.downloadViaHttp(httpUrl, HttpHelper.ContentType.HTML, 4096);
    } catch (IOException ioe) {
      // ignore this
      return;
    }
    if (contents != null && contents.length() > 0) {
      Matcher m = TITLE_PATTERN.matcher(contents);
      if (m.find()) {
        String title = m.group(1);
        if (title != null && !title.isEmpty()) {
          title = Html.fromHtml(title).toString();
          if (title.length() > MAX_TITLE_LEN) {
            title = title.substring(0, MAX_TITLE_LEN) + "...";
          }
          append(httpUrl, null, new String[] {title}, httpUrl);
        }
      }
    }
  }

}


text:
rm -R results
rm -R temp_results


text:
module.exports = require('../build/Release/bigmaths.node');

module.exports.countto_jsversion = function(ubound, skip) {
    var i = 0, c = 0;
    while ( i < ubound ) {
        i += skip;
        c ++;
    }

    return c;
};

/**
 * wrap C++/JS functionality in a timer
 * @param runner - JS or C
 * @param uBound
 * @param skip
 */
module.exports.timedCountTo = function(runner, uBound, skip) {
    var starttime = new Date().getTime();
    if (runner == "JS") {
        module.exports.countto_jsversion(uBound, skip);
    } else {
        module.exports.countto(uBound, skip);
    }
    var endtime = new Date().getTime();
    var dur = (endtime - starttime)/1000;

    console.log("Counting from 0 to " + uBound + " (skipping by " + skip + ") took " + dur + " seconds with " + runner);
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.netapp.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Encryption settings. */
@Fluent
public final class AccountEncryption {
    /*
     * The encryption keySource (provider). Possible values (case-insensitive):  Microsoft.NetApp, Microsoft.KeyVault
     */
    @JsonProperty(value = "keySource")
    private KeySource keySource;

    /*
     * Properties provided by KeVault. Applicable if keySource is 'Microsoft.KeyVault'.
     */
    @JsonProperty(value = "keyVaultProperties")
    private KeyVaultProperties keyVaultProperties;

    /*
     * Identity used to authenticate to KeyVault. Applicable if keySource is 'Microsoft.KeyVault'.
     */
    @JsonProperty(value = "identity")
    private EncryptionIdentity identity;

    /**
     * Get the keySource property: The encryption keySource (provider). Possible values (case-insensitive):
     * Microsoft.NetApp, Microsoft.KeyVault.
     *
     * @return the keySource value.
     */
    public KeySource keySource() {
        return this.keySource;
    }

    /**
     * Set the keySource property: The encryption keySource (provider). Possible values (case-insensitive):
     * Microsoft.NetApp, Microsoft.KeyVault.
     *
     * @param keySource the keySource value to set.
     * @return the AccountEncryption object itself.
     */
    public AccountEncryption withKeySource(KeySource keySource) {
        this.keySource = keySource;
        return this;
    }

    /**
     * Get the keyVaultProperties property: Properties provided by KeVault. Applicable if keySource is
     * 'Microsoft.KeyVault'.
     *
     * @return the keyVaultProperties value.
     */
    public KeyVaultProperties keyVaultProperties() {
        return this.keyVaultProperties;
    }

    /**
     * Set the keyVaultProperties property: Properties provided by KeVault. Applicable if keySource is
     * 'Microsoft.KeyVault'.
     *
     * @param keyVaultProperties the keyVaultProperties value to set.
     * @return the AccountEncryption object itself.
     */
    public AccountEncryption withKeyVaultProperties(KeyVaultProperties keyVaultProperties) {
        this.keyVaultProperties = keyVaultProperties;
        return this;
    }

    /**
     * Get the identity property: Identity used to authenticate to KeyVault. Applicable if keySource is
     * 'Microsoft.KeyVault'.
     *
     * @return the identity value.
     */
    public EncryptionIdentity identity() {
        return this.identity;
    }

    /**
     * Set the identity property: Identity used to authenticate to KeyVault. Applicable if keySource is
     * 'Microsoft.KeyVault'.
     *
     * @param identity the identity value to set.
     * @return the AccountEncryption object itself.
     */
    public AccountEncryption withIdentity(EncryptionIdentity identity) {
        this.identity = identity;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (keyVaultProperties() != null) {
            keyVaultProperties().validate();
        }
        if (identity() != null) {
            identity().validate();
        }
    }
}