text:
using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Windows.Forms.Integration;
using System.Windows.Media;

namespace LiveCharts.WinForms
{
    /// <summary>
    ///
    /// </summary>
    /// <seealso cref="System.Windows.Forms.Integration.ElementHost" />
    [Designer("System.Windows.Forms.Design.ControlDesigner, System.Design")]
    [DesignerSerializer("System.ComponentModel.Design.Serialization.TypeCodeDomSerializer , System.Design", "System.ComponentModel.Design.Serialization.CodeDomSerializer, System.Design")]

    public class SolidGauge : ElementHost
    {
        /// <summary>
        /// The WPF base
        /// </summary>
        protected readonly Wpf.Gauge WpfBase = new Wpf.Gauge();

        /// <summary>
        /// Initializes a new instance of the <see cref="SolidGauge"/> class.
        /// </summary>
        public SolidGauge()
        {
            Child = WpfBase;
        }

        /// <summary>
        /// Gets the base.
        /// </summary>
        /// <value>
        /// The base.
        /// </value>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Wpf.Gauge Base
        {
            get { return WpfBase; }
        }

        /// <summary>
        /// Gets or sets a value indicating whether [uses360 mode].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [uses360 mode]; otherwise, <c>false</c>.
        /// </value>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public bool Uses360Mode
        {
            get { return WpfBase.Uses360Mode; }
            set { WpfBase.Uses360Mode = value; }
        }

        /// <summary>
        /// Gets or sets from.
        /// </summary>
        /// <value>
        /// From.
        /// </value>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public double From
        {
            get { return WpfBase.From; }
            set { WpfBase.From = value; }
        }

        /// <summary>
        /// Gets or sets to.
        /// </summary>
        /// <value>
        /// To.
        /// </value>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public double To
        {
            get { return WpfBase.To; }
            set { WpfBase.To = value; }
        }

        /// <summary>
        /// Gets or sets the value.
        /// </summary>
        /// <value>
        /// The value.
        /// </value>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public double Value
        {
            get { return WpfBase.Value; }
            set { WpfBase.Value = value; }
        }

        /// <summary>
        /// Gets or sets the inner radius.
        /// </summary>
        /// <value>
        /// The inner radius.
        /// </value>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public double? InnerRadius
        {
            get { return WpfBase.InnerRadius; }
            set { WpfBase.InnerRadius = value; }
        }

        /// <summary>
        /// Gets or sets the stroke.
        /// </summary>
        /// <value>
        /// The stroke.
        /// </value>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Brush Stroke
        {
            get { return WpfBase.Stroke; }
            set { WpfBase.Stroke = value; }
        }

        /// <summary>
        /// Gets or sets the stroke thickness.
        /// </summary>
        /// <value>
        /// The stroke thickness.
        /// </value>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public double StrokeThickness
        {
            get { return WpfBase.StrokeThickness; }
            set { WpfBase.StrokeThickness = value; }
        }

        /// <summary>
        /// Gets or sets to color.
        /// </summary>
        /// <value>
        /// To color.
        /// </value>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Color ToColor
        {
            get { return WpfBase.ToColor; }
            set { WpfBase.ToColor = value; }
        }

        /// <summary>
        /// Gets or sets from color.
        /// </summary>
        /// <value>
        /// From color.
        /// </value>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Color FromColor
        {
            get { return WpfBase.FromColor; }
            set { WpfBase.FromColor = value; }
        }

        /// <summary>
        /// Gets or sets the gauge background.
        /// </summary>
        /// <value>
        /// The gauge background.
        /// </value>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Brush GaugeBackground
        {
            get { return WpfBase.GaugeBackground; }
            set { WpfBase.GaugeBackground = value; }
        }

        /// <summary>
        /// Gets or sets the animations speed.
        /// </summary>
        /// <value>
        /// The animations speed.
        /// </value>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public TimeSpan AnimationsSpeed
        {
            get { return WpfBase.AnimationsSpeed; }
            set { WpfBase.AnimationsSpeed = value; }
        }

        /// <summary>
        /// Gets or sets the label formatter.
        /// </summary>
        /// <value>
        /// The label formatter.
        /// </value>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Func<double, string> LabelFormatter
        {
            get { return WpfBase.LabelFormatter; }
            set { WpfBase.LabelFormatter = value; }
        }

        /// <summary>
        /// Gets or sets the size of the high font.
        /// </summary>
        /// <value>
        /// The size of the high font.
        /// </value>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public double? HighFontSize
        {
            get { return WpfBase.HighFontSize; }
            set { WpfBase.HighFontSize = value; }
        }
    }
}


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W29890_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans2.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans1.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans2.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans186.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">
1-13"? 1W

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans58.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">16' W WM 7' fishy TA Configuration (05 left by drilling rig!

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

redpajama_set_name: RedPajamaGithub


text:
package uk.ac.ebi.pride.archive.web.service.controller.check;

import com.mangofactory.swagger.annotations.ApiIgnore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import uk.ac.ebi.pride.archive.repo.file.service.FileSummary;
import uk.ac.ebi.pride.archive.repo.project.service.ProjectSummary;
import uk.ac.ebi.pride.archive.security.file.FileSecureService;
import uk.ac.ebi.pride.archive.security.project.ProjectSecureService;
import uk.ac.ebi.pride.archive.web.service.controller.file.FileController;
import uk.ac.ebi.pride.archive.web.service.model.file.FileDetail;
import uk.ac.ebi.pride.archive.web.service.model.file.FileDetailList;
import uk.ac.ebi.pride.archive.web.service.util.ObjectMapper;
import uk.ac.ebi.pride.archive.utils.config.FilePathBuilder;
import uk.ac.ebi.pride.archive.utils.streaming.FileUtils;

import java.io.File;
import java.net.URL;
import java.util.Collection;

/**
 * Health check for the web service, to be used by nagios
 *
 * @author Rui Wang
 * @author Florian Reisinger
 * @since 1.0.4
 */
@Controller
@ApiIgnore
@RequestMapping("/check")
public class CheckController {

    private static final String TEST_PROJECT_ACCESSION = "PXD000001";

    @Value("#{buildConfig['prider.ws.project.name']}")
    private String projectName;

    @Value("#{buildConfig['prider.ws.project.version']}")
    private String projectVersion;

    @Value("#{buildConfig['prider.ws.build.profiles']}")
    private String buildProfile;

    @Value("#{buildConfig['prider.ws.build.user.name']}")
    private String buildUserName;

    @Value("#{buildConfig['prider.ws.service.layer.version']}")
    private String serviceLayerVersion;

    @Value("#{fileConfig['file.location.prefix']}")
    private String fileLocationPrefix;

    @Autowired
    private ProjectSecureService projectService;

    @Autowired
    private FileController fileController;

    @Autowired
    private FileUtils fileUtils;

    @Autowired
    private FilePathBuilder filePathBuilder;

    @ApiIgnore
    @RequestMapping(method = RequestMethod.GET, produces = MediaType.TEXT_PLAIN_VALUE)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public String healthCheck() {
        StringBuilder builder = new StringBuilder();

        // check overall health
        boolean projectHealthy = testProjectQuery();
        boolean projectFileDownloadHealthy = testQueryForProjectFile();

        String lineSeparator = System.getProperty("line.separator");

        builder.append("Overall Check: ").append(projectHealthy && projectFileDownloadHealthy).append(lineSeparator);
        builder.append("Project Query Check: ").append(projectHealthy).append(lineSeparator);
        builder.append("Project File Download Check: ").append(projectFileDownloadHealthy).append(lineSeparator);

        // project name
        builder.append("Project Name: ").append(projectName).append(lineSeparator);

        // project version
        builder.append("Project Version: ").append(projectVersion).append(lineSeparator);

        // build profile
        builder.append("Build Profile: ").append(buildProfile).append(lineSeparator);

        // build user name
        builder.append("Build User: ").append(buildUserName).append(lineSeparator);

        // Service layer version
        builder.append("Service Layer Version: ").append(serviceLayerVersion).append(lineSeparator);

        return builder.toString();
    }

    private boolean testProjectQuery() {
        try {
            ProjectSummary projectSummary = projectService.findByAccession(TEST_PROJECT_ACCESSION);
            if (projectSummary == null) { return false; }
            if ( !projectSummary.getAccession().equalsIgnoreCase(TEST_PROJECT_ACCESSION) ) { return false; }
            ObjectMapper.mapProjectSummary2WSProjectDetail(projectSummary, null);
            // if there was no exception trying to map the search result, then we assume all is OK
            return true;
        } catch (Exception ex) {
            return false;
        }
    }

    private boolean testQueryForProjectFile() {
        try {
            // retrieve the file records for the test project
            FileDetailList projectFiles = fileController.getFilesByProjectAccession(TEST_PROJECT_ACCESSION);
            if (projectFiles == null || projectFiles.getList() == null || projectFiles.getList().isEmpty()) { return false; }

            // get the first file to run some more checks
            FileDetail fileDetail = projectFiles.getList().iterator().next();

            // there has to be a non-empty file name
            String fileName = fileDetail.getFileName();
            if (fileName == null || fileName.trim().isEmpty()) { return false; }

            // there has to be a download URL (since we are testing a public project)
            URL fileUrl = fileDetail.getDownloadLink();
            if (fileUrl == null) { return false; }

            // the download URL has to end in the file name
            String fileString = fileUrl.getFile();
            if (fileString == null || !fileString.endsWith(fileName)) { return false; }

            // we don't test if the file is actually available at the provided URL

            // if all checks passed and there is no exception, we assume all is OK
            return true;

        } catch (Exception ex) {
            return false;
        }
    }

}


text:
<hgroup id="main-title" class="thin">

Generic styles

</hgroup>

The template provides a set of styling classes:

Shadows

Box shadows

class="lite-box-shadow"

class="box-shadow"

class="strong-box-shadow"

class="large-box-shadow"

Text shadows

class="lite-text-shadow"

class="text-shadow"

class="strong-text-shadow"

class="large-text-shadow"

Bevels and emboss

Top bevel

class="top-bevel-on-light"

class="top-bevel"

class="top-bevel-on-dark"

Bottom bevel

class="bottom-bevel-on-light"

class="bottom-bevel"

class="bottom-bevel-on-dark"

Bevel

class="bevel-on-light"

class="bevel"

class="bevel-on-dark"

Emboss

class="emboss"

class="emboss-on-dark"

Quick tip

				bevel and emboss classes are available for ul/ol elements: add the suffix -subs to the class name and all children elements will be styled, (e.g. bevel-subs).

Text bevel

class="bright-text-bevel"

class="bright-text-bevel-on-dark"

class="dark-text-bevel"

class="dark-text-bevel-on-dark"

Effects

Border

class="with-border"

This class forces a border on an element which does not have one by default. Color is inherited from element's styling.

Glow

class="glow"

Add a subtle glow effect. Does not work on IE7 due to lack of proper styling support.

Stripes

Stripes are created by adding an overlaying block, thus the parent element needs to have position:absolute or position:relative. If not, just add the class relative:

