text:
package foodtruck.mail;

import java.text.MessageFormat;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.google.common.base.Joiner;
import com.google.inject.Inject;

import org.joda.time.format.DateTimeFormatter;

import foodtruck.model.Location;
import foodtruck.model.LoginMethod;
import foodtruck.model.StaticConfig;
import foodtruck.model.Stop;
import foodtruck.model.Story;
import foodtruck.model.TrackingDevice;
import foodtruck.model.Truck;
import foodtruck.model.TruckStop;
import foodtruck.time.TimeFormatter;

/**
 * An email notifier that sends the email immediately.
 * @author aviolette
 * @since 4/29/13
 */
class SimpleEmailNotifier implements SystemNotificationService {
  public static Logger log = Logger.getLogger(SimpleEmailNotifier.class.getName());
  private final StaticConfig staticConfig;
  private final DateTimeFormatter dateTimeFormatter;
  private final EmailSender sender;

  @Inject
  public SimpleEmailNotifier(StaticConfig staticConfig, @TimeFormatter DateTimeFormatter dateTimeFormatter,
      EmailSender sender) {
    this.staticConfig = staticConfig;
    this.dateTimeFormatter = dateTimeFormatter;
    this.sender = sender;
  }

  @Override
  public void systemNotifyOffTheRoad(Truck truck, Story tweet) {
    String msgBody = MessageFormat.format("This tweet might indicate that {0} is off the road:\n" +
        "\n \"{1}\"\n\n" +
        "Click here to take the truck off the road: " + staticConfig.getBaseUrl() +
        "/admin/trucks/{2}/offtheroad", truck.getName(), tweet.getText(), truck.getId());
    sender.sendSystemMessage(truck.getName() + " might be off the road", msgBody);
  }

  private String locationAddedMessage(Location location, Story tweet, Truck truck) {
    return MessageFormat.format("This tweet \"{0}\" triggered the following location to be added {1}.  Click here to " +
            "view the location {4}/admin/locations/{2} .  " +
            "Also, view the truck here: {4}/admin/trucks/{3}", tweet.getText(), location.getName(),
        String.valueOf(location.getKey()), truck.getId(), staticConfig.getBaseUrl());
  }

  @Override
  public void systemNotifyLocationAdded(Location location, Story tweet, Truck truck) {
    try {
      sender.sendSystemMessage("New Location Added: " + location.getName(),
          locationAddedMessage(location, tweet, truck));
    } catch (Exception e) {
      log.log(Level.WARNING, e.getMessage(), e);
    }
  }

  @Override
  public void systemNotifyLocationAdded(Location location, String principalName) {
    try {
      sender.sendSystemMessage("New Location Added Via Vendor Portal: " + location.getName(),
          MessageFormat.format("{0} added the location {1}: {2}/admin/locations/{3} via the vendor portal.",
              principalName, location.getName(), staticConfig.getBaseUrl(), String.valueOf(location.getKey())));
    } catch (Exception e) {
      log.log(Level.WARNING, e.getMessage(), e);
    }

  }

  @Override
  public void systemNotifyTrucksAddedByObserver(Map<Truck, Story> trucksAdded) {
    StringBuilder builder = new StringBuilder("The following trucks were added: \n\n");
    for (Map.Entry<Truck, Story> entry : trucksAdded.entrySet()) {
      builder.append(entry.getKey()
          .getName())
          .append(" ")
          .append(staticConfig.getBaseUrl())
          .append("/admin/trucks/")
          .append(entry.getKey()
              .getId())
          .append(" => @")
          .append(entry.getValue()
              .getScreenName())
          .append(" '")
          .append(entry.getValue()
              .getText())
          .append("'\n\n");
    }
    try {
      sender.sendSystemMessage("New stops added by observers", builder.toString());
    } catch (Exception e) {
      log.log(Level.WARNING, e.getMessage(), e);
    }
  }

  @Override
  public void systemNotifyAutoCanceled(Truck truck, Story tweet) {
    String msgBody = MessageFormat.format("This tweet might indicate that {0} is off the road:\n" +
            "\n \"{1}\"\n\n" +
            "Because it was flagged as high-confidenced, all remaining stops were cancelled", truck.getName(),
        tweet.getText());
    sender.sendSystemMessage("Stops auto-canceled for " + truck.getName(), msgBody);
  }

  @Override
  public void systemNotifyWarnError(String error) {
    sender.sendSystemMessage("Errors detected! (" + staticConfig.getCityState() + ")",
        "Errors detected on the site:\n\n" + error);
  }

  @Override
  public void systemNotifyVendorPortalLogin(String screenName, LoginMethod loginMethod) {
    String msgBody = MessageFormat.format("Vendor {0} logged in to vendor portal via {1}", screenName,
        loginMethod.toString());
    sender.sendSystemMessage("Vendor portal login", msgBody);
  }

  @Override
  public void notifyAddMentionedTrucks(Set<String> truckIds, TruckStop stop, String text) {
    String truckIdString = Joiner.on(",")
        .join(truckIds),
        url = staticConfig.getBaseUrl() + "/admin/event_at/" + stop.getLocation()
            .getKey() +
            "?selected=" + truckIdString + "&startTime=" + dateTimeFormatter.print(stop.getStartTime()) + "&endTime=" +
            dateTimeFormatter.print(stop.getEndTime());
    String msgBody = MessageFormat.format(
        "This tweet \"{0}\"\n\n from {1} might have indicated that there additional trucks to be added to the system.\n\n  Click here {2} to add the trucks",
        text, stop.getTruck()
            .getName(), url);
    sender.sendSystemMessage("Truck was mentioned by another truck", msgBody);
  }

  @Override
  public void notifyDeviceAnomalyDetected(Stop stop, TrackingDevice device) {
    try {
      String msgBody = MessageFormat.format(
          "The last polled stop for {0} is different than the current polled stop {1}, with no intermediary travel.  The last stop in the travel history is {2}.\n\n{3}/admin/trucks/{4}",
          device.getLabel(), device.getLastLocation()
              .getName(), stop.getLocation()
              .getName(), staticConfig.getBaseUrl(), device.getTruckOwnerId());
      sender.sendSystemMessage("Device anomaly found for " + device.getLabel(), msgBody);
    } catch (Exception e) {
      log.log(Level.SEVERE, e.getMessage(), e);
    }
  }
}


text:
package net.bartzz.pexmanager.data;

import java.util.Collection;
import java.util.UUID;

import net.bartzz.pexmanager.Main;
import net.bartzz.pexmanager.manager.PermissionPlayerManager;

public class PermissionPlayer {

	private UUID 	uuid;
	private String 	nick;
	private Group 	group;
	private Collection<String> permissions;

	public PermissionPlayer(UUID uuid, String nick, Group group, Collection<String> permissions) {

		this.uuid = uuid;
		this.nick = nick;
		this.group = group;
		this.permissions = permissions;
	}

	public static PermissionPlayer getPermissionPlayer(UUID uuid) {
		for(PermissionPlayer player : PermissionPlayerManager.getPermissionPlayers()) {
			if(player.getUuid().equals(uuid)) {
				return player;
			}
		}
		return null;
	}

	public void insert() {
		Main.getMCDatabase().update(true, "insert into permission_players (uuid, nick, group) values ('" + this.uuid + "', '" + this.nick + "', '" + this.group.toString() + "')");
	}

	public void update(boolean now) {
		Main.getMCDatabase().update(now, "update permission_players set nick='" + this.nick + "', group='" + this.group.getName() + "' where uuid='" + this.uuid + "'");
	}

	public void delete() {
		Main.getMCDatabase().update(true, "delete from permission_players where uuid='" + this.uuid + "'");
	}

	public void addPermission(String permission) {
		if(this.permissions.contains(permission)) {
			return;
		}

		this.permissions.add(permission);
		Main.getMCDatabase().update(true, "insert into permission (permission, nick) values ('" + permission + "', '" + this.nick + "')");
	}

	public void removePermission(String permission) {
		if(!this.permissions.contains(permission)) {
			return;
		}

		this.permissions.remove(permission);
		Main.getMCDatabase().update(true, "delete from permission where permission='" + permission + "'");
	}

	public UUID getUuid() {
		return uuid;
	}

	public String getNick() {
		return nick;
	}

	public Group getGroup() {
		return group;
	}

	public Collection<String> getPermissions() {
		return permissions;
	}

	public void setGroup(Group group) {
		this.group = group;
	}

	public void setPermissions(Collection<String> permissions) {
		this.permissions = permissions;
	}
}

redpajama_set_name: RedPajamaGithub


text:
from venster.windows import *
from venster.wtl import *
from venster.lib import form

class MyForm(form.Form):
    """sample showing how a form can be prevented from closing by
    overriding the OnClose method of Form"""

    _window_icon_ = _window_icon_sm_ = Icon("blinky.ico")
    _window_title_ = "Test close"

    _form_menu_ = [(MF_POPUP, "&File",
                    [(MF_STRING, "&New\bCtrl+N", form.ID_NEW),
                     (MF_SEPARATOR,),
                     (MF_STRING, "&Exit", form.ID_EXIT)])]

    _form_accels_ = [(FCONTROL|FVIRTKEY, ord("N"), form.ID_NEW)]

    _form_exit_ = form.EXIT_ONLASTDESTROY

    def OnNew(self, event):
        newForm = MyForm()
        newForm.ShowWindow()

    cmd_handler(form.ID_NEW)(OnNew)

    def OnClose(self, event):
        res = MessageBox(self.handle, "Really close?", "Test Close", MB_YESNO | MB_ICONQUESTION)
        if res == IDYES: event.handled = False #mark as unhandled, default handler will close window

if __name__ == '__main__':
    mainForm = MyForm()
    mainForm.ShowWindow()

    application = Application()
    application.Run()


text:
import sys
import os
import scipy.io.wavfile
import scipy.signal
import matplotlib.pyplot as plt
# from matplotlib.pyplot import specgram

os.chdir(sys.argv[1])
# Directory provided as a command line argument will be opened to visualize the files inside
wavfiles = []
for wavfile in os.listdir(sys.argv[1]):
    if wavfile.endswith("wav"):
        wavfiles.append(wavfile)

wavfiles.sort()

# Declare sampling rates and song arrays for each arg
sampling_rates = []
song_arrays = []

# Read wavfiles
for wavfile in wavfiles:
	sampling_rate, song_array = scipy.io.wavfile.read(wavfile)
	sampling_rates.append(sampling_rate)
	song_arrays.append(song_array)

i = 1  # plot number
# Plot spectrogram for each wave_file
for song_id, song_array, sampling_rate in zip(wavfiles, song_arrays, sampling_rates):
    # Create subplots
    plt.subplot(10, 10, i)
    i += 1
    #plt.title(song_id)
    plt.specgram(song_array[:30000], Fs=sampling_rate)
    print("Plotting spectrogram of song_id: " + song_id)

plt.savefig('Spectrogram.png')
plt.show()


text:
using HarmonyLib;
using HarmonyLibTests.Assets;
using NUnit.Framework;
using System;

namespace HarmonyLibTests.Tools
{
	[TestFixture, NonParallelizable]
	public class TestTraverse_Methods : TestLogger
	{
		[Test]
		public void Traverse_Method_Instance()
		{
			var instance = new TraverseMethods_Instance();
			var trv = Traverse.Create(instance);

			instance.Method1_called = false;
			var mtrv1 = trv.Method("Method1");
			Assert.AreEqual(null, mtrv1.GetValue());
			Assert.AreEqual(true, instance.Method1_called);

			var mtrv2 = trv.Method("Method2", new object[] { "arg" });
			Assert.AreEqual("argarg", mtrv2.GetValue());
		}

