text:
package org.zstack.sdk;

public class BaremetalPxeServerInventory  {

    public java.lang.String uuid;
    public void setUuid(java.lang.String uuid) {
        this.uuid = uuid;
    }
    public java.lang.String getUuid() {
        return this.uuid;
    }

    public java.lang.String zoneUuid;
    public void setZoneUuid(java.lang.String zoneUuid) {
        this.zoneUuid = zoneUuid;
    }
    public java.lang.String getZoneUuid() {
        return this.zoneUuid;
    }

    public java.lang.String name;
    public void setName(java.lang.String name) {
        this.name = name;
    }
    public java.lang.String getName() {
        return this.name;
    }

    public java.lang.String description;
    public void setDescription(java.lang.String description) {
        this.description = description;
    }
    public java.lang.String getDescription() {
        return this.description;
    }

    public java.lang.String hostname;
    public void setHostname(java.lang.String hostname) {
        this.hostname = hostname;
    }
    public java.lang.String getHostname() {
        return this.hostname;
    }

    public java.lang.String sshUsername;
    public void setSshUsername(java.lang.String sshUsername) {
        this.sshUsername = sshUsername;
    }
    public java.lang.String getSshUsername() {
        return this.sshUsername;
    }

    public java.lang.String sshPassword;
    public void setSshPassword(java.lang.String sshPassword) {
        this.sshPassword = sshPassword;
    }
    public java.lang.String getSshPassword() {
        return this.sshPassword;
    }

    public java.lang.Integer sshPort;
    public void setSshPort(java.lang.Integer sshPort) {
        this.sshPort = sshPort;
    }
    public java.lang.Integer getSshPort() {
        return this.sshPort;
    }

    public java.lang.String storagePath;
    public void setStoragePath(java.lang.String storagePath) {
        this.storagePath = storagePath;
    }
    public java.lang.String getStoragePath() {
        return this.storagePath;
    }

    public java.lang.String dhcpInterface;
    public void setDhcpInterface(java.lang.String dhcpInterface) {
        this.dhcpInterface = dhcpInterface;
    }
    public java.lang.String getDhcpInterface() {
        return this.dhcpInterface;
    }

    public java.lang.String dhcpInterfaceAddress;
    public void setDhcpInterfaceAddress(java.lang.String dhcpInterfaceAddress) {
        this.dhcpInterfaceAddress = dhcpInterfaceAddress;
    }
    public java.lang.String getDhcpInterfaceAddress() {
        return this.dhcpInterfaceAddress;
    }

    public java.lang.String dhcpRangeBegin;
    public void setDhcpRangeBegin(java.lang.String dhcpRangeBegin) {
        this.dhcpRangeBegin = dhcpRangeBegin;
    }
    public java.lang.String getDhcpRangeBegin() {
        return this.dhcpRangeBegin;
    }

    public java.lang.String dhcpRangeEnd;
    public void setDhcpRangeEnd(java.lang.String dhcpRangeEnd) {
        this.dhcpRangeEnd = dhcpRangeEnd;
    }
    public java.lang.String getDhcpRangeEnd() {
        return this.dhcpRangeEnd;
    }

    public java.lang.String dhcpRangeNetmask;
    public void setDhcpRangeNetmask(java.lang.String dhcpRangeNetmask) {
        this.dhcpRangeNetmask = dhcpRangeNetmask;
    }
    public java.lang.String getDhcpRangeNetmask() {
        return this.dhcpRangeNetmask;
    }

    public java.lang.String state;
    public void setState(java.lang.String state) {
        this.state = state;
    }
    public java.lang.String getState() {
        return this.state;
    }

    public java.lang.String status;
    public void setStatus(java.lang.String status) {
        this.status = status;
    }
    public java.lang.String getStatus() {
        return this.status;
    }

    public java.sql.Timestamp createDate;
    public void setCreateDate(java.sql.Timestamp createDate) {
        this.createDate = createDate;
    }
    public java.sql.Timestamp getCreateDate() {
        return this.createDate;
    }

    public java.sql.Timestamp lastOpDate;
    public void setLastOpDate(java.sql.Timestamp lastOpDate) {
        this.lastOpDate = lastOpDate;
    }
    public java.sql.Timestamp getLastOpDate() {
        return this.lastOpDate;
    }

    public java.lang.Long totalCapacity;
    public void setTotalCapacity(java.lang.Long totalCapacity) {
        this.totalCapacity = totalCapacity;
    }
    public java.lang.Long getTotalCapacity() {
        return this.totalCapacity;
    }

    public java.lang.Long availableCapacity;
    public void setAvailableCapacity(java.lang.Long availableCapacity) {
        this.availableCapacity = availableCapacity;
    }
    public java.lang.Long getAvailableCapacity() {
        return this.availableCapacity;
    }

    public java.util.List attachedClusterUuids;
    public void setAttachedClusterUuids(java.util.List attachedClusterUuids) {
        this.attachedClusterUuids = attachedClusterUuids;
    }
    public java.util.List getAttachedClusterUuids() {
        return this.attachedClusterUuids;
    }

}


text:
package org.restler.http.security.authentication;

import org.restler.http.Request;

public abstract class HeaderBasedAuthenticationStrategy implements AuthenticationStrategy {

    protected abstract String getHeaderName(AuthenticationContext context);

    protected abstract String getHeaderValue(AuthenticationContext context);