<div class="relative">
	Block content
	<div class="stripes"></div>
</div>

Light stripes

class="thin-stripes"

class="stripes"

class="big-stripes"

Dark stripes

class="dark-thin-stripes"

class="dark-stripes"

class="dark-big-stripes"

Animated stripes

Just add the class animated to get moving stripes. This work for all stripes sizes or color, but use it with caution as some slow computers have a hard time rendering them on large elements.

class="dark-stripes animated"


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

using Xamarin.Forms;

namespace ViewGalleryInst
{
    public partial class ActivityIndicatorPage : ContentPage
    {
        public ActivityIndicatorPage()
        {
            InitializeComponent();
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();
            activityIndicator.IsRunning = true;
        }

        protected override void OnDisappearing()
        {
            base.OnDisappearing();
            activityIndicator.IsRunning = false;
        }
    }
}


text:
using System;
using System.Windows.Forms;
using System.Diagnostics;
using System.Drawing;

namespace Layout
{
	/// <summary>
	/// An inputbox saving the typed chars.
	/// </summary>
	public class Inputbox : Textbox
	{
		/******** Variables ********/
		/// <summary>
		/// Internally used random object.
		/// </summary>
		private Random random;
		/// <summary>
		/// Indicating if the next char typed by the user should be added.
		/// </summary>
		private bool handled;
		/// <summary>
		/// The maximum length of the entered string.
		/// </summary>
		private int _maxLength;
		/// <summary>
		/// Indicating if the input box should have a fixed size to fit the maximum string length.
		/// </summary>
		private bool _maxSize;
		/// <summary>
		/// The delimiter causing the call of OnDelimiterEntered.
		/// </summary>
		public Keys delimiter;
		/// <summary>
		/// The time the blinking cursor is visible/invisible.
		/// </summary>
		private int cursorBlinkInterval;

		private Stopwatch stopwatch;
		private bool cursorVisible;
		public bool cursor;
		public Pen cursorPen;

		/// <summary>
		/// Represents a method dealing with an event that contains a string as event data.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		public delegate void StringEventHandler(object sender, StringEventArgs e);
		/// <summary>
		/// Called when the delimiter is entered.
		/// </summary>
		public event StringEventHandler OnDelimiterEntered;

		/******** Getter & Setter ********/

		/// <summary>
		/// Gets or sets the maximum length of the entered string.
		/// Can't be set to a value less than 0.
		/// </summary>
		public int maxLength
		{
			get { return (_maxLength); }
			set
			{
				if (value >= 0) _maxLength = value;
				else _maxLength = 0;

				try
				{
					text = text.Remove(maxLength);
				}
				catch (ArgumentOutOfRangeException)
				{
					// Do nothing if the maximum length is bigger than the current length
				}
			}
		}

		/// <summary>
		/// Indicating if the input box should have a fixed size to fit the maximum string length.
		/// Disables Textbox.boxAdaptive.
		/// </summary>
		public bool maxSize
		{
			get { return (_maxSize); }
			set
			{
				if (value)
				{
					boxAdaptive = false;
					_maxSize = true;
				}
				else
				{
					_maxSize = false;
				}
			}
		}

		/******** Functions ********/

		public Inputbox(string identifier = "")
			: base(identifier)
		{
			maxLength = 50;
			delimiter = Keys.Enter;
			cursorBlinkInterval = 500;

#warning Adapt to different Framerates with Update
			random = new Random((int)DateTime.Now.Ticks);
			stopwatch = new Stopwatch();
			stopwatch.Start();
			cursorPen = new Pen(Brushes.Black, 1);
			cursor = true;
		}

		/// <summary>
		/// Updates the Inputbox.
		/// </summary>
		public override void Update()
		{
			base.Update();
			if (cursor && stopwatch.Elapsed.Milliseconds >= cursorBlinkInterval)
			{
				stopwatch.Restart();
				cursorVisible = !cursorVisible;
			}
		}

		/// <summary>
		/// Renders the Inputbox to the given graphics object.
		/// </summary>
		/// <param name="g">The grahpics object to render the element to.</param>
		public override void Draw(System.Drawing.Graphics g)
		{
			if (!visible) return;
			// Fixing box to maximum size.
			if(maxSize)
			{
				string temp = new string('W', maxLength);
				AdaptToContent(g, temp);
			}

			// Disable adaptiveness of Inputbox, so the size calculated
			// by the following call of AdaptToContent will not be overwritten
			// in base class. This is done to get the same height as a filled Inputbox.
			bool wasAdaptive = false;
			if (text == "" && boxAdaptive == true)
			{
				boxAdaptive = false;
				wasAdaptive = true;
				AdaptToContent(g, ".");
				width = 2 * padding;
			}
			base.Draw(g);
			if(wasAdaptive)
			{
				boxAdaptive = true;
			}

			// Displaying cursor.
			if(cursorVisible)
			{
				Point cursorPosition = textPosition;
				if(text == "")
				{
					cursorPosition.X = absoluteX + padding;
					cursorPosition.Y = absoluteY + padding;
				}
				else
				{
					cursorPosition.X += GetTextSize(g).Width + 1;
				}

				Point cursorBottomPosition = cursorPosition;
				cursorBottomPosition.Y += height - 2 * padding;
				g.DrawLine(cursorPen, cursorPosition, cursorBottomPosition);
			}
		}

		/// <summary>
		/// Called if a key has been pressed.
		/// Passes this event to all elements within the layout.
		/// </summary>
		/// <param name="e">An object containing information about the event.</param>
		public override void KeyPressed(KeyEventArgs e)
		{
			if (!visible) return;
			base.KeyPressed(e);

			handled = true;
			switch (e.KeyCode)
			{
				// When the user is pressing backspace, the last character is deleted.
				// If the users is simultaneoulsy pressing control, the entire string is deleted.
				case Keys.Back:
					handled = false;
					if (text.Length > 0)
					{
						text = text.Remove(text.Length - 1);
						SFXPlayer.Play(Sound.Click1 + random.Next(0, 4));
					}
					if (e.Control) text = "";
					break;
				// Ignore '\r' and '\n' and Escape
				case Keys.Enter:
				case Keys.Escape:
					handled = false;
					break;
			}

			// If the delimiter key is pressed, the OnDelimiterEntered Event is beeing invoked
			if (e.KeyCode == delimiter)
			{
				SFXPlayer.Play(Sound.Menu_Confirm);
				if (OnDelimiterEntered != null) OnDelimiterEntered.Invoke(this, new StringEventArgs(text));
			}
		}

		/// <summary>
		/// Called, if a character on the keyboard has been pressed.
		/// Passes this event to all elements within the layout.
		/// </summary>
		/// <param name="e">An object containing information about the event.</param>
		public override void CharPressed(KeyPressEventArgs e)
		{
			if (!visible) return;

			base.CharPressed(e);
			if (handled && text.Length < maxLength)
			{
				SFXPlayer.Play(Sound.Click1 + random.Next(0, 4));
				text += e.KeyChar;
			}
		}
	}

	/// <summary>
	/// An extension to the EventArgs class containing a string.
	/// </summary>
	public class StringEventArgs : EventArgs
	{
		public string text { get; private set; }

		public StringEventArgs(string text)
		{
			this.text = text;
		}
	}
}


text:
package com.cilinet.godutch.category.entity;

import com.cilinet.godutch.framework.entity.BaseEntity;

/**
 * 消费类别
 * @author zhxl
 *
 */
public class Category extends BaseEntity {

	/** 类型标记名称 **/
	public String typeFlag;

	/** 父类别Id **/
	public int parentId = 0;

	/** 类别路径(面包屑) **/
	public String path;

	public String toString(){
		return "id:" + id + "--name:" + name + "--typeFlag:"+ typeFlag + "--parentId:" + parentId + "--path:" + path + "--state:" + state + "--createDate:" + createDate;
	}

}


text:
package org.elasticsearch.index.query;

import org.apache.lucene.search.Filter;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.cache.filter.support.CacheKeyFilter;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.geo.GeoPointFieldDataType;
import org.elasticsearch.index.mapper.geo.GeoPointFieldMapper;
import org.elasticsearch.index.search.geo.*;

import java.io.IOException;

import static org.elasticsearch.index.query.support.QueryParsers.wrapSmartNameFilter;

/**
 * <pre>
 * {
 *     "name.lat" : 1.1,
 *     "name.lon" : 1.2,
 * }
 * </pre>
 */
public class GeoDistanceFilterParser implements FilterParser {

    public static final String NAME = "geo_distance";

    @Inject
    public GeoDistanceFilterParser() {
    }

    @Override
    public String[] names() {
        return new String[]{NAME, "geoDistance"};
    }

    @Override
    public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
        XContentParser parser = parseContext.parser();

        XContentParser.Token token;