		[Test]
		public void Traverse_Method_Static()
		{
			var trv = Traverse.Create(typeof(TraverseMethods_Static));
			var mtrv = trv.Method("StaticMethod", new object[] { 6, 7 });
			Assert.AreEqual(42, mtrv.GetValue<int>());
		}

		[Test]
		public void Traverse_Method_VariableArguments()
		{
			var trv = Traverse.Create(typeof(TraverseMethods_VarArgs));

			Assert.AreEqual(30, trv.Method("Test1", 10, 20).GetValue<int>());
			Assert.AreEqual(60, trv.Method("Test2", 10, 20, 30).GetValue<int>());

			// Calling varargs methods directly won't work. Use parameter array instead
			// Assert.AreEqual(60, trv.Method("Test3", 100, 10, 20, 30).GetValue<int>());
			Assert.AreEqual(6000, trv.Method("Test3", 100, new int[] { 10, 20, 30 }).GetValue<int>());
		}

		[Test]
		public void Traverse_Method_RefParameters()
		{
			var trv = Traverse.Create(typeof(TraverseMethods_Parameter));

			string result = null;
			var parameters = new object[] { result };
			var types = new Type[] { typeof(string).MakeByRefType() };
			var mtrv1 = trv.Method("WithRefParameter", types, parameters);
			Assert.AreEqual("ok", mtrv1.GetValue<string>());
			Assert.AreEqual("hello", parameters[0]);
		}

		[Test]
		public void Traverse_Method_OutParameters()
		{
			var trv = Traverse.Create(typeof(TraverseMethods_Parameter));

			string result = null;
			var parameters = new object[] { result };
			var types = new Type[] { typeof(string).MakeByRefType() };
			var mtrv1 = trv.Method("WithOutParameter", types, parameters);
			Assert.AreEqual("ok", mtrv1.GetValue<string>());
			Assert.AreEqual("hello", parameters[0]);
		}

		[Test]
		public void Traverse_Method_Overloads()
		{
			var instance = new TraverseMethods_Overloads();
			var trv = Traverse.Create(instance);

			var mtrv1 = trv.Method("SomeMethod", new Type[] { typeof(string), typeof(bool) });
			Assert.AreEqual(true, mtrv1.GetValue<bool>("test", false));
			Assert.AreEqual(false, mtrv1.GetValue<bool>("test", true));
		}
	}
}


text:
/*
 * Base structure
 */

/* Move down content because we have a fixed navbar that is 50px tall */
body {
  padding-top: 50px;
}

/*
 * Global add-ons
 */

.sub-header {
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

/*
 * Top navigation
 * Hide default border to remove 1px line.
 */
.navbar-fixed-top {
  border: 0;
}

/*
 * Main content
 */
.main {
  padding: 20px;
}
@media (min-width: 768px) {
  .main {
    padding-right: 40px;
    padding-left: 40px;
  }
}
.main .page-header {
  margin-top: 0;
}

.posts-container {
  padding-top: 10px;
}

@media (min-width: 768px) {
  .posts-container {
    margin: 0 auto;
    width: 70%;
  }
}

.post .post-profile-picture {
  width: 40px;
  height: 40px;
  float: left;
  margin-right: 10px;
}

.post .post-profile-name {
  padding-left: 10px;
}

.post .post-time {
  font-size: 80%;
}

.form-login {
  max-width: 330px;
  padding: 15px;
  margin: 0 auto;
}
.form-login .form-login-heading,
.form-login .checkbox {
  margin-bottom: 10px;
}
.form-login .checkbox {
  font-weight: normal;
}
.form-login .form-control {
  position: relative;
  height: auto;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  padding: 10px;
  font-size: 16px;
}
.form-login .form-control:focus {
  z-index: 2;
}
.form-login input[type="email"] {
  margin-bottom: -1px;
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
}
.form-login input[type="password"] {
  margin-bottom: 10px;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}

.navbar-profile-picture {
  width: 45px;
  height: 45px;
  margin-top: 3px;
  margin-right: 10px;
}

.tag {
  margin-left: 5px;
}

.tag a {
  color: #fff;
}

.signup-form {
  max-width: 330px;
  padding: 15px;
  margin: 0 auto;
}
.signup-form .signup-form-heading {
  margin-bottom: 10px;
}
.signup-form .form-control {
  position: relative;
  height: auto;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  padding: 10px;
  font-size: 16px;
}
.signup-form .form-control:focus {
  z-index: 2;
}
.signup-form input {
  margin-bottom: -1px;
}
.signup-form input, .signup-form select {
  border-radius: 0px;
}
.signup-form input:first-of-type {
  border-top-right-radius: 4px;
  border-top-left-radius: 4px;
}

.signup-form input:last-of-type {
  margin-bottom: 10px;
  border-bottom-right-radius: 4px;
  border-bottom-left-radius: 4px;
}

.signup-form input[type='date']::before {
  content: attr(placeholder)
}


text:
package cc.siara.csv_ml;

import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import cc.siara.csv.CSVParser;

/**
 * Constructs csv_ml string from Document object
 *
 * @author Arundale R.
 * @since 1.0
 */
public class Outputter {

    /**
     * Constructs csv_ml string from Document object
     *
     * @param dom
     *            Input document
     * @return output csv_ml string
     */
    public static String generate(Document dom) {

        // Initialize schema with default directive. TODO: to handle encoding,
        // root and namespaces
        StringBuffer schema = new StringBuffer("csv_ml,1.0\n");

        StringBuffer data = new StringBuffer();
        outputCSVRecursively(dom.getDocumentElement(), schema, data, "");
        return schema.append("end_schema\n").append(data).toString();

    }

    /**
     * Builds the csv_ml string starting at the root node
     *
     * @param ele
     *            Initially the root element
     * @param schema
     * @param data
     * @param hierarchy_space_prefix
     */
    private static void outputCSVRecursively(Element ele, StringBuffer schema,
            StringBuffer data, String hierarchy_space_prefix) {

        String node_name = ele.getNodeName();

        boolean is_schema_updated = false;
        if (schema.indexOf("\n" + hierarchy_space_prefix + node_name + ",") != -1)
            is_schema_updated = true;

        // Export node
        // TODO: does not generate data for root node
        if (ele.getParentNode().getParentNode() != null) {

            // Export node
            if (!is_schema_updated)
                schema.append(hierarchy_space_prefix).append(node_name);
            data.append(hierarchy_space_prefix).append(node_name);

            // Export attributes
            NamedNodeMap attributes = ele.getAttributes();
            for (int j = 0; j < attributes.getLength(); j++) {
                if (!is_schema_updated)
                    schema.append(",").append(attributes.item(j).getNodeName());
                data.append(",")
                        .append(Util.encodeToCSVText(attributes.item(j)
                                .getNodeValue()));
            }

            // TODO: Is text content to be exported?
            // String tc = ele.getTextContent();
            // if (tc != null && !tc.equals(""))
            // data.append(",").append(encodeToCSVText(tc));

            // Export CData sections
            NodeList childNodes = ele.getChildNodes();
            for (int i = 0; i < childNodes.getLength(); i++) {
                if (childNodes.item(i).getNodeType() != Node.CDATA_SECTION_NODE)
                    continue;
                CDATASection cdata_section = (CDATASection) childNodes.item(i);
                data.append(",").append(
                        Util.encodeToCSVText(cdata_section.getData()));
            }
            if (!is_schema_updated)
                schema.append("\n");
            data.append("\n");
            hierarchy_space_prefix += " ";

        }

        // Recurse children
        NodeList childNodes = ele.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            if (childNodes.item(i).getNodeType() != Node.ELEMENT_NODE)
                continue;
            outputCSVRecursively((Element) childNodes.item(i), schema, data,
                    hierarchy_space_prefix);
        }

    }

}


text:
var assert = require("assert"),
    vows = require("vows"),
    mock = require("./../lib/mock"),
    authBasic = require("./../lib/auth/basic"),
    utils = require("./../lib/utils");

vows.describe("auth/basic").addBatch({
    "An authBasic middleware": {
        "when no validation function is given": {
            "should throw": function () {
                assert.throws(function () {
                    var app = authBasic(utils.empty);
                }, /validation function/);
            }
        },
        "when authorization fails": {
            topic: function () {
                var user = "michael";
                var pass = "s3krit";
                var credentials = new Buffer(user + ":" + pass).toString("base64");

                var app = authBasic(utils.empty, function (user, pass, callback) {
                    callback(null, false);
                });

                mock.request({
                    headers: {
                        "Authorization": "Basic " + credentials
                    }
                }, app, this.callback);
            },
            "should return 401": function (err, status, headers, body) {
                assert.equal(status, 401);
                assert.ok(headers["WWW-Authenticate"]);
            }
        },
        "when authorization succeeds": {
            topic: function () {
                var user = "michael";
                var pass = "s3krit";
                var credentials = new Buffer(user + ":" + pass).toString("base64");

                var app = authBasic(function (env, callback) {
                    callback(200, {
                        "Content-Type": "text/plain",
                        "X-RemoteUser": env.remoteUser
                    }, "");
                }, function (user, pass, callback) {
                    callback(null, user);
                });

                mock.request({
                    headers: {
                        "Authorization": "Basic " + credentials
                    }
                }, app, this.callback);
            },
            "should pass the request downstream": function (err, status, headers, body) {
                assert.equal(status, 200);
            },
            "should set the remoteUser environment variable": function (err, status, headers, body) {
                assert.ok(headers["X-RemoteUser"]);
                assert.equal(headers["X-RemoteUser"], "michael");
            }
        }
    }
}).export(module);


text:
package org.elasticsearch.xpack.runtimefields.mapper;

import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.util.ArrayUtil;
import org.elasticsearch.search.lookup.SearchLookup;

import java.util.Map;

/**
 * Common base class for script field scripts that return long values.
 */
public abstract class AbstractLongFieldScript extends AbstractFieldScript {
    private long[] values = new long[1];
    private int count;

    public AbstractLongFieldScript(String fieldName, Map<String, Object> params, SearchLookup searchLookup, LeafReaderContext ctx) {
        super(fieldName, params, searchLookup, ctx);
    }

    /**
     * Execute the script for the provided {@code docId}.
     */
    public final void runForDoc(int docId) {
        count = 0;
        setDocument(docId);
        execute();
    }

    /**
     * Values from the last time {@link #runForDoc(int)} was called. This array
     * is mutable and will change with the next call of {@link #runForDoc(int)}.
     * It is also oversized and will contain garbage at all indices at and
     * above {@link #count()}.
     */
    public final long[] values() {
        return values;
    }

    /**
     * The number of results produced the last time {@link #runForDoc(int)} was called.
     */
    public final int count() {
        return count;
    }

    protected final void emit(long v) {
        checkMaxSize(count);
        if (values.length < count + 1) {
            values = ArrayUtil.grow(values, count + 1);
        }
        values[count++] = v;
    }
}


text:
require 'active_record'

require 'rpush/daemon/store/active_record/reconnectable'