    @Override
    public <T> Request<T> authenticate(Request<T> request, AuthenticationContext context) {
        return request.setHeader(getHeaderName(context), getHeaderValue(context));
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * DataBindingDirection defines constants that represent possible values for the `direction` property of a
 * {@link interface:mayhem/binding.IBindArguments bind arguments object}.
 */
enum DataBindingDirection {
	/**
	 * Create a one-way binding from source to target.
	 */
	ONE_WAY = 1,

	/**
	 * Create a two-way binding between the source and the target.
	 */
	TWO_WAY = 2
}

export = DataBindingDirection;


text:
using System.Threading.Tasks;
using System.Threading;
using NBlockchain.Models;

namespace NBlockchain.Interfaces
{
    public interface IConsensusMethod
    {
        Task BuildConsensus(Block block, CancellationToken cancellationToken);
        bool VerifyConsensus(Block block);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using ESRI.ArcLogistics.DomainObjects;
using System.Windows.Media;
using System.Windows;
using ESRI.ArcLogistics.App.DragAndDrop;
using System.Diagnostics;

namespace ESRI.ArcLogistics.App.Controls
{
    /// <summary>
    /// Class that represents a gantt item element that corresponds to a route without stops.
    /// </summary>
    internal class EmptyGanttItemElement : IGanttItemElement
    {
        /// <summary>
        /// Initializes a new instance of the <c>EmptyGanttItemElement</c> class.
        /// </summary>
        public EmptyGanttItemElement(IGanttItem parent)
        {
            _startTime = DateTime.MinValue;
            _endTime = DateTime.MaxValue;
            _parent = parent;
        }

        #region IGanttItemElement Members

        /// <summary>
        /// Gets start time.
        /// </summary>
        public DateTime StartTime
        {
            get
            {
                return _startTime;
            }
        }

        /// <summary>
        /// Gets end time.
        /// </summary>
        public DateTime EndTime
        {
            get
            {
                return _endTime;
            }
        }

        /// <summary>
        /// Gets route instance associated with this gantt item element.
        /// </summary>
        /// <remarks>
        /// All empty elements that belong to the same gantt item have the same tag value.
        /// </remarks>
        public object Tag
        {
            get
            {
                return _parent.Tag;
            }
        }

        /// <summary>
        /// Gets parent gantt item.
        /// </summary>
        public IGanttItem ParentGanttItem
        {
            get
            {
                return _parent;
            }
        }

        /// <summary>
        /// Returns "true" if elemnt is in progress.
        /// </summary>
        public bool IsInProgress
        {
            get { return false; }
        }

        /// <summary>
        /// Raised each time when element should be redraw.
        /// </summary>
        public event EventHandler RedrawRequired;

        /// <summary>
        /// Event is raised each time when drive time arrive time or depart time has changed.
        /// </summary>
        public event EventHandler TimeRangeChanged;

        /// <summary>
        /// Property cahnged event.
        /// </summary>
        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Draws transparent element with container's width in default. If element is dragged over highlights Time windows of dregged order.
        /// </summary>
        /// <param name="context">Drawing context.</param>
        public void Draw(GanttItemElementDrawingContext context)
        {
            Rect elementSize = new Rect(context.DrawingArea.X, context.DrawingArea.Top, context.DrawingArea.Width, context.DrawingArea.Height);

            SolidColorBrush fillBrush = new SolidColorBrush(Colors.Transparent);
            Pen drawPen = GanttControlHelper.GetPen();

            // Draw element.
            context.DrawingContext.DrawRectangle(fillBrush, drawPen, elementSize);

            // Draw dragged over element.
            if (context.DrawDraggedOver)
            {
                Debug.Assert(ParentGanttItem.Tag != null);

                Brush draggedOverBrush = GanttControlHelper.GetEmptyElementDragOverFillBrush(((Route)ParentGanttItem.Tag).Color);
                Pen pen = new Pen(fillBrush, 0);
                pen.Freeze();

                // Define collection of highlighted rectangles.
                Collection<Rect> highlightedRects = _GetHighlightedRects(context);

                if (highlightedRects == null)
                    return;

                // Draw dragged over areas.
                foreach (Rect rect in highlightedRects)
                    context.DrawingContext.DrawRoundedRectangle(draggedOverBrush, pen, rect, ROUND_RADIUS, ROUND_RADIUS);
            }
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Returns collection of rectangles which should be highlighted.
        /// </summary>
        /// <param name="context">Drawing context.</param>
        /// <returns>Collection of rectangles.</returns>
        private Collection<Rect> _GetHighlightedRects(GanttItemElementDrawingContext context)
        {
            DragAndDropHelper helper = new DragAndDropHelper();

            // Define collection of dragged orders.
            Collection<Order> orders = helper.GetDraggingOrders(context.DraggedData);

            // If more than one order is dragged - we don't need to highlight anything. Just return.
            if (orders.Count > 1)
                return null;

            // Define default values for dates.
            DateTime startTime = DateTime.MinValue;
            DateTime endTime = DateTime.MaxValue;

            // Create result collection.
            Collection<Rect> rectResults = new Collection<Rect>();

            Order order = orders[0];
            Debug.Assert(order != null);

            // If both indows are wideopen - define wideopen time span - from MinDate to MaxDate.
            if (order.TimeWindow.IsWideOpen && order.TimeWindow2.IsWideOpen)
                rectResults.Add(new Rect(context.DrawingArea.X, context.DrawingArea.Top, context.DrawingArea.Width, context.DrawingArea.Height + ANTI_ALIASING_GAP));

            // If first time window is not wideopen - define first time span.
            if (!order.TimeWindow.IsWideOpen)
            {
                startTime = new DateTime(order.TimeWindow.EffectiveFrom.Ticks);
                endTime = new DateTime(order.TimeWindow.EffectiveTo.Ticks);

                rectResults.Add(_GetRect(startTime, endTime, context));
            }

            // If second time window is not wideopen - define second time span.
            if (!order.TimeWindow2.IsWideOpen)
            {
                startTime = new DateTime(order.TimeWindow2.EffectiveFrom.Ticks);
                endTime = new DateTime(order.TimeWindow2.EffectiveTo.Ticks);

                rectResults.Add(_GetRect(startTime, endTime, context));
            }

            return rectResults;
        }

        /// <summary>
        /// Returns rect area by input parameters.
        /// </summary>
        /// <param name="startTime">Start area time.</param>
        /// <param name="endTime">End area time.</param>
        /// <param name="context">Drawing context.</param>
        /// <returns>Rect area.</returns>
        private Rect _GetRect(DateTime startTime, DateTime endTime, GanttItemElementDrawingContext context)
        {
            // Define count of pixels in minimal time span.
            double pixelsPerTick = context.DrawingArea.Width / (context.EndTime.TimeOfDay - context.StartTime.TimeOfDay).Ticks;

            // Define vertical dimensions.
            double yPos = context.DrawingArea.Top;
            double height = context.DrawingArea.Height;

            // Define horisontal dimensions.
            double xPos = (startTime.TimeOfDay - context.StartTime.TimeOfDay).Ticks * pixelsPerTick;
            double width = Math.Abs((endTime.TimeOfDay - startTime.TimeOfDay).Ticks* pixelsPerTick);

            // Return element size.
            return new Rect(xPos, yPos, width, height + ANTI_ALIASING_GAP);
        }

        #endregion

        #region Private Constants

        /// <summary>
        /// Radius of rounded rectangle.
        /// </summary>
        private const int ROUND_RADIUS = 3;

        /// <summary>
        /// Gap in 1 pixel to correct anti-aliasing.
        /// </summary>
        private const int ANTI_ALIASING_GAP = 1;

        #endregion

        #region Private fields

        /// <summary>
        /// Parent gantt item.
        /// </summary>
        private IGanttItem _parent;

        /// <summary>
        /// Start time.
        /// </summary>
        private DateTime _startTime;

        /// <summary>
        /// End time.
        /// </summary>
        private DateTime _endTime;

        #endregion
    }
}


text:
package UI;

import UI.tabControls.ControlTab;
import UI.tabControls.PathTab;
import UI.tabControls.PointTab;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.layout.Pane;

import java.io.IOException;

/**
 * Initializes the tab pane and all UI controls.
 * <p/>
 * Created by CyberPuck on 2016-02-21.
 */
public class TabController {
    private TabPane tabPane;
    // needed for getting UI to startup simulator
    private SimulatorController controller;
    // List of controllers, this enables the simulation to update the UI
    private ControlTab control;
    private PathTab path;
    private PointTab point;

    public TabController(TabPane tabPane, SimulatorController controller) {
        this.tabPane = tabPane;
        this.controller = controller;
    }

    public void init() {
        // Add the control tab (part 1)
        Tab controlTab = new Tab();
        controlTab.setText("Control");
        // load the FXML
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("controlPane.fxml"));
        try {
            Pane testPane = fxmlLoader.load();
            controlTab.setContent(testPane);
            tabPane.getTabs().add(controlTab);
            // add the controller
            fxmlLoader.<ControlTab>getController().setController(controller);
            control = fxmlLoader.getController();
        } catch (IOException e) {
            System.err.println("Failed to load control tab pane");
        }

        // Add point tab
        Tab pointTab = new Tab();
        pointTab.setText("Point");
        fxmlLoader = new FXMLLoader(getClass().getResource("pointPane.fxml"));
        try {
            Pane testPane = fxmlLoader.load();
            pointTab.setContent(testPane);
            tabPane.getTabs().add(pointTab);
            fxmlLoader.<PointTab>getController().setController(controller);
            point = fxmlLoader.getController();
        } catch (IOException e) {
            System.err.println("Failed to load point tab pane");
        }

        // Add path tab
        Tab pathTab = new Tab();
        pathTab.setText("Path");
        fxmlLoader = new FXMLLoader(getClass().getResource("pathPane.fxml"));
        try {
            Pane testPane = fxmlLoader.load();
            pathTab.setContent(testPane);
            tabPane.getTabs().add(pathTab);
            // add the controller
            fxmlLoader.<PathTab>getController().setController(controller);
            path = fxmlLoader.getController();
        } catch (IOException e) {
            System.err.println("Failed to load path tab pane");
        }
    }

    public void updateUIs() {
        control.update();
        point.update();
        path.update();
    }
}


text:
<?php defined('BX_DOL') or die('hack attempt');

bx_import('BxDolForm');

class BxDolSearchExtended extends BxDolFactory implements iBxDolFactoryObject
{
    public static $SEARCHABLE_TYPES = array(
        'text', 'textarea', 'number',
        'select', 'radio_set',
        'checkbox_set', 'select_multiple',
        'checkbox', 'switcher',
        'datepicker', 'datetime',
        'location'
    );

    public static $TYPE_TO_TYPE_SEARCH = array(
        'text' => array('text'),
        'textarea' => array('text'),
        'number' => array('text'),
        'text_auto' => array('text_auto'),
        'select' => array('checkbox_set', 'select_multiple', 'select'),
        'radio_set' => array('checkbox_set', 'select_multiple', 'select'),
        'checkbox_set' => array('checkbox_set', 'select_multiple', 'select'),
        'select_multiple' => array('checkbox_set', 'select_multiple', 'select'),
        'checkbox' => array('checkbox', 'switcher'),
        'switcher' => array('checkbox', 'switcher'),
        'datepicker' => array('datepicker_range', 'datepicker_range_age'),
        'datetime' => array('datetime_range', 'datetime_range_age'),
        'location' => array('location')
    );

    public static $TYPE_TO_OPERATOR = array(
        'text' => array('like', '='),
        'textarea' => array('like', '='),
        'number' => array('='),
        'text_auto' => array('in'),
        'select' => array('in'),
        'radio_set' => array('in'),
        'checkbox_set' => array('and'),
        'select_multiple' => array('and'),
        'checkbox' => array('='),
        'switcher' => array('='),
    	'datepicker' => array('between'),
    	'datetime' => array('between'),
        'location' => array('locate')
    );

    protected $_oDb;

    protected $_sObject;
    protected $_aObject;

    /**
     * Constructor
     * @param $aObject array of search options
     */
    protected function __construct($aObject)
    {
        parent::__construct();

        $this->_oDb = new BxDolSearchExtendedQuery($this->_aObject);

        $this->_sObject = $aObject['object'];
        $this->_aObject = $aObject;
    }

    /**
     * Get editor object instance by object name
     * @param $sObject object name
     * @return object instance or false on error
     */
    static public function getObjectInstance($sObject, $oTemplate = false)
    {
        if(isset($GLOBALS['bxDolClasses']['BxDolSearchExtended!' . $sObject]))
            return $GLOBALS['bxDolClasses']['BxDolSearchExtended!' . $sObject];

        $aObject = BxDolSearchExtendedQuery::getSearchObject($sObject);
        if(!$aObject || !is_array($aObject))
            return false;

        $sClass = 'BxTemplSearchExtended';
        if(!empty($aObject['class_name'])) {
            $sClass = $aObject['class_name'];
            if(!empty($aObject['class_file']))
                require_once(BX_DIRECTORY_PATH_ROOT . $aObject['class_file']);
        }

        $o = new $sClass($aObject, $oTemplate);
        return ($GLOBALS['bxDolClasses']['BxDolSearchExtended!' . $sObject] = $o);
    }

    static public function actionGetAuthors()
    {
        $aResult = BxDolService::call('system', 'profiles_search', array(bx_get('term')), 'TemplServiceProfiles');

        header('Content-Type:text/javascript; charset=utf-8');
        echo json_encode($aResult);
    }

    public function isEnabled()
    {
        return isset($this->_aObject['active']) && (int)$this->_aObject['active'] != 0;
    }

    public function clean()
    {
        return $this->_oDb->deleteFields(array('object' => $this->_sObject)) !== false;
    }

    public function reset()
    {
        if(!$this->clean())
            return false;

        $this->_aObject['fields'] = BxDolSearchExtendedQuery::getSearchFields($this->_aObject);
        return true;
    }
}

/** @} */


text:
namespace content {

namespace {

class PepperFileChooserHostTest : public RenderViewTest {
 public:
  PepperFileChooserHostTest()
      : pp_instance_(123456) {}

  virtual void SetUp() {
    SetContentClient(&client_);
    RenderViewTest::SetUp();
    ppapi::ProxyLock::DisableLockingOnThreadForTest();

    globals_.GetResourceTracker()->DidCreateInstance(pp_instance_);
  }
  virtual void TearDown() {
    globals_.GetResourceTracker()->DidDeleteInstance(pp_instance_);

    RenderViewTest::TearDown();
  }

  PP_Instance pp_instance() const { return pp_instance_; }

 private:
  PP_Instance pp_instance_;

  ppapi::TestGlobals globals_;
  TestContentClient client_;
};

// For testing to convert our hardcoded file paths to 8-bit.
std::string FilePathToUTF8(const base::FilePath::StringType& path) {
#if defined(OS_WIN)
  return UTF16ToUTF8(path);
#else
  return path;
#endif
}

}  // namespace

TEST_F(PepperFileChooserHostTest, Show) {
  PP_Resource pp_resource = 123;

  MockRendererPpapiHost host(view_, pp_instance());
  PepperFileChooserHost chooser(&host, pp_instance(), pp_resource);

  // Say there's a user gesture.
  host.set_has_user_gesture(true);

  std::vector<std::string> accept;
  accept.push_back("text/plain");
  PpapiHostMsg_FileChooser_Show show_msg(false, false, std::string(), accept);

  ppapi::proxy::ResourceMessageCallParams call_params(pp_resource, 0);
  ppapi::host::HostMessageContext context(call_params);
  int32 result = chooser.OnResourceMessageReceived(show_msg, &context);
  EXPECT_EQ(PP_OK_COMPLETIONPENDING, result);

  // The render view should have sent a chooser request to the browser
  // (caught by the render thread's test message sink).
  const IPC::Message* msg = render_thread_->sink().GetUniqueMessageMatching(
      ViewHostMsg_RunFileChooser::ID);
  ASSERT_TRUE(msg);
  ViewHostMsg_RunFileChooser::Schema::Param call_msg_param;
  ASSERT_TRUE(ViewHostMsg_RunFileChooser::Read(msg, &call_msg_param));
  const FileChooserParams& chooser_params = call_msg_param.a;

  // Basic validation of request.
  EXPECT_EQ(FileChooserParams::Open, chooser_params.mode);
  ASSERT_EQ(1u, chooser_params.accept_types.size());
  EXPECT_EQ(accept[0], UTF16ToUTF8(chooser_params.accept_types[0]));

  // Send a chooser reply to the render view. Note our reply path has to have a
  // path separator so we include both a Unix and a Windows one.
  ui::SelectedFileInfo selected_info;
  selected_info.display_name = FILE_PATH_LITERAL("Hello, world");
  selected_info.local_path = base::FilePath(FILE_PATH_LITERAL("myp\\ath/foo"));
  std::vector<ui::SelectedFileInfo> selected_info_vector;
  selected_info_vector.push_back(selected_info);
  RenderViewImpl* view_impl = static_cast<RenderViewImpl*>(view_);
  ViewMsg_RunFileChooserResponse response(view_impl->routing_id(),
                                          selected_info_vector);
  EXPECT_TRUE(view_impl->OnMessageReceived(response));

  // This should have sent the Pepper reply to our test sink.
  ppapi::proxy::ResourceMessageReplyParams reply_params;
  IPC::Message reply_msg;
  ASSERT_TRUE(host.sink().GetFirstResourceReplyMatching(
      PpapiPluginMsg_FileChooser_ShowReply::ID, &reply_params, &reply_msg));

  // Basic validation of reply.
  EXPECT_EQ(call_params.sequence(), reply_params.sequence());
  EXPECT_EQ(PP_OK, reply_params.result());
  PpapiPluginMsg_FileChooser_ShowReply::Schema::Param reply_msg_param;
  ASSERT_TRUE(PpapiPluginMsg_FileChooser_ShowReply::Read(&reply_msg,
                                                         &reply_msg_param));
  const std::vector<ppapi::FileRefCreateInfo>& chooser_results =
      reply_msg_param.a;
  ASSERT_EQ(1u, chooser_results.size());
  EXPECT_EQ(FilePathToUTF8(selected_info.display_name),
            chooser_results[0].display_name);
}

TEST_F(PepperFileChooserHostTest, NoUserGesture) {
  PP_Resource pp_resource = 123;

  MockRendererPpapiHost host(view_, pp_instance());
  PepperFileChooserHost chooser(&host, pp_instance(), pp_resource);

  // Say there's no user gesture.
  host.set_has_user_gesture(false);

  std::vector<std::string> accept;
  accept.push_back("text/plain");
  PpapiHostMsg_FileChooser_Show show_msg(false, false, std::string(), accept);

  ppapi::proxy::ResourceMessageCallParams call_params(pp_resource, 0);
  ppapi::host::HostMessageContext context(call_params);
  int32 result = chooser.OnResourceMessageReceived(show_msg, &context);
  EXPECT_EQ(PP_ERROR_NO_USER_GESTURE, result);
}

}  // namespace content


text:
package flags

const (
	ApiVersionLongName    = "version"
	ApiVersionShortName   = "v"
	ApiVersionDefault     = "2.13"
	ApiVersionDescription = "[Optional] The version number of OSB API the request will use."
	BrokerLongName        = "broker"
	BrokerShortName       = "b"
	HostLongName          = "host"
	HostBrokerDefault     = "https://servicebroker.googleapis.com"
	ProjectLongName       = "project"
	ProjectShortName      = "p"
	ServerLongName        = "server"
	ServerShortName       = "s"
)


text:
var fs = require('fs-extra');
var path = require('path');
var vision = require('@google-cloud/vision')({
	keyFilename: './key.json',
	projectId: 'MyCamera'
});

var imageFile = "./stream/image.jpg";

function AnalyzeImage(imageFile,callback) {
	return new Promise(function(resolve,reject) {
		vision.detect(imageFile, [
			"crops",
			"document",
			"faces",
			"landmarks",
			"labels",
			"logos",
			"properties",
			"safeSearch",
			"similar",
			"text"
		],
		function(err, info, resp) {
			if (err) reject(err);
			resolve(info);
		});
	})
}

/*
console.log("Checking with google machine...");
AnalyzeImage('./kittens.jpg').then(info => {
	console.log("Got something back!");
	console.log(JSON.stringify(info,null,2));
}).catch(err => {
	console.dir(err);
})
*/

module.exports.AnalyzeImage = AnalyzeImage;


text:
package com.dangdang.ddframe.rdb.sharding.jdbc.adapter;

import com.dangdang.ddframe.rdb.sharding.jdbc.unsupported.AbstractUnsupportedOperationConnection;
import com.dangdang.ddframe.rdb.sharding.metrics.MetricsContext;
import com.dangdang.ddframe.rdb.sharding.util.SQLUtil;
import com.dangdang.ddframe.rdb.sharding.util.ThrowableSQLExceptionMethod;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.util.Collection;

/**
 * 数据库连接适配类.
 *
 * @author zhangliang
 */
public abstract class AbstractConnectionAdapter extends AbstractUnsupportedOperationConnection {

    private boolean autoCommit = true;

    private boolean readOnly = true;

    private boolean closed;

    private int transactionIsolation = TRANSACTION_READ_UNCOMMITTED;

    protected abstract Collection<Connection> getConnections();

    @Override
    public final boolean getAutoCommit() throws SQLException {
        return autoCommit;
    }

    @Override
    public final void setAutoCommit(final boolean autoCommit) throws SQLException {
        this.autoCommit = autoCommit;
        if (getConnections().isEmpty()) {
            recordMethodInvocation(Connection.class, "setAutoCommit", new Class[] {boolean.class}, new Object[] {autoCommit});
            return;
        }
        for (Connection each : getConnections()) {
            each.setAutoCommit(autoCommit);
        }
    }

    @Override
    public final void commit() throws SQLException {
        for (Connection each : getConnections()) {
            each.commit();
        }
    }

    @Override
    public final void rollback() throws SQLException {
        SQLUtil.safeInvoke(getConnections(), new ThrowableSQLExceptionMethod<Connection>() {
            @Override
            public void apply(final Connection object) throws SQLException {
                object.rollback();
            }
        });
    }

    @Override
    public void close() throws SQLException {
        SQLUtil.safeInvoke(getConnections(), new ThrowableSQLExceptionMethod<Connection>() {
            @Override
            public void apply(final Connection object) throws SQLException {
                object.close();
            }
        });
        closed = true;
        MetricsContext.clear();
    }

    @Override
    public final boolean isClosed() throws SQLException {
        return closed;
    }

    @Override
    public final boolean isReadOnly() throws SQLException {
        return readOnly;
    }

    @Override
    public final void setReadOnly(final boolean readOnly) throws SQLException {
        this.readOnly = readOnly;
        if (getConnections().isEmpty()) {
            recordMethodInvocation(Connection.class, "setReadOnly", new Class[] {boolean.class}, new Object[] {readOnly});
            return;
        }
        for (Connection each : getConnections()) {
            each.setReadOnly(readOnly);
        }
    }

    @Override
    public final int getTransactionIsolation() throws SQLException {
        return transactionIsolation;
    }

    @Override
    public final void setTransactionIsolation(final int level) throws SQLException {
        transactionIsolation = level;
        if (getConnections().isEmpty()) {
            recordMethodInvocation(Connection.class, "setTransactionIsolation", new Class[] {int.class}, new Object[] {level});
            return;
        }
        for (Connection each : getConnections()) {
            each.setTransactionIsolation(level);
        }
    }

    // -------以下代码与MySQL实现保持一致.-------

    @Override
    public SQLWarning getWarnings() throws SQLException {
        return null;
    }

    @Override
    public void clearWarnings() throws SQLException {
    }

    @Override
    public final int getHoldability() throws SQLException {
        return ResultSet.CLOSE_CURSORS_AT_COMMIT;
    }

    @Override
    public final void setHoldability(final int holdability) throws SQLException {
    }
}


text:
package com.gregorbyte.designer.headless.socket;

import java.io.PrintWriter;

import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;

public class BuildJobChangeAdapter extends JobChangeAdapter {

	private PrintWriter writer;

	public BuildJobChangeAdapter(PrintWriter writer) {

		this.writer = writer;

	}

	@Override
	public void scheduled(IJobChangeEvent event) {

		if (event != null && event.getResult() != null && event.getResult().isOK())
			writer.println("BUILD JOB SCHEDULED");

		super.scheduled(event);
	}

	@Override
	public void aboutToRun(IJobChangeEvent event) {

		//writer.println("...BUILD JOB ABOUT TO RUN");
		super.aboutToRun(event);

	}

	@Override
	public void awake(IJobChangeEvent event) {

		writer.println("BUILD JOB AWAKE");
		super.awake(event);

	}

	@Override
	public void running(IJobChangeEvent event) {

		writer.println("BUILD JOB RUNNING");
		super.running(event);
	}

	@Override
	public void sleeping(IJobChangeEvent event) {

		writer.println("BUILD JOB SLEEPING");
		super.sleeping(event);

	}

	@Override
	public void done(IJobChangeEvent event) {

		if (event.getResult().isOK())
			writer.println("BUILD JOB STATUS: SUCCESS");
		else {
			writer.println("BUILD JOB STATUS: FAIL");
			writer.println(event.getResult().getMessage() + event.getResult().getCode());
			if (event.getResult().getException() != null) {
				writer.println(event.getResult().getException().getMessage());
			}

		}

		super.done(event);
	}

}


text:
The Observer Pattern is a kind of behavior pattern which is concerned with the assignment of responsibilities between objects.
This pattern defines a one-to-many dependency between objects so that when one object changes state,
all its dependents are notified and updated automatically. The key objects in this pattern are subject and observer.
A subject may have any number of dependent observers.
All observers are notified whenever the subject undergoes a change in its state.

## Java's built-in Observer Pattern
Java has built-in support for the Observer Pattern.
The most general is the Observer interface and the Observable class in the java.util package.

## How to use it?
In this example we build the Observer pattern without using built-in support but it can be easily changed
with minimal effort. So lets start with `Subject.java` interface - it defines interface for subscribing and unsubscribing listeners.
The `Observer.java` interface defines interface of listener. Method `update` is called by the subject(`observable object`)
in order to notify it when there is a change in the state of the subject. Check the file `CommentaryObject.java` it
includes the concrete implementation of observable object(`subject`). `SMSUser.java` it is concrete
listener which implements the Observer interface. Finally, check our example `ExampleObserverPattern.java` -
during the demo, in runtime, we removed one and added more listeners to existing subject(`observable object`).

## When to use the Observer
1. When a change to one object requires changing others, and you don't know how many objects need to be changed.
2. When an object should be able to notify other objects without making assumptions about who these objects are.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Anaptychia speciosa f. angustata Nádv.

### Remarks
null


text:
package sagan.support.github;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.util.UriTemplate;

public class StubGithubRestClient extends GitHubClient {

    private Map<String, String> responseMap = new HashMap<>();

    public StubGithubRestClient() {
        super(null, null);
    }

    public void putResponse(String url, String response) {
        responseMap.put(url, response);
    }

    public void clearResponses() {
        responseMap.clear();
    }

    @Override
    public String sendRequestForJson(String path, Object... uriVariables) {
        return handleRequest(path, uriVariables);
    }

    @Override
    public String sendRequestForHtml(String path, Object... uriVariables) {
        return handleRequest(path, uriVariables);
    }

    @Override
    public String sendPostRequestForHtml(String path, String body, Object... uriVariables) {
        return "
HTML
";
    }

    private String handleRequest(String path, Object[] uriVariables) {
        String url = new UriTemplate(path).expand(uriVariables).getPath();
        if (!responseMap.containsKey(url)) {
            throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "no response for: " + url);
        }
        return responseMap.get(url);
    }
}


text:
"""A simple script to download existing Facilities in Data Commons."""

import os
import pathlib

import datacommons
import pandas as pd

from absl import app
from absl import flags

FLAGS = flags.FLAGS

flags.DEFINE_string('output_path', 'tmp_data', 'Output directory')

def main(_):
    assert FLAGS.output_path
    pathlib.Path(FLAGS.output_path).mkdir(exist_ok=True)
    out_file = os.path.join(FLAGS.output_path, 'existing_facilities.csv')

    q = "SELECT DISTINCT ?dcid WHERE {?a typeOf EpaReportingFacility . ?a dcid ?dcid }"
    res = datacommons.query(q)

    facility_ids = []
    for facility in res:
        facility_ids.append(facility["?dcid"])

    df = pd.DataFrame.from_dict({"epaGhgrpFacilityId": facility_ids})
    df.to_csv(out_file, mode="w", header=True, index=False)

if __name__ == '__main__':
    app.run(main)


text:
REM invoke AwsWinSysOps_Config.bat to initialize all variables
call %~dp0\AwsWinSysOps_Config.bat

REM configure scripts folder location
set scriptsFolder=%baseFolder%\AmazonCloudWatchMonitoringWindows

REM execute mon-put-metrics-mem.ps1
Powershell.exe -ExecutionPolicy ByPass -command "'--> ' + $env:COMPUTERNAME + ' / mon-put-metrics-mem.ps1 / ' + (Get-Date).ToUniversalTime() | out-file -filepath %logFile% -append"
Powershell.exe -ExecutionPolicy ByPass -command "%scriptsFolder%\mon-put-metrics-mem.ps1 -aws_credential_file %baseFolder%\awscreds.conf -mem_util -mem_used -mem_avail -page_avail -page_used -page_util -memory_units Megabytes -from_scheduler -logfile %logFile%"

REM execute mon-put-metrics-disk.ps1
Powershell.exe -ExecutionPolicy ByPass -command "'--> ' + $env:COMPUTERNAME + ' / mon-put-metrics-disk.ps1 / ' + (Get-Date).ToUniversalTime() | out-file -filepath %logFile% -append"
Powershell.exe -ExecutionPolicy ByPass -command "%scriptsFolder%\mon-put-metrics-disk.ps1 -aws_credential_file %baseFolder%\awscreds.conf -disk_drive C:,D:,E:,F:,G: -disk_space_util -disk_space_used -disk_space_avail -disk_space_units Gigabytes -from_scheduler -logfile %logFile%"

REM execute mon-put-metrics-perfmon.ps1
Powershell.exe -ExecutionPolicy ByPass -command "'--> ' + $env:COMPUTERNAME + ' / mon-put-metrics-perfmon.ps1 / ' + (Get-Date).ToUniversalTime() | out-file -filepath %logFile% -append"
Powershell.exe -ExecutionPolicy ByPass -command "%scriptsFolder%\mon-put-metrics-perfmon.ps1 -aws_credential_file %baseFolder%\awscreds.conf -pages_input -processor_queue -from_scheduler -logfile %logFile%"

REM configure scripts folder location
set scriptsFolder=%baseFolder%\Scripts

REM execute mon-windows-services.ps1
Powershell.exe -ExecutionPolicy ByPass -command "'--> ' + $env:COMPUTERNAME + ' / mon-windows-services.ps1 / ' + (Get-Date).ToUniversalTime() | out-file -filepath %logFile% -append"
Powershell.exe -ExecutionPolicy ByPass -command "%scriptsFolder%\mon-windows-services.ps1 -aws_credential_file %baseFolder%\awscreds.conf  -service_name_filter '*' -from_scheduler -logfile %logFile%"


text:
Unit tests can be added for your App.

1.  After creating a new App using the `rab init AppName` command.
    1.  You will notice that there are a few new files when the app is created.
    2.  The package.json file is used to make your app a local node application.
    3.  The Gruntfile.js file holds the instructions for how to test your app.
2.  Install local dependencies for the testing environment using `npm install`.
3.  Run the example test using `grunt`.


text:
package com.google.security.zynamics.binnavi.Gui.CodeBookmarks;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import com.google.security.zynamics.binnavi.Gui.CodeBookmarks.CCodeBookmarkTableModel;
import com.google.security.zynamics.binnavi.disassembly.Modules.MockModule;
import com.google.security.zynamics.binnavi.models.Bookmarks.code.CCodeBookmark;
import com.google.security.zynamics.binnavi.models.Bookmarks.code.CCodeBookmarkManager;
import com.google.security.zynamics.zylib.disassembly.MockAddress;
import com.google.security.zynamics.zylib.reflection.ReflectionHelpers;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.util.LinkedHashSet;

@RunWith(JUnit4.class)
public class CCodeBookmarkTableModelTest {
  @Test
  public void test1Simple() {
    final CCodeBookmarkManager bookmarkManager = new CCodeBookmarkManager();
    final CCodeBookmarkTableModel tableModel = new CCodeBookmarkTableModel(bookmarkManager);

    assertEquals(3, tableModel.getColumnCount());
    assertEquals(0, tableModel.getRowCount());
  }

  @Test
  public void test2setValueAtWorking() {
    final CCodeBookmarkManager bookmarkManager = new CCodeBookmarkManager();
    final CCodeBookmarkTableModel tableModel = new CCodeBookmarkTableModel(bookmarkManager);

    final CCodeBookmark bookmark = new CCodeBookmark(new MockModule(), new MockAddress(), "burzel");
    bookmarkManager.addBookmark(bookmark);

    assertEquals("burzel", tableModel.getValueAt(0, 2));

    tableModel.setValueAt("working", 0, 2);

    assertEquals(1, tableModel.getRowCount());
    assertEquals("working", tableModel.getValueAt(0, 2));
  }

  @Test
  public void test3setValueAtFail() {
    final CCodeBookmarkManager bookmarkManager = new CCodeBookmarkManager();
    final CCodeBookmarkTableModel tableModel = new CCodeBookmarkTableModel(bookmarkManager);

    final CCodeBookmark bookmark = new CCodeBookmark(new MockModule(), new MockAddress(), "burzel");
    bookmarkManager.addBookmark(bookmark);

    assertEquals("burzel", tableModel.getValueAt(0, 2));

    try {
      tableModel.setValueAt("working", 0, 1);
      fail();
    } catch (final IllegalArgumentException e) {
    }
  }

  @Test
  public void test4getValueAtWorking() {
    final CCodeBookmarkManager bookmarkManager = new CCodeBookmarkManager();
    final CCodeBookmarkTableModel tableModel = new CCodeBookmarkTableModel(bookmarkManager);

    final CCodeBookmark bookmark =
        new CCodeBookmark(new MockModule(), new MockAddress(), "burzel");
    bookmarkManager.addBookmark(bookmark);

    final MockAddress mock = new MockAddress();

    assertEquals("burzel", tableModel.getValueAt(0, 2));
    assertEquals(mock.toHexString(), tableModel.getValueAt(0, 1));
    assertEquals("Mock Module", tableModel.getValueAt(0, 0));
  }

  @Test
  public void test5getValueAtFail() {
    final CCodeBookmarkManager bookmarkManager = new CCodeBookmarkManager();
    final CCodeBookmarkTableModel tableModel = new CCodeBookmarkTableModel(bookmarkManager);

    final CCodeBookmark bookmark =
        new CCodeBookmark(new MockModule(), new MockAddress(), "burzel");
    bookmarkManager.addBookmark(bookmark);

    try {
      tableModel.getValueAt(0, 4);
      fail();
    } catch (final IllegalArgumentException e) {
    }
  }

  @Test
  public void test6getColumnName() {
    final CCodeBookmarkManager bookmarkManager = new CCodeBookmarkManager();
    final CCodeBookmarkTableModel tableModel = new CCodeBookmarkTableModel(bookmarkManager);

    final CCodeBookmark bookmark =
        new CCodeBookmark(new MockModule(), new MockAddress(), "burzel");
    bookmarkManager.addBookmark(bookmark);

    assertEquals("Module", tableModel.getColumnName(0));
    assertEquals("Address", tableModel.getColumnName(1));
    assertEquals("Description", tableModel.getColumnName(2));
  }

  @Test
  public void test7removeBookmarkWorking() {
    final CCodeBookmarkManager bookmarkManager = new CCodeBookmarkManager();
    final CCodeBookmarkTableModel tableModel = new CCodeBookmarkTableModel(bookmarkManager);

    final CCodeBookmark bookmark = new CCodeBookmark(new MockModule(), new MockAddress(), "burzel");
    bookmarkManager.addBookmark(bookmark);

    assertEquals("burzel", tableModel.getValueAt(0, 2));

    tableModel.setValueAt("working", 0, 2);

    assertEquals(1, tableModel.getRowCount());
    assertEquals("working", tableModel.getValueAt(0, 2));

    bookmarkManager.removeBookmark(bookmark);

    assertEquals(0, tableModel.getRowCount());
  }

  @Test
  public void test8checkEditable() {
    final CCodeBookmarkManager bookmarkManager = new CCodeBookmarkManager();
    final CCodeBookmarkTableModel tableModel = new CCodeBookmarkTableModel(bookmarkManager);

    final CCodeBookmark bookmark = new CCodeBookmark(new MockModule(), new MockAddress(), "burzel");
    bookmarkManager.addBookmark(bookmark);

    assertFalse(tableModel.isCellEditable(0, 0));
    assertFalse(tableModel.isCellEditable(0, 1));
    assertTrue(tableModel.isCellEditable(0, 2));
  }

  @Test
  public void test9checkRemoveListeners() throws IllegalArgumentException, SecurityException,
      IllegalAccessException, NoSuchFieldException {
    final CCodeBookmarkManager bookmarkManager = new CCodeBookmarkManager();
    final CCodeBookmarkTableModel tableModel = new CCodeBookmarkTableModel(bookmarkManager);

    final LinkedHashSet<?> m_daListeners =
        (LinkedHashSet<?>) ReflectionHelpers.getField(
            ReflectionHelpers.getField(bookmarkManager, "m_listeners"), "m_listeners");

    assertEquals(1, m_daListeners.size());

    final CCodeBookmark bookmark = new CCodeBookmark(new MockModule(), new MockAddress(), "burzel");
    bookmarkManager.addBookmark(bookmark);

    final LinkedHashSet<?> m_bmListeners =
        (LinkedHashSet<?>) ReflectionHelpers.getField(
            ReflectionHelpers.getField(bookmark, "m_listeners"), "m_listeners");

    assertEquals(1, m_bmListeners.size());

    tableModel.dispose();

    assertTrue(m_daListeners.isEmpty());
    assertTrue(m_bmListeners.isEmpty());
  }
}


text:
render associative data from
[level-assoc](https://npmjs.org/package/level-assoc)
with [hyperkey](https://npmjs.org/package/hyperkey)
for live server+client rendering with progressive enhancement

# example

In the browser, just load [hyperkey](https://npmjs.org/package/hyperkey)
render modules and specify nested rendering sub-components. In this case,
each hackerspace has a nested collection of hackers:

``` js
var shoe = require('shoe');
var sock = shoe('/sock');
var rassoc = require('render-assoc');

var render = require('./render/hackerspace.js')();

render.pipe(sock).pipe(rassoc(render, {
    hacker: require('./render/hacker.js')
}));

render.appendTo('#hackerspaces');
```

The [associations](https://npmjs.org/package/level-assoc) on the server
server-side are:

``` js
var level = require('level-test')();
var sub = require('level-sublevel');
var db = sub(level('hyperkey-example.db', { valueEncoding: 'json' }));
var assoc = require('level-assoc')(db);

assoc.add('hackerspace')
    .hasMany('hackers', [ 'type', 'hacker' ])
    .hasMany('tools', [ 'type', 'tool' ])
;
assoc.add('hacker')
    .hasMany('projects', [ 'type', 'project' ])
    .hasMany('usage', [ 'type', 'usage' ])
;
assoc.add('tool')
    .hasMany('usage', [ 'type', 'usage' ])
;

module.exports = assoc;
```

we can write a simple server that uses `assoc.track()` to plumb up reactive live
updates over websockets:

``` js
var http = require('http');
var ecstatic = require('ecstatic')(__dirname + '/static');
var trumpet = require('trumpet');
var fs = require('fs');

var assoc = require('./data.js');
var render = require('./render/hackerspace.js');

var server = http.createServer(function (req, res) {
    if (req.url === '/') {
        var tr = trumpet();
        var q = assoc.list('hackerspace');

        var elem = tr.select('#hackerspaces');
        elem.setAttribute('data-start', q.startKey);
        elem.setAttribute('data-end', q.endKey);

        q.pipe(render()).pipe(elem.createWriteStream());
        readStream('index.html').pipe(tr).pipe(res);
    }
    else ecstatic(req, res);
});
server.listen(5000);

var shoe = require('shoe');
var sock = shoe(function (stream) {
    stream.pipe(assoc.track()).pipe(stream);
});
sock.install(server, '/sock');

function readStream (file) {
    return fs.createReadStream(__dirname + '/static/' + file);
}
```

And the shared [hyperkey](https://npmjs.org/package/hyperkey) rendering code and
html looks like:

``` html
<div class="hacker">
  <i class="name"></i>
</div>
```

``` js
var hyperkey = require('hyperkey');
var fs = require('fs');
var html = fs.readFileSync(__dirname + '/hacker.html');

module.exports = function () {
    return hyperkey(html, function (row) {
        return { '.name': row.name };
    });
};
```

``` html
<div class="hackerspace">
  <h1 class="name"></h1>
  <div class="hackers"></div>
</div>
```

``` js
var hyperkey = require('hyperkey');
var fs = require('fs');
var html = fs.readFileSync(__dirname + '/hackerspace.html');
var hacker = require('./hacker.js');

module.exports = function () {
    return hyperkey(html, function (row) {
        return {
            '.name': row.name,
            '.hackers': (function (stream) {
                return {
                    'data-start': stream.startKey,
                    'data-end': stream.endKey,
                    _html: stream.pipe(hacker())
                };
            })(row.hackers())
        };
    });
};
```

Compile the browser code with [browserify](http://browserify.org)
and [brfs](https://npmjs.org/package/brfs) and then your nested collections will
automatically update as the data changes on the server while preserving
server-side rendering!

# methods

``` js
var rassoc = require('render-assoc');
```

## rassoc(render, subRenderers)

Create a writable stream for `assoc.track()` data to be written to across a
websocket from a
[hyperkey](https://npmjs.org/package/hyperkey) `render` function and an object
of `subRenders` mapping assocation types to sub-collection render functions.

In a later release this will be more generalized to account for multiple render
targets through the same stream.

# install

With [npm](https://npmjs.org) do:

```
npm install render-assoc
```

# license

MIT


text:
package org.kuali.kfs.module.purap.businessobject;

import java.util.List;

import org.kuali.kfs.sys.KFSConstants;
import org.kuali.rice.krad.bo.Note;

/**
 * Requisition View Business Object.
 */
public class CorrectionReceivingView extends AbstractRelatedView {
    private String lineItemReceivingDocumentNumber;

    public String getLineItemReceivingDocumentNumber() {
        return lineItemReceivingDocumentNumber;
    }

    public void setLineItemReceivingDocumentNumber(String lineItemReceivingDocumentNumber) {
        this.lineItemReceivingDocumentNumber = lineItemReceivingDocumentNumber;
    }

    /**
     * The next three methods are overridden but shouldnt be! If they arent overridden, they dont show up in the tag, not sure why
     * at this point! (AAP)
     *
     * @see org.kuali.kfs.module.purap.businessobject.AbstractRelatedView#getPurapDocumentIdentifier()
     */
    @Override
    public Integer getPurapDocumentIdentifier() {
        return super.getPurapDocumentIdentifier();
    }

    @Override
    public String getDocumentIdentifierString() {
        return super.getDocumentIdentifierString();
    }

    /**
     * @see org.kuali.kfs.module.purap.businessobject.AbstractRelatedView#getNotes()
     */
    @Override
    public List<Note> getNotes() {
        return super.getNotes();
    }

    /**
     * @see org.kuali.kfs.module.purap.businessobject.AbstractRelatedView#getUrl()
     */
    @Override
    public String getUrl() {
        return super.getUrl();
    }

    /**
     * @see org.kuali.kfs.module.purap.businessobject.AbstractRelatedView#getDocumentTypeName()
     */
    @Override
    public String getDocumentTypeName() {
        return KFSConstants.FinancialDocumentTypeCodes.CORRECTION_RECEIVING;
    }

}


text:
package org.rythmengine.template;

/*-
 * #%L
 * Rythm Template Engine
 * %%
 * Copyright (C) 2017 - 2021 OSGL (Open Source General Library)
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

import org.rythmengine.Rythm;
import org.rythmengine.RythmEngine;
import org.rythmengine.conf.RythmConfiguration;
import org.rythmengine.extension.ICodeType;
import org.rythmengine.internal.compiler.TemplateClass;
import org.rythmengine.utils.Escape;
import org.rythmengine.utils.JSONWrapper;

import java.io.OutputStream;
import java.io.Writer;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedDeque;

/**
 * Define a template instance API
 */
public interface ITemplate extends ITag, Cloneable {

    /**
     * Return the engine instance that is running this template
     *
     * @return the {@link org.rythmengine.RythmEngine engine} instance
     */
    RythmEngine __engine();

    /**
     * Return the template class of this template instance
     *
     * @param useCaller if set to true then return caller template class if this template has no template class
     * @return the template class
     */
    TemplateClass __getTemplateClass(boolean useCaller);

    /**
     * Set binary output stream to the template instance.
     *
     * @param os
     * @throws NullPointerException  if os specified is null
     * @throws IllegalStateException if output stream or {@link #__setWriter(java.io.Writer) writer}
     *                               is already set
     * @return this template instance
     */
    ITemplate __setOutputStream(OutputStream os);

    /**
     * Set a character based writer to the template instance
     *
     * @param writer
     * @throws NullPointerException  if os specified is null
     * @throws IllegalStateException if {@link #__setOutputStream(java.io.OutputStream) output stream}
     *                               or writer is already set
     * @return this template instance
     */
    ITemplate __setWriter(Writer writer);

    /**
     * Set user context to the template instance
     *
     * @param userContext
     * @return this template instance
     */
    ITemplate __setUserContext(Map<String, Object> userContext);

    /**
     * Return user context previously set to this template instance.
     * if there is no user context has been set, then an empty Map is returned.
     *
     * @return the user context
     */
    Map<String, Object> __getUserContext();

    /**
     * Set renderArgs in name-value pair
     *
     * @param args
     * @return this template instance
     */
    ITemplate __setRenderArgs(Map<String, Object> args);

    /**
     * Set renderArgs in position
     *
     * @param args
     * @return this template instance
     */
    ITemplate __setRenderArgs(Object... args);

    /**
     * Set a render arg by name
     *
     * @param name
     * @param arg
     * @return this template instance
     */
    ITemplate __setRenderArg(String name, Object arg);

    /**
     * Return a render arg value by name
     *
     * @param name
     * @param <T>
     * @return render arg by name
     */
    <T> T __getRenderArg(String name);

    /**
     * Set a render arg by position
     *
     * @param position
     * @param arg
     * @return this template instance
     */
    ITemplate __setRenderArg(int position, Object arg);

    /**
     * Set renderArgs using JSON data
     *
     * @param jsonData
     * @return this template instance
     */
    ITemplate __setRenderArg(JSONWrapper jsonData);

    /**
     * Render the template and return result as String
     *
     * @return render result
     */
    String render();

    /**
     * Render the template and put the result into outputstream
     *
     * @param os
     */
    void render(OutputStream os);

    /**
     * Render the template and put the result into writer
     *
     * @param w
     */
    void render(Writer w);

    /**
     * Must be called before real render() happened.
     * Also if the template extends a parent template, then
     * the parent template's __init() must be called before this template's __init()
     */
    void __init();

    /**
     * Return the internal buffer
     *
     * @return buffer
     */
    StringBuilder __getBuffer();

    /**
     * Set secure code (for sandbox purpse)
     *
     * @param secureCode
     * @return this template
     */
    ITemplate __setSecureCode(String secureCode);

    /**
     * Get a copy of this template instance and pass in the engine and caller
     *
     * @param engine the rythm engine
     * @param caller the caller template
     * @return a cloned instance of this template class
     */
    ITemplate __cloneMe(RythmEngine engine, ITemplate caller);

    /**
     * (not API)
     * Return the current locale
     *
     * @return the locale
     */
    Locale __curLocale();

    /**
     * (not API)
     * Return the current escape scheme
     *
     * @return the escape
     */
    Escape __curEscape();

    /**
     * (not API)
     * Return current code type.
     *
     * @return current {@link org.rythmengine.extension.ICodeType type}
     */
    ICodeType __curCodeType();

    /**
     * The render time context. Not to be used in user application or template
     */
    public static class __Context {

        /**
         * Code type stack. Used to enable the
         * {@link org.rythmengine.conf.RythmConfigurationKey#FEATURE_NATURAL_TEMPLATE_ENABLED}
         *
         * @see {@link #localeStack}
         */
        private Deque<ICodeType> codeTypeStack = new ConcurrentLinkedDeque<ICodeType>();

        /**
         * template escape stack. Used to enable the
         * {@link org.rythmengine.conf.RythmConfigurationKey#FEATURE_SMART_ESCAPE_ENABLED}
         */
        private Deque<Escape> escapeStack = new ConcurrentLinkedDeque<Escape>();

        /**
         * template locale stack. Used to track the locale in the current context.
         */
        private Deque<Locale> localeStack = new ConcurrentLinkedDeque<Locale>();

        private TemplateBase tmpl;

        private RythmConfiguration conf;

        private void setTemplate(TemplateBase tmpl, RythmConfiguration conf) {
            this.tmpl = tmpl;
            this.conf = conf;
        }

        /**
         * init the context with template and base code type
         *
         * @param templateBase
         * @param type
         * @param locale
         */
        public void init(TemplateBase templateBase, ICodeType type, Locale locale, TemplateClass tc,  RythmEngine engine) {
            if (null == type) {
                type = engine.renderSettings.codeType();
                if (null == type) type = tc.codeType;
            }
            if (null == locale) {
                locale = engine.renderSettings.locale();
            }
            codeTypeStack.push(type);
            localeStack.push(locale);
            setTemplate(templateBase, engine.conf());
        }

        public ICodeType currentCodeType() {
            if (codeTypeStack.isEmpty()) {
                return conf.defaultCodeType();
            } else {
                return codeTypeStack.peek();
            }
        }

        public void pushCodeType(ICodeType type) {
            ICodeType cur = currentCodeType();
            if (null != cur) {
                type.setParent(cur);
            }
            codeTypeStack.push(type);
            Rythm.RenderTime.setCodeType(type);
        }

        public ICodeType popCodeType() {
            ICodeType cur = codeTypeStack.pop();
            cur.setParent(null);
            return cur;
        }

        public Locale currentLocale() {
            if (localeStack.isEmpty()) {
                return conf.locale();
            } else {
                return localeStack.peek();
            }
        }

        public void pushLocale(Locale locale) {
            localeStack.push(locale);
        }

        public Locale popLocale() {
            return localeStack.pop();
        }

        public Escape currentEscape() {
            if (!escapeStack.isEmpty()) {
                return escapeStack.peek();
            } else {
                return currentCodeType().escape();
            }
        }

        public void pushEscape(Escape escape) {
            escapeStack.push(escape);
            Rythm.RenderTime.setEscape(escape);
        }

        public Escape popEscape() {
            return escapeStack.pop();
        }

        public __Context() {
            //codeTypeStack = new Stack<ICodeType>();
            //escapeStack = new Stack<Escape>();
            //localeStack = new Stack<Locale>();
//            codeTypeStack.addAll(clone.codeTypeStack);
//            escapeStack.addAll(clone.escapeStack);
//            localeStack.addAll(clone.localeStack);
//            setTemplate(tmpl, conf);
        }
    }

}


text:
title: "Ampumapäällikkökilpailu 2006"
date: "2006-04-22"
tags: [ampumapäällikkö]
gallery:
  - thb: "/assets/blog/ampumapaallikko-2006/Thumbnails/luokittelematonampumapaallikko2006_01b.jpg"
    img: "/assets/blog/ampumapaallikko-2006/luokittelematonampumapaallikko2006_01b.jpg"
  - thb: "/assets/blog/ampumapaallikko-2006/Thumbnails/luokittelematonampumapaallikko2006_02b.jpg"
    img: "/assets/blog/ampumapaallikko-2006/luokittelematonampumapaallikko2006_02b.jpg"
  - thb: "/assets/blog/ampumapaallikko-2006/Thumbnails/luokittelematonampumapaallikko2006_03b.jpg"
    img: "/assets/blog/ampumapaallikko-2006/luokittelematonampumapaallikko2006_03b.jpg"
  - thb: "/assets/blog/ampumapaallikko-2006/Thumbnails/luokittelematonampumapaallikko2006_04b.jpg"
    img: "/assets/blog/ampumapaallikko-2006/luokittelematonampumapaallikko2006_04b.jpg"
  - thb: "/assets/blog/ampumapaallikko-2006/Thumbnails/luokittelematonampumapaallikko2006_05b.jpg"
    img: "/assets/blog/ampumapaallikko-2006/luokittelematonampumapaallikko2006_05b.jpg"
  - thb: "/assets/blog/ampumapaallikko-2006/Thumbnails/luokittelematonampumapaallikko2006_06b.jpg"
    img: "/assets/blog/ampumapaallikko-2006/luokittelematonampumapaallikko2006_06b.jpg"
  - thb: "/assets/blog/ampumapaallikko-2006/Thumbnails/luokittelematonampumapaallikko2006_07b.jpg"
    img: "/assets/blog/ampumapaallikko-2006/luokittelematonampumapaallikko2006_07b.jpg"
  - thb: "/assets/blog/ampumapaallikko-2006/Thumbnails/luokittelematonampumapaallikko2006_08b.jpg"
    img: "/assets/blog/ampumapaallikko-2006/luokittelematonampumapaallikko2006_08b.jpg"
  - thb: "/assets/blog/ampumapaallikko-2006/Thumbnails/luokittelematonampumapaallikko2006_09b.jpg"
    img: "/assets/blog/ampumapaallikko-2006/luokittelematonampumapaallikko2006_09b.jpg"
  - thb: "/assets/blog/ampumapaallikko-2006/Thumbnails/luokittelematonampumapaallikko2006_10b.jpg"
    img: "/assets/blog/ampumapaallikko-2006/luokittelematonampumapaallikko2006_10b.jpg"
  - thb: "/assets/blog/ampumapaallikko-2006/Thumbnails/luokittelematonampumapaallikko2006_11b.jpg"
    img: "/assets/blog/ampumapaallikko-2006/luokittelematonampumapaallikko2006_11b.jpg"
  - thb: "/assets/blog/ampumapaallikko-2006/Thumbnails/luokittelematonampumapaallikko2006_12b.jpg"
    img: "/assets/blog/ampumapaallikko-2006/luokittelematonampumapaallikko2006_12b.jpg"
  - thb: "/assets/blog/ampumapaallikko-2006/Thumbnails/luokittelematonampumapaallikko2006_13b.jpg"
    img: "/assets/blog/ampumapaallikko-2006/luokittelematonampumapaallikko2006_13b.jpg"
  - thb: "/assets/blog/ampumapaallikko-2006/Thumbnails/luokittelematonampumapaallikko2006_14b.jpg"
    img: "/assets/blog/ampumapaallikko-2006/luokittelematonampumapaallikko2006_14b.jpg"
  - thb: "/assets/blog/ampumapaallikko-2006/Thumbnails/luokittelematonampumapaallikko2006_15b.jpg"
    img: "/assets/blog/ampumapaallikko-2006/luokittelematonampumapaallikko2006_15b.jpg"
  - thb: "/assets/blog/ampumapaallikko-2006/Thumbnails/luokittelematonampumapaallikko2006_16b.jpg"
    img: "/assets/blog/ampumapaallikko-2006/luokittelematonampumapaallikko2006_16b.jpg"
---

Vuoden 2006 Ampumapäällikkökilpailu ammuttiin tutussa maastossa Halkian
ampumaradalla. Sää suosi toimintaa viileänä, muttei liian sateisena.
Tänä vuonna kisattiin kolmessa lajissa, jotka olivat Kainalo-trap,
pikahaulikko ja hirvikivääri. Mestaruus ratkaistiin edellä mainittujen
kolmen lajin yhteissijoitusten perusteella. Kisaajia oli paikalle
saapunut kiitettävästi 10, joiden joukossa Pasi, joka "[tuli paikalle
värikkäissä varusteissa. Rikkikin
olivat...](/uutisia-joita-yha-odotetaan/)"

Ampumapäällikkö 2006 kolmen kärki

1.  Jappe
2.  Passe
3.  Kimmo


text:
/********************************************************************************
 * 8080 Pseudo-Instruction Set Object for the 8080 Assembler			*
 * Pramuka Perera								*
 * 26 July, 2017								*
 * 8080's assembler level instructions:						*
 * Pseudo-instructions help the assembler put the program into the computer	*
 ********************************************************************************/

#ifndef INCLUDE
	#include <stdlib.h>
	#include <stdio.h>
	#include <stdint.h>
	#include <string.h>
	#include "common.h"

	#define INCLUDE
#endif

//#define NO_PSEUDO_FOUND (-1)
//#define	ORG		  0
//#define	EQU		  1
//#define END		  2

#define NUM_PSEUDO	  5	//# of available pseudo-instructions

typedef struct pseudo_instruction_data
{
	char *mnemonic;
	pseudo_identifier identifier;
}
pseudo_data;

pseudo_data pseudo_instruction_set[NUM_PSEUDO] =
{
	{"org", ORG},
	{"equ", EQU},
	{"db" ,  DB},
	{"dw" ,  DW},
	{"end", END}
};

//finds pseudo-instruction in the line and replaces it with whitespace
//returns an value identifying the pseudo-instruction
pseudo_identifier FindPseudoInstruction(char *line)
{
	int 	i,j,k,
		line_length,
		pseudo_length;
	pseudo_data 	p;

	line_length = strlen(line);

	//iterate through pseudo_instruction_set
	for(i = 0; i< NUM_PSEUDO; i++)
	{
		p = pseudo_instruction_set[i];
		pseudo_length = strlen(p.mnemonic);

		//iterate through line
		for(j = 0; pseudo_length + j <= line_length; j++)
		{
			if(strncmp(p.mnemonic, line + j, pseudo_length) == MATCH)
			{
				//check that matching part of line is not within another word (ex. "ORG" in "ORGAN")
				if(strlen(line + j) > pseudo_length)
				{
					if(line[j + pseudo_length] == ' '
					|| line[j + pseudo_length] == TAB
					|| line[j + pseudo_length] == '\a')
					{
						for(k = j; k < j + pseudo_length; k++)
						{
							line[k] = ' ';
						}
						return p.identifier;
					}
				}
				else
				{
					return p.identifier;
				}
			}
		}
	}

	return NO_PSEUDO_FOUND;
}


text:
@interface GlanceController()

@property (weak, nonatomic) IBOutlet WKInterfaceImage *image;
@property (weak, nonatomic) IBOutlet WKInterfaceLabel *label;
@property (weak, nonatomic) IBOutlet WKInterfaceLabel *titleLabel;

@end

@implementation GlanceController

- (void)awakeWithContext:(id)context {
    [super awakeWithContext:context];

    // Configure interface objects here.

    CGFloat width = self.contentFrame.size.width;
    CGFloat height = self.contentFrame.size.height;

    JYGraphView *graphView = [[JYGraphView alloc] initWithFrame:CGRectMake(0, 0, width, height)];

    graphView.graphData = @[@10,@11,@14,@13,@15,@18];
    graphView.useCurvedLine = YES;
    graphView.hidePoints = YES;
    graphView.backgroundViewColor = [UIColor clearColor];
    graphView.barColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.1];
    graphView.labelBackgroundColor = [UIColor clearColor];
    graphView.labelFont = [UIFont systemFontOfSize:18];
    graphView.strokeWidth = 4;

    [graphView plotGraphData];

    [_image setImage:[graphView graphImage]];

    [self.label setText:@"\u00B0C - Next 6 hours"];

    [self.titleLabel setText:@"11\u00B0C"];
}

- (void)willActivate {
    // This method is called when watch view controller is about to be visible to user
    [super willActivate];

}

- (void)didDeactivate {
    // This method is called when watch view controller is no longer visible
    [super didDeactivate];
}

@end


text:
require 'rails_helper'

describe TopTopic do

  it { is_expected.to belong_to :topic }

  context "refresh!" do

    let!(:t1) { Fabricate(:topic) }
    let!(:t2) { Fabricate(:topic) }

    it "begins blank" do
      expect(TopTopic.all).to be_blank
    end

    context "after calculating" do

      before do
        TopTopic.refresh!
      end

      it "should have top topics" do
        expect(TopTopic.pluck(:topic_id)).to match_array([t1.id, t2.id])
      end

    end

  end

end


text:
/**
 * layout.js
 * ce fichier gère le fonctionnement global de l'application
 */

$(function () {
    init();
});

function init() {

    //datepicker
    $('.datepicker').click(function () {
        $(this).datepicker({dateFormat: 'dd.mm.yy'}).datepicker("show");
    });

    //datatable
    $('.datatable').dataTable();

    $('.tabular .item').tab();

    /**
     * scan la page à la recherche de pattern à respecter pour tous les inputs type="text"
     */
    $("input[data-formatter=true]").each(function () {

        var pattern = $(this).attr("data-pattern");

        $(this).formatter({
            persistent: true,
            pattern: pattern
        });
    });

    /**
     * On met en place le petit script tout simple de recherche
     *
     * La recherche se fait en méthode GET donc on passe la variable dans l'URL.
     *
     */
    $('#layout-search').search({
        apiSettings: {
            url: Routing.generate('app_search_layout')+'?pattern={query}'
        },
        type: 'category'
    });

    var $menu_search =  $('#menu_search');
    var menu_entries = $menu_search.data("entries");
    $menu_search.search({
        source: menu_entries,
        searchFields   : ['title'],
        searchFullText: false
    });

}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MuDBHelper
{
    public class Item
    {
        public string EMPTY = new string('F', 32);
        public string EMPTY_LARGE = new string('F', 64);
        public string def = new string('0', 22) + new string('F', 10);
        public const int length = 32;
        private char[] item;
        private string hex;

        private int start;
        private int end;

        public ExcOpts excellent_options { get; private set; }
        public int durability { get; private set; }
        public int level { get; private set; }
        public int addLevel { get; private set; }
        public Boolean luck { get; private set; }
        public Boolean skill { get; private set; }
        public string serial { get; private set; }
        public int index { get; private set; }
        public int category { get; private set; }

        public int ancientID { get; set; }

        public Dictionary<int, int> sockets { get; set; }

        public int harmoney_opt { get; set; }

        public int harmoney_lvl { get; set; }

        public int refineID { get; set; }

        public Item()
        {
            hex = new string('F', 32);
            item = new char[hex.Length];
            initItem();
        }

        public Item(string hex, int start, int end) : this(hex)
        {
            this.start = start;
            this.end = end;
        }

        public Item(string hex)
        {
            item = new char[hex.Length];
            this.hex = hex;
            initItem();
            initByte2();
            initExcOpts();
        }

        public Item(int index, int category, bool skill, bool luck, int level, int addLevel, int durability, int ancID, int harm_opt, int harm_lvl, int refine_id, ExcOpts excellent_options)
        {
            item     = new char[32];
            this.hex = def;
            initItem();
            changeIndex(index);
            changeCategory(category);
            changeAncient(ancID);
            changeLevel(level);
            changeSkill(skill);
            changeLuck(luck);
            changeAdditionalOpts(addLevel);
            setDurability(durability);
            initExcOptsFromObject(excellent_options.getCode(), excellent_options);
            initExcOptsToItem();
            //changeHarmoneyOption(harm_opt);
            //changeHarmoneyLevel(harm_lvl);
            //changeRefine(refine_id);
            updateHex();
        }

        public Boolean isEmpty()
        {
            return (hex == EMPTY || hex == EMPTY_LARGE);
        }

        public void initItem()
        {
            item = hex.ToCharArray();
        }

        public void initExcOpts()
        {
            string exc_hex = "" + item[14] + item[15];
            initExcOptsFromObject(exc_hex, null);
        }

        public void initExcOptsFromObject(string exc_hex, ExcOpts opts)
        {
            if (exc_hex.Equals("00") || exc_hex.Equals("FF")) excellent_options = new ExcOpts();
            else
            {
                if (addLevel > 3)
                {
                    int dec = (int)hexToDec(exc_hex.Substring(0, 1));
                    dec -= 4;
                    exc_hex = decToHex(dec).Substring(1, 1) + exc_hex.Substring(1, 1);
                }

                excellent_options = (opts == null) ? new ExcOpts(exc_hex) : opts;
            }
        }

        public void initExcOptsToItem()
        {
            if (excellent_options == null) return;
            else
            {
                string hex_str = excellent_options.getCode();

                int dec  = (int)hexToDec(hex_str.Substring(0, 1));
                int dec2 = (int)hexToDec(hex_str.Substring(1, 1));
                int res = (addLevel > 3) ? 4 : 0;

                dec += res;
                item[14] = char.Parse(decToHex(dec).Substring(1, 1));
                item[15] = char.Parse(decToHex(dec2).Substring(1, 1));
            }
        }

        public void initProperties()
        {
           initByte2();
           getDurabilityFromHex();
           setSerial();
        }

        public void updateHex()
        {
            hex = new string(item);
        }

        public string getHexString()
        {
            return hex;
        }

        public char[] getItemFull()
        {
            return item;
        }

        public void calculateIndex()
        {
            index = (int)hexToDec("" + item[0] + item[1]);
        }

        public void calculteCategory()
        {
            category = (int)hexToDec("" + item[18]);
        }

        public void changeIndex(int index_change)
        {
            if (index_change > 255 || index_change < 0) return;
            else
            {
                string index_hex = decToHex(index_change);
                item[0] = char.Parse(index_hex.Substring(0, 1));
                item[1] = char.Parse(index_hex.Substring(1, 1));
                index = index_change;
            }
        }

        public void changeCategory(int category_change)
        {
            if (category_change > 255 || category_change < 0) return;
            else
            {
                string cat_hex = decToHex(category_change);
                item[18] = char.Parse(cat_hex.Substring(1, 1));
                //item[19] = char.Parse(cat_hex.Substring(1, 1));
                category = category_change;
            }
        }

        public void changeRefine(int refine_id)
        {
            if (refine_id < 0) return;

            refineID = refine_id;

            if (refine_id != 0)
                item[19] = '8';
            else
                item[19] = '0';
        }

        public void changeAncient(int ancient_id)
        {
            string anc_hex = decToHex(ancient_id);
            item[16] = char.Parse(anc_hex.Substring(0, 1));
            item[17] = char.Parse(anc_hex.Substring(1, 1));
            ancientID = ancient_id;
        }

        public void changeLuck(Boolean luck_changed)
        {
            if (luck_changed == luck) return;
            else
            {
                int dec = (int)hexToDec(item[3].ToString());
                dec += (luck_changed) ? 4 : -4;
                item[3] = char.Parse(decToHex(dec).Substring(1, 1));
                luck = true;
            }
        }

        public void changeHarmoneyOption(int harmoneyID)
        {
            harmoney_opt = harmoneyID;
            item[20] = char.Parse(decToHex(harmoneyID));
        }

        public void changeHarmoneyLevel(int harm_level)
        {
            harmoney_lvl = harm_level;
            item[21] = char.Parse(decToHex(harm_level));
        }

        public void changeSkill(Boolean skill_changed)
        {
            if (skill_changed == skill) return;
            else
            {
                int dec = (int)hexToDec(item[2].ToString());
                if (skill_changed) dec += 6;
                else dec -= 6;
                item[2] = char.Parse(decToHex(dec).Substring(1, 1));
                skill = true;
            }
        }

        public int getDurabilityFromHex()
        {
            return (int) hexToDec("" + item[4] + item[5]);
        }

        public void setDurability(int dur)
        {
            if (dur > 255 || dur < 0) return;
            else
            {
                string hex_dur = decToHex(dur);
                item[4] = char.Parse(hex_dur.Substring(0, 1));
                item[5] = char.Parse(hex_dur.Substring(1, 1));
                durability = dur;
            }
        }

        public void changeLevel(int new_level)
        {
            if (new_level > 15 || new_level < 0) return;
            else
            {
                int dec = (int)hexToDec(item[2].ToString() + item[3].ToString());
                if (new_level > level) dec += (8* (new_level - level));
                else dec -= (8* (level - new_level));
                level = dec / 8;

                string hex_temp = decToHex(dec);
                item[2] = char.Parse(hex_temp.Substring(0, 1));
                item[3] = char.Parse(hex_temp.Substring(1, 1));
            }
        }

        public void changeAdditionalOpts(int opt_level)
        {
            if (opt_level == addLevel || opt_level < 0 || opt_level > 7) return;
            else
            {
                int dec = (int)hexToDec(item[3].ToString());
                int dec2 = (int)hexToDec(item[14].ToString());

                if (addLevel == null)
                {
                    if (opt_level > 3)
                    {
                        dec2 += 4;
                        dec += (opt_level - 4);
                    }

                    else
                        dec += opt_level;
                }

                else
                {

                    if (opt_level > 3 && addLevel <= 3)
                    {
                        dec2 += 4;
                        int dec_temp = opt_level - 4;
                        dec -= addLevel;
                        dec += dec_temp;

                    }
                    else if (opt_level <= 3 && addLevel > 3)
                    {
                        dec2 -= 4;
                        int dec_temp = addLevel - 4;
                        dec -= dec_temp;
                        dec += opt_level;
                    }

                    else
                    {
                        int dec_temp = (addLevel > 3) ? addLevel - 4 : addLevel;
                        dec -= dec_temp;
                        dec += (opt_level > 3) ? opt_level - 4 : opt_level;
                    }
                }

                item[3] = char.Parse(decToHex(dec).Substring(1, 1));
                item[14] = char.Parse(decToHex(dec2).Substring(1, 1));
                addLevel = opt_level;
            }
        }

        public bool isItemEmpty()
        {
            return hex.Substring(0, 2).ToLower().Equals("ff") && hex.Substring(17, 2).ToLower().Equals("ff");
        }

        //--------------------------------------------------------------
        //Skill, level, luck and additional damge properties calculated
        //--------------------------------------------------------------
        public void initByte2()
        {
            if (hex == null) return;
            else
            {
                index = (int)hexToDec(hex.Substring(0, 2));
                category = (int)hexToDec(hex.Substring(18, 1));
                ancientID = (int)hexToDec(hex.Substring(16, 2));
                harmoney_opt = (int)hexToDec(hex.Substring(20, 1));
                harmoney_lvl = (int)hexToDec(hex.Substring(21, 1));
                refineID = (int)hexToDec(hex.Substring(19, 1));

                int[] temp = { (int)hexToDec(hex.Substring(2, 1)), (int)hexToDec(hex.Substring(3, 1)) };
                int addOpt = (int)hexToDec(hex.Substring(14, 1));
                bool is_opt = false;

                //add opts adds +4 @ pos 14 if opts are >= +16
                if (addOpt >= 4) is_opt = true;

                //Determining +skill
                if (temp[0] > 7)
                {
                    skill = true;
                    temp[0] -= 8;
                }

                //deal with level, luck and additional opts
                if (temp[1] < 4) luck = false;

                //item has luck and possibly additional opts
                else if (temp[1] >= 4 && temp[1] <= 7)
                {
                    luck = true;
                    temp[1] -= 4;
                    addLevel = temp[1] + addOpt;
                    temp[1] = 0;
                    level = (int)hexToDec("" + temp[0] + temp[1]) / 8;
                }

                //item has luck additional opts and level > 0
                else if (temp[1] >= 12 && temp[1] <= 15)
                {
                    luck = true;
                    temp[1] -= 4;
                    temp[1] -= 8; //temp remove level component to find add_level. Add back later.
                    addLevel = temp[1] + addOpt;
                    temp[1] = 8;
                    level = (int)hexToDec("" + temp[0] + temp[1]) / 8;
                }
            }
        }

        public string generateSerial()
        {
            int dec = 0; // call WZ_GetItemSerial 1 and fetch new item count
            return String.Format("{0:X8}", dec);
        }

        public string getSerialFromHex()
        {
            String serial = "";
            for (int i = 6; i <= 13; i++)
                serial += item[i];
            return serial;
        }

        public void setSerial()
        {
            serial = getSerialFromHex();
        }

        public static string decToHex(int dec)
        {
            string hex_str = ((dec < 16) ? "0" : "") + dec.ToString("X");
            return hex_str;
        }

        public static long hexToDec(string hex)
        {
            return Convert.ToInt64(hex, 16);
        }

        public static long parseBinary(long n)
        {
            return int.Parse(Convert.ToString(n, 2));
        }

        public static long[] toArray(long n)
        {
            string n2 = n.ToString();
            long[] temp = new long[n2.Length];
            for (int i = 0; i < n2.Length; i++)
                temp[i] = int.Parse(n2.Substring(i, 1));
            return temp;
        }

        public string getItemCode()
        {
            string hex_code = "";
            foreach (char index in item)
                hex_code += index;
            return hex_code;
        }

        public string getImagePath()
        {
            Debug.WriteLine("index: " + index + " category " + category);
            string path = DBLoader.calcItemImage(index, category, 0, 0);
            if(path == null) path = "default.gif";

            return path;
        }

        public int getItemType()
        {
            return getItemType(category, index);
        }

        public static int getItemType(int category, int index)
        {
            //misc or invalid item
            if (category < 0 || category > 16) return 4;

            //weapons
            else if (category < 7) return 0;

            //armour
            else if (category < 12) return 1;

            //wings
            else if (category == 12 && (index < 7 || (index >= 36 && index <= 43) || (index >= 49 && index <= 50) || (index >= 130 && index <= 135) || (index >= 262 && index <= 267)))
                return 2;

            //scrolls
            else if (category == 15)
                return 3;

            //misc
            else
                return 4;
        }
    }
}


text:
function __init() {

	##
	## Process input params
	##
	while [ "${1}" != "" ]; do
		case ${1} in
			-d | --domain )
				shift
				__msg debug "Processing input parameter: -d ${1}"
				export Domain=${1}
				[[ ! "${Domain}" == *.* ]] && __usage "Domain must be a FQDN"
				export ParentDomain=$(echo ${Domain}|awk -F '[.]' '{print $(NF-1)"."$NF}')
				[[ ! "${ParentDomain}" == *.* ]] && __usage "Generated Parent Domain value from given domain does not contain FQDN value. Unknown error"
				# Lets set ParentDomain to null if given domain is not a subdomain.
				[[ "${ParentDomain}" == "${Domain}" ]] && export ParentDomain=
				__msg debug "Domain is ${Domain} and ParentDomain is ${ParentDomain}"
				;;
			-r | --record )
				shift
				__msg debug "Processing input parameter: -r ${1}"
				export RecordsView+="#${1}" #We will use for display purpose
				local tmpDnsName=$(echo ${1}|awk -F ':' '{print $1}')
				[[ "${tmpDnsName}" =~ [^a-zA-Z0-9-] ]] && __usage "DNS Name - \"${tmpDnsName}\": must be alphanumeric."
				local tmpRecordType=$(echo ${1}|awk -F ':' '{print $2}')
				[[ ! "${tmpRecordType}" =~ ^(${ValidDnsRecordTypes})$ ]] && __usage "DNS Record Type - \"${tmpRecordType}\": is invalid. Valid Record types are - ${ValidDnsRecordTypes}"
				local tmpValue="$(echo ${1}|awk -F ':' '{print $3}')"
				__msg debug "Inpute value ${1} is validated"
				# Lets validate values
				for i in $(echo ${tmpValue}|sed 's/,/ /g')
				do
					[[ "${IpCheck}" != "1" ]] && badIp=0 || badIp=$(checkIp ${i})
					if [[ "$badIp" != "0" && "${tmpRecordType}" == "A" ]]; then
						__usage "DNS Record Value - ${i}: is not a valid IP for host record type ${tmpRecordType}"
					elif [[  "${i}" =~ [^a-zA-Z0-9.-] || "${i}" != *.* && "${tmpRecordType}" == "CNAME" ]]; then
						__usage "DNS record value - ${i}: is not a valid FQDN value for host record type ${tmpRecordType}"
					fi
					__msg debug "Record: ${tmpDnsName} Record Type: ${tmpRecordType} Value Set $tmpValue: validated DNS record Value: $i"
				done
				# Check if we have comma separated multiple values for DNS record
				if [[ "${tmpValue}" == *,* ]]; then
					# Set value of tmpValue variable with quotes and comma so that we can directly use it in jq command
					local valueData="$(echo ${tmpValue}|sed 's/^/{"Value":"/; s/,/"},{"Value":"/g; s/$/"}/')"
				else
					local valueData="$(echo ${tmpValue}|sed 's/^/{"Value":"/;s/$/"}/')"
				fi
				local tmpTtl=$(echo ${1}|awk -F ':' '{print $4}')
				if [[ "${tmpTtl}" == "" ]]; then
					local tmpTtl=${DefaultDnsTtl}
				else
					[[ "${tmpTtl}" =~ [^0-9] ]] && __msg warn "TTL - ${tmpTtl}: is not valid number, using default value" && tmpTtl=${DefaultDnsTtl}
				fi
				# Lets update the records data
				export RecordsData=$(jq ".Changes += [{
					\"Action\": \"UPSERT\",
					\"ResourceRecordSet\": {
						\"Name\": \"${tmpDnsName}.SETME_DOMAIN\",
						\"Type\":\"${tmpRecordType}\",
						\"TTL\": ${tmpTtl},
						\"ResourceRecords\": [
							${valueData}
						]
					}
				}]" <<<"$RecordsData")
				__msg debug "Processed input parameter value successfully: ${1}"
				;;
			--no-zone-check )
				__msg debug "Processing input parameter: --no-zone-check"
				export ZoneCheck=0
				if [[ "${AWS_HOSTED_ZONE_ID}" == "" ]]; then
					__usage "Zone check is disabled and variable AWS_HOSTED_ZONE_ID is not set. Please remove -n|--no-zone-check from command parameters or export AWS_HOSTED_ZONE_ID variable with correct zone ID"
				fi
				;;
			--no-ip-check )
				__msg debug "Processing input parameter: --no-ip-check"
				export IpCheck=0
				;;
			-h | --help )
				__msg debug "Processing input parameter: -h"
				usage
				exit
				;;
			* )
				__msg debug "Processing input parameter: none"
				__usage "Invalid parameters"
				exit 1
		esac
		shift
	done

	##
	## Validations
	##
	__msg debug "Validation begins"
	[[ ! ${Domain} ]] && __usage "Domain is missing"
	__msg debug "Domain is validated and its value is: ${Domain}"
	[[ ! ${AWS_ACCESS_KEY_ID} ]] && __usage "AWS_ACCESS_KEY_ID variable is not set"
	__msg debug "AWS_ACCESS_KEY_ID is validated and its value is: ${AWS_ACCESS_KEY_ID}"
	[[ ! ${AWS_SECRET_ACCESS_KEY} ]] && __usage "AWS_SECRET_ACCESS_KEY variable is not set"
	__msg debug "AWS_SECRET_ACCESS_KEY is validated and its value is: XXXXXXXXXXXXX"
	[[ ! ${AWS_REGION} ]] && export AWS_REGION=us-east-1 && __msg debug "AWS_REGION is set to us-east-1 as default value"
	__msg debug "AWS_REGION is validated and its value is: ${AWS_REGION}"
	[[ "${RecordsView}" == "" ]] && __usage "Records are not provided"
	__msg debug "Records validated and its value is: ${RecordsView}"
	return 0 # success
}

##
## application main function
##

function __main() {
	## Lets set correct ZoneId based on variables or by fetching IDs from AWS R53 service
	# Lets create subdomain zone if it does not exists and zone check is enabled.
	if [[ "${ZoneCheck}" == "1" ]]; then
		__msg debug "ZoneCheck is forced"
		if [[ "${ParentDomain}" != "" ]]; then
			__msg info "Getting Parent Domain zone ID for ${ParentDomain} from AWS R53 Service"
			getZoneId ${ParentDomain} "soft" # Returns TmpZoneId
			export ParentZoneId=${TmpZoneId}
			if [[ "${ParentZoneId}" == "" ]]; then
				__msg warn "Could not retrieve parent Zone ID, ignoring NS record creation/update/check for ${Domain}"
			else
				__msg info "Successfully retrieved Parent domain zone ID for ${ParentDomain}. Zone ID: ${ParentZoneId}"
			fi
		else
			__msg info "${Domain} does not require any NS records update/creation in its parent domain zone."
			__msg info "If DNS records do not get resolved correctly, you might need to set/check ${Domain} NS records manually at your domain registrar."
		fi
		__msg info "Fetching domain zone ID for ${Domain} from AWS R53 service..."
		getZoneId ${Domain} "soft" # Returns TmpZoneId
		export DomainZoneId=${TmpZoneId}
		if [[ "${DomainZoneId}" == "" ]]; then
			# We could not fetch the zone, lets try creating it
			__msg info "We could not get domain zone ID from AWS R53 service for ${Domain}..."
			createHostedZone "${Domain}" # returns DomainZoneId for newly created domain
		fi
		if [[ "${DomainZoneId}" == "" && "${AWS_HOSTED_ZONE_ID}" != "" ]]; then
			__msg warn "Could not fetch the Zone ID of ${Domain}, assuming AWS_HOSTED_ZONE_ID to be correct value..."
			export DomainZoneId=${AWS_HOSTED_ZONE_ID}
		fi
	else
		__msg debug "ZoneCheck is ignored and AWS_HOSTED_ZONE_ID is set to: ${AWS_HOSTED_ZONE_ID}"
		if [[ "${AWS_HOSTED_ZONE_ID}" == "" ]]; then
			__usage "Zone check is disabled and AWS_HOSTED_ZONE_ID is missing. I need either."
		else
			export DomainZoneId=${AWS_HOSTED_ZONE_ID}
		fi
	fi

	if [[ "${ParentDomain}" != "" && "${ParentZoneId}" != "" && "${ZoneCheck}" == "1" ]]; then
		createNsRecords "${Domain}" "${ParentDomain}" "${DomainZoneId}" "${ParentZoneId}"
	fi
	createDnsRecords "${Domain}" "${DomainZoneId}" "${RecordsData}"
	__msg info "Successfully submitted request to create below records"
	__msg info " ---------------------------------------------------------------------------------------------------"
	__msg info "$(printf " | %-50s | %-10s | %-40s\n " DNS\ Name Type Value)"
	for i in $(echo $RecordsView|sed 's/#/ /g')
	do
		local domain=$(echo `echo ${i}|awk -F '[:]' '{ print $1 }'`.${Domain})
		local recordType=$(echo ${i}|awk -F '[:]' '{ print $2 }')
		local value=$(echo ${i}|awk -F '[:]' '{ print $3 }')
		__msg info " $(printf "| %-50s | %-10s | %-40s\n " ${domain} ${recordType} ${value})"
	done
	__msg info " ----------------------------------------------------------------------------------------------------"
	return 0 # success
}

##
## application worker functions
##

function createHostedZone() {
	## ----- head -----
	##
	## DESCRIPTION:
	##   This function creates hosted R53 DNS Zone in AWS
	##
	## ARGUMENTS:
	##   domain (require) 			= FQDN value
	##
	local domain=${1}
	## create the hosted zone for the Domain if does not exists
	__msg info "Creating ${domain} zone in AWS R53 service..."
	aws route53 create-hosted-zone --name "${domain}" --caller-reference "${domain}-$(uuidgen)" --output=json >/dev/null 2>&1
	if [[ "$?" != "0" ]]; then
		__msg err "Creating hosted zone for ${domain} failed. Please fix it manually"
		__die 2
	fi
	getZoneId ${domain} "soft" # Returns TmpZoneId
	export DomainZoneId=${TmpZoneId}
	if [[ "${DomainZoneId}" == "" ]]; then
		__msg err "Could not create/fetch zone using AWS R53 service for ${domain}, please check Route53. Possible cause - incorrect permissions"
		__die 2
	else
		__msg info "${domain} zone created successfully, Zone ID: ${DomainZoneId}"
		__msg warn "Please check for duplicate zones. AWS allows multiple zone creation for same domains."

	fi
	return 0 # Success
}

function getZoneId() {
	## ----- head -----
	##
	## DESCRIPTION:
	##   This function retrieves Zone ID of given domain from AWS R53 service
	##
	## ARGUMENTS:
	##   domain (require) 			= Domain FQDN value
	##	 errorCheck					= hard|soft. Hard means exit if fails, soft means just return null. Default is hard
	##
	## This functions returns global variable TmpZodeId
	local domain=${1}
	local errorCheck=${2}
	[[ "${errorCheck}" == "" ]] && local errorCheck="hard"
	__msg debug "We are inside getZoneId function and input parameters are: domain: ${domain}, errorCheck: ${errorCheck}"
	__msg debug "Command is: aws route53 list-hosted-zones --output=json| jq -r \".HostedZones[]|select(.Name==\\\"${domain}.\\\")|.Id\"|sed 's/\\/hostedzone\\///'"
	export TmpZoneId=$(aws route53 list-hosted-zones --output=json| jq -r ".HostedZones[]|select(.Name==\"${domain}.\")|.Id"|sed 's/\/hostedzone\///'; local exitCode=${PIPESTATUS[0]})
	if [[ "${exitCode}" != "0" ]]; then
		[[ "${errorCheck}" == "hard" ]] && __die 3 "Could not get Domain Zone ID from AWS R53 service"
	fi
	__msg debug "getZoneId function is returning domain zone id as: $TmpZoneId"
	return 0
}

function createNsRecords() {
	## ----- head -----
	##
	## DESCRIPTION:
	##   This function creates NS records for given Domain zone into parent Zone
	##
	## ARGUMENTS:
	##   domain (require) 			= Domain FQDN value
	##	 parentDomain (require)		= Parent domain FQDN value
	##	 domainZoneId			 	= AWS R53 Zone ID for given domain
	##	 parentZoneId 				= AWS R53 Zone ID for given parent domain
	##
	## TODO: First check if NS records match with fetched ones rather overwriting NS records regardless
	local domain=${1}
	local parentDomain=${2}
	local domainZoneId=${3}
	local parentZoneId=${4}

	__msg info "Setting up NS records for $domain zone for delegation in parent zone $parentDomain..."
	# Create Update zone template
	echo '{
	"Comment": "Create a Domain NS record in the parent domain",
	"Changes": [{
		"Action": "UPSERT",
		"ResourceRecordSet": {
		"Name": "",
		"Type": "NS",
		"TTL": 300,
		"ResourceRecords": []
		}
	}]
	}' > ${TmplZoneFile}