        boolean cache = false;
        CacheKeyFilter.Key cacheKey = null;
        String filterName = null;
        String currentFieldName = null;
        double lat = 0;
        double lon = 0;
        String fieldName = null;
        double distance = 0;
        Object vDistance = null;
        DistanceUnit unit = DistanceUnit.KILOMETERS; // default unit
        GeoDistance geoDistance = GeoDistance.ARC;
        String optimizeBbox = "memory";
        boolean normalizeLon = true;
        boolean normalizeLat = true;
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                currentFieldName = parser.currentName();
            } else if (token == XContentParser.Token.START_ARRAY) {
                token = parser.nextToken();
                lon = parser.doubleValue();
                token = parser.nextToken();
                lat = parser.doubleValue();
                while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {

                }
                fieldName = currentFieldName;
            } else if (token == XContentParser.Token.START_OBJECT) {
                // the json in the format of -> field : { lat : 30, lon : 12 }
                String currentName = parser.currentName();
                fieldName = currentFieldName;
                while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                    if (token == XContentParser.Token.FIELD_NAME) {
                        currentName = parser.currentName();
                    } else if (token.isValue()) {
                        if (currentName.equals(GeoPointFieldMapper.Names.LAT)) {
                            lat = parser.doubleValue();
                        } else if (currentName.equals(GeoPointFieldMapper.Names.LON)) {
                            lon = parser.doubleValue();
                        } else if (currentName.equals(GeoPointFieldMapper.Names.GEOHASH)) {
                            double[] values = GeoHashUtils.decode(parser.text());
                            lat = values[0];
                            lon = values[1];
                        } else {
                            throw new QueryParsingException(parseContext.index(), "[geo_distance] filter does not support [" + currentFieldName + "]");
                        }
                    }
                }
            } else if (token.isValue()) {
                if (currentFieldName.equals("distance")) {
                    if (token == XContentParser.Token.VALUE_STRING) {
                        vDistance = parser.text(); // a String
                    } else {
                        vDistance = parser.numberValue(); // a Number
                    }
                } else if (currentFieldName.equals("unit")) {
                    unit = DistanceUnit.fromString(parser.text());
                } else if (currentFieldName.equals("distance_type") || currentFieldName.equals("distanceType")) {
                    geoDistance = GeoDistance.fromString(parser.text());
                } else if (currentFieldName.endsWith(GeoPointFieldMapper.Names.LAT_SUFFIX)) {
                    lat = parser.doubleValue();
                    fieldName = currentFieldName.substring(0, currentFieldName.length() - GeoPointFieldMapper.Names.LAT_SUFFIX.length());
                } else if (currentFieldName.endsWith(GeoPointFieldMapper.Names.LON_SUFFIX)) {
                    lon = parser.doubleValue();
                    fieldName = currentFieldName.substring(0, currentFieldName.length() - GeoPointFieldMapper.Names.LON_SUFFIX.length());
                } else if (currentFieldName.endsWith(GeoPointFieldMapper.Names.GEOHASH_SUFFIX)) {
                    double[] values = GeoHashUtils.decode(parser.text());
                    lat = values[0];
                    lon = values[1];
                    fieldName = currentFieldName.substring(0, currentFieldName.length() - GeoPointFieldMapper.Names.GEOHASH_SUFFIX.length());
                } else if ("_name".equals(currentFieldName)) {
                    filterName = parser.text();
                } else if ("_cache".equals(currentFieldName)) {
                    cache = parser.booleanValue();
                } else if ("_cache_key".equals(currentFieldName) || "_cacheKey".equals(currentFieldName)) {
                    cacheKey = new CacheKeyFilter.Key(parser.text());
                } else if ("optimize_bbox".equals(currentFieldName) || "optimizeBbox".equals(currentFieldName)) {
                    optimizeBbox = parser.textOrNull();
                } else if ("normalize".equals(currentFieldName)) {
                    normalizeLat = parser.booleanValue();
                    normalizeLon = parser.booleanValue();
                } else {
                    // assume the value is the actual value
                    String value = parser.text();
                    int comma = value.indexOf(',');
                    if (comma != -1) {
                        lat = Double.parseDouble(value.substring(0, comma).trim());
                        lon = Double.parseDouble(value.substring(comma + 1).trim());
                    } else {
                        double[] values = GeoHashUtils.decode(value);
                        lat = values[0];
                        lon = values[1];
                    }
                    fieldName = currentFieldName;
                }
            }
        }

        if (vDistance instanceof Number) {
            distance = unit.toMiles(((Number) vDistance).doubleValue());
        } else {
            distance = DistanceUnit.parse((String) vDistance, unit, DistanceUnit.MILES);
        }
        distance = geoDistance.normalize(distance, DistanceUnit.MILES);

        if (normalizeLat || normalizeLon) {
            Point point = new Point(lat, lon);
            GeoUtils.normalizePoint(point, normalizeLat, normalizeLon);
            lat = point.lat;
            lon = point.lon;
        }

        MapperService.SmartNameFieldMappers smartMappers = parseContext.smartFieldMappers(fieldName);
        if (smartMappers == null || !smartMappers.hasMapper()) {
            throw new QueryParsingException(parseContext.index(), "failed to find geo_point field [" + fieldName + "]");
        }
        FieldMapper mapper = smartMappers.mapper();
        if (mapper.fieldDataType() != GeoPointFieldDataType.TYPE) {
            throw new QueryParsingException(parseContext.index(), "field [" + fieldName + "] is not a geo_point field");
        }
        GeoPointFieldMapper geoMapper = ((GeoPointFieldMapper.GeoStringFieldMapper) mapper).geoMapper();
        fieldName = mapper.names().indexName();

        Filter filter = new GeoDistanceFilter(lat, lon, distance, geoDistance, fieldName, geoMapper, parseContext.indexCache().fieldData(), optimizeBbox);
        if (cache) {
            filter = parseContext.cacheFilter(filter, cacheKey);
        }
        filter = wrapSmartNameFilter(filter, smartMappers, parseContext);
        if (filterName != null) {
            parseContext.addNamedFilter(filterName, filter);
        }
        return filter;
    }
}


text:
Todos os contatos

Novo contato


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const bignumber_js_1 = require("bignumber.js");
const assert_throws_1 = require("./utils/assert_throws");
const evm_increaseTime_1 = require("./utils/evm_increaseTime");
const now_1 = require("./utils/now");
const time_1 = require("./utils/time");
const PreICOCrowdsale = artifacts.require("./PreICOCrowdsale.sol");
const DualMintableToken = artifacts.require("./DualMintableToken.sol");
const PBToken = artifacts.require("./PBToken.sol");
const RefundVault = artifacts.require("./RefundVault.sol");
contract("PreICOCrowdsale", accounts => {
    const owner = accounts[0];
    const wallet = accounts[9];
    const buyer = accounts[1];
    const tokenAccount = accounts[9];
    const bonusRate = 40000;
    const duration = 60 * 60 * 24
        * 12; // Days
    const GOAL = new bignumber_js_1.BigNumber(web3.toWei(1500, "ether"));
    const CAP = new bignumber_js_1.BigNumber(web3.toWei(30000, "ether"));
    const RATE = 30000;
    describe("Creation", async () => {
        it("Fails on wallet: 0, token: 0", async () => {
            const soon = await now_1.safeSoon();
            await assert_throws_1.assert_throws(PreICOCrowdsale.new(0, 0, soon));
        });
        it("Succeeds with wallet and token, has correct params", async () => {
            const soon = await now_1.safeSoon();
            const token = await DualMintableToken.new(owner, owner);
            const crowdsale = await PreICOCrowdsale.new(wallet, token.address, soon);
            const startTime = soon;
            const endTime = soon + 12 * time_1.day;
            assert((await crowdsale.startTime()).equals(startTime), "Start time should match");
            assert((await crowdsale.endTime()).equals(endTime), "End time should match");
            assert((await crowdsale.rate()).equals(RATE), "Rate should match");
            assert((await crowdsale.goal()).equals(GOAL), "Goal should match");
            assert((await crowdsale.cap()).equals(CAP), "Cap should match");
            assert.equal(await crowdsale.wallet(), (wallet), "Wallet should match");
        });
    });
    describe("Token sale", async () => {
        it("Sells tokens only during crowdsale", async () => {
            const soon = await now_1.safeSoon();
            const token = await PBToken.new(owner, owner); // Use PB for sanity check
            const crowdsale = await PreICOCrowdsale.new(wallet, token.address, soon);
            await token.transferOwnership(crowdsale.address, { from: owner });
            const value = 100;
            await assert_throws_1.assert_throws(crowdsale.buyTokens(buyer, { from: buyer, value }), "Should not allow purchases before");
            await evm_increaseTime_1.evm_increaseTime(1000);
            await crowdsale.buyTokens(buyer, { from: buyer, value });
            const tokenAmount = bonusRate * value;
            assert.equal(await token.balanceOf(buyer), tokenAmount, "Buyer should get tokens");
            assert.equal(await token.totalSupply(), tokenAmount, "Token supply should increase");
            await evm_increaseTime_1.evm_increaseTime(duration);
            await assert_throws_1.assert_throws(crowdsale.buyTokens(buyer, { from: buyer, value }), "Should not allow purchases after");
        });
        it("Gives bonuses", async () => {
            const soon = await now_1.safeSoon();
            const token = await DualMintableToken.new(owner, owner);
            const crowdsale = await PreICOCrowdsale.new(wallet, token.address, soon);
            await token.transferOwnership(crowdsale.address, { from: owner });
            await evm_increaseTime_1.evm_increaseTime(1000);
            const value = 100;
            await crowdsale.buyTokens(buyer, { from: buyer, value });
            const tokenAmount = bonusRate * value;
            assert.equal(await token.balanceOf(buyer), tokenAmount, "Buyer should get tokens at bonus rate");
            await evm_increaseTime_1.evm_increaseTime(time_1.day);
            const normalRate = RATE;
            await crowdsale.buyTokens(buyer, { from: buyer, value });
            const tokenAmount_ = tokenAmount + normalRate * value;
            assert.equal(await token.balanceOf(buyer), tokenAmount_, "Buyer should get tokens at normal rate");
        });
    });
    describe("Cap - 30'000 ETH", async () => {
        it("Limits amount of ETH and successfully ends crowdsale", async () => {
            const soon = await now_1.safeSoon();
            const token = await DualMintableToken.new(owner, owner);
            const crowdsale = await PreICOCrowdsale.new(wallet, token.address, soon);
            const vault = RefundVault.at(await crowdsale.vault());
            assert.equal(await vault.state(), 0, "Vault should be active");
            await token.transferOwnership(crowdsale.address, { from: owner });
            await evm_increaseTime_1.evm_increaseTime(1000);
            const value = CAP;
            await crowdsale.buyTokens(buyer, { from: buyer, value });
            assert.equal(await crowdsale.hasEnded.call(), true);
            assert_throws_1.assert_throws(crowdsale.buyTokens(buyer, { from: buyer, value }), "Should throw after end");
            const beforeAmount = web3.eth.getBalance(wallet);
            await crowdsale.finalize();
            const afterAmount = web3.eth.getBalance(wallet);
            assert(afterAmount.minus(beforeAmount).equals(value), `Amounts should be equal: ${afterAmount.minus(beforeAmount).toString()} != ${new bignumber_js_1.BigNumber(value).toString()}`);
            assert.equal(await vault.state(), 2, "Vault should be closed");
        });
    });
    describe("Goal - 1500 ETH", async () => {
        it("Allows funds to be withdrawn after end if met", async () => {
            const soon = await now_1.safeSoon();
            const token = await DualMintableToken.new(owner, owner);
            const crowdsale = await PreICOCrowdsale.new(wallet, token.address, soon);
            const vault = RefundVault.at(await crowdsale.vault());
            assert.equal(await vault.state(), 0, "Vault should be active");
            await token.transferOwnership(crowdsale.address, { from: owner });
            await evm_increaseTime_1.evm_increaseTime(1000);
            // goal
            const value = GOAL;
            await crowdsale.buyTokens(buyer, { from: buyer, value });
            await evm_increaseTime_1.safe_evm_increaseTime(duration);
            assert.equal(await crowdsale.hasEnded.call(), true);
            const beforeAmount = web3.eth.getBalance(wallet);
            await crowdsale.finalize();
            const afterAmount = web3.eth.getBalance(wallet);
            assert(afterAmount.minus(beforeAmount).equals(value), `Amounts should be equal: ${afterAmount.minus(beforeAmount).toString()} != ${new bignumber_js_1.BigNumber(value).toString()}`);
            assert.equal(await vault.state(), 2, "Vault should be closed");
        });
    });
    describe("End Time", async () => {
        it("Crowdsale has ended after duration", async () => {
            const soon = await now_1.safeSoon();
            const token = await DualMintableToken.new(owner, owner);
            const crowdsale = await PreICOCrowdsale.new(wallet, token.address, soon);
            await token.transferOwnership(crowdsale.address, { from: owner });
            await evm_increaseTime_1.safe_evm_increaseTime(duration + 1000);
            assert.equal(await crowdsale.hasEnded.call(), true);
            await crowdsale.finalize();
        });
    });
    describe("Refunds", async () => {
        it("Should happen if goal is not reached", async () => {
            const soon = await now_1.safeSoon();
            const token = await DualMintableToken.new(owner, owner);
            const crowdsale = await PreICOCrowdsale.new(wallet, token.address, soon);
            const vault = RefundVault.at(await crowdsale.vault());
            await token.transferOwnership(crowdsale.address, { from: owner });
            assert.equal(await vault.state(), 0, "Vault should be active");
            await evm_increaseTime_1.evm_increaseTime(1000); // Await start
            const value = 100;
            const gasPrice = 0; // To get exact results
            const balance = web3.eth.getBalance(buyer);
            await crowdsale.buyTokens(tokenAccount, { from: buyer, value, gasPrice });
            assert.equal(await token.balanceOf(tokenAccount), value * bonusRate, "Token account should have received tokens");
            assert.equal(await vault.deposited(buyer), value, "Deposit should match value");
            await evm_increaseTime_1.evm_increaseTime(duration); // Await end
            await crowdsale.finalize();
            assert.equal(await vault.state(), 1, "Vault should be refunding");
            await crowdsale.claimRefund({ from: buyer, gasPrice });
            assert.deepEqual(web3.eth.getBalance(buyer), balance, "Balance should be restored after refund");
        });
    });
});