module Rpush
  module Daemon
    module Store
      class ActiveRecord
        include Reconnectable

        DEFAULT_MARK_OPTIONS = {:persist => true}

        def deliverable_notifications(apps)
          with_database_reconnect_and_retry do
            batch_size = Rpush.config.batch_size
            relation = Rpush::Notification.ready_for_delivery.for_apps(apps)
            relation = relation.limit(batch_size) unless Rpush.config.push
            relation.to_a
          end
        end

        def mark_retryable(notification, deliver_after, opts = {})
          opts = DEFAULT_MARK_OPTIONS.dup.merge(opts)
          notification.retries += 1
          notification.deliver_after = deliver_after

          if opts[:persist]
            with_database_reconnect_and_retry do
              notification.save!(:validate => false)
            end
          end
        end

        def mark_batch_retryable(notifications, deliver_after)
          ids = []
          notifications.each do |n|
            mark_retryable(n, deliver_after, :persist => false)
            ids << n.id
          end
          with_database_reconnect_and_retry do
            Rpush::Notification.where(:id => ids).update_all(['retries = retries + 1, deliver_after = ?', deliver_after])
          end
        end

        def mark_delivered(notification, time, opts = {})
          opts = DEFAULT_MARK_OPTIONS.dup.merge(opts)
          notification.delivered = true
          notification.delivered_at = time

          if opts[:persist]
            with_database_reconnect_and_retry do
              notification.save!(:validate => false)
            end
          end
        end

        def mark_batch_delivered(notifications)
          now = Time.now
          ids = []
          notifications.each do |n|
            mark_delivered(n, now, :persist => false)
            ids << n.id
          end
          with_database_reconnect_and_retry do
            Rpush::Notification.where(:id => ids).update_all(['delivered = ?, delivered_at = ?', true, now])
          end
        end

        def mark_failed(notification, code, description, time, opts = {})
          opts = DEFAULT_MARK_OPTIONS.dup.merge(opts)
          notification.delivered = false
          notification.delivered_at = nil
          notification.failed = true
          notification.failed_at = time
          notification.error_code = code
          notification.error_description = description

          if opts[:persist]
            with_database_reconnect_and_retry do
              notification.save!(:validate => false)
            end
          end
        end

        def mark_batch_failed(notifications, code, description)
          now = Time.now
          ids = []
          notifications.each do |n|
            mark_failed(n, code, description, now, :persist => false)
            ids << n.id
          end
          with_database_reconnect_and_retry do
            Rpush::Notification.where(:id => ids).update_all(['delivered = ?, delivered_at = NULL, failed = ?, failed_at = ?, error_code = ?, error_description = ?', false, true, now, code, description])
          end
        end

        def create_apns_feedback(failed_at, device_token, app)
          with_database_reconnect_and_retry do
            Rpush::Apns::Feedback.create!(:failed_at => failed_at,
              :device_token => device_token, :app => app)
          end
        end

        def create_gcm_notification(attrs, data, registration_ids, deliver_after, app)
          notification = Rpush::Gcm::Notification.new
          create_gcm_like_notification(notification, attrs, data, registration_ids, deliver_after, app)
        end

        def create_adm_notification(attrs, data, registration_ids, deliver_after, app)
          notification = Rpush::Adm::Notification.new
          create_gcm_like_notification(notification, attrs, data, registration_ids, deliver_after, app)
        end

        def update_app(app)
          with_database_reconnect_and_retry do
            app.save!
          end
        end

        def update_notification(notification)
          with_database_reconnect_and_retry do
            notification.save!
          end
        end

        def after_daemonize
          reconnect_database
        end

        def release_connection
          begin
            ::ActiveRecord::Base.connection_pool.release_connection
          rescue StandardError => e
            Rpush.logger.error(e)
          end
        end

        private

        def create_gcm_like_notification(notification, attrs, data, registration_ids, deliver_after, app)
          with_database_reconnect_and_retry do
            notification.assign_attributes(attrs)
            notification.data = data
            notification.registration_ids = registration_ids
            notification.deliver_after = deliver_after
            notification.app = app
            notification.save!
            notification
          end
        end
      end
    end
  end
end


text:
If "trust proxy" is enabled, this variable contains the IP addresses in this request's "X-Forwarded-For" header as an array of the IP address strings. Otherwise an empty array is returned.

### Usage
```js
req.ips;
```

### Example
If a request contains a header: "X-Forwarded-For: client, proxy1, proxy2":

```js
req.ips;
// -> ["client", "proxy1", "proxy2"]`

