repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
kristianenge/ienge
Models/ValidationResponse.cs
247
namespace IEnge.Models { public class ValidationResponse { public bool IsValidated { get; set; } public string UserName { get; set; } public string Mail { get; set; } public string Id { get; set; } } }
mit
laicasaane/VFW
Assets/Plugins/Vexe/Runtime/Libs/Helpers/RuntimeHelper.cs
5398
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using UnityEngine; using UnityEngine.SceneManagement; using Vexe.Runtime.Extensions; using Vexe.Runtime.Types; namespace Vexe.Runtime.Helpers { public static class RuntimeHelper { private static GameObject _emptyGO; /// <summary> /// Returns a cached reference to an empty GO (think NullObject) /// If none is found, a new one is created /// </summary> public static GameObject EmptyGO { get { if (_emptyGO == null) { string na = "__Empty"; _emptyGO = GameObject.Find(na) ?? CreateGo(na, null, HideFlags.HideInHierarchy); } return _emptyGO; } } /// <summary> /// Creates and returns a GameObject with the passed name, parent and HideFlags /// </summary> public static GameObject CreateGo(string name, Transform parent = null, HideFlags flags = HideFlags.None) { var go = new GameObject(name); go.hideFlags = flags; if (parent) { go.transform.parent = parent; go.transform.Reset(); } return go; } /// <summary> /// Creates a GameObject with a MonoBehaviour specified by the generic T arg - returns the MB added /// </summary> public static T CreateGoWithMb<T>(string name, out GameObject createdGo, Transform parent = null, HideFlags flags = HideFlags.None) where T : MonoBehaviour { createdGo = CreateGo(name, parent, flags); var comp = createdGo.AddComponent<T>(); return comp; } /// <summary> /// Creates a GameObject with a MonoBehaviour specified by the generic T arg - returns the MB added /// </summary> public static T CreateGoWithMb<T>(string name, Transform parent = null, HideFlags flags = HideFlags.None) where T : MonoBehaviour { var go = new GameObject(); return CreateGoWithMb<T>(name, out go, parent, flags); } public static string GetCallStack() { return GetCallStack(false); } public static string GetCallStack(bool verbose) { if (verbose) { return string.Join(" -> \r\n", new StackTrace() .GetFrames() .Select(x => { var method = x.GetMethod(); return string.Format("{0}.{1}", method.DeclaringType.GetNiceName(), x.GetMethod().GetNiceName()); }) .ToArray()); } return string.Join(" -> ", new StackTrace() .GetFrames() .Select(x => x.GetMethod().Name) .ToArray()); } public static void Swap<T>(ref T value0, ref T value1) { T tmp = value0; value0 = value1; value1 = tmp; } public static string GetCurrentSceneName() { string sceneName; #if UNITY_EDITOR sceneName = Application.isPlaying ? SceneManager.GetActiveScene().name : System.IO.Path.GetFileNameWithoutExtension(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().name); if (string.IsNullOrEmpty(sceneName)) { sceneName = "Unnamed"; } #else sceneName = SceneManager.GetActiveScene().name; #endif return sceneName; } public static int GetTargetID(object target) { var beh = target as BaseBehaviour; if (beh != null) return beh.GetPersistentId(); var obj = target as BaseScriptableObject; if (obj != null) return obj.GetPersistentId(); return RuntimeHelpers.GetHashCode(target); } public static int CombineHashCodes<Item0, Item1>(Item0 item0, Item1 item1) { int hash = 17; hash = hash * 31 + item0.GetHashCode(); hash = hash * 31 + item1.GetHashCode(); return hash; } public static int CombineHashCodes<Item0, Item1, Item2>(Item0 item0, Item1 item1, Item2 item2) { int hash = 17; hash = hash * 31 + item0.GetHashCode(); hash = hash * 31 + item1.GetHashCode(); hash = hash * 31 + item2.GetHashCode(); return hash; } public static void Measure(string msg, int nTimes, Action<string> log, Action code) { log(string.Format("Time took to `{0}` is `{1}` ms", msg, Measure(nTimes, code))); } public static float Measure(int nTimes, Action code) { var w = System.Diagnostics.Stopwatch.StartNew(); for (int i = 0; i < nTimes; i++) code(); return w.ElapsedMilliseconds; } public static Dictionary<T, U> CreateDictionary<T, U>(IEnumerable<T> keys, IList<U> values) { return keys.Select((k, i) => new { k, v = values[i] }).ToDictionary(x => x.k, x => x.v); } public static Texture2D GetTexture(byte r, byte g, byte b, byte a, HideFlags flags) { var texture = new Texture2D(1, 1); texture.SetPixel(0, 0, new Color32(r, g, b, a)); texture.Apply(); texture.hideFlags = flags; return texture; } public static Texture2D GetTexture(Color32 c, HideFlags flags) { return GetTexture(c.r, c.g, c.b, c.a, flags); } public static Texture2D GetTexture(Color32 c) { return GetTexture(c, HideFlags.None); } public static Color HexToColor(string hex) { byte r = byte.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber); byte g = byte.Parse(hex.Substring(2, 2), System.Globalization.NumberStyles.HexNumber); byte b = byte.Parse(hex.Substring(4, 2), System.Globalization.NumberStyles.HexNumber); return new Color32(r, g, b, 255); } public static string ColorToHex(Color32 color) { string hex = color.r.ToString("X2") + color.g.ToString("X2") + color.b.ToString("X2"); return hex; } } }
mit
JannoEsko/q3panel
classes/api/API.php
9604
<?php /** * API class, handles all of the API calls. * @author Janno */ class API { private $username; private $password; /** * Constructs the API object. * @param string $username The username of the requestor. * @param string $password The password of the requestor. */ function __construct($username, $password) { $this->username = $username; $this->password = $password; } /** * Gets the servers. * $param SQL $sql The SQL handle. * @param int $server_id [optional] The server ID, if not specified gets all the servers. */ public function getServers(SQL $sql, $server_id = null) { require_once __DIR__ . "/../Constants.php"; require_once __DIR__ . "/../users/User.php"; require_once __DIR__ . "/../servers/Server.php"; $user = new User($this->username, $this->password); $dat = $user->authenticate($sql); if (!isset($dat['error']) && intval($dat['group_id']) === Constants::$PANEL_ADMIN) { if ($server_id !== null || strlen($server_id) > 0) { $dat = Server::getServersWithHostAndGame($sql, $dat['user_id'], $server_id); for ($i = 0; $i < sizeof($dat); $i++) { $dat[$i]['server_password'] = ""; } return $dat; } $dat = Server::getServersWithHostAndGame($sql, $dat['user_id']); for ($i = 0; $i < sizeof($dat); $i++) { $dat[$i]['server_password'] = ""; } return $dat; } else { return "NOT_AUTHORIZED"; } } /** * Stops the server * @param SQL $sql The SQL handle. * @param int $server_id The server ID which to stop. * @return string Returns the API message. */ public function stopServer(SQL $sql, $server_id) { require_once __DIR__ . "/../Constants.php"; require_once __DIR__ . "/../users/User.php"; require_once __DIR__ . "/../servers/host/Host.php"; require_once __DIR__ . "/../ssh/SSH.php"; require_once __DIR__ . "/../servers/Server.php"; require_once __DIR__ . "/../servers/Game.php"; $user = new User($this->username, $this->password); $dat = $user->authenticate($sql); if (!isset($dat['error']) && intval($dat['group_id']) === Constants::$PANEL_ADMIN) { $srvData = Server::getServersWithHostAndGame($sql, $dat['user_id'], $server_id); if (sizeof($srvData) === 1) { $srvData = $srvData[0]; $host = new Host($srvData['host_id'], $srvData['servername'], $srvData['hostname'], $srvData['sshport'], $srvData['host_username'], $srvData['host_password']); $game = new Game($srvData['game_id'], $srvData['game_name'], $srvData['game_location'], $srvData['startscript']); $server = new Server($srvData['server_id'], $host, $srvData['server_name'], $game, $srvData['server_port'], $srvData['server_account'], $srvData['server_password'], $srvData['server_status'], $srvData['server_startscript'], $srvData['current_players'], $srvData['max_players'], $srvData['rconpassword']); $dat = $server->stopServer($sql); if ($dat === true) { return "SERVER_STOPPED"; } else { return $dat; } } else { return "BAD_METHOD_CALL"; } } else { return "NOT_AUTHORIZED"; } } /** * Starts the server * @param SQL $sql The SQL handle. * @param int $server_id The server ID which to start. * @return string Returns the API message. */ public function startServer(SQL $sql, $server_id) { require_once __DIR__ . "/../Constants.php"; require_once __DIR__ . "/../users/User.php"; require_once __DIR__ . "/../servers/host/Host.php"; require_once __DIR__ . "/../ssh/SSH.php"; require_once __DIR__ . "/../servers/Server.php"; require_once __DIR__ . "/../servers/Game.php"; $user = new User($this->username, $this->password); $dat = $user->authenticate($sql); if (!isset($dat['error']) && intval($dat['group_id']) === Constants::$PANEL_ADMIN) { $srvData = Server::getServersWithHostAndGame($sql, $dat['user_id'], $server_id); if (sizeof($srvData) === 1) { $srvData = $srvData[0]; $host = new Host($srvData['host_id'], $srvData['servername'], $srvData['hostname'], $srvData['sshport'], $srvData['host_username'], $srvData['host_password']); $game = new Game($srvData['game_id'], $srvData['game_name'], $srvData['game_location'], $srvData['startscript']); $server = new Server($srvData['server_id'], $host, $srvData['server_name'], $game, $srvData['server_port'], $srvData['server_account'], $srvData['server_password'], $srvData['server_status'], $srvData['server_startscript'], $srvData['current_players'], $srvData['max_players'], $srvData['rconpassword']); if (intval($server->getServer_status()) === Constants::$SERVER_DISABLED) { return "SERVER_DISABLED_CANT_START"; } $dat = $server->startServer($sql); if ($dat === true) { return "SERVER_STARTED"; } else { return $dat; } } else { return "BAD_METHOD_CALL"; } } else { return "NOT_AUTHORIZED"; } } /** * Disables the server * @param SQL $sql The SQL handle. * @param int $server_id The server ID which to disable. * @return string Returns the API message. */ public function disableServer(SQL $sql, $server_id) { require_once __DIR__ . "/../Constants.php"; require_once __DIR__ . "/../users/User.php"; require_once __DIR__ . "/../servers/host/Host.php"; require_once __DIR__ . "/../ssh/SSH.php"; require_once __DIR__ . "/../servers/Server.php"; require_once __DIR__ . "/../servers/Game.php"; $user = new User($this->username, $this->password); $dat = $user->authenticate($sql); if (!isset($dat['error']) && intval($dat['group_id']) === Constants::$PANEL_ADMIN) { $srvData = Server::getServersWithHostAndGame($sql, $dat['user_id'], $server_id); if (sizeof($srvData) === 1) { $srvData = $srvData[0]; $host = new Host($srvData['host_id'], $srvData['servername'], $srvData['hostname'], $srvData['sshport'], $srvData['host_username'], $srvData['host_password']); $game = new Game($srvData['game_id'], $srvData['game_name'], $srvData['game_location'], $srvData['startscript']); $server = new Server($srvData['server_id'], $host, $srvData['server_name'], $game, $srvData['server_port'], $srvData['server_account'], $srvData['server_password'], $srvData['server_status'], $srvData['server_startscript'], $srvData['current_players'], $srvData['max_players'], $srvData['rconpassword']); $server->stopServer($sql); $dat = $server->disableServer($sql); if ($dat === true) { return "SERVER_DISABLED"; } else { return $dat; } } else { return "BAD_METHOD_CALL"; } } else { return "NOT_AUTHORIZED"; } } /** * Enables the server * @param SQL $sql The SQL handle. * @param int $server_id The server ID which to enable. * @return string Returns the API message. */ public function enableServer(SQL $sql, $server_id) { require_once __DIR__ . "/../Constants.php"; require_once __DIR__ . "/../users/User.php"; require_once __DIR__ . "/../servers/host/Host.php"; require_once __DIR__ . "/../ssh/SSH.php"; require_once __DIR__ . "/../servers/Server.php"; require_once __DIR__ . "/../servers/Game.php"; $user = new User($this->username, $this->password); $dat = $user->authenticate($sql); if (!isset($dat['error']) && intval($dat['group_id']) === Constants::$PANEL_ADMIN) { $srvData = Server::getServersWithHostAndGame($sql, $dat['user_id'], $server_id); if (sizeof($srvData) === 1) { $srvData = $srvData[0]; $host = new Host($srvData['host_id'], $srvData['servername'], $srvData['hostname'], $srvData['sshport'], $srvData['host_username'], $srvData['host_password']); $game = new Game($srvData['game_id'], $srvData['game_name'], $srvData['game_location'], $srvData['startscript']); $server = new Server($srvData['server_id'], $host, $srvData['server_name'], $game, $srvData['server_port'], $srvData['server_account'], $srvData['server_password'], $srvData['server_status'], $srvData['server_startscript'], $srvData['current_players'], $srvData['max_players'], $srvData['rconpassword']); $dat = $server->enableServer($sql); if ($dat === true) { return "SERVER_ENABLED"; } else { return $dat; } } else { return "BAD_METHOD_CALL"; } } else { return "NOT_AUTHORIZED"; } } }
mit
kleisauke/fullcalendar
locale/hi.js
1732
import 'moment/locale/hi'; import * as FullCalendar from 'fullcalendar'; /* Hindi initialisation for the jQuery UI date picker plugin. */ /* Written by Michael Dawart. */ FullCalendar.datepickerLocale('hi', 'hi', { closeText: "बंद", prevText: "पिछला", nextText: "अगला", currentText: "आज", monthNames: [ "जनवरी ","फरवरी","मार्च","अप्रेल","मई","जून", "जूलाई","अगस्त ","सितम्बर","अक्टूबर","नवम्बर","दिसम्बर" ], monthNamesShort: [ "जन", "फर", "मार्च", "अप्रेल", "मई", "जून", "जूलाई", "अग", "सित", "अक्ट", "नव", "दि" ], dayNames: [ "रविवार", "सोमवार", "मंगलवार", "बुधवार", "गुरुवार", "शुक्रवार", "शनिवार" ], dayNamesShort: [ "रवि", "सोम", "मंगल", "बुध", "गुरु", "शुक्र", "शनि" ], dayNamesMin: [ "रवि", "सोम", "मंगल", "बुध", "गुरु", "शुक्र", "शनि" ], weekHeader: "हफ्ता", dateFormat: "dd/mm/yy", firstDay: 1, isRTL: false, showMonthAfterYear: false, yearSuffix: "" }); FullCalendar.locale("hi", { buttonText: { month: "महीना", week: "सप्ताह", day: "दिन", list: "कार्यसूची" }, allDayText: "सभी दिन", eventLimitText: function(n) { return "+अधिक " + n; }, noEventsMessage: "कोई घटनाओं को प्रदर्शित करने के लिए" });
mit
msosland/data-structures
array-list/array_list_spec.rb
4163
require_relative 'array_list' describe ArrayList do let(:list) {ArrayList.new} describe "#new" do it "instantiates a new dynamic list with initial capacity of 16" do expect(FixedArray).to receive(:new).with(16) ArrayList.new end it "instantiates a new dynamic list with a specified initial capacity" do initialCapacity = 32 expect(FixedArray).to receive(:new).with(initialCapacity) ArrayList.new(initialCapacity) end end describe "#add" do it "adds the element to the list" do expect { list.add(double(:object)) }.to change { list.length }.by(1) end it "returns the object that was added" do object = double(:object) expect(list.add(object)).to eq object end it "adds more space when needed" do list = ArrayList.new(16) 16.times do list.add(double(:object)) end expect { list.add(double(:new_object)) }.not_to raise_error end end describe "#get" do it "returns the element at the specified index in the list" do object = double(:object) list.add(object) expect(list.get(0)).to eq object end it "raises OutOFBoundsException if specified position is less than zero" do expect { list.get(-1) }.to raise_error(IndexOutOfBoundsError) end it "raises OutOFBoundsException if specified position is greater than or equal to size" do expect { list.get(0) }.to raise_error(IndexOutOfBoundsError) end end describe "#set" do let(:original_object) { double(:original_object) } let(:replacement_object) { double(:replacement_object) } before do list.add(original_object) end it "replaces the element at the specified index with the specified element" do expect { list.set(0, replacement_object) }.to change { list.get(0) }.from(original_object).to(replacement_object) end it "returns the replacement element" do expect(list.set(0, replacement_object)).to eq replacement_object end it "raises OutOFBoundsException if specified position is less than zero" do expect { list.set(-1, replacement_object) }.to raise_error(IndexOutOfBoundsError) end it "raises OutOFBoundsException if specified position is greater than or equal to size" do expect { list.set(list.length, replacement_object) }.to raise_error(IndexOutOfBoundsError) end end describe "#length" do it "returns 0 for an empty list" do list = ArrayList.new expect(list.length).to eq 0 end it "returns the number of elements in the list" do 5.times do list.add(double(:object)) end expect(list.length).to eq 5 end end describe "#insert" do let(:first_object) { double(:first_object) } let(:middle_object) { double(:middle_object) } let(:last_object) { double(:last_object) } before do list.add(first_object) list.add(last_object) end it "inserts the specified element at the specified position in this list" do expect { list.insert(1, middle_object) }.to change { list.get(1) }.from(last_object).to(middle_object) end it "shift all proceeding elements in the list down by 1 position" do expect { list.insert(1, middle_object) }.not_to change { list.get(list.length - 1) } end it "returns the inserted element" do expect(list.insert(1, middle_object)).to eq middle_object end it "increments length by 1" do expect { list.insert(1, middle_object) }.to change { list.length }.by(1) end it "raises OutOFBoundsException if specified position is less than zero" do expect { list.insert(-1, middle_object) }.to raise_error(IndexOutOfBoundsError) end it "raises OutOFBoundsException if specified position is greater than size" do expect { list.insert(list.length + 1, middle_object) }.to raise_error(IndexOutOfBoundsError) end it "adds more space when needed" do list = ArrayList.new(16) 16.times do list.add(double(:object)) end expect { list.insert(0, double(:new_object)) }.not_to raise_error end end end
mit
austinsand/doc-roba
automation/classes/node/ready_checker.js
3231
"use strict"; var Future = require("fibers/future"), _ = require("underscore"), assert = require("assert"), log4js = require("log4js"), logger = log4js.getLogger("ready"), commands = [ "waitFor", "waitForChecked", "waitForEnabled", "waitForExist", "waitForSelected", "waitForText", "waitForValue", "waitForVisible" ]; logger.setLevel("TRACE"); class ReadyChecker { /** * ReadyChecker * @param driver * @param timeout * @return {ReadyChecker} */ constructor (driver, timeout) { logger.debug("Creating ready checker"); // can't function without a driver assert(driver, "ReadyChecker requires a driver"); // create the list of commands var ready = this; ready.commandList = []; ready.driver = driver; ready.checks = []; ready.timeout = timeout || 5000; // hook up the command listeners _.each(commands, function (command) { logger.trace("Registering Ready Check: ", command); ready.commandList.push(command); ready[ command ] = function () { logger.debug("Ready Command called: ", command); var commandArgs = arguments, args = _.map(_.keys(commandArgs), function (i) { return commandArgs[ "" + i ]; }); ready.checks.push({ command: command, args : args }); }; }); return ready; } /** * Perform the ready checks */ check () { // make sure there are checks to run if (!this.checks.length) { logger.trace("Ready.check called with no checks"); return true; } var ready = this, driver = ready.driver.driver, future = new Future(), startTime = Date.now(), allPass = true, checksReturned = 0, result; // run the checks logger.debug("Running ready checks"); _.each(ready.checks, function (check, i) { var args = check.args; args.push(ready.timeout); args.push(function (error, result) { // log the result allPass = allPass && result; check.result = { pass : result, time : Date.now() - startTime, timeout: ready.timeout }; if (error) { logger.error("Check returned error: ", i, checksReturned, check.result, error); check.result.error = error; } else { logger.trace("Check returned: ", i, checksReturned, check.result); } // check for completion checksReturned++; if (checksReturned == ready.checks.length) { future.return(); } }); logger.debug("Ready Check Command setup: ", check.command, check.args[ 0 ]); driver[ check.command ].apply(driver, args); }); // wait for the checks to return logger.trace("Ready Checker waiting for checks"); future.wait(); // make sure everything passed logger.debug("Ready Checker complete: ", allPass); return allPass; } } module.exports = ReadyChecker;
mit
luismpsilva/spl-invent
www/scripts/common.js
20570
/********************************************* GLOBAL VARIABLES *********************************************/ var app = null, db = null, jsconfirm = null, dataDirectory = null, tempDirectory = "Temp"; /******************************************** GLOBAL OBSERVABELS ********************************************/ var obs_inventario = null; /******************************************* NOTIFICATION DIALOGS *******************************************/ function notificacao(mensagem, tipo, title, autoClose, confirm) { if (!autoClose) { var type = null; var $title = 'Erro'; var $icon = 'fa fa-warning'; if (tipo && tipo == "error") { type = "error"; console.log(mensagem); } else { type = "info"; $title = 'Informação'; $icon = 'fa fa-info-circle'; } if (title) { $title = title; } if (navigator && navigator.notification) { mensagem = mensagem.replace(/<br>/g, '\n').replace(/<br\/>/g, '\n').replace(/<br \/>/g, '\n'); navigator.notification.alert(mensagem, function () { }, $title); } else { $.confirm({ title: $title, content: mensagem, backgroundDismiss: false, icon: $icon, theme: 'hololight', titleClass: 'app-bottom-line', autoClose: autoClose ? 'confirm|3000' : null, buttons: { Ok: { btnClass: 'app-bottom-line confirm-button-noborder btn-default-width100', text: 'Ok', action: confirm } }, }); } } else { if (!$(document).data("kendoNotification")) { $(document).kendoNotification({ stacking: "down", autoHideAfter: 3000, animation: { open: { effects: "slideIn:left" }, close: { effects: "slideIn:left", reverse: true } }, position: { pinned: true, top: 10, right: 10 }, templates: [{ type: "warning", template: "<div class='k-notification-wrap' style='box-shadow: 0 0 15px rgb(250, 189, 33)'><i class='fa fa-exclamation-triangle' aria-hidden='true' style='margin-right:5px'></i>#= mensagem #</div>" }, { type: "info", template: "<div class='k-notification-wrap' style='box-shadow: 0 0 15px rgb(0, 124, 192)'><i class='fa fa-info-circle' aria-hidden='true' style='margin-right:5px'></i>#= mensagem #</div>" }, { type: "error", template: "<div class='k-notification-wrap' style='box-shadow: 0 0 15px rgb(255, 113, 113)'><i class='fa fa-times-circle-o' aria-hidden='true' style='margin-right:5px'></i>#= mensagem #</div>" }, { type: "success", template: "<div class='k-notification-wrap' style='box-shadow: 0 0 15px rgb(17, 167, 81)'><i class='fa fa-check-circle-o' aria-hidden='true' style='margin-right:5px'></i>#= mensagem #</div>" } ] }).data("kendoNotification").show({ mensagem: mensagem }, tipo); } else { $(document).data("kendoNotification").show({ mensagem: mensagem }, tipo); } } } function $confirm(message, confirmCallback, title, buttonLabels, event, closeIcon) { var useNative = typeof nativeDialogs != 'undefined' && nativeDialogs, isNavigator = typeof navigator != 'undefined'; if (isNavigator && useNative && navigator.notification) { navigator.notification.confirm(message, confirmCallback, title, buttonLabels); } else { var confirmButton = buttonLabels != undefined ? buttonLabels[0] : ['OK']; var cancelButton = (buttonLabels != undefined && buttonLabels.length > 1) ? buttonLabels[1] : false; var confirmButtonText = buttonLabels != undefined ? buttonLabels[0].toLowerCase() : 'ok'; var cancelButtonText = (buttonLabels != undefined && buttonLabels.length > 1) ? buttonLabels[1].toLowerCase() : 'fechar'; if (jsconfirm && jsconfirm.$content && jsconfirm.$content.html() === message) { return; } jsconfirm = $.confirm({ closeIcon: closeIcon, closeIconClass: 'fa fa-times-circle-o confirm-close-icon', //columnClass: 'col-md-7 col-md-offset-2', title: title, content: message, backgroundDismiss: false, icon: "fa fa-question-circle", theme: 'hololight', titleClass: 'app-bottom-line', buttons: { confirm: { btnClass: 'app-bottom-line confirm-button-noborder', text: confirmButton, action: function () { jsconfirm = null; if (confirmCallback) { confirmCallback.call(this, 1); } } }, cancel: { btnClass: 'app-bottom-line confirm-button-noborder', text: cancelButtonText, action: function () { jsconfirm = null; if (confirmCallback) { confirmCallback.call(this, 2); } } } } }); if (typeof SpeechRecognition != 'undefined') { if (!recognition) { recognition = new SpeechRecognition(); } recognition.onresult = function (event) { if (event.results.length > 0) { if (event.results[0][0].transcript == confirmButtonText) { if (confirmCallback) { confirmCallback.call(this, 1); } } else { if (event.results[0][0].transcript == cancelButtonText || event.results[0][0].transcript == 'fechar') { if (confirmCallback) { confirmCallback.call(this, 2); } } } } } } } } /****************************************** MODAL GENERIC FUNCTIONS *****************************************/ function openModalView(args, viewname, dataItem) { if (viewname && $("#" + viewname).length > 0 && $("#" + viewname).data("kendoMobileModalView")) { if (args && args.target !== args.currentTarget) { args.target = args.currentTarget; } if (dataItem) { args.dataItem = dataItem; } $("#" + viewname).data("kendoMobileModalView").trigger("open", args); $("#" + viewname).kendoMobileModalView("open"); } // origem da chamada =================== //if (args) { // var target = args && args.target ? args.target : null; // if (target && $(target).data("modalview")) { // $(args.sender).data("caller", $(target).data("modalview")); // $(args.sender).data("open_next", true); // if ($(args.sender) && $(args.sender).attr('id')) { // $($(args.sender).attr('id')).data('modalview', $(target).data("modalview")); // } // closeModalView(null, $(target).data("modalview")); // } // else { // $(args.sender).data("open_next", false); // $(args.sender).data("caller", null); // if (args && args.sender && args.sender.id) // $(args.sender.id).data('modalview', null); // } //} //====================================== } function closeModalView(args, viewname) { if (args) { if (args.button) { var data = args.button.data(); viewname = data.viewname; } else { if (args.sender && args.sender.element) { var data = args.sender.element.data(); viewname = data.viewname; } else { if (args.currentTarget) { var data = $(args.currentTarget).data(); viewname = data.viewname; } } } } if (viewname && viewname !== '' && viewname.indexOf('#') < 0) { viewname = '#' + viewname; } if (viewname && $(viewname).length > 0) { if ($(viewname).data('kendoMobileModalView')) { $(viewname).data('kendoMobileModalView').close(); } if ($(viewname).data('modalview')) { var modalview = $('#' + $(viewname).data('modalview')); if (modalview.data('kendoMobileModalView')) {// initialized modalview.kendoMobileModalView("open"); } } } } /********************************************* LOADER FUNCTIONS *********************************************/ function Loading(show) { if (show) kendo.mobile.application.showLoading(); else kendo.mobile.application.hideLoading(); } /*********************************************** DB OPERATIONS **********************************************/ function startTransation() { return $.Deferred(function () { var that = this; if (db) { db.transaction(function (tr) { that.resolve(tr); }, function (error) { notificacao('Transaction error: ' + error.message, 'error', 'Ups...'); }, function () { console.log('Transaction Ok'); }); } else { that.resolve(); } }); } function removeFromDb(query, fields) { if (db) { startTransation().then(function (tr) { tr.executeSql(query, fields, function (tx, res) { notificacao("Removido com sucesso " + res.rowsAffected + " registo(s).", "success", null, true); }, function (tx, error) { notificacao("DELETE error: [removeFromDb]: " + error.message, "error", 'Ups...'); }); }); } } function clearTable(table) { return $.Deferred(function () { var that = this; startTransation().then(function (tr) { tr.executeSql("DELETE FROM " + table, [], function (tx, res) { notificacao("Removido com sucesso " + res.rowsAffected + " registo(s).", "success", null, true); that.resolve(); }, function (tx, error) { notificacao("DELETE error: [clearTable]: " + error.message, "error", 'Ups...'); }); }); }); } function updateFromDb(query, fields, isMultiple) { return $.Deferred(function () { var that = this; startTransation().then(function (tr) { if (!isMultiple) { tr.executeSql(query, fields, function (tx, res) { console.log("insertId: " + res.insertId); notificacao(res.rowsAffected + " Registos actualizado(s) com sucesso!", "success", null, true); that.resolve(); }, cbErrorTransaction); } else { var regActualizados = 0, promises = [], promCount = 0; Loading(true); for (var i = 0, length = isMultiple.length; i < length; i++) { var dfd = new $.Deferred(); promises.push(dfd); tr.executeSql(isMultiple[i].query, isMultiple[i].fields, function (tx, res) { regActualizados++; console.log("insertId: " + res.insertId); promises[promCount].resolve(); promCount++; }, function (tx, error) { promises[promCount].resolve(); promCount++; }); } $.when.apply(undefined, promises).then(function () { Loading(); notificacao(regActualizados + " Registos actualizado(s) com sucesso!", "success", null, true); that.resolve(); }); } }); }); } function Count(tr, table) { return $.Deferred(function () { var that = this; tr.executeSql("SELECT count(*) AS mycount FROM " + table, [], function (tx, rs) { that.resolve(rs.rows.item(0).mycount); }, function (tx, error) { notificacao('COUNT error: ' + error.message, 'error', 'Ups...'); }); }); } function ListTables() { return $.Deferred(function () { var that = this; startTransation().then(function (tr) { tr.executeSql("SELECT name FROM sqlite_master WHERE type='table'", [], function (tx, resultSet) { try { var data = []; if (resultSet.rows.length > 0) { for (var x = 0; x < resultSet.rows.length; x++) { data.push(new TABELS(resultSet.rows.item(x))); } } that.resolve(data); } catch (ex) { notificacao('Erro ao criar objecto [ListTable]: ' + ex.message, 'error', 'Ups...'); } }, cbErrorTransaction); }); }); } function closeDB() { return $.Deferred(function () { var that = this; db.close(function () { console.log("DB closed!"); that.resolve() }, function (error) { console.log("Error closing DB:" + error.message); that.resolve() }); }) } function cbErrorTransaction(tx, error) { notificacao("Ocorreu um erro ao executar o sql: " + error.message, "error", 'Ups...'); Loading(); } /********************************************** OBJECT CLASSES **********************************************/ function INVENTARIO(data) { this.ID = data.id; this.DESCRICAO = data.descricao; this.ID_TIPO = data.id_tipo; this.TIPO = data.tipo; this.QUANTIDADE = data.quantidade; this.QUANTIDADE_PICADA = data.quantidade_picada; this.FOTO = (data.foto && data.foto != 'null') ? data.foto : null; //return this; } function TIPO(data) { this.ID = data.id; this.DESC_TIPO = data.desc_tipo; this.DESCRICAO = data.descricao } function TABELS(data) { this.TABLE = data.name; } /********************************************** EMAIL FUNCTIONS *********************************************/ function openEmail(data) { return $.Deferred(function () { var that = this; if (data) { cordova.plugins.email.open({ to: data.to ? data.to : null, //Array - email addresses for TO field cc: data.cc ? data.cc : null, //Array - email addresses for CC field bcc: data.bcc ? data.bcc : null, //Array - email addresses for BCC field attachments: data.attachments ? data.attachments : null, //Array - file paths or base64 data streams subject: data.subject ? data.subject : null, //String - subject of the email body: data.body ? data.body : null, //String email body (for HTML, set isHtml to true) isHtml: data.isHtml ? true : null, //Boolean - indicats if the body is HTML or plain text }, function (a, b, c) { console.log(a); that.resolve(); }); } else { cordova.plugins.email.open({}, function (a, b, c) { console.log(a); that.resolve(); }); } }); } function mailAvailable() { return $.Deferred(function () { var that = this; cordova.plugins.email.isAvailable(function (hasAccount) { if (hasAccount) { that.resolve(); } else { notificacao("Não tem conta de E-Mail configurada.", "error", "Ups..."); } }); }); } /*********************************************** DD FUNCTIONS ***********************************************/ function dd_addNewTipo(widgetId, value) { var widget = $("#" + widgetId).getKendoDropDownList(); var dataSource = widget.dataSource; if (confirm("Tem a certeza?")) { startTransation().then(function (tx) { var query = "INSERT INTO tipo (desc_tipo) VALUES ('" + value + "')"; tx.executeSql(query, [], function (tx, res) { dataSource.add({ ID: res.insertId, DESC_TIPO: value }); dataSource.one("sync", function () { widget.select(dataSource.view().length - 1); }); dataSource.sync(); notificacao("Inserido com sucesso.", "success", null, true); Loading(); }, cbErrorTransaction); }, function (error) { notificacao("Erro de transaction [dd_addNewTipo]: " + error.message, "error", 'Ups...'); Loading(); }); } }; /******************************************* APP GLOBAL FUNCTIONS *******************************************/ function exitFromApp() { closeDB().then(function () { if (navigator && navigator.app) navigator.app.exitApp(); }); } function saveAsBlob(dataURI) { var blob = dataURI; // could be a Blob object if (typeof dataURI == "string") { var parts = dataURI.split(";base64,"); var contentType = parts[0]; var base64 = atob(parts[1]); var array = new Uint8Array(base64.length); for (var idx = 0; idx < base64.length; idx++) { array[idx] = base64.charCodeAt(idx); } blob = new Blob([array.buffer], { type: contentType }); } return blob; } function showImageHandler(open, data) { if (open) { $("#my-overlay p").text(data.text); $("#my-overlay").removeClass("hidden").css("background-image", "url(data:image/jpeg;base64," + data.image + ")"); } else { $("#my-overlay p").text(null); $("#my-overlay").css("background-image", '').addClass("hidden"); } } function createGuid() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } var isMobile = { getUserAgent: function () { return navigator.userAgent; }, Android: function () { return /Android/i.test(isMobile.getUserAgent()) && !isMobile.Windows(); }, BlackBerry: function () { return /BlackBerry|BB10|PlayBook/i.test(isMobile.getUserAgent());; }, iPhone: function () { return /iPhone/i.test(isMobile.getUserAgent()) && !isMobile.iPad() && !isMobile.Windows(); }, iPod: function () { return /iPod/i.test(isMobile.getUserAgent()); }, iPad: function () { return /iPad/i.test(isMobile.getUserAgent()); }, iOS: function () { return (isMobile.iPad() || isMobile.iPod() || isMobile.iPhone()); }, Opera: function () { return /Opera Mini/i.test(isMobile.getUserAgent()); }, Windows: function () { return /Windows Phone|IEMobile|WPDesktop|Edge/i.test(isMobile.getUserAgent()); }, KindleFire: function () { return /Kindle Fire|Silk|KFAPWA|KFSOWI|KFJWA|KFJWI|KFAPWI|KFAPWI|KFOT|KFTT|KFTHWI|KFTHWA|KFASWI|KFTBWI|KFMEWI|KFFOWI|KFSAWA|KFSAWI|KFARWI/i.test(isMobile.getUserAgent()); }, any: function () { return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows()); } }; var delay = (function () { var timer = 0; return function (callback, ms) { clearTimeout(timer); timer = setTimeout(callback, ms); }; })();
mit
oleg-alexandrov/PolyView
geom/polyUtils.cpp
20206
// MIT License Terms (http://en.wikipedia.org/wiki/MIT_License) // // Copyright (C) 2011 by Oleg Alexandrov // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include <cmath> #include <cstdlib> #include <iostream> #include <cmath> #include <cfloat> #include <cstring> #include <cassert> #include <algorithm> #include <edgeUtils.h> #include <dPoly.h> #include <polyUtils.h> #include <geomUtils.h> #include <kdTree.h> #include <dTree.h> using namespace std; using namespace utils; void utils::findClosestAnnotation(// inputs double x0, double y0, const std::vector<dPoly> & polyVec, // outputs int & polyVecIndex, int & annoIndexInCurrPoly, double & minDist ){ // Find the closest annotation in a given vector of polygons to a given point. polyVecIndex = -1; annoIndexInCurrPoly = -1; minDist = DBL_MAX; for (int s = 0; s < (int)polyVec.size(); s++){ double minDist0; int annoIndex; polyVec[s].findClosestAnnotation(// inputs x0, y0, // outputs annoIndex, minDist0 ); if (minDist0 <= minDist){ polyVecIndex = s; annoIndexInCurrPoly = annoIndex; minDist = minDist0; } } return; } void utils::findClosestPolyVertex(// inputs double x0, double y0, const std::vector<dPoly> & polyVec, // outputs int & polyVecIndex, int & polyIndexInCurrPoly, int & vertIndexInCurrPoly, double & minX, double & minY, double & minDist ){ // Find the closest point in a given vector of polygons to a given point. polyVecIndex = -1; polyIndexInCurrPoly = -1; vertIndexInCurrPoly = -1; minX = x0; minY = y0; minDist = DBL_MAX; for (int s = 0; s < (int)polyVec.size(); s++){ double minX0, minY0, minDist0; int polyIndex, vertIndex; polyVec[s].findClosestPolyVertex(// inputs x0, y0, // outputs polyIndex, vertIndex, minX0, minY0, minDist0 ); if (minDist0 <= minDist){ polyVecIndex = s; polyIndexInCurrPoly = polyIndex; vertIndexInCurrPoly = vertIndex; minDist = minDist0; minX = minX0; minY = minY0; } } return; } void utils::findClosestPolyEdge(// inputs double x0, double y0, const std::vector<dPoly> & polyVec, // outputs int & vecIndex, int & polyIndex, int & vertIndex, double & minX, double & minY, double & minDist ){ // Find the closest edge in a given vector of polygons to a given point. vecIndex = -1; polyIndex = -1; vertIndex = -1; minX = DBL_MAX; minY = DBL_MAX; minDist = DBL_MAX; for (int vecIter = 0; vecIter < (int)polyVec.size(); vecIter++){ double lx, ly, ldist; int pIndex, vIndex; polyVec[vecIter].findClosestPolyEdge(x0, y0, // in pIndex, vIndex, lx, ly, ldist // out ); if (ldist <= minDist){ vecIndex = vecIter; polyIndex = pIndex; vertIndex = vIndex; minX = lx; minY = ly; minDist = ldist; } } return; } void utils::alignPoly1ToPoly2(dPoly & poly1, const dPoly & poly2, utils::linTrans & T // save the applied transform ){ // Find the closest pair of vertices from poly1 to poly2. Shift poly1 // so that the first vertex is on top of the second one. vector<segDist> distVec; findDistanceFromVertsOfPoly1ToVertsPoly2(// inputs poly1, poly2, // outputs distVec ); int len = distVec.size(); if (len == 0) return; // one of the polygons is empty segDist S = distVec[len -1]; // this corresponds to shortest distance poly1.applyTransform(1, 0, 0, 1, S.endx - S.begx, S.endy - S.begy, T); return; } void utils::findDistanceFromVertsOfPoly1ToVertsPoly2(// inputs const dPoly & poly1, const dPoly & poly2, // outputs std::vector<segDist> & distVec ){ // Given two sets of polygons, for each vertex in the first set of // polygons find the distance to the closest vertex in the second // set of polygons, and the segment with the smallest distance. Sort // these segments in decreasing value of their lengths. // The complexity of this algorithm is roughly // size(poly1)*log(size(poly2)). distVec.clear(); const double * x1 = poly1.get_xv(); const double * y1 = poly1.get_yv(); int numVerts1 = poly1.get_totalNumVerts(); const double * x2 = poly2.get_xv(); const double * y2 = poly2.get_yv(); int numVerts2 = poly2.get_totalNumVerts(); if (numVerts1 == 0 || numVerts2 == 0) return; // no vertices // Put the edges of the second polygon in a tree for fast access kdTree T; T.formTreeOfPoints(numVerts2, x2, y2); for (int t = 0; t < numVerts1; t++){ double x = x1[t], y = y1[t]; double closestDist; PointWithId closestPt; T.findClosestVertexToPoint(// inputs x, y, // outputs closestPt, closestDist ); distVec.push_back(segDist(x, y, closestPt.x, closestPt.y, closestDist)); } sort(distVec.begin(), distVec.end(), segDistGreaterThan); return; } void utils::findDistanceBwPolys(// inputs const dPoly & poly1, const dPoly & poly2, // outputs std::vector<segDist> & distVec ){ // Find the distances from poly1 to poly2, then from poly2 to poly1. // Sort them in decreasing order of their lengths. See // findDistanceFromPoly1ToPoly2 for more info. findDistanceFromPoly1ToPoly2(poly1, poly2, // inputs distVec // outputs ); vector<segDist> l_distVec; findDistanceFromPoly1ToPoly2(poly2, poly1, // inputs l_distVec // outputs ); for (int s = 0; s < (int)l_distVec.size(); s++) distVec.push_back(l_distVec[s]); sort(distVec.begin(), distVec.end(), segDistGreaterThan); return; } void utils::findDistanceFromPoly1ToPoly2(// inputs const dPoly & poly1, const dPoly & poly2, // outputs std::vector<segDist> & distVec ){ // Given two sets of polygons, for each vertex in the first set of // polygons find the distance to the closest point (may be on edge) // in the second set of polygons, and the segment with the smallest // distance. Sort these segments in decreasing value of their // lengths. // The complexity of this algorithm is roughly // size(poly1)*log(size(poly2)). distVec.clear(); const double * x1 = poly1.get_xv(); const double * y1 = poly1.get_yv(); int numVerts1 = poly1.get_totalNumVerts(); int numVerts2 = poly2.get_totalNumVerts(); if (numVerts1 == 0 || numVerts2 == 0) return; // no vertices // Put the edges of the second polygon in a tree for fast access edgeTree T; T.putPolyEdgesInTree(poly2); for (int t = 0; t < numVerts1; t++){ double x = x1[t], y = y1[t]; double closestX, closestY, closestDist; seg closestEdge; T.findClosestEdgeToPoint(x, y, // inputs closestEdge, closestDist, closestX, closestY // outputs ); distVec.push_back(segDist(x, y, closestX, closestY, closestDist)); } sort(distVec.begin(), distVec.end(), segDistGreaterThan); return; } void utils::findDistanceBwPolysBruteForce(// inputs const dPoly & poly1, const dPoly & poly2, // outputs std::vector<segDist> & distVec ){ // A naive (but simple) implementation of findDistanceFromPoly1ToPoly2. distVec.clear(); const double * x = poly1.get_xv(); const double * y = poly1.get_yv(); int numVerts1 = poly1.get_totalNumVerts(); int numVerts2 = poly2.get_totalNumVerts(); if (numVerts1 == 0 || numVerts2 == 0) return; // no vertices for (int t = 0; t < numVerts1; t++){ int minPolyIndex, minVertIndex; double minX, minY, minDist = DBL_MAX; poly2.findClosestPolyEdge(x[t], y[t], // inputs minPolyIndex, minVertIndex, minX, minY, minDist // outputs ); if (minDist != DBL_MAX) distVec.push_back(segDist(x[t], y[t], minX, minY, minDist)); } sort(distVec.begin(), distVec.end(), segDistGreaterThan); return; } void utils::putPolyInMultiSet(const dPoly & P, std::multiset<dPoint> & mP){ const double * x = P.get_xv(); const double * y = P.get_yv(); int totalNumVerts = P.get_totalNumVerts(); mP.clear(); for (int v = 0; v < totalNumVerts; v++){ dPoint P; P.x = x[v]; P.y = y[v]; mP.insert(P); } return; } void utils::findPolyDiff(const dPoly & P, const dPoly & Q, // inputs std::vector<dPoint> & vP, std::vector<dPoint> & vQ // outputs ){ // Compare two polygons point-by-point. We assume that the polygons // may have collinear points. If one polygon has a point repeated // twice, but the second polygon has it repeated just once, this // will be flagged as a difference as well. // This utility will not be able to detect when two polygons are // different but contain exactly the same points. multiset<dPoint> mP; putPolyInMultiSet(P, mP); multiset<dPoint> mQ; putPolyInMultiSet(Q, mQ); // If a point is in mP, and also in mQ, mark it as being in mP and wipe it from mQ vector<dPoint> shared; shared.clear(); multiset<dPoint>::iterator ip, iq; for (ip = mP.begin(); ip != mP.end(); ip++){ iq = mQ.find(*ip); if ( iq != mQ.end() ){ shared.push_back(*ip); mQ.erase(iq); // Erase just the current instance of the given value } } // Wipe it from mP as well for (int s = 0; s < (int)shared.size(); s++){ ip = mP.find(shared[s]); if ( ip != mP.end() ){ mP.erase(ip); // Erase just the current instance of the given value } } vP.clear(); vQ.clear(); for (ip = mP.begin(); ip != mP.end(); ip++){ dPoint p; p.x = ip->x; p.y = ip->y; vP.push_back(p); } for (iq = mQ.begin(); iq != mQ.end(); iq++){ dPoint q; q.x = iq->x; q.y = iq->y; vQ.push_back(q); } return; } void utils::bdBox(const std::vector<dPoly> & polyVec, // outputs double & xll, double & yll, double & xur, double & yur ){ double big = DBL_MAX; xll = big; yll = big; xur = -big; yur = -big; for (int p = 0; p < (int)polyVec.size(); p++){ if (polyVec[p].get_totalNumVerts() == 0) continue; double xll0, yll0, xur0, yur0; polyVec[p].bdBox(xll0, yll0, xur0, yur0); xll = min(xll, xll0); xur = max(xur, xur0); yll = min(yll, yll0); yur = max(yur, yur0); } return; } void utils::setUpViewBox(// inputs const std::vector<dPoly> & polyVec, // outputs double & xll, double & yll, double & widx, double & widy ){ // Given a set of polygons, set up a box containing these polygons. double xur, yur; // local variables bdBox(polyVec, // inputs xll, yll, xur, yur // outputs ); // Treat the case of empty polygons if (xur < xll || yur < yll){ xll = 0.0; yll = 0.0; xur = 1000.0; yur = 1000.0; } // Treat the case when the polygons are degenerate if (xur == xll){ xll -= 0.5; xur += 0.5; } if (yur == yll){ yll -= 0.5; yur += 0.5; } widx = xur - xll; assert(widx > 0.0); widy = yur - yll; assert(widy > 0.0); // Expand the box slightly for plotting purposes double factor = 0.05; xll -= widx*factor; xur += widx*factor; widx *= 1.0 + 2*factor; yll -= widy*factor; yur += widy*factor; widy *= 1.0 + 2*factor; return; } void utils::markPolysInHlts(// Inputs const std::vector<dPoly> & polyVec, const std::vector<dPoly> & highlights, // Outputs std::map< int, std::map<int, int> > & markedPolyIndices ){ markedPolyIndices.clear(); for (int s = 0; s < (int)highlights.size(); s++){ double xll, yll, xur, yur; assert(highlights[s].get_totalNumVerts() == 4); highlights[s].bdBox(xll, yll, xur, yur); map<int, int> mark; for (int t = 0; t < (int)polyVec.size(); t++){ polyVec[t].markPolysIntersectingBox(xll, yll, xur, yur, // Inputs mark // Outputs ); for (map<int, int>::iterator it = mark.begin(); it != mark.end(); it++){ markedPolyIndices[t][it->first] = it->second; } } } return; } void utils::shiftMarkedPolys(// Inputs std::map< int, std::map<int, int> > & markedPolyIndices, double shift_x, double shift_y, // Inputs-outputs std::vector<dPoly> & polyVec ){ for (int pIter = 0; pIter < (int)polyVec.size(); pIter++){ polyVec[pIter].shiftMarkedPolys(markedPolyIndices[pIter], shift_x, shift_y); } return; } void utils::scaleMarkedPolysAroundCtr(// Inputs std::map< int, std::map<int, int> > & markedPolyIndices, double scale, // Inputs-outputs std::vector<dPoly> & polyVec ){ matrix2 M; M.a11 = scale; M.a12 = 0.0; M.a21 = 0.0; M.a22 = scale; transformMarkedPolysAroundCtr(// Inputs markedPolyIndices, M, // Inputs-outputs polyVec ); return; } void utils::rotateMarkedPolysAroundCtr(// Inputs std::map< int, std::map<int, int> > & markedPolyIndices, double angle, // Inputs-outputs std::vector<dPoly> & polyVec ){ double a = angle*M_PI/180.0, c = cos(a), s= sin(a); if (angle == round(angle) && int(angle)%90 == 0 ){ // The special case of angle multiple of 90 degrees c = round(c), s = round(s); } matrix2 M; M.a11 = c; M.a12 = -s; M.a21 = s; M.a22 = c; transformMarkedPolysAroundCtr(// Inputs markedPolyIndices, M, // Inputs-outputs polyVec ); return; } void utils::transformMarkedPolysAroundCtr(// Inputs std::map< int, std::map<int, int> > & markedPolyIndices, const utils::matrix2 & M, // Inputs-outputs std::vector<dPoly> & polyVec ){ if (getNumElements(markedPolyIndices) == 0) return; vector<dPoly> extractedPolyVec; extractMarkedPolys(// Inputs polyVec, markedPolyIndices, // Outputs extractedPolyVec ); // Find the center of the bounding box of the marked polygons double xll, yll, xur, yur; bdBox(extractedPolyVec, // inputs xll, yll, xur, yur // outputs ); dPoint P; P.x = (xll + xur)/2.0; P.y = (yll + yur)/2.0; for (int pIter = 0; pIter < (int)polyVec.size(); pIter++){ polyVec[pIter].transformMarkedPolysAroundPt(markedPolyIndices[pIter], M, P); } return; } void utils::eraseMarkedPolys(// Inputs std::map< int, std::map<int, int> > & markedPolyIndices, // Inputs-outputs std::vector<dPoly> & polyVec ){ for (int pIter = 0; pIter < (int)polyVec.size(); pIter++){ polyVec[pIter].eraseMarkedPolys(markedPolyIndices[pIter]); } return; } void utils::extractMarkedPolys(// Inputs const std::vector<dPoly> & polyVec, std::map< int, std::map<int, int> > & markedPolyIndices, // Outputs std::vector<dPoly> & extractedPolyVec ){ int pSize = polyVec.size(); extractedPolyVec.resize(pSize); for (int pIter = 0; pIter < pSize; pIter++){ polyVec[pIter].extractMarkedPolys(markedPolyIndices[pIter], // input extractedPolyVec[pIter] // output ); } return; } int utils::getNumElements(std::map< int, std::map<int, int> > & Indices){ int num = 0; map< int, map<int, int> >::iterator it; for (it = Indices.begin(); it != Indices.end(); it++){ num += (it->second).size(); } return num; }
mit
webignition/app.simplytestable.com
tests/Unit/Model/User/Summary/TeamTest.php
1816
<?php namespace App\Tests\Unit\User\Summary; use App\Model\User\Summary\Team as TeamSummary; class TeamTest extends \PHPUnit\Framework\TestCase { /** * @dataProvider jsonSerializeDataProvider * * @param bool $userIsInTeam * @param bool $hasInvite * @param array $expectedReturnValue */ public function testJsonSerialize( $userIsInTeam, $hasInvite, $expectedReturnValue ) { $teamSummary = new TeamSummary($userIsInTeam, $hasInvite); $this->assertEquals($expectedReturnValue, $teamSummary->jsonSerialize()); } /** * @return array */ public function jsonSerializeDataProvider() { return [ 'not in team, no invite' => [ 'userIsInTeam' => false, 'hasInvite' => false, 'expectedReturnValue' => [ 'in' => false, 'has_invite' => false, ], ], 'not in team, has invite' => [ 'userIsInTeam' => false, 'hasInvite' => true, 'expectedReturnValue' => [ 'in' => false, 'has_invite' => true, ], ], 'in team, no invite' => [ 'userIsInTeam' => true, 'hasInvite' => false, 'expectedReturnValue' => [ 'in' => true, 'has_invite' => false, ], ], 'in team, has invite' => [ 'userIsInTeam' => true, 'hasInvite' => true, 'expectedReturnValue' => [ 'in' => true, 'has_invite' => true, ], ], ]; } }
mit
patmaddox/method_matching
spec/extendable_block_spec.rb
286
require File.dirname(__FILE__) + '/spec_helper' module MethodMatching describe ExtendableBlock do it "should give a friendly message when block is called but none is set" do ExtendableBlock.new { block.call }. should raise_error(/No block given/) end end end
mit
ismaproco/maxtube
maxtube-appserver/app.js
1806
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); // module to enable cross domain var cors = require('cors') var routes = require('./routes/index'); var users = require('./routes/users'); var timer = require('./routes/timer'); var action = require('./routes/action'); var playlist = require('./routes/playlist'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(__dirname + '/public/favicon.ico')); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); //Add the cors module to express app.use(cors()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', routes); app.use('/users', users); app.use('/getTimer', timer); app.use('/actions', action); app.use('/playlist', playlist); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
mit
ndimatteo/7770-theme
assets/js/main.js
18414
var map; var info; var geocoder; var markers = {} var bounds = {} var dot; jQuery(function($) { geocoder = new google.maps.Geocoder(); info = new google.maps.InfoWindow({}) var location = new google.maps.LatLng(38.988469,-77.096562); var stylesArray = [ { "featureType": "all", "elementType": "all", "stylers": [ { "visibility": "on" } ] }, { "featureType": "all", "elementType": "labels.text.fill", "stylers": [ { "saturation": 36 }, { "color": "#333333" }, { "lightness": 40 } ] }, { "featureType": "all", "elementType": "labels.text.stroke", "stylers": [ { "visibility": "on" }, { "color": "#ffffff" }, { "lightness": 16 } ] }, { "featureType": "all", "elementType": "labels.icon", "stylers": [ { "visibility": "off" } ] }, { "featureType": "administrative", "elementType": "geometry.fill", "stylers": [ { "color": "#c0c0c0" }, { "lightness": 20 }, { "visibility": "off" } ] }, { "featureType": "administrative", "elementType": "geometry.stroke", "stylers": [ { "color": "#fefefe" }, { "lightness": 17 }, { "weight": 1.2 } ] }, { "featureType": "administrative", "elementType": "labels.icon", "stylers": [ { "visibility": "off" } ] }, { "featureType": "landscape", "elementType": "geometry", "stylers": [ { "color": "#f5f5f5" }, { "lightness": 20 } ] }, { "featureType": "poi", "elementType": "geometry", "stylers": [ { "color": "#e1e7e8" }, { "lightness": 21 } ] }, { "featureType": "poi", "elementType": "labels", "stylers": [ { "visibility": "off" }, { "hue": "#ff4e00" } ] }, { "featureType": "poi", "elementType": "labels.text", "stylers": [ { "color": "#e07a4d" }, { "weight": "0.01" } ] }, { "featureType": "poi", "elementType": "labels.icon", "stylers": [ { "hue": "#ff4e00" } ] }, { "featureType": "poi.park", "elementType": "geometry", "stylers": [ { "color": "#b9bfc8" }, { "lightness": 21 } ] }, { "featureType": "road.highway", "elementType": "geometry.fill", "stylers": [ { "color": "#ffffff" }, { "lightness": 17 } ] }, { "featureType": "road.highway", "elementType": "geometry.stroke", "stylers": [ { "color": "#ffffff" }, { "lightness": 29 }, { "weight": 0.2 } ] }, { "featureType": "road.arterial", "elementType": "geometry", "stylers": [ { "color": "#ffffff" }, { "lightness": 18 } ] }, { "featureType": "road.local", "elementType": "geometry", "stylers": [ { "color": "#ffffff" }, { "lightness": 16 } ] }, { "featureType": "transit", "elementType": "geometry", "stylers": [ { "lightness": 19 }, { "color": "#e07a4d" } ] }, { "featureType": "transit.station", "elementType": "geometry", "stylers": [ { "visibility": "on" } ] }, { "featureType": "transit.station", "elementType": "labels.icon", "stylers": [ { "hue": "#ff4e00" } ] }, { "featureType": "water", "elementType": "geometry", "stylers": [ { "color": "#4e5468" }, { "lightness": 17 } ] } ]; var myOptions = { center: location, zoom: 14, styles: stylesArray, disableDefaultUI: true, scrollwheel: false, mapTypeId: google.maps.MapTypeId.ROADMAP }; // var styledMap = new google.maps.StyledMapType(styles, {name: "Styled Map"}); bounds['all'] = new google.maps.LatLngBounds(); map = new google.maps.Map(document.getElementById('map'), myOptions); //Add a marker and modal box var logo = new google.maps.MarkerImage('/assets/img/icn.logo-marker.png', //Marker size null, //Origin null, //Anchor null, //Retina new google.maps.Size(60,70)); //place a custom marker var logoMarker = new google.maps.Marker({ position: location, map: map, icon: logo }); //add map custom map controls map.controls[google.maps.ControlPosition.BOTTOM_RIGHT].push(new ZoomPanControl(map)); //create elements function CreateElement(tagName, properties) { var elem = document.createElement(tagName); for (var prop in properties) { if (prop == "style") elem.style.cssText = properties[prop]; else if (prop == "class") elem.className = properties[prop]; else elem.setAttribute(prop, properties[prop]); } return elem; } function ZoomPanControl(map) { this.map = map var t = this var zoomPanContainer = CreateElement("div", { 'class':'map-controls' }) //Map Controls div = CreateElement("div", {'title': 'Zoom in', 'class':'zoom-in' }) icon = CreateElement("i", {'class':'fa fa-plus'}) div.appendChild(icon) google.maps.event.addDomListener(div, "click", function() { t.zoom(ZoomDirection.IN); }) zoomPanContainer.appendChild(div) div = CreateElement("div", {'title': 'Zoom out', 'class':'zoom-out' }) icon = CreateElement("i", {'class':'fa fa-minus'}) div.appendChild(icon) google.maps.event.addDomListener(div, "click", function() { t.zoom(ZoomDirection.OUT); }) zoomPanContainer.appendChild(div) return zoomPanContainer } ZoomPanControl.prototype.zoom = function(direction) { var zoom = this.map.getZoom(); if (direction == ZoomDirection.IN && zoom < 19) this.map.setZoom(zoom + 1); else if (direction == ZoomDirection.OUT && zoom > 1) this.map.setZoom(zoom - 1); } var ZoomDirection = { IN: 0, OUT: 1 } return; }); //setup filter controls $('#map-filter a').on('click', function(e) { e.preventDefault() $('#map-filter li').removeClass('active') $(this).parent().toggleClass('active') var path = $(this).attr('href') route(path) }) function route(path) { if (!path) return; var type = path; if (!type) type = 'all'; info.close(); for (t in markers) { $(markers[t]).each(function(i, m) { m.setMap(null); }); } if (type == 'all') { for (t in locations){ show_locations(t, true); bounds['all'].union(bounds[t]); } map.fitBounds(bounds['all']); $('#type-nav-all').addClass('selected').siblings().removeClass('selected'); $('#groups-display > .type').removeClass('selected'); $('#groups-display > .type ').hide().fadeIn(); } else { show_locations(type); $('#type-nav-'+type).addClass('selected').siblings().removeClass('selected'); $('#type-'+type).hide().addClass('selected').fadeIn().siblings().removeClass('selected').hide() } } function show_locations(type, no_clear) { var $ = jQuery; if (!locations[type] && type != 'all') return; if (!no_clear) no_clear = false; var last = $(map).data('last'); var iconType = '/assets/img/icn.map-marker-orange.png'; $(map).data('last', type); if (!markers[type]) { markers[type] = []; bounds[type] = new google.maps.LatLngBounds() if (type == 'restaurants') { iconType = '/assets/img/icn.map-marker-orange.png'; } else if (type == 'shops') { iconType = '/assets/img/icn.map-marker-orange.png'; } else if (type == 'culture') { iconType = '/assets/img/icn.map-marker-orange.png'; } else if (type == 'nightlife') { iconType = '/assets/img/icn.map-marker-orange.png'; } var iconImage = new google.maps.MarkerImage(iconType, null, null, null, new google.maps.Size(20,25)); $(locations[type]).each(function(i, location) { var marker = new google.maps.Marker({ map: map, icon: iconImage, position: new google.maps.LatLng(location['latlng']['lat'], location['latlng']['lng']) }); google.maps.event.addListener(marker, 'click', function() { info.setContent(make_info_html(type, location)); info.open(map, marker); }); $('#group-'+location['id']).click(function() { google.maps.event.trigger(marker, 'click'); }); markers[type].push(marker); bounds[type].extend(marker.getPosition()); }); } else { $(markers[type]).each(function(i, m) { m.setMap(map); }); } if (!no_clear) if (bounds[type]) map.fitBounds(bounds[type]); } function make_info_html(type, p) { console.log(p); return '<div id="infowindow">' + '<strong>'+p['name']+'</strong><br />'+ p['addr'] + '<br />' + '<a href="https://www.google.com/maps/dir//'+escape(p['addr_raw'])+'" target="_blank">Get Directions</a><br /><br />' + (p['phone'] ? 'Phone: '+p['phone'] + '<br />' : '') + (p['website'] ? '<a href="'+p['website'] +'">visit website</a><br />' : '') + (p['twitter'] ? '<a href="https://twitter.com/'+p['twitter'] +'">@'+p['twitter']+'</a><br />' : '') + '</div>'; } //floor plan functions function selectFloorType(type) { var activeType = type.attr('href').substring(1) //apply active class $('#floor-type li').removeClass('selected') type.parent().addClass('selected') //set floor level $('#floor-level li').removeClass('selected').addClass('disabled') $('#floor-level a[data-type~="'+activeType+'"]').parent().removeClass('disabled') //reset available plans $('#select-plan li').removeClass('selected').addClass('disabled') $('#floorplates img, #units img, #plans .plan').fadeOut(300, function() { $('#floor-plans .background').fadeIn(300) }) } function selectFloorLevel(level) { var activeType = $('#floor-type li.selected a').attr('href').substring(1) var activeLevel = level.attr('href').substring(1) //fade-out current level and fade-in activeLevel $('#floor-plans .background, #floorplates img, #units img, #plans .plan, #plans > div').fadeOut(300) $('#floorplates .'+activeLevel+', #units .'+activeLevel+' img[data-plan~="'+activeType+'"]').fadeIn(300) //apply active class $('#floor-level li').removeClass('selected') level.parent().addClass('selected') //set available plans $('#select-plan li').removeClass('selected').addClass('disabled') $('#select-plan a[data-plan~="'+activeLevel+'-'+activeType+'"]').parent().removeClass('disabled') } function selectFloorPlan(plan) { var activeType = $('#floor-type li.selected a').attr('href').substring(1) var activeLevel = $('#floor-level li.selected a').attr('href').substring(1) //apply active class $('#select-plan li').removeClass('selected') plan.parent().addClass('selected') if ($(window).width() < 768) { //slideup options for mobile $('.widget-options-wrapper').slideUp(800, 'easeInOutExpo') //show plan $('#plans .'+activeLevel+' .'+activeType+'-'+plan.attr('href').substring(1)).show() $('#plans .'+activeLevel).fadeIn(300) } else { $('#floorplates img:visible, #units img:visible, #plans .plan:visible, #plans > div:visible').fadeOut(300, function() { //show plan $('#plans .'+activeLevel+' .'+activeType+'-'+plan.attr('href').substring(1)).show() $('#plans .'+activeLevel).fadeIn(300) }); } // $('.debug.plan').text(plan.attr('href').substring(1)+' FROM '+activeLevel) } (function() { // Highlight current section while scrolling DOWN $('.section').waypoint(function(direction) { if (direction === 'down') { var $link = $('a[href="/' + this.id + '"]'); $('ul.nav.navbar-nav li').removeClass('active'); $link.parent().addClass('active'); } }, { offset: '50%' }); // Highlight current section while scrolling UP $('.section').waypoint(function(direction) { if (direction === 'up') { var $link = $('a[href="/' + this.id + '"]'); $('ul.nav.navbar-nav li').removeClass('active'); $link.parent().addClass('active'); } }, { offset: function() { // This is the calculation that would give you // "bottom of element hits middle of window" return $.waypoints('viewportHeight') / 2 - $(this).outerHeight(); } }); // header shrink $('#wrapper').waypoint(function(direction) { if(direction === 'up') { //do something $('#header').removeClass('shrink') } else if(direction === 'down') { //do something $('#header').addClass('shrink') } }, { offset: 85 }) // history.js $('ul.internal li a, .anchor-link').on('click', addressUpdate) function addressUpdate(ev) { ev.preventDefault() var $that = $(this) var separator = ' | ' var title = $(document).find('title').text() title = title.substring(title.indexOf(separator), title.length) //set title if($(this).hasClass('anchor-link')) { title = $(this).data('title') + title } else { title = $that.text() + title } //update url + title var href = $that.attr('href') History.pushState(null, title, href) //toggle nav for mobile if($('.toggle-btn').hasClass('open')) { $('.toggle-btn').trigger('click') } //scroll to section var scrollOffset = ($('.menu-toggle').is(':visible') ? 55 : 70) $('html, body').stop().animate({ scrollTop: ($('#' + href.replace('/', '')).offset().top - scrollOffset) }, 1200,'easeInOutExpo') } })(); $(document).ready(function() { route('all'); //backstretch if backgroundsize not possible if( !$('html.backgroundsize') ) { var backstretchImg = $('#background').css('background-image') backstretchImg = backstretchImg.replace('url(','').replace(')','').replace(/"/g, ''); $('#background').backstretch(backstretchImg) } //mobile menu $('.toggle-btn').on('click', function(e) { e.preventDefault $(this).toggleClass('open') $('#main-nav').slideToggle(400, 'easeInOutExpo') }) //features slider $('.slider').each(function() { var $that = $(this); $that.slick({ slide: '.slide', infinite: true, autoplay: false, arrows: false, dots: false, speed: 600, cssEase: 'cubic-bezier(0.86, 0, 0.07, 1)', slidesToShow: 1, slidesToScroll: 1 }) //captions $that.on('beforeChange', function(slide, slider) { $that.closest('.wrapper').find('.caption').animate({ opacity: 0 }, 200) }) $that.on('afterChange', function(slide, slider) { var caption = $('.slick-active img', this).attr('alt') if(caption) { $that.closest('.wrapper').find('.caption p').text(caption).parent().animate({ opacity: 1 }, 200) } $that.closest('.tab-pane').find('.slider-thumbs .slide').removeClass('active') $that.closest('.tab-pane').find('.slider-thumbs .slide').eq($that.slick('slickCurrentSlide')).addClass('active') }) }) //manual buttons $('.next').on('click', function() { $(this).parent().parent().slick('slickNext') }) $('.prev').on('click', function() { $(this).parent().parent().slick('slickPrev') }) //gallery thumbs $('.slider-thumbs .slide').on('click', function(e) { var slide = $(this).index() $(this).closest('.tab-pane').find('.slider').slick('slickGoTo', slide) }) $('.gallery-nav a').on('shown.bs.tab', function(e) { $('.slider').slick('setOption', null, null, true) }) //floor plans widget $('#floor-type a').on('click', function(e) { e.preventDefault() selectFloorType($(this)) }) $('#floor-level').on('click', 'li:not(.disabled) a', function(e) { e.preventDefault() selectFloorLevel($(this)) }) $('#select-plan').on('click', 'li:not(.disabled) a', function(e) { e.preventDefault() selectFloorPlan($(this)) }) //floor plans buttons $('.show-floorplans').on('click', function(e) { e.preventDefault() $('.floor-intro').fadeOut(300, function() { $('body').addClass('floorplans-open') $('.floor-widget').fadeIn(300) $('.close-floorplans').fadeIn(300) }) }) $('.close-floorplans').on('click', function(e) { e.preventDefault() $('.close-floorplans').fadeOut(300) $('.floor-widget').fadeOut(300, function() { $('body').removeClass('floorplans-open') $('.floor-intro').fadeIn(300) $('#floor-plans .background').fadeIn(300) //reset widget options $('.widget-options-wrapper').slideDown() $('#floorplates img, #units img, #plans .plan').hide() $('#floor-type li').removeClass('selected') $('#floor-level li, #select-plan li').removeClass('selected').addClass('disabled') }) }) $('.go-back').on('click', function(e) { e.preventDefault() $('#plans > div').fadeOut(300) $('#select-plan li').removeClass('selected') $('.widget-options-wrapper').slideDown(800, 'easeInOutExpo', function() { $('#plans .plan').hide() }) }) }) // on page load $(window).load(function() { // scroll to section var path = document.location.pathname path = path.substring(path.lastIndexOf('/') + 1, path.length) if ($('#' + path).length) { var scrollOffset = ($('.menu-toggle').is(':visible') ? 55 : 70) $('html, body').stop().animate({ scrollTop: ($('#' + path).offset().top - scrollOffset) }, 1200,'easeInOutExpo') } })
mit
WebSpanner/track
tests/TestCase.php
924
<?php namespace Tests; use Config; use Illuminate\Foundation\Testing\TestCase as BaseTestCase; abstract class TestCase extends BaseTestCase { /** * The base URL to use while testing the application. * * @var string */ protected $baseUrl = 'http://localhost'; /** * Creates the application. * * @return \Illuminate\Foundation\Application */ public function createApplication() { $app = require __DIR__.'/../bootstrap/app.php'; $app->make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap(); return $app; } protected function actingAsUser() { $user = factory(\App\User::class)->create(); $this->actingAs($user); return $user; } protected function usingTestDisplayTimeZone($timezone = null) { Config::set('app.display_timezone', $timezone ?? 'Australia/Sydney'); } }
mit
iliyaST/TelerikAcademy
C#2/6-Strings-And-Text-Processing/05.ParseTags/Program.cs
835
using System; using System.Text; class ParseTags { static void Main() { string text = Console.ReadLine(); StringBuilder newText = new StringBuilder(); bool isOpened = false; for (int i = 0; i < text.Length; i++) { if (text[i] == '<') { while (text[i] != '>') { i++; } i++; while (text[i] != '<') { newText.Append(text[i].ToString().ToUpper()); i++; } while (text[i] != '>') { i++; } continue; } newText.Append(text[i]); } Console.WriteLine(newText); } }
mit
all-trees/tree-domain
src/main/java/nl/dvberkel/tree/Tree.java
121
package nl.dvberkel.tree; import static java.lang.Math.max; public interface Tree { int size(); int depth(); }
mit
matita/barscan
js/app.min.js
237142
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ /** * CallBacks: * __________________________________________________________________________________ * All the callback function should have one parameter: * function(result){}; * And the result parameter will contain an array of objects that look like BarcodeReader. * result = [{Format: the barcode type, Value: the value of the barcode}]; * __________________________________________________________________________________ * * You can use either the set functions or just access the properties directly to set callback or * other properties. Just always remember to call Init() before starting to decode something never mess * around with the SupportedFormats property. * */ var EXIF = require('./exif'); var decoderWorkerBlobString = require('./DecoderWorker'); BarcodeReader = { Config: { // Set to false if the decoder should look for one barcode and then stop. Increases performance. Multiple: true, // The formats that the decoder will look for. DecodeFormats: ["Code128", "Code93", "Code39", "EAN-13", "2Of5", "Inter2Of5", "Codabar"], // ForceUnique just must makes sure that the callback function isn't repeatedly called // with the same barcode. Especially in the case of a video stream. ForceUnique: true, // Set to true if information about the localization should be recieved from the worker. LocalizationFeedback: false, // Set to true if checking orientation of the image should be skipped. // Checking orientation takes a bit of time for larger images, so if // you are sure that the image orientation is 1 you should skip it. SkipOrientation: false }, SupportedFormats: ["Code128", "Code93", "Code39", "EAN-13", "2Of5", "Inter2Of5", "Codabar"], // Don't touch. ScanCanvas: null, // Don't touch the canvas either. ScanContext: null, SquashCanvas: document.createElement("canvas"), ImageCallback: null, // Callback for the decoding of an image. StreamCallback: null, // Callback for the decoding of a video. LocalizationCallback: null, // Callback for localization. Stream: null, // The actual video. DecodeStreamActive: false, // Will be set to false when StopStreamDecode() is called. Decoded: [], // Used to enfore the ForceUnique property. DecoderWorker: new Worker( URL.createObjectURL(new Blob([decoderWorkerBlobString], {type: "application/javascript"}) ) ), OrientationCallback: null, // Always call the Init(). Init: function() { BarcodeReader.ScanCanvas = BarcodeReader.FixCanvas(document.createElement("canvas")); BarcodeReader.ScanCanvas.width = 640; BarcodeReader.ScanCanvas.height = 480; BarcodeReader.ScanContext = BarcodeReader.ScanCanvas.getContext("2d"); }, // Value should be true or false. SetRotationSkip: function(value) { BarcodeReader.Config.SkipOrientation = value; }, // Sets the callback function for the image decoding. SetImageCallback: function(callBack) { BarcodeReader.ImageCallback = callBack; }, // Sets the callback function for the video decoding. SetStreamCallback: function(callBack) { BarcodeReader.StreamCallback = callBack; }, // Sets callback for localization, the callback function should take one argument. // This will be an array with objects with format. // {x, y, width, height} // This represents a localization rectangle. // The rectangle comes from a 320, 240 area i.e the search canvas. SetLocalizationCallback: function(callBack) { BarcodeReader.LocalizationCallback = callBack; BarcodeReader.Config.LocalizationFeedback = true; }, // Set to true if LocalizationCallback is set and you would like to // receive the feedback or false if SwitchLocalizationFeedback: function(bool) { BarcodeReader.Config.LocalizationFeedback = bool; }, // Switches for changing the Multiple property. DecodeSingleBarcode: function() { BarcodeReader.Config.Multiple = false; }, DecodeMultiple: function() { BarcodeReader.Config.Multiple = true; }, // Sets the formats to decode, formats should be an array of a subset of the supported formats. SetDecodeFormats: function(formats) { BarcodeReader.Config.DecodeFormats = []; for (var i = 0; i < formats.length; i++) { if (BarcodeReader.SupportedFormats.indexOf(formats[i]) !== -1) { BarcodeReader.Config.DecodeFormats.push(formats[i]); } } if (BarcodeReader.Config.DecodeFormats.length === 0) { BarcodeReader.Config.DecodeFormats = BarcodeReader.SupportedFormats.slice(); } }, // Removes a list of formats from the formats to decode. SkipFormats: function(formats) { for (var i = 0; i < formats.length; i++) { var index = BarcodeReader.Config.DecodeFormats.indexOf(formats[i]); if (index >= 0) { BarcodeReader.Config.DecodeFormats.splice(index, 1); } } }, // Adds a list of formats to the formats to decode. AddFormats: function(formats) { for (var i = 0; i < formats.length; i++) { if (BarcodeReader.SupportedFormats.indexOf(formats[i]) !== -1) { if (BarcodeReader.Config.DecodeFormats.indexOf(formats[i]) === -1) { BarcodeReader.Config.DecodeFormats.push(formats[i]); } } } }, // The callback function for image decoding used internally by BarcodeReader. BarcodeReaderImageCallback: function(e) { if (e.data.success === "localization") { if (BarcodeReader.Config.LocalizationFeedback) { BarcodeReader.LocalizationCallback(e.data.result); } return; } if (e.data.success === "orientationData") { BarcodeReader.OrientationCallback(e.data.result); return; } var filteredData = []; for (var i = 0; i < e.data.result.length; i++) { if (BarcodeReader.Decoded.indexOf(e.data.result[i].Value) === -1 || BarcodeReader.Config.ForceUnique === false) { filteredData.push(e.data.result[i]); if (BarcodeReader.Config.ForceUnique) BarcodeReader.Decoded.push(e.data.result[i].Value); } } BarcodeReader.ImageCallback(filteredData); BarcodeReader.Decoded = []; }, // The callback function for stream decoding used internally by BarcodeReader. BarcodeReaderStreamCallback: function(e) { if (e.data.success === "localization") { if (BarcodeReader.Config.LocalizationFeedback) { BarcodeReader.LocalizationCallback(e.data.result); } return; } if (e.data.success && BarcodeReader.DecodeStreamActive) { var filteredData = []; for (var i = 0; i < e.data.result.length; i++) { if (BarcodeReader.Decoded.indexOf(e.data.result[i].Value) === -1 || BarcodeReader.ForceUnique === false) { filteredData.push(e.data.result[i]); if (BarcodeReader.ForceUnique) BarcodeReader.Decoded.push(e.data.result[i].Value); } } if (filteredData.length > 0) { BarcodeReader.StreamCallback(filteredData); } } if (BarcodeReader.DecodeStreamActive) { BarcodeReader.ScanContext.drawImage(BarcodeReader.Stream, 0, 0, BarcodeReader.ScanCanvas.width, BarcodeReader.ScanCanvas.height); BarcodeReader.DecoderWorker.postMessage({ scan: BarcodeReader.ScanContext.getImageData(0, 0, BarcodeReader.ScanCanvas.width, BarcodeReader.ScanCanvas.height).data, scanWidth: BarcodeReader.ScanCanvas.width, scanHeight: BarcodeReader.ScanCanvas.height, multiple: BarcodeReader.Config.Multiple, decodeFormats: BarcodeReader.Config.DecodeFormats, cmd: "normal", rotation: 1, }); } if (!BarcodeReader.DecodeStreamActive) { BarcodeReader.Decoded = []; } }, // The image decoding function, image is a data source for an image or an image element. DecodeImage: function(image) { var img = new Image(); if (image instanceof Image || image instanceof HTMLImageElement) { image.exifdata = false; if (image.complete) { if (BarcodeReader.Config.SkipOrientation) { BarcodeReader.BarcodeReaderDecodeImage(image, 1, ""); } else { EXIF.getData(image, function(exifImage) { var orientation = EXIF.getTag(exifImage, "Orientation"); var sceneType = EXIF.getTag(exifImage, "SceneCaptureType"); if (typeof orientation !== 'number') orientation = 1; BarcodeReader.BarcodeReaderDecodeImage(exifImage, orientation, sceneType); }); } } else { img.onload = function() { if (BarcodeReader.Config.SkipOrientation) { BarcodeReader.BarcodeReaderDecodeImage(img, 1, ""); } else { EXIF.getData(this, function(exifImage) { var orientation = EXIF.getTag(exifImage, "Orientation"); var sceneType = EXIF.getTag(exifImage, "SceneCaptureType"); if (typeof orientation !== 'number') orientation = 1; BarcodeReader.BarcodeReaderDecodeImage(exifImage, orientation, sceneType); }); } }; img.src = image.src; } } else { img.onload = function() { if (BarcodeReader.Config.SkipOrientation) { BarcodeReader.BarcodeReaderDecodeImage(img, 1, ""); } else { EXIF.getData(this, function(exifImage) { var orientation = EXIF.getTag(exifImage, "Orientation"); var sceneType = EXIF.getTag(exifImage, "SceneCaptureType"); if (typeof orientation !== 'number') orientation = 1; BarcodeReader.BarcodeReaderDecodeImage(exifImage, orientation, sceneType); }); } }; img.src = image; } }, // Starts the decoding of a stream, the stream is a video not a blob i.e it's an element. DecodeStream: function(stream) { BarcodeReader.Stream = stream; BarcodeReader.DecodeStreamActive = true; BarcodeReader.DecoderWorker.onmessage = BarcodeReader.BarcodeReaderStreamCallback; BarcodeReader.ScanContext.drawImage(stream, 0, 0, BarcodeReader.ScanCanvas.width, BarcodeReader.ScanCanvas.height); BarcodeReader.DecoderWorker.postMessage({ scan: BarcodeReader.ScanContext.getImageData(0, 0, BarcodeReader.ScanCanvas.width, BarcodeReader.ScanCanvas.height).data, scanWidth: BarcodeReader.ScanCanvas.width, scanHeight: BarcodeReader.ScanCanvas.height, multiple: BarcodeReader.Config.Multiple, decodeFormats: BarcodeReader.Config.DecodeFormats, cmd: "normal", rotation: 1, }); }, // Stops the decoding of a stream. StopStreamDecode: function() { BarcodeReader.DecodeStreamActive = false; BarcodeReader.Decoded = []; }, BarcodeReaderDecodeImage: function(image, orientation, sceneCaptureType) { if (orientation === 8 || orientation === 6) { if (sceneCaptureType === "Landscape" && image.width > image.height) { orientation = 1; BarcodeReader.ScanCanvas.width = 640; BarcodeReader.ScanCanvas.height = 480; } else { BarcodeReader.ScanCanvas.width = 480; BarcodeReader.ScanCanvas.height = 640; } } else { BarcodeReader.ScanCanvas.width = 640; BarcodeReader.ScanCanvas.height = 480; } BarcodeReader.DecoderWorker.onmessage = BarcodeReader.BarcodeReaderImageCallback; BarcodeReader.ScanContext.drawImage(image, 0, 0, BarcodeReader.ScanCanvas.width, BarcodeReader.ScanCanvas.height); BarcodeReader.Orientation = orientation; BarcodeReader.DecoderWorker.postMessage({ scan: BarcodeReader.ScanContext.getImageData(0, 0, BarcodeReader.ScanCanvas.width, BarcodeReader.ScanCanvas.height).data, scanWidth: BarcodeReader.ScanCanvas.width, scanHeight: BarcodeReader.ScanCanvas.height, multiple: BarcodeReader.Config.Multiple, decodeFormats: BarcodeReader.Config.DecodeFormats, cmd: "normal", rotation: orientation, postOrientation: BarcodeReader.PostOrientation }); }, DetectVerticalSquash: function(img) { var ih = img.naturalHeight; var canvas = BarcodeReader.SquashCanvas; var alpha; var data; canvas.width = 1; canvas.height = ih; var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); try { data = ctx.getImageData(0, 0, 1, ih).data; } catch (err) { console.log("Cannot check verticalSquash: CORS?"); return 1; } var sy = 0; var ey = ih; var py = ih; while (py > sy) { alpha = data[(py - 1) * 4 + 3]; if (alpha === 0) { ey = py; } else { sy = py; } py = (ey + sy) >> 1; } var ratio = (py / ih); return (ratio === 0) ? 1 : ratio; }, FixCanvas: function(canvas) { var ctx = canvas.getContext('2d'); var drawImage = ctx.drawImage; ctx.drawImage = function(img, sx, sy, sw, sh, dx, dy, dw, dh) { var vertSquashRatio = 1; if (!!img && img.nodeName === 'IMG') { vertSquashRatio = BarcodeReader.DetectVerticalSquash(img); // sw || (sw = img.naturalWidth); // sh || (sh = img.naturalHeight); } if (arguments.length === 9) drawImage.call(ctx, img, sx, sy, sw, sh, dx, dy, dw, dh / vertSquashRatio); else if (typeof sw !== 'undefined') drawImage.call(ctx, img, sx, sy, sw, sh / vertSquashRatio); else drawImage.call(ctx, img, sx, sy); }; return canvas; } }; module.exports = BarcodeReader; },{"./DecoderWorker":2,"./exif":3}],2:[function(require,module,exports){ /* -------------------------------------------------- Javascript Only Barcode_Reader (BarcodeReader) V1.6 by Eddie Larsson <https://github.com/EddieLa/BarcodeReader> This software is provided under the MIT license, http://opensource.org/licenses/MIT. All use of this software must include this text, including the reference to the creator of the original source code. The originator accepts no responsibility of any kind pertaining to use of this software. Copyright (c) 2013 Eddie Larsson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------ */ var decoderWorkerBlob = function decoderWorkerBlob(){ function Rotate(data, width, height, rotation) { var newData = []; var x, y; switch (rotation) { case 90: for (x = 0; x < width * 4; x += 4) { for (y = width * 4 * (height - 1); y >= 0; y -= width * 4) { newData.push(data[x + y]); newData.push(data[x + y + 1]); newData.push(data[x + y + 2]); newData.push(data[x + y + 3]); } } break; case -90: for (x = width * 4 - 4; x >= 0; x -= 4) { for (y = 0; y < data.length; y += width * 4) { newData.push(data[x + y]); newData.push(data[x + y + 1]); newData.push(data[x + y + 2]); newData.push(data[x + y + 3]); } } break; case 180: for (y = width * 4 * (height - 1); y >= 0; y -= width * 4) { for (x = width * 4 - 4; x >= 0; x -= 4) { newData.push(data[x + y]); newData.push(data[x + y + 1]); newData.push(data[x + y + 2]); newData.push(data[x + y + 3]); } } } return new Uint8ClampedArray(newData); } function BoxFilter(data, width, radius) { var elements = []; var sum = []; var val; var x, y, i; for (x = 0; x < width; x++) { elements.push([]); sum.push(0); for (y = 0; y < (radius + 1) * width; y += width) { elements[elements.length - 1].push(data[x + y]); sum[sum.length - 1] = sum[sum.length - 1] + data[x + y]; } } var newData = []; for (y = 0; y < data.length; y += width) { for (x = 0; x < width; x++) { var newVal = 0; var length = 0; for (i = x; i >= 0; i--) { newVal += sum[i]; length++; if (length === radius + 1) break; } var tempLength = 0; for (i = x + 1; i < width; i++) { newVal += sum[i]; length++; tempLength++; if (tempLength === radius) break; } length *= elements[0].length; newVal /= length; newData.push(newVal); } if (y - radius * width >= 0) { for (i = 0; i < elements.length; i++) { val = elements[i].shift(); sum[i] = sum[i] - val; } } if (y + (radius + 1) * width < data.length) { for (i = 0; i < elements.length; i++) { val = data[i + y + (radius + 1) * width]; elements[i].push(val); sum[i] = sum[i] + val; } } } return newData; } function Scale(data, width, height) { var newData = []; var x, y; for (y = 0; y < data.length; y += width * 8) { for (x = 0; x < width * 4; x += 8) { var r = (data[y + x] + data[y + x + 4] + data[y + width * 4 + x] + data[y + width * 4 + x + 4]) / 4; newData.push(r); var g = (data[y + x + 1] + data[y + x + 4 + 1] + data[y + width * 4 + x + 1] + data[y + width * 4 + x + 4 + 1]) / 4; newData.push(g); var b = (data[y + x + 2] + data[y + x + 4 + 2] + data[y + width * 4 + x + 2] + data[y + width * 4 + x + 4 + 2]) / 4; newData.push(b); newData.push(255); } } return new Uint8ClampedArray(newData); } function IntensityGradient(data, width) { var newData = []; var max = Number.MIN_VALUE; var min = Number.MAX_VALUE; var x, y, i; for (y = 0; y < data.length; y += width * 4) { for (x = 0; x < width * 4; x += 4) { var horizontalDiff = 0; var verticalDiff = 0; for (i = 1; i < 2; i++) { if (x + i * 4 < width * 4) { horizontalDiff = horizontalDiff + Math.abs(data[y + x] - data[y + x + i * 4]); } if (y + width * 4 * i < data.length) { verticalDiff += verticalDiff + Math.abs(data[y + x] - data[y + x + width * 4 * i]); } } var diff = horizontalDiff - verticalDiff; max = diff > max ? diff : max; min = diff < min ? diff : min; newData.push(diff); } } if (min < 0) { for (i = 0; i < newData.length; i++) { newData[i] = newData[i] - min; } min = 0; } return newData; } function greyScale(data) { var i; for (i = 0; i < data.length; i += 4) { var max = 0; var min = 255; max = data[i] > max ? data[i] : max; max = data[i + 1] > max ? data[i + 1] : max; max = data[i + 2] > max ? data[i + 2] : max; min = data[i] < min ? data[i] : min; min = data[i + 1] < min ? data[i + 1] : min; min = data[i + 2] < min ? data[i + 2] : min; data[i] = data[i + 1] = data[i + 2] = (max + min) / 2; } } function histogram(data) { var i; var hist = []; for (i = 0; i < 256; i++) { hist[i] = 0; } for (i = 0; i < data.length; i += 4) { hist[data[i]] = hist[data[i]] + 1; } return hist; } function otsu(histogram, total) { var i; var sum = 0; for (i = 1; i < histogram.length; ++i) sum += i * histogram[i]; var sumB = 0; var wB = 0; var wF = 0; var mB; var mF; var max = 0.0; var between = 0.0; var threshold1 = 0.0; var threshold2 = 0.0; for (i = 0; i < histogram.length; ++i) { wB += histogram[i]; if (wB === 0) continue; wF = total - wB; if (wF === 0) break; sumB += i * histogram[i]; mB = sumB / wB; mF = (sum - sumB) / wF; between = wB * wF * Math.pow(mB - mF, 2); if (between >= max) { threshold1 = i; if (between > max) { threshold2 = i; } max = between; } } return (threshold1 + threshold2) / 2.0; } function CreateImageData() { Image.data = new Uint8ClampedArray(Image.width * Image.height * 4); var Converter; var x, y; for (y = 0; y < Image.height; y++) { for (x = 0; x < Image.width; x++) { Converter = y * 4 * Image.width; Image.data[Converter + x * 4] = Image.table[x][y][0]; Image.data[Converter + x * 4 + 1] = Image.table[x][y][1]; Image.data[Converter + x * 4 + 2] = Image.table[x][y][2]; Image.data[Converter + x * 4 + 3] = Image.table[x][y][3]; } } } function CreateScanImageData() { ScanImage.data = new Uint8ClampedArray(ScanImage.width * ScanImage.height * 4); var Converter; var x, y; for (y = 0; y < ScanImage.height; y++) { for (x = 0; x < ScanImage.width; x++) { Converter = y * 4 * ScanImage.width; ScanImage.data[Converter + x * 4] = ScanImage.table[x][y][0]; ScanImage.data[Converter + x * 4 + 1] = ScanImage.table[x][y][1]; ScanImage.data[Converter + x * 4 + 2] = ScanImage.table[x][y][2]; ScanImage.data[Converter + x * 4 + 3] = ScanImage.table[x][y][3]; } } } function CreateTable() { Image.table = []; var tempArray = []; var i, j; for (i = 0; i < Image.width * 4; i += 4) { tempArray = []; for (j = i; j < Image.data.length; j += Image.width * 4) { tempArray.push([Image.data[j], Image.data[j + 1], Image.data[j + 2], Image.data[j + 3]]); } Image.table.push(tempArray); } } function CreateScanTable() { ScanImage.table = []; var tempArray = []; var i, j; for (i = 0; i < ScanImage.width * 4; i += 4) { tempArray = []; for (j = i; j < ScanImage.data.length; j += ScanImage.width * 4) { tempArray.push([ScanImage.data[j], ScanImage.data[j + 1], ScanImage.data[j + 2], ScanImage.data[j + 3]]); } ScanImage.table.push(tempArray); } } function EnlargeTable(h, w) { var TempArray = []; var x, y, i; for (x = 0; x < Image.width; x++) { TempArray = []; for (y = 0; y < Image.height; y++) { for (i = 0; i < h; i++) { TempArray.push(Image.table[x][y]); } } Image.table[x] = TempArray.slice(); } TempArray = Image.table.slice(); for (x = 0; x < Image.width; x++) { for (i = 0; i < w; i++) { Image.table[x * w + i] = TempArray[x].slice(); } } Image.width = Image.table.length; Image.height = Image.table[0].length; CreateImageData(); } function ScaleHeight(scale) { var tempArray = []; var avrgRed = 0; var avrgGreen = 0; var avrgBlue = 0; var i, j, k; for (i = 0; i < Image.height - scale; i += scale) { for (j = 0; j < Image.width; j++) { avrgRed = 0; avrgGreen = 0; avrgBlue = 0; for (k = i; k < i + scale; k++) { avrgRed += Image.table[j][k][0]; avrgGreen += Image.table[j][k][1]; avrgBlue += Image.table[j][k][2]; } tempArray.push(avrgRed / scale); tempArray.push(avrgGreen / scale); tempArray.push(avrgBlue / scale); tempArray.push(255); } } return new Uint8ClampedArray(tempArray); } function Intersects(rectOne, rectTwo) { return (rectOne[0][0] <= rectTwo[0][1] && rectTwo[0][0] <= rectOne[0][1] && rectOne[1][0] <= rectTwo[1][1] && rectTwo[1][0] <= rectOne[1][1]); } function maxLocalization(max, maxPos, data) { var originalMax = max; var rects = []; var x, y, i; do { var startX = maxPos % Image.width; var startY = (maxPos - startX) / Image.width; var minY = 0; var maxY = Image.height; var minX = 0; var maxX = Image.width - 1; for (y = startY; y < Image.height - 1; y++) { if (Image.table[startX][y + 1][0] === 0) { maxY = y; break; } } for (y = startY; y > 0; y--) { if (Image.table[startX][y - 1][0] === 0) { minY = y; break; } } for (x = startX; x < Image.width - 1; x++) { if (Image.table[x + 1][startY][0] === 0) { maxX = x; break; } } for (x = startX; x > 0; x--) { if (Image.table[x - 1][startY][0] === 0) { minX = x; break; } } for (y = minY * Image.width; y <= maxY * Image.width; y += Image.width) { for (x = minX; x <= maxX; x++) { data[y + x] = 0; } } var newRect = [ [minX, maxX], [minY, maxY] ]; for (i = 0; i < rects.length; i++) { if (Intersects(newRect, rects[i])) { if (rects[i][0][1] - rects[i][0][0] > newRect[0][1] - newRect[0][0]) { rects[i][0][0] = rects[i][0][0] < newRect[0][0] ? rects[i][0][0] : newRect[0][0]; rects[i][0][1] = rects[i][0][1] > newRect[0][1] ? rects[i][0][1] : newRect[0][1]; newRect = []; break; } else { rects[i][0][0] = rects[i][0][0] < newRect[0][0] ? rects[i][0][0] : newRect[0][0]; rects[i][0][1] = rects[i][0][1] > newRect[0][1] ? rects[i][0][1] : newRect[0][1]; rects[i][1][0] = newRect[1][0]; rects[i][1][1] = newRect[1][1]; newRect = []; break; } } } if (newRect.length > 0) { rects.push(newRect); } max = 0; maxPos = 0; var newMaxPos = 0; for (i = 0; i < data.length; i++) { if (data[i] > max) { max = data[i]; maxPos = i; } } } while (max > originalMax * 0.70); return rects; } function ImgProcessing() { greyScale(Image.data); var newData = IntensityGradient(Image.data, Image.width); newData = BoxFilter(newData, Image.width, 15); var min = newData[0]; var i, x, y; for (i = 1; i < newData.length; i++) { min = min > newData[i] ? newData[i] : min; } var max = 0; var maxPos = 0; var avrgLight = 0; for (i = 0; i < newData.length; i++) { newData[i] = Math.round((newData[i] - min)); avrgLight += newData[i]; if (max < newData[i]) { max = newData[i]; maxPos = i; } } avrgLight /= newData.length; if (avrgLight < 15) { newData = BoxFilter(newData, Image.width, 8); min = newData[0]; for (i = 1; i < newData.length; i++) { min = min > newData[i] ? newData[i] : min; } max = 0; maxPos = 0; for (i = 0; i < newData.length; i++) { newData[i] = Math.round((newData[i] - min)); if (max < newData[i]) { max = newData[i]; maxPos = i; } } } var hist = []; for (i = 0; i <= max; i++) { hist[i] = 0; } for (i = 0; i < newData.length; i++) { hist[newData[i]] = hist[newData[i]] + 1; } var thresh = otsu(hist, newData.length); for (i = 0; i < newData.length; i++) { if (newData[i] < thresh) { Image.data[i * 4] = Image.data[i * 4 + 1] = Image.data[i * 4 + 2] = 0; } else { Image.data[i * 4] = Image.data[i * 4 + 1] = Image.data[i * 4 + 2] = 255; } } CreateTable(); var rects = maxLocalization(max, maxPos, newData); var feedBack = []; for (i = 0; i < rects.length; i++) { feedBack.push({ x: rects[i][0][0], y: rects[i][1][0], width: rects[i][0][1] - rects[i][0][0], height: rects[i][1][1] - rects[i][1][0] }); } if (feedBack.length > 0) postMessage({ result: feedBack, success: "localization" }); allTables = []; for (i = 0; i < rects.length; i++) { var newTable = []; for (x = rects[i][0][0] * 2; x < rects[i][0][1] * 2; x++) { var tempArray = []; for (y = rects[i][1][0] * 2; y < rects[i][1][1] * 2; y++) { tempArray.push([ScanImage.table[x][y][0], ScanImage.table[x][y][1], ScanImage.table[x][y][2], 255]); } newTable.push(tempArray); } if (newTable.length < 1) continue; Image.table = newTable; Image.width = newTable.length; Image.height = newTable[0].length; CreateImageData(); allTables.push({ table: newTable, data: new Uint8ClampedArray(Image.data), width: Image.width, height: Image.height }); } } function showImage(data, width, height) { postMessage({ result: data, width: width, height: height, success: "image" }); } function Main() { ImgProcessing(); var allResults = []; var tempObj; var tempData; var hist; var val; var thresh; var start; var end; var z, i; for (z = 0; z < allTables.length; z++) { Image = allTables[z]; var scaled = ScaleHeight(30); var variationData; var incrmt = 0; var format = ""; var first = true; var eanStatistics = {}; var eanOrder = []; Selection = false; do { tempData = scaled.subarray(incrmt, incrmt + Image.width * 4); hist = []; for (i = 0; i < 256; i++) { hist[i] = 0; } for (i = 0; i < tempData.length; i += 4) { val = Math.round((tempData[i] + tempData[i + 1] + tempData[i + 2]) / 3); hist[val] = hist[val] + 1; } thresh = otsu(hist, tempData.length / 4); start = thresh < 41 ? 1 : thresh - 40; end = thresh > 254 - 40 ? 254 : thresh + 40; variationData = yStraighten(tempData, start, end); Selection = BinaryString(variationData); if (Selection.string) { format = Selection.format; tempObj = Selection; Selection = Selection.string; if (format === "EAN-13") { if (typeof eanStatistics[Selection] === 'undefined') { eanStatistics[Selection] = { count: 1, correction: tempObj.correction }; eanOrder.push(Selection); } else { eanStatistics[Selection].count = eanStatistics[Selection].count + 1; eanStatistics[Selection].correction = eanStatistics[Selection].correction + tempObj.correction; } Selection = false; } } else { Selection = false; } incrmt += Image.width * 4; } while (!Selection && incrmt < scaled.length); if (Selection && format !== "EAN-13") allResults.push({ Format: format, Value: Selection }); if (format === "EAN-13") Selection = false; if (!Selection) { EnlargeTable(4, 2); incrmt = 0; scaled = ScaleHeight(20); do { tempData = scaled.subarray(incrmt, incrmt + Image.width * 4); hist = []; for (i = 0; i < 256; i++) { hist[i] = 0; } for (i = 0; i < tempData.length; i += 4) { val = Math.round((tempData[i] + tempData[i + 1] + tempData[i + 2]) / 3); hist[val] = hist[val] + 1; } thresh = otsu(hist, tempData.length / 4); start = thresh < 40 ? 0 : thresh - 40; end = thresh > 255 - 40 ? 255 : thresh + 40; variationData = yStraighten(tempData, start, end); Selection = BinaryString(variationData); if (Selection.string) { format = Selection.format; tempObj = Selection; Selection = Selection.string; if (format === "EAN-13") { if (typeof eanStatistics[Selection] === 'undefined') { eanStatistics[Selection] = { count: 1, correction: tempObj.correction }; eanOrder.push(Selection); } else { eanStatistics[Selection].count = eanStatistics[Selection].count + 1; eanStatistics[Selection].correction = eanStatistics[Selection].correction + tempObj.correction; } Selection = false; } } else { Selection = false; } incrmt += Image.width * 4; } while (!Selection && incrmt < scaled.length); if (format === "EAN-13") { var points = {}; for (var key in eanStatistics) { eanStatistics[key].correction = eanStatistics[key].correction / eanStatistics[key].count; var pointTemp = eanStatistics[key].correction; pointTemp -= eanStatistics[key].count; pointTemp += eanOrder.indexOf(key); points[key] = pointTemp; } var minPoints = Number.POSITIVE_INFINITY; var tempString = ""; for (var point in points) { if (points[point] < minPoints) { minPoints = points[point]; tempString = key; } } if (minPoints < 11) { Selection = tempString; } else { Selection = false; } } if (Selection) allResults.push({ Format: format, Value: Selection }); } if (allResults.length > 0 && !Multiple) break; } return allResults; } function yStraighten(img, start, end) { var average = 0; var threshold; var newImg = new Uint8ClampedArray(Image.width * (end - start + 1) * 4); var i, j; for (i = 0; i < newImg.length; i++) { newImg[i] = 255; } for (i = 0; i < Image.width * 4; i += 4) { threshold = end; average = (img[i] + img[i + 1] + img[i + 2]) / 3; if (i < Image.width * 4 - 4) { average += (img[i + 4] + img[i + 5] + img[i + 6]) / 3; average /= 2; } for (j = i; j < newImg.length; j += Image.width * 4) { if (average < threshold) { newImg[j] = newImg[j + 1] = newImg[j + 2] = 0; } threshold--; } } return newImg; } function CheckEan13(values, middle) { if (middle) { if (values.length !== 5) return false; } else { if (values.length !== 3) return false; } var avrg = 0; var i; for (i = 0; i < values.length; i++) { avrg += values[i]; } avrg /= values.length; for (i = 0; i < values.length; i++) { if (values[i] / avrg < 0.5 || values[i] / avrg > 1.5) return false; } return true; } function TwoOfFiveStartEnd(values, start) { if (values.length < 5 || values.length > 6) return false; var maximum = 0; var TwoOfFiveMax = [0, 0]; var u; for (u = 0; u < values.length; u++) { if (values[u] > maximum) { maximum = values[u]; TwoOfFiveMax[0] = u; } } maximum = 0; for (u = 0; u < values.length; u++) { if (u === TwoOfFiveMax[0]) continue; if (values[u] > maximum) { maximum = values[u]; TwoOfFiveMax[1] = u; } } if (start) { return TwoOfFiveMax[0] + TwoOfFiveMax[1] === 2; } else { return TwoOfFiveMax[0] + TwoOfFiveMax[1] === 2; } } function CheckInterleaved(values, start) { var average = 0; var i; for (i = 0; i < values.length; i++) { average += values[i]; } average /= 4; if (start) { if (values.length !== 4) return false; for (i = 0; i < values.length; i++) { if (values[i] / average < 0.5 || values[i] / average > 1.5) return false; } return true; } else { if (values.length !== 3) return false; var max = 0; var pos; for (i = 0; i < values.length; i++) { if (values[i] > max) { max = values[i]; pos = i; } } if (pos !== 0) return false; if (values[0] / average < 1.5 || values[0] / average > 2.5) return false; for (i = 1; i < values.length; i++) { if (values[i] / average < 0.5 || values[i] / average > 1.5) return false; } return true; } } function BinaryConfiguration(binaryString, type) { var result = []; var binTemp = []; var count = 0; var bars; var len; var totalBars; var i; if (type === "Code128" || type === "Code93") { totalBars = 6; len = binaryString[0]; if (type === "Code128") len /= 2; for (i = 0; i < binaryString.length; i++) { if (binaryString[i] > len * 6) { binaryString.splice(i, binaryString.length); break; } } do { if (binaryString.length === 7 && type === "Code128") { result.push(binaryString.splice(0, binaryString.length)); } else { result.push(binaryString.splice(0, totalBars)); } if (type === "Code93" && binaryString.length < 6) binaryString.splice(0, totalBars); } while (binaryString.length > 0); } if (type === "Code39") { totalBars = 9; len = binaryString[0]; for (i = 0; i < binaryString.length; i++) { if (binaryString[i] > len * 5) { binaryString.splice(i, binaryString.length); break; } } do { result.push(binaryString.splice(0, totalBars)); binaryString.splice(0, 1); } while (binaryString.length > 0); } if (type === "EAN-13") { totalBars = 4; len = binaryString[0]; var secureCount = 0; for (i = 0; i < binaryString.length; i++) { if (binaryString[i] > len * 6) { binaryString.splice(i, binaryString.length); break; } } if (CheckEan13(binaryString.splice(0, 3), false)) secureCount++; count = 0; do { result.push(binaryString.splice(0, totalBars)); count++; if (count === 6) if (CheckEan13(binaryString.splice(0, 5), true)) secureCount++; } while (result.length < 12 && binaryString.length > 0); if (CheckEan13(binaryString.splice(0, 3), false)) secureCount++; if (secureCount < 2) return []; } if (type === "2Of5") { totalBars = 5; len = binaryString[0] / 2; for (i = 0; i < binaryString.length; i++) { if (binaryString[i] > len * 5) { binaryString.splice(i, binaryString.length); break; } } var temp = binaryString.splice(0, 6); result.push(temp); do { binTemp = []; for (i = 0; i < totalBars; i++) { binTemp.push(binaryString.splice(0, 1)[0]); // binaryString.splice(0, 1)[0]; } result.push(binTemp); if (binaryString.length === 5) result.push(binaryString.splice(0, 5)); } while (binaryString.length > 0); } if (type === "Inter2Of5") { totalBars = 5; len = binaryString[0]; for (i = 0; i < binaryString.length; i++) { if (binaryString[i] > len * 5) { binaryString.splice(i, binaryString.length); break; } } result.push(binaryString.splice(0, 4)); var binTempWhite = []; do { binTemp = []; binTempWhite = []; for (i = 0; i < totalBars; i++) { binTemp.push(binaryString.splice(0, 1)[0]); binTempWhite.push(binaryString.splice(0, 1)[0]); } result.push(binTemp); result.push(binTempWhite); if (binaryString.length === 3) result.push(binaryString.splice(0, 3)); } while (binaryString.length > 0); } if (type === "Codabar") { totalBars = 7; len = binaryString[0]; for (i = 0; i < binaryString.length; i++) { if (binaryString[i] > len * 5) { binaryString.splice(i, binaryString.length); break; } } do { result.push(binaryString.splice(0, totalBars)); binaryString.splice(0, 1); } while (binaryString.length > 0); } return result; } function BinaryString(img, type) { var binaryString = []; var binTemp = []; var container = 255; var count = 0; var format; var tempString; var j, i; for (j = 0; j < img.length - Image.width * 4; j += Image.width * 4) { var SlicedArray = img.subarray(j, j + Image.width * 4); binaryString = []; i = 0; while (SlicedArray[i] === 255) { i += 4; } while (i < SlicedArray.length) { count = 0; container = SlicedArray[i]; while (SlicedArray[i] === container && i < SlicedArray.length) { count++; i += 4; } binaryString.push(count); } if (binaryString.length > 2 && binaryString[0] <= binaryString[1] / 10) { binaryString.splice(0, 2); } var binaryHolder = binaryString.slice(); var success = false; for (i = 0; i < FormatPriority.length; i++) { binaryString = binaryHolder.slice(); var first; var second; binaryString = BinaryConfiguration(binaryString, FormatPriority[i]); if (FormatPriority[i] === "2Of5" || FormatPriority[i] === "Inter2Of5") { first = binaryString.splice(0, 1)[0]; second = binaryString.splice(binaryString.length - 1, 1)[0]; } binTemp = Distribution(binaryString, FormatPriority[i]); if (FormatPriority[i] === "EAN-13") { binaryString = binTemp.data; corrections = binTemp.correction; } else { binaryString = binTemp; } if (typeof binaryString === 'undefined') continue; if (binaryString.length > 4 || (FormatPriority[i] === "Code39" && binaryString.length > 2)) { if (FormatPriority[i] === "Code128") { if (CheckCode128(binaryString)) { binaryString = DecodeCode128(binaryString); success = true; } } else if (FormatPriority[i] === "Code93") { if (CheckCode93(binaryString)) { binaryString = DecodeCode93(binaryString); success = true; } } else if (FormatPriority[i] === "Code39") { if (CheckCode39(binaryString)) { binaryString = DecodeCode39(binaryString); success = true; } } else if (FormatPriority[i] === "EAN-13") { tempString = DecodeEAN13(binaryString); if (tempString) { if (tempString.length === 13) { binaryString = tempString; success = true; } } } else if (FormatPriority[i] === "2Of5" || FormatPriority[i] === "Inter2Of5") { if (FormatPriority[i] === "2Of5") { if (typeof first !== 'undefined') if (!TwoOfFiveStartEnd(first, true)) continue; if (typeof second !== 'undefined') if (!TwoOfFiveStartEnd(second, false)) continue; } if (FormatPriority[i] === "Inter2Of5") { if (typeof first !== 'undefined') if (!CheckInterleaved(first, true)) continue; if (typeof second !== 'undefined') if (!CheckInterleaved(second, false)) continue; } tempString = Decode2Of5(binaryString); if (tempString) { binaryString = tempString; success = true; } } else if (FormatPriority[i] === "Codabar") { tempString = DecodeCodaBar(binaryString); if (tempString) { binaryString = tempString; success = true; } } } if (success) { format = FormatPriority[i]; if (format === "Inter2Of5") format = "Interleaved 2 of 5"; if (format === "2Of5") format = "Standard 2 of 5"; break; } } if (success) break; } if (format === "Code128") { if (typeof binaryString.string === 'string') { return binaryString; } else { return { string: false }; } } if (typeof binaryString === 'string') { if (format === "EAN-13") { return { string: binaryString, format: format, correction: corrections }; } else { return { string: binaryString, format: format }; } } else { return { string: false }; } } function Distribution(totalBinArray, type) { var testData = 0; var result = []; var totalBars; var total; var maxLength; var k, i, j; var blackMax; var whiteMax; var wideAvrg; var narrowAvrg; var prevPos; var wideValues; var max; type = availableFormats.indexOf(type); if (type === 0) { total = 11; totalBars = 6; maxLength = 4; } else if (type === 1) { total = 9; totalBars = 6; maxLength = 4; } else if (type === 2) { total = 12; totalBars = 9; } else if (type === 3) { total = 7; totalBars = 4; maxLength = 4; } else if (type === 6) { totalBars = 7; } for (k = 0; k < totalBinArray.length; k++) { var BinArray = totalBinArray[k]; var sum = 0; var counter = 0; var tempBin = []; var narrowArr = []; var wideArr = []; if (type === 6) { var upperTolerance = 1.5; var lowerTolerance = 1 / 2; if (BinArray.length !== 7) return []; if (k === 0 || k === totalBinArray.length - 1) { whiteMax = [ [0, 0], [0, 0] ]; blackMax = [0, 0]; for (i = 0; i < BinArray.length; i++) { if (i % 2 === 0) { if (BinArray[i] > blackMax[0]) { blackMax[0] = BinArray[i]; blackMax[1] = i; } } else { if (BinArray[i] > whiteMax[0][0]) { whiteMax[0][0] = BinArray[i]; prevPos = whiteMax[0][1]; whiteMax[0][1] = i; i = prevPos - 1; continue; } if (BinArray[i] > whiteMax[1][0] && i !== whiteMax[0][1]) { whiteMax[1][0] = BinArray[i]; whiteMax[1][1] = i; } } } if (SecureCodabar) { wideAvrg = whiteMax[0][0] + whiteMax[1][0] + blackMax[0]; wideAvrg /= 3; wideValues = [whiteMax[0][0], whiteMax[1][0], blackMax[0]]; for (i = 0; i < wideValues.length; i++) { if (wideValues[i] / wideAvrg > upperTolerance || wideValues[i] / wideAvrg < lowerTolerance) return []; } narrowAvrg = 0; for (i = 0; i < BinArray.length; i++) { if (i === blackMax[1] || i === whiteMax[0][1] || i === whiteMax[1][1]) continue; narrowAvrg += BinArray[i]; } narrowAvrg /= 4; for (i = 0; i < BinArray.length; i++) { if (i === blackMax[1] || i === whiteMax[0][1] || i === whiteMax[1][1]) continue; if (BinArray[i] / narrowAvrg > upperTolerance || BinArray[i] / narrowAvrg < lowerTolerance) return []; } } for (i = 0; i < BinArray.length; i++) { if (i === blackMax[1] || i === whiteMax[0][1] || i === whiteMax[1][1]) { tempBin.push(1); } else { tempBin.push(0); } } } else { blackMax = [0, 0]; whiteMax = [0, 0]; for (i = 0; i < BinArray.length; i++) { if (i % 2 === 0) { if (BinArray[i] > blackMax[0]) { blackMax[0] = BinArray[i]; blackMax[1] = i; } } else { if (BinArray[i] > whiteMax[0]) { whiteMax[0] = BinArray[i]; whiteMax[1] = i; } } } if (blackMax[0] / whiteMax[0] > 1.55) { var tempArray = blackMax; blackMax = [tempArray, [0, 0], [0, 0] ]; for (i = 0; i < BinArray.length; i++) { if (i % 2 === 0) { if (BinArray[i] > blackMax[1][0] && i !== blackMax[0][1]) { blackMax[1][0] = BinArray[i]; prevPos = blackMax[1][1]; blackMax[1][1] = i; i = prevPos - 1; continue; } if (BinArray[i] > blackMax[2][0] && i !== blackMax[0][1] && i !== blackMax[1][1]) { blackMax[2][0] = BinArray[i]; blackMax[2][1] = i; } } } if (SecureCodabar) { wideAvrg = blackMax[0][0] + blackMax[1][0] + blackMax[2][0]; wideAvrg /= 3; for (i = 0; i < blackMax.length; i++) { if (blackMax[i][0] / wideAvrg > upperTolerance || blackMax[i][0] / wideAvrg < lowerTolerance) return []; } narrowAvrg = 0; for (i = 0; i < BinArray.length; i++) { if (i === blackMax[0][1] || i === blackMax[1][1] || i === blackMax[2][1]) continue; narrowAvrg += BinArray[i]; } narrowAvrg /= 4; for (i = 0; i < BinArray.length; i++) { if (i === blackMax[0][1] || i === blackMax[1][1] || i === blackMax[2][1]) continue; if (BinArray[i] / narrowAvrg > upperTolerance || BinArray[i] / narrowAvrg < lowerTolerance) return []; } } for (i = 0; i < BinArray.length; i++) { if (i === blackMax[0][1] || i === blackMax[1][1] || i === blackMax[2][1]) { tempBin.push(1); } else { tempBin.push(0); } } } else { if (SecureCodabar) { wideAvrg = blackMax[0] + whiteMax[0]; wideAvrg /= 2; if (blackMax[0] / wideAvrg > 1.5 || blackMax[0] / wideAvrg < 0.5) return []; if (whiteMax[0] / wideAvrg > 1.5 || whiteMax[0] / wideAvrg < 0.5) return []; narrowAvrg = 0; for (i = 0; i < BinArray.length; i++) { if (i === blackMax[1] || i === whiteMax[1]) continue; narrowAvrg += BinArray[i]; } narrowAvrg /= 5; for (i = 0; i < BinArray.length; i++) { if (i === blackMax[1] || i === whiteMax[1]) continue; if (BinArray[i] / narrowAvrg > upperTolerance || BinArray[i] / narrowAvrg < lowerTolerance) return []; } } for (i = 0; i < BinArray.length; i++) { if (i === blackMax[1] || i === whiteMax[1]) { tempBin.push(1); } else { tempBin.push(0); } } } } result.push(tempBin); continue; } if (type === 4 || type === 5) { max = [ [0, 0], [0, 0] ]; for (i = 0; i < BinArray.length; i++) { if (!isFinite(BinArray[i])) return []; if (BinArray[i] > max[0][0]) { max[0][0] = BinArray[i]; prevPos = max[0][1]; max[0][1] = i; i = prevPos - 1; } if (BinArray[i] > max[1][0] && i !== max[0][1]) { max[1][0] = BinArray[i]; max[1][1] = i; } } if (Secure2Of5) { wideAvrg = max[0][0] + max[1][0]; wideAvrg /= 2; if (max[0][0] / wideAvrg > 1.3 || max[0][0] / wideAvrg < 0.7) return []; if (max[1][0] / wideAvrg > 1.3 || max[1][0] / wideAvrg < 0.7) return []; narrowAvrg = 0; for (i = 0; i < BinArray.length; i++) { if (i === max[0][1] || i === max[1][1]) continue; narrowAvrg += BinArray[i]; } narrowAvrg /= 3; for (i = 0; i < BinArray.length; i++) { if (i === max[0][1] || i === max[1][1]) continue; if (BinArray[i] / narrowAvrg > 1.3 || BinArray[i] / narrowAvrg < 0.7) return []; } } for (i = 0; i < BinArray.length; i++) { if (i === max[0][1] || i === max[1][1]) { tempBin.push(1); continue; } tempBin.push(0); } result.push(tempBin); continue; } while (counter < totalBars) { sum += BinArray[counter]; counter++; } if (type === 2) { var indexCount = []; blackMax = [ [0, 0], [0, 0] ]; whiteMax = [0, 0]; for (j = 0; j < BinArray.length; j++) { if (j % 2 === 0) { if (BinArray[j] > blackMax[0][0]) { blackMax[0][0] = BinArray[j]; prevPos = blackMax[0][1]; blackMax[0][1] = j; j = prevPos; } if (BinArray[j] > blackMax[1][0] && j !== blackMax[0][1]) { blackMax[1][0] = BinArray[j]; blackMax[1][1] = j; } } else { if (BinArray[j] > whiteMax[0]) { whiteMax[0] = BinArray[j]; whiteMax[1] = j; } } } if (whiteMax[0] / blackMax[0][0] > 1.5 && whiteMax[0] / blackMax[1][0] > 1.5) { blackMax = [ [0, 0], [0, 0] ]; for (j = 0; j < BinArray.length; j++) { if (j % 2 !== 0) { if (BinArray[j] > blackMax[0][0] && j !== whiteMax[1]) { blackMax[0][0] = BinArray[j]; prevPos = blackMax[0][1]; blackMax[0][1] = j; j = prevPos; } if (BinArray[j] > blackMax[1][0] && j !== blackMax[0][1] && j !== whiteMax[1]) { blackMax[1][0] = BinArray[j]; blackMax[1][1] = j; } } } } wideAvrg = blackMax[0][0] + blackMax[1][0] + whiteMax[0]; wideAvrg /= 3; if (blackMax[0][0] / wideAvrg > 1.6 || blackMax[0][0] / wideAvrg < 0.4) return []; if (blackMax[1][0] / wideAvrg > 1.6 || blackMax[1][0] / wideAvrg < 0.4) return []; if (whiteMax[0] / wideAvrg > 1.6 || whiteMax[0] / wideAvrg < 0.4) return []; narrowAvrg = 0; for (i = 0; i < BinArray.length; i++) { if (i === blackMax[0][1] || i === blackMax[1][1] || i === whiteMax[1]) continue; narrowAvrg += BinArray[i]; } narrowAvrg /= 6; for (i = 0; i < BinArray.length; i++) { if (i === blackMax[0][1] || i === blackMax[1][1] || i === whiteMax[1]) continue; if (BinArray[i] / narrowAvrg > 1.6 || BinArray[i] / narrowAvrg < 0.4) return []; } for (j = 0; j < BinArray.length; j++) { if (j === blackMax[0][1] || j === blackMax[1][1] || j === whiteMax[1]) { tempBin.push(2); } else { tempBin.push(1); } } result.push(tempBin); continue; } if (type === 3) { max = [ [0, 0], [0, 0], [0, 0] ]; for (j = 0; j < BinArray.length; j++) { if (BinArray[j] > max[0][0]) { max[0][0] = BinArray[j]; prevPos = max[0][1]; max[0][1] = j; j = prevPos; } if (BinArray[j] > max[1][0] && j !== max[0][1]) { max[1][0] = BinArray[j]; prevPos = max[1][1]; max[1][1] = j; j = prevPos; } if (BinArray[j] > max[2][0] && j !== max[0][1] && j !== max[1][1]) { max[2][0] = BinArray[j]; max[2][1] = j; } } if (max[0][0] / max[1][0] >= 3) { narrowAvrg = 0; for (j = 0; j < BinArray.length; j++) { if (j === max[0][1]) continue; narrowAvrg += BinArray[j]; } narrowAvrg /= 3; for (j = 0; j < BinArray.length; j++) { if (j === max[0][1]) continue; if (BinArray[j] / narrowAvrg < 0.02 || BinArray[j] / narrowAvrg > 3) return { data: [], correction: 0 }; } if (max[0][0] / narrowAvrg < 2.2 || max[0][0] / narrowAvrg > 6) return { data: [], correction: 0 }; for (j = 0; j < BinArray.length; j++) { if (j === max[0][1]) { tempBin.push(4); } else { tempBin.push(1); } } result.push(tempBin); } else if (max[0][0] / max[2][0] > 2) { wideAvrg = max[0][0] + max[1][0]; wideAvrg /= 5; if (max[0][0] / (wideAvrg * 3) < 0.02 || max[0][0] / (wideAvrg * 3) > 3) return { data: [], correction: 0 }; if (max[1][0] / (wideAvrg * 2) < 0.02 || max[1][0] / (wideAvrg * 2) > 3) return { data: [], correction: 0 }; narrowAvrg = 0; for (j = 0; j < BinArray.length; j++) { if (j === max[0][1] || j === max[1][1]) continue; narrowAvrg += BinArray[j]; } narrowAvrg /= 2; for (j = 0; j < BinArray.length; j++) { if (j === max[0][1] || j === max[1][1]) continue; if (BinArray[j] / narrowAvrg < 0.02 || BinArray[j] / narrowAvrg > 3) return { data: [], correction: 0 }; } for (j = 0; j < BinArray.length; j++) { if (j === max[0][1]) { tempBin.push(3); } else if (j === max[1][1]) { tempBin.push(2); } else { tempBin.push(1); } } result.push(tempBin); } else { if (max[0][1] % 2 === max[1][1] % 2 && max[0][1] % 2 === max[2][1] % 2) { var modMem = max[0][1] % 2; max[2] = [0, 0]; for (j = 0; j < BinArray.length; j++) { if (j % 2 === modMem) continue; if (BinArray[j] > max[2][0]) { max[2][0] = BinArray[j]; max[2][1] = j; } } } wideAvrg = max[0][0] + max[1][0] + max[2][0]; wideAvrg /= 3; for (j = 0; j < max.length; j++) { if (max[j][0] / wideAvrg < 0.02 || max[j][0] / wideAvrg > 3) return { data: [], correction: 0 }; } var narrow = 0; for (j = 0; j < BinArray.length; j++) { if (j === max[0][1] || j === max[1][1] || j === max[2][1]) continue; narrow = BinArray[j]; } if (wideAvrg / narrow < 0.02 || wideAvrg / narrow > 3) return { data: [], correction: 0 }; for (j = 0; j < BinArray.length; j++) { if (j === max[0][1] || j === max[1][1] || j === max[2][1]) { tempBin.push(2); } else { tempBin.push(1); } } result.push(tempBin); } for (j = 0; j < tempBin.length; j++) { testData += Math.abs(tempBin[j] - (BinArray[j] / sum) * total); } continue; } counter = 0; while (counter < totalBars) { tempBin.push((BinArray[counter] / sum) * total); counter++; } counter = 0; while (counter < totalBars) { tempBin[counter] = tempBin[counter] > maxLength ? maxLength : tempBin[counter]; tempBin[counter] = tempBin[counter] < 1 ? 1 : tempBin[counter]; tempBin[counter] = Math.round(tempBin[counter]); counter++; } if (type === 3) { var checking = 0; for (i = 0; i < tempBin.length; i++) { checking += tempBin[i]; } if (checking > 7) { max = 0; var hitIndex = 0; for (i = 0; i < tempBin.length; i++) { if (tempBin[i] > max) { max = tempBin[i]; hitIndex = i; } } tempBin[hitIndex] = max - (checking - 7); } } if (type === 3) { for (i = 0; i < tempBin.length; i++) { testData += Math.abs(tempBin[i] - (BinArray[i] / sum) * total); } } result.push(tempBin); } if (type === 3) { return { data: result, correction: testData }; } else { return result; } } function CheckCode128(string) { var checksum = string[string.length - 2].join(""); var i; checksum = Code128Encoding.value.indexOf(checksum); if (checksum === -1) return false; var summarizer = Code128Encoding.value.indexOf(string[0].join("")); if (summarizer === -1) return false; var startChar = Code128Encoding[string[0].join("")]; if (typeof startChar === 'undefined') return false; if (startChar !== "A" && startChar !== "B" && startChar !== "C") return false; for (i = 1; i < (string.length - 2); i++) { summarizer += Code128Encoding.value.indexOf(string[i].join("")) * i; if (Code128Encoding.value.indexOf(string[i].join("")) === -1) return false; } return (summarizer % 103 === checksum); } function Decode2Of5(string) { var result = ""; var i; for (i = 0; i < string.length; i++) { if (TwoOfFiveEncoding.indexOf(string[i].join("")) === -1) return false; result += TwoOfFiveEncoding.indexOf(string[i].join("")); } return result; } function DecodeCodaBar(string) { var result = ""; var start = string[0].join(""); var end = string[string.length - 1].join(""); var i; if (!(CodaBarEncoding[start] === "A" || CodaBarEncoding[start] === "B" || CodaBarEncoding[start] === "C" || CodaBarEncoding[start] === "D")) return false; if (!(CodaBarEncoding[end] === "A" || CodaBarEncoding[end] === "B" || CodaBarEncoding[end] === "C" || CodaBarEncoding[end] === "D")) return false; for (i = 1; i < string.length - 1; i++) { if (typeof CodaBarEncoding[string[i].join("")] === 'undefined') return false; result += CodaBarEncoding[string[i].join("")]; } return result; } function DecodeEAN13(string) { if (string.length !== 12) return false; var leftSide = string.slice(0, 6); var trigger = false; var rightSide = string.slice(6, string.length); var i; for (i = 0; i < leftSide.length; i++) { leftSide[i] = leftSide[i].join(""); if (leftSide[i].length !== 4) { trigger = true; break; } } if (trigger) return false; for (i = 0; i < rightSide.length; i++) { rightSide[i] = rightSide[i].join(""); if (rightSide[i].length !== 4) { trigger = true; break; } } if (trigger) return false; var decodeFormat = []; for (i = 0; i < leftSide.length; i++) { if (typeof EAN13Encoding.L[leftSide[i]] !== 'undefined') { decodeFormat.push("L"); } else if (typeof EAN13Encoding.G[leftSide[i]] !== 'undefined') { decodeFormat.push("G"); } else { trigger = true; break; } } if (trigger) return false; var resultArray = []; if (typeof EAN13Encoding.formats[decodeFormat.join("")] === 'undefined') return false; resultArray.push(EAN13Encoding.formats[decodeFormat.join("")]); for (i = 0; i < leftSide.length; i++) { if (typeof EAN13Encoding[decodeFormat[i]][leftSide[i]] === 'undefined') { trigger = true; break; } resultArray.push(EAN13Encoding[decodeFormat[i]][leftSide[i]]); } if (trigger) return false; for (i = 0; i < rightSide.length; i++) { if (typeof EAN13Encoding.R[rightSide[i]] === 'undefined') { trigger = true; break; } resultArray.push(EAN13Encoding.R[rightSide[i]]); } if (trigger) return false; var weight = 3; var sum = 0; for (i = resultArray.length - 2; i >= 0; i--) { sum += resultArray[i] * weight; if (weight === 3) { weight = 1; } else { weight = 3; } } sum = (10 - sum % 10) % 10; if (resultArray[resultArray.length - 1] === sum) { return resultArray.join(""); } else { return false; } } function CheckCode93(string) { var checkOne = string[string.length - 3].join(""); var checkTwo = string[string.length - 2].join(""); var failSafe = true; if (typeof Code93Encoding[checkOne] === 'undefined') return false; if (typeof Code93Encoding[checkTwo] === 'undefined') return false; var checkSum = Code93Encoding[checkOne].value; var weight = 1; var sum = 0; var i; for (i = string.length - 4; i > 0; i--) { failSafe = typeof Code93Encoding[string[i].join("")] === 'undefined' ? false : failSafe; if (!failSafe) break; sum += Code93Encoding[string[i].join("")].value * weight; weight++; if (weight > 20) weight = 1; } var firstCheck = sum % 47; var firstBool = firstCheck === checkSum; if (!firstBool) return false; if (!failSafe) return false; sum = firstCheck; weight = 2; checkSum = Code93Encoding[checkTwo].value; for (i = string.length - 4; i > 0; i--) { failSafe = typeof Code93Encoding[string[i].join("")] === 'undefined' ? false : failSafe; if (!failSafe) break; sum += Code93Encoding[string[i].join("")].value * weight; weight++; if (weight > 15) weight = 1; } var secondCheck = sum % 47; var secondBool = secondCheck === checkSum; return secondBool && firstBool; } function CheckCode39(string) { var trigger = true; if (typeof Code39Encoding[string[0].join("")] === 'undefined') return false; if (Code39Encoding[string[0].join("")].character !== "*") return false; if (typeof Code39Encoding[string[string.length - 1].join("")] === 'undefined') return false; if (Code39Encoding[string[string.length - 1].join("")].character !== "*") return false; for (i = 1; i < string.length - 1; i++) { if (typeof Code39Encoding[string[i].join("")] === 'undefined') { trigger = false; break; } } return trigger; } function DecodeCode39(string) { var resultString = ""; var special = false; var character = ""; var specialchar = ""; for (i = 1; i < string.length - 1; i++) { character = Code39Encoding[string[i].join("")].character; if (character === "$" || character === "/" || character === "+" || character === "%") { // if next character exists => this a special character if (i + 1 < string.length - 1) { special = true; specialchar = character; continue; } } if (special) { if (typeof ExtendedEncoding[specialchar + character] === 'undefined') {} else { resultString += ExtendedEncoding[specialchar + character]; } special = false; continue; } resultString += character; } return resultString; } function DecodeCode93(string) { var resultString = ""; var special = false; var character = ""; var specialchar = ""; for (i = 1; i < string.length - 3; i++) { character = Code93Encoding[string[i].join("")].character; if (character === "($)" || character === "(/)" || character === "(+)" || character === "(%)") { special = true; specialchar = character[1]; continue; } if (special) { if (typeof ExtendedEncoding[specialchar + character] === 'undefined') {} else { resultString += ExtendedEncoding[specialchar + character]; } special = false; continue; } resultString += character; } return resultString; } function DecodeCode128(string) { var set = Code128Encoding[string[0].join("")]; var symbol; var Code128Format = "Code128"; var resultString = ""; var i; for (i = 1; i < (string.length - 2); i++) { symbol = Code128Encoding[string[i].join("")][set]; switch (symbol) { case "FNC1": if (i === 1) Code128Format = "GS1-128"; break; case "FNC2": case "FNC3": case "FNC4": break; case "SHIFT_B": i++; resultString += Code128Encoding[string[i].join("")].B; break; case "SHIFT_A": i++; resultString += Code128Encoding[string[i].join("")].A; break; case "Code_A": set = "A"; break; case "Code_B": set = "B"; break; case "Code_C": set = "C"; break; default: resultString += symbol; } } return { string: resultString, format: Code128Format }; } TwoOfFiveEncoding = ["00110", "10001", "01001", "11000", "00101", "10100", "01100", "00011", "10010", "01010"]; Code128Encoding = { "212222": { A: " ", B: " ", C: "00" }, "222122": { A: "!", B: "!", C: "01" }, "222221": { A: '"', B: '"', C: "02" }, "121223": { A: "#", B: "#", C: "03" }, "121322": { A: "$", B: "$", C: "04" }, "131222": { A: "%", B: "%", C: "05" }, "122213": { A: "&", B: "&", C: "06" }, "122312": { A: "'", B: "'", C: "07" }, "132212": { A: "(", B: "(", C: "08" }, "221213": { A: ")", B: ")", C: "09" }, "221312": { A: "*", B: "*", C: "10" }, "231212": { A: "+", B: "+", C: "11" }, "112232": { A: ",", B: ",", C: "12" }, "122132": { A: "-", B: "-", C: "13" }, "122231": { A: ".", B: ".", C: "14" }, "113222": { A: "/", B: "/", C: "15" }, "123122": { A: "0", B: "0", C: "16" }, "123221": { A: "1", B: "1", C: "17" }, "223211": { A: "2", B: "2", C: "18" }, "221132": { A: "3", B: "3", C: "19" }, "221231": { A: "4", B: "4", C: "20" }, "213212": { A: "5", B: "5", C: "21" }, "223112": { A: "6", B: "6", C: "22" }, "312131": { A: "7", B: "7", C: "23" }, "311222": { A: "8", B: "8", C: "24" }, "321122": { A: "9", B: "9", C: "25" }, "321221": { A: ":", B: ":", C: "26" }, "312212": { A: ";", B: ";", C: "27" }, "322112": { A: "<", B: "<", C: "28" }, "322211": { A: "=", B: "=", C: "29" }, "212123": { A: ">", B: ">", C: "30" }, "212321": { A: "?", B: "?", C: "31" }, "232121": { A: "@", B: "@", C: "32" }, "111323": { A: "A", B: "A", C: "33" }, "131123": { A: "B", B: "B", C: "34" }, "131321": { A: "C", B: "C", C: "35" }, "112313": { A: "D", B: "D", C: "36" }, "132113": { A: "E", B: "E", C: "37" }, "132311": { A: "F", B: "F", C: "38" }, "211313": { A: "G", B: "G", C: "39" }, "231113": { A: "H", B: "H", C: "40" }, "231311": { A: "I", B: "I", C: "41" }, "112133": { A: "J", B: "J", C: "42" }, "112331": { A: "K", B: "K", C: "43" }, "132131": { A: "L", B: "L", C: "44" }, "113123": { A: "M", B: "M", C: "45" }, "113321": { A: "N", B: "N", C: "46" }, "133121": { A: "O", B: "O", C: "47" }, "313121": { A: "P", B: "P", C: "48" }, "211331": { A: "Q", B: "Q", C: "49" }, "231131": { A: "R", B: "R", C: "50" }, "213113": { A: "S", B: "S", C: "51" }, "213311": { A: "T", B: "T", C: "52" }, "213131": { A: "U", B: "U", C: "53" }, "311123": { A: "V", B: "V", C: "54" }, "311321": { A: "W", B: "W", C: "55" }, "331121": { A: "X", B: "X", C: "56" }, "312113": { A: "Y", B: "Y", C: "57" }, "312311": { A: "Z", B: "Z", C: "58" }, "332111": { A: "[", B: "[", C: "59" }, "314111": { A: "\\", B: "\\", C: "60" }, "221411": { A: "]", B: "]", C: "61" }, "431111": { A: "^", B: "^", C: "62" }, "111224": { A: "_", B: "_", C: "63" }, "111422": { A: "NUL", B: "`", C: "64" }, "121124": { A: "SOH", B: "a", C: "65" }, "121421": { A: "STX", B: "b", C: "66" }, "141122": { A: "ETX", B: "c", C: "67" }, "141221": { A: "EOT", B: "d", C: "68" }, "112214": { A: "ENQ", B: "e", C: "69" }, "112412": { A: "ACK", B: "f", C: "70" }, "122114": { A: "BEL", B: "g", C: "71" }, "122411": { A: "BS", B: "h", C: "72" }, "142112": { A: "HT", B: "i", C: "73" }, "142211": { A: "LF", B: "j", C: "74" }, "241211": { A: "VT", B: "k", C: "75" }, "221114": { A: "FF", B: "l", C: "76" }, "413111": { A: "CR", B: "m", C: "77" }, "241112": { A: "SO", B: "n", C: "78" }, "134111": { A: "SI", B: "o", C: "79" }, "111242": { A: "DLE", B: "p", C: "80" }, "121142": { A: "DC1", B: "q", C: "81" }, "121241": { A: "DC2", B: "r", C: "82" }, "114212": { A: "DC3", B: "s", C: "83" }, "124112": { A: "DC4", B: "t", C: "84" }, "124211": { A: "NAK", B: "u", C: "85" }, "411212": { A: "SYN", B: "v", C: "86" }, "421112": { A: "ETB", B: "w", C: "87" }, "421211": { A: "CAN", B: "x", C: "88" }, "212141": { A: "EM", B: "y", C: "89" }, "214121": { A: "SUB", B: "z", C: "90" }, "412121": { A: "ESC", B: "{", C: "91" }, "111143": { A: "FS", B: "|", C: "92" }, "111341": { A: "GS", B: "}", C: "93" }, "131141": { A: "RS", B: "~", C: "94" }, "114113": { A: "US", B: "DEL", C: "95" }, "114311": { A: "FNC3", B: "FNC3", C: "96" }, "411113": { A: "FNC2", B: "FNC2", C: "97" }, "411311": { A: "SHIFT_B", B: "SHIFT_A", C: "98" }, "113141": { A: "Code_C", B: "Code_C", C: "99" }, "114131": { A: "Code_B", B: "FNC4", C: "Code_B" }, "311141": { A: "FNC4", B: "Code_A", C: "Code_A" }, "411131": { A: "FNC1", B: "FNC1", C: "FNC1" }, "211412": "A", "211214": "B", "211232": "C", "233111": { A: "STOP", B: "STOP", C: "STOP" }, value: [ "212222", "222122", "222221", "121223", "121322", "131222", "122213", "122312", "132212", "221213", "221312", "231212", "112232", "122132", "122231", "113222", "123122", "123221", "223211", "221132", "221231", "213212", "223112", "312131", "311222", "321122", "321221", "312212", "322112", "322211", "212123", "212321", "232121", "111323", "131123", "131321", "112313", "132113", "132311", "211313", "231113", "231311", "112133", "112331", "132131", "113123", "113321", "133121", "313121", "211331", "231131", "213113", "213311", "213131", "311123", "311321", "331121", "312113", "312311", "332111", "314111", "221411", "431111", "111224", "111422", "121124", "121421", "141122", "141221", "112214", "112412", "122114", "122411", "142112", "142211", "241211", "221114", "413111", "241112", "134111", "111242", "121142", "121241", "114212", "124112", "124211", "411212", "421112", "421211", "212141", "214121", "412121", "111143", "111341", "131141", "114113", "114311", "411113", "411311", "113141", "114131", "311141", "411131", "211412", "211214", "211232", "233111" ] }; Code93Encoding = { "131112": { value: 0, character: "0" }, "111213": { value: 1, character: "1" }, "111312": { value: 2, character: "2" }, "111411": { value: 3, character: "3" }, "121113": { value: 4, character: "4" }, "121212": { value: 5, character: "5" }, "121311": { value: 6, character: "6" }, "111114": { value: 7, character: "7" }, "131211": { value: 8, character: "8" }, "141111": { value: 9, character: "9" }, "211113": { value: 10, character: "A" }, "211212": { value: 11, character: "B" }, "211311": { value: 12, character: "C" }, "221112": { value: 13, character: "D" }, "221211": { value: 14, character: "E" }, "231111": { value: 15, character: "F" }, "112113": { value: 16, character: "G" }, "112212": { value: 17, character: "H" }, "112311": { value: 18, character: "I" }, "122112": { value: 19, character: "J" }, "132111": { value: 20, character: "K" }, "111123": { value: 21, character: "L" }, "111222": { value: 22, character: "M" }, "111321": { value: 23, character: "N" }, "121122": { value: 24, character: "O" }, "131121": { value: 25, character: "P" }, "212112": { value: 26, character: "Q" }, "212211": { value: 27, character: "R" }, "211122": { value: 28, character: "S" }, "211221": { value: 29, character: "T" }, "221121": { value: 30, character: "U" }, "222111": { value: 31, character: "V" }, "112122": { value: 32, character: "W" }, "112221": { value: 33, character: "X" }, "122121": { value: 34, character: "Y" }, "123111": { value: 35, character: "Z" }, "121131": { value: 36, character: "-" }, "311112": { value: 37, character: "." }, "311211": { value: 38, character: " " }, "321111": { value: 39, character: "$" }, "112131": { value: 40, character: "/" }, "113121": { value: 41, character: "+" }, "211131": { value: 42, character: "%" }, "121221": { value: 43, character: "($)" }, "312111": { value: 44, character: "(%)" }, "311121": { value: 45, character: "(/)" }, "122211": { value: 46, character: "(+)" }, "111141": { value: -1, character: "*" } }; Code39Encoding = { "111221211": { value: 0, character: "0" }, "211211112": { value: 1, character: "1" }, "112211112": { value: 2, character: "2" }, "212211111": { value: 3, character: "3" }, "111221112": { value: 4, character: "4" }, "211221111": { value: 5, character: "5" }, "112221111": { value: 6, character: "6" }, "111211212": { value: 7, character: "7" }, "211211211": { value: 8, character: "8" }, "112211211": { value: 9, character: "9" }, "211112112": { value: 10, character: "A" }, "112112112": { value: 11, character: "B" }, "212112111": { value: 12, character: "C" }, "111122112": { value: 13, character: "D" }, "211122111": { value: 14, character: "E" }, "112122111": { value: 15, character: "F" }, "111112212": { value: 16, character: "G" }, "211112211": { value: 17, character: "H" }, "112112211": { value: 18, character: "I" }, "111122211": { value: 19, character: "J" }, "211111122": { value: 20, character: "K" }, "112111122": { value: 21, character: "L" }, "212111121": { value: 22, character: "M" }, "111121122": { value: 23, character: "N" }, "211121121": { value: 24, character: "O" }, "112121121": { value: 25, character: "P" }, "111111222": { value: 26, character: "Q" }, "211111221": { value: 27, character: "R" }, "112111221": { value: 28, character: "S" }, "111121221": { value: 29, character: "T" }, "221111112": { value: 30, character: "U" }, "122111112": { value: 31, character: "V" }, "222111111": { value: 32, character: "W" }, "121121112": { value: 33, character: "X" }, "221121111": { value: 34, character: "Y" }, "122121111": { value: 35, character: "Z" }, "121111212": { value: 36, character: "-" }, "221111211": { value: 37, character: "." }, "122111211": { value: 38, character: " " }, "121212111": { value: 39, character: "$" }, "121211121": { value: 40, character: "/" }, "121112121": { value: 41, character: "+" }, "111212121": { value: 42, character: "%" }, "121121211": { value: -1, character: "*" } }; ExtendedEncoding = { "/A": '!', "/B": '"', "/C": '#', "/D": '$', "/E": '%', "/F": '&', "/G": "'", "/H": '(', "/I": ')', "/J": '*', "/K": '+', "/L": ',', "/O": '/', "/Z": ':', "%F": ';', "%G": '<', "%H": '=', "%I": '>', "%J": '?', "%K": '[', "%L": "\\", "%M": ']', "%N": '^', "%O": '_', "+A": 'a', "+B": 'b', "+C": 'c', "+D": 'd', "+E": 'e', "+F": 'f', "+G": 'g', "+H": 'h', "+I": 'i', "+J": 'j', "+K": 'k', "+L": 'l', "+M": 'm', "+N": 'n', "+O": 'o', "+P": 'p', "+Q": 'q', "+R": 'r', "+S": 's', "+T": 't', "+U": 'u', "+V": 'v', "+W": 'w', "+X": 'x', "+Y": 'y', "+Z": 'z', "%P": "{", "%Q": '|', "%R": '|', "%S": '~', }; CodaBarEncoding = { "0000011": "0", "0000110": "1", "0001001": "2", "1100000": "3", "0010010": "4", "1000010": "5", "0100001": "6", "0100100": "7", "0110000": "8", "1001000": "9", "0001100": "-", "0011000": "$", "1000101": ":", "1010001": "/", "1010100": ".", "0011111": "+", "0011010": "A", "0001011": "B", "0101001": "C", "0001110": "D" }; EAN13Encoding = { "L": { "3211": 0, "2221": 1, "2122": 2, "1411": 3, "1132": 4, "1231": 5, "1114": 6, "1312": 7, "1213": 8, "3112": 9 }, "G": { "1123": 0, "1222": 1, "2212": 2, "1141": 3, "2311": 4, "1321": 5, "4111": 6, "2131": 7, "3121": 8, "2113": 9 }, "R": { "3211": 0, "2221": 1, "2122": 2, "1411": 3, "1132": 4, "1231": 5, "1114": 6, "1312": 7, "1213": 8, "3112": 9 }, formats: { "LLLLLL": 0, "LLGLGG": 1, "LLGGLG": 2, "LLGGGL": 3, "LGLLGG": 4, "LGGLLG": 5, "LGGGLL": 6, "LGLGLG": 7, "LGLGGL": 8, "LGGLGL": 9 } }; self.onmessage = function(e) { var width; var i; ScanImage = { data: new Uint8ClampedArray(e.data.scan), width: e.data.scanWidth, height: e.data.scanHeight }; switch (e.data.rotation) { case 8: ScanImage.data = Rotate(ScanImage.data, ScanImage.width, ScanImage.height, -90); width = e.data.scanWidth; ScanImage.width = ScanImage.height; ScanImage.height = width; break; case 6: ScanImage.data = Rotate(ScanImage.data, ScanImage.width, ScanImage.height, 90); width = e.data.scanWidth; ScanImage.width = ScanImage.height; ScanImage.height = width; break; case 3: ScanImage.data = Rotate(ScanImage.data, ScanImage.width, ScanImage.height, 180); } Image = { data: Scale(ScanImage.data, ScanImage.width, ScanImage.height), width: ScanImage.width / 2, height: ScanImage.height / 2 }; if (e.data.postOrientation) { postMessage({ result: Image, success: "orientationData" }); } availableFormats = ["Code128", "Code93", "Code39", "EAN-13", "2Of5", "Inter2Of5", "Codabar"]; FormatPriority = []; var decodeFormats = ["Code128", "Code93", "Code39", "EAN-13", "2Of5", "Inter2Of5", "Codabar"]; SecureCodabar = true; Secure2Of5 = true; Multiple = true; if (typeof e.data.multiple !== 'undefined') { Multiple = e.data.multiple; } if (typeof e.data.decodeFormats !== 'undefined') { decodeFormats = e.data.decodeFormats; } for (i = 0; i < decodeFormats.length; i++) { FormatPriority.push(decodeFormats[i]); } CreateTable(); CreateScanTable(); var FinalResult = Main(); if (FinalResult.length > 0) { postMessage({ result: FinalResult, success: true }); } else { postMessage({ result: FinalResult, success: false }); } }; }; var decoderWorkerBlobString = decoderWorkerBlob.toString(); decoderWorkerBlobString = decoderWorkerBlobString.substring(decoderWorkerBlobString.indexOf("{")+1, decoderWorkerBlobString.lastIndexOf("}")); module.exports = decoderWorkerBlobString; },{}],3:[function(require,module,exports){ (function() { var debug = false; var root = this; var EXIF = function(obj) { if (obj instanceof EXIF) return obj; if (!(this instanceof EXIF)) return new EXIF(obj); this.EXIFwrapped = obj; }; if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = EXIF; } exports.EXIF = EXIF; } else { root.EXIF = EXIF; } var ExifTags = EXIF.Tags = { // version tags 0x9000: "ExifVersion", // EXIF version 0xA000: "FlashpixVersion", // Flashpix format version // colorspace tags 0xA001: "ColorSpace", // Color space information tag // image configuration 0xA002: "PixelXDimension", // Valid width of meaningful image 0xA003: "PixelYDimension", // Valid height of meaningful image 0x9101: "ComponentsConfiguration", // Information about channels 0x9102: "CompressedBitsPerPixel", // Compressed bits per pixel // user information 0x927C: "MakerNote", // Any desired information written by the manufacturer 0x9286: "UserComment", // Comments by user // related file 0xA004: "RelatedSoundFile", // Name of related sound file // date and time 0x9003: "DateTimeOriginal", // Date and time when the original image was generated 0x9004: "DateTimeDigitized", // Date and time when the image was stored digitally 0x9290: "SubsecTime", // Fractions of seconds for DateTime 0x9291: "SubsecTimeOriginal", // Fractions of seconds for DateTimeOriginal 0x9292: "SubsecTimeDigitized", // Fractions of seconds for DateTimeDigitized // picture-taking conditions 0x829A: "ExposureTime", // Exposure time (in seconds) 0x829D: "FNumber", // F number 0x8822: "ExposureProgram", // Exposure program 0x8824: "SpectralSensitivity", // Spectral sensitivity 0x8827: "ISOSpeedRatings", // ISO speed rating 0x8828: "OECF", // Optoelectric conversion factor 0x9201: "ShutterSpeedValue", // Shutter speed 0x9202: "ApertureValue", // Lens aperture 0x9203: "BrightnessValue", // Value of brightness 0x9204: "ExposureBias", // Exposure bias 0x9205: "MaxApertureValue", // Smallest F number of lens 0x9206: "SubjectDistance", // Distance to subject in meters 0x9207: "MeteringMode", // Metering mode 0x9208: "LightSource", // Kind of light source 0x9209: "Flash", // Flash status 0x9214: "SubjectArea", // Location and area of main subject 0x920A: "FocalLength", // Focal length of the lens in mm 0xA20B: "FlashEnergy", // Strobe energy in BCPS 0xA20C: "SpatialFrequencyResponse", // 0xA20E: "FocalPlaneXResolution", // Number of pixels in width direction per FocalPlaneResolutionUnit 0xA20F: "FocalPlaneYResolution", // Number of pixels in height direction per FocalPlaneResolutionUnit 0xA210: "FocalPlaneResolutionUnit", // Unit for measuring FocalPlaneXResolution and FocalPlaneYResolution 0xA214: "SubjectLocation", // Location of subject in image 0xA215: "ExposureIndex", // Exposure index selected on camera 0xA217: "SensingMethod", // Image sensor type 0xA300: "FileSource", // Image source (3 == DSC) 0xA301: "SceneType", // Scene type (1 == directly photographed) 0xA302: "CFAPattern", // Color filter array geometric pattern 0xA401: "CustomRendered", // Special processing 0xA402: "ExposureMode", // Exposure mode 0xA403: "WhiteBalance", // 1 = auto white balance, 2 = manual 0xA404: "DigitalZoomRation", // Digital zoom ratio 0xA405: "FocalLengthIn35mmFilm", // Equivalent foacl length assuming 35mm film camera (in mm) 0xA406: "SceneCaptureType", // Type of scene 0xA407: "GainControl", // Degree of overall image gain adjustment 0xA408: "Contrast", // Direction of contrast processing applied by camera 0xA409: "Saturation", // Direction of saturation processing applied by camera 0xA40A: "Sharpness", // Direction of sharpness processing applied by camera 0xA40B: "DeviceSettingDescription", // 0xA40C: "SubjectDistanceRange", // Distance to subject // other tags 0xA005: "InteroperabilityIFDPointer", 0xA420: "ImageUniqueID" // Identifier assigned uniquely to each image }; var TiffTags = EXIF.TiffTags = { 0x0100: "ImageWidth", 0x0101: "ImageHeight", 0x8769: "ExifIFDPointer", 0x8825: "GPSInfoIFDPointer", 0xA005: "InteroperabilityIFDPointer", 0x0102: "BitsPerSample", 0x0103: "Compression", 0x0106: "PhotometricInterpretation", 0x0112: "Orientation", 0x0115: "SamplesPerPixel", 0x011C: "PlanarConfiguration", 0x0212: "YCbCrSubSampling", 0x0213: "YCbCrPositioning", 0x011A: "XResolution", 0x011B: "YResolution", 0x0128: "ResolutionUnit", 0x0111: "StripOffsets", 0x0116: "RowsPerStrip", 0x0117: "StripByteCounts", 0x0201: "JPEGInterchangeFormat", 0x0202: "JPEGInterchangeFormatLength", 0x012D: "TransferFunction", 0x013E: "WhitePoint", 0x013F: "PrimaryChromaticities", 0x0211: "YCbCrCoefficients", 0x0214: "ReferenceBlackWhite", 0x0132: "DateTime", 0x010E: "ImageDescription", 0x010F: "Make", 0x0110: "Model", 0x0131: "Software", 0x013B: "Artist", 0x8298: "Copyright" }; var GPSTags = EXIF.GPSTags = { 0x0000: "GPSVersionID", 0x0001: "GPSLatitudeRef", 0x0002: "GPSLatitude", 0x0003: "GPSLongitudeRef", 0x0004: "GPSLongitude", 0x0005: "GPSAltitudeRef", 0x0006: "GPSAltitude", 0x0007: "GPSTimeStamp", 0x0008: "GPSSatellites", 0x0009: "GPSStatus", 0x000A: "GPSMeasureMode", 0x000B: "GPSDOP", 0x000C: "GPSSpeedRef", 0x000D: "GPSSpeed", 0x000E: "GPSTrackRef", 0x000F: "GPSTrack", 0x0010: "GPSImgDirectionRef", 0x0011: "GPSImgDirection", 0x0012: "GPSMapDatum", 0x0013: "GPSDestLatitudeRef", 0x0014: "GPSDestLatitude", 0x0015: "GPSDestLongitudeRef", 0x0016: "GPSDestLongitude", 0x0017: "GPSDestBearingRef", 0x0018: "GPSDestBearing", 0x0019: "GPSDestDistanceRef", 0x001A: "GPSDestDistance", 0x001B: "GPSProcessingMethod", 0x001C: "GPSAreaInformation", 0x001D: "GPSDateStamp", 0x001E: "GPSDifferential" }; var StringValues = EXIF.StringValues = { ExposureProgram: { 0: "Not defined", 1: "Manual", 2: "Normal program", 3: "Aperture priority", 4: "Shutter priority", 5: "Creative program", 6: "Action program", 7: "Portrait mode", 8: "Landscape mode" }, MeteringMode: { 0: "Unknown", 1: "Average", 2: "CenterWeightedAverage", 3: "Spot", 4: "MultiSpot", 5: "Pattern", 6: "Partial", 255: "Other" }, LightSource: { 0: "Unknown", 1: "Daylight", 2: "Fluorescent", 3: "Tungsten (incandescent light)", 4: "Flash", 9: "Fine weather", 10: "Cloudy weather", 11: "Shade", 12: "Daylight fluorescent (D 5700 - 7100K)", 13: "Day white fluorescent (N 4600 - 5400K)", 14: "Cool white fluorescent (W 3900 - 4500K)", 15: "White fluorescent (WW 3200 - 3700K)", 17: "Standard light A", 18: "Standard light B", 19: "Standard light C", 20: "D55", 21: "D65", 22: "D75", 23: "D50", 24: "ISO studio tungsten", 255: "Other" }, Flash: { 0x0000: "Flash did not fire", 0x0001: "Flash fired", 0x0005: "Strobe return light not detected", 0x0007: "Strobe return light detected", 0x0009: "Flash fired, compulsory flash mode", 0x000D: "Flash fired, compulsory flash mode, return light not detected", 0x000F: "Flash fired, compulsory flash mode, return light detected", 0x0010: "Flash did not fire, compulsory flash mode", 0x0018: "Flash did not fire, auto mode", 0x0019: "Flash fired, auto mode", 0x001D: "Flash fired, auto mode, return light not detected", 0x001F: "Flash fired, auto mode, return light detected", 0x0020: "No flash function", 0x0041: "Flash fired, red-eye reduction mode", 0x0045: "Flash fired, red-eye reduction mode, return light not detected", 0x0047: "Flash fired, red-eye reduction mode, return light detected", 0x0049: "Flash fired, compulsory flash mode, red-eye reduction mode", 0x004D: "Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected", 0x004F: "Flash fired, compulsory flash mode, red-eye reduction mode, return light detected", 0x0059: "Flash fired, auto mode, red-eye reduction mode", 0x005D: "Flash fired, auto mode, return light not detected, red-eye reduction mode", 0x005F: "Flash fired, auto mode, return light detected, red-eye reduction mode" }, SensingMethod: { 1: "Not defined", 2: "One-chip color area sensor", 3: "Two-chip color area sensor", 4: "Three-chip color area sensor", 5: "Color sequential area sensor", 7: "Trilinear sensor", 8: "Color sequential linear sensor" }, SceneCaptureType: { 0: "Standard", 1: "Landscape", 2: "Portrait", 3: "Night scene" }, SceneType: { 1: "Directly photographed" }, CustomRendered: { 0: "Normal process", 1: "Custom process" }, WhiteBalance: { 0: "Auto white balance", 1: "Manual white balance" }, GainControl: { 0: "None", 1: "Low gain up", 2: "High gain up", 3: "Low gain down", 4: "High gain down" }, Contrast: { 0: "Normal", 1: "Soft", 2: "Hard" }, Saturation: { 0: "Normal", 1: "Low saturation", 2: "High saturation" }, Sharpness: { 0: "Normal", 1: "Soft", 2: "Hard" }, SubjectDistanceRange: { 0: "Unknown", 1: "Macro", 2: "Close view", 3: "Distant view" }, FileSource: { 3: "DSC" }, Components: { 0: "", 1: "Y", 2: "Cb", 3: "Cr", 4: "R", 5: "G", 6: "B" } }; function addEvent(element, event, handler) { if (element.addEventListener) { element.addEventListener(event, handler, false); } else if (element.attachEvent) { element.attachEvent("on" + event, handler); } } function imageHasData(img) { return !!(img.exifdata); } function base64ToArrayBuffer(base64, contentType) { contentType = contentType || base64.match(/^data\:([^\;]+)\;base64,/mi)[1] || ''; // e.g. 'data:image/jpeg;base64,...' => 'image/jpeg' base64 = base64.replace(/^data\:([^\;]+)\;base64,/gmi, ''); var binary = atob(base64); var len = binary.length; var buffer = new ArrayBuffer(len); var view = new Uint8Array(buffer); for (var i = 0; i < len; i++) { view[i] = binary.charCodeAt(i); } return buffer; } function objectURLToBlob(url, callback) { var http = new XMLHttpRequest(); http.open("GET", url, true); http.responseType = "blob"; http.onload = function(e) { if (this.status == 200 || this.status === 0) { callback(this.response); } }; http.send(); } function getImageData(img, callback) { var fileReader = new FileReader(); var handleBinaryFile = function handleBinaryFile(binFile) { var data = findEXIFinJPEG(binFile); var iptcdata = findIPTCinJPEG(binFile); img.exifdata = data || {}; img.iptcdata = iptcdata || {}; if (callback) { callback(img); } }; if (img.src) { if (/^data\:/i.test(img.src)) { // Data URI var arrayBuffer = base64ToArrayBuffer(img.src); handleBinaryFile(arrayBuffer); } else if (/^blob\:/i.test(img.src)) { // Object URL fileReader.onload = function(e) { handleBinaryFile(e.target.result); }; objectURLToBlob(img.src, function(blob) { fileReader.readAsArrayBuffer(blob); }); } else { var http = new XMLHttpRequest(); http.onload = function() { if (this.status == 200 || this.status === 0) { handleBinaryFile(http.response); } else { throw "Could not load image"; } http = null; }; http.open("GET", img.src, true); http.responseType = "arraybuffer"; http.send(null); } } else if (window.FileReader && (img instanceof window.Blob || img instanceof window.File)) { fileReader.onload = function(e) { if (debug) console.log("Got file of length " + e.target.result.byteLength); handleBinaryFile(e.target.result); }; fileReader.readAsArrayBuffer(img); } } function findEXIFinJPEG(file) { var dataView = new DataView(file); if (debug) console.log("Got file of length " + file.byteLength); if ((dataView.getUint8(0) != 0xFF) || (dataView.getUint8(1) != 0xD8)) { if (debug) console.log("Not a valid JPEG"); return false; // not a valid jpeg } var offset = 2, length = file.byteLength, marker; while (offset < length) { if (dataView.getUint8(offset) != 0xFF) { if (debug) console.log("Not a valid marker at offset " + offset + ", found: " + dataView.getUint8(offset)); return false; // not a valid marker, something is wrong } marker = dataView.getUint8(offset + 1); if (debug) console.log(marker); // we could implement handling for other markers here, // but we're only looking for 0xFFE1 for EXIF data if (marker == 225) { if (debug) console.log("Found 0xFFE1 marker"); return readEXIFData(dataView, offset + 4, dataView.getUint16(offset + 2) - 2); // offset += 2 + file.getShortAt(offset+2, true); } else { offset += 2 + dataView.getUint16(offset + 2); } } } function findIPTCinJPEG(file) { var dataView = new DataView(file); if (debug) console.log("Got file of length " + file.byteLength); if ((dataView.getUint8(0) != 0xFF) || (dataView.getUint8(1) != 0xD8)) { if (debug) console.log("Not a valid JPEG"); return false; // not a valid jpeg } var offset = 2, length = file.byteLength; var isFieldSegmentStart = function(dataView, offset) { return ( dataView.getUint8(offset) === 0x38 && dataView.getUint8(offset + 1) === 0x42 && dataView.getUint8(offset + 2) === 0x49 && dataView.getUint8(offset + 3) === 0x4D && dataView.getUint8(offset + 4) === 0x04 && dataView.getUint8(offset + 5) === 0x04 ); }; while (offset < length) { if (isFieldSegmentStart(dataView, offset)) { // Get the length of the name header (which is padded to an even number of bytes) var nameHeaderLength = dataView.getUint8(offset + 7); if (nameHeaderLength % 2 !== 0) nameHeaderLength += 1; // Check for pre photoshop 6 format if (nameHeaderLength === 0) { // Always 4 nameHeaderLength = 4; } var startOffset = offset + 8 + nameHeaderLength; var sectionLength = dataView.getUint16(offset + 6 + nameHeaderLength); return readIPTCData(file, startOffset, sectionLength); } // Not the marker, continue searching offset++; } } var IptcFieldMap = { 0x78: 'caption', 0x6E: 'credit', 0x19: 'keywords', 0x37: 'dateCreated', 0x50: 'byline', 0x55: 'bylineTitle', 0x7A: 'captionWriter', 0x69: 'headline', 0x74: 'copyright', 0x0F: 'category' }; function readIPTCData(file, startOffset, sectionLength) { var dataView = new DataView(file); var data = {}; var fieldValue, fieldName, dataSize, segmentType, segmentSize; var segmentStartPos = startOffset; while (segmentStartPos < startOffset + sectionLength) { if (dataView.getUint8(segmentStartPos) === 0x1C && dataView.getUint8(segmentStartPos + 1) === 0x02) { segmentType = dataView.getUint8(segmentStartPos + 2); if (segmentType in IptcFieldMap) { dataSize = dataView.getInt16(segmentStartPos + 3); segmentSize = dataSize + 5; fieldName = IptcFieldMap[segmentType]; fieldValue = getStringFromDB(dataView, segmentStartPos + 5, dataSize); // Check if we already stored a value with this name if (data.hasOwnProperty(fieldName)) { // Value already stored with this name, create multivalue field if (data[fieldName] instanceof Array) { data[fieldName].push(fieldValue); } else { data[fieldName] = [data[fieldName], fieldValue]; } } else { data[fieldName] = fieldValue; } } } segmentStartPos++; } return data; } function readTags(file, tiffStart, dirStart, strings, bigEnd) { var entries = file.getUint16(dirStart, !bigEnd), tags = {}, entryOffset, tag, i; for (i = 0; i < entries; i++) { entryOffset = dirStart + i * 12 + 2; tag = strings[file.getUint16(entryOffset, !bigEnd)]; if (!tag && debug) console.log("Unknown tag: " + file.getUint16(entryOffset, !bigEnd)); tags[tag] = readTagValue(file, entryOffset, tiffStart, dirStart, bigEnd); } return tags; } function readTagValue(file, entryOffset, tiffStart, dirStart, bigEnd) { var type = file.getUint16(entryOffset + 2, !bigEnd), numValues = file.getUint32(entryOffset + 4, !bigEnd), valueOffset = file.getUint32(entryOffset + 8, !bigEnd) + tiffStart, offset, vals, val, n, numerator, denominator; switch (type) { case 1: // byte, 8-bit unsigned int case 7: // undefined, 8-bit byte, value depending on field if (numValues == 1) { return file.getUint8(entryOffset + 8, !bigEnd); } else { offset = numValues > 4 ? valueOffset : (entryOffset + 8); vals = []; for (n = 0; n < numValues; n++) { vals[n] = file.getUint8(offset + n); } return vals; } break; case 2: // ascii, 8-bit byte offset = numValues > 4 ? valueOffset : (entryOffset + 8); return getStringFromDB(file, offset, numValues - 1); case 3: // short, 16 bit int if (numValues == 1) { return file.getUint16(entryOffset + 8, !bigEnd); } else { offset = numValues > 2 ? valueOffset : (entryOffset + 8); vals = []; for (n = 0; n < numValues; n++) { vals[n] = file.getUint16(offset + 2 * n, !bigEnd); } return vals; } break; case 4: // long, 32 bit int if (numValues == 1) { return file.getUint32(entryOffset + 8, !bigEnd); } else { vals = []; for (n = 0; n < numValues; n++) { vals[n] = file.getUint32(valueOffset + 4 * n, !bigEnd); } return vals; } break; case 5: // rational = two long values, first is numerator, second is denominator if (numValues == 1) { numerator = file.getUint32(valueOffset, !bigEnd); denominator = file.getUint32(valueOffset + 4, !bigEnd); val = numerator / denominator; val.numerator = numerator; val.denominator = denominator; return val; } else { vals = []; for (n = 0; n < numValues; n++) { numerator = file.getUint32(valueOffset + 8 * n, !bigEnd); denominator = file.getUint32(valueOffset + 4 + 8 * n, !bigEnd); vals[n] = numerator / denominator; vals[n].numerator = numerator; vals[n].denominator = denominator; } return vals; } break; case 9: // slong, 32 bit signed int if (numValues == 1) { return file.getInt32(entryOffset + 8, !bigEnd); } else { vals = []; for (n = 0; n < numValues; n++) { vals[n] = file.getInt32(valueOffset + 4 * n, !bigEnd); } return vals; } break; case 10: // signed rational, two slongs, first is numerator, second is denominator if (numValues == 1) { return file.getInt32(valueOffset, !bigEnd) / file.getInt32(valueOffset + 4, !bigEnd); } else { vals = []; for (n = 0; n < numValues; n++) { vals[n] = file.getInt32(valueOffset + 8 * n, !bigEnd) / file.getInt32(valueOffset + 4 + 8 * n, !bigEnd); } return vals; } } } function getStringFromDB(buffer, start, length) { var outstr = ""; var n; for (n = start; n < start + length; n++) { outstr += String.fromCharCode(buffer.getUint8(n)); } return outstr; } function readEXIFData(file, start) { if (getStringFromDB(file, start, 4) != "Exif") { if (debug) console.log("Not valid EXIF data! " + getStringFromDB(file, start, 4)); return false; } var bigEnd, tags, tag, exifData, gpsData, tiffOffset = start + 6; // test for TIFF validity and endianness if (file.getUint16(tiffOffset) == 0x4949) { bigEnd = false; } else if (file.getUint16(tiffOffset) == 0x4D4D) { bigEnd = true; } else { if (debug) console.log("Not valid TIFF data! (no 0x4949 or 0x4D4D)"); return false; } if (file.getUint16(tiffOffset + 2, !bigEnd) != 0x002A) { if (debug) console.log("Not valid TIFF data! (no 0x002A)"); return false; } var firstIFDOffset = file.getUint32(tiffOffset + 4, !bigEnd); if (firstIFDOffset < 0x00000008) { if (debug) console.log("Not valid TIFF data! (First offset less than 8)", file.getUint32(tiffOffset + 4, !bigEnd)); return false; } tags = readTags(file, tiffOffset, tiffOffset + firstIFDOffset, TiffTags, bigEnd); if (tags.ExifIFDPointer) { exifData = readTags(file, tiffOffset, tiffOffset + tags.ExifIFDPointer, ExifTags, bigEnd); for (tag in exifData) { switch (tag) { case "LightSource": case "Flash": case "MeteringMode": case "ExposureProgram": case "SensingMethod": case "SceneCaptureType": case "SceneType": case "CustomRendered": case "WhiteBalance": case "GainControl": case "Contrast": case "Saturation": case "Sharpness": case "SubjectDistanceRange": case "FileSource": exifData[tag] = StringValues[tag][exifData[tag]]; break; case "ExifVersion": case "FlashpixVersion": exifData[tag] = String.fromCharCode(exifData[tag][0], exifData[tag][1], exifData[tag][2], exifData[tag][3]); break; case "ComponentsConfiguration": exifData[tag] = StringValues.Components[exifData[tag][0]] + StringValues.Components[exifData[tag][1]] + StringValues.Components[exifData[tag][2]] + StringValues.Components[exifData[tag][3]]; break; } tags[tag] = exifData[tag]; } } if (tags.GPSInfoIFDPointer) { gpsData = readTags(file, tiffOffset, tiffOffset + tags.GPSInfoIFDPointer, GPSTags, bigEnd); for (tag in gpsData) { switch (tag) { case "GPSVersionID": gpsData[tag] = gpsData[tag][0] + "." + gpsData[tag][1] + "." + gpsData[tag][2] + "." + gpsData[tag][3]; break; } tags[tag] = gpsData[tag]; } } return tags; } EXIF.getData = function(img, callback) { if ((img instanceof Image || img instanceof HTMLImageElement) && !img.complete) return false; if (!imageHasData(img)) { getImageData(img, callback); } else { if (callback) { callback(img); } } return true; }; EXIF.getTag = function(img, tag) { if (!imageHasData(img)) return; return img.exifdata[tag]; }; EXIF.getAllTags = function(img) { if (!imageHasData(img)) return {}; var a, data = img.exifdata, tags = {}; for (a in data) { if (data.hasOwnProperty(a)) { tags[a] = data[a]; } } return tags; }; EXIF.pretty = function(img) { if (!imageHasData(img)) return ""; var a, data = img.exifdata, strPretty = ""; for (a in data) { if (data.hasOwnProperty(a)) { if (typeof data[a] == "object") { if (data[a] instanceof Number) { strPretty += a + " : " + data[a] + " [" + data[a].numerator + "/" + data[a].denominator + "]\r\n"; } else { strPretty += a + " : [" + data[a].length + " values]\r\n"; } } else { strPretty += a + " : " + data[a] + "\r\n"; } } } return strPretty; }; EXIF.readFromBinaryFile = function(file) { return findEXIFinJPEG(file); }; if (typeof define === 'function' && define.amd) { define('exif-js', [], function() { return EXIF; }); } }.call(this)); },{}],4:[function(require,module,exports){ /** * Expose `isUrl`. */ module.exports = isUrl; /** * Matcher. */ var matcher = /^(?:\w+:)?\/\/([^\s\.]+\.\S{2}|localhost[\:?\d]*)\S*$/; /** * Loosely validate a URL `string`. * * @param {String} string * @return {Boolean} */ function isUrl(string){ return matcher.test(string); } },{}],5:[function(require,module,exports){ /* Ported to JavaScript by Lazar Laszlo 2011 [email protected], www.lazarsoft.info */ /* * * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ !(function() { 'use strict'; var qrcode = require('./qrcode'); function AlignmentPattern(posX, posY, estimatedModuleSize) { this.x=posX; this.y=posY; this.count = 1; this.estimatedModuleSize = estimatedModuleSize; this.__defineGetter__("EstimatedModuleSize", function() { return this.estimatedModuleSize; }); this.__defineGetter__("Count", function() { return this.count; }); this.__defineGetter__("X", function() { return Math.floor(this.x); }); this.__defineGetter__("Y", function() { return Math.floor(this.y); }); this.incrementCount = function() { this.count++; } this.aboutEquals=function( moduleSize, i, j) { if (Math.abs(i - this.y) <= moduleSize && Math.abs(j - this.x) <= moduleSize) { var moduleSizeDiff = Math.abs(moduleSize - this.estimatedModuleSize); return moduleSizeDiff <= 1.0 || moduleSizeDiff / this.estimatedModuleSize <= 1.0; } return false; } } var AlignmentPatternFinder = module.exports = function ( image, startX, startY, width, height, moduleSize, resultPointCallback) { this.image = image; this.possibleCenters = new Array(); this.startX = startX; this.startY = startY; this.width = width; this.height = height; this.moduleSize = moduleSize; this.crossCheckStateCount = new Array(0,0,0); this.resultPointCallback = resultPointCallback; this.centerFromEnd=function(stateCount, end) { return (end - stateCount[2]) - stateCount[1] / 2.0; } this.foundPatternCross = function(stateCount) { var moduleSize = this.moduleSize; var maxVariance = moduleSize / 2.0; for (var i = 0; i < 3; i++) { if (Math.abs(moduleSize - stateCount[i]) >= maxVariance) { return false; } } return true; } this.crossCheckVertical=function( startI, centerJ, maxCount, originalStateCountTotal) { var image = this.image; var maxI = qrcode.height; var stateCount = this.crossCheckStateCount; stateCount[0] = 0; stateCount[1] = 0; stateCount[2] = 0; // Start counting up from center var i = startI; while (i >= 0 && image[centerJ + i*qrcode.width] && stateCount[1] <= maxCount) { stateCount[1]++; i--; } // If already too many modules in this state or ran off the edge: if (i < 0 || stateCount[1] > maxCount) { return NaN; } while (i >= 0 && !image[centerJ + i*qrcode.width] && stateCount[0] <= maxCount) { stateCount[0]++; i--; } if (stateCount[0] > maxCount) { return NaN; } // Now also count down from center i = startI + 1; while (i < maxI && image[centerJ + i*qrcode.width] && stateCount[1] <= maxCount) { stateCount[1]++; i++; } if (i == maxI || stateCount[1] > maxCount) { return NaN; } while (i < maxI && !image[centerJ + i*qrcode.width] && stateCount[2] <= maxCount) { stateCount[2]++; i++; } if (stateCount[2] > maxCount) { return NaN; } var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2]; if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) { return NaN; } return this.foundPatternCross(stateCount)?this.centerFromEnd(stateCount, i):NaN; } this.handlePossibleCenter=function( stateCount, i, j) { var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2]; var centerJ = this.centerFromEnd(stateCount, j); var centerI = this.crossCheckVertical(i, Math.floor (centerJ), 2 * stateCount[1], stateCountTotal); if (!isNaN(centerI)) { var estimatedModuleSize = (stateCount[0] + stateCount[1] + stateCount[2]) / 3.0; var max = this.possibleCenters.length; for (var index = 0; index < max; index++) { var center = this.possibleCenters[index]; // Look for about the same center and module size: if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) { return new AlignmentPattern(centerJ, centerI, estimatedModuleSize); } } // Hadn't found this before; save it var point = new AlignmentPattern(centerJ, centerI, estimatedModuleSize); this.possibleCenters.push(point); if (this.resultPointCallback != null) { this.resultPointCallback.foundPossibleResultPoint(point); } } return null; } this.find = function() { var startX = this.startX; var height = this.height; var maxJ = startX + width; var middleI = startY + (height >> 1); // We are looking for black/white/black modules in 1:1:1 ratio; // this tracks the number of black/white/black modules seen so far var stateCount = new Array(0,0,0); for (var iGen = 0; iGen < height; iGen++) { // Search from middle outwards var i = middleI + ((iGen & 0x01) == 0?((iGen + 1) >> 1):- ((iGen + 1) >> 1)); stateCount[0] = 0; stateCount[1] = 0; stateCount[2] = 0; var j = startX; // Burn off leading white pixels before anything else; if we start in the middle of // a white run, it doesn't make sense to count its length, since we don't know if the // white run continued to the left of the start point while (j < maxJ && !image[j + qrcode.width* i]) { j++; } var currentState = 0; while (j < maxJ) { if (image[j + i*qrcode.width]) { // Black pixel if (currentState == 1) { // Counting black pixels stateCount[currentState]++; } else { // Counting white pixels if (currentState == 2) { // A winner? if (this.foundPatternCross(stateCount)) { // Yes var confirmed = this.handlePossibleCenter(stateCount, i, j); if (confirmed != null) { return confirmed; } } stateCount[0] = stateCount[2]; stateCount[1] = 1; stateCount[2] = 0; currentState = 1; } else { stateCount[++currentState]++; } } } else { // White pixel if (currentState == 1) { // Counting black pixels currentState++; } stateCount[currentState]++; } j++; } if (this.foundPatternCross(stateCount)) { var confirmed = this.handlePossibleCenter(stateCount, i, maxJ); if (confirmed != null) { return confirmed; } } } // Hmm, nothing we saw was observed and confirmed twice. If we had // any guess at all, return it. if (!(this.possibleCenters.length == 0)) { return this.possibleCenters[0]; } throw "Couldn't find enough alignment patterns"; } } }).call({}); },{"./qrcode":19}],6:[function(require,module,exports){ /* Ported to JavaScript by Lazar Laszlo 2011 [email protected], www.lazarsoft.info */ /* * * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ !(function() { 'use strict'; var URShift = require('./urshift'); module.exports = function ( width, height) { if(!height) height=width; if (width < 1 || height < 1) { throw "Both dimensions must be greater than 0"; } this.width = width; this.height = height; var rowSize = width >> 5; if ((width & 0x1f) != 0) { rowSize++; } this.rowSize = rowSize; this.bits = new Array(rowSize * height); for(var i=0;i<this.bits.length;i++) this.bits[i]=0; this.__defineGetter__("Width", function() { return this.width; }); this.__defineGetter__("Height", function() { return this.height; }); this.__defineGetter__("Dimension", function() { if (this.width != this.height) { throw "Can't call getDimension() on a non-square matrix"; } return this.width; }); this.get_Renamed=function( x, y) { var offset = y * this.rowSize + (x >> 5); return ((URShift(this.bits[offset], (x & 0x1f))) & 1) != 0; } this.set_Renamed=function( x, y) { var offset = y * this.rowSize + (x >> 5); this.bits[offset] |= 1 << (x & 0x1f); } this.flip=function( x, y) { var offset = y * this.rowSize + (x >> 5); this.bits[offset] ^= 1 << (x & 0x1f); } this.clear=function() { var max = this.bits.length; for (var i = 0; i < max; i++) { this.bits[i] = 0; } } this.setRegion=function( left, top, width, height) { if (top < 0 || left < 0) { throw "Left and top must be nonnegative"; } if (height < 1 || width < 1) { throw "Height and width must be at least 1"; } var right = left + width; var bottom = top + height; if (bottom > this.height || right > this.width) { throw "The region must fit inside the matrix"; } for (var y = top; y < bottom; y++) { var offset = y * this.rowSize; for (var x = left; x < right; x++) { this.bits[offset + (x >> 5)] |= 1 << (x & 0x1f); } } } } }).call({}); },{"./urshift":21}],7:[function(require,module,exports){ /* Ported to JavaScript by Lazar Laszlo 2011 [email protected], www.lazarsoft.info */ /* * * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ !(function() { 'use strict'; var DataMaskForReference = require('./datamask'); var FormatInformation = require('./formatinf'); var Version = require('./version'); module.exports = function BitMatrixParser(bitMatrix) { var dimension = bitMatrix.Dimension; if (dimension < 21 || (dimension & 0x03) != 1) { throw "Error BitMatrixParser"; } this.bitMatrix = bitMatrix; this.parsedVersion = null; this.parsedFormatInfo = null; this.copyBit=function( i, j, versionBits) { return this.bitMatrix.get_Renamed(i, j)?(versionBits << 1) | 0x1:versionBits << 1; } this.readFormatInformation=function() { if (this.parsedFormatInfo != null) { return this.parsedFormatInfo; } // Read top-left format info bits var formatInfoBits = 0; for (var i = 0; i < 6; i++) { formatInfoBits = this.copyBit(i, 8, formatInfoBits); } // .. and skip a bit in the timing pattern ... formatInfoBits = this.copyBit(7, 8, formatInfoBits); formatInfoBits = this.copyBit(8, 8, formatInfoBits); formatInfoBits = this.copyBit(8, 7, formatInfoBits); // .. and skip a bit in the timing pattern ... for (var j = 5; j >= 0; j--) { formatInfoBits = this.copyBit(8, j, formatInfoBits); } this.parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits); if (this.parsedFormatInfo != null) { return this.parsedFormatInfo; } // Hmm, failed. Try the top-right/bottom-left pattern var dimension = this.bitMatrix.Dimension; formatInfoBits = 0; var iMin = dimension - 8; for (var i = dimension - 1; i >= iMin; i--) { formatInfoBits = this.copyBit(i, 8, formatInfoBits); } for (var j = dimension - 7; j < dimension; j++) { formatInfoBits = this.copyBit(8, j, formatInfoBits); } this.parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits); if (this.parsedFormatInfo != null) { return this.parsedFormatInfo; } throw "Error readFormatInformation"; } this.readVersion=function() { if (this.parsedVersion != null) { return this.parsedVersion; } var dimension = this.bitMatrix.Dimension; var provisionalVersion = (dimension - 17) >> 2; if (provisionalVersion <= 6) { return Version.getVersionForNumber(provisionalVersion); } // Read top-right version info: 3 wide by 6 tall var versionBits = 0; var ijMin = dimension - 11; for (var j = 5; j >= 0; j--) { for (var i = dimension - 9; i >= ijMin; i--) { versionBits = this.copyBit(i, j, versionBits); } } this.parsedVersion = Version.decodeVersionInformation(versionBits); if (this.parsedVersion != null && this.parsedVersion.DimensionForVersion == dimension) { return this.parsedVersion; } // Hmm, failed. Try bottom left: 6 wide by 3 tall versionBits = 0; for (var i = 5; i >= 0; i--) { for (var j = dimension - 9; j >= ijMin; j--) { versionBits = this.copyBit(i, j, versionBits); } } this.parsedVersion = Version.decodeVersionInformation(versionBits); if (this.parsedVersion != null && this.parsedVersion.DimensionForVersion == dimension) { return this.parsedVersion; } throw "Error readVersion"; } this.readCodewords=function() { var formatInfo = this.readFormatInformation(); var version = this.readVersion(); // Get the data mask for the format used in this QR Code. This will exclude // some bits from reading as we wind through the bit matrix. var dataMask = DataMaskForReference( formatInfo.DataMask); var dimension = this.bitMatrix.Dimension; dataMask.unmaskBitMatrix(this.bitMatrix, dimension); var functionPattern = version.buildFunctionPattern(); var readingUp = true; var result = new Array(version.TotalCodewords); var resultOffset = 0; var currentByte = 0; var bitsRead = 0; // Read columns in pairs, from right to left for (var j = dimension - 1; j > 0; j -= 2) { if (j == 6) { // Skip whole column with vertical alignment pattern; // saves time and makes the other code proceed more cleanly j--; } // Read alternatingly from bottom to top then top to bottom for (var count = 0; count < dimension; count++) { var i = readingUp?dimension - 1 - count:count; for (var col = 0; col < 2; col++) { // Ignore bits covered by the function pattern if (!functionPattern.get_Renamed(j - col, i)) { // Read a bit bitsRead++; currentByte <<= 1; if (this.bitMatrix.get_Renamed(j - col, i)) { currentByte |= 1; } // If we've made a whole byte, save it off if (bitsRead == 8) { result[resultOffset++] = currentByte; bitsRead = 0; currentByte = 0; } } } } readingUp ^= true; // readingUp = !readingUp; // switch directions } if (resultOffset != version.TotalCodewords) { throw "Error readCodewords"; } return result; } } }).call({}); },{"./datamask":10,"./formatinf":15,"./version":22}],8:[function(require,module,exports){ /* Ported to JavaScript by Lazar Laszlo 2011 [email protected], www.lazarsoft.info */ /* * * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ !(function() { 'use strict'; var DataBlock = module.exports = function (numDataCodewords, codewords) { this.numDataCodewords = numDataCodewords; this.codewords = codewords; this.__defineGetter__("NumDataCodewords", function() { return this.numDataCodewords; }); this.__defineGetter__("Codewords", function() { return this.codewords; }); } DataBlock.getDataBlocks=function(rawCodewords, version, ecLevel) { if (rawCodewords.length != version.TotalCodewords) { throw "ArgumentException"; } // Figure out the number and size of data blocks used by this version and // error correction level var ecBlocks = version.getECBlocksForLevel(ecLevel); // First count the total number of data blocks var totalBlocks = 0; var ecBlockArray = ecBlocks.getECBlocks(); for (var i = 0; i < ecBlockArray.length; i++) { totalBlocks += ecBlockArray[i].Count; } // Now establish DataBlocks of the appropriate size and number of data codewords var result = new Array(totalBlocks); var numResultBlocks = 0; for (var j = 0; j < ecBlockArray.length; j++) { var ecBlock = ecBlockArray[j]; for (var i = 0; i < ecBlock.Count; i++) { var numDataCodewords = ecBlock.DataCodewords; var numBlockCodewords = ecBlocks.ECCodewordsPerBlock + numDataCodewords; result[numResultBlocks++] = new DataBlock(numDataCodewords, new Array(numBlockCodewords)); } } // All blocks have the same amount of data, except that the last n // (where n may be 0) have 1 more byte. Figure out where these start. var shorterBlocksTotalCodewords = result[0].codewords.length; var longerBlocksStartAt = result.length - 1; while (longerBlocksStartAt >= 0) { var numCodewords = result[longerBlocksStartAt].codewords.length; if (numCodewords == shorterBlocksTotalCodewords) { break; } longerBlocksStartAt--; } longerBlocksStartAt++; var shorterBlocksNumDataCodewords = shorterBlocksTotalCodewords - ecBlocks.ECCodewordsPerBlock; // The last elements of result may be 1 element longer; // first fill out as many elements as all of them have var rawCodewordsOffset = 0; for (var i = 0; i < shorterBlocksNumDataCodewords; i++) { for (var j = 0; j < numResultBlocks; j++) { result[j].codewords[i] = rawCodewords[rawCodewordsOffset++]; } } // Fill out the last data block in the longer ones for (var j = longerBlocksStartAt; j < numResultBlocks; j++) { result[j].codewords[shorterBlocksNumDataCodewords] = rawCodewords[rawCodewordsOffset++]; } // Now add in error correction blocks var max = result[0].codewords.length; for (var i = shorterBlocksNumDataCodewords; i < max; i++) { for (var j = 0; j < numResultBlocks; j++) { var iOffset = j < longerBlocksStartAt?i:i + 1; result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset++]; } } return result; } }).call({}); },{}],9:[function(require,module,exports){ /* Ported to JavaScript by Lazar Laszlo 2011 [email protected], www.lazarsoft.info */ /* * * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ !(function() { 'use strict'; var qrcode = require('./qrcode'); module.exports = function QRCodeDataBlockReader(blocks, version, numErrorCorrectionCode) { this.blockPointer = 0; this.bitPointer = 7; this.dataLength = 0; this.blocks = blocks; this.numErrorCorrectionCode = numErrorCorrectionCode; if (version <= 9) this.dataLengthMode = 0; else if (version >= 10 && version <= 26) this.dataLengthMode = 1; else if (version >= 27 && version <= 40) this.dataLengthMode = 2; this.getNextBits = function( numBits) { var bits = 0; if (numBits < this.bitPointer + 1) { // next word fits into current data block var mask = 0; for (var i = 0; i < numBits; i++) { mask += (1 << i); } mask <<= (this.bitPointer - numBits + 1); bits = (this.blocks[this.blockPointer] & mask) >> (this.bitPointer - numBits + 1); this.bitPointer -= numBits; return bits; } else if (numBits < this.bitPointer + 1 + 8) { // next word crosses 2 data blocks var mask1 = 0; for (var i = 0; i < this.bitPointer + 1; i++) { mask1 += (1 << i); } bits = (this.blocks[this.blockPointer] & mask1) << (numBits - (this.bitPointer + 1)); this.blockPointer++; bits += ((this.blocks[this.blockPointer]) >> (8 - (numBits - (this.bitPointer + 1)))); this.bitPointer = this.bitPointer - numBits % 8; if (this.bitPointer < 0) { this.bitPointer = 8 + this.bitPointer; } return bits; } else if (numBits < this.bitPointer + 1 + 16) { // next word crosses 3 data blocks var mask1 = 0; // mask of first block var mask3 = 0; // mask of 3rd block //bitPointer + 1 : number of bits of the 1st block //8 : number of the 2nd block (note that use already 8bits because next word uses 3 data blocks) //numBits - (bitPointer + 1 + 8) : number of bits of the 3rd block for (var i = 0; i < this.bitPointer + 1; i++) { mask1 += (1 << i); } var bitsFirstBlock = (this.blocks[this.blockPointer] & mask1) << (numBits - (this.bitPointer + 1)); this.blockPointer++; var bitsSecondBlock = this.blocks[this.blockPointer] << (numBits - (this.bitPointer + 1 + 8)); this.blockPointer++; for (var i = 0; i < numBits - (this.bitPointer + 1 + 8); i++) { mask3 += (1 << i); } mask3 <<= 8 - (numBits - (this.bitPointer + 1 + 8)); var bitsThirdBlock = (this.blocks[this.blockPointer] & mask3) >> (8 - (numBits - (this.bitPointer + 1 + 8))); bits = bitsFirstBlock + bitsSecondBlock + bitsThirdBlock; this.bitPointer = this.bitPointer - (numBits - 8) % 8; if (this.bitPointer < 0) { this.bitPointer = 8 + this.bitPointer; } return bits; } else { return 0; } } this.NextMode=function() { if ((this.blockPointer > this.blocks.length - this.numErrorCorrectionCode - 2)) return 0; else return this.getNextBits(4); } this.getDataLength=function( modeIndicator) { var index = 0; while (true) { if ((modeIndicator >> index) == 1) break; index++; } return this.getNextBits(qrcode.sizeOfDataLengthInfo[this.dataLengthMode][index]); } this.getRomanAndFigureString=function( dataLength) { var length = dataLength; var intData = 0; var strData = ""; var tableRomanAndFigure = new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ', '$', '%', '*', '+', '-', '.', '/', ':'); do { if (length > 1) { intData = this.getNextBits(11); var firstLetter = Math.floor(intData / 45); var secondLetter = intData % 45; strData += tableRomanAndFigure[firstLetter]; strData += tableRomanAndFigure[secondLetter]; length -= 2; } else if (length == 1) { intData = this.getNextBits(6); strData += tableRomanAndFigure[intData]; length -= 1; } } while (length > 0); return strData; } this.getFigureString=function( dataLength) { var length = dataLength; var intData = 0; var strData = ""; do { if (length >= 3) { intData = this.getNextBits(10); if (intData < 100) strData += "0"; if (intData < 10) strData += "0"; length -= 3; } else if (length == 2) { intData = this.getNextBits(7); if (intData < 10) strData += "0"; length -= 2; } else if (length == 1) { intData = this.getNextBits(4); length -= 1; } strData += intData; } while (length > 0); return strData; } this.get8bitByteArray=function( dataLength) { var length = dataLength; var intData = 0; var output = new Array(); do { intData = this.getNextBits(8); output.push( intData); length--; } while (length > 0); return output; } this.getKanjiString=function( dataLength) { var length = dataLength; var intData = 0; var unicodeString = ""; do { intData = getNextBits(13); var lowerByte = intData % 0xC0; var higherByte = intData / 0xC0; var tempWord = (higherByte << 8) + lowerByte; var shiftjisWord = 0; if (tempWord + 0x8140 <= 0x9FFC) { // between 8140 - 9FFC on Shift_JIS character set shiftjisWord = tempWord + 0x8140; } else { // between E040 - EBBF on Shift_JIS character set shiftjisWord = tempWord + 0xC140; } //var tempByte = new Array(0,0); //tempByte[0] = (sbyte) (shiftjisWord >> 8); //tempByte[1] = (sbyte) (shiftjisWord & 0xFF); //unicodeString += new String(SystemUtils.ToCharArray(SystemUtils.ToByteArray(tempByte))); unicodeString += String.fromCharCode(shiftjisWord); length--; } while (length > 0); return unicodeString; } this.__defineGetter__("DataByte", function() { var output = new Array(); var MODE_NUMBER = 1; var MODE_ROMAN_AND_NUMBER = 2; var MODE_8BIT_BYTE = 4; var MODE_KANJI = 8; do { var mode = this.NextMode(); //canvas.println("mode: " + mode); if (mode == 0) { if (output.length > 0) break; else throw "Empty data block"; } //if (mode != 1 && mode != 2 && mode != 4 && mode != 8) // break; //} if (mode != MODE_NUMBER && mode != MODE_ROMAN_AND_NUMBER && mode != MODE_8BIT_BYTE && mode != MODE_KANJI) { /* canvas.println("Invalid mode: " + mode); mode = guessMode(mode); canvas.println("Guessed mode: " + mode); */ throw "Invalid mode: " + mode + " in (block:" + this.blockPointer + " bit:" + this.bitPointer + ")"; } var dataLength = this.getDataLength(mode); if (dataLength < 1) throw "Invalid data length: " + dataLength; //canvas.println("length: " + dataLength); switch (mode) { case MODE_NUMBER: //canvas.println("Mode: Figure"); var temp_str = this.getFigureString(dataLength); var ta = new Array(temp_str.length); for(var j=0;j<temp_str.length;j++) ta[j]=temp_str.charCodeAt(j); output.push(ta); break; case MODE_ROMAN_AND_NUMBER: //canvas.println("Mode: Roman&Figure"); var temp_str = this.getRomanAndFigureString(dataLength); var ta = new Array(temp_str.length); for(var j=0;j<temp_str.length;j++) ta[j]=temp_str.charCodeAt(j); output.push(ta ); //output.Write(SystemUtils.ToByteArray(temp_sbyteArray2), 0, temp_sbyteArray2.Length); break; case MODE_8BIT_BYTE: //canvas.println("Mode: 8bit Byte"); //sbyte[] temp_sbyteArray3; var temp_sbyteArray3 = this.get8bitByteArray(dataLength); output.push(temp_sbyteArray3); //output.Write(SystemUtils.ToByteArray(temp_sbyteArray3), 0, temp_sbyteArray3.Length); break; case MODE_KANJI: //canvas.println("Mode: Kanji"); //sbyte[] temp_sbyteArray4; //temp_sbyteArray4 = SystemUtils.ToSByteArray(SystemUtils.ToByteArray(getKanjiString(dataLength))); //output.Write(SystemUtils.ToByteArray(temp_sbyteArray4), 0, temp_sbyteArray4.Length); var temp_str = this.getKanjiString(dataLength); output.push(temp_str); break; } // //canvas.println("DataLength: " + dataLength); //Console.out.println(dataString); } while (true); return output; }); } }).call({}); },{"./qrcode":19}],10:[function(require,module,exports){ /* Ported to JavaScript by Lazar Laszlo 2011 [email protected], www.lazarsoft.info */ /* * * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ !(function() { 'use strict'; var URShift = require('./urshift'); var DataMask = {}; module.exports = function(reference) { if (reference < 0 || reference > 7) { throw "System.ArgumentException"; } return DataMask.DATA_MASKS[reference]; } function DataMask000() { this.unmaskBitMatrix=function(bits, dimension) { for (var i = 0; i < dimension; i++) { for (var j = 0; j < dimension; j++) { if (this.isMasked(i, j)) { bits.flip(j, i); } } } } this.isMasked=function( i, j) { return ((i + j) & 0x01) == 0; } } function DataMask001() { this.unmaskBitMatrix=function(bits, dimension) { for (var i = 0; i < dimension; i++) { for (var j = 0; j < dimension; j++) { if (this.isMasked(i, j)) { bits.flip(j, i); } } } } this.isMasked=function( i, j) { return (i & 0x01) == 0; } } function DataMask010() { this.unmaskBitMatrix=function(bits, dimension) { for (var i = 0; i < dimension; i++) { for (var j = 0; j < dimension; j++) { if (this.isMasked(i, j)) { bits.flip(j, i); } } } } this.isMasked=function( i, j) { return j % 3 == 0; } } function DataMask011() { this.unmaskBitMatrix=function(bits, dimension) { for (var i = 0; i < dimension; i++) { for (var j = 0; j < dimension; j++) { if (this.isMasked(i, j)) { bits.flip(j, i); } } } } this.isMasked=function( i, j) { return (i + j) % 3 == 0; } } function DataMask100() { this.unmaskBitMatrix=function(bits, dimension) { for (var i = 0; i < dimension; i++) { for (var j = 0; j < dimension; j++) { if (this.isMasked(i, j)) { bits.flip(j, i); } } } } this.isMasked=function( i, j) { return (((URShift(i, 1)) + (j / 3)) & 0x01) == 0; } } function DataMask101() { this.unmaskBitMatrix=function(bits, dimension) { for (var i = 0; i < dimension; i++) { for (var j = 0; j < dimension; j++) { if (this.isMasked(i, j)) { bits.flip(j, i); } } } } this.isMasked=function( i, j) { var temp = i * j; return (temp & 0x01) + (temp % 3) == 0; } } function DataMask110() { this.unmaskBitMatrix=function(bits, dimension) { for (var i = 0; i < dimension; i++) { for (var j = 0; j < dimension; j++) { if (this.isMasked(i, j)) { bits.flip(j, i); } } } } this.isMasked=function( i, j) { var temp = i * j; return (((temp & 0x01) + (temp % 3)) & 0x01) == 0; } } function DataMask111() { this.unmaskBitMatrix=function(bits, dimension) { for (var i = 0; i < dimension; i++) { for (var j = 0; j < dimension; j++) { if (this.isMasked(i, j)) { bits.flip(j, i); } } } } this.isMasked=function( i, j) { return ((((i + j) & 0x01) + ((i * j) % 3)) & 0x01) == 0; } } DataMask.DATA_MASKS = new Array(new DataMask000(), new DataMask001(), new DataMask010(), new DataMask011(), new DataMask100(), new DataMask101(), new DataMask110(), new DataMask111()); }).call({}); },{"./urshift":21}],11:[function(require,module,exports){ /* Ported to JavaScript by Lazar Laszlo 2011 [email protected], www.lazarsoft.info */ /* * * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ !(function() { 'use strict'; var GF256 = require('./gf256'); var DataBlock = require('./datablock'); var BitMatrixParser = require('./bmparser'); var ReedSolomonDecoder = require('./rsdecoder'); var QRCodeDataBlockReader = require('./databr'); var Decoder = module.exports = {}; Decoder.rsDecoder = new ReedSolomonDecoder(GF256.QR_CODE_FIELD); Decoder.correctErrors=function( codewordBytes, numDataCodewords) { var numCodewords = codewordBytes.length; // First read into an array of ints var codewordsInts = new Array(numCodewords); for (var i = 0; i < numCodewords; i++) { codewordsInts[i] = codewordBytes[i] & 0xFF; } var numECCodewords = codewordBytes.length - numDataCodewords; try { Decoder.rsDecoder.decode(codewordsInts, numECCodewords); //var corrector = new ReedSolomon(codewordsInts, numECCodewords); //corrector.correct(); } catch ( rse) { throw rse; } // Copy back into array of bytes -- only need to worry about the bytes that were data // We don't care about errors in the error-correction codewords for (var i = 0; i < numDataCodewords; i++) { codewordBytes[i] = codewordsInts[i]; } } Decoder.decode=function(bits) { var parser = new BitMatrixParser(bits); var version = parser.readVersion(); var ecLevel = parser.readFormatInformation().ErrorCorrectionLevel; // Read codewords var codewords = parser.readCodewords(); // Separate into data blocks var dataBlocks = DataBlock.getDataBlocks(codewords, version, ecLevel); // Count total number of data bytes var totalBytes = 0; for (var i = 0; i < dataBlocks.length; i++) { totalBytes += dataBlocks[i].NumDataCodewords; } var resultBytes = new Array(totalBytes); var resultOffset = 0; // Error-correct and copy data blocks together into a stream of bytes for (var j = 0; j < dataBlocks.length; j++) { var dataBlock = dataBlocks[j]; var codewordBytes = dataBlock.Codewords; var numDataCodewords = dataBlock.NumDataCodewords; Decoder.correctErrors(codewordBytes, numDataCodewords); for (var i = 0; i < numDataCodewords; i++) { resultBytes[resultOffset++] = codewordBytes[i]; } } // Decode the contents of that stream of bytes var reader = new QRCodeDataBlockReader(resultBytes, version.VersionNumber, ecLevel.Bits); return reader; //return DecodedBitStreamParser.decode(resultBytes, version, ecLevel); } }).call({}); },{"./bmparser":7,"./datablock":8,"./databr":9,"./gf256":16,"./rsdecoder":20}],12:[function(require,module,exports){ /* Ported to JavaScript by Lazar Laszlo 2011 [email protected], www.lazarsoft.info */ /* * * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ !(function() { 'use strict'; var AlignmentPatternFinder = require('./alignpat'); var FinderPatternFinder = require('./findpat'); var GridSampler = require('./grid'); var Version = require('./version'); var qrcode = require('./qrcode'); module.exports = {}; var PerspectiveTransform = module.exports.PerspectiveTransform = function( a11, a21, a31, a12, a22, a32, a13, a23, a33) { this.a11 = a11; this.a12 = a12; this.a13 = a13; this.a21 = a21; this.a22 = a22; this.a23 = a23; this.a31 = a31; this.a32 = a32; this.a33 = a33; this.transformPoints1=function( points) { var max = points.length; var a11 = this.a11; var a12 = this.a12; var a13 = this.a13; var a21 = this.a21; var a22 = this.a22; var a23 = this.a23; var a31 = this.a31; var a32 = this.a32; var a33 = this.a33; for (var i = 0; i < max; i += 2) { var x = points[i]; var y = points[i + 1]; var denominator = a13 * x + a23 * y + a33; points[i] = (a11 * x + a21 * y + a31) / denominator; points[i + 1] = (a12 * x + a22 * y + a32) / denominator; } } this. transformPoints2=function(xValues, yValues) { var n = xValues.length; for (var i = 0; i < n; i++) { var x = xValues[i]; var y = yValues[i]; var denominator = this.a13 * x + this.a23 * y + this.a33; xValues[i] = (this.a11 * x + this.a21 * y + this.a31) / denominator; yValues[i] = (this.a12 * x + this.a22 * y + this.a32) / denominator; } } this.buildAdjoint=function() { // Adjoint is the transpose of the cofactor matrix: return new PerspectiveTransform(this.a22 * this.a33 - this.a23 * this.a32, this.a23 * this.a31 - this.a21 * this.a33, this.a21 * this.a32 - this.a22 * this.a31, this.a13 * this.a32 - this.a12 * this.a33, this.a11 * this.a33 - this.a13 * this.a31, this.a12 * this.a31 - this.a11 * this.a32, this.a12 * this.a23 - this.a13 * this.a22, this.a13 * this.a21 - this.a11 * this.a23, this.a11 * this.a22 - this.a12 * this.a21); } this.times=function( other) { return new PerspectiveTransform(this.a11 * other.a11 + this.a21 * other.a12 + this.a31 * other.a13, this.a11 * other.a21 + this.a21 * other.a22 + this.a31 * other.a23, this.a11 * other.a31 + this.a21 * other.a32 + this.a31 * other.a33, this.a12 * other.a11 + this.a22 * other.a12 + this.a32 * other.a13, this.a12 * other.a21 + this.a22 * other.a22 + this.a32 * other.a23, this.a12 * other.a31 + this.a22 * other.a32 + this.a32 * other.a33, this.a13 * other.a11 + this.a23 * other.a12 +this.a33 * other.a13, this.a13 * other.a21 + this.a23 * other.a22 + this.a33 * other.a23, this.a13 * other.a31 + this.a23 * other.a32 + this.a33 * other.a33); } } PerspectiveTransform.quadrilateralToQuadrilateral=function( x0, y0, x1, y1, x2, y2, x3, y3, x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p) { var qToS = this.quadrilateralToSquare(x0, y0, x1, y1, x2, y2, x3, y3); var sToQ = this.squareToQuadrilateral(x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p); return sToQ.times(qToS); } PerspectiveTransform.squareToQuadrilateral=function( x0, y0, x1, y1, x2, y2, x3, y3) { var dy2 = y3 - y2, dy3 = y0 - y1 + y2 - y3; if (dy2 == 0.0 && dy3 == 0.0) { return new PerspectiveTransform(x1 - x0, x2 - x1, x0, y1 - y0, y2 - y1, y0, 0.0, 0.0, 1.0); } else { var dx1 = x1 - x2, dx2 = x3 - x2, dx3 = x0 - x1 + x2 - x3, dy1 = y1 - y2, denominator = dx1 * dy2 - dx2 * dy1, a13 = (dx3 * dy2 - dx2 * dy3) / denominator, a23 = (dx1 * dy3 - dx3 * dy1) / denominator; return new PerspectiveTransform(x1 - x0 + a13 * x1, x3 - x0 + a23 * x3, x0, y1 - y0 + a13 * y1, y3 - y0 + a23 * y3, y0, a13, a23, 1.0); } } PerspectiveTransform.quadrilateralToSquare=function( x0, y0, x1, y1, x2, y2, x3, y3) { // Here, the adjoint serves as the inverse: return this.squareToQuadrilateral(x0, y0, x1, y1, x2, y2, x3, y3).buildAdjoint(); } function DetectorResult(bits, points) { this.bits = bits; this.points = points; } module.exports.Detector = function(image) { this.image=image; this.resultPointCallback = null; this.sizeOfBlackWhiteBlackRun=function( fromX, fromY, toX, toY) { // Mild variant of Bresenham's algorithm; // see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm var steep = Math.abs(toY - fromY) > Math.abs(toX - fromX); if (steep) { var temp = fromX; fromX = fromY; fromY = temp; temp = toX; toX = toY; toY = temp; } var dx = Math.abs(toX - fromX); var dy = Math.abs(toY - fromY); var error = - dx >> 1; var ystep = fromY < toY?1:- 1; var xstep = fromX < toX?1:- 1; var state = 0; // In black pixels, looking for white, first or second time for (var x = fromX, y = fromY; x != toX; x += xstep) { var realX = steep?y:x; var realY = steep?x:y; if (state == 1) { // In white pixels, looking for black if (this.image[realX + realY*qrcode.width]) { state++; } } else { if (!this.image[realX + realY*qrcode.width]) { state++; } } if (state == 3) { // Found black, white, black, and stumbled back onto white; done var diffX = x - fromX; var diffY = y - fromY; return Math.sqrt( (diffX * diffX + diffY * diffY)); } error += dy; if (error > 0) { if (y == toY) { break; } y += ystep; error -= dx; } } var diffX2 = toX - fromX; var diffY2 = toY - fromY; return Math.sqrt( (diffX2 * diffX2 + diffY2 * diffY2)); } this.sizeOfBlackWhiteBlackRunBothWays=function( fromX, fromY, toX, toY) { var result = this.sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY); // Now count other way -- don't run off image though of course var scale = 1.0; var otherToX = fromX - (toX - fromX); if (otherToX < 0) { scale = fromX / (fromX - otherToX); otherToX = 0; } else if (otherToX >= qrcode.width) { scale = (qrcode.width - 1 - fromX) / (otherToX - fromX); otherToX = qrcode.width - 1; } var otherToY = Math.floor (fromY - (toY - fromY) * scale); scale = 1.0; if (otherToY < 0) { scale = fromY / (fromY - otherToY); otherToY = 0; } else if (otherToY >= qrcode.height) { scale = (qrcode.height - 1 - fromY) / (otherToY - fromY); otherToY = qrcode.height - 1; } otherToX = Math.floor (fromX + (otherToX - fromX) * scale); result += this.sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY); return result - 1.0; // -1 because we counted the middle pixel twice } this.calculateModuleSizeOneWay=function( pattern, otherPattern) { var moduleSizeEst1 = this.sizeOfBlackWhiteBlackRunBothWays(Math.floor( pattern.X), Math.floor( pattern.Y), Math.floor( otherPattern.X), Math.floor(otherPattern.Y)); var moduleSizeEst2 = this.sizeOfBlackWhiteBlackRunBothWays(Math.floor(otherPattern.X), Math.floor(otherPattern.Y), Math.floor( pattern.X), Math.floor(pattern.Y)); if (isNaN(moduleSizeEst1)) { return moduleSizeEst2 / 7.0; } if (isNaN(moduleSizeEst2)) { return moduleSizeEst1 / 7.0; } // Average them, and divide by 7 since we've counted the width of 3 black modules, // and 1 white and 1 black module on either side. Ergo, divide sum by 14. return (moduleSizeEst1 + moduleSizeEst2) / 14.0; } this.calculateModuleSize=function( topLeft, topRight, bottomLeft) { // Take the average return (this.calculateModuleSizeOneWay(topLeft, topRight) + this.calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0; } this.distance=function( pattern1, pattern2) { var xDiff = pattern1.X - pattern2.X; var yDiff = pattern1.Y - pattern2.Y; return Math.sqrt( (xDiff * xDiff + yDiff * yDiff)); } this.computeDimension=function( topLeft, topRight, bottomLeft, moduleSize) { var tltrCentersDimension = Math.round(this.distance(topLeft, topRight) / moduleSize); var tlblCentersDimension = Math.round(this.distance(topLeft, bottomLeft) / moduleSize); var dimension = ((tltrCentersDimension + tlblCentersDimension) >> 1) + 7; switch (dimension & 0x03) { // mod 4 case 0: dimension++; break; // 1? do nothing case 2: dimension--; break; case 3: throw "Error"; } return dimension; } this.findAlignmentInRegion=function( overallEstModuleSize, estAlignmentX, estAlignmentY, allowanceFactor) { // Look for an alignment pattern (3 modules in size) around where it // should be var allowance = Math.floor (allowanceFactor * overallEstModuleSize); var alignmentAreaLeftX = Math.max(0, estAlignmentX - allowance); var alignmentAreaRightX = Math.min(qrcode.width - 1, estAlignmentX + allowance); if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3) { throw "Error"; } var alignmentAreaTopY = Math.max(0, estAlignmentY - allowance); var alignmentAreaBottomY = Math.min(qrcode.height - 1, estAlignmentY + allowance); var alignmentFinder = new AlignmentPatternFinder(this.image, alignmentAreaLeftX, alignmentAreaTopY, alignmentAreaRightX - alignmentAreaLeftX, alignmentAreaBottomY - alignmentAreaTopY, overallEstModuleSize, this.resultPointCallback); return alignmentFinder.find(); } this.createTransform=function( topLeft, topRight, bottomLeft, alignmentPattern, dimension) { var dimMinusThree = dimension - 3.5; var bottomRightX; var bottomRightY; var sourceBottomRightX; var sourceBottomRightY; if (alignmentPattern != null) { bottomRightX = alignmentPattern.X; bottomRightY = alignmentPattern.Y; sourceBottomRightX = sourceBottomRightY = dimMinusThree - 3.0; } else { // Don't have an alignment pattern, just make up the bottom-right point bottomRightX = (topRight.X - topLeft.X) + bottomLeft.X; bottomRightY = (topRight.Y - topLeft.Y) + bottomLeft.Y; sourceBottomRightX = sourceBottomRightY = dimMinusThree; } var transform = PerspectiveTransform.quadrilateralToQuadrilateral(3.5, 3.5, dimMinusThree, 3.5, sourceBottomRightX, sourceBottomRightY, 3.5, dimMinusThree, topLeft.X, topLeft.Y, topRight.X, topRight.Y, bottomRightX, bottomRightY, bottomLeft.X, bottomLeft.Y); return transform; } this.sampleGrid=function( image, transform, dimension) { var sampler = GridSampler; return sampler.sampleGrid3(image, dimension, transform); } this.processFinderPatternInfo = function( info) { var topLeft = info.TopLeft; var topRight = info.TopRight; var bottomLeft = info.BottomLeft; var moduleSize = this.calculateModuleSize(topLeft, topRight, bottomLeft); if (moduleSize < 1.0) { throw "Error"; } var dimension = this.computeDimension(topLeft, topRight, bottomLeft, moduleSize); var provisionalVersion = Version.getProvisionalVersionForDimension(dimension); var modulesBetweenFPCenters = provisionalVersion.DimensionForVersion - 7; var alignmentPattern = null; // Anything above version 1 has an alignment pattern if (provisionalVersion.AlignmentPatternCenters.length > 0) { // Guess where a "bottom right" finder pattern would have been var bottomRightX = topRight.X - topLeft.X + bottomLeft.X; var bottomRightY = topRight.Y - topLeft.Y + bottomLeft.Y; // Estimate that alignment pattern is closer by 3 modules // from "bottom right" to known top left location var correctionToTopLeft = 1.0 - 3.0 / modulesBetweenFPCenters; var estAlignmentX = Math.floor (topLeft.X + correctionToTopLeft * (bottomRightX - topLeft.X)); var estAlignmentY = Math.floor (topLeft.Y + correctionToTopLeft * (bottomRightY - topLeft.Y)); // Kind of arbitrary -- expand search radius before giving up for (var i = 4; i <= 16; i <<= 1) { try { alignmentPattern = this.findAlignmentInRegion(moduleSize, estAlignmentX, estAlignmentY, i); break; } catch (re) { // try next round } } // If we didn't find alignment pattern... well try anyway without it } var transform = this.createTransform(topLeft, topRight, bottomLeft, alignmentPattern, dimension); var bits = this.sampleGrid(this.image, transform, dimension); var points; if (alignmentPattern == null) { points = new Array(bottomLeft, topLeft, topRight); } else { points = new Array(bottomLeft, topLeft, topRight, alignmentPattern); } return new DetectorResult(bits, points); } this.detect=function() { var info = new FinderPatternFinder().findFinderPattern(this.image); return this.processFinderPatternInfo(info); } } }).call({}); },{"./alignpat":5,"./findpat":14,"./grid":18,"./qrcode":19,"./version":22}],13:[function(require,module,exports){ /* Ported to JavaScript by Lazar Laszlo 2011 [email protected], www.lazarsoft.info */ /* * * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ !(function() { 'use strict'; var ErrorCorrectionLevel = module.exports = function(ordinal, bits, name) { this.ordinal_Renamed_Field = ordinal; this.bits = bits; this.name = name; this.__defineGetter__("Bits", function() { return this.bits; }); this.__defineGetter__("Name", function() { return this.name; }); this.ordinal=function() { return this.ordinal_Renamed_Field; } } ErrorCorrectionLevel.forBits=function( bits) { if (bits < 0 || bits >= FOR_BITS.length) { throw "ArgumentException"; } return FOR_BITS[bits]; } var L = new ErrorCorrectionLevel(0, 0x01, "L"); var M = new ErrorCorrectionLevel(1, 0x00, "M"); var Q = new ErrorCorrectionLevel(2, 0x03, "Q"); var H = new ErrorCorrectionLevel(3, 0x02, "H"); var FOR_BITS = new Array( M, L, H, Q); }).call({}); },{}],14:[function(require,module,exports){ /* Ported to JavaScript by Lazar Laszlo 2011 [email protected], www.lazarsoft.info */ /* * * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ !(function() { 'use strict'; var qrcode = require('./qrcode'); var MIN_SKIP = 3; var MAX_MODULES = 57; var INTEGER_MATH_SHIFT = 8; var CENTER_QUORUM = 2; function remove(arr, from, to) { var rest = arr.slice((to || from) + 1 || arr.length); arr.length = from < 0 ? arr.length + from : from; return arr.push.apply(arr, rest); }; function FinderPattern(posX, posY, estimatedModuleSize) { this.x=posX; this.y=posY; this.count = 1; this.estimatedModuleSize = estimatedModuleSize; this.__defineGetter__("EstimatedModuleSize", function() { return this.estimatedModuleSize; }); this.__defineGetter__("Count", function() { return this.count; }); this.__defineGetter__("X", function() { return this.x; }); this.__defineGetter__("Y", function() { return this.y; }); this.incrementCount = function() { this.count++; } this.aboutEquals=function( moduleSize, i, j) { if (Math.abs(i - this.y) <= moduleSize && Math.abs(j - this.x) <= moduleSize) { var moduleSizeDiff = Math.abs(moduleSize - this.estimatedModuleSize); return moduleSizeDiff <= 1.0 || moduleSizeDiff / this.estimatedModuleSize <= 1.0; } return false; } } function FinderPatternInfo(patternCenters) { this.bottomLeft = patternCenters[0]; this.topLeft = patternCenters[1]; this.topRight = patternCenters[2]; this.__defineGetter__("BottomLeft", function() { return this.bottomLeft; }); this.__defineGetter__("TopLeft", function() { return this.topLeft; }); this.__defineGetter__("TopRight", function() { return this.topRight; }); } module.exports = function() { this.image=null; this.possibleCenters = []; this.hasSkipped = false; this.crossCheckStateCount = new Array(0,0,0,0,0); this.resultPointCallback = null; this.__defineGetter__("CrossCheckStateCount", function() { this.crossCheckStateCount[0] = 0; this.crossCheckStateCount[1] = 0; this.crossCheckStateCount[2] = 0; this.crossCheckStateCount[3] = 0; this.crossCheckStateCount[4] = 0; return this.crossCheckStateCount; }); this.foundPatternCross=function( stateCount) { var totalModuleSize = 0; for (var i = 0; i < 5; i++) { var count = stateCount[i]; if (count == 0) { return false; } totalModuleSize += count; } if (totalModuleSize < 7) { return false; } var moduleSize = Math.floor((totalModuleSize << INTEGER_MATH_SHIFT) / 7); var maxVariance = Math.floor(moduleSize / 2); // Allow less than 50% variance from 1-1-3-1-1 proportions return Math.abs(moduleSize - (stateCount[0] << INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(moduleSize - (stateCount[1] << INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(3 * moduleSize - (stateCount[2] << INTEGER_MATH_SHIFT)) < 3 * maxVariance && Math.abs(moduleSize - (stateCount[3] << INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(moduleSize - (stateCount[4] << INTEGER_MATH_SHIFT)) < maxVariance; } this.centerFromEnd=function( stateCount, end) { return (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0; } this.crossCheckVertical=function( startI, centerJ, maxCount, originalStateCountTotal) { var image = this.image; var maxI = qrcode.height; var stateCount = this.CrossCheckStateCount; // Start counting up from center var i = startI; while (i >= 0 && image[centerJ + i*qrcode.width]) { stateCount[2]++; i--; } if (i < 0) { return NaN; } while (i >= 0 && !image[centerJ +i*qrcode.width] && stateCount[1] <= maxCount) { stateCount[1]++; i--; } // If already too many modules in this state or ran off the edge: if (i < 0 || stateCount[1] > maxCount) { return NaN; } while (i >= 0 && image[centerJ + i*qrcode.width] && stateCount[0] <= maxCount) { stateCount[0]++; i--; } if (stateCount[0] > maxCount) { return NaN; } // Now also count down from center i = startI + 1; while (i < maxI && image[centerJ +i*qrcode.width]) { stateCount[2]++; i++; } if (i == maxI) { return NaN; } while (i < maxI && !image[centerJ + i*qrcode.width] && stateCount[3] < maxCount) { stateCount[3]++; i++; } if (i == maxI || stateCount[3] >= maxCount) { return NaN; } while (i < maxI && image[centerJ + i*qrcode.width] && stateCount[4] < maxCount) { stateCount[4]++; i++; } if (stateCount[4] >= maxCount) { return NaN; } // If we found a finder-pattern-like section, but its size is more than 40% different than // the original, assume it's a false positive var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) { return NaN; } return this.foundPatternCross(stateCount)?this.centerFromEnd(stateCount, i):NaN; } this.crossCheckHorizontal=function( startJ, centerI, maxCount, originalStateCountTotal) { var image = this.image; var maxJ = qrcode.width; var stateCount = this.CrossCheckStateCount; var j = startJ; while (j >= 0 && image[j+ centerI*qrcode.width]) { stateCount[2]++; j--; } if (j < 0) { return NaN; } while (j >= 0 && !image[j+ centerI*qrcode.width] && stateCount[1] <= maxCount) { stateCount[1]++; j--; } if (j < 0 || stateCount[1] > maxCount) { return NaN; } while (j >= 0 && image[j+ centerI*qrcode.width] && stateCount[0] <= maxCount) { stateCount[0]++; j--; } if (stateCount[0] > maxCount) { return NaN; } j = startJ + 1; while (j < maxJ && image[j+ centerI*qrcode.width]) { stateCount[2]++; j++; } if (j == maxJ) { return NaN; } while (j < maxJ && !image[j+ centerI*qrcode.width] && stateCount[3] < maxCount) { stateCount[3]++; j++; } if (j == maxJ || stateCount[3] >= maxCount) { return NaN; } while (j < maxJ && image[j+ centerI*qrcode.width] && stateCount[4] < maxCount) { stateCount[4]++; j++; } if (stateCount[4] >= maxCount) { return NaN; } // If we found a finder-pattern-like section, but its size is significantly different than // the original, assume it's a false positive var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) { return NaN; } return this.foundPatternCross(stateCount)?this.centerFromEnd(stateCount, j):NaN; } this.handlePossibleCenter=function( stateCount, i, j) { var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; var centerJ = this.centerFromEnd(stateCount, j); //float var centerI = this.crossCheckVertical(i, Math.floor( centerJ), stateCount[2], stateCountTotal); //float if (!isNaN(centerI)) { // Re-cross check centerJ = this.crossCheckHorizontal(Math.floor( centerJ), Math.floor( centerI), stateCount[2], stateCountTotal); if (!isNaN(centerJ)) { var estimatedModuleSize = stateCountTotal / 7.0; var found = false; var max = this.possibleCenters.length; for (var index = 0; index < max; index++) { var center = this.possibleCenters[index]; // Look for about the same center and module size: if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) { center.incrementCount(); found = true; break; } } if (!found) { var point = new FinderPattern(centerJ, centerI, estimatedModuleSize); this.possibleCenters.push(point); if (this.resultPointCallback != null) { this.resultPointCallback.foundPossibleResultPoint(point); } } return true; } } return false; } this.selectBestPatterns=function() { var startSize = this.possibleCenters.length; if (startSize < 3) { // Couldn't find enough finder patterns throw "Couldn't find enough finder patterns"; } // Filter outlier possibilities whose module size is too different if (startSize > 3) { // But we can only afford to do so if we have at least 4 possibilities to choose from var totalModuleSize = 0.0; var square = 0.0; for (var i = 0; i < startSize; i++) { //totalModuleSize += this.possibleCenters[i].EstimatedModuleSize; var centerValue=this.possibleCenters[i].EstimatedModuleSize; totalModuleSize += centerValue; square += (centerValue * centerValue); } var average = totalModuleSize / startSize; this.possibleCenters.sort(function(center1,center2) { var dA=Math.abs(center2.EstimatedModuleSize - average); var dB=Math.abs(center1.EstimatedModuleSize - average); if (dA < dB) { return (-1); } else if (dA == dB) { return 0; } else { return 1; } }); var stdDev = Math.sqrt(square / startSize - average * average); var limit = Math.max(0.2 * average, stdDev); for (var i = 0; i < this.possibleCenters.length && this.possibleCenters.length > 3; i++) { var pattern = this.possibleCenters[i]; //if (Math.abs(pattern.EstimatedModuleSize - average) > 0.2 * average) if (Math.abs(pattern.EstimatedModuleSize - average) > limit) { remove(this.possibleCenters, i); i--; } } } if (this.possibleCenters.length > 3) { // Throw away all but those first size candidate points we found. this.possibleCenters.sort(function(a, b){ if (a.count > b.count){return -1;} if (a.count < b.count){return 1;} return 0; }); } return new Array( this.possibleCenters[0], this.possibleCenters[1], this.possibleCenters[2]); } this.findRowSkip=function() { var max = this.possibleCenters.length; if (max <= 1) { return 0; } var firstConfirmedCenter = null; for (var i = 0; i < max; i++) { var center = this.possibleCenters[i]; if (center.Count >= CENTER_QUORUM) { if (firstConfirmedCenter == null) { firstConfirmedCenter = center; } else { // We have two confirmed centers // How far down can we skip before resuming looking for the next // pattern? In the worst case, only the difference between the // difference in the x / y coordinates of the two centers. // This is the case where you find top left last. this.hasSkipped = true; return Math.floor ((Math.abs(firstConfirmedCenter.X - center.X) - Math.abs(firstConfirmedCenter.Y - center.Y)) / 2); } } } return 0; } this.haveMultiplyConfirmedCenters=function() { var confirmedCount = 0; var totalModuleSize = 0.0; var max = this.possibleCenters.length; for (var i = 0; i < max; i++) { var pattern = this.possibleCenters[i]; if (pattern.Count >= CENTER_QUORUM) { confirmedCount++; totalModuleSize += pattern.EstimatedModuleSize; } } if (confirmedCount < 3) { return false; } // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive" // and that we need to keep looking. We detect this by asking if the estimated module sizes // vary too much. We arbitrarily say that when the total deviation from average exceeds // 5% of the total module size estimates, it's too much. var average = totalModuleSize / max; var totalDeviation = 0.0; for (var i = 0; i < max; i++) { pattern = this.possibleCenters[i]; totalDeviation += Math.abs(pattern.EstimatedModuleSize - average); } return totalDeviation <= 0.05 * totalModuleSize; } this.findFinderPattern = function(image){ var tryHarder = false; this.image=image; var maxI = qrcode.height; var maxJ = qrcode.width; var iSkip = Math.floor((3 * maxI) / (4 * MAX_MODULES)); if (iSkip < MIN_SKIP || tryHarder) { iSkip = MIN_SKIP; } var done = false; var stateCount = new Array(5); console.log(maxI, maxJ, iSkip, MIN_SKIP, tryHarder, qrcode.height, qrcode.width, qrcode.asdf); for (var i = iSkip - 1; i < maxI && !done; i += iSkip) { // Get a row of black/white values stateCount[0] = 0; stateCount[1] = 0; stateCount[2] = 0; stateCount[3] = 0; stateCount[4] = 0; var currentState = 0; for (var j = 0; j < maxJ; j++) { if (image[j+i*qrcode.width] ) { // Black pixel if ((currentState & 1) == 1) { // Counting white pixels currentState++; } stateCount[currentState]++; } else { // White pixel if ((currentState & 1) == 0) { // Counting black pixels if (currentState == 4) { // A winner? if (this.foundPatternCross(stateCount)) { // Yes var confirmed = this.handlePossibleCenter(stateCount, i, j); if (confirmed) { // Start examining every other line. Checking each line turned out to be too // expensive and didn't improve performance. iSkip = 2; if (this.hasSkipped) { done = this.haveMultiplyConfirmedCenters(); } else { var rowSkip = this.findRowSkip(); if (rowSkip > stateCount[2]) { // Skip rows between row of lower confirmed center // and top of presumed third confirmed center // but back up a bit to get a full chance of detecting // it, entire width of center of finder pattern // Skip by rowSkip, but back off by stateCount[2] (size of last center // of pattern we saw) to be conservative, and also back off by iSkip which // is about to be re-added i += rowSkip - stateCount[2] - iSkip; j = maxJ - 1; } } } else { // Advance to next black pixel do { j++; } while (j < maxJ && !image[j + i*qrcode.width]); j--; // back up to that last white pixel } // Clear state to start looking again currentState = 0; stateCount[0] = 0; stateCount[1] = 0; stateCount[2] = 0; stateCount[3] = 0; stateCount[4] = 0; } else { // No, shift counts back by two stateCount[0] = stateCount[2]; stateCount[1] = stateCount[3]; stateCount[2] = stateCount[4]; stateCount[3] = 1; stateCount[4] = 0; currentState = 3; } } else { stateCount[++currentState]++; } } else { // Counting white pixels stateCount[currentState]++; } } } if (this.foundPatternCross(stateCount)) { var confirmed = this.handlePossibleCenter(stateCount, i, maxJ); if (confirmed) { iSkip = stateCount[0]; if (this.hasSkipped) { // Found a third one done = haveMultiplyConfirmedCenters(); } } } } var patternInfo = this.selectBestPatterns(); qrcode.orderBestPatterns(patternInfo); return new FinderPatternInfo(patternInfo); }; } }).call({}); },{"./qrcode":19}],15:[function(require,module,exports){ /* Ported to JavaScript by Lazar Laszlo 2011 [email protected], www.lazarsoft.info */ /* * * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ !(function() { 'use strict'; var URShift = require('./urshift'); var ErrorCorrectionLevel = require('./errorlevel'); var FORMAT_INFO_MASK_QR = 0x5412; var FORMAT_INFO_DECODE_LOOKUP = new Array(new Array(0x5412, 0x00), new Array(0x5125, 0x01), new Array(0x5E7C, 0x02), new Array(0x5B4B, 0x03), new Array(0x45F9, 0x04), new Array(0x40CE, 0x05), new Array(0x4F97, 0x06), new Array(0x4AA0, 0x07), new Array(0x77C4, 0x08), new Array(0x72F3, 0x09), new Array(0x7DAA, 0x0A), new Array(0x789D, 0x0B), new Array(0x662F, 0x0C), new Array(0x6318, 0x0D), new Array(0x6C41, 0x0E), new Array(0x6976, 0x0F), new Array(0x1689, 0x10), new Array(0x13BE, 0x11), new Array(0x1CE7, 0x12), new Array(0x19D0, 0x13), new Array(0x0762, 0x14), new Array(0x0255, 0x15), new Array(0x0D0C, 0x16), new Array(0x083B, 0x17), new Array(0x355F, 0x18), new Array(0x3068, 0x19), new Array(0x3F31, 0x1A), new Array(0x3A06, 0x1B), new Array(0x24B4, 0x1C), new Array(0x2183, 0x1D), new Array(0x2EDA, 0x1E), new Array(0x2BED, 0x1F)); var BITS_SET_IN_HALF_BYTE = new Array(0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4); var FormatInformation = module.exports = function(formatInfo) { this.errorCorrectionLevel = ErrorCorrectionLevel.forBits((formatInfo >> 3) & 0x03); this.dataMask = (formatInfo & 0x07); this.__defineGetter__("ErrorCorrectionLevel", function() { return this.errorCorrectionLevel; }); this.__defineGetter__("DataMask", function() { return this.dataMask; }); this.GetHashCode=function() { return (this.errorCorrectionLevel.ordinal() << 3) | dataMask; } this.Equals=function( o) { var other = o; return this.errorCorrectionLevel == other.errorCorrectionLevel && this.dataMask == other.dataMask; } } FormatInformation.numBitsDiffering=function( a, b) { a ^= b; // a now has a 1 bit exactly where its bit differs with b's // Count bits set quickly with a series of lookups: return BITS_SET_IN_HALF_BYTE[a & 0x0F] + BITS_SET_IN_HALF_BYTE[(URShift(a, 4) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 8) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 12) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 16) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 20) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 24) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 28) & 0x0F)]; } FormatInformation.decodeFormatInformation=function( maskedFormatInfo) { var formatInfo = FormatInformation.doDecodeFormatInformation(maskedFormatInfo); if (formatInfo != null) { return formatInfo; } // Should return null, but, some QR codes apparently // do not mask this info. Try again by actually masking the pattern // first return FormatInformation.doDecodeFormatInformation(maskedFormatInfo ^ FORMAT_INFO_MASK_QR); } FormatInformation.doDecodeFormatInformation=function( maskedFormatInfo) { // Find the int in FORMAT_INFO_DECODE_LOOKUP with fewest bits differing var bestDifference = 0xffffffff; var bestFormatInfo = 0; for (var i = 0; i < FORMAT_INFO_DECODE_LOOKUP.length; i++) { var decodeInfo = FORMAT_INFO_DECODE_LOOKUP[i]; var targetInfo = decodeInfo[0]; if (targetInfo == maskedFormatInfo) { // Found an exact match return new FormatInformation(decodeInfo[1]); } var bitsDifference = this.numBitsDiffering(maskedFormatInfo, targetInfo); if (bitsDifference < bestDifference) { bestFormatInfo = decodeInfo[1]; bestDifference = bitsDifference; } } // Hamming distance of the 32 masked codes is 7, by construction, so <= 3 bits // differing means we found a match if (bestDifference <= 3) { return new FormatInformation(bestFormatInfo); } return null; } }).call({}); },{"./errorlevel":13,"./urshift":21}],16:[function(require,module,exports){ /* Ported to JavaScript by Lazar Laszlo 2011 [email protected], www.lazarsoft.info */ /* * * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ !(function() { 'use strict'; var GF256Poly = require('./gf256poly'); var GF256 = module.exports = function( primitive) { this.expTable = new Array(256); this.logTable = new Array(256); var x = 1; for (var i = 0; i < 256; i++) { this.expTable[i] = x; x <<= 1; // x = x * 2; we're assuming the generator alpha is 2 if (x >= 0x100) { x ^= primitive; } } for (var i = 0; i < 255; i++) { this.logTable[this.expTable[i]] = i; } // logTable[0] == 0 but this should never be used var at0=new Array(1);at0[0]=0; this.zero = new GF256Poly(this, new Array(at0)); var at1=new Array(1);at1[0]=1; this.one = new GF256Poly(this, new Array(at1)); this.__defineGetter__("Zero", function() { return this.zero; }); this.__defineGetter__("One", function() { return this.one; }); this.buildMonomial=function( degree, coefficient) { if (degree < 0) { throw "System.ArgumentException"; } if (coefficient == 0) { return zero; } var coefficients = new Array(degree + 1); for(var i=0;i<coefficients.length;i++)coefficients[i]=0; coefficients[0] = coefficient; return new GF256Poly(this, coefficients); } this.exp=function( a) { return this.expTable[a]; } this.log=function( a) { if (a == 0) { throw "System.ArgumentException"; } return this.logTable[a]; } this.inverse=function( a) { if (a == 0) { throw "System.ArithmeticException"; } return this.expTable[255 - this.logTable[a]]; } this.multiply=function( a, b) { if (a == 0 || b == 0) { return 0; } if (a == 1) { return b; } if (b == 1) { return a; } return this.expTable[(this.logTable[a] + this.logTable[b]) % 255]; } } GF256.QR_CODE_FIELD = new GF256(0x011D); GF256.DATA_MATRIX_FIELD = new GF256(0x012D); GF256.addOrSubtract=function( a, b) { return a ^ b; } }).call({}); },{"./gf256poly":17}],17:[function(require,module,exports){ /* Ported to JavaScript by Lazar Laszlo 2011 [email protected], www.lazarsoft.info */ /* * * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ !(function() { 'use strict'; var GF256Poly = module.exports = function(field, coefficients) { var GF256 = require('./gf256'); if (coefficients == null || coefficients.length == 0) { throw "System.ArgumentException"; } this.field = field; var coefficientsLength = coefficients.length; if (coefficientsLength > 1 && coefficients[0] == 0) { // Leading term must be non-zero for anything except the constant polynomial "0" var firstNonZero = 1; while (firstNonZero < coefficientsLength && coefficients[firstNonZero] == 0) { firstNonZero++; } if (firstNonZero == coefficientsLength) { this.coefficients = field.Zero.coefficients; } else { this.coefficients = new Array(coefficientsLength - firstNonZero); for(var i=0;i<this.coefficients.length;i++)this.coefficients[i]=0; //Array.Copy(coefficients, firstNonZero, this.coefficients, 0, this.coefficients.length); for(var ci=0;ci<this.coefficients.length;ci++)this.coefficients[ci]=coefficients[firstNonZero+ci]; } } else { this.coefficients = coefficients; } this.__defineGetter__("Zero", function() { return this.coefficients[0] == 0; }); this.__defineGetter__("Degree", function() { return this.coefficients.length - 1; }); this.__defineGetter__("Coefficients", function() { return this.coefficients; }); this.getCoefficient=function( degree) { return this.coefficients[this.coefficients.length - 1 - degree]; } this.evaluateAt=function( a) { if (a == 0) { // Just return the x^0 coefficient return this.getCoefficient(0); } var size = this.coefficients.length; if (a == 1) { // Just the sum of the coefficients var result = 0; for (var i = 0; i < size; i++) { result = GF256.addOrSubtract(result, this.coefficients[i]); } return result; } var result2 = this.coefficients[0]; for (var i = 1; i < size; i++) { result2 = GF256.addOrSubtract(this.field.multiply(a, result2), this.coefficients[i]); } return result2; } this.addOrSubtract=function( other) { if (this.field != other.field) { throw "GF256Polys do not have same GF256 field"; } if (this.Zero) { return other; } if (other.Zero) { return this; } var smallerCoefficients = this.coefficients; var largerCoefficients = other.coefficients; if (smallerCoefficients.length > largerCoefficients.length) { var temp = smallerCoefficients; smallerCoefficients = largerCoefficients; largerCoefficients = temp; } var sumDiff = new Array(largerCoefficients.length); var lengthDiff = largerCoefficients.length - smallerCoefficients.length; // Copy high-order terms only found in higher-degree polynomial's coefficients //Array.Copy(largerCoefficients, 0, sumDiff, 0, lengthDiff); for(var ci=0;ci<lengthDiff;ci++)sumDiff[ci]=largerCoefficients[ci]; for (var i = lengthDiff; i < largerCoefficients.length; i++) { sumDiff[i] = GF256.addOrSubtract(smallerCoefficients[i - lengthDiff], largerCoefficients[i]); } return new GF256Poly(field, sumDiff); } this.multiply1=function( other) { if (this.field!=other.field) { throw "GF256Polys do not have same GF256 field"; } if (this.Zero || other.Zero) { return this.field.Zero; } var aCoefficients = this.coefficients; var aLength = aCoefficients.length; var bCoefficients = other.coefficients; var bLength = bCoefficients.length; var product = new Array(aLength + bLength - 1); for (var i = 0; i < aLength; i++) { var aCoeff = aCoefficients[i]; for (var j = 0; j < bLength; j++) { product[i + j] = GF256.addOrSubtract(product[i + j], this.field.multiply(aCoeff, bCoefficients[j])); } } return new GF256Poly(this.field, product); } this.multiply2=function( scalar) { if (scalar == 0) { return this.field.Zero; } if (scalar == 1) { return this; } var size = this.coefficients.length; var product = new Array(size); for (var i = 0; i < size; i++) { product[i] = this.field.multiply(this.coefficients[i], scalar); } return new GF256Poly(this.field, product); } this.multiplyByMonomial=function( degree, coefficient) { if (degree < 0) { throw "System.ArgumentException"; } if (coefficient == 0) { return this.field.Zero; } var size = this.coefficients.length; var product = new Array(size + degree); for(var i=0;i<product.length;i++)product[i]=0; for (var i = 0; i < size; i++) { product[i] = this.field.multiply(this.coefficients[i], coefficient); } return new GF256Poly(this.field, product); } this.divide=function( other) { if (this.field!=other.field) { throw "GF256Polys do not have same GF256 field"; } if (other.Zero) { throw "Divide by 0"; } var quotient = this.field.Zero; var remainder = this; var denominatorLeadingTerm = other.getCoefficient(other.Degree); var inverseDenominatorLeadingTerm = this.field.inverse(denominatorLeadingTerm); while (remainder.Degree >= other.Degree && !remainder.Zero) { var degreeDifference = remainder.Degree - other.Degree; var scale = this.field.multiply(remainder.getCoefficient(remainder.Degree), inverseDenominatorLeadingTerm); var term = other.multiplyByMonomial(degreeDifference, scale); var iterationQuotient = this.field.buildMonomial(degreeDifference, scale); quotient = quotient.addOrSubtract(iterationQuotient); remainder = remainder.addOrSubtract(term); } return new Array(quotient, remainder); } } }).call({}); },{"./gf256":16}],18:[function(require,module,exports){ /* Ported to JavaScript by Lazar Laszlo 2011 [email protected], www.lazarsoft.info */ /* * * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ !(function() { 'use strict'; var qrcode = require('./qrcode'); var BitMatrix = require('./bitmat'); var PerspectiveTransform = require('./detector').PerspectiveTransform; var GridSampler = module.exports = {}; GridSampler.checkAndNudgePoints=function( image, points) { var width = qrcode.width; var height = qrcode.height; // Check and nudge points from start until we see some that are OK: var nudged = true; for (var offset = 0; offset < points.length && nudged; offset += 2) { var x = Math.floor (points[offset]); var y = Math.floor( points[offset + 1]); if (x < - 1 || x > width || y < - 1 || y > height) { throw "Error.checkAndNudgePoints "; } nudged = false; if (x == - 1) { points[offset] = 0.0; nudged = true; } else if (x == width) { points[offset] = width - 1; nudged = true; } if (y == - 1) { points[offset + 1] = 0.0; nudged = true; } else if (y == height) { points[offset + 1] = height - 1; nudged = true; } } // Check and nudge points from end: nudged = true; for (var offset = points.length - 2; offset >= 0 && nudged; offset -= 2) { var x = Math.floor( points[offset]); var y = Math.floor( points[offset + 1]); if (x < - 1 || x > width || y < - 1 || y > height) { throw "Error.checkAndNudgePoints "; } nudged = false; if (x == - 1) { points[offset] = 0.0; nudged = true; } else if (x == width) { points[offset] = width - 1; nudged = true; } if (y == - 1) { points[offset + 1] = 0.0; nudged = true; } else if (y == height) { points[offset + 1] = height - 1; nudged = true; } } } GridSampler.sampleGrid3=function( image, dimension, transform) { var bits = new BitMatrix(dimension); var points = new Array(dimension << 1); for (var y = 0; y < dimension; y++) { var max = points.length; var iValue = y + 0.5; for (var x = 0; x < max; x += 2) { points[x] = (x >> 1) + 0.5; points[x + 1] = iValue; } transform.transformPoints1(points); // Quick check to see if points transformed to something inside the image; // sufficient to check the endpoints GridSampler.checkAndNudgePoints(image, points); try { for (var x = 0; x < max; x += 2) { var xpoint = (Math.floor( points[x]) * 4) + (Math.floor( points[x + 1]) * qrcode.width * 4); var bit = image[Math.floor( points[x])+ qrcode.width* Math.floor( points[x + 1])]; qrcode.imagedata.data[xpoint] = bit?255:0; qrcode.imagedata.data[xpoint+1] = bit?255:0; qrcode.imagedata.data[xpoint+2] = 0; qrcode.imagedata.data[xpoint+3] = 255; //bits[x >> 1][ y]=bit; if(bit) bits.set_Renamed(x >> 1, y); } } catch ( aioobe) { // This feels wrong, but, sometimes if the finder patterns are misidentified, the resulting // transform gets "twisted" such that it maps a straight line of points to a set of points // whose endpoints are in bounds, but others are not. There is probably some mathematical // way to detect this about the transformation that I don't know yet. // This results in an ugly runtime exception despite our clever checks above -- can't have // that. We could check each point's coordinates but that feels duplicative. We settle for // catching and wrapping ArrayIndexOutOfBoundsException. throw "Error.checkAndNudgePoints"; } } return bits; } GridSampler.sampleGridx=function( image, dimension, p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY, p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY) { var transform = PerspectiveTransform.quadrilateralToQuadrilateral(p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY, p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY); return GridSampler.sampleGrid3(image, dimension, transform); } }).call({}); },{"./bitmat":6,"./detector":12,"./qrcode":19}],19:[function(require,module,exports){ /* Copyright 2011 Lazar Laszlo ([email protected], www.lazarsoft.info) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ !(function() { 'use strict'; var Decoder = require('./decoder'); var Detector = require('./detector').Detector; var qrcode = module.exports; qrcode.imagedata = null; qrcode.width = 0; qrcode.height = 0; qrcode.qrCodeSymbol = null; qrcode.debug = false; qrcode.maxImgSize = 1024*1024; qrcode.sizeOfDataLengthInfo = [ [ 10, 9, 8, 8 ], [ 12, 11, 16, 10 ], [ 14, 13, 16, 12 ] ]; qrcode.decode = function(src, callback){ if (src == null) { throw new Error("Must provide a callback"); } else if (callback == null) { callback = src; src = null; } if (typeof callback !== "function") { throw new Error("Must provide a callback"); } if(src == null) { //callback = src; var canvas_qr = document.getElementById("qr-canvas"); var context = canvas_qr.getContext('2d'); qrcode.width = canvas_qr.width; qrcode.height = canvas_qr.height; qrcode.imagedata = context.getImageData(0, 0, qrcode.width, qrcode.height); try { qrcode.result = qrcode.process(context); callback(null, qrcode.result); } catch (e) { callback(e); } } else { if (typeof src !== "string") { callback(new Error("Must provide image source as a URI")); } var image = new Image(); image.onload=function(){ //var canvas_qr = document.getElementById("qr-canvas"); var canvas_qr = document.createElement('canvas'); var context = canvas_qr.getContext('2d'); var nheight = image.height; var nwidth = image.width; if(image.width*image.height>qrcode.maxImgSize) { var ir = image.width / image.height; nheight = Math.sqrt(qrcode.maxImgSize/ir); nwidth=ir*nheight; } canvas_qr.width = nwidth; canvas_qr.height = nheight; context.drawImage(image, 0, 0, canvas_qr.width, canvas_qr.height ); qrcode.width = canvas_qr.width; qrcode.height = canvas_qr.height; try{ qrcode.imagedata = context.getImageData(0, 0, canvas_qr.width, canvas_qr.height); }catch(e){ qrcode.result = null; callback(new Error( "Cross domain image reading not supported in your browser! Save it to your computer then drag and drop the file!")); return; } try { qrcode.result = qrcode.process(context); } catch(e) { callback(e); return } callback(null, qrcode.result); } image.src = src; } } qrcode.isUrl = function(s) { var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/; return regexp.test(s); } qrcode.decode_url = function (s) { var escaped = ""; try{ escaped = escape( s ); } catch(e) { escaped = s; } var ret = ""; try{ ret = decodeURIComponent( escaped ); } catch(e) { ret = escaped; } return ret; } qrcode.decode_utf8 = function ( s ) { if(qrcode.isUrl(s)) return qrcode.decode_url(s); else return s; } qrcode.process = function(ctx){ var start = new Date().getTime(); var image = qrcode.grayScaleToBitmap(qrcode.grayscale()); //var image = qrcode.binarize(128); if(qrcode.debug) { for (var y = 0; y < qrcode.height; y++) { for (var x = 0; x < qrcode.width; x++) { var point = (x * 4) + (y * qrcode.width * 4); qrcode.imagedata.data[point] = image[x+y*qrcode.width]?0:0; qrcode.imagedata.data[point+1] = image[x+y*qrcode.width]?0:0; qrcode.imagedata.data[point+2] = image[x+y*qrcode.width]?255:0; } } ctx.putImageData(qrcode.imagedata, 0, 0); } //var finderPatternInfo = new FinderPatternFinder().findFinderPattern(image); var detector = new Detector(image); var qRCodeMatrix = detector.detect(); /*for (var y = 0; y < qRCodeMatrix.bits.Height; y++) { for (var x = 0; x < qRCodeMatrix.bits.Width; x++) { var point = (x * 4*2) + (y*2 * qrcode.width * 4); qrcode.imagedata.data[point] = qRCodeMatrix.bits.get_Renamed(x,y)?0:0; qrcode.imagedata.data[point+1] = qRCodeMatrix.bits.get_Renamed(x,y)?0:0; qrcode.imagedata.data[point+2] = qRCodeMatrix.bits.get_Renamed(x,y)?255:0; } }*/ if(qrcode.debug) ctx.putImageData(qrcode.imagedata, 0, 0); var reader = Decoder.decode(qRCodeMatrix.bits); var data = reader.DataByte; var str=""; for(var i=0;i<data.length;i++) { for(var j=0;j<data[i].length;j++) str+=String.fromCharCode(data[i][j]); } var end = new Date().getTime(); var time = end - start; console.log(time); return qrcode.decode_utf8(str); //alert("Time:" + time + " Code: "+str); } qrcode.getPixel = function(x,y){ if (qrcode.width < x) { throw "point error"; } if (qrcode.height < y) { throw "point error"; } var point = (x * 4) + (y * qrcode.width * 4); var p = (qrcode.imagedata.data[point]*33 + qrcode.imagedata.data[point + 1]*34 + qrcode.imagedata.data[point + 2]*33)/100; return p; } qrcode.binarize = function(th){ var ret = new Array(qrcode.width*qrcode.height); for (var y = 0; y < qrcode.height; y++) { for (var x = 0; x < qrcode.width; x++) { var gray = qrcode.getPixel(x, y); ret[x+y*qrcode.width] = gray<=th?true:false; } } return ret; } qrcode.getMiddleBrightnessPerArea=function(image) { var numSqrtArea = 4; //obtain middle brightness((min + max) / 2) per area var areaWidth = Math.floor(qrcode.width / numSqrtArea); var areaHeight = Math.floor(qrcode.height / numSqrtArea); var minmax = new Array(numSqrtArea); for (var i = 0; i < numSqrtArea; i++) { minmax[i] = new Array(numSqrtArea); for (var i2 = 0; i2 < numSqrtArea; i2++) { minmax[i][i2] = new Array(0,0); } } for (var ay = 0; ay < numSqrtArea; ay++) { for (var ax = 0; ax < numSqrtArea; ax++) { minmax[ax][ay][0] = 0xFF; for (var dy = 0; dy < areaHeight; dy++) { for (var dx = 0; dx < areaWidth; dx++) { var target = image[areaWidth * ax + dx+(areaHeight * ay + dy)*qrcode.width]; if (target < minmax[ax][ay][0]) minmax[ax][ay][0] = target; if (target > minmax[ax][ay][1]) minmax[ax][ay][1] = target; } } //minmax[ax][ay][0] = (minmax[ax][ay][0] + minmax[ax][ay][1]) / 2; } } var middle = new Array(numSqrtArea); for (var i3 = 0; i3 < numSqrtArea; i3++) { middle[i3] = new Array(numSqrtArea); } for (var ay = 0; ay < numSqrtArea; ay++) { for (var ax = 0; ax < numSqrtArea; ax++) { middle[ax][ay] = Math.floor((minmax[ax][ay][0] + minmax[ax][ay][1]) / 2); //Console.out.print(middle[ax][ay] + ","); } //Console.out.println(""); } //Console.out.println(""); return middle; } qrcode.grayScaleToBitmap=function(grayScale) { var middle = qrcode.getMiddleBrightnessPerArea(grayScale); var sqrtNumArea = middle.length; var areaWidth = Math.floor(qrcode.width / sqrtNumArea); var areaHeight = Math.floor(qrcode.height / sqrtNumArea); var bitmap = new Array(qrcode.height*qrcode.width); for (var ay = 0; ay < sqrtNumArea; ay++) { for (var ax = 0; ax < sqrtNumArea; ax++) { for (var dy = 0; dy < areaHeight; dy++) { for (var dx = 0; dx < areaWidth; dx++) { bitmap[areaWidth * ax + dx+ (areaHeight * ay + dy)*qrcode.width] = (grayScale[areaWidth * ax + dx+ (areaHeight * ay + dy)*qrcode.width] < middle[ax][ay])?true:false; } } } } return bitmap; } qrcode.grayscale = function(){ var ret = new Array(qrcode.width*qrcode.height); for (var y = 0; y < qrcode.height; y++) { for (var x = 0; x < qrcode.width; x++) { var gray = qrcode.getPixel(x, y); ret[x+y*qrcode.width] = gray; } } return ret; } qrcode.orderBestPatterns=function(patterns) { function distance( pattern1, pattern2) { var xDiff = pattern1.X - pattern2.X; var yDiff = pattern1.Y - pattern2.Y; return Math.sqrt( (xDiff * xDiff + yDiff * yDiff)); } /// <summary> Returns the z component of the cross product between vectors BC and BA.</summary> function crossProductZ( pointA, pointB, pointC) { var bX = pointB.x; var bY = pointB.y; return ((pointC.x - bX) * (pointA.y - bY)) - ((pointC.y - bY) * (pointA.x - bX)); } // Find distances between pattern centers var zeroOneDistance = distance(patterns[0], patterns[1]); var oneTwoDistance = distance(patterns[1], patterns[2]); var zeroTwoDistance = distance(patterns[0], patterns[2]); var pointA, pointB, pointC; // Assume one closest to other two is B; A and C will just be guesses at first if (oneTwoDistance >= zeroOneDistance && oneTwoDistance >= zeroTwoDistance) { pointB = patterns[0]; pointA = patterns[1]; pointC = patterns[2]; } else if (zeroTwoDistance >= oneTwoDistance && zeroTwoDistance >= zeroOneDistance) { pointB = patterns[1]; pointA = patterns[0]; pointC = patterns[2]; } else { pointB = patterns[2]; pointA = patterns[0]; pointC = patterns[1]; } // Use cross product to figure out whether A and C are correct or flipped. // This asks whether BC x BA has a positive z component, which is the arrangement // we want for A, B, C. If it's negative, then we've got it flipped around and // should swap A and C. if (crossProductZ(pointA, pointB, pointC) < 0.0) { var temp = pointA; pointA = pointC; pointC = temp; } patterns[0] = pointA; patterns[1] = pointB; patterns[2] = pointC; } }).call({}); },{"./decoder":11,"./detector":12}],20:[function(require,module,exports){ /* Ported to JavaScript by Lazar Laszlo 2011 [email protected], www.lazarsoft.info */ /* * * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ !(function() { 'use strict'; var GF256 = require('./gf256'); var GF256Poly = require('./gf256poly'); module.exports = function(field) { this.field = field; this.decode=function(received, twoS) { var poly = new GF256Poly(this.field, received); var syndromeCoefficients = new Array(twoS); for(var i=0;i<syndromeCoefficients.length;i++)syndromeCoefficients[i]=0; var dataMatrix = false;//this.field.Equals(GF256.DATA_MATRIX_FIELD); var noError = true; for (var i = 0; i < twoS; i++) { // Thanks to sanfordsquires for this fix: var evalResult = poly.evaluateAt(this.field.exp(dataMatrix?i + 1:i)); syndromeCoefficients[syndromeCoefficients.length - 1 - i] = evalResult; if (evalResult != 0) { noError = false; } } if (noError) { return ; } var syndrome = new GF256Poly(this.field, syndromeCoefficients); var sigmaOmega = this.runEuclideanAlgorithm(this.field.buildMonomial(twoS, 1), syndrome, twoS); var sigma = sigmaOmega[0]; var omega = sigmaOmega[1]; var errorLocations = this.findErrorLocations(sigma); var errorMagnitudes = this.findErrorMagnitudes(omega, errorLocations, dataMatrix); for (var i = 0; i < errorLocations.length; i++) { var position = received.length - 1 - this.field.log(errorLocations[i]); if (position < 0) { throw "ReedSolomonException Bad error location"; } received[position] = GF256.addOrSubtract(received[position], errorMagnitudes[i]); } } this.runEuclideanAlgorithm=function( a, b, R) { // Assume a's degree is >= b's if (a.Degree < b.Degree) { var temp = a; a = b; b = temp; } var rLast = a; var r = b; var sLast = this.field.One; var s = this.field.Zero; var tLast = this.field.Zero; var t = this.field.One; // Run Euclidean algorithm until r's degree is less than R/2 while (r.Degree >= Math.floor(R / 2)) { var rLastLast = rLast; var sLastLast = sLast; var tLastLast = tLast; rLast = r; sLast = s; tLast = t; // Divide rLastLast by rLast, with quotient in q and remainder in r if (rLast.Zero) { // Oops, Euclidean algorithm already terminated? throw "r_{i-1} was zero"; } r = rLastLast; var q = this.field.Zero; var denominatorLeadingTerm = rLast.getCoefficient(rLast.Degree); var dltInverse = this.field.inverse(denominatorLeadingTerm); while (r.Degree >= rLast.Degree && !r.Zero) { var degreeDiff = r.Degree - rLast.Degree; var scale = this.field.multiply(r.getCoefficient(r.Degree), dltInverse); q = q.addOrSubtract(this.field.buildMonomial(degreeDiff, scale)); r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale)); //r.EXE(); } s = q.multiply1(sLast).addOrSubtract(sLastLast); t = q.multiply1(tLast).addOrSubtract(tLastLast); } var sigmaTildeAtZero = t.getCoefficient(0); if (sigmaTildeAtZero == 0) { throw "ReedSolomonException sigmaTilde(0) was zero"; } var inverse = this.field.inverse(sigmaTildeAtZero); var sigma = t.multiply2(inverse); var omega = r.multiply2(inverse); return new Array(sigma, omega); } this.findErrorLocations=function( errorLocator) { // This is a direct application of Chien's search var numErrors = errorLocator.Degree; if (numErrors == 1) { // shortcut return new Array(errorLocator.getCoefficient(1)); } var result = new Array(numErrors); var e = 0; for (var i = 1; i < 256 && e < numErrors; i++) { if (errorLocator.evaluateAt(i) == 0) { result[e] = this.field.inverse(i); e++; } } if (e != numErrors) { throw "Error locator degree does not match number of roots"; } return result; } this.findErrorMagnitudes=function( errorEvaluator, errorLocations, dataMatrix) { // This is directly applying Forney's Formula var s = errorLocations.length; var result = new Array(s); for (var i = 0; i < s; i++) { var xiInverse = this.field.inverse(errorLocations[i]); var denominator = 1; for (var j = 0; j < s; j++) { if (i != j) { denominator = this.field.multiply(denominator, GF256.addOrSubtract(1, this.field.multiply(errorLocations[j], xiInverse))); } } result[i] = this.field.multiply(errorEvaluator.evaluateAt(xiInverse), this.field.inverse(denominator)); // Thanks to sanfordsquires for this fix: if (dataMatrix) { result[i] = this.field.multiply(result[i], xiInverse); } } return result; } } }).call({}); },{"./gf256":16,"./gf256poly":17}],21:[function(require,module,exports){ /* Ported to JavaScript by Lazar Laszlo 2011 [email protected], www.lazarsoft.info */ /* * * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ !(function() { 'use strict'; module.exports = function( number, bits) { if (number >= 0) return number >> bits; else return (number >> bits) + (2 << ~bits); } }).call({}); },{}],22:[function(require,module,exports){ /* Ported to JavaScript by Lazar Laszlo 2011 [email protected], www.lazarsoft.info */ /* * * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ !(function() { 'use strict'; var BitMatrix = require('./bitmat'); var FormatInformation = require('./formatinf'); function ECB(count, dataCodewords) { this.count = count; this.dataCodewords = dataCodewords; this.__defineGetter__("Count", function() { return this.count; }); this.__defineGetter__("DataCodewords", function() { return this.dataCodewords; }); } function ECBlocks( ecCodewordsPerBlock, ecBlocks1, ecBlocks2) { this.ecCodewordsPerBlock = ecCodewordsPerBlock; if(ecBlocks2) this.ecBlocks = new Array(ecBlocks1, ecBlocks2); else this.ecBlocks = new Array(ecBlocks1); this.__defineGetter__("ECCodewordsPerBlock", function() { return this.ecCodewordsPerBlock; }); this.__defineGetter__("TotalECCodewords", function() { return this.ecCodewordsPerBlock * this.NumBlocks; }); this.__defineGetter__("NumBlocks", function() { var total = 0; for (var i = 0; i < this.ecBlocks.length; i++) { total += this.ecBlocks[i].length; } return total; }); this.getECBlocks=function() { return this.ecBlocks; } } var Version = module.exports = function( versionNumber, alignmentPatternCenters, ecBlocks1, ecBlocks2, ecBlocks3, ecBlocks4) { this.versionNumber = versionNumber; this.alignmentPatternCenters = alignmentPatternCenters; this.ecBlocks = new Array(ecBlocks1, ecBlocks2, ecBlocks3, ecBlocks4); var total = 0; var ecCodewords = ecBlocks1.ECCodewordsPerBlock; var ecbArray = ecBlocks1.getECBlocks(); for (var i = 0; i < ecbArray.length; i++) { var ecBlock = ecbArray[i]; total += ecBlock.Count * (ecBlock.DataCodewords + ecCodewords); } this.totalCodewords = total; this.__defineGetter__("VersionNumber", function() { return this.versionNumber; }); this.__defineGetter__("AlignmentPatternCenters", function() { return this.alignmentPatternCenters; }); this.__defineGetter__("TotalCodewords", function() { return this.totalCodewords; }); this.__defineGetter__("DimensionForVersion", function() { return 17 + 4 * this.versionNumber; }); this.buildFunctionPattern=function() { var dimension = this.DimensionForVersion; var bitMatrix = new BitMatrix(dimension); // Top left finder pattern + separator + format bitMatrix.setRegion(0, 0, 9, 9); // Top right finder pattern + separator + format bitMatrix.setRegion(dimension - 8, 0, 8, 9); // Bottom left finder pattern + separator + format bitMatrix.setRegion(0, dimension - 8, 9, 8); // Alignment patterns var max = this.alignmentPatternCenters.length; for (var x = 0; x < max; x++) { var i = this.alignmentPatternCenters[x] - 2; for (var y = 0; y < max; y++) { if ((x == 0 && (y == 0 || y == max - 1)) || (x == max - 1 && y == 0)) { // No alignment patterns near the three finder paterns continue; } bitMatrix.setRegion(this.alignmentPatternCenters[y] - 2, i, 5, 5); } } // Vertical timing pattern bitMatrix.setRegion(6, 9, 1, dimension - 17); // Horizontal timing pattern bitMatrix.setRegion(9, 6, dimension - 17, 1); if (this.versionNumber > 6) { // Version info, top right bitMatrix.setRegion(dimension - 11, 0, 3, 6); // Version info, bottom left bitMatrix.setRegion(0, dimension - 11, 6, 3); } return bitMatrix; } this.getECBlocksForLevel=function( ecLevel) { return this.ecBlocks[ecLevel.ordinal()]; } } Version.VERSION_DECODE_INFO = new Array(0x07C94, 0x085BC, 0x09A99, 0x0A4D3, 0x0BBF6, 0x0C762, 0x0D847, 0x0E60D, 0x0F928, 0x10B78, 0x1145D, 0x12A17, 0x13532, 0x149A6, 0x15683, 0x168C9, 0x177EC, 0x18EC4, 0x191E1, 0x1AFAB, 0x1B08E, 0x1CC1A, 0x1D33F, 0x1ED75, 0x1F250, 0x209D5, 0x216F0, 0x228BA, 0x2379F, 0x24B0B, 0x2542E, 0x26A64, 0x27541, 0x28C69); Version.VERSIONS = buildVersions(); Version.getVersionForNumber=function( versionNumber) { if (versionNumber < 1 || versionNumber > 40) { throw "ArgumentException"; } return Version.VERSIONS[versionNumber - 1]; } Version.getProvisionalVersionForDimension=function(dimension) { if (dimension % 4 != 1) { throw "Error getProvisionalVersionForDimension"; } try { return Version.getVersionForNumber((dimension - 17) >> 2); } catch ( iae) { throw "Error getVersionForNumber"; } } Version.decodeVersionInformation=function( versionBits) { var bestDifference = 0xffffffff; var bestVersion = 0; for (var i = 0; i < Version.VERSION_DECODE_INFO.length; i++) { var targetVersion = Version.VERSION_DECODE_INFO[i]; // Do the version info bits match exactly? done. if (targetVersion == versionBits) { return this.getVersionForNumber(i + 7); } // Otherwise see if this is the closest to a real version info bit string // we have seen so far var bitsDifference = FormatInformation.numBitsDiffering(versionBits, targetVersion); if (bitsDifference < bestDifference) { bestVersion = i + 7; bestDifference = bitsDifference; } } // We can tolerate up to 3 bits of error since no two version info codewords will // differ in less than 4 bits. if (bestDifference <= 3) { return this.getVersionForNumber(bestVersion); } // If we didn't find a close enough match, fail return null; } function buildVersions() { return new Array(new Version(1, new Array(), new ECBlocks(7, new ECB(1, 19)), new ECBlocks(10, new ECB(1, 16)), new ECBlocks(13, new ECB(1, 13)), new ECBlocks(17, new ECB(1, 9))), new Version(2, new Array(6, 18), new ECBlocks(10, new ECB(1, 34)), new ECBlocks(16, new ECB(1, 28)), new ECBlocks(22, new ECB(1, 22)), new ECBlocks(28, new ECB(1, 16))), new Version(3, new Array(6, 22), new ECBlocks(15, new ECB(1, 55)), new ECBlocks(26, new ECB(1, 44)), new ECBlocks(18, new ECB(2, 17)), new ECBlocks(22, new ECB(2, 13))), new Version(4, new Array(6, 26), new ECBlocks(20, new ECB(1, 80)), new ECBlocks(18, new ECB(2, 32)), new ECBlocks(26, new ECB(2, 24)), new ECBlocks(16, new ECB(4, 9))), new Version(5, new Array(6, 30), new ECBlocks(26, new ECB(1, 108)), new ECBlocks(24, new ECB(2, 43)), new ECBlocks(18, new ECB(2, 15), new ECB(2, 16)), new ECBlocks(22, new ECB(2, 11), new ECB(2, 12))), new Version(6, new Array(6, 34), new ECBlocks(18, new ECB(2, 68)), new ECBlocks(16, new ECB(4, 27)), new ECBlocks(24, new ECB(4, 19)), new ECBlocks(28, new ECB(4, 15))), new Version(7, new Array(6, 22, 38), new ECBlocks(20, new ECB(2, 78)), new ECBlocks(18, new ECB(4, 31)), new ECBlocks(18, new ECB(2, 14), new ECB(4, 15)), new ECBlocks(26, new ECB(4, 13), new ECB(1, 14))), new Version(8, new Array(6, 24, 42), new ECBlocks(24, new ECB(2, 97)), new ECBlocks(22, new ECB(2, 38), new ECB(2, 39)), new ECBlocks(22, new ECB(4, 18), new ECB(2, 19)), new ECBlocks(26, new ECB(4, 14), new ECB(2, 15))), new Version(9, new Array(6, 26, 46), new ECBlocks(30, new ECB(2, 116)), new ECBlocks(22, new ECB(3, 36), new ECB(2, 37)), new ECBlocks(20, new ECB(4, 16), new ECB(4, 17)), new ECBlocks(24, new ECB(4, 12), new ECB(4, 13))), new Version(10, new Array(6, 28, 50), new ECBlocks(18, new ECB(2, 68), new ECB(2, 69)), new ECBlocks(26, new ECB(4, 43), new ECB(1, 44)), new ECBlocks(24, new ECB(6, 19), new ECB(2, 20)), new ECBlocks(28, new ECB(6, 15), new ECB(2, 16))), new Version(11, new Array(6, 30, 54), new ECBlocks(20, new ECB(4, 81)), new ECBlocks(30, new ECB(1, 50), new ECB(4, 51)), new ECBlocks(28, new ECB(4, 22), new ECB(4, 23)), new ECBlocks(24, new ECB(3, 12), new ECB(8, 13))), new Version(12, new Array(6, 32, 58), new ECBlocks(24, new ECB(2, 92), new ECB(2, 93)), new ECBlocks(22, new ECB(6, 36), new ECB(2, 37)), new ECBlocks(26, new ECB(4, 20), new ECB(6, 21)), new ECBlocks(28, new ECB(7, 14), new ECB(4, 15))), new Version(13, new Array(6, 34, 62), new ECBlocks(26, new ECB(4, 107)), new ECBlocks(22, new ECB(8, 37), new ECB(1, 38)), new ECBlocks(24, new ECB(8, 20), new ECB(4, 21)), new ECBlocks(22, new ECB(12, 11), new ECB(4, 12))), new Version(14, new Array(6, 26, 46, 66), new ECBlocks(30, new ECB(3, 115), new ECB(1, 116)), new ECBlocks(24, new ECB(4, 40), new ECB(5, 41)), new ECBlocks(20, new ECB(11, 16), new ECB(5, 17)), new ECBlocks(24, new ECB(11, 12), new ECB(5, 13))), new Version(15, new Array(6, 26, 48, 70), new ECBlocks(22, new ECB(5, 87), new ECB(1, 88)), new ECBlocks(24, new ECB(5, 41), new ECB(5, 42)), new ECBlocks(30, new ECB(5, 24), new ECB(7, 25)), new ECBlocks(24, new ECB(11, 12), new ECB(7, 13))), new Version(16, new Array(6, 26, 50, 74), new ECBlocks(24, new ECB(5, 98), new ECB(1, 99)), new ECBlocks(28, new ECB(7, 45), new ECB(3, 46)), new ECBlocks(24, new ECB(15, 19), new ECB(2, 20)), new ECBlocks(30, new ECB(3, 15), new ECB(13, 16))), new Version(17, new Array(6, 30, 54, 78), new ECBlocks(28, new ECB(1, 107), new ECB(5, 108)), new ECBlocks(28, new ECB(10, 46), new ECB(1, 47)), new ECBlocks(28, new ECB(1, 22), new ECB(15, 23)), new ECBlocks(28, new ECB(2, 14), new ECB(17, 15))), new Version(18, new Array(6, 30, 56, 82), new ECBlocks(30, new ECB(5, 120), new ECB(1, 121)), new ECBlocks(26, new ECB(9, 43), new ECB(4, 44)), new ECBlocks(28, new ECB(17, 22), new ECB(1, 23)), new ECBlocks(28, new ECB(2, 14), new ECB(19, 15))), new Version(19, new Array(6, 30, 58, 86), new ECBlocks(28, new ECB(3, 113), new ECB(4, 114)), new ECBlocks(26, new ECB(3, 44), new ECB(11, 45)), new ECBlocks(26, new ECB(17, 21), new ECB(4, 22)), new ECBlocks(26, new ECB(9, 13), new ECB(16, 14))), new Version(20, new Array(6, 34, 62, 90), new ECBlocks(28, new ECB(3, 107), new ECB(5, 108)), new ECBlocks(26, new ECB(3, 41), new ECB(13, 42)), new ECBlocks(30, new ECB(15, 24), new ECB(5, 25)), new ECBlocks(28, new ECB(15, 15), new ECB(10, 16))), new Version(21, new Array(6, 28, 50, 72, 94), new ECBlocks(28, new ECB(4, 116), new ECB(4, 117)), new ECBlocks(26, new ECB(17, 42)), new ECBlocks(28, new ECB(17, 22), new ECB(6, 23)), new ECBlocks(30, new ECB(19, 16), new ECB(6, 17))), new Version(22, new Array(6, 26, 50, 74, 98), new ECBlocks(28, new ECB(2, 111), new ECB(7, 112)), new ECBlocks(28, new ECB(17, 46)), new ECBlocks(30, new ECB(7, 24), new ECB(16, 25)), new ECBlocks(24, new ECB(34, 13))), new Version(23, new Array(6, 30, 54, 74, 102), new ECBlocks(30, new ECB(4, 121), new ECB(5, 122)), new ECBlocks(28, new ECB(4, 47), new ECB(14, 48)), new ECBlocks(30, new ECB(11, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(16, 15), new ECB(14, 16))), new Version(24, new Array(6, 28, 54, 80, 106), new ECBlocks(30, new ECB(6, 117), new ECB(4, 118)), new ECBlocks(28, new ECB(6, 45), new ECB(14, 46)), new ECBlocks(30, new ECB(11, 24), new ECB(16, 25)), new ECBlocks(30, new ECB(30, 16), new ECB(2, 17))), new Version(25, new Array(6, 32, 58, 84, 110), new ECBlocks(26, new ECB(8, 106), new ECB(4, 107)), new ECBlocks(28, new ECB(8, 47), new ECB(13, 48)), new ECBlocks(30, new ECB(7, 24), new ECB(22, 25)), new ECBlocks(30, new ECB(22, 15), new ECB(13, 16))), new Version(26, new Array(6, 30, 58, 86, 114), new ECBlocks(28, new ECB(10, 114), new ECB(2, 115)), new ECBlocks(28, new ECB(19, 46), new ECB(4, 47)), new ECBlocks(28, new ECB(28, 22), new ECB(6, 23)), new ECBlocks(30, new ECB(33, 16), new ECB(4, 17))), new Version(27, new Array(6, 34, 62, 90, 118), new ECBlocks(30, new ECB(8, 122), new ECB(4, 123)), new ECBlocks(28, new ECB(22, 45), new ECB(3, 46)), new ECBlocks(30, new ECB(8, 23), new ECB(26, 24)), new ECBlocks(30, new ECB(12, 15), new ECB(28, 16))), new Version(28, new Array(6, 26, 50, 74, 98, 122), new ECBlocks(30, new ECB(3, 117), new ECB(10, 118)), new ECBlocks(28, new ECB(3, 45), new ECB(23, 46)), new ECBlocks(30, new ECB(4, 24), new ECB(31, 25)), new ECBlocks(30, new ECB(11, 15), new ECB(31, 16))), new Version(29, new Array(6, 30, 54, 78, 102, 126), new ECBlocks(30, new ECB(7, 116), new ECB(7, 117)), new ECBlocks(28, new ECB(21, 45), new ECB(7, 46)), new ECBlocks(30, new ECB(1, 23), new ECB(37, 24)), new ECBlocks(30, new ECB(19, 15), new ECB(26, 16))), new Version(30, new Array(6, 26, 52, 78, 104, 130), new ECBlocks(30, new ECB(5, 115), new ECB(10, 116)), new ECBlocks(28, new ECB(19, 47), new ECB(10, 48)), new ECBlocks(30, new ECB(15, 24), new ECB(25, 25)), new ECBlocks(30, new ECB(23, 15), new ECB(25, 16))), new Version(31, new Array(6, 30, 56, 82, 108, 134), new ECBlocks(30, new ECB(13, 115), new ECB(3, 116)), new ECBlocks(28, new ECB(2, 46), new ECB(29, 47)), new ECBlocks(30, new ECB(42, 24), new ECB(1, 25)), new ECBlocks(30, new ECB(23, 15), new ECB(28, 16))), new Version(32, new Array(6, 34, 60, 86, 112, 138), new ECBlocks(30, new ECB(17, 115)), new ECBlocks(28, new ECB(10, 46), new ECB(23, 47)), new ECBlocks(30, new ECB(10, 24), new ECB(35, 25)), new ECBlocks(30, new ECB(19, 15), new ECB(35, 16))), new Version(33, new Array(6, 30, 58, 86, 114, 142), new ECBlocks(30, new ECB(17, 115), new ECB(1, 116)), new ECBlocks(28, new ECB(14, 46), new ECB(21, 47)), new ECBlocks(30, new ECB(29, 24), new ECB(19, 25)), new ECBlocks(30, new ECB(11, 15), new ECB(46, 16))), new Version(34, new Array(6, 34, 62, 90, 118, 146), new ECBlocks(30, new ECB(13, 115), new ECB(6, 116)), new ECBlocks(28, new ECB(14, 46), new ECB(23, 47)), new ECBlocks(30, new ECB(44, 24), new ECB(7, 25)), new ECBlocks(30, new ECB(59, 16), new ECB(1, 17))), new Version(35, new Array(6, 30, 54, 78, 102, 126, 150), new ECBlocks(30, new ECB(12, 121), new ECB(7, 122)), new ECBlocks(28, new ECB(12, 47), new ECB(26, 48)), new ECBlocks(30, new ECB(39, 24), new ECB(14, 25)),new ECBlocks(30, new ECB(22, 15), new ECB(41, 16))), new Version(36, new Array(6, 24, 50, 76, 102, 128, 154), new ECBlocks(30, new ECB(6, 121), new ECB(14, 122)), new ECBlocks(28, new ECB(6, 47), new ECB(34, 48)), new ECBlocks(30, new ECB(46, 24), new ECB(10, 25)), new ECBlocks(30, new ECB(2, 15), new ECB(64, 16))), new Version(37, new Array(6, 28, 54, 80, 106, 132, 158), new ECBlocks(30, new ECB(17, 122), new ECB(4, 123)), new ECBlocks(28, new ECB(29, 46), new ECB(14, 47)), new ECBlocks(30, new ECB(49, 24), new ECB(10, 25)), new ECBlocks(30, new ECB(24, 15), new ECB(46, 16))), new Version(38, new Array(6, 32, 58, 84, 110, 136, 162), new ECBlocks(30, new ECB(4, 122), new ECB(18, 123)), new ECBlocks(28, new ECB(13, 46), new ECB(32, 47)), new ECBlocks(30, new ECB(48, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(42, 15), new ECB(32, 16))), new Version(39, new Array(6, 26, 54, 82, 110, 138, 166), new ECBlocks(30, new ECB(20, 117), new ECB(4, 118)), new ECBlocks(28, new ECB(40, 47), new ECB(7, 48)), new ECBlocks(30, new ECB(43, 24), new ECB(22, 25)), new ECBlocks(30, new ECB(10, 15), new ECB(67, 16))), new Version(40, new Array(6, 30, 58, 86, 114, 142, 170), new ECBlocks(30, new ECB(19, 118), new ECB(6, 119)), new ECBlocks(28, new ECB(18, 47), new ECB(31, 48)), new ECBlocks(30, new ECB(34, 24), new ECB(34, 25)), new ECBlocks(30, new ECB(20, 15), new ECB(61, 16)))); } }).call({}); },{"./bitmat":6,"./formatinf":15}],23:[function(require,module,exports){ var scan = require('./scanner.js'); var inp = document.getElementById('capture'); var results = require('./view/results.js')('.results'); inp.addEventListener('change', function(e) { var file = e.target.files[0]; if (!file) return; results.setScanning(true); scan(file, function(err, result, format) { results.setScanning(false); if (err) return alert(err); results.add(result); }); }, false); },{"./scanner.js":24,"./view/results.js":29}],24:[function(require,module,exports){ var scanQR = require('./util/scanqr.js'); var scanBarcode = require('./util/scanbarcode.js'); var imageFromFile = require('./util/image-from-file.js'); module.exports = function(file, callback) { imageFromFile(file, 250, 250, function(img) { scanQR(img, function(qrErr, result) { if (!qrErr && result) return callback(null, result, 'QR'); scanBarcode(img, function(barcodeErr, result, format) { if (barcodeErr) return callback(qrErr, null, null); if (result) return callback(null, result, format); }); }); }); }; },{"./util/image-from-file.js":26,"./util/scanbarcode.js":27,"./util/scanqr.js":28}],25:[function(require,module,exports){ module.exports = function(img, ctx) { var canvas = ctx.canvas ; var hRatio = canvas.width / img.width ; var vRatio = canvas.height / img.height ; var ratio = Math.min ( hRatio, vRatio ); var centerShift_x = ( canvas.width - img.width*ratio ) / 2; var centerShift_y = ( canvas.height - img.height*ratio ) / 2; ctx.clearRect(0,0,canvas.width, canvas.height); ctx.drawImage(img, 0,0, img.width, img.height, centerShift_x,centerShift_y,img.width*ratio, img.height*ratio); }; },{}],26:[function(require,module,exports){ var drawImageScaled = require('./draw-image-scaled.js'); module.exports = function(file, width, height, callback) { var img = new Image(); img.onload = function() { var canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; var ctx = canvas.getContext('2d'); drawImageScaled(img, ctx); var scaledImg = new Image(); scaledImg.onload = function() { callback(scaledImg); } scaledImg.src = canvas.toDataURL(); URL.revokeObjectURL(img.src); } img.src = URL.createObjectURL(file); }; },{"./draw-image-scaled.js":25}],27:[function(require,module,exports){ var BarcodeReader = require('barcode-reader'); var extCallback; BarcodeReader.Init(); BarcodeReader.DecodeSingleBarcode(); BarcodeReader.SetImageCallback(function(results) { if (!extCallback) return; if (results.length > 0) { var result = results[0]; extCallback(null, result.Value, result.Format); } else { extCallback('No barcode found'); } extCallback = null; }); module.exports = function(img, callback) { extCallback = callback; BarcodeReader.DecodeImage(img); } },{"barcode-reader":1}],28:[function(require,module,exports){ var qrcode = require('zxing'); var drawImageScaled = require('./draw-image-scaled.js'); module.exports = function(img, callback) { var canvas = document.getElementById('qr-canvas'); if (!canvas) { canvas = document.createElement('canvas'); canvas.style.display = 'none'; document.body.appendChild(canvas); } canvas.width = 500; canvas.height = 500; var ctx = canvas.getContext('2d'); drawImageScaled(img, ctx); qrcode.decode(callback); }; },{"./draw-image-scaled.js":25,"zxing":19}],29:[function(require,module,exports){ var isUrl = require('is-url'); function tmpl(value) { if (isUrl(value)) return '<a href="' + value + '">' + value + '</a>'; return value; } module.exports = function(selector) { var dom = document.querySelector(selector); return { add: function(value, format) { dom.innerHTML = '<li>' + tmpl(value, format) + '</li>' + dom.innerHTML; }, setScanning: function(isScanning) { if (isScanning) dom.classList.add('is-scanning'); else dom.classList.remove('is-scanning'); } } } },{"is-url":4}]},{},[23]);
mit
Krigu/bookstore
bookstore-jpa/src/main/java/org/books/data/dto/CustomerInfo.java
1687
package org.books.data.dto; import org.books.data.entity.Customer; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import java.io.Serializable; @XmlRootElement(name = "customerInfo") @XmlAccessorType(XmlAccessType.FIELD) @XmlType(propOrder = {"number", "email", "firstName", "lastName"}) public class CustomerInfo implements Serializable { private String email; private String firstName; private String lastName; private String number; public CustomerInfo() { } public CustomerInfo(String email, String firstName, String lastName, String number) { this.email = email; this.firstName = firstName; this.lastName = lastName; this.number = number; } public CustomerInfo(Customer customer) { this.email = customer.getEmail(); this.firstName = customer.getFirstName(); this.lastName = customer.getLastName(); this.number = customer.getNumber(); } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
mit
padosoft/laravel-affiliate-network
src/Networks/Admitad.php
7821
<?php namespace Padosoft\AffiliateNetwork\Networks; use Padosoft\AffiliateNetwork\Transaction; use Padosoft\AffiliateNetwork\DealsResultset; use Padosoft\AffiliateNetwork\Merchant; use Padosoft\AffiliateNetwork\Stat; use Padosoft\AffiliateNetwork\Deal; use Padosoft\AffiliateNetwork\AbstractNetwork; use Padosoft\AffiliateNetwork\NetworkInterface; use Padosoft\AffiliateNetwork\ProductsResultset; /** * Class Admitad * @package Padosoft\AffiliateNetwork\Networks */ class Admitad extends AbstractNetwork implements NetworkInterface { /** * @var object */ private $_network = null; private $_username = ''; private $_password = ''; private $_apiClient = null; protected $_tracking_parameter = ''; private $_idSite = ''; /** * @method __construct */ public function __construct(string $username, string $password, string $idSite='') { $this->_network = new \Oara\Network\Publisher\Admitad; $this->_username = $username; $this->_password = $password; $this->_idSite = $idSite; $this->login( $this->_username, $this->_password, $idSite ); } public function login(string $username, string $password,string $idSite=''): bool{ $this->_logged = false; if (isNullOrEmpty( $username ) || isNullOrEmpty( $password )) { return false; } $this->_username = $username; $this->_password = $password; $this->_idSite = $idSite; $credentials = array(); $credentials["user"] = $this->_username; $credentials["password"] = $this->_password; $credentials["idSite"] = $this->_idSite; $this->_network->login($credentials); if ($this->_network->checkConnection()) { $this->_logged = true; } return $this->_logged; } /** * @return bool */ public function checkLogin() : bool { return $this->_logged; } /** * @return array of Merchants * @throws \Exception */ public function getMerchants() : array { $arrResult = array(); $merchantList = $this->_network->getMerchantList(); foreach($merchantList as $merchant) { $Merchant = Merchant::createInstance(); $Merchant->merchant_ID = $merchant['cid']; $Merchant->name = $merchant['name']; $Merchant->status = $merchant['status']; $Merchant->url = $merchant['url']; if (!empty($merchant['launch_date'])) { $date = new \DateTime($merchant['launch_date']); $Merchant->launch_date = $date; } $arrResult[] = $Merchant; } return $arrResult; } /** * @param null $merchantID * @param int $page * @param int $items_per_page * @return DealsResultset array of Deal * @throws \Exception */ public function getDeals($merchantID=NULL,int $page=0,int $items_per_page=100 ): DealsResultset { $arrResult = array(); $result = DealsResultset::createInstance(); $arrVouchers = $this->_network->getVouchers($this->_idSite); foreach($arrVouchers as $voucher) { if (!empty($voucher['tracking']) && !empty($voucher['advertiser_id'])) { $Deal = Deal::createInstance(); $Deal->deal_ID = md5($voucher['tracking']); // Use link to generate a unique deal ID $Deal->merchant_ID = $voucher['advertiser_id']; $Deal->merchant_name = $voucher['advertiser_name']; $Deal->code = $voucher['code']; $Deal->name = $voucher['name']; $Deal->description = $voucher['description']; $Deal->start_date = $Deal->convertDate($voucher['start_date']); $Deal->end_date = $Deal->convertDate($voucher['end_date']); $Deal->default_track_uri = $voucher['tracking']; $Deal->discount_amount = $voucher['discount_amount']; $Deal->is_percentage = $voucher['is_percentage']; $Deal->is_exclusive = false; $Deal->deal_type = $voucher['type']; $arrResult[] = $Deal; } } $result->deals[]=$arrResult; return $result; } /** * @param \DateTime $dateFrom * @param \DateTime $dateTo * @param array $arrMerchantID * @return array of Transaction * @throws \Exception */ public function getSales(\DateTime $dateFrom, \DateTime $dateTo, array $arrMerchantID = array()) : array { $arrResult = array(); $transactionList = $this->_network->getTransactionList($arrMerchantID, $dateFrom, $dateTo); foreach($transactionList as $transaction) { $Transaction = Transaction::createInstance(); if (isset($transaction['currency']) && !empty($transaction['currency'])) { $Transaction->currency = $transaction['currency']; } else { $Transaction->currency = "EUR"; } $Transaction->status = $transaction['status']; $Transaction->amount = $transaction['amount']; array_key_exists_safe( $transaction,'custom_id' ) ? $Transaction->custom_ID = $transaction['custom_id'] : $Transaction->custom_ID = ''; $Transaction->title = ''; $Transaction->unique_ID = $transaction['unique_id']; $Transaction->commission = $transaction['commission']; $date = new \DateTime($transaction['date']); $Transaction->date = $date; // $date->format('Y-m-d H:i:s'); // Future use - Only few providers returns these dates values - <PN> - 2017-06-29 if (isset($transaction['click_date']) && !empty($transaction['click_date'])) { $Transaction->click_date = new \DateTime($transaction['click_date']); } if (isset($transaction['update_date']) && !empty($transaction['update_date'])) { $Transaction->update_date = new \DateTime($transaction['update_date']); } $Transaction->merchant_ID = $transaction['merchantId']; $Transaction->campaign_name = $transaction['merchantName']; $Transaction->IP = $transaction['IP']; $Transaction->approved = false; if ($Transaction->status == \Oara\Utilities::STATUS_CONFIRMED){ $Transaction->approved = true; } $arrResult[] = $Transaction; } return $arrResult; } /** * @param \DateTime $dateFrom * @param \DateTime $dateTo * @param int $merchantID * @return array of Stat */ public function getStats(\DateTime $dateFrom, \DateTime $dateTo, int $merchantID = 0) : array { // TODO return array(); /* $this->_apiClient->setConnectId($this->_username); $this->_apiClient->setSecretKey($this->_password); $dateFromIsoEngFormat = $dateFrom->format('Y-m-d'); $dateToIsoEngFormat = $dateTo->format('Y-m-d'); $response = $this->_apiClient->getReportBasic($dateFromIsoEngFormat, $dateToIsoEngFormat); $arrResponse = json_decode($response, true); $reportItems = $arrResponse['reportItems']; $Stat = Stat::createInstance(); $Stat->reportItems = $reportItems; return array($Stat); */ } /** * @param array $params * @return ProductsResultset * @throws \Exception */ public function getProducts(array $params = []): ProductsResultset { // TODO: Implement getProducts() method. throw new \Exception("Not implemented yet"); } public function getTrackingParameter(){ return $this->_tracking_parameter; } }
mit
Ivanbmstu/angular
src/app/modules/hero/service/hero.service.ts
3660
/** * Created by pohodnaivan on 03.06.17. */ import {Injectable} from '@angular/core'; import { Headers, Http } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import {Hero, MagicPower, Power} from '../../../models/Model'; import AuthService = require("../../../service/web/auth.service"); import {User} from "../../../models/Model"; import {MdSnackBar} from "@angular/material"; import {CommonCrudService} from '../../shared/editor/common-crud.service'; @Injectable() export class HeroService extends CommonCrudService { private heroesUrl = 'api/heroes'; // URL to web api private headers = new Headers({'Content-Type': 'application/json'}); private currentUser: User; constructor(private http: Http, private authService: AuthService, snackBar: MdSnackBar) { super(snackBar); this.currentUser = authService.getCurrentUser(); this.authService.authorizeObservable().subscribe((user: User) => { this.currentUser = user; }); } getHeroes(): Promise<Hero[]> { return this.currentUser ? Promise.resolve(this.currentUser.heroes) : Promise.resolve([]); } private handleError(error: any): Promise<any> { console.error('An error occurred', error); // for demo purposes only return Promise.reject(error.message || error); } getHero(id: number): Promise<Hero> { let user = this.authService.getCurrentUser(); if (user) { return new Promise((res) => { setTimeout(() => { res(user.heroes.find((p) => p.id === id)); }, 1000); }); } else { return Promise.resolve(null); } } update(hero: Hero): Promise<boolean> { let promise = this.doUpdateHero(hero); promise.then(this.onOperationPerformedNotify('update')); return promise; } doUpdateHero(hero: Hero): Promise<boolean> { let user = this.authService.getCurrentUser(); if (user) { return new Promise((res) => { setTimeout(() => { // todo remove id assignment user.heroes = user.heroes.filter((stored) => stored.id !== hero.id); user.heroes.push(hero); const updatedPowerIds = hero.powers.map((power) => power.id); user.powers = user.powers.filter((power) => updatedPowerIds.indexOf(power.id) === -1); user.powers = user.powers.concat(hero.powers); res(true); }, 1000); }); } else { return Promise.resolve(false); } } doCreateHero(hero: Hero): Promise<boolean> { let user = this.authService.getCurrentUser(); if (user) { return new Promise((res) => { setTimeout(() => { // todo remove id assignment hero.id = 999; user.heroes.push(hero); user.powers = user.powers.concat(hero.powers); res(true); }, 1000); }); } else { return Promise.resolve(false); } } create(hero: Hero): Promise<boolean> { let promise = this.doCreateHero(hero); promise.then(this.onOperationPerformedNotify('create')); return promise; } delete(id: number): Promise<void> { const url = `${this.heroesUrl}/${id}`; return this.http.delete(url, {headers: this.headers}) .toPromise() .then(() => null) .catch(this.handleError); } } export class HeroServiceUpperCase extends HeroService { async getHeroes(): Promise<Hero[]> { let heroes = await super.getHeroes(); heroes.forEach((item) => { item.name = item.name.toUpperCase(); }); return heroes; } } export let heroServiceFactory = (http: Http, authService: AuthService, snackBar: MdSnackBar) => { return new HeroService(http, authService, snackBar); };
mit
sourcegraph/python-langserver
test/test_graphql_core.py
2331
from .harness import Harness import uuid import pytest graphql_core_workspace = Harness("repos/graphql-core") graphql_core_workspace.initialize( "git://github.com/plangrid/graphql-core?" + str(uuid.uuid4())) def test_relative_import_definition(): result = graphql_core_workspace.definition("/graphql/__init__.py", 52, 8) assert result == [ { 'symbol': { 'package': { 'name': 'graphql' }, 'name': 'GraphQLObjectType', 'container': 'graphql.type.definition', 'kind': 'class', 'file': 'definition.py', 'position': { 'line': 138, 'character': 6 } }, 'location': { 'uri': 'file:///graphql/type/definition.py', 'range': { 'start': { 'line': 138, 'character': 6 }, 'end': { 'line': 138, 'character': 23 } } } }, { 'symbol': { 'package': { 'name': 'graphql' }, 'name': 'GraphQLObjectType', 'container': 'graphql.type', 'kind': 'class', 'file': '__init__.py', 'position': { 'line': 3, 'character': 4 } }, 'location': { 'uri': 'file:///graphql/type/__init__.py', 'range': { 'start': { 'line': 3, 'character': 4 }, 'end': { 'line': 3, 'character': 21 } } } }, ] # TODO(aaron): not all relative imports work; seems to be a Jedi bug, as # it appears in other Jedi-based extensions too @pytest.mark.skip(reason="Jedi bug") def test_relative_import_definition_broken(): result = graphql_core_workspace.definition("/graphql/__init__.py", 52, 8) assert result == []
mit
Jecma/JecmaBlog
vendor/texy/texy/examples/syntax highlighting/demo-fshl.php
1818
<?php /** * This demo shows how combine Texy! with syntax highlighter FSHL * - define user callback (for /--code elements) */ // include libs require_once __DIR__ . '/../../src/texy.php'; $fshlPath = __DIR__.'/fshl/'; @include_once $fshlPath . 'fshl.php'; if (!class_exists('fshlParser')) { die('DOWNLOAD <a href="http://hvge.sk/scripts/fshl/">FSHL</a> AND UNPACK TO FSHL FOLDER FIRST!'); } /** * User handler for code block * @return Texy\HtmlElement */ function blockHandler(Texy\HandlerInvocation $invocation, $blocktype, $content, $lang, Texy\Modifier $modifier) { if ($blocktype !== 'block/code') { return $invocation->proceed(); } $lang = strtoupper($lang); if ($lang == 'JAVASCRIPT') { $lang = 'JS'; } $fshl = new fshlParser('HTML_UTF8', P_TAB_INDENT); if (!$fshl->isLanguage($lang)) { return $invocation->proceed(); } $texy = $invocation->getTexy(); $content = Texy\Helpers::outdent($content); $content = $fshl->highlightString($lang, $content); $content = $texy->protect($content, $texy::CONTENT_BLOCK); $elPre = new Texy\HtmlElement('pre'); if ($modifier) { $modifier->decorate($texy, $elPre); } $elPre->attrs['class'] = strtolower($lang); $elCode = $elPre->create('code', $content); return $elPre; } $texy = new Texy(); $texy->addHandler('block', 'blockHandler'); // processing $text = file_get_contents('sample.texy'); $html = $texy->process($text); // that's all folks! // echo Geshi Stylesheet header('Content-type: text/html; charset=utf-8'); echo '<style type="text/css">'. file_get_contents($fshlPath.'styles/COHEN_style.css') . '</style>'; echo '<title>' . $texy->headingModule->title . '</title>'; // echo formated output echo $html; // and echo generated HTML code echo '<hr />'; echo '<pre>'; echo htmlSpecialChars($html); echo '</pre>';
mit
AdiSai/FRC_Scouting_V2
FRC_Scouting_V2.Desktop/Events/2015_RecycleRush/RecycleRush_Northbay_Information.cs
6249
//*********************************License*************************************** //=============================================================================== //The MIT License (MIT) //Copyright (c) 2014 FRC_Scouting_V2 //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: //The above copyright notice and this permission notice shall be included in all //copies or substantial portions of the Software. //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. //=============================================================================== using System; using System.Windows.Forms; using FRC_Scouting_V2.Properties; namespace FRC_Scouting_V2.Events._2015_RecycleRush { public partial class RecycleRush_Northbay_Information : Form { private readonly Random gen = new Random(); private int previousNum; private int randomNum = 100; private string sponsorLevel; private string sponsorName; public RecycleRush_Northbay_Information() { InitializeComponent(); } private void RecycleRush_Northbay_Information_Load(object sender, EventArgs e) { randomNum = gen.Next(13); previousNum = randomNum; UpdateSponsor(); timer1.Tick += timer_Tick; timer1.Start(); } public void UpdateSponsor() { switch (randomNum) { case 0: sponsorPictureBox.Image = Resources.fednor_platinum_northbay_2014; sponsorName = ("FedNor"); sponsorLevel = ("Platinum"); break; case 1: sponsorPictureBox.Image = Resources.redpath_platinum_northbay_2014; sponsorName = ("RedPath"); sponsorLevel = ("Platinum"); break; case 2: sponsorPictureBox.Image = Resources.nipu_platinum_northbay_2014; sponsorName = ("Nipissing University"); sponsorLevel = ("Platinum"); break; case 3: sponsorPictureBox.Image = Resources.atlascopco_gold_northbay_2014; sponsorName = ("Atlas Copco"); sponsorLevel = ("Gold"); break; case 4: sponsorPictureBox.Image = Resources.twg_gold_northbay_2014; sponsorName = ("twg* Communications"); sponsorLevel = ("Gold"); break; case 5: sponsorPictureBox.Image = Resources.ontario_silver_northbay_2014; sponsorName = ("Ontario | Northern Ontario Heritage Fund Corporation"); sponsorLevel = ("Silver"); break; case 6: sponsorPictureBox.Image = Resources.forbetteorforworse_silver_northbay_2014; sponsorName = ("For Better for Worse"); sponsorLevel = ("Silver"); break; case 7: sponsorPictureBox.Image = Resources.canadore_silver_northbay_2014; sponsorName = ("Canadore College"); sponsorLevel = ("Silver"); break; case 8: sponsorPictureBox.Image = Resources.stantec_bronze_northbay_2014; sponsorName = ("Stantec"); sponsorLevel = ("Bronze"); break; case 9: sponsorPictureBox.Image = Resources.north_bay_strategicpartner_northbay_2014; sponsorName = ("North Bay"); sponsorLevel = ("Strategic Partner"); break; case 10: sponsorPictureBox.Image = Resources.nearnorth_strategicpartner_northbay_2014; sponsorName = ("Near North District School Board"); sponsorLevel = ("Strategic Partner"); break; case 11: sponsorPictureBox.Image = Resources.metso_inkind_northbay_2014; sponsorName = ("Metso Minerals"); sponsorLevel = ("In Kind"); break; case 12: sponsorPictureBox.Image = Resources.astowing_inkind_northbay_2014; sponsorName = ("A&S Towing"); sponsorLevel = ("In Kind"); break; case 13: sponsorPictureBox.Image = Resources.sms_inkind_northbay_2014; sponsorName = ("SMS Rents"); sponsorLevel = ("In Kind"); break; } sponsorLevelDisplayLabel.Text = ("Sponsor Level: " + sponsorLevel); sponsorNameDisplayLabel.Text = ("Sponsor Name: " + sponsorName); } private void timer_Tick(object sender, EventArgs e) { randomNum = gen.Next(13); if (randomNum != previousNum) { UpdateSponsor(); } else { randomNum = gen.Next(13); UpdateSponsor(); } previousNum = randomNum; } } }
mit
YanZhiwei/DotNet.Utilities
YanZhiwei.DotNet.Core.DownloadExamples/BackHandler/FileDownloadHandler.ashx.cs
722
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Web; using YanZhiwei.DotNet.Core.Download; namespace YanZhiwei.DotNet.Core.DownloadExamples.BackHandler { /// <summary> /// DownloadHandler 的摘要说明 /// </summary> public class FileDownloadHandler : DownloadHandler { public override string GetResult(string fileName, string filePath, string err) { return err; } public override void OnDownloaded(HttpContext context, string fileName, string filePath) { Debug.WriteLine(string.Format("文件[{0}]下载成功,映射路径:{1}", fileName, filePath)); } } }
mit
bdebor/cine-project
src/CineProject/PublicBundle/Entity/Movie.php
6706
<?php namespace CineProject\PublicBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; /** * Movie * * @ORM\Table(name="movie") * @ORM\Entity(repositoryClass="CineProject\PublicBundle\Repository\MovieRepository") */ class Movie { /** * @var int * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * @Assert\NotBlank(message = "Vous devez saisir un titre") * @Assert\Length( * min = 5, * max = 50, * minMessage = "Your first name must be at least {{ limit }} characters long", * maxMessage = "Your first name cannot be longer than {{ limit }} characters" * ) * * @ORM\Column(name="title", type="string", length=255) */ private $title; /** * @var string * * @ORM\Column(name="description", type="text") */ private $description; /** * @var \DateTime * * @ORM\Column(name="release_date", type="datetime") */ private $releaseDate; /** * @var boolean * * @ORM\Column(name="visible", type="boolean") */ private $visible; /** * @ORM\ManyToMany(targetEntity="CineProject\PublicBundle\Entity\Actor", inversedBy="movies") */ private $actors; /** * @var integer * @ORM\Column(name="grade", type="integer", nullable=true) */ private $grade; /** * @ORM\ManyToOne(targetEntity="CineProject\PublicBundle\Entity\Category", inversedBy="movies") */ private $category; /** * @ORM\ManyToMany(targetEntity="CineProject\PublicBundle\Entity\Director", inversedBy="movies") */ private $directors; /** * @ORM\OneToMany(targetEntity="CineProject\PublicBundle\Entity\Category", mappedBy="movie") */ private $sessions; public function __construct() { $this->actors = new ArrayCollection(); $this->directors = new ArrayCollection(); $this->sessions = new ArrayCollection(); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set title * * @param string $title * @return Movie */ public function setTitle($title) { $this->title = $title; return $this; } /** * Get title * * @return string */ public function getTitle() { return $this->title; } /** * Set description * * @param string $description * @return Movie */ public function setDescription($description) { $this->description = $description; return $this; } /** * Get description * * @return string */ public function getDescription() { return $this->description; } /** * Set releaseDate * * @param \DateTime $releaseDate * @return Movie */ public function setReleaseDate($releaseDate) { $this->releaseDate = $releaseDate; return $this; } /** * Get releaseDate * * @return \DateTime */ public function getReleaseDate() { return $this->releaseDate; } /** * Set visible * * @param boolean $visible * @return Movie */ public function setVisible($visible) { $this->visible = $visible; return $this; } /** * Get visible * * @return boolean */ public function getVisible() { return $this->visible; } /** * Add actors * * @param \CineProject\PublicBundle\Entity\Actor $actors * @return Movie */ public function addActor(\CineProject\PublicBundle\Entity\Actor $actors) { $this->actors[] = $actors; return $this; } /** * Remove actors * * @param \CineProject\PublicBundle\Entity\Actor $actors */ public function removeActor(\CineProject\PublicBundle\Entity\Actor $actors) { $this->actors->removeElement($actors); } /** * Get actors * * @return \Doctrine\Common\Collections\Collection */ public function getActors() { return $this->actors; } /** * Set grade * * @param integer $grade * @return Movie */ public function setGrade($grade) { $this->grade = $grade; return $this; } /** * Get grade * * @return integer */ public function getGrade() { return $this->grade; } /** * Set category * * @param \CineProject\PublicBundle\Entity\Category $category * @return Movie */ public function setCategory(\CineProject\PublicBundle\Entity\Category $category = null) { $this->category = $category; return $this; } /** * Get category * * @return \CineProject\PublicBundle\Entity\Category */ public function getCategory() { return $this->category; } /** * Add directors * * @param \CineProject\PublicBundle\Entity\Director $directors * @return Movie */ public function addDirector(\CineProject\PublicBundle\Entity\Director $directors) { $this->directors[] = $directors; return $this; } /** * Remove directors * * @param \CineProject\PublicBundle\Entity\Director $directors */ public function removeDirector(\CineProject\PublicBundle\Entity\Director $directors) { $this->directors->removeElement($directors); } /** * Get directors * * @return \Doctrine\Common\Collections\Collection */ public function getDirectors() { return $this->directors; } /** * Add sessions * * @param \CineProject\PublicBundle\Entity\Category $sessions * @return Movie */ public function addSession(\CineProject\PublicBundle\Entity\Category $sessions) { $this->sessions[] = $sessions; return $this; } /** * Remove sessions * * @param \CineProject\PublicBundle\Entity\Category $sessions */ public function removeSession(\CineProject\PublicBundle\Entity\Category $sessions) { $this->sessions->removeElement($sessions); } /** * Get sessions * * @return \Doctrine\Common\Collections\Collection */ public function getSessions() { return $this->sessions; } }
mit
tomaszdurka/CM
client-vendor/after-body-source/cm/tests/media/audioTest.js
379
require(['cm/tests/media/common'], function(common) { require(["cm/media/audio"], function(Audio) { QUnit.module('cm/media/audio'); if ('HTMLAudioElement' in window) { var audioUrl = 'client-vendor/after-body-source/cm/tests/resources/opus-48khz.weba'; common.test(Audio, audioUrl); } else { // skip on phantomjs common.skip(); } }); });
mit
LibreGSX/api_server
controllers/v1/public.js
31219
var models = require("../../models"); var bcrypt = require('bcrypt'); var jwt = require('jsonwebtoken'); var blacklist = require('express-jwt-blacklist'); var uuid = require('uuid-v4'); var fs = require('fs'); var sg = require('sendgrid')('INSERT SENDGRID API KEY HERE') var jwtPrivateKey = fs.readFileSync(appRoot + '/keys/jwt/private.pem'); var Public = function() {}; Public.prototype.account = {}; Public.prototype.devices = {}; blacklist.configure({ strict: false, store: { type: 'redis', host: '127.0.0.1', port: 6379, keyPrefix: 'jwt-blacklist:' }, tokenId: 'uuid', indexBy: 'iat', }); Public.prototype.authenticate = function(req, res) { models.accounts.gsx_organisations_users_accounts.findOne({ where: { user_email: req.body.email, deleted_at: null } }).then(function(data) { if (data) { switch (data.get('user_account_status')) { case "ACTIVE": { bcrypt.compare(req.body.password, data.get('user_password_hash'), function(err, valid) { if (valid && !err) { var sessionToken = jwt.sign({ uuid: data.get('user_uuid'), permissions: JSON.parse(data.get('user_permissions_scopes')) || "", }, jwtPrivateKey, { algorithm: 'ES256', issuer: 'com.libregsx.api.web.v1', notBefore: -60, expiresIn: 21600 }); res.cookie('sc', sessionToken, { domain: '.libregsx.com', //secure: true, httpOnly: true, maxAge: 21600000, }); res.status(200).json({ status: "success", data: { sessionToken: sessionToken } }); } else if (err) { res.status(500).json({ status: "error", message: "An error has occurred whilst authenticating." }); } else { res.status(401).json({ status: "fail", data: { message: "The password you entered is incorrect." } }); } }); break; } case "EMAIL_ACTIVATION": { res.status(401).json({ status: "fail", data: { message: "Please verify your email address." } }); break; } case "ORG_ACTIVATION": { if (data.get('user_email_status') == 'UNVERIFIED') { res.status(401).json({ status: "fail", data: { message: "Please verify your email address." } }); } else { res.status(401).json({ status: "fail", data: { message: "Waiting for authorization from your organisation." } }); } break; } case "SUSPENDED": { res.status(401).json({ status: "fail", data: { message: "Account currently suspended. Please contact support." } }); break; } case "INACTIVE": { res.status(400).json({ status: "fail", data: { message: "User not found." } }); break; } default: { res.status(400).json({ status: "fail", data: { message: "User not found." } }); break; } } } else { res.status(400).json({ status: "fail", data: { message: "User not found." } }); } }).error(function(err) { res.status(500).json({ status: "error", message: "An error occurred during authentication." }); }).catch(function(err) { res.status(500).json({ status: "error", message: "An error occurred during authentication." }); }); }; Public.prototype.logout = function(req, res) { blacklist.revoke(req.user, 21600, function(err) { if (!err) { res.json({ status: 'success', data: { message: "Successfully logged out." } }); } else { res.json({ status: 'error', message: "An error occurred whilst logging you out." }); } }); } Public.prototype.account.register = function(req, res) { switch (req.body.regType) { case "createOrganisation": { var organisationUuid = uuid(); var passwordHash = bcrypt.hashSync(req.body.password, 12); generateAccountId(function(err, accountId) { if (!err && accountId !== undefined && organisationUuid !== undefined && passwordHash !== undefined) { models.accounts.gsx_organisations_users_accounts.findOrCreate({ where: { user_email: req.body.email, deleted_at: null }, defaults: { user_uuid: uuid(), user_first_name: req.body.first_name, user_last_name: req.body.last_name, user_email: req.body.email, user_email_status: 'UNVERIFIED', user_account_status: 'EMAIL_ACTIVATION', user_password_hash: passwordHash, user_account_id: accountId, user_organisation_uuid: organisationUuid, user_organisation_role: 'ADMIN', user_permissions_scopes: '[]', created_at: Math.floor(Date.now() / 1000) } }).spread(function(data, created) { if (data && created == true) { models.accounts.gsx_organisations_accounts.findOrCreate({ where: { organisation_email: req.body.email, deleted_at: null }, defaults: { organisation_uuid: uuid(), organisation_name: req.body.organisation_name, organisation_email: req.body.email, organisation_account_id: accountId, organisation_account_status: 'ACTIVE', organisation_latitude: req.body.latitude || null, organisation_longitude: req.body.longitude || null, organisation_website: req.body.website || null, organisation_permissions_scopes: null, organisation_is_delinquent: 0, created_at: Math.floor(Date.now() / 1000) } }).spread(function(data, created) { if (data && created == true) { var request = sg.emptyRequest({ method: 'POST', path: '/v3/mail/send', body: { personalizations: [ { to: [ { email: req.body.email, name: req.body.first_name + ' ' + req.body.last_name }, ], substitutions: { '-subject-': 'INSERT SUBJECT HERE', '-title-': 'INSERT TITLE HERE', '-firstName-': req.body.first_name, '-verifyLink-': 'https://INSERT YOUR FQDN HERE/v1/web/account/verify/' + data.get('email_token') } } ], template_id: 'INSERT SENDGRID TEMPLATE ID HERE', from: { email: 'INSERT SENDER EMAIL HERE', name: 'INSERT SENDER NAME HERE' }, reply_to: { email: 'INSERT REPLY-TO EMAIL HERE', name: 'INSERT REPLY-TO NAME HERE' } } }); sg.API(request, function(error, response) { if (error) { sendJsonResponse(res, 500, { status: "error", message: "An error occurred during registration. Contact support." }); } else { sendJsonResponse(res, 200, { status: "success", data: { user_email: req.body.email, organisation_account_id: req.body.account_id, message: "Organisation created. Verify email to continue." } }); } }); } else if (data && created == false) { sendJsonResponse(res, 400, { status: "fail", data: { organisation_name: data.get('organisation_name'), organisation_email: data.get('organisation_email'), message: "An organisation with that email already exists. Please login to manage the organisation." } }); } else { sendJsonResponse(res, 500, { status: "error", message: "An error occurred during registration." }); } }).catch(function(err) { sendJsonResponse(res, 500, { status: "error", message: "An error occurred during registration." }); }); } else if (data && created == false) { sendJsonResponse(res, 400, { status: "fail", data: { message: "Email already in use." } }); } else { sendJsonResponse(res, 500, { status: "error", message: "An error occurred during registration." }); } }).catch(function(err) { sendJsonResponse(res, 500, { status: "error", message: "An error occurred during registration." }); }); } else { sendJsonResponse(res, 500, { status: "error", message: "An error occurred during registration." }); } }); break; } case "joinOrganisation": { var passwordHash = bcrypt.hashSync(req.body.password, 12); models.accounts.gsx_organisations_accounts.findOne({ where: { organisation_account_id: req.body.account_id, organisation_account_status: 'ACTIVE', deleted_at: null } }).then(function(data) { if (data) { models.accounts.gsx_organisations_users_accounts.findOrCreate({ where: { user_email: req.body.email, deleted_at: null }, defaults: { user_uuid: uuid(), user_first_name: req.body.first_name, user_last_name: req.body.last_name, user_email: req.body.email, user_email_status: 'UNVERIFIED', user_account_status: 'ORG_ACTIVATION', user_password_hash: passwordHash, user_account_id: null, user_organisation_uuid: null, user_organisation_role: 'USER', user_permissions_scopes: '[]', created_at: Math.floor(Date.now() / 1000) } }).spread(function(data, created) { if (data && created == true) { var emailToken = uuid(); models.accounts.gsx_email_tokens.findOrCreate({ where: { user_uuid: data.get('user_uuid'), deleted_at: null }, defaults: { user_uuid: data.get('user_uuid'), email_token: emailToken, created_at: Math.floor(Date.now() / 1000) } }).spread(function(data, created) { if (data) { var request = sg.emptyRequest({ method: 'POST', path: '/v3/mail/send', body: { personalizations: [ { to: [ { email: req.body.email, name: req.body.first_name + ' ' + req.body.last_name }, ], substitutions: { '-subject-': 'INSERT SUBJECT HERE', '-title-': 'INSERT TITLE HERE', '-firstName-': req.body.first_name, '-verifyLink-': 'https://INSERT YOUR FQDN HERE/v1/web/account/verify/' + data.get('email_token') } } ], template_id: 'INSERT SENDGRID TEMPLATE ID HERE', from: { email: 'INSERT SENDER EMAIL HERE', name: 'INSERT SENDER NAME HERE' }, reply_to: { email: 'INSERT REPLY-TO EMAIL HERE', name: 'INSERT REPLY-TO NAME HERE' } } }); sg.API(request, function(error, response) { if (error) { sendJsonResponse(res, 500, { status: "error", message: "An error occurred during registration. Contact support." }); } else { sendJsonResponse(res, 200, { status: "success", data: { user_email: req.body.email, organisation_account_id: req.body.account_id, message: "Request to join organisation submitted." } }); } }); } else { sendJsonResponse(res, 500, { status: "error", message: "An error occurred during registration. Contact support." }); } }).catch(function(err) { sendJsonResponse(res, 500, { status: "error", message: "An error occurred during registration." }); }); } else if (data && created == false) { sendJsonResponse(res, 400, { status: "fail", data: { message: "User is already registered. Please login to continue." } }); } else { sendJsonResponse(res, 400, { status: "error", message: "An error occurred during registration." }); } }).catch(function(err) { sendJsonResponse(res, 500, { status: "error", message: "An error occurred during registration." }); }); } else { sendJsonResponse(res, 400, { status: "fail", data: { message: "Organisation not found." } }); } }).catch(function(data) { sendJsonResponse(res, 500, { status: "error", message: "An error occurred during registration." }); }); break; } default: { sendJsonResponse(res, 400, { status: "fail", data: { message: "Invalid registration type." } }); break; } } }; Public.prototype.account.verify = function(req, res) { models.accounts.gsx_email_tokens.findOne({ where: { email_token: req.params.token, deleted_at: null } }).then(function(tokenData) { models.accounts.gsx_organisations_users_accounts.findOne({ where: { user_uuid: tokenData.get('user_uuid'), deleted_at: null } }).then(function(userData) { if (userData) { if (userData.get('user_email_status') == 'UNVERIFIED' && userData.get('user_account_status') == 'EMAIL_ACTIVATION') { userData.update({ user_email_status: 'VERIFIED', user_account_status: 'ACTIVE' }).then(function(data) { if (data) { tokenData.update({ deleted_at: Math.floor(Date.now() / 1000) }).then(function(data) { sendJsonResponse(res, 200, { status: "success", data: { message: "Email address verified. You may now login." } }); }).catch(function(err) { sendJsonResponse(res, 500, { status: "error", message: "An error occurred whilst verifiying your email." }); }); } else { sendJsonResponse(res, 500, { status: "error", message: "An error occurred whilst verifiying your email." }); } }).catch(function(err) { sendJsonResponse(res, 500, { status: "error", message: "An error occurred whilst verifiying your email." }); }); } else if (userData.get('user_email_status') == 'UNVERIFIED' && userData.get('user_account_status') == 'ORG_ACTIVATION') { userData.update({ user_email_status: 'VERIFIED', }).then(function(data) { if (data) { tokenData.update({ deleted_at: Math.floor(Date.now() / 1000) }).then(function(data) { sendJsonResponse(res, 200, { status: "success", data: { message: "Email address verified. Contact the organisation administrator to activate your account." } }); }).catch(function(err) { sendJsonResponse(res, 500, { status: "error", message: "An error occurred whilst verifiying your email." }); }); } else { sendJsonResponse(res, 500, { status: "error", message: "An error occurred whilst verifiying your email." }); } }).catch(function(err) { sendJsonResponse(res, 500, { status: "error", message: "An error occurred whilst verifiying your email." }); }); } else { userData.update({ user_email_status: 'VERIFIED', }).then(function(data) { if (data) { tokenData.update({ deleted_at: Math.floor(Date.now() / 1000) }).then(function(data) { sendJsonResponse(res, 200, { status: "success", data: { message: "Email address verified." } }); }).catch(function(err) { sendJsonResponse(res, 500, { status: "error", message: "An error occurred whilst verifiying your email." }); }); } else { sendJsonResponse(res, 500, { status: "error", message: "An error occurred whilst verifiying your email." }); } }).catch(function(err) { sendJsonResponse(res, 500, { status: "error", message: "An error occurred whilst verifiying your email." }); }); } } else { sendJsonResponse(res, 400, { status: "fail", data: { message: "Not user was found for that token. Contact support." } }); } }).catch(function(err) { sendJsonResponse(res, 500, { status: "error", message: "An error occurred whilst verifiying your email." }); }) }).catch(function(err) { sendJsonResponse(res, 500, { status: "error", message: "An error occurred whilst verifiying your email." }); }) } Public.prototype.devices.list_device_events = function(req, res) { models.ast.gsx_users_diagnostics_headers.findAll({ where: { user_uuid: req.user.uuid, deleted_at: null }, limit: req.body.quantity || 2000, offset: req.body.offset || 0, order: [ [models.ast.sequelize.col('diagnostic_start_timestamp'), 'DESC'], ] }).then(function(data) { var results = []; var index; for (index = 0; index < data.length; ++index) { results.push({ serial_number: data[index].serial_number, event_number: data[index].diagnostic_event_number, tool_id: data[index].tool_id, tool_version: data[index].tool_version, test_start: data[index].diagnostic_start_timestamp, test_end: data[index].diagnostic_end_timestamp || "", test_result: data[index].test_result || "" }); if (index == data.length - 1) { sendJsonResponse(res, 200, { status: "success", data: { entries: req.body.quantity || data.length, offset: req.body.offset || 0, results: results } }); } } }).catch(function(err) { res.status(500).json({ status: "error", message: "An error occurred whilst retrieving the list of events." }); }); }; Public.prototype.devices.device_summary = function(req, res) { models.ast.gsx_users_diagnostics_headers.findAll({ where: { user_uuid: req.user.uuid, serial_number: req.params.serial, deleted_at: null }, limit: req.body.quantity || 20, offset: req.body.offset || 0, order: [ [models.ast.sequelize.col('diagnostic_start_timestamp'), 'DESC'], ] }).then(function(data) { if (data) { var results = []; var index; for (index = 0; index < data.length; ++index) { results.push({ serial_number: data[index].serial_number, event_number: data[index].diagnostic_event_number, tool_id: data[index].tool_id, tool_version: data[index].tool_version, test_start: data[index].diagnostic_start_timestamp, test_end: data[index].diagnostic_end_timestamp || "", test_result: data[index].test_result || "" }); if (index == data.length - 1) { sendJsonResponse(res, 200, { status: "success", data: { entries: req.body.quantity || data.length, offset: req.body.offset || 0, results: results } }); } } } else { res.status(400).json({ status: "fail", message: "No device information found." }); } }).catch(function(err) { res.status(500).json({ status: "error", message: "An error occurred whilst retrieving the device information." }); }); }; Public.prototype.devices.device_diagnostic_summary = function(req, res) { var response = {}; models.ast.gsx_users_diagnostics_headers.findOne({ where: { user_uuid: req.user.uuid, serial_number: req.params.serial, diagnostic_event_number: req.params.event_number, deleted_at: null } }).then(function(headerData) { if (headerData) { response.serial_number = headerData.get('serial_number'); response.event_number = headerData.get('diagnostic_event_number'); response.tool_id = headerData.get('tool_id'); response.tool_version = headerData.get('tool_version'); response.test_start = headerData.get('diagnostic_start_timestamp'); response.test_end = headerData.get('diagnostic_end_timestamp'); response.test_result = headerData.get('test_result'); response.test_pass_count = headerData.get('pass_count'); response.test_profile_available = headerData.get('profile_file') !== null; response.test_log_available = headerData.get('log_file') !== null; models.ast.gsx_users_diagnostics_results.findAll({ where: { user_uuid: req.user.uuid, diagnostic_event_number: req.params.event_number, deleted_at: null } }).then(function(resultData) { if (resultData.length > 0) { if (headerData.get('test_result') !== 'SUCCESS') { response.results = []; var index; for (index = 0; index < resultData.length; ++index) { response.results.push({ module_name: resultData[index].module_name, module_location: resultData[index].module_location, module_serial_number: function() { if(resultData[index].module_serial_number == 'n/a' || resultData[index].module_serial_number == 'none' || resultData[index].module_serial_number == null) { return null; } else { return resultData[index].module_serial_number; } }, module_test_name: resultData[index].module_test_name, module_test_result: resultData[index].module_test_result }); if (index == resultData.length - 1) { sendJsonResponse(res, 200, { status: "success", data: response }); } } } } else { sendJsonResponse(res, 200, { status: "success", data: response }); } }).catch(function(err) { res.status(500).json({ status: "error", message: "An error occurred whilst retrieving the device diagnostic information." }); }); } else { res.status(400).json({ status: "fail", data: { message: "No diagnostic event information found." } }); } }).catch(function(err) { res.status(500).json({ status: "error", message: "An error occurred whilst retrieving the device diagnostic information." }); }); }; Public.prototype.devices.device_diagnostic_profile = function(req, res) { models.ast.gsx_users_diagnostics_headers.findOne({ where: { user_uuid: req.user.uuid, serial_number: req.params.serial, diagnostic_event_number: req.params.event_number, deleted_at: null } }).then(function(data) { if (data) { if (data.get('profile_file') !== null) { fs.readFile(data.get('profile_file'), (err, data) => { if (!err) { res.status(200).json({ status: "success", data: { contents: new Buffer(data).toString('base64') } }); new Buffer(data).toString('base64') } else { res.status(500).json({ status: "error", message: "An error occurred whilst reading the profile data." }); } }); } else { res.status(400).json({ status: "fail", data: { message: "No profile data is available for this diagnostic event." } }); } } else { res.status(400).json({ status: "fail", data: { message: "No diagnostic event information found." } }); } }).catch(function(err) { res.status(500).json({ status: "error", message: "An error occurred whilst retrieving the device diagnostic information." }); }); }; Public.prototype.devices.device_diagnostic_log = function(req, res) { models.ast.gsx_users_diagnostics_headers.findOne({ where: { user_uuid: req.user.uuid, serial_number: req.params.serial, diagnostic_event_number: req.params.event_number, deleted_at: null } }).then(function(data) { if (data) { if (data.get('log_file') !== null) { fs.readFile(data.get('log_file'), (err, data) => { if (!err) { res.status(200).json({ status: "success", data: { contents: new Buffer(data).toString('base64') } }); new Buffer(data).toString('base64') } else { res.status(500).json({ status: "error", message: "An error occurred whilst reading the log data." }); } }); } else { res.status(400).json({ status: "fail", data: { message: "No log data is available for this diagnostic event." } }); } } else { res.status(400).json({ status: "fail", data: { message: "No diagnostic event information found." } }); } }).catch(function(err) { res.status(500).json({ status: "error", message: "An error occurred whilst retrieving the device diagnostic information." }); }); }; function generateAccountId(next) { var accountId = Math.floor(Math.random() * 900000) + 100000; models.accounts.gsx_organisations_accounts.findOne({ where: { organisation_account_id: accountId } }).then(function(data) { if (!data) { return next(null, accountId); } else { generateAccountId(); return; } }).catch(function(err) { return next(new Error("An error occurred whilst generating the Account ID."), null); }); } function sendJsonResponse(res, status, payload) { res.status(status).json(payload); } exports.Public = new Public();
mit
AzureAD/microsoft-authentication-library-for-java
src/integrationtest/java/com.microsoft.aad.msal4j/HttpClientIT.java
1789
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.microsoft.aad.msal4j; import labapi.LabUserProvider; import labapi.User; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.Collections; public class HttpClientIT { private LabUserProvider labUserProvider; @BeforeClass public void setUp() { labUserProvider = LabUserProvider.getInstance(); } @Test public void acquireToken_okHttpClient() throws Exception { User user = labUserProvider.getDefaultUser(); assertAcquireTokenCommon(user, new OkHttpClientAdapter()); } @Test public void acquireToken_apacheHttpClient() throws Exception { User user = labUserProvider.getDefaultUser(); assertAcquireTokenCommon(user, new ApacheHttpClientAdapter()); } private void assertAcquireTokenCommon(User user, IHttpClient httpClient) throws Exception { PublicClientApplication pca = PublicClientApplication.builder( user.getAppId()). authority(TestConstants.ORGANIZATIONS_AUTHORITY). httpClient(httpClient). build(); IAuthenticationResult result = pca.acquireToken(UserNamePasswordParameters. builder(Collections.singleton(TestConstants.GRAPH_DEFAULT_SCOPE), user.getUpn(), user.getPassword().toCharArray()) .build()) .get(); Assert.assertNotNull(result); Assert.assertNotNull(result.accessToken()); Assert.assertNotNull(result.idToken()); Assert.assertEquals(user.getUpn(), result.account().username()); } }
mit
hsheth2/gonet
udp/udpWrite.py
551
import socket import sys import datetime DST_IP = "127.0.0.1" if len(sys.argv) <= 1: UDP_DST_PORT = 20000 else: UDP_DST_PORT = int(sys.argv[1]) if len(sys.argv) >= 2: MESSAGE = str(sys.argv[2]).zfill(5) else: MESSAGE = "Hello, World!" #print "UDP target IP:", DST_IP #print "UDP target port:", UDP_DST_PORT #print "message:", MESSAGE print "Sent ", MESSAGE, " at ", datetime.datetime.now() sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP sock.sendto(MESSAGE, (DST_IP, UDP_DST_PORT))
mit
MiaoMiaosha/Cocos
SampleFlashImport/cocos2d/cocos/2d/CCSprite.cpp
29881
/**************************************************************************** Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2011 Zynga Inc. Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "CCSpriteBatchNode.h" #include <string.h> #include <algorithm> #include "CCAnimation.h" #include "CCAnimationCache.h" #include "ccConfig.h" #include "CCSprite.h" #include "CCSpriteFrame.h" #include "CCSpriteFrameCache.h" #include "CCTextureCache.h" #include "CCDrawingPrimitives.h" #include "CCShaderCache.h" #include "ccGLStateCache.h" #include "CCGLProgram.h" #include "CCDirector.h" #include "CCGeometry.h" #include "CCTexture2D.h" #include "CCAffineTransform.h" #include "TransformUtils.h" #include "CCProfiling.h" #include "CCDirector.h" #include "renderer/CCRenderer.h" #include "renderer/CCFrustum.h" // external #include "kazmath/GL/matrix.h" #include "kazmath/kazmath.h" using namespace std; NS_CC_BEGIN #if CC_SPRITEBATCHNODE_RENDER_SUBPIXEL #define RENDER_IN_SUBPIXEL #else #define RENDER_IN_SUBPIXEL(__ARGS__) (ceil(__ARGS__)) #endif Sprite* Sprite::createWithTexture(Texture2D *texture) { Sprite *sprite = new Sprite(); if (sprite && sprite->initWithTexture(texture)) { sprite->autorelease(); return sprite; } CC_SAFE_DELETE(sprite); return nullptr; } Sprite* Sprite::createWithTexture(Texture2D *texture, const Rect& rect, bool rotated) { Sprite *sprite = new Sprite(); if (sprite && sprite->initWithTexture(texture, rect, rotated)) { sprite->autorelease(); return sprite; } CC_SAFE_DELETE(sprite); return nullptr; } Sprite* Sprite::create(const std::string& filename) { Sprite *sprite = new Sprite(); if (sprite && sprite->initWithFile(filename)) { sprite->autorelease(); return sprite; } CC_SAFE_DELETE(sprite); return nullptr; } Sprite* Sprite::create(const std::string& filename, const Rect& rect) { Sprite *sprite = new Sprite(); if (sprite && sprite->initWithFile(filename, rect)) { sprite->autorelease(); return sprite; } CC_SAFE_DELETE(sprite); return nullptr; } Sprite* Sprite::createWithSpriteFrame(SpriteFrame *spriteFrame) { Sprite *sprite = new Sprite(); if (spriteFrame && sprite && sprite->initWithSpriteFrame(spriteFrame)) { sprite->autorelease(); return sprite; } CC_SAFE_DELETE(sprite); return nullptr; } Sprite* Sprite::createWithSpriteFrameName(const std::string& spriteFrameName) { SpriteFrame *frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName); #if COCOS2D_DEBUG > 0 char msg[256] = {0}; sprintf(msg, "Invalid spriteFrameName: %s", spriteFrameName.c_str()); CCASSERT(frame != nullptr, msg); #endif return createWithSpriteFrame(frame); } Sprite* Sprite::create() { Sprite *sprite = new Sprite(); if (sprite && sprite->init()) { sprite->autorelease(); return sprite; } CC_SAFE_DELETE(sprite); return nullptr; } bool Sprite::init(void) { return initWithTexture(nullptr, Rect::ZERO ); } bool Sprite::initWithTexture(Texture2D *texture) { CCASSERT(texture != nullptr, "Invalid texture for sprite"); Rect rect = Rect::ZERO; rect.size = texture->getContentSize(); return initWithTexture(texture, rect); } bool Sprite::initWithTexture(Texture2D *texture, const Rect& rect) { return initWithTexture(texture, rect, false); } bool Sprite::initWithFile(const std::string& filename) { CCASSERT(filename.size()>0, "Invalid filename for sprite"); Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename); if (texture) { Rect rect = Rect::ZERO; rect.size = texture->getContentSize(); return initWithTexture(texture, rect); } // don't release here. // when load texture failed, it's better to get a "transparent" sprite then a crashed program // this->release(); return false; } bool Sprite::initWithFile(const std::string &filename, const Rect& rect) { CCASSERT(filename.size()>0, "Invalid filename"); Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename); if (texture) { return initWithTexture(texture, rect); } // don't release here. // when load texture failed, it's better to get a "transparent" sprite then a crashed program // this->release(); return false; } bool Sprite::initWithSpriteFrameName(const std::string& spriteFrameName) { CCASSERT(spriteFrameName.size() > 0, "Invalid spriteFrameName"); SpriteFrame *frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName); return initWithSpriteFrame(frame); } bool Sprite::initWithSpriteFrame(SpriteFrame *spriteFrame) { CCASSERT(spriteFrame != nullptr, ""); bool bRet = initWithTexture(spriteFrame->getTexture(), spriteFrame->getRect()); setSpriteFrame(spriteFrame); return bRet; } // designated initializer bool Sprite::initWithTexture(Texture2D *texture, const Rect& rect, bool rotated) { bool result; if (Node::init()) { _batchNode = nullptr; _recursiveDirty = false; setDirty(false); _opacityModifyRGB = true; _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED; _flippedX = _flippedY = false; // default transform anchor: center setAnchorPoint(Point(0.5f, 0.5f)); // zwoptex default values _offsetPosition = Point::ZERO; // clean the Quad memset(&_quad, 0, sizeof(_quad)); // Atlas: Color _quad.bl.colors = Color4B::WHITE; _quad.br.colors = Color4B::WHITE; _quad.tl.colors = Color4B::WHITE; _quad.tr.colors = Color4B::WHITE; // shader program setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP)); // update texture (calls updateBlendFunc) setTexture(texture); setTextureRect(rect, rotated, rect.size); // by default use "Self Render". // if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render" setBatchNode(nullptr); result = true; } else { result = false; } _recursiveDirty = true; setDirty(true); return result; } Sprite::Sprite(void) : _shouldBeHidden(false) , _texture(nullptr) { } Sprite::~Sprite(void) { CC_SAFE_RELEASE(_texture); } /* * Texture methods */ /* * This array is the data of a white image with 2 by 2 dimension. * It's used for creating a default texture when sprite's texture is set to nullptr. * Supposing codes as follows: * * auto sp = new Sprite(); * sp->init(); // Texture was set to nullptr, in order to make opacity and color to work correctly, we need to create a 2x2 white texture. * * The test is in "TestCpp/SpriteTest/Sprite without texture". */ static unsigned char cc_2x2_white_image[] = { // RGBA8888 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; #define CC_2x2_WHITE_IMAGE_KEY "/cc_2x2_white_image" void Sprite::setTexture(const std::string &filename) { Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename); setTexture(texture); Rect rect = Rect::ZERO; rect.size = texture->getContentSize(); setTextureRect(rect); } void Sprite::setTexture(Texture2D *texture) { // If batchnode, then texture id should be the same CCASSERT(! _batchNode || texture->getName() == _batchNode->getTexture()->getName(), "CCSprite: Batched sprites should use the same texture as the batchnode"); // accept texture==nil as argument CCASSERT( !texture || dynamic_cast<Texture2D*>(texture), "setTexture expects a Texture2D. Invalid argument"); if (texture == nullptr) { // Gets the texture by key firstly. texture = Director::getInstance()->getTextureCache()->getTextureForKey(CC_2x2_WHITE_IMAGE_KEY); // If texture wasn't in cache, create it from RAW data. if (texture == nullptr) { Image* image = new Image(); bool isOK = image->initWithRawData(cc_2x2_white_image, sizeof(cc_2x2_white_image), 2, 2, 8); CCASSERT(isOK, "The 2x2 empty texture was created unsuccessfully."); texture = Director::getInstance()->getTextureCache()->addImage(image, CC_2x2_WHITE_IMAGE_KEY); CC_SAFE_RELEASE(image); } } if (!_batchNode && _texture != texture) { CC_SAFE_RETAIN(texture); CC_SAFE_RELEASE(_texture); _texture = texture; updateBlendFunc(); } } Texture2D* Sprite::getTexture() const { return _texture; } void Sprite::setTextureRect(const Rect& rect) { setTextureRect(rect, false, rect.size); } void Sprite::setTextureRect(const Rect& rect, bool rotated, const Size& untrimmedSize) { _rectRotated = rotated; setContentSize(untrimmedSize); setVertexRect(rect); setTextureCoords(rect); Point relativeOffset = _unflippedOffsetPositionFromCenter; // issue #732 if (_flippedX) { relativeOffset.x = -relativeOffset.x; } if (_flippedY) { relativeOffset.y = -relativeOffset.y; } _offsetPosition.x = relativeOffset.x + (_contentSize.width - _rect.size.width) / 2; _offsetPosition.y = relativeOffset.y + (_contentSize.height - _rect.size.height) / 2; // rendering using batch node if (_batchNode) { // update dirty_, don't update recursiveDirty_ setDirty(true); } else { // self rendering // Atlas: Vertex float x1 = 0 + _offsetPosition.x; float y1 = 0 + _offsetPosition.y; float x2 = x1 + _rect.size.width; float y2 = y1 + _rect.size.height; // Don't update Z. _quad.bl.vertices = Vertex3F(x1, y1, 0); _quad.br.vertices = Vertex3F(x2, y1, 0); _quad.tl.vertices = Vertex3F(x1, y2, 0); _quad.tr.vertices = Vertex3F(x2, y2, 0); } } // override this method to generate "double scale" sprites void Sprite::setVertexRect(const Rect& rect) { _rect = rect; } void Sprite::setTextureCoords(Rect rect) { rect = CC_RECT_POINTS_TO_PIXELS(rect); Texture2D *tex = _batchNode ? _textureAtlas->getTexture() : _texture; if (! tex) { return; } float atlasWidth = (float)tex->getPixelsWide(); float atlasHeight = (float)tex->getPixelsHigh(); float left, right, top, bottom; if (_rectRotated) { #if CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL left = (2*rect.origin.x+1)/(2*atlasWidth); right = left+(rect.size.height*2-2)/(2*atlasWidth); top = (2*rect.origin.y+1)/(2*atlasHeight); bottom = top+(rect.size.width*2-2)/(2*atlasHeight); #else left = rect.origin.x/atlasWidth; right = (rect.origin.x+rect.size.height) / atlasWidth; top = rect.origin.y/atlasHeight; bottom = (rect.origin.y+rect.size.width) / atlasHeight; #endif // CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL if (_flippedX) { CC_SWAP(top, bottom, float); } if (_flippedY) { CC_SWAP(left, right, float); } _quad.bl.texCoords.u = left; _quad.bl.texCoords.v = top; _quad.br.texCoords.u = left; _quad.br.texCoords.v = bottom; _quad.tl.texCoords.u = right; _quad.tl.texCoords.v = top; _quad.tr.texCoords.u = right; _quad.tr.texCoords.v = bottom; } else { #if CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL left = (2*rect.origin.x+1)/(2*atlasWidth); right = left + (rect.size.width*2-2)/(2*atlasWidth); top = (2*rect.origin.y+1)/(2*atlasHeight); bottom = top + (rect.size.height*2-2)/(2*atlasHeight); #else left = rect.origin.x/atlasWidth; right = (rect.origin.x + rect.size.width) / atlasWidth; top = rect.origin.y/atlasHeight; bottom = (rect.origin.y + rect.size.height) / atlasHeight; #endif // ! CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL if(_flippedX) { CC_SWAP(left,right,float); } if(_flippedY) { CC_SWAP(top,bottom,float); } _quad.bl.texCoords.u = left; _quad.bl.texCoords.v = bottom; _quad.br.texCoords.u = right; _quad.br.texCoords.v = bottom; _quad.tl.texCoords.u = left; _quad.tl.texCoords.v = top; _quad.tr.texCoords.u = right; _quad.tr.texCoords.v = top; } } void Sprite::updateTransform(void) { CCASSERT(_batchNode, "updateTransform is only valid when Sprite is being rendered using an SpriteBatchNode"); // recalculate matrix only if it is dirty if( isDirty() ) { // If it is not visible, or one of its ancestors is not visible, then do nothing: if( !_visible || ( _parent && _parent != _batchNode && static_cast<Sprite*>(_parent)->_shouldBeHidden) ) { _quad.br.vertices = _quad.tl.vertices = _quad.tr.vertices = _quad.bl.vertices = Vertex3F(0,0,0); _shouldBeHidden = true; } else { _shouldBeHidden = false; if( ! _parent || _parent == _batchNode ) { _transformToBatch = getNodeToParentTransform(); } else { CCASSERT( dynamic_cast<Sprite*>(_parent), "Logic error in Sprite. Parent must be a Sprite"); kmMat4 nodeToParent = getNodeToParentTransform(); kmMat4 parentTransform = static_cast<Sprite*>(_parent)->_transformToBatch; kmMat4Multiply(&_transformToBatch, &parentTransform, &nodeToParent); } // // calculate the Quad based on the Affine Matrix // Size size = _rect.size; float x1 = _offsetPosition.x; float y1 = _offsetPosition.y; float x2 = x1 + size.width; float y2 = y1 + size.height; float x = _transformToBatch.mat[12]; float y = _transformToBatch.mat[13]; float cr = _transformToBatch.mat[0]; float sr = _transformToBatch.mat[1]; float cr2 = _transformToBatch.mat[5]; float sr2 = -_transformToBatch.mat[4]; float ax = x1 * cr - y1 * sr2 + x; float ay = x1 * sr + y1 * cr2 + y; float bx = x2 * cr - y1 * sr2 + x; float by = x2 * sr + y1 * cr2 + y; float cx = x2 * cr - y2 * sr2 + x; float cy = x2 * sr + y2 * cr2 + y; float dx = x1 * cr - y2 * sr2 + x; float dy = x1 * sr + y2 * cr2 + y; _quad.bl.vertices = Vertex3F( RENDER_IN_SUBPIXEL(ax), RENDER_IN_SUBPIXEL(ay), _positionZ ); _quad.br.vertices = Vertex3F( RENDER_IN_SUBPIXEL(bx), RENDER_IN_SUBPIXEL(by), _positionZ ); _quad.tl.vertices = Vertex3F( RENDER_IN_SUBPIXEL(dx), RENDER_IN_SUBPIXEL(dy), _positionZ ); _quad.tr.vertices = Vertex3F( RENDER_IN_SUBPIXEL(cx), RENDER_IN_SUBPIXEL(cy), _positionZ ); } // MARMALADE CHANGE: ADDED CHECK FOR nullptr, TO PERMIT SPRITES WITH NO BATCH NODE / TEXTURE ATLAS if (_textureAtlas) { _textureAtlas->updateQuad(&_quad, _atlasIndex); } _recursiveDirty = false; setDirty(false); } // MARMALADE CHANGED // recursively iterate over children /* if( _hasChildren ) { // MARMALADE: CHANGED TO USE Node* // NOTE THAT WE HAVE ALSO DEFINED virtual Node::updateTransform() arrayMakeObjectsPerformSelector(_children, updateTransform, Sprite*); }*/ Node::updateTransform(); } // draw void Sprite::draw(void) { if(isInsideBounds()) { _quadCommand.init(_globalZOrder, _texture->getName(), _shaderProgram, _blendFunc, &_quad, 1, _modelViewTransform); Director::getInstance()->getRenderer()->addCommand(&_quadCommand); #if CC_SPRITE_DEBUG_DRAW _customDebugDrawCommand.init(_globalZOrder); _customDebugDrawCommand.func = CC_CALLBACK_0(Sprite::drawDebugData, this); Director::getInstance()->getRenderer()->addCommand(&_customDebugDrawCommand); #endif //CC_SPRITE_DEBUG_DRAW } } #if CC_SPRITE_DEBUG_DRAW void Sprite::drawDebugData() { kmMat4 oldModelView; kmGLGetMatrix(KM_GL_MODELVIEW, &oldModelView); kmGLLoadMatrix(&_modelViewTransform); // draw bounding box Point vertices[4] = { Point( _quad.bl.vertices.x, _quad.bl.vertices.y ), Point( _quad.br.vertices.x, _quad.br.vertices.y ), Point( _quad.tr.vertices.x, _quad.tr.vertices.y ), Point( _quad.tl.vertices.x, _quad.tl.vertices.y ), }; DrawPrimitives::drawPoly(vertices, 4, true); kmGLLoadMatrix(&oldModelView); } #endif //CC_SPRITE_DEBUG_DRAW // Culling function from cocos2d-iphone CCSprite.m file bool Sprite::isInsideBounds() const { // half size of the screen Size screen_half = Director::getInstance()->getWinSize(); screen_half.width /= 2; screen_half.height /= 2; float hcsx = _contentSize.width / 2; float hcsy = _contentSize.height / 2; // convert to world coordinates float x = hcsx * _modelViewTransform.mat[0] + hcsy * _modelViewTransform.mat[4] + _modelViewTransform.mat[12]; float y = hcsx * _modelViewTransform.mat[1] + hcsy * _modelViewTransform.mat[5] + _modelViewTransform.mat[13]; // center of screen is (0,0) x -= screen_half.width; y -= screen_half.height; // convert content size to world coordinates float wchw = hcsx * std::max(fabsf(_modelViewTransform.mat[0] + _modelViewTransform.mat[4]), fabsf(_modelViewTransform.mat[0] - _modelViewTransform.mat[4])); float wchh = hcsy * std::max(fabsf(_modelViewTransform.mat[1] + _modelViewTransform.mat[5]), fabsf(_modelViewTransform.mat[1] - _modelViewTransform.mat[5])); // compare if it in the positive quadrant of the screen float tmpx = (fabsf(x)-wchw); float tmpy = (fabsf(y)-wchh); return (tmpx < screen_half.width && tmpy < screen_half.height); } // Node overrides void Sprite::addChild(Node *child, int zOrder, int tag) { CCASSERT(child != nullptr, "Argument must be non-nullptr"); if (_batchNode) { Sprite* childSprite = dynamic_cast<Sprite*>(child); CCASSERT( childSprite, "CCSprite only supports Sprites as children when using SpriteBatchNode"); CCASSERT(childSprite->getTexture()->getName() == _textureAtlas->getTexture()->getName(), ""); //put it in descendants array of batch node _batchNode->appendChild(childSprite); if (!_reorderChildDirty) { setReorderChildDirtyRecursively(); } } //CCNode already sets isReorderChildDirty_ so this needs to be after batchNode check Node::addChild(child, zOrder, tag); } void Sprite::reorderChild(Node *child, int zOrder) { CCASSERT(child != nullptr, "child must be non null"); CCASSERT(_children.contains(child), "child does not belong to this"); if( _batchNode && ! _reorderChildDirty) { setReorderChildDirtyRecursively(); _batchNode->reorderBatch(true); } Node::reorderChild(child, zOrder); } void Sprite::removeChild(Node *child, bool cleanup) { if (_batchNode) { _batchNode->removeSpriteFromAtlas((Sprite*)(child)); } Node::removeChild(child, cleanup); } void Sprite::removeAllChildrenWithCleanup(bool cleanup) { if (_batchNode) { for(const auto &child : _children) { Sprite* sprite = dynamic_cast<Sprite*>(child); if (sprite) { _batchNode->removeSpriteFromAtlas(sprite); } } } Node::removeAllChildrenWithCleanup(cleanup); } void Sprite::sortAllChildren() { if (_reorderChildDirty) { std::sort(std::begin(_children), std::end(_children), nodeComparisonLess); if ( _batchNode) { for(const auto &child : _children) child->sortAllChildren(); } _reorderChildDirty = false; } } // // Node property overloads // used only when parent is SpriteBatchNode // void Sprite::setReorderChildDirtyRecursively(void) { //only set parents flag the first time if ( ! _reorderChildDirty ) { _reorderChildDirty = true; Node* node = static_cast<Node*>(_parent); while (node && node != _batchNode) { static_cast<Sprite*>(node)->setReorderChildDirtyRecursively(); node=node->getParent(); } } } void Sprite::setDirtyRecursively(bool bValue) { _recursiveDirty = bValue; setDirty(bValue); for(const auto &child: _children) { Sprite* sp = dynamic_cast<Sprite*>(child); if (sp) { sp->setDirtyRecursively(true); } } } // XXX HACK: optimization #define SET_DIRTY_RECURSIVELY() { \ if (! _recursiveDirty) { \ _recursiveDirty = true; \ setDirty(true); \ if (!_children.empty()) \ setDirtyRecursively(true); \ } \ } void Sprite::setPosition(const Point& pos) { Node::setPosition(pos); SET_DIRTY_RECURSIVELY(); } void Sprite::setPosition(float x, float y) { Node::setPosition(x, y); SET_DIRTY_RECURSIVELY(); } void Sprite::setRotation(float rotation) { Node::setRotation(rotation); SET_DIRTY_RECURSIVELY(); } void Sprite::setRotationSkewX(float fRotationX) { Node::setRotationSkewX(fRotationX); SET_DIRTY_RECURSIVELY(); } void Sprite::setRotationSkewY(float fRotationY) { Node::setRotationSkewY(fRotationY); SET_DIRTY_RECURSIVELY(); } void Sprite::setSkewX(float sx) { Node::setSkewX(sx); SET_DIRTY_RECURSIVELY(); } void Sprite::setSkewY(float sy) { Node::setSkewY(sy); SET_DIRTY_RECURSIVELY(); } void Sprite::setScaleX(float scaleX) { Node::setScaleX(scaleX); SET_DIRTY_RECURSIVELY(); } void Sprite::setScaleY(float scaleY) { Node::setScaleY(scaleY); SET_DIRTY_RECURSIVELY(); } void Sprite::setScale(float fScale) { Node::setScale(fScale); SET_DIRTY_RECURSIVELY(); } void Sprite::setScale(float scaleX, float scaleY) { Node::setScale(scaleX, scaleY); SET_DIRTY_RECURSIVELY(); } void Sprite::setPositionZ(float fVertexZ) { Node::setPositionZ(fVertexZ); SET_DIRTY_RECURSIVELY(); } void Sprite::setAnchorPoint(const Point& anchor) { Node::setAnchorPoint(anchor); SET_DIRTY_RECURSIVELY(); } void Sprite::ignoreAnchorPointForPosition(bool value) { CCASSERT(! _batchNode, "ignoreAnchorPointForPosition is invalid in Sprite"); Node::ignoreAnchorPointForPosition(value); } void Sprite::setVisible(bool bVisible) { Node::setVisible(bVisible); SET_DIRTY_RECURSIVELY(); } void Sprite::setFlippedX(bool flippedX) { if (_flippedX != flippedX) { _flippedX = flippedX; setTextureRect(_rect, _rectRotated, _contentSize); } } bool Sprite::isFlippedX(void) const { return _flippedX; } void Sprite::setFlippedY(bool flippedY) { if (_flippedY != flippedY) { _flippedY = flippedY; setTextureRect(_rect, _rectRotated, _contentSize); } } bool Sprite::isFlippedY(void) const { return _flippedY; } // // RGBA protocol // void Sprite::updateColor(void) { Color4B color4( _displayedColor.r, _displayedColor.g, _displayedColor.b, _displayedOpacity ); // special opacity for premultiplied textures if (_opacityModifyRGB) { color4.r *= _displayedOpacity/255.0f; color4.g *= _displayedOpacity/255.0f; color4.b *= _displayedOpacity/255.0f; } _quad.bl.colors = color4; _quad.br.colors = color4; _quad.tl.colors = color4; _quad.tr.colors = color4; // renders using batch node if (_batchNode) { if (_atlasIndex != INDEX_NOT_INITIALIZED) { _textureAtlas->updateQuad(&_quad, _atlasIndex); } else { // no need to set it recursively // update dirty_, don't update recursiveDirty_ setDirty(true); } } // self render // do nothing } void Sprite::setOpacityModifyRGB(bool modify) { if (_opacityModifyRGB != modify) { _opacityModifyRGB = modify; updateColor(); } } bool Sprite::isOpacityModifyRGB(void) const { return _opacityModifyRGB; } // Frames void Sprite::setSpriteFrame(const std::string &spriteFrameName) { SpriteFrameCache *cache = SpriteFrameCache::getInstance(); SpriteFrame *spriteFrame = cache->getSpriteFrameByName(spriteFrameName); CCASSERT(spriteFrame, "Invalid spriteFrameName"); setSpriteFrame(spriteFrame); } void Sprite::setSpriteFrame(SpriteFrame *spriteFrame) { _unflippedOffsetPositionFromCenter = spriteFrame->getOffset(); Texture2D *texture = spriteFrame->getTexture(); // update texture before updating texture rect if (texture != _texture) { setTexture(texture); } // update rect _rectRotated = spriteFrame->isRotated(); setTextureRect(spriteFrame->getRect(), _rectRotated, spriteFrame->getOriginalSize()); } void Sprite::setDisplayFrameWithAnimationName(const std::string& animationName, ssize_t frameIndex) { CCASSERT(animationName.size()>0, "CCSprite#setDisplayFrameWithAnimationName. animationName must not be nullptr"); Animation *a = AnimationCache::getInstance()->getAnimation(animationName); CCASSERT(a, "CCSprite#setDisplayFrameWithAnimationName: Frame not found"); AnimationFrame* frame = a->getFrames().at(frameIndex); CCASSERT(frame, "CCSprite#setDisplayFrame. Invalid frame"); setSpriteFrame(frame->getSpriteFrame()); } bool Sprite::isFrameDisplayed(SpriteFrame *frame) const { Rect r = frame->getRect(); return (r.equals(_rect) && frame->getTexture()->getName() == _texture->getName() && frame->getOffset().equals(_unflippedOffsetPositionFromCenter)); } SpriteFrame* Sprite::getSpriteFrame() const { return SpriteFrame::createWithTexture(_texture, CC_RECT_POINTS_TO_PIXELS(_rect), _rectRotated, CC_POINT_POINTS_TO_PIXELS(_unflippedOffsetPositionFromCenter), CC_SIZE_POINTS_TO_PIXELS(_contentSize)); } SpriteBatchNode* Sprite::getBatchNode() { return _batchNode; } void Sprite::setBatchNode(SpriteBatchNode *spriteBatchNode) { _batchNode = spriteBatchNode; // weak reference // self render if( ! _batchNode ) { _atlasIndex = INDEX_NOT_INITIALIZED; setTextureAtlas(nullptr); _recursiveDirty = false; setDirty(false); float x1 = _offsetPosition.x; float y1 = _offsetPosition.y; float x2 = x1 + _rect.size.width; float y2 = y1 + _rect.size.height; _quad.bl.vertices = Vertex3F( x1, y1, 0 ); _quad.br.vertices = Vertex3F( x2, y1, 0 ); _quad.tl.vertices = Vertex3F( x1, y2, 0 ); _quad.tr.vertices = Vertex3F( x2, y2, 0 ); } else { // using batch kmMat4Identity(&_transformToBatch); setTextureAtlas(_batchNode->getTextureAtlas()); // weak ref } } // Texture protocol void Sprite::updateBlendFunc(void) { CCASSERT(! _batchNode, "CCSprite: updateBlendFunc doesn't work when the sprite is rendered using a SpriteBatchNode"); // it is possible to have an untextured sprite if (! _texture || ! _texture->hasPremultipliedAlpha()) { _blendFunc = BlendFunc::ALPHA_NON_PREMULTIPLIED; setOpacityModifyRGB(false); } else { _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED; setOpacityModifyRGB(true); } } std::string Sprite::getDescription() const { int texture_id = -1; if( _batchNode ) texture_id = _batchNode->getTextureAtlas()->getTexture()->getName(); else texture_id = _texture->getName(); return StringUtils::format("<Sprite | Tag = %d, TextureID = %d>", _tag, texture_id ); } NS_CC_END
mit
bobdesaunois/emmaphp
config.php
1647
<?php /**************************************************** * Routing engine * ****************************************************/ // Router::get('stateName', 'URI', 'Controller@method') Router::get('home', '/', 'Index@index'); Router::get("defaultPage", "/page", "Index@page"); Router::get('page', '/page/(:any)', 'Index@page'); /**************************************************** * Application Configuration * ****************************************************/ // Set debug mode define ("DEBUG_MODE", true); // Set the default controller define ("DEFAULT_CONTROLLER", "index"); // Debug mode if (DEBUG_MODE) ini_set ("display_errors", "on"); else ini_set ("display_errors", "off"); /**************************************************** * Database * ****************************************************/ // Database Switch define ("DB", false); // Database Details define ("DB_HOST", ""); define ("DB_NAME", ""); define ("DB_USERNAME", ""); define ("DB_PASSWORD", ""); /**************************************************** * Autoloader * ****************************************************/ AutoLoader::$autoloadModels = array (); /**************************************************** * Constants * ****************************************************/ define ("TITLE", "EmmaPHP Framework"); define ("BASEPATH", "http://localhost/emmaphp/"); define ("APPPATH", BASEPATH . "application/"); //DEFINE ANY CONSTANTS BELOW
mit
markuscandido/estudo-trilha-testes
jasmine(js)/my-app-test/src/MaiorEMenor.js
404
function MaiorEMenor(){ var menor; var maior; var clazz = { encontra: function(numeros) { menor = Number.MAX_VALUE; maior = Number.MIN_VALUE; numeros.forEach(function(numero) { if(numero < menor) menor = numero; if(numero > maior) maior = numero; }); }, pegaMenor: function() { return menor; }, pegaMaior: function() { return maior; } }; return clazz; };
mit
lpxzz/laravel-shop
app/Admin/Repositories/Presenter/MenuPresenter.php
2121
<?php /** * Created by PhpStorm. * User: xzz * Date: 17-1-11 * Time: 下午8:38 */ namespace App\Admin\Repositories\Presenter; class MenuPresenter{ public function getCategory($menu) { if ($menu){ } } public function getMenuList($menu) { if ($menu){ $item = ''; foreach ($menu as $v){ $item .= $this->getComments($v['id'],$v['title'],$v['child'],$v['order'],$v['url']); } return $item; } return '没有菜单'; } public function getComments($id,$title,$child,$order,$url) { if ($child){ return $this->getHandleList($id,$title,$child,$order,$url); } return ' <li data-order="'.$order.'"class="dd-item" data-id="'.$id.'"><div class="dd-handle"><span class="pull-right"> <a href ="'.route('menu.edit',$id).'"> <button type="button" class="btn btn-xs ink-reaction btn-raised btn-info"><i class=" fa fa-pencil"></i></button> </a> <a href ="'.route('menu.delete',$id).'"> <button type="button" class="btn btn-xs ink-reaction btn-raised btn-danger"><i class=" fa fa-trash"></i></button> </a> </span>'.$title.' ('.$url.')</div></li>'; } public function getHandleList($id,$title,$child,$order,$url) { $handle = '<li data-order="'.$order.'" class="dd-item" data-id="'.$id.'"><div class="dd-handle"><span class="pull-right"> <a href ="'.route('menu.edit',$id).'"> <button type="button" class="btn btn-xs ink-reaction btn-raised btn-info"><i class=" fa fa-pencil"></i></button> </a> <a href ="'.route('menu.delete',$id).'"> <button type="button" class="btn btn-xs ink-reaction btn-raised btn-danger"><i class=" fa fa-trash"></i></button> </a> </span>'.$title.' ('.$url.')</div><ol class="dd-list">'; foreach ($child as $v){ $handle .= $this->getComments($v['id'],$v['title'],$v['child'],$v['order'],$v['url']); } $handle .= '</ol></li>'; return $handle; } }
mit
juqian/Slithice
Slithice/src/jqian/sootex/dependency/DependencyQuery.java
2826
package jqian.sootex.dependency; import java.util.*; import jqian.sootex.CFGProvider; import jqian.sootex.du.IGlobalDUQuery; import jqian.sootex.du.IReachingDUQuery; import jqian.sootex.location.Location; import jqian.sootex.util.SootUtils; import soot.SootMethod; import soot.Unit; import soot.toolkits.graph.UnitGraph; /** * XXX: This class do not cache data, so, could be very slow if reenter. */ public class DependencyQuery implements IDependencyQuery { private IGlobalDUQuery _duQuery; private CFGProvider _cfgProvider; private Map<Unit,Collection<Unit>>[] _method2ctrlDepMap; @SuppressWarnings("unchecked") public DependencyQuery(IGlobalDUQuery duQuery, CFGProvider cfgProvider){ this._duQuery = duQuery; this._cfgProvider = cfgProvider; this._method2ctrlDepMap = new Map[SootUtils.getMethodCount()]; } public void release(SootMethod m){ int mId = m.getNumber(); _duQuery.releaseQuery(m); _method2ctrlDepMap[mId] = null; } public Collection<Unit> getCtrlDependences(SootMethod m, Unit u){ int mId = m.getNumber(); Map<Unit,Collection<Unit>> map = _method2ctrlDepMap[mId]; if(map==null){ UnitGraph cfg = _cfgProvider.getCFG(m); map = DependencyHelper.calcCtrlDependences(cfg); _method2ctrlDepMap[mId] = map; } Collection<Unit> result = map.get(u); return result; } /** Get Write->Read dependences. */ public Collection<Unit> getWRDependences(SootMethod m, Unit u){ IReachingDUQuery rd = _duQuery.getRDQuery(m); IReachingDUQuery ru = _duQuery.getRUQuery(m); Collection<Location> usedLocations = ru.getDULocations(u); Collection<Unit> defs = rd.getReachingDUSites(u, null, usedLocations); return defs; } /** Get Read->Write dependences. */ public Collection<Unit> getRWDependences(SootMethod m, Unit u){ IReachingDUQuery rd = _duQuery.getRDQuery(m); IReachingDUQuery ru = _duQuery.getRUQuery(m); Collection<Location> defLocations = rd.getDULocations(u); Collection<Unit> uses = ru.getReachingDUSites(u, null, defLocations); return uses; } /** Get Write->Write dependences. */ public Collection<Unit> getWWDependences(SootMethod m, Unit u){ IReachingDUQuery rd = _duQuery.getRDQuery(m); Collection<Location> defLocations = rd.getDULocations(u); Collection<Unit> defs = rd.getReachingDUSites(u, null, defLocations); return defs; } public Collection<Unit> getAllDependences(SootMethod m, Unit u){ Collection<Unit> cd = getCtrlDependences(m, u); Collection<Unit> rwd = getRWDependences(m, u); Collection<Unit> wrd = getWRDependences(m, u); Collection<Unit> wwd = getWWDependences(m, u); Collection<Unit> dep = new HashSet<Unit>(); dep.addAll(cd); dep.addAll(rwd); dep.addAll(wrd); dep.addAll(wwd); return dep; } }
mit
diegocastrolosada/SISTRANS
src/jms/AerolineasMDB.java
5570
package jms; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import javax.jms.DeliveryMode; import javax.jms.ExceptionListener; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.Session; import javax.jms.TextMessage; import javax.jms.Topic; import javax.jms.TopicConnection; import javax.jms.TopicConnectionFactory; import javax.jms.TopicPublisher; import javax.jms.TopicSession; import javax.jms.TopicSubscriber; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.xml.bind.DatatypeConverter; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import com.rabbitmq.jms.admin.RMQDestination; import dtm.VuelAndesDistributed; import vos.*; import vos2.ExchangeMsg; public class AerolineasMDB implements MessageListener, ExceptionListener { public final static int TIME_OUT = 5; private final static String APP = "D03"; private final static String GLOBAL_TOPIC_NAME = "java:global/RMQTopicIngresoAerolineas"; private final static String LOCAL_TOPIC_NAME = "java:global/RMQIngresoAerolineasLocal"; private final static String REQUEST = "REQUEST"; private final static String REQUEST_ANSWER = "REQUEST_ANSWER"; private TopicConnection topicConnection; private TopicSession topicSession; private Topic globalTopic; private Topic localTopic; private List<Aerolinea> answer = new ArrayList<Aerolinea>(); public AerolineasMDB(TopicConnectionFactory factory, InitialContext ctx) throws JMSException, NamingException { topicConnection = factory.createTopicConnection(); topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); globalTopic = (RMQDestination) ctx.lookup(GLOBAL_TOPIC_NAME); TopicSubscriber topicSubscriber = topicSession.createSubscriber(globalTopic); topicSubscriber.setMessageListener(this); localTopic = (RMQDestination) ctx.lookup(LOCAL_TOPIC_NAME); topicSubscriber = topicSession.createSubscriber(localTopic); topicSubscriber.setMessageListener(this); topicConnection.setExceptionListener(this); } public void start() throws JMSException { topicConnection.start(); } public void close() throws JMSException { topicSession.close(); topicConnection.close(); } public ListaAerolineas getRemoteAerolineas() throws JsonGenerationException, JsonMappingException, JMSException, IOException, NonReplyException, InterruptedException, NoSuchAlgorithmException { answer.clear(); String id = APP+""+System.currentTimeMillis(); MessageDigest md = MessageDigest.getInstance("MD5"); id = DatatypeConverter.printHexBinary(md.digest(id.getBytes())).substring(0, 8); // id = new String(md.digest(id.getBytes())); sendMessage("", REQUEST, globalTopic, id); boolean waiting = true; int count = 0; while(TIME_OUT != count){ TimeUnit.SECONDS.sleep(1); count++; } if(count == TIME_OUT){ if(this.answer.isEmpty()){ waiting = false; throw new NonReplyException("Time Out - No Reply"); } } waiting = false; if(answer.isEmpty()) throw new NonReplyException("Non Response"); ListaAerolineas res = new ListaAerolineas(answer); return res; } private void sendMessage(String payload, String status, Topic dest, String id) throws JMSException, JsonGenerationException, JsonMappingException, IOException { ObjectMapper mapper = new ObjectMapper(); System.out.println(id); ExchangeMsg msg = new ExchangeMsg("aerolineas.general.D03", APP, payload, status, id); TopicPublisher topicPublisher = topicSession.createPublisher(dest); topicPublisher.setDeliveryMode(DeliveryMode.PERSISTENT); TextMessage txtMsg = topicSession.createTextMessage(); txtMsg.setJMSType("TextMessage"); String envelope = mapper.writeValueAsString(msg); System.out.println(envelope); txtMsg.setText(envelope); topicPublisher.publish(txtMsg); } @Override public void onMessage(Message message) { TextMessage txt = (TextMessage) message; try { String body = txt.getText(); System.out.println(body); ObjectMapper mapper = new ObjectMapper(); ExchangeMsg ex = mapper.readValue(body, ExchangeMsg.class); String id = ex.getMsgId(); System.out.println(ex.getSender()); System.out.println(ex.getStatus()); if(!ex.getSender().equals(APP)) { if(ex.getStatus().equals(REQUEST)) { VuelAndesDistributed dtm = VuelAndesDistributed.getInstance(); ListaAerolineas aerolineas = dtm.getLocalAerolineas(); String payload = mapper.writeValueAsString(aerolineas); Topic t = new RMQDestination("", "aerolineas.test", ex.getRoutingKey(), "", false); sendMessage(payload, REQUEST_ANSWER, t, id); } else if(ex.getStatus().equals(REQUEST_ANSWER)) { ListaAerolineas v = mapper.readValue(ex.getPayload(), ListaAerolineas.class); answer.addAll(v.getAerolineas()); } } } catch (JMSException e) { e.printStackTrace(); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } @Override public void onException(JMSException exception) { System.out.println(exception); } }
mit
aredotna/case
ios/node_modules/ast-types/def/es6.js
8841
module.exports = function (fork) { fork.use(require("./core")); var types = fork.use(require("../lib/types")); var def = types.Type.def; var or = types.Type.or; var defaults = fork.use(require("../lib/shared")).defaults; def("Function") .field("generator", Boolean, defaults["false"]) .field("expression", Boolean, defaults["false"]) .field("defaults", [or(def("Expression"), null)], defaults.emptyArray) // TODO This could be represented as a RestElement in .params. .field("rest", or(def("Identifier"), null), defaults["null"]); // The ESTree way of representing a ...rest parameter. def("RestElement") .bases("Pattern") .build("argument") .field("argument", def("Pattern")) .field("typeAnnotation", // for Babylon. Flow parser puts it on the identifier or(def("TypeAnnotation"), def("TSTypeAnnotation"), null), defaults["null"]); def("SpreadElementPattern") .bases("Pattern") .build("argument") .field("argument", def("Pattern")); def("FunctionDeclaration") .build("id", "params", "body", "generator", "expression"); def("FunctionExpression") .build("id", "params", "body", "generator", "expression"); // The Parser API calls this ArrowExpression, but Esprima and all other // actual parsers use ArrowFunctionExpression. def("ArrowFunctionExpression") .bases("Function", "Expression") .build("params", "body", "expression") // The forced null value here is compatible with the overridden // definition of the "id" field in the Function interface. .field("id", null, defaults["null"]) // Arrow function bodies are allowed to be expressions. .field("body", or(def("BlockStatement"), def("Expression"))) // The current spec forbids arrow generators, so I have taken the // liberty of enforcing that. TODO Report this. .field("generator", false, defaults["false"]); def("ForOfStatement") .bases("Statement") .build("left", "right", "body") .field("left", or( def("VariableDeclaration"), def("Pattern"))) .field("right", def("Expression")) .field("body", def("Statement")); def("YieldExpression") .bases("Expression") .build("argument", "delegate") .field("argument", or(def("Expression"), null)) .field("delegate", Boolean, defaults["false"]); def("GeneratorExpression") .bases("Expression") .build("body", "blocks", "filter") .field("body", def("Expression")) .field("blocks", [def("ComprehensionBlock")]) .field("filter", or(def("Expression"), null)); def("ComprehensionExpression") .bases("Expression") .build("body", "blocks", "filter") .field("body", def("Expression")) .field("blocks", [def("ComprehensionBlock")]) .field("filter", or(def("Expression"), null)); def("ComprehensionBlock") .bases("Node") .build("left", "right", "each") .field("left", def("Pattern")) .field("right", def("Expression")) .field("each", Boolean); def("Property") .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) .field("value", or(def("Expression"), def("Pattern"))) .field("method", Boolean, defaults["false"]) .field("shorthand", Boolean, defaults["false"]) .field("computed", Boolean, defaults["false"]); def("ObjectProperty") .field("shorthand", Boolean, defaults["false"]); def("PropertyPattern") .bases("Pattern") .build("key", "pattern") .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) .field("pattern", def("Pattern")) .field("computed", Boolean, defaults["false"]); def("ObjectPattern") .bases("Pattern") .build("properties") .field("properties", [or(def("PropertyPattern"), def("Property"))]); def("ArrayPattern") .bases("Pattern") .build("elements") .field("elements", [or(def("Pattern"), null)]); def("MethodDefinition") .bases("Declaration") .build("kind", "key", "value", "static") .field("kind", or("constructor", "method", "get", "set")) .field("key", def("Expression")) .field("value", def("Function")) .field("computed", Boolean, defaults["false"]) .field("static", Boolean, defaults["false"]); def("SpreadElement") .bases("Node") .build("argument") .field("argument", def("Expression")); def("ArrayExpression") .field("elements", [or( def("Expression"), def("SpreadElement"), def("RestElement"), null )]); def("NewExpression") .field("arguments", [or(def("Expression"), def("SpreadElement"))]); def("CallExpression") .field("arguments", [or(def("Expression"), def("SpreadElement"))]); // Note: this node type is *not* an AssignmentExpression with a Pattern on // the left-hand side! The existing AssignmentExpression type already // supports destructuring assignments. AssignmentPattern nodes may appear // wherever a Pattern is allowed, and the right-hand side represents a // default value to be destructured against the left-hand side, if no // value is otherwise provided. For example: default parameter values. def("AssignmentPattern") .bases("Pattern") .build("left", "right") .field("left", def("Pattern")) .field("right", def("Expression")); var ClassBodyElement = or( def("MethodDefinition"), def("VariableDeclarator"), def("ClassPropertyDefinition"), def("ClassProperty") ); def("ClassProperty") .bases("Declaration") .build("key") .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) .field("computed", Boolean, defaults["false"]); def("ClassPropertyDefinition") // static property .bases("Declaration") .build("definition") // Yes, Virginia, circular definitions are permitted. .field("definition", ClassBodyElement); def("ClassBody") .bases("Declaration") .build("body") .field("body", [ClassBodyElement]); def("ClassDeclaration") .bases("Declaration") .build("id", "body", "superClass") .field("id", or(def("Identifier"), null)) .field("body", def("ClassBody")) .field("superClass", or(def("Expression"), null), defaults["null"]); def("ClassExpression") .bases("Expression") .build("id", "body", "superClass") .field("id", or(def("Identifier"), null), defaults["null"]) .field("body", def("ClassBody")) .field("superClass", or(def("Expression"), null), defaults["null"]); // Specifier and ModuleSpecifier are abstract non-standard types // introduced for definitional convenience. def("Specifier").bases("Node"); // This supertype is shared/abused by both def/babel.js and // def/esprima.js. In the future, it will be possible to load only one set // of definitions appropriate for a given parser, but until then we must // rely on default functions to reconcile the conflicting AST formats. def("ModuleSpecifier") .bases("Specifier") // This local field is used by Babel/Acorn. It should not technically // be optional in the Babel/Acorn AST format, but it must be optional // in the Esprima AST format. .field("local", or(def("Identifier"), null), defaults["null"]) // The id and name fields are used by Esprima. The id field should not // technically be optional in the Esprima AST format, but it must be // optional in the Babel/Acorn AST format. .field("id", or(def("Identifier"), null), defaults["null"]) .field("name", or(def("Identifier"), null), defaults["null"]); // Like ModuleSpecifier, except type:"ImportSpecifier" and buildable. // import {<id [as name]>} from ...; def("ImportSpecifier") .bases("ModuleSpecifier") .build("id", "name"); // import <* as id> from ...; def("ImportNamespaceSpecifier") .bases("ModuleSpecifier") .build("id"); // import <id> from ...; def("ImportDefaultSpecifier") .bases("ModuleSpecifier") .build("id"); def("ImportDeclaration") .bases("Declaration") .build("specifiers", "source", "importKind") .field("specifiers", [or( def("ImportSpecifier"), def("ImportNamespaceSpecifier"), def("ImportDefaultSpecifier") )], defaults.emptyArray) .field("source", def("Literal")) .field("importKind", or( "value", "type" ), function() { return "value"; }); def("TaggedTemplateExpression") .bases("Expression") .build("tag", "quasi") .field("tag", def("Expression")) .field("quasi", def("TemplateLiteral")); def("TemplateLiteral") .bases("Expression") .build("quasis", "expressions") .field("quasis", [def("TemplateElement")]) .field("expressions", [def("Expression")]); def("TemplateElement") .bases("Node") .build("value", "tail") .field("value", {"cooked": String, "raw": String}) .field("tail", Boolean); };
mit
hungpham2511/toppra
cpp/tests/test_spline_parametrizer.cpp
2494
#include <toppra/parametrizer/spline.hpp> #include <toppra/geometric_path/piecewise_poly_path.hpp> #include "gtest/gtest.h" #define TEST_PRECISION 1e-15 class ParametrizeSpline : public testing::Test { public: ParametrizeSpline() { toppra::Matrix coeff0{4, 2}, coeff1{4, 2}, coeff2{4, 2}; coeff0 << -0.500000, -0.500000, 1.500000, 0.500000, 0.000000, 3.000000, 0.000000, 0.000000; coeff1 << -0.500000, -0.500000, 0.000000, -1.000000, 1.500000, 2.500000, 1.000000, 3.000000; coeff2 << -0.500000, -0.500000, -1.500000, -2.500000, 0.000000, -1.000000, 2.000000, 4.000000; toppra::Matrices coefficents = {coeff0, coeff1, coeff2}; path = std::make_shared<toppra::PiecewisePolyPath>( coefficents, std::vector<toppra::value_type>{0, 1, 2, 3}); }; std::shared_ptr<toppra::PiecewisePolyPath> path; }; TEST_F(ParametrizeSpline, BasicUsage) { toppra::Vector gridpoints = toppra::Vector::LinSpaced(10, 0, 3); toppra::Vector vsquared{10}; vsquared << 1, 0.9, 0.8, 0.7, 0.6, 0.6, 0.7, 0.8, 0.9, 1; auto p = toppra::parametrizer::Spline(path, gridpoints, vsquared); // Assert q at each gridpoint toppra::value_type t = 0.0; toppra::Vector actual_q = p.eval_single(t), desired_q = path->eval_single(t); for (size_t i = 1; i < gridpoints.rows(); i++) { ASSERT_NEAR(actual_q[0], desired_q[0], TEST_PRECISION); ASSERT_NEAR(actual_q[1], desired_q[1], TEST_PRECISION); t += (gridpoints[i] - gridpoints[i - 1]) / (std::sqrt(vsquared[i]) + std::sqrt(vsquared[i - 1])) * 2; actual_q = p.eval_single(t); desired_q = path->eval_single(gridpoints[i]); } toppra::Bound path_interval = p.pathInterval(); toppra::Vector ts = toppra::Vector{2}; ts << path_interval[0], path_interval[1]; toppra::Vectors qd = p.eval(ts, 1); toppra::Vector qd_init (2), qd_final (2); qd_init << 0 * std::sqrt(vsquared[0]), 3 * std::sqrt(vsquared[0]); qd_final << (-1.5 * std::pow(3 - 2, 2) - 3 * (3 - 2)) * std::sqrt(vsquared[vsquared.rows() - 1]), (-1.5 * std::pow(3 - 2, 2) - 5 * (3 - 2) - 1) * std::sqrt(vsquared[vsquared.rows() - 1]); // Assert qd at endpoints ASSERT_NEAR(qd[0][0], qd_init[0], TEST_PRECISION); ASSERT_NEAR(qd[0][1], qd_init[1], TEST_PRECISION); ASSERT_NEAR(qd[1][0], qd_final[0], TEST_PRECISION); ASSERT_NEAR(qd[1][1], qd_final[1], TEST_PRECISION); }
mit
Symfony-Plugins/sfDIPlugin
lib/DataIntegrator/OAuth/Token.php
1624
<?php /** * OAuth Model objects * * Adapted from Andy Smith's OAuth library for PHP * * @link http://oauth.net/core/1.0 * @link http://oauth.googlecode.com/svn/spec/ext/consumer_request/1.0/drafts/1/spec.html * @link http://oauth.googlecode.com/svn/code/php/ * @link http://term.ie/oauth/example/ * * @package OAuth * * @author jhart * @copyright Copyright (c) 2008, Photobucket, Inc. * @license http://www.opensource.org/licenses/mit-license.php The MIT License */ /** * OAuth Token representation * * @package OAuth */ class OAuth_Token { /** * Token key * * @var string oauth_token */ public $key; /** * Token secret * * @var string oauth_token_secret */ public $secret; /** * Constructor * * @param string $key oauth_token * @param string $secret oauth_token_secret */ public function __construct($key, $secret) { $this->key = $key; $this->secret = $secret; } /** * Returns postdata representation of the token * * @return string postdata and OAuth Standard representation */ public function __toString() { return 'oauth_token=' . urlencode($this->getKey()) . '&oauth_token_secret=' . urlencode($this->getSecret()); } /** * get key * * @return string oauth_token */ public function getKey() { return $this->key; } /** * get token * * @return string oauth_token_secret */ public function getSecret() { return $this->secret; } }
mit
unknownzerx/go-mysql
replication/event.go
8450
package replication import ( "encoding/binary" //"encoding/hex" "fmt" "io" "strconv" "strings" "time" "unicode" "github.com/satori/go.uuid" . "github.com/siddontang/go-mysql/mysql" ) const ( EventHeaderSize = 19 ) type BinlogEvent struct { // raw binlog data, including crc32 checksum if exists RawData []byte Header *EventHeader Event Event } func (e *BinlogEvent) Dump(w io.Writer) { e.Header.Dump(w) e.Event.Dump(w) } type Event interface { //Dump Event, format like python-mysql-replication Dump(w io.Writer) Decode(data []byte) error } type EventError struct { Header *EventHeader //Error message Err string //Event data Data []byte } func (e *EventError) Error() string { return e.Err } type EventHeader struct { Timestamp uint32 EventType EventType ServerID uint32 EventSize uint32 LogPos uint32 Flags uint16 } func (h *EventHeader) Decode(data []byte) error { if len(data) < EventHeaderSize { return fmt.Errorf("header size too short %d, must 19", len(data)) } pos := 0 h.Timestamp = binary.LittleEndian.Uint32(data[pos:]) pos += 4 h.EventType = EventType(data[pos]) pos++ h.ServerID = binary.LittleEndian.Uint32(data[pos:]) pos += 4 h.EventSize = binary.LittleEndian.Uint32(data[pos:]) pos += 4 h.LogPos = binary.LittleEndian.Uint32(data[pos:]) pos += 4 h.Flags = binary.LittleEndian.Uint16(data[pos:]) pos += 2 if h.EventSize < uint32(EventHeaderSize) { return fmt.Errorf("invalid event size %d, must >= 19", h.EventSize) } return nil } func (h *EventHeader) Dump(w io.Writer) { fmt.Fprintf(w, "=== %s ===\n", EventType(h.EventType)) fmt.Fprintf(w, "Date: %s\n", time.Unix(int64(h.Timestamp), 0).Format(TimeFormat)) fmt.Fprintf(w, "Log position: %d\n", h.LogPos) fmt.Fprintf(w, "Event size: %d\n", h.EventSize) } var ( checksumVersionSplitMysql []int = []int{5, 6, 1} checksumVersionProductMysql int = (checksumVersionSplitMysql[0]*256+checksumVersionSplitMysql[1])*256 + checksumVersionSplitMysql[2] checksumVersionSplitMariaDB []int = []int{5, 3, 0} checksumVersionProductMariaDB int = (checksumVersionSplitMariaDB[0]*256+checksumVersionSplitMariaDB[1])*256 + checksumVersionSplitMariaDB[2] ) // server version format X.Y.Zabc, a is not . or number func splitServerVersion(server string) []int { seps := strings.Split(server, ".") if len(seps) < 3 { return []int{0, 0, 0} } x, _ := strconv.Atoi(seps[0]) y, _ := strconv.Atoi(seps[1]) index := 0 for i, c := range seps[2] { if !unicode.IsNumber(c) { index = i break } } z, _ := strconv.Atoi(seps[2][0:index]) return []int{x, y, z} } func calcVersionProduct(server string) int { versionSplit := splitServerVersion(server) return ((versionSplit[0]*256+versionSplit[1])*256 + versionSplit[2]) } type FormatDescriptionEvent struct { Version uint16 //len = 50 ServerVersion []byte CreateTimestamp uint32 EventHeaderLength uint8 EventTypeHeaderLengths []byte // 0 is off, 1 is for CRC32, 255 is undefined ChecksumAlgorithm byte } func (e *FormatDescriptionEvent) Decode(data []byte) error { pos := 0 e.Version = binary.LittleEndian.Uint16(data[pos:]) pos += 2 e.ServerVersion = make([]byte, 50) copy(e.ServerVersion, data[pos:]) pos += 50 e.CreateTimestamp = binary.LittleEndian.Uint32(data[pos:]) pos += 4 e.EventHeaderLength = data[pos] pos++ if e.EventHeaderLength != byte(EventHeaderSize) { return fmt.Errorf("invalid event header length %d, must 19", e.EventHeaderLength) } server := string(e.ServerVersion) checksumProduct := checksumVersionProductMysql if strings.Contains(strings.ToLower(server), "mariadb") { checksumProduct = checksumVersionProductMariaDB } if calcVersionProduct(string(e.ServerVersion)) >= checksumProduct { // here, the last 5 bytes is 1 byte check sum alg type and 4 byte checksum if exists e.ChecksumAlgorithm = data[len(data)-5] e.EventTypeHeaderLengths = data[pos : len(data)-5] } else { e.ChecksumAlgorithm = BINLOG_CHECKSUM_ALG_UNDEF e.EventTypeHeaderLengths = data[pos:] } return nil } func (e *FormatDescriptionEvent) Dump(w io.Writer) { fmt.Fprintf(w, "Version: %d\n", e.Version) fmt.Fprintf(w, "Server version: %s\n", e.ServerVersion) //fmt.Fprintf(w, "Create date: %s\n", time.Unix(int64(e.CreateTimestamp), 0).Format(TimeFormat)) fmt.Fprintf(w, "Checksum algorithm: %d\n", e.ChecksumAlgorithm) //fmt.Fprintf(w, "Event header lengths: \n%s", hex.Dump(e.EventTypeHeaderLengths)) fmt.Fprintln(w) } type RotateEvent struct { Position uint64 NextLogName []byte } func (e *RotateEvent) Decode(data []byte) error { e.Position = binary.LittleEndian.Uint64(data[0:]) e.NextLogName = data[8:] return nil } func (e *RotateEvent) Dump(w io.Writer) { fmt.Fprintf(w, "Position: %d\n", e.Position) fmt.Fprintf(w, "Next log name: %s\n", e.NextLogName) fmt.Fprintln(w) } type XIDEvent struct { XID uint64 } func (e *XIDEvent) Decode(data []byte) error { e.XID = binary.LittleEndian.Uint64(data) return nil } func (e *XIDEvent) Dump(w io.Writer) { fmt.Fprintf(w, "XID: %d\n", e.XID) fmt.Fprintln(w) } type QueryEvent struct { SlaveProxyID uint32 ExecutionTime uint32 ErrorCode uint16 StatusVars []byte Schema []byte Query []byte } func (e *QueryEvent) Decode(data []byte) error { pos := 0 e.SlaveProxyID = binary.LittleEndian.Uint32(data[pos:]) pos += 4 e.ExecutionTime = binary.LittleEndian.Uint32(data[pos:]) pos += 4 schemaLength := uint8(data[pos]) pos++ e.ErrorCode = binary.LittleEndian.Uint16(data[pos:]) pos += 2 statusVarsLength := binary.LittleEndian.Uint16(data[pos:]) pos += 2 e.StatusVars = data[pos : pos+int(statusVarsLength)] pos += int(statusVarsLength) e.Schema = data[pos : pos+int(schemaLength)] pos += int(schemaLength) //skip 0x00 pos++ e.Query = data[pos:] return nil } func (e *QueryEvent) Dump(w io.Writer) { fmt.Fprintf(w, "Salve proxy ID: %d\n", e.SlaveProxyID) fmt.Fprintf(w, "Execution time: %d\n", e.ExecutionTime) fmt.Fprintf(w, "Error code: %d\n", e.ErrorCode) //fmt.Fprintf(w, "Status vars: \n%s", hex.Dump(e.StatusVars)) fmt.Fprintf(w, "Schema: %s\n", e.Schema) fmt.Fprintf(w, "Query: %s\n", e.Query) fmt.Fprintln(w) } type GTIDEvent struct { CommitFlag uint8 SID []byte GNO int64 } func (e *GTIDEvent) Decode(data []byte) error { e.CommitFlag = uint8(data[0]) e.SID = data[1:17] e.GNO = int64(binary.LittleEndian.Uint64(data[17:])) return nil } func (e *GTIDEvent) Dump(w io.Writer) { fmt.Fprintf(w, "Commit flag: %d\n", e.CommitFlag) u, _ := uuid.FromBytes(e.SID) fmt.Fprintf(w, "GTID_NEXT: %s:%d\n", u.String(), e.GNO) fmt.Fprintln(w) } func (e *GTIDEvent) GtidDesc() string { u, _ := uuid.FromBytes(e.SID) return fmt.Sprintf("%s:%d", u.String(), e.GNO) } // case MARIADB_ANNOTATE_ROWS_EVENT: // return "MariadbAnnotateRowsEvent" type MariadbAnnotaeRowsEvent struct { Query []byte } func (e *MariadbAnnotaeRowsEvent) Decode(data []byte) error { e.Query = data return nil } func (e *MariadbAnnotaeRowsEvent) Dump(w io.Writer) { fmt.Fprintf(w, "Query: %s\n", e.Query) fmt.Fprintln(w) } type MariadbBinlogCheckPointEvent struct { Info []byte } func (e *MariadbBinlogCheckPointEvent) Decode(data []byte) error { e.Info = data return nil } func (e *MariadbBinlogCheckPointEvent) Dump(w io.Writer) { fmt.Fprintf(w, "Info: %s\n", e.Info) fmt.Fprintln(w) } type MariadbGTIDEvent struct { GTID MariadbGTID } func (e *MariadbGTIDEvent) Decode(data []byte) error { e.GTID.SequenceNumber = binary.LittleEndian.Uint64(data) e.GTID.DomainID = binary.LittleEndian.Uint32(data[8:]) // we don't care commit id now, maybe later return nil } func (e *MariadbGTIDEvent) Dump(w io.Writer) { fmt.Fprintf(w, "GTID: %s\n", e.GTID) fmt.Fprintln(w) } type MariadbGTIDListEvent struct { GTIDs []MariadbGTID } func (e *MariadbGTIDListEvent) Decode(data []byte) error { pos := 0 v := binary.LittleEndian.Uint32(data[pos:]) pos += 4 count := v & uint32((1<<28)-1) e.GTIDs = make([]MariadbGTID, count) for i := uint32(0); i < count; i++ { e.GTIDs[i].DomainID = binary.LittleEndian.Uint32(data[pos:]) pos += 4 e.GTIDs[i].ServerID = binary.LittleEndian.Uint32(data[pos:]) pos += 4 e.GTIDs[i].SequenceNumber = binary.LittleEndian.Uint64(data[pos:]) } return nil } func (e *MariadbGTIDListEvent) Dump(w io.Writer) { fmt.Fprintf(w, "Lists: %v\n", e.GTIDs) fmt.Fprintln(w) }
mit
andela-iukwuoma/docman
client/tests/components/layouts/Sidebar.spec.js
2058
import expect from 'expect'; import sinon from 'sinon'; import React from 'react'; import { shallow, mount } from 'enzyme'; import { Sidebar } from '../../../components/layouts/Sidebar'; const logout = sinon.spy(() => Promise.resolve()); const deleteUser = sinon.spy(() => Promise.resolve()); const swal = sinon.spy(() => Promise.resolve()); const props = { user: { id: 3 }, access: { user: { roleId: 2 } }, logout, deleteUser }; describe('Sidebar Component', () => { it('renders the document sidebar', () => { const wrapper = shallow(<Sidebar {...props} />, { context: { router: { push: () => {} } } }); expect(wrapper.find('DocumentSidebar').length).toBe(1); }); it('renders the admin sidebar for admins', () => { const wrapper = shallow(<Sidebar {...props} />, { context: { router: { push: () => {} } } }); expect(wrapper.find('AdminSidebar').length).toBe(1); }); it('correctly passes in props', () => { const wrapper = shallow(<Sidebar {...props} />, { context: { router: { push: () => {} } } }); expect(wrapper.find('AdminSidebar').props().access) .toEqual(wrapper.state('access')); }); it('does not render the admin sidebar for non-admins', () => { props.access.user.roleId = 3; const wrapper = shallow(<Sidebar {...props} />, { context: { router: { push: () => {} } } }); expect(wrapper.find('AdminSidebar').length).toBe(0); }); it('updates the user in state if user id changes', () => { const spy = sinon.spy(Sidebar.prototype, 'componentWillReceiveProps'); const wrapper = shallow(<Sidebar {...props} />, { context: { router: { push: () => {} } } }); wrapper.setProps({ user: { id: 4 } }); expect(wrapper.state().user).toEqual({ id: 4 }); expect(spy.calledOnce).toEqual(true); }); it('deletes a user when delete functions runs', () => { const wrapper = shallow(<Sidebar {...props} />, { context: { router: { push: () => {} } } }); wrapper.instance().delete(); expect(deleteUser.calledOnce).toBe(true); }); });
mit
shelmesky/raft
protobuf/request_vote_responses.pb.go
1088
// Code generated by protoc-gen-go. // source: request_vote_responses.proto // DO NOT EDIT! package protobuf import proto "github.com/golang/protobuf/proto" import math "math" // discarding unused import gogoproto "code.google.com/p/gogoprotobuf/gogoproto/gogo.pb" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = math.Inf type RequestVoteResponse struct { Term *uint64 `protobuf:"varint,1,req" json:"Term,omitempty"` VoteGranted *bool `protobuf:"varint,2,req" json:"VoteGranted,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *RequestVoteResponse) Reset() { *m = RequestVoteResponse{} } func (m *RequestVoteResponse) String() string { return proto.CompactTextString(m) } func (*RequestVoteResponse) ProtoMessage() {} func (m *RequestVoteResponse) GetTerm() uint64 { if m != nil && m.Term != nil { return *m.Term } return 0 } func (m *RequestVoteResponse) GetVoteGranted() bool { if m != nil && m.VoteGranted != nil { return *m.VoteGranted } return false } func init() { }
mit
giuliopb/ES2
application/views/backend/login.php
1673
<div class="container"> <div class="row"> <div class="col-md-4 col-md-offset-4"> <div class="login-panel panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Entrar no sistema</h3> </div> <div class="panel-body"> <?php if(isset($erro)){ echo '<div class="alert alert-danger">'.$erro.'</div>'; } echo validation_errors('<div class="alert alert-danger">','</div>'); echo form_open(base_url('admin/usuarios/login')); ?> <fieldset> <div class="form-group"> <input class="form-control" placeholder="Usuário" name="txt-user" type="text" autofocus> </div> <div class="form-group"> <input class="form-control" placeholder="Senha" name="txt-senha" type="password" value=""> </div> <!-- Change this to a button or input when using this as a form --> <button class="btn btn-lg btn-success btn-block">Entrar</button> </fieldset> <?php echo form_close(); ?> </div> </div> </div> </div> </div>
mit
solodeuva/polideportivo
application/libraries/jpgraph/ci_jpgraph.php
100556
<?php //======================================================================= // File: JPGRAPH.PHP // Description: PHP Graph Plotting library. Base module. // Created: 2001-01-08 // Ver: $Id: jpgraph.php 1924 2010-01-11 14:03:26Z ljp $ // // Copyright (c) Asial Corporation. All rights reserved. //======================================================================== require_once('jpg-config.inc.php'); require_once('jpgraph_gradient.php'); require_once('jpgraph_errhandler.inc.php'); require_once('jpgraph_ttf.inc.php'); require_once('jpgraph_rgb.inc.php'); require_once('jpgraph_text.inc.php'); require_once('jpgraph_legend.inc.php'); require_once('jpgraph_theme.inc.php'); require_once('gd_image.inc.php'); // Version info define('JPG_VERSION','3.5.0b1'); // Minimum required PHP version define('MIN_PHPVERSION','5.1.0'); // Special file name to indicate that we only want to calc // the image map in the call to Graph::Stroke() used // internally from the GetHTMLCSIM() method. define('_CSIM_SPECIALFILE','_csim_special_'); // HTTP GET argument that is used with image map // to indicate to the script to just generate the image // and not the full CSIM HTML page. define('_CSIM_DISPLAY','_jpg_csimd'); // Special filename for Graph::Stroke(). If this filename is given // then the image will NOT be streamed to browser of file. Instead the // Stroke call will return the handler for the created GD image. define('_IMG_HANDLER','__handle'); // Special filename for Graph::Stroke(). If this filename is given // the image will be stroked to a file with a name based on the script name. define('_IMG_AUTO','auto'); // Tick density define("TICKD_DENSE",1); define("TICKD_NORMAL",2); define("TICKD_SPARSE",3); define("TICKD_VERYSPARSE",4); // Side for ticks and labels. define("SIDE_LEFT",-1); define("SIDE_RIGHT",1); define("SIDE_DOWN",-1); define("SIDE_BOTTOM",-1); define("SIDE_UP",1); define("SIDE_TOP",1); // Legend type stacked vertical or horizontal define("LEGEND_VERT",0); define("LEGEND_HOR",1); // Mark types for plot marks define("MARK_SQUARE",1); define("MARK_UTRIANGLE",2); define("MARK_DTRIANGLE",3); define("MARK_DIAMOND",4); define("MARK_CIRCLE",5); define("MARK_FILLEDCIRCLE",6); define("MARK_CROSS",7); define("MARK_STAR",8); define("MARK_X",9); define("MARK_LEFTTRIANGLE",10); define("MARK_RIGHTTRIANGLE",11); define("MARK_FLASH",12); define("MARK_IMG",13); define("MARK_FLAG1",14); define("MARK_FLAG2",15); define("MARK_FLAG3",16); define("MARK_FLAG4",17); // Builtin images define("MARK_IMG_PUSHPIN",50); define("MARK_IMG_SPUSHPIN",50); define("MARK_IMG_LPUSHPIN",51); define("MARK_IMG_DIAMOND",52); define("MARK_IMG_SQUARE",53); define("MARK_IMG_STAR",54); define("MARK_IMG_BALL",55); define("MARK_IMG_SBALL",55); define("MARK_IMG_MBALL",56); define("MARK_IMG_LBALL",57); define("MARK_IMG_BEVEL",58); // Inline defines define("INLINE_YES",1); define("INLINE_NO",0); // Format for background images define("BGIMG_FILLPLOT",1); define("BGIMG_FILLFRAME",2); define("BGIMG_COPY",3); define("BGIMG_CENTER",4); define("BGIMG_FREE",5); // Depth of objects define("DEPTH_BACK",0); define("DEPTH_FRONT",1); // Direction define("VERTICAL",1); define("HORIZONTAL",0); // Axis styles for scientific style axis define('AXSTYLE_SIMPLE',1); define('AXSTYLE_BOXIN',2); define('AXSTYLE_BOXOUT',3); define('AXSTYLE_YBOXIN',4); define('AXSTYLE_YBOXOUT',5); // Style for title backgrounds define('TITLEBKG_STYLE1',1); define('TITLEBKG_STYLE2',2); define('TITLEBKG_STYLE3',3); define('TITLEBKG_FRAME_NONE',0); define('TITLEBKG_FRAME_FULL',1); define('TITLEBKG_FRAME_BOTTOM',2); define('TITLEBKG_FRAME_BEVEL',3); define('TITLEBKG_FILLSTYLE_HSTRIPED',1); define('TITLEBKG_FILLSTYLE_VSTRIPED',2); define('TITLEBKG_FILLSTYLE_SOLID',3); // Styles for axis labels background define('LABELBKG_NONE',0); define('LABELBKG_XAXIS',1); define('LABELBKG_YAXIS',2); define('LABELBKG_XAXISFULL',3); define('LABELBKG_YAXISFULL',4); define('LABELBKG_XYFULL',5); define('LABELBKG_XY',6); // Style for background gradient fills define('BGRAD_FRAME',1); define('BGRAD_MARGIN',2); define('BGRAD_PLOT',3); // Width of tab titles define('TABTITLE_WIDTHFIT',0); define('TABTITLE_WIDTHFULL',-1); // Defines for 3D skew directions define('SKEW3D_UP',0); define('SKEW3D_DOWN',1); define('SKEW3D_LEFT',2); define('SKEW3D_RIGHT',3); // For internal use only define("_JPG_DEBUG",false); define("_FORCE_IMGTOFILE",false); define("_FORCE_IMGDIR",'/tmp/jpgimg/'); // // Automatic settings of path for cache and font directory // if they have not been previously specified // if(USE_CACHE) { if (!defined('CACHE_DIR')) { if ( strstr( PHP_OS, 'WIN') ) { if( empty($_SERVER['TEMP']) ) { $t = new ErrMsgText(); $msg = $t->Get(11,$file,$lineno); die($msg); } else { define('CACHE_DIR', $_SERVER['TEMP'] . '/'); } } else { define('CACHE_DIR','/tmp/jpgraph_cache/'); } } } elseif( !defined('CACHE_DIR') ) { define('CACHE_DIR', ''); } // // Setup path for western/latin TTF fonts // if (!defined('TTF_DIR')) { if (strstr( PHP_OS, 'WIN') ) { $sroot = getenv('SystemRoot'); if( empty($sroot) ) { $t = new ErrMsgText(); $msg = $t->Get(12,$file,$lineno); die($msg); } else { define('TTF_DIR', $sroot.'/fonts/'); } } else { define('TTF_DIR','/usr/share/fonts/truetype/'); } } // // Setup path for MultiByte TTF fonts (japanese, chinese etc.) // if (!defined('MBTTF_DIR')) { if (strstr( PHP_OS, 'WIN') ) { $sroot = getenv('SystemRoot'); if( empty($sroot) ) { $t = new ErrMsgText(); $msg = $t->Get(12,$file,$lineno); die($msg); } else { define('MBTTF_DIR', $sroot.'/fonts/'); } } else { define('MBTTF_DIR','/usr/share/fonts/truetype/'); } } // // Check minimum PHP version // function CheckPHPVersion($aMinVersion) { list($majorC, $minorC, $editC) = preg_split('/[\/.-]/', PHP_VERSION); list($majorR, $minorR, $editR) = preg_split('/[\/.-]/', $aMinVersion); if ($majorC != $majorR) return false; if ($majorC < $majorR) return false; // same major - check minor if ($minorC > $minorR) return true; if ($minorC < $minorR) return false; // and same minor if ($editC >= $editR) return true; return true; } // // Make sure PHP version is high enough // if( !CheckPHPVersion(MIN_PHPVERSION) ) { JpGraphError::RaiseL(13,PHP_VERSION,MIN_PHPVERSION); die(); } // // Make GD sanity check // if( !function_exists("imagetypes") || !function_exists('imagecreatefromstring') ) { JpGraphError::RaiseL(25001); //("This PHP installation is not configured with the GD library. Please recompile PHP with GD support to run JpGraph. (Neither function imagetypes() nor imagecreatefromstring() does exist)"); } // // Setup PHP error handler // function _phpErrorHandler($errno,$errmsg,$filename, $linenum, $vars) { // Respect current error level if( $errno & error_reporting() ) { JpGraphError::RaiseL(25003,basename($filename),$linenum,$errmsg); } } if( INSTALL_PHP_ERR_HANDLER ) { set_error_handler("_phpErrorHandler"); } // // Check if there were any warnings, perhaps some wrong includes by the user. In this // case we raise it immediately since otherwise the image will not show and makes // debugging difficult. This is controlled by the user setting CATCH_PHPERRMSG // if( isset($GLOBALS['php_errormsg']) && CATCH_PHPERRMSG && !preg_match('/|Deprecated|/i', $GLOBALS['php_errormsg']) ) { JpGraphError::RaiseL(25004,$GLOBALS['php_errormsg']); } // Useful mathematical function function sign($a) {return $a >= 0 ? 1 : -1;} // // Utility function to generate an image name based on the filename we // are running from and assuming we use auto detection of graphic format // (top level), i.e it is safe to call this function // from a script that uses JpGraph // function GenImgName() { // Determine what format we should use when we save the images $supported = imagetypes(); if( $supported & IMG_PNG ) $img_format="png"; elseif( $supported & IMG_GIF ) $img_format="gif"; elseif( $supported & IMG_JPG ) $img_format="jpeg"; elseif( $supported & IMG_WBMP ) $img_format="wbmp"; elseif( $supported & IMG_XPM ) $img_format="xpm"; if( !isset($_SERVER['PHP_SELF']) ) { JpGraphError::RaiseL(25005); //(" Can't access PHP_SELF, PHP global variable. You can't run PHP from command line if you want to use the 'auto' naming of cache or image files."); } $fname = basename($_SERVER['PHP_SELF']); if( !empty($_SERVER['QUERY_STRING']) ) { $q = @$_SERVER['QUERY_STRING']; $fname .= '_'.preg_replace("/\W/", "_", $q).'.'.$img_format; } else { $fname = substr($fname,0,strlen($fname)-4).'.'.$img_format; } return $fname; } //=================================================== // CLASS JpgTimer // Description: General timing utility class to handle // time measurement of generating graphs. Multiple // timers can be started. //=================================================== class JpgTimer { private $start, $idx; function __construct() { $this->idx=0; } // Push a new timer start on stack function Push() { list($ms,$s)=explode(" ",microtime()); $this->start[$this->idx++]=floor($ms*1000) + 1000*$s; } // Pop the latest timer start and return the diff with the // current time function Pop() { assert($this->idx>0); list($ms,$s)=explode(" ",microtime()); $etime=floor($ms*1000) + (1000*$s); $this->idx--; return $etime-$this->start[$this->idx]; } } // Class //=================================================== // CLASS DateLocale // Description: Hold localized text used in dates //=================================================== class DateLocale { public $iLocale = 'C'; // environmental locale be used by default private $iDayAbb = null, $iShortDay = null, $iShortMonth = null, $iMonthName = null; function __construct() { settype($this->iDayAbb, 'array'); settype($this->iShortDay, 'array'); settype($this->iShortMonth, 'array'); settype($this->iMonthName, 'array'); $this->Set('C'); } function Set($aLocale) { if ( in_array($aLocale, array_keys($this->iDayAbb)) ){ $this->iLocale = $aLocale; return TRUE; // already cached nothing else to do! } $pLocale = setlocale(LC_TIME, 0); // get current locale for LC_TIME if (is_array($aLocale)) { foreach ($aLocale as $loc) { $res = @setlocale(LC_TIME, $loc); if ( $res ) { $aLocale = $loc; break; } } } else { $res = @setlocale(LC_TIME, $aLocale); } if ( ! $res ) { JpGraphError::RaiseL(25007,$aLocale); //("You are trying to use the locale ($aLocale) which your PHP installation does not support. Hint: Use '' to indicate the default locale for this geographic region."); return FALSE; } $this->iLocale = $aLocale; for( $i = 0, $ofs = 0 - strftime('%w'); $i < 7; $i++, $ofs++ ) { $day = strftime('%a', strtotime("$ofs day")); $day[0] = strtoupper($day[0]); $this->iDayAbb[$aLocale][]= $day[0]; $this->iShortDay[$aLocale][]= $day; } for($i=1; $i<=12; ++$i) { list($short ,$full) = explode('|', strftime("%b|%B",strtotime("2001-$i-01"))); $this->iShortMonth[$aLocale][] = ucfirst($short); $this->iMonthName [$aLocale][] = ucfirst($full); } setlocale(LC_TIME, $pLocale); return TRUE; } function GetDayAbb() { return $this->iDayAbb[$this->iLocale]; } function GetShortDay() { return $this->iShortDay[$this->iLocale]; } function GetShortMonth() { return $this->iShortMonth[$this->iLocale]; } function GetShortMonthName($aNbr) { return $this->iShortMonth[$this->iLocale][$aNbr]; } function GetLongMonthName($aNbr) { return $this->iMonthName[$this->iLocale][$aNbr]; } function GetMonth() { return $this->iMonthName[$this->iLocale]; } } // Global object handlers $gDateLocale = new DateLocale(); $gJpgDateLocale = new DateLocale(); //======================================================= // CLASS Footer // Description: Encapsulates the footer line in the Graph //======================================================= class Footer { public $iLeftMargin = 3, $iRightMargin = 3, $iBottomMargin = 3 ; public $left,$center,$right; private $iTimer=null, $itimerpoststring=''; function __construct() { $this->left = new Text(); $this->left->ParagraphAlign('left'); $this->center = new Text(); $this->center->ParagraphAlign('center'); $this->right = new Text(); $this->right->ParagraphAlign('right'); } function SetTimer($aTimer,$aTimerPostString='') { $this->iTimer = $aTimer; $this->itimerpoststring = $aTimerPostString; } function SetMargin($aLeft=3,$aRight=3,$aBottom=3) { $this->iLeftMargin = $aLeft; $this->iRightMargin = $aRight; $this->iBottomMargin = $aBottom; } function Stroke($aImg) { $y = $aImg->height - $this->iBottomMargin; $x = $this->iLeftMargin; $this->left->Align('left','bottom'); $this->left->Stroke($aImg,$x,$y); $x = ($aImg->width - $this->iLeftMargin - $this->iRightMargin)/2; $this->center->Align('center','bottom'); $this->center->Stroke($aImg,$x,$y); $x = $aImg->width - $this->iRightMargin; $this->right->Align('right','bottom'); if( $this->iTimer != null ) { $this->right->Set( $this->right->t . sprintf('%.3f',$this->iTimer->Pop()/1000.0) . $this->itimerpoststring ); } $this->right->Stroke($aImg,$x,$y); } } //=================================================== // CLASS LineProperty // Description: Holds properties for a line //=================================================== class LineProperty { public $iWeight=1, $iColor='black', $iStyle='solid', $iShow=false; function __construct($aWeight=1,$aColor='black',$aStyle='solid') { $this->iWeight = $aWeight; $this->iColor = $aColor; $this->iStyle = $aStyle; } function SetColor($aColor) { $this->iColor = $aColor; } function SetWeight($aWeight) { $this->iWeight = $aWeight; } function SetStyle($aStyle) { $this->iStyle = $aStyle; } function Show($aShow=true) { $this->iShow=$aShow; } function Stroke($aImg,$aX1,$aY1,$aX2,$aY2) { if( $this->iShow ) { $aImg->PushColor($this->iColor); $oldls = $aImg->line_style; $oldlw = $aImg->line_weight; $aImg->SetLineWeight($this->iWeight); $aImg->SetLineStyle($this->iStyle); $aImg->StyleLine($aX1,$aY1,$aX2,$aY2); $aImg->PopColor($this->iColor); $aImg->line_style = $oldls; $aImg->line_weight = $oldlw; } } } //=================================================== // CLASS GraphTabTitle // Description: Draw "tab" titles on top of graphs //=================================================== class GraphTabTitle extends Text{ private $corner = 6 , $posx = 7, $posy = 4; private $fillcolor='lightyellow',$bordercolor='black'; private $align = 'left', $width=TABTITLE_WIDTHFIT; function __construct() { $this->t = ''; $this->font_style = FS_BOLD; $this->hide = true; $this->color = 'darkred'; } function SetColor($aTxtColor,$aFillColor='lightyellow',$aBorderColor='black') { $this->color = $aTxtColor; $this->fillcolor = $aFillColor; $this->bordercolor = $aBorderColor; } function SetFillColor($aFillColor) { $this->fillcolor = $aFillColor; } function SetTabAlign($aAlign) { $this->align = $aAlign; } function SetWidth($aWidth) { $this->width = $aWidth ; } function Set($t) { $this->t = $t; $this->hide = false; } function SetCorner($aD) { $this->corner = $aD ; } function Stroke($aImg,$aDummy1=null,$aDummy2=null) { if( $this->hide ) return; $this->boxed = false; $w = $this->GetWidth($aImg) + 2*$this->posx; $h = $this->GetTextHeight($aImg) + 2*$this->posy; $x = $aImg->left_margin; $y = $aImg->top_margin; if( $this->width === TABTITLE_WIDTHFIT ) { if( $this->align == 'left' ) { $p = array($x, $y, $x, $y-$h+$this->corner, $x + $this->corner,$y-$h, $x + $w - $this->corner, $y-$h, $x + $w, $y-$h+$this->corner, $x + $w, $y); } elseif( $this->align == 'center' ) { $x += round($aImg->plotwidth/2) - round($w/2); $p = array($x, $y, $x, $y-$h+$this->corner, $x + $this->corner, $y-$h, $x + $w - $this->corner, $y-$h, $x + $w, $y-$h+$this->corner, $x + $w, $y); } else { $x += $aImg->plotwidth -$w; $p = array($x, $y, $x, $y-$h+$this->corner, $x + $this->corner,$y-$h, $x + $w - $this->corner, $y-$h, $x + $w, $y-$h+$this->corner, $x + $w, $y); } } else { if( $this->width === TABTITLE_WIDTHFULL ) { $w = $aImg->plotwidth ; } else { $w = $this->width ; } // Make the tab fit the width of the plot area $p = array($x, $y, $x, $y-$h+$this->corner, $x + $this->corner,$y-$h, $x + $w - $this->corner, $y-$h, $x + $w, $y-$h+$this->corner, $x + $w, $y); } if( $this->halign == 'left' ) { $aImg->SetTextAlign('left','bottom'); $x += $this->posx; $y -= $this->posy; } elseif( $this->halign == 'center' ) { $aImg->SetTextAlign('center','bottom'); $x += $w/2; $y -= $this->posy; } else { $aImg->SetTextAlign('right','bottom'); $x += $w - $this->posx; $y -= $this->posy; } $aImg->SetColor($this->fillcolor); $aImg->FilledPolygon($p); $aImg->SetColor($this->bordercolor); $aImg->Polygon($p,true); $aImg->SetColor($this->color); $aImg->SetFont($this->font_family,$this->font_style,$this->font_size); $aImg->StrokeText($x,$y,$this->t,0,'center'); } } //=================================================== // CLASS SuperScriptText // Description: Format a superscript text //=================================================== class SuperScriptText extends Text { private $iSuper=''; private $sfont_family='',$sfont_style='',$sfont_size=8; private $iSuperMargin=2,$iVertOverlap=4,$iSuperScale=0.65; private $iSDir=0; private $iSimple=false; function __construct($aTxt='',$aSuper='',$aXAbsPos=0,$aYAbsPos=0) { parent::__construct($aTxt,$aXAbsPos,$aYAbsPos); $this->iSuper = $aSuper; } function FromReal($aVal,$aPrecision=2) { // Convert a floating point number to scientific notation $neg=1.0; if( $aVal < 0 ) { $neg = -1.0; $aVal = -$aVal; } $l = floor(log10($aVal)); $a = sprintf("%0.".$aPrecision."f",round($aVal / pow(10,$l),$aPrecision)); $a *= $neg; if( $this->iSimple && ($a == 1 || $a==-1) ) $a = ''; if( $a != '' ) { $this->t = $a.' * 10'; } else { if( $neg == 1 ) { $this->t = '10'; } else { $this->t = '-10'; } } $this->iSuper = $l; } function Set($aTxt,$aSuper='') { $this->t = $aTxt; $this->iSuper = $aSuper; } function SetSuperFont($aFontFam,$aFontStyle=FS_NORMAL,$aFontSize=8) { $this->sfont_family = $aFontFam; $this->sfont_style = $aFontStyle; $this->sfont_size = $aFontSize; } // Total width of text function GetWidth($aImg) { $aImg->SetFont($this->font_family,$this->font_style,$this->font_size); $w = $aImg->GetTextWidth($this->t); $aImg->SetFont($this->sfont_family,$this->sfont_style,$this->sfont_size); $w += $aImg->GetTextWidth($this->iSuper); $w += $this->iSuperMargin; return $w; } // Hight of font (approximate the height of the text) function GetFontHeight($aImg) { $aImg->SetFont($this->font_family,$this->font_style,$this->font_size); $h = $aImg->GetFontHeight(); $aImg->SetFont($this->sfont_family,$this->sfont_style,$this->sfont_size); $h += $aImg->GetFontHeight(); return $h; } // Hight of text function GetTextHeight($aImg) { $aImg->SetFont($this->font_family,$this->font_style,$this->font_size); $h = $aImg->GetTextHeight($this->t); $aImg->SetFont($this->sfont_family,$this->sfont_style,$this->sfont_size); $h += $aImg->GetTextHeight($this->iSuper); return $h; } function Stroke($aImg,$ax=-1,$ay=-1) { // To position the super script correctly we need different // cases to handle the alignmewnt specified since that will // determine how we can interpret the x,y coordinates $w = parent::GetWidth($aImg); $h = parent::GetTextHeight($aImg); switch( $this->valign ) { case 'top': $sy = $this->y; break; case 'center': $sy = $this->y - $h/2; break; case 'bottom': $sy = $this->y - $h; break; default: JpGraphError::RaiseL(25052);//('PANIC: Internal error in SuperScript::Stroke(). Unknown vertical alignment for text'); break; } switch( $this->halign ) { case 'left': $sx = $this->x + $w; break; case 'center': $sx = $this->x + $w/2; break; case 'right': $sx = $this->x; break; default: JpGraphError::RaiseL(25053);//('PANIC: Internal error in SuperScript::Stroke(). Unknown horizontal alignment for text'); break; } $sx += $this->iSuperMargin; $sy += $this->iVertOverlap; // Should we automatically determine the font or // has the user specified it explicetly? if( $this->sfont_family == '' ) { if( $this->font_family <= FF_FONT2 ) { if( $this->font_family == FF_FONT0 ) { $sff = FF_FONT0; } elseif( $this->font_family == FF_FONT1 ) { if( $this->font_style == FS_NORMAL ) { $sff = FF_FONT0; } else { $sff = FF_FONT1; } } else { $sff = FF_FONT1; } $sfs = $this->font_style; $sfz = $this->font_size; } else { // TTF fonts $sff = $this->font_family; $sfs = $this->font_style; $sfz = floor($this->font_size*$this->iSuperScale); if( $sfz < 8 ) $sfz = 8; } $this->sfont_family = $sff; $this->sfont_style = $sfs; $this->sfont_size = $sfz; } else { $sff = $this->sfont_family; $sfs = $this->sfont_style; $sfz = $this->sfont_size; } parent::Stroke($aImg,$ax,$ay); // For the builtin fonts we need to reduce the margins // since the bounding bx reported for the builtin fonts // are much larger than for the TTF fonts. if( $sff <= FF_FONT2 ) { $sx -= 2; $sy += 3; } $aImg->SetTextAlign('left','bottom'); $aImg->SetFont($sff,$sfs,$sfz); $aImg->PushColor($this->color); $aImg->StrokeText($sx,$sy,$this->iSuper,$this->iSDir,'left'); $aImg->PopColor(); } } //=================================================== // CLASS Grid // Description: responsible for drawing grid lines in graph //=================================================== class Grid { protected $img; protected $scale; protected $majorcolor='#CCCCCC',$minorcolor='#DDDDDD'; protected $majortype='solid',$minortype='solid'; protected $show=false, $showMinor=false,$majorweight=1,$minorweight=1; protected $fill=false,$fillcolor=array('#EFEFEF','#BBCCFF'); function __construct($aAxis) { $this->scale = $aAxis->scale; $this->img = $aAxis->img; } function SetColor($aMajColor,$aMinColor=false) { $this->majorcolor=$aMajColor; if( $aMinColor === false ) { $aMinColor = $aMajColor ; } $this->minorcolor = $aMinColor; } function SetWeight($aMajorWeight,$aMinorWeight=1) { $this->majorweight=$aMajorWeight; $this->minorweight=$aMinorWeight; } // Specify if grid should be dashed, dotted or solid function SetLineStyle($aMajorType,$aMinorType='solid') { $this->majortype = $aMajorType; $this->minortype = $aMinorType; } function SetStyle($aMajorType,$aMinorType='solid') { $this->SetLineStyle($aMajorType,$aMinorType); } // Decide if both major and minor grid should be displayed function Show($aShowMajor=true,$aShowMinor=false) { $this->show=$aShowMajor; $this->showMinor=$aShowMinor; } function SetFill($aFlg=true,$aColor1='lightgray',$aColor2='lightblue') { $this->fill = $aFlg; $this->fillcolor = array( $aColor1, $aColor2 ); } // Display the grid function Stroke() { if( $this->showMinor && !$this->scale->textscale ) { $this->DoStroke($this->scale->ticks->ticks_pos,$this->minortype,$this->minorcolor,$this->minorweight); $this->DoStroke($this->scale->ticks->maj_ticks_pos,$this->majortype,$this->majorcolor,$this->majorweight); } else { $this->DoStroke($this->scale->ticks->maj_ticks_pos,$this->majortype,$this->majorcolor,$this->majorweight); } } //-------------- // Private methods // Draw the grid function DoStroke($aTicksPos,$aType,$aColor,$aWeight) { if( !$this->show ) return; $nbrgrids = count($aTicksPos); if( $this->scale->type == 'y' ) { $xl=$this->img->left_margin; $xr=$this->img->width-$this->img->right_margin; if( $this->fill ) { // Draw filled areas $y2 = $aTicksPos[0]; $i=1; while( $i < $nbrgrids ) { $y1 = $y2; $y2 = $aTicksPos[$i++]; $this->img->SetColor($this->fillcolor[$i & 1]); $this->img->FilledRectangle($xl,$y1,$xr,$y2); } } $this->img->SetColor($aColor); $this->img->SetLineWeight($aWeight); // Draw grid lines switch( $aType ) { case 'solid': $style = LINESTYLE_SOLID; break; case 'dotted': $style = LINESTYLE_DOTTED; break; case 'dashed': $style = LINESTYLE_DASHED; break; case 'longdashed': $style = LINESTYLE_LONGDASH; break; default: $style = LINESTYLE_SOLID; break; } for($i=0; $i < $nbrgrids; ++$i) { $y=$aTicksPos[$i]; $this->img->StyleLine($xl,$y,$xr,$y,$style,true); } } elseif( $this->scale->type == 'x' ) { $yu=$this->img->top_margin; $yl=$this->img->height-$this->img->bottom_margin; $limit=$this->img->width-$this->img->right_margin; if( $this->fill ) { // Draw filled areas $x2 = $aTicksPos[0]; $i=1; while( $i < $nbrgrids ) { $x1 = $x2; $x2 = min($aTicksPos[$i++],$limit) ; $this->img->SetColor($this->fillcolor[$i & 1]); $this->img->FilledRectangle($x1,$yu,$x2,$yl); } } $this->img->SetColor($aColor); $this->img->SetLineWeight($aWeight); // We must also test for limit since we might have // an offset and the number of ticks is calculated with // assumption offset==0 so we might end up drawing one // to many gridlines $i=0; $x=$aTicksPos[$i]; while( $i<count($aTicksPos) && ($x=$aTicksPos[$i]) <= $limit ) { if ( $aType == 'solid' ) $this->img->Line($x,$yl,$x,$yu); elseif( $aType == 'dotted' ) $this->img->DashedLineForGrid($x,$yl,$x,$yu,1,6); elseif( $aType == 'dashed' ) $this->img->DashedLineForGrid($x,$yl,$x,$yu,2,4); elseif( $aType == 'longdashed' ) $this->img->DashedLineForGrid($x,$yl,$x,$yu,8,6); ++$i; } } else { JpGraphError::RaiseL(25054,$this->scale->type);//('Internal error: Unknown grid axis ['.$this->scale->type.']'); } return true; } } // Class //=================================================== // CLASS Axis // Description: Defines X and Y axis. Notes that at the // moment the code is not really good since the axis on // several occasion must know wheter it's an X or Y axis. // This was a design decision to make the code easier to // follow. //=================================================== class AxisPrototype { public $scale=null; public $img=null; public $hide=false,$hide_labels=false; public $title=null; public $font_family=FF_DEFAULT,$font_style=FS_NORMAL,$font_size=8,$label_angle=0; public $tick_step=1; public $pos = false; public $ticks_label = array(); protected $weight=1; protected $color=array(0,0,0),$label_color=array(0,0,0); protected $ticks_label_colors=null; protected $show_first_label=true,$show_last_label=true; protected $label_step=1; // Used by a text axis to specify what multiple of major steps // should be labeled. protected $labelPos=0; // Which side of the axis should the labels be? protected $title_adjust,$title_margin,$title_side=SIDE_LEFT; protected $tick_label_margin=5; protected $label_halign = '',$label_valign = '', $label_para_align='left'; protected $hide_line=false; protected $iDeltaAbsPos=0; function __construct($img,$aScale,$color = array(0,0,0)) { $this->img = $img; $this->scale = $aScale; $this->color = $color; $this->title=new Text(''); if( $aScale->type == 'y' ) { $this->title_margin = 25; $this->title_adjust = 'middle'; $this->title->SetOrientation(90); $this->tick_label_margin=7; $this->labelPos=SIDE_LEFT; } else { $this->title_margin = 5; $this->title_adjust = 'high'; $this->title->SetOrientation(0); $this->tick_label_margin=5; $this->labelPos=SIDE_DOWN; $this->title_side=SIDE_DOWN; } } function SetLabelFormat($aFormStr) { $this->scale->ticks->SetLabelFormat($aFormStr); } function SetLabelFormatString($aFormStr,$aDate=false) { $this->scale->ticks->SetLabelFormat($aFormStr,$aDate); } function SetLabelFormatCallback($aFuncName) { $this->scale->ticks->SetFormatCallback($aFuncName); } function SetLabelAlign($aHAlign,$aVAlign='top',$aParagraphAlign='left') { $this->label_halign = $aHAlign; $this->label_valign = $aVAlign; $this->label_para_align = $aParagraphAlign; } // Don't display the first label function HideFirstTickLabel($aShow=false) { $this->show_first_label=$aShow; } function HideLastTickLabel($aShow=false) { $this->show_last_label=$aShow; } // Manually specify the major and (optional) minor tick position and labels function SetTickPositions($aMajPos,$aMinPos=NULL,$aLabels=NULL) { $this->scale->ticks->SetTickPositions($aMajPos,$aMinPos,$aLabels); } // Manually specify major tick positions and optional labels function SetMajTickPositions($aMajPos,$aLabels=NULL) { $this->scale->ticks->SetTickPositions($aMajPos,NULL,$aLabels); } // Hide minor or major tick marks function HideTicks($aHideMinor=true,$aHideMajor=true) { $this->scale->ticks->SupressMinorTickMarks($aHideMinor); $this->scale->ticks->SupressTickMarks($aHideMajor); } // Hide zero label function HideZeroLabel($aFlag=true) { $this->scale->ticks->SupressZeroLabel(); } function HideFirstLastLabel() { // The two first calls to ticks method will supress // automatically generated scale values. However, that // will not affect manually specified value, e.g text-scales. // therefor we also make a kludge here to supress manually // specified scale labels. $this->scale->ticks->SupressLast(); $this->scale->ticks->SupressFirst(); $this->show_first_label = false; $this->show_last_label = false; } // Hide the axis function Hide($aHide=true) { $this->hide=$aHide; } // Hide the actual axis-line, but still print the labels function HideLine($aHide=true) { $this->hide_line = $aHide; } function HideLabels($aHide=true) { $this->hide_labels = $aHide; } // Weight of axis function SetWeight($aWeight) { $this->weight = $aWeight; } // Axis color function SetColor($aColor,$aLabelColor=false) { $this->color = $aColor; if( !$aLabelColor ) $this->label_color = $aColor; else $this->label_color = $aLabelColor; } // Title on axis function SetTitle($aTitle,$aAdjustAlign='high') { $this->title->Set($aTitle); $this->title_adjust=$aAdjustAlign; } // Specify distance from the axis function SetTitleMargin($aMargin) { $this->title_margin=$aMargin; } // Which side of the axis should the axis title be? function SetTitleSide($aSideOfAxis) { $this->title_side = $aSideOfAxis; } function SetTickSide($aDir) { $this->scale->ticks->SetSide($aDir); } function SetTickSize($aMajSize,$aMinSize=3) { $this->scale->ticks->SetSize($aMajSize,$aMinSize=3); } // Specify text labels for the ticks. One label for each data point function SetTickLabels($aLabelArray,$aLabelColorArray=null) { $this->ticks_label = $aLabelArray; $this->ticks_label_colors = $aLabelColorArray; } function SetLabelMargin($aMargin) { $this->tick_label_margin=$aMargin; } // Specify that every $step of the ticks should be displayed starting // at $start function SetTextTickInterval($aStep,$aStart=0) { $this->scale->ticks->SetTextLabelStart($aStart); $this->tick_step=$aStep; } // Specify that every $step tick mark should have a label // should be displayed starting function SetTextLabelInterval($aStep) { if( $aStep < 1 ) { JpGraphError::RaiseL(25058);//(" Text label interval must be specified >= 1."); } $this->label_step=$aStep; } function SetLabelSide($aSidePos) { $this->labelPos=$aSidePos; } // Set the font function SetFont($aFamily,$aStyle=FS_NORMAL,$aSize=10) { $this->font_family = $aFamily; $this->font_style = $aStyle; $this->font_size = $aSize; } // Position for axis line on the "other" scale function SetPos($aPosOnOtherScale) { $this->pos=$aPosOnOtherScale; } // Set the position of the axis to be X-pixels delta to the right // of the max X-position (used to position the multiple Y-axis) function SetPosAbsDelta($aDelta) { $this->iDeltaAbsPos=$aDelta; } // Specify the angle for the tick labels function SetLabelAngle($aAngle) { $this->label_angle = $aAngle; } } // Class //=================================================== // CLASS Axis // Description: Defines X and Y axis. Notes that at the // moment the code is not really good since the axis on // several occasion must know wheter it's an X or Y axis. // This was a design decision to make the code easier to // follow. //=================================================== class Axis extends AxisPrototype { function __construct($img,$aScale,$color='black') { parent::__construct($img,$aScale,$color); } // Stroke the axis. function Stroke($aOtherAxisScale,$aStrokeLabels=true) { if( $this->hide ) return; if( is_numeric($this->pos) ) { $pos=$aOtherAxisScale->Translate($this->pos); } else { // Default to minimum of other scale if pos not set if( ($aOtherAxisScale->GetMinVal() >= 0 && $this->pos==false) || $this->pos == 'min' ) { $pos = $aOtherAxisScale->scale_abs[0]; } elseif($this->pos == "max") { $pos = $aOtherAxisScale->scale_abs[1]; } else { // If negative set x-axis at 0 $this->pos=0; $pos=$aOtherAxisScale->Translate(0); } } $pos += $this->iDeltaAbsPos; $this->img->SetLineWeight($this->weight); $this->img->SetColor($this->color); $this->img->SetFont($this->font_family,$this->font_style,$this->font_size); if( $this->scale->type == "x" ) { if( !$this->hide_line ) { // Stroke X-axis $this->img->FilledRectangle( $this->img->left_margin, $pos, $this->img->width - $this->img->right_margin, $pos + $this->weight-1 ); } if( $this->title_side == SIDE_DOWN ) { $y = $pos + $this->img->GetFontHeight() + $this->title_margin + $this->title->margin; $yalign = 'top'; } else { $y = $pos - $this->img->GetFontHeight() - $this->title_margin - $this->title->margin; $yalign = 'bottom'; } if( $this->title_adjust=='high' ) { $this->title->SetPos($this->img->width-$this->img->right_margin,$y,'right',$yalign); } elseif( $this->title_adjust=='middle' || $this->title_adjust=='center' ) { $this->title->SetPos(($this->img->width-$this->img->left_margin-$this->img->right_margin)/2+$this->img->left_margin,$y,'center',$yalign); } elseif($this->title_adjust=='low') { $this->title->SetPos($this->img->left_margin,$y,'left',$yalign); } else { JpGraphError::RaiseL(25060,$this->title_adjust);//('Unknown alignment specified for X-axis title. ('.$this->title_adjust.')'); } } elseif( $this->scale->type == "y" ) { // Add line weight to the height of the axis since // the x-axis could have a width>1 and we want the axis to fit nicely together. if( !$this->hide_line ) { // Stroke Y-axis $this->img->FilledRectangle( $pos - $this->weight + 1, $this->img->top_margin, $pos, $this->img->height - $this->img->bottom_margin + $this->weight - 1 ); } $x=$pos ; if( $this->title_side == SIDE_LEFT ) { $x -= $this->title_margin; $x -= $this->title->margin; $halign = 'right'; } else { $x += $this->title_margin; $x += $this->title->margin; $halign = 'left'; } // If the user has manually specified an hor. align // then we override the automatic settings with this // specifed setting. Since default is 'left' we compare // with that. (This means a manually set 'left' align // will have no effect.) if( $this->title->halign != 'left' ) { $halign = $this->title->halign; } if( $this->title_adjust == 'high' ) { $this->title->SetPos($x,$this->img->top_margin,$halign,'top'); } elseif($this->title_adjust=='middle' || $this->title_adjust=='center') { $this->title->SetPos($x,($this->img->height-$this->img->top_margin-$this->img->bottom_margin)/2+$this->img->top_margin,$halign,"center"); } elseif($this->title_adjust=='low') { $this->title->SetPos($x,$this->img->height-$this->img->bottom_margin,$halign,'bottom'); } else { JpGraphError::RaiseL(25061,$this->title_adjust);//('Unknown alignment specified for Y-axis title. ('.$this->title_adjust.')'); } } $this->scale->ticks->Stroke($this->img,$this->scale,$pos); if( $aStrokeLabels ) { if( !$this->hide_labels ) { $this->StrokeLabels($pos); } $this->title->Stroke($this->img); } } //--------------- // PRIVATE METHODS // Draw all the tick labels on major tick marks function StrokeLabels($aPos,$aMinor=false,$aAbsLabel=false) { if( is_array($this->label_color) && count($this->label_color) > 3 ) { $this->ticks_label_colors = $this->label_color; $this->img->SetColor($this->label_color[0]); } else { $this->img->SetColor($this->label_color); } $this->img->SetFont($this->font_family,$this->font_style,$this->font_size); $yoff=$this->img->GetFontHeight()/2; // Only draw labels at major tick marks $nbr = count($this->scale->ticks->maj_ticks_label); // We have the option to not-display the very first mark // (Usefull when the first label might interfere with another // axis.) $i = $this->show_first_label ? 0 : 1 ; if( !$this->show_last_label ) { --$nbr; } // Now run through all labels making sure we don't overshoot the end // of the scale. $ncolor=0; if( isset($this->ticks_label_colors) ) { $ncolor=count($this->ticks_label_colors); } while( $i < $nbr ) { // $tpos holds the absolute text position for the label $tpos=$this->scale->ticks->maj_ticklabels_pos[$i]; // Note. the $limit is only used for the x axis since we // might otherwise overshoot if the scale has been centered // This is due to us "loosing" the last tick mark if we center. if( $this->scale->type == 'x' && $tpos > $this->img->width-$this->img->right_margin+1 ) { return; } // we only draw every $label_step label if( ($i % $this->label_step)==0 ) { // Set specific label color if specified if( $ncolor > 0 ) { $this->img->SetColor($this->ticks_label_colors[$i % $ncolor]); } // If the label has been specified use that and in other case // just label the mark with the actual scale value $m=$this->scale->ticks->GetMajor(); // ticks_label has an entry for each data point and is the array // that holds the labels set by the user. If the user hasn't // specified any values we use whats in the automatically asigned // labels in the maj_ticks_label if( isset($this->ticks_label[$i*$m]) ) { $label=$this->ticks_label[$i*$m]; } else { if( $aAbsLabel ) { $label=abs($this->scale->ticks->maj_ticks_label[$i]); } else { $label=$this->scale->ticks->maj_ticks_label[$i]; } // We number the scale from 1 and not from 0 so increase by one if( $this->scale->textscale && $this->scale->ticks->label_formfunc == '' && ! $this->scale->ticks->HaveManualLabels() ) { ++$label; } } if( $this->scale->type == "x" ) { if( $this->labelPos == SIDE_DOWN ) { if( $this->label_angle==0 || $this->label_angle==90 ) { if( $this->label_halign=='' && $this->label_valign=='') { $this->img->SetTextAlign('center','top'); } else { $this->img->SetTextAlign($this->label_halign,$this->label_valign); } } else { if( $this->label_halign=='' && $this->label_valign=='') { $this->img->SetTextAlign("right","top"); } else { $this->img->SetTextAlign($this->label_halign,$this->label_valign); } } $this->img->StrokeText($tpos,$aPos+$this->tick_label_margin,$label, $this->label_angle,$this->label_para_align); } else { if( $this->label_angle==0 || $this->label_angle==90 ) { if( $this->label_halign=='' && $this->label_valign=='') { $this->img->SetTextAlign("center","bottom"); } else { $this->img->SetTextAlign($this->label_halign,$this->label_valign); } } else { if( $this->label_halign=='' && $this->label_valign=='') { $this->img->SetTextAlign("right","bottom"); } else { $this->img->SetTextAlign($this->label_halign,$this->label_valign); } } $this->img->StrokeText($tpos,$aPos-$this->tick_label_margin-1,$label, $this->label_angle,$this->label_para_align); } } else { // scale->type == "y" //if( $this->label_angle!=0 ) //JpGraphError::Raise(" Labels at an angle are not supported on Y-axis"); if( $this->labelPos == SIDE_LEFT ) { // To the left of y-axis if( $this->label_halign=='' && $this->label_valign=='') { $this->img->SetTextAlign("right","center"); } else { $this->img->SetTextAlign($this->label_halign,$this->label_valign); } $this->img->StrokeText($aPos-$this->tick_label_margin,$tpos,$label,$this->label_angle,$this->label_para_align); } else { // To the right of the y-axis if( $this->label_halign=='' && $this->label_valign=='') { $this->img->SetTextAlign("left","center"); } else { $this->img->SetTextAlign($this->label_halign,$this->label_valign); } $this->img->StrokeText($aPos+$this->tick_label_margin,$tpos,$label,$this->label_angle,$this->label_para_align); } } } ++$i; } } } //=================================================== // CLASS Ticks // Description: Abstract base class for drawing linear and logarithmic // tick marks on axis //=================================================== class Ticks { public $label_formatstr=''; // C-style format string to use for labels public $label_formfunc=''; public $label_dateformatstr=''; public $direction=1; // Should ticks be in(=1) the plot area or outside (=-1) public $supress_last=false,$supress_tickmarks=false,$supress_minor_tickmarks=false; public $maj_ticks_pos = array(), $maj_ticklabels_pos = array(), $ticks_pos = array(), $maj_ticks_label = array(); public $precision; protected $minor_abs_size=3, $major_abs_size=5; protected $scale; protected $is_set=false; protected $supress_zerolabel=false,$supress_first=false; protected $mincolor='',$majcolor=''; protected $weight=1; protected $label_usedateformat=FALSE; function __construct($aScale) { $this->scale=$aScale; $this->precision = -1; } // Set format string for automatic labels function SetLabelFormat($aFormatString,$aDate=FALSE) { $this->label_formatstr=$aFormatString; $this->label_usedateformat=$aDate; } function SetLabelDateFormat($aFormatString) { $this->label_dateformatstr=$aFormatString; } function SetFormatCallback($aCallbackFuncName) { $this->label_formfunc = $aCallbackFuncName; } // Don't display the first zero label function SupressZeroLabel($aFlag=true) { $this->supress_zerolabel=$aFlag; } // Don't display minor tick marks function SupressMinorTickMarks($aHide=true) { $this->supress_minor_tickmarks=$aHide; } // Don't display major tick marks function SupressTickMarks($aHide=true) { $this->supress_tickmarks=$aHide; } // Hide the first tick mark function SupressFirst($aHide=true) { $this->supress_first=$aHide; } // Hide the last tick mark function SupressLast($aHide=true) { $this->supress_last=$aHide; } // Size (in pixels) of minor tick marks function GetMinTickAbsSize() { return $this->minor_abs_size; } // Size (in pixels) of major tick marks function GetMajTickAbsSize() { return $this->major_abs_size; } function SetSize($aMajSize,$aMinSize=3) { $this->major_abs_size = $aMajSize; $this->minor_abs_size = $aMinSize; } // Have the ticks been specified function IsSpecified() { return $this->is_set; } function SetSide($aSide) { $this->direction=$aSide; } // Which side of the axis should the ticks be on function SetDirection($aSide=SIDE_RIGHT) { $this->direction=$aSide; } // Set colors for major and minor tick marks function SetMarkColor($aMajorColor,$aMinorColor='') { $this->SetColor($aMajorColor,$aMinorColor); } function SetColor($aMajorColor,$aMinorColor='') { $this->majcolor=$aMajorColor; // If not specified use same as major if( $aMinorColor == '' ) { $this->mincolor=$aMajorColor; } else { $this->mincolor=$aMinorColor; } } function SetWeight($aWeight) { $this->weight=$aWeight; } } // Class //=================================================== // CLASS LinearTicks // Description: Draw linear ticks on axis //=================================================== class LinearTicks extends Ticks { public $minor_step=1, $major_step=2; public $xlabel_offset=0,$xtick_offset=0; private $label_offset=0; // What offset should the displayed label have // i.e should we display 0,1,2 or 1,2,3,4 or 2,3,4 etc private $text_label_start=0; private $iManualTickPos = NULL, $iManualMinTickPos = NULL, $iManualTickLabels = NULL; private $iAdjustForDST = false; // If a date falls within the DST period add one hour to the diaplyed time function __construct() { $this->precision = -1; } // Return major step size in world coordinates function GetMajor() { return $this->major_step; } // Return minor step size in world coordinates function GetMinor() { return $this->minor_step; } // Set Minor and Major ticks (in world coordinates) function Set($aMajStep,$aMinStep=false) { if( $aMinStep==false ) { $aMinStep=$aMajStep; } if( $aMajStep <= 0 || $aMinStep <= 0 ) { JpGraphError::RaiseL(25064); //(" Minor or major step size is 0. Check that you haven't got an accidental SetTextTicks(0) in your code. If this is not the case you might have stumbled upon a bug in JpGraph. Please report this and if possible include the data that caused the problem."); } $this->major_step=$aMajStep; $this->minor_step=$aMinStep; $this->is_set = true; } function SetMajTickPositions($aMajPos,$aLabels=NULL) { $this->SetTickPositions($aMajPos,NULL,$aLabels); } function SetTickPositions($aMajPos,$aMinPos=NULL,$aLabels=NULL) { if( !is_array($aMajPos) || ($aMinPos!==NULL && !is_array($aMinPos)) ) { JpGraphError::RaiseL(25065);//('Tick positions must be specifued as an array()'); return; } $n=count($aMajPos); if( is_array($aLabels) && (count($aLabels) != $n) ) { JpGraphError::RaiseL(25066);//('When manually specifying tick positions and labels the number of labels must be the same as the number of specified ticks.'); } $this->iManualTickPos = $aMajPos; $this->iManualMinTickPos = $aMinPos; $this->iManualTickLabels = $aLabels; } function HaveManualLabels() { return count($this->iManualTickLabels) > 0; } // Specify all the tick positions manually and possible also the exact labels function _doManualTickPos($aScale) { $n=count($this->iManualTickPos); $m=count($this->iManualMinTickPos); $doLbl=count($this->iManualTickLabels) > 0; $this->maj_ticks_pos = array(); $this->maj_ticklabels_pos = array(); $this->ticks_pos = array(); // Now loop through the supplied positions and translate them to screen coordinates // and store them in the maj_label_positions $minScale = $aScale->scale[0]; $maxScale = $aScale->scale[1]; $j=0; for($i=0; $i < $n ; ++$i ) { // First make sure that the first tick is not lower than the lower scale value if( !isset($this->iManualTickPos[$i]) || $this->iManualTickPos[$i] < $minScale || $this->iManualTickPos[$i] > $maxScale) { continue; } $this->maj_ticks_pos[$j] = $aScale->Translate($this->iManualTickPos[$i]); $this->maj_ticklabels_pos[$j] = $this->maj_ticks_pos[$j]; // Set the minor tick marks the same as major if not specified if( $m <= 0 ) { $this->ticks_pos[$j] = $this->maj_ticks_pos[$j]; } if( $doLbl ) { $this->maj_ticks_label[$j] = $this->iManualTickLabels[$i]; } else { $this->maj_ticks_label[$j]=$this->_doLabelFormat($this->iManualTickPos[$i],$i,$n); } ++$j; } // Some sanity check if( count($this->maj_ticks_pos) < 2 ) { JpGraphError::RaiseL(25067);//('Your manually specified scale and ticks is not correct. The scale seems to be too small to hold any of the specified tickl marks.'); } // Setup the minor tick marks $j=0; for($i=0; $i < $m; ++$i ) { if( empty($this->iManualMinTickPos[$i]) || $this->iManualMinTickPos[$i] < $minScale || $this->iManualMinTickPos[$i] > $maxScale) { continue; } $this->ticks_pos[$j] = $aScale->Translate($this->iManualMinTickPos[$i]); ++$j; } } function _doAutoTickPos($aScale) { $maj_step_abs = $aScale->scale_factor*$this->major_step; $min_step_abs = $aScale->scale_factor*$this->minor_step; if( $min_step_abs==0 || $maj_step_abs==0 ) { JpGraphError::RaiseL(25068);//("A plot has an illegal scale. This could for example be that you are trying to use text autoscaling to draw a line plot with only one point or that the plot area is too small. It could also be that no input data value is numeric (perhaps only '-' or 'x')"); } // We need to make this an int since comparing it below // with the result from round() can give wrong result, such that // (40 < 40) == TRUE !!! $limit = (int)$aScale->scale_abs[1]; if( $aScale->textscale ) { // This can only be true for a X-scale (horizontal) // Define ticks for a text scale. This is slightly different from a // normal linear type of scale since the position might be adjusted // and the labels start at on $label = (float)$aScale->GetMinVal()+$this->text_label_start+$this->label_offset; $start_abs=$aScale->scale_factor*$this->text_label_start; $nbrmajticks=round(($aScale->GetMaxVal()-$aScale->GetMinVal()-$this->text_label_start )/$this->major_step)+1; $x = $aScale->scale_abs[0]+$start_abs+$this->xlabel_offset*$min_step_abs; for( $i=0; $label <= $aScale->GetMaxVal()+$this->label_offset; ++$i ) { // Apply format to label $this->maj_ticks_label[$i]=$this->_doLabelFormat($label,$i,$nbrmajticks); $label+=$this->major_step; // The x-position of the tick marks can be different from the labels. // Note that we record the tick position (not the label) so that the grid // happen upon tick marks and not labels. $xtick=$aScale->scale_abs[0]+$start_abs+$this->xtick_offset*$min_step_abs+$i*$maj_step_abs; $this->maj_ticks_pos[$i]=$xtick; $this->maj_ticklabels_pos[$i] = round($x); $x += $maj_step_abs; } } else { $label = $aScale->GetMinVal(); $abs_pos = $aScale->scale_abs[0]; $j=0; $i=0; $step = round($maj_step_abs/$min_step_abs); if( $aScale->type == "x" ) { // For a normal linear type of scale the major ticks will always be multiples // of the minor ticks. In order to avoid any rounding issues the major ticks are // defined as every "step" minor ticks and not calculated separately $nbrmajticks=round(($aScale->GetMaxVal()-$aScale->GetMinVal()-$this->text_label_start )/$this->major_step)+1; while( round($abs_pos) <= $limit ) { $this->ticks_pos[] = round($abs_pos); $this->ticks_label[] = $label; if( $step== 0 || $i % $step == 0 && $j < $nbrmajticks ) { $this->maj_ticks_pos[$j] = round($abs_pos); $this->maj_ticklabels_pos[$j] = round($abs_pos); $this->maj_ticks_label[$j]=$this->_doLabelFormat($label,$j,$nbrmajticks); ++$j; } ++$i; $abs_pos += $min_step_abs; $label+=$this->minor_step; } } elseif( $aScale->type == "y" ) { //@todo s=2:20,12 s=1:50,6 $this->major_step:$nbr // abs_point,limit s=1:270,80 s=2:540,160 // $this->major_step = 50; $nbrmajticks=round(($aScale->GetMaxVal()-$aScale->GetMinVal())/$this->major_step)+1; // $step = 5; while( round($abs_pos) >= $limit ) { $this->ticks_pos[$i] = round($abs_pos); $this->ticks_label[$i]=$label; if( $step== 0 || $i % $step == 0 && $j < $nbrmajticks) { $this->maj_ticks_pos[$j] = round($abs_pos); $this->maj_ticklabels_pos[$j] = round($abs_pos); $this->maj_ticks_label[$j]=$this->_doLabelFormat($label,$j,$nbrmajticks); ++$j; } ++$i; $abs_pos += $min_step_abs; $label += $this->minor_step; } } } } function AdjustForDST($aFlg=true) { $this->iAdjustForDST = $aFlg; } function _doLabelFormat($aVal,$aIdx,$aNbrTicks) { // If precision hasn't been specified set it to a sensible value if( $this->precision==-1 ) { $t = log10($this->minor_step); if( $t > 0 ) { $precision = 0; } else { $precision = -floor($t); } } else { $precision = $this->precision; } if( $this->label_formfunc != '' ) { $f=$this->label_formfunc; if( $this->label_formatstr == '' ) { $l = call_user_func($f,$aVal); } else { $l = sprintf($this->label_formatstr, call_user_func($f,$aVal)); } } elseif( $this->label_formatstr != '' || $this->label_dateformatstr != '' ) { if( $this->label_usedateformat ) { // Adjust the value to take daylight savings into account if (date("I",$aVal)==1 && $this->iAdjustForDST ) { // DST $aVal+=3600; } $l = date($this->label_formatstr,$aVal); if( $this->label_formatstr == 'W' ) { // If we use week formatting then add a single 'w' in front of the // week number to differentiate it from dates $l = 'w'.$l; } } else { if( $this->label_dateformatstr !== '' ) { // Adjust the value to take daylight savings into account if (date("I",$aVal)==1 && $this->iAdjustForDST ) { // DST $aVal+=3600; } $l = date($this->label_dateformatstr,$aVal); if( $this->label_formatstr == 'W' ) { // If we use week formatting then add a single 'w' in front of the // week number to differentiate it from dates $l = 'w'.$l; } } else { $l = sprintf($this->label_formatstr,$aVal); } } } else { $l = sprintf('%01.'.$precision.'f',round($aVal,$precision)); } if( ($this->supress_zerolabel && $l==0) || ($this->supress_first && $aIdx==0) || ($this->supress_last && $aIdx==$aNbrTicks-1) ) { $l=''; } return $l; } // Stroke ticks on either X or Y axis function _StrokeTicks($aImg,$aScale,$aPos) { $hor = $aScale->type == 'x'; $aImg->SetLineWeight($this->weight); // We need to make this an int since comparing it below // with the result from round() can give wrong result, such that // (40 < 40) == TRUE !!! $limit = (int)$aScale->scale_abs[1]; // A text scale doesn't have any minor ticks if( !$aScale->textscale ) { // Stroke minor ticks $yu = $aPos - $this->direction*$this->GetMinTickAbsSize(); $xr = $aPos + $this->direction*$this->GetMinTickAbsSize(); $n = count($this->ticks_pos); for($i=0; $i < $n; ++$i ) { if( !$this->supress_tickmarks && !$this->supress_minor_tickmarks) { if( $this->mincolor != '') { $aImg->PushColor($this->mincolor); } if( $hor ) { //if( $this->ticks_pos[$i] <= $limit ) $aImg->Line($this->ticks_pos[$i],$aPos,$this->ticks_pos[$i],$yu); } else { //if( $this->ticks_pos[$i] >= $limit ) $aImg->Line($aPos,$this->ticks_pos[$i],$xr,$this->ticks_pos[$i]); } if( $this->mincolor != '' ) { $aImg->PopColor(); } } } } // Stroke major ticks $yu = $aPos - $this->direction*$this->GetMajTickAbsSize(); $xr = $aPos + $this->direction*$this->GetMajTickAbsSize(); $nbrmajticks=round(($aScale->GetMaxVal()-$aScale->GetMinVal()-$this->text_label_start )/$this->major_step)+1; $n = count($this->maj_ticks_pos); for($i=0; $i < $n ; ++$i ) { if(!($this->xtick_offset > 0 && $i==$nbrmajticks-1) && !$this->supress_tickmarks) { if( $this->majcolor != '') { $aImg->PushColor($this->majcolor); } if( $hor ) { //if( $this->maj_ticks_pos[$i] <= $limit ) $aImg->Line($this->maj_ticks_pos[$i],$aPos,$this->maj_ticks_pos[$i],$yu); } else { //if( $this->maj_ticks_pos[$i] >= $limit ) $aImg->Line($aPos,$this->maj_ticks_pos[$i],$xr,$this->maj_ticks_pos[$i]); } if( $this->majcolor != '') { $aImg->PopColor(); } } } } // Draw linear ticks function Stroke($aImg,$aScale,$aPos) { if( $this->iManualTickPos != NULL ) { $this->_doManualTickPos($aScale); } else { $this->_doAutoTickPos($aScale); } $this->_StrokeTicks($aImg,$aScale,$aPos, $aScale->type == 'x' ); } //--------------- // PRIVATE METHODS // Spoecify the offset of the displayed tick mark with the tick "space" // Legal values for $o is [0,1] used to adjust where the tick marks and label // should be positioned within the major tick-size // $lo specifies the label offset and $to specifies the tick offset // this comes in handy for example in bar graphs where we wont no offset for the // tick but have the labels displayed halfway under the bars. function SetXLabelOffset($aLabelOff,$aTickOff=-1) { $this->xlabel_offset=$aLabelOff; if( $aTickOff==-1 ) { // Same as label offset $this->xtick_offset=$aLabelOff; } else { $this->xtick_offset=$aTickOff; } if( $aLabelOff>0 ) { $this->SupressLast(); // The last tick wont fit } } // Which tick label should we start with? function SetTextLabelStart($aTextLabelOff) { $this->text_label_start=$aTextLabelOff; } } // Class //=================================================== // CLASS LinearScale // Description: Handle linear scaling between screen and world //=================================================== class LinearScale { public $textscale=false; // Just a flag to let the Plot class find out if // we are a textscale or not. This is a cludge since // this information is available in Graph::axtype but // we don't have access to the graph object in the Plots // stroke method. So we let graph store the status here // when the linear scale is created. A real cludge... public $type; // is this x or y scale ? public $ticks=null; // Store ticks public $text_scale_off = 0; public $scale_abs=array(0,0); public $scale_factor; // Scale factor between world and screen public $off; // Offset between image edge and plot area public $scale=array(0,0); public $name = 'lin'; public $auto_ticks=false; // When using manual scale should the ticks be automatically set? public $world_abs_size; // Plot area size in pixels (Needed public in jpgraph_radar.php) public $intscale=false; // Restrict autoscale to integers protected $autoscale_min=false; // Forced minimum value, auto determine max protected $autoscale_max=false; // Forced maximum value, auto determine min private $gracetop=0,$gracebottom=0; private $_world_size; // Plot area size in world coordinates function __construct($aMin=0,$aMax=0,$aType='y') { assert($aType=='x' || $aType=='y' ); assert($aMin<=$aMax); $this->type=$aType; $this->scale=array($aMin,$aMax); $this->world_size=$aMax-$aMin; $this->ticks = new LinearTicks(); } // Check if scale is set or if we should autoscale // We should do this is either scale or ticks has not been set function IsSpecified() { if( $this->GetMinVal()==$this->GetMaxVal() ) { // Scale not set return false; } return true; } // Set the minimum data value when the autoscaling is used. // Usefull if you want a fix minimum (like 0) but have an // automatic maximum function SetAutoMin($aMin) { $this->autoscale_min=$aMin; } // Set the minimum data value when the autoscaling is used. // Usefull if you want a fix minimum (like 0) but have an // automatic maximum function SetAutoMax($aMax) { $this->autoscale_max=$aMax; } // If the user manually specifies a scale should the ticks // still be set automatically? function SetAutoTicks($aFlag=true) { $this->auto_ticks = $aFlag; } // Specify scale "grace" value (top and bottom) function SetGrace($aGraceTop,$aGraceBottom=0) { if( $aGraceTop<0 || $aGraceBottom < 0 ) { JpGraphError::RaiseL(25069);//(" Grace must be larger then 0"); } $this->gracetop=$aGraceTop; $this->gracebottom=$aGraceBottom; } // Get the minimum value in the scale function GetMinVal() { return $this->scale[0]; } // get maximum value for scale function GetMaxVal() { return $this->scale[1]; } // Specify a new min/max value for sclae function Update($aImg,$aMin,$aMax) { $this->scale=array($aMin,$aMax); $this->world_size=$aMax-$aMin; $this->InitConstants($aImg); } // Translate between world and screen function Translate($aCoord) { if( !is_numeric($aCoord) ) { if( $aCoord != '' && $aCoord != '-' && $aCoord != 'x' ) { JpGraphError::RaiseL(25070);//('Your data contains non-numeric values.'); } return 0; } else { return round($this->off+($aCoord - $this->scale[0]) * $this->scale_factor); } } // Relative translate (don't include offset) usefull when we just want // to know the relative position (in pixels) on the axis function RelTranslate($aCoord) { if( !is_numeric($aCoord) ) { if( $aCoord != '' && $aCoord != '-' && $aCoord != 'x' ) { JpGraphError::RaiseL(25070);//('Your data contains non-numeric values.'); } return 0; } else { return ($aCoord - $this->scale[0]) * $this->scale_factor; } } // Restrict autoscaling to only use integers function SetIntScale($aIntScale=true) { $this->intscale=$aIntScale; } // Calculate an integer autoscale function IntAutoScale($img,$min,$max,$maxsteps,$majend=true) { // Make sure limits are integers $min=floor($min); $max=ceil($max); if( abs($min-$max)==0 ) { --$min; ++$max; } $maxsteps = floor($maxsteps); $gracetop=round(($this->gracetop/100.0)*abs($max-$min)); $gracebottom=round(($this->gracebottom/100.0)*abs($max-$min)); if( is_numeric($this->autoscale_min) ) { $min = ceil($this->autoscale_min); if( $min >= $max ) { JpGraphError::RaiseL(25071);//('You have specified a min value with SetAutoMin() which is larger than the maximum value used for the scale. This is not possible.'); } } if( is_numeric($this->autoscale_max) ) { $max = ceil($this->autoscale_max); if( $min >= $max ) { JpGraphError::RaiseL(25072);//('You have specified a max value with SetAutoMax() which is smaller than the miminum value used for the scale. This is not possible.'); } } if( abs($min-$max ) == 0 ) { ++$max; --$min; } $min -= $gracebottom; $max += $gracetop; // First get tickmarks as multiples of 1, 10, ... if( $majend ) { list($num1steps,$adj1min,$adj1max,$maj1step) = $this->IntCalcTicks($maxsteps,$min,$max,1); } else { $adj1min = $min; $adj1max = $max; list($num1steps,$maj1step) = $this->IntCalcTicksFreeze($maxsteps,$min,$max,1); } if( abs($min-$max) > 2 ) { // Then get tick marks as 2:s 2, 20, ... if( $majend ) { list($num2steps,$adj2min,$adj2max,$maj2step) = $this->IntCalcTicks($maxsteps,$min,$max,5); } else { $adj2min = $min; $adj2max = $max; list($num2steps,$maj2step) = $this->IntCalcTicksFreeze($maxsteps,$min,$max,5); } } else { $num2steps = 10000; // Dummy high value so we don't choose this } if( abs($min-$max) > 5 ) { // Then get tickmarks as 5:s 5, 50, 500, ... if( $majend ) { list($num5steps,$adj5min,$adj5max,$maj5step) = $this->IntCalcTicks($maxsteps,$min,$max,2); } else { $adj5min = $min; $adj5max = $max; list($num5steps,$maj5step) = $this->IntCalcTicksFreeze($maxsteps,$min,$max,2); } } else { $num5steps = 10000; // Dummy high value so we don't choose this } // Check to see whichof 1:s, 2:s or 5:s fit better with // the requested number of major ticks $match1=abs($num1steps-$maxsteps); $match2=abs($num2steps-$maxsteps); if( !empty($maj5step) && $maj5step > 1 ) { $match5=abs($num5steps-$maxsteps); } else { $match5=10000; // Dummy high value } // Compare these three values and see which is the closest match // We use a 0.6 weight to gravitate towards multiple of 5:s if( $match1 < $match2 ) { if( $match1 < $match5 ) $r=1; else $r=3; } else { if( $match2 < $match5 ) $r=2; else $r=3; } // Minsteps are always the same as maxsteps for integer scale switch( $r ) { case 1: $this->ticks->Set($maj1step,$maj1step); $this->Update($img,$adj1min,$adj1max); break; case 2: $this->ticks->Set($maj2step,$maj2step); $this->Update($img,$adj2min,$adj2max); break; case 3: $this->ticks->Set($maj5step,$maj5step); $this->Update($img,$adj5min,$adj5max); break; default: JpGraphError::RaiseL(25073,$r);//('Internal error. Integer scale algorithm comparison out of bound (r=$r)'); } } // Calculate autoscale. Used if user hasn't given a scale and ticks // $maxsteps is the maximum number of major tickmarks allowed. function AutoScale($img,$min,$max,$maxsteps,$majend=true) { if( !is_numeric($min) || !is_numeric($max) ) { JpGraphError::Raise(25044); } if( $this->intscale ) { $this->IntAutoScale($img,$min,$max,$maxsteps,$majend); return; } if( abs($min-$max) < 0.00001 ) { // We need some difference to be able to autoscale // make it 5% above and 5% below value if( $min==0 && $max==0 ) { // Special case $min=-1; $max=1; } else { $delta = (abs($max)+abs($min))*0.005; $min -= $delta; $max += $delta; } } $gracetop=($this->gracetop/100.0)*abs($max-$min); $gracebottom=($this->gracebottom/100.0)*abs($max-$min); if( is_numeric($this->autoscale_min) ) { $min = $this->autoscale_min; if( $min >= $max ) { JpGraphError::RaiseL(25071);//('You have specified a min value with SetAutoMin() which is larger than the maximum value used for the scale. This is not possible.'); } if( abs($min-$max ) < 0.001 ) { $max *= 1.2; } } if( is_numeric($this->autoscale_max) ) { $max = $this->autoscale_max; if( $min >= $max ) { JpGraphError::RaiseL(25072);//('You have specified a max value with SetAutoMax() which is smaller than the miminum value used for the scale. This is not possible.'); } if( abs($min-$max ) < 0.001 ) { $min *= 0.8; } } $min -= $gracebottom; $max += $gracetop; // First get tickmarks as multiples of 0.1, 1, 10, ... if( $majend ) { list($num1steps,$adj1min,$adj1max,$min1step,$maj1step) = $this->CalcTicks($maxsteps,$min,$max,1,2); } else { $adj1min=$min; $adj1max=$max; list($num1steps,$min1step,$maj1step) = $this->CalcTicksFreeze($maxsteps,$min,$max,1,2,false); } // Then get tick marks as 2:s 0.2, 2, 20, ... if( $majend ) { list($num2steps,$adj2min,$adj2max,$min2step,$maj2step) = $this->CalcTicks($maxsteps,$min,$max,5,2); } else { $adj2min=$min; $adj2max=$max; list($num2steps,$min2step,$maj2step) = $this->CalcTicksFreeze($maxsteps,$min,$max,5,2,false); } // Then get tickmarks as 5:s 0.05, 0.5, 5, 50, ... if( $majend ) { list($num5steps,$adj5min,$adj5max,$min5step,$maj5step) = $this->CalcTicks($maxsteps,$min,$max,2,5); } else { $adj5min=$min; $adj5max=$max; list($num5steps,$min5step,$maj5step) = $this->CalcTicksFreeze($maxsteps,$min,$max,2,5,false); } // Check to see whichof 1:s, 2:s or 5:s fit better with // the requested number of major ticks $match1=abs($num1steps-$maxsteps); $match2=abs($num2steps-$maxsteps); $match5=abs($num5steps-$maxsteps); // Compare these three values and see which is the closest match // We use a 0.8 weight to gravitate towards multiple of 5:s $r=$this->MatchMin3($match1,$match2,$match5,0.8); switch( $r ) { case 1: $this->Update($img,$adj1min,$adj1max); $this->ticks->Set($maj1step,$min1step); break; case 2: $this->Update($img,$adj2min,$adj2max); $this->ticks->Set($maj2step,$min2step); break; case 3: $this->Update($img,$adj5min,$adj5max); $this->ticks->Set($maj5step,$min5step); break; } } //--------------- // PRIVATE METHODS // This method recalculates all constants that are depending on the // margins in the image. If the margins in the image are changed // this method should be called for every scale that is registred with // that image. Should really be installed as an observer of that image. function InitConstants($img) { if( $this->type=='x' ) { $this->world_abs_size=$img->width - $img->left_margin - $img->right_margin; $this->off=$img->left_margin; $this->scale_factor = 0; if( $this->world_size > 0 ) { $this->scale_factor=$this->world_abs_size/($this->world_size*1.0); } } else { // y scale $this->world_abs_size=$img->height - $img->top_margin - $img->bottom_margin; $this->off=$img->top_margin+$this->world_abs_size; $this->scale_factor = 0; if( $this->world_size > 0 ) { $this->scale_factor=-$this->world_abs_size/($this->world_size*1.0); } } $size = $this->world_size * $this->scale_factor; $this->scale_abs=array($this->off,$this->off + $size); } // Initialize the conversion constants for this scale // This tries to pre-calculate as much as possible to speed up the // actual conversion (with Translate()) later on // $start =scale start in absolute pixels (for x-scale this is an y-position // and for an y-scale this is an x-position // $len =absolute length in pixels of scale function SetConstants($aStart,$aLen) { $this->world_abs_size=$aLen; $this->off=$aStart; if( $this->world_size<=0 ) { // This should never ever happen !! JpGraphError::RaiseL(25074); //("You have unfortunately stumbled upon a bug in JpGraph. It seems like the scale range is ".$this->world_size." [for ".$this->type." scale] <br> Please report Bug #01 to [email protected] and include the script that gave this error. This problem could potentially be caused by trying to use \"illegal\" values in the input data arrays (like trying to send in strings or only NULL values) which causes the autoscaling to fail."); } // scale_factor = number of pixels per world unit $this->scale_factor=$this->world_abs_size/($this->world_size*1.0); // scale_abs = start and end points of scale in absolute pixels $this->scale_abs=array($this->off,$this->off+$this->world_size*$this->scale_factor); } // Calculate number of ticks steps with a specific division // $a is the divisor of 10**x to generate the first maj tick intervall // $a=1, $b=2 give major ticks with multiple of 10, ...,0.1,1,10,... // $a=5, $b=2 give major ticks with multiple of 2:s ...,0.2,2,20,... // $a=2, $b=5 give major ticks with multiple of 5:s ...,0.5,5,50,... // We return a vector of // [$numsteps,$adjmin,$adjmax,$minstep,$majstep] // If $majend==true then the first and last marks on the axis will be major // labeled tick marks otherwise it will be adjusted to the closest min tick mark function CalcTicks($maxsteps,$min,$max,$a,$b,$majend=true) { $diff=$max-$min; if( $diff==0 ) { $ld=0; } else { $ld=floor(log10($diff)); } // Gravitate min towards zero if we are close if( $min>0 && $min < pow(10,$ld) ) $min=0; //$majstep=pow(10,$ld-1)/$a; $majstep=pow(10,$ld)/$a; $minstep=$majstep/$b; $adjmax=ceil($max/$minstep)*$minstep; $adjmin=floor($min/$minstep)*$minstep; $adjdiff = $adjmax-$adjmin; $numsteps=$adjdiff/$majstep; while( $numsteps>$maxsteps ) { $majstep=pow(10,$ld)/$a; $numsteps=$adjdiff/$majstep; ++$ld; } $minstep=$majstep/$b; $adjmin=floor($min/$minstep)*$minstep; $adjdiff = $adjmax-$adjmin; if( $majend ) { $adjmin = floor($min/$majstep)*$majstep; $adjdiff = $adjmax-$adjmin; $adjmax = ceil($adjdiff/$majstep)*$majstep+$adjmin; } else { $adjmax=ceil($max/$minstep)*$minstep; } return array($numsteps,$adjmin,$adjmax,$minstep,$majstep); } function CalcTicksFreeze($maxsteps,$min,$max,$a,$b) { // Same as CalcTicks but don't adjust min/max values $diff=$max-$min; if( $diff==0 ) { $ld=0; } else { $ld=floor(log10($diff)); } //$majstep=pow(10,$ld-1)/$a; $majstep=pow(10,$ld)/$a; $minstep=$majstep/$b; $numsteps=floor($diff/$majstep); while( $numsteps > $maxsteps ) { $majstep=pow(10,$ld)/$a; $numsteps=floor($diff/$majstep); ++$ld; } $minstep=$majstep/$b; return array($numsteps,$minstep,$majstep); } function IntCalcTicks($maxsteps,$min,$max,$a,$majend=true) { $diff=$max-$min; if( $diff==0 ) { JpGraphError::RaiseL(25075);//('Can\'t automatically determine ticks since min==max.'); } else { $ld=floor(log10($diff)); } // Gravitate min towards zero if we are close if( $min>0 && $min < pow(10,$ld) ) { $min=0; } if( $ld == 0 ) { $ld=1; } if( $a == 1 ) { $majstep = 1; } else { $majstep=pow(10,$ld)/$a; } $adjmax=ceil($max/$majstep)*$majstep; $adjmin=floor($min/$majstep)*$majstep; $adjdiff = $adjmax-$adjmin; $numsteps=$adjdiff/$majstep; while( $numsteps>$maxsteps ) { $majstep=pow(10,$ld)/$a; $numsteps=$adjdiff/$majstep; ++$ld; } $adjmin=floor($min/$majstep)*$majstep; $adjdiff = $adjmax-$adjmin; if( $majend ) { $adjmin = floor($min/$majstep)*$majstep; $adjdiff = $adjmax-$adjmin; $adjmax = ceil($adjdiff/$majstep)*$majstep+$adjmin; } else { $adjmax=ceil($max/$majstep)*$majstep; } return array($numsteps,$adjmin,$adjmax,$majstep); } function IntCalcTicksFreeze($maxsteps,$min,$max,$a) { // Same as IntCalcTick but don't change min/max values $diff=$max-$min; if( $diff==0 ) { JpGraphError::RaiseL(25075);//('Can\'t automatically determine ticks since min==max.'); } else { $ld=floor(log10($diff)); } if( $ld == 0 ) { $ld=1; } if( $a == 1 ) { $majstep = 1; } else { $majstep=pow(10,$ld)/$a; } $numsteps=floor($diff/$majstep); while( $numsteps > $maxsteps ) { $majstep=pow(10,$ld)/$a; $numsteps=floor($diff/$majstep); ++$ld; } return array($numsteps,$majstep); } // Determine the minimum of three values witha weight for last value function MatchMin3($a,$b,$c,$weight) { if( $a < $b ) { if( $a < ($c*$weight) ) { return 1; // $a smallest } else { return 3; // $c smallest } } elseif( $b < ($c*$weight) ) { return 2; // $b smallest } return 3; // $c smallest } function __get($name) { $variable_name = '_' . $name; if (isset($this->$variable_name)) { return $this->$variable_name * SUPERSAMPLING_SCALE; } else { JpGraphError::RaiseL('25132', $name); } } function __set($name, $value) { $this->{'_'.$name} = $value; } } // Class //=================================================== // CLASS DisplayValue // Description: Used to print data values at data points //=================================================== class DisplayValue { public $margin=5; public $show=false; public $valign='',$halign='center'; public $format='%.1f',$negformat=''; private $ff=FF_DEFAULT,$fs=FS_NORMAL,$fsize=8; private $iFormCallback=''; private $angle=0; private $color='navy',$negcolor=''; private $iHideZero=false; public $txt=null; function __construct() { $this->txt = new Text(); } function Show($aFlag=true) { $this->show=$aFlag; } function SetColor($aColor,$aNegcolor='') { $this->color = $aColor; $this->negcolor = $aNegcolor; } function SetFont($aFontFamily,$aFontStyle=FS_NORMAL,$aFontSize=8) { $this->ff=$aFontFamily; $this->fs=$aFontStyle; $this->fsize=$aFontSize; } function ApplyFont($aImg) { $aImg->SetFont($this->ff,$this->fs,$this->fsize); } function SetMargin($aMargin) { $this->margin = $aMargin; } function SetAngle($aAngle) { $this->angle = $aAngle; } function SetAlign($aHAlign,$aVAlign='') { $this->halign = $aHAlign; $this->valign = $aVAlign; } function SetFormat($aFormat,$aNegFormat='') { $this->format= $aFormat; $this->negformat= $aNegFormat; } function SetFormatCallback($aFunc) { $this->iFormCallback = $aFunc; } function HideZero($aFlag=true) { $this->iHideZero=$aFlag; } function Stroke($img,$aVal,$x,$y) { if( $this->show ) { if( $this->negformat=='' ) { $this->negformat=$this->format; } if( $this->negcolor=='' ) { $this->negcolor=$this->color; } if( $aVal===NULL || (is_string($aVal) && ($aVal=='' || $aVal=='-' || $aVal=='x' ) ) ) { return; } if( is_numeric($aVal) && $aVal==0 && $this->iHideZero ) { return; } // Since the value is used in different cirumstances we need to check what // kind of formatting we shall use. For example, to display values in a line // graph we simply display the formatted value, but in the case where the user // has already specified a text string we don't fo anything. if( $this->iFormCallback != '' ) { $f = $this->iFormCallback; $sval = call_user_func($f,$aVal); } elseif( is_numeric($aVal) ) { if( $aVal >= 0 ) { $sval=sprintf($this->format,$aVal); } else { $sval=sprintf($this->negformat,$aVal); } } else { $sval=$aVal; } $y = $y-sign($aVal)*$this->margin; $this->txt->Set($sval); $this->txt->SetPos($x,$y); $this->txt->SetFont($this->ff,$this->fs,$this->fsize); if( $this->valign == '' ) { if( $aVal >= 0 ) { $valign = "bottom"; } else { $valign = "top"; } } else { $valign = $this->valign; } $this->txt->Align($this->halign,$valign); $this->txt->SetOrientation($this->angle); if( $aVal > 0 ) { $this->txt->SetColor($this->color); } else { $this->txt->SetColor($this->negcolor); } $this->txt->Stroke($img); } } } //=================================================== // CLASS Plot // Description: Abstract base class for all concrete plot classes //=================================================== class Plot { public $numpoints=0; public $value; public $legend=''; public $coords=array(); public $color='black'; public $hidelegend=false; public $line_weight=1; public $csimtargets=array(),$csimwintargets=array(); // Array of targets for CSIM public $csimareas=''; // Resultant CSIM area tags public $csimalts=null; // ALT:s for corresponding target public $legendcsimtarget='',$legendcsimwintarget=''; public $legendcsimalt=''; protected $weight=1; protected $center=false; protected $inputValues; protected $isRunningClear = false; function __construct($aDatay,$aDatax=false) { $this->numpoints = count($aDatay); if( $this->numpoints==0 ) { JpGraphError::RaiseL(25121);//("Empty input data array specified for plot. Must have at least one data point."); } if (!$this->isRunningClear) { $this->inputValues = array(); $this->inputValues['aDatay'] = $aDatay; $this->inputValues['aDatax'] = $aDatax; } $this->coords[0]=$aDatay; if( is_array($aDatax) ) { $this->coords[1]=$aDatax; $n = count($aDatax); for( $i=0; $i < $n; ++$i ) { if( !is_numeric($aDatax[$i]) ) { JpGraphError::RaiseL(25070); } } } $this->value = new DisplayValue(); } // Stroke the plot // "virtual" function which must be implemented by // the subclasses function Stroke($aImg,$aXScale,$aYScale) { JpGraphError::RaiseL(25122);//("JpGraph: Stroke() must be implemented by concrete subclass to class Plot"); } function HideLegend($f=true) { $this->hidelegend = $f; } function DoLegend($graph) { if( !$this->hidelegend ) $this->Legend($graph); } function StrokeDataValue($img,$aVal,$x,$y) { $this->value->Stroke($img,$aVal,$x,$y); } // Set href targets for CSIM function SetCSIMTargets($aTargets,$aAlts='',$aWinTargets='') { $this->csimtargets=$aTargets; $this->csimwintargets=$aWinTargets; $this->csimalts=$aAlts; } // Get all created areas function GetCSIMareas() { return $this->csimareas; } // "Virtual" function which gets called before any scale // or axis are stroked used to do any plot specific adjustment function PreStrokeAdjust($aGraph) { if( substr($aGraph->axtype,0,4) == "text" && (isset($this->coords[1])) ) { JpGraphError::RaiseL(25123);//("JpGraph: You can't use a text X-scale with specified X-coords. Use a \"int\" or \"lin\" scale instead."); } return true; } // Virtual function to the the concrete plot class to make any changes to the graph // and scale before the stroke process begins function PreScaleSetup($aGraph) { // Empty } // Get minimum values in plot function Min() { if( isset($this->coords[1]) ) { $x=$this->coords[1]; } else { $x=''; } if( $x != '' && count($x) > 0 ) { $xm=min($x); } else { $xm=0; } $y=$this->coords[0]; $cnt = count($y); if( $cnt > 0 ) { $i=0; while( $i<$cnt && !is_numeric($ym=$y[$i]) ) { $i++; } while( $i < $cnt) { if( is_numeric($y[$i]) ) { $ym=min($ym,$y[$i]); } ++$i; } } else { $ym=''; } return array($xm,$ym); } // Get maximum value in plot function Max() { if( isset($this->coords[1]) ) { $x=$this->coords[1]; } else { $x=''; } if( $x!='' && count($x) > 0 ) { $xm=max($x); } else { $xm = $this->numpoints-1; } $y=$this->coords[0]; if( count($y) > 0 ) { $cnt = count($y); $i=0; while( $i<$cnt && !is_numeric($ym=$y[$i]) ) { $i++; } while( $i < $cnt ) { if( is_numeric($y[$i]) ) { $ym=max($ym,$y[$i]); } ++$i; } } else { $ym=''; } return array($xm,$ym); } function SetColor($aColor) { $this->color=$aColor; } function SetLegend($aLegend,$aCSIM='',$aCSIMAlt='',$aCSIMWinTarget='') { $this->legend = $aLegend; $this->legendcsimtarget = $aCSIM; $this->legendcsimwintarget = $aCSIMWinTarget; $this->legendcsimalt = $aCSIMAlt; } function SetWeight($aWeight) { $this->weight=$aWeight; } function SetLineWeight($aWeight=1) { $this->line_weight=$aWeight; } function SetCenter($aCenter=true) { $this->center = $aCenter; } // This method gets called by Graph class to plot anything that should go // into the margin after the margin color has been set. function StrokeMargin($aImg) { return true; } // Framework function the chance for each plot class to set a legend function Legend($aGraph) { if( $this->legend != '' ) { $aGraph->legend->Add($this->legend,$this->color,'',0,$this->legendcsimtarget,$this->legendcsimalt,$this->legendcsimwintarget); } } function Clear() { $this->isRunningClear = true; $this->__construct($this->inputValues['aDatay'], $this->inputValues['aDatax']); $this->isRunningClear = false; } } // Class // Provide a deterministic list of new colors whenever the getColor() method // is called. Used to automatically set colors of plots. class ColorFactory { static private $iIdx = 0; static private $iColorList = array( 'black', 'blue', 'orange', 'darkgreen', 'red', 'AntiqueWhite3', 'aquamarine3', 'azure4', 'brown', 'cadetblue3', 'chartreuse4', 'chocolate', 'darkblue', 'darkgoldenrod3', 'darkorchid3', 'darksalmon', 'darkseagreen4', 'deepskyblue2', 'dodgerblue4', 'gold3', 'hotpink', 'lawngreen', 'lightcoral', 'lightpink3', 'lightseagreen', 'lightslateblue', 'mediumpurple', 'olivedrab', 'orangered1', 'peru', 'slategray', 'yellow4', 'springgreen2'); static private $iNum = 33; static function getColor() { if( ColorFactory::$iIdx >= ColorFactory::$iNum ) ColorFactory::$iIdx = 0; return ColorFactory::$iColorList[ColorFactory::$iIdx++]; } } // <EOF> ?>
mit
apo-j/Projects_Working
Bivi/src/Bivi.FrontOffice/Bivi.FrontOffice.Web.ViewModels/ViewModels/PopinVideoViewModel.cs
472
using System; using Bivi.Domaine; using Bivi.FrontOffice.Web.ViewModels.Pages.Common; using Bivi.Infrastructure.Services.Caching; namespace Bivi.FrontOffice.Web.ViewModels { public class PopinVideoViewModel { public ICaching TranslatorService { get; set; } public string Titre { get; set; } public string Url { get; set; } public string VideoType { get; set; } public bool External { get; set; } } }
mit
italinux/Authentication
lib/vendor/symfony/lib/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query/Part.php
2067
<?php /* * $Id: Part.php 7490 2010-03-29 19:53:27Z jwage $ * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information, see * <http://www.propel-project.org>. */ /** * Propel_Query_Part * * @package Propel * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.propel-project.org * @since 1.0 * @version $Revision: 7490 $ * @author Konsta Vesterinen <[email protected]> */ abstract class Propel_Query_Part { /** * @var Propel_Query $query the query object associated with this parser */ protected $query; protected $_tokenizer; /** * @param Propel_Query $query the query object associated with this parser */ public function __construct($query, Propel_Query_Tokenizer $tokenizer = null) { $this->query = $query; if ( ! $tokenizer) { $tokenizer = new Propel_Query_Tokenizer(); } $this->_tokenizer = $tokenizer; } /** * @return Propel_Query $query the query object associated with this parser */ public function getQuery() { return $this->query; } }
mit
jrahlf/3D-Non-Contact-Laser-Profilometer
xpcc/src/xpcc/driver/connectivity/i2c/constants.hpp
2143
// coding: utf-8 // ---------------------------------------------------------------------------- /* Copyright (c) 2012, Roboterclub Aachen e.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Roboterclub Aachen e.V. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY ROBOTERCLUB AACHEN E.V. ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL ROBOTERCLUB AACHEN E.V. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // ---------------------------------------------------------------------------- #ifndef XPCC_I2C__CONSTANTS_HPP #define XPCC_I2C__CONSTANTS_HPP #include <stdint.h> namespace xpcc { /** * \brief I2C Interface * \ingroup i2c */ namespace i2c { static const uint8_t WRITE = 0x00; static const uint8_t READ = 0x01; namespace adapter { enum State { BUSY, NO_ERROR, ERROR }; } } } #endif // XPCC_I2C__CONSTANTS_HPP
mit
Trancendances/anchor-theme
functions.php
7704
<?php function podcasts_posts() { // only run on the first call if( ! Registry::has('trance_post_archive')) { // capture original article if one is set if($article = Registry::get('article')) { Registry::set('original_article', $article); } } if( ! $posts = Registry::get('trance_post_archive')) { $posts = Post::where('status', '=', 'published')->sort('created', 'desc')->get(); Registry::set('trance_post_archive', $posts = new Items($posts)); } if($result = $posts->valid()) { // register single post Registry::set('article', $posts->current()); // move to next $posts->next(); } else { // back to the start $posts->rewind(); // reset original article Registry::set('article', Registry::get('original_article')); // remove items Registry::set('trance_post_archive', false); } return $result; } /** * Sort posts by custom field 'date' * You have to call it 2 times: the first with param $end = FALSE * the second with param $end = TRUE * @param boolean $from_newest_to_oldest wheter should sort ascending or descending * @param booelan $end if true, resets the original order */ function sort_posts_by_date($from_newest_to_oldest = TRUE, $end = FALSE) { #restore old 'posts' value if ($end) { Registry::set('posts', Registry::get('old-posts')); Registry::set('old-posts', NULL); } #sort posts by 'date' custom field else { $soirees = Category::slug('soirees'); list(, $posts) = Post::listing($soirees); usort($posts, function($a, $b) { $date_a = Extend::field('post', 'date', $a->data['id']); $date_b = Extend::field('post', 'date', $b->data['id']); $hour_a = Extend::field('post', 'heure', $a->data['id']); $hour_b = Extend::field('post', 'heure', $b->data['id']); #try to sort by date (from newest to oldest) if (($date_a = $date_a->value->text." ".$hour_a->value->text) && ($date_b = $date_b->value->text." ".$hour_b->value->text)) { #uses American notation MM/DD/YYYY $date_a = strtotime($date_a); $date_b = strtotime($date_b); return $date_b > $date_a; } #if at least one of the posts doesn't have a date, do nothing else return -1; }); #if specified, reverse the order if (!$from_newest_to_oldest) $posts = array_reverse($posts); #lets you use 'posts()' as you normally would Registry::set('old-posts', Registry::get('posts')); Registry::set('posts', new Items($posts)); } } function rwar_latest_posts($limit = 3) { // only run on the first call if( ! Registry::has('rwar_latest_posts')) { // capture original article if one is set if($article = Registry::get('article')) { Registry::set('original_article', $article); } } if( ! $posts = Registry::get('rwar_latest_posts')) { $posts = Post::where('status', '=', 'published') ->where('category', '<>', 4) ->sort('created', 'desc') ->take($limit)->get(); Registry::set('rwar_latest_posts', $posts = new Items($posts)); } if($result = $posts->valid()) { // register single post Registry::set('article', $posts->current()); // move to next $posts->next(); } else { // back to the start $posts->rewind(); // reset original article Registry::set('article', Registry::get('original_article')); // remove items Registry::set('rwar_latest_posts', false); } return $result; } function rwar_posts_by_categories($slugs,$limit = 3) { // only run on the first call if( ! Registry::has('rwar_posts_by_categories')) { // capture original article if one is set if($article = Registry::get('article')) { Registry::set('original_article', $article); } } if( ! $posts = Registry::get('rwar_posts_by_categories')) { $posts = Post::where('status', '=', 'published'); if (count($slugs) > 1) { foreach ($slugs as $slug) { $category = Category::slug($slug); $posts = $posts->or_where('category','=', $category->id); } $posts = $posts; } else { $category = Category::slug($slugs[0]); $posts = $posts->where('category','=', $category->id); } $posts = $posts->sort('created', 'desc')->take($limit)->get(); Registry::set('rwar_posts_by_categories', $posts = new Items($posts)); } if($result = $posts->valid()) { // register single post Registry::set('article', $posts->current()); // move to next $posts->next(); } else { // back to the start $posts->rewind(); // reset original article Registry::set('article', Registry::get('original_article')); // remove items Registry::set('rwar_posts_by_categories', false); } return $result; } function post_list() { // only run on the first call if( ! Registry::has('rwar_post_archive')) { // capture original article if one is set if($article = Registry::get('article')) { Registry::set('original_article', $article); } } if( ! $posts = Registry::get('rwar_post_archive')) { $posts = Post::where('status', '=', 'published')->sort('created', 'desc')->get(); Registry::set('rwar_post_archive', $posts = new Items($posts)); } if($result = $posts->valid()) { // register single post Registry::set('article', $posts->current()); // move to next $posts->next(); } else { // back to the start $posts->rewind(); // reset original article Registry::set('article', Registry::get('original_article')); // remove items Registry::set('rwar_post_archive', false); } return $result; } function article_category_id() { if($category = Registry::prop('article', 'category')) { $categories = Registry::get('all_categories'); return $categories[$category]->id; } } /****************************************/ /* FONCTIONS API */ /****************************************/ function define_tab($element, $tab) { if($element == "podcasts") { while(podcasts_posts()) { if(article_category_slug() == "podcasts") { $url = article_custom_field("podcast_file"); $type = get_headers($url, 1); $description = article_description(); $titre = article_title(); $description = article_description(); $mimetype = $type['Content-Type']; libxml_use_internal_errors(true); // Désactive les erreurs dues à du HTML non valide $post = new DOMDocument(); $post->loadHTML(article_markdown()); $tracks = $post->getElementsByTagName('li'); $tracklist = array( "length" => $tracks->length ); for ($i = 0; $i < $tracks->length; $i++) { $links = $tracks->item($i)->getElementsByTagName('a'); $link = ""; for ($j = 0; $j < $links->length; $j++) { $link = $links->item($j)->getAttribute('href'); } $trackname = strtok($tracks->item($i)->nodeValue, "]"); if($i != 0 && $i != ($tracks->length)-1){ $trackname = $trackname."]"; } $track = array( "trackname" => $trackname, "link" => $link ); array_push($tracklist, $track); } $episode = array( "name" => $titre, "description" => $description, "tracklist" => $tracklist, "direct_link" => $url, "mimetype" => $mimetype ); array_push($tab, $episode); } } } return $tab; } ?>
mit
slhad/FullScreenCheckAndRun
Source/FSCR/Libs/FullscreenChecker.cs
2253
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using System.Windows.Forms; using System.Drawing; [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left; public int Top; public int Right; public int Bottom; } public struct Size { public int Width; public int Height; } namespace FSCR.Libs { class FullscreenChecker { [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] private static extern IntPtr GetDesktopWindow(); [DllImport("user32.dll")] private static extern IntPtr GetShellWindow(); [DllImport("user32.dll", SetLastError = true)] private static extern int GetWindowRect(IntPtr hwnd, out RECT rc); private IntPtr desktopHandle; //Window handle for the desktop private IntPtr shellHandle; //Window handle for the shell public bool check() { //Get the handles for the desktop and shell now. desktopHandle = GetDesktopWindow(); shellHandle = GetShellWindow(); //get the dimensions of the active window IntPtr hWnd = GetForegroundWindow(); bool runningFullScreen = false; RECT appBounds; Size size; Rectangle screenBounds; if (hWnd != null && !hWnd.Equals(IntPtr.Zero)) { //Check we haven't picked up the desktop or the shell if (!(hWnd.Equals(desktopHandle) || hWnd.Equals(shellHandle))) { GetWindowRect(hWnd, out appBounds); size.Height = appBounds.Bottom + appBounds.Top; size.Width = appBounds.Right + appBounds.Left; //determine if window is fullscreen screenBounds = Screen.FromHandle(hWnd).Bounds; if (size.Height == screenBounds.Height && size.Width == screenBounds.Width) { runningFullScreen = true; } } } return runningFullScreen; } } }
mit
flagship-llc/jq_upload_rails_paperclip
spec/models/upload_spec.rb
134
require 'spec_helper' RSpec.describe JqUploadRailsPaperclip::Upload, :type => :model do it { should have_attachment(:file) } end
mit
umpirsky/Transliterator
src/Transliterator/data/ru/ALA_LC.php
1269
<?php /* * This file is part of the Transliterator package. * * (c) Саша Стаменковић <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Russian mapping (ALA-LC system). * * @see http://en.wikipedia.org/wiki/Romanization_of_Russian */ return array ( 'cyr' => array( 'щ', 'ж', 'х', 'ц', 'ч', 'ш', 'ъ', 'э', 'ю', 'я', 'Щ', 'Ж', 'Х', 'Ц', 'Ч', 'Ш', 'Ъ', 'Э', 'Ю', 'Я', 'а', 'б', 'в', 'г', 'д', 'е', 'ё', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'ь', 'ы', 'А', 'Б', 'В', 'Г', 'Д', 'Е', 'Ё', 'З', 'И', 'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р', 'С', 'Т', 'У', 'Ф', 'Ь', 'Ы' ), 'lat' => array( 'shch', 'zh', 'kh', 't͡s', 'ch', 'sh', 'ʺ', 'ė', 'i͡u', 'i͡a', 'Shch', 'Zh', 'Kh', 'T͡s', 'Ch', 'Sh', 'ʺ', 'Ė', 'I͡u', 'I͡a', 'a', 'b', 'v', 'g', 'd', 'e', 'ë', 'z', 'i', 'ĭ', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'f', 'ʹ', 'y', 'A', 'B', 'V', 'G', 'D', 'E', 'Ë', 'Z', 'I', 'Ĭ', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'F', 'ʹ', 'Y' ) );
mit
xhhjin/heroku-ghost
node_modules/sqlite3/test/trace.test.js
1846
var sqlite3 = require('..'); var assert = require('assert'); describe('tracing', function() { it('Database tracing', function(done) { var db = new sqlite3.Database(':memory:'); var create = false; var select = false; db.on('trace', function(sql) { if (sql.match(/^SELECT/)) { assert.ok(!select); assert.equal(sql, "SELECT * FROM foo"); select = true; } else if (sql.match(/^CREATE/)) { assert.ok(!create); assert.equal(sql, "CREATE TABLE foo (id int)"); create = true; } else { assert.ok(false); } }); db.serialize(function() { db.run("CREATE TABLE foo (id int)"); db.run("SELECT * FROM foo"); }); db.close(function(err) { if (err) throw err; assert.ok(create); assert.ok(select); done(); }); }); it('test disabling tracing #1', function(done) { var db = new sqlite3.Database(':memory:'); db.on('trace', function(sql) {}); db.removeAllListeners('trace'); db._events['trace'] = function(sql) { assert.ok(false); }; db.run("CREATE TABLE foo (id int)"); db.close(done); }); it('test disabling tracing #2', function(done) { var db = new sqlite3.Database(':memory:'); var trace = function(sql) {}; db.on('trace', trace); db.removeListener('trace', trace); db._events['trace'] = function(sql) { assert.ok(false); }; db.run("CREATE TABLE foo (id int)"); db.close(done); }); });
mit
sergap1812/quiz
controllers/comment_controller.js
1898
var models = require('../models'); var Sequelize = require('sequelize'); // Autoload el comentario asociado a :commentId exports.load = function(req, res, next, commentId) { models.Comment.findById(commentId).then(function(comment) { if(comment) { req.comment = comment; next(); } else { next(new Error('No existe commentId=' + commentId)); } }).catch(function(error) { next(error); }); }; // GET /quizzes/:quizId/comments/new exports.new = function(req, res, next) { var comment = models.Comment.build({text: ''}); res.render('comments/new', {comment: comment, quiz: req.quiz}); }; // POST /quizzes/:quizId/comments exports.create = function(req, res, next) { var authorId = (req.session.user && req.session.user.id) || 0; var comment = models.Comment.build({ text: req.body.comment.text, QuizId: req.quiz.id, AuthorId: authorId }); comment.save({ fields: ['text', 'QuizId', 'AuthorId'] }).then(function(comment) { req.flash('success', 'Comentario creado con éxito.'); res.redirect('/quizzes/' + req.quiz.id); }).catch(Sequelize.ValidationError, function(error) { req.flash('error', 'Errores en el formulario.'); for(var i in error.errors) { req.flash('error', error.errors[i].value); }; res.render('comments/new', {comment: comment, quiz: req.quiz}); }).catch(function(error) { req.flash('error', 'Error al crear un comentario: ' + error.message); next(error); }); }; // PUT /quizzes/:quizId/comments/:commentId/accept exports.accept = function(req, res, next) { req.comment.accepted = true; req.comment.save(['accepted']).then(function(comment) { req.flash('success', 'Comentario aceptado con éxito.'); res.redirect('/quizzes/' + req.params.quizId); }).catch(function(error) { req.flash('error', 'Error al aceptar un comentario: ' + error.message); next(error); }); };
mit
rdazza/tarea_api_restful
src/main/java/edu/upc/eetac/dsa/grouptalk/entity/User.java
1072
package edu.upc.eetac.dsa.grouptalk.entity; import org.glassfish.jersey.linking.InjectLinks; import javax.ws.rs.core.Link; import java.util.List; /** * Created by ruben on 24/10/15. */ public class User { @InjectLinks({}) private List<Link> links; private String id; private String loginid; private String email; private String fullname; public List<Link> getLinks() { return links; } public void setLinks(List<Link> links) { this.links = links; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getLoginid() { return loginid; } public void setLoginid(String loginid) { this.loginid = loginid; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getFullname() { return fullname; } public void setFullname(String fullname) { this.fullname = fullname; } }
mit
extant1/training
items.cs
34791
//// // Armor //// // Regular Padded Set function regularpadded(%quality) { if(%quality){ echo("## Adding Regular Padded Set - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 891 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 892 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 893 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 894 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 895 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 896 1 " @ %quality @ " 100000"); } else { echo("## Adding Regular Padded Set - Q100 ##"); cmChatCommand('@', "/ADD 891 1 100 100000"); cmChatCommand('@', "/ADD 892 1 100 100000"); cmChatCommand('@', "/ADD 893 1 100 100000"); cmChatCommand('@', "/ADD 894 1 100 100000"); cmChatCommand('@', "/ADD 895 1 100 100000"); cmChatCommand('@', "/ADD 896 1 100 100000"); } } // Heavy Padded Set function heavypadded(%quality) { if(%quality){ echo("## Adding Heavy Padded Set - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 897 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 898 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 899 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 900 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 901 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 902 1 " @ %quality @ " 100000"); } else { echo("## Adding Heavy Padded Set - Q100 ##"); cmChatCommand('@', "/ADD 897 1 100 100000"); cmChatCommand('@', "/ADD 898 1 100 100000"); cmChatCommand('@', "/ADD 899 1 100 100000"); cmChatCommand('@', "/ADD 900 1 100 100000"); cmChatCommand('@', "/ADD 901 1 100 100000"); cmChatCommand('@', "/ADD 902 1 100 100000"); } } // Royal Padded Set function royalpadded(%quality) { if(%quality){ echo("## Adding Royal Padded Set - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 903 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 904 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 905 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 906 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 907 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 908 1 " @ %quality @ " 100000"); } else { echo("## Adding Royal Padded Set - Q100 ##"); cmChatCommand('@', "/ADD 903 1 100 100000"); cmChatCommand('@', "/ADD 904 1 100 100000"); cmChatCommand('@', "/ADD 905 1 100 100000"); cmChatCommand('@', "/ADD 906 1 100 100000"); cmChatCommand('@', "/ADD 907 1 100 100000"); cmChatCommand('@', "/ADD 908 1 100 100000"); } } // Regular Scale Set function regularscale(%quality) { if(%quality){ echo("## Adding Regular Scale Set - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 809 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 810 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 811 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 812 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 813 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 814 1 " @ %quality @ " 100000"); } else { echo("## Adding Regular Scale Set - Q100 ##"); cmChatCommand('@', "/ADD 809 1 100 100000"); cmChatCommand('@', "/ADD 810 1 100 100000"); cmChatCommand('@', "/ADD 811 1 100 100000"); cmChatCommand('@', "/ADD 812 1 100 100000"); cmChatCommand('@', "/ADD 813 1 100 100000"); cmChatCommand('@', "/ADD 814 1 100 100000"); } } // Heavy Scale Set function heavyscale(%quality) { if(%quality){ echo("## Adding Heavy Scale Set - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 815 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 816 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 817 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 818 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 819 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 820 1 " @ %quality @ " 100000"); } else { echo("## Adding Heavy Scale Set - Q100 ##"); cmChatCommand('@', "/ADD 815 1 100 100000"); cmChatCommand('@', "/ADD 816 1 100 100000"); cmChatCommand('@', "/ADD 817 1 100 100000"); cmChatCommand('@', "/ADD 818 1 100 100000"); cmChatCommand('@', "/ADD 819 1 100 100000"); cmChatCommand('@', "/ADD 820 1 100 100000"); } } // Heavy Scale Set function royalscale(%quality) { if(%quality){ echo("## Adding Royal Scale Set - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 821 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 822 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 823 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 824 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 825 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 826 1 " @ %quality @ " 100000"); } else { echo("## Adding Royal Scale Set - Q100 ##"); cmChatCommand('@', "/ADD 821 1 100 100000"); cmChatCommand('@', "/ADD 822 1 100 100000"); cmChatCommand('@', "/ADD 823 1 100 100000"); cmChatCommand('@', "/ADD 824 1 100 100000"); cmChatCommand('@', "/ADD 825 1 100 100000"); cmChatCommand('@', "/ADD 826 1 100 100000"); } } // Regular Leather Set function regularleather(%quality) { if(%quality){ echo("## Adding Regular Leather Set - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 863 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 864 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 865 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 866 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 867 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 868 1 " @ %quality @ " 100000"); } else { echo("## Adding Regular Leather Set - Q100 ##"); cmChatCommand('@', "/ADD 863 1 100 100000"); cmChatCommand('@', "/ADD 864 1 100 100000"); cmChatCommand('@', "/ADD 865 1 100 100000"); cmChatCommand('@', "/ADD 866 1 100 100000"); cmChatCommand('@', "/ADD 867 1 100 100000"); cmChatCommand('@', "/ADD 868 1 100 100000"); } } // Heavy Leather Set function heavyleather(%quality) { if(%quality){ echo("## Adding Heavy Leather Set - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 869 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 870 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 871 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 872 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 873 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 874 1 " @ %quality @ " 100000"); } else { echo("## Adding Heavy Leather Set - Q100 ##"); cmChatCommand('@', "/ADD 869 1 100 100000"); cmChatCommand('@', "/ADD 870 1 100 100000"); cmChatCommand('@', "/ADD 871 1 100 100000"); cmChatCommand('@', "/ADD 872 1 100 100000"); cmChatCommand('@', "/ADD 873 1 100 100000"); cmChatCommand('@', "/ADD 874 1 100 100000"); } } // Royal Leather Set function royalleather(%quality) { if(%quality){ echo("## Adding Royal Leather Set - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 875 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 876 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 877 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 878 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 879 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 880 1 " @ %quality @ " 100000"); } else { echo("## Adding Royal Leather Set - Q100 ##"); cmChatCommand('@', "/ADD 875 1 100 100000"); cmChatCommand('@', "/ADD 876 1 100 100000"); cmChatCommand('@', "/ADD 877 1 100 100000"); cmChatCommand('@', "/ADD 878 1 100 100000"); cmChatCommand('@', "/ADD 879 1 100 100000"); cmChatCommand('@', "/ADD 880 1 100 100000"); } } // Regular Chain Set function regularchain(%quality) { if(%quality){ echo("## Adding Regular Chain Set - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 836 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 837 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 838 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 839 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 840 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 910 1 " @ %quality @ " 100000"); } else { echo("## Adding Regular Chain Set - Q100 ##"); cmChatCommand('@', "/ADD 836 1 100 100000"); cmChatCommand('@', "/ADD 837 1 100 100000"); cmChatCommand('@', "/ADD 838 1 100 100000"); cmChatCommand('@', "/ADD 839 1 100 100000"); cmChatCommand('@', "/ADD 840 1 100 100000"); cmChatCommand('@', "/ADD 910 1 100 100000"); } } // Heavy Chain Set function heavychain(%quality) { if(%quality){ echo("## Adding Heavy Chain Set - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 841 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 842 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 843 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 844 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 845 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 846 1 " @ %quality @ " 100000"); } else { echo("## Adding Heavy Chain Set - Q100 ##"); cmChatCommand('@', "/ADD 841 1 100 100000"); cmChatCommand('@', "/ADD 842 1 100 100000"); cmChatCommand('@', "/ADD 843 1 100 100000"); cmChatCommand('@', "/ADD 844 1 100 100000"); cmChatCommand('@', "/ADD 845 1 100 100000"); cmChatCommand('@', "/ADD 846 1 100 100000"); } } // Royal Chain Set function royalchain(%quality) { if(%quality){ echo("## Adding Royal Chain Set - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 847 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 848 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 849 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 850 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 851 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 852 1 " @ %quality @ " 100000"); } else { echo("## Adding Royal Chain Set - Q100 ##"); cmChatCommand('@', "/ADD 847 1 100 100000"); cmChatCommand('@', "/ADD 848 1 100 100000"); cmChatCommand('@', "/ADD 849 1 100 100000"); cmChatCommand('@', "/ADD 850 1 100 100000"); cmChatCommand('@', "/ADD 851 1 100 100000"); cmChatCommand('@', "/ADD 852 1 100 100000"); } } // Half Plate Set function halfplate(%quality) { if(%quality){ echo("## Adding Half Plate Set - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 627 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 628 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 629 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 630 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 631 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 632 1 " @ %quality @ " 100000"); } else { echo("## Adding Half Plate Set - Q100 ##"); cmChatCommand('@', "/ADD 627 1 100 100000"); cmChatCommand('@', "/ADD 628 1 100 100000"); cmChatCommand('@', "/ADD 629 1 100 100000"); cmChatCommand('@', "/ADD 630 1 100 100000"); cmChatCommand('@', "/ADD 631 1 100 100000"); cmChatCommand('@', "/ADD 632 1 100 100000"); } } // Full Plate Set function fullplate(%quality) { if(%quality){ echo("## Adding Full Plate Set - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 547 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 548 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 549 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 550 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 551 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 552 1 " @ %quality @ " 100000"); } else { echo("## Adding Full Plate Set - Q100 ##"); cmChatCommand('@', "/ADD 547 1 100 100000"); cmChatCommand('@', "/ADD 548 1 100 100000"); cmChatCommand('@', "/ADD 549 1 100 100000"); cmChatCommand('@', "/ADD 550 1 100 100000"); cmChatCommand('@', "/ADD 551 1 100 100000"); cmChatCommand('@', "/ADD 552 1 100 100000"); } } // Royal Full Plate Set function royalplate(%quality) { if(%quality){ echo("## Adding Royal Plate Set - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 797 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 798 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 799 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 800 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 801 1 " @ %quality @ " 100000"); cmChatCommand('@', "/ADD 802 1 " @ %quality @ " 100000"); } else { echo("## Adding Royal Plate Set - Q100 ##"); cmChatCommand('@', "/ADD 797 1 100 100000"); cmChatCommand('@', "/ADD 798 1 100 100000"); cmChatCommand('@', "/ADD 799 1 100 100000"); cmChatCommand('@', "/ADD 800 1 100 100000"); cmChatCommand('@', "/ADD 801 1 100 100000"); cmChatCommand('@', "/ADD 802 1 100 100000"); } } //// // Weapons //// //Militia function pitckfork(%quality) { if(%quality){ echo("## Adding Pitchfork - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 588 1 " @ %quality @ " 100000"); } else { echo("## Adding Pitchfork - Q100 ##"); cmChatCommand('@', "/ADD 588 1 100 100000"); } } // Spears function boarspear(%quality) { if(%quality){ echo("## Adding Boar Spear - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 592 1 " @ %quality @ " 100000"); } else { echo("## Adding Boar Spear - Q100 ##"); cmChatCommand('@', "/ADD 592 1 100 100000"); } } function bs(%quality) { boarspear(%quality); } function spear(%quality) { if(%quality){ echo("## Adding Spear - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 591 1 " @ %quality @ " 100000"); } else { echo("## Adding Spear - Q100 ##"); cmChatCommand('@', "/ADD 591 1 100 100000"); } } function awlpike(%quality) { if(%quality){ echo("## Adding Awl Pike - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 593 1 " @ %quality @ " 100000"); } else { echo("## Adding Awl Pike - Q100 ##"); cmChatCommand('@', "/ADD 593 1 100 100000"); } } function becdecorbin(%quality) { if(%quality){ echo("## Adding Bec De Corbin - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 594 1 " @ %quality @ " 100000"); } else { echo("## Adding Bec De Corbin - Q100 ##"); cmChatCommand('@', "/ADD 594 1 100 100000"); } } // Polearms function partisan(%quality) { if(%quality){ echo("## Adding Boar Spear - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 589 1 " @ %quality @ " 100000"); } else { echo("## Adding Boar Spear - Q100 ##"); cmChatCommand('@', "/ADD 589 1 100 100000"); } } function p(%quality) { partisan(%quality); } function glaive(%quality) { if(%quality){ echo("## Adding Glaive - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 585 1 " @ %quality @ " 100000"); } else { echo("## Adding Glaive - Q100 ##"); cmChatCommand('@', "/ADD 585 1 100 100000"); } } function guisarme(%quality) { if(%quality){ echo("## Adding Guuisarme - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 586 1 " @ %quality @ " 100000"); } else { echo("## Adding Guisarme - Q100 ##"); cmChatCommand('@', "/ADD 586 1 100 100000"); } } function pollaxe(%quality) { if(%quality){ echo("## Adding Pollaxe - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 579 1 " @ %quality @ " 100000"); } else { echo("## Adding Pollaxe - Q100 ##"); cmChatCommand('@', "/ADD 579 1 100 100000"); } } function staff(%quality) { if(%quality){ echo("## Adding Staff - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 590 1 " @ %quality @ "100000"); } else { echo("## Adding Staff - Q100 ##"); cmChatCommand('@', "/ADD 590 1 100 100000"); } } // 1H Axe function practiceaxe(%quality) { if(%quality){ echo("## Adding Practice Axe - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 566 1 " @ %quality @ "100000"); } else { echo("## Adding Practice Axe - Q100 ##"); cmChatCommand('@', "/ADD 566 1 100 100000"); } } function battleaxe(%quality) { if(%quality){ echo("## Adding Battle Axe - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 568 1 " @ %quality @ "100000"); } else { echo("## Adding Battle Axe - Q100 ##"); cmChatCommand('@', "/ADD 568 1 100 100000"); } } function nordicaxe(%quality) { if(%quality){ echo("## Adding Nordic Axe - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 569 1 " @ %quality @ "100000"); } else { echo("## Adding Nordic Axe - Q100 ##"); cmChatCommand('@', "/ADD 569 1 100 100000"); } } function waraxe(%quality) { if(%quality){ echo("## Adding War Axe - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 567 1 " @ %quality @ "100000"); } else { echo("## Adding War Axe - Q100 ##"); cmChatCommand('@', "/ADD 567 1 100 100000"); } } // Lances function lance(%quality) { if(%quality){ echo("## Adding Lance - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 598 1 " @ %quality @ " 100000"); } else { echo("## Adding Lance - Q100 ##"); cmChatCommand('@', "/ADD 598 1 100 1000000"); } } function decorated(%quality) { if(%quality){ echo("## Adding Decorated Jousting Lance - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 1141 1 " @ %quality @ " 100000"); } else { echo("## Adding Decorated Jousting Lance - Q100 ##"); cmChatCommand('@', "/ADD 1141 1 100 1000000"); } } function jousting(%quality) { if(%quality){ echo("## Adding Jousting Lance - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 599 1 " @ %quality @ " 100000"); } else { echo("## Adding Jousting Lance - Q100 ##"); cmChatCommand('@', "/ADD 599 1 100 100000"); } } // Pikes function shortpike(%quality) { if(%quality){ echo("## Adding Short Pike - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 595 1 " @ %quality @ " 100000"); } else { echo("## Adding Short Pike - Q100 ##"); cmChatCommand('@', "/ADD 595 1 100 100000"); } } function mediumpike(%quality) { if(%quality){ echo("## Adding Medium Pike - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 596 1 " @ %quality @ " 100000"); } else { echo("## Adding Medium Pike - Q100 ##"); cmChatCommand('@', "/ADD 596 1 100 100000"); } } function longpike(%quality) { if(%quality){ echo("## Adding Long Pike - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 597 1 " @ %quality @ " 100000"); } else { echo("## Adding Long Pike - Q100 ##"); cmChatCommand('@', "/ADD 597 1 100 100000"); } } // Bows function shortbow(%quality) { if(%quality){ echo("## Adding Short Bow - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 601 1 " @ %quality @ " 100000"); } else { echo("## Adding Short Bow - Q100 ##"); cmChatCommand('@', "/ADD 601 1 100 100000"); } } function longbow(%quality) { if(%quality){ echo("## Adding Long Bow - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 602 1 " @ %quality @ " 100000"); } else { echo("## Adding Long Bow - Q100 ##"); cmChatCommand('@', "/ADD 602 1 100 100000"); } } function compositebow(%quality) { if(%quality){ echo("## Adding Composite Bow - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 603 1 " @ %quality @ " 100000"); } else { echo("## Adding Composite Bow - Q100 ##"); cmChatCommand('@', "/ADD 603 1 100 100000"); } } // Crossbows function lightcrossbow(%quality) { if(%quality){ echo("## Adding Light Crossbow - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 604 1 " @ %quality @ " 100000"); } else { echo("## Adding Light Crossbow - Q100 ##"); cmChatCommand('@', "/ADD 604 1 100 100000"); } } function heavycrossbow(%quality) { if(%quality){ echo("## Adding Heavy Crossbow - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 606 1 " @ %quality @ " 100000"); } else { echo("## Adding Heavy Crossbow - Q100 ##"); cmChatCommand('@', "/ADD 606 1 100 100000"); } } function arbalest(%quality) { if(%quality){ echo("## Adding Arbalest - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 605 1 " @ %quality @ " 100000"); } else { echo("## Adding Arbalest - Q100 ##"); cmChatCommand('@', "/ADD 605 1 100 100000"); } } // Thrown weapons function throwingknife(%quality) { if(%quality){ echo("## Adding Throwing Knife - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 608 1 " @ %quality @ " 100000"); } else { echo("## Adding Throwing Knife - Q100 ##"); cmChatCommand('@', "/ADD 608 1 100 100000"); } } function javelin(%quality) { if(%quality){ echo("## Adding Javelin - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 609 1 " @ %quality @ " 100000"); } else { echo("## Adding Javelin - Q100 ##"); cmChatCommand('@', "/ADD 609 1 100 100000"); } } function throwingaxe(%quality) { if(%quality){ echo("## Adding Throwing Axe - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 610 1 " @ %quality @ " 100000"); } else { echo("## Adding Throwing Axe - Q100 ##"); cmChatCommand('@', "/ADD 610 1 100 100000"); } } function naphthapot(%quality) { if(%quality){ echo("## Adding Naphtha Pot - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 1104 1 " @ %quality @ "100000"); } else { echo("## Adding Naphtha Pot - Q100 ##"); cmChatCommand('@', "/ADD 1104 1 100 100000"); } } function naphtha(%quality) { naphthapot(%quality); } function fireworkpot(%quality) { if(%quality){ echo("## Adding Firework Pot - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 1341 1 " @ %quality @ "100000"); } else { echo("## Adding Firework Pot - Q100 ##"); cmChatCommand('@', "/ADD 1341 1 100 100000"); } } function sling(%quality) { if(%quality){ echo("## Adding Sling - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 607 1 " @ %quality @ "100000"); } else { echo("## Adding Sling - Q100 ##"); cmChatCommand('@', "/ADD 607 1 100 100000"); } } // 2H Swords function practicelongsword(%quality) { if(%quality){ echo("## Adding Practice Longsword - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 574 1 " @ %quality @ "100000"); } else { echo("## Adding Practice Longsword - Q100 ##"); cmChatCommand('@', "/ADD 574 1 100 100000"); } } function zweihaender(%quality) { if(%quality){ echo("## Adding Zweihaender - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 576 1 " @ %quality @ " 100000"); } else { echo("## Adding Zweihaender - Q100 ##"); cmChatCommand('@', "/ADD 576 1 100 100000"); } } function zwei(%quality) { zweihaender(%quality); } function claymore(%quality) { if(%quality){ echo("## Adding Claymore - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 575 1 " @ %quality @ " 100000"); } else { echo("## Adding Claymore - Q100 ##"); cmChatCommand('@', "/ADD 575 1 100 100000"); } } function flamberge(%quality) { if(%quality){ echo("## Adding Flamberge - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 577 1 " @ %quality @ " 100000"); } else { echo("## Adding Flamberge - Q100 ##"); cmChatCommand('@', "/ADD 577 1 100 100000"); } } // Half hand swords function bigfalchion(%quality) { if(%quality){ echo("## Adding Big Falchion - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 564 1 " @ %quality @ " 100000"); } else { echo("## Adding Big Falchion - Q100 ##"); cmChatCommand('@', "/ADD 564 1 100 100000"); } } function practicebastard(%quality) { if(%quality){ echo("## Adding Practice Bastard - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 561 1 " @ %quality @ "100000"); } else { echo("## Adding Practice Bastard - Q100 ##"); cmChatCommand('@', "/ADD 561 1 100 100000"); } } function bastard(%quality) { if(%quality){ echo("## Adding Bastard - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 563 1 " @ %quality @ " 100000"); } else { echo("## Adding Bastard - Q100 ##"); cmChatCommand('@', "/ADD 563 1 100 100000"); } } function estoc(%quality) { if(%quality){ echo("## Adding Estoc - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 562 1 " @ %quality @ " 100000"); } else { echo("## Adding Estoc - Q100 ##"); cmChatCommand('@', "/ADD 562 1 100 100000"); } } function knight(%quality) { if(%quality){ echo("## Adding Knight Sword - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 557 1 " @ %quality @ "100000"); } else { echo("## Adding Knight Sword - Q100 ##"); cmChatCommand('@', "/ADD 557 1 100 100000"); } } // 2H Axe function practicegreataxe(%quality) { if(%quality){ echo("## Adding Practice Great Axe - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 578 1 " @ %quality @ "100000"); } else { echo("## Adding Practice Great Axe - Q100 ##"); cmChatCommand('@', "/ADD 578 1 100 100000"); } } function bardiche(%quality) { if(%quality){ echo("## Adding Bardiche - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 580 1 " @ %quality @ "100000"); } else { echo("## Adding Bardiche - Q100 ##"); cmChatCommand('@', "/ADD 580 1 100 100000"); } } function broadaxe(%quality) { if(%quality){ echo("## Adding Broad Axe - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 581 1 " @ %quality @ "100000"); } else { echo("## Adding Broad Axe - Q100 ##"); cmChatCommand('@', "/ADD 581 1 581 100000"); } } function warscythe(%quality) { if(%quality){ echo("## Adding War Scythe - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 587 1 " @ %quality @ "100000"); } else { echo("## Adding War Scythe - Q100 ##"); cmChatCommand('@', "/ADD 587 1 100 100000"); } } // 2H Blunt function maul(%quality) { if(%quality){ echo("## Adding Maul - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 583 1 " @ %quality @ "100000"); } else { echo("## Adding Maul - Q100 ##"); cmChatCommand('@', "/ADD 583 1 100 100000"); } } function practicemaul(%quality) { if(%quality){ echo("## Adding Practice Maul - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 584 1 " @ %quality @ "100000"); } else { echo("## Adding Practice Maul - Q100 ##"); cmChatCommand('@', "/ADD 584 1 100 100000"); } } function sledgehammer(%quality) { if(%quality){ echo("## Adding Sledge Hammer - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 582 1 " @ %quality @ "100000"); } else { echo("## Adding Sledge Hammer - Q100 ##"); cmChatCommand('@', "/ADD 582 1 100 100000"); } } // 1H Blunt function warpick(%quality) { if(%quality){ echo("## Adding Warpick - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 573 1 " @ %quality @ "100000"); } else { echo("## Adding Warpick - Q100 ##"); cmChatCommand('@', "/ADD 573 1 100 100000"); } } function mace(%quality) { if(%quality){ echo("## Adding Mace - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 571 1 " @ %quality @ "100000"); } else { echo("## Adding Mace - Q100 ##"); cmChatCommand('@', "/ADD 571 1 100 100000"); } } function flangedmace(%quality) { mace(%quality); } function cudgel(%quality) { if(%quality){ echo("## Adding Cudgel - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 572 1 " @ %quality @ "100000"); } else { echo("## Adding Cudgel - Q100 ##"); cmChatCommand('@', "/ADD 572 1 100 100000"); } } function morningstar(%quality) { if(%quality){ echo("## Adding Morning Star - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 570 1 " @ %quality @ "100000"); } else { echo("## Adding Morning Star - Q100 ##"); cmChatCommand('@', "/ADD 570 1 100 100000"); } } // 1H Swords function practicesword(%quality) { if(%quality){ echo("## Adding Practice Sword - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 555 1 " @ %quality @ "100000"); } else { echo("## Adding Practice Sword - Q100 ##"); cmChatCommand('@', "/ADD 555 1 100 100000"); } } function falchion(%quality) { if(%quality){ echo("## Adding Boar Spear - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 560 1 " @ %quality @ "100000"); } else { echo("## Adding Boar Spear - Q100 ##"); cmChatCommand('@', "/ADD 560 1 100 100000"); } } function grossmesser(%quality) { if(%quality){ echo("## Adding Grossmesser - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 565 1 " @ %quality @ "100000"); } else { echo("## Adding Grossmesser - Q100 ##"); cmChatCommand('@', "/ADD 565 1 100 100000"); } } function gross(%quality) { grossmesser(%quality); } function scimitar(%quality) { if(%quality){ echo("## Adding Scimitar - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 559 1 " @ %quality @ "100000"); } else { echo("## Adding Scimitar - Q100 ##"); cmChatCommand('@', "/ADD 559 1 100 100000"); } } function nordicsword(%quality) { if(%quality){ echo("## Adding Nordic Sword - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 556 1 " @ %quality @ "100000"); } else { echo("## Adding Nordic Sword - Q100 ##"); cmChatCommand('@', "/ADD 556 1 100 100000"); } } function lightsabre(%quality) { if(%quality){ echo("## Adding Light Sabre - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 558 1 " @ %quality @ "100000"); } else { echo("## Adding Light Sabre - Q100 ##"); cmChatCommand('@', "/ADD 558 1 100 100000"); } } // Arrows function arrow(%quantity) { if(%quantity){ echo("## Adding " @ %quantity @ " Basic Arrows - Q100 ##"); cmChatCommand('@', "/ADD 660 " @ %quantity @ " 100"); } else { echo("## Adding 30 Basic Arrows - Q100 ##"); cmChatCommand('@', "/ADD 660 30 100"); } } function broadhead(%quantity) { if(%quantity){ echo("## Adding " @ %quantity @ " Broadhead Arrows - Q100 ##"); cmChatCommand('@', "/ADD 657 " @ %quantity @ " 100"); } else { echo("## Adding 30 Broadhead Arrows - Q100 ##"); cmChatCommand('@', "/ADD 657 30 100"); } } function fire(%quantity) { if(%quantity){ echo("## Adding " @ %quantity @ " Fire Arrows - Q100 ##"); cmChatCommand('@', "/ADD 658 " @ %quantity @ " 100"); } else { echo("## Adding 30 Fire Arrows - Q100 ##"); cmChatCommand('@', "/ADD 658 30 100"); } } function firework(%quantity) { if(%quantity){ echo("## Adding " @ %quantity @ " Firework Arrows - Q100 ##"); cmChatCommand('@', "/ADD 1339 " @ %quantity @ " 100"); } else { echo("## Adding 30 Firework Arrows - Q100 ##"); cmChatCommand('@', "/ADD 1339 30 100"); } } function dull(%quantity) { if(%quantity){ echo("## Adding " @ %quantity @ " Dull Arrows - Q100 ##"); cmChatCommand('@', "/ADD 659 " @ %quantity @ " 100"); } else { echo("## Adding 30 Dull Arrows - Q100 ##"); cmChatCommand('@', "/ADD 659 30 100"); } } function bodkin(%quantity) { if(%quantity){ echo("## Adding " @ %quantity @ " Bodkin Arrows - Q100 ##"); cmChatCommand('@', "/ADD 656 " @ %quantity @ " 100"); } else { echo("## Adding 30 Bodkin Arrows - Q100 ##"); cmChatCommand('@', "/ADD 656 30 100"); } } // Bolts function bolt(%quantity) { if(%quantity){ echo("## Adding " @ %quantity @ " Basic Bolts - Q100 ##"); cmChatCommand('@', "/ADD 662 " @ %quantity @ " 100"); } else { echo("## Adding 30 Basic Bolts - Q100 ##"); cmChatCommand('@', "/ADD 662 30 100"); } } function dullbolt(%quantity) { if(%quantity){ echo("## Adding " @ %quantity @ " Dull Bolts - Q100 ##"); cmChatCommand('@', "/ADD 663 " @ %quantity @ " 100"); } else { echo("## Adding 30 Dull Bolts - Q100 ##"); cmChatCommand('@', "/ADD 663 30 100"); } } function heavybolt(%quantity) { if(%quantity){ echo("## Adding " @ %quantity @ " Heavy Bolts - Q100 ##"); cmChatCommand('@', "/ADD 664 " @ %quantity @ " 100"); } else { echo("## Adding 30 Heavy Bolts - Q100 ##"); cmChatCommand('@', "/ADD 664 30 100"); } } function fireworkbolt(%quantity) { if(%quantity){ echo("## Adding " @ %quantity @ " Firework Bolts - Q100 ##"); cmChatCommand('@', "/ADD 1340 " @ %quantity @ " 100"); } else { echo("## Adding 30 Firework Bolts - Q100 ##"); cmChatCommand('@', "/ADD 1340 30 100"); } } // Siege function stoneammo(%quality) { if(%quantity){ echo("## Adding 1 Stone ammo - Q" @%quality @ " ##"); cmChatCommand('@', "/ADD 1107 1 " @ %quality); } else { echo("## Adding 1 Stone ammo - Q100 ##"); cmChatCommand('@', "/ADD 1107 1 100"); } } // Shields function targe(%quality) { if(%quality){ echo("## Adding Targe Shield - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 612 1 " @ %quality @ "100000"); } else { echo("## Adding Targe Shield - Q100 ##"); cmChatCommand('@', "/ADD 612 1 100 1000000"); } } function heavytarge(%quality) { if(%quality){ echo("## Adding Heavy Targe Shield - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 1066 1 " @ %quality @ "100000"); } else { echo("## Adding Heavy Targe Shield - Q100 ##"); cmChatCommand('@', "/ADD 1066 1 100 1000000"); } } function heater(%quality) { if(%quality){ echo("## Adding Heater Shield - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 615 1 " @ %quality @ "1000000"); } else { echo("## Adding Heater Shield - Q100 ##"); cmChatCommand('@', "/ADD 615 1 100 1000000"); } } function kite(%quality) { if(%quality){ echo("## Adding Kite Shield - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 616 1 " @ %quality @ "100000"); } else { echo("## Adding Kite Shield - Q100 ##"); cmChatCommand('@', "/ADD 616 1 100 1000000"); } } function tower(%quality) { if(%quality){ echo("## Adding Tower Shield - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 617 1 " @ %quality @ "100000"); } else { echo("## Adding Tower Shield - Q100 ##"); cmChatCommand('@', "/ADD 617 1 100 1000000"); } } function pavise(%quality) { if(%quality){ echo("## Adding Pavise - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 618 1 " @ %quality @ "100000"); } else { echo("## Adding Pavise - Q100 ##"); cmChatCommand('@', "/ADD 618 1 100 1000000"); } } // Misc function slingammo(%quality) { if(%quality){ echo("## Adding Sling Ammo - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 1096 1 " @ %quality @ "100000"); } else { echo("## Adding Sling Ammo - Q100 ##"); cmChatCommand('@', "/ADD 1096 1 100 100000"); } } function tabard(%quality) { if(%quality){ echo("## Adding Targe Shield - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 1376 1 " @ %quality @ "100000"); } else { echo("## Adding Targe Shield - Q100 ##"); cmChatCommand('@', "/ADD 1376 1 100 1000000"); } } function gold() { echo("## Adding Gold Ingot ##"); cmChatCommand('@', "/ADD 406 1 100"); } // Horses function warhorse(%quality) { if(%quality){ echo("## Adding Warhorse - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 1042 1 " @ %quality); } else { echo("## Adding Warhorse - Q100 ##"); cmChatCommand('@', "/ADD 1042 1 100"); } } function spirited(%quality) { if(%quality){ echo("## Adding Spirited Warhorse - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 1043 1 " @ %quality); } else { echo("## Adding Spirited Warhorse - Q100 ##"); cmChatCommand('@', "/ADD 1043 1 100"); } } function hardy(%quality) { if(%quality){ echo("## Adding Hardy Warhorse - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 1044 1 " @ %quality); } else { echo("## Adding Hardy Warhorse - Q100 ##"); cmChatCommand('@', "/ADD 1044 1 100"); } } function heavy(%quality) { if(%quality){ echo("## Adding Heavy Warhorse - Q" @ %quality @ " ##"); cmChatCommand('@', "/ADD 1045 1 " @ %quality); } else { echo("## Adding Heavy Warhorse - Q100 ##"); cmChatCommand('@', "/ADD 1045 1 100"); } }
mit
Ruby-SG/simple_datatable
app/helpers/simple_datatable/application_helper.rb
480
module SimpleDatatable module ApplicationHelper def simple_datatable(cols = [], html_options = {}) html_options[:class] ||= '' html_options[:class] << 'dataTable' content_tag :table, html_options do content_tag :thead do content_tag :tr do cols.each_with_object('') do |col, html| html << content_tag(:th, col.capitalize) end.html_safe end end end.html_safe end end end
mit
flowcommerce/delta
www/app/controllers/TokensController.scala
3195
package controllers import io.flow.delta.v0.errors.UnitResponse import io.flow.delta.v0.models.{Token, TokenForm} import io.flow.delta.www.lib.DeltaClientProvider import io.flow.play.controllers.{FlowControllerComponents, IdentifiedRequest} import io.flow.play.util.{Config, PaginatedCollection, Pagination} import scala.concurrent.{ExecutionContext, Future} import play.api.mvc._ import play.api.data._ import play.api.data.Forms._ class TokensController @javax.inject.Inject() ( val config: Config, deltaClientProvider: DeltaClientProvider, controllerComponents: ControllerComponents, flowControllerComponents: FlowControllerComponents )(implicit ec: ExecutionContext) extends controllers.BaseController(deltaClientProvider, controllerComponents, flowControllerComponents) { override def section = None def index(page: Int = 0) = User.async { implicit request => for { tokens <- deltaClient(request).tokens.get( limit = Pagination.DefaultLimit.toLong + 1L, offset = page * Pagination.DefaultLimit.toLong ) } yield { Ok(views.html.tokens.index(uiData(request), PaginatedCollection(page, tokens))) } } def show(id: String) = User.async { implicit request => withToken(request, id) { token => Future { Ok(views.html.tokens.show(uiData(request), token)) } } } def create() = User { implicit request => Ok(views.html.tokens.create(uiData(request), TokensController.tokenForm)) } def postCreate = User.async { implicit request => val form = TokensController.tokenForm.bindFromRequest() form.fold ( errors => Future { Ok(views.html.tokens.create(uiData(request), errors)) }, valid => { deltaClient(request).tokens.post( TokenForm( userId = request.user.id, description = valid.description ) ).map { token => Redirect(routes.TokensController.show(token.id)).flashing("success" -> "Token created") }.recover { case r: io.flow.delta.v0.errors.GenericErrorResponse => { Ok(views.html.tokens.create(uiData(request), form, r.genericError.messages)) } } } ) } def postDelete(id: String) = User.async { implicit request => deltaClient(request).tokens.deleteById(id).map { _ => Redirect(routes.TokensController.index()).flashing("success" -> s"Token deleted") }.recover { case UnitResponse(404) => { Redirect(routes.TokensController.index()).flashing("warning" -> s"Token not found") } } } def withToken[T]( request: IdentifiedRequest[T], id: String )( f: Token => Future[Result] ) = { deltaClient(request).tokens.getById(id).flatMap { token => f(token) }.recover { case UnitResponse(404) => { Redirect(routes.TokensController.index()).flashing("warning" -> s"Token not found") } } } } object TokensController { case class TokenData( description: Option[String] ) private[controllers] val tokenForm = Form( mapping( "description" -> optional(nonEmptyText) )(TokenData.apply)(TokenData.unapply) ) }
mit
amironov73/ManagedIrbis
Source/Classic/Libs/ManagedIrbis/Source/Quality/Rules/Check10.cs
2597
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /* Check10.cs -- ISBN и цена. * Ars Magna project, http://arsmagna.ru * ------------------------------------------------------- * Status: poor */ #region Using directives using System.Text.RegularExpressions; using AM; using JetBrains.Annotations; using MoonSharp.Interpreter; #endregion namespace ManagedIrbis.Quality.Rules { /// <summary> /// ISBN и цена. /// </summary> [PublicAPI] [MoonSharpUserData] public sealed class Check10 : QualityRule { #region Private members private void CheckField ( RecordField field ) { MustNotContainText(field); SubField isbn = field.GetFirstSubField('a'); if (isbn != null) { if (isbn.Value.SafeContains("(", " ", ".", ";", "--")) { AddDefect ( field, isbn, 1, "Неверно введен ISBN в поле 10" ); } } SubField price = field.GetFirstSubField('d'); if (price != null) { if (!Regex.IsMatch ( price.Value.ThrowIfNull("price.Value"), @"\d+\.\d{2}" )) { AddDefect ( field, price, 5, "Неверный формат цены в поле 10" ); } } } #endregion #region QualityRule members /// <inheritdoc cref="QualityRule.FieldSpec" /> public override string FieldSpec { get { return "10"; } } /// <inheritdoc cref="QualityRule.CheckRecord" /> public override RuleReport CheckRecord ( RuleContext context ) { BeginCheck(context); RecordField[] fields = GetFields(); foreach (RecordField field in fields) { CheckField(field); } return EndCheck(); } #endregion } }
mit
sosuke-k/cornel-movie-dialogs-corpus-storm
mdcorpus/examples/conversation_and_line.py
1117
#! /usr/bin/env python # -*- coding: utf-8 -*- from storm.locals import * from mdcorpus.orm import * database = create_database("sqlite:") store = Store(database) store.execute(MovieConversation.CREATE_SQL) store.execute(MovieLine.CREATE_SQL) conversation = store.add(MovieConversation(0, 2, 0)) line194 = store.add(MovieLine( 194, "Can we make this quick? Roxanne Korrine and Andrew Barrett are having an incredibly horrendous public break- up on the quad. Again.")) line195 = store.add(MovieLine( 195, "Well, I thought we'd start with pronunciation, if that's okay with you.")) line196 = store.add(MovieLine( 196, "Not the hacking and gagging and spitting part. Please.")) line197 = store.add(MovieLine( 197, "Okay... then how 'bout we try out some French cuisine. Saturday? Night?")) store.flush() line_id_list = [194, 195, 196, 197] for (i, line_id) in enumerate(line_id_list): line = store.find(MovieLine, MovieLine.id == line_id).one() line.number = i + 1 conversation.lines.add(line) store.commit() for line in conversation.line_list(): print "'" + line.text + "'"
mit
seekmas/makoto.local
app/cache/prod/twig/cd/db/19282cb43ee68e0c31ea17292c7e80a739fbdee92fffebcbafc6f482f4d4.php
1726
<?php /* TwigBundle:Exception:error.js.twig */ class __TwigTemplate_cddb19282cb43ee68e0c31ea17292c7e80a739fbdee92fffebcbafc6f482f4d4 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 echo "/* "; // line 2 echo twig_escape_filter($this->env, (isset($context["status_code"]) ? $context["status_code"] : null), "html", null, true); echo " "; echo twig_escape_filter($this->env, (isset($context["status_text"]) ? $context["status_text"] : null), "html", null, true); echo " */ "; } public function getTemplateName() { return "TwigBundle:Exception:error.js.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 25 => 3, 31 => 5, 26 => 3, 98 => 40, 93 => 9, 88 => 6, 78 => 40, 46 => 7, 44 => 9, 32 => 9, 27 => 4, 22 => 2, 43 => 8, 40 => 8, 35 => 4, 29 => 4, 21 => 2, 19 => 1, 209 => 82, 203 => 78, 199 => 76, 193 => 73, 189 => 71, 187 => 70, 182 => 68, 176 => 64, 173 => 63, 168 => 62, 164 => 60, 162 => 59, 154 => 54, 149 => 51, 147 => 50, 144 => 49, 141 => 48, 133 => 42, 130 => 41, 125 => 38, 122 => 37, 116 => 36, 112 => 35, 109 => 34, 106 => 33, 103 => 32, 99 => 30, 95 => 28, 92 => 27, 86 => 24, 82 => 22, 80 => 41, 73 => 19, 64 => 15, 60 => 13, 57 => 12, 54 => 11, 51 => 10, 48 => 9, 45 => 8, 42 => 7, 39 => 8, 36 => 7, 33 => 4, 30 => 3,); } }
mit
kenyonduan/amazon-mws
src/main/java/com/amazonservices/mws/jaxb/BuyerPrice.java
6758
package com.amazonservices.mws.jaxb; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>BuyerPrice complex type的 Java 类。 * * <p>以下模式片段指定包含在此类中的预期内容。 * * <pre> * &lt;complexType name="BuyerPrice"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Component" maxOccurs="unbounded"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Type"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="Principal"/> * &lt;enumeration value="Shipping"/> * &lt;enumeration value="CODFee"/> * &lt;enumeration value="Tax"/> * &lt;enumeration value="ShippingTax"/> * &lt;enumeration value="RestockingFee"/> * &lt;enumeration value="RestockingFeeTax"/> * &lt;enumeration value="GiftWrap"/> * &lt;enumeration value="GiftWrapTax"/> * &lt;enumeration value="Surcharge"/> * &lt;enumeration value="ReturnShipping"/> * &lt;enumeration value="Goodwill"/> * &lt;enumeration value="ExportCharge"/> * &lt;enumeration value="COD"/> * &lt;enumeration value="CODTax"/> * &lt;enumeration value="Other"/> * &lt;enumeration value="FreeReplacementReturnShipping"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="Amount" type="{}CurrencyAmount"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "BuyerPrice", propOrder = { "component" }) public class BuyerPrice { @XmlElement(name = "Component", required = true) protected List<Component> component; /** * Gets the value of the component property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the component property. * * <p> * For example, to add a new item, do as follows: * <pre> * getComponent().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Component } * * */ public List<Component> getComponent() { if (component == null) { component = new ArrayList<Component>(); } return this.component; } /** * <p>anonymous complex type的 Java 类。 * * <p>以下模式片段指定包含在此类中的预期内容。 * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Type"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="Principal"/> * &lt;enumeration value="Shipping"/> * &lt;enumeration value="CODFee"/> * &lt;enumeration value="Tax"/> * &lt;enumeration value="ShippingTax"/> * &lt;enumeration value="RestockingFee"/> * &lt;enumeration value="RestockingFeeTax"/> * &lt;enumeration value="GiftWrap"/> * &lt;enumeration value="GiftWrapTax"/> * &lt;enumeration value="Surcharge"/> * &lt;enumeration value="ReturnShipping"/> * &lt;enumeration value="Goodwill"/> * &lt;enumeration value="ExportCharge"/> * &lt;enumeration value="COD"/> * &lt;enumeration value="CODTax"/> * &lt;enumeration value="Other"/> * &lt;enumeration value="FreeReplacementReturnShipping"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="Amount" type="{}CurrencyAmount"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "type", "amount" }) public static class Component { @XmlElement(name = "Type", required = true) protected String type; @XmlElement(name = "Amount", required = true) protected CurrencyAmount amount; /** * 获取type属性的值。 * * @return * possible object is * {@link String } * */ public String getType() { return type; } /** * 设置type属性的值。 * * @param value * allowed object is * {@link String } * */ public void setType(String value) { this.type = value; } /** * 获取amount属性的值。 * * @return * possible object is * {@link CurrencyAmount } * */ public CurrencyAmount getAmount() { return amount; } /** * 设置amount属性的值。 * * @param value * allowed object is * {@link CurrencyAmount } * */ public void setAmount(CurrencyAmount value) { this.amount = value; } } }
mit
sapegin/mrm
packages/mrm-core/src/__tests__/npm.spec.js
14055
jest.mock('fs'); jest.mock('../util/log', () => ({ info: jest.fn(), })); const fs = require('fs-extra'); const vol = require('memfs').vol; const log = require('../util/log'); const _npm = require('../npm'); const install = _npm.install; const uninstall = _npm.uninstall; const modules = ['eslint', 'babel-core']; const options = { cwd: undefined, stdio: 'inherit', }; const createPackageJson = (dependencies, devDependencies) => { fs.writeFileSync( 'package.json', JSON.stringify({ dependencies, devDependencies, }) ); }; const createNodeModulesPackageJson = (name, version) => { fs.mkdirpSync(`/node_modules/${name}`); fs.writeFileSync( `/node_modules/${name}/package.json`, JSON.stringify({ version, }) ); }; afterEach(() => { vol.reset(); log.info.mockClear(); }); describe('install()', () => { it('should install an npm packages to devDependencies', () => { const spawn = jest.fn(); createPackageJson({}, {}); install(modules, undefined, spawn); expect(spawn).toBeCalledWith( expect.stringMatching(/npm(\.cmd)?/), ['install', '--save-dev', 'eslint@latest', 'babel-core@latest'], options ); }); it('should install yarn packages to devDependencies', () => { const spawn = jest.fn(); createPackageJson({}, {}); install(modules, { yarn: true }, spawn); expect(spawn).toBeCalledWith( expect.stringMatching(/yarn(\.cmd)?/), [ 'add', '--dev', '--ignore-workspace-root-check', 'eslint@latest', 'babel-core@latest', ], options ); }); it('should install yarn@berry packages to devDependencies', () => { const spawn = jest.fn(); createPackageJson({}, {}); install(modules, { yarnBerry: true }, spawn); expect(spawn).toBeCalledWith( expect.stringMatching(/yarn(\.cmd)?/), ['add', '--dev', 'eslint@latest', 'babel-core@latest'], options ); }); it('should install a pnpm packages to devDependencies', () => { const spawn = jest.fn(); createPackageJson({}, {}); install(modules, { pnpm: true }, spawn); expect(spawn).toBeCalledWith( expect.stringMatching(/pnpm(\.cmd)?/), ['install', '--save-dev', 'eslint@latest', 'babel-core@latest'], options ); }); it('should install an npm packages to dependencies', () => { const spawn = jest.fn(); createPackageJson({}, {}); install(modules, { dev: false }, spawn); expect(spawn).toBeCalledWith( expect.stringMatching(/npm(\.cmd)?/), ['install', '--save', 'eslint@latest', 'babel-core@latest'], options ); }); it('should install yarn packages to dependencies', () => { const spawn = jest.fn(); createPackageJson({}, {}); install(modules, { dev: false, yarn: true }, spawn); expect(spawn).toBeCalledWith( expect.stringMatching(/yarn(\.cmd)?/), [ 'add', '--ignore-workspace-root-check', 'eslint@latest', 'babel-core@latest', ], options ); }); it('should install yarn@berry packages to dependencies', () => { const spawn = jest.fn(); createPackageJson({}, {}); install(modules, { dev: false, yarnBerry: true }, spawn); expect(spawn).toBeCalledWith( expect.stringMatching(/yarn(\.cmd)?/), ['add', 'eslint@latest', 'babel-core@latest'], options ); }); it('should install a pnpm packages to dependencies', () => { const spawn = jest.fn(); createPackageJson({}, {}); install(modules, { dev: false, pnpm: true }, spawn); expect(spawn).toBeCalledWith( expect.stringMatching(/pnpm(\.cmd)?/), ['install', '--save', 'eslint@latest', 'babel-core@latest'], options ); }); it('should run Yarn if project is already using Yarn', () => { const spawn = jest.fn(); fs.writeFileSync('yarn.lock', ''); createPackageJson({}, {}); install(modules, undefined, spawn); expect(spawn).toBeCalledWith( expect.stringMatching(/yarn(\.cmd)?/), [ 'add', '--dev', '--ignore-workspace-root-check', 'eslint@latest', 'babel-core@latest', ], { cwd: undefined, stdio: 'inherit', } ); }); it('should run Yarn Berry if project is already using Yarn Berry', () => { const spawn = jest.fn(); fs.writeFileSync('yarn.lock', ''); fs.writeFileSync('.yarnrc.yml', ''); createPackageJson({}, {}); install(modules, undefined, spawn); expect(spawn).toBeCalledWith( expect.stringMatching(/yarn(\.cmd)?/), ['add', '--dev', 'eslint@latest', 'babel-core@latest'], { cwd: undefined, stdio: 'inherit', } ); }); it('should not install already installed packages', () => { const spawn = jest.fn(); createNodeModulesPackageJson('eslint', '4.2.0'); createPackageJson({}, { eslint: '*' }); install(modules, undefined, spawn); expect(spawn).toBeCalledWith( expect.stringMatching(/npm(\.cmd)?/), ['install', '--save-dev', 'babel-core@latest'], options ); }); it('should accept the first parameter as a string', () => { const spawn = jest.fn(); createPackageJson({}, {}); install(modules[0], undefined, spawn); expect(spawn).toBeCalledWith( expect.stringMatching(/npm(\.cmd)?/), ['install', '--save-dev', `${modules[0]}@latest`], options ); }); it('should not run npm when there are no new packages', () => { const spawn = jest.fn(); createNodeModulesPackageJson('eslint', '4.2.0'); createNodeModulesPackageJson('babel-core', '7.1.0'); createPackageJson( {}, { eslint: '*', 'babel-core': '*', } ); install(modules, undefined, spawn); expect(spawn).toHaveBeenCalledTimes(0); }); it('should install packages that are in node_modules but not in package.json', () => { const spawn = jest.fn(); createNodeModulesPackageJson('eslint', '4.2.0'); createNodeModulesPackageJson('babel-core', '7.1.0'); createPackageJson( {}, { eslint: '*', } ); install(modules, undefined, spawn); expect(spawn).toBeCalledWith( expect.stringMatching(/npm(\.cmd)?/), ['install', '--save-dev', 'babel-core@latest'], options ); }); it('should update packages if newer versions are required', () => { const versions = { eslint: '^5.0.0', 'babel-core': '7.1.0', }; const spawn = jest.fn(); createNodeModulesPackageJson('eslint', '4.2.0'); createNodeModulesPackageJson('babel-core', '7.1.0'); createPackageJson( {}, { eslint: '*', 'babel-core': '*', } ); install(modules, { versions }, spawn); expect(spawn).toBeCalledWith( expect.stringMatching(/npm(\.cmd)?/), [ 'install', '--save-dev', // Since the result depend on the platform // we need to allow both output expect.stringMatching(/eslint@(\^{1}|\^{4})5.0.0/), ], options ); }); it('should accept dependencies list as an object', () => { const versions = { eslint: '^5.0.0', 'babel-core': '7.1.0', prettier: '^1.1.0', }; const spawn = jest.fn(); createNodeModulesPackageJson('eslint', '4.2.0'); createNodeModulesPackageJson('babel-core', '7.1.0'); createPackageJson( {}, { eslint: '*', 'babel-core': '*', } ); install(versions, undefined, spawn); expect(spawn).toBeCalledWith( expect.stringMatching(/npm(\.cmd)?/), [ 'install', '--save-dev', // Since the result depend on the platform // we need to allow both output expect.stringMatching(/eslint@(\^{1}|\^{4})5.0.0/), expect.stringMatching(/prettier@(\^{1}|\^{4})1.1.0/), ], options ); }); it('should throw when version is invalid version', () => { const spawn = jest.fn(); createNodeModulesPackageJson('eslint', '4.2.0'); const fn = () => install({ eslint: 'pizza' }, undefined, spawn); expect(fn).toThrow('Invalid npm version'); }); it('should not throw when version is valid range', () => { const spawn = jest.fn(); createNodeModulesPackageJson('eslint', '4.2.0'); const fn = () => install({ eslint: '~4.2.0' }, undefined, spawn); expect(fn).not.toThrow('Invalid npm version'); }); it.each([ ['github', 'github/package'], ['github https', 'https://github.com/user/package/tarball/v0.0.1'], ['github protocol', 'github:mygithubuser/myproject'], ['gist', 'gist:101a11beef'], ['bitbucket protocol', 'bitbucket:mybitbucketuser/myproject'], ])( 'should not automatically add version data to non-registry installs: %s', (name, resource) => { const spawn = jest.fn(); install([resource], undefined, spawn); expect(spawn).toBeCalledWith( expect.stringMatching(/npm(\.cmd)?/), ['install', '--save-dev', resource], options ); } ); it.each([ ['github', 'github/package', '1.0.0'], [ 'github https', 'https://github.com/user/package/tarball/v0.0.1', '>=2.0.0', ], ['github protocol', 'github:mygithubuser/myproject', '>3.0.0'], ['gist', 'gist:101a11beef', '4.0.0'], ['bitbucket protocol', 'bitbucket:mybitbucketuser/myproject', '5.0.0'], ])( 'should not automatically add version data to non-registry installs: %s', (name, resource, version) => { const spawn = jest.fn(); const matcher = new RegExp(`^${resource}#semver:${version}$`); install({ [resource]: version }, undefined, spawn); expect(spawn).toBeCalledWith( expect.stringMatching(/npm(\.cmd)?/), ['install', '--save-dev', expect.stringMatching(matcher)], options ); } ); it('should not throw when package.json not found', () => { const spawn = jest.fn(); const fn = () => install(modules, undefined, spawn); expect(fn).not.toThrow(); }); it('should not throw when package.json has no dependencies section', () => { const spawn = jest.fn(); createPackageJson(); const fn = () => install(modules, undefined, spawn); expect(fn).not.toThrow(); }); it('should print module names', () => { install(modules, undefined, () => {}); expect(log.info).toBeCalledWith('Installing eslint and babel-core...'); }); it('should print only module names that are not installed', () => { createNodeModulesPackageJson('eslint', '4.2.0'); createPackageJson( {}, { eslint: '*', } ); install(modules, undefined, () => {}); expect(log.info).toBeCalledWith('Installing babel-core...'); }); }); describe('uninstall()', () => { it('should uninstall npm packages from devDependencies', () => { const spawn = jest.fn(); createPackageJson( {}, { eslint: '*', 'babel-core': '*', } ); uninstall(modules, undefined, spawn); expect(spawn).toBeCalledWith( expect.stringMatching(/npm(\.cmd)?/), ['uninstall', '--save-dev', 'eslint', 'babel-core'], options ); }); it('should uninstall yarn packages from devDependencies', () => { const spawn = jest.fn(); createPackageJson( {}, { eslint: '*', 'babel-core': '*', } ); uninstall(modules, { yarn: true }, spawn); expect(spawn).toBeCalledWith( expect.stringMatching(/yarn(\.cmd)?/), ['remove', 'eslint', 'babel-core'], options ); }); it('should uninstall pnpm packages from devDependencies', () => { const spawn = jest.fn(); createPackageJson( {}, { eslint: '*', 'babel-core': '*', } ); uninstall(modules, { pnpm: true }, spawn); expect(spawn).toBeCalledWith( expect.stringMatching(/npm(\.cmd)?/), ['uninstall', '--save-dev', 'eslint', 'babel-core'], options ); }); it('should uninstall npm packages from dependencies', () => { const spawn = jest.fn(); createPackageJson( { eslint: '*', 'babel-core': '*', }, {} ); uninstall(modules, { dev: false }, spawn); expect(spawn).toBeCalledWith( expect.stringMatching(/npm(\.cmd)?/), ['uninstall', '--save', 'eslint', 'babel-core'], options ); }); it('should uninstall yarn packages from dependencies', () => { const spawn = jest.fn(); createPackageJson( { eslint: '*', 'babel-core': '*', }, {} ); uninstall(modules, { dev: false, yarn: true }, spawn); expect(spawn).toBeCalledWith( expect.stringMatching(/yarn(\.cmd)?/), ['remove', 'eslint', 'babel-core'], options ); }); it('should run Yarn if project is already using Yarn', () => { const spawn = jest.fn(); fs.writeFileSync('yarn.lock', ''); createPackageJson( {}, { eslint: '*', } ); uninstall(modules, undefined, spawn); expect(spawn).toBeCalledWith( expect.stringMatching(/yarn(\.cmd)?/), ['remove', 'eslint'], { cwd: undefined, stdio: 'inherit', } ); }); it('should not uninstall not installed packages', () => { const spawn = jest.fn(); createPackageJson({}, { eslint: '*' }); uninstall(modules, undefined, spawn); expect(spawn).toBeCalledWith( expect.stringMatching(/npm(\.cmd)?/), ['uninstall', '--save-dev', 'eslint'], options ); }); it('should accept the first parameter as a string', () => { const spawn = jest.fn(); createPackageJson( {}, { eslint: '*', } ); uninstall(modules[0], undefined, spawn); expect(spawn).toBeCalledWith( expect.stringMatching(/npm(\.cmd)?/), ['uninstall', '--save-dev', modules[0]], options ); }); it('should not run npm when there are no packages to uninstall', () => { const spawn = jest.fn(); createPackageJson({}, {}); uninstall(modules, undefined, spawn); expect(spawn).toHaveBeenCalledTimes(0); }); it('should not throw when package.json not found', () => { const spawn = jest.fn(); const fn = () => uninstall(modules, undefined, spawn); expect(fn).not.toThrow(); }); it('should not throw when package.json has no dependencies section', () => { const spawn = jest.fn(); createPackageJson(); const fn = () => uninstall(modules, undefined, spawn); expect(fn).not.toThrow(); }); it('should print module names', () => { createPackageJson( {}, { eslint: '*', 'babel-core': '*', } ); uninstall(modules, undefined, () => {}); expect(log.info).toBeCalledWith('Uninstalling eslint and babel-core...'); }); it('should print only module names that are installed', () => { createPackageJson( {}, { eslint: '*', } ); uninstall(modules, undefined, () => {}); expect(log.info).toBeCalledWith('Uninstalling eslint...'); }); });
mit
pwim/docomo_css
test/docomo_css/filter_test.rb
6838
require 'test_helper' require File.join File.dirname(__FILE__), '..', '..', 'lib', 'docomo_css', 'filter' class DocomoCss::FilterTest < Test::Unit::TestCase def setup @filter = DocomoCss::Filter.new end def test_invalid_response_content_type response = mock("invalid_response") do expects(:content_type).returns('text/html').once expects(:body).never end controller = stub("invalid_controller", :response => response) @filter.after(controller) end def test_escape_numeric_character_reference assert_equal "HTMLCSSINLINERESCAPE123456789::::::::", @filter.escape_numeric_character_reference("&#123456789;") assert_equal "HTMLCSSINLINERESCAPEx123def::::::::", @filter.escape_numeric_character_reference("&#x123def;") end def test_unescape_numeric_character_reference assert_equal "&#123456789;", @filter.unescape_numeric_character_reference("HTMLCSSINLINERESCAPE123456789::::::::") assert_equal "&#x123def;", @filter.unescape_numeric_character_reference("HTMLCSSINLINERESCAPEx123def::::::::") end def test_pseudo_selectors css = TinyCss.new.read_string(<<-CSS) a:visited { color: FF00FF; } CSS assert_equal ["a:visited"], @filter.pseudo_selectors(css) css = TinyCss.new.read_string(<<-CSS) .purple { color: FF00FF; } CSS assert_equal [], @filter.pseudo_selectors(css) end def test_stylesheet_link_node doc = Nokogiri::HTML(<<-HTML) <link href="a.css"/> <link href="b.css" rel="stylesheet"/> HTML @filter.stylesheet_link_node(doc).each do |node| assert_equal 'b.css', node['href'] end end def test_extract_pseudo_style css = TinyCss.new.read_string <<-CSS a:link { color: red; } a:focus { color: green; } a:visited { color: blue; } div.title { background-color: #999 } CSS pseudo_style = @filter.extract_pseudo_style css assert_equal('red', pseudo_style.style['a:link']['color']) assert_equal('green', pseudo_style.style['a:focus']['color']) assert_equal('blue', pseudo_style.style['a:visited']['color']) assert_equal('#999', css.style['div.title']['background-color']) end def test_embed_pseudo_style css = TinyCss.new assert_equal nil, @filter.embed_pseudo_style(nil, css) css = TinyCss.new.read_string <<-CSS a:link { color: red; } a:focus { color: green; } a:visited { color: blue; } CSS doc = Nokogiri::HTML <<-HTML <html> <head></head> <body></body> </html> HTML doc = @filter.embed_pseudo_style doc, css assert_match %r'<style .*?/style>'m, doc.to_xhtml doc = Nokogiri::HTML <<-HTML <html> <body></body> </html> HTML assert_raise RuntimeError do @filter.embed_pseudo_style doc, css end end def test_embed_style css = TinyCss.new.read_string <<-CSS .title { color: red; } CSS doc = Nokogiri::HTML <<-HTML <html> <body> <div class="title">bar</div> </body> </html> HTML @filter.embed_style doc, css assert_match %r'style="color:red"', doc.to_xhtml doc = Nokogiri::HTML <<-HTML <html> <body> <div class="title" style="background-color:black">bar</div> </body> </html> HTML @filter.embed_style doc, css assert_match %r'style="background-color:black;color:red"', doc.to_xhtml doc = Nokogiri::HTML <<-HTML <html> <body> <div class="title" style="background-color:silver;">bar</div> </body> </html> HTML @filter.embed_style doc, css assert_match %r'style="background-color:silver;color:red"', doc.to_xhtml end def test_embed_style_in_multiple_h1s css = TinyCss.new.read_string("h1 { color: red; }") doc = Nokogiri::HTML("<h1>foo</h1><h1>bar</h1>") @filter.embed_style doc, css assert_match '<span style="color:red">foo</span>', doc.search('h1')[0].children.to_xhtml assert_match '<span style="color:red">bar</span>', doc.search('h1')[1].children.to_xhtml end def test_xml_declare doc = stub("doc", :encoding => "Shift_JIS") assert_equal <<-XML, @filter.xml_declare(doc) <?xml version="1.0" encoding="Shift_JIS"?> XML doc = stub("doc", :encoding => "UTF-8") assert_equal <<-XML, @filter.xml_declare(doc) <?xml version="1.0" encoding="UTF-8"?> XML end def test_remove_xml_declare assert_equal '', @filter.remove_xml_declare('<?xml version="1.0"?>') assert_equal '', @filter.remove_xml_declare('<?xml encoding="Shift_JIS"?>') assert_equal '', @filter.remove_xml_declare('<?xml version="1.0" encoding="Shift_JIS" ?>') assert_equal '', @filter.remove_xml_declare('<?xml?>') end def test_output_with_docomo_1_0_browser request = stub('request', :user_agent => 'DoCoMo/2.0 D905i(c100;TB;W24H17)') response = stub("response") do expects(:content_type).returns('application/xhtml+xml') expects(:body).returns(File.open(File.join(File.dirname(__FILE__), '../actual.html'), 'rb'){ |f| f.read }) expects(:body=).with(File.open(File.join(File.dirname(__FILE__), '../expected.html'), 'rb'){ |f| f.read }) end controller = stub("controller", :response => response, :request => request) @filter.after(controller) end def test_output_with_docomo_1_0_browser_and_utf8_charset request = stub('request', :user_agent => 'DoCoMo/2.0 D905i(c100;TB;W24H17)') response = stub("response") do expects(:content_type).returns('application/xhtml+xml; charset=utf-8') expects(:body).returns(File.open(File.join(File.dirname(__FILE__), '../actual.html'), 'rb'){ |f| f.read }) expects(:body=).with(File.open(File.join(File.dirname(__FILE__), '../expected.html'), 'rb'){ |f| f.read }) end controller = stub("controller", :response => response, :request => request) @filter.after(controller) end def test_output_with_docomo_2_0_browser request = stub('request', :user_agent => 'DoCoMo/2.0 N03B(c500;TB;W24H16)') response = stub("response") do expects(:content_type).returns('application/xhtml+xml') expects(:body).never end controller = stub("controller", :response => response, :request => request) @filter.after(controller) end def test_embed_css_detects_missing_character_encoding xml = <<-EOD <?xml version='1.0' encoding='utf-8' ?> <!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd"> <html lang='ja' xml:lang='ja' xmlns='http://www.w3.org/1999/xhtml'> <head> </head> <body> ほげ </body> </html> EOD encoded_body = @filter.embed_css(xml) assert_match "ほげ", encoded_body assert_match '<meta content="application/xhtml+xml;charset=UTF-8" http-equiv="content-type" />', encoded_body assert_match '<!-- Please explicitly specify the encoding of your document as below. Assuming UTF-8. -->', encoded_body end end
mit
offmbs/Open-GDR
database/migrations/2014_10_12_000000_create_users_table.php
1332
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->bigInteger('level')->default(0); $table->boolean('banned')->default(false); $table->dateTime('banned_at', 0)->nullable(); $table->string('name')->nullable(); $table->string('surname')->nullable(); $table->date('date_of_birth')->nullable(); $table->string('motto')->nullable(); $table->longText('description')->nullable(); //todo: aggiungiamo i social link all'utente? //$table->json('socials')->nullable(); $table->rememberToken(); $table->timestamps(); $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } }
mit
Scottell/salmon-mvc
web/classes/Login.class.php
308
<?php class Login { public static function isLoggedIn() { $key = 'loggedin'; session_start(); if (isset($_SESSION[$key])) { return true; } if ($_POST['pw'] == 'password') { $_SESSION[$key] = true; Mvcer::postHandled(); return true; } return false; } } ?>
mit
mbuhot/mbuhot-euler-solutions
python/problem-041.py
687
#! /usr/bin/env python3 import prime from itertools import permutations description = """ Pandigital prime Problem 41 We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime. What is the largest n-digit pandigital prime that exists? """ def digitsToInt(l): return sum(d*10**i for (i,d) in enumerate(reversed(l))) assert(digitsToInt([1,5,3,2,4]) == 15324) pandigitals = (digitsToInt(perm) for n in range(2, 10) for perm in permutations(range(1, n+1))) primePandigitals = filter(prime.isPrime, pandigitals) print(max(primePandigitals))
mit
yogeshsaroya/new-cdnjs
ajax/libs/mediaelement/2.10.2/mediaelement.js
130
version https://git-lfs.github.com/spec/v1 oid sha256:e703012675ae8feb9a5eb413146c4acf4740731a2693e0d51a674096a45e416c size 53160
mit
soulteary/xSwitch.js
demo/assets/preload-1.0.0.js
29
console.log('preload 1.0.0');
mit
jaysonthepirate/MHGenDatabase
app/src/main/java/com/ghstudios/android/data/database/ItemToSkillTreeCursor.java
2879
package com.ghstudios.android.data.database; import android.database.Cursor; import android.database.CursorWrapper; import com.ghstudios.android.data.classes.Item; import com.ghstudios.android.data.classes.ItemToSkillTree; import com.ghstudios.android.data.classes.SkillTree; /** * A convenience class to wrap a cursor that returns rows from the "item_to_skill_tree" * table. The {@link getItemToSkillTree()} method will give you a ItemToSkillTree instance * representing the current row. */ public class ItemToSkillTreeCursor extends CursorWrapper { public ItemToSkillTreeCursor(Cursor c) { super(c); } /** * Returns a ItemToSkillTree object configured for the current row, or null if the * current row is invalid. */ public ItemToSkillTree getItemToSkillTree() { if (isBeforeFirst() || isAfterLast()) return null; ItemToSkillTree itemToSkillTree = new ItemToSkillTree(); long id = getLong(getColumnIndex(S.COLUMN_ITEM_TO_SKILL_TREE_ID)); int points = getInt(getColumnIndex(S.COLUMN_ITEM_TO_SKILL_TREE_POINT_VALUE)); itemToSkillTree.setId(id); itemToSkillTree.setPoints(points); // Get the Item Item item = new Item(); long itemId = getLong(getColumnIndex(S.COLUMN_ITEM_TO_SKILL_TREE_ITEM_ID)); String itemName = getString(getColumnIndex("i" + S.COLUMN_ITEMS_NAME)); // String jpnName = getString(getColumnIndex(S.COLUMN_ITEMS_JPN_NAME)); String type = getString(getColumnIndex(S.COLUMN_ITEMS_TYPE)); int rarity = getInt(getColumnIndex(S.COLUMN_ITEMS_RARITY)); // int carry_capacity = getInt(getColumnIndex(S.COLUMN_ITEMS_CARRY_CAPACITY)); // int buy = getInt(getColumnIndex(S.COLUMN_ITEMS_BUY)); // int sell = getInt(getColumnIndex(S.COLUMN_ITEMS_SELL)); // String description = getString(getColumnIndex(S.COLUMN_ITEMS_DESCRIPTION)); String fileLocation = getString(getColumnIndex(S.COLUMN_ITEMS_ICON_NAME)); // String armor_dupe_name_fix = getString(getColumnIndex(S.COLUMN_ITEMS_ARMOR_DUPE_NAME_FIX)); item.setId(itemId); item.setName(itemName); // item.setJpnName(jpnName); item.setType(type); item.setRarity(rarity); // item.setCarryCapacity(carry_capacity); // item.setBuy(buy); // item.setSell(sell); // item.setDescription(description); item.setFileLocation(fileLocation); // item.setArmorDupeNameFix(armor_dupe_name_fix); itemToSkillTree.setItem(item); // Get the SkillTree SkillTree skillTree = new SkillTree(); long skillTreeId = getLong(getColumnIndex(S.COLUMN_ITEM_TO_SKILL_TREE_SKILL_TREE_ID)); String skillTreeName = getString(getColumnIndex("s" + S.COLUMN_SKILL_TREES_NAME)); // String jpnName = getString(getColumnIndex(S.COLUMN_SKILL_TREES_JPN_NAME)); skillTree.setId(skillTreeId); skillTree.setName(skillTreeName); // skillTree.setJpnName(jpnName); itemToSkillTree.setSkillTree(skillTree); return itemToSkillTree; } }
mit
hoge1e3/Tonyu2
www/js/lib/jquery.keyvalueeditor.js
16328
// https://github.com/hoge1e3/jQuery-KeyValue-Editor // Forked from: https://github.com/a85/jQuery-KeyValue-Editor (function ($) { var methods = { //Not sure if this is needed settings:function () { }, //Initialization init:function (options) { methods.settings = $.extend({}, $.fn.keyvalueeditor.defaults, options); return this.each(function () { var $this = $(this); var data = $this.data('keyvalueeditor'); //Not already initialized if (!data) { data = { settings:methods.settings, editor:$this }; if (data.settings.editableKeys) { var toggleA = methods.getToggleLink(data); var textareaDiv="<div id='keyvalueeditor-textarea-div' style='display:none'><textarea id='keyvalueeditor-textarea' rows='6' cols='55'></textarea></div>"; var h = "<div id='keyvalueeditor-form-div'>" + methods.getLastRow(data); + "</div>"; $this.append(toggleA); $this.append(textareaDiv); $this.append(h); } $this.on("focus.keyvalueeditor", '.keyvalueeditor-last', data, methods.focusEventHandler); $this.on("focus.keyvalueeditor", '.keyvalueeditor-row input', data, methods.rowFocusEventHandler); $this.on("blur.keyvalueeditor", '.keyvalueeditor-row input', data, methods.blurEventHandler); $this.on("blur.keyvalueeditor", '#keyvalueeditor-textarea', data, methods.blurEventHandlerTextArea); $this.on("change.keyvalueeditor", '.keyvalueeditor-valueTypeSelector ', data, methods.valueTypeSelectEventHandler); $this.on("click.keyvalueeditor", '.keyvalueeditor-delete', data, methods.deleteRowHandler); $this.on("click.keyvalueeditor", '.keyvalueeditor-toggle', data, methods.toggleRowHandler); $(this).data('keyvalueeditor', data); } }); }, getLastRow:function (state) { var settings = state.settings; var pKey = settings.placeHolderKey; var pValue = settings.placeHolderValue; var valueTypes = settings.valueTypes; var key = ""; var value = ""; var h; h = '<div class="keyvalueeditor-row keyvalueeditor-last">'; h += '<input tabindex="-1" type="checkbox" class="keyvalueeditor-rowcheck" checked="checked"> '; h += '<input type="text" class="keyvalueeditor-key" placeHolder="' + pKey + '" name="keyvalueeditor-key"' + '"/>'; h += '<input type="text" class="keyvalueeditor-value keyvalueeditor-value-text" placeHolder="' + pValue + '" name="keyvalueeditor-value"' + '"/>'; if ($.inArray("file", valueTypes) >= 0) { h += '<input type="file" multiple class="keyvalueeditor-value keyvalueeditor-value-file" placeHolder="' + pValue + '" name="keyvalueeditor-value' + '" value="' + value + '" style="display: none;"/>'; h += '<select class="keyvalueeditor-valueTypeSelector"><option value="text" selected>Text</option>' + '<option value="file">File</option></select>'; } h += '</div>'; return h; }, getNewRow:function (key, value, type, state) { var settings = state.settings; var pKey = settings.placeHolderKey; var pValue = settings.placeHolderValue; var valueTypes = settings.valueTypes; key = key ? key : ""; value = value ? value : ""; key = key.replace(/'/g, "&apos;").replace(/"/g, "&quot;"); value = value.replace(/'/g, "&apos;").replace(/"/g, "&quot;"); var h; h = '<div class="keyvalueeditor-row">'; h += '<input tabindex="-1" type="checkbox" class="keyvalueeditor-rowcheck" checked="checked"> '; h += '<input type="text" class="keyvalueeditor-key" placeHolder="' + pKey + '" name="keyvalueeditor-' + key + '" value="' + key + '"'; if (!settings.editableKeys) { h += ' data-editable="false"'; h += ' readonly="readonly"'; h += '/>'; } else { h += '"/>'; } if ($.inArray("file", valueTypes) >= 0) { if (type === "file") { h += '<input type="text" class="keyvalueeditor-value keyvalueeditor-value-text" placeHolder="' + pValue + '" name="keyvalueeditor-' + value + '" value="' + value + '" style="display: none;"/>'; h += '<input type="file" multiple class="keyvalueeditor-value keyvalueeditor-value-file" placeHolder="' + pValue + '" name="keyvalueeditor-' + value + '" value="' + value + '"/>'; h += '<select class="keyvalueeditor-valueTypeSelector"><option value="text">Text</option>' + '<option value="file" selected>File</option></select>'; } else { h += '<input type="text" class="keyvalueeditor-value keyvalueeditor-value-text" placeHolder="' + pValue + '" name="keyvalueeditor-' + value + '" value="' + value + '"/>'; h += '<input type="file" multiple class="keyvalueeditor-value keyvalueeditor-value-file" placeHolder="' + pValue + '" name="keyvalueeditor-' + value + '" value="' + value + '" style="display: none;"/>'; h += '<select class="keyvalueeditor-valueTypeSelector"><option value="text" selected>Text</option>' + '<option value="file">File</option></select>'; } } else { h += '<input type="text" class="keyvalueeditor-value keyvalueeditor-value-text" placeHolder="' + pValue + '" name="keyvalueeditor-' + value + '" value="' + value + '"/>'; } h += methods.getDeleteLink(state); h += '</div>'; return h; }, getDeleteLink:function (state) { if (state.settings.editableKeys) { return '<a tabindex="-1" class="keyvalueeditor-delete">' + state.settings.deleteButton + '</a>'; } else { return ""; } }, deleteRowHandler:function (event) { var parentDiv = $(this).parent().parent(); var target = event.currentTarget; $(target).parent().remove(); var data = event.data; data.settings.onDeleteRow(); var currentFormFields = methods.getValues(parentDiv); $("#keyvalueeditor-textarea").val( methods.settings.formToTextFunction(currentFormFields) ); }, getToggleLink:function(state) { if (!state.settings.toggleButton) return ""; return '<a tabindex="-1" class="keyvalueeditor-toggle">' + state.settings.toggleButton + '</a>'; }, toggleRowHandler:function (event) { $("#keyvalueeditor-textarea-div").toggle(); $("#keyvalueeditor-form-div").toggle(); }, valueTypeSelectEventHandler:function (event) { var target = event.currentTarget; var valueType = $(target).val(); var valueTypes = event.data.settings.valueTypes; for (var i = 0; i < valueTypes.length; i++) { $(target).parent().find('.keyvalueeditor-value').css("display", "none"); } $(target).parent().find('input[type="' + valueType + '"]').css("display", "inline-block"); }, focusEventHandler:function (event) { var editableKeys = event.data.settings.editableKeys; if (!editableKeys) { return; } var params = {key:"", value:""}; var editor = event.data.editor; $(this).removeClass('keyvalueeditor-last'); var row = methods.getLastRow(event.data); if (event.data.settings.valueTypes.length > 1) { $(this).find('select:last').after(methods.getDeleteLink(event.data)); } else { $(this).find('input:last').after(methods.getDeleteLink(event.data)); } $(this).after(row); }, rowFocusEventHandler:function (event) { var data = event.data; data.settings.onFocusElement(event); }, blurEventHandler:function (event) { var data = event.data; data.settings.onBlurElement(); var parentDiv = $(this).parent().parent(); var currentFormFields = methods.getValues(parentDiv); $("#keyvalueeditor-textarea").val( methods.settings.formToTextFunction(currentFormFields) ); }, blurEventHandlerTextArea:function (event) { var data = event.data; var text = $(this).val(); var newFields = data.settings.textToFormFunction(text); data.editor.keyvalueeditor('reset',newFields) }, //For external use addParam:function (param, state) { if (typeof param === "object") { if(!("type" in param)) { param.type = "text"; } if (state.settings.editableKeys) { $(state.editor).find('#keyvalueeditor-form-div .keyvalueeditor-last').before(methods.getNewRow(param.key, param.value, param.type, state)); } else { $(state.editor).find('#keyvalueeditor-form-div').append(methods.getNewRow(param.key, param.value, param.type, state)); } } }, //Check for duplicates here addParams:function (params, state) { if (!state) { state = $(this).data('keyvalueeditor'); } var count = params.length; for (var i = 0; i < count; i++) { var param = params[i]; methods.addParam(param, state); } }, getValues:function (parentDiv) { if(parentDiv==null) { parentDiv=$(this); } var pairs = []; parentDiv.find('.keyvalueeditor-row').each(function () { var isEnabled = $(this).find('.keyvalueeditor-rowcheck').is(':checked'); if(!isEnabled) { return true; } var key = $(this).find('.keyvalueeditor-key').val(); var value = $(this).find('.keyvalueeditor-value').val(); var type = $(this).find('.keyvalueeditor-valueTypeSelector').val(); if (type === undefined) { type = "text"; } if (key) { var pair = { key:key.trim(), value:value.trim(), type:type, name: key }; pairs.push(pair); } }); return pairs; }, getElements:function () { var rows = []; var state = $(this).data('keyvalueeditor'); var valueTypes = state.settings.valueTypes; $(this).find('.keyvalueeditor-row').each(function () { var keyElement = $(this).find('.keyvalueeditor-key'); var valueElement; var type = "text"; if ($.inArray("file", valueTypes)) { type = $(this).find('.keyvalueeditor-valueTypeSelector').val(); if (type === "file") { valueElement = $(this).find('.keyvalueeditor-value-file'); } else { valueElement = $(this).find('.keyvalueeditor-value-text'); } } else { valueElement = $(this).find('.keyvalueeditor-value-text'); } if (keyElement.val()) { var row = { keyElement:keyElement, valueElement:valueElement, valueType:type }; rows.push(row); } }); return rows; }, clear:function (state) { $(state.editor).find('.keyvalueeditor-row').each(function () { $(this).remove(); }); $("#keyvalueeditor-form-div").val(""); if (state.settings.editableKeys) { var h = methods.getLastRow(state); $(state.editor).find("#keyvalueeditor-form-div").append(h); } }, reset:function (params, state) { if(state==null) { state = $(this).data('keyvalueeditor'); } methods.clear(state); if (params) { methods.addParams(params, state); } state.settings.onReset(); }, add:function (params) { var state = $(this).data('keyvalueeditor'); methods.clear(state); if (params) { methods.addParams(params, state); } }, destroy:function () { return this.each(function () { //unbind listeners if needed }); } }; $.fn.keyvalueeditor = function (method) { //Method calling logic if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.keyvalueeditor'); } }; $.fn.keyvalueeditor.defaults = { type:"normal", fields:2, deleteButton:"Delete", toggleButton:"Toggle view", placeHolderKey:"Key", placeHolderValue:"Value", valueTypes:["text"], editableKeys:true, onInit:function () { }, onReset:function () { }, onFocusElement:function () { }, onBlurElement:function () { }, onDeleteRow:function () { }, onAddedParam:function () { }, textToFormFunction:function(text) { var lines = text.split("\n"); var numLines = lines.length; var newHeaders=[]; var i; for(i=0;i<numLines;i++) { var newHeader={}; var thisPair = lines[i].split(":"); if(thisPair.length!=2) { console.log("Incorrect format for " + lines[i]); continue; } newHeader["key"]=newHeader["name"]=thisPair[0].trim(); newHeader["type"]="text"; newHeader["value"]=thisPair[1].trim(); newHeaders.push(newHeader); } return newHeaders; }, formToTextFunction:function(arr) { var text=""; var len = arr.length; var i=0; for(i=0;i<len;i++) { text+=arr[i]["key"]+": "+arr[i]["value"]+"\n"; } return text; } }; })(jQuery);
mit
ArthurHoaro/Public-GitLab
spec/requests/api/repositories_spec.rb
7823
require 'spec_helper' describe API::API do include ApiHelpers before(:each) { enable_observers } after(:each) {disable_observers} let(:user) { create(:user) } let(:user2) { create(:user) } let!(:project) { create(:project_with_code, creator_id: user.id) } let!(:users_project) { create(:users_project, user: user, project: project, project_access: UsersProject::MASTER) } before { project.team << [user, :reporter] } describe "GET /projects/:id/repository/branches" do it "should return an array of project branches" do get api("/projects/#{project.id}/repository/branches", user) response.status.should == 200 json_response.should be_an Array json_response.first['name'].should == project.repo.heads.sort_by(&:name).first.name end end describe "GET /projects/:id/repository/branches/:branch" do it "should return the branch information for a single branch" do get api("/projects/#{project.id}/repository/branches/new_design", user) response.status.should == 200 json_response['name'].should == 'new_design' json_response['commit']['id'].should == '621491c677087aa243f165eab467bfdfbee00be1' json_response['protected'].should == false end it "should return a 404 error if branch is not available" do get api("/projects/#{project.id}/repository/branches/unknown", user) response.status.should == 404 end end describe "PUT /projects/:id/repository/branches/:branch/protect" do it "should protect a single branch" do put api("/projects/#{project.id}/repository/branches/new_design/protect", user) response.status.should == 200 json_response['name'].should == 'new_design' json_response['commit']['id'].should == '621491c677087aa243f165eab467bfdfbee00be1' json_response['protected'].should == true end it "should return a 404 error if branch not found" do put api("/projects/#{project.id}/repository/branches/unknown/protect", user) response.status.should == 404 end it "should return success when protect branch again" do put api("/projects/#{project.id}/repository/branches/new_design/protect", user) put api("/projects/#{project.id}/repository/branches/new_design/protect", user) response.status.should == 200 end end describe "PUT /projects/:id/repository/branches/:branch/unprotect" do it "should unprotect a single branch" do put api("/projects/#{project.id}/repository/branches/new_design/unprotect", user) response.status.should == 200 json_response['name'].should == 'new_design' json_response['commit']['id'].should == '621491c677087aa243f165eab467bfdfbee00be1' json_response['protected'].should == false end it "should return success when unprotect branch" do put api("/projects/#{project.id}/repository/branches/unknown/unprotect", user) response.status.should == 404 end it "should return success when unprotect branch again" do put api("/projects/#{project.id}/repository/branches/new_design/unprotect", user) put api("/projects/#{project.id}/repository/branches/new_design/unprotect", user) response.status.should == 200 end end describe "GET /projects/:id/repository/tags" do it "should return an array of project tags" do get api("/projects/#{project.id}/repository/tags", user) response.status.should == 200 json_response.should be_an Array json_response.first['name'].should == project.repo.tags.sort_by(&:name).reverse.first.name end end describe "GET /projects/:id/repository/commits" do context "authorized user" do before { project.team << [user2, :reporter] } it "should return project commits" do get api("/projects/#{project.id}/repository/commits", user) response.status.should == 200 json_response.should be_an Array json_response.first['id'].should == project.repository.commit.id end end context "unauthorized user" do it "should not return project commits" do get api("/projects/#{project.id}/repository/commits") response.status.should == 401 end end end describe "GET /projects:id/repository/commits/:sha" do context "authorized user" do it "should return a commit by sha" do get api("/projects/#{project.id}/repository/commits/#{project.repository.commit.id}", user) response.status.should == 200 json_response['id'].should == project.repository.commit.id json_response['title'].should == project.repository.commit.title end it "should return a 404 error if not found" do get api("/projects/#{project.id}/repository/commits/invalid_sha", user) response.status.should == 404 end end context "unauthorized user" do it "should not return the selected commit" do get api("/projects/#{project.id}/repository/commits/#{project.repository.commit.id}") response.status.should == 401 end end end describe "GET /projects:id/repository/commits/:sha/diff" do context "authorized user" do before { project.team << [user2, :reporter] } it "should return the diff of the selected commit" do get api("/projects/#{project.id}/repository/commits/#{project.repository.commit.id}/diff", user) response.status.should == 200 json_response.should be_an Array json_response.length.should >= 1 json_response.first.keys.should include "diff" end it "should return a 404 error if invalid commit" do get api("/projects/#{project.id}/repository/commits/invalid_sha/diff", user) response.status.should == 404 end end context "unauthorized user" do it "should not return the diff of the selected commit" do get api("/projects/#{project.id}/repository/commits/#{project.repository.commit.id}/diff") response.status.should == 401 end end end describe "GET /projects/:id/repository/tree" do context "authorized user" do before { project.team << [user2, :reporter] } it "should return project commits" do get api("/projects/#{project.id}/repository/tree", user) response.status.should == 200 json_response.should be_an Array json_response.first['name'].should == 'app' json_response.first['type'].should == 'tree' json_response.first['mode'].should == '040000' end end context "unauthorized user" do it "should not return project commits" do get api("/projects/#{project.id}/repository/tree") response.status.should == 401 end end end describe "GET /projects/:id/repository/blobs/:sha" do it "should get the raw file contents" do get api("/projects/#{project.id}/repository/blobs/master?filepath=README.md", user) response.status.should == 200 end it "should return 404 for invalid branch_name" do get api("/projects/#{project.id}/repository/blobs/invalid_branch_name?filepath=README.md", user) response.status.should == 404 end it "should return 404 for invalid file" do get api("/projects/#{project.id}/repository/blobs/master?filepath=README.invalid", user) response.status.should == 404 end it "should return a 400 error if filepath is missing" do get api("/projects/#{project.id}/repository/blobs/master", user) response.status.should == 400 end end describe "GET /projects/:id/repository/commits/:sha/blob" do it "should get the raw file contents" do get api("/projects/#{project.id}/repository/commits/master/blob?filepath=README.md", user) response.status.should == 200 end end end
mit
fCarl/planA
Server/TCPConnection.cpp
1044
#include "TCPConnection.h" TCPConnection::TCPConnection(int connection_handle) { if (connection_handle < 0) { //TODO: //throw exception } _connection_handle = connection_handle; _read_buffer = NULL; _current_bufsize = 0; } int TCPConnection::read(std::string& buffer, int bufsize) { //adjust the size of buffer to which _read_buffer points //if _read_buffer is NULL or length of the buffer is smaller than specified size if (_current_bufsize == 0) { _read_buffer = new char[bufsize]; _current_bufsize = bufsize; } else if (_current_bufsize < bufsize) { delete _read_buffer; _read_buffer = new char[bufsize]; _current_bufsize = bufsize; } int byte_num = recv(_connection_handle, _read_buffer, bufsize, 0); buffer.assign(_read_buffer, byte_num); return byte_num; } void TCPConnection::close() { ::close(_connection_handle); } TCPConnection::~TCPConnection() { if (_read_buffer != NULL) { delete _read_buffer; } }
mit
npccoin/npccoin
test/util/bitcoin-util-test.py
6728
#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for npccoin utils. Runs automatically during `make check`. Can also be run manually.""" from __future__ import division,print_function,unicode_literals import argparse import binascii try: import configparser except ImportError: import ConfigParser as configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "bitcoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, npccoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main()
mit
StefNoMan/twitter-bot
index.php
134
<?php require 'vendor/autoload.php'; require 'app/app.php'; $app = new Stefnoman\Twitterbot\App(); $app->run(); ?>
mit
perminder-klair/kato
backend/views/block/_form.php
947
<?php use yii\helpers\Html; use yii\bootstrap\ActiveForm; use kato\sirtrevorjs\SirTrevor; /** * @var yii\web\View $this * @var backend\models\Block $model * @var yii\bootstrap\ActiveForm $form */ ?> <div class="block-form"> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'title')->textInput(['maxlength' => 70]) ?> <?= $form->field($model, 'content')->widget(SirTrevor::classname(), [ 'imageUploadUrl' => Yii::$app->urlManager->createAdminUrl(['block/upload']), ]); ?> <?= $form->field($model, 'status')->dropDownList($model->listStatus()); ?> <?= $form->field($model, 'parent')->dropDownList($model->listParents(), ['prompt'=>'No Parent']); ?> <div class="form-group"> <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?> </div>
mit
karim/adila
database/src/main/java/adila/db/mintss.java
216
// This file is automatically generated. package adila.db; /* * Samsung Galaxy Star * * DEVICE: mintss * MODEL: GT-S5280 */ final class mintss { public static final String DATA = "Samsung|Galaxy Star|"; }
mit
main24/ebayapi-19
lib/ebay/types/feature_definitions.rb
46010
require 'ebay/types/listing_duration_definition' require 'ebay/types/shipping_term_required_definition' require 'ebay/types/best_offer_enabled_definition' require 'ebay/types/dutch_bin_enabled_definition' require 'ebay/types/user_consent_required_definition' require 'ebay/types/home_page_featured_enabled_definition' require 'ebay/types/pro_pack_enabled_definition' require 'ebay/types/basic_upgrade_pack_enabled_definition' require 'ebay/types/value_pack_enabled_definition' require 'ebay/types/pro_pack_plus_enabled_definition' require 'ebay/types/ad_format_enabled_definition' require 'ebay/types/best_offer_counter_enabled_definition' require 'ebay/types/best_offer_auto_decline_enabled_definition' require 'ebay/types/local_market_speciality_subscription_definition' require 'ebay/types/local_market_regular_subscription_definition' require 'ebay/types/local_market_premium_subscription_definition' require 'ebay/types/local_market_non_subscription_definition' require 'ebay/types/express_enabled_definition' require 'ebay/types/express_pictures_required_definition' require 'ebay/types/express_condition_required_definition' require 'ebay/types/minimum_reserve_price_definition' require 'ebay/types/tcr_enabled_definition' require 'ebay/types/seller_contact_details_enabled_definition' require 'ebay/types/store_inventory_enabled_definition' require 'ebay/types/skype_me_transactional_enabled_definition' require 'ebay/types/skype_me_non_transactional_enabled_definition' require 'ebay/types/local_listing_distances_regular_definition' require 'ebay/types/local_listing_distances_specialty_definition' require 'ebay/types/local_listing_distances_non_subscription_definition' require 'ebay/types/classified_ad_payment_method_enabled_definition' require 'ebay/types/classified_ad_shipping_method_enabled_definition' require 'ebay/types/classified_ad_best_offer_enabled_definition' require 'ebay/types/classified_ad_counter_offer_enabled_definition' require 'ebay/types/classified_ad_auto_decline_enabled_definition' require 'ebay/types/classified_ad_contact_by_phone_enabled_definition' require 'ebay/types/classified_ad_contact_by_email_enabled_defintion' require 'ebay/types/safe_payment_required_definition' require 'ebay/types/classified_ad_pay_per_lead_enabled_definition' require 'ebay/types/item_specifics_enabled_definition' require 'ebay/types/paisa_pay_full_escrow_enabled_definition' require 'ebay/types/isbn_identifier_enabled_definition' require 'ebay/types/upc_identifier_enabled_definition' require 'ebay/types/ean_identifier_enabled_definition' require 'ebay/types/brand_mpn_identifier_enabled_definition' require 'ebay/types/best_offer_auto_accept_enabled_definition' require 'ebay/types/classified_ad_auto_accept_enabled_definition' require 'ebay/types/cross_border_trade_north_america_enabled_definition' require 'ebay/types/cross_border_trade_gb_enabled_definition' require 'ebay/types/cross_border_trade_australia_enabled_definition' require 'ebay/types/paypal_buyer_protection_enabled_definition' require 'ebay/types/buyer_guarantee_enabled_definition' require 'ebay/types/combined_fixed_price_treatment_enabled_definition' require 'ebay/types/listing_enhancement_duration_definition' require 'ebay/types/in_escrow_workflow_timeline_definition' require 'ebay/types/paypal_required_definition' require 'ebay/types/ebay_motors_pro_ad_format_enabled_definition' require 'ebay/types/ebay_motors_pro_contact_by_phone_enabled_definition' require 'ebay/types/ebay_motors_pro_phone_count_definition' require 'ebay/types/ebay_motors_pro_contact_by_address_enabled_definition' require 'ebay/types/ebay_motors_pro_street_count_definition' require 'ebay/types/ebay_motors_pro_company_name_enabled_definition' require 'ebay/types/ebay_motors_pro_contact_by_email_enabled_definition' require 'ebay/types/ebay_motors_pro_best_offer_enabled_definition' require 'ebay/types/ebay_motors_pro_auto_accept_enabled_definition' require 'ebay/types/ebay_motors_pro_auto_decline_enabled_definition' require 'ebay/types/ebay_motors_pro_payment_method_check_out_enabled_definition' require 'ebay/types/ebay_motors_pro_shipping_method_enabled_definition' require 'ebay/types/ebay_motors_pro_counter_offer_enabled_definition' require 'ebay/types/ebay_motors_pro_seller_contact_details_enabled_definition' require 'ebay/types/local_market_ad_format_enabled_definition' require 'ebay/types/local_market_contact_by_phone_enabled_definition' require 'ebay/types/local_market_phone_count_definition' require 'ebay/types/local_market_contact_by_address_enabled_definition' require 'ebay/types/local_market_street_count_definition' require 'ebay/types/local_market_company_name_enabled_definition' require 'ebay/types/local_market_contact_by_email_enabled_definition' require 'ebay/types/local_market_best_offer_enabled_definition' require 'ebay/types/local_market_auto_accept_enabled_definition' require 'ebay/types/local_market_auto_decline_enabled_definition' require 'ebay/types/local_market_payment_method_check_out_enabled_definition' require 'ebay/types/local_market_shipping_method_enabled_definition' require 'ebay/types/local_market_counter_offer_enabled_definition' require 'ebay/types/local_market_seller_contact_details_enabled_definition' require 'ebay/types/classified_ad_phone_count_definition' require 'ebay/types/classified_ad_contact_by_address_enabled_definition' require 'ebay/types/classified_ad_street_count_definition' require 'ebay/types/classified_ad_company_name_enabled_definition' require 'ebay/types/speciality_subscription_definition' require 'ebay/types/regular_subscription_definition' require 'ebay/types/premium_subscription_definition' require 'ebay/types/non_subscription_definition' require 'ebay/types/return_policy_enabled_definition' require 'ebay/types/handling_time_enabled_definition' require 'ebay/types/paypal_required_for_store_owner_definition' require 'ebay/types/revise_quantity_allowed_definition' require 'ebay/types/revise_price_allowed_definition' require 'ebay/types/store_owner_extended_listing_durations_enabled_definition' require 'ebay/types/store_owner_extended_listing_durations_definition' require 'ebay/types/payment_method_definition' require 'ebay/types/group1_max_flat_shipping_cost_definition' require 'ebay/types/group2_max_flat_shipping_cost_definition' require 'ebay/types/group3_max_flat_shipping_cost_definition' require 'ebay/types/max_flat_shipping_cost_cbt_exempt_definition' require 'ebay/types/max_flat_shipping_cost_definition' require 'ebay/types/variations_enabled_definition' require 'ebay/types/attribute_conversion_enabled_feature_definition' require 'ebay/types/free_gallery_plus_enabled_definition' require 'ebay/types/free_picture_pack_enabled_definition' require 'ebay/types/item_compatibility_enabled_definition' require 'ebay/types/max_item_compatibility_definition' require 'ebay/types/min_item_compatibility_definition' require 'ebay/types/condition_enabled_definition' require 'ebay/types/condition_values_definition' require 'ebay/types/value_category_definition' require 'ebay/types/product_creation_enabled_definition' require 'ebay/types/ean_enabled_definition' require 'ebay/types/isbn_enabled_definition' require 'ebay/types/upc_enabled_definition' require 'ebay/types/compatible_vehicle_type_definition' require 'ebay/types/max_granular_fitment_count_definition' require 'ebay/types/payment_options_group_enabled_definition' require 'ebay/types/profile_category_group_definition' require 'ebay/types/vin_supported_definition' require 'ebay/types/vrm_supported_definition' require 'ebay/types/seller_provided_title_supported_definition' require 'ebay/types/deposit_supported_definition' require 'ebay/types/global_shipping_enabled_definition' require 'ebay/types/additional_compatibility_enabled_definition' require 'ebay/types/pickup_drop_off_enabled_definition' require 'ebay/types/digital_good_delivery_enabled_definition' module Ebay # :nodoc: module Types # :nodoc: # == Attributes # array_node :listing_durations, 'ListingDurations', 'ListingDuration', :class => ListingDurationDefinition, :default_value => [] # object_node :shipping_terms_required, 'ShippingTermsRequired', :class => ShippingTermRequiredDefinition, :optional => true # object_node :best_offer_enabled, 'BestOfferEnabled', :class => BestOfferEnabledDefinition, :optional => true # object_node :dutch_bin_enabled, 'DutchBINEnabled', :class => DutchBINEnabledDefinition, :optional => true # object_node :user_consent_required, 'UserConsentRequired', :class => UserConsentRequiredDefinition, :optional => true # object_node :home_page_featured_enabled, 'HomePageFeaturedEnabled', :class => HomePageFeaturedEnabledDefinition, :optional => true # object_node :pro_pack_enabled, 'ProPackEnabled', :class => ProPackEnabledDefinition, :optional => true # object_node :basic_upgrade_pack_enabled, 'BasicUpgradePackEnabled', :class => BasicUpgradePackEnabledDefinition, :optional => true # object_node :value_pack_enabled, 'ValuePackEnabled', :class => ValuePackEnabledDefinition, :optional => true # object_node :pro_pack_plus_enabled, 'ProPackPlusEnabled', :class => ProPackPlusEnabledDefinition, :optional => true # object_node :ad_format_enabled, 'AdFormatEnabled', :class => AdFormatEnabledDefinition, :optional => true # object_node :best_offer_counter_enabled, 'BestOfferCounterEnabled', :class => BestOfferCounterEnabledDefinition, :optional => true # object_node :best_offer_auto_decline_enabled, 'BestOfferAutoDeclineEnabled', :class => BestOfferAutoDeclineEnabledDefinition, :optional => true # object_node :local_market_speciality_subscription, 'LocalMarketSpecialitySubscription', :class => LocalMarketSpecialitySubscriptionDefinition, :optional => true # object_node :local_market_regular_subscription, 'LocalMarketRegularSubscription', :class => LocalMarketRegularSubscriptionDefinition, :optional => true # object_node :local_market_premium_subscription, 'LocalMarketPremiumSubscription', :class => LocalMarketPremiumSubscriptionDefinition, :optional => true # object_node :local_market_non_subscription, 'LocalMarketNonSubscription', :class => LocalMarketNonSubscriptionDefinition, :optional => true # object_node :express_enabled, 'ExpressEnabled', :class => ExpressEnabledDefinition, :optional => true # object_node :express_pictures_required, 'ExpressPicturesRequired', :class => ExpressPicturesRequiredDefinition, :optional => true # object_node :express_condition_required, 'ExpressConditionRequired', :class => ExpressConditionRequiredDefinition, :optional => true # object_node :minimum_reserve_price, 'MinimumReservePrice', :class => MinimumReservePriceDefinition, :optional => true # object_node :transaction_confirmation_request_enabled, 'TransactionConfirmationRequestEnabled', :class => TCREnabledDefinition, :optional => true # object_node :seller_contact_details_enabled, 'SellerContactDetailsEnabled', :class => SellerContactDetailsEnabledDefinition, :optional => true # object_node :store_inventory_enabled, 'StoreInventoryEnabled', :class => StoreInventoryEnabledDefinition, :optional => true # object_node :skype_me_transactional_enabled, 'SkypeMeTransactionalEnabled', :class => SkypeMeTransactionalEnabledDefinition, :optional => true # object_node :skype_me_non_transactional_enabled, 'SkypeMeNonTransactionalEnabled', :class => SkypeMeNonTransactionalEnabledDefinition, :optional => true # object_node :local_listing_distances_regular, 'LocalListingDistancesRegular', :class => LocalListingDistancesRegularDefinition, :optional => true # object_node :local_listing_distances_specialty, 'LocalListingDistancesSpecialty', :class => LocalListingDistancesSpecialtyDefinition, :optional => true # object_node :local_listing_distances_non_subscription, 'LocalListingDistancesNonSubscription', :class => LocalListingDistancesNonSubscriptionDefinition, :optional => true # object_node :classified_ad_payment_method_enabled, 'ClassifiedAdPaymentMethodEnabled', :class => ClassifiedAdPaymentMethodEnabledDefinition, :optional => true # object_node :classified_ad_shipping_method_enabled, 'ClassifiedAdShippingMethodEnabled', :class => ClassifiedAdShippingMethodEnabledDefinition, :optional => true # object_node :classified_ad_best_offer_enabled, 'ClassifiedAdBestOfferEnabled', :class => ClassifiedAdBestOfferEnabledDefinition, :optional => true # object_node :classified_ad_counter_offer_enabled, 'ClassifiedAdCounterOfferEnabled', :class => ClassifiedAdCounterOfferEnabledDefinition, :optional => true # object_node :classified_ad_auto_decline_enabled, 'ClassifiedAdAutoDeclineEnabled', :class => ClassifiedAdAutoDeclineEnabledDefinition, :optional => true # object_node :classified_ad_contact_by_phone_enabled, 'ClassifiedAdContactByPhoneEnabled', :class => ClassifiedAdContactByPhoneEnabledDefinition, :optional => true # object_node :classified_ad_contact_by_email_enabled, 'ClassifiedAdContactByEmailEnabled', :class => ClassifiedAdContactByEmailEnabledDefintion, :optional => true # object_node :safe_payment_required, 'SafePaymentRequired', :class => SafePaymentRequiredDefinition, :optional => true # object_node :classified_ad_pay_per_lead_enabled, 'ClassifiedAdPayPerLeadEnabled', :class => ClassifiedAdPayPerLeadEnabledDefinition, :optional => true # object_node :item_specifics_enabled, 'ItemSpecificsEnabled', :class => ItemSpecificsEnabledDefinition, :optional => true # object_node :paisa_pay_full_escrow_enabled, 'PaisaPayFullEscrowEnabled', :class => PaisaPayFullEscrowEnabledDefinition, :optional => true # object_node :isbn_identifier_enabled, 'ISBNIdentifierEnabled', :class => ISBNIdentifierEnabledDefinition, :optional => true # object_node :upc_identifier_enabled, 'UPCIdentifierEnabled', :class => UPCIdentifierEnabledDefinition, :optional => true # object_node :ean_identifier_enabled, 'EANIdentifierEnabled', :class => EANIdentifierEnabledDefinition, :optional => true # object_node :brand_mpn_identifier_enabled, 'BrandMPNIdentifierEnabled', :class => BrandMPNIdentifierEnabledDefinition, :optional => true # object_node :best_offer_auto_accept_enabled, 'BestOfferAutoAcceptEnabled', :class => BestOfferAutoAcceptEnabledDefinition, :optional => true # object_node :classified_ad_auto_accept_enabled, 'ClassifiedAdAutoAcceptEnabled', :class => ClassifiedAdAutoAcceptEnabledDefinition, :optional => true # object_node :cross_border_trade_north_america_enabled, 'CrossBorderTradeNorthAmericaEnabled', :class => CrossBorderTradeNorthAmericaEnabledDefinition, :optional => true # object_node :cross_border_trade_gb_enabled, 'CrossBorderTradeGBEnabled', :class => CrossBorderTradeGBEnabledDefinition, :optional => true # object_node :cross_border_trade_australia_enabled, 'CrossBorderTradeAustraliaEnabled', :class => CrossBorderTradeAustraliaEnabledDefinition, :optional => true # object_node :paypal_buyer_protection_enabled, 'PayPalBuyerProtectionEnabled', :class => PayPalBuyerProtectionEnabledDefinition, :optional => true # object_node :buyer_guarantee_enabled, 'BuyerGuaranteeEnabled', :class => BuyerGuaranteeEnabledDefinition, :optional => true # object_node :combined_fixed_price_treatment_enabled, 'CombinedFixedPriceTreatmentEnabled', :class => CombinedFixedPriceTreatmentEnabledDefinition, :optional => true # object_node :gallery_featured_durations, 'GalleryFeaturedDurations', :class => ListingEnhancementDurationDefinition, :optional => true # object_node :in_escrow_workflow_timeline, 'INEscrowWorkflowTimeline', :class => INEscrowWorkflowTimelineDefinition, :optional => true # object_node :paypal_required, 'PayPalRequired', :class => PayPalRequiredDefinition, :optional => true # object_node :ebay_motors_pro_ad_format_enabled, 'eBayMotorsProAdFormatEnabled', :class => EBayMotorsProAdFormatEnabledDefinition, :optional => true # object_node :ebay_motors_pro_contact_by_phone_enabled, 'eBayMotorsProContactByPhoneEnabled', :class => EBayMotorsProContactByPhoneEnabledDefinition, :optional => true # object_node :ebay_motors_pro_phone_count, 'eBayMotorsProPhoneCount', :class => EBayMotorsProPhoneCountDefinition, :optional => true # object_node :ebay_motors_pro_contact_by_address_enabled, 'eBayMotorsProContactByAddressEnabled', :class => EBayMotorsProContactByAddressEnabledDefinition, :optional => true # object_node :ebay_motors_pro_street_count, 'eBayMotorsProStreetCount', :class => EBayMotorsProStreetCountDefinition, :optional => true # object_node :ebay_motors_pro_company_name_enabled, 'eBayMotorsProCompanyNameEnabled', :class => EBayMotorsProCompanyNameEnabledDefinition, :optional => true # object_node :ebay_motors_pro_contact_by_email_enabled, 'eBayMotorsProContactByEmailEnabled', :class => EBayMotorsProContactByEmailEnabledDefinition, :optional => true # object_node :ebay_motors_pro_best_offer_enabled, 'eBayMotorsProBestOfferEnabled', :class => EBayMotorsProBestOfferEnabledDefinition, :optional => true # object_node :ebay_motors_pro_auto_accept_enabled, 'eBayMotorsProAutoAcceptEnabled', :class => EBayMotorsProAutoAcceptEnabledDefinition, :optional => true # object_node :ebay_motors_pro_auto_decline_enabled, 'eBayMotorsProAutoDeclineEnabled', :class => EBayMotorsProAutoDeclineEnabledDefinition, :optional => true # object_node :ebay_motors_pro_payment_method_check_out_enabled, 'eBayMotorsProPaymentMethodCheckOutEnabled', :class => EBayMotorsProPaymentMethodCheckOutEnabledDefinition, :optional => true # object_node :ebay_motors_pro_shipping_method_enabled, 'eBayMotorsProShippingMethodEnabled', :class => EBayMotorsProShippingMethodEnabledDefinition, :optional => true # object_node :ebay_motors_pro_counter_offer_enabled, 'eBayMotorsProCounterOfferEnabled', :class => EBayMotorsProCounterOfferEnabledDefinition, :optional => true # object_node :ebay_motors_pro_seller_contact_details_enabled, 'eBayMotorsProSellerContactDetailsEnabled', :class => EBayMotorsProSellerContactDetailsEnabledDefinition, :optional => true # object_node :local_market_ad_format_enabled, 'LocalMarketAdFormatEnabled', :class => LocalMarketAdFormatEnabledDefinition, :optional => true # object_node :local_market_contact_by_phone_enabled, 'LocalMarketContactByPhoneEnabled', :class => LocalMarketContactByPhoneEnabledDefinition, :optional => true # object_node :local_market_phone_count, 'LocalMarketPhoneCount', :class => LocalMarketPhoneCountDefinition, :optional => true # object_node :local_market_contact_by_address_enabled, 'LocalMarketContactByAddressEnabled', :class => LocalMarketContactByAddressEnabledDefinition, :optional => true # object_node :local_market_street_count, 'LocalMarketStreetCount', :class => LocalMarketStreetCountDefinition, :optional => true # object_node :local_market_company_name_enabled, 'LocalMarketCompanyNameEnabled', :class => LocalMarketCompanyNameEnabledDefinition, :optional => true # object_node :local_market_contact_by_email_enabled, 'LocalMarketContactByEmailEnabled', :class => LocalMarketContactByEmailEnabledDefinition, :optional => true # object_node :local_market_best_offer_enabled, 'LocalMarketBestOfferEnabled', :class => LocalMarketBestOfferEnabledDefinition, :optional => true # object_node :local_market_auto_accept_enabled, 'LocalMarketAutoAcceptEnabled', :class => LocalMarketAutoAcceptEnabledDefinition, :optional => true # object_node :local_market_auto_decline_enabled, 'LocalMarketAutoDeclineEnabled', :class => LocalMarketAutoDeclineEnabledDefinition, :optional => true # object_node :local_market_payment_method_check_out_enabled, 'LocalMarketPaymentMethodCheckOutEnabled', :class => LocalMarketPaymentMethodCheckOutEnabledDefinition, :optional => true # object_node :local_market_shipping_method_enabled, 'LocalMarketShippingMethodEnabled', :class => LocalMarketShippingMethodEnabledDefinition, :optional => true # object_node :local_market_counter_offer_enabled, 'LocalMarketCounterOfferEnabled', :class => LocalMarketCounterOfferEnabledDefinition, :optional => true # object_node :local_market_seller_contact_details_enabled, 'LocalMarketSellerContactDetailsEnabled', :class => LocalMarketSellerContactDetailsEnabledDefinition, :optional => true # object_node :classified_ad_phone_count, 'ClassifiedAdPhoneCount', :class => ClassifiedAdPhoneCountDefinition, :optional => true # object_node :classified_ad_contact_by_address_enabled, 'ClassifiedAdContactByAddressEnabled', :class => ClassifiedAdContactByAddressEnabledDefinition, :optional => true # object_node :classified_ad_street_count, 'ClassifiedAdStreetCount', :class => ClassifiedAdStreetCountDefinition, :optional => true # object_node :classified_ad_company_name_enabled, 'ClassifiedAdCompanyNameEnabled', :class => ClassifiedAdCompanyNameEnabledDefinition, :optional => true # object_node :speciality_subscription, 'SpecialitySubscription', :class => SpecialitySubscriptionDefinition, :optional => true # object_node :regular_subscription, 'RegularSubscription', :class => RegularSubscriptionDefinition, :optional => true # object_node :premium_subscription, 'PremiumSubscription', :class => PremiumSubscriptionDefinition, :optional => true # object_node :non_subscription, 'NonSubscription', :class => NonSubscriptionDefinition, :optional => true # object_node :return_policy_enabled, 'ReturnPolicyEnabled', :class => ReturnPolicyEnabledDefinition, :optional => true # object_node :handling_time_enabled, 'HandlingTimeEnabled', :class => HandlingTimeEnabledDefinition, :optional => true # object_node :paypal_required_for_store_owner, 'PayPalRequiredForStoreOwner', :class => PayPalRequiredForStoreOwnerDefinition, :optional => true # object_node :revise_quantity_allowed, 'ReviseQuantityAllowed', :class => ReviseQuantityAllowedDefinition, :optional => true # object_node :revise_price_allowed, 'RevisePriceAllowed', :class => RevisePriceAllowedDefinition, :optional => true # object_node :store_owner_extended_listing_durations_enabled, 'StoreOwnerExtendedListingDurationsEnabled', :class => StoreOwnerExtendedListingDurationsEnabledDefinition, :optional => true # object_node :store_owner_extended_listing_durations, 'StoreOwnerExtendedListingDurations', :class => StoreOwnerExtendedListingDurationsDefinition, :optional => true # object_node :payment_method, 'PaymentMethod', :class => PaymentMethodDefinition, :optional => true # object_node :group1_max_flat_shipping_cost, 'Group1MaxFlatShippingCost', :class => Group1MaxFlatShippingCostDefinition, :optional => true # object_node :group2_max_flat_shipping_cost, 'Group2MaxFlatShippingCost', :class => Group2MaxFlatShippingCostDefinition, :optional => true # object_node :group3_max_flat_shipping_cost, 'Group3MaxFlatShippingCost', :class => Group3MaxFlatShippingCostDefinition, :optional => true # object_node :max_flat_shipping_cost_cbt_exempt, 'MaxFlatShippingCostCBTExempt', :class => MaxFlatShippingCostCBTExemptDefinition, :optional => true # object_node :max_flat_shipping_cost, 'MaxFlatShippingCost', :class => MaxFlatShippingCostDefinition, :optional => true # object_node :variations_enabled, 'VariationsEnabled', :class => VariationsEnabledDefinition, :optional => true # object_node :attribute_conversion_enabled, 'AttributeConversionEnabled', :class => AttributeConversionEnabledFeatureDefinition, :optional => true # object_node :free_gallery_plus_enabled, 'FreeGalleryPlusEnabled', :class => FreeGalleryPlusEnabledDefinition, :optional => true # object_node :free_picture_pack_enabled, 'FreePicturePackEnabled', :class => FreePicturePackEnabledDefinition, :optional => true # object_node :item_compatibility_enabled, 'ItemCompatibilityEnabled', :class => ItemCompatibilityEnabledDefinition, :optional => true # object_node :max_item_compatibility, 'MaxItemCompatibility', :class => MaxItemCompatibilityDefinition, :optional => true # object_node :min_item_compatibility, 'MinItemCompatibility', :class => MinItemCompatibilityDefinition, :optional => true # object_node :condition_enabled, 'ConditionEnabled', :class => ConditionEnabledDefinition, :optional => true # object_node :condition_values, 'ConditionValues', :class => ConditionValuesDefinition, :optional => true # object_node :value_category, 'ValueCategory', :class => ValueCategoryDefinition, :optional => true # object_node :product_creation_enabled, 'ProductCreationEnabled', :class => ProductCreationEnabledDefinition, :optional => true # object_node :ean_enabled, 'EANEnabled', :class => EANEnabledDefinition, :optional => true # object_node :isbn_enabled, 'ISBNEnabled', :class => ISBNEnabledDefinition, :optional => true # object_node :upc_enabled, 'UPCEnabled', :class => UPCEnabledDefinition, :optional => true # object_node :compatible_vehicle_type, 'CompatibleVehicleType', :class => CompatibleVehicleTypeDefinition, :optional => true # object_node :max_granular_fitment_count, 'MaxGranularFitmentCount', :class => MaxGranularFitmentCountDefinition, :optional => true # object_node :payment_options_group, 'PaymentOptionsGroup', :class => PaymentOptionsGroupEnabledDefinition, :optional => true # object_node :shipping_profile_category_group, 'ShippingProfileCategoryGroup', :class => ProfileCategoryGroupDefinition, :optional => true # object_node :payment_profile_category_group, 'PaymentProfileCategoryGroup', :class => ProfileCategoryGroupDefinition, :optional => true # object_node :return_policy_profile_category_group, 'ReturnPolicyProfileCategoryGroup', :class => ProfileCategoryGroupDefinition, :optional => true # object_node :vin_supported, 'VINSupported', :class => VINSupportedDefinition, :optional => true # object_node :vrm_supported, 'VRMSupported', :class => VRMSupportedDefinition, :optional => true # object_node :seller_provided_title_supported, 'SellerProvidedTitleSupported', :class => SellerProvidedTitleSupportedDefinition, :optional => true # object_node :deposit_supported, 'DepositSupported', :class => DepositSupportedDefinition, :optional => true # object_node :global_shipping_enabled, 'GlobalShippingEnabled', :class => GlobalShippingEnabledDefinition, :optional => true # object_node :additional_compatibility_enabled, 'AdditionalCompatibilityEnabled', :class => AdditionalCompatibilityEnabledDefinition, :optional => true # object_node :pickup_drop_off_enabled, 'PickupDropOffEnabled', :class => PickupDropOffEnabledDefinition, :optional => true # object_node :digital_good_delivery_enabled, 'DigitalGoodDeliveryEnabled', :class => DigitalGoodDeliveryEnabledDefinition, :optional => true class FeatureDefinitions include XML::Mapping include Initializer root_element_name 'FeatureDefinitions' array_node :listing_durations, 'ListingDurations', 'ListingDuration', :class => ListingDurationDefinition, :default_value => [] object_node :shipping_terms_required, 'ShippingTermsRequired', :class => ShippingTermRequiredDefinition, :optional => true object_node :best_offer_enabled, 'BestOfferEnabled', :class => BestOfferEnabledDefinition, :optional => true object_node :dutch_bin_enabled, 'DutchBINEnabled', :class => DutchBINEnabledDefinition, :optional => true object_node :user_consent_required, 'UserConsentRequired', :class => UserConsentRequiredDefinition, :optional => true object_node :home_page_featured_enabled, 'HomePageFeaturedEnabled', :class => HomePageFeaturedEnabledDefinition, :optional => true object_node :pro_pack_enabled, 'ProPackEnabled', :class => ProPackEnabledDefinition, :optional => true object_node :basic_upgrade_pack_enabled, 'BasicUpgradePackEnabled', :class => BasicUpgradePackEnabledDefinition, :optional => true object_node :value_pack_enabled, 'ValuePackEnabled', :class => ValuePackEnabledDefinition, :optional => true object_node :pro_pack_plus_enabled, 'ProPackPlusEnabled', :class => ProPackPlusEnabledDefinition, :optional => true object_node :ad_format_enabled, 'AdFormatEnabled', :class => AdFormatEnabledDefinition, :optional => true object_node :best_offer_counter_enabled, 'BestOfferCounterEnabled', :class => BestOfferCounterEnabledDefinition, :optional => true object_node :best_offer_auto_decline_enabled, 'BestOfferAutoDeclineEnabled', :class => BestOfferAutoDeclineEnabledDefinition, :optional => true object_node :local_market_speciality_subscription, 'LocalMarketSpecialitySubscription', :class => LocalMarketSpecialitySubscriptionDefinition, :optional => true object_node :local_market_regular_subscription, 'LocalMarketRegularSubscription', :class => LocalMarketRegularSubscriptionDefinition, :optional => true object_node :local_market_premium_subscription, 'LocalMarketPremiumSubscription', :class => LocalMarketPremiumSubscriptionDefinition, :optional => true object_node :local_market_non_subscription, 'LocalMarketNonSubscription', :class => LocalMarketNonSubscriptionDefinition, :optional => true object_node :express_enabled, 'ExpressEnabled', :class => ExpressEnabledDefinition, :optional => true object_node :express_pictures_required, 'ExpressPicturesRequired', :class => ExpressPicturesRequiredDefinition, :optional => true object_node :express_condition_required, 'ExpressConditionRequired', :class => ExpressConditionRequiredDefinition, :optional => true object_node :minimum_reserve_price, 'MinimumReservePrice', :class => MinimumReservePriceDefinition, :optional => true object_node :transaction_confirmation_request_enabled, 'TransactionConfirmationRequestEnabled', :class => TCREnabledDefinition, :optional => true object_node :seller_contact_details_enabled, 'SellerContactDetailsEnabled', :class => SellerContactDetailsEnabledDefinition, :optional => true object_node :store_inventory_enabled, 'StoreInventoryEnabled', :class => StoreInventoryEnabledDefinition, :optional => true object_node :skype_me_transactional_enabled, 'SkypeMeTransactionalEnabled', :class => SkypeMeTransactionalEnabledDefinition, :optional => true object_node :skype_me_non_transactional_enabled, 'SkypeMeNonTransactionalEnabled', :class => SkypeMeNonTransactionalEnabledDefinition, :optional => true object_node :local_listing_distances_regular, 'LocalListingDistancesRegular', :class => LocalListingDistancesRegularDefinition, :optional => true object_node :local_listing_distances_specialty, 'LocalListingDistancesSpecialty', :class => LocalListingDistancesSpecialtyDefinition, :optional => true object_node :local_listing_distances_non_subscription, 'LocalListingDistancesNonSubscription', :class => LocalListingDistancesNonSubscriptionDefinition, :optional => true object_node :classified_ad_payment_method_enabled, 'ClassifiedAdPaymentMethodEnabled', :class => ClassifiedAdPaymentMethodEnabledDefinition, :optional => true object_node :classified_ad_shipping_method_enabled, 'ClassifiedAdShippingMethodEnabled', :class => ClassifiedAdShippingMethodEnabledDefinition, :optional => true object_node :classified_ad_best_offer_enabled, 'ClassifiedAdBestOfferEnabled', :class => ClassifiedAdBestOfferEnabledDefinition, :optional => true object_node :classified_ad_counter_offer_enabled, 'ClassifiedAdCounterOfferEnabled', :class => ClassifiedAdCounterOfferEnabledDefinition, :optional => true object_node :classified_ad_auto_decline_enabled, 'ClassifiedAdAutoDeclineEnabled', :class => ClassifiedAdAutoDeclineEnabledDefinition, :optional => true object_node :classified_ad_contact_by_phone_enabled, 'ClassifiedAdContactByPhoneEnabled', :class => ClassifiedAdContactByPhoneEnabledDefinition, :optional => true object_node :classified_ad_contact_by_email_enabled, 'ClassifiedAdContactByEmailEnabled', :class => ClassifiedAdContactByEmailEnabledDefintion, :optional => true object_node :safe_payment_required, 'SafePaymentRequired', :class => SafePaymentRequiredDefinition, :optional => true object_node :classified_ad_pay_per_lead_enabled, 'ClassifiedAdPayPerLeadEnabled', :class => ClassifiedAdPayPerLeadEnabledDefinition, :optional => true object_node :item_specifics_enabled, 'ItemSpecificsEnabled', :class => ItemSpecificsEnabledDefinition, :optional => true object_node :paisa_pay_full_escrow_enabled, 'PaisaPayFullEscrowEnabled', :class => PaisaPayFullEscrowEnabledDefinition, :optional => true object_node :isbn_identifier_enabled, 'ISBNIdentifierEnabled', :class => ISBNIdentifierEnabledDefinition, :optional => true object_node :upc_identifier_enabled, 'UPCIdentifierEnabled', :class => UPCIdentifierEnabledDefinition, :optional => true object_node :ean_identifier_enabled, 'EANIdentifierEnabled', :class => EANIdentifierEnabledDefinition, :optional => true object_node :brand_mpn_identifier_enabled, 'BrandMPNIdentifierEnabled', :class => BrandMPNIdentifierEnabledDefinition, :optional => true object_node :best_offer_auto_accept_enabled, 'BestOfferAutoAcceptEnabled', :class => BestOfferAutoAcceptEnabledDefinition, :optional => true object_node :classified_ad_auto_accept_enabled, 'ClassifiedAdAutoAcceptEnabled', :class => ClassifiedAdAutoAcceptEnabledDefinition, :optional => true object_node :cross_border_trade_north_america_enabled, 'CrossBorderTradeNorthAmericaEnabled', :class => CrossBorderTradeNorthAmericaEnabledDefinition, :optional => true object_node :cross_border_trade_gb_enabled, 'CrossBorderTradeGBEnabled', :class => CrossBorderTradeGBEnabledDefinition, :optional => true object_node :cross_border_trade_australia_enabled, 'CrossBorderTradeAustraliaEnabled', :class => CrossBorderTradeAustraliaEnabledDefinition, :optional => true object_node :paypal_buyer_protection_enabled, 'PayPalBuyerProtectionEnabled', :class => PayPalBuyerProtectionEnabledDefinition, :optional => true object_node :buyer_guarantee_enabled, 'BuyerGuaranteeEnabled', :class => BuyerGuaranteeEnabledDefinition, :optional => true object_node :combined_fixed_price_treatment_enabled, 'CombinedFixedPriceTreatmentEnabled', :class => CombinedFixedPriceTreatmentEnabledDefinition, :optional => true object_node :gallery_featured_durations, 'GalleryFeaturedDurations', :class => ListingEnhancementDurationDefinition, :optional => true object_node :in_escrow_workflow_timeline, 'INEscrowWorkflowTimeline', :class => INEscrowWorkflowTimelineDefinition, :optional => true object_node :paypal_required, 'PayPalRequired', :class => PayPalRequiredDefinition, :optional => true object_node :ebay_motors_pro_ad_format_enabled, 'eBayMotorsProAdFormatEnabled', :class => EBayMotorsProAdFormatEnabledDefinition, :optional => true object_node :ebay_motors_pro_contact_by_phone_enabled, 'eBayMotorsProContactByPhoneEnabled', :class => EBayMotorsProContactByPhoneEnabledDefinition, :optional => true object_node :ebay_motors_pro_phone_count, 'eBayMotorsProPhoneCount', :class => EBayMotorsProPhoneCountDefinition, :optional => true object_node :ebay_motors_pro_contact_by_address_enabled, 'eBayMotorsProContactByAddressEnabled', :class => EBayMotorsProContactByAddressEnabledDefinition, :optional => true object_node :ebay_motors_pro_street_count, 'eBayMotorsProStreetCount', :class => EBayMotorsProStreetCountDefinition, :optional => true object_node :ebay_motors_pro_company_name_enabled, 'eBayMotorsProCompanyNameEnabled', :class => EBayMotorsProCompanyNameEnabledDefinition, :optional => true object_node :ebay_motors_pro_contact_by_email_enabled, 'eBayMotorsProContactByEmailEnabled', :class => EBayMotorsProContactByEmailEnabledDefinition, :optional => true object_node :ebay_motors_pro_best_offer_enabled, 'eBayMotorsProBestOfferEnabled', :class => EBayMotorsProBestOfferEnabledDefinition, :optional => true object_node :ebay_motors_pro_auto_accept_enabled, 'eBayMotorsProAutoAcceptEnabled', :class => EBayMotorsProAutoAcceptEnabledDefinition, :optional => true object_node :ebay_motors_pro_auto_decline_enabled, 'eBayMotorsProAutoDeclineEnabled', :class => EBayMotorsProAutoDeclineEnabledDefinition, :optional => true object_node :ebay_motors_pro_payment_method_check_out_enabled, 'eBayMotorsProPaymentMethodCheckOutEnabled', :class => EBayMotorsProPaymentMethodCheckOutEnabledDefinition, :optional => true object_node :ebay_motors_pro_shipping_method_enabled, 'eBayMotorsProShippingMethodEnabled', :class => EBayMotorsProShippingMethodEnabledDefinition, :optional => true object_node :ebay_motors_pro_counter_offer_enabled, 'eBayMotorsProCounterOfferEnabled', :class => EBayMotorsProCounterOfferEnabledDefinition, :optional => true object_node :ebay_motors_pro_seller_contact_details_enabled, 'eBayMotorsProSellerContactDetailsEnabled', :class => EBayMotorsProSellerContactDetailsEnabledDefinition, :optional => true object_node :local_market_ad_format_enabled, 'LocalMarketAdFormatEnabled', :class => LocalMarketAdFormatEnabledDefinition, :optional => true object_node :local_market_contact_by_phone_enabled, 'LocalMarketContactByPhoneEnabled', :class => LocalMarketContactByPhoneEnabledDefinition, :optional => true object_node :local_market_phone_count, 'LocalMarketPhoneCount', :class => LocalMarketPhoneCountDefinition, :optional => true object_node :local_market_contact_by_address_enabled, 'LocalMarketContactByAddressEnabled', :class => LocalMarketContactByAddressEnabledDefinition, :optional => true object_node :local_market_street_count, 'LocalMarketStreetCount', :class => LocalMarketStreetCountDefinition, :optional => true object_node :local_market_company_name_enabled, 'LocalMarketCompanyNameEnabled', :class => LocalMarketCompanyNameEnabledDefinition, :optional => true object_node :local_market_contact_by_email_enabled, 'LocalMarketContactByEmailEnabled', :class => LocalMarketContactByEmailEnabledDefinition, :optional => true object_node :local_market_best_offer_enabled, 'LocalMarketBestOfferEnabled', :class => LocalMarketBestOfferEnabledDefinition, :optional => true object_node :local_market_auto_accept_enabled, 'LocalMarketAutoAcceptEnabled', :class => LocalMarketAutoAcceptEnabledDefinition, :optional => true object_node :local_market_auto_decline_enabled, 'LocalMarketAutoDeclineEnabled', :class => LocalMarketAutoDeclineEnabledDefinition, :optional => true object_node :local_market_payment_method_check_out_enabled, 'LocalMarketPaymentMethodCheckOutEnabled', :class => LocalMarketPaymentMethodCheckOutEnabledDefinition, :optional => true object_node :local_market_shipping_method_enabled, 'LocalMarketShippingMethodEnabled', :class => LocalMarketShippingMethodEnabledDefinition, :optional => true object_node :local_market_counter_offer_enabled, 'LocalMarketCounterOfferEnabled', :class => LocalMarketCounterOfferEnabledDefinition, :optional => true object_node :local_market_seller_contact_details_enabled, 'LocalMarketSellerContactDetailsEnabled', :class => LocalMarketSellerContactDetailsEnabledDefinition, :optional => true object_node :classified_ad_phone_count, 'ClassifiedAdPhoneCount', :class => ClassifiedAdPhoneCountDefinition, :optional => true object_node :classified_ad_contact_by_address_enabled, 'ClassifiedAdContactByAddressEnabled', :class => ClassifiedAdContactByAddressEnabledDefinition, :optional => true object_node :classified_ad_street_count, 'ClassifiedAdStreetCount', :class => ClassifiedAdStreetCountDefinition, :optional => true object_node :classified_ad_company_name_enabled, 'ClassifiedAdCompanyNameEnabled', :class => ClassifiedAdCompanyNameEnabledDefinition, :optional => true object_node :speciality_subscription, 'SpecialitySubscription', :class => SpecialitySubscriptionDefinition, :optional => true object_node :regular_subscription, 'RegularSubscription', :class => RegularSubscriptionDefinition, :optional => true object_node :premium_subscription, 'PremiumSubscription', :class => PremiumSubscriptionDefinition, :optional => true object_node :non_subscription, 'NonSubscription', :class => NonSubscriptionDefinition, :optional => true object_node :return_policy_enabled, 'ReturnPolicyEnabled', :class => ReturnPolicyEnabledDefinition, :optional => true object_node :handling_time_enabled, 'HandlingTimeEnabled', :class => HandlingTimeEnabledDefinition, :optional => true object_node :paypal_required_for_store_owner, 'PayPalRequiredForStoreOwner', :class => PayPalRequiredForStoreOwnerDefinition, :optional => true object_node :revise_quantity_allowed, 'ReviseQuantityAllowed', :class => ReviseQuantityAllowedDefinition, :optional => true object_node :revise_price_allowed, 'RevisePriceAllowed', :class => RevisePriceAllowedDefinition, :optional => true object_node :store_owner_extended_listing_durations_enabled, 'StoreOwnerExtendedListingDurationsEnabled', :class => StoreOwnerExtendedListingDurationsEnabledDefinition, :optional => true object_node :store_owner_extended_listing_durations, 'StoreOwnerExtendedListingDurations', :class => StoreOwnerExtendedListingDurationsDefinition, :optional => true object_node :payment_method, 'PaymentMethod', :class => PaymentMethodDefinition, :optional => true object_node :group1_max_flat_shipping_cost, 'Group1MaxFlatShippingCost', :class => Group1MaxFlatShippingCostDefinition, :optional => true object_node :group2_max_flat_shipping_cost, 'Group2MaxFlatShippingCost', :class => Group2MaxFlatShippingCostDefinition, :optional => true object_node :group3_max_flat_shipping_cost, 'Group3MaxFlatShippingCost', :class => Group3MaxFlatShippingCostDefinition, :optional => true object_node :max_flat_shipping_cost_cbt_exempt, 'MaxFlatShippingCostCBTExempt', :class => MaxFlatShippingCostCBTExemptDefinition, :optional => true object_node :max_flat_shipping_cost, 'MaxFlatShippingCost', :class => MaxFlatShippingCostDefinition, :optional => true object_node :variations_enabled, 'VariationsEnabled', :class => VariationsEnabledDefinition, :optional => true object_node :attribute_conversion_enabled, 'AttributeConversionEnabled', :class => AttributeConversionEnabledFeatureDefinition, :optional => true object_node :free_gallery_plus_enabled, 'FreeGalleryPlusEnabled', :class => FreeGalleryPlusEnabledDefinition, :optional => true object_node :free_picture_pack_enabled, 'FreePicturePackEnabled', :class => FreePicturePackEnabledDefinition, :optional => true object_node :item_compatibility_enabled, 'ItemCompatibilityEnabled', :class => ItemCompatibilityEnabledDefinition, :optional => true object_node :max_item_compatibility, 'MaxItemCompatibility', :class => MaxItemCompatibilityDefinition, :optional => true object_node :min_item_compatibility, 'MinItemCompatibility', :class => MinItemCompatibilityDefinition, :optional => true object_node :condition_enabled, 'ConditionEnabled', :class => ConditionEnabledDefinition, :optional => true object_node :condition_values, 'ConditionValues', :class => ConditionValuesDefinition, :optional => true object_node :value_category, 'ValueCategory', :class => ValueCategoryDefinition, :optional => true object_node :product_creation_enabled, 'ProductCreationEnabled', :class => ProductCreationEnabledDefinition, :optional => true object_node :ean_enabled, 'EANEnabled', :class => EANEnabledDefinition, :optional => true object_node :isbn_enabled, 'ISBNEnabled', :class => ISBNEnabledDefinition, :optional => true object_node :upc_enabled, 'UPCEnabled', :class => UPCEnabledDefinition, :optional => true object_node :compatible_vehicle_type, 'CompatibleVehicleType', :class => CompatibleVehicleTypeDefinition, :optional => true object_node :max_granular_fitment_count, 'MaxGranularFitmentCount', :class => MaxGranularFitmentCountDefinition, :optional => true object_node :payment_options_group, 'PaymentOptionsGroup', :class => PaymentOptionsGroupEnabledDefinition, :optional => true object_node :shipping_profile_category_group, 'ShippingProfileCategoryGroup', :class => ProfileCategoryGroupDefinition, :optional => true object_node :payment_profile_category_group, 'PaymentProfileCategoryGroup', :class => ProfileCategoryGroupDefinition, :optional => true object_node :return_policy_profile_category_group, 'ReturnPolicyProfileCategoryGroup', :class => ProfileCategoryGroupDefinition, :optional => true object_node :vin_supported, 'VINSupported', :class => VINSupportedDefinition, :optional => true object_node :vrm_supported, 'VRMSupported', :class => VRMSupportedDefinition, :optional => true object_node :seller_provided_title_supported, 'SellerProvidedTitleSupported', :class => SellerProvidedTitleSupportedDefinition, :optional => true object_node :deposit_supported, 'DepositSupported', :class => DepositSupportedDefinition, :optional => true object_node :global_shipping_enabled, 'GlobalShippingEnabled', :class => GlobalShippingEnabledDefinition, :optional => true object_node :additional_compatibility_enabled, 'AdditionalCompatibilityEnabled', :class => AdditionalCompatibilityEnabledDefinition, :optional => true object_node :pickup_drop_off_enabled, 'PickupDropOffEnabled', :class => PickupDropOffEnabledDefinition, :optional => true object_node :digital_good_delivery_enabled, 'DigitalGoodDeliveryEnabled', :class => DigitalGoodDeliveryEnabledDefinition, :optional => true end end end
mit
mrpapercut/wscript
testfiles/COMobjects/JSclasses/Microsoft.MediaCenter.iTv.CiTvServiceInfo.js
883
class microsoft_mediacenter_itv_citvserviceinfo { constructor() { // int AudioPID {get;set;} this.AudioPID = undefined; // int NID {get;} this.NID = undefined; // int ONID {get;} this.ONID = undefined; // int PcrPID {get;set;} this.PcrPID = undefined; // int SID {get;} this.SID = undefined; // int TSID {get;} this.TSID = undefined; // int VideoPID {get;set;} this.VideoPID = undefined; } // void IiTvServiceInfo.AddDataPidOverride(int PID) AddDataPidOverride() { } // bool Equals(System.Object obj) Equals() { } // int GetHashCode() GetHashCode() { } // type GetType() GetType() { } // string ToString() ToString() { } } module.exports = microsoft_mediacenter_itv_citvserviceinfo;
mit
romka-chev/yii2-swiper
tests/unit/swiper/SwiperTest.php
17308
<?php namespace romkaChev\yii2\swiper\tests\unit\swiper; use romkaChev\yii2\swiper\Slide; use romkaChev\yii2\swiper\Swiper; use romkaChev\yii2\swiper\tests\unit\BaseTestCase; class SwiperTest extends BaseTestCase { public function testInvalidBehaviour() { $this->setExpectedException( '\InvalidArgumentException', 'Unknown behaviour badBehaviour' ); new Swiper( [ 'behaviours' => [ Swiper::BEHAVIOUR_PAGINATION, 'badBehaviour' ] ] ); } public function testConstructItemsViaStrings() { $swiper = new Swiper( [ 'items' => [ 'slide 01', 'slide 02', 'slide 03', ] ] ); foreach ($swiper->items as $item) { $this->assertInstanceOf( Slide::className(), $item ); } } public function testConstructItemsViaArrays() { $swiper = new Swiper( [ 'items' => [ [ 'content' => 'slide 01' ], [ 'content' => 'slide 02' ], [ 'content' => 'slide 03' ], ] ] ); foreach ($swiper->items as $item) { $this->assertInstanceOf( Slide::className(), $item ); } } public function testConstructItemsViaObjects() { $swiper = new Swiper( [ 'items' => [ new Slide( 'slide 01' ), new Slide( 'slide 02' ), new Slide( 'slide 03' ), ] ] ); foreach ($swiper->items as $item) { $this->assertInstanceOf( Slide::className(), $item ); } } public function testConstructItemsComplex() { $swiper = new Swiper( [ 'items' => [ 'slide 01', [ 'content' => 'slide 02' ], new Slide( 'slide 03' ), ] ] ); foreach ($swiper->items as $item) { $this->assertInstanceOf( Slide::className(), $item ); } } public function testInvalidItemsInjectionFailed() { $swiper = new Swiper( [ 'items' => [ 'slide 01', [ 'content' => 'slide 02' ], new Slide( 'slide 03' ), ] ] ); $swiper->items[] = 'badValue'; $swiper->items[] = [ 'content' => 'slide 02' ]; $this->setExpectedException( 'yii\base\ErrorException', 'must be an instance of romkaChev\yii2\swiper\Slide' ); $swiper->run(); } public function testValidItemInjectionSuccessed() { $swiper = new Swiper( [ 'items' => [ 'slide 01', [ 'content' => 'slide 02' ], new Slide( 'slide 03' ), ] ] ); $swiper->items[] = new Slide( 'slide 04' ); $swiper->run(); } public function testItemsInjectionViaSpecialMethodSuccessed() { $swiper = new Swiper( [ 'items' => [ 'slide 01', [ 'content' => 'slide 02' ], new Slide( 'slide 03' ), ] ] ); $swiper->addItem( 'slide 04' ); $swiper->addItem( [ 'content' => 'slide 05' ] ); $swiper->addItem( new Slide( 'slide 03' ) ); $swiper->run(); } public function testBatchItemsInjectionViaSpecialMethodSuccessed() { $swiper = new Swiper( [ 'items' => [ 'slide 01', [ 'content' => 'slide 02' ], new Slide( 'slide 03' ), ] ] ); $swiper->addItems( [ 'slide 04', [ 'content' => 'slide 05' ], new Slide( 'slide 03' ) ] ); $swiper->run(); } public function testContainerOptions() { $swiper = new Swiper( [ 'items' => [ 'slide 01', 'slide 02', 'slide 03', ], 'containerOptions' => [ 'id' => 'custom-id', 'class' => 'custom-class custom-another-class', 'data' => [ 'id' => 'custom-data-id' ] ] ] ); $this->assertEquals( 'custom-id', $swiper->containerOptions['id'] ); $this->assertEquals( 'custom-id-wrapper', $swiper->wrapperOptions['id'] ); $this->assertEquals( 'custom-id-pagination', $swiper->paginationOptions['id'] ); $this->assertEquals( 'custom-id-scrollbar', $swiper->scrollbarOptions['id'] ); $this->assertEquals( 'custom-id-button-next', $swiper->nextButtonOptions['id'] ); $this->assertEquals( 'custom-id-button-prev', $swiper->prevButtonOptions['id'] ); $this->assertEquals( 'custom-id-parallax', $swiper->parallaxOptions['id'] ); $this->assertEquals( 'custom-class custom-another-class swiper-container', $swiper->containerOptions['class'] ); $this->assertEquals( 'custom-data-id', $swiper->containerOptions['data']['id'] ); } public function testWrapperOptions() { $swiper = new Swiper( [ 'items' => [ 'slide 01', 'slide 02', 'slide 03', ], 'wrapperOptions' => [ 'id' => 'custom-wrapper-id', 'class' => 'custom-wrapper-class custom-another-wrapper-class', 'data' => [ 'id' => 'custom-data-wrapper-id' ] ] ] ); $this->assertEquals( 'custom-wrapper-id', $swiper->wrapperOptions['id'] ); $this->assertEquals( 'custom-wrapper-class custom-another-wrapper-class swiper-wrapper', $swiper->wrapperOptions['class'] ); $this->assertEquals( 'custom-data-wrapper-id', $swiper->wrapperOptions['data']['id'] ); } public function testPaginationOptions() { $swiper = new Swiper( [ 'items' => [ 'slide 01', 'slide 02', 'slide 03', ], 'paginationOptions' => [ 'id' => 'custom-pagination-id', 'class' => 'custom-pagination-class custom-another-pagination-class', 'data' => [ 'id' => 'custom-data-pagination-id' ] ] ] ); $this->assertEquals( 'custom-pagination-id', $swiper->paginationOptions['id'] ); $this->assertEquals( 'custom-pagination-class custom-another-pagination-class swiper-pagination', $swiper->paginationOptions['class'] ); $this->assertEquals( 'custom-data-pagination-id', $swiper->paginationOptions['data']['id'] ); } public function testScrollbarOptions() { $swiper = new Swiper( [ 'items' => [ 'slide 01', 'slide 02', 'slide 03', ], 'scrollbarOptions' => [ 'id' => 'custom-scrollbar-id', 'class' => 'custom-scrollbar-class custom-another-scrollbar-class', 'data' => [ 'id' => 'custom-data-scrollbar-id' ] ] ] ); $this->assertEquals( 'custom-scrollbar-id', $swiper->scrollbarOptions['id'] ); $this->assertEquals( 'custom-scrollbar-class custom-another-scrollbar-class swiper-scrollbar', $swiper->scrollbarOptions['class'] ); $this->assertEquals( 'custom-data-scrollbar-id', $swiper->scrollbarOptions['data']['id'] ); } public function testNextButtonOptions() { $swiper = new Swiper( [ 'items' => [ 'slide 01', 'slide 02', 'slide 03', ], 'nextButtonOptions' => [ 'id' => 'custom-next-button-id', 'class' => 'custom-next-button-class custom-another-next-button-class', 'data' => [ 'id' => 'custom-data-next-button-id' ] ] ] ); $this->assertEquals( 'custom-next-button-id', $swiper->nextButtonOptions['id'] ); $this->assertEquals( 'custom-next-button-class custom-another-next-button-class swiper-button-next', $swiper->nextButtonOptions['class'] ); $this->assertEquals( 'custom-data-next-button-id', $swiper->nextButtonOptions['data']['id'] ); } public function testPrevButtonOptions() { $swiper = new Swiper( [ 'items' => [ 'slide 01', 'slide 02', 'slide 03', ], 'prevButtonOptions' => [ 'id' => 'custom-prev-button-id', 'class' => 'custom-prev-button-class custom-another-prev-button-class', 'data' => [ 'id' => 'custom-data-prev-button-id' ] ] ] ); $this->assertEquals( 'custom-prev-button-id', $swiper->prevButtonOptions['id'] ); $this->assertEquals( 'custom-prev-button-class custom-another-prev-button-class swiper-button-prev', $swiper->prevButtonOptions['class'] ); $this->assertEquals( 'custom-data-prev-button-id', $swiper->prevButtonOptions['data']['id'] ); } public function testParallaxBackgroundMatching() { $swiper = new Swiper( [ 'items' => [ 'slide 01', ], 'parallaxOptions' => [ 'style' => 'color: #ffffff; background:url(http://lorempixel.com/900/600/nightlife/2/);', 'data' => [ 'swiper-parallax' => '23%', 'swiper-parallax-duration' => '750', ] ] ] ); $this->assertEquals( 'http://lorempixel.com/900/600/nightlife/2/', $swiper->parallaxOptions['background'] ); $swiper = new Swiper( [ 'items' => [ 'slide 01', ], 'parallaxOptions' => [ 'style' => 'color: #ffffff; background-image:url(http://lorempixel.com/900/600/nightlife/2/);', 'data' => [ 'swiper-parallax' => '23%', 'swiper-parallax-duration' => '750', ] ] ] ); $this->assertEquals( 'http://lorempixel.com/900/600/nightlife/2/', $swiper->parallaxOptions['background'] ); } public function testParallaxOptionsViaShorthands() { $swiper = new Swiper( [ 'items' => [ 'slide 01', 'slide 02', 'slide 03', ], 'parallaxOptions' => [ Swiper::PARALLAX_BACKGROUND => 'http://lorempixel.com/900/600/nightlife/2/', Swiper::PARALLAX_TRANSITION => '23%', Swiper::PARALLAX_TRANSITION_X => '10%', Swiper::PARALLAX_TRANSITION_Y => '15%', Swiper::PARALLAX_DURATION => '750', 'id' => 'custom-parallax-id', 'class' => 'custom-parallax-class custom-another-parallax-class', 'data' => [ 'id' => 'custom-data-parallax-id' ] ] ] ); $this->assertEquals( 'http://lorempixel.com/900/600/nightlife/2/', $swiper->parallaxOptions['background'] ); $this->assertEquals( '23%', $swiper->parallaxOptions['transition'] ); $this->assertEquals( '10%', $swiper->parallaxOptions['transitionX'] ); $this->assertEquals( '15%', $swiper->parallaxOptions['transitionY'] ); $this->assertEquals( '750', $swiper->parallaxOptions['duration'] ); $this->assertEquals( 'background-image:url(http://lorempixel.com/900/600/nightlife/2/)', $swiper->parallaxOptions['style'] ); $this->assertEquals( '23%', $swiper->parallaxOptions['data']['swiper-parallax'] ); $this->assertEquals( '10%', $swiper->parallaxOptions['data']['swiper-parallax-x'] ); $this->assertEquals( '15%', $swiper->parallaxOptions['data']['swiper-parallax-y'] ); $this->assertEquals( '750', $swiper->parallaxOptions['data']['swiper-parallax-duration'] ); $this->assertEquals( 'custom-parallax-id', $swiper->parallaxOptions['id'] ); $this->assertEquals( 'custom-parallax-class custom-another-parallax-class parallax-bg', $swiper->parallaxOptions['class'] ); $this->assertEquals( 'custom-data-parallax-id', $swiper->parallaxOptions['data']['id'] ); } public function testParallaxOptionsViaDirectAttributes() { $swiper = new Swiper( [ 'items' => [ 'slide 01', 'slide 02', 'slide 03', ], 'parallaxOptions' => [ 'style' => 'color: #ffffff; background-image:url(http://lorempixel.com/900/600/nightlife/2/);', 'data' => [ 'swiper-parallax' => '23%', 'swiper-parallax-x' => '10%', 'swiper-parallax-y' => '15%', 'swiper-parallax-duration' => '750', 'id' => 'custom-data-parallax-id' ], 'id' => 'custom-parallax-id', 'class' => 'custom-parallax-class custom-another-parallax-class', ] ] ); $this->assertEquals( 'http://lorempixel.com/900/600/nightlife/2/', $swiper->parallaxOptions['background'] ); $this->assertEquals( '23%', $swiper->parallaxOptions['transition'] ); $this->assertEquals( '10%', $swiper->parallaxOptions['transitionX'] ); $this->assertEquals( '15%', $swiper->parallaxOptions['transitionY'] ); $this->assertEquals( '750', $swiper->parallaxOptions['duration'] ); $this->assertEquals( 'color: #ffffff; background-image:url(http://lorempixel.com/900/600/nightlife/2/);', $swiper->parallaxOptions['style'] ); $this->assertEquals( '23%', $swiper->parallaxOptions['data']['swiper-parallax'] ); $this->assertEquals( '10%', $swiper->parallaxOptions['data']['swiper-parallax-x'] ); $this->assertEquals( '15%', $swiper->parallaxOptions['data']['swiper-parallax-y'] ); $this->assertEquals( '750', $swiper->parallaxOptions['data']['swiper-parallax-duration'] ); $this->assertEquals( 'custom-parallax-id', $swiper->parallaxOptions['id'] ); $this->assertEquals( 'custom-parallax-class custom-another-parallax-class parallax-bg', $swiper->parallaxOptions['class'] ); $this->assertEquals( 'custom-data-parallax-id', $swiper->parallaxOptions['data']['id'] ); } public function testParallaxOptionsViaShorthandsHaveMorePriorityThanViaDirectAttributes() { $swiper = new Swiper( [ 'items' => [ 'slide 01', 'slide 02', 'slide 03', ], 'parallaxOptions' => [ Swiper::PARALLAX_BACKGROUND => 'http://lorempixel.com/900/600/nightlife/5/', Swiper::PARALLAX_TRANSITION => '20%', Swiper::PARALLAX_TRANSITION_X => '20%', Swiper::PARALLAX_TRANSITION_Y => '20%', Swiper::PARALLAX_DURATION => '500', 'style' => 'color: #ffffff; background-image:url(http://lorempixel.com/900/600/nightlife/2/);', 'data' => [ 'swiper-parallax' => '15%', 'swiper-parallax-x' => '15%', 'swiper-parallax-y' => '15%', 'swiper-parallax-duration' => '750', 'id' => 'custom-data-parallax-id' ], 'id' => 'custom-parallax-id', 'class' => 'custom-parallax-class custom-another-parallax-class', ] ] ); $this->assertEquals( 'http://lorempixel.com/900/600/nightlife/5/', $swiper->parallaxOptions['background'] ); $this->assertEquals( '20%', $swiper->parallaxOptions['transition'] ); $this->assertEquals( '20%', $swiper->parallaxOptions['transitionX'] ); $this->assertEquals( '20%', $swiper->parallaxOptions['transitionY'] ); $this->assertEquals( '500', $swiper->parallaxOptions['duration'] ); $this->assertEquals( 'color: #ffffff; background-image:url(http://lorempixel.com/900/600/nightlife/2/); background-image:url(http://lorempixel.com/900/600/nightlife/5/)', $swiper->parallaxOptions['style'] ); $this->assertEquals( '20%', $swiper->parallaxOptions['data']['swiper-parallax'] ); $this->assertEquals( '20%', $swiper->parallaxOptions['data']['swiper-parallax-x'] ); $this->assertEquals( '20%', $swiper->parallaxOptions['data']['swiper-parallax-y'] ); $this->assertEquals( '500', $swiper->parallaxOptions['data']['swiper-parallax-duration'] ); } }
mit
mikefourie/MSBuildExtensionPack
Solutions/Main/Framework/SqlServer/SqlCmd.cs
29883
//------------------------------------------------------------------------------------------------------------------------------------------------------------------- // <copyright file="SqlCmd.cs">(c) 2017 Mike Fourie and Contributors (https://github.com/mikefourie/MSBuildExtensionPack) under MIT License. See https://opensource.org/licenses/MIT </copyright> //------------------------------------------------------------------------------------------------------------------------------------------------------------------- namespace MSBuild.ExtensionPack.SqlServer { using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text; using System.Text.RegularExpressions; using Microsoft.Build.Framework; using MSBuild.ExtensionPack.SqlServer.Extended; /// <summary> /// Wraps the SQL Server command line executable SqlCmd.exe. /// <para /> /// <b>Valid TaskActions are:</b> /// <para><i>Execute</i> (<b>Required: </b>CommandLineQuery or InputFiles <b>Optional: </b>Database, DedicatedAdminConnection, DisableVariableSubstitution, EchoInput, EnableQuotedIdentifiers, Headers, LoginTimeout, LogOn, NewPassword, OutputFile, Password, QueryTimeout, RedirectStandardError, Server, SeverityLevel, SqlCmdPath, UnicodeOutput, UseClientRegionalSettings, Variables, Workstation)</para> /// <para><b>Remote Execution Support:</b> Yes</para> /// </summary> /// <example> /// <code lang="xml"><![CDATA[ /// <Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> /// <PropertyGroup> /// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath> /// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath> /// </PropertyGroup> /// <Import Project="$(TPath)"/> /// <ItemGroup> /// <InputFile Include="C:\File1.sql"/> /// <InputFile Include="C:\File2.sql"/> /// <InputFile Include="C:\File3.sql"/> /// </ItemGroup> /// <ItemGroup> /// <Variable Include="DbName"> /// <Value>master</Value> /// </Variable> /// </ItemGroup> /// <Target Name="Default"> /// <!-- Simple CommandLineQuery --> /// <MSBuild.ExtensionPack.SqlServer.SqlCmd TaskAction="Execute" CommandLineQuery="SELECT @@VERSION;" /> /// <!-- Simple CommandLineQuery setting the Server and Database and outputing to a file --> /// <MSBuild.ExtensionPack.SqlServer.SqlCmd TaskAction="Execute" Server="(local)" Database="@(DbName)" CommandLineQuery="SELECT @@VERSION;" OutputFile="C:\Output.txt"/> /// <!-- Simple CommandLineQuery setting the Server and Database and running external files --> /// <MSBuild.ExtensionPack.SqlServer.SqlCmd TaskAction="Execute" Server="(local)" Database="@(DbName)" InputFiles="@(InputFile)" /> /// <!-- Simple CommandLineQuery setting the Server and Database, running external files and using variable substition --> /// <MSBuild.ExtensionPack.SqlServer.SqlCmd TaskAction="Execute" Server="(local)" Database="@(DbName)" InputFiles="@(InputFile)" Variables="@(Variable)" /> /// </Target> /// </Project> /// ]]></code> /// </example> public class SqlCmd : BaseTask { private const string ExecuteTaskAction = "Execute"; private const string ExecutionMessage = "Executing '{0}' with '{1}'"; private const string InputFileMessage = "Adding input file '{0}'"; private const string InvalidSqlCmdPathError = "Unable to resolve path to sqlcmd.exe. Assuming it is in the PATH environment variable."; private const string InvalidTaskActionError = "Invalid TaskAction passed: {0}"; private const string LoginTimeoutRangeError = "The LoginTimeout value specified '{0}' does not fall in the allowed range of 0 to 65534. Using the default value of eight (8) seconds."; private const string QueryMessage = "Adding query '{0}'"; private const string QueryTimeoutRangeError = "The QueryTimeout value specified '{0}' does not fall in the allowed range of 1 to 65535."; // 8191 * 4 = 32,764; 8,191 is the documented maximum number of characters in a command-line string(see http://support.microsoft.com/kb/830473). private const int CommandLineMaxLength = 32764; private int loginTimeout = 8; private int queryTimeout; private string server = "."; /// <summary> /// Initializes a new instance of the SqlCmd class /// </summary> public SqlCmd() { this.DisableVariableSubstitution = false; this.EchoInput = false; this.RedirectStandardError = false; this.UseClientRegionalSettings = false; } /// <summary> /// Gets or sets the path to the sqlcmd.exe. /// </summary> public string SqlCmdPath { get; set; } #region Login Related Options /// <summary> /// <para>Gets or sets the user login id. If neither the <see cref="LogOn"/> or <see cref="Password"/> option is specified, /// <see cref="SqlCmd"/> tries to connect by using Microsoft Windows Authentication mode. Authentication is /// based on the Windows account of the user who is running <see cref="SqlCmd"/>.</para> /// <para><b>Note:</b> The <i>OSQLUSER</i> environment variable is available for backwards compatibility. The <i> /// SQLCMDUSER</i> environment variable takes precedence over the <i>OSQLUSER</i> environment variable. This /// means that <see cref="SqlCmd"/> and <b>osql</b> can be used next to each other without interference.</para> /// </summary> public string LogOn { get; set; } /// <summary> /// <para>Gets or sets the user specified password. Passwords are case-sensitive. If the <see cref="LogOn"/> option /// is used and the <see cref="Password"/> option is not used, and the <i>SQLCMDPASSWORD</i> environment variable /// has not been set, <see cref="SqlCmd"/> uses the default password (NULL).</para> /// </summary> public string Password { get; set; } /// <summary> /// Changes the password for a user. /// </summary> public string NewPassword { get; set; } /// <summary> /// <para>Gets or sets the name of the SQL Server to which to connect. It sets the <see cref="SqlCmd"/> scripting variable /// <i>SQLCMDSERVER</i>.</para> /// <para>Specify <see cref="Server"/> to connect to the default instance of SQL Server on that server computer. Specify /// <see cref="Server"/> to connect to a named instance of SQL Server on that server computer. If no server computer is /// specified, <see cref="SqlCmd"/> connects to the default instance of SQL Server on the local computer. This option is /// required when you execute sqlcmd from a remote computer on the network.</para> /// <para>If you do not specify a <see cref="Server" /> when you start <see cref="SqlCmd" />, SQL Server checks for and /// uses the <i>SQLCMDSERVER</i> environment variable.</para> /// <para><b>Note: </b>The <i>OSQLSERVER</i> environment variable has been kept for backward compatibility. The /// <i>SQLCMDSERVER</i> environment variable takes precedence over the <i>OSQLSERVER</i> environment variable.</para> /// </summary> public string Server { get => this.server; set => this.server = value; } /// <summary> /// Gets or sets the workstation name. This option sets the <see cref="SqlCmd"/> scripting variable <i>SQLCMDWORKSTATION</i>. /// The workstation name is listed in the <b>hostname</b> column of the <b>sys.processes</b> catalog view and can be returned /// using the stored procedure <b>sp_who</b>. If this option is not specified, the default is the current computer name. This name /// can be used to identify different sqlcmd sessions. /// </summary> public string Workstation { get; set; } /// <summary> /// Gets or sets the name of the database to connect to. Issues a <code>USE</code> <i>db_name</i> statement when you start /// <see cref="SqlCmd"/>. This option sets the <see cref="SqlCmd"/> scripting variable <i>SQLCMDDBNAME</i>. This specifies /// the initial database. The default is your login's default-database property. If the database does not exist, an error message /// is generated and <see cref="SqlCmd"/> exits. /// </summary> public string Database { get; set; } /// <summary> /// Gets or sets the number of seconds before the <see cref="SqlCmd"/> login to the OLE DB provider times out when /// you try to connect to a server. The default login time-out for <see cref="SqlCmd"/> is eight (8) seconds. The login time- /// out value must be a number between 0 and 65534. If the value supplied is not numeric or does not fall into that range, /// the <see cref="SqlCmd"/> generates an error message. A value of 0 specifies the time-out to be indefinite. /// </summary> public int LoginTimeout { get => this.loginTimeout; set { if (value >= 0 && value <= 65534) { this.loginTimeout = value; } else { this.LogTaskWarning(string.Format(CultureInfo.InvariantCulture, LoginTimeoutRangeError, value)); } } } /// <summary> /// Gets or sets a flag that indicates if the connection to SQL Server should use a Dedicated Administrator Connection (DAC). /// This kind of connection is used to troubleshoot a server. This will only work with server computers that support DAC. If /// DAC is not available, <see cref="SqlCmd"/> generates an error message and then exits. For more information about DAC, see /// <a href="http://msdn.microsoft.com/en-us/library/ms189595.aspx">Using a Dedicated Administrator Connection</a>. /// </summary> public bool DedicatedAdminConnection { get; set; } #endregion #region Input/Output Options /// <summary> /// <para>Gets or sets the path to a file that contains a batch of SQL statements. Multiple files may be specified that will be read /// and processed in order. Do not use any spaces between the file names. <see cref="SqlCmd"/> will first check to see /// whether all files exist. If one or more files do not exist, <see cref="SqlCmd"/> will exit. The <see cref="InputFiles"/> and /// <see cref="CommandLineQuery"/> options are mutually exclusive.</para> /// Please note that if you provide a large number of files, you may exceed the maximum length of a command line (http://support.microsoft.com/kb/830473). It's recommended you make use of smaller batches if you encounter this issue. /// </summary> public ITaskItem[] InputFiles { get; set; } /// <summary> /// <para>Gets or sets the file that receives output from <see cref="SqlCmd"/>.</para> /// <para>If the <see cref="UnicodeOutput"/> option is specified, the <i>output file</i> is stored in Unicode format. /// If the file name is not valid, an error message is generated, and <see cref="SqlCmd"/> exits. <see cref="SqlCmd"/> does /// not support concurrent writing of multiple <see cref="SqlCmd"/> processes to the same file. The file output will be /// corrupted or incorrect. This file will be created if it does not exist. A file of the same name from a prior <see cref="SqlCmd"/> session /// will be overwritten. The file specified here is not the stdout file. If a stdout file is specified this file will not be used.</para> /// </summary> public string OutputFile { get; set; } /// <summary> /// Gets or sets a flag that indicates if the <see cref="OutputFile"/> is stored in Unicode format, regardless of the /// format of the <see cref="InputFiles"/>. /// </summary> public bool UnicodeOutput { get; set; } /// <summary> /// Gets or sets a flag that indicates whether or not to redirect the error message output to the screen /// (<b>stderr</b>).If you do not specify a parameter or if you specify <b>0</b>, only error messages that /// have a severity level of 11 or higher are redirected. If you specify <b>1</b>, all error message output including /// PRINT is redirected. Has no effect if you use <see cref="OutputFile"/>. By default, messages are sent to <b>stdout</b>. /// </summary> public bool RedirectStandardError { get; set; } /// <summary> /// Gets or sets a flag that indicates if the SQL Server OLE DB provider uses the client regional settings when it converts /// currency, and date and time data to character data. The default is server regional settings. /// </summary> public bool UseClientRegionalSettings { get; set; } #endregion #region Query Execution Options /// <summary> /// Gets or sets one or more command line queries to execute when <see cref="SqlCmd"/> starts, but does not exit /// sqlcmd when the query has finished running. /// </summary> public ITaskItem[] CommandLineQuery { get; set; } /// <summary> /// Gets or sets a flag that indicates if the input scripts are written to the standard output device (<b>stdout</b>). /// </summary> public bool EchoInput { get; set; } /// <summary> /// Gets or sets a flag that sets the <code>SET QUOTED_IDENTIFIER</code> connection option to <code>ON</code>. By /// default, it is set to <code>OFF</code>. For more information, see /// <a href="http://msdn.microsoft.com/en-us/library/ms174393.aspx">SET QUOTED_IDENTIFIER (Transact-SQL).</a> /// </summary> public bool EnableQuotedIdentifiers { get; set; } /// <summary> /// Controls the severity level that is used to set the ERRORLEVEL variable. If the ERRORLEVEL reported is >= SeverityLevel then the task will log an error. /// </summary> public int SeverityLevel { get; set; } /// <summary> /// <para>Gets or sets the number of seconds before a command (or SQL statement) times out. This option sets the <see cref="SqlCmd"/> /// scripting variable <i>SQLCMDSTATTIMEOUT</i>. If a <i>time_out</i> value is not specified, the command does not time out. The /// query <i>time_out</i> must be a number between 1 and 65535. If the value supplied is not numeric or does not fall into that range, /// <see cref="SqlCmd"/> generates an error message.</para> /// <para><b>Note:</b> The actual time out value may vary from the specified <i>time_out</i> value by several seconds.</para> /// </summary> public int QueryTimeout { get => this.queryTimeout; set { if (value >= 1 && value <= 65535) { this.queryTimeout = value; } else { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, QueryTimeoutRangeError, value)); } } } /// <summary> /// Creates a <see cref="SqlCmd"/> scripting variable that can be used in a <see cref="SqlCmd"/> script. You can specify multiple /// <see cref="Variables"/> and values. If there are errors in any of the values specified, <see cref="SqlCmd"/> generates an error /// message and then exits. /// </summary> public ITaskItem[] Variables { get; set; } /// <summary> /// Causes <see cref="SqlCmd"/> to ignore scripting variables. This is useful when a script contains many INSERT statements that /// may contain strings that have the same format as regular variables, such as $(variable_name). /// </summary> public bool DisableVariableSubstitution { get; set; } #endregion #region Formatting Options /// <summary> /// Specifies the number of rows to print between the column headings. The default is to print headings one time for each set of /// query results. This option sets the sqlcmd scripting variable <i>SQLCMDHEADERS</i>. Use -1 to specify that headers must not be /// printed. Any value that is not valid causes <see cref="SqlCmd"/> to generate an error message and then exit. /// </summary> public int Headers { get; set; } #endregion protected override void InternalExecute() { if (this.InputFiles == null && this.CommandLineQuery == null) { this.Log.LogError("InputFiles or CommandLineQuery is required"); return; } switch (this.TaskAction) { case ExecuteTaskAction: this.SqlExecute(); break; default: this.Log.LogError(InvalidTaskActionError, this.TaskAction); return; } } private string BuildArguments() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); // Login Related Options // Login Id if (!string.IsNullOrEmpty(this.LogOn)) { sb.Append(" -U "); sb.Append(this.LogOn); // Only pass in the password if a user id has been specified // Password if (!string.IsNullOrEmpty(this.Password)) { sb.Append(" -P "); sb.Append(this.Password); } } else { // default to assume Trusted sb.Append(" -E "); } // New Password and exit if (!string.IsNullOrEmpty(this.NewPassword)) { sb.Append(" -Z "); sb.Append(this.NewPassword); } // Server if (!string.IsNullOrEmpty(this.Server)) { sb.Append(" -S "); sb.Append(this.server); } // Workstation if (!string.IsNullOrEmpty(this.Workstation)) { sb.Append(" -H "); sb.Append(this.Workstation); } if (!string.IsNullOrEmpty(this.Database)) { sb.Append(" -d "); sb.Append(this.Database); } // Login Timeout sb.Append(" -l "); sb.Append(this.LoginTimeout); if (this.DedicatedAdminConnection) { sb.Append(" -A "); } // Output file if (!string.IsNullOrEmpty(this.OutputFile)) { sb.Append(" -o "); sb.Append("\""); sb.Append(this.OutputFile); sb.Append("\""); } // Code Page // Unicode if (this.UnicodeOutput) { sb.Append(" -u "); } // SeverityLevel if (this.SeverityLevel > 0) { sb.Append(" -V " + this.SeverityLevel); } // Redirect Standard Error if (this.RedirectStandardError) { sb.Append(" -r 1 "); } // Client Regional settings if (this.UseClientRegionalSettings) { sb.Append(" -R "); } // Query Execution Options // Command line query if (this.CommandLineQuery != null) { foreach (ITaskItem query in this.CommandLineQuery) { this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, QueryMessage, query.ItemSpec)); sb.Append(" -Q "); sb.Append("\""); sb.Append(query.ItemSpec); sb.Append("\""); } } // Echo Input if (this.EchoInput) { sb.Append(" -e "); } // Enabled Quoted Identifiers if (this.EnableQuotedIdentifiers) { sb.Append(" -I "); } // Query timeout if (this.QueryTimeout > 0) { sb.Append(" -t "); sb.Append(this.QueryTimeout); } // Variables if (this.Variables != null) { foreach (ITaskItem variable in this.Variables) { sb.Append(" -v "); sb.Append(variable.ItemSpec); sb.Append("=\""); sb.Append(variable.GetMetadata("Value")); sb.Append("\""); } } // DisableVariableSubstitution if (this.DisableVariableSubstitution) { sb.Append(" -x "); } return sb.ToString(); } private void ExecuteCommand(string arguments) { var sqlCmdWrapper = new SqlCmdWrapper(this.SqlCmdPath, arguments, string.Empty); this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, ExecutionMessage, sqlCmdWrapper.Executable, arguments)); // Get the return value int returnValue = sqlCmdWrapper.Execute(); // Write out the output if (!string.IsNullOrEmpty(sqlCmdWrapper.StandardOutput)) { this.LogTaskMessage(MessageImportance.Normal, sqlCmdWrapper.StandardOutput); } // Write out any errors this.SwitchReturnValue(returnValue, sqlCmdWrapper.StandardError.Trim()); string[] stdOutLines = sqlCmdWrapper.StandardOutput?.Split(new[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries) ?? new string[0]; var regex = new Regex(@"^(Msg|HResult) (?<ErrorCode>(0x[0-9A-F]+)|\d+), Level (?<Level>\d+), State (?<StateID>\d+)(, Server [^,]+(, (?<ObjectName>[^,]+))?, Line (?<LineNumber>\d+))?$"); bool foundError = false; string errorCode = string.Empty; string objectName = string.Empty; int lineNum = 0; int severityLevel = 0; bool loggingErrorsBySeverityLevel = this.SeverityLevel > 0; foreach (string line in stdOutLines) { if (foundError) { if (loggingErrorsBySeverityLevel && severityLevel >= this.SeverityLevel) { this.Log.LogError(string.Empty, errorCode, string.Empty, objectName, lineNum, 0, 0, 0, line); } else { this.Log.LogWarning(string.Empty, errorCode, string.Empty, objectName, lineNum, 0, 0, 0, line); } foundError = false; continue; } var match = regex.Match(line); if (match.Success) { var groups = match.Groups; int.TryParse(groups["LineNumber"].ToString(), out lineNum); int.TryParse(groups["Level"].ToString(), out severityLevel); errorCode = groups["ErrorCode"].ToString(); objectName = groups["ObjectName"].ToString(); if (loggingErrorsBySeverityLevel && severityLevel >= this.SeverityLevel) { this.Log.LogError(string.Empty, errorCode, string.Empty, objectName, lineNum, 0, 0, 0, line); } else { this.Log.LogWarning(string.Empty, errorCode, string.Empty, objectName, lineNum, 0, 0, 0, line); } foundError = true; } } if (loggingErrorsBySeverityLevel && returnValue >= this.SeverityLevel) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "SeverityLevel: {0} has been met or exceeded: {1}", this.SeverityLevel, returnValue)); } } private void SqlExecute() { // Resolve the path to the sqlcmd.exe tool if (!System.IO.File.Exists(this.SqlCmdPath)) { this.LogTaskMessage(MessageImportance.Low, InvalidSqlCmdPathError); this.SqlCmdPath = "sqlcmd.exe"; } string baseArguments = this.BuildArguments(); if (this.InputFiles != null && this.InputFiles.Length > 0) { int lengthRemaining = CommandLineMaxLength - this.SqlCmdPath.Length - baseArguments.Length - 2; this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "There are {0} characters available in the argument list for the input files.", lengthRemaining)); using (InputFileArgumentCollection ifac = new InputFileArgumentCollection(this, this.InputFiles, lengthRemaining)) { foreach (var inputFileArgs in ifac) { this.ExecuteCommand(baseArguments + " " + inputFileArgs); } } } else { this.ExecuteCommand(baseArguments); } } private void SwitchReturnValue(int returnValue, string error) { switch (returnValue) { case 1: this.LogTaskWarning("Exit Code 1. Failure: " + error); break; } } private sealed class InputFileArgumentCollection : IEnumerator<string>, IEnumerable<string> { private readonly BaseTask task; private readonly int maxArgLength; private readonly ITaskItem[] inputFiles; private int currentIndex; private StringBuilder currentArgList; public InputFileArgumentCollection(BaseTask baseTask, ITaskItem[] inputFileList, int maxArgLength) { this.task = baseTask; this.inputFiles = inputFileList; this.maxArgLength = maxArgLength; this.Reset(); } public string Current => this.currentArgList.ToString(); object IEnumerator.Current => this.Current; public void Dispose() { GC.SuppressFinalize(this); } public bool MoveNext() { if (this.inputFiles == null || this.currentIndex >= this.inputFiles.Length) { return false; } this.currentArgList = new StringBuilder(); for (; this.currentIndex < this.inputFiles.Length; ++this.currentIndex) { ITaskItem file = this.inputFiles[this.currentIndex]; string fullPath = file.GetMetadata("FullPath"); if (this.currentArgList.Length + 6 + fullPath.Length > this.maxArgLength) { break; } this.task.LogTaskMessage(string.Format(CultureInfo.CurrentUICulture, InputFileMessage, file.GetMetadata("FullPath"))); this.currentArgList.Append(" -i "); this.currentArgList.Append("\""); this.currentArgList.Append(file.GetMetadata("FullPath")); this.currentArgList.Append("\""); } return true; } public void Reset() { this.currentIndex = 0; this.currentArgList = new StringBuilder(); } public IEnumerator<string> GetEnumerator() { return this; } IEnumerator IEnumerable.GetEnumerator() { return this; } } } }
mit
yakirn/YTrack
src/components/Results.js
1088
'use strict'; import React from 'react'; import MovieItem from './MovieItem'; var searchStore = require('stores/SearchStore'); require('styles/Results.scss'); export class Results extends React.Component { constructor (props) { super(props); this.state = {results: searchStore.results}; this.onStoreChange = this.onStoreChange.bind(this); } componentDidMount() { this.unsubscribeCountChange = searchStore.listen(this.onStoreChange); } componentWillUnmount() { this.unsubscribeCountChange(); } onStoreChange (searchResults){ this.setState({results: searchResults}); } render () { return ( <div className="Results"> {this.state.count} <ul className="results-list"> { this.state.results.map(function(result){ switch (result.type){ case 'movie': return <MovieItem title={result.movie.title} year={result.movie.year} imdbId={result.movie.ids.imdb}/>; break; } })} </ul> </div> ); } }
mit
Raymans/config-service
common/api/InboxSvc.js
129
import {get} from './utils' export async function getInboxAPI () { return get('https://jsonplaceholder.typicode.com/users') }
mit
ridencww/uniroster-server
routes/oneroster/v1_0/enrollments.js
5085
var app = require('../../../uniroster-server.js'); var db = require('../../../lib/database.js'); var express = require('express'); var utils = require('../../../lib/onerosterUtils.js'); var router = express.Router(); var buildEnrollment = function(row, hrefBase, metaFields) { var enrollment = {}; enrollment.sourcedId = row.sourcedId; enrollment.status = row.status ? row.status : "active"; enrollment.dateLastModified = row.dateLastModified; var metadata = {}; metaFields.forEach(function(field) { metadata[field.jsonColumn] = row[field.dbColumn]; }); if (metaFields.length > 0) { enrollment.metadata = metadata; } enrollment.userSourcedId = row.userSourcedId; enrollment.classSourcedId = row.classSourcedId; enrollment.schoolSourcedId = row.schoolSourcedId; enrollment.role = row.role; enrollment.primary = row.primary; return enrollment; }; var queryEnrollment = function(req, res, next) { db.setup(req, res, function(connection, hrefBase, type) { db.tableFields(connection, 'enrollments', function(fields) { var select = utils.buildSelectStmt(req, res, fields); if (select === null) { connection.release(); return; } var where = utils.buildWhereStmt(req, res, fields, '', 'sourcedId = ?'); if (where === null) { connection.release(); return; } var orderBy = utils.buildOrderByStmt(req, res, fields); if (orderBy === null) { connection.release(); return; } var sql = select + 'FROM enrollments '; sql += where; sql += orderBy; sql += utils.buildLimitStmt(req); connection.query(sql, [req.params.id], function(err, rows) { connection.release(); if (err) { utils.reportServerError(res, err); return; } if (rows.length == 0) { utils.reportNotFound(res); } else { var wrapper = {}; wrapper.enrollment = buildEnrollment(rows[0], hrefBase, fields.metaFields); res.json(wrapper); } }); }); }); }; var queryEnrollments = function(req, res, next, type) { db.setup(req, res, function(connection, hrefBase, type) { db.tableFields(connection, 'enrollments', function(fields) { var select = utils.buildSelectStmt(req, res, fields); if (select === null) { connection.release(); return; } var where = utils.buildWhereStmt(req, res, fields); if (where === null) { connection.release(); return; } var orderBy = utils.buildOrderByStmt(req, res, fields); if (orderBy === null) { connection.release(); return; } var sql = select + 'FROM enrollments '; sql += where; sql += orderBy; sql += utils.buildLimitStmt(req); connection.query(sql, function(err, rows) { connection.release(); if (err) { utils.reportServerError(res, err); return; } var wrapper = {}; wrapper.enrollments = []; rows.forEach(function(row) { wrapper.enrollments.push(buildEnrollment(row, hrefBase, fields.metaFields)); }); res.json(wrapper); }); }); }); }; var queryEnrollmentsBySchool = function(req, res, next, type) { db.setup(req, res, function(connection, hrefBase, type) { db.tableFields(connection, 'enrollments', function(fields) { var select = utils.buildSelectStmt(req, res, fields); if (select === null) { connection.release(); return; } var whereStr = 'schoolSourcedId = ? '; if (req.params.cid) { whereStr += 'AND classSourcedId = ? '; } var where = utils.buildWhereStmt(req, res, fields, '', whereStr); if (where === null) { connection.release(); return; } var orderBy = utils.buildOrderByStmt(req, res, fields); if (orderBy === null) { connection.release(); return; } var sql = select + 'FROM enrollments '; sql += where; sql += orderBy; sql += utils.buildLimitStmt(req); connection.query(sql, [req.params.sid, req.params.cid], function(err, rows) { connection.release(); if (err) { utils.reportServerError(res, err); return; } var wrapper = {}; wrapper.enrollments = []; rows.forEach(function(row) { wrapper.enrollments.push(buildEnrollment(row, hrefBase, fields.metaFields)); }); res.json(wrapper); }); }); }); }; router.get('/enrollments', function(req, res, next) { queryEnrollments(req, res, next); }); router.get('/enrollments/:id', function(req, res, next) { queryEnrollment(req, res, next); }); router.get('/schools/:sid/enrollments', function(req, res, next) { queryEnrollmentsBySchool(req, res, next); }); router.get('/schools/:sid/classes/:cid/enrollments', function(req, res, next) { queryEnrollmentsBySchool(req, res, next); }); module.exports = router;
mit
gonetcats/betaseries-api-redux-sdk
tests/modules/shows/actions/doFetchMemberShows.js
1509
import showsReducer from '../../../../lib/modules/shows/reducers/shows'; import membersShowsReducer from '../../../../lib/modules/shows/reducers/members'; const actionFile = '../lib/modules/shows/actions/doFetchManyShows'; const showsFixture = require('../../../fixtures/shows.json'); describe('Retrieve member shows', () => { /** * getInstance method */ function getInstance(promise) { return proxyquire.noCallThru().load(actionFile, { '../../../utils/fetch/ApiFetch': { get: () => promise } }).default; } describe('call api with all shows ID list', () => { let action; const actionToDispatch = getInstance( Promise.resolve({ shows: showsFixture.slice(0, 2) }) ); before(async () => { const store = mockStore({ shows: {}, showsMembersEpisodesToSee: { 1: [982, 10212] } }); action = await store.dispatch(actionToDispatch()); }); it('validate action', () => { expect(action.type).to.equal('FETCH_MEMBER_SHOWS'); expect(action.payload.shows).to.have.lengthOf(2); }); it('validate shows reducer', () => { const stateShowsReducer = showsReducer(undefined, action); expect(Object.keys(stateShowsReducer)).to.deep.equal(['982', '10212']); }); it('validate member shows reducer', () => { const stateMembersShowsReducer = membersShowsReducer(undefined, action); expect(stateMembersShowsReducer[1]).to.deep.equal(['982', '10212']); }); }); });
mit
CyclopsMC/IntegratedDynamics
src/main/java/org/cyclops/integrateddynamics/api/block/cable/ICableFakeable.java
687
package org.cyclops.integrateddynamics.api.block.cable; /** * Capability for cables that can become unreal. * A cable can only become fake for a full block, not just for one side. * This means that for example parts can exist in that block space without the cable being there. * @author rubensworks */ public interface ICableFakeable { /** * @return If this cable is a real cable, otherwise it is just a holder block for parts without connections. */ public boolean isRealCable(); /** * @param real If this cable is a real cable, otherwise it is just a holder block for parts without connections. */ public void setRealCable(boolean real); }
mit
abhishekkothari09/WebScraping
Clean Wikipedia/Clean_wiki.py
797
import bs4 from bs4 import BeautifulSoup as soup from urllib.request import urlopen as uOpen from docx import Document def html_parsing(my_url): # Open the connection and get the page. opn = uOpen(my_url) page_html = opn.read() opn.close() # HTML parsing page_soup = soup(page_html, 'html.parser') return page_soup def remove_links(page_soup): # Get the <p> tags and remove the hyperlinks and images ptags = page_soup.findAll("p") for ptag in ptags: print(ptag.text) document.add_paragraph(ptag.text) # First page #my_url = 'https://en.wikipedia.org/wiki/Film' my_url = input("Please enter the URL from wikipedia : ") page_soup = html_parsing(my_url) document = Document() cleaned = remove_links(page_soup) document.save('demo.docx')
mit
rachellcarbone/angular-seed
www/app/views/auth/resetPassword/resetPassword.controller.js
2689
'use strict'; /* * Reset Password Page * * Controller for the Reset Password Page. */ angular.module('app.auth.resetPassword', []) .controller('ResetPasswordCtrl', ['$scope', '$state', '$log', '$window', '$timeout', 'AuthService', 'AlertConfirmService', '$stateParams', function ($scope, $state, $log, $window, $timeout, AuthService, AlertConfirmService, $stateParams) { $scope.$state = $state; $scope.form = {}; $scope.signupAlerts = {}; $scope.showPasswordRules = false; $scope.showPasswordMissmatch = false; if ($stateParams.usertoken) { $scope.usertoken = { 'usertoken': $stateParams.usertoken }; AuthService.forgotemailaddress($scope.usertoken).then(function (results) { $scope.newUser = { 'email': results.user.email, 'password': '', 'passwordB': '' }; }, function (error) { $scope.signupAlerts.error(error); $timeout(function () { $state.go('app.auth.login'); }, 5000); }); } $scope.SubmitResetPasswordForm = function () { if (!$scope.form.resetPassword.$valid) { $scope.form.resetPassword.$setDirty(); $scope.signupAlerts.error('Please fill in all Password fields.'); } else if ($scope.newUser.password !== $scope.newUser.passwordB) { $scope.form.resetPassword.$setDirty(); $scope.signupAlerts.error('Passwords do not match.'); } else { //API Call to save the Reset Password AuthService.resetpassword($scope.newUser).then(function (results) { $scope.signupAlerts.error(results.msg); }, function (error) { $scope.signupAlerts.error(error); }); } }; var passwordValidator = /^(?=.*\d)(?=.*[A-Za-z])[A-Za-z0-9_!@#$%^&*+=-]{8,100}$/; $scope.onChangeValidatePassword = function () { $scope.showPasswordRules = (!passwordValidator.test($scope.newUser.password)); $scope.onChangeValidateConfirmPassword(); }; $scope.onChangeValidateConfirmPassword = function () { $scope.showPasswordMissmatch = ($scope.newUser.password !== $scope.newUser.passwordB); }; }]);
mit
hahoyer/reni.cs
src/ReniUIWithForms/CompilationView/CodeView.cs
475
using System; using System.Collections.Generic; using System.Linq; using hw.Scanner; using Reni.Code; namespace ReniUI.CompilationView { sealed class CodeView : ChildView { public CodeView(CodeBase item, SourceView master) : base(master, "Code: " + item.NodeDump) { Client = item.CreateView(Master); SourceParts = T(item.GetSource()); } protected override SourcePart[] SourceParts { get; } } }
mit
Narnach/is_the_website_down
lib/is_the_website_down/service.rb
594
require 'is_the_website_down' require 'haml' root_dir = File.expand_path(File.join(File.dirname(__FILE__),'..','..')) sites_file = File.join(root_dir,'config','sites.txt') unless File.exist? sites_file STDERR.puts "config/sites.txt is missing. Please create it. See config/sites.txt.example for examples" exit 1 end websites = IsTheWebsiteDown::WebsiteList.load_file(sites_file) websites.auto_update locals = { :title => "Is the website down?", :websites => websites } get '/' do haml :index, :locals => locals end get '/style.css' do content_type 'text/css' sass :style end
mit
matudelatower/logiautos
src/CuestionariosBundle/Form/EncuestaOpcionRespuestaType.php
961
<?php namespace CuestionariosBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class EncuestaOpcionRespuestaType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('textoOpcion') ->add('encuestaPregunta') ->add('orden') ; } /** * @param OptionsResolver $resolver */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'CuestionariosBundle\Entity\EncuestaOpcionRespuesta' )); } /** * @return string */ public function getName() { return 'cuestionariosbundle_encuestaopcionrespuesta'; } }
mit
HCB2-NPT/QuanLyNhaSach
QuanLyNhaSach/Errors/ErrorTypes/AppErrors.cs
3630
using QuanLyNhaSach.Errors; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace QuanLyNhaSach.Managers { public partial class ErrorManager { public Error CantOpenAppMoreTimes { get { return new Error( "Lỗi chương trình!", "Không thể mở chương trình này hai lần!\n(Chạy song song được nhưng không thích cho chạy.)"); } } public Error CantConfig { get { return new Error( "Lỗi chương trình!", "Config không đúng, xin kiểm tra lại!"); } } public Error OutLookError { get { return new Error( "Outlook!", "Outlook chưa được cài đặt.\nHoặc đã có lỗi trong quá trình mở!", false); } } public Error AppCanNotUseNow { get { return new Error( "Thiếu chức năng!", "Chức năng chưa được làm.", false); } } public Error MinNumberLimitBookInStorage { get { return new Error( "Lỗi thông số!", "Số lượng trong kho của sản phẩm nhỏ hơn so với quy định.", false); } } public Error LimitMaxDebtMoney { get { return new Error( "Lỗi thông số!", "Lượng tiền nợ sau khi mua của khách hàng lớn hơn so với qui định.", false); } } public Error UnknowCustomer { get { return new Error( "Lỗi thông tin!", "Không có thông tin khách hàng.", false); } } public Error PopularCustomer { get { return new Error( "Lỗi thông số!", "Khách hàng thông thường không cho phép nợ!", false); } } public Error BillEmpty { get { return new Error( "Lỗi thông số!", "Hóa đơn rỗng.", false); } } public Error BookCantInsert { get { return new Error( "Lỗi số lượng!", "Số lượng trong kho còn nhiều , không thể nhập.", false); } } public Error WrongDateTime { get { return new Error( "Lỗi thông số!", "Ngày nhập kho phải tính từ hôm nay trở đi.", false); } } public Error InfoIsNull { get { return new Error( "Lỗi thông số!", "Dữ liệu không tồn tại hoặc trống.", false); } } } }
mit
drm/Mystique
src/Mystique/PHP/Token/Tokenizer.php
583
<?php namespace Mystique\PHP\Token; use Mystique\Common\Token\Tokenizer as BaseTokenizer; class Tokenizer implements BaseTokenizer { static function tokenize($str) { return token_get_all($str); } static function tokenizePhp($str) { return array_slice(token_get_all('<?php ' . $str), 1); } /** * @return \Mystique\Common\Token\TokenStream */ function getTokens($source, $ignore = array(T_DOC_COMMENT, T_COMMENT, T_WHITESPACE)) { return new \Mystique\Common\Token\TokenStream(self::tokenize($source), $ignore); } }
mit
gim-projekt-ai/nano-ai
base/say-no.go
64
package main import "fmt" func main() { fmt.Println("No") }
mit
angular/angular-cli-stress-test
src/app/components/comp-1681/comp-1681.component.spec.ts
847
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { Comp1681Component } from './comp-1681.component'; describe('Comp1681Component', () => { let component: Comp1681Component; let fixture: ComponentFixture<Comp1681Component>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ Comp1681Component ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(Comp1681Component); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
mit
udarapathmin/ApnaDeals
application/views/category/editcategory.php
1842
<div class="container"> <div class="row"> <div class="col-md-12"> <h3><i class="fa fa-th-list"></i> Edit Category</h3><hr> </div> </div> <div class="row"> <div class="col-md-12"> <?php if (validation_errors()) { ?> <div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <?php echo validation_errors(); ?> </div> <?php } ?> <?php if (isset($succ_message)) { ?> <div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <?php echo $succ_message; ?> </div> <?php } ?> <?php if (isset($error_message)) { ?> <div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <?php echo $error_message; ?> </div> <?php } ?> </div> </div> <div class="row"> <div class="col-md-6"> <?php echo form_open('category/EditCategory/'.$catid); ?> <div class="form-group"> <label>Category</label> <input type="text" class="form-control" name="category" placeholder="Category" value="<?php echo $categorydet ?>"> </div> <button type="submit" class="btn btn-success">Edit Category</button> <?php echo form_close(); ?> </div> </div> </div>
mit
MatthewGross/RemoteWAKE
server/RemoteWake.py
4866
#!/usr/bin/env python # RemoteWAKE Python Server # This server receives responses from the website, authenticates them, parses them, and if everything is in working # order, creates a alarm of annoyingness set by yourself. Good Luck! # Now I have to put a disclaimer... Kind of ridiculous... I know... # Disclaimer: This software is provided as is. The developers, contributors and/or maintainers of this open source project # are not AND will not be held responsible for any physical damage or harm caused this application/software. If you # have any heart, nerve conditions and disabilities or high blood pressure, PLEASE DO NOT USE THIS SOFTWARE APPLICATION. # Copyright 2014 Matthew Gross (Matt Gross) (mattgross.net)(http://github.com/MatthewGross) # Github: http://github.com/MatthewGross/RemoteWAKE # Website: http://mattgross.net/projects/remotewake # Enjoy! Litle note: Only give this to people you trust. If you are stupid enough to throw the login on Facebook or Twitter # I tend to believe you deserve to be woken up with a huge alarm every 5 seconds. # !-- Massive Comments End! # !-- Software.... COMMENCE... # File Description: # RemoteWake.py - Primary run script and listener for the RemoteWAKE Server. import socket import sys from time import sleep # for setting alarms in advance from config import * from logic import run_alarm if not HOST: HOST = "localhost" # default : localhost if not PORT: PORT = 2040 # default port is 2040 if not LISTEN_FROM: print >>sys.stderr, 'Please set LISTEN_FROM within config.py' # exit sys.exit() # variables already set from "from config import *: HOST, PORT, BUFFER_SIZE, LISTEN_FROM def RemoteWakeListener(HOST, PORT, LISTEN_FROM): # configs set... let's go! sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_addr = (host, port) print >>sys.stderr, 'Starting RemoteWAKE Server on %s port %s ... Listening...' % server_addr sock.bind(server_addr) # Listen for incoming sock.listen(1) while True: # waiting... # no message required connection, client_addr = sock.accept() try: print >>sys.stderr, 'Incoming Connection from ', client_addr # define default response message message = '' # check if client_addr matches LISTEN_FROM, otherwise it's another site... if client_addr == LISTEN_FROM: # some configs wake_up_message = 'Running Alarm! WAKE UP!' # allowed IP # listen for data while True: data = connection.recv(16) print >>sys.stderr, 'received "%s"' % data if data: print >>sys.stderr, 'Data Received... Parsing...' pairs = data.split('||') # split by '||' # setup dict result = {} # loop through splitted data for pair in pairs: (key, value) = pair.split('==') result[key] = value print >>sys.stderr, 'Config %s set to "%s"' %(key, value) print >>sys.stderr, "All Results Set... Completing Action..." # setup variables, we are going to need them either way... alarm_type = int(result.get("alarm_type")) # is an integer how_long = int(float(result.get("how_long")) # in seconds from_name = result.get("from_name") # string from_message = result.get("from_message") # string # check action if action == "startAlarm": # start alarm now print >>sys.stderr, wake_up_message run_alarm(alarm_type, how_long, from_name, from_message) if action == "setAlarm": # setting the alarm in advance... Start the countdown countdown = int(float(result.get("time")) # in seconds # post status to server print >>sys.stderr, 'Setting Countdown at %s Seconds' % countdown # countdown! while True: # counting down from countdown if countdown > 0: countdown = (countdown-1) print >>sys.stderr, 'Alarm in %s Seconds...' % countdown else: # countdown is 0 print >>sys.stderr, wake_up_message # run alarm run_alarm(alarm_type, how_long, from_name, from_message) # exit while loop: break else: print >>sys.stderr, 'No More Data from', client_addr break else: # send connection refused message message = "Connection Refused... Your IP Address is Not Allowed to send to this server. Error: IP_CONNECTION_REFUSED" # send default message connection.send(message) if __name__ == "__main__": RemoteWakeListener(HOST, PORT, LISTEN_FROM)
mit
mramasco/VG-Soundboard
SoundMixer/SoundContainer.cs
176
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Soundboard { public class SoundContainer { } }
mit
nycmobiledev/transit-app-experiments
gtfs/GTFSApi/Domain.GTFS.Static.Subway.Entities/Trip.cs
398
using System; namespace NYCMobileDev.TransitApp.Domain.GTFS.Static.Subway.Entities { public class Trip { public string RouteId { get; set; } public string TripId { get; set; } public string ServiceId { get; set; } public string TripHeadsign { get; set; } public string DirectionId { get; set; } public string ShapeId { get; set; } } }
mit
makcedward/nlpaug
scripts/lambada/data_processing.py
766
import argparse import os import pandas as pd def prepare_mlm_data(labels, texts, output_file_path, sep_token): with open(os.path.join(output_file_path, 'mlm_data.txt'), 'w') as f: for label, text in zip(labels, texts): f.write(' '.join([label, sep_token, text]) + '\n') def main(args): data = pd.read_csv(args.data_path) prepare_mlm_data(data['label'].tolist(), data['text'].tolist(), args.output_dir, '[SEP]') if __name__ == '__main__': parser = argparse.ArgumentParser(description='parameters', prefix_chars='-') parser.add_argument('--data_path', default='./test/res/text/classification.csv', help='Data path') parser.add_argument('--output_dir', default='./test/res/text', help='File output directory') args = parser.parse_args() main(args)
mit
GhassenRjab/wekan
client/components/cards/minicard.js
717
// Template.cards.events({ // 'click .member': Popup.open('cardMember') // }); BlazeComponent.extendComponent({ template() { return 'minicard'; }, events() { return [ { 'click .js-linked-link'() { if (this.data().isLinkedCard()) Utils.goCardId(this.data().linkedId); else if (this.data().isLinkedBoard()) Utils.goBoardId(this.data().linkedId); }, }, { 'click .js-toggle-minicard-label-text'() { Meteor.call('toggleMinicardLabelText'); }, }, ]; }, }).register('minicard'); Template.minicard.helpers({ hiddenMinicardLabelText() { return Meteor.user().hasHiddenMinicardLabelText(); }, });
mit
ddki/my_study_project
client/android/demos/WebviewTest/app/src/test/java/com/freekite/android/test/webviewtest/ExampleUnitTest.java
415
package com.freekite.android.test.webviewtest; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
mit
nepalez/faceter
spec/unit/functions/clean_spec.rb
533
# encoding: utf-8 describe Faceter::Functions, ".clean" do let(:arguments) { [:clean, Selector.new(options)] } let(:input) { { foo: { foo: :FOO }, bar: {}, baz: {}, qux: :QUX } } it_behaves_like :transforming_immutable_data do let(:options) { {} } let(:output) { { foo: { foo: :FOO }, qux: :QUX } } end it_behaves_like :transforming_immutable_data do let(:options) { { only: [:foo, :bar] } } let(:output) { { foo: { foo: :FOO }, baz: {}, qux: :QUX } } end end # describe Faceter::Functions.clean
mit