text:
using System;

namespace Pulse.Core
{
    public sealed class ProgressSender : IProgressSender
    {
        public event Action<long> ProgressTotalChanged;
        public event Action<long> ProgressIncremented;

        public void IncrementProgress(long value)
        {
            ProgressIncremented.NullSafeInvoke(value);
        }

        public void ChangeTotal(long value)
        {
            ProgressTotalChanged.NullSafeInvoke(value);
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

    <title>luaposix 33.3.0 Reference</title>
    <link rel="stylesheet" href="../ldoc.css" type="text/css" />

<big></big>

luaposix 33.3.0

Index

Contents

Functions

Constants

Modules

posix

posix.ctype

posix.curses

posix.dirent

posix.errno

posix.fcntl

posix.fnmatch

posix.getopt

posix.glob

posix.grp

posix.libgen

posix.poll

posix.pwd

posix.sched

posix.signal

posix.stdio

posix.stdlib

posix.sys.msg

posix.sys.resource

posix.sys.socket

posix.sys.stat

posix.sys.statvfs

posix.sys.time

posix.sys.times

posix.sys.utsname

posix.sys.wait

posix.syslog

posix.termio

posix.time

posix.unistd

posix.utime

Classes

posix.curses.chstr

posix.curses.window

Examples

curses.lua

dir.lua

fork.lua

fork2.lua

getopt.lua

glob.lua

limit.lua

lock.lua

netlink-uevent.lua

ping.lua

poll.lua

rt_sched.lua

signal.lua

socket.lua

termios.lua

tree.lua

Module posix.sched

Kernel Thread Scheduling Priority.

 Where supported by the underlying system, functions to discover and
 change the kernel thread scheduling priority.  If the module loads
 successfully, but there is no kernel support, then posix.sched.version
 will be set, but the unsupported APIs will be nil.

Functions

	sched_getscheduler ([pid=0])
	get scheduling policy

	sched_setscheduler ([pid=0[, policy=`SCHED_OTHER`[, priority=0]]])
	set scheduling policy/priority

Constants

	posix.sched
	Scheduler constants.

Functions

    sched_getscheduler ([pid=0])

    get scheduling policy

Parameters:

pid
            int
         process to act on, or 0 for caller process
         (default 0)

Returns:

           int
        scheduling policy SCHED_FIFO, SCHED_RR, SCHED_OTHER,
  if successful

Or

        nil

           string
        error message

           int
        errnum

See also:

         sched_getscheduler(2)

    sched_setscheduler ([pid=0[, policy=`SCHED_OTHER`[, priority=0]]])

    set scheduling policy/priority

Parameters:

pid
            int
         process to act on, or 0 for caller process
         (default 0)

policy
            int
         one of SCHED_FIFO, SCHED_RR or
  SCHED_OTHER
         (default `SCHED_OTHER`)

priority
            int
         must be 0 for SCHED_OTHER, or else a positive
  number below 100 for real-time policies
         (default 0)

Returns:

           int
        0, if successful

Or

        nil

           string
        error message

           int
        errnum

See also:

         sched_setscheduler(2)

Constants

    posix.sched

    Scheduler constants.
Any constants not available in the underlying system will be nil valued.

Fields:

SCHED_FIFO
            int
          first-in, first-out scheduling policy

SCHED_RR
            int
         round-robin scheduling policy

SCHED_OTHER
            int
         another scheduling policy

Usage:

  -- Print scheduler constants supported on this host.
  for name, value in pairs (require "posix.sched") do
    if type (value) == "number" then
      print (name, value)
     end
  end

generated by LDoc 1.4.3
Last updated 2015-03-01 09:06:02


text:
import { describe, it } from 'flow-typed-test';
import execa from 'execa';
import type { ExecaError, Result, SyncResult, ExecaPromise } from 'execa';

const printStdout = (res: Result) => console.log(res.stdout);
const printErrno = (err: ExecaError) => console.log(err.errno);

describe('execa', () => {
  it('should behave like a promise', () => {
    (execa('ls'): ExecaPromise);

    execa('ls').then(res => {
      (res.command: string);
      (res.exitCode: number);
      (res.killed: boolean);
    }).finally(res => {});
    // $FlowExpectedError
    execa('ls').then(res => res.foo);

    execa('foo').catch(err => {
      (err.command: string);
      (err.exitCode: number);
      (err.errno: $PropertyType<ErrnoError, 'errno'>);
    });
    // $FlowExpectedError
    execa('foo').catch(err => err.foo);

    async () => {
      const { stdout } = await execa('noop', ['foo'], { stripEof: false });
    };

    async () => {
      const child: ExecaPromise = execa('stdin');
      child.stdin.end('unicorns');
      const { stdout } = await child;
    };

  });

  it('should provide child process info', () => {
    (execa('ls').pid: number);
    execa('ls').stdout.pipe(process.stdout);
    // $FlowExpectedError
    execa('ls').foo;
  });

  it('should accept options', () => {
    execa('ls', { stderr: 'pipe' }).then(printStdout);
    execa('ls', { stderr: 10 }).then(printStdout);
    execa('ls', { input: 'foobar' });
    execa('ls', { input: new Buffer('foobar') });
    execa('ls', { input: process.stdin });
    // $FlowExpectedError
    execa('ls', { foo: 666 });
    // $FlowExpectedError
    execa('ls', { input: 42 });
  });

  it('should accept args', () => {
    execa('ls', ['-l']).then(printStdout, printErrno);
    execa('ls', ['-l'], { localDir: '~/' }).then(printStdout);
    // $FlowExpectedError
    execa(['ls', '-l']).then(printStdout);
    // $FlowExpectedError
    execa('ls').then(printErrno);
  });

  it('can cancel the subprocess', () => {
    execa('ls').cancel();
  });
});

describe('execa.command', () => {
  it('should behave like execa', () => {
    (execa.command('ls pipe'): ExecaPromise);
    execa.command('ls pipe').then(res => {
      (res.command: string);
    }).finally(res => {});
  });
  it('should accept options', () => {
    execa.command('ls pipe', { stderr: 'pipe' }).then(printStdout);
    execa.command('ls pipe', { stderr: 10 }).then(printStdout);
    execa.command('ls pipe', { input: 'foobar' });
    execa.command('ls pipe', { input: new Buffer('foobar') });
    execa.command('ls pipe', { input: process.stdin });
    // $FlowExpectedError
    execa.command('ls pipe', { foo: 666 });
    // $FlowExpectedError
    execa.command('ls pipe', { input: 42 });
  });
  it('should not accept args', () => {
    // $FlowExpectedError
    execa.command('ls', ['-l']).then(printStdout, printErrno);
    // $FlowExpectedError
    execa.command('ls', ['-l'], { localDir: '~/' }).then(printStdout);
  });
});

describe('execa.commandSync', () => {
  it('should behave like execa', () => {
    (execa.commandSync('ls pipe'): ExecaPromise);
    execa.commandSync('ls pipe').then(res => {
      (res.command: string);
    }).finally(res => {});
  });
  it('should accept options', () => {
    execa.commandSync('ls pipe', { stderr: 'pipe' }).then(printStdout);
    execa.commandSync('ls pipe', { stderr: 10 }).then(printStdout);
    execa.commandSync('ls pipe', { input: 'foobar' });
    execa.commandSync('ls pipe', { input: new Buffer('foobar') });
    execa.commandSync('ls pipe', { input: process.stdin });
    // $FlowExpectedError
    execa.commandSync('ls pipe', { foo: 666 });
    // $FlowExpectedError
    execa.commandSync('ls pipe', { input: 42 });
  });
  it('should not accept args', () => {
    // $FlowExpectedError
    execa.commandSync('ls', ['-l']).then(printStdout, printErrno);
    // $FlowExpectedError
    execa.commandSync('ls', ['-l'], { localDir: '~/' }).then(printStdout);
  });
});

describe('execa.node', () => {
  it('should behave like child_process.fork', () => {
    execa.node('subprocess');
    execa.node('subprocess', ['normal']);
  });
});

describe('execa.sync', () => {
  it('should provide result', () => {
    (execa.sync('ls'): SyncResult);
    (execa.sync('ls', ['-l']).stdout: string);
    (execa.sync('ls', { stderr: 'pipe' }).signal: ?string);
    (execa.sync('ls', ['-l'], { localDir: '~/' }).failed: boolean);
  });
  it('should not accept options or args', () => {
    // $FlowExpectedError
    execa.sync(['ls']);
    // $FlowExpectedError
    execa.sync('ls', { foo: 666 });
    // $FlowExpectedError
    execa.sync('ls').killed;
    // $FlowExpectedError
    execa.sync('ls', { input: process.stdin });
  });
});


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Indian Phytopath. 22: 75 (1969)

#### Original name
Phyllachora diospyri Ullasa, 1969

### Remarks
null


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Perform custom request</title>

http_request_method_unregister

http_redirect

HTTP Functions

PHP Manual

http_request

(PECL pecl_http >= 1.0.0)

http_request — Perform custom request

Description

   string http_request
    ( int $method
   , string $url
   [, string $body
   [, array $options
   [, array &$info
  ]]] )

   Performs a custom HTTP request on the supplied url.

See the full list of request options.

Parameters

method

       Request method

url

       URL

body

       Request body

options

       request options

info

       Request/response information

Return Values

   Returns the HTTP response(s) as string on
success, or FALSE on failure.

http_request_method_unregister

http_redirect

HTTP Functions

PHP Manual


text:
using System;
namespace com.google.zxing.qrcode.encoder
{

	/// <summary> JAVAPORT: This should be combined with BitArray in the future, although that class is not yet
	/// dynamically resizeable. This implementation is reasonable but there is a lot of function calling
	/// in loops I'd like to get rid of.
	///
	/// </summary>
	/// <author>  satorux@google.com (Satoru Takabayashi) - creator
	/// </author>
	/// <author>  dswitkin@google.com (Daniel Switkin) - ported from C++
	/// </author>
	/// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
	/// </author>
	public sealed class BitVector
	{
		public sbyte[] Array
		{
			// Callers should not assume that array.length is the exact number of bytes needed to hold
			// sizeInBits - it will typically be larger for efficiency.

			get
			{
				return array;
			}

		}

		private int sizeInBits;
		private sbyte[] array;

		// For efficiency, start out with some room to work.
		private const int DEFAULT_SIZE_IN_BYTES = 32;

		public BitVector()
		{
			sizeInBits = 0;
			array = new sbyte[DEFAULT_SIZE_IN_BYTES];
		}

		// Return the bit value at "index".
		public int at(int index)
		{
			if (index < 0 || index >= sizeInBits)
			{
				throw new System.ArgumentException("Bad index: " + index);
			}
			int value_Renamed = array[index >> 3] & 0xff;
			return (value_Renamed >> (7 - (index & 0x7))) & 1;
		}

		// Return the number of bits in the bit vector.
		public int size()
		{
			return sizeInBits;
		}

		// Return the number of bytes in the bit vector.
		public int sizeInBytes()
		{
			return (sizeInBits + 7) >> 3;
		}

		// Append one bit to the bit vector.
		public void  appendBit(int bit)
		{
			if (!(bit == 0 || bit == 1))
			{
				throw new System.ArgumentException("Bad bit");
			}
			int numBitsInLastByte = sizeInBits & 0x7;
			// We'll expand array if we don't have bits in the last byte.
			if (numBitsInLastByte == 0)
			{
				appendByte(0);
				sizeInBits -= 8;
			}
			// Modify the last byte.
			array[sizeInBits >> 3] |= (sbyte) ((bit << (7 - numBitsInLastByte)));
			++sizeInBits;
		}

		// Append "numBits" bits in "value" to the bit vector.
		// REQUIRES: 0<= numBits <= 32.
		//
		// Examples:
		// - appendBits(0x00, 1) adds 0.
		// - appendBits(0x00, 4) adds 0000.
		// - appendBits(0xff, 8) adds 11111111.
		public void  appendBits(int value_Renamed, int numBits)
		{
			if (numBits < 0 || numBits > 32)
			{
				throw new System.ArgumentException("Num bits must be between 0 and 32");
			}
			int numBitsLeft = numBits;
			while (numBitsLeft > 0)
			{
				// Optimization for byte-oriented appending.
				if ((sizeInBits & 0x7) == 0 && numBitsLeft >= 8)
				{
					int newByte = (value_Renamed >> (numBitsLeft - 8)) & 0xff;
					appendByte(newByte);
					numBitsLeft -= 8;
				}
				else
				{
					int bit = (value_Renamed >> (numBitsLeft - 1)) & 1;
					appendBit(bit);
					--numBitsLeft;
				}
			}
		}

		// Append "bits".
		public void  appendBitVector(BitVector bits)
		{
			int size = bits.size();
			for (int i = 0; i < size; ++i)
			{
				appendBit(bits.at(i));
			}
		}

		// Modify the bit vector by XOR'ing with "other"
		public void  xor(BitVector other)
		{
			if (sizeInBits != other.size())
			{
				throw new System.ArgumentException("BitVector sizes don't match");
			}
			int sizeInBytes = (sizeInBits + 7) >> 3;
			for (int i = 0; i < sizeInBytes; ++i)
			{
				// The last byte could be incomplete (i.e. not have 8 bits in
				// it) but there is no problem since 0 XOR 0 == 0.
				array[i] ^= other.array[i];
			}
		}

		// Return String like "01110111" for debugging.
		public override System.String ToString()
		{
			System.Text.StringBuilder result = new System.Text.StringBuilder(sizeInBits);
			for (int i = 0; i < sizeInBits; ++i)
			{
				if (at(i) == 0)
				{
					result.Append('0');
				}
				else if (at(i) == 1)
				{
					result.Append('1');
				}
				else
				{
					throw new System.ArgumentException("Byte isn't 0 or 1");
				}
			}
			return result.ToString();
		}

		// Add a new byte to the end, possibly reallocating and doubling the size of the array if we've
		// run out of room.
		private void  appendByte(int value_Renamed)
		{
			if ((sizeInBits >> 3) == array.Length)
			{
				sbyte[] newArray = new sbyte[(array.Length << 1)];
                // Redivivus.in Java to c# Porting update
                // 30/01/2010
                // added namespace system
				System.Array.Copy(array, 0, newArray, 0, array.Length);
				array = newArray;
			}
			array[sizeInBits >> 3] = (sbyte) value_Renamed;
			sizeInBits += 8;
		}
	}
}


text:
import datetime
from decimal import Decimal as D, InvalidOperation

from django.contrib import messages
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.loading import get_model
from django.db.models import fields, Q, Sum, Count
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.utils.datastructures import SortedDict
from django.views.generic import ListView, DetailView, UpdateView, FormView
from django.conf import settings

from oscar.core.loading import get_class
from oscar.core.utils import format_datetime
from oscar.apps.dashboard.orders import forms
from oscar.views.generic import BulkEditMixin
from oscar.apps.dashboard.reports.csv_utils import CsvUnicodeWriter
from oscar.apps.payment.exceptions import PaymentError
from oscar.apps.order.exceptions import InvalidShippingEvent, InvalidStatus

Order = get_model('order', 'Order')
OrderNote = get_model('order', 'OrderNote')
ShippingAddress = get_model('order', 'ShippingAddress')
Transaction = get_model('payment', 'Transaction')
Line = get_model('order', 'Line')
ShippingEventType = get_model('order', 'ShippingEventType')
PaymentEventType = get_model('order', 'PaymentEventType')
EventHandler = get_class('order.processing', 'EventHandler')

class OrderStatsView(FormView):
    template_name = 'dashboard/orders/statistics.html'
    form_class = forms.OrderStatsForm

    def get(self, request, *args, **kwargs):
        return self.post(request, *args, **kwargs)

    def form_valid(self, form):
        ctx = self.get_context_data(form=form,
                                    filters=form.get_filters())
        return self.render_to_response(ctx)

    def get_form_kwargs(self):
        kwargs = super(OrderStatsView, self).get_form_kwargs()
        kwargs['data'] = self.request.GET
        return kwargs

    def get_context_data(self, **kwargs):
        ctx = super(OrderStatsView, self).get_context_data(**kwargs)
        filters = kwargs.get('filters', {})
        ctx.update(self.get_stats(filters))
        ctx['title'] = kwargs['form'].get_filter_description()
        return ctx

    def get_stats(self, filters):
        orders = Order.objects.filter(**filters)
        stats = {
            'total_orders': orders.count(),
            'total_lines': Line.objects.filter(order__in=orders).count(),
            'total_revenue': orders.aggregate(
                Sum('total_incl_tax'))['total_incl_tax__sum'] or D('0.00'),
            'order_status_breakdown': orders.order_by('status').values(
                'status').annotate(freq=Count('id'))
        }
        return stats

class OrderListView(BulkEditMixin, ListView):
    model = Order
    context_object_name = 'orders'
    template_name = 'dashboard/orders/order_list.html'
    form_class = forms.OrderSearchForm
    desc_template = _("%(main_filter)s %(name_filter)s %(title_filter)s"
                      "%(upc_filter)s %(sku_filter)s %(date_filter)s"
                      "%(voucher_filter)s %(payment_filter)s %(status_filter)s")
    paginate_by = 25
    description = ''
    actions = ('download_selected_orders',)
    current_view = 'dashboard:order-list'

    def get(self, request, *args, **kwargs):
        if 'order_number' in request.GET and request.GET.get('response_format', 'html') == 'html':
            try:
                order = Order.objects.get(number=request.GET['order_number'])
            except Order.DoesNotExist:
                pass
            else:
                return HttpResponseRedirect(reverse('dashboard:order-detail', kwargs={'number': order.number}))
        return super(OrderListView, self).get(request, *args, **kwargs)

    def get_desc_context(self, data=None):
        """Update the title that describes the queryset"""
        desc_ctx = {
            'main_filter': _('All orders'),
            'name_filter': '',
            'title_filter': '',
            'upc_filter': '',
            'sku_filter': '',
            'date_filter': '',
            'voucher_filter': '',
            'payment_filter': '',
            'status_filter': '',
        }

        if 'order_status' in self.request.GET:
            status = self.request.GET['order_status']
            if status.lower() == 'none':
                desc_ctx['main_filter'] = _("Orders without an order status")
            else:
                desc_ctx['main_filter'] = _("Orders with status '%s'") % status
        if data is None:
            return desc_ctx

        if data['order_number']:
            desc_ctx['main_filter'] = _('Orders with number starting with "%s"') % data['order_number']

        if data['name']:
            desc_ctx['name_filter'] = _(" with customer name matching '%s'") % data['name']

        if data['product_title']:
            desc_ctx['title_filter'] = _(" including an item with title matching '%s'") % data['product_title']

        if data['upc']:
            desc_ctx['upc_filter'] = _(" including an item with UPC '%s'") % data['upc']

        if data['partner_sku']:
            desc_ctx['upc_filter'] = _(" including an item with ID '%s'") % data['partner_sku']

        if data['date_from'] and data['date_to']:
            desc_ctx['date_filter'] = _(" placed between %(start_date)s and %(end_date)s") % {
                'start_date': format_datetime(data['date_from']),
                'end_date': format_datetime(data['date_to'])}
        elif data['date_from']:
            desc_ctx['date_filter'] = _(" placed since %s") % format_datetime(data['date_from'])
        elif data['date_to']:
            date_to = data['date_to'] + datetime.timedelta(days=1)
            desc_ctx['date_filter'] = _(" placed before %s") % format_datetime(data['date_to'])

        if data['voucher']:
            desc_ctx['voucher_filter'] = _(" using voucher '%s'") % data['voucher']

        if data['payment_method']:
            desc_ctx['payment_filter'] = _(" paid for by %s") % data['payment_method']

        if data['status']:
            desc_ctx['status_filter'] = _(" with status %s") % data['status']

        return desc_ctx

    def get_queryset(self):
        """
        Build the queryset for this list.
        """
        queryset = self.model.objects.all().order_by('-date_placed')
        queryset = self.sort_queryset(queryset)

        # Look for shortcut query filters
        if 'order_status' in self.request.GET:
            self.form = self.form_class()
            status = self.request.GET['order_status']
            if status.lower() == 'none':
                status = None
            self.description = self.desc_template % self.get_desc_context()
            return self.model.objects.filter(status=status)

        if 'order_number' not in self.request.GET:
            self.description = self.desc_template % self.get_desc_context()
            self.form = self.form_class()
            return queryset

        self.form = self.form_class(self.request.GET)
        if not self.form.is_valid():
            return queryset

        data = self.form.cleaned_data

        if data['order_number']:
            queryset = self.model.objects.filter(number__istartswith=data['order_number'])

        if data['name']:
            # If the value is two words, then assume they are first name and last name
            parts = data['name'].split()
            allow_anon = getattr(settings, 'OSCAR_ALLOW_ANON_CHECKOUT', False)

            if len(parts) == 1:
                parts = [data['name'], data['name']]
            else:
                parts = [parts[0], parts[1:]]

            filter = Q(user__first_name__istartswith=parts[0]) |\
                     Q(user__last_name__istartswith=parts[1])
            if allow_anon:
                filter |= Q(billing_address__first_name__istartswith=parts[0]) |\
                          Q(shipping_address__first_name__istartswith=parts[0]) |\
                          Q(billing_address__last_name__istartswith=parts[1]) |\
                          Q(shipping_address__last_name__istartswith=parts[1])

            queryset = queryset.filter(filter).distinct()

        if data['product_title']:
            queryset = queryset.filter(lines__title__istartswith=data['product_title']).distinct()

        if data['upc']:
            queryset = queryset.filter(lines__upc=data['upc'])

        if data['partner_sku']:
            queryset = queryset.filter(lines__partner_sku=data['partner_sku'])

        if data['date_from'] and data['date_to']:
            # Add 24 hours to make search inclusive
            date_to = data['date_to'] + datetime.timedelta(days=1)
            queryset = queryset.filter(date_placed__gte=data['date_from']).filter(date_placed__lt=date_to)
        elif data['date_from']:
            queryset = queryset.filter(date_placed__gte=data['date_from'])
        elif data['date_to']:
            date_to = data['date_to'] + datetime.timedelta(days=1)
            queryset = queryset.filter(date_placed__lt=date_to)

        if data['voucher']:
            queryset = queryset.filter(discounts__voucher_code=data['voucher']).distinct()

        if data['payment_method']:
            queryset = queryset.filter(sources__source_type__code=data['payment_method']).distinct()

        if data['status']:
            queryset = queryset.filter(status=data['status'])

        self.description = self.desc_template % self.get_desc_context(data)
        return queryset

    def sort_queryset(self, queryset):
        sort = self.request.GET.get('sort', None)
        allowed_sorts = ['number', 'total_incl_tax']
        if sort in allowed_sorts:
            direction = self.request.GET.get('dir', 'desc')
            sort = ('-' if direction == 'desc' else '') + sort
            queryset = queryset.order_by(sort)
        return queryset

    def get_context_data(self, **kwargs):
        ctx = super(OrderListView, self).get_context_data(**kwargs)
        ctx['queryset_description'] = self.description
        ctx['form'] = self.form
        return ctx

    def is_csv_download(self):
        return self.request.GET.get('response_format', None) == 'csv'

    def get_paginate_by(self, queryset):
        return None if self.is_csv_download() else self.paginate_by

    def render_to_response(self, context, **response_kwargs):
        if self.is_csv_download():
            return self.download_selected_orders(
                self.request,
                context['object_list'])
        return super(OrderListView, self).render_to_response(
            context, **response_kwargs)

    def get_download_filename(self, request):
        return 'orders.csv'

    def download_selected_orders(self, request, orders):
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename=%s' % self.get_download_filename(request)
        writer = CsvUnicodeWriter(response, delimiter=',')

        meta_data = (('number', _('Order number')),
                     ('value', _('Order value')),
                     ('date', _('Date of purchase')),
                     ('num_items', _('Number of items')),
                     ('status', _('Order status')),
                     ('customer', _('Customer email address')),
                     ('shipping_address_name', _('Deliver to name')),
                     ('billing_address_name', _('Bill to name')),
                     )
        columns = SortedDict()
        for k, v in meta_data:
            columns[k] = v

        writer.writerow(columns.values())
        for order in orders:
            row = columns.copy()
            row['number'] = order.number
            row['value'] = order.total_incl_tax
            row['date'] = format_datetime(order.date_placed, 'DATETIME_FORMAT')
            row['num_items'] = order.num_items
            row['status'] = order.status
            row['customer'] = order.email
            if order.shipping_address:
                row['shipping_address_name'] = order.shipping_address.name
            else:
                row['shipping_address_name'] = ''
            if order.billing_address:
                row['billing_address_name'] = order.billing_address.name
            else:
                row['billing_address_name'] = ''

            encoded_values = [unicode(value).encode('utf8') for value in row.values()]
            writer.writerow(encoded_values)
        return response

class OrderDetailView(DetailView):
    model = Order
    context_object_name = 'order'
    template_name = 'dashboard/orders/order_detail.html'
    order_actions = ('save_note', 'delete_note', 'change_order_status',
                     'create_order_payment_event')
    line_actions = ('change_line_statuses', 'create_shipping_event',
                    'create_payment_event')

    def get_object(self, queryset=None):
        return get_object_or_404(self.model, number=self.kwargs['number'])

    def get_context_data(self, **kwargs):
        ctx = super(OrderDetailView, self).get_context_data(**kwargs)
        ctx['active_tab'] = kwargs.get('active_tab', 'lines')
        ctx['note_form'] = self.get_order_note_form()
        ctx['line_statuses'] = Line.all_statuses()
        ctx['shipping_event_types'] = ShippingEventType.objects.all()
        ctx['payment_event_types'] = PaymentEventType.objects.all()
        ctx['payment_transactions'] = self.get_payment_transactions()
        return ctx

    def get_payment_transactions(self):
        return Transaction.objects.filter(
            source__order=self.object)

    def get_order_note_form(self):
        post_data = None
        kwargs = {}
        if self.request.method == 'POST':
            post_data = self.request.POST
        note_id = self.kwargs.get('note_id', None)
        if note_id:
            note = get_object_or_404(OrderNote, order=self.object, id=note_id)
            if note.is_editable():
                kwargs['instance'] = note
        return forms.OrderNoteForm(post_data, **kwargs)

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        order = self.object

        # Look for order-level action
        order_action = request.POST.get('order_action', '').lower()
        if order_action:
            if order_action not in self.order_actions:
                messages.error(self.request, _("Invalid action"))
                return self.reload_page_response()
            else:
                return getattr(self, order_action)(request, order)

        # Look for line-level action
        line_action = request.POST.get('line_action', '').lower()
        if line_action:
            if line_action not in self.line_actions:
                messages.error(self.request, "Invalid action")
                return self.reload_page_response()
            else:
                line_ids = request.POST.getlist('selected_line')
                line_quantities = []
                for line_id in line_ids:
                    qty = request.POST.get('selected_line_qty_%s' % line_id)
                    line_quantities.append(int(qty))
                lines = order.lines.filter(id__in=line_ids)
                if lines.count() == 0:
                    messages.error(self.request, _("You must select some lines to act on"))
                    return self.reload_page_response()
                return getattr(self, line_action)(request, order, lines, line_quantities)

        messages.error(request, _("No valid action submitted"))
        return self.reload_page_response()

    def reload_page_response(self, fragment=None):
        url = reverse('dashboard:order-detail', kwargs={'number': self.object.number})
        if fragment:
            url += '#' + fragment
        return HttpResponseRedirect(url)

    def save_note(self, request, order):
        form = self.get_order_note_form()
        success_msg = _("Note saved")
        if form.is_valid():
            note = form.save(commit=False)
            note.user = request.user
            note.order = order
            note.save()
            messages.success(self.request, success_msg)
            return self.reload_page_response(fragment='notes')
        ctx = self.get_context_data(note_form=form, active_tab='notes')
        return self.render_to_response(ctx)

    def delete_note(self, request, order):
        try:
            note = order.notes.get(id=request.POST.get('note_id', None))
        except ObjectDoesNotExist:
            messages.error(request, _("Note cannot be deleted"))
        else:
            messages.info(request, _("Note deleted"))
            note.delete()
        return self.reload_page_response()

    def change_order_status(self, request, order):
        new_status = request.POST['new_status'].strip()
        if not new_status:
            messages.error(request, _("The new status '%s' is not valid") % new_status)
            return self.reload_page_response()
        if not new_status in order.available_statuses():
            messages.error(request, _("The new status '%s' is not valid for this order") % new_status)
            return self.reload_page_response()

        handler = EventHandler(request.user)
        try:
            handler.handle_order_status_change(order, new_status)
        except PaymentError, e:
            messages.error(request, _("Unable to change order status due to payment error: %s") % e)
        else:
            msg = _("Order status changed from '%(old_status)s' to '%(new_status)s'") % {
                'old_status': order.status,
                'new_status': new_status}
            messages.info(request, msg)
            order.notes.create(user=request.user, message=msg,
                            note_type=OrderNote.SYSTEM)
        return self.reload_page_response(fragment='activity')

    def change_line_statuses(self, request, order, lines, quantities):
        new_status = request.POST['new_status'].strip()
        if not new_status:
            messages.error(request, _("The new status '%s' is not valid") % new_status)
            return self.reload_page_response()
        errors = []
        for line in lines:
            if new_status not in line.available_statuses():
                errors.append(_("'%(status)s' is not a valid new status for line %(line_id)d") % {
                    'status': new_status,
                    'line_id': line.id})
        if errors:
            messages.error(request, "\n".join(errors))
            return self.reload_page_response()

        msgs = []
        for line in lines:
            msg = _("Status of line #%(line_id)d changed from '%(old_status)s' to '%(new_status)s'") % {
                        'line_id': line.id,
                        'old_status': line.status,
                        'new_status': new_status}
            msgs.append(msg)
            line.set_status(new_status)
        message = "\n".join(msgs)
        messages.info(request, message)
        order.notes.create(user=request.user, message=message,
                           note_type=OrderNote.SYSTEM)
        return self.reload_page_response()

    def create_shipping_event(self, request, order, lines, quantities):
        code = request.POST['shipping_event_type']
        try:
            event_type = ShippingEventType._default_manager.get(code=code)
        except ShippingEventType.DoesNotExist:
            messages.error(request, _("The event type '%s' is not valid") % code)
            return self.reload_page_response()

        reference = request.POST.get('reference', None)
        try:
            EventHandler().handle_shipping_event(order, event_type, lines,
                                                 quantities,
                                                 reference=reference)
        except InvalidShippingEvent, e:
            messages.error(request, _("Unable to create shipping event: %s") % e)
        except InvalidStatus, e:
            messages.error(request, _("Unable to create shipping event: %s") % e)
        except PaymentError, e:
            messages.error(request, _("Unable to create shipping event due to payment error: %s") % e)
        else:
            messages.success(request, _("Shipping event created"))
        return self.reload_page_response()

    def create_order_payment_event(self, request, order):
        amount_str = request.POST.get('amount', None)
        try:
            amount = D(amount_str)
        except InvalidOperation:
            messages.error(request, _("Please choose a valid amount"))
            return self.reload_page_response()
        return self._create_payment_event(request, order, amount)

    def _create_payment_event(self, request, order, amount, lines=None,
                              quantities=None):
        code = request.POST['payment_event_type']
        try:
            event_type = PaymentEventType._default_manager.get(code=code)
        except PaymentEventType.DoesNotExist:
            messages.error(request, _("The event type '%s' is not valid") % code)
            return self.reload_page_response()
        try:
            EventHandler().handle_payment_event(order, event_type, amount,
                                                lines, quantities)
        except PaymentError, e:
            messages.error(request, _("Unable to change order status due to payment error: %s") % e)
        else:
            messages.info(request, _("Payment event created"))
        return self.reload_page_response()

    def create_payment_event(self, request, order, lines, quantities):
        amount_str = request.POST.get('amount', None)

        # If no amount passed, then we add up the total of the selected lines
        if not amount_str:
            amount = D('0.00')
            for line, quantity in zip(lines, quantities):
                amount += int(quantity) * line.line_price_incl_tax
        else:
            try:
                amount = D(amount_str)
            except InvalidOperation:
                messages.error(request, _("Please choose a valid amount"))
                return self.reload_page_response()

        return self._create_payment_event(request, order, amount, lines,
                                          quantities)

class LineDetailView(DetailView):
    model = Line
    context_object_name = 'line'
    template_name = 'dashboard/orders/line_detail.html'

    def get_object(self, queryset=None):
        return get_object_or_404(self.model, pk=self.kwargs['line_id'])

def get_changes_between_models(model1, model2, excludes=None):
    """
    Return a dict of differences between two model instances
    """
    if excludes is None:
        excludes = []
    changes = {}
    for field in model1._meta.fields:
        if not (isinstance(field, (fields.AutoField, fields.related.RelatedField))
                or field.name in excludes):
            if field.value_from_object(model1) != field.value_from_object(model2):
                changes[field.verbose_name] = (field.value_from_object(model1),
                                               field.value_from_object(model2))
    return changes

def get_change_summary(model1, model2):
    """
    Generate a summary of the changes between two address models
    """
    changes = get_changes_between_models(model1, model2, ['search_text'])
    change_descriptions = []
    for field, delta in changes.items():
        change_descriptions.append(_("%(field)s changed from '%(old_value)s' to '%(new_value)s'") % {
            'field': field,
            'old_value': delta[0],
            'new_value': delta[1]})
    return "\n".join(change_descriptions)

class ShippingAddressUpdateView(UpdateView):
    model = ShippingAddress
    context_object_name = 'address'
    template_name = 'dashboard/orders/shippingaddress_form.html'
    form_class = forms.ShippingAddressForm

    def get_object(self, queryset=None):
        return get_object_or_404(self.model, order__number=self.kwargs['number'])

    def get_context_data(self, **kwargs):
        ctx = super(ShippingAddressUpdateView, self).get_context_data(**kwargs)
        ctx['order'] = self.object.order
        return ctx

    def form_valid(self, form):
        old_address = ShippingAddress.objects.get(id=self.object.id)
        response = super(ShippingAddressUpdateView, self).form_valid(form)
        changes = get_change_summary(old_address, self.object)
        if changes:
            msg = _("Delivery address updated:\n%s") % changes
            self.object.order.notes.create(user=self.request.user, message=msg,
                                        note_type=OrderNote.SYSTEM)
        return response

    def get_success_url(self):
        messages.info(self.request, _("Delivery address updated"))
        return reverse('dashboard:order-detail', kwargs={'number': self.object.order.number, })


text:
local sass     = require "resty.sass"
local styles   = require "resty.sass.styles"
local tonumber = tonumber
local pairs    = pairs
local ngx      = ngx
local print    = ngx.print
local exit     = ngx.exit
local var      = ngx.var
local notfound = ngx.HTTP_NOT_FOUND
local error    = ngx.HTTP_INTERNAL_SERVER_ERROR
local io       = io
local open     = io.open
local close    = io.close
local sub      = string.sub
local nginx    = {}

local function enabled(val)
    if val == nil then return nil end
    return val == true or (val == "1" or val == "true" or val == "on")
end

local defaults = {
    cache                  = enabled(var.sass_cache),
    precision              = tonumber(var.sass_precision)             or 5,
    output_style           = tonumber(var.sass_output_style)          or styles[var.sass_output_style] or 0,
    source_comments        = enabled(var.sass_source_comments)        or false,
    source_map             = enabled(var.sass_source_map)             or false,
    source_map_embed       = enabled(var.sass_source_map_embed)       or false,
    source_map_contents    = enabled(var.sass_source_map_contents)    or false,
    source_map_url         = var.sass_source_map_url,
    omit_source_map_url    = enabled(var.sass_omit_source_map_url)    or false,
    is_indented_syntax_src = enabled(var.sass_is_indented_syntax_src) or false,
    include_path           = var.sass_include_path,
    plugin_path            = var.sass_plugin_path
}

function nginx.compile(options)
    local out = var.request_filename
    local len = #out
    local map = sub(out, len - 2) == "map"
    local inp
    if map then
        out = sub(out, 1, len - 4)
        inp = sub(out, 1, len - 7) .. "scss"
    else
        inp = sub(out, 1, len - 3) .. "scss"
    end
    local f = open(inp, "r")
    if not f then
        exit(notfound)
    end
    close(f)
    local c = options or defaults
    local s = sass.new()
    local o = s.options
    for k, v in pairs(defaults) do
        local opt = c[k] or v
        if opt then
            o[k] = opt
        end
    end
    if o.source_map then
        o.source_map_file = out .. ".map"
    end
    if o.cache then
        if map then
            local ok, c = s:compile_file(inp, out)
            if ok then return print(c) end
        else
            local c = s:compile_file(inp, out)
            if c then return print(c) end
        end
    else
        if map then
            local ok, c = s:compile_file(inp)
            if ok then return print(c) end
        else
            local c = s:compile_file(inp)
            if c then return print(c) end
        end
    end
    return exit(error)
end

return nginx


text:
import { NotificationType, Position } from 'vscode-languageclient';

export class PublishHintsNotification {
  public static type = new NotificationType<HintsParams>(
    'candy/textDocument/publishHints'
  );
}
export interface HintsParams {
  readonly uri: string;
  readonly hints: Hint[];
}
export interface Hint {
  readonly kind: HintKind;
  readonly text: string;
  readonly position: Position;
}
export type HintKind = 'value' | 'panic' | 'fuzz';


text:
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.0"?>

<!--
-->

<plugin>

   <extension point="org.eclipse.ui.newWizards">
      <!-- @generated forsyde -->
      <category
            id="org.eclipse.emf.ecore.Wizard.category.ID"
            name="%_UI_Wizard_category"/>
      <wizard
            id="forsyde.presentation.ForsydeModelWizardID"
            name="%_UI_ForsydeModelWizard_label"
            class="forsyde.presentation.ForsydeModelWizard"
            category="org.eclipse.emf.ecore.Wizard.category.ID"
            icon="icons/full/obj16/ForsydeModelFile.gif">
         <description>%_UI_ForsydeModelWizard_description</description>
         <selection class="org.eclipse.core.resources.IResource"/>
      </wizard>
   </extension>

   <extension point="org.eclipse.ui.editors">
      <!-- @generated forsyde -->
      <editor
            id="forsyde.presentation.ForsydeEditorID"
            name="%_UI_ForsydeEditor_label"
            icon="icons/full/obj16/ForsydeModelFile.gif"
            extensions="forsyde"
            class="forsyde.presentation.ForsydeEditor"
            contributorClass="forsyde.presentation.ForsydeActionBarContributor">
      </editor>
   </extension>

</plugin>


text:
LinkLuaModifier("modifier_item_guardian_greaves_arena", "items/item_guardian_greaves_arena.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_item_guardian_greaves_arena_effect", "items/item_guardian_greaves_arena.lua", LUA_MODIFIER_MOTION_NONE)

item_guardian_greaves_arena = class({
	GetIntrinsicModifierName = function() return "modifier_item_guardian_greaves_arena" end,
})

if IsServer() then
	function item_guardian_greaves_arena:OnSpellStart()
		local caster = self:GetCaster()
		caster:EmitSound("Item.GuardianGreaves.Activate")
		ParticleManager:CreateParticle("particles/items3_fx/warmage.vpcf", PATTACH_ABSORIGIN_FOLLOW, caster)
		for _,v in ipairs(FindUnitsInRadius(caster:GetTeamNumber(), caster:GetAbsOrigin(), nil, self:GetSpecialValueFor("radius"), self:GetAbilityTargetTeam(), self:GetAbilityTargetType(), self:GetAbilityTargetFlags(), FIND_ANY_ORDER, false)) do
			SafeHeal(v, self:GetSpecialValueFor("replenish_health"), self)
			v:GiveMana(self:GetSpecialValueFor("replenish_mana"))
			ParticleManager:CreateParticle("particles/items3_fx/warmage_recipient.vpcf", PATTACH_ABSORIGIN_FOLLOW, v, caster)
			v:EmitSound("Item.GuardianGreaves.Target")
			v:Purge(false, true, false, true, false)
		end
	end
end

modifier_item_guardian_greaves_arena = class({
	IsHidden      = function() return true end,
	GetAttributes = function() return MODIFIER_ATTRIBUTE_MULTIPLE end,
	IsPurgable    = function() return false end,
})

function modifier_item_guardian_greaves_arena:DeclareFunctions()
	return {
		MODIFIER_PROPERTY_STATS_STRENGTH_BONUS,
		MODIFIER_PROPERTY_STATS_AGILITY_BONUS,
		MODIFIER_PROPERTY_STATS_INTELLECT_BONUS,
		MODIFIER_PROPERTY_PHYSICAL_ARMOR_BONUS,
		MODIFIER_PROPERTY_HEALTH_BONUS,
		MODIFIER_PROPERTY_MANA_BONUS,
		MODIFIER_PROPERTY_MOVESPEED_BONUS_UNIQUE
	}
end
function modifier_item_guardian_greaves_arena:GetModifierHealthBonus()
	return self:GetAbility():GetSpecialValueFor("bonus_health")
end
function modifier_item_guardian_greaves_arena:GetModifierManaBonus()
	return self:GetAbility():GetSpecialValueFor("bonus_mana")
end
function modifier_item_guardian_greaves_arena:GetModifierMoveSpeedBonus_Special_Boots()
	return self:GetAbility():GetSpecialValueFor("bonus_movement")
end
function modifier_item_guardian_greaves_arena:GetModifierBonusStats_Strength()
	return self:GetAbility():GetSpecialValueFor("bonus_all_stats")
end
function modifier_item_guardian_greaves_arena:GetModifierBonusStats_Agility()
	return self:GetAbility():GetSpecialValueFor("bonus_all_stats")
end
function modifier_item_guardian_greaves_arena:GetModifierBonusStats_Intellect()
	return self:GetAbility():GetSpecialValueFor("bonus_all_stats")
end
function modifier_item_guardian_greaves_arena:GetModifierPhysicalArmorBonus()
	return self:GetAbility():GetSpecialValueFor("bonus_armor")
end
function modifier_item_guardian_greaves_arena:GetModifierAura()
	return "modifier_item_guardian_greaves_arena_effect"
end
function modifier_item_guardian_greaves_arena:IsAura()
	return true
end
function modifier_item_guardian_greaves_arena:GetAuraRadius()
	return self:GetAbility():GetSpecialValueFor("radius")
end
function modifier_item_guardian_greaves_arena:GetAuraSearchTeam()
	return self:GetAbility():GetAbilityTargetTeam()
end
function modifier_item_guardian_greaves_arena:GetAuraSearchType()
	return self:GetAbility():GetAbilityTargetType()
end
function modifier_item_guardian_greaves_arena:GetAuraSearchFlags()
	return self:GetAbility():GetAbilityTargetFlags()
end

modifier_item_guardian_greaves_arena_effect = class({})
function modifier_item_guardian_greaves_arena_effect:DeclareFunctions()
	return {
		MODIFIER_PROPERTY_HEALTH_REGEN_CONSTANT,
		MODIFIER_PROPERTY_PHYSICAL_ARMOR_BONUS
	}
end
function modifier_item_guardian_greaves_arena_effect:GetModifierConstantHealthRegen()
	local parent = self:GetParent()
	local ability = self:GetAbility()
	if ability then
		return ability:GetSpecialValueFor(parent:GetHealth() / parent:GetMaxHealth() > ability:GetSpecialValueFor("aura_bonus_threshold_pct") * 0.01 and "aura_health_regen" or "aura_health_regen_bonus")
	end
end
function modifier_item_guardian_greaves_arena_effect:GetModifierPhysicalArmorBonus()
	local parent = self:GetParent()
	local ability = self:GetAbility()
	if ability then
		local s = parent:GetHealthPercent() >= ability:GetSpecialValueFor("aura_bonus_threshold_pct") and "aura_armor" or "aura_armor_bonus"
		return ability:GetSpecialValueFor(s)
	end
end


text:
Juhuri Keyboards for Windows, OSX, and Linux

To Install, clone this repo and follow the instructions in the INSTALL file for each OS.


text:
/**
 * Linked List
 */

const Node = require('./nodes/').Node;

/**
 * Creates an empty LinkedList.
 *
 * @constructor
 */
function LinkedList() {
    this._head = null;
    this._tail = null;
    this._length = 0;
}

/**
 * Returns the number of elements in this list.
 *
 * @returns {Number} - the number of elements in this list.
 */
LinkedList.prototype.size = function () {
    return this._length;
};

/**
 * Tests if this LinkedList is empty.
 *
 * @returns {boolean} - true if and only if this LinkedList contains no items; false otherwise.
 */
LinkedList.prototype.isEmpty = function () {
    return this.size() === 0;
};

/**
 * Inserts the specified element at the beginning of this list.
 *
 * @param data - the element to add
 */
LinkedList.prototype.addFirst = function (data) {
    if (this.isEmpty()) {
        this._head = this._tail = new Node(data);
    } else {
        const newNode = new Node(data);
        newNode.setNext(this._head);
        this._head = newNode;
    }
    this._length++;
};

/**
 * Appends the specified element to the end of this list.
 *
 * @param data - the element to add
 */
LinkedList.prototype.addLast = function (data) {
    if (this.isEmpty()) {
        this._head = this._tail = new Node(data);
    } else {
        const newNode = new Node(data);
        this._tail.setNext(newNode);
        this._tail = newNode;
    }
    this._length++;
};

/**
 * Inserts the specified element at the specified position in this list.
 * Shifts the element currently at that position (if any) and any subsequent elements to the right
 * (adds one to their indices).
 *
 * @throws IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())
 * @param index - index at which the specified element is to be inserted
 * @param element - element to be inserted
 */
LinkedList.prototype.add = function (index, element) {
    if (index < 0 || index >= this.size())
        throw new Error('IndexOutOfBoundsException');

    const newNode = new Node(element);

    if (index === 0) {
        newNode.setNext(this._head);
        this._head = newNode;
    }
    else {
        let prev_node = this._head;
        for (; index > 1; index--)
            prev_node = prev_node.getNext();

        newNode.setNext(prev_node.getNext());
        prev_node.setNext(newNode);
    }
    this._length++;
};

/**
 * Removes the element at the specified position in this list. Shifts any subsequent elements to the left
 * (subtracts one from their indices).
 * Returns the element that was removed from the list.
 *
 * @throws IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())
 * @param index - the index of the element to be removed
 * @returns {*} - the element previously at the specified position
 */
LinkedList.prototype.remove = function (index) {
    if (index < 0 || index >= this.size())
        throw new Error('IndexOutOfBoundsException');

    let result;
    if (index === 0) {
        result = this._head;
        this._head = this._head.getNext();
    }
    else {
        let prev_node = this._head;
        for (; index > 1; index--)
            prev_node = prev_node.getNext();

        const old_node = prev_node.getNext();
        result = old_node;
        prev_node.setNext(old_node.getNext());
    }
    this._length--;
    return result;
};

/**
 * Removes all of the elements from this list. The list will be empty after this call returns.
 */
LinkedList.prototype.clear = function () {
    while (!this.isEmpty()) {
        this.remove(0);
    }
};

/**
 * Returns the element at the specified position in this list.
 *
 * @throws IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())
 * @param index - index of the element to return
 * @returns {*} - the element at the specified position in this list
 */
LinkedList.prototype.get = function (index) {
    if (index < 0 || index >= this.size())
        throw new Error('IndexOutOfBoundsException');

    if (index === 0)
        return this._head.getValue();
    else {
        let current_node = this._head;
        for (; index > 0; index--)
            current_node = current_node.getNext();

        return current_node.getValue();
    }
};

module.exports = LinkedList;


text:
package wikiparse

import (
	"crypto/md5"
	"encoding/hex"
	"net/url"
	"regexp"
	"strings"
)

var fileRE *regexp.Regexp

func init() {
	fileRE = regexp.MustCompile(`\[File:([^\|\]]+)`)
}

// FindFiles finds all the File references from within an article
// body.
//
// This includes things in comments, as many I found were commented
// out.
func FindFiles(text string) []string {
	cleaned := nowikiRE.ReplaceAllString(text, "")
	matches := fileRE.FindAllStringSubmatch(cleaned, 10000)

	rv := []string{}
	for _, x := range matches {
		rv = append(rv, x[1])
	}

	return rv
}

// URLForFile gets the wikimedia URL for the given named file.
func URLForFile(name string) string {
	m := md5.New()
	name = strings.Replace(name, " ", "_", -1)
	m.Write([]byte(name))
	h := hex.EncodeToString(m.Sum([]byte{}))

	return "http://upload.wikimedia.org/wikipedia/commons/" +
		string(h[0]) + "/" + h[0:2] + "/" + url.QueryEscape(name)
}


text:
class Daisydisk < Cask
  url 'http://www.daisydiskapp.com/downloads/DaisyDisk.zip'
  appcast 'http://www.daisydiskapp.com/downloads/appcastFeed.php'
  homepage 'http://www.daisydiskapp.com'
  version 'latest'
  sha256 :no_check
  link 'DaisyDisk.app'

  after_install do
    # Don't ask to move the app bundle to /Applications
    system '/usr/bin/defaults', 'write', 'com.daisydiskapp.DaisyDiskStandAlone', 'moveToApplicationsFolderAlertSuppress', '-bool', 'true'
  end
end


text:
BuildRequires += $(BinDir)/scons

include ../../Library/Scons.mk

Title=		MongoDB
Name=		mongodb
Version=	2.6.0
Site=		http://www.mongodb.org/
Source=		http://downloads.mongodb.org/src/$(Name)-src-r$(Version).tar.gz
License=	AGPL
LicenseFile=	$(SourceDir)/GNU-AGPL-3.0.txt

UncompressedName=$(Name)-src-r$(Version)


text:
package org.nvonop.selenium.framework.actionbot;

import org.nvonop.selenium.framework.controls.BaseControl;
import org.openqa.selenium.*;

import java.util.logging.Level;
import java.util.logging.Logger;

public class ActionBot extends BaseControl {

    private static final Logger LOGGER = Logger.getLogger(ActionBot.class
            .getName());

    public ActionBot(WebDriver driver) {

        super.driver = driver;
    }

    /**
     * Clicks the element.
     *
     * @param locator
     */
    public void click(By locator) {
        findControl(locator).click();
    }

    /**
     * Checks visibility
     *
     * @param locator
     */
    public boolean checkVisibility(By locator) {
        try {
            return findControl(locator).isDisplayed();
        } catch (ElementNotVisibleException e) {
            LOGGER.log(Level.INFO,
                    "ElementNotVisibleException in exists() method", e);
            return false;
        } catch (TimeoutException e) {
            LOGGER.log(Level.INFO, "TimeoutException in exists() method", e);
            return false;
        }
    }

    /**
     * Submits an element.
     *
     * @param locator
     */
    public void submit(By locator) {

        findControl(locator).submit();

    }

    /**
     * Reads the text value of an element.
     *
     * @param locator
     */
    public String readText(By locator) {

        return findControl(locator).getText();
    }

    /**
     * Reads the specified attribute of an element.
     *
     * @param locator
     * @param attribute
     */
    public String readAttribute(By locator, String attribute) {

        return findControl(locator).getAttribute("value");
    }

    /**
     * Type something into an input field. WebDriver doesn't normally clear
     * these before typing, so this method does that first. It also sends a
     * return key to move the focus out of the element.
     *
     * @param locator
     */
    public void type(By locator, String text) {

        findControl(locator).sendKeys(text);
    }
}


text:
using System;

namespace SharpLib.Audio.SoundFont
{
    internal class Preset
    {
        #region Ïîëÿ

        private ushort bank;

        internal ushort endPresetZoneIndex;

        internal uint genre;

        internal uint library;

        internal uint morphology;

        private string name;

        private ushort patchNumber;

        internal ushort startPresetZoneIndex;

        #endregion

        #region Ñâîéñòâà

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public ushort PatchNumber
        {
            get { return patchNumber; }
            set { patchNumber = value; }
        }

        public ushort Bank
        {
            get { return bank; }
            set { bank = value; }
        }

        public Zone[] Zones { get; set; }

        #endregion

        #region Ìåòîäû

        public override string ToString()
        {
            return String.Format("{0}-{1} {2}", bank, patchNumber, name);
        }

        #endregion
    }
}


text:
package expression

import (
	cesql "github.com/cloudevents/sdk-go/sql/v2"
	"github.com/cloudevents/sdk-go/sql/v2/utils"
	cloudevents "github.com/cloudevents/sdk-go/v2"
)

type notExpression baseUnaryExpression

func (l notExpression) Evaluate(event cloudevents.Event) (interface{}, error) {
	val, err := l.child.Evaluate(event)
	if err != nil {
		return nil, err
	}

	val, err = utils.Cast(val, cesql.BooleanType)
	if err != nil {
		return nil, err
	}

	return !(val.(bool)), nil
}

func NewNotExpression(child cesql.Expression) cesql.Expression {
	return notExpression{child: child}
}