// ("proxy2" is the furthest "down-stream" IP address)
```

<docmeta name="uniqueID" value="reqips78262">
<docmeta name="displayName" value="req.ips">


text:
<?php echo $post['title']; ?>

Posted on: <?php echo $post['created_at']; ?>

<img src="<?php echo site_url(); ?>assets/images/posts/<?php echo $post['post_image']; ?>">

	<?php echo $post['body']; ?>

<?php if($this->session->userdata('user_id') == $post['user_id']): ?>

	<a class="btn btn-default pull-left" href="<?php echo base_url(); ?>posts/edit/<?php echo $post['slug']; ?>">Edit
	<?php echo form_open('/posts/delete/'.$post['id']); ?>
		<input type="submit" value="Delete" class="btn btn-warning">
	</form>
<?php endif; ?>

Comments

<?php if($comments) : ?>
	<?php foreach($comments as $comment) : ?>

<?php echo $comment['body']; ?> [by <?php echo $comment['name']; ?>]

	<?php endforeach; ?>
<?php else : ?>

No Comments To Display

<?php endif; ?>

Add Comment

<?php echo validation_errors(); ?>
<?php echo form_open('comments/create/'.$post['id']); ?>

		Name
		<input type="text" name="name" class="form-control">

		Email
		<input type="text" name="email" class="form-control">

		Body
		<textarea name="body" class="form-control"></textarea>

	<input type="hidden" name="slug" value="<?php echo $post['slug']; ?>">
	<button class="btn btn-primary" type="submit">Submit</button>
</form>


text:
import React from 'react';
import Radium, { StyleRoot } from 'radium'

import stylePlayer from '../style/liveplayer'

// import './index.scss';

const log = console.log.bind(console);
const logError = console.error ? console.error.bind(console) : log;
const logWarning = console.warn ? console.warn.bind(console) : log;

/* converts given number of seconds to standard time display format
 * http://goo.gl/kEvnKn
 */
function convertToTime (number) {
  const mins = Math.floor(number / 60);
  const secs = (number % 60).toFixed();
  return `${ mins < 10 ? '0' : '' }${ mins }:${ secs < 10 ? '0' : '' }${ secs }`;
}

/*
 * AudioPlayer
 *
 * Accepts 'playlist' prop of the form:
 *
 * [{ "url": "./path/to/file.mp3",
 *    "displayText": "ArtistA - Track 1" },
 *  { "url": "https://domain.com/track2.ogg",
 *    "displayText": "ArtistB - Track 2" }]
 *
 * Accepts 'autoplay' prop (true/[false]).
 *
 * Accepts 'autoplayDelayInSeconds' prop (default 0).
 *
 * Accepts 'gapLengthInSeconds' prop (default 0).
 * Specifies gap at end of one track before next
 * track begins (ignored for manual skip).
 *
 * Accepts 'hideBackSkip' prop (default false,
 * hides back skip button if true).
 *
 * Accepts 'hideForwardSkip' prop (default false,
 * hides forward skip button if true).
 *
 * Accepts 'disableSeek' prop (default false,
 * disables seeking through the audio if true).
 *
 * Accepts 'cycle' prop (default true,
 * starts playing at the beginning of the playlist
 * when finished if true).
 *
 * Accepts 'stayOnBackSkipThreshold' prop, default 5,
 * is number of seconds to progress until pressing back skip
 * restarts the current track.
 *
 * Accepts 'style' prop, object, is applied to
 * outermost div (React styles).
 *
 * Accepts 'onMediaEvent' prop, an object used for
 * listening to media events on the underlying audio element.
 *
 * Accepts 'audioElementRef' prop, a function called after
 * the component mounts and before it unmounts with the
 * internally-referenced HTML audio element as its only parameter.
 * Similar to: https://facebook.github.io/react/docs/refs-and-the-dom.html
 */
class AudioPlayer extends React.Component {

  constructor (props) {
    super(props);

    /* true if the user is currently dragging the mouse
     * to seek a new track position
     */
    this.seekInProgress = false;
    // index matching requested track (whether track has loaded or not)
    this.currentTrackIndex = 0;

    this.defaultState = {
      /* activeTrackIndex will change to match
       * this.currentTrackIndex once metadata has loaded
       */
      activeTrackIndex: -1,
      // indicates whether audio player should be paused
      paused: true,
      /* elapsed time for current track, in seconds -
       * DISPLAY ONLY! the actual elapsed time may
       * not match up if we're currently seeking, since
       * the new time is visually previewed before the
       * audio seeks.
       */
      displayedTime: 0,
      playing: false
    };

    this.state = this.defaultState;

    // html audio element used for playback
    this.audio = null;
    this.audioProgressContainer = null;
    /* bounding rectangle used for calculating seek
     * position from mouse/touch coordinates
     */
    this.audioProgressBoundingRect = null;

    // event listeners to add on mount and remove on unmount
    this.seekReleaseListener = e => this.seek(e);
    // this.resizeListener = () => this.fetchAudioProgressBoundingRect();
    this.audioPlayListener = () => this.setState({ paused: false });
    this.audioPauseListener = () => this.setState({ paused: true });
    this.audioEndListener = () => {
      const gapLengthInSeconds = this.props.gapLengthInSeconds || 0;
      clearTimeout(this.gapLengthTimeout);
      this.gapLengthTimeout = setTimeout(() => this.skipToNextTrack(), gapLengthInSeconds * 1000);
    };
    this.audioStallListener = () => this.togglePause(true);
    this.audioTimeUpdateListener = () => this.handleTimeUpdate();
    this.audioMetadataLoadedListener = () => this.setState({
      activeTrackIndex: this.currentTrackIndex
    });
  }

  componentDidMount () {
    // add event listeners bound outside the scope of our component
    window.addEventListener('mouseup', this.seekReleaseListener);
    document.addEventListener('touchend', this.seekReleaseListener);

    const audio = this.audio = document.createElement('audio');

    // add event listeners on the audio element
    audio.preload = 'metadata';
    audio.addEventListener('play', this.audioPlayListener);
    audio.addEventListener('pause', this.audioPauseListener);
    audio.addEventListener('ended', this.audioEndListener);
    audio.addEventListener('stalled', this.audioStallListener);
    audio.addEventListener('timeupdate', this.audioTimeUpdateListener);
    audio.addEventListener('loadedmetadata', this.audioMetadataLoadedListener);
    this.addMediaEventListeners(this.props.onMediaEvent);

    if (this.props.playlist && this.props.playlist.length) {
      this.updateSource();
      if (this.props.autoplay) {
        const delay = this.props.autoplayDelayInSeconds || 0;
        clearTimeout(this.delayTimeout);
        this.delayTimeout = setTimeout(() => this.togglePause(false), delay * 1000);
      }
    }

    if (this.props.audioElementRef) {
      this.props.audioElementRef(audio);
    }
  }

  componentWillUnmount () {
    // remove event listeners bound outside the scope of our component
    window.removeEventListener('mouseup', this.seekReleaseListener);
    document.removeEventListener('touchend', this.seekReleaseListener);
    window.removeEventListener('resize', this.resizeListener);

    // remove event listeners on the audio element
    this.audio.removeEventListener('play', this.audioPlayListener);
    this.audio.removeEventListener('pause', this.audioPauseListener);
    this.audio.removeEventListener('ended', this.audioEndListener);
    this.audio.removeEventListener('stalled', this.audioStallListener);
    this.audio.removeEventListener('timeupdate', this.audioTimeUpdateListener);
    this.audio.removeEventListener('loadedmetadata', this.audioMetadataLoadedListener);
    this.removeMediaEventListeners(this.props.onMediaEvent);
    clearTimeout(this.gapLengthTimeout);
    clearTimeout(this.delayTimeout);

    // pause the audio element before we unmount
    this.audio.pause();

    if (this.props.audioElementRef) {
      this.props.audioElementRef(this.audio);
    }
  }

  componentWillReceiveProps (nextProps) {
    // Update media event listeners that may have changed
    this.removeMediaEventListeners(this.props.onMediaEvent);
    this.addMediaEventListeners(nextProps.onMediaEvent);

    const newPlaylist = nextProps.playlist;
    if (!newPlaylist || !newPlaylist.length) {
      if (this.audio) {
        this.audio.src = '';
      }
      this.currentTrackIndex = 0;
      return this.setState(this.defaultState);
    }

    const oldPlaylist = this.props.playlist;

    const currentTrackUrl = ((oldPlaylist || [])[this.currentTrackIndex] || {}).url;
    this.currentTrackIndex = 1;
    /* if the track we're already playing is in the new playlist, update the
     * activeTrackIndex.
     */
    if (this.currentTrackIndex !== -1) {
      this.setState({
        activeTrackIndex: this.currentTrackIndex
      });
    }
  }

  addMediaEventListeners (mediaEvents) {
    if (!mediaEvents) {
      return;
    }
    Object.keys(mediaEvents).forEach((type) => {
      if (typeof mediaEvents[type] !== 'function') {
        return;
      }
      this.audio.addEventListener(type, mediaEvents[type]);
    });
  }

  removeMediaEventListeners (mediaEvents) {
    if (!mediaEvents) {
      return;
    }
    Object.keys(mediaEvents).forEach((type) => {
      if (typeof mediaEvents[type] !== 'function') {
        return;
      }
      this.audio.removeEventListener(type, mediaEvents[type]);
    });
  }

  componentDidUpdate () {
    /* if we loaded a new playlist and reset the current track marker, we
     * should load up the first one.
     */
    if (this.audio && this.currentTrackIndex === -1) {
      this.skipToNextTrack(false);
    }
  }

  togglePause (value) {
    if (!this.audio) {
      return;
    }
    const pause = typeof value === 'boolean' ? value : !this.state.paused;
    if (pause) {
        this.audio.pause();
        this.setState({ playing: !this.state.playing })
        return;
    }
    if (!this.props.playlist || !this.props.playlist.length) {
      return;
    }
    try {
      this.audio.play();
        this.setState({ playing: !this.state.playing })
    } catch (error) {
      logError(error);
      const warningMessage =
        'Audio playback failed at ' +
        new Date().toLocaleTimeString() +
        '! (Perhaps autoplay is disabled in this browser.)';
      logWarning(warningMessage);
    }
  }

//   backSkip () {
//     if (!this.props.playlist || !this.props.playlist.length) {
//       return;
//     }
//     const audio = this.audio;
//     let stayOnBackSkipThreshold = this.props.stayOnBackSkipThreshold;
//     if (isNaN(stayOnBackSkipThreshold)) {
//       stayOnBackSkipThreshold = 5;
//     }
//     if (audio.currentTime >= stayOnBackSkipThreshold) {
//       return audio.currentTime = 0;
//     }
//     let i = this.currentTrackIndex - 1;
//     if (i < 0) {
//       i = this.props.playlist.length - 1;
//     }
//     this.currentTrackIndex = i - 1;
//     this.skipToNextTrack();
//   }

  updateSource () {
    this.audio.src = this.props.playlist[this.currentTrackIndex].url;
  }

//   fetchAudioProgressBoundingRect () {
//     this.audioProgressBoundingRect = this.audioProgressContainer.getBoundingClientRect();
//   }

  handleTimeUpdate () {
    if (!this.seekInProgress && this.audio) {
      this.setState({
        displayedTime: this.audio.currentTime
      });
    }
  }

  adjustDisplayedTime (event) {
    if (!this.props.playlist || !this.props.playlist.length || this.props.disableSeek) {
      return;
    }
    // make sure we don't select stuff in the background while seeking
    if (event.type === 'mousedown' || event.type === 'touchstart') {
      this.seekInProgress = true;
      document.body.classList.add('noselect');
    } else if (!this.seekInProgress) {
      return;
    }
    /* we don't want mouse handlers to receive the event
     * after touch handlers if we're seeking.
     */
    event.preventDefault();
    const boundingRect = this.audioProgressBoundingRect;
    const isTouch = event.type.slice(0, 5) === 'touch';
    const pageX = isTouch ? event.targetTouches.item(0).pageX : event.pageX;
    const position = pageX - boundingRect.left - document.body.scrollLeft;
    const containerWidth = boundingRect.width;
    const progressPercentage = position / containerWidth;
    this.setState({
      displayedTime: progressPercentage * this.audio.duration
    });
  }

  seek (event) {
    /* this function is activated when the user lets
     * go of the mouse, so if .noselect was applied
     * to the document body, get rid of it.
     */
    document.body.classList.remove('noselect');
    if (!this.seekInProgress) {
      return;
    }
    /* we don't want mouse handlers to receive the event
     * after touch handlers if we're seeking.
     */
    event.preventDefault();
    this.seekInProgress = false;
    const displayedTime = this.state.displayedTime;
    if (isNaN(displayedTime)) {
      return;
    }
    this.audio.currentTime = displayedTime;
  }

  render () {
    const activeIndex = this.state.activeTrackIndex;
    const displayText = this.props.playlist ? (
      activeIndex < 0 ? null : this.props.playlist[activeIndex].displayText
    ) : 'Please load a playlist';

    const displayedTime = this.state.displayedTime;
    const duration = this.audio && this.audio.duration || 0;

    const elapsedTime = convertToTime(displayedTime);
    const fullTime = convertToTime(duration);
    const timeRatio = `${ elapsedTime } / ${ fullTime }`;

    const progressBarWidth = `${ (displayedTime / duration) * 100 }%`;

    const adjustDisplayedTime = e => this.adjustDisplayedTime(e);

    let element
    if (this.state.playing) {
      element = (<svg fill="#fff" viewBox="0 0 24 24" height="100%" xmlns="http://www.w3.org/2000/svg">
          <path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/>
          <path d="M0 0h24v24H0z" fill="none"/>
        </svg>)
    } else {
      element = (<svg fill="#fff" viewBox="0 0 24 24" height="100%" xmlns="http://www.w3.org/2000/svg">
            <path d="M8 5v14l11-7z"/>
            <path d="M0 0h24v24H0z" fill="none"/>
          </svg>)
    }

    return (
      <StyleRoot>
        <div
          id="audio_player"
          title={displayText}
          style={this.props.style}
        >
          <div
            style={stylePlayer.button}
          >
            <div onClick={() => this.togglePause()}>
              {element}
            </div>
          </div>
        </div>
      </StyleRoot>
    );
  }

}

AudioPlayer.propTypes = {
  playlist: React.PropTypes.array,
  autoplay: React.PropTypes.bool,
  autoplayDelayInSeconds: React.PropTypes.number,
  gapLengthInSeconds: React.PropTypes.number,
  hideBackSkip: React.PropTypes.bool,
  hideForwardSkip: React.PropTypes.bool,
  cycle: React.PropTypes.bool,
  disableSeek: React.PropTypes.bool,
  stayOnBackSkipThreshold: React.PropTypes.number,
  style: React.PropTypes.object,
  onMediaEvent: React.PropTypes.object,
  audioElementRef: React.PropTypes.func
};

AudioPlayer.defaultProps = {
  cycle: true
};

export default AudioPlayer;


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="referrer" content="always">
    <meta name="robots" content="index, follow">
    <link rel="icon" href="about:blank" type="image/x-icon">

    <title>
        events
    </title>

    <meta name="title" content="events">
    <meta name="description" content="">
    <meta name="keywords" content="">

    <link rel="stylesheet" href="css/animate.css">

    <link href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
    <link rel="stylesheet" href="css/style.css">

                                中文

                            Unitalks

                            News

                            Knowledge

                            Events

                            Home

                <template v-for="content in contents">

                                        {{ content.intro }}

                                    {{ content.title }}

0 && content.top != 1">

                                        {{ content.intro }}

                                    {{ content.title }}

                </template>

© UNITIMES. All Rights Reserved.


text:
<?php

require_once 'vendor/autoload.php';

// Configuration
$config = Spyc::YAMLLoad(realpath(dirname(__FILE__)) . '/../../../config/config.yaml');

// get arguments to pass on to nightly.php
if (isset($argv) & sizeof($argv) > 1)
{
    $args       = join(" ", array_slice($argv, 1));
    $outputHtml = (array_search("--html", $argv) > 0 ? true : false);
}
else
{
    $args       = "";
    $outputHtml = false;
}
// Default Timezone. See: http://us3.php.net/manual/en/timezones.php
$DEFAULT_TIMEZONE = $config['nightly']['timezone'];
date_default_timezone_set($DEFAULT_TIMEZONE);

// Display format for date
$DAY_DISPLAY = date($config['nightly']['displayFormat'], strtotime('yesterday'));

// Info for regular report recipients
$RECIPIENTS    = $config['nightly']['recipients'];
$GREETING      = "Below are the hourly Suma counts for " . $DAY_DISPLAY . ". " . "Please note that missing counts may have been performed but not yet uploaded to the Suma server.";
$SENDER        = (isset($config['nightly']['emailFrom']) ? $config['nightly']['emailFrom'] : null);
$defaultSubj   = "Suma Nightly Report: ";
$subjectLeadIn = (isset($config['nightly']['emailSubj']) ? $config['nightly']['emailSubj'] : $defaultSubj);
$SUBJECT       = $subjectLeadIn . $DAY_DISPLAY;

// Info for error report recipients
$ERROR_RECIPIENTS = $config['nightly']['errorRecipients'];
$ERROR_GREETING   = 'The nightly Suma report encountered an error.';
$ERROR_SUBJECT    = 'ERROR: Suma Nightly Report: ' . $DAY_DISPLAY;

// Run Script
$dir = realpath(dirname(__FILE__));
$data = `php $dir/nightly.php $args`;

$errorCheck = explode(" ", $data);

if ($errorCheck[0] === "Error:")
{
    $message = $ERROR_GREETING . "\n" . $data;
    mail($ERROR_RECIPIENTS, $ERROR_SUBJECT, $message);
}
else
{
    $emailHeaders = (isset($SENDER) ? 'From: ' . $SENDER . PHP_EOL : "");

    // additional headers if reporting by location, to support HTML in email
    if ($outputHtml)
    {
        $emailHeaders .= 'MIME-Version: 1.0' . PHP_EOL;
        $emailHeaders .= 'Content-type: text/html; charset=utf-8' . PHP_EOL;
    }

    $message = $GREETING . "\n" . $data;
    mail($RECIPIENTS, $SUBJECT, $message, $emailHeaders);
}


text:
<root>
	<sent>
		<text>Female , age greater than 30 , has a known history of HIV , multiple or severe drug allergies , or severe post-treatment hypersensitivity reactions .</text>
		<entity class="Condition" index="T1" negated="N" relation="None" start="0"> Female </entity>
		 <entity class="Observation" index="T2" negated="N" relation="T3:has_value" start="2"> age </entity>
		 <attribute class="Measurement" index="T3" start="3"> greater than 30 </attribute>
		 <entity class="Condition" index="T4" negated="N" relation="T6:modified_by|T5:modified_by" start="12"> HIV </entity>
		 <attribute class="Qualifier" index="T5" start="14"> multiple </attribute>
		 <attribute class="Qualifier" index="T6" start="16"> severe </attribute>
		 <entity class="Condition" index="T7" negated="N" relation="T6:modified_by|T5:modified_by" start="17"> drug allergies </entity>
		 <attribute class="Qualifier" index="T8" start="21"> severe </attribute>
		 <entity class="Condition" index="T9" negated="N" relation="T8:modified_by" start="22"> post-treatment hypersensitivity reactions </entity>

	</sent>
</root>

<root>
	<sent>
		<text>Within the previous 2 years, unstable or clinically significant cardiovascular disease</text>
		<attribute class="Temporal_measurement" index="T1" start="1">Within the previous 2 years </attribute>
		<attribute class="Qualifier" index="T2" start="7">unstable</attribute>
		<attribute class="Qualifier" index="T3" start="9">clinicallly significant</attribute>
		<entity class="Condition" encoding="40568109" index="T4" negation="N" relation="T2:modified_by|T3:modified_by|T1:has_tempMea" start="11">cardiovascular disease</entity>
	</sent>
</root>

<root>
	<sent>
		<text>GDS 15 score is less than 6.</text>
		<entity class="Observation" encoding="45514749" index="T1" negation="N" relation="T2:has_value" start="0">GDS 15 score</entity>
		<attribute class="Measurement" index="T2" start="4">less than 6 </attribute>
	</sent>
</root>


text:
require "spec_helper"

describe BsdApi::UrlGenerator do
  context "all api input" do
    let(:api_host_name){"name"}
    let(:api_path){"path"}
    let(:api_id){"id"}
    let(:api_secret){"secret"}

    it " returns a url " do
      url  = BsdApi::UrlGenerator.get_url(api_host_name, api_path, api_id, api_secret)
      url.should include(api_host_name)
      url.should include(api_path)
      url.should include(api_id)
    end
  end
end


text:
import * as i0 from '@angular/core';
import { forwardRef, EventEmitter, Component, ChangeDetectionStrategy, ViewEncapsulation, Input, Output, NgModule } from '@angular/core';
import * as i1 from '@angular/common';
import { CommonModule } from '@angular/common';
import { NG_VALUE_ACCESSOR } from '@angular/forms';

const KNOB_VALUE_ACCESSOR = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => Knob),
    multi: true
};
class Knob {
    constructor(cd, el) {
        this.cd = cd;
        this.el = el;
        this.valueColor = "var(--primary-color, Black)";
        this.rangeColor = "var(--surface-d, LightGray)";
        this.textColor = "var(--text-color-secondary, Black)";
        this.valueTemplate = "{value}";
        this.size = 100;
        this.step = 1;
        this.min = 0;
        this.max = 100;
        this.strokeWidth = 14;
        this.showValue = true;
        this.readonly = false;
        this.onChange = new EventEmitter();
        this.radius = 40;
        this.midX = 50;
        this.midY = 50;
        this.minRadians = 4 * Math.PI / 3;
        this.maxRadians = -Math.PI / 3;
        this.value = null;
        this.onModelChange = () => { };
        this.onModelTouched = () => { };
    }
    mapRange(x, inMin, inMax, outMin, outMax) {
        return (x - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
    }
    onClick(event) {
        if (!this.disabled && !this.readonly) {
            this.updateValue(event.offsetX, event.offsetY);
        }
    }
    updateValue(offsetX, offsetY) {
        let dx = offsetX - this.size / 2;
        let dy = this.size / 2 - offsetY;
        let angle = Math.atan2(dy, dx);
        let start = -Math.PI / 2 - Math.PI / 6;
        this.updateModel(angle, start);
    }
    updateModel(angle, start) {
        let mappedValue;
        if (angle > this.maxRadians)
            mappedValue = this.mapRange(angle, this.minRadians, this.maxRadians, this.min, this.max);
        else if (angle < start)
            mappedValue = this.mapRange(angle + 2 * Math.PI, this.minRadians, this.maxRadians, this.min, this.max);
        else
            return;
        let newValue = Math.round((mappedValue - this.min) / this.step) * this.step + this.min;
        this.value = newValue;
        this.onModelChange(this.value);
        this.onChange.emit(this.value);
    }
    onMouseDown(event) {
        if (!this.disabled && !this.readonly) {
            this.windowMouseMoveListener = this.onMouseMove.bind(this);
            this.windowMouseUpListener = this.onMouseUp.bind(this);
            window.addEventListener('mousemove', this.windowMouseMoveListener);
            window.addEventListener('mouseup', this.windowMouseUpListener);
            event.preventDefault();
        }
    }
    onMouseUp(event) {
        if (!this.disabled && !this.readonly) {
            window.removeEventListener('mousemove', this.windowMouseMoveListener);
            window.removeEventListener('mouseup', this.windowMouseUpListener);
            this.windowMouseUpListener = null;
            this.windowMouseMoveListener = null;
            event.preventDefault();
        }
    }
    onTouchStart(event) {
        if (!this.disabled && !this.readonly) {
            this.windowTouchMoveListener = this.onTouchMove.bind(this);
            this.windowTouchEndListener = this.onTouchEnd.bind(this);
            window.addEventListener('touchmove', this.windowTouchMoveListener);
            window.addEventListener('touchend', this.windowTouchEndListener);
            event.preventDefault();
        }
    }
    onTouchEnd(event) {
        if (!this.disabled && !this.readonly) {
            window.removeEventListener('touchmove', this.windowTouchMoveListener);
            window.removeEventListener('touchend', this.windowTouchEndListener);
            this.windowTouchMoveListener = null;
            this.windowTouchEndListener = null;
            event.preventDefault();
        }
    }
    onMouseMove(event) {
        if (!this.disabled && !this.readonly) {
            this.updateValue(event.offsetX, event.offsetY);
            event.preventDefault();
        }
    }
    onTouchMove(event) {
        if (!this.disabled && !this.readonly && event.touches.length == 1) {
            const rect = this.el.nativeElement.children[0].getBoundingClientRect();
            const touch = event.targetTouches.item(0);
            const offsetX = touch.clientX - rect.left;
            const offsetY = touch.clientY - rect.top;
            this.updateValue(offsetX, offsetY);
        }
    }
    writeValue(value) {
        this.value = value;
        this.cd.markForCheck();
    }
    registerOnChange(fn) {
        this.onModelChange = fn;
    }
    registerOnTouched(fn) {
        this.onModelTouched = fn;
    }
    setDisabledState(val) {
        this.disabled = val;
        this.cd.markForCheck();
    }
    containerClass() {
        return {
            'p-knob p-component': true,
            'p-disabled': this.disabled
        };
    }
    rangePath() {
        return `M ${this.minX()} ${this.minY()} A ${this.radius} ${this.radius} 0 1 1 ${this.maxX()} ${this.maxY()}`;
    }
    valuePath() {
        return `M ${this.zeroX()} ${this.zeroY()} A ${this.radius} ${this.radius} 0 ${this.largeArc()} ${this.sweep()} ${this.valueX()} ${this.valueY()}`;
    }
    zeroRadians() {
        if (this.min > 0 && this.max > 0)
            return this.mapRange(this.min, this.min, this.max, this.minRadians, this.maxRadians);
        else
            return this.mapRange(0, this.min, this.max, this.minRadians, this.maxRadians);
    }
    valueRadians() {
        return this.mapRange(this._value, this.min, this.max, this.minRadians, this.maxRadians);
    }
    minX() {
        return this.midX + Math.cos(this.minRadians) * this.radius;
    }
    minY() {
        return this.midY - Math.sin(this.minRadians) * this.radius;
    }
    maxX() {
        return this.midX + Math.cos(this.maxRadians) * this.radius;
    }
    maxY() {
        return this.midY - Math.sin(this.maxRadians) * this.radius;
    }
    zeroX() {
        return this.midX + Math.cos(this.zeroRadians()) * this.radius;
    }
    zeroY() {
        return this.midY - Math.sin(this.zeroRadians()) * this.radius;
    }
    valueX() {
        return this.midX + Math.cos(this.valueRadians()) * this.radius;
    }
    valueY() {
        return this.midY - Math.sin(this.valueRadians()) * this.radius;
    }
    largeArc() {
        return Math.abs(this.zeroRadians() - this.valueRadians()) < Math.PI ? 0 : 1;
    }
    sweep() {
        return this.valueRadians() > this.zeroRadians() ? 0 : 1;
    }
    valueToDisplay() {
        return this.valueTemplate.replace("{value}", this._value.toString());
    }
    get _value() {
        return this.value != null ? this.value : this.min;
    }
}
Knob.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: Knob, deps: [{ token: i0.ChangeDetectorRef }, { token: i0.ElementRef }], target: i0.ɵɵFactoryTarget.Component });
Knob.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "12.0.5", type: Knob, selector: "p-knob", inputs: { styleClass: "styleClass", style: "style", severity: "severity", valueColor: "valueColor", rangeColor: "rangeColor", textColor: "textColor", valueTemplate: "valueTemplate", name: "name", size: "size", step: "step", min: "min", max: "max", strokeWidth: "strokeWidth", disabled: "disabled", showValue: "showValue", readonly: "readonly" }, outputs: { onChange: "onChange" }, providers: [KNOB_VALUE_ACCESSOR], ngImport: i0, template: `
        <div [ngClass]="containerClass()" [class]="styleClass" [ngStyle]="style">
        <svg viewBox="0 0 100 100" [style.width]="size + 'px'" [style.height]="size + 'px'" (click)="onClick($event)" (mousedown)="onMouseDown($event)" (mouseup)="onMouseUp($event)"
            (touchstart)="onTouchStart($event)" (touchend)="onTouchEnd($event)">
            <path [attr.d]="rangePath()" [attr.stroke-width]="strokeWidth" [attr.stroke]="rangeColor" class="p-knob-range"></path>
            <path [attr.d]="valuePath()" [attr.stroke-width]="strokeWidth" [attr.stroke]="valueColor" class="p-knob-value"></path>
            <text *ngIf="showValue" [attr.x]="50" [attr.y]="57" text-anchor="middle" [attr.fill]="textColor" class="p-knob-text" [attr.name]="name">{{valueToDisplay()}}</text>
        </svg>
        </div>
    `, isInline: true, styles: ["@keyframes dash-frame{to{stroke-dashoffset:0}}.p-knob-range{fill:none;transition:stroke .1s ease-in}.p-knob-value{animation-name:dash-frame;animation-fill-mode:forwards;fill:none}.p-knob-text{font-size:1.3rem;text-align:center}"], directives: [{ type: i1.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { type: i1.NgStyle, selector: "[ngStyle]", inputs: ["ngStyle"] }, { type: i1.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: Knob, decorators: [{
            type: Component,
            args: [{
                    selector: 'p-knob',
                    template: `
        <div [ngClass]="containerClass()" [class]="styleClass" [ngStyle]="style">
        <svg viewBox="0 0 100 100" [style.width]="size + 'px'" [style.height]="size + 'px'" (click)="onClick($event)" (mousedown)="onMouseDown($event)" (mouseup)="onMouseUp($event)"
            (touchstart)="onTouchStart($event)" (touchend)="onTouchEnd($event)">
            <path [attr.d]="rangePath()" [attr.stroke-width]="strokeWidth" [attr.stroke]="rangeColor" class="p-knob-range"></path>
            <path [attr.d]="valuePath()" [attr.stroke-width]="strokeWidth" [attr.stroke]="valueColor" class="p-knob-value"></path>
            <text *ngIf="showValue" [attr.x]="50" [attr.y]="57" text-anchor="middle" [attr.fill]="textColor" class="p-knob-text" [attr.name]="name">{{valueToDisplay()}}</text>
        </svg>
        </div>
    `,
                    providers: [KNOB_VALUE_ACCESSOR],
                    changeDetection: ChangeDetectionStrategy.OnPush,
                    encapsulation: ViewEncapsulation.None,
                    styleUrls: ['./knob.css']
                }]
        }], ctorParameters: function () { return [{ type: i0.ChangeDetectorRef }, { type: i0.ElementRef }]; }, propDecorators: { styleClass: [{
                type: Input
            }], style: [{
                type: Input
            }], severity: [{
                type: Input
            }], valueColor: [{
                type: Input
            }], rangeColor: [{
                type: Input
            }], textColor: [{
                type: Input
            }], valueTemplate: [{
                type: Input
            }], name: [{
                type: Input
            }], size: [{
                type: Input
            }], step: [{
                type: Input
            }], min: [{
                type: Input
            }], max: [{
                type: Input
            }], strokeWidth: [{
                type: Input
            }], disabled: [{
                type: Input
            }], showValue: [{
                type: Input
            }], readonly: [{
                type: Input
            }], onChange: [{
                type: Output
            }] } });
class KnobModule {
}
KnobModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: KnobModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
KnobModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: KnobModule, declarations: [Knob], imports: [CommonModule], exports: [Knob] });
KnobModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: KnobModule, imports: [[CommonModule]] });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: KnobModule, decorators: [{
            type: NgModule,
            args: [{
                    imports: [CommonModule],
                    exports: [Knob],
                    declarations: [Knob]
                }]
        }] });

/**
 * Generated bundle index. Do not edit.
 */

export { KNOB_VALUE_ACCESSOR, Knob, KnobModule };
//# sourceMappingURL=primeng-knob.js.map


text:
using System.Text;
using System.IO;

namespace DragonBones
{
    internal class BinaryDataWriter : BinaryWriter
    {
        public BinaryDataWriter() : base(new MemoryStream(0x100))
        {
        }

        internal BinaryDataWriter(Stream stream) : base(stream)
        {
        }

        public BinaryDataWriter(Encoding encoding) : base(new MemoryStream(0x100), encoding)
        {
        }

        internal BinaryDataWriter(Stream stream, Encoding encoding) : base(stream, encoding)
        {
        }

        public virtual void Write(bool[] value)
        {
            foreach (bool flag in value)
            {
                base.Write(flag);
            }
        }

        public override void Write(byte[] value)
        {
            foreach (byte num in value)
            {
                base.Write(num);
            }
        }

        public override void Write(char[] value)
        {
            foreach (char ch in value)
            {
                base.Write(ch);
            }
        }

        public virtual void Write(decimal[] value)
        {
            foreach (decimal num in value)
            {
                base.Write(num);
            }
        }

        public virtual void Write(double[] value)
        {
            foreach (double num in value)
            {
                base.Write(num);
            }
        }

        public virtual void Write(short[] value)
        {
            foreach (short num in value)
            {
                base.Write(num);
            }
        }

        public virtual void Write(int[] value)
        {
            foreach (int num in value)
            {
                base.Write(num);
            }
        }

        public virtual void Write(long[] value)
        {
            foreach (long num in value)
            {
                base.Write(num);
            }
        }

        public virtual void Write(sbyte[] value)
        {
            foreach (sbyte num in value)
            {
                base.Write(num);
            }
        }

        public virtual void Write(float[] value)
        {
            foreach (float num in value)
            {
                base.Write(num);
            }
        }

        public virtual void Write(string[] value)
        {
            foreach (string str in value)
            {
                base.Write(str);
            }
        }

        public virtual void Write(ushort[] value)
        {
            foreach (ushort num in value)
            {
                base.Write(num);
            }
        }

        public virtual void Write(uint[] value)
        {
            foreach (uint num in value)
            {
                base.Write(num);
            }
        }

        public virtual void Write(ulong[] value)
        {
            foreach (ulong num in value)
            {
                base.Write(num);
            }
        }

        private long Length
        {
            get
            {
                return this.BaseStream.Length;
            }
        }
    }

}


text:
package org.killbill.billing.jaxrs.json;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.annotation.Nullable;

import org.apache.shiro.util.CollectionUtils;
import org.joda.time.LocalDate;
import org.killbill.billing.catalog.api.Currency;
import org.killbill.billing.invoice.api.Invoice;
import org.killbill.billing.invoice.api.InvoiceItem;
import org.killbill.billing.invoice.api.InvoiceItemType;
import org.killbill.billing.invoice.api.InvoiceStatus;
import org.killbill.billing.util.audit.AccountAuditLogs;
import org.killbill.billing.util.audit.AuditLog;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import io.swagger.annotations.ApiModel;

@ApiModel(value="Invoice", parent = JsonBase.class)
public class InvoiceJson extends JsonBase {

    private final BigDecimal amount;
    private final Currency currency;
    private final UUID invoiceId;
    private final LocalDate invoiceDate;
    private final LocalDate targetDate;
    private final String invoiceNumber;
    private final BigDecimal balance;
    private final BigDecimal creditAdj;
    private final BigDecimal refundAdj;
    private final UUID accountId;
    private final List<InvoiceItemJson> items;
    private final String bundleKeys;
    private final List<InvoiceItemJson> credits;
    private final InvoiceStatus status;
    private final Boolean isParentInvoice;
    private final UUID parentInvoiceId;
    private final UUID parentAccountId;
    private final List<String> trackingIds;

    @JsonCreator
    public InvoiceJson(@JsonProperty("amount") final BigDecimal amount,
                       @JsonProperty("currency") final Currency currency,
                       @JsonProperty("status") final InvoiceStatus status,
                       @JsonProperty("creditAdj") final BigDecimal creditAdj,
                       @JsonProperty("refundAdj") final BigDecimal refundAdj,
                       @JsonProperty("invoiceId") final UUID invoiceId,
                       @JsonProperty("invoiceDate") final LocalDate invoiceDate,
                       @JsonProperty("targetDate") final LocalDate targetDate,
                       @JsonProperty("invoiceNumber") final String invoiceNumber,
                       @JsonProperty("balance") final BigDecimal balance,
                       @JsonProperty("accountId") final UUID accountId,
                       @JsonProperty("bundleKeys") final String bundleKeys,
                       @JsonProperty("credits") final List<InvoiceItemJson> credits,
                       @JsonProperty("items") final List<InvoiceItemJson> items,
                       @JsonProperty("trackingIds") final List<String> trackingIds,
                       @JsonProperty("isParentInvoice") final Boolean isParentInvoice,
                       @JsonProperty("parentInvoiceId") final UUID parentInvoiceId,
                       @JsonProperty("parentAccountId") final UUID parentAccountId,
                       @JsonProperty("auditLogs") @Nullable final List<AuditLogJson> auditLogs) {
        super(auditLogs);
        this.amount = amount;
        this.currency = currency;
        this.status = status;
        this.creditAdj = creditAdj;
        this.refundAdj = refundAdj;
        this.invoiceId = invoiceId;
        this.invoiceDate = invoiceDate;
        this.targetDate = targetDate;
        this.invoiceNumber = invoiceNumber;
        this.balance = balance;
        this.accountId = accountId;
        this.bundleKeys = bundleKeys;
        this.credits = credits;
        this.items = items;
        this.trackingIds = trackingIds;
        this.isParentInvoice = isParentInvoice;
        this.parentInvoiceId = parentInvoiceId;
        this.parentAccountId = parentAccountId;
    }

    public InvoiceJson(final Invoice input) {
        this(input, null, null);
    }

    public InvoiceJson(final Invoice input, final String bundleKeys, final List<InvoiceItemJson> credits, final List<AuditLog> auditLogs) {
        this(input.getChargedAmount(), input.getCurrency(), input.getStatus(), input.getCreditedAmount(), input.getRefundedAmount(),
             input.getId(), input.getInvoiceDate(), input.getTargetDate(), String.valueOf(input.getInvoiceNumber()),
             input.getBalance(), input.getAccountId(), bundleKeys, credits, null, null, input.isParentInvoice(),
             input.getParentInvoiceId(),
             input.getParentAccountId(),
             toAuditLogJson(auditLogs));
    }

    public InvoiceJson(final Invoice input, final List<InvoiceItem> childItems, @Nullable final AccountAuditLogs accountAuditLogs) {
        super(toAuditLogJson(accountAuditLogs == null ? null : accountAuditLogs.getAuditLogsForInvoice(input.getId())));
        this.items = new ArrayList<InvoiceItemJson>(input.getInvoiceItems().size());
        for (final InvoiceItem item : input.getInvoiceItems()) {
            ImmutableList<InvoiceItem> childItemsFiltered = null;
            if (item.getInvoiceItemType().equals(InvoiceItemType.PARENT_SUMMARY) && !CollectionUtils.isEmpty(childItems)) {
                childItemsFiltered = ImmutableList.copyOf(Iterables.filter(childItems, new Predicate<InvoiceItem>() {
                    @Override
                    public boolean apply(@Nullable final InvoiceItem invoice) {
                        return invoice.getAccountId().equals(item.getChildAccountId());
                    }
                }));
            }
            this.items.add(new InvoiceItemJson(item, childItemsFiltered, accountAuditLogs == null ? null : accountAuditLogs.getAuditLogsForInvoiceItem(item.getId())));
        }
        this.trackingIds = input.getTrackingIds();
        this.amount = input.getChargedAmount();
        this.currency = input.getCurrency();
        this.status = input.getStatus();
        this.creditAdj = input.getCreditedAmount();
        this.refundAdj = input.getRefundedAmount();
        this.invoiceId = input.getId();
        this.invoiceDate = input.getInvoiceDate();
        this.targetDate = input.getTargetDate();
        this.invoiceNumber = input.getInvoiceNumber() == null ? null : String.valueOf(input.getInvoiceNumber());
        this.balance = input.getBalance();
        this.accountId = input.getAccountId();
        this.bundleKeys = null;
        this.credits = null;
        this.isParentInvoice = input.isParentInvoice();
        this.parentInvoiceId = input.getParentInvoiceId();
        this.parentAccountId = input.getParentAccountId();
    }

    public BigDecimal getAmount() {
        return amount;
    }

    public Currency getCurrency() {
        return currency;
    }

    public UUID getInvoiceId() {
        return invoiceId;
    }

    public LocalDate getInvoiceDate() {
        return invoiceDate;
    }

    public LocalDate getTargetDate() {
        return targetDate;
    }

    public String getInvoiceNumber() {
        return invoiceNumber;
    }

    public BigDecimal getBalance() {
        return balance;
    }

    public BigDecimal getCreditAdj() {
        return creditAdj;
    }

    public BigDecimal getRefundAdj() {
        return refundAdj;
    }

    public UUID getAccountId() {
        return accountId;
    }

    public List<InvoiceItemJson> getItems() {
        return items;
    }

    public String getBundleKeys() {
        return bundleKeys;
    }

    public List<InvoiceItemJson> getCredits() {
        return credits;
    }

    public InvoiceStatus getStatus() {
        return status;
    }

    public Boolean getIsParentInvoice() {
        return isParentInvoice;
    }

    public UUID getParentInvoiceId() {
        return parentInvoiceId;
    }

    public UUID getParentAccountId() {
        return parentAccountId;
    }

    public List<String> getTrackingIds() {
        return trackingIds;
    }

    @Override
    public String toString() {
        return "InvoiceJson{" +
               "amount=" + amount +
               ", currency='" + currency + '\'' +
               ", status='" + status + '\'' +
               ", invoiceId='" + invoiceId + '\'' +
               ", invoiceDate=" + invoiceDate +
               ", targetDate=" + targetDate +
               ", invoiceNumber='" + invoiceNumber + '\'' +
               ", balance=" + balance +
               ", creditAdj=" + creditAdj +
               ", refundAdj=" + refundAdj +
               ", accountId='" + accountId + '\'' +
               ", items=" + items +
               ", bundleKeys='" + bundleKeys + '\'' +
               ", credits=" + credits +
               ", isParentInvoice=" + isParentInvoice +
               ", parentInvoiceId=" + parentInvoiceId +
               ", parentAccountId=" + parentAccountId +
               '}';
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        final InvoiceJson that = (InvoiceJson) o;

        if (accountId != null ? !accountId.equals(that.accountId) : that.accountId != null) {
            return false;
        }
        if (amount != null ? amount.compareTo(that.amount) != 0 : that.amount != null) {
            return false;
        }
        if (balance != null ? balance.compareTo(that.balance) != 0 : that.balance != null) {
            return false;
        }
        if (bundleKeys != null ? !bundleKeys.equals(that.bundleKeys) : that.bundleKeys != null) {
            return false;
        }
        if (creditAdj != null ? creditAdj.compareTo(that.creditAdj) != 0 : that.creditAdj != null) {
            return false;
        }
        if (credits != null ? !credits.equals(that.credits) : that.credits != null) {
            return false;
        }
        if (currency != null ? !currency.equals(that.currency) : that.currency != null) {
            return false;
        }
        if (invoiceDate != null ? invoiceDate.compareTo(that.invoiceDate) != 0 : that.invoiceDate != null) {
            return false;
        }
        if (invoiceId != null ? !invoiceId.equals(that.invoiceId) : that.invoiceId != null) {
            return false;
        }
        if (invoiceNumber != null ? !invoiceNumber.equals(that.invoiceNumber) : that.invoiceNumber != null) {
            return false;
        }
        if (items != null ? !items.equals(that.items) : that.items != null) {
            return false;
        }
        if (refundAdj != null ? refundAdj.compareTo(that.refundAdj) != 0 : that.refundAdj != null) {
            return false;
        }
        if (targetDate != null ? targetDate.compareTo(that.targetDate) != 0 : that.targetDate != null) {
            return false;
        }
        if (status != null ? !status.equals(that.status) : that.status != null) {
            return false;
        }
        if (isParentInvoice != null ? !isParentInvoice.equals(that.isParentInvoice) : that.isParentInvoice != null) {
            return false;
        }
        if (parentInvoiceId != null ? !parentInvoiceId.equals(that.parentInvoiceId) : that.parentInvoiceId != null) {
            return false;
        }
        if (parentAccountId != null ? !parentAccountId.equals(that.parentAccountId) : that.parentAccountId != null) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int result = amount != null ? amount.hashCode() : 0;
        result = 31 * result + (currency != null ? currency.hashCode() : 0);
        result = 31 * result + (status != null ? status.hashCode() : 0);
        result = 31 * result + (invoiceId != null ? invoiceId.hashCode() : 0);
        result = 31 * result + (invoiceDate != null ? invoiceDate.hashCode() : 0);
        result = 31 * result + (targetDate != null ? targetDate.hashCode() : 0);
        result = 31 * result + (invoiceNumber != null ? invoiceNumber.hashCode() : 0);
        result = 31 * result + (balance != null ? balance.hashCode() : 0);
        result = 31 * result + (creditAdj != null ? creditAdj.hashCode() : 0);
        result = 31 * result + (refundAdj != null ? refundAdj.hashCode() : 0);
        result = 31 * result + (accountId != null ? accountId.hashCode() : 0);
        result = 31 * result + (items != null ? items.hashCode() : 0);
        result = 31 * result + (bundleKeys != null ? bundleKeys.hashCode() : 0);
        result = 31 * result + (credits != null ? credits.hashCode() : 0);
        result = 31 * result + (isParentInvoice != null ? isParentInvoice.hashCode() : 0);
        result = 31 * result + (parentInvoiceId != null ? parentInvoiceId.hashCode() : 0);
        result = 31 * result + (parentAccountId != null ? parentAccountId.hashCode() : 0);
        return result;
    }
}


text:
package com.android.camera;

import android.annotation.TargetApi;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaActionSound;
import android.media.SoundPool;
import android.os.Build;

import com.android.camera.debug.Log;
import com.android.camera.util.ApiHelper;
import com.android.camera2.R;

/*
 * This class controls the sound playback according to the API level.
 */
public class SoundClips {
    // Sound actions.
    public static final int FOCUS_COMPLETE = 0;
    public static final int START_VIDEO_RECORDING = 1;
    public static final int STOP_VIDEO_RECORDING = 2;
    public static final int SHUTTER_CLICK = 3;

    public interface Player {
        public void release();
        public void play(int action);
    }

    public static Player getPlayer(Context context) {
        if (ApiHelper.HAS_MEDIA_ACTION_SOUND) {
            return new MediaActionSoundPlayer();
        } else {
            return new SoundPoolPlayer(context);
        }
    }

    public static int getAudioTypeForSoundPool() {
        // STREAM_SYSTEM_ENFORCED is hidden API.
        return ApiHelper.getIntFieldIfExists(AudioManager.class,
                "STREAM_SYSTEM_ENFORCED", null, AudioManager.STREAM_RING);
    }

    /**
     * This class implements SoundClips.Player using MediaActionSound,
     * which exists since API level 16.
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private static class MediaActionSoundPlayer implements Player {
        private static final Log.Tag TAG = new Log.Tag("MediaActSndPlayer");
        private MediaActionSound mSound;

        @Override
        public void release() {
            if (mSound != null) {
                mSound.release();
                mSound = null;
            }
        }

        public MediaActionSoundPlayer() {
            mSound = new MediaActionSound();
            mSound.load(MediaActionSound.START_VIDEO_RECORDING);
            mSound.load(MediaActionSound.STOP_VIDEO_RECORDING);
            mSound.load(MediaActionSound.FOCUS_COMPLETE);
            mSound.load(MediaActionSound.SHUTTER_CLICK);
        }

        @Override
        public synchronized void play(int action) {
            switch(action) {
                case FOCUS_COMPLETE:
                    mSound.play(MediaActionSound.FOCUS_COMPLETE);
                    break;
                case START_VIDEO_RECORDING:
                    mSound.play(MediaActionSound.START_VIDEO_RECORDING);
                    break;
                case STOP_VIDEO_RECORDING:
                    mSound.play(MediaActionSound.STOP_VIDEO_RECORDING);
                    break;
                case SHUTTER_CLICK:
                    mSound.play(MediaActionSound.SHUTTER_CLICK);
                    break;
                default:
                    Log.w(TAG, "Unrecognized action:" + action);
            }
        }
    }

    /**
     * This class implements SoundClips.Player using SoundPool, which
     * exists since API level 1.
     */
    private static class SoundPoolPlayer implements
            Player, SoundPool.OnLoadCompleteListener {

        private static final Log.Tag TAG = new Log.Tag("SoundPoolPlayer");
        private static final int NUM_SOUND_STREAMS = 1;
        private static final int[] SOUND_RES = { // Soundtrack res IDs.
                R.raw.focus_complete,
                R.raw.video_record,
                R.raw.video_record,
                R.raw.shutter
        };

        // ID returned by load() should be non-zero.
        private static final int ID_NOT_LOADED = 0;

        // Maps a sound action to the id;
        private final int[] mSoundRes = {0, 1, 2, 3};
        // Store the context for lazy loading.
        private Context mContext;
        // mSoundPool is created every time load() is called and cleared every
        // time release() is called.
        private SoundPool mSoundPool;
        // Sound ID of each sound resources. Given when the sound is loaded.
        private final int[] mSoundIDs;
        private final boolean[] mSoundIDReady;
        private int mSoundIDToPlay;

        public SoundPoolPlayer(Context context) {
            mContext = context;

            mSoundIDToPlay = ID_NOT_LOADED;

            mSoundPool = new SoundPool(NUM_SOUND_STREAMS, getAudioTypeForSoundPool(), 0);
            mSoundPool.setOnLoadCompleteListener(this);

            mSoundIDs = new int[SOUND_RES.length];
            mSoundIDReady = new boolean[SOUND_RES.length];
            for (int i = 0; i < SOUND_RES.length; i++) {
                mSoundIDs[i] = mSoundPool.load(mContext, SOUND_RES[i], 1);
                mSoundIDReady[i] = false;
            }
        }

        @Override
        public synchronized void release() {
            if (mSoundPool != null) {
                mSoundPool.release();
                mSoundPool = null;
            }
        }

        @Override
        public synchronized void play(int action) {
            if (action < 0 || action >= mSoundRes.length) {
                Log.e(TAG, "Resource ID not found for action:" + action + " in play().");
                return;
            }

            int index = mSoundRes[action];
            if (mSoundIDs[index] == ID_NOT_LOADED) {
                // Not loaded yet, load first and then play when the loading is complete.
                mSoundIDs[index] = mSoundPool.load(mContext, SOUND_RES[index], 1);
                mSoundIDToPlay = mSoundIDs[index];
            } else if (!mSoundIDReady[index]) {
                // Loading and not ready yet.
                mSoundIDToPlay = mSoundIDs[index];
            } else {
                mSoundPool.play(mSoundIDs[index], 1f, 1f, 0, 0, 1f);
            }
        }

        @Override
        public void onLoadComplete(SoundPool pool, int soundID, int status) {
            if (status != 0) {
                Log.e(TAG, "loading sound tracks failed (status=" + status + ")");
                for (int i = 0; i < mSoundIDs.length; i++ ) {
                    if (mSoundIDs[i] == soundID) {
                        mSoundIDs[i] = ID_NOT_LOADED;
                        break;
                    }
                }
                return;
            }

            for (int i = 0; i < mSoundIDs.length; i++ ) {
                if (mSoundIDs[i] == soundID) {
                    mSoundIDReady[i] = true;
                    break;
                }
            }

            if (soundID == mSoundIDToPlay) {
                mSoundIDToPlay = ID_NOT_LOADED;
                mSoundPool.play(soundID, 1f, 1f, 0, 0, 1f);
            }
        }
    }
}


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

namespace ZDevTools.Test.Security
{
    public class UnitTest_RSAHelper
    {
        [Fact]
        public RSAHelper.RSAKey GenerateKey()
        {
            var rsaKey = RSAHelper.GenerateRASKey();
            Assert.True(!string.IsNullOrEmpty(rsaKey.PrivateKey));
            Assert.True(!string.IsNullOrEmpty(rsaKey.PublicKey));

            return rsaKey;
        }

        [Fact]
        public (List<byte> CipherBytes, RSAHelper.RSAKey Key, string Clear) Encrypt()
        {
            var key = GenerateKey();

            string clear = "\0\0\0测试一级棒\0\0\0skfsdlkfklsjfliwu;" +
                "skjflksjf;s" +
                "sdfsdklfjsdlfjsl;ufeio" +
                "sdfjsldjfoieurpjzavna" +
                "skfjskfjsldfj";
            var clearBytes = Encoding.Default.GetBytes(clear);

            //测试私钥加密
            var cipherBytes = RSAHelper.Encrypt(clearBytes, key.PrivateKey);

            Assert.NotNull(cipherBytes);

            return (cipherBytes, key, clear);
        }

        [Fact]
        public void Decrypt()
        {
            (var cipherBytes, var key, var clear) = Encrypt();

            //公钥解密
            var clearBytes = RSAHelper.Decrypt(cipherBytes, key.PublicKey);

            var deClear = Encoding.Default.GetString(clearBytes.ToArray());

            //原文与解密后的原文必须一致
            Assert.True(clear == deClear);
        }

    }
}


text:
<!DOCTYPE html>
<html ng-app="dataphoria" ng-strict-di>
<head>
	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, target-densitydpi=medium-dpi, user-scalable=0" />

	<title>Dataphoria</title>

	<link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap.min.css">

	<!--Uncompressed for debugging-->
	<script type="text/javascript" src="js/libs/angular/angular.js"></script>
	<script type="text/javascript" src="js/libs/angular/angular-route.js"></script>
	<script type="text/javascript" src="js/libs/angular/angular-resource.js"></script>
	<script type="text/javascript" src="js/libs/jquery/jquery-1.9.1.js"></script>
	<!--Minified - Production and Performance Testings-->
	<!--
	<script type="text/javascript" src="js/libs/angular/angular.min.js"></script>
	<script type="text/javascript" src="js/libs/angular/angular-route.min.js"></script>
	<script type="text/javascript" src="js/libs/angular/angular-resource.min.js"></script>
	<script type="text/javascript" src="js/libs/jquery/jquery-1.9.1.min.js"></script>
	-->

	<script type="text/javascript" src="js/app.js"></script>
	<script type="text/javascript" src="js/appSettings.js"></script>

	<!--Filters-->

	<!--Directives-->
	<script type="text/javascript" src="js/directives/directives.js"></script>
	<script type="text/javascript" src="js/directives/homeEdit.js"></script>

	<!--Controllers-->
	<script type="text/javascript" src="js/controllers/controllers.js"></script>
	<script type="text/javascript" src="js/controllers/homeCtrl.js"></script>

	<!--Services-->
	<script type="text/javascript" src="js/services/services.js"></script>
	<script type="text/javascript" src="js/services/dataservice.js"></script>

</head>

<body ng-controller="AppCtrl as appCtrl">
	<div ng-view></div>
</body>
</html>


text:
from flask import Flask, render_template, request, url_for, g, jsonify
import sqlite3 as sql
import os

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATABASE = os.path.join(BASE_DIR, "database.db")
app = Flask(__name__)

def get_db():
	# check if _database attribute exist
    db = getattr(g, '_database', None)
    if db is None:
    	# if doesnt, establish a new connection and save _database attribute
    	# this prevents multiple instances to the database
        db = g._database = sql.connect(DATABASE)
        db.row_factory = sql.Row
    return db

# @function for querying/retrieving database
def query_db(query, args=(), one=False):
	try:
	    cur = get_db().execute(query, args)
	    data = cur.fetchall()
	    cur.close()
	    if ( data ) :
	    	# If one=True
	    	if one :
	    		# Only return the first data
	    		return data[0]
	    	else:
	    		# Return all data in an array
	    		return data
	    else:
	    	# No data
	    	return None;
	except:
		# Table does not exist
		print "Database query error"
		return None;

# @function for creating a new user column in database
def insert_user(name,password,description):
	# Create a Connection to the Database
	con = sql.connect(DATABASE)
	cur = con.cursor()
	# Run and execute SQL query; Insert name, password and description with respective values into the users table
	cur.execute("INSERT INTO users (name,password,description) VALUES (?,?,?)", (name,password,description))
	con.commit()
	# Get latest id
	newid = cur.lastrowid
	con.close()
	return newid

# @function updating user in database
def update_user(user_id, params):
	# Check if user exist
	if checkUser(False, user_id):
		# Create connection to database
		con = sql.connect(DATABASE)
		cur = con.cursor()
		# Update the users table
		query = "UPDATE users SET "
		counter = 0;
		# For each key:value in {params}, accumalate it to the query variable

		for i in params :
			counter = counter + 1
			query += str(i) + "=" + str(params[i])
			if (counter != len(params)) :
				query += ","
			query += " "
		query += "WHERE id=" + str(user_id)
		print query
		# So it will be like UPDATE users SET key1=value1, key2 value2 WHERE id=3
		con.execute(query);
		con.commit()
		con.close()
		print "Updated User";
	else:
		print "User does not exist!"

# @function for getting user data; by default is to use the user's name to retrieve data, but you can also use user_id
def getUser(name, user_id = False):
	if ( user_id ) :
		# If user_id is True
		# Run data by selecting user's id
		data = query_db("select * from users WHERE id=(?)", (user_id,), True);
	else:
		# If user_id is False (default)
		# Run data by selecting user's name
		data = query_db("select * from users WHERE name=(?)", (name,), True);

	if data == None:
		# Error, return false
		return False;
	else:
		# Sucess, return data
		return data;

# @function for checking if User Exist
def checkUser(name, user_id = False):
	data = query_db("select * from users")
	if data != None:
		# No error, proceed with looping
		for user in data:
			if name != False:
				# If name is given in parameter, check if user exist by comparing with user names
				if user["name"] == name :
					return True;
					break
			else:
				# Else, check if user exist by comparing with user ids'
				if ( int(user_id) == user["id"] ) :
					return True;
					break;
	return False;

# Below are all functions for Flask's routing
# requst.form["param"] = Getting param from the POST request
# jsonify = Converts a dictionary into a JSON string for HTML viewing
@app.teardown_appcontext
def close_connection(exception):
    db = getattr(g, '_database', None)
    if db is not None:
        db.close()

@app.route('/addUser/', methods=['POST'])
def addUser():
    name=request.form['name']
    password=request.form['password']
    description=request.form['description']
    try:
    	# No error, return new_id
    	newid = insert_user(name,password,description);
    	response = {"id" : newid }
    except:
    	# Error
    	response = {"error" : True}

    return jsonify(response);

@app.route('/updateExp/', methods=['POST'])
def updateExp():
	user_id=request.form["id"]
	exp = request.form["exp"]
	weekly_exp = request.form["weekly_exp"];
	level = request.form["level"]
	try:
		# No error
		update_user(user_id, { "exp" : exp, "weekly_exp" : weekly_exp, "level" : level });
		response = {"success" : True}
	except:
		# Error
		response = {"error" : True}

	return jsonify(response)

@app.route('/updateDescription/', methods=['POST'])
def updateDescription():
	user_id=request.form["id"]
	description = "'{}'".format(request.form["description"])
	try:
		# No error
		update_user(user_id, {"description" : description});
		response = {"success" : True}
	except:
		# Error
		response = {"error" : True}
	return jsonify(response)

@app.route("/usernames/", methods=["GET"])
def usernames():
	users = []
	data = query_db("select * from users")
	if data != None:
		# If no error
		for i in range(0, len(data)):
			user = data[i]
			# Add each user's name into the users[]
			users.append(user["name"])
		# Create a response dictionary containing users[]
		response = { "users": users }
	else:
		# Error
		response = { "error": True }

	return jsonify(response)

@app.route("/public/", methods=["GET"])
def public():
	users = {}
	data = query_db("select * from users")
	if ( data != None ) :
		# If no error
		for user in data:
			# Add user's info into users{}
			users[user["id"]] = { "name" : user["name"], "exp" : user["exp"], "weekly_exp" : user["weekly_exp"], "level" : user["level"] }
		# Create a response variable to contain the users{}
		response = users;
	else:
		# Error
		response = { "error" : True }
	return jsonify(response);

@app.route("/loginUser/", methods=["POST"])
def loginUser():
	name=request.form["name"]
	print name, checkUser(name)
	if ( checkUser(name) ):
		# If user exist
		response = {  "password" : getUser(name)["password"], "id": getUser(name)["id"], "name": getUser(name)["name"], "description": getUser(name)["description"], "exp": getUser(name)["exp"], "weekly_exp" : getUser(name)["weekly_exp"], "level" : getUser(name)["level"] }
	else:
		response = { "error" : True }
	return jsonify(response)

@app.route("/user/", methods=["POST"])
def user():
	user_id=request.form["id"]
	# Check if User exist given user_id
	if ( checkUser(False, user_id) ) :
		# User exists
		data = getUser(False, user_id)
		response = { "name" : data["name"], "level" : data["level"], "description" : data["description"] }
	else:
		# User does not exist, error
		response = { "error" : True }
	return jsonify(response);

if __name__ == "__main__":
	with app.app_context():
		# Run flask run on machine's IP on port 5002
		app.run(host="0.0.0.0", port=5002)


text:
<!doctype html>
<meta charset=utf-8>
<title>RTCPeerConnection.prototype.getTransceivers</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script>
  'use strict';

  // Test is based on the following editor draft:
  // https://w3c.github.io/webrtc-pc/archives/20170605/webrtc.html

  /*
   *  5.1. RTCPeerConnection Interface Extensions
   *  partial interface RTCPeerConnection {
   *      sequence<RTCRtpSender>      getSenders();
   *      sequence<RTCRtpReceiver>    getReceivers();
   *      sequence<RTCRtpTransceiver> getTransceivers();
   *      ...
   *  };
   */

  test(t => {
    const pc = new RTCPeerConnection();

    assert_idl_attribute(pc, 'getSenders');
    const senders = pc.getSenders();
    assert_array_equals([], senders, 'Expect senders to be empty array');

    assert_idl_attribute(pc, 'getReceivers');
    const receivers = pc.getReceivers();
    assert_array_equals([], receivers, 'Expect receivers to be empty array');

    assert_idl_attribute(pc, 'getTransceivers');
    const transceivers = pc.getTransceivers();
    assert_array_equals([], transceivers, 'Expect transceivers to be empty array');

  }, 'Initial peer connection should have list of zero senders, receivers and transceivers');

</script>


text:
package org.zaproxy.zap.view.panelsearch.items;

import java.util.ArrayList;
import javax.swing.JTable;
import org.zaproxy.zap.view.panelsearch.HighlightedComponent;
import org.zaproxy.zap.view.panelsearch.HighlighterUtils;

public class TableSearch extends AbstractComponentSearch<JTable> {

    @Override
    protected Object[] getComponentsInternal(JTable component) {
        ArrayList<TableCellElement> elements = new ArrayList<>();
        for (int rIndex = 0; rIndex < component.getRowCount(); rIndex++) {
            for (int cIndex = 0; cIndex < component.getColumnCount(); cIndex++) {
                Object cellValue = component.getModel().getValueAt(rIndex, cIndex);
                Object columnIdentifier =
                        component.getColumnModel().getColumn(cIndex).getIdentifier();
                elements.add(
                        new TableCellElement(
                                component, columnIdentifier, cIndex, rIndex, cellValue));
            }
        }

        return elements.toArray();
    }

    @Override
    protected HighlightedComponent highlightAsParentInternal(JTable component) {
        return HighlighterUtils.highlightBorder(
                component, HighlighterUtils.DEFAULT_HIGHLIGHT_COLOR);
    }

    @Override
    protected void undoHighlightAsParentInternal(
            HighlightedComponent highlightedComponent, JTable component) {
        HighlighterUtils.undoHighlightBorder(highlightedComponent, component);
    }
}


text:
<?php

namespace Magento\Sales\Block\Reorder;

use Magento\Customer\Model\Context;

/**
 * Last ordered items sidebar
 */
class Sidebar extends \Magento\Framework\View\Element\Template
{
    /**
     * @var \Magento\Framework\App\Http\Context
     */
    protected $httpContext;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Framework\App\Http\Context $httpContext
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\App\Http\Context $httpContext,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->httpContext = $httpContext;
    }

    /**
     * Retrieve form action url and set "secure" param to avoid confirm
     * message when we submit form from secure page to unsecure
     *
     * @return string
     */
    public function getFormActionUrl()
    {
        return $this->getUrl('checkout/cart/addgroup', ['_secure' => true]);
    }

    /**
     * Render "My Orders" sidebar block
     *
     * @return string
     */
    protected function _toHtml()
    {
        $isValid = $this->httpContext->getValue(Context::CONTEXT_AUTH) || $this->getCustomerId();
        return $isValid ? parent::_toHtml() : '';
    }
}


text:
using System;
using ExpressMapper.Tests.Model.Models.Structs;

namespace ExpressMapper.Tests.Model.Models
{
    public class City
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public Feature[] Features { get; set; }
    }
}