	# Get domainZoneId if not provided.
	if [[ "${domainZoneId}" == "" ]]; then
		getZoneId ${domain} # Returns TmpZoneId
		local domainZoneId=${TmpZoneId}
	fi

	# generate the changeset for the parent zone
	cat ${TmplZoneFile} \
	| jq ".Changes[].ResourceRecordSet.Name=\"${domain}.\"" \
	| jq ".Changes[].ResourceRecordSet.ResourceRecords=$(aws route53 get-hosted-zone --id ${domainZoneId} --output=json| jq ".DelegationSet.NameServers|[{\"Value\": .[]}]")" > ${ZoneFile}

	# Lets get parentZoneId if not provided
	if [[ "${parentZoneId}" == "" ]]; then
		getZoneId ${domain} "soft" # Returns TmpZoneId
		local parentZoneId=${TmpZoneId}
		if [[ "${parentZoneId}" == "" ]]; then
			__msg warn "Could not get Parent Domain Zone ID from AWS R53 service, please set/check NS records manually (without this newly added DNS records may not work)"
		fi
	fi
	# create a NS record for the Domain in the parent zone
	if [[ "${parentZoneId}" != "" ]]; then
		aws route53 change-resource-record-sets --output=json --hosted-zone-id ${parentZoneId} --change-batch file://${ZoneFile} >/dev/null 2>&1
		if [[ "$?" != "0" ]]; then
			__msg warn "Creating NS records for ${domain} at parent domain zone ${parentDomain} failed. Please fix it manually"
		fi
	fi
}

function createDnsRecords() {
	## ----- head -----
	##
	## DESCRIPTION:
	##   This function creates DNS records in R53 DNS Zone in AWS
	##
	## ARGUMENTS:
	##   domain (require) 			= Domain FQDN value
	##	 domainZoneId (require)		= AWS R53 Zone ID for given domain
	##	 recordsData (require)		= DNS records data json in expected AWS R53 service format
	##
	## create DNS records in the given hosted zone
	local domain=${1}
	local domainZoneId=${2}
	local recordsData=${3}

	__msg debug "We are inside createDnsRecords function and input params are - domain:${domain}, domainZoneId:${domainZoneId}, recordsData: ${recordsData}"
	echo ${recordsData} | sed "s/SETME_DOMAIN/${domain}/g" > ${ZoneFile}
	[[ -f ${ZoneFile} ]] && __msg debug "Zone file is written at ${ZoneFile}" || __msg debug "Zone file writing at ${ZoneFile} failed"
	__msg debug "Command is: aws route53 change-resource-record-sets --output=json --hosted-zone-id ${domainZoneId} --change-batch file://${ZoneFile}"
	aws route53 change-resource-record-sets --output=json --hosted-zone-id ${domainZoneId} --change-batch file://${ZoneFile}>/dev/null 2>&1
	if [[ "$?" != "0" ]]; then
		__die 4 "Creating DNS records for ${domain} failed. Please fix it manually"
	fi
	return 0 # Success
}
function __usage() {
	__msg err "${1}"
	__msg info "┌-------------------------------------------------------------------------------------------------------------------------------------------------"
	__msg info "| Usage: $0 -d|--domain <domain> --no-zone-check --no-ip-check -r|--record <Name:Type:Value1,Value2:TTL>"
	__msg info "|"
	__msg info "| PARAMETERS:"
	__msg info "|   -d|--domain          :  Domain in FQDN format"
	__msg info "|   -r|--record          :  DNS record in format: 'Name:Type:Value' (You can provide multiple inputs of -r input type)"
	__msg info "|       Name             :  Only Alphanumerics and hyphen '-' allowed"
	__msg info "|       Type Values      :  ${ValidDnsRecordTypes}"
	__msg info "|       Value            :  Valid IP for record type A and non IP, alphanumeric and FQDN for CNAME"
	__msg info "|       TTL              :  Time To Live value in seconds for record. (Optional, default value is 300 seconds)"
	__msg info "|   --no-zone-check      :  Disabled checking given ZONEID"
	__msg info "|   --no-ip-check        :  Disabled checking given IP for DNS record"
	__msg info "|-------------------------------------------------------------------------------------------------------------------------------------------------"
	__msg info "|   Required Commands    :  aws, jq, checkIP (script)"
	__msg info "|   Required Variables   :  AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION, AWS_HOSTED_ZONE_ID (optional when --no-zone-check is not used)"
	__msg info "|   Note                 :  Please test route53 access using aws cli to confirm that given key can update or create DNS records"
	__msg info "|   Example              :  $0 -s test -d google.com -r 'api:A:1.1.1.1:300' -r 'docs:A:2.2.2.2,3.3.3.3:60'"
	__msg info "└-------------------------------------------------------------------------------------------------------------------------------------------------"
    __die 1 "We can not continue"
}