code_text
stringlengths
604
999k
repo_name
stringlengths
4
100
file_path
stringlengths
4
873
language
stringclasses
23 values
license
stringclasses
15 values
size
int32
1.02k
999k
//! moment.js locale configuration //! locale : macedonian (mk) //! author : Borislav Mickov : https://github.com/B0k0 import moment from '../moment'; export default moment.defineLocale('mk', { months : 'јануари_февруари_март_април_мај_јуни_јули_август_септември_октомври_ноември_декември'.split('_'), monthsShort : 'јан_фев_мар_апр_мај_јун_јул_авг_сеп_окт_ное_дек'.split('_'), weekdays : 'недела_понеделник_вторник_среда_четврток_петок_сабота'.split('_'), weekdaysShort : 'нед_пон_вто_сре_чет_пет_саб'.split('_'), weekdaysMin : 'нe_пo_вт_ср_че_пе_сa'.split('_'), longDateFormat : { LT : 'H:mm', LTS : 'LT:ss', L : 'D.MM.YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY LT', LLLL : 'dddd, D MMMM YYYY LT' }, calendar : { sameDay : '[Денес во] LT', nextDay : '[Утре во] LT', nextWeek : 'dddd [во] LT', lastDay : '[Вчера во] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: case 6: return '[Во изминатата] dddd [во] LT'; case 1: case 2: case 4: case 5: return '[Во изминатиот] dddd [во] LT'; } }, sameElse : 'L' }, relativeTime : { future : 'после %s', past : 'пред %s', s : 'неколку секунди', m : 'минута', mm : '%d минути', h : 'час', hh : '%d часа', d : 'ден', dd : '%d дена', M : 'месец', MM : '%d месеци', y : 'година', yy : '%d години' }, ordinalParse: /\d{1,2}-(ев|ен|ти|ви|ри|ми)/, ordinal : function (number) { var lastDigit = number % 10, last2Digits = number % 100; if (number === 0) { return number + '-ев'; } else if (last2Digits === 0) { return number + '-ен'; } else if (last2Digits > 10 && last2Digits < 20) { return number + '-ти'; } else if (lastDigit === 1) { return number + '-ви'; } else if (lastDigit === 2) { return number + '-ри'; } else if (lastDigit === 7 || lastDigit === 8) { return number + '-ми'; } else { return number + '-ти'; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } });
wikitree-website/wikitree-page
docs/bower_components/moment/src/locale/mk.js
JavaScript
mit
2,851
body, td, pre {color:#000; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px; margin:8px;} body {background:#FFF;} body.mceForceColors {background:#FFF; color:#000;} h1 {font-size: 2em} h2 {font-size: 1.5em} h3 {font-size: 1.17em} h4 {font-size: 1em} h5 {font-size: .83em} h6 {font-size: .75em} .mceItemTable, .mceItemTable td, .mceItemTable th, .mceItemTable caption, .mceItemVisualAid {border: 1px dashed #BBB;} a.mceItemAnchor {display:inline-block; width:11px !important; height:11px !important; background:url(../default/img/items.gif) no-repeat 0 0;} span.mceItemNbsp {background: #DDD} td.mceSelected, th.mceSelected {background-color:#3399ff !important} img {border:0;} table {cursor:default} table td, table th {cursor:text} ins {border-bottom:1px solid green; text-decoration: none; color:green} del {color:red; text-decoration:line-through} cite {border-bottom:1px dashed blue} acronym {border-bottom:1px dotted #CCC; cursor:help} abbr {border-bottom:1px dashed #CCC; cursor:help} /* IE */ * html body { scrollbar-3dlight-color:#F0F0EE; scrollbar-arrow-color:#676662; scrollbar-base-color:#F0F0EE; scrollbar-darkshadow-color:#DDD; scrollbar-face-color:#E0E0DD; scrollbar-highlight-color:#F0F0EE; scrollbar-shadow-color:#F0F0EE; scrollbar-track-color:#F5F5F5; } img:-moz-broken {-moz-force-broken-image-icon:1; width:24px; height:24px} font[face=mceinline] {font-family:inherit !important}
clejer/concrete_
concrete/js/tiny_mce/themes/concrete/skins/o2k7/content.css
CSS
mit
1,419
<?php class Swift_StreamFilters_ByteArrayReplacementFilterTest extends \PHPUnit_Framework_TestCase { public function testBasicReplacementsAreMade() { $filter = $this->_createFilter(array(0x61, 0x62), array(0x63, 0x64)); $this->assertEquals( array(0x59, 0x60, 0x63, 0x64, 0x65), $filter->filter(array(0x59, 0x60, 0x61, 0x62, 0x65)) ); } public function testShouldBufferReturnsTrueIfPartialMatchAtEndOfBuffer() { $filter = $this->_createFilter(array(0x61, 0x62), array(0x63, 0x64)); $this->assertTrue($filter->shouldBuffer(array(0x59, 0x60, 0x61)), '%s: Filter should buffer since 0x61 0x62 is the needle and the ending ' . '0x61 could be from 0x61 0x62' ); } public function testFilterCanMakeMultipleReplacements() { $filter = $this->_createFilter(array(array(0x61), array(0x62)), array(0x63)); $this->assertEquals( array(0x60, 0x63, 0x60, 0x63, 0x60), $filter->filter(array(0x60, 0x61, 0x60, 0x62, 0x60)) ); } public function testMultipleReplacementsCanBeDifferent() { $filter = $this->_createFilter(array(array(0x61), array(0x62)), array(array(0x63), array(0x64))); $this->assertEquals( array(0x60, 0x63, 0x60, 0x64, 0x60), $filter->filter(array(0x60, 0x61, 0x60, 0x62, 0x60)) ); } public function testShouldBufferReturnsFalseIfPartialMatchNotAtEndOfString() { $filter = $this->_createFilter(array(0x0D, 0x0A), array(0x0A)); $this->assertFalse($filter->shouldBuffer(array(0x61, 0x62, 0x0D, 0x0A, 0x63)), '%s: Filter should not buffer since x0Dx0A is the needle and is not at EOF' ); } public function testShouldBufferReturnsTrueIfAnyOfMultipleMatchesAtEndOfString() { $filter = $this->_createFilter(array(array(0x61, 0x62), array(0x63)), array(0x64)); $this->assertTrue($filter->shouldBuffer(array(0x59, 0x60, 0x61)), '%s: Filter should buffer since 0x61 0x62 is a needle and the ending ' . '0x61 could be from 0x61 0x62' ); } public function testConvertingAllLineEndingsToCRLFWhenInputIsLF() { $filter = $this->_createFilter( array(array(0x0D, 0x0A), array(0x0D), array(0x0A)), array(array(0x0A), array(0x0A), array(0x0D, 0x0A)) ); $this->assertEquals( array(0x60, 0x0D, 0x0A, 0x61, 0x0D, 0x0A, 0x62, 0x0D, 0x0A, 0x63), $filter->filter(array(0x60, 0x0A, 0x61, 0x0A, 0x62, 0x0A, 0x63)) ); } public function testConvertingAllLineEndingsToCRLFWhenInputIsCR() { $filter = $this->_createFilter( array(array(0x0D, 0x0A), array(0x0D), array(0x0A)), array(array(0x0A), array(0x0A), array(0x0D, 0x0A)) ); $this->assertEquals( array(0x60, 0x0D, 0x0A, 0x61, 0x0D, 0x0A, 0x62, 0x0D, 0x0A, 0x63), $filter->filter(array(0x60, 0x0D, 0x61, 0x0D, 0x62, 0x0D, 0x63)) ); } public function testConvertingAllLineEndingsToCRLFWhenInputIsCRLF() { $filter = $this->_createFilter( array(array(0x0D, 0x0A), array(0x0D), array(0x0A)), array(array(0x0A), array(0x0A), array(0x0D, 0x0A)) ); $this->assertEquals( array(0x60, 0x0D, 0x0A, 0x61, 0x0D, 0x0A, 0x62, 0x0D, 0x0A, 0x63), $filter->filter(array(0x60, 0x0D, 0x0A, 0x61, 0x0D, 0x0A, 0x62, 0x0D, 0x0A, 0x63)) ); } public function testConvertingAllLineEndingsToCRLFWhenInputIsLFCR() { $filter = $this->_createFilter( array(array(0x0D, 0x0A), array(0x0D), array(0x0A)), array(array(0x0A), array(0x0A), array(0x0D, 0x0A)) ); $this->assertEquals( array(0x60, 0x0D, 0x0A, 0x0D, 0x0A, 0x61, 0x0D, 0x0A, 0x0D, 0x0A, 0x62, 0x0D, 0x0A, 0x0D, 0x0A, 0x63), $filter->filter(array(0x60, 0x0A, 0x0D, 0x61, 0x0A, 0x0D, 0x62, 0x0A, 0x0D, 0x63)) ); } public function testConvertingAllLineEndingsToCRLFWhenInputContainsLFLF() { //Lighthouse Bug #23 $filter = $this->_createFilter( array(array(0x0D, 0x0A), array(0x0D), array(0x0A)), array(array(0x0A), array(0x0A), array(0x0D, 0x0A)) ); $this->assertEquals( array(0x60, 0x0D, 0x0A, 0x0D, 0x0A, 0x61, 0x0D, 0x0A, 0x0D, 0x0A, 0x62, 0x0D, 0x0A, 0x0D, 0x0A, 0x63), $filter->filter(array(0x60, 0x0A, 0x0A, 0x61, 0x0A, 0x0A, 0x62, 0x0A, 0x0A, 0x63)) ); } // -- Creation methods private function _createFilter($search, $replace) { return new Swift_StreamFilters_ByteArrayReplacementFilter($search, $replace); } }
jcherencia/Gestor_de_cocina
vendor/swiftmailer/swiftmailer/tests/unit/Swift/StreamFilters/ByteArrayReplacementFilterTest.php
PHP
mit
4,887
/* * jquery.inputmask.bundle * http://github.com/RobinHerbots/jquery.inputmask * Copyright (c) 2010 - 2014 Robin Herbots * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) * Version: 3.1.27 */ !function($) { function isInputEventSupported(eventName) { var el = document.createElement("input"), evName = "on" + eventName, isSupported = evName in el; return isSupported || (el.setAttribute(evName, "return;"), isSupported = "function" == typeof el[evName]), el = null, isSupported; } function isInputTypeSupported(inputType) { var isSupported = "text" == inputType || "tel" == inputType; if (!isSupported) { var el = document.createElement("input"); el.setAttribute("type", inputType), isSupported = "text" === el.type, el = null; } return isSupported; } function resolveAlias(aliasStr, options, opts) { var aliasDefinition = opts.aliases[aliasStr]; return aliasDefinition ? (aliasDefinition.alias && resolveAlias(aliasDefinition.alias, void 0, opts), $.extend(!0, opts, aliasDefinition), $.extend(!0, opts, options), !0) : !1; } function generateMaskSet(opts, multi) { function analyseMask(mask) { function maskToken(isGroup, isOptional, isQuantifier, isAlternator) { this.matches = [], this.isGroup = isGroup || !1, this.isOptional = isOptional || !1, this.isQuantifier = isQuantifier || !1, this.isAlternator = isAlternator || !1, this.quantifier = { min: 1, max: 1 }; } function insertTestDefinition(mtoken, element, position) { var maskdef = opts.definitions[element], newBlockMarker = 0 == mtoken.matches.length; if (position = void 0 != position ? position : mtoken.matches.length, maskdef && !escaped) { for (var prevalidators = maskdef.prevalidator, prevalidatorsL = prevalidators ? prevalidators.length : 0, i = 1; i < maskdef.cardinality; i++) { var prevalidator = prevalidatorsL >= i ? prevalidators[i - 1] : [], validator = prevalidator.validator, cardinality = prevalidator.cardinality; mtoken.matches.splice(position++, 0, { fn: validator ? "string" == typeof validator ? new RegExp(validator) : new function() { this.test = validator; }() : new RegExp("."), cardinality: cardinality ? cardinality : 1, optionality: mtoken.isOptional, newBlockMarker: newBlockMarker, casing: maskdef.casing, def: maskdef.definitionSymbol || element, placeholder: maskdef.placeholder, mask: element }); } mtoken.matches.splice(position++, 0, { fn: maskdef.validator ? "string" == typeof maskdef.validator ? new RegExp(maskdef.validator) : new function() { this.test = maskdef.validator; }() : new RegExp("."), cardinality: maskdef.cardinality, optionality: mtoken.isOptional, newBlockMarker: newBlockMarker, casing: maskdef.casing, def: maskdef.definitionSymbol || element, placeholder: maskdef.placeholder, mask: element }); } else mtoken.matches.splice(position++, 0, { fn: null, cardinality: 0, optionality: mtoken.isOptional, newBlockMarker: newBlockMarker, casing: null, def: element, placeholder: void 0, mask: element }), escaped = !1; } for (var match, m, openingToken, currentOpeningToken, alternator, lastMatch, tokenizer = /(?:[?*+]|\{[0-9\+\*]+(?:,[0-9\+\*]*)?\})\??|[^.?*+^${[]()|\\]+|./g, escaped = !1, currentToken = new maskToken(), openenings = [], maskTokens = []; match = tokenizer.exec(mask); ) switch (m = match[0], m.charAt(0)) { case opts.optionalmarker.end: case opts.groupmarker.end: if (openingToken = openenings.pop(), openenings.length > 0) { if (currentOpeningToken = openenings[openenings.length - 1], currentOpeningToken.matches.push(openingToken), currentOpeningToken.isAlternator) { alternator = openenings.pop(); for (var mndx = 0; mndx < alternator.matches.length; mndx++) alternator.matches[mndx].isGroup = !1; openenings.length > 0 ? (currentOpeningToken = openenings[openenings.length - 1], currentOpeningToken.matches.push(alternator)) : currentToken.matches.push(alternator); } } else currentToken.matches.push(openingToken); break; case opts.optionalmarker.start: openenings.push(new maskToken(!1, !0)); break; case opts.groupmarker.start: openenings.push(new maskToken(!0)); break; case opts.quantifiermarker.start: var quantifier = new maskToken(!1, !1, !0); m = m.replace(/[{}]/g, ""); var mq = m.split(","), mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]), mq1 = 1 == mq.length ? mq0 : isNaN(mq[1]) ? mq[1] : parseInt(mq[1]); if (("*" == mq1 || "+" == mq1) && (mq0 = "*" == mq1 ? 0 : 1), quantifier.quantifier = { min: mq0, max: mq1 }, openenings.length > 0) { var matches = openenings[openenings.length - 1].matches; if (match = matches.pop(), !match.isGroup) { var groupToken = new maskToken(!0); groupToken.matches.push(match), match = groupToken; } matches.push(match), matches.push(quantifier); } else { if (match = currentToken.matches.pop(), !match.isGroup) { var groupToken = new maskToken(!0); groupToken.matches.push(match), match = groupToken; } currentToken.matches.push(match), currentToken.matches.push(quantifier); } break; case opts.escapeChar: escaped = !0; break; case opts.alternatormarker: openenings.length > 0 ? (currentOpeningToken = openenings[openenings.length - 1], lastMatch = currentOpeningToken.matches.pop()) : lastMatch = currentToken.matches.pop(), lastMatch.isAlternator ? openenings.push(lastMatch) : (alternator = new maskToken(!1, !1, !1, !0), alternator.matches.push(lastMatch), openenings.push(alternator)); break; default: if (openenings.length > 0) { if (currentOpeningToken = openenings[openenings.length - 1], currentOpeningToken.matches.length > 0 && (lastMatch = currentOpeningToken.matches[currentOpeningToken.matches.length - 1], lastMatch.isGroup && (lastMatch.isGroup = !1, insertTestDefinition(lastMatch, opts.groupmarker.start, 0), insertTestDefinition(lastMatch, opts.groupmarker.end))), insertTestDefinition(currentOpeningToken, m), currentOpeningToken.isAlternator) { alternator = openenings.pop(); for (var mndx = 0; mndx < alternator.matches.length; mndx++) alternator.matches[mndx].isGroup = !1; openenings.length > 0 ? (currentOpeningToken = openenings[openenings.length - 1], currentOpeningToken.matches.push(alternator)) : currentToken.matches.push(alternator); } } else currentToken.matches.length > 0 && (lastMatch = currentToken.matches[currentToken.matches.length - 1], lastMatch.isGroup && (lastMatch.isGroup = !1, insertTestDefinition(lastMatch, opts.groupmarker.start, 0), insertTestDefinition(lastMatch, opts.groupmarker.end))), insertTestDefinition(currentToken, m); } return currentToken.matches.length > 0 && (lastMatch = currentToken.matches[currentToken.matches.length - 1], lastMatch.isGroup && (lastMatch.isGroup = !1, insertTestDefinition(lastMatch, opts.groupmarker.start, 0), insertTestDefinition(lastMatch, opts.groupmarker.end)), maskTokens.push(currentToken)), maskTokens; } function generateMask(mask, metadata) { if (opts.numericInput && opts.multi !== !0) { mask = mask.split("").reverse(); for (var ndx = 0; ndx < mask.length; ndx++) mask[ndx] == opts.optionalmarker.start ? mask[ndx] = opts.optionalmarker.end : mask[ndx] == opts.optionalmarker.end ? mask[ndx] = opts.optionalmarker.start : mask[ndx] == opts.groupmarker.start ? mask[ndx] = opts.groupmarker.end : mask[ndx] == opts.groupmarker.end && (mask[ndx] = opts.groupmarker.start); mask = mask.join(""); } if (void 0 == mask || "" == mask) return void 0; if (1 == mask.length && 0 == opts.greedy && 0 != opts.repeat && (opts.placeholder = ""), opts.repeat > 0 || "*" == opts.repeat || "+" == opts.repeat) { var repeatStart = "*" == opts.repeat ? 0 : "+" == opts.repeat ? 1 : opts.repeat; mask = opts.groupmarker.start + mask + opts.groupmarker.end + opts.quantifiermarker.start + repeatStart + "," + opts.repeat + opts.quantifiermarker.end; } return void 0 == $.inputmask.masksCache[mask] && ($.inputmask.masksCache[mask] = { mask: mask, maskToken: analyseMask(mask), validPositions: {}, _buffer: void 0, buffer: void 0, tests: {}, metadata: metadata }), $.extend(!0, {}, $.inputmask.masksCache[mask]); } var ms = void 0; if ($.isFunction(opts.mask) && (opts.mask = opts.mask.call(this, opts)), $.isArray(opts.mask)) if (multi) ms = [], $.each(opts.mask, function(ndx, msk) { ms.push(void 0 == msk.mask || $.isFunction(msk.mask) ? generateMask(msk.toString(), msk) : generateMask(msk.mask.toString(), msk)); }); else { opts.keepStatic = void 0 == opts.keepStatic ? !0 : opts.keepStatic; var altMask = "("; $.each(opts.mask, function(ndx, msk) { altMask.length > 1 && (altMask += ")|("), altMask += void 0 == msk.mask || $.isFunction(msk.mask) ? msk.toString() : msk.mask.toString(); }), altMask += ")", ms = generateMask(altMask, opts.mask); } else opts.mask && (ms = void 0 == opts.mask.mask || $.isFunction(opts.mask.mask) ? generateMask(opts.mask.toString(), opts.mask) : generateMask(opts.mask.mask.toString(), opts.mask)); return ms; } function maskScope(actionObj, maskset, opts) { function getMaskTemplate(baseOnInput, minimalPos, includeInput) { minimalPos = minimalPos || 0; var ndxIntlzr, test, testPos, maskTemplate = [], pos = 0; do { if (baseOnInput === !0 && getMaskSet().validPositions[pos]) { var validPos = getMaskSet().validPositions[pos]; test = validPos.match, ndxIntlzr = validPos.locator.slice(), maskTemplate.push(includeInput === !0 ? validPos.input : getPlaceholder(pos, test)); } else { if (minimalPos > pos) { var testPositions = getTests(pos, ndxIntlzr, pos - 1); testPos = testPositions[0]; } else testPos = getTestTemplate(pos, ndxIntlzr, pos - 1); test = testPos.match, ndxIntlzr = testPos.locator.slice(), maskTemplate.push(getPlaceholder(pos, test)); } pos++; } while ((void 0 == maxLength || maxLength > pos - 1) && null != test.fn || null == test.fn && "" != test.def || minimalPos >= pos); return maskTemplate.pop(), maskTemplate; } function getMaskSet() { return maskset; } function resetMaskSet(soft) { var maskset = getMaskSet(); maskset.buffer = void 0, maskset.tests = {}, soft !== !0 && (maskset._buffer = void 0, maskset.validPositions = {}, maskset.p = 0); } function getLastValidPosition(closestTo) { var maskset = getMaskSet(), lastValidPosition = -1, valids = maskset.validPositions; void 0 == closestTo && (closestTo = -1); var before = lastValidPosition, after = lastValidPosition; for (var posNdx in valids) { var psNdx = parseInt(posNdx); (-1 == closestTo || null != valids[psNdx].match.fn) && (closestTo > psNdx && (before = psNdx), psNdx >= closestTo && (after = psNdx)); } return lastValidPosition = closestTo - before > 1 || closestTo > after ? before : after; } function setValidPosition(pos, validTest, fromSetValid) { if (opts.insertMode && void 0 != getMaskSet().validPositions[pos] && void 0 == fromSetValid) { var i, positionsClone = $.extend(!0, {}, getMaskSet().validPositions), lvp = getLastValidPosition(); for (i = pos; lvp >= i; i++) delete getMaskSet().validPositions[i]; getMaskSet().validPositions[pos] = validTest; var j, valid = !0; for (i = pos; lvp >= i; i++) { var t = positionsClone[i]; if (void 0 != t) { var vps = getMaskSet().validPositions; j = !opts.keepStatic && (void 0 != vps[i + 1] && getTests(i + 1, vps[i].locator.slice(), i).length > 1 || vps[i] && void 0 != vps[i].alternation) ? i + 1 : seekNext(i), valid = positionCanMatchDefinition(j, t.match.def) ? valid && isValid(j, t.input, !0, !0) !== !1 : null == t.match.fn; } if (!valid) break; } if (!valid) return getMaskSet().validPositions = $.extend(!0, {}, positionsClone), !1; } else getMaskSet().validPositions[pos] = validTest; return !0; } function stripValidPositions(start, end) { var i, startPos = start; for (void 0 != getMaskSet().validPositions[start] && getMaskSet().validPositions[start].input == opts.radixPoint && (end++, startPos++), i = startPos; end > i; i++) void 0 == getMaskSet().validPositions[i] || getMaskSet().validPositions[i].input == opts.radixPoint && i != getLastValidPosition() || delete getMaskSet().validPositions[i]; for (i = end; i <= getLastValidPosition(); ) { var t = getMaskSet().validPositions[i], s = getMaskSet().validPositions[startPos]; void 0 != t && void 0 == s ? (positionCanMatchDefinition(startPos, t.match.def) && isValid(startPos, t.input, !0) !== !1 && (delete getMaskSet().validPositions[i], i++), startPos++) : i++; } var lvp = getLastValidPosition(); lvp >= start && void 0 != getMaskSet().validPositions[lvp] && getMaskSet().validPositions[lvp].input == opts.radixPoint && delete getMaskSet().validPositions[lvp], resetMaskSet(!0); } function getTestTemplate(pos, ndxIntlzr, tstPs) { for (var testPos, testPositions = getTests(pos, ndxIntlzr, tstPs), lvp = getLastValidPosition(), lvTest = getMaskSet().validPositions[lvp] || getTests(0)[0], lvTestAltArr = void 0 != lvTest.alternation ? lvTest.locator[lvTest.alternation].split(",") : [], ndx = 0; ndx < testPositions.length && (testPos = testPositions[ndx], !opts.greedy && (!testPos.match || testPos.match.optionality !== !1 && testPos.match.newBlockMarker !== !1 || testPos.match.optionalQuantifier === !0 || void 0 != lvTest.alternation && (void 0 == testPos.locator[lvTest.alternation] || -1 != $.inArray(testPos.locator[lvTest.alternation].toString(), lvTestAltArr)))); ndx++) ; return testPos; } function getTest(pos) { return getMaskSet().validPositions[pos] ? getMaskSet().validPositions[pos].match : getTests(pos)[0].match; } function positionCanMatchDefinition(pos, def) { for (var valid = !1, tests = getTests(pos), tndx = 0; tndx < tests.length; tndx++) if (tests[tndx].match && tests[tndx].match.def == def) { valid = !0; break; } return valid; } function getTests(pos, ndxIntlzr, tstPs) { function ResolveTestFromToken(maskToken, ndxInitializer, loopNdx, quantifierRecurse) { function handleMatch(match, loopNdx, quantifierRecurse) { if (testPos > 1e4) return alert("jquery.inputmask: There is probably an error in your mask definition or in the code. Create an issue on github with an example of the mask you are using. " + getMaskSet().mask), !0; if (testPos == pos && void 0 == match.matches) return matches.push({ match: match, locator: loopNdx.reverse() }), !0; if (void 0 != match.matches) { if (match.isGroup && quantifierRecurse !== !0) { if (match = handleMatch(maskToken.matches[tndx + 1], loopNdx)) return !0; } else if (match.isOptional) { var optionalToken = match; if (match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse)) { var latestMatch = matches[matches.length - 1].match, isFirstMatch = 0 == $.inArray(latestMatch, optionalToken.matches); isFirstMatch && (insertStop = !0), testPos = pos; } } else if (match.isAlternator) { var maltMatches, alternateToken = match, malternateMatches = [], currentMatches = matches.slice(), loopNdxCnt = loopNdx.length, altIndex = ndxInitializer.length > 0 ? ndxInitializer.shift() : -1; if (-1 == altIndex || "string" == typeof altIndex) { var altIndexArr, currentPos = testPos, ndxInitializerClone = ndxInitializer.slice(); "string" == typeof altIndex && (altIndexArr = altIndex.split(",")); for (var amndx = 0; amndx < alternateToken.matches.length; amndx++) { matches = [], match = handleMatch(alternateToken.matches[amndx], [ amndx ].concat(loopNdx), quantifierRecurse) || match, maltMatches = matches.slice(), testPos = currentPos, matches = []; for (var i = 0; i < ndxInitializerClone.length; i++) ndxInitializer[i] = ndxInitializerClone[i]; for (var ndx1 = 0; ndx1 < maltMatches.length; ndx1++) for (var altMatch = maltMatches[ndx1], ndx2 = 0; ndx2 < malternateMatches.length; ndx2++) { var altMatch2 = malternateMatches[ndx2]; if (altMatch.match.mask == altMatch2.match.mask && ("string" != typeof altIndex || -1 != $.inArray(altMatch.locator[loopNdxCnt].toString(), altIndexArr))) { maltMatches.splice(ndx1, 1), altMatch2.locator[loopNdxCnt] = altMatch2.locator[loopNdxCnt] + "," + altMatch.locator[loopNdxCnt], altMatch2.alternation = loopNdxCnt; break; } } malternateMatches = malternateMatches.concat(maltMatches); } "string" == typeof altIndex && (malternateMatches = $.map(malternateMatches, function(lmnt, ndx) { if (isFinite(ndx)) { var mamatch, altLocArr = lmnt.locator[loopNdxCnt].toString().split(","); lmnt.locator[loopNdxCnt] = void 0, lmnt.alternation = void 0; for (var alndx = 0; alndx < altLocArr.length; alndx++) mamatch = -1 != $.inArray(altLocArr[alndx], altIndexArr), mamatch && (void 0 != lmnt.locator[loopNdxCnt] ? (lmnt.locator[loopNdxCnt] += ",", lmnt.alternation = loopNdxCnt, lmnt.locator[loopNdxCnt] += altLocArr[alndx]) : lmnt.locator[loopNdxCnt] = parseInt(altLocArr[alndx])); if (void 0 != lmnt.locator[loopNdxCnt]) return lmnt; } })), matches = currentMatches.concat(malternateMatches), insertStop = !0; } else match = handleMatch(alternateToken.matches[altIndex], [ altIndex ].concat(loopNdx), quantifierRecurse); if (match) return !0; } else if (match.isQuantifier && quantifierRecurse !== !0) { var qt = match; opts.greedy = opts.greedy && isFinite(qt.quantifier.max); for (var qndx = ndxInitializer.length > 0 && quantifierRecurse !== !0 ? ndxInitializer.shift() : 0; qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max) && pos >= testPos; qndx++) { var tokenGroup = maskToken.matches[$.inArray(qt, maskToken.matches) - 1]; if (match = handleMatch(tokenGroup, [ qndx ].concat(loopNdx), !0)) { var latestMatch = matches[matches.length - 1].match; latestMatch.optionalQuantifier = qndx > qt.quantifier.min - 1; var isFirstMatch = 0 == $.inArray(latestMatch, tokenGroup.matches); if (isFirstMatch) { if (qndx > qt.quantifier.min - 1) { insertStop = !0, testPos = pos; break; } return !0; } return !0; } } } else if (match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse)) return !0; } else testPos++; } for (var tndx = ndxInitializer.length > 0 ? ndxInitializer.shift() : 0; tndx < maskToken.matches.length; tndx++) if (maskToken.matches[tndx].isQuantifier !== !0) { var match = handleMatch(maskToken.matches[tndx], [ tndx ].concat(loopNdx), quantifierRecurse); if (match && testPos == pos) return match; if (testPos > pos) break; } } var maskTokens = getMaskSet().maskToken, testPos = ndxIntlzr ? tstPs : 0, ndxInitializer = ndxIntlzr || [ 0 ], matches = [], insertStop = !1; if (void 0 == ndxIntlzr) { for (var test, previousPos = pos - 1; void 0 == (test = getMaskSet().validPositions[previousPos]) && previousPos > -1; ) previousPos--; if (void 0 != test && previousPos > -1) testPos = previousPos, ndxInitializer = test.locator.slice(); else { for (previousPos = pos - 1; void 0 == (test = getMaskSet().tests[previousPos]) && previousPos > -1; ) previousPos--; void 0 != test && previousPos > -1 && (testPos = previousPos, ndxInitializer = test[0].locator.slice()); } } for (var mtndx = ndxInitializer.shift(); mtndx < maskTokens.length; mtndx++) { var match = ResolveTestFromToken(maskTokens[mtndx], ndxInitializer, [ mtndx ]); if (match && testPos == pos || testPos > pos) break; } return (0 == matches.length || insertStop) && matches.push({ match: { fn: null, cardinality: 0, optionality: !0, casing: null, def: "" }, locator: [] }), getMaskSet().tests[pos] = $.extend(!0, [], matches), getMaskSet().tests[pos]; } function getBufferTemplate() { return void 0 == getMaskSet()._buffer && (getMaskSet()._buffer = getMaskTemplate(!1, 1)), getMaskSet()._buffer; } function getBuffer() { return void 0 == getMaskSet().buffer && (getMaskSet().buffer = getMaskTemplate(!0, getLastValidPosition(), !0)), getMaskSet().buffer; } function refreshFromBuffer(start, end) { var buffer = getBuffer().slice(); if (start === !0) resetMaskSet(), start = 0, end = buffer.length; else for (var i = start; end > i; i++) delete getMaskSet().validPositions[i], delete getMaskSet().tests[i]; for (var i = start; end > i; i++) buffer[i] != opts.skipOptionalPartCharacter && isValid(i, buffer[i], !0, !0); } function casing(elem, test) { switch (test.casing) { case "upper": elem = elem.toUpperCase(); break; case "lower": elem = elem.toLowerCase(); } return elem; } function isValid(pos, c, strict, fromSetValid) { function _isValid(position, c, strict, fromSetValid) { var rslt = !1; return $.each(getTests(position), function(ndx, tst) { for (var test = tst.match, loopend = c ? 1 : 0, chrs = "", i = (getBuffer(), test.cardinality); i > loopend; i--) chrs += getBufferElement(position - (i - 1)); if (c && (chrs += c), rslt = null != test.fn ? test.fn.test(chrs, getMaskSet(), position, strict, opts) : c != test.def && c != opts.skipOptionalPartCharacter || "" == test.def ? !1 : { c: test.def, pos: position }, rslt !== !1) { var elem = void 0 != rslt.c ? rslt.c : c; elem = elem == opts.skipOptionalPartCharacter && null === test.fn ? test.def : elem; var validatedPos = position; if (void 0 != rslt.remove && stripValidPositions(rslt.remove, rslt.remove + 1), rslt.refreshFromBuffer) { var refresh = rslt.refreshFromBuffer; if (strict = !0, refreshFromBuffer(refresh === !0 ? refresh : refresh.start, refresh.end), void 0 == rslt.pos && void 0 == rslt.c) return rslt.pos = getLastValidPosition(), !1; if (validatedPos = void 0 != rslt.pos ? rslt.pos : position, validatedPos != position) return rslt = $.extend(rslt, isValid(validatedPos, elem, !0)), !1; } else if (rslt !== !0 && void 0 != rslt.pos && rslt.pos != position && (validatedPos = rslt.pos, refreshFromBuffer(position, validatedPos), validatedPos != position)) return rslt = $.extend(rslt, isValid(validatedPos, elem, !0)), !1; return 1 != rslt && void 0 == rslt.pos && void 0 == rslt.c ? !1 : (ndx > 0 && resetMaskSet(!0), setValidPosition(validatedPos, $.extend({}, tst, { input: casing(elem, test) }), fromSetValid) || (rslt = !1), !1); } }), rslt; } function alternate(pos, c, strict, fromSetValid) { var lastAlt, alternation, validPsClone = $.extend(!0, {}, getMaskSet().validPositions); for (lastAlt = getLastValidPosition(); lastAlt >= 0; lastAlt--) if (getMaskSet().validPositions[lastAlt] && void 0 != getMaskSet().validPositions[lastAlt].alternation) { alternation = getMaskSet().validPositions[lastAlt].alternation; break; } if (void 0 != alternation) for (var decisionPos in getMaskSet().validPositions) if (parseInt(decisionPos) > parseInt(lastAlt) && void 0 === getMaskSet().validPositions[decisionPos].alternation) { for (var altPos = getMaskSet().validPositions[decisionPos], decisionTaker = altPos.locator[alternation], altNdxs = getMaskSet().validPositions[lastAlt].locator[alternation].split(","), mndx = 0; mndx < altNdxs.length; mndx++) if (decisionTaker < altNdxs[mndx]) { for (var possibilityPos, possibilities, dp = decisionPos - 1; dp >= 0; dp--) if (possibilityPos = getMaskSet().validPositions[dp], void 0 != possibilityPos) { possibilities = possibilityPos.locator[alternation], possibilityPos.locator[alternation] = altNdxs[mndx]; break; } if (decisionTaker != possibilityPos.locator[alternation]) { for (var buffer = getBuffer().slice(), i = decisionPos; i < getLastValidPosition() + 1; i++) delete getMaskSet().validPositions[i], delete getMaskSet().tests[i]; resetMaskSet(!0), opts.keepStatic = !opts.keepStatic; for (var i = decisionPos; i < buffer.length; i++) buffer[i] != opts.skipOptionalPartCharacter && isValid(getLastValidPosition() + 1, buffer[i], !1, !0); possibilityPos.locator[alternation] = possibilities; var isValidRslt = isValid(pos, c, strict, fromSetValid); if (opts.keepStatic = !opts.keepStatic, isValidRslt) return isValidRslt; resetMaskSet(), getMaskSet().validPositions = $.extend(!0, {}, validPsClone); } } break; } return !1; } strict = strict === !0; for (var buffer = getBuffer(), pndx = pos - 1; pndx > -1 && (!getMaskSet().validPositions[pndx] || null != getMaskSet().validPositions[pndx].match.fn); pndx--) void 0 == getMaskSet().validPositions[pndx] && (!isMask(pndx) || buffer[pndx] != getPlaceholder(pndx)) && getTests(pndx).length > 1 && _isValid(pndx, buffer[pndx], !0); var maskPos = pos, result = !1; if (fromSetValid && maskPos >= getMaskLength() && resetMaskSet(!0), maskPos < getMaskLength() && (result = _isValid(maskPos, c, strict, fromSetValid), !strict && result === !1)) { var currentPosValid = getMaskSet().validPositions[maskPos]; if (!currentPosValid || null != currentPosValid.match.fn || currentPosValid.match.def != c && c != opts.skipOptionalPartCharacter) { if ((opts.insertMode || void 0 == getMaskSet().validPositions[seekNext(maskPos)]) && !isMask(maskPos)) for (var nPos = maskPos + 1, snPos = seekNext(maskPos); snPos >= nPos; nPos++) if (result = _isValid(nPos, c, strict, fromSetValid), result !== !1) { maskPos = nPos; break; } } else result = { caret: seekNext(maskPos) }; } return result === !1 && opts.keepStatic && isComplete(buffer) && (result = alternate(pos, c, strict, fromSetValid)), result === !0 && (result = { pos: maskPos }), result; } function isMask(pos) { var test = getTest(pos); return null != test.fn ? test.fn : !1; } function getMaskLength() { var maskLength; if (maxLength = $el.prop("maxLength"), -1 == maxLength && (maxLength = void 0), 0 == opts.greedy) { var pos, lvp = getLastValidPosition(), testPos = getMaskSet().validPositions[lvp], ndxIntlzr = void 0 != testPos ? testPos.locator.slice() : void 0; for (pos = lvp + 1; void 0 == testPos || null != testPos.match.fn || null == testPos.match.fn && "" != testPos.match.def; pos++) testPos = getTestTemplate(pos, ndxIntlzr, pos - 1), ndxIntlzr = testPos.locator.slice(); maskLength = pos; } else maskLength = getBuffer().length; return void 0 == maxLength || maxLength > maskLength ? maskLength : maxLength; } function seekNext(pos) { var maskL = getMaskLength(); if (pos >= maskL) return maskL; for (var position = pos; ++position < maskL && !isMask(position) && (opts.nojumps !== !0 || opts.nojumpsThreshold > position); ) ; return position; } function seekPrevious(pos) { var position = pos; if (0 >= position) return 0; for (;--position > 0 && !isMask(position); ) ; return position; } function getBufferElement(position) { return void 0 == getMaskSet().validPositions[position] ? getPlaceholder(position) : getMaskSet().validPositions[position].input; } function writeBuffer(input, buffer, caretPos) { input._valueSet(buffer.join("")), void 0 != caretPos && caret(input, caretPos); } function getPlaceholder(pos, test) { test = test || getTest(pos); var placeholder = $.isFunction(test.placeholder) ? test.placeholder.call(this, opts) : test.placeholder; return void 0 != placeholder ? placeholder : null == test.fn ? test.def : opts.placeholder.charAt(pos % opts.placeholder.length); } function checkVal(input, writeOut, strict, nptvl, intelliCheck) { var inputValue = void 0 != nptvl ? nptvl.slice() : truncateInput(input._valueGet()).split(""); if (resetMaskSet(), writeOut && input._valueSet(""), $.each(inputValue, function(ndx, charCode) { if (intelliCheck === !0) { var lvp = getLastValidPosition(), pos = -1 == lvp ? ndx : seekNext(lvp); -1 == $.inArray(charCode, getBufferTemplate().slice(lvp + 1, pos)) && keypressEvent.call(input, void 0, !0, charCode.charCodeAt(0), !1, strict, strict ? ndx : getMaskSet().p); } else keypressEvent.call(input, void 0, !0, charCode.charCodeAt(0), !1, strict, strict ? ndx : getMaskSet().p), strict = strict || ndx > 0 && ndx > getMaskSet().p; }), writeOut) { var keypressResult = opts.onKeyPress.call(this, void 0, getBuffer(), 0, opts); handleOnKeyResult(input, keypressResult), writeBuffer(input, getBuffer(), $(input).is(":focus") ? seekNext(getLastValidPosition(0)) : void 0); } } function escapeRegex(str) { return $.inputmask.escapeRegex.call(this, str); } function truncateInput(inputValue) { return inputValue.replace(new RegExp("(" + escapeRegex(getBufferTemplate().join("")) + ")*$"), ""); } function unmaskedvalue($input) { if ($input.data("_inputmask") && !$input.hasClass("hasDatepicker")) { var umValue = [], vps = getMaskSet().validPositions; for (var pndx in vps) vps[pndx].match && null != vps[pndx].match.fn && umValue.push(vps[pndx].input); var unmaskedValue = (isRTL ? umValue.reverse() : umValue).join(""), bufferValue = (isRTL ? getBuffer().slice().reverse() : getBuffer()).join(""); return $.isFunction(opts.onUnMask) && (unmaskedValue = opts.onUnMask.call($input, bufferValue, unmaskedValue, opts) || unmaskedValue), unmaskedValue; } return $input[0]._valueGet(); } function TranslatePosition(pos) { if (isRTL && "number" == typeof pos && (!opts.greedy || "" != opts.placeholder)) { var bffrLght = getBuffer().length; pos = bffrLght - pos; } return pos; } function caret(input, begin, end) { var range, npt = input.jquery && input.length > 0 ? input[0] : input; if ("number" != typeof begin) { var data = $(npt).data("_inputmask"); return !$(npt).is(":visible") && data && void 0 != data.caret ? (begin = data.caret.begin, end = data.caret.end) : npt.setSelectionRange ? (begin = npt.selectionStart, end = npt.selectionEnd) : document.selection && document.selection.createRange && (range = document.selection.createRange(), begin = 0 - range.duplicate().moveStart("character", -1e5), end = begin + range.text.length), begin = TranslatePosition(begin), end = TranslatePosition(end), { begin: begin, end: end }; } begin = TranslatePosition(begin), end = TranslatePosition(end), end = "number" == typeof end ? end : begin; var data = $(npt).data("_inputmask") || {}; data.caret = { begin: begin, end: end }, $(npt).data("_inputmask", data), $(npt).is(":visible") && (npt.scrollLeft = npt.scrollWidth, 0 == opts.insertMode && begin == end && end++, npt.setSelectionRange ? (npt.selectionStart = begin, npt.selectionEnd = end) : npt.createTextRange && (range = npt.createTextRange(), range.collapse(!0), range.moveEnd("character", end), range.moveStart("character", begin), range.select())); } function determineLastRequiredPosition(returnDefinition) { var pos, testPos, buffer = getBuffer(), bl = buffer.length, lvp = getLastValidPosition(), positions = {}, lvTest = getMaskSet().validPositions[lvp], ndxIntlzr = void 0 != lvTest ? lvTest.locator.slice() : void 0; for (pos = lvp + 1; pos < buffer.length; pos++) testPos = getTestTemplate(pos, ndxIntlzr, pos - 1), ndxIntlzr = testPos.locator.slice(), positions[pos] = $.extend(!0, {}, testPos); var lvTestAltArr = lvTest && void 0 != lvTest.alternation ? lvTest.locator[lvTest.alternation].split(",") : []; for (pos = bl - 1; pos > lvp && (testPos = positions[pos].match, (testPos.optionality || testPos.optionalQuantifier || lvTest && void 0 != lvTest.alternation && void 0 != positions[pos].locator[lvTest.alternation] && -1 != $.inArray(positions[pos].locator[lvTest.alternation].toString(), lvTestAltArr)) && buffer[pos] == getPlaceholder(pos, testPos)); pos--) bl--; return returnDefinition ? { l: bl, def: positions[bl] ? positions[bl].match : void 0 } : bl; } function clearOptionalTail(input) { for (var buffer = getBuffer(), tmpBuffer = buffer.slice(), rl = determineLastRequiredPosition(), lmib = tmpBuffer.length - 1; lmib > rl && !isMask(lmib); lmib--) ; tmpBuffer.splice(rl, lmib + 1 - rl), writeBuffer(input, tmpBuffer); } function isComplete(buffer) { if ($.isFunction(opts.isComplete)) return opts.isComplete.call($el, buffer, opts); if ("*" == opts.repeat) return void 0; var complete = !1, lrp = determineLastRequiredPosition(!0), aml = seekPrevious(lrp.l), lvp = getLastValidPosition(); if (lvp == aml && (void 0 == lrp.def || lrp.def.newBlockMarker || lrp.def.optionalQuantifier)) { complete = !0; for (var i = 0; aml >= i; i++) { var mask = isMask(i); if (mask && (void 0 == buffer[i] || buffer[i] == getPlaceholder(i)) || !mask && buffer[i] != getPlaceholder(i)) { complete = !1; break; } } } return complete; } function isSelection(begin, end) { return isRTL ? begin - end > 1 || begin - end == 1 && opts.insertMode : end - begin > 1 || end - begin == 1 && opts.insertMode; } function installEventRuler(npt) { var events = $._data(npt).events; $.each(events, function(eventType, eventHandlers) { $.each(eventHandlers, function(ndx, eventHandler) { if ("inputmask" == eventHandler.namespace && "setvalue" != eventHandler.type) { var handler = eventHandler.handler; eventHandler.handler = function(e) { return this.readOnly || this.disabled ? void e.preventDefault : handler.apply(this, arguments); }; } }); }); } function patchValueProperty(npt) { function PatchValhook(type) { if (void 0 == $.valHooks[type] || 1 != $.valHooks[type].inputmaskpatch) { var valueGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function(elem) { return elem.value; }, valueSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function(elem, value) { return elem.value = value, elem; }; $.valHooks[type] = { get: function(elem) { var $elem = $(elem); if ($elem.data("_inputmask")) { if ($elem.data("_inputmask").opts.autoUnmask) return $elem.inputmask("unmaskedvalue"); var result = valueGet(elem), inputData = $elem.data("_inputmask"), maskset = inputData.maskset, bufferTemplate = maskset._buffer; return bufferTemplate = bufferTemplate ? bufferTemplate.join("") : "", result != bufferTemplate ? result : ""; } return valueGet(elem); }, set: function(elem, value) { var result, $elem = $(elem), inputData = $elem.data("_inputmask"); return inputData ? (result = valueSet(elem, $.isFunction(inputData.opts.onBeforeMask) ? inputData.opts.onBeforeMask.call(el, value, inputData.opts) || value : value), $elem.triggerHandler("setvalue.inputmask")) : result = valueSet(elem, value), result; }, inputmaskpatch: !0 }; } } function getter() { var $self = $(this), inputData = $(this).data("_inputmask"); return inputData ? inputData.opts.autoUnmask ? $self.inputmask("unmaskedvalue") : valueGet.call(this) != getBufferTemplate().join("") ? valueGet.call(this) : "" : valueGet.call(this); } function setter(value) { var inputData = $(this).data("_inputmask"); inputData ? (valueSet.call(this, $.isFunction(inputData.opts.onBeforeMask) ? inputData.opts.onBeforeMask.call(el, value, inputData.opts) || value : value), $(this).triggerHandler("setvalue.inputmask")) : valueSet.call(this, value); } function InstallNativeValueSetFallback(npt) { $(npt).bind("mouseenter.inputmask", function() { var $input = $(this), input = this, value = input._valueGet(); "" != value && value != getBuffer().join("") && $input.trigger("setvalue"); }); var events = $._data(npt).events, handlers = events.mouseover; if (handlers) { for (var ourHandler = handlers[handlers.length - 1], i = handlers.length - 1; i > 0; i--) handlers[i] = handlers[i - 1]; handlers[0] = ourHandler; } } var valueGet, valueSet; if (!npt._valueGet) { if (Object.getOwnPropertyDescriptor) { Object.getOwnPropertyDescriptor(npt, "value"); } document.__lookupGetter__ && npt.__lookupGetter__("value") ? (valueGet = npt.__lookupGetter__("value"), valueSet = npt.__lookupSetter__("value"), npt.__defineGetter__("value", getter), npt.__defineSetter__("value", setter)) : (valueGet = function() { return npt.value; }, valueSet = function(value) { npt.value = value; }, PatchValhook(npt.type), InstallNativeValueSetFallback(npt)), npt._valueGet = function() { return isRTL ? valueGet.call(this).split("").reverse().join("") : valueGet.call(this); }, npt._valueSet = function(value) { valueSet.call(this, isRTL ? value.split("").reverse().join("") : value); }; } } function handleRemove(input, k, pos) { function generalize() { if (opts.keepStatic) { resetMaskSet(!0); var lastAlt, validInputs = []; for (lastAlt = getLastValidPosition(); lastAlt >= 0; lastAlt--) if (getMaskSet().validPositions[lastAlt]) { if (void 0 != getMaskSet().validPositions[lastAlt].alternation) break; validInputs.push(getMaskSet().validPositions[lastAlt].input), delete getMaskSet().validPositions[lastAlt]; } if (lastAlt > 0) for (;validInputs.length > 0; ) getMaskSet().p = seekNext(getLastValidPosition()), keypressEvent.call(input, void 0, !0, validInputs.pop().charCodeAt(0), !1, !1, getMaskSet().p); } } if ((opts.numericInput || isRTL) && (k == $.inputmask.keyCode.BACKSPACE ? k = $.inputmask.keyCode.DELETE : k == $.inputmask.keyCode.DELETE && (k = $.inputmask.keyCode.BACKSPACE), isRTL)) { var pend = pos.end; pos.end = pos.begin, pos.begin = pend; } k == $.inputmask.keyCode.BACKSPACE && pos.end - pos.begin <= 1 ? pos.begin = seekPrevious(pos.begin) : k == $.inputmask.keyCode.DELETE && pos.begin == pos.end && pos.end++, stripValidPositions(pos.begin, pos.end), generalize(); var firstMaskedPos = getLastValidPosition(pos.begin); firstMaskedPos < pos.begin ? (-1 == firstMaskedPos && resetMaskSet(), getMaskSet().p = seekNext(firstMaskedPos)) : getMaskSet().p = pos.begin; } function handleOnKeyResult(input, keyResult, caretPos) { if (keyResult && keyResult.refreshFromBuffer) { var refresh = keyResult.refreshFromBuffer; refreshFromBuffer(refresh === !0 ? refresh : refresh.start, refresh.end), resetMaskSet(!0), void 0 != caretPos && (writeBuffer(input, getBuffer()), caret(input, keyResult.caret || caretPos.begin, keyResult.caret || caretPos.end)); } } function keydownEvent(e) { skipKeyPressEvent = !1; var input = this, $input = $(input), k = e.keyCode, pos = caret(input); k == $.inputmask.keyCode.BACKSPACE || k == $.inputmask.keyCode.DELETE || iphone && 127 == k || e.ctrlKey && 88 == k ? (e.preventDefault(), 88 == k && (valueOnFocus = getBuffer().join("")), handleRemove(input, k, pos), writeBuffer(input, getBuffer(), getMaskSet().p), input._valueGet() == getBufferTemplate().join("") && $input.trigger("cleared"), opts.showTooltip && $input.prop("title", getMaskSet().mask)) : k == $.inputmask.keyCode.END || k == $.inputmask.keyCode.PAGE_DOWN ? setTimeout(function() { var caretPos = seekNext(getLastValidPosition()); opts.insertMode || caretPos != getMaskLength() || e.shiftKey || caretPos--, caret(input, e.shiftKey ? pos.begin : caretPos, caretPos); }, 0) : k == $.inputmask.keyCode.HOME && !e.shiftKey || k == $.inputmask.keyCode.PAGE_UP ? caret(input, 0, e.shiftKey ? pos.begin : 0) : k == $.inputmask.keyCode.ESCAPE || 90 == k && e.ctrlKey ? (checkVal(input, !0, !1, valueOnFocus.split("")), $input.click()) : k != $.inputmask.keyCode.INSERT || e.shiftKey || e.ctrlKey ? 0 != opts.insertMode || e.shiftKey || (k == $.inputmask.keyCode.RIGHT ? setTimeout(function() { var caretPos = caret(input); caret(input, caretPos.begin); }, 0) : k == $.inputmask.keyCode.LEFT && setTimeout(function() { var caretPos = caret(input); caret(input, isRTL ? caretPos.begin + 1 : caretPos.begin - 1); }, 0)) : (opts.insertMode = !opts.insertMode, caret(input, opts.insertMode || pos.begin != getMaskLength() ? pos.begin : pos.begin - 1)); var currentCaretPos = caret(input), keydownResult = opts.onKeyDown.call(this, e, getBuffer(), currentCaretPos.begin, opts); handleOnKeyResult(input, keydownResult, currentCaretPos), ignorable = -1 != $.inArray(k, opts.ignorables); } function keypressEvent(e, checkval, k, writeOut, strict, ndx) { if (void 0 == k && skipKeyPressEvent) return !1; skipKeyPressEvent = !0; var input = this, $input = $(input); e = e || window.event; var k = checkval ? k : e.which || e.charCode || e.keyCode; if (!(checkval === !0 || e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable)) return !0; if (k) { checkval !== !0 && 46 == k && 0 == e.shiftKey && "," == opts.radixPoint && (k = 44); var forwardPosition, pos = checkval ? { begin: ndx, end: ndx } : caret(input), c = String.fromCharCode(k), isSlctn = isSelection(pos.begin, pos.end); isSlctn && (getMaskSet().undoPositions = $.extend(!0, {}, getMaskSet().validPositions), handleRemove(input, $.inputmask.keyCode.DELETE, pos), opts.insertMode || (opts.insertMode = !opts.insertMode, setValidPosition(pos.begin, strict), opts.insertMode = !opts.insertMode), isSlctn = !opts.multi), getMaskSet().writeOutBuffer = !0; var p = isRTL && !isSlctn ? pos.end : pos.begin, valResult = isValid(p, c, strict); if (valResult !== !1) { if (valResult !== !0 && (p = void 0 != valResult.pos ? valResult.pos : p, c = void 0 != valResult.c ? valResult.c : c), resetMaskSet(!0), void 0 != valResult.caret) forwardPosition = valResult.caret; else { var vps = getMaskSet().validPositions; forwardPosition = !opts.keepStatic && (void 0 != vps[p + 1] && getTests(p + 1, vps[p].locator.slice(), p).length > 1 || void 0 != vps[p].alternation) ? p + 1 : seekNext(p); } getMaskSet().p = forwardPosition; } if (writeOut !== !1) { var self = this; if (setTimeout(function() { opts.onKeyValidation.call(self, valResult, opts); }, 0), getMaskSet().writeOutBuffer && valResult !== !1) { var buffer = getBuffer(); writeBuffer(input, buffer, checkval ? void 0 : opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition), checkval !== !0 && setTimeout(function() { isComplete(buffer) === !0 && $input.trigger("complete"), skipInputEvent = !0, $input.trigger("input"); }, 0); } else isSlctn && (getMaskSet().buffer = void 0, getMaskSet().validPositions = getMaskSet().undoPositions); } else isSlctn && (getMaskSet().buffer = void 0, getMaskSet().validPositions = getMaskSet().undoPositions); if (opts.showTooltip && $input.prop("title", getMaskSet().mask), e && 1 != checkval) { e.preventDefault(); var currentCaretPos = caret(input), keypressResult = opts.onKeyPress.call(this, e, getBuffer(), currentCaretPos.begin, opts); handleOnKeyResult(input, keypressResult, currentCaretPos); } } } function keyupEvent(e) { var $input = $(this), input = this, k = e.keyCode, buffer = getBuffer(), currentCaretPos = caret(input), keyupResult = opts.onKeyUp.call(this, e, buffer, currentCaretPos.begin, opts); handleOnKeyResult(input, keyupResult, currentCaretPos), k == $.inputmask.keyCode.TAB && opts.showMaskOnFocus && ($input.hasClass("focus-inputmask") && 0 == input._valueGet().length ? (resetMaskSet(), buffer = getBuffer(), writeBuffer(input, buffer), caret(input, 0), valueOnFocus = getBuffer().join("")) : (writeBuffer(input, buffer), caret(input, TranslatePosition(0), TranslatePosition(getMaskLength())))); } function pasteEvent(e) { if (skipInputEvent === !0 && "input" == e.type) return skipInputEvent = !1, !0; var input = this, $input = $(input), inputValue = input._valueGet(); if ("propertychange" == e.type && input._valueGet().length <= getMaskLength()) return !0; "paste" == e.type && (window.clipboardData && window.clipboardData.getData ? inputValue = window.clipboardData.getData("Text") : e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.getData && (inputValue = e.originalEvent.clipboardData.getData("text/plain"))); var pasteValue = $.isFunction(opts.onBeforePaste) ? opts.onBeforePaste.call(input, inputValue, opts) || inputValue : inputValue; return checkVal(input, !0, !1, isRTL ? pasteValue.split("").reverse() : pasteValue.split(""), !0), $input.click(), isComplete(getBuffer()) === !0 && $input.trigger("complete"), !1; } function mobileInputEvent(e) { if (skipInputEvent === !0 && "input" == e.type) return skipInputEvent = !1, !0; var input = this, caretPos = caret(input), currentValue = input._valueGet(); currentValue = currentValue.replace(new RegExp("(" + escapeRegex(getBufferTemplate().join("")) + ")*"), ""), caretPos.begin > currentValue.length && (caret(input, currentValue.length), caretPos = caret(input)), getBuffer().length - currentValue.length != 1 || currentValue.charAt(caretPos.begin) == getBuffer()[caretPos.begin] || currentValue.charAt(caretPos.begin + 1) == getBuffer()[caretPos.begin] || isMask(caretPos.begin) || (e.keyCode = $.inputmask.keyCode.BACKSPACE, keydownEvent.call(input, e)), e.preventDefault(); } function inputFallBackEvent(e) { if (skipInputEvent === !0 && "input" == e.type) return skipInputEvent = !1, !0; var input = this, caretPos = caret(input), currentValue = input._valueGet(); caret(input, caretPos.begin - 1); var keypress = $.Event("keypress"); keypress.which = currentValue.charCodeAt(caretPos.begin - 1), skipKeyPressEvent = !1, ignorable = !1, keypressEvent.call(input, keypress, void 0, void 0, !1); var forwardPosition = getMaskSet().p; writeBuffer(input, getBuffer(), opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition), e.preventDefault(); } function compositionupdateEvent(e) { skipInputEvent = !0; var input = this; return setTimeout(function() { caret(input, caret(input).begin - 1); var keypress = $.Event("keypress"); keypress.which = e.originalEvent.data.charCodeAt(0), skipKeyPressEvent = !1, ignorable = !1, keypressEvent.call(input, keypress, void 0, void 0, !1); var forwardPosition = getMaskSet().p; writeBuffer(input, getBuffer(), opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition); }, 0), !1; } function mask(el) { if ($el = $(el), $el.is(":input") && isInputTypeSupported($el.attr("type"))) { if ($el.data("_inputmask", { maskset: maskset, opts: opts, isRTL: !1 }), opts.showTooltip && $el.prop("title", getMaskSet().mask), ("rtl" == el.dir || opts.rightAlign) && $el.css("text-align", "right"), "rtl" == el.dir || opts.numericInput) { el.dir = "ltr", $el.removeAttr("dir"); var inputData = $el.data("_inputmask"); inputData.isRTL = !0, $el.data("_inputmask", inputData), isRTL = !0; } $el.unbind(".inputmask"), $el.removeClass("focus-inputmask"), $el.closest("form").bind("submit", function() { valueOnFocus != getBuffer().join("") && $el.change(), $el[0]._valueGet && $el[0]._valueGet() == getBufferTemplate().join("") && $el[0]._valueSet(""), opts.autoUnmask && opts.removeMaskOnSubmit && $el.inputmask("remove"); }).bind("reset", function() { setTimeout(function() { $el.trigger("setvalue"); }, 0); }), $el.bind("mouseenter.inputmask", function() { var $input = $(this), input = this; !$input.hasClass("focus-inputmask") && opts.showMaskOnHover && input._valueGet() != getBuffer().join("") && writeBuffer(input, getBuffer()); }).bind("blur.inputmask", function() { var $input = $(this), input = this; if ($input.data("_inputmask")) { var nptValue = input._valueGet(), buffer = getBuffer(); $input.removeClass("focus-inputmask"), valueOnFocus != getBuffer().join("") && $input.change(), opts.clearMaskOnLostFocus && "" != nptValue && (nptValue == getBufferTemplate().join("") ? input._valueSet("") : clearOptionalTail(input)), isComplete(buffer) === !1 && ($input.trigger("incomplete"), opts.clearIncomplete && (resetMaskSet(), opts.clearMaskOnLostFocus ? input._valueSet("") : (buffer = getBufferTemplate().slice(), writeBuffer(input, buffer)))); } }).bind("focus.inputmask", function() { var $input = $(this), input = this, nptValue = input._valueGet(); opts.showMaskOnFocus && !$input.hasClass("focus-inputmask") && (!opts.showMaskOnHover || opts.showMaskOnHover && "" == nptValue) && input._valueGet() != getBuffer().join("") && writeBuffer(input, getBuffer(), seekNext(getLastValidPosition())), $input.addClass("focus-inputmask"), valueOnFocus = getBuffer().join(""); }).bind("mouseleave.inputmask", function() { var $input = $(this), input = this; opts.clearMaskOnLostFocus && ($input.hasClass("focus-inputmask") || input._valueGet() == $input.attr("placeholder") || (input._valueGet() == getBufferTemplate().join("") || "" == input._valueGet() ? input._valueSet("") : clearOptionalTail(input))); }).bind("click.inputmask", function() { var input = this; $(input).is(":focus") && setTimeout(function() { var selectedCaret = caret(input); if (selectedCaret.begin == selectedCaret.end) if (opts.radixFocus && "" != opts.radixPoint && -1 != $.inArray(opts.radixPoint, getBuffer()) && getBuffer().join("") == getBufferTemplate().join("")) caret(input, $.inArray(opts.radixPoint, getBuffer())); else { var clickPosition = isRTL ? TranslatePosition(selectedCaret.begin) : selectedCaret.begin, lastPosition = seekNext(getLastValidPosition(clickPosition)); lastPosition > clickPosition ? caret(input, isMask(clickPosition) ? clickPosition : seekNext(clickPosition)) : caret(input, lastPosition); } }, 0); }).bind("dblclick.inputmask", function() { var input = this; setTimeout(function() { caret(input, 0, seekNext(getLastValidPosition())); }, 0); }).bind(PasteEventType + ".inputmask dragdrop.inputmask drop.inputmask", pasteEvent).bind("setvalue.inputmask", function() { var input = this; checkVal(input, !0, !1, void 0, !0), valueOnFocus = getBuffer().join(""), (opts.clearMaskOnLostFocus || opts.clearIncomplete) && input._valueGet() == getBufferTemplate().join("") && input._valueSet(""); }).bind("complete.inputmask", opts.oncomplete).bind("incomplete.inputmask", opts.onincomplete).bind("cleared.inputmask", opts.oncleared), $el.bind("keydown.inputmask", keydownEvent).bind("keypress.inputmask", keypressEvent).bind("keyup.inputmask", keyupEvent).bind("compositionupdate.inputmask", compositionupdateEvent), "paste" !== PasteEventType || msie1x || $el.bind("input.inputmask", inputFallBackEvent), msie1x && $el.bind("input.inputmask", pasteEvent), (android || androidfirefox || androidchrome || kindle) && ("input" == PasteEventType && $el.unbind(PasteEventType + ".inputmask"), $el.bind("input.inputmask", mobileInputEvent)), patchValueProperty(el); var initialValue = $.isFunction(opts.onBeforeMask) ? opts.onBeforeMask.call(el, el._valueGet(), opts) || el._valueGet() : el._valueGet(); checkVal(el, !0, !1, initialValue.split(""), !0), valueOnFocus = getBuffer().join(""); var activeElement; try { activeElement = document.activeElement; } catch (e) {} isComplete(getBuffer()) === !1 && opts.clearIncomplete && resetMaskSet(), opts.clearMaskOnLostFocus ? getBuffer().join("") == getBufferTemplate().join("") ? el._valueSet("") : clearOptionalTail(el) : writeBuffer(el, getBuffer()), activeElement === el && ($el.addClass("focus-inputmask"), caret(el, seekNext(getLastValidPosition()))), installEventRuler(el); } } var valueOnFocus, $el, maxLength, isRTL = !1, skipKeyPressEvent = !1, skipInputEvent = !1, ignorable = !1; if (void 0 != actionObj) switch (actionObj.action) { case "isComplete": return $el = $(actionObj.el), maskset = $el.data("_inputmask").maskset, opts = $el.data("_inputmask").opts, isComplete(actionObj.buffer); case "unmaskedvalue": return $el = actionObj.$input, maskset = $el.data("_inputmask").maskset, opts = $el.data("_inputmask").opts, isRTL = actionObj.$input.data("_inputmask").isRTL, unmaskedvalue(actionObj.$input); case "mask": valueOnFocus = getBuffer().join(""), mask(actionObj.el); break; case "format": $el = $({}), $el.data("_inputmask", { maskset: maskset, opts: opts, isRTL: opts.numericInput }), opts.numericInput && (isRTL = !0); var valueBuffer = ($.isFunction(opts.onBeforeMask) ? opts.onBeforeMask.call($el, actionObj.value, opts) || actionObj.value : actionObj.value).split(""); return checkVal($el, !1, !1, isRTL ? valueBuffer.reverse() : valueBuffer, !0), opts.onKeyPress.call(this, void 0, getBuffer(), 0, opts), actionObj.metadata ? { value: isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join(""), metadata: $el.inputmask("getmetadata") } : isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join(""); case "isValid": $el = $({}), $el.data("_inputmask", { maskset: maskset, opts: opts, isRTL: opts.numericInput }), opts.numericInput && (isRTL = !0); var valueBuffer = actionObj.value.split(""); checkVal($el, !1, !0, isRTL ? valueBuffer.reverse() : valueBuffer); for (var buffer = getBuffer(), rl = determineLastRequiredPosition(), lmib = buffer.length - 1; lmib > rl && !isMask(lmib); lmib--) ; return buffer.splice(rl, lmib + 1 - rl), isComplete(buffer) && actionObj.value == buffer.join(""); case "getemptymask": return $el = $(actionObj.el), maskset = $el.data("_inputmask").maskset, opts = $el.data("_inputmask").opts, getBufferTemplate(); case "remove": var el = actionObj.el; $el = $(el), maskset = $el.data("_inputmask").maskset, opts = $el.data("_inputmask").opts, el._valueSet(unmaskedvalue($el)), $el.unbind(".inputmask"), $el.removeClass("focus-inputmask"), $el.removeData("_inputmask"); var valueProperty; Object.getOwnPropertyDescriptor && (valueProperty = Object.getOwnPropertyDescriptor(el, "value")), valueProperty && valueProperty.get ? el._valueGet && Object.defineProperty(el, "value", { get: el._valueGet, set: el._valueSet }) : document.__lookupGetter__ && el.__lookupGetter__("value") && el._valueGet && (el.__defineGetter__("value", el._valueGet), el.__defineSetter__("value", el._valueSet)); try { delete el._valueGet, delete el._valueSet; } catch (e) { el._valueGet = void 0, el._valueSet = void 0; } break; case "getmetadata": if ($el = $(actionObj.el), maskset = $el.data("_inputmask").maskset, opts = $el.data("_inputmask").opts, $.isArray(maskset.metadata)) { for (var alternation, lvp = getLastValidPosition(), firstAlt = lvp; firstAlt >= 0; firstAlt--) if (getMaskSet().validPositions[firstAlt] && void 0 != getMaskSet().validPositions[firstAlt].alternation) { alternation = getMaskSet().validPositions[firstAlt].alternation; break; } return void 0 != alternation ? maskset.metadata[getMaskSet().validPositions[lvp].locator[alternation]] : maskset.metadata[0]; } return maskset.metadata; } } if (void 0 === $.fn.inputmask) { var msie1x = "function" == typeof ScriptEngineMajorVersion ? ScriptEngineMajorVersion() : new Function("/*@cc_on return @_jscript_version; @*/")() >= 10, ua = navigator.userAgent, iphone = null !== ua.match(new RegExp("iphone", "i")), android = null !== ua.match(new RegExp("android.*safari.*", "i")), androidchrome = null !== ua.match(new RegExp("android.*chrome.*", "i")), androidfirefox = null !== ua.match(new RegExp("android.*firefox.*", "i")), kindle = /Kindle/i.test(ua) || /Silk/i.test(ua) || /KFTT/i.test(ua) || /KFOT/i.test(ua) || /KFJWA/i.test(ua) || /KFJWI/i.test(ua) || /KFSOWI/i.test(ua) || /KFTHWA/i.test(ua) || /KFTHWI/i.test(ua) || /KFAPWA/i.test(ua) || /KFAPWI/i.test(ua), PasteEventType = isInputEventSupported("paste") ? "paste" : isInputEventSupported("input") ? "input" : "propertychange"; $.inputmask = { defaults: { placeholder: "_", optionalmarker: { start: "[", end: "]" }, quantifiermarker: { start: "{", end: "}" }, groupmarker: { start: "(", end: ")" }, alternatormarker: "|", escapeChar: "\\", mask: null, oncomplete: $.noop, onincomplete: $.noop, oncleared: $.noop, repeat: 0, greedy: !0, autoUnmask: !1, removeMaskOnSubmit: !0, clearMaskOnLostFocus: !0, insertMode: !0, clearIncomplete: !1, aliases: {}, alias: null, onKeyUp: $.noop, onKeyPress: $.noop, onKeyDown: $.noop, onBeforeMask: void 0, onBeforePaste: void 0, onUnMask: void 0, showMaskOnFocus: !0, showMaskOnHover: !0, onKeyValidation: $.noop, skipOptionalPartCharacter: " ", showTooltip: !1, numericInput: !1, rightAlign: !1, radixPoint: "", radixFocus: !1, nojumps: !1, nojumpsThreshold: 0, keepStatic: void 0, definitions: { "9": { validator: "[0-9]", cardinality: 1, definitionSymbol: "*" }, a: { validator: "[A-Za-zА-яЁёÀ-ÿµ]", cardinality: 1, definitionSymbol: "*" }, "*": { validator: "[0-9A-Za-zА-яЁёÀ-ÿµ]", cardinality: 1 } }, ignorables: [ 8, 9, 13, 19, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 93, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123 ], isComplete: void 0 }, keyCode: { ALT: 18, BACKSPACE: 8, CAPS_LOCK: 20, COMMA: 188, COMMAND: 91, COMMAND_LEFT: 91, COMMAND_RIGHT: 93, CONTROL: 17, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, INSERT: 45, LEFT: 37, MENU: 93, NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108, NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38, WINDOWS: 91 }, masksCache: {}, escapeRegex: function(str) { var specials = [ "/", ".", "*", "+", "?", "|", "(", ")", "[", "]", "{", "}", "\\" ]; return str.replace(new RegExp("(\\" + specials.join("|\\") + ")", "gim"), "\\$1"); }, format: function(value, options, metadata) { var opts = $.extend(!0, {}, $.inputmask.defaults, options); return resolveAlias(opts.alias, options, opts), maskScope({ action: "format", value: value, metadata: metadata }, generateMaskSet(opts), opts); }, isValid: function(value, options) { var opts = $.extend(!0, {}, $.inputmask.defaults, options); return resolveAlias(opts.alias, options, opts), maskScope({ action: "isValid", value: value }, generateMaskSet(opts), opts); } }, $.fn.inputmask = function(fn, options, targetScope, targetData, msk) { function importAttributeOptions(npt, opts, importedOptionsContainer) { var $npt = $(npt); $npt.data("inputmask-alias") && resolveAlias($npt.data("inputmask-alias"), {}, opts); for (var option in opts) { var optionData = $npt.data("inputmask-" + option.toLowerCase()); void 0 != optionData && ("mask" == option && 0 == optionData.indexOf("[") ? (opts[option] = optionData.replace(/[\s[\]]/g, "").split("','"), opts[option][0] = opts[option][0].replace("'", ""), opts[option][opts[option].length - 1] = opts[option][opts[option].length - 1].replace("'", "")) : opts[option] = "boolean" == typeof optionData ? optionData : optionData.toString(), importedOptionsContainer && (importedOptionsContainer[option] = opts[option])); } return opts; } targetScope = targetScope || maskScope, targetData = targetData || "_inputmask"; var maskset, opts = $.extend(!0, {}, $.inputmask.defaults, options); if ("string" == typeof fn) switch (fn) { case "mask": return resolveAlias(opts.alias, options, opts), maskset = generateMaskSet(opts, targetScope !== maskScope), void 0 == maskset ? this : this.each(function() { targetScope({ action: "mask", el: this }, $.extend(!0, {}, maskset), importAttributeOptions(this, opts)); }); case "unmaskedvalue": var $input = $(this); return $input.data(targetData) ? targetScope({ action: "unmaskedvalue", $input: $input }) : $input.val(); case "remove": return this.each(function() { var $input = $(this); $input.data(targetData) && targetScope({ action: "remove", el: this }); }); case "getemptymask": return this.data(targetData) ? targetScope({ action: "getemptymask", el: this }) : ""; case "hasMaskedValue": return this.data(targetData) ? !this.data(targetData).opts.autoUnmask : !1; case "isComplete": return this.data(targetData) ? targetScope({ action: "isComplete", buffer: this[0]._valueGet().split(""), el: this }) : !0; case "getmetadata": return this.data(targetData) ? targetScope({ action: "getmetadata", el: this }) : void 0; case "_detectScope": return resolveAlias(opts.alias, options, opts), void 0 == msk || resolveAlias(msk, options, opts) || -1 != $.inArray(msk, [ "mask", "unmaskedvalue", "remove", "getemptymask", "hasMaskedValue", "isComplete", "getmetadata", "_detectScope" ]) || (opts.mask = msk), $.isFunction(opts.mask) && (opts.mask = opts.mask.call(this, opts)), $.isArray(opts.mask); default: return resolveAlias(opts.alias, options, opts), resolveAlias(fn, options, opts) || (opts.mask = fn), maskset = generateMaskSet(opts, targetScope !== maskScope), void 0 == maskset ? this : this.each(function() { targetScope({ action: "mask", el: this }, $.extend(!0, {}, maskset), importAttributeOptions(this, opts)); }); } else { if ("object" == typeof fn) return opts = $.extend(!0, {}, $.inputmask.defaults, fn), resolveAlias(opts.alias, fn, opts), maskset = generateMaskSet(opts, targetScope !== maskScope), void 0 == maskset ? this : this.each(function() { targetScope({ action: "mask", el: this }, $.extend(!0, {}, maskset), importAttributeOptions(this, opts)); }); if (void 0 == fn) return this.each(function() { var attrOptions = $(this).attr("data-inputmask"); if (attrOptions && "" != attrOptions) try { attrOptions = attrOptions.replace(new RegExp("'", "g"), '"'); var dataoptions = $.parseJSON("{" + attrOptions + "}"); $.extend(!0, dataoptions, options), opts = $.extend(!0, {}, $.inputmask.defaults, dataoptions), opts = importAttributeOptions(this, opts), resolveAlias(opts.alias, dataoptions, opts), opts.alias = void 0, $(this).inputmask("mask", opts, targetScope); } catch (ex) {} if ($(this).attr("data-inputmask-mask") || $(this).attr("data-inputmask-alias")) { opts = $.extend(!0, {}, $.inputmask.defaults, {}); var dataOptions = {}; opts = importAttributeOptions(this, opts, dataOptions), resolveAlias(opts.alias, dataOptions, opts), opts.alias = void 0, $(this).inputmask("mask", opts, targetScope); } }); } }; } return $.fn.inputmask; }(jQuery), function($) { return $.extend($.inputmask.defaults.definitions, { h: { validator: "[01][0-9]|2[0-3]", cardinality: 2, prevalidator: [ { validator: "[0-2]", cardinality: 1 } ] }, s: { validator: "[0-5][0-9]", cardinality: 2, prevalidator: [ { validator: "[0-5]", cardinality: 1 } ] }, d: { validator: "0[1-9]|[12][0-9]|3[01]", cardinality: 2, prevalidator: [ { validator: "[0-3]", cardinality: 1 } ] }, m: { validator: "0[1-9]|1[012]", cardinality: 2, prevalidator: [ { validator: "[01]", cardinality: 1 } ] }, y: { validator: "(19|20)\\d{2}", cardinality: 4, prevalidator: [ { validator: "[12]", cardinality: 1 }, { validator: "(19|20)", cardinality: 2 }, { validator: "(19|20)\\d", cardinality: 3 } ] } }), $.extend($.inputmask.defaults.aliases, { "dd/mm/yyyy": { mask: "1/2/y", placeholder: "dd/mm/yyyy", regex: { val1pre: new RegExp("[0-3]"), val1: new RegExp("0[1-9]|[12][0-9]|3[01]"), val2pre: function(separator) { var escapedSeparator = $.inputmask.escapeRegex.call(this, separator); return new RegExp("((0[1-9]|[12][0-9]|3[01])" + escapedSeparator + "[01])"); }, val2: function(separator) { var escapedSeparator = $.inputmask.escapeRegex.call(this, separator); return new RegExp("((0[1-9]|[12][0-9])" + escapedSeparator + "(0[1-9]|1[012]))|(30" + escapedSeparator + "(0[13-9]|1[012]))|(31" + escapedSeparator + "(0[13578]|1[02]))"); } }, leapday: "29/02/", separator: "/", yearrange: { minyear: 1900, maxyear: 2099 }, isInYearRange: function(chrs, minyear, maxyear) { if (isNaN(chrs)) return !1; var enteredyear = parseInt(chrs.concat(minyear.toString().slice(chrs.length))), enteredyear2 = parseInt(chrs.concat(maxyear.toString().slice(chrs.length))); return (isNaN(enteredyear) ? !1 : enteredyear >= minyear && maxyear >= enteredyear) || (isNaN(enteredyear2) ? !1 : enteredyear2 >= minyear && maxyear >= enteredyear2); }, determinebaseyear: function(minyear, maxyear, hint) { var currentyear = new Date().getFullYear(); if (minyear > currentyear) return minyear; if (currentyear > maxyear) { for (var maxYearPrefix = maxyear.toString().slice(0, 2), maxYearPostfix = maxyear.toString().slice(2, 4); maxYearPrefix + hint > maxyear; ) maxYearPrefix--; var maxxYear = maxYearPrefix + maxYearPostfix; return minyear > maxxYear ? minyear : maxxYear; } return currentyear; }, onKeyUp: function(e) { var $input = $(this); if (e.ctrlKey && e.keyCode == $.inputmask.keyCode.RIGHT) { var today = new Date(); $input.val(today.getDate().toString() + (today.getMonth() + 1).toString() + today.getFullYear().toString()); } }, definitions: { "1": { validator: function(chrs, maskset, pos, strict, opts) { var isValid = opts.regex.val1.test(chrs); return strict || isValid || chrs.charAt(1) != opts.separator && -1 == "-./".indexOf(chrs.charAt(1)) || !(isValid = opts.regex.val1.test("0" + chrs.charAt(0))) ? isValid : (maskset.buffer[pos - 1] = "0", { refreshFromBuffer: { start: pos - 1, end: pos }, pos: pos, c: chrs.charAt(0) }); }, cardinality: 2, prevalidator: [ { validator: function(chrs, maskset, pos, strict, opts) { isNaN(maskset.buffer[pos + 1]) || (chrs += maskset.buffer[pos + 1]); var isValid = 1 == chrs.length ? opts.regex.val1pre.test(chrs) : opts.regex.val1.test(chrs); return strict || isValid || !(isValid = opts.regex.val1.test("0" + chrs)) ? isValid : (maskset.buffer[pos] = "0", pos++, { pos: pos }); }, cardinality: 1 } ] }, "2": { validator: function(chrs, maskset, pos, strict, opts) { var frontValue = opts.mask.indexOf("2") == opts.mask.length - 1 ? maskset.buffer.join("").substr(5, 3) : maskset.buffer.join("").substr(0, 3); -1 != frontValue.indexOf(opts.placeholder[0]) && (frontValue = "01" + opts.separator); var isValid = opts.regex.val2(opts.separator).test(frontValue + chrs); if (!strict && !isValid && (chrs.charAt(1) == opts.separator || -1 != "-./".indexOf(chrs.charAt(1))) && (isValid = opts.regex.val2(opts.separator).test(frontValue + "0" + chrs.charAt(0)))) return maskset.buffer[pos - 1] = "0", { refreshFromBuffer: { start: pos - 1, end: pos }, pos: pos, c: chrs.charAt(0) }; if (opts.mask.indexOf("2") == opts.mask.length - 1 && isValid) { var dayMonthValue = maskset.buffer.join("").substr(4, 4) + chrs; if (dayMonthValue != opts.leapday) return !0; var year = parseInt(maskset.buffer.join("").substr(0, 4), 10); return year % 4 === 0 ? year % 100 === 0 ? year % 400 === 0 ? !0 : !1 : !0 : !1; } return isValid; }, cardinality: 2, prevalidator: [ { validator: function(chrs, maskset, pos, strict, opts) { isNaN(maskset.buffer[pos + 1]) || (chrs += maskset.buffer[pos + 1]); var frontValue = opts.mask.indexOf("2") == opts.mask.length - 1 ? maskset.buffer.join("").substr(5, 3) : maskset.buffer.join("").substr(0, 3); -1 != frontValue.indexOf(opts.placeholder[0]) && (frontValue = "01" + opts.separator); var isValid = 1 == chrs.length ? opts.regex.val2pre(opts.separator).test(frontValue + chrs) : opts.regex.val2(opts.separator).test(frontValue + chrs); return strict || isValid || !(isValid = opts.regex.val2(opts.separator).test(frontValue + "0" + chrs)) ? isValid : (maskset.buffer[pos] = "0", pos++, { pos: pos }); }, cardinality: 1 } ] }, y: { validator: function(chrs, maskset, pos, strict, opts) { if (opts.isInYearRange(chrs, opts.yearrange.minyear, opts.yearrange.maxyear)) { var dayMonthValue = maskset.buffer.join("").substr(0, 6); if (dayMonthValue != opts.leapday) return !0; var year = parseInt(chrs, 10); return year % 4 === 0 ? year % 100 === 0 ? year % 400 === 0 ? !0 : !1 : !0 : !1; } return !1; }, cardinality: 4, prevalidator: [ { validator: function(chrs, maskset, pos, strict, opts) { var isValid = opts.isInYearRange(chrs, opts.yearrange.minyear, opts.yearrange.maxyear); if (!strict && !isValid) { var yearPrefix = opts.determinebaseyear(opts.yearrange.minyear, opts.yearrange.maxyear, chrs + "0").toString().slice(0, 1); if (isValid = opts.isInYearRange(yearPrefix + chrs, opts.yearrange.minyear, opts.yearrange.maxyear)) return maskset.buffer[pos++] = yearPrefix.charAt(0), { pos: pos }; if (yearPrefix = opts.determinebaseyear(opts.yearrange.minyear, opts.yearrange.maxyear, chrs + "0").toString().slice(0, 2), isValid = opts.isInYearRange(yearPrefix + chrs, opts.yearrange.minyear, opts.yearrange.maxyear)) return maskset.buffer[pos++] = yearPrefix.charAt(0), maskset.buffer[pos++] = yearPrefix.charAt(1), { pos: pos }; } return isValid; }, cardinality: 1 }, { validator: function(chrs, maskset, pos, strict, opts) { var isValid = opts.isInYearRange(chrs, opts.yearrange.minyear, opts.yearrange.maxyear); if (!strict && !isValid) { var yearPrefix = opts.determinebaseyear(opts.yearrange.minyear, opts.yearrange.maxyear, chrs).toString().slice(0, 2); if (isValid = opts.isInYearRange(chrs[0] + yearPrefix[1] + chrs[1], opts.yearrange.minyear, opts.yearrange.maxyear)) return maskset.buffer[pos++] = yearPrefix.charAt(1), { pos: pos }; if (yearPrefix = opts.determinebaseyear(opts.yearrange.minyear, opts.yearrange.maxyear, chrs).toString().slice(0, 2), opts.isInYearRange(yearPrefix + chrs, opts.yearrange.minyear, opts.yearrange.maxyear)) { var dayMonthValue = maskset.buffer.join("").substr(0, 6); if (dayMonthValue != opts.leapday) isValid = !0; else { var year = parseInt(chrs, 10); isValid = year % 4 === 0 ? year % 100 === 0 ? year % 400 === 0 ? !0 : !1 : !0 : !1; } } else isValid = !1; if (isValid) return maskset.buffer[pos - 1] = yearPrefix.charAt(0), maskset.buffer[pos++] = yearPrefix.charAt(1), maskset.buffer[pos++] = chrs.charAt(0), { refreshFromBuffer: { start: pos - 3, end: pos }, pos: pos }; } return isValid; }, cardinality: 2 }, { validator: function(chrs, maskset, pos, strict, opts) { return opts.isInYearRange(chrs, opts.yearrange.minyear, opts.yearrange.maxyear); }, cardinality: 3 } ] } }, insertMode: !1, autoUnmask: !1 }, "mm/dd/yyyy": { placeholder: "mm/dd/yyyy", alias: "dd/mm/yyyy", regex: { val2pre: function(separator) { var escapedSeparator = $.inputmask.escapeRegex.call(this, separator); return new RegExp("((0[13-9]|1[012])" + escapedSeparator + "[0-3])|(02" + escapedSeparator + "[0-2])"); }, val2: function(separator) { var escapedSeparator = $.inputmask.escapeRegex.call(this, separator); return new RegExp("((0[1-9]|1[012])" + escapedSeparator + "(0[1-9]|[12][0-9]))|((0[13-9]|1[012])" + escapedSeparator + "30)|((0[13578]|1[02])" + escapedSeparator + "31)"); }, val1pre: new RegExp("[01]"), val1: new RegExp("0[1-9]|1[012]") }, leapday: "02/29/", onKeyUp: function(e) { var $input = $(this); if (e.ctrlKey && e.keyCode == $.inputmask.keyCode.RIGHT) { var today = new Date(); $input.val((today.getMonth() + 1).toString() + today.getDate().toString() + today.getFullYear().toString()); } } }, "yyyy/mm/dd": { mask: "y/1/2", placeholder: "yyyy/mm/dd", alias: "mm/dd/yyyy", leapday: "/02/29", onKeyUp: function(e) { var $input = $(this); if (e.ctrlKey && e.keyCode == $.inputmask.keyCode.RIGHT) { var today = new Date(); $input.val(today.getFullYear().toString() + (today.getMonth() + 1).toString() + today.getDate().toString()); } } }, "dd.mm.yyyy": { mask: "1.2.y", placeholder: "dd.mm.yyyy", leapday: "29.02.", separator: ".", alias: "dd/mm/yyyy" }, "dd-mm-yyyy": { mask: "1-2-y", placeholder: "dd-mm-yyyy", leapday: "29-02-", separator: "-", alias: "dd/mm/yyyy" }, "mm.dd.yyyy": { mask: "1.2.y", placeholder: "mm.dd.yyyy", leapday: "02.29.", separator: ".", alias: "mm/dd/yyyy" }, "mm-dd-yyyy": { mask: "1-2-y", placeholder: "mm-dd-yyyy", leapday: "02-29-", separator: "-", alias: "mm/dd/yyyy" }, "yyyy.mm.dd": { mask: "y.1.2", placeholder: "yyyy.mm.dd", leapday: ".02.29", separator: ".", alias: "yyyy/mm/dd" }, "yyyy-mm-dd": { mask: "y-1-2", placeholder: "yyyy-mm-dd", leapday: "-02-29", separator: "-", alias: "yyyy/mm/dd" }, datetime: { mask: "1/2/y h:s", placeholder: "dd/mm/yyyy hh:mm", alias: "dd/mm/yyyy", regex: { hrspre: new RegExp("[012]"), hrs24: new RegExp("2[0-4]|1[3-9]"), hrs: new RegExp("[01][0-9]|2[0-4]"), ampm: new RegExp("^[a|p|A|P][m|M]"), mspre: new RegExp("[0-5]"), ms: new RegExp("[0-5][0-9]") }, timeseparator: ":", hourFormat: "24", definitions: { h: { validator: function(chrs, maskset, pos, strict, opts) { if ("24" == opts.hourFormat && 24 == parseInt(chrs, 10)) return maskset.buffer[pos - 1] = "0", maskset.buffer[pos] = "0", { refreshFromBuffer: { start: pos - 1, end: pos }, c: "0" }; var isValid = opts.regex.hrs.test(chrs); if (!strict && !isValid && (chrs.charAt(1) == opts.timeseparator || -1 != "-.:".indexOf(chrs.charAt(1))) && (isValid = opts.regex.hrs.test("0" + chrs.charAt(0)))) return maskset.buffer[pos - 1] = "0", maskset.buffer[pos] = chrs.charAt(0), pos++, { refreshFromBuffer: { start: pos - 2, end: pos }, pos: pos, c: opts.timeseparator }; if (isValid && "24" !== opts.hourFormat && opts.regex.hrs24.test(chrs)) { var tmp = parseInt(chrs, 10); return 24 == tmp ? (maskset.buffer[pos + 5] = "a", maskset.buffer[pos + 6] = "m") : (maskset.buffer[pos + 5] = "p", maskset.buffer[pos + 6] = "m"), tmp -= 12, 10 > tmp ? (maskset.buffer[pos] = tmp.toString(), maskset.buffer[pos - 1] = "0") : (maskset.buffer[pos] = tmp.toString().charAt(1), maskset.buffer[pos - 1] = tmp.toString().charAt(0)), { refreshFromBuffer: { start: pos - 1, end: pos + 6 }, c: maskset.buffer[pos] }; } return isValid; }, cardinality: 2, prevalidator: [ { validator: function(chrs, maskset, pos, strict, opts) { var isValid = opts.regex.hrspre.test(chrs); return strict || isValid || !(isValid = opts.regex.hrs.test("0" + chrs)) ? isValid : (maskset.buffer[pos] = "0", pos++, { pos: pos }); }, cardinality: 1 } ] }, s: { validator: "[0-5][0-9]", cardinality: 2, prevalidator: [ { validator: function(chrs, maskset, pos, strict, opts) { var isValid = opts.regex.mspre.test(chrs); return strict || isValid || !(isValid = opts.regex.ms.test("0" + chrs)) ? isValid : (maskset.buffer[pos] = "0", pos++, { pos: pos }); }, cardinality: 1 } ] }, t: { validator: function(chrs, maskset, pos, strict, opts) { return opts.regex.ampm.test(chrs + "m"); }, casing: "lower", cardinality: 1 } }, insertMode: !1, autoUnmask: !1 }, datetime12: { mask: "1/2/y h:s t\\m", placeholder: "dd/mm/yyyy hh:mm xm", alias: "datetime", hourFormat: "12" }, "hh:mm t": { mask: "h:s t\\m", placeholder: "hh:mm xm", alias: "datetime", hourFormat: "12" }, "h:s t": { mask: "h:s t\\m", placeholder: "hh:mm xm", alias: "datetime", hourFormat: "12" }, "hh:mm:ss": { mask: "h:s:s", placeholder: "hh:mm:ss", alias: "datetime", autoUnmask: !1 }, "hh:mm": { mask: "h:s", placeholder: "hh:mm", alias: "datetime", autoUnmask: !1 }, date: { alias: "dd/mm/yyyy" }, "mm/yyyy": { mask: "1/y", placeholder: "mm/yyyy", leapday: "donotuse", separator: "/", alias: "mm/dd/yyyy" } }), $.fn.inputmask; }(jQuery), function($) { return $.extend($.inputmask.defaults.definitions, { A: { validator: "[A-Za-zА-яЁёÀ-ÿµ]", cardinality: 1, casing: "upper" }, "#": { validator: "[0-9A-Za-zА-яЁёÀ-ÿµ]", cardinality: 1, casing: "upper" } }), $.extend($.inputmask.defaults.aliases, { url: { mask: "ir", placeholder: "", separator: "", defaultPrefix: "http://", regex: { urlpre1: new RegExp("[fh]"), urlpre2: new RegExp("(ft|ht)"), urlpre3: new RegExp("(ftp|htt)"), urlpre4: new RegExp("(ftp:|http|ftps)"), urlpre5: new RegExp("(ftp:/|ftps:|http:|https)"), urlpre6: new RegExp("(ftp://|ftps:/|http:/|https:)"), urlpre7: new RegExp("(ftp://|ftps://|http://|https:/)"), urlpre8: new RegExp("(ftp://|ftps://|http://|https://)") }, definitions: { i: { validator: function() { return !0; }, cardinality: 8, prevalidator: function() { for (var result = [], prefixLimit = 8, i = 0; prefixLimit > i; i++) result[i] = function() { var j = i; return { validator: function(chrs, maskset, pos, strict, opts) { if (opts.regex["urlpre" + (j + 1)]) { var k, tmp = chrs; j + 1 - chrs.length > 0 && (tmp = maskset.buffer.join("").substring(0, j + 1 - chrs.length) + "" + tmp); var isValid = opts.regex["urlpre" + (j + 1)].test(tmp); if (!strict && !isValid) { for (pos -= j, k = 0; k < opts.defaultPrefix.length; k++) maskset.buffer[pos] = opts.defaultPrefix[k], pos++; for (k = 0; k < tmp.length - 1; k++) maskset.buffer[pos] = tmp[k], pos++; return { pos: pos }; } return isValid; } return !1; }, cardinality: j }; }(); return result; }() }, r: { validator: ".", cardinality: 50 } }, insertMode: !1, autoUnmask: !1 }, ip: { mask: "i[i[i]].i[i[i]].i[i[i]].i[i[i]]", definitions: { i: { validator: function(chrs, maskset, pos) { return pos - 1 > -1 && "." != maskset.buffer[pos - 1] ? (chrs = maskset.buffer[pos - 1] + chrs, chrs = pos - 2 > -1 && "." != maskset.buffer[pos - 2] ? maskset.buffer[pos - 2] + chrs : "0" + chrs) : chrs = "00" + chrs, new RegExp("25[0-5]|2[0-4][0-9]|[01][0-9][0-9]").test(chrs); }, cardinality: 1 } } }, email: { mask: "*{1,64}[.*{1,64}][.*{1,64}][.*{1,64}]@*{1,64}[.*{2,64}][.*{2,6}][.*{1,2}]", greedy: !1, onBeforePaste: function(pastedValue) { return pastedValue = pastedValue.toLowerCase(), pastedValue.replace("mailto:", ""); }, definitions: { "*": { validator: "[0-9A-Za-z!#$%&'*+/=?^_`{|}~-]", cardinality: 1, casing: "lower" } } } }), $.fn.inputmask; }(jQuery), function($) { return $.extend($.inputmask.defaults.aliases, { numeric: { mask: function(opts) { if (0 !== opts.repeat && isNaN(opts.integerDigits) && (opts.integerDigits = opts.repeat), opts.repeat = 0, opts.groupSeparator == opts.radixPoint && (opts.groupSeparator = "." == opts.radixPoint ? "," : "," == opts.radixPoint ? "." : ""), " " === opts.groupSeparator && (opts.skipOptionalPartCharacter = void 0), opts.autoGroup = opts.autoGroup && "" != opts.groupSeparator, opts.autoGroup && isFinite(opts.integerDigits)) { var seps = Math.floor(opts.integerDigits / opts.groupSize), mod = opts.integerDigits % opts.groupSize; opts.integerDigits += 0 == mod ? seps - 1 : seps; } opts.definitions[";"] = opts.definitions["~"]; var mask = opts.prefix; return mask += "[+]", mask += "~{1," + opts.integerDigits + "}", void 0 != opts.digits && (isNaN(opts.digits) || parseInt(opts.digits) > 0) && (mask += opts.digitsOptional ? "[" + (opts.decimalProtect ? ":" : opts.radixPoint) + ";{" + opts.digits + "}]" : (opts.decimalProtect ? ":" : opts.radixPoint) + ";{" + opts.digits + "}"), mask += opts.suffix; }, placeholder: "", greedy: !1, digits: "*", digitsOptional: !0, groupSeparator: "", radixPoint: ".", radixFocus: !0, groupSize: 3, autoGroup: !1, allowPlus: !0, allowMinus: !0, integerDigits: "+", prefix: "", suffix: "", rightAlign: !0, decimalProtect: !0, postFormat: function(buffer, pos, reformatOnly, opts) { var needsRefresh = !1, charAtPos = buffer[pos]; if ("" == opts.groupSeparator || -1 != $.inArray(opts.radixPoint, buffer) && pos >= $.inArray(opts.radixPoint, buffer) || new RegExp("[-+]").test(charAtPos)) return { pos: pos }; var cbuf = buffer.slice(); charAtPos == opts.groupSeparator && (cbuf.splice(pos--, 1), charAtPos = cbuf[pos]), reformatOnly ? cbuf[pos] = "?" : cbuf.splice(pos, 0, "?"); var bufVal = cbuf.join(""); if (opts.autoGroup || reformatOnly && -1 != bufVal.indexOf(opts.groupSeparator)) { var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator); needsRefresh = 0 == bufVal.indexOf(opts.groupSeparator), bufVal = bufVal.replace(new RegExp(escapedGroupSeparator, "g"), ""); var radixSplit = bufVal.split(opts.radixPoint); if (bufVal = radixSplit[0], bufVal != opts.prefix + "?0" && bufVal.length >= opts.groupSize + opts.prefix.length) { needsRefresh = !0; for (var reg = new RegExp("([-+]?[\\d?]+)([\\d?]{" + opts.groupSize + "})"); reg.test(bufVal); ) bufVal = bufVal.replace(reg, "$1" + opts.groupSeparator + "$2"), bufVal = bufVal.replace(opts.groupSeparator + opts.groupSeparator, opts.groupSeparator); } radixSplit.length > 1 && (bufVal += opts.radixPoint + radixSplit[1]); } buffer.length = bufVal.length; for (var i = 0, l = bufVal.length; l > i; i++) buffer[i] = bufVal.charAt(i); var newPos = $.inArray("?", buffer); return reformatOnly ? buffer[newPos] = charAtPos : buffer.splice(newPos, 1), { pos: newPos, refreshFromBuffer: needsRefresh }; }, onKeyDown: function(e, buffer, caretPos, opts) { if (e.keyCode == $.inputmask.keyCode.TAB && "0" != opts.placeholder.charAt(0)) { var radixPosition = $.inArray(opts.radixPoint, buffer); if (-1 != radixPosition && isFinite(opts.digits)) { for (var i = 1; i <= opts.digits; i++) (void 0 == buffer[radixPosition + i] || buffer[radixPosition + i] == opts.placeholder.charAt(0)) && (buffer[radixPosition + i] = "0"); return { refreshFromBuffer: { start: ++radixPosition, end: radixPosition + opts.digits } }; } } else if (opts.autoGroup && (e.keyCode == $.inputmask.keyCode.DELETE || e.keyCode == $.inputmask.keyCode.BACKSPACE)) { var rslt = opts.postFormat(buffer, caretPos - 1, !0, opts); return rslt.caret = rslt.pos + 1, rslt; } }, onKeyPress: function(e, buffer, caretPos, opts) { if (opts.autoGroup) { var rslt = opts.postFormat(buffer, caretPos - 1, !0, opts); return rslt.caret = rslt.pos + 1, rslt; } }, regex: { integerPart: function() { return new RegExp("[-+]?\\d+"); }, integerNPart: function() { return new RegExp("\\d+"); } }, signHandler: function(chrs, buffer, pos, strict, opts) { if (!strict && (opts.allowMinus && "-" === chrs || opts.allowPlus && "+" === chrs)) { var matchRslt = buffer.join("").match(opts.regex.integerPart(opts)); if (matchRslt && matchRslt.length > 0 && "0" !== matchRslt[matchRslt.index]) return buffer[matchRslt.index] == ("-" === chrs ? "+" : "-") ? { pos: matchRslt.index, c: chrs, remove: matchRslt.index, caret: pos } : buffer[matchRslt.index] == ("-" === chrs ? "-" : "+") ? { remove: matchRslt.index, caret: pos - 1 } : { pos: matchRslt.index, c: chrs, caret: pos + 1 }; } return !1; }, radixHandler: function(chrs, maskset, pos, strict, opts) { if (!strict && chrs === opts.radixPoint) { var radixPos = $.inArray(opts.radixPoint, maskset.buffer), integerValue = maskset.buffer.join("").match(opts.regex.integerPart(opts)); if (-1 != radixPos) return maskset.validPositions[radixPos - 1] ? { caret: radixPos + 1 } : { pos: integerValue.index, c: integerValue[0], caret: radixPos + 1 }; } return !1; }, leadingZeroHandler: function(chrs, maskset, pos, strict, opts) { var matchRslt = maskset.buffer.join("").match(opts.regex.integerNPart(opts)), radixPosition = $.inArray(opts.radixPoint, maskset.buffer); if (matchRslt && !strict && (-1 == radixPosition || matchRslt.index < radixPosition)) if (0 == matchRslt[0].indexOf("0") && pos >= opts.prefix.length) { if (-1 == radixPosition || radixPosition >= pos && void 0 == maskset.validPositions[radixPosition]) return maskset.buffer.splice(matchRslt.index, 1), pos = pos > matchRslt.index ? pos - 1 : matchRslt.index, { pos: pos, remove: matchRslt.index }; if (pos > matchRslt.index && radixPosition >= pos) return maskset.buffer.splice(matchRslt.index, 1), pos = pos > matchRslt.index ? pos - 1 : matchRslt.index, { pos: pos, remove: matchRslt.index }; } else if ("0" == chrs && pos <= matchRslt.index) return !1; return !0; }, definitions: { "~": { validator: function(chrs, maskset, pos, strict, opts) { var isValid = opts.signHandler(chrs, maskset.buffer, pos, strict, opts); if (!isValid && (isValid = opts.radixHandler(chrs, maskset, pos, strict, opts), !isValid && (isValid = strict ? new RegExp("[0-9" + $.inputmask.escapeRegex.call(this, opts.groupSeparator) + "]").test(chrs) : new RegExp("[0-9]").test(chrs), isValid === !0 && (isValid = opts.leadingZeroHandler(chrs, maskset, pos, strict, opts), isValid === !0)))) { var radixPosition = $.inArray(opts.radixPoint, maskset.buffer); return opts.digitsOptional === !1 && pos > radixPosition && !strict ? { pos: pos, remove: pos } : { pos: pos }; } return isValid; }, cardinality: 1, prevalidator: null }, "+": { validator: function(chrs, maskset, pos, strict, opts) { var isValid = opts.signHandler(chrs, maskset.buffer, pos, strict, opts); if (!isValid) { var signed = "["; opts.allowMinus === !0 && (signed += "-"), opts.allowPlus === !0 && (signed += "+"), signed += "]", isValid = new RegExp(signed).test(chrs); } return isValid; }, cardinality: 1, prevalidator: null, placeholder: "" }, ":": { validator: function(chrs, maskset, pos, strict, opts) { var isValid = opts.signHandler(chrs, maskset.buffer, pos, strict, opts); if (!isValid) { var radix = "[" + $.inputmask.escapeRegex.call(this, opts.radixPoint) + "]"; isValid = new RegExp(radix).test(chrs), isValid && maskset.validPositions[pos] && maskset.validPositions[pos].match.placeholder == opts.radixPoint && (isValid = { pos: pos, remove: pos }); } return isValid; }, cardinality: 1, prevalidator: null, placeholder: function(opts) { return opts.radixPoint; } } }, insertMode: !0, autoUnmask: !1, onUnMask: function(maskedValue, unmaskedValue, opts) { var processValue = maskedValue.replace(opts.prefix, ""); return processValue = processValue.replace(opts.suffix, ""), processValue = processValue.replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), ""); }, isComplete: function(buffer, opts) { var maskedValue = buffer.join(""), bufClone = buffer.slice(); if (opts.postFormat(bufClone, 0, !0, opts), bufClone.join("") != maskedValue) return !1; var processValue = maskedValue.replace(opts.prefix, ""); return processValue = processValue.replace(opts.suffix, ""), processValue = processValue.replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), ""), processValue = processValue.replace($.inputmask.escapeRegex.call(this, opts.radixPoint), "."), isFinite(processValue); }, onBeforeMask: function(initialValue, opts) { if (isFinite(initialValue)) return initialValue.toString().replace(".", opts.radixPoint); var kommaMatches = initialValue.match(/,/g), dotMatches = initialValue.match(/\./g); return dotMatches && kommaMatches ? dotMatches.length > kommaMatches.length ? (initialValue = initialValue.replace(/\./g, ""), initialValue = initialValue.replace(",", opts.radixPoint)) : kommaMatches.length > dotMatches.length && (initialValue = initialValue.replace(/,/g, ""), initialValue = initialValue.replace(".", opts.radixPoint)) : initialValue = initialValue.replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), ""), initialValue; } }, currency: { prefix: "$ ", groupSeparator: ",", radixPoint: ".", alias: "numeric", placeholder: "0", autoGroup: !0, digits: 2, digitsOptional: !1, clearMaskOnLostFocus: !1, decimalProtect: !0 }, decimal: { alias: "numeric" }, integer: { alias: "numeric", digits: "0" } }), $.fn.inputmask; }(jQuery), function($) { return $.extend($.inputmask.defaults.aliases, { phone: { url: "phone-codes/phone-codes.js", maskInit: "+pp(pp)pppppppp", mask: function(opts) { opts.definitions = { p: { validator: function() { return !1; }, cardinality: 1 }, "#": { validator: "[0-9]", cardinality: 1 } }; var maskList = []; return $.ajax({ url: opts.url, async: !1, dataType: "json", success: function(response) { maskList = response; } }), maskList.splice(0, 0, opts.maskInit), maskList.sort(function(a, b) { return a.length - b.length; }), maskList; }, nojumps: !0, nojumpsThreshold: 1 }, phonebe: { alias: "phone", url: "phone-codes/phone-be.js", maskInit: "+32(pp)pppppppp", nojumpsThreshold: 4 } }), $.fn.inputmask; }(jQuery), function($) { return $.extend($.inputmask.defaults.aliases, { Regex: { mask: "r", greedy: !1, repeat: "*", regex: null, regexTokens: null, tokenizer: /\[\^?]?(?:[^\\\]]+|\\[\S\s]?)*]?|\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9][0-9]*|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|c[A-Za-z]|[\S\s]?)|\((?:\?[:=!]?)?|(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??|[^.?*+^${[()|\\]+|./g, quantifierFilter: /[0-9]+[^,]/, isComplete: function(buffer, opts) { return new RegExp(opts.regex).test(buffer.join("")); }, definitions: { r: { validator: function(chrs, maskset, pos, strict, opts) { function regexToken(isGroup, isQuantifier) { this.matches = [], this.isGroup = isGroup || !1, this.isQuantifier = isQuantifier || !1, this.quantifier = { min: 1, max: 1 }, this.repeaterPart = void 0; } function analyseRegex() { var match, m, currentToken = new regexToken(), opengroups = []; for (opts.regexTokens = []; match = opts.tokenizer.exec(opts.regex); ) switch (m = match[0], m.charAt(0)) { case "(": opengroups.push(new regexToken(!0)); break; case ")": var groupToken = opengroups.pop(); opengroups.length > 0 ? opengroups[opengroups.length - 1].matches.push(groupToken) : currentToken.matches.push(groupToken); break; case "{": case "+": case "*": var quantifierToken = new regexToken(!1, !0); m = m.replace(/[{}]/g, ""); var mq = m.split(","), mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]), mq1 = 1 == mq.length ? mq0 : isNaN(mq[1]) ? mq[1] : parseInt(mq[1]); if (quantifierToken.quantifier = { min: mq0, max: mq1 }, opengroups.length > 0) { var matches = opengroups[opengroups.length - 1].matches; if (match = matches.pop(), !match.isGroup) { var groupToken = new regexToken(!0); groupToken.matches.push(match), match = groupToken; } matches.push(match), matches.push(quantifierToken); } else { if (match = currentToken.matches.pop(), !match.isGroup) { var groupToken = new regexToken(!0); groupToken.matches.push(match), match = groupToken; } currentToken.matches.push(match), currentToken.matches.push(quantifierToken); } break; default: opengroups.length > 0 ? opengroups[opengroups.length - 1].matches.push(m) : currentToken.matches.push(m); } currentToken.matches.length > 0 && opts.regexTokens.push(currentToken); } function validateRegexToken(token, fromGroup) { var isvalid = !1; fromGroup && (regexPart += "(", openGroupCount++); for (var mndx = 0; mndx < token.matches.length; mndx++) { var matchToken = token.matches[mndx]; if (1 == matchToken.isGroup) isvalid = validateRegexToken(matchToken, !0); else if (1 == matchToken.isQuantifier) { var crrntndx = $.inArray(matchToken, token.matches), matchGroup = token.matches[crrntndx - 1], regexPartBak = regexPart; if (isNaN(matchToken.quantifier.max)) { for (;matchToken.repeaterPart && matchToken.repeaterPart != regexPart && matchToken.repeaterPart.length > regexPart.length && !(isvalid = validateRegexToken(matchGroup, !0)); ) ; isvalid = isvalid || validateRegexToken(matchGroup, !0), isvalid && (matchToken.repeaterPart = regexPart), regexPart = regexPartBak + matchToken.quantifier.max; } else { for (var i = 0, qm = matchToken.quantifier.max - 1; qm > i && !(isvalid = validateRegexToken(matchGroup, !0)); i++) ; regexPart = regexPartBak + "{" + matchToken.quantifier.min + "," + matchToken.quantifier.max + "}"; } } else if (void 0 != matchToken.matches) for (var k = 0; k < matchToken.length && !(isvalid = validateRegexToken(matchToken[k], fromGroup)); k++) ; else { var testExp; if ("[" == matchToken.charAt(0)) { testExp = regexPart, testExp += matchToken; for (var j = 0; openGroupCount > j; j++) testExp += ")"; var exp = new RegExp("^(" + testExp + ")$"); isvalid = exp.test(bufferStr); } else for (var l = 0, tl = matchToken.length; tl > l; l++) if ("\\" != matchToken.charAt(l)) { testExp = regexPart, testExp += matchToken.substr(0, l + 1), testExp = testExp.replace(/\|$/, ""); for (var j = 0; openGroupCount > j; j++) testExp += ")"; var exp = new RegExp("^(" + testExp + ")$"); if (isvalid = exp.test(bufferStr)) break; } regexPart += matchToken; } if (isvalid) break; } return fromGroup && (regexPart += ")", openGroupCount--), isvalid; } null == opts.regexTokens && analyseRegex(); var cbuffer = maskset.buffer.slice(), regexPart = "", isValid = !1, openGroupCount = 0; cbuffer.splice(pos, 0, chrs); for (var bufferStr = cbuffer.join(""), i = 0; i < opts.regexTokens.length; i++) { var regexToken = opts.regexTokens[i]; if (isValid = validateRegexToken(regexToken, regexToken.isGroup)) break; } return isValid; }, cardinality: 1 } } } }), $.fn.inputmask; }(jQuery);
wil93/cdnjs
ajax/libs/jquery.inputmask/3.1.27/jquery.inputmask.bundle.js
JavaScript
mit
127,036
/*! * inputmask.min.js * http://github.com/RobinHerbots/jquery.inputmask * Copyright (c) 2010 - 2016 Robin Herbots * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) * Version: 3.2.7 */ !function(a){"function"==typeof define&&define.amd?define(["inputmask.dependencyLib"],a):"object"==typeof exports?module.exports=a(require("./inputmask.dependencyLib.jquery")):a(window.dependencyLib||jQuery)}(function(a){function b(c,d){return this instanceof b?(a.isPlainObject(c)?d=c:(d=d||{},d.alias=c),this.el=void 0,this.opts=a.extend(!0,{},this.defaults,d),this.noMasksCache=d&&void 0!==d.definitions,this.userOptions=d||{},this.events={},void e(this.opts.alias,d,this.opts)):new b(c,d)}function c(a){var b=document.createElement("input"),c="on"+a,d=c in b;return d||(b.setAttribute(c,"return;"),d="function"==typeof b[c]),b=null,d}function d(b,c){var d=b.getAttribute("type"),e="INPUT"===b.tagName&&-1!==a.inArray(d,c.supportsInputType)||b.isContentEditable||"TEXTAREA"===b.tagName;if(!e){var f=document.createElement("input");f.setAttribute("type",d),e="text"===f.type,f=null}return e}function e(b,c,d){var f=d.aliases[b];return f?(f.alias&&e(f.alias,void 0,d),a.extend(!0,d,f),a.extend(!0,d,c),!0):(null===d.mask&&(d.mask=b),!1)}function f(b,c,d){function f(a,c){c=void 0!==c?c:b.getAttribute("data-inputmask-"+a),null!==c&&("string"==typeof c&&(0===a.indexOf("on")?c=window[c]:"false"===c?c=!1:"true"===c&&(c=!0)),d[a]=c)}var g,h,i,j,k=b.getAttribute("data-inputmask");if(k&&""!==k&&(k=k.replace(new RegExp("'","g"),'"'),h=JSON.parse("{"+k+"}")),h){i=void 0;for(j in h)if("alias"===j.toLowerCase()){i=h[j];break}}f("alias",i),d.alias&&e(d.alias,d,c);for(g in c){if(h){i=void 0;for(j in h)if(j.toLowerCase()===g.toLowerCase()){i=h[j];break}}f(g,i)}return a.extend(!0,c,d),c}function g(c,d){function e(b){function d(a,b,c,d){this.matches=[],this.isGroup=a||!1,this.isOptional=b||!1,this.isQuantifier=c||!1,this.isAlternator=d||!1,this.quantifier={min:1,max:1}}function e(b,d,e){var f=c.definitions[d];e=void 0!==e?e:b.matches.length;var g=b.matches[e-1];if(f&&!r){f.placeholder=a.isFunction(f.placeholder)?f.placeholder(c):f.placeholder;for(var h=f.prevalidator,i=h?h.length:0,j=1;j<f.cardinality;j++){var k=i>=j?h[j-1]:[],l=k.validator,m=k.cardinality;b.matches.splice(e++,0,{fn:l?"string"==typeof l?new RegExp(l):new function(){this.test=l}:new RegExp("."),cardinality:m?m:1,optionality:b.isOptional,newBlockMarker:void 0===g||g.def!==(f.definitionSymbol||d),casing:f.casing,def:f.definitionSymbol||d,placeholder:f.placeholder,mask:d}),g=b.matches[e-1]}b.matches.splice(e++,0,{fn:f.validator?"string"==typeof f.validator?new RegExp(f.validator):new function(){this.test=f.validator}:new RegExp("."),cardinality:f.cardinality,optionality:b.isOptional,newBlockMarker:void 0===g||g.def!==(f.definitionSymbol||d),casing:f.casing,def:f.definitionSymbol||d,placeholder:f.placeholder,mask:d})}else b.matches.splice(e++,0,{fn:null,cardinality:0,optionality:b.isOptional,newBlockMarker:void 0===g||g.def!==d,casing:null,def:c.staticDefinitionSymbol||d,placeholder:void 0!==c.staticDefinitionSymbol?d:void 0,mask:d}),r=!1}function f(a,b){a.isGroup&&(a.isGroup=!1,e(a,c.groupmarker.start,0),b!==!0&&e(a,c.groupmarker.end))}function g(a,b,c,d){b.matches.length>0&&(void 0===d||d)&&(c=b.matches[b.matches.length-1],f(c)),e(b,a)}function h(){if(t.length>0){if(m=t[t.length-1],g(k,m,o,!m.isAlternator),m.isAlternator){n=t.pop();for(var a=0;a<n.matches.length;a++)n.matches[a].isGroup=!1;t.length>0?(m=t[t.length-1],m.matches.push(n)):s.matches.push(n)}}else g(k,s,o)}function i(a){function b(a){return a===c.optionalmarker.start?a=c.optionalmarker.end:a===c.optionalmarker.end?a=c.optionalmarker.start:a===c.groupmarker.start?a=c.groupmarker.end:a===c.groupmarker.end&&(a=c.groupmarker.start),a}a.matches=a.matches.reverse();for(var d in a.matches){var e=parseInt(d);if(a.matches[d].isQuantifier&&a.matches[e+1]&&a.matches[e+1].isGroup){var f=a.matches[d];a.matches.splice(d,1),a.matches.splice(e+1,0,f)}void 0!==a.matches[d].matches?a.matches[d]=i(a.matches[d]):a.matches[d]=b(a.matches[d])}return a}for(var j,k,l,m,n,o,p,q=/(?:[?*+]|\{[0-9\+\*]+(?:,[0-9\+\*]*)?\})|[^.?*+^${[]()|\\]+|./g,r=!1,s=new d,t=[],u=[];j=q.exec(b);)if(k=j[0],r)h();else switch(k.charAt(0)){case c.escapeChar:r=!0;break;case c.optionalmarker.end:case c.groupmarker.end:if(l=t.pop(),void 0!==l)if(t.length>0){if(m=t[t.length-1],m.matches.push(l),m.isAlternator){n=t.pop();for(var v=0;v<n.matches.length;v++)n.matches[v].isGroup=!1;t.length>0?(m=t[t.length-1],m.matches.push(n)):s.matches.push(n)}}else s.matches.push(l);else h();break;case c.optionalmarker.start:t.push(new d(!1,!0));break;case c.groupmarker.start:t.push(new d(!0));break;case c.quantifiermarker.start:var w=new d(!1,!1,!0);k=k.replace(/[{}]/g,"");var x=k.split(","),y=isNaN(x[0])?x[0]:parseInt(x[0]),z=1===x.length?y:isNaN(x[1])?x[1]:parseInt(x[1]);if(("*"===z||"+"===z)&&(y="*"===z?0:1),w.quantifier={min:y,max:z},t.length>0){var A=t[t.length-1].matches;j=A.pop(),j.isGroup||(p=new d(!0),p.matches.push(j),j=p),A.push(j),A.push(w)}else j=s.matches.pop(),j.isGroup||(p=new d(!0),p.matches.push(j),j=p),s.matches.push(j),s.matches.push(w);break;case c.alternatormarker:t.length>0?(m=t[t.length-1],o=m.matches.pop()):o=s.matches.pop(),o.isAlternator?t.push(o):(n=new d(!1,!1,!1,!0),n.matches.push(o),t.push(n));break;default:h()}for(;t.length>0;)l=t.pop(),f(l,!0),s.matches.push(l);return s.matches.length>0&&(o=s.matches[s.matches.length-1],f(o),u.push(s)),c.numericInput&&i(u[0]),u}function f(f,g){if(null===f||""===f)return void 0;if(1===f.length&&c.greedy===!1&&0!==c.repeat&&(c.placeholder=""),c.repeat>0||"*"===c.repeat||"+"===c.repeat){var h="*"===c.repeat?0:"+"===c.repeat?1:c.repeat;f=c.groupmarker.start+f+c.groupmarker.end+c.quantifiermarker.start+h+","+c.repeat+c.quantifiermarker.end}var i;return void 0===b.prototype.masksCache[f]||d===!0?(i={mask:f,maskToken:e(f),validPositions:{},_buffer:void 0,buffer:void 0,tests:{},metadata:g},d!==!0&&(b.prototype.masksCache[c.numericInput?f.split("").reverse().join(""):f]=i,i=a.extend(!0,{},b.prototype.masksCache[c.numericInput?f.split("").reverse().join(""):f]))):i=a.extend(!0,{},b.prototype.masksCache[c.numericInput?f.split("").reverse().join(""):f]),i}function g(a){return a=a.toString()}var h;if(a.isFunction(c.mask)&&(c.mask=c.mask(c)),a.isArray(c.mask)){if(c.mask.length>1){c.keepStatic=null===c.keepStatic?!0:c.keepStatic;var i="(";return a.each(c.numericInput?c.mask.reverse():c.mask,function(b,c){i.length>1&&(i+=")|("),i+=g(void 0===c.mask||a.isFunction(c.mask)?c:c.mask)}),i+=")",f(i,c.mask)}c.mask=c.mask.pop()}return c.mask&&(h=void 0===c.mask.mask||a.isFunction(c.mask.mask)?f(g(c.mask),c.mask):f(g(c.mask.mask),c.mask)),h}function h(e,f,g){function i(a,b,c){b=b||0;var d,e,f,h=[],i=0,j=o();do{if(a===!0&&m().validPositions[i]){var k=m().validPositions[i];e=k.match,d=k.locator.slice(),h.push(c===!0?k.input:I(i,e))}else f=r(i,d,i-1),e=f.match,d=f.locator.slice(),(g.jitMasking===!1||j>i||isFinite(g.jitMasking)&&g.jitMasking>i)&&h.push(I(i,e));i++}while((void 0===ma||ma>i-1)&&null!==e.fn||null===e.fn&&""!==e.def||b>=i);return""===h[h.length-1]&&h.pop(),h}function m(){return f}function n(a){var b=m();b.buffer=void 0,a!==!0&&(b.tests={},b._buffer=void 0,b.validPositions={},b.p=0)}function o(a,b){var c=-1,d=-1,e=m().validPositions;void 0===a&&(a=-1);for(var f in e){var g=parseInt(f);e[g]&&(b||null!==e[g].match.fn)&&(a>=g&&(c=g),g>=a&&(d=g))}return-1!==c&&a-c>1||a>d?c:d}function p(b,c,d){if(g.insertMode&&void 0!==m().validPositions[b]&&void 0===d){var e,f=a.extend(!0,{},m().validPositions),h=o();for(e=b;h>=e;e++)delete m().validPositions[e];m().validPositions[b]=c;var i,j=!0,k=m().validPositions;for(e=i=b;h>=e;e++){var l=f[e];if(void 0!==l)for(var p=i,q=-1;p<D()&&(null==l.match.fn&&k[e]&&(k[e].match.optionalQuantifier===!0||k[e].match.optionality===!0)||null!=l.match.fn);){if(null===l.match.fn||!g.keepStatic&&k[e]&&(void 0!==k[e+1]&&v(e+1,k[e].locator.slice(),e).length>1||void 0!==k[e].alternation)?p++:p=E(i),t(p,l.match.def)){var r=B(p,l.input,!0,!0);j=r!==!1,i=r.caret||r.insert?o():p;break}if(j=null==l.match.fn,q===p)break;q=p}if(!j)break}if(!j)return m().validPositions=a.extend(!0,{},f),n(!0),!1}else m().validPositions[b]=c;return n(!0),!0}function q(a,b,c,d){var e,f=a;for(m().p=a,e=f;b>e;e++)void 0!==m().validPositions[e]&&(c===!0||g.canClearPosition(m(),e,o(),d,g)!==!1)&&delete m().validPositions[e];for(e=f+1;e<=o();){for(;void 0!==m().validPositions[f];)f++;var h=m().validPositions[f];if(f>e&&(e=f+1),void 0===m().validPositions[e]&&C(e)||void 0!==h)e++;else{var i=r(e);t(f,i.match.def)?B(f,i.input||I(e),!0)!==!1&&(delete m().validPositions[e],e++):C(e)||(e++,f--),f++}}var j=o(),k=D();for(d!==!0&&c!==!0&&void 0!==m().validPositions[j]&&m().validPositions[j].input===g.radixPoint&&delete m().validPositions[j],e=j+1;k>=e;e++)m().validPositions[e]&&delete m().validPositions[e];n(!0)}function r(a,b,c){var d=m().validPositions[a];if(void 0===d)for(var e=v(a,b,c),f=o(),h=m().validPositions[f]||v(0)[0],i=void 0!==h.alternation?h.locator[h.alternation].toString().split(","):[],j=0;j<e.length&&(d=e[j],!(d.match&&(g.greedy&&d.match.optionalQuantifier!==!0||(d.match.optionality===!1||d.match.newBlockMarker===!1)&&d.match.optionalQuantifier!==!0)&&(void 0===h.alternation||h.alternation!==d.alternation||void 0!==d.locator[h.alternation]&&A(d.locator[h.alternation].toString().split(","),i))));j++);return d}function s(a){return m().validPositions[a]?m().validPositions[a].match:v(a)[0].match}function t(a,b){for(var c=!1,d=v(a),e=0;e<d.length;e++)if(d[e].match&&d[e].match.def===b){c=!0;break}return c}function u(b,c){var d,e;return(m().tests[b]||m().validPositions[b])&&a.each(m().tests[b]||[m().validPositions[b]],function(a,b){var f=b.alternation?b.locator[b.alternation].toString().indexOf(c):-1;(void 0===e||e>f)&&-1!==f&&(d=b,e=f)}),d}function v(b,c,d){function e(c,d,f,h){function j(f,h,o){function p(b,c){var d=0===a.inArray(b,c.matches);return d||a.each(c.matches,function(a,e){return e.isQuantifier===!0&&(d=p(b,c.matches[a-1]))?!1:void 0}),d}function q(a,b){var c=u(a,b);return c?c.locator.slice(c.alternation+1):[]}if(i>1e4)throw"Inputmask: There is probably an error in your mask definition or in the code. Create an issue on github with an example of the mask you are using. "+m().mask;if(i===b&&void 0===f.matches)return k.push({match:f,locator:h.reverse(),cd:n}),!0;if(void 0!==f.matches){if(f.isGroup&&o!==f){if(f=j(c.matches[a.inArray(f,c.matches)+1],h))return!0}else if(f.isOptional){var r=f;if(f=e(f,d,h,o)){if(g=k[k.length-1].match,!p(g,r))return!0;l=!0,i=b}}else if(f.isAlternator){var s,t=f,v=[],w=k.slice(),x=h.length,y=d.length>0?d.shift():-1;if(-1===y||"string"==typeof y){var z,A=i,B=d.slice(),C=[];if("string"==typeof y)C=y.split(",");else for(z=0;z<t.matches.length;z++)C.push(z);for(var D=0;D<C.length;D++){if(z=parseInt(C[D]),k=[],d=q(i,z),f=j(t.matches[z]||c.matches[z],[z].concat(h),o)||f,f!==!0&&void 0!==f&&C[C.length-1]<t.matches.length){var E=a.inArray(f,c.matches)+1;c.matches.length>E&&(f=j(c.matches[E],[E].concat(h.slice(1,h.length)),o),f&&(C.push(E.toString()),a.each(k,function(a,b){b.alternation=h.length-1})))}s=k.slice(),i=A,k=[];for(var F=0;F<B.length;F++)d[F]=B[F];for(var G=0;G<s.length;G++){var H=s[G];H.alternation=H.alternation||x;for(var I=0;I<v.length;I++){var J=v[I];if(H.match.def===J.match.def&&("string"!=typeof y||-1!==a.inArray(H.locator[H.alternation].toString(),C))){H.match.mask===J.match.mask&&(s.splice(G,1),G--),-1===J.locator[H.alternation].toString().indexOf(H.locator[H.alternation])&&(J.locator[H.alternation]=J.locator[H.alternation]+","+H.locator[H.alternation],J.alternation=H.alternation);break}}}v=v.concat(s)}"string"==typeof y&&(v=a.map(v,function(b,c){if(isFinite(c)){var d,e=b.alternation,f=b.locator[e].toString().split(",");b.locator[e]=void 0,b.alternation=void 0;for(var g=0;g<f.length;g++)d=-1!==a.inArray(f[g],C),d&&(void 0!==b.locator[e]?(b.locator[e]+=",",b.locator[e]+=f[g]):b.locator[e]=parseInt(f[g]),b.alternation=e);if(void 0!==b.locator[e])return b}})),k=w.concat(v),i=b,l=k.length>0}else f=j(t.matches[y]||c.matches[y],[y].concat(h),o);if(f)return!0}else if(f.isQuantifier&&o!==c.matches[a.inArray(f,c.matches)-1])for(var K=f,L=d.length>0?d.shift():0;L<(isNaN(K.quantifier.max)?L+1:K.quantifier.max)&&b>=i;L++){var M=c.matches[a.inArray(K,c.matches)-1];if(f=j(M,[L].concat(h),M)){if(g=k[k.length-1].match,g.optionalQuantifier=L>K.quantifier.min-1,p(g,M)){if(L>K.quantifier.min-1){l=!0,i=b;break}return!0}return!0}}else if(f=e(f,d,h,o))return!0}else i++}for(var o=d.length>0?d.shift():0;o<c.matches.length;o++)if(c.matches[o].isQuantifier!==!0){var p=j(c.matches[o],[o].concat(f),h);if(p&&i===b)return p;if(i>b)break}}function f(a){var b=a[0]||a;return b.locator.slice()}var g,h=m().maskToken,i=c?d:0,j=c||[0],k=[],l=!1,n=c?c.join(""):"";if(b>-1){if(void 0===c){for(var o,p=b-1;void 0===(o=m().validPositions[p]||m().tests[p])&&p>-1;)p--;void 0!==o&&p>-1&&(j=f(o),n=j.join(""),o=o[0]||o,i=p)}if(m().tests[b]&&m().tests[b][0].cd===n)return m().tests[b];for(var q=j.shift();q<h.length;q++){var r=e(h[q],j,[q]);if(r&&i===b||i>b)break}}return(0===k.length||l)&&k.push({match:{fn:null,cardinality:0,optionality:!0,casing:null,def:""},locator:[]}),m().tests[b]=a.extend(!0,[],k),m().tests[b]}function w(){return void 0===m()._buffer&&(m()._buffer=i(!1,1)),m()._buffer}function x(a){if(void 0===m().buffer||a===!0){if(a===!0)for(var b in m().tests)void 0===m().validPositions[b]&&delete m().tests[b];m().buffer=i(!0,o(),!0)}return m().buffer}function y(a,b,c){var d;if(c=c,a===!0)n(),a=0,b=c.length;else for(d=a;b>d;d++)delete m().validPositions[d],delete m().tests[d];for(d=a;b>d;d++)n(!0),c[d]!==g.skipOptionalPartCharacter&&B(d,c[d],!0,!0)}function z(a,b){switch(b.casing){case"upper":a=a.toUpperCase();break;case"lower":a=a.toLowerCase()}return a}function A(b,c){for(var d=g.greedy?c:c.slice(0,1),e=!1,f=0;f<b.length;f++)if(-1!==a.inArray(b[f],d)){e=!0;break}return e}function B(b,c,d,e){function f(b,c,d,e){var f=!1;return a.each(v(b),function(h,i){for(var j=i.match,k=c?1:0,l="",r=j.cardinality;r>k;r--)l+=G(b-(r-1));if(c&&(l+=c),x(!0),f=null!=j.fn?j.fn.test(l,m(),b,d,g):c!==j.def&&c!==g.skipOptionalPartCharacter||""===j.def?!1:{c:j.placeholder||j.def,pos:b},f!==!1){var s=void 0!==f.c?f.c:c;s=s===g.skipOptionalPartCharacter&&null===j.fn?j.placeholder||j.def:s;var t=b,u=x();if(void 0!==f.remove&&(a.isArray(f.remove)||(f.remove=[f.remove]),a.each(f.remove.sort(function(a,b){return b-a}),function(a,b){q(b,b+1,!0)})),void 0!==f.insert&&(a.isArray(f.insert)||(f.insert=[f.insert]),a.each(f.insert.sort(function(a,b){return a-b}),function(a,b){B(b.pos,b.c,!1,e)})),f.refreshFromBuffer){var v=f.refreshFromBuffer;if(d=!0,y(v===!0?v:v.start,v.end,u),void 0===f.pos&&void 0===f.c)return f.pos=o(),!1;if(t=void 0!==f.pos?f.pos:b,t!==b)return f=a.extend(f,B(t,s,!0,e)),!1}else if(f!==!0&&void 0!==f.pos&&f.pos!==b&&(t=f.pos,y(b,t,x().slice()),t!==b))return f=a.extend(f,B(t,s,!0)),!1;return f!==!0&&void 0===f.pos&&void 0===f.c?!1:(h>0&&n(!0),p(t,a.extend({},i,{input:z(s,j)}),e)||(f=!1),!1)}}),f}function h(b,c,d,e){for(var f,h,i,j,k,l,p=a.extend(!0,{},m().validPositions),q=a.extend(!0,{},m().tests),s=o();s>=0&&(j=m().validPositions[s],!j||void 0===j.alternation||(f=s,h=m().validPositions[f].alternation,r(f).locator[j.alternation]===j.locator[j.alternation]));s--);if(void 0!==h){f=parseInt(f);for(var t in m().validPositions)if(t=parseInt(t),j=m().validPositions[t],t>=f&&void 0!==j.alternation){var v;0===f?(v=[],a.each(m().tests[f],function(a,b){void 0!==b.locator[h]&&(v=v.concat(b.locator[h].toString().split(",")))})):v=m().validPositions[f].locator[h].toString().split(",");var w=void 0!==j.locator[h]?j.locator[h]:v[0];w.length>0&&(w=w.split(",")[0]);for(var x=0;x<v.length;x++){var y=[],z=0,A=0;if(w<v[x]){for(var C,D,E=t;E>=0;E--)if(C=m().validPositions[E],void 0!==C){var F=u(E,v[x]);m().validPositions[E].match.def!==F.match.def&&(y.push(m().validPositions[E].input),m().validPositions[E]=F,m().validPositions[E].input=I(E),null===m().validPositions[E].match.fn&&A++,C=F),D=C.locator[h],C.locator[h]=parseInt(v[x]);break}if(w!==C.locator[h]){for(k=t+1;k<o(void 0,!0)+1;k++)l=m().validPositions[k],l&&null!=l.match.fn?y.push(l.input):b>k&&z++,delete m().validPositions[k],delete m().tests[k];for(n(!0),g.keepStatic=!g.keepStatic,i=!0;y.length>0;){var G=y.shift();if(G!==g.skipOptionalPartCharacter&&!(i=B(o(void 0,!0)+1,G,!1,e)))break}if(C.alternation=h,C.locator[h]=D,i){var H=o(b)+1;for(k=t+1;k<o()+1;k++)l=m().validPositions[k],(void 0===l||null==l.match.fn)&&b>k&&A++;b+=A-z,i=B(b>H?H:b,c,d,e)}if(g.keepStatic=!g.keepStatic,i)return i;n(),m().validPositions=a.extend(!0,{},p),m().tests=a.extend(!0,{},q)}}}break}}return!1}function i(b,c){for(var d=m().validPositions[c],e=d.locator,f=e.length,g=b;c>g;g++)if(void 0===m().validPositions[g]&&!C(g,!0)){var h=v(g),i=h[0],j=-1;a.each(h,function(a,b){for(var c=0;f>c&&(void 0!==b.locator[c]&&A(b.locator[c].toString().split(","),e[c].toString().split(",")));c++)c>j&&(j=c,i=b)}),p(g,a.extend({},i,{input:i.match.placeholder||i.match.def}),!0)}}d=d===!0;for(var j=x(),k=b-1;k>-1&&!m().validPositions[k];k--);for(k++;b>k;k++)void 0===m().validPositions[k]&&((!C(k)||j[k]!==I(k))&&v(k).length>1||j[k]===g.radixPoint||"0"===j[k]&&a.inArray(g.radixPoint,j)<k)&&f(k,j[k],!0,e);var l=b,s=!1,t=a.extend(!0,{},m().validPositions);if(l<D()&&(s=f(l,c,d,e),(!d||e===!0)&&s===!1)){var w=m().validPositions[l];if(!w||null!==w.match.fn||w.match.def!==c&&c!==g.skipOptionalPartCharacter){if((g.insertMode||void 0===m().validPositions[E(l)])&&!C(l,!0)){var F=r(l).match,F=F.placeholder||F.def;f(l,F,d,e);for(var H=l+1,J=E(l);J>=H;H++)if(s=f(H,c,d,e),s!==!1){i(l,H),l=H;break}}}else s={caret:E(l)}}if(s===!1&&g.keepStatic&&(s=h(b,c,d,e)),s===!0&&(s={pos:l}),a.isFunction(g.postValidation)&&s!==!1&&!d&&e!==!0){var K=g.postValidation(x(!0),s,g);if(K){if(K.refreshFromBuffer){var L=K.refreshFromBuffer;y(L===!0?L:L.start,L.end,K.buffer),n(!0),s=K}}else n(!0),m().validPositions=a.extend(!0,{},t),s=!1}return s}function C(a,b){var c;if(b?(c=r(a).match,""==c.def&&(c=s(a))):c=s(a),null!=c.fn)return c.fn;if(b!==!0&&a>-1&&!g.keepStatic&&void 0===m().validPositions[a]){var d=v(a);return d.length>2}return!1}function D(){var a;ma=void 0!==ka?ka.maxLength:void 0,-1===ma&&(ma=void 0);var b,c=o(),d=m().validPositions[c],e=void 0!==d?d.locator.slice():void 0;for(b=c+1;void 0===d||null!==d.match.fn||null===d.match.fn&&""!==d.match.def;b++)d=r(b,e,b-1),e=d.locator.slice();var f=s(b-1);return a=""!==f.def?b:b-1,void 0===ma||ma>a?a:ma}function E(a,b){var c=D();if(a>=c)return c;for(var d=a;++d<c&&(b===!0&&(s(d).newBlockMarker!==!0||!C(d))||b!==!0&&!C(d)&&(g.nojumps!==!0||g.nojumpsThreshold>d)););return d}function F(a,b){var c=a;if(0>=c)return 0;for(;--c>0&&(b===!0&&s(c).newBlockMarker!==!0||b!==!0&&!C(c)););return c}function G(a){return void 0===m().validPositions[a]?I(a):m().validPositions[a].input}function H(b,c,d,e,f){if(e&&a.isFunction(g.onBeforeWrite)){var h=g.onBeforeWrite(e,c,d,g);if(h){if(h.refreshFromBuffer){var i=h.refreshFromBuffer;y(i===!0?i:i.start,i.end,h.buffer||c),c=x(!0)}void 0!==d&&(d=void 0!==h.caret?h.caret:d)}}b.inputmask._valueSet(c.join("")),void 0===d||void 0!==e&&"blur"===e.type||L(b,d),f===!0&&(qa=!0,a(b).trigger("input"))}function I(a,b){if(b=b||s(a),void 0!==b.placeholder)return b.placeholder;if(null===b.fn){if(a>-1&&!g.keepStatic&&void 0===m().validPositions[a]){var c,d=v(a),e=0;if(d.length>2)for(var f=0;f<d.length;f++)if(d[f].match.optionality!==!0&&d[f].match.optionalQuantifier!==!0&&(null===d[f].match.fn||void 0===c||d[f].match.fn.test(c.match.def,m(),a,!0,g)!==!1)&&(e++,null===d[f].match.fn&&(c=d[f]),e>1))return g.placeholder.charAt(a%g.placeholder.length)}return b.def}return g.placeholder.charAt(a%g.placeholder.length)}function J(c,d,e,f){function h(){var a=!1,b=w().slice(k,E(k)).join("").indexOf(j);if(-1!==b&&!C(k)){a=!0;for(var c=w().slice(k,k+b),d=0;d<c.length;d++)if(" "!==c[d]){a=!1;break}}return a}var i=f.slice(),j="",k=0;if(n(),m().p=E(-1),!e)if(g.autoUnmask!==!0){var l=w().slice(0,E(-1)).join(""),p=i.join("").match(new RegExp("^"+b.escapeRegex(l),"g"));p&&p.length>0&&(i.splice(0,p.length*l.length),k=E(k))}else k=E(k);a.each(i,function(b,d){if(void 0!==d){var f=new a.Event("keypress");f.which=d.charCodeAt(0),j+=d;var i=o(void 0,!0),l=m().validPositions[i],n=r(i+1,l?l.locator.slice():void 0,i);if(!h()||e||g.autoUnmask){var p=e?b:null==n.match.fn&&n.match.optionality&&i+1<m().p?i+1:m().p;T.call(c,f,!0,!1,e,p),k=p+1,j=""}else T.call(c,f,!0,!1,!0,i+1)}}),d&&H(c,x(),document.activeElement===c?E(o(0)):void 0,new a.Event("checkval"))}function K(b){if(b&&void 0===b.inputmask)return b.value;var c=[],d=m().validPositions;for(var e in d)d[e].match&&null!=d[e].match.fn&&c.push(d[e].input);var f=0===c.length?null:(oa?c.reverse():c).join("");if(null!==f){var h=(oa?x().slice().reverse():x()).join("");a.isFunction(g.onUnMask)&&(f=g.onUnMask(h,f,g)||f)}return f}function L(a,b,c,d){function e(a){if(d!==!0&&oa&&"number"==typeof a&&(!g.greedy||""!==g.placeholder)){var b=x().join("").length;a=b-a}return a}var f;if("number"!=typeof b)return a.setSelectionRange?(b=a.selectionStart,c=a.selectionEnd):window.getSelection?(f=window.getSelection().getRangeAt(0),(f.commonAncestorContainer.parentNode===a||f.commonAncestorContainer===a)&&(b=f.startOffset,c=f.endOffset)):document.selection&&document.selection.createRange&&(f=document.selection.createRange(),b=0-f.duplicate().moveStart("character",-1e5),c=b+f.text.length),{begin:e(b),end:e(c)};b=e(b),c=e(c),c="number"==typeof c?c:b;var h=parseInt(((a.ownerDocument.defaultView||window).getComputedStyle?(a.ownerDocument.defaultView||window).getComputedStyle(a,null):a.currentStyle).fontSize)*c;if(a.scrollLeft=h>a.scrollWidth?h:0,j||g.insertMode!==!1||b!==c||c++,a.setSelectionRange)a.selectionStart=b,a.selectionEnd=c;else if(window.getSelection){if(f=document.createRange(),void 0===a.firstChild||null===a.firstChild){var i=document.createTextNode("");a.appendChild(i)}f.setStart(a.firstChild,b<a.inputmask._valueGet().length?b:a.inputmask._valueGet().length),f.setEnd(a.firstChild,c<a.inputmask._valueGet().length?c:a.inputmask._valueGet().length),f.collapse(!0);var k=window.getSelection();k.removeAllRanges(),k.addRange(f)}else a.createTextRange&&(f=a.createTextRange(),f.collapse(!0),f.moveEnd("character",c),f.moveStart("character",b),f.select())}function M(b){var c,d,e=x(),f=e.length,g=o(),h={},i=m().validPositions[g],j=void 0!==i?i.locator.slice():void 0;for(c=g+1;c<e.length;c++)d=r(c,j,c-1),j=d.locator.slice(),h[c]=a.extend(!0,{},d);var k=i&&void 0!==i.alternation?i.locator[i.alternation]:void 0;for(c=f-1;c>g&&(d=h[c],(d.match.optionality||d.match.optionalQuantifier||k&&(k!==h[c].locator[i.alternation]&&null!=d.match.fn||null===d.match.fn&&d.locator[i.alternation]&&A(d.locator[i.alternation].toString().split(","),k.toString().split(","))&&""!==v(c)[0].def))&&e[c]===I(c,d.match));c--)f--;return b?{l:f,def:h[f]?h[f].match:void 0}:f}function N(a){for(var b=M(),c=a.length-1;c>b&&!C(c);c--);return a.splice(b,c+1-b),a}function O(b){if(a.isFunction(g.isComplete))return g.isComplete(b,g);if("*"===g.repeat)return void 0;var c=!1,d=M(!0),e=F(d.l);if(void 0===d.def||d.def.newBlockMarker||d.def.optionality||d.def.optionalQuantifier){c=!0;for(var f=0;e>=f;f++){var h=r(f).match;if(null!==h.fn&&void 0===m().validPositions[f]&&h.optionality!==!0&&h.optionalQuantifier!==!0||null===h.fn&&b[f]!==I(f,h)){c=!1;break}}}return c}function P(a,b){return oa?a-b>1||a-b===1&&g.insertMode:b-a>1||b-a===1&&g.insertMode}function Q(b){function c(b){if(a.valHooks&&(void 0===a.valHooks[b]||a.valHooks[b].inputmaskpatch!==!0)){var c=a.valHooks[b]&&a.valHooks[b].get?a.valHooks[b].get:function(a){return a.value},d=a.valHooks[b]&&a.valHooks[b].set?a.valHooks[b].set:function(a,b){return a.value=b,a};a.valHooks[b]={get:function(a){if(a.inputmask){if(a.inputmask.opts.autoUnmask)return a.inputmask.unmaskedvalue();var b=c(a),d=a.inputmask.maskset,e=d._buffer;return e=e?e.join(""):"",b!==e?b:""}return c(a)},set:function(b,c){var e,f=a(b);return e=d(b,c),b.inputmask&&f.trigger("setvalue"),e},inputmaskpatch:!0}}}function d(){return this.inputmask?this.inputmask.opts.autoUnmask?this.inputmask.unmaskedvalue():h.call(this)!==w().join("")?document.activeElement===this&&g.clearMaskOnLostFocus?(oa?N(x().slice()).reverse():N(x().slice())).join(""):h.call(this):"":h.call(this)}function e(b){i.call(this,b),this.inputmask&&a(this).trigger("setvalue")}function f(b){ua.on(b,"mouseenter",function(b){var c=a(this),d=this,e=d.inputmask._valueGet();e!==x().join("")&&o()>0&&c.trigger("setvalue")})}var h,i;b.inputmask.__valueGet||(Object.getOwnPropertyDescriptor&&void 0===b.value?(h=function(){return this.textContent},i=function(a){this.textContent=a},Object.defineProperty(b,"value",{get:d,set:e})):document.__lookupGetter__&&b.__lookupGetter__("value")?(h=b.__lookupGetter__("value"),i=b.__lookupSetter__("value"),b.__defineGetter__("value",d),b.__defineSetter__("value",e)):(h=function(){return b.value},i=function(a){b.value=a},c(b.type),f(b)),b.inputmask.__valueGet=h,b.inputmask._valueGet=function(a){return oa&&a!==!0?h.call(this.el).split("").reverse().join(""):h.call(this.el)},b.inputmask.__valueSet=i,b.inputmask._valueSet=function(a,b){i.call(this.el,null===a||void 0===a?"":b!==!0&&oa?a.split("").reverse().join(""):a)})}function R(c,d,e,f){function h(){if(g.keepStatic){n(!0);var b,d=[],e=a.extend(!0,{},m().validPositions);for(b=o();b>=0;b--){var f=m().validPositions[b];if(f&&(null!=f.match.fn&&d.push(f.input),delete m().validPositions[b],void 0!==f.alternation&&f.locator[f.alternation]===r(b).locator[f.alternation]))break}if(b>-1)for(;d.length>0;){m().p=E(o());var h=new a.Event("keypress");h.which=d.pop().charCodeAt(0),T.call(c,h,!0,!1,!1,m().p)}else m().validPositions=a.extend(!0,{},e)}}if((g.numericInput||oa)&&(d===b.keyCode.BACKSPACE?d=b.keyCode.DELETE:d===b.keyCode.DELETE&&(d=b.keyCode.BACKSPACE),oa)){var i=e.end;e.end=e.begin,e.begin=i}d===b.keyCode.BACKSPACE&&(e.end-e.begin<1||g.insertMode===!1)?(e.begin=F(e.begin),void 0===m().validPositions[e.begin]||m().validPositions[e.begin].input!==g.groupSeparator&&m().validPositions[e.begin].input!==g.radixPoint||e.begin--):d===b.keyCode.DELETE&&e.begin===e.end&&(e.end=C(e.end)?e.end+1:E(e.end)+1,void 0===m().validPositions[e.begin]||m().validPositions[e.begin].input!==g.groupSeparator&&m().validPositions[e.begin].input!==g.radixPoint||e.end++),q(e.begin,e.end,!1,f),f!==!0&&h();var j=o(e.begin);j<e.begin?(-1===j&&n(),m().p=E(j)):f!==!0&&(m().p=e.begin)}function S(d){var e=this,f=a(e),h=d.keyCode,i=L(e);if(h===b.keyCode.BACKSPACE||h===b.keyCode.DELETE||l&&127===h||d.ctrlKey&&88===h&&!c("cut"))d.preventDefault(),88===h&&(ia=x().join("")),R(e,h,i),H(e,x(),m().p,d,ia!==x().join("")),e.inputmask._valueGet()===w().join("")?f.trigger("cleared"):O(x())===!0&&f.trigger("complete"),g.showTooltip&&(e.title=g.tooltip||m().mask);else if(h===b.keyCode.END||h===b.keyCode.PAGE_DOWN){d.preventDefault();var j=E(o());g.insertMode||j!==D()||d.shiftKey||j--,L(e,d.shiftKey?i.begin:j,j,!0)}else h===b.keyCode.HOME&&!d.shiftKey||h===b.keyCode.PAGE_UP?(d.preventDefault(),L(e,0,d.shiftKey?i.begin:0,!0)):(g.undoOnEscape&&h===b.keyCode.ESCAPE||90===h&&d.ctrlKey)&&d.altKey!==!0?(J(e,!0,!1,ia.split("")),f.trigger("click")):h!==b.keyCode.INSERT||d.shiftKey||d.ctrlKey?g.tabThrough===!0&&h===b.keyCode.TAB?(d.shiftKey===!0?(null===s(i.begin).fn&&(i.begin=E(i.begin)),i.end=F(i.begin,!0),i.begin=F(i.end,!0)):(i.begin=E(i.begin,!0),i.end=E(i.begin,!0),i.end<D()&&i.end--),i.begin<D()&&(d.preventDefault(),L(e,i.begin,i.end))):g.insertMode!==!1||d.shiftKey||(h===b.keyCode.RIGHT?setTimeout(function(){var a=L(e);L(e,a.begin)},0):h===b.keyCode.LEFT&&setTimeout(function(){var a=L(e);L(e,oa?a.begin+1:a.begin-1)},0)):(g.insertMode=!g.insertMode,L(e,g.insertMode||i.begin!==D()?i.begin:i.begin-1));g.onKeyDown.call(this,d,x(),L(e).begin,g),ra=-1!==a.inArray(h,g.ignorables)}function T(c,d,e,f,h){var i=this,j=a(i),k=c.which||c.charCode||c.keyCode;if(!(d===!0||c.ctrlKey&&c.altKey)&&(c.ctrlKey||c.metaKey||ra))return k===b.keyCode.ENTER&&ia!==x().join("")&&(ia=x().join(""),setTimeout(function(){j.trigger("change")},0)),!0;if(k){46===k&&c.shiftKey===!1&&","===g.radixPoint&&(k=44);var l,o=d?{begin:h,end:h}:L(i),q=String.fromCharCode(k),r=P(o.begin,o.end);r&&(m().undoPositions=a.extend(!0,{},m().validPositions),R(i,b.keyCode.DELETE,o,!0),o.begin=m().p,g.insertMode||(g.insertMode=!g.insertMode,p(o.begin,f),g.insertMode=!g.insertMode),r=!g.multi),m().writeOutBuffer=!0;var s=oa&&!r?o.end:o.begin,t=B(s,q,f);if(t!==!1){if(t!==!0&&(s=void 0!==t.pos?t.pos:s,q=void 0!==t.c?t.c:q),n(!0),void 0!==t.caret)l=t.caret;else{var u=m().validPositions;l=!g.keepStatic&&(void 0!==u[s+1]&&v(s+1,u[s].locator.slice(),s).length>1||void 0!==u[s].alternation)?s+1:E(s)}m().p=l}if(e!==!1){var w=this;if(setTimeout(function(){g.onKeyValidation.call(w,k,t,g)},0),m().writeOutBuffer&&t!==!1){var z=x();H(i,z,g.numericInput&&void 0===t.caret?F(l):l,c,d!==!0),d!==!0&&setTimeout(function(){O(z)===!0&&j.trigger("complete")},0)}else r&&(m().buffer=void 0,m().validPositions=m().undoPositions)}else r&&(m().buffer=void 0,m().validPositions=m().undoPositions);if(g.showTooltip&&(i.title=g.tooltip||m().mask),d&&a.isFunction(g.onBeforeWrite)){var A=g.onBeforeWrite(c,x(),l,g);if(A&&A.refreshFromBuffer){var C=A.refreshFromBuffer;y(C===!0?C:C.start,C.end,A.buffer),n(!0),A.caret&&(m().p=A.caret)}}if(c.preventDefault(),d)return t}}function U(b){var c=this,d=b.originalEvent||b,e=a(c),f=c.inputmask._valueGet(!0),h=L(c),i=f.substr(0,h.begin),j=f.substr(h.end,f.length);i===w().slice(0,h.begin).join("")&&(i=""),j===w().slice(h.end).join("")&&(j=""),window.clipboardData&&window.clipboardData.getData?f=i+window.clipboardData.getData("Text")+j:d.clipboardData&&d.clipboardData.getData&&(f=i+d.clipboardData.getData("text/plain")+j);var k=f;if(a.isFunction(g.onBeforePaste)){if(k=g.onBeforePaste(f,g),k===!1)return b.preventDefault(),!1;k||(k=f)}return J(c,!1,!1,oa?k.split("").reverse():k.toString().split("")),H(c,x(),void 0,b,!0),e.trigger("click"),O(x())===!0&&e.trigger("complete"),!1}function V(c){var d=this,e=d.inputmask._valueGet();if(x().join("")!==e){var f=L(d);if(e=e.replace(new RegExp("("+b.escapeRegex(w().join(""))+")*"),""),k){var g=e.replace(x().join(""),"");if(1===g.length){var h=new a.Event("keypress");return h.which=g.charCodeAt(0),T.call(d,h,!0,!0,!1,m().validPositions[f.begin-1]?f.begin:f.begin-1),!1}}if(f.begin>e.length&&(L(d,e.length),f=L(d)),x().length-e.length!==1||e.charAt(f.begin)===x()[f.begin]||e.charAt(f.begin+1)===x()[f.begin]||C(f.begin)){for(var i=o()+1,j=x().slice(i).join("");null===e.match(b.escapeRegex(j)+"$");)j=j.slice(1);e=e.replace(j,""),e=e.split(""),J(d,!0,!1,e),O(x())===!0&&a(d).trigger("complete")}else c.keyCode=b.keyCode.BACKSPACE,S.call(d,c);c.preventDefault()}}function W(a){var b=a.originalEvent||a;ia=x().join(""),""===ja||0!==b.data.indexOf(ja)}function X(b){var c=this,d=b.originalEvent||b,e=x().join("");0===d.data.indexOf(ja)&&(n(),m().p=E(-1));for(var f=d.data,h=0;h<f.length;h++){var i=new a.Event("keypress");i.which=f.charCodeAt(h),pa=!1,ra=!1,T.call(c,i,!0,!1,!1,m().p)}e!==x().join("")&&setTimeout(function(){var a=m().p;H(c,x(),g.numericInput?F(a):a)},0),ja=d.data}function Y(a){}function Z(b){var c=this,d=c.inputmask._valueGet();J(c,!0,!1,(a.isFunction(g.onBeforeMask)?g.onBeforeMask(d,g)||d:d).split("")),ia=x().join(""),(g.clearMaskOnLostFocus||g.clearIncomplete)&&c.inputmask._valueGet()===w().join("")&&c.inputmask._valueSet("")}function $(a){var b=this,c=b.inputmask._valueGet();g.showMaskOnFocus&&(!g.showMaskOnHover||g.showMaskOnHover&&""===c)?b.inputmask._valueGet()!==x().join("")&&H(b,x(),E(o())):sa===!1&&L(b,E(o())),g.positionCaretOnTab===!0&&setTimeout(function(){L(b,E(o()))},0),ia=x().join("")}function _(a){var b=this;if(sa=!1,g.clearMaskOnLostFocus&&document.activeElement!==b){var c=x().slice(),d=b.inputmask._valueGet();d!==b.getAttribute("placeholder")&&""!==d&&(-1===o()&&d===w().join("")?c=[]:N(c),H(b,c))}}function aa(b){function c(b){if(g.radixFocus&&""!==g.radixPoint){var c=m().validPositions; if(void 0===c[b]||c[b].input===I(b)){if(b<E(-1))return!0;var d=a.inArray(g.radixPoint,x());if(-1!==d){for(var e in c)if(e>d&&c[e].input!==I(e))return!1;return!0}}}return!1}var d=this;if(document.activeElement===d){var e=L(d);if(e.begin===e.end)if(c(e.begin))L(d,g.numericInput?E(a.inArray(g.radixPoint,x())):a.inArray(g.radixPoint,x()));else{var f=e.begin,h=o(f),i=E(h);i>f?L(d,C(f)||C(f-1)?f:E(f)):((x()[i]!==I(i)||!C(i,!0)&&s(i).def===I(i))&&(i=E(i)),L(d,i))}}}function ba(a){var b=this;setTimeout(function(){L(b,0,E(o()))},0)}function ca(c){var d=this,e=a(d),f=L(d),h=c.originalEvent||c,i=window.clipboardData||h.clipboardData,j=oa?x().slice(f.end,f.begin):x().slice(f.begin,f.end);i.setData("text",oa?j.reverse().join(""):j.join("")),document.execCommand&&document.execCommand("copy"),R(d,b.keyCode.DELETE,f),H(d,x(),m().p,c,ia!==x().join("")),d.inputmask._valueGet()===w().join("")&&e.trigger("cleared"),g.showTooltip&&(d.title=g.tooltip||m().mask)}function da(b){var c=a(this),d=this;if(d.inputmask){var e=d.inputmask._valueGet(),f=x().slice();ia!==f.join("")&&setTimeout(function(){c.trigger("change"),ia=f.join("")},0),""!==e&&(g.clearMaskOnLostFocus&&(-1===o()&&e===w().join("")?f=[]:N(f)),O(f)===!1&&(setTimeout(function(){c.trigger("incomplete")},0),g.clearIncomplete&&(n(),f=g.clearMaskOnLostFocus?[]:w().slice())),H(d,f,void 0,b))}}function ea(a){var b=this;sa=!0,document.activeElement!==b&&g.showMaskOnHover&&b.inputmask._valueGet()!==x().join("")&&H(b,x())}function fa(a){ia!==x().join("")&&la.trigger("change"),g.clearMaskOnLostFocus&&-1===o()&&ka.inputmask._valueGet&&ka.inputmask._valueGet()===w().join("")&&ka.inputmask._valueSet(""),g.removeMaskOnSubmit&&(ka.inputmask._valueSet(ka.inputmask.unmaskedvalue(),!0),setTimeout(function(){H(ka,x())},0))}function ga(a){setTimeout(function(){la.trigger("setvalue")},0)}function ha(b){if(ka=b,la=a(ka),g.showTooltip&&(ka.title=g.tooltip||m().mask),("rtl"===ka.dir||g.rightAlign)&&(ka.style.textAlign="right"),("rtl"===ka.dir||g.numericInput)&&(ka.dir="ltr",ka.removeAttribute("dir"),ka.inputmask.isRTL=!0,oa=!0),ua.off(ka),Q(ka),d(ka,g)&&(ua.on(ka,"submit",fa),ua.on(ka,"reset",ga),ua.on(ka,"mouseenter",ea),ua.on(ka,"blur",da),ua.on(ka,"focus",$),ua.on(ka,"mouseleave",_),ua.on(ka,"click",aa),ua.on(ka,"dblclick",ba),ua.on(ka,"paste",U),ua.on(ka,"dragdrop",U),ua.on(ka,"drop",U),ua.on(ka,"cut",ca),ua.on(ka,"complete",g.oncomplete),ua.on(ka,"incomplete",g.onincomplete),ua.on(ka,"cleared",g.oncleared),ua.on(ka,"keydown",S),ua.on(ka,"keypress",T),ua.on(ka,"input",V),j||(ua.on(ka,"compositionstart",W),ua.on(ka,"compositionupdate",X),ua.on(ka,"compositionend",Y))),ua.on(ka,"setvalue",Z),""!==ka.inputmask._valueGet()||g.clearMaskOnLostFocus===!1){var c=a.isFunction(g.onBeforeMask)?g.onBeforeMask(ka.inputmask._valueGet(),g)||ka.inputmask._valueGet():ka.inputmask._valueGet();J(ka,!0,!1,c.split(""));var e=x().slice();ia=e.join(""),O(e)===!1&&g.clearIncomplete&&n(),g.clearMaskOnLostFocus&&(e.join("")===w().join("")?e=[]:N(e)),H(ka,e),document.activeElement===ka&&L(ka,E(o()))}}var ia,ja,ka,la,ma,na,oa=!1,pa=!1,qa=!1,ra=!1,sa=!0,ta=!1,ua={on:function(c,d,e){var f=function(c){if(void 0===this.inputmask&&"FORM"!==this.nodeName){var d=a.data(this,"_inputmask_opts");d?new b(d).mask(this):ua.off(this)}else{if("setvalue"===c.type||!(this.disabled||this.readOnly&&!("keydown"===c.type&&c.ctrlKey&&67===c.keyCode||g.tabThrough===!1&&c.keyCode===b.keyCode.TAB))){switch(c.type){case"input":if(qa===!0||ta===!0)return qa=ta,c.preventDefault();break;case"keydown":pa=!1,qa=!1,ta=!1;break;case"keypress":if(pa===!0)return c.preventDefault();pa=!0;break;case"compositionstart":ta=!0;break;case"compositionupdate":qa=!0;break;case"compositionend":ta=!1;break;case"cut":qa=!0;break;case"click":if(k){var f=this;return setTimeout(function(){e.apply(f,arguments)},0),!1}}return e.apply(this,arguments)}c.preventDefault()}};c.inputmask.events[d]=c.inputmask.events[d]||[],c.inputmask.events[d].push(f),-1!==a.inArray(d,["submit","reset"])?null!=c.form&&a(c.form).on(d,f):a(c).on(d,f)},off:function(b,c){if(b.inputmask&&b.inputmask.events){var d;c?(d=[],d[c]=b.inputmask.events[c]):d=b.inputmask.events,a.each(d,function(c,d){for(;d.length>0;){var e=d.pop();-1!==a.inArray(c,["submit","reset"])?null!=b.form&&a(b.form).off(c,e):a(b).off(c,e)}delete b.inputmask.events[c]})}}};if(void 0!==e)switch(e.action){case"isComplete":return ka=e.el,O(x());case"unmaskedvalue":return ka=e.el,void 0!==ka&&void 0!==ka.inputmask?(f=ka.inputmask.maskset,g=ka.inputmask.opts,oa=ka.inputmask.isRTL):(na=e.value,g.numericInput&&(oa=!0),na=(a.isFunction(g.onBeforeMask)?g.onBeforeMask(na,g)||na:na).split(""),J(void 0,!1,!1,oa?na.reverse():na),a.isFunction(g.onBeforeWrite)&&g.onBeforeWrite(void 0,x(),0,g)),K(ka);case"mask":ka=e.el,f=ka.inputmask.maskset,g=ka.inputmask.opts,oa=ka.inputmask.isRTL,ia=x().join(""),ha(ka);break;case"format":return g.numericInput&&(oa=!0),na=(a.isFunction(g.onBeforeMask)?g.onBeforeMask(e.value,g)||e.value:e.value).split(""),J(void 0,!1,!1,oa?na.reverse():na),a.isFunction(g.onBeforeWrite)&&g.onBeforeWrite(void 0,x(),0,g),e.metadata?{value:oa?x().slice().reverse().join(""):x().join(""),metadata:h({action:"getmetadata"},f,g)}:oa?x().slice().reverse().join(""):x().join("");case"isValid":g.numericInput&&(oa=!0),e.value?(na=e.value.split(""),J(void 0,!1,!0,oa?na.reverse():na)):e.value=x().join("");for(var va=x(),wa=M(),xa=va.length-1;xa>wa&&!C(xa);xa--);return va.splice(wa,xa+1-wa),O(va)&&e.value===x().join("");case"getemptymask":return w();case"remove":ka=e.el,la=a(ka),f=ka.inputmask.maskset,g=ka.inputmask.opts,ka.inputmask._valueSet(K(ka)),ua.off(ka);var ya;Object.getOwnPropertyDescriptor&&(ya=Object.getOwnPropertyDescriptor(ka,"value")),ya&&ya.get?ka.inputmask.__valueGet&&Object.defineProperty(ka,"value",{get:ka.inputmask.__valueGet,set:ka.inputmask.__valueSet}):document.__lookupGetter__&&ka.__lookupGetter__("value")&&ka.inputmask.__valueGet&&(ka.__defineGetter__("value",ka.inputmask.__valueGet),ka.__defineSetter__("value",ka.inputmask.__valueSet)),ka.inputmask=void 0;break;case"getmetadata":if(a.isArray(f.metadata)){for(var za,Aa=o(),Ba=Aa;Ba>=0;Ba--)if(m().validPositions[Ba]&&void 0!==m().validPositions[Ba].alternation){za=m().validPositions[Ba].alternation;break}return void 0!==za?f.metadata[m().validPositions[Aa].locator[za]]:f.metadata[0]}return f.metadata}}b.prototype={defaults:{placeholder:"_",optionalmarker:{start:"[",end:"]"},quantifiermarker:{start:"{",end:"}"},groupmarker:{start:"(",end:")"},alternatormarker:"|",escapeChar:"\\",mask:null,oncomplete:a.noop,onincomplete:a.noop,oncleared:a.noop,repeat:0,greedy:!0,autoUnmask:!1,removeMaskOnSubmit:!1,clearMaskOnLostFocus:!0,insertMode:!0,clearIncomplete:!1,aliases:{},alias:null,onKeyDown:a.noop,onBeforeMask:null,onBeforePaste:function(b,c){return a.isFunction(c.onBeforeMask)?c.onBeforeMask(b,c):b},onBeforeWrite:null,onUnMask:null,showMaskOnFocus:!0,showMaskOnHover:!0,onKeyValidation:a.noop,skipOptionalPartCharacter:" ",showTooltip:!1,tooltip:void 0,numericInput:!1,rightAlign:!1,undoOnEscape:!0,radixPoint:"",groupSeparator:"",radixFocus:!1,nojumps:!1,nojumpsThreshold:0,keepStatic:null,positionCaretOnTab:!1,tabThrough:!1,supportsInputType:["text","tel","password"],definitions:{9:{validator:"[0-9]",cardinality:1,definitionSymbol:"*"},a:{validator:"[A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]",cardinality:1,definitionSymbol:"*"},"*":{validator:"[0-9A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]",cardinality:1}},ignorables:[8,9,13,19,27,33,34,35,36,37,38,39,40,45,46,93,112,113,114,115,116,117,118,119,120,121,122,123],isComplete:null,canClearPosition:a.noop,postValidation:null,staticDefinitionSymbol:void 0,jitMasking:!1},masksCache:{},mask:function(c){var d=this;return"string"==typeof c&&(c=document.getElementById(c)||document.querySelectorAll(c)),c=c.nodeName?[c]:c,a.each(c,function(c,e){var i=a.extend(!0,{},d.opts);f(e,i,a.extend(!0,{},d.userOptions));var j=g(i,d.noMasksCache);void 0!==j&&(void 0!==e.inputmask&&e.inputmask.remove(),e.inputmask=new b,e.inputmask.opts=i,e.inputmask.noMasksCache=d.noMasksCache,e.inputmask.userOptions=a.extend(!0,{},d.userOptions),e.inputmask.el=e,e.inputmask.maskset=j,e.inputmask.isRTL=!1,a.data(e,"_inputmask_opts",i),h({action:"mask",el:e}))}),c&&c[0]?c[0].inputmask||this:this},option:function(b){return"string"==typeof b?this.opts[b]:"object"==typeof b?(a.extend(this.opts,b),a.extend(this.userOptions,b),this.el&&(void 0!==b.mask||void 0!==b.alias?this.mask(this.el):(a.data(this.el,"_inputmask_opts",this.opts),h({action:"mask",el:this.el}))),this):void 0},unmaskedvalue:function(a){return h({action:"unmaskedvalue",el:this.el,value:a},this.el&&this.el.inputmask?this.el.inputmask.maskset:g(this.opts,this.noMasksCache),this.opts)},remove:function(){return this.el?(h({action:"remove",el:this.el}),this.el.inputmask=void 0,this.el):void 0},getemptymask:function(){return h({action:"getemptymask"},this.maskset||g(this.opts,this.noMasksCache),this.opts)},hasMaskedValue:function(){return!this.opts.autoUnmask},isComplete:function(){return h({action:"isComplete",el:this.el},this.maskset||g(this.opts,this.noMasksCache),this.opts)},getmetadata:function(){return h({action:"getmetadata"},this.maskset||g(this.opts,this.noMasksCache),this.opts)},isValid:function(a){return h({action:"isValid",value:a},this.maskset||g(this.opts,this.noMasksCache),this.opts)},format:function(a,b){return h({action:"format",value:a,metadata:b},this.maskset||g(this.opts,this.noMasksCache),this.opts)}},b.extendDefaults=function(c){a.extend(!0,b.prototype.defaults,c)},b.extendDefinitions=function(c){a.extend(!0,b.prototype.defaults.definitions,c)},b.extendAliases=function(c){a.extend(!0,b.prototype.defaults.aliases,c)},b.format=function(a,c,d){return b(c).format(a,d)},b.unmask=function(a,c){return b(c).unmaskedvalue(a)},b.isValid=function(a,c){return b(c).isValid(a)},b.remove=function(b){a.each(b,function(a,b){b.inputmask&&b.inputmask.remove()})},b.escapeRegex=function(a){var b=["/",".","*","+","?","|","(",")","[","]","{","}","\\","$","^"];return a.replace(new RegExp("(\\"+b.join("|\\")+")","gim"),"\\$1")},b.keyCode={ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91};var i=navigator.userAgent,j=/mobile/i.test(i),k=/iemobile/i.test(i),l=/iphone/i.test(i)&&!k;/android.*safari.*/i.test(i)&&!k;return window.Inputmask=b,b});
tonytomov/cdnjs
ajax/libs/jquery.inputmask/3.2.7/min/inputmask/inputmask.min.js
JavaScript
mit
42,873
/*! * https://github.com/es-shims/es5-shim * @license es5-shim Copyright 2009-2015 by contributors, MIT License * see https://github.com/es-shims/es5-shim/blob/master/LICENSE */ // vim: ts=4 sts=4 sw=4 expandtab // Add semicolon to prevent IIFE from being passed as argument to concatenated code. ; // UMD (Universal Module Definition) // see https://github.com/umdjs/umd/blob/master/templates/returnExports.js (function (root, factory) { 'use strict'; /* global define, exports, module */ if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(factory); } else if (typeof exports === 'object') { // Node. Does not work with strict CommonJS, but // only CommonJS-like enviroments that support module.exports, // like Node. module.exports = factory(); } else { // Browser globals (root is window) root.returnExports = factory(); } }(this, function () { var call = Function.call; var prototypeOfObject = Object.prototype; var owns = call.bind(prototypeOfObject.hasOwnProperty); var isEnumerable = call.bind(prototypeOfObject.propertyIsEnumerable); var toStr = call.bind(prototypeOfObject.toString); // If JS engine supports accessors creating shortcuts. var defineGetter; var defineSetter; var lookupGetter; var lookupSetter; var supportsAccessors = owns(prototypeOfObject, '__defineGetter__'); if (supportsAccessors) { /* eslint-disable no-underscore-dangle */ defineGetter = call.bind(prototypeOfObject.__defineGetter__); defineSetter = call.bind(prototypeOfObject.__defineSetter__); lookupGetter = call.bind(prototypeOfObject.__lookupGetter__); lookupSetter = call.bind(prototypeOfObject.__lookupSetter__); /* eslint-enable no-underscore-dangle */ } // ES5 15.2.3.2 // http://es5.github.com/#x15.2.3.2 if (!Object.getPrototypeOf) { // https://github.com/es-shims/es5-shim/issues#issue/2 // http://ejohn.org/blog/objectgetprototypeof/ // recommended by fschaefer on github // // sure, and webreflection says ^_^ // ... this will nerever possibly return null // ... Opera Mini breaks here with infinite loops Object.getPrototypeOf = function getPrototypeOf(object) { /* eslint-disable no-proto */ var proto = object.__proto__; /* eslint-enable no-proto */ if (proto || proto === null) { return proto; } else if (toStr(object.constructor) === '[object Function]') { return object.constructor.prototype; } else if (object instanceof Object) { return prototypeOfObject; } else { // Correctly return null for Objects created with `Object.create(null)` // (shammed or native) or `{ __proto__: null}`. Also returns null for // cross-realm objects on browsers that lack `__proto__` support (like // IE <11), but that's the best we can do. return null; } }; } // ES5 15.2.3.3 // http://es5.github.com/#x15.2.3.3 var doesGetOwnPropertyDescriptorWork = function doesGetOwnPropertyDescriptorWork(object) { try { object.sentinel = 0; return Object.getOwnPropertyDescriptor(object, 'sentinel').value === 0; } catch (exception) { return false; } }; // check whether getOwnPropertyDescriptor works if it's given. Otherwise, shim partially. if (Object.defineProperty) { var getOwnPropertyDescriptorWorksOnObject = doesGetOwnPropertyDescriptorWork({}); var getOwnPropertyDescriptorWorksOnDom = typeof document === 'undefined' || doesGetOwnPropertyDescriptorWork(document.createElement('div')); if (!getOwnPropertyDescriptorWorksOnDom || !getOwnPropertyDescriptorWorksOnObject) { var getOwnPropertyDescriptorFallback = Object.getOwnPropertyDescriptor; } } if (!Object.getOwnPropertyDescriptor || getOwnPropertyDescriptorFallback) { var ERR_NON_OBJECT = 'Object.getOwnPropertyDescriptor called on a non-object: '; /* eslint-disable no-proto */ Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) { if ((typeof object !== 'object' && typeof object !== 'function') || object === null) { throw new TypeError(ERR_NON_OBJECT + object); } // make a valiant attempt to use the real getOwnPropertyDescriptor // for I8's DOM elements. if (getOwnPropertyDescriptorFallback) { try { return getOwnPropertyDescriptorFallback.call(Object, object, property); } catch (exception) { // try the shim if the real one doesn't work } } var descriptor; // If object does not owns property return undefined immediately. if (!owns(object, property)) { return descriptor; } // If object has a property then it's for sure `configurable`, and // probably `enumerable`. Detect enumerability though. descriptor = { enumerable: isEnumerable(object, property), configurable: true }; // If JS engine supports accessor properties then property may be a // getter or setter. if (supportsAccessors) { // Unfortunately `__lookupGetter__` will return a getter even // if object has own non getter property along with a same named // inherited getter. To avoid misbehavior we temporary remove // `__proto__` so that `__lookupGetter__` will return getter only // if it's owned by an object. var prototype = object.__proto__; var notPrototypeOfObject = object !== prototypeOfObject; // avoid recursion problem, breaking in Opera Mini when // Object.getOwnPropertyDescriptor(Object.prototype, 'toString') // or any other Object.prototype accessor if (notPrototypeOfObject) { object.__proto__ = prototypeOfObject; } var getter = lookupGetter(object, property); var setter = lookupSetter(object, property); if (notPrototypeOfObject) { // Once we have getter and setter we can put values back. object.__proto__ = prototype; } if (getter || setter) { if (getter) { descriptor.get = getter; } if (setter) { descriptor.set = setter; } // If it was accessor property we're done and return here // in order to avoid adding `value` to the descriptor. return descriptor; } } // If we got this far we know that object has an own property that is // not an accessor so we set it as a value and return descriptor. descriptor.value = object[property]; descriptor.writable = true; return descriptor; }; /* eslint-enable no-proto */ } // ES5 15.2.3.4 // http://es5.github.com/#x15.2.3.4 if (!Object.getOwnPropertyNames) { Object.getOwnPropertyNames = function getOwnPropertyNames(object) { return Object.keys(object); }; } // ES5 15.2.3.5 // http://es5.github.com/#x15.2.3.5 if (!Object.create) { // Contributed by Brandon Benvie, October, 2012 var createEmpty; var supportsProto = !({ __proto__: null } instanceof Object); // the following produces false positives // in Opera Mini => not a reliable check // Object.prototype.__proto__ === null // Check for document.domain and active x support // No need to use active x approach when document.domain is not set // see https://github.com/es-shims/es5-shim/issues/150 // variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346 /* global ActiveXObject */ var shouldUseActiveX = function shouldUseActiveX() { // return early if document.domain not set if (!document.domain) { return false; } try { return !!new ActiveXObject('htmlfile'); } catch (exception) { return false; } }; // This supports IE8 when document.domain is used // see https://github.com/es-shims/es5-shim/issues/150 // variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346 var getEmptyViaActiveX = function getEmptyViaActiveX() { var empty; var xDoc; xDoc = new ActiveXObject('htmlfile'); xDoc.write('<script><\/script>'); xDoc.close(); empty = xDoc.parentWindow.Object.prototype; xDoc = null; return empty; }; // The original implementation using an iframe // before the activex approach was added // see https://github.com/es-shims/es5-shim/issues/150 var getEmptyViaIFrame = function getEmptyViaIFrame() { var iframe = document.createElement('iframe'); var parent = document.body || document.documentElement; var empty; iframe.style.display = 'none'; parent.appendChild(iframe); /* eslint-disable no-script-url */ iframe.src = 'javascript:'; /* eslint-enable no-script-url */ empty = iframe.contentWindow.Object.prototype; parent.removeChild(iframe); iframe = null; return empty; }; /* global document */ if (supportsProto || typeof document === 'undefined') { createEmpty = function () { return { __proto__: null }; }; } else { // In old IE __proto__ can't be used to manually set `null`, nor does // any other method exist to make an object that inherits from nothing, // aside from Object.prototype itself. Instead, create a new global // object and *steal* its Object.prototype and strip it bare. This is // used as the prototype to create nullary objects. createEmpty = function () { // Determine which approach to use // see https://github.com/es-shims/es5-shim/issues/150 var empty = shouldUseActiveX() ? getEmptyViaActiveX() : getEmptyViaIFrame(); delete empty.constructor; delete empty.hasOwnProperty; delete empty.propertyIsEnumerable; delete empty.isPrototypeOf; delete empty.toLocaleString; delete empty.toString; delete empty.valueOf; var Empty = function Empty() {}; Empty.prototype = empty; // short-circuit future calls createEmpty = function () { return new Empty(); }; return new Empty(); }; } Object.create = function create(prototype, properties) { var object; var Type = function Type() {}; // An empty constructor. if (prototype === null) { object = createEmpty(); } else { if (typeof prototype !== 'object' && typeof prototype !== 'function') { // In the native implementation `parent` can be `null` // OR *any* `instanceof Object` (Object|Function|Array|RegExp|etc) // Use `typeof` tho, b/c in old IE, DOM elements are not `instanceof Object` // like they are in modern browsers. Using `Object.create` on DOM elements // is...err...probably inappropriate, but the native version allows for it. throw new TypeError('Object prototype may only be an Object or null'); // same msg as Chrome } Type.prototype = prototype; object = new Type(); // IE has no built-in implementation of `Object.getPrototypeOf` // neither `__proto__`, but this manually setting `__proto__` will // guarantee that `Object.getPrototypeOf` will work as expected with // objects created using `Object.create` /* eslint-disable no-proto */ object.__proto__ = prototype; /* eslint-enable no-proto */ } if (properties !== void 0) { Object.defineProperties(object, properties); } return object; }; } // ES5 15.2.3.6 // http://es5.github.com/#x15.2.3.6 // Patch for WebKit and IE8 standard mode // Designed by hax <hax.github.com> // related issue: https://github.com/es-shims/es5-shim/issues#issue/5 // IE8 Reference: // http://msdn.microsoft.com/en-us/library/dd282900.aspx // http://msdn.microsoft.com/en-us/library/dd229916.aspx // WebKit Bugs: // https://bugs.webkit.org/show_bug.cgi?id=36423 var doesDefinePropertyWork = function doesDefinePropertyWork(object) { try { Object.defineProperty(object, 'sentinel', {}); return 'sentinel' in object; } catch (exception) { return false; } }; // check whether defineProperty works if it's given. Otherwise, // shim partially. if (Object.defineProperty) { var definePropertyWorksOnObject = doesDefinePropertyWork({}); var definePropertyWorksOnDom = typeof document === 'undefined' || doesDefinePropertyWork(document.createElement('div')); if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) { var definePropertyFallback = Object.defineProperty, definePropertiesFallback = Object.defineProperties; } } if (!Object.defineProperty || definePropertyFallback) { var ERR_NON_OBJECT_DESCRIPTOR = 'Property description must be an object: '; var ERR_NON_OBJECT_TARGET = 'Object.defineProperty called on non-object: '; var ERR_ACCESSORS_NOT_SUPPORTED = 'getters & setters can not be defined on this javascript engine'; Object.defineProperty = function defineProperty(object, property, descriptor) { if ((typeof object !== 'object' && typeof object !== 'function') || object === null) { throw new TypeError(ERR_NON_OBJECT_TARGET + object); } if ((typeof descriptor !== 'object' && typeof descriptor !== 'function') || descriptor === null) { throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor); } // make a valiant attempt to use the real defineProperty // for I8's DOM elements. if (definePropertyFallback) { try { return definePropertyFallback.call(Object, object, property, descriptor); } catch (exception) { // try the shim if the real one doesn't work } } // If it's a data property. if ('value' in descriptor) { // fail silently if 'writable', 'enumerable', or 'configurable' // are requested but not supported /* // alternate approach: if ( // can't implement these features; allow false but not true ('writable' in descriptor && !descriptor.writable) || ('enumerable' in descriptor && !descriptor.enumerable) || ('configurable' in descriptor && !descriptor.configurable) )) throw new RangeError( 'This implementation of Object.defineProperty does not support configurable, enumerable, or writable.' ); */ if (supportsAccessors && (lookupGetter(object, property) || lookupSetter(object, property))) { // As accessors are supported only on engines implementing // `__proto__` we can safely override `__proto__` while defining // a property to make sure that we don't hit an inherited // accessor. /* eslint-disable no-proto */ var prototype = object.__proto__; object.__proto__ = prototypeOfObject; // Deleting a property anyway since getter / setter may be // defined on object itself. delete object[property]; object[property] = descriptor.value; // Setting original `__proto__` back now. object.__proto__ = prototype; /* eslint-enable no-proto */ } else { object[property] = descriptor.value; } } else { if (!supportsAccessors && (('get' in descriptor) || ('set' in descriptor))) { throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED); } // If we got that far then getters and setters can be defined !! if ('get' in descriptor) { defineGetter(object, property, descriptor.get); } if ('set' in descriptor) { defineSetter(object, property, descriptor.set); } } return object; }; } // ES5 15.2.3.7 // http://es5.github.com/#x15.2.3.7 if (!Object.defineProperties || definePropertiesFallback) { Object.defineProperties = function defineProperties(object, properties) { // make a valiant attempt to use the real defineProperties if (definePropertiesFallback) { try { return definePropertiesFallback.call(Object, object, properties); } catch (exception) { // try the shim if the real one doesn't work } } Object.keys(properties).forEach(function (property) { if (property !== '__proto__') { Object.defineProperty(object, property, properties[property]); } }); return object; }; } // ES5 15.2.3.8 // http://es5.github.com/#x15.2.3.8 if (!Object.seal) { Object.seal = function seal(object) { if (Object(object) !== object) { throw new TypeError('Object.seal can only be called on Objects.'); } // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // ES5 15.2.3.9 // http://es5.github.com/#x15.2.3.9 if (!Object.freeze) { Object.freeze = function freeze(object) { if (Object(object) !== object) { throw new TypeError('Object.freeze can only be called on Objects.'); } // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // detect a Rhino bug and patch it try { Object.freeze(function () {}); } catch (exception) { Object.freeze = (function (freezeObject) { return function freeze(object) { if (typeof object === 'function') { return object; } else { return freezeObject(object); } }; }(Object.freeze)); } // ES5 15.2.3.10 // http://es5.github.com/#x15.2.3.10 if (!Object.preventExtensions) { Object.preventExtensions = function preventExtensions(object) { if (Object(object) !== object) { throw new TypeError('Object.preventExtensions can only be called on Objects.'); } // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // ES5 15.2.3.11 // http://es5.github.com/#x15.2.3.11 if (!Object.isSealed) { Object.isSealed = function isSealed(object) { if (Object(object) !== object) { throw new TypeError('Object.isSealed can only be called on Objects.'); } return false; }; } // ES5 15.2.3.12 // http://es5.github.com/#x15.2.3.12 if (!Object.isFrozen) { Object.isFrozen = function isFrozen(object) { if (Object(object) !== object) { throw new TypeError('Object.isFrozen can only be called on Objects.'); } return false; }; } // ES5 15.2.3.13 // http://es5.github.com/#x15.2.3.13 if (!Object.isExtensible) { Object.isExtensible = function isExtensible(object) { // 1. If Type(O) is not Object throw a TypeError exception. if (Object(object) !== object) { throw new TypeError('Object.isExtensible can only be called on Objects.'); } // 2. Return the Boolean value of the [[Extensible]] internal property of O. var name = ''; while (owns(object, name)) { name += '?'; } object[name] = true; var returnValue = owns(object, name); delete object[name]; return returnValue; }; } }));
jdh8/cdnjs
ajax/libs/es5-shim/4.5.0/es5-sham.js
JavaScript
mit
20,673
/*! backbone.paginator - v0.6.0 - 3/15/2013 * http://github.com/addyosmani/backbone.paginator * Copyright (c) 2013 Addy Osmani; Licensed MIT */ Backbone.Paginator=function(e,t,n){"use strict";var r={};return r.version="0.6.0",r.clientPager=e.Collection.extend({useDiacriticsPlugin:!0,useLevenshteinPlugin:!0,sortColumn:"",sortDirection:"desc",lastSortColumn:"",fieldFilterRules:[],lastFieldFilterRules:[],filterFields:"",filterExpression:"",lastFilterExpression:"",defaults_ui:{firstPage:0,currentPage:1,perPage:5,totalPages:10,pagesInRange:4},initialize:function(){this.on("add",this.addModel,this),this.on("remove",this.removeModel,this),this.setDefaults()},setDefaults:function(){var e=t.defaults(this.paginator_ui,this.defaults_ui);t.defaults(this,e)},addModel:function(e){this.origModels.push(e)},removeModel:function(e){var n=t.indexOf(this.origModels,e);this.origModels.splice(n,1)},sync:function(r,i,s){var o=this;this.setDefaults();var u={};t.each(t.result(o,"server_api"),function(e,n){t.isFunction(e)&&(e=t.bind(e,o),e=e()),u[n]=e});var a=t.clone(o.paginator_core);t.each(a,function(e,n){t.isFunction(e)&&(e=t.bind(e,o),e=e()),a[n]=e}),a=t.defaults(a,{timeout:25e3,cache:!1,type:"GET",dataType:"jsonp"}),a=t.extend(a,{data:decodeURIComponent(n.param(u)),processData:!1,url:t.result(a,"url")},s);var f=e.VERSION.split("."),l=parseInt(f[0],10)===0&&parseInt(f[1],10)===9&&parseInt(f[2],10)<=9,c=a.success;a.success=function(e,t,n){c&&(l?c(e,t,n):c(i,e,a)),i&&i.trigger&&i.trigger("sync",i,e,a)};var h=a.error;a.error=function(e){h&&h(i,e,a),i&&i.trigger&&i.trigger("error",i,e,a)};var p=a.xhr=n.ajax(a);return i&&i.trigger&&i.trigger("request",i,p,a),p},nextPage:function(e){this.currentPage<this.information.totalPages&&(this.currentPage=++this.currentPage,this.pager(e))},previousPage:function(e){this.currentPage>1&&(this.currentPage=--this.currentPage,this.pager(e))},goTo:function(e,t){e!==undefined&&(this.currentPage=parseInt(e,10),this.pager(t))},howManyPer:function(e){if(e!==undefined){var t=this.perPage;this.perPage=parseInt(e,10),this.currentPage=Math.ceil((t*(this.currentPage-1)+1)/e),this.pager()}},setSort:function(e,t){e!==undefined&&t!==undefined&&(this.lastSortColumn=this.sortColumn,this.sortColumn=e,this.sortDirection=t,this.pager(),this.info())},setFieldFilter:function(e){t.isEmpty(e)?(this.lastFieldFilterRules=this.fieldFilterRules,this.fieldFilterRules="",this.pager(),this.info()):(this.lastFieldFilterRules=this.fieldFilterRules,this.fieldFilterRules=e,this.pager(),this.info())},doFakeFieldFilter:function(e){if(!t.isEmpty(e)){var n=this.origModels;return n===undefined&&(n=this.models),n=this._fieldFilter(n,e),this.filterExpression!==""&&(n=this._filter(n,this.filterFields,this.filterExpression)),n.length}},setFilter:function(e,t){e!==undefined&&t!==undefined&&(this.filterFields=e,this.lastFilterExpression=this.filterExpression,this.filterExpression=t,this.pager(),this.info())},doFakeFilter:function(e,n){if(e!==undefined&&n!==undefined){var r=this.origModels;return r===undefined&&(r=this.models),t.isEmpty(this.fieldFilterRules)||(r=this._fieldFilter(r,this.fieldFilterRules)),r=this._filter(r,e,n),r.length}},pager:function(e){var n=this,r=this.perPage,i=(n.currentPage-1)*r,s=i+r;n.origModels===undefined&&(n.origModels=n.models),n.models=n.origModels.slice(),this.sortColumn!==""&&(n.models=n._sort(n.models,this.sortColumn,this.sortDirection)),t.isEmpty(this.fieldFilterRules)||(n.models=n._fieldFilter(n.models,this.fieldFilterRules)),this.filterExpression!==""&&(n.models=n._filter(n.models,this.filterFields,this.filterExpression));if(this.lastSortColumn!==this.sortColumn||this.lastFilterExpression!==this.filterExpression||!t.isEqual(this.fieldFilterRules,this.lastFieldFilterRules))i=0,s=i+r,n.currentPage=1,this.lastSortColumn=this.sortColumn,this.lastFieldFilterRules=this.fieldFilterRules,this.lastFilterExpression=this.filterExpression;n.sortedAndFilteredModels=n.models.slice(),n.info(),n.reset(n.models.slice(i,s)),t.result(e,"success")},_sort:function(e,n,r){return e=e.sort(function(e,i){var s=e.get(n),o=i.get(n);if(t.isUndefined(s)||t.isUndefined(o)||s===null||o===null)return 0;s=s.toString().toLowerCase(),o=o.toString().toLowerCase();if(r==="desc")if(!s.match(/[^\-\d\.]/)&&s.match(/-?[\d\.]+/)&&!o.match(/[^\-\d\.]/)&&o.match(/-?[\d\.]+/)){if(s-0<o-0)return 1;if(s-0>o-0)return-1}else{if(s<o)return 1;if(s>o)return-1}else if(!s.match(/[^\-\d\.]/)&&s.match(/-?[\d\.]+/)&&!o.match(/[^\-\d\.]/)&&o.match(/-?[\d\.]+/)){if(s-0<o-0)return-1;if(s-0>o-0)return 1}else{if(s<o)return-1;if(s>o)return 1}if(e.cid&&i.cid){var u=e.cid,a=i.cid;if(u<a)return-1;if(u>a)return 1}return 0}),e},_fieldFilter:function(e,n){if(t.isEmpty(n))return e;var r=[];return t.each(e,function(e){var i=!0;t.each(n,function(n){if(!i)return!1;i=!1;if(n.type==="function"){var r=t.wrap(n.value,function(t){return t(e.get(n.field))});r()&&(i=!0)}else n.type==="required"?t.isEmpty(e.get(n.field).toString())||(i=!0):n.type==="min"?!t.isNaN(Number(e.get(n.field)))&&!t.isNaN(Number(n.value))&&Number(e.get(n.field))>=Number(n.value)&&(i=!0):n.type==="max"?!t.isNaN(Number(e.get(n.field)))&&!t.isNaN(Number(n.value))&&Number(e.get(n.field))<=Number(n.value)&&(i=!0):n.type==="range"?!t.isNaN(Number(e.get(n.field)))&&t.isObject(n.value)&&!t.isNaN(Number(n.value.min))&&!t.isNaN(Number(n.value.max))&&Number(e.get(n.field))>=Number(n.value.min)&&Number(e.get(n.field))<=Number(n.value.max)&&(i=!0):n.type==="minLength"?e.get(n.field).toString().length>=n.value&&(i=!0):n.type==="maxLength"?e.get(n.field).toString().length<=n.value&&(i=!0):n.type==="rangeLength"?t.isObject(n.value)&&!t.isNaN(Number(n.value.min))&&!t.isNaN(Number(n.value.max))&&e.get(n.field).toString().length>=n.value.min&&e.get(n.field).toString().length<=n.value.max&&(i=!0):n.type==="oneOf"?t.isArray(n.value)&&t.include(n.value,e.get(n.field))&&(i=!0):n.type==="equalTo"?n.value===e.get(n.field)&&(i=!0):n.type==="containsAllOf"?t.isArray(n.value)&&t.isArray(e.get(n.field))&&t.intersection(n.value,e.get(n.field)).length===n.value.length&&(i=!0):n.type==="pattern"?e.get(n.field).toString().match(n.value)&&(i=!0):i=!1}),i&&r.push(e)}),r},_filter:function(n,r,i){var s=this,o={};t.isString(r)?o[r]={cmp_method:"regexp"}:t.isArray(r)?t.each(r,function(e){o[e]={cmp_method:"regexp"}}):t.each(r,function(e,n){o[n]=t.defaults(e,{cmp_method:"regexp"})}),r=o,t.has(e.Paginator,"removeDiacritics")&&s.useDiacriticsPlugin&&(i=e.Paginator.removeDiacritics(i));if(i===""||!t.isString(i))return n;var u=t.map(i.match(/\w+/ig),function(e){return e.toLowerCase()}),a="("+t.uniq(u).join("|")+")",f=new RegExp(a,"igm"),l=[];return t.each(n,function(n){var o=[];t.each(r,function(r,a){var l=n.get(a);if(l){var c=[];t.has(e.Paginator,"removeDiacritics")&&s.useDiacriticsPlugin?l=e.Paginator.removeDiacritics(l.toString()):l=l.toString();if(r.cmp_method==="levenshtein"&&t.has(e.Paginator,"levenshtein")&&s.useLevenshteinPlugin){var h=e.Paginator.levenshtein(l,i);t.defaults(r,{max_distance:0}),h<=r.max_distance&&(c=t.uniq(u))}else c=l.match(f);c=t.map(c,function(e){return e.toString().toLowerCase()}),t.each(c,function(e){o.push(e)})}}),o=t.uniq(t.without(o,"")),t.isEmpty(t.difference(u,o))&&l.push(n)}),l},info:function(){var e=this,t={},n=e.sortedAndFilteredModels?e.sortedAndFilteredModels.length:e.length,r=Math.ceil(n/e.perPage);return t={totalUnfilteredRecords:e.origModels.length,totalRecords:n,currentPage:e.currentPage,perPage:this.perPage,totalPages:r,lastPage:r,previous:!1,next:!1,startRecord:n===0?0:(e.currentPage-1)*this.perPage+1,endRecord:Math.min(n,e.currentPage*this.perPage)},e.currentPage>1&&(t.previous=e.currentPage-1),e.currentPage<t.totalPages&&(t.next=e.currentPage+1),t.pageSet=e.setPagination(t),e.information=t,t},setPagination:function(e){var t=[],n=0,r=0,i=this.pagesInRange*2,s=Math.ceil(e.totalRecords/e.perPage);if(s>1)if(s<=1+i)for(n=1,r=s;n<=r;n++)t.push(n);else if(e.currentPage<=this.pagesInRange+1)for(n=1,r=2+i;n<r;n++)t.push(n);else if(s-this.pagesInRange>e.currentPage&&e.currentPage>this.pagesInRange)for(n=e.currentPage-this.pagesInRange;n<=e.currentPage+this.pagesInRange;n++)t.push(n);else for(n=s-i;n<=s;n++)t.push(n);return t},bootstrap:function(e){return t.extend(this,e),this.goTo(1),this.info(),this}}),r.clientPager.prototype.prevPage=r.clientPager.prototype.previousPage,r.requestPager=e.Collection.extend({sync:function(r,i,s){var o=this;o.setDefaults();var u={};t.each(t.result(o,"server_api"),function(e,n){t.isFunction(e)&&(e=t.bind(e,o),e=e()),u[n]=e});var a=t.clone(o.paginator_core);t.each(a,function(e,n){t.isFunction(e)&&(e=t.bind(e,o),e=e()),a[n]=e}),a=t.defaults(a,{timeout:25e3,cache:!1,type:"GET",dataType:"jsonp"}),s.data?s.data=decodeURIComponent(n.param(t.extend(u,s.data))):s.data=decodeURIComponent(n.param(u)),a=t.extend(a,{data:decodeURIComponent(n.param(u)),processData:!1,url:t.result(a,"url")},s);var f=e.VERSION.split("."),l=parseInt(f[0],10)===0&&parseInt(f[1],10)===9&&parseInt(f[2],10)<=9,c=a.success;a.success=function(e,t,n){c&&(l?c(e,t,n):c(i,e,a)),i&&i.trigger&&i.trigger("sync",i,e,a)};var h=a.error;a.error=function(e){h&&h(i,e,a),i&&i.trigger&&i.trigger("error",i,e,a)};var p=a.xhr=n.ajax(a);return i&&i.trigger&&i.trigger("request",i,p,a),p},setDefaults:function(){var e=this;t.defaults(e.paginator_ui,{firstPage:0,currentPage:1,perPage:5,totalPages:10,pagesInRange:4}),t.each(e.paginator_ui,function(n,r){t.isUndefined(e[r])&&(e[r]=e.paginator_ui[r])})},requestNextPage:function(e){if(this.currentPage!==undefined)return this.currentPage+=1,this.pager(e);var t=new n.Deferred;return t.reject(),t.promise()},requestPreviousPage:function(e){if(this.currentPage!==undefined)return this.currentPage-=1,this.pager(e);var t=new n.Deferred;return t.reject(),t.promise()},updateOrder:function(e){e!==undefined&&(this.sortField=e,this.pager())},goTo:function(e,t){if(e!==undefined)return this.currentPage=parseInt(e,10),this.pager(t);var r=new n.Deferred;return r.reject(),r.promise()},howManyPer:function(e){e!==undefined&&(this.currentPage=this.firstPage,this.perPage=e,this.pager())},info:function(){var e={totalRecords:this.totalRecords||0,currentPage:this.currentPage,firstPage:this.firstPage,totalPages:Math.ceil(this.totalRecords/this.perPage),lastPage:this.totalPages,perPage:this.perPage,previous:!1,next:!1};return this.currentPage>1&&(e.previous=this.currentPage-1),this.currentPage<e.totalPages&&(e.next=this.currentPage+1),e.hasNext=e.next,e.hasPrevious=e.next,e.pageSet=this.setPagination(e),this.information=e,e},setPagination:function(e){var t=[],n=0,r=0,i=this.pagesInRange*2,s=Math.ceil(e.totalRecords/e.perPage);if(s>1)if(s<=1+i)for(n=1,r=s;n<=r;n++)t.push(n);else if(e.currentPage<=this.pagesInRange+1)for(n=1,r=2+i;n<r;n++)t.push(n);else if(s-this.pagesInRange>e.currentPage&&e.currentPage>this.pagesInRange)for(n=e.currentPage-this.pagesInRange;n<=e.currentPage+this.pagesInRange;n++)t.push(n);else for(n=s-i;n<=s;n++)t.push(n);return t},pager:function(e){return t.isObject(e)||(e={}),this.fetch(e)},url:function(){return this.paginator_core!==undefined&&this.paginator_core.url!==undefined?this.paginator_core.url:null},bootstrap:function(e){return t.extend(this,e),this.setDefaults(),this.info(),this}}),r.requestPager.prototype.nextPage=r.requestPager.prototype.requestNextPage,r.requestPager.prototype.prevPage=r.requestPager.prototype.requestPreviousPage,r}(Backbone,_,jQuery);
ZDroid/cdnjs
ajax/libs/backbone.paginator/0.6/backbone.paginator.min.js
JavaScript
mit
11,379
(function(t){"object"==typeof exports?module.exports=t():"function"==typeof define?define(t):breeze=t()})(function(){function t(t,e){for(var n in t)K.call(t,n)&&e(n,t[n])}function e(t,e){for(var n in t)if(K.call(t,n)){var r=t[n];if(e(n,r))return{key:n,value:r}}return null}function n(t,e){var n=[];for(var r in t)if(K.call(t,r)){var i=e(r,t[r]);i&&n.push(i)}return n}function r(t,e){return function(n){return n[t]===e}}function i(t){return function(e){return e[t]}}function a(t){var e=[];for(var n in t)K.call(t,n)&&e.push(t[n]);return e}function o(t,e){if(!e)return t;for(var n in e)K.call(e,n)&&(t[n]=e[n]);return t}function s(t,e){var n={};for(var r in t)if(K.call(t,r)&&"_"!=r.substr(0,1)){var i=t[r];if(S(i))continue;"object"==typeof i?i&&i.parentEnum&&(n[r]=i.name):n[r]=i}return e&&e.forEach(function(e){n[e]=t[e]}),n}function u(t,e){for(var n=0,r=t.length;r>n;n++)if(e(t[n]))return t[n];return null}function p(t,e){for(var n=0,r=t.length;r>n;n++)if(e(t[n]))return n;return-1}function c(t,e){for(var n=S(e)?e:void 0,r=t.length,i=0;r>i;i++)if(n?n(t[i]):t[i]===e)return t.splice(i,1),i;return-1}function y(t,e,n){for(var r=[],i=Math.min(t.length,e.length),a=0;i>a;++a)r.push(n(t[a],e[a]));return r}function l(t,e,n){if(!t||!e)return!1;if(t.length!=e.length)return!1;for(var r=0;t.length>r;r++)if(Array.isArray(t[r])){if(!l(t[r],e[r]))return!1}else if(n){if(!n(t[r],e[r]))return!1}else if(t[r]!=e[r])return!1;return!0}function f(t,e){for(var n=t.split(";"),r=0,i=n.length;i>r;r++){var a=h(n[r]);if(a)return a}throw Error("Unable to initialize "+t+". "+e||"")}function h(t){var e=window[t];return e?e:(window.require&&(e=window.require(t)),e?e:null)}function d(t,e,n,r){var i=t[e];if(n===i)return r();t[e]=n;try{return r()}finally{t[e]=i}}function m(t,e,n){var r;try{return r=t(),n()}catch(i){throw"object"==typeof r&&(r.error=i),i}finally{e(r)}}function g(t){return function(){for(var e=Array.prototype.slice.call(arguments),n="",r=e.length,i=null;r--;)i=e[r],n+=i===Object(i)?JSON.stringify(i):i,t.memoize||(t.memoize={});return n in t.memoize?t.memoize[n]:t.memoize[n]=t.apply(this,e)}}function v(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var e=0|16*Math.random(),n="x"==t?e:8|3&e;return n.toString(16)})}function P(t){if("string"!=typeof t)throw Error("Invalid ISO8601 duration '"+t+"'");var e=/^P((\d+Y)?(\d+M)?(\d+D)?)?(T(\d+H)?(\d+M)?(\d+S)?)?$/.exec(t);if(!e)throw Error("Invalid ISO8601 duration '"+t+"'");for(var n=[2,3,4,6,7,8],r=[31104e3,2592e3,86400,3600,60,1],i=0,a=0;6>a;a++){var o=e[n[a]];o=o?+o.replace(/[A-Za-z]+/g,""):0,i+=o*r[a]}return i}function E(t){return null===t?"null":void 0===t?"undefined":Object.prototype.toString.call(t).slice(8,-1).toLowerCase()}function T(t){return"date"===E(t)&&!isNaN(t.getTime())}function S(t){return"function"===E(t)}function _(t){return"string"==typeof t&&/[a-fA-F\d]{8}-(?:[a-fA-F\d]{4}-){3}[a-fA-F\d]{12}/.test(t)}function b(t){return"string"==typeof t&&/^(-|)?P([0-9]+Y|)?([0-9]+M|)?([0-9]+D|)?T?([0-9]+H|)?([0-9]+M|)?([0-9]+S|)?/.test(t)}function w(t){if(null===t||void 0===t)return!0;for(var e in t)if(K.call(t,e))return!1;return!0}function N(t){return!isNaN(parseFloat(t))&&isFinite(t)}function O(t,e){return t&&e?0===t.indexOf(e,0):!1}function C(t,e){return t&&e?-1!==t.indexOf(e,t.length-e.length):!1}function A(t){var e=arguments,n=RegExp("%([1-"+(arguments.length-1)+"])","g");return t.replace(n,function(t,n){return e[n]})}function x(t){switch(t){case W.String:return H.string;case W.Int64:return H.int64;case W.Int32:return H.int32;case W.Int16:return H.int16;case W.Decimal:return H.number;case W.Double:return H.number;case W.Single:return H.number;case W.DateTime:return H.date;case W.Boolean:return H.bool;case W.Guid:return H.guid;case W.Byte:return H.byte;case W.Binary:return H.none;case W.Time:return H.duration;case W.Undefined:return H.none}}function M(t,e,n){var r=n(),i=t.dataType;if(i&&i.parse&&(e=i.parse(e,typeof e)),e!==r){var a,o,s=this,u=t.name,p=this.entityAspect;p?(o=p,a=u):(o=this.complexAspect,p=o.entityAspect,a=o.parent?o.propertyPath+"."+u:u);var c=p._inProcess;if(c){if(c.indexOf(t)>=0)return;c.push(t)}else c=[t],p._inProcess=c;var y=p.entity;try{var l=p.entityManager;if(p.entityState.isUnchangedOrModified()&&void 0===o.originalValues[u]&&t.isDataProperty&&!t.isComplexProperty&&(o.originalValues[u]=void 0!==r?r:t.defaultValue),t.isNavigationProperty){if(!t.isScalar)throw Error("Nonscalar navigation properties are readonly - entities can be added or removed but the collection may not be changed.");var f,h=t.inverse;if(e){if(l){if(e.entityAspect.entityState.isDetached())l.isLoading||l.attachEntity(e,Y.Added);else if(e.entityAspect.entityManager!==l)throw Error("An Entity cannot be attached to an entity in another EntityManager. One of the two entities must be detached first.")}else if(e.entityAspect&&e.entityAspect.entityManager){l=e.entityAspect.entityManager;var d=l.isLoading?Y.Unchanged:Y.Added;l.attachEntity(p.entity,d)}if(h)if(h.isScalar)r&&r.setProperty(h.name,null),e.setProperty(h.name,this);else{if(r){f=r.getProperty(h.name);var m=f.indexOf(this);-1!==m&&f.splice(m,1)}var g=e.getProperty(h.name);g.push(this)}}else if(h)if(h.isScalar)r&&r.setProperty(h.name,null);else if(r){f=r.getProperty(h.name);var m=f.indexOf(this);-1!==m&&f.splice(m,1)}if(n(e),l&&!l.isLoading&&(p.entityState.isUnchanged()&&!t.isUnmapped&&p.setModified(),l.validationOptions.validateOnPropertyChange&&p._validateProperty(e,{entity:this,property:t,propertyName:a,oldValue:r})),t.relatedDataProperties&&!p.entityState.isDeleted()){var v=t.entityType.keyProperties;v.forEach(function(n,r){var i=e?e.getProperty(n.name):n.defaultValue;s.setProperty(t.relatedDataProperties[r].name,i)})}}else if(t.isComplexProperty){if(!e)throw Error(A("You cannot set the '%1' property to null because it's datatype is the ComplexType: '%2'",t.name,t.dataType.name));if(!r){var P=i.getCtor();r=new P,n(r)}i.dataProperties.forEach(function(t){var n=t.name,i=e.getProperty(n);r.setProperty(n,i)})}else{if(t.isPartOfKey&&l&&!l.isLoading){var E=this.entityType.keyProperties,T=E.map(function(n){return n==t?e:this.getProperty(n.name)},this),S=new ne(this.entityType,T);if(l.findEntityByKey(S))throw Error("An entity with this key is already in the cache: "+(""+S));var _=this.entityAspect.getKey(),b=l.findEntityGroup(this.entityType);b._replaceKey(_,S)}if(n(e),l&&!l.isLoading&&(p.entityState.isUnchanged()&&!t.isUnmapped&&p.setModified(),l.validationOptions.validateOnPropertyChange&&p._validateProperty(e,{entity:y,property:t,propertyName:a,oldValue:r})),t.relatedNavigationProperty&&l){var w=t.relatedNavigationProperty;if(e){var N=new ne(w.entityType,[e]),O=l.findEntityByKey(N);O?this.setProperty(w.name,O):l._unattachedChildrenMap.addChild(N,w,this)}else this.setProperty(w.name,null)}t.isPartOfKey&&(r&&!p.entityState.isDetached()&&(p.primaryKeyWasChanged=!0),this.entityType.navigationProperties.forEach(function(n){var r=n.inverse;if(r&&0!==r.foreignKeyNames.length){var i=s.getProperty(n.name),a=s.entityType.keyProperties.indexOf(t),o=r.foreignKeyNames[a];if(n.isScalar){if(!i)return;i.setProperty(o,e)}else i.forEach(function(t){t.setProperty(o,e)})}}),p.getKey(!0))}var C={entity:y,property:t,propertyName:a,oldValue:r,newValue:e};l?l.isLoading||l.isRejectingChanges||(p.propertyChanged.publish(C),l.entityChanged.publish({entityAction:Z.PropertyChange,entity:y,args:C})):p.propertyChanged.publish(C)}finally{c.pop()}}}function k(t){return t.indexOf(":#")>=0}function I(t,e){return t+":#"+e}function D(t,e){if(!t)return null;if(O(t,oe.ANONTYPE_PREFIX))return{shortTypeName:t,namespace:"",typeName:t,isAnon:!0};var n=t.split(",")[0],r=n.split(".");if(r.length>1){var i,a=r[r.length-1];if(e)i=j(a,e);else{var o=r.slice(0,r.length-1);i=o.join(".")}return{shortTypeName:a,namespace:i,typeName:I(a,i)}}return{shortTypeName:t,namespace:"",typeName:t}}function j(t,e){var n,r=e.cSpaceOSpaceMapping;if(r){var i=r[e.namespace+"."+t];n=i&&i.substr(0,i.length-(t.length+1))}return n||e.namespace}function F(t,e){var n;if(n=Array.isArray(e)?e:e.split("."),1===n.length)return t.getProperty(e);for(var r=t,i=0;n.length>i&&(r=r.getProperty(n[i]),null!=r);i++);return r}function R(t){return t===W.DateTime?function(t){return t&&t.getTime()}:t===W.Time?function(t){return t&&P(t)}:function(t){return t}}var V={version:"1.2.5"};V.entityModel=V,V.entityTracking_backingStore="backingStore",V.entityTracking_ko="ko",V.entityTracking_backbone="backbone",V.remoteAccess_odata="odata",V.remoteAccess_webApi="webApi";var K=Object.prototype.hasOwnProperty;Object.create||(Object.create=function(t){var e=function(){};return e.prototype=t,new e});var L={};L.getOwnPropertyValues=a,L.objectForEach=t,L.objectMapToArray=n,L.objectFirst=e,L.extend=o,L.propEq=r,L.pluck=i,L.arrayEquals=l,L.arrayFirst=u,L.arrayIndexOf=p,L.arrayRemoveItem=c,L.arrayZip=y,L.requireLib=f,L.using=d,L.wrapExecution=m,L.memoize=g,L.getUuid=v,L.durationToSeconds=P,L.isDate=T,L.isGuid=_,L.isDuration=b,L.isFunction=S,L.isEmpty=w,L.isNumeric=N,L.stringStartsWith=O,L.stringEndsWith=C,L.formatString=A,L.parent=V,V.core=L;var q=function(){function t(t,e){return null==e?!1:"string"==typeof e&&e.length>0}function e(t,e){return null==e?!1:typeof e===t.typeName?!0:!1}function n(t,e){return null==e?!1:e instanceof t.type}function r(t,e){return null==e?!1:void 0!==e[t.propertyName]}function i(t,e){return null==e?!1:t.enumType.contains(e)}function a(t,e){return t.allowNull?void 0!==e:null!=e}function s(t,e){if(null==e)return!0;var n=t.prevContext;return n?n.fn(n,e):!0}function u(t,e){var n=t.prevContext,r=n?" or it "+y(n,e):"";return"is optional"+r}function p(t,e){if(!Array.isArray(e))return!1;if(t.mustNotBeEmpty&&0===e.length)return!1;var n=t.prevContext;return n?e.every(function(t){return n.fn(n,t)}):!0}function c(t,e){var n=t.mustNotBeEmpty?"a nonEmpty array":"an array",r=t.prevContext,i=r?" where each element "+y(r,e):"";return" must be "+n+i}function y(t,e){var n=t.msg;return"function"==typeof n&&(n=n(t,e)),n}function l(t,e){if(t._context){for(var n=t._context;null!=n.prevContext;)n=n.prevContext;if(null===n.prevContext)return n.prevContext=e,t;if(null!==e.prevContext)throw Error("Illegal construction - use 'or' to combine checks");e.prevContext=t._context}return f(t,e)}function f(t,e){return t._contexts[t._contexts.length-1]=e,t._context=e,t}function h(t){var e=t._contexts;return null==e[e.length-1]&&e.pop(),0===e.length?void 0:e.some(function(e){return e.fn(e,t.v)})}var d=function(t,e){this.v=t,this.name=e,this._contexts=[null]},m=d.prototype;return m.isObject=function(){return this.isTypeOf("object")},m.isBoolean=function(){return this.isTypeOf("boolean")},m.isString=function(){return this.isTypeOf("string")},m.isNonEmptyString=function(){return l(this,{fn:t,msg:"must be a nonEmpty string"})},m.isNumber=function(){return this.isTypeOf("number")},m.isFunction=function(){return this.isTypeOf("function")},m.isTypeOf=function(t){return l(this,{fn:e,typeName:t,msg:A("must be a '%1'",t)})},m.isInstanceOf=function(t,e){return l(this,{fn:n,type:t,typeName:e||t.prototype._$typeName,msg:A("must be an instance of '%1'",e)})},m.hasProperty=function(t){return l(this,{fn:r,propertyName:t,msg:A("must have a '%1' property ",t)})},m.isEnumOf=function(t){return l(this,{fn:i,enumType:t,msg:A("must be an instance of the '%1' enumeration",t.name)})},m.isRequired=function(t){return l(this,{fn:a,allowNull:t,msg:"is required"})},m.isOptional=function(){var t={fn:s,prevContext:null,msg:u};return l(this,t)},m.isNonEmptyArray=function(){return this.isArray(!0)},m.isArray=function(t){var e={fn:p,mustNotBeEmpty:t,prevContext:null,msg:c};return l(this,e)},m.or=function(){return this._contexts.push(null),this._context=null,this},m.check=function(t){var e=h(this);if(void 0!==e){if(!e)throw Error(this.getMessage());return void 0!==this.v?this.v:t}},m._addContext=function(t){return l(this,t)},m.getMessage=function(){var t=this,e=this._contexts.map(function(e){return y(e,t.v)}).join(", or it ");return A(this.MESSAGE_PREFIX,this.name)+" "+e},m.withDefault=function(t){return this.defaultValue=t,this},m.whereParam=function(t){return this.parent.whereParam(t)},m.applyAll=function(t,e){e=null==e?!0:e;var n=o({},this.parent.config);if(this.parent.params.forEach(function(r){e&&delete n[r.name],r._applyOne(t)}),e)for(var r in n)if(void 0!==n[r])throw Error("Invalid property in config: "+r)},m._applyOne=function(t){this.check(),void 0!==this.v?t[this.name]=this.v:void 0!==this.defaultValue&&(t[this.name]=this.defaultValue)},m.MESSAGE_PREFIX="The '%1' parameter ",d}(),B=function(t,e){return new q(t,e)},z=function(){var t=function(t){if("object"!=typeof t)throw Error("Configuration parameter should be an object, instead it is a: "+typeof t);this.config=t,this.params=[]},e=t.prototype;return e.whereParam=function(t){var e=new q(this.config[t],t);return e.parent=this,this.params.push(e),e},t}(),U=function(t){return new z(t)};L.Param=q,L.assertParam=B,L.assertConfig=U;var $=function(){function t(){}var e=function(e,n){this.name=e;var r=new t(n);r.parentEnum=this,this._symbolPrototype=r,n&&Object.keys(n).forEach(function(t){r[t]=n[t]})},n=e.prototype;return e.isSymbol=function(e){return e instanceof t},n.fromName=function(t){return this[t]},n.addSymbol=function(t){var e=Object.create(this._symbolPrototype);return t&&Object.keys(t).forEach(function(n){e[n]=t[n]}),setTimeout(function(){e.getName()},0),e},n.seal=function(){this.getSymbols().forEach(function(t){return t.getName()})},n.getSymbols=function(){return this.getNames().map(function(t){return this[t]},this)},n.getNames=function(){var t=[];for(var e in this)this.hasOwnProperty(e)&&("name"==e||"_"===e.substr(0,1)||S(this[e])||t.push(e));return t},n.contains=function(e){return e instanceof t?this[e.getName()]===e:!1},t.prototype.getName=function(){if(!this.name){var t=this;this.name=u(this.parentEnum.getNames(),function(e){return t.parentEnum[e]===t})}return this.name},t.prototype.toString=function(){return this.getName()},t.prototype.toJSON=function(){return{_$typeName:this.parentEnum.name,name:this.name}},e}();L.Enum=$;var G=function(){function t(t,e,r){var i=t._subscribers;return i?(i.forEach(function(i){try{i.callback(e)}catch(a){a.context="unable to publish on topic: "+t.name,r?r(a):t._defaultErrorCallback?t._defaultErrorCallback(a):n(a)}}),void 0):!0}function e(t){if(r[t])return t;var e=u(Object.keys(r),function(e){return 0===e.indexOf(t)});if(!e)throw Error("Unable to find any registered event that matches: "+t);return e}function n(){}var r={},i=function(t,e,n){B(t,"eventName").isNonEmptyString().check(),B(e,"publisher").isObject().check(),this.name=t,r[t]=!0,this.publisher=e,this._nextUnsubKey=1,n&&(this._defaultErrorCallback=n)},a=i.prototype;return a.publish=function(e,n,r){return i._isEnabled(this.name,this.publisher)?(n===!0?setTimeout(t,0,this,e,r):t(this,e,r),!0):!1},a.publishAsync=function(t,e){this.publish(t,!0,e)},a.subscribe=function(t){this._subscribers||(this._subscribers=[]);var e=this._nextUnsubKey;return this._subscribers.push({unsubKey:e,callback:t}),++this._nextUnsubKey,e},a.unsubscribe=function(t){if(!this._subscribers)return!1;var e=this._subscribers,n=p(e,function(e){return e.unsubKey===t});return-1!==n?(e.splice(n,1),0===e.length&&(this._subscribers=null),!0):!1},a.clear=function(){this._subscribers=null},i.bubbleEvent=function(t,e){t._getEventParent=e},i.enable=function(t,n,r){B(t,"eventName").isNonEmptyString().check(),B(n,"obj").isObject().check(),B(r,"isEnabled").isBoolean().isOptional().or().isFunction().check(),t=e(t),n._$eventMap||(n._$eventMap={}),n._$eventMap[t]=r},i._enableFast=function(t,e,n){e._$eventMap||(e._$eventMap={}),e._$eventMap[t.name]=n},i.isEnabled=function(t,n){if(B(t,"eventName").isNonEmptyString().check(),B(n,"obj").isObject().check(),!n._getEventParent)throw Error("This object does not support event enabling/disabling");return i._isEnabled(n,e(t))},i._isEnabled=function(t,e){var n=null,r=e._$eventMap;if(r&&(n=r[t]),null!=n)return"function"==typeof n?n(e):!!n;var a=e._getEventParent&&e._getEventParent();return a?i._isEnabled(t,a):!0},i}();L.Event=G;var Q=function(){function t(t,e,n){var r=e.defaultInstance;return r||(r=new e.ctor,e.defaultInstance=r,r._$impl=e),r.initialize(),n&&(t.defaultInstance=r),i.interfaceInitialized.publish({interfaceName:t.name,instance:r,isDefault:!0}),r.checkForRecomposition&&i.interfaceInitialized.subscribe(function(t){r.checkForRecomposition(t)}),r}function r(t){var n=t.toLowerCase(),r=e(i.interfaceRegistry||{},function(t){return t.toLowerCase()===n});if(!r)throw Error("Unknown interface name: "+t);return r.value}var i={};i.functionRegistry={},i.typeRegistry={},i.objectRegistry={},i.interfaceInitialized=new G("interfaceInitialized_config",i);var a=function(t){this.name=t,this.defaultInstance=null,this._implMap={}};return a.prototype.registerCtor=function(t,e){this._implMap[t.toLowerCase()]={ctor:e,defaultInstance:null}},a.prototype.getImpl=function(t){return this._implMap[t.toLowerCase()]},a.prototype.getFirstImpl=function(){var t=e(this._implMap,function(){return!0});return t?t.value:null},i.interfaceRegistry={ajax:new a("ajax"),modelLibrary:new a("modelLibrary"),dataService:new a("dataService")},i.interfaceRegistry.modelLibrary.getDefaultInstance=function(){if(!this.defaultInstance)throw Error("Unable to locate the default implementation of the '"+this.name+"' interface. Possible options are 'ko', 'backingStore' or 'backbone'. See the breeze.config.initializeAdapterInstances method.");return this.defaultInstance},i.setProperties=function(t){U(t).whereParam("remoteAccessImplementation").isOptional().whereParam("trackingImplementation").isOptional().whereParam("ajaxImplementation").isOptional().applyAll(t),t.remoteAccessImplementation&&i.initializeAdapterInstance("dataService",t.remoteAccessImplementation),t.trackingImplementation&&i.initializeAdapterInstance("modelLibrary",t.trackingImplementation),t.ajaxImplementation&&i.initializeAdapterInstance("ajax",t.ajaxImplementation)},i.registerAdapter=function(t,e){B(t,"interfaceName").isNonEmptyString().check(),B(e,"adapterCtor").isFunction().check();var n=new e,i=n.name;if(!i)throw Error("Unable to locate a 'name' property on the constructor passed into the 'registerAdapter' call.");var a=r(t);a.registerCtor(i,e)},i.getAdapter=function(t,e){var n=r(t);if(e){var i=n.getImpl(e);return i?i.ctor:null}return n.defaultInstance?n.defaultInstance._$impl.ctor:null},i.initializeAdapterInstances=function(t){return U(t).whereParam("dataService").isOptional().whereParam("modelLibrary").isOptional().whereParam("ajax").isOptional(),n(t,i.initializeAdapterInstance)},i.initializeAdapterInstance=function(e,n,i){i=void 0===i?!0:i,B(e,"interfaceName").isNonEmptyString().check(),B(n,"adapterName").isNonEmptyString().check(),B(i,"isDefault").isBoolean().check();var a=r(e),o=a.getImpl(n);if(!o)throw Error("Unregistered adapter. Interface: "+e+" AdapterName: "+n);return t(a,o,i)},i.getAdapterInstance=function(e,n){var i,a=r(e);return n&""!==n?(i=a.getImpl(n),i?i.defaultInstance:null):a.defaultInstance?a.defaultInstance:(i=a.getFirstImpl(),i.defaultInstance?i.defaultInstance:t(a,i,!0))},i.registerFunction=function(t,e){B(t,"fn").isFunction().check(),B(e,"fnName").isString().check(),t.prototype._$fnName=e,i.functionRegistry[e]=t},i._storeObject=function(t,e,n){var r=("string"==typeof e?e:e.prototype._$typeName)+"."+n;i.objectRegistry[r]=t},i._fetchObject=function(t,e){if(!e)return void 0;var n=("string"==typeof t?t:t.prototype._$typeName)+"."+e,r=i.objectRegistry[n];if(!r)throw Error("Unable to locate a registered object by the name: "+n);return r},i.registerType=function(t,e){B(t,"ctor").isFunction().check(),B(e,"typeName").isString().check(),t.prototype._$typeName=e,i.typeRegistry[e]=t},i.stringifyPad=" ",i}(),J=Q.interfaceRegistry.modelLibrary;L.config=Q,V.config=Q;var W=function(){var t={},e=function(t){return null==t?t:""+t},n=function(t,e){if("string"===e){var n=parseInt(t,10);return isNaN(n)?t:n}return"number"===e?Math.round(t):t},r=function(t,e){if("string"===e){var n=parseFloat(t);return isNaN(n)?t:n}return t},i=function(t,e){if("string"===e){var n=new Date(Date.parse(t));return T(n)?n:t}if("number"===e){var n=new Date(t);return T(n)?n:t}return t},a=function(t,e){if("string"===e){var n=t.trim().toLowerCase();return"false"===n?!1:"true"===n?!0:t}return t},o=new $("DataType",t);o.String=o.addSymbol({defaultValue:"",parse:e}),o.Int64=o.addSymbol({defaultValue:0,isNumeric:!0,isInteger:!0,parse:n}),o.Int32=o.addSymbol({defaultValue:0,isNumeric:!0,isInteger:!0,parse:n}),o.Int16=o.addSymbol({defaultValue:0,isNumeric:!0,isInteger:!0,parse:n}),o.Decimal=o.addSymbol({defaultValue:0,isNumeric:!0,parse:r}),o.Double=o.addSymbol({defaultValue:0,isNumeric:!0,parse:r}),o.Single=o.addSymbol({defaultValue:0,isNumeric:!0,parse:r}),o.DateTime=o.addSymbol({defaultValue:new Date(1900,0,1),parse:i}),o.Time=o.addSymbol({defaultValue:"PT0S"}),o.Boolean=o.addSymbol({defaultValue:!1,parse:a}),o.Guid=o.addSymbol({defaultValue:"00000000-0000-0000-0000-000000000000"}),o.Byte=o.addSymbol({defaultValue:0}),o.Binary=o.addSymbol({defaultValue:null}),o.Undefined=o.addSymbol({defaultValue:void 0}),o.seal(),o.fromEdmDataType=function(t){var e=null,n=t.split(".");if(n.length>1){var r=n[1];"image"===r?e=o.Byte:2==n.length?(e=o.fromName(r),e||(e="DateTimeOffset"===r?o.DateTime:o.Undefined)):e=o.String}return e},o.fromValue=function(t){if(T(t))return o.DateTime;switch(typeof t){case"string":return _(t)?o.Guid:b(t)?o.Time:o.String;case"boolean":return o.Boolean;case"number":return o.Int32}return o.Undefined};var s=/.\d{3}$/;return o.parseDateAsUTC=function(t){if("string"==typeof t){var e=s.test(t);t=e?t+"Z":t}return t=new Date(Date.parse(t))},o.parseDateFromServer=o.parseDateAsUTC,o}();V.DataType=W;var H=function(){function e(t,e,n){return e?t.replace(/%([^%]+)%/g,function(t,r){var i;return i=n?e.hasOwnProperty(r)?e[r]:"":e[r],i?S(i)?i(e):i:""}):t}function n(t,e,n,r){return y.messageTemplates[t]=A("'%displayName%' must be an integer between the values of %1 and %2",e,n),function(){var i=function(t,r){return null==t?!0:("string"==typeof t&&r&&r.allowString&&(t=parseInt(t,0)),"number"!=typeof t||isNaN(t)||Math.floor(t)!==t?!1:null!=e&&e>t?!1:null!=n&&t>n?!1:!0)};return new y(t,i,r)}}var r=-32768,i=32767,a=-2147483648,s=2147483647,u=0,p=255,c={displayName:function(t){return t.property?t.property.displayName||t.propertyName||t.property.name:"Value"}},y=function(t,e,n){this._baseContext=n||{},this._baseContext.validatorName=t,n=o(Object.create(c),this._baseContext),n.messageTemplate=n.messageTemplate||y.messageTemplates[t],this.name=t,this.valFn=e,this.context=n},l=y.prototype;return l._$typeName="Validator",l.validate=function(t,e){var n;return n=e?o(Object.create(this.context),e):this.context,this.currentContext=n,this.valFn(t,n)?null:(n.value=t,new X(this,n,this.getMessage()))},l.getMessage=function(){try{var t=this.currentContext,n=t.message;return n?"function"==typeof n?n(t):n:t.messageTemplate?e(t.messageTemplate,t):"invalid value: "+this.validatorName||"{unnamed validator}"}catch(r){return"Unable to format error message"+(""+r)}},l.toJSON=function(){return this._baseContext},y.fromJSON=function(t){var e="Validator."+t.validatorName,n=Q.functionRegistry[e];if(!n)throw Error("Unable to locate a validator named:"+t.validatorName);return n(t)},y.register=function(t){Q.registerFunction(function(){return t},"Validator."+t.name)},y.registerFactory=function(t,e){Q.registerFunction(t,"Validator."+e)},y.messageTemplates={required:"'%displayName%' is required",date:"'%displayName%' must be a date",string:"'%displayName%' must be a string",bool:"'%displayName%' must be a 'true' or 'false' value",guid:"'%displayName%' must be a GUID",duration:"'%displayName%' must be a ISO8601 duration string, such as 'P3H24M60S'",number:"'%displayName%' must be a number",integer:"'%displayName%' must be an integer",integerRange:"'%displayName%' must be an integer between the values of %minValue% and %maxValue%",maxLength:"'%displayName%' must be a string with less than %maxLength% characters",stringLength:"'%displayName%' must be a string with between %minLength% and %maxLength% characters"},y.required=function(){var t=function(t,e){return"string"==typeof t?e&&e.allowEmptyStrings?!0:t.length>0:null!=t};return new y("required",t)},y.maxLength=function(t){var e=function(t,e){return null==t?!0:"string"!=typeof t?!1:t.length<=e.maxLength};return new y("maxLength",e,t)},y.stringLength=function(t){var e=function(t,e){return null==t?!0:"string"!=typeof t?!1:null!=e.minLength&&t.length<e.minLength?!1:null!=e.maxLength&&t.length>e.maxLength?!1:!0};return new y("stringLength",e,t)},y.string=function(){var t=function(t){return null==t?!0:"string"==typeof t};return new y("string",t)},y.guid=function(){var t=function(t){return null==t?!0:_(t)};return new y("guid",t)},y.duration=function(){var t=function(t){return null==t?!0:b(t)};return new y("duration",t)},y.number=y.double=y.single=function(t){var e=function(t,e){return null==t?!0:("string"==typeof t&&e&&e.allowString&&(t=parseInt(t,10)),"number"==typeof t&&!isNaN(t))};return new y("number",e,t)},y.integer=y.int64=function(t){var e=function(t,e){return null==t?!0:("string"==typeof t&&e&&e.allowString&&(t=parseInt(t,10)),"number"==typeof t&&!isNaN(t)&&Math.floor(t)===t)};return new y("integer",e,t)},y.int32=function(t){return n("int32",a,s,t)()},y.int16=function(t){return n("int16",r,i,t)()},y.byte=function(t){return n("byte",u,p,t)()},y.bool=function(){var t=function(t){return null==t?!0:t===!0||t===!1};return new y("bool",t)},y.none=function(){var t=function(){return!0};return new y("none",t)},y.date=function(){var t=function(t){if(null==t)return!0;if("string"!=typeof t)return T(t);try{return!isNaN(Date.parse(t))}catch(e){return!1}};return new y("date",t)},t(y,function(t,e){"function"==typeof e&&"fromJSON"!==t&&"register"!==t&&"registerFactory"!==t&&Q.registerFunction(e,"Validator."+t)}),y}(),X=function(){var t=function(t,e,n){B(t,"validator").isString().or().isInstanceOf(H).check(),this.validator=t,e=e||{},this.context=e,this.property=e.property,this.property&&(this.propertyName=e.propertyName||e.property.name),this.errorMessage=n,this.key=X.getKey(t,this.propertyName)};return t.getKey=function(t,e){return(e||"")+":"+t.name},t}();W.getSymbols().forEach(function(t){t.validatorCtor=x(t)}),V.Validator=H,V.ValidationError=X;var Y=function(){var t={isUnchanged:function(){return this===e.Unchanged},isAdded:function(){return this===e.Added},isModified:function(){return this===e.Modified},isDeleted:function(){return this===e.Deleted},isDetached:function(){return this===e.Detached},isUnchangedOrModified:function(){return this===e.Unchanged||this===e.Modified},isAddedModifiedOrDeleted:function(){return this===e.Added||this===e.Modified||this===e.Deleted}},e=new $("EntityState",t);return e.Unchanged=e.addSymbol(),e.Added=e.addSymbol(),e.Modified=e.addSymbol(),e.Deleted=e.addSymbol(),e.Detached=e.addSymbol(),e.seal(),e}(),Z=function(){var t={isAttach:function(){return!!this.isAttach},isDetach:function(){return!!this.isDetach},isModification:function(){return!!this.isModification}},e=new $("EntityAction",t);return e.Attach=e.addSymbol({isAttach:!0}),e.AttachOnQuery=e.addSymbol({isAttach:!0}),e.AttachOnImport=e.addSymbol({isAttach:!0}),e.Detach=e.addSymbol({isDetach:!0}),e.MergeOnQuery=e.addSymbol({isModification:!0}),e.MergeOnImport=e.addSymbol({isModification:!0}),e.MergeOnSave=e.addSymbol({isModification:!0}),e.PropertyChange=e.addSymbol({isModification:!0}),e.EntityStateChange=e.addSymbol(),e.AcceptChanges=e.addSymbol(),e.RejectChanges=e.addSymbol({isModification:!0}),e.Clear=e.addSymbol({isDetach:!0}),e.seal(),e}(),te=function(){function e(t){var n=t.entityAspect||t.complexAspect,r=t.entityType||t.complexType,i=n.originalValues;for(var a in i)t.setProperty(a,i[a]);r.complexProperties.forEach(function(n){var r=t.getProperty(n.name);e(r)})}function n(t){var e=t.entityAspect||t.complexAspect;e.originalValues={};var r=t.entityType||t.complexType;r.complexProperties.forEach(function(e){var r=t.getProperty(e.name);n(r)})}function r(t){var e=!0,n=t.entityType||t.complexType,a=t.entityAspect||t.complexAspect,o=t.entityAspect||t.complexAspect.entityAspect;return n.getProperties().forEach(function(n){var i=t.getProperty(n.name),s=a.propertyPath?a.propertyPath+"."+n.name:n.name;if(n.validators.length>0){var u={entity:o.entity,property:n,propertyName:s};e=o._validateProperty(i,u)&&e}n.isComplexProperty&&(e=r(i)&&e)}),n.validators.forEach(function(t){e=i(o,t,a.entity)&&e}),e}function i(t,e,n,r){var i=e.validate(n,r);return i?(t._addValidationError(i),!1):(t._removeValidationError(e,r?r.propertyName:null),!0)}var o=function(t){if(null===t){var e=te._nullInstance;if(e)return e;te._nullInstance=this}else{if(void 0===t)throw Error("The EntityAspect ctor requires an entity as its only argument.");if(t.entityAspect)return t.entityAspect}if(!(this instanceof te))return new te(t);if(this.entity=t,this.entityGroup=null,this.entityManager=null,this.entityState=Y.Detached,this.isBeingSaved=!1,this.originalValues={},this._validationErrors={},this.validationErrorsChanged=new G("validationErrorsChanged_entityAspect",this),this.propertyChanged=new G("propertyChanged_entityAspect",this),null!=t){t.entityAspect=this;var n=t.entityType;if(!n){var r=t.prototype._$typeName;throw r?Error("Metadata for this entityType has not yet been resolved: "+r):Error("This entity is not registered as a valid EntityType")}var i=n.getEntityCtor();J.getDefaultInstance().startTracking(t,i.prototype)}},s=o.prototype;return s._postInitialize=function(){var t=this.entity,e=t.entityType.getEntityCtor(),n=e._$initializationFn;n&&("string"==typeof n&&(n=t[n]),n(t))},G.bubbleEvent(s,function(){return this.entityManager}),s.getKey=function(t){if(t=B(t,"forceRefresh").isBoolean().isOptional().check(!1),t||!this._entityKey){var e=this.entity.entityType,n=e.keyProperties,r=n.map(function(t){return this.entity.getProperty(t.name)},this);this._entityKey=new ne(e,r)}return this._entityKey},s.acceptChanges=function(){var t=this.entityManager;this.entityState.isDeleted()?t.detachEntity(this.entity):this.setUnchanged(),t.entityChanged.publish({entityAction:Z.AcceptChanges,entity:this.entity})},s.rejectChanges=function(){var t=this.entity,n=this.entityManager;d(n,"isRejectingChanges",!0,function(){e(t)}),this.entityState.isAdded()?(n.detachEntity(t),n._notifyStateChange(t,!1)):(this.entityState.isDeleted()&&this.entityManager._linkRelatedEntities(t),this.setUnchanged(),this.propertyChanged.publish({entity:t,propertyName:null}),this.entityManager.entityChanged.publish({entityAction:Z.RejectChanges,entity:t}))},s.setUnchanged=function(){n(this.entity),delete this.hasTempKey,this.entityState=Y.Unchanged,this.entityManager._notifyStateChange(this.entity,!1)},s.setModified=function(){this.entityState=Y.Modified,this.entityManager._notifyStateChange(this.entity,!0)},s.setDeleted=function(){var t=this.entityManager;this.entityState.isAdded()?(t.detachEntity(this.entity),t._notifyStateChange(this.entity,!1)):(this.entityState=Y.Deleted,this._removeFromRelations(),t._notifyStateChange(this.entity,!0))},s.validateEntity=function(){var t=!0;return this._processValidationOpAndPublish(function(e){t=r(e.entity)}),t},s.validateProperty=function(t,e){var n=this.getPropertyValue(t);return n.complexAspect?r(n):(e=e||{},e.entity=this.entity,"string"==typeof t?(e.property=this.entity.entityType.getProperty(t,!0),e.propertyName=t):(e.property=t,e.propertyName=t.name),this._validateProperty(n,e))},s.getValidationErrors=function(t){B(t,"property").isOptional().isEntityProperty().or().isString().check();var e=a(this._validationErrors);if(t){var n="string"==typeof t?t:t.name;e=e.filter(function(t){return t.property.name===n})}return e},s.addValidationError=function(t){B(t,"validationError").isInstanceOf(X).check(),this._processValidationOpAndPublish(function(e){e._addValidationError(t)})},s.removeValidationError=function(t,e){B(t,"validator").isString().or().isInstanceOf(H).check(),B(e,"property").isOptional().isEntityProperty().check(),this._processValidationOpAndPublish(function(n){n._removeValidationError(t,e&&e.name) })},s.clearValidationErrors=function(){this._processValidationOpAndPublish(function(e){t(e._validationErrors,function(t,n){n&&(delete e._validationErrors[t],e._pendingValidationResult.removed.push(n))})})},s.getParentKey=function(t){var e=t.foreignKeyNames;if(0===e.length)return null;var n=this,r=e.map(function(t){return n.entity.getProperty(t)});return new ne(t.entityType,r)},s.getPropertyValue=function(t){B(t,"property").isString().or().isEntityProperty().check();var e;if("string"==typeof t){var n=t.trim().split("."),r=n.shift();for(e=this.entity,e=e.getProperty(r);n.length>0;)r=n.shift(),e=e.getProperty(r)}else{if(!(t.parentType instanceof pe))throw Error("The validateProperty method does not accept a 'property' parameter whose parentType is a ComplexType; Pass a 'property path' string as the 'property' paramter instead ");e=this.entity.getProperty(t.name)}return e},s._detach=function(){this.entityGroup=null,this.entityManager=null,this.entityState=Y.Detached,this.originalValues={},this._validationErrors={},this.validationErrorsChanged.clear(),this.propertyChanged.clear()},s._removeFromRelations=function(){var t=this.entity;t.entityType.navigationProperties.forEach(function(e){var n=e.inverse;if(n){var r=t.getProperty(e.name);if(e.isScalar){if(r){if(n.isScalar)r.setProperty(n.name,null);else{var i=r.getProperty(n.name);i.length&&c(i,t)}t.setProperty(e.name,null)}}else r.slice(0).forEach(function(t){n.isScalar&&t.setProperty(n.name,null)}),r.length=0}})},s._validateProperty=function(t,e){var n=!0;return this._processValidationOpAndPublish(function(r){e.property.validators.forEach(function(a){n=n&&i(r,a,t,e)})}),n},s._processValidationOpAndPublish=function(t){if(this._pendingValidationResult)t(this);else try{this._pendingValidationResult={entity:this.entity,added:[],removed:[]},t(this),(this._pendingValidationResult.added.length>0||this._pendingValidationResult.removed.length>0)&&this.validationErrorsChanged.publish(this._pendingValidationResult)}finally{this._pendingValidationResult=void 0}},s._addValidationError=function(t){this._validationErrors[t.key]=t,this._pendingValidationResult.added.push(t)},s._removeValidationError=function(t,e){var n=X.getKey(t,e),r=this._validationErrors[n];r&&(delete this._validationErrors[n],this._pendingValidationResult.removed.push(r))},o}(),ee=function(){var t=function(t,e,n){if(!t)throw Error("The ComplexAspect ctor requires an entity as its only argument.");if(t.complexAspect)return t.complexAspect;if(!(this instanceof ee))return new ee(t,e,n);if(this.complexObject=t,t.complexAspect=this,this.originalValues={},null==e)this.entityAspect=new te(null);else{this.parent=e,this.parentProperty=n,this.propertyPath=n;for(var r=e;r.complexType;)this.propertyPath=r.complexAspect.propertyPath+"."+this.propertyPath,r=r.complexType.parent;this.entityAspect=r.entityAspect}var i=t.complexType;if(!i){var a=t.prototype._$typeName;throw a?Error("Metadata for this complexType has not yet been resolved: "+a):Error("This entity is not registered as a valid ComplexType")}var o=i.getCtor();J.getDefaultInstance().startTracking(t,o.prototype)},e=t.prototype;return e._postInitialize=function(){var t=this.complexObject,e=t.complexType.getCtor(),n=e._$initializationFn;n&&("string"==typeof n?t[n](t):e._$initializationFn(t))},t}(),ne=function(){function t(t){return t.join(e)}var e=":::",n=function(e,n){Array.isArray(n)||(n=Array.prototype.slice.call(arguments,1)),this.entityType=e,this.values=n,this._keyInGroup=t(n)};n._$typeName="EntityKey";var r=n.prototype;return r.toJSON=function(){return{entityType:this.entityType.name,values:this.values}},n.fromJSON=function(t,e){var n=e.getEntityType(t.entityType,!0);return new ne(n,t.values)},r.equals=function(t){return t instanceof ne?this.entityType===t.entityType&&l(this.values,t.values):!1},r.toString=function(){return this.entityType.name+"-"+this._keyInGroup},n.equals=function(t,e){return t instanceof ne?t.equals(e):!1},r._isEmpty=function(){return 0===this.values.join("").length},n._fromRawEntity=function(t,e){var n=e.keyProperties.map(function(e){return t[e.nameOnServer]});return new ne(e,n)},n}();V.EntityAspect=te,V.ComplexAspect=ee,V.EntityState=Y,V.EntityAction=Z,V.EntityKey=ne;var re=f("Q","See https://github.com/kriskowal/q "),ie=function(){var t=function(t){U(t||{}).whereParam("name").isOptional().isString().whereParam("isCaseSensitive").isOptional().isBoolean().withDefault(!1).whereParam("usesSql92CompliantStringComparison").isBoolean().withDefault(!0).applyAll(this),this.name||(this.name=v()),Q._storeObject(this,e._$typeName,this.name)},e=t.prototype;return e._$typeName="LocalQueryComparisonOptions",t.caseInsensitiveSQL=new t({name:"caseInsensitiveSQL",isCaseSensitive:!1,usesSql92CompliantStringComparison:!0}),t.defaultInstance=t.caseInsensitiveSQL,e.setAsDefault=function(){return t.defaultInstance=this,this},t}(),ae=function(){var t=function(t){U(t||{}).whereParam("name").isOptional().isString().whereParam("serverPropertyNameToClient").isFunction().whereParam("clientPropertyNameToServer").isFunction().applyAll(this),this.name||(this.name=v()),Q._storeObject(this,e._$typeName,this.name)},e=t.prototype;return e._$typeName="NamingConvention",t.none=new t({name:"noChange",serverPropertyNameToClient:function(t){return t},clientPropertyNameToServer:function(t){return t}}),t.camelCase=new t({name:"camelCase",serverPropertyNameToClient:function(t){return t.substr(0,1).toLowerCase()+t.substr(1)},clientPropertyNameToServer:function(t){return t.substr(0,1).toUpperCase()+t.substr(1)}}),t.defaultInstance=t.none,e.setAsDefault=function(){return t.defaultInstance=this,this},t}(),oe=function(){function e(){return function(){}}function r(t,e,n,r){var i=p(t,n,!1),a=e[i];if(!a){if(r)return null;throw Error("Unable to locate a 'Type' by the name: "+n)}if(a.length){var o=a.join(",");throw Error("There are multiple types with this 'shortName': "+o)}return a}function a(t){var e=[];for(var n in t){var r=t[n];n===r.name&&e.push(t[n])}return e}function s(t,e){var n=t._typeRegistry[e.name]||t._typeRegistry[e.shortName];n&&(n.prototype._$typeName=e.name,e._setCtor(n),t._structuralTypeMap[e.name]=e)}function p(t,e,n){if(k(e))return e;var r=t._shortNameMap[e];if(!r&&n)throw Error("Unable to locate 'entityTypeName' of: "+e);return r}function c(t,e,n){var r=t.name,a=j(r,e),o=new pe({shortName:r,namespace:a}),s=E(t.key.propertyRef).map(i("name"));return E(t.property).forEach(function(t){l(o,t,e,s)}),E(t.navigationProperty).forEach(function(t){g(o,t,e)}),n.addEntityType(o),o}function y(t,e,n){var r=t.name,i=j(r,e),a=new ce({shortName:r,namespace:i});return E(t.property).forEach(function(t){l(a,t,e)}),n.addEntityType(a),a}function l(t,e,n,r){var i,a=e.type.split(".");return 2==a.length?i=h(t,e,r):f(e,n)?(i=h(t,e,r),i&&(i.enumType=e.type)):i=d(t,e,n),i&&(t.addProperty(i),m(i)),i}function f(t,e){if(!e.enumType)return!1;var n=E(e.enumType),r=t.type.split("."),i=r[r.length-1];return n.some(function(t){return t.name===i})}function h(t,e,n){var r=W.fromEdmDataType(e.type);if(null==r)return t.warnings.push("Unable to recognize DataType for property: "+e.name+" DateType: "+e.type),null;var i="true"===e.nullable||null==e.nullable,a=e.fixedLength?e.fixedLength===!0:void 0,o=null!=n&&n.indexOf(e.name)>=0;t.autoGeneratedKeyType==fe.None&&v(e)&&(t.autoGeneratedKeyType=fe.Identity);var s=e.maxLength;s=null==s||"Max"===s?null:parseInt(s);var u=new ye({nameOnServer:e.name,dataType:r,isNullable:i,isPartOfKey:o,maxLength:s,fixedLength:a,concurrencyMode:e.concurrencyMode});return r===W.Undefined&&(u.rawTypeName=e.type),u}function d(t,e,n){var r=D(e.type,n).typeName,i=new ye({nameOnServer:e.name,complexTypeName:r,isNullable:!1});return i}function m(t){var e;if(t.isNullable||t.validators.push(H.required()),!t.isComplexProperty){if(t.dataType===W.String)if(t.maxLength){var n={maxLength:t.maxLength};e=H.maxLength(n)}else e=H.string();else e=t.dataType.validatorCtor();t.validators.push(e)}}function g(t,e,n){var r=P(e,n),a=u(r.end,function(t){return t.role===e.toRole}),o=!("*"===a.multiplicity),s=D(a.type,n).typeName,p=[];if(a&&o){var c=r.referentialConstraint;if(c){var y,l=c.principal,f=c.dependent;y=e.fromRole===l.role?E(l.propertyRef):E(f.propertyRef),p=y.map(i("name"))}}var h=new le({nameOnServer:e.name,entityTypeName:s,isScalar:o,associationName:r.name,foreignKeyNamesOnServer:p});return t.addProperty(h),h}function v(t){var e=u(Object.keys(t),function(t){return t.indexOf("StoreGeneratedPattern")>=0});if(e)return"Identity"===t[e];var n=t.extensions;if(!n)return!1;var r=u(n,function(t){return"StoreGeneratedPattern"===t.name&&"Identity"===t.value});return!!r}function P(t,e){var n=D(t.relationship,e).shortTypeName,r=e.association;if(!r)return null;Array.isArray(r)||(r=[r]);var i=u(r,function(t){return t.name===n});return i}function E(t){return t?Array.isArray(t)?t:[t]:[]}var T=0,S=function(t){t=t||{},U(t).whereParam("namingConvention").isOptional().isInstanceOf(ae).withDefault(ae.defaultInstance).whereParam("localQueryComparisonOptions").isOptional().isInstanceOf(ie).withDefault(ie.defaultInstance).applyAll(this),this.dataServices=[],this._resourceEntityTypeMap={},this._entityTypeResourceMap={},this._structuralTypeMap={},this._shortNameMap={},this._id=T++,this._typeRegistry={},this._incompleteTypeMap={}},_=S.prototype;return _._$typeName="MetadataStore",S.ANONTYPE_PREFIX="_IB_",_.addDataService=function(t){B(t,"dataService").isInstanceOf(se).check();var e=this.dataServices.some(function(e){return t.serviceName===e.serviceName});if(e)throw Error("A dataService with this name '"+t.serviceName+"' already exists in this MetadataStore");this.dataServices.push(t)},_.addEntityType=function(t){if(this.getEntityType(t.name,!0),t.metadataStore=this,!t.isAnonymous&&(this._structuralTypeMap[t.name]=t,this._shortNameMap[t.shortName]=t.name,t instanceof pe)){var e=this._entityTypeResourceMap[t.name];e&&(t.defaultResourceName=e)}t._fixup(),t.getProperties().forEach(function(e){e.isUnmapped||t._mappedPropertiesCount++})},_.exportMetadata=function(){var t=JSON.stringify(this,function(t,e){return"metadataStore"===t?null:"adapterInstance"===t?null:"namingConvention"===t||"localQueryComparisonOptions"===t?e.name:e},Q.stringifyPad);return t},_.importMetadata=function(e){var n=JSON.parse(e),r=n.namingConvention,i=n.localQueryComparisonOptions;if(delete n.namingConvention,delete n.localQueryComparisonOptions,this.isEmpty())this.namingConvention=Q._fetchObject(ae,r),this.localQueryComparisonOptions=Q._fetchObject(ie,i);else{if(this.namingConvention.name!==r)throw Error("Cannot import metadata with a different 'namingConvention' from the current MetadataStore");if(this.localQueryComparisonOptions.name!==i)throw Error("Cannot import metadata with different 'localQueryComparisonOptions' from the current MetadataStore")}var a={},u=this;return t(n._structuralTypeMap,function(t,e){a[t]=u._structuralTypeFromJson(e),s(u,a[t])}),n._structuralTypeMap=a,o(this,n),this},S.importMetadata=function(t){var e=new oe;return e.importMetadata(t),e},_.hasMetadataFor=function(t){return!!this.getDataService(t)},_.getDataService=function(t){return B(t,"serviceName").isString().check(),t=se._normalizeServiceName(t),u(this.dataServices,function(e){return e.serviceName===t})},_.fetchMetadata=function(t,e,n){if(B(t,"dataService").isString().or().isInstanceOf(se).check(),B(e,"callback").isFunction().isOptional().check(),B(n,"errorCallback").isFunction().isOptional().check(),"string"==typeof t&&(t=this.getDataService(t)||new se({serviceName:t})),this.hasMetadataFor(t.serviceName))throw Error("Metadata for a specific serviceName may only be fetched once per MetadataStore. ServiceName: "+t.serviceName);var r=re.defer();return t.adapterInstance.fetchMetadata(this,t,r.resolve,r.reject),r.promise.then(function(t){return e&&e(t),re.resolve(t)},function(t){return n&&n(t),re.reject(t)})},_.trackUnmappedType=function(t,e){B(t,"entityCtor").isFunction().check(),B(e,"interceptor").isFunction().isOptional().check();var n=new pe(this);n._setCtor(t,e)},_.registerEntityTypeCtor=function(t,n,r){B(t,"structuralTypeName").isString().check(),B(n,"aCtor").isFunction().isOptional().check(),B(r,"initializationFn").isOptional().isFunction().or().isString().check(),n||(n=e());var i,a=p(this,t,!1);if(a){var o=this._structuralTypeMap[a];o&&o._setCtor(n),i=a}else i=t;n.prototype._$typeName=i,this._typeRegistry[i]=n,r&&(n._$initializationFn=r)},_.isEmpty=function(){return 0===this.dataServices.length},_.getEntityType=function(t,e){return B(t,"structuralTypeName").isString().check(),B(e,"okIfNotFound").isBoolean().isOptional().check(!1),r(this,this._structuralTypeMap,t,e)},_.getEntityTypes=function(){return a(this._structuralTypeMap)},_.getIncompleteNavigationProperties=function(){return n(this._structuralTypeMap,function(t,e){if(e instanceof ce)return null;var n=e.navigationProperties.filter(function(t){return!t.entityType});return 0===n.length?null:n})},_.getEntityTypeNameForResourceName=function(t){return B(t,"resourceName").isString().check(),this._resourceEntityTypeMap[t]},_.setEntityTypeForResourceName=function(t,e){B(t,"resourceName").isString().check(),B(e,"entityTypeOrName").isInstanceOf(pe).or().isString().check();var n;n=e instanceof pe?e.name:p(this,e,!0),this._resourceEntityTypeMap[t]=n,this._entityTypeResourceMap[n]=t;var r=this.getEntityType(n,!0);r&&(r.defaultResourceName=r.defaultResourceName||t)},_._structuralTypeFromJson=function(t){var e=this.getEntityType(t.name,!0);if(e)return e;var n={shortName:t.shortName,namespace:t.namespace},r=!!t.navigationProperties;return e=r?new pe(n):new ce(n),t.validators=t.validators.map(H.fromJSON),t.dataProperties=t.dataProperties.map(function(t){return ye.fromJSON(t,e)}),r&&(t.autoGeneratedKeyType=fe.fromName(t.autoGeneratedKeyType),t.navigationProperties=t.navigationProperties.map(function(t){return le.fromJSON(t,e)})),e=o(e,t),this.addEntityType(e),e},_._checkEntityType=function(t){if(!t.entityType){var e=t.prototype._$typeName;if(!e)throw Error("This entity has not been registered. See the MetadataStore.registerEntityTypeCtor method");var n=this.getEntityType(e);n&&(t.entityType=n)}},_._parseODataMetadata=function(t,e){var n=this;E(e).forEach(function(t){if(t.cSpaceOSpaceMapping){var e=JSON.parse(t.cSpaceOSpaceMapping),r={};e.forEach(function(t){r[t[0]]=t[1]}),t.cSpaceOSpaceMapping=r}t.entityContainer&&E(t.entityContainer).forEach(function(e){E(e.entitySet).forEach(function(e){var r=D(e.entityType,t).typeName;n.setEntityTypeForResourceName(e.name,r)})}),t.complexType&&E(t.complexType).forEach(function(e){var r=y(e,t,n);s(n,r)}),t.entityType&&E(t.entityType).forEach(function(e){var r=c(e,t,n);s(n,r)})});var r=this.getIncompleteNavigationProperties();if(r.length>0)throw Error("Bad nav properties")},S}(),se=function(){var t=function(t){if(1!=arguments.length)throw Error("The DataService ctor should be called with a single argument that is a configuration object.");U(t).whereParam("serviceName").isNonEmptyString().whereParam("adapterName").isString().isOptional().withDefault(null).whereParam("hasServerMetadata").isBoolean().isOptional().withDefault(!0).whereParam("jsonResultsAdapter").isInstanceOf(ue).isOptional().withDefault(null).applyAll(this),this.serviceName=se._normalizeServiceName(this.serviceName),this.adapterInstance=Q.getAdapterInstance("dataService",this.adapterName),this.jsonResultsAdapter||(this.jsonResultsAdapter=this.adapterInstance.jsonResultsAdapter)},e=t.prototype;return e._$typeName="DataService",t._normalizeServiceName=function(t){return t=t.trim(),"/"!==t.substr(-1)?t+"/":t},e.toJSON=function(){var t=s(this);return t.jsonResultsAdapter=this.jsonResultsAdapter.name,t},t.fromJSON=function(t){return t.jsonResultsAdapter=Q._fetchObject(ue,t.jsonResultsAdapter),new se(t)},t}(),ue=function(){function t(t){return t.results}var e=function(e){if(1!=arguments.length)throw Error("The JsonResultsAdapter ctor should be called with a single argument that is a configuration object.");U(e).whereParam("name").isNonEmptyString().whereParam("extractResults").isFunction().isOptional().withDefault(t).whereParam("visitNode").isFunction().applyAll(this),Q._storeObject(this,n._$typeName,this.name)},n=e.prototype;return n._$typeName="JsonResultsAdapter",e}(),pe=function(){function e(){return function(){}}function n(e){var r=e.metadataStore._incompleteTypeMap,i=r[e.name];return w(i)?(delete r[e.name],void 0):(i&&t(i,function(t,r){r.entityType||r.entityTypeName===e.name&&(r.entityType=e,delete i[t],n(r.parentType))}),void 0)}function a(t){if(!t.foreignKeyProperties){var e=o(t);e&&e.forEach(function(e){e.relatedNavigationProperty=t,t.parentType.foreignKeyProperties.push(e),t.relatedDataProperties?t.relatedDataProperties.push(e):t.relatedDataProperties=[e]})}}function o(t){var e=t.foreignKeyNames,n=0==e.length;if(n&&(e=t.foreignKeyNamesOnServer,0==e.length))return t.foreignKeyProperties=[],t.foreignKeyProperties;var r=!0,a=t.parentType,o=e.map(function(t){var e=a.getDataProperty(t,n);return r=r&&!!e,e});return r?(n&&(t.foreignKeyNames=o.map(i("name"))),t.foreignKeyProperties=o,o):null}function p(t){var e=t.parentType.metadataStore,n=e._incompleteTypeMap,r=e.getEntityType(t.entityTypeName,!0);r&&(t.entityType=r);var i=n[t.entityTypeName];if(i){var a=i[t.associationName];a?y(n,t,a):c(n,t)}else c(n,t)}function c(t,e){if(!e.entityType){var n=t[e.entityTypeName];n||(n={},t[e.entityTypeName]=n),n[e.associationName]=e}var r=t[e.parentType.name];r||(r={},t[e.parentType.name]=r),r[e.associationName]=e}function y(t,e,n){e.inverse=n;var r=t[e.entityTypeName];if(delete r[e.associationName],w(r)&&delete t[e.entityTypeName],!n.inverse){n.inverse=e,null==n.entityType&&(n.entityType=e.parentType);var i=t[e.parentType.name];i&&(delete i[e.associationName],w(i)&&delete t[e.parentType.name])}}function l(t,e){var n=t.getPropertyNames(),r=J.getDefaultInstance().getTrackablePropertyNames(e);r.forEach(function(e){if(-1==n.indexOf(e)){var r=new ye({name:e,dataType:W.Undefined,isNullable:!0,isUnmapped:!0});t.addProperty(r)}})}var f=0,h=function(t){if(arguments.length>1)throw Error("The EntityType ctor has a single argument that is either a 'MetadataStore' or a configuration object.");"MetadataStore"===t._$typeName?(this.metadataStore=t,this.shortName="Anon_"+ ++f,this.namespace="",this.isAnonymous=!0):U(t).whereParam("shortName").isNonEmptyString().whereParam("namespace").isString().isOptional().withDefault("").whereParam("autoGeneratedKeyType").isEnumOf(fe).isOptional().withDefault(fe.None).whereParam("defaultResourceName").isNonEmptyString().isOptional().withDefault(null).applyAll(this),this.name=I(this.shortName,this.namespace),this.dataProperties=[],this.navigationProperties=[],this.complexProperties=[],this.keyProperties=[],this.foreignKeyProperties=[],this.concurrencyProperties=[],this.unmappedProperties=[],this.validators=[],this.warnings=[],this._mappedPropertiesCount=0},d=h.prototype;return d._$typeName="EntityType",d.setProperties=function(t){U(t).whereParam("autoGeneratedKeyType").isEnumOf(fe).isOptional().whereParam("defaultResourceName").isString().isOptional().applyAll(this),t.defaultResourceName&&(this.defaultResourceName=t.defaultResourceName)},d.addProperty=function(t){if(B(t,"dataProperty").isInstanceOf(ye).or().isInstanceOf(le).check(),this.metadataStore&&!t.isUnmapped)throw Error("The '"+this.name+"' EntityType has already been added to a MetadataStore and therefore no additional properties may be added to it.");if(t.parentType){if(t.parentType!==this)throw Error("This dataProperty has already been added to "+t.parentType.name);return this}return t.parentType=this,t.isDataProperty?this._addDataProperty(t):this._addNavigationProperty(t),this},d.createEntity=function(e){var n=this._createEntityCore();return e&&t(e,function(t,e){n.setProperty(t,e)}),n.entityAspect._postInitialize(),n},d._createEntityCore=function(){var t=this.getEntityCtor(),e=new t;return new te(e),e},d.getEntityCtor=function(){if(this._ctor)return this._ctor;var t=this.metadataStore._typeRegistry,n=t[this.name]||t[this.shortName];if(!n){var r=J.getDefaultInstance().createCtor;n=r?r(this):e()}return this._setCtor(n),n},d._setCtor=function(t,e){var n=new t,r=t.prototype;"EntityType"==this._$typeName?(l(this,n),r.entityType=this):(l(this,n),r.complexType=this),r._$interceptor=e?e:M,J.getDefaultInstance().initializeEntityPrototype(r),this._ctor=t},d.addValidator=function(t,e){B(t,"validator").isInstanceOf(H).check(),B(e,"property").isOptional().isString().or().isEntityProperty().check(),e?("string"==typeof e&&(e=this.getProperty(e,!0)),e.validators.push(t)):this.validators.push(t)},d.getProperties=function(){return this.dataProperties.concat(this.navigationProperties)},d.getPropertyNames=function(){return this.getProperties().map(i("name"))},d.getDataProperty=function(t,e){var n=e?"nameOnServer":"name";return u(this.dataProperties,r(n,t))},d.getNavigationProperty=function(t,e){var n=e?"nameOnServer":"name";return u(this.navigationProperties,r(n,t))},d.getProperty=function(t,e){e=e||!1;var n=Array.isArray(t)?t:t.trim().split("."),i=n[0],a=u(this.getProperties(),r("name",i));if(1===n.length){if(a)return a;if(e)throw Error("unable to locate property: "+i+" on entityType: "+this.name);return null}if(a){n.shift();var o=a.isNavigationProperty?a.entityType:a.dataType;if(o)return o.getProperty(n,e);throw Error("should not get here - unknown property type for: "+a.name)}if(e)throw Error("unable to locate property: "+i+" on type: "+this.name);return null},d.toString=function(){return this.name},d.toJSON=function(){return s(this,["dataProperties","navigationProperties","validators"])},d._clientPropertyPathToServer=function(t){var e=this.metadataStore.namingConvention.clientPropertyNameToServer,n=this,r=t.split(".").map(function(t){var r=n.getProperty(t);return e(t,r)}).join("/");return r},d._updateProperty=function(t){var e,n,r=this.metadataStore.namingConvention,i=t.nameOnServer;if(i){if(e=r.serverPropertyNameToClient(i,t),n=r.clientPropertyNameToServer(e,t),i!==n)throw Error("NamingConvention for this server property name does not roundtrip properly:"+i+"-->"+n);t.name=e}else{if(e=t.name,i=r.clientPropertyNameToServer(e,t),n=r.serverPropertyNameToClient(i,t),e!==n)throw Error("NamingConvention for this client property name does not roundtrip properly:"+e+"-->"+n);t.nameOnServer=i}if(t.isComplexProperty){var o=this.metadataStore.getEntityType(t.complexTypeName,!1);if(!(o&&o instanceof ce))throw Error("Unable to resolve ComplexType with the name: "+t.complexTypeName+" for the property: "+t.name);t.dataType=o,t.defaultValue=null}else t.isNavigationProperty&&(a(t),p(t))},h._getNormalizedTypeName=g(function(t){return t&&D(t).typeName}),d._checkNavProperty=function(t){if(t.isNavigationProperty){if(t.parentType!=this)throw Error(A("The navigationProperty '%1' is not a property of entity type '%2'",t.name,this.name));return t}if("string"==typeof t){var e=this.getProperty(t);if(e&&e.isNavigationProperty)return e}throw Error("The 'navigationProperty' parameter must either be a NavigationProperty or the name of a NavigationProperty")},d._addDataProperty=function(t){this.dataProperties.push(t),t.isPartOfKey&&this.keyProperties.push(t),t.isComplexProperty&&this.complexProperties.push(t),t.concurrencyMode&&"None"!==t.concurrencyMode&&this.concurrencyProperties.push(t),t.isUnmapped&&this.unmappedProperties.push(t)},d._addNavigationProperty=function(t){this.navigationProperties.push(t),k(t.entityTypeName)||(t.entityTypeName=I(t.entityTypeName,this.namespace))},d._fixup=function(){var t=this;this.getProperties().forEach(function(e){t._updateProperty(e)}),n(this)},h}(),ce=function(){var e=function(t){if(arguments.length>1)throw Error("The ComplexType ctor has a single argument that is a configuration object.");U(t).whereParam("shortName").isNonEmptyString().whereParam("namespace").isString().isOptional().withDefault("").applyAll(this),this.name=I(this.shortName,this.namespace),this.dataProperties=[],this.complexProperties=[],this.validators=[],this.concurrencyProperties=[],this.unmappedProperties=[]},n=e.prototype;return n.createInstance=function(e){var n=this._createInstanceCore();return e&&t(e,function(t,e){n.setProperty(t,e)}),n.complexAspect._postInitialize(),n},n._createInstanceCore=function(t,e){var n=this.getCtor(),r=new n;return new ee(r,t,e),t&&r.complexAspect._postInitialize(),r},n.addProperty=function(t){if(B(t,"dataProperty").isInstanceOf(ye).check(),this.metadataStore&&!t.isUnmapped)throw Error("The '"+this.name+"' ComplexType has already been added to a MetadataStore and therefore no additional properties may be added to it.");if(t.parentType){if(t.parentType!==this)throw Error("This dataProperty has already been added to "+property.parentType.name);return this}return this._addDataProperty(t),this},n.getProperties=function(){return this.dataProperties},n.addValidator=pe.prototype.addValidator,n.getProperty=pe.prototype.getProperty,n.getPropertyNames=pe.prototype.getPropertyNames,n._addDataProperty=pe.prototype._addDataProperty,n._updateProperty=pe.prototype._updateProperty,n.getCtor=pe.prototype.getEntityCtor,n._setCtor=pe.prototype._setCtor,n.toJSON=function(){return s(this,["dataProperties","validators"])},n._fixup=function(){var t=this;this.dataProperties.forEach(function(e){t._updateProperty(e)})},n._$typeName="ComplexType",e}(),ye=function(){var t=function(t){U(t).whereParam("name").isString().isOptional().whereParam("nameOnServer").isString().isOptional().whereParam("dataType").isEnumOf(W).isOptional().or().isInstanceOf(ce).whereParam("complexTypeName").isOptional().whereParam("isNullable").isBoolean().isOptional().withDefault(!0).whereParam("defaultValue").isOptional().whereParam("isPartOfKey").isBoolean().isOptional().whereParam("isUnmapped").isBoolean().isOptional().whereParam("concurrencyMode").isString().isOptional().whereParam("maxLength").isNumber().isOptional().whereParam("fixedLength").isBoolean().isOptional().whereParam("validators").isInstanceOf(H).isArray().isOptional().withDefault([]).whereParam("enumType").isOptional().whereParam("rawTypeName").isOptional().applyAll(this);var e=!(!this.name&&!this.nameOnServer);if(!e)throw Error("A DataProperty must be instantiated with either a 'name' or a 'nameOnServer' property");if(this.complexTypeName?this.isComplexProperty=!0:this.dataType||(this.dataType=W.String),null==this.defaultValue)if(this.isNullable)this.defaultValue=null;else if(this.isComplexProperty);else if(this.dataType===W.Binary)this.defaultValue="AAAAAAAAJ3U=";else if(this.defaultValue=this.dataType.defaultValue,null==this.defaultValue)throw Error("A nonnullable DataProperty cannot have a null defaultValue. Name: "+this.name)},e=t.prototype;return e._$typeName="DataProperty",e.isDataProperty=!0,e.isNavigationProperty=!1,e.toJSON=function(){var t=s(this,["validators"]);return delete t.isComplexProperty,t},t.fromJSON=function(t,e){t.dataType=W.fromName(t.dataType),t.validators=t.validators.map(H.fromJSON);var n=new ye(t);return e.addProperty(n),n},t}(),le=function(){var t=function(t){U(t).whereParam("name").isString().isOptional().whereParam("nameOnServer").isString().isOptional().whereParam("entityTypeName").isString().whereParam("isScalar").isBoolean().whereParam("associationName").isString().isOptional().whereParam("foreignKeyNames").isArray().isString().isOptional().withDefault([]).whereParam("foreignKeyNamesOnServer").isArray().isString().isOptional().withDefault([]).whereParam("validators").isInstanceOf(H).isArray().isOptional().withDefault([]).applyAll(this);var e=!(!this.name&&!this.nameOnServer);if(!e)throw Error("A Navigation property must be instantiated with either a 'name' or a 'nameOnServer' property")},e=t.prototype;return e._$typeName="NavigationProperty",e.isDataProperty=!1,e.isNavigationProperty=!0,e.toJSON=function(){return s(this,["validators","foreignKeyNames","foreignKeyNamesOnServer"])},t.fromJSON=function(t,e){t.validators=t.validators.map(H.fromJSON);var n=new le(t);return e.addProperty(n),n},t}(),fe=function(){var t=new $("AutoGeneratedKeyType");return t.None=t.addSymbol(),t.Identity=t.addSymbol(),t.KeyGenerator=t.addSymbol(),t.seal(),t}();(function(){function t(t,e){return null==e?!1:void 0!==e.entityType}function e(t,e){return null==e?!1:e.isDataProperty||e.isNavigationProperty}var n=q.prototype;n.isEntity=function(){return this._addContext({fn:t,msg:" must be an entity"})},n.isEntityProperty=function(){return this._addContext({fn:e,msg:" must be either a DataProperty or a NavigationProperty"})}})(),V.MetadataStore=oe,V.DataService=se,V.JsonResultsAdapter=ue,V.EntityType=pe,V.ComplexType=ce,V.DataProperty=ye,V.NavigationProperty=le,V.DataType=W,V.AutoGeneratedKeyType=fe,V.NamingConvention=ae;var he=function(){function t(t){return t}function e(t){return B(t,"propertyPaths").isOptional().isString().or().isArray().isString().check(),"string"==typeof t&&(t=t.split(",")),t=t.map(function(t){return t.trim()})}function n(t){var e=t.entityType,n=e.keyProperties.map(function(e){return Pe.create(e.name,ge.Equals,t.getProperty(e.name))}),r=Pe.and(n);return r}function r(t,e,n){var r,i=t._clone();return e?(r=Se.create(e,n),i.orderByClause?i.orderByClause.addClause(r):i.orderByClause=r,i):(i.orderByClause=null,i)}function i(t,e){var n=t._clone();return e?(n.selectClause=new we(e),n):(n.selectClause=null,n)}function a(t,e){var n=t._clone();return e?(n.expandClause=new Ne(e),n):(n.expandClause=null,n)}function s(t,e){var n=t._clone();return n.parameters=e,n}function u(t){var e=t.entityType.keyProperties,n=y(e,t.values,function(t,e){return Pe.create(t.name,ge.Equals,e)}),r=Pe.and(n);return r}function p(t,e){if(e.isScalar){if(0===e.foreignKeyNames.length)return null;var n=e.foreignKeyNames.map(function(e){return t.getProperty(e)}),r=new ne(e.entityType,n);return u(r)}var i=e.inverse;if(!i)return null;var a=i.foreignKeyNames;if(0===a.length)return null;var o=t.entityAspect.getKey().values,s=y(a,o,function(t,e){return Pe.create(t,ge.Equals,e)}),p=Pe.and(s);return p}var c=function(e){B(e,"resourceName").isOptional().isString().check(),this.resourceName=t(e),this.entityType=null,this.wherePredicate=null,this.orderByClause=null,this.selectClause=null,this.skipCount=null,this.takeCount=null,this.expandClause=null,this.parameters={},this.inlineCountEnabled=!1,this.queryOptions=null,this.entityManager=null,this.dataService=null},l=c.prototype;return l.from=function(e){B(e,"resourceName").isString().check(),e=t(e);var n=this.resourceName;if(n&&n!==e)throw Error("This query already has an resourceName - the resourceName may only be set once per query");var r=this._clone();return r.resourceName=e,r},c.from=function(t){return B(t,"resourceName").isString().check(),new he(t)},l.toType=function(t){B(t,"entityType").isString().or.isInstanceOf(pe).check();var e=this._clone();e.toEntityType=t},l.where=function(t){var e=this._clone();if(0===arguments.length)return e.wherePredicate=null,e;var n;return n=Pe.isPredicate(t)?t:Pe.create(Array.prototype.slice.call(arguments)),e.entityType&&n.validate(e.entityType),e.wherePredicate=e.wherePredicate?new Te("and",[e.wherePredicate,n]):n,e},l.orderBy=function(t){return r(this,e(t))},l.orderByDesc=function(t){return r(this,e(t),!0)},l.select=function(t){return i(this,e(t))},l.skip=function(t){B(t,"count").isOptional().isNumber().check();var e=this._clone();return e.skipCount=0===arguments.length?null:t,e},l.top=function(t){return this.take(t)},l.take=function(t){B(t,"count").isOptional().isNumber().check();var e=this._clone();return e.takeCount=0===arguments.length?null:t,e},l.expand=function(t){return a(this,e(t))},l.withParameters=function(t){return B(t,"parameters").isObject().check(),s(this,t)},l.inlineCount=function(t){void 0===t&&(t=!0);var e=this._clone();return e.inlineCountEnabled=t,e},l.using=function(t){var e=this._clone();if(t instanceof Ce)e.entityManager=t;else if(xe.contains(t)||Me.contains(t)){var n=this.queryOptions||ke.defaultInstance;e.queryOptions=n.using(t)}else if(t instanceof se)e.dataService=t; else{if(!(t instanceof ue))throw Error("EntityQuery.using parameter must be either an EntityManager, a Query Strategy, a FetchStrategy, a DataService or a JsonResultsAdapter");e.jsonResultsAdapter=t}return e},l.execute=function(t,e){if(!this.entityManager)throw Error("An EntityQuery must have its EntityManager property set before calling 'execute'");return this.entityManager.executeQuery(this,t,e)},l.executeLocally=function(){if(!this.entityManager)throw Error("An EntityQuery must have its EntityManager property set before calling 'executeLocally'");return this.entityManager.executeQueryLocally(this)},c.fromEntities=function(t){B(t,"entities").isEntity().or().isNonEmptyArray().isEntity().check(),Array.isArray(t)||(t=Array.prototype.slice.call(arguments));var e=t[0],r=new he(e.entityType.defaultResourceName),i=t.map(function(t){return n(t)}),a=Pe.or(i);r=r.where(a);var o=e.entityAspect.entityManager;return o&&(r=r.using(o)),r},c.fromEntityKey=function(t){B(t,"entityKey").isInstanceOf(ne).check();var e=new he(t.entityType.defaultResourceName),n=u(t);return e=e.where(n)},c.fromEntityNavigation=function(t,e){B(t,"entity").isEntity().check(),B(e,"navigationProperty").isInstanceOf(le).check();var n=t.entityType._checkNavProperty(e),r=new he(n.entityType.defaultResourceName),i=p(t,n);r=r.where(i);var a=t.entityAspect.entityManager;return a&&(r=r.using(a)),r},l._getFromEntityType=function(t,e){var n=this.entityType;if(!n){var r=this.resourceName;if(!r)throw Error("There is no resourceName for this query");if(t.isEmpty()){if(e)throw Error("There is no metadata available for this query");return null}var i=t.getEntityTypeNameForResourceName(r);if(!i){if(e)throw Error("Cannot find resourceName of: "+r);return null}if(n=t.getEntityType(i),!n){if(e)throw Error("Cannot find an entityType for an entityTypeName of: "+i);return null}this.entityType=n}return n},l._getToEntityType=function(t){return this.toEntityType instanceof pe?this.toEntityType:this.toEntityType?(this.toEntityType=t.getEntityType(this.toEntityType,!1),this.toEntityType):!this.selectClause&&this._getFromEntityType(t,!1)},l._clone=function(){var t=new he;return t.resourceName=this.resourceName,t.entityType=this.entityType,t.wherePredicate=this.wherePredicate,t.orderByClause=this.orderByClause,t.selectClause=this.selectClause,t.skipCount=this.skipCount,t.takeCount=this.takeCount,t.expandClause=this.expandClause,t.inlineCountEnabled=this.inlineCountEnabled,t.parameters=o({},this.parameters),t.queryOptions=this.queryOptions,t.entityManager=this.entityManager,t},l._toUri=function(t){function e(){var t=y.wherePredicate;return t?(y.entityType&&t.validate(y.entityType),t.toOdataFragment(c)):""}function n(){return y.inlineCountEnabled?y.inlineCountEnabled?"allpages":"none":""}function r(){var t=y.orderByClause;return t?(y.entityType&&t.validate(y.entityType),t.toOdataFragment(c)):""}function i(){var t=y.selectClause;return t?(y.entityType&&t.validate(y.entityType),t.toOdataFragment(c)):""}function a(){var t=y.expandClause;return t?t.toOdataFragment(c):""}function s(){var t=y.skipCount;return t?""+t:""}function u(){var t=y.takeCount;return t?""+t:""}function p(t){var e=[];for(var n in t){var r=t[n];r&&e.push(n+"="+encodeURIComponent(r))}return e.length>0?"?"+e.join("&"):""}var c=this._getFromEntityType(t,!1);c||(c=new pe(t));var y=this,l={};l.$filter=e(),l.$orderby=r(),l.$skip=s(),l.$top=u(),l.$expand=a(),l.$select=i(),l.$inlinecount=n(),l=o(l,this.parameters);var f=p(l);return this.resourceName+f},l._toFilterFunction=function(t){var e=this.wherePredicate;return e?(e.validate(t),e.toFunction(t)):null},l._toOrderByComparer=function(t){var e=this.orderByClause;return e?(e.validate(t),e.getComparer()):null},c}(),de=function(){var t={toupper:{fn:function(t){return t.toUpperCase()},dataType:W.String},tolower:{fn:function(t){return t.toLowerCase()},dataType:W.String},substring:{fn:function(t,e,n){return t.substring(e,n)},dataType:W.String},substringof:{fn:function(t,e){return e.indexOf(t)>=0},dataType:W.Boolean},length:{fn:function(t){return t.length},dataType:W.Int32},trim:{fn:function(t){return t.trim()},dataType:W.String},concat:{fn:function(t,e){return t.concat(e)},dataType:W.String},replace:{fn:function(t,e,n){return t.replace(e,n)},dataType:W.String},startswith:{fn:function(t,e){return O(t,e)},dataType:W.Boolean},endswith:{fn:function(t,e){return C(t,e)},dataType:W.Boolean},indexof:{fn:function(t,e){return t.indexOf(e)},dataType:W.Int32},round:{fn:function(t){return Math.round(t)},dataType:W.Int32},ceiling:{fn:function(t){return Math.ceil(t)},dataType:W.Int32},floor:{fn:function(t){return Math.floor(t)},dataType:W.Int32},second:{fn:function(t){return t.second},dataType:W.Int32},minute:{fn:function(t){return t.minute},dataType:W.Int32},day:{fn:function(t){return t.day},dataType:W.Int32},month:{fn:function(t){return t.month},dataType:W.Int32},year:{fn:function(t){return t.year},dataType:W.Int32}};return t}(),me=function(){function t(t){var e=t.split(".");return 1===e.length?function(e){return e.getProperty(t)}:function(t){return F(t,e)}}var e=/^[a-z_][\w.$]*$/i,n=/('[^']*'|[^,]+)/g,r=/("[^"]*"|[^,]+)/g,i=function(i,a,o){var s=i.split(":");if(o&&(this.isValidated=!0),1==s.length){var u=s[0].trim();this.value=u;var p=u.substr(0,1),c="'"==p||'"'==p;if(c){var y=u.substr(1,u.length-2);this.fn=function(){return y},this.dataType=W.String}else{var l=e.test(u);if(l){if(o&&null==o.getProperty(u,!1))return this.isValidated=!1,void 0;this.propertyPath=u,this.fn=t(u)}else{if(o)return this.isValidated=!1,void 0;this.fn=function(){return u},this.dataType=W.fromValue(u)}}}else try{this.fnName=s[0].trim().toLowerCase();var f=de[this.fnName];this.localFn=f.fn,this.dataType=f.dataType;var h=this;this.fn=function(t){var e=h.fnNodes.map(function(e){var n=e.fn(t);return n}),n=h.localFn.apply(null,e);return n};var d=a[s[1]].trim();"("==d.substr(0,1)&&(d=d.substr(1,d.length-2));var m=i.indexOf("'")>=0?n:r,g=d.match(m);this.fnNodes=g.map(function(t){return new me(t,a)})}catch(v){this.isValidated=!1}},a=i.prototype;return i.create=function(t,e){if("string"!=typeof t)return null;for(var n,r=/\([^()]*\)/,i=[],a=0;n=r.exec(t);){var o=n[0];i.push(o);var s=":"+a++;t=t.replace(o,s)}var u=new me(t,i,e);return u.isValidated===!1?null:u},a.toString=function(){if(this.fnName){var t=this.fnNodes.map(function(t){return""+t}),e=this.fnName+"("+t.join(",")+")";return e}return this.value},a.updateWithEntityType=function(t){if(this.propertyPath){if(t.isAnonymous)return;var e=t.getProperty(this.propertyPath);if(!e){var n=A("Unable to resolve propertyPath. EntityType: '%1' PropertyPath: '%2'",t.name,this.propertyPath);throw Error(n)}this.dataType=e.dataType}},a.toOdataFragment=function(t){if(this.updateWithEntityType(t),this.fnName){var e=this.fnNodes.map(function(e){return e.toOdataFragment(t)}),n=this.fnName+"("+e.join(",")+")";return n}var r=this.value.substr(0,1);return"'"===r||'"'===r?this.value:this.value==this.propertyPath?t._clientPropertyPathToServer(this.propertyPath):this.value},a.validate=function(t){if(void 0===this.isValidated)if(this.isValidated=!0,this.propertyPath){var e=t.getProperty(this.propertyPath,!0);this.dataType=e.isDataProperty?e.dataType:e.entityType}else this.fnNodes&&this.fnNodes.forEach(function(e){e.validate(t)})},i}(),ge=function(){var t=new $("FilterQueryOp");return t.Equals=t.addSymbol({operator:"eq",aliases:["=="]}),t.NotEquals=t.addSymbol({operator:"ne",aliases:["!="]}),t.GreaterThan=t.addSymbol({operator:"gt",aliases:[">"]}),t.LessThan=t.addSymbol({operator:"lt",aliases:["<"]}),t.GreaterThanOrEqual=t.addSymbol({operator:"ge",aliases:[">="]}),t.LessThanOrEqual=t.addSymbol({operator:"le",aliases:["<="]}),t.Contains=t.addSymbol({operator:"substringof",isFunction:!0}),t.StartsWith=t.addSymbol({operator:"startswith",isFunction:!0}),t.EndsWith=t.addSymbol({operator:"endswith",isFunction:!0}),t.seal(),t._map=function(){var e={};return t.getSymbols().forEach(function(t){e[t.name.toLowerCase()]=t,e[t.operator.toLowerCase()]=t,t.aliases&&t.aliases.forEach(function(n){e[n.toLowerCase()]=t})}),e}(),t.from=function(e){return t.contains(e)?e:t._map[e.toLowerCase()]},t}(),ve=function(){var t=new $("BooleanQueryOp");return t.And=t.addSymbol({operator:"and",aliases:["&&"]}),t.Or=t.addSymbol({operator:"or",aliases:["||"]}),t.Not=t.addSymbol({operator:"not",aliases:["~","!"]}),t.seal(),t._map=function(){var e={};return t.getSymbols().forEach(function(t){e[t.name.toLowerCase()]=t,e[t.operator.toLowerCase()]=t,t.aliases&&t.aliases.forEach(function(n){e[n.toLowerCase()]=t})}),e}(),t.from=function(e){return t.contains(e)?e:t._map[e.toLowerCase()]},t}(),Pe=function(){function t(t){if(1===t.length&&Array.isArray(t[0]))return t[0];var e=Array.prototype.slice.call(t);return Pe.isPredicate(e[0])?e:[Pe.create(e)]}var e=function(t,e,n,r){return arguments[0].prototype===!0?this:new Ee(t,e,n,r)},n=e.prototype;return e.isPredicate=function(t){return t instanceof Pe},e.create=function(t,e,n,r){return Array.isArray(t)?(r=4===t.length?t[3]:!1,new Ee(t[0],t[1],t[2],r)):new Ee(t,e,n,r)},e.and=function(e){return e=t(arguments),1===e.length?e[0]:new Te("and",e)},e.or=function(e){return e=t(arguments),1===e.length?e[0]:new Te("or",e)},e.not=function(t){return new Te("not",[t])},n.and=function(n){return n=t(arguments),n.unshift(this),e.and(n)},n.or=function(n){return n=t(arguments),n.unshift(this),e.or(n)},n.not=function(){return new Te("not",[this])},e}(),Ee=function(){function t(t,a,o){var s,u=t.metadataStore.localQueryComparisonOptions,p=R(o);switch(a){case ge.Equals:s=function(t,n){return t&&"string"==typeof t?e(t,n,u):p(t)==p(n)};break;case ge.NotEquals:s=function(t,n){return t&&"string"==typeof t?!e(t,n,u):p(t)!=p(n)};break;case ge.GreaterThan:s=function(t,e){return p(t)>p(e)};break;case ge.GreaterThanOrEqual:s=function(t,e){return p(t)>=p(e)};break;case ge.LessThan:s=function(t,e){return p(t)<p(e)};break;case ge.LessThanOrEqual:s=function(t,e){return p(t)<=p(e)};break;case ge.StartsWith:s=function(t,e){return n(t,e,u)};break;case ge.EndsWith:s=function(t,e){return r(t,e,u)};break;case ge.Contains:s=function(t,e){return i(t,e,u)};break;default:throw Error("Unknown FilterQueryOp: "+a)}return s}function e(t,e,n){return null==e?!1:("string"!=typeof e&&(e=""+e),n.usesSql92CompliantStringComparison&&(t=(t||"").trim(),e=(e||"").trim()),n.isCaseSensitive||(t=(t||"").toLowerCase(),e=(e||"").toLowerCase()),t==e)}function n(t,e,n){return n.isCaseSensitive||(t=(t||"").toLowerCase(),e=(e||"").toLowerCase()),O(t,e)}function r(t,e,n){return n.isCaseSensitive||(t=(t||"").toLowerCase(),e=(e||"").toLowerCase()),C(t,e)}function i(t,e,n){return n.isCaseSensitive||(t=(t||"").toLowerCase(),e=(e||"").toLowerCase()),t.indexOf(e)>=0}function a(t,e){if(null==t)return null;var n;if(e=e||W.fromValue(t),e.isNumeric)return"string"==typeof t&&(t=e.isInteger?parseInt(t):parseFloat(t)),t;if(e===W.String)return"'"+t+"'";if(e!==W.DateTime){if(e==W.Time){if(!b(t))throw n=A("'%1' is not a valid ISO 8601 duration",t),Error(n);return"time'"+t+"'"}if(e===W.Guid){if(!_(t))throw n=A("'%1' is not a valid guid",t),Error(n);return"guid'"+t+"'"}return e===W.Boolean?"string"==typeof t?"true"===t.trim().toLowerCase():t:t}try{return"datetime'"+t.toISOString()+"'"}catch(r){throw n=A("'%1' is not a valid dateTime",t),Error(n)}}var o=function(t,e,n,r){if(B(t,"propertyOrExpr").isString().check(),B(e,"operator").isEnumOf(ge).or().isString().check(),B(n,"value").isRequired(!0).check(),B(r).isOptional().isBoolean().check(),this._propertyOrExpr=t,this._fnNode1=me.create(t,null),this._filterQueryOp=ge.from(e),!this._filterQueryOp)throw Error("Unknown query operation: "+e);this._value=n,this._valueIsLiteral=r},s=new Pe({prototype:!0});return o.prototype=s,s.toOdataFragment=function(t){var e,n=this._fnNode1.toOdataFragment(t);return void 0!==this.fnNode2||this._valueIsLiteral||(this.fnNode2=me.create(this._value,t)),e=this.fnNode2?this.fnNode2.toOdataFragment(t):a(this._value,this._fnNode1.dataType),this._filterQueryOp.isFunction?this._filterQueryOp==ge.Contains?this._filterQueryOp.operator+"("+e+","+n+") eq true":this._filterQueryOp.operator+"("+n+","+e+") eq true":n+" "+this._filterQueryOp.operator+" "+e},s.toFunction=function(e){var n=this._fnNode1.dataType||W.fromValue(this._value),r=t(e,this._filterQueryOp,n),i=this._fnNode1.fn;if(void 0!==this.fnNode2||this._valueIsLiteral||(this.fnNode2=me.create(this._value,e)),this.fnNode2){var a=this.fnNode2.fn;return function(t){return r(i(t),a(t))}}var o=this._value;return function(t){return r(i(t),o)}},s.toString=function(){return A("{%1} %2 {%3}",this._propertyOrExpr,this._filterQueryOp.operator,this._value)},s.validate=function(t){this._fnNode1.validate(t),this.dataType=this._fnNode1.dataType},o}(),Te=function(){function t(t,e,n){var r,i;switch(e){case ve.Not:return r=n[0].toFunction(t),function(t){return!r(t)};case ve.And:return i=n.map(function(e){return e.toFunction(t)}),function(t){var e=i.reduce(function(e,n){return e&&n(t)},!0);return e};case ve.Or:return i=n.map(function(e){return e.toFunction(t)}),function(t){var e=i.reduce(function(e,n){return e||n(t)},!1);return e};default:throw Error("Invalid boolean operator:"+e)}}var e=function(t,e){if(!Array.isArray(e))throw Error("predicates parameter must be an array");if("not"===this.symbol&&1!==e.length)throw Error("Only a single predicate can be passed in with the 'Not' operator");if(this._booleanQueryOp=ve.from(t),!this._booleanQueryOp)throw Error("Unknown query operation: "+t);this._predicates=e},n=new Pe({prototype:!0});return e.prototype=n,n.toOdataFragment=function(t){if(1==this._predicates.length)return this._booleanQueryOp.operator+" "+"("+this._predicates[0].toOdataFragment(t)+")";var e=this._predicates.map(function(e){return"("+e.toOdataFragment(t)+")"}).join(" "+this._booleanQueryOp.operator+" ");return e},n.toFunction=function(e){return t(e,this._booleanQueryOp,this._predicates)},n.toString=function(){if(1==this._predicates.length)return this._booleanQueryOp.operator+" "+"("+this._predicates[0]+")";var t=this._predicates.map(function(t){return"("+(""+t)+")"}).join(" "+this._booleanQueryOp.operator+" ");return t},n.validate=function(t){this._isValidated||(this._predicates.every(function(e){e.validate(t)}),this._isValidated=!0)},e}(),Se=function(){var t=function(e,n){return e.prototype===!0?this:t.create(e,n)},e=t.prototype;return t.create=function(t,e){if(t.length>1){var n=t.map(function(t){return new _e(t,e)});return new be(n)}return new _e(t[0],e)},t.combine=function(t){return new be(t)},t.isOrderByClause=function(t){return t instanceof Se},e.addClause=function(t){return new be([this,t])},t}(),_e=function(){var t=function(t,e){if("string"!=typeof t)throw Error("propertyPath is not a string");t=t.trim();var n=t.split(" ");if(n.length>1&&e!==!0&&e!==!1&&(e=O(n[1].toLowerCase(),"desc"),!e)){var r=O(n[1].toLowerCase(),"asc");if(!r)throw Error("the second word in the propertyPath must begin with 'desc' or 'asc'")}this.propertyPath=n[0],this.isDesc=e},e=new Se({prototype:!0});return t.prototype=e,e.validate=function(t){t&&(this.lastProperty=t.getProperty(this.propertyPath,!0))},e.toOdataFragment=function(t){return t._clientPropertyPathToServer(this.propertyPath)+(this.isDesc?" desc":"")},e.getComparer=function(){var t=this.propertyPath,e=this.isDesc,n=this;return function(r,i){var a=F(r,t),o=F(i,t),s=(n.lastProperty||{}).dataType;if(s===W.String)n.lastProperty.parentType.metadataStore.localQueryComparisonOptions.isCaseSensitive||(a=(a||"").toLowerCase(),o=(o||"").toLowerCase());else{var u=R(s);a=u(a),o=u(o)}return a==o?0:a>o?e?-1:1:e?1:-1}},t}(),be=function(){var t=function(t){var e=[];t.forEach(function(t){if(t instanceof be)e=e.concat(t.orderByClauses);else{if(!(t instanceof _e))throw Error("Invalid argument to CompositeOrderByClause ctor.");e.push(t)}}),this._orderByClauses=e},e=new Se({prototype:!0});return t.prototype=e,e.validate=function(t){this._orderByClauses.forEach(function(e){e.validate(t)})},e.toOdataFragment=function(t){var e=this._orderByClauses.map(function(e){return e.toOdataFragment(t)});return e.join(",")},e.getComparer=function(){var t=this._orderByClauses.map(function(t){return t.getComparer()});return function(e,n){for(var r=0;t.length>r;r++){var i=t[r](e,n);if(0!=i)return i}return 0}},t}(),we=function(){var t=function(t){this.propertyPaths=t,this._pathNames=t.map(function(t){return t.replace(".","_")})},e=t.prototype;return e.validate=function(t){t&&this.propertyPaths.forEach(function(e){t.getProperty(e,!0)})},e.toOdataFragment=function(t){var e=this.propertyPaths.map(function(e){return t._clientPropertyPathToServer(e)}).join(",");return e},e.toFunction=function(){var t=this;return function(e){var n={};return t.propertyPaths.forEach(function(r,i){n[t._pathNames[i]]=F(e,r)}),n}},t}(),Ne=function(){var t=function(t){this.propertyPaths=t},e=t.prototype;return e.toOdataFragment=function(t){var e=this.propertyPaths.map(function(e){return t._clientPropertyPathToServer(e)}).join(",");return e},t}();te.prototype.loadNavigationProperty=function(t,e,n){var r=this.entity,i=r.entityType._checkNavProperty(t),a=he.fromEntityNavigation(r,i,e,n);return r.entityAspect.entityManager.executeQuery(a,e,n)},V.FilterQueryOp=ge,V.Predicate=Pe,V.EntityQuery=he,V.FnNode=me,V.OrderByClause=Se;var Oe=function(){function t(t,e,n){var r=e.name+".."+e.parentType.name,i=t._tempIdMap[r];return i||n&&(i={entityType:e.parentType,propertyName:e.name,keyMap:{}},t._tempIdMap[r]=i),i}function e(t,e){if(e.isNumeric)return n(t);if(e===W.String)return this.stringPrefix+(""+n(t));if(e===W.Guid)return v();if(e===W.DateTime)return Date.now();throw Error("Cannot use a property with a dataType of: "+(""+e)+" for id generation")}function n(t){var e=t.nextNumber;return t.nextNumber+=t.nextNumberIncrement,e}var r=function(){this._tempIdMap={},this.nextNumber=-1,this.nextNumberIncrement=-1,this.stringPrefix="K_"},i=r.prototype;return i.generateTempKeyValue=function(n){var r=n.keyProperties;if(r.length>1)throw Error("Ids can not be autogenerated for entities with multipart keys");var i=r[0],a=e(this,i.dataType),o=t(this,i,!0);return o.keyMap[""+a]=null,a},i.getTempKeys=function(){var t=[];for(var e in this._tempIdMap){var n=this._tempIdMap[e],r=n.entityType;for(var i in n.keyMap)t.push(new ne(r,[i]))}return t},i.isTempKey=function(e){var n=e.entityType.keyProperties;if(n.length>1)return!1;var r=n[0],i=t(this,r);return i?void 0!==i.keyMap[""+e.values[0]]:!1},Q.registerType(r,"KeyGenerator"),r}();V.KeyGenerator=Oe,V.makeRelationArray=function(){function t(t,n){var r=e(t,n);if(!r.length)return r;var i=t.parentEntity,a=i.entityAspect.entityManager;return a&&!a.isLoading&&r.forEach(function(e){if(e.entityAspect.entityState.isDetached()){t._inProgress=!0;try{a.attachEntity(e,Y.Added)}finally{t._inProgress=!1}}}),r}function e(t,e){var n=t.navigationProperty.inverse,r=e.filter(function(e){if(t._addsInProcess.indexOf(e)>=0)return!1;var r=e.getProperty(n.name);return r!=t.parentEntity});return r}function n(t,e){var n=t.navigationProperty.inverse;if(n){var i=t._addsInProcess,a=i.length;try{e.forEach(function(e){i.push(e),e.setProperty(n.name,t.parentEntity)})}finally{i.splice(a,e.length)}}r(t,"arrayChanged",{relationArray:t,added:e})}function r(t,e,n){var r=t._getPendingPubs();r?t._pendingArgs?i(t._pendingArgs,n):(t._pendingArgs=n,r.push(function(){t[e].publish(t._pendingArgs),t._pendingArgs=null})):t[e].publish(n)}function i(t,e){for(var n in e)if("relationArray"!==n&&t.hasOwnProperty(n)){var r=e[n],i=t[n];if(i){if(!Array.isArray(i))throw Error("Cannot combine non array args");Array.prototype.push.apply(i,r)}else t[n]=r}}function a(t,e){var n=t.navigationProperty.inverse;n&&e.forEach(function(t){t.setProperty(n.name,null)}),r(t,"arrayChanged",{relationArray:t,removed:e})}function s(t,e,n){return t.parentEntity=e,t.navigationProperty=n,t.arrayChanged=new G("arrayChanged_entityCollection",t),t._addsInProcess=[],o(t,u)}var u={};return u.push=function(){if(this._inProgress)return-1;var e=t(this,Array.prototype.slice.call(arguments));if(!e.length)return this.length;var r=Array.prototype.push.apply(this,e);return n(this,e),r},u.unshift=function(){var e=t(this,Array.prototype.slice.call(arguments));if(!e.length)return this.length;var r=Array.prototype.unshift.apply(this,e);return n(this,Array.prototype.slice.call(e)),r},u.pop=function(){var t=Array.prototype.pop.apply(this);return a(this,[t]),t},u.shift=function(){var t=Array.prototype.shift.apply(this);return a(this,[t]),t},u.splice=function(){var e=t(this,Array.prototype.slice.call(arguments,2)),r=Array.prototype.slice.call(arguments,0,2).concat(e),i=Array.prototype.splice.apply(this,r);return a(this,i),e.length&&n(this,e),i},u.load=function(t,e){var n=this.parentEntity,r=he.fromEntityNavigation(this.parentEntity,this.navigationProperty),i=n.entityAspect.entityManager;return i.executeQuery(r,t,e)},u._getEventParent=function(){return this.parentEntity.entityAspect},u._getPendingPubs=function(){var t=this.parentEntity.entityAspect.entityManager;return t&&t._pendingPubs},s}();var Ce=function(){function e(t,e){if(t.length!=e.length)return!1;for(var n=0,r=t.length;r>n;n++)if(t[n]!==e[n])return!1;return!0}function n(t,e){return B(e,"entityTypes").isString().isOptional().or().isNonEmptyArray().isString().or().isInstanceOf(pe).or().isNonEmptyArray().isInstanceOf(pe).check(),"string"==typeof e?e=t.metadataStore.getEntityType(e,!1):Array.isArray(e)&&"string"==typeof e[0]&&(e=e.map(function(e){return t.metadataStore.getEntityType(e,!1)})),e}function r(t,e){if(e[0]instanceof ne)return{entityKey:e[0],remainingArgs:Array.prototype.slice.call(e,1)};if("string"==typeof e[0]&&e.length>=2){var n=t.metadataStore.getEntityType(e[0],!1);return{entityKey:new ne(n,e[1]),remainingArgs:Array.prototype.slice.call(e,2)}}throw Error("This method requires as its initial parameters either an EntityKey or an entityType name followed by a value or an array of values.")}function o(t,e){t.forEach(function(t){t.entityAspect.isBeingSaved=e})}function s(e,n){var r;n?(r={},n.forEach(function(t){var e=r[t.entityType.name];e||(e={},e.entityType=t.entityType,e._entities=[],r[t.entityType.name]=e),e._entities.push(t)})):r=e._entityGroupMap;var i=[],a={};return t(r,function(t,e){a[t]=p(e,i)}),{entityGroupMap:a,tempKeys:i}}function p(t,e){var n={},r=t.entityType,a=r.dataProperties.map(i("name"));n.dataPropertyNames=a;var o=[];return t._entities.forEach(function(t){if(t){var n=[];a.forEach(function(e){n.push(t.getProperty(e))});var r=t.entityAspect,i=r.entityState,s={tempNavPropNames:l(r,e),entityState:i.name};(i.isModified()||i.isDeleted())&&(s.originalValuesMap=r.originalValues),n.push(s),o.push(n)}}),n.entities=o,n}function l(t,e){var n=t.entity;t.hasTempKey&&e.push(t.getKey().toJSON());var r;return n.entityType.navigationProperties.forEach(function(t){if(t.relatedDataProperties){var e=n.getProperty(t.name);e&&e.entityAspect.hasTempKey&&(r=r||[],r.push(t.name))}}),r}function f(t,e,n){var r=n.tempKeyMap,i=t.entityType,a=n.mergeStrategy===xe.OverwriteChanges,o=null,s=e.dataPropertyNames,u=s.map(function(t){return i.getProperty(t)}),p=i.keyProperties.map(function(t){return s.indexOf(t.name)}),c=s.length,y=t.entityManager.entityChanged;e.entities.forEach(function(e){var n,s=e[c],l=p.map(function(t){return e[t]}),f=new ne(i,l),h=Y.fromName(s.entityState);if(h.isAdded()?(n=r[""+f],o=void 0===n?t.findEntityByKey(f):null):o=t.findEntityByKey(f),o){var d=o.entityAspect.entityState.isUnchanged();a||d?(u.forEach(function(t,n){t.dataType==W.DateTime?o.setProperty(t.name,new Date(Date.parse(e[n]))):o.setProperty(t.name,e[n])}),y.publish({entityAction:Z.MergeOnImport,entity:o}),d?h.isUnchanged()||t.entityManager._notifyStateChange(o,!0):h.isUnchanged()&&t.entityManager._notifyStateChange(o,!1)):o=null}else o=i._createEntityCore(),u.forEach(function(t,n){t.dataType==W.DateTime?o.setProperty(t.name,new Date(Date.parse(e[n]))):o.setProperty(t.name,e[n])}),void 0!==n&&(o.setProperty(i.keyProperties[0].name,n),s.tempNavPropNames&&s.tempNavPropNames.forEach(function(t){var e=i.getNavigationProperty(t),n=e.relatedDataProperties[0].name,a=o.getProperty(n),s=new ne(e.entityType,[a]),u=r[""+s];o.setProperty(n,u)})),o.entityAspect._postInitialize(),o=t.attachEntity(o,h),y&&(y.publish({entityAction:Z.AttachOnImport,entity:o}),h.isUnchanged()||t.entityManager._notifyStateChange(o,!0));o&&(o.entityAspect.entityState=h,h.isModified()&&(o.entityAspect.originalValuesMap=s.originalValues),t.entityManager._linkRelatedEntities(o))})}function h(t,e,n){return t=t.then(function(t){return e&&e(t),re.resolve(t)}).fail(function(t){return n&&n(t),re.reject(t)})}function g(t,e){var n;return n=e?e.filter(function(e){if(e.entityAspect.entityManager!==t)throw Error("Only entities in this entityManager may be saved");return!e.entityAspect.entityState.isDetached()}):t.getChanges()}function P(t,e){e.forEach(function(e){var n=pe._getNormalizedTypeName(e.EntityTypeName),r=t._entityGroupMap[n];r._fixupKey(e.TempValue,e.RealValue)})}function E(t,e){function n(){return Error("The EntityManager.getChanges() 'entityTypes' parameter must be either an entityType or an array of entityTypes or null")}var r=t._entityGroupMap;if(e){if(e instanceof pe)return[r[e.name]];if(Array.isArray(e))return e.map(function(t){if(t instanceof pe)return r[t.name];throw n()});throw n()}return a(r)}function S(t,e){var n=e.entityAspect.getKey(),r=y(e.entityType.keyProperties,n.values,function(t,e){return t.defaultValue===e?t:null}).filter(function(t){return null!==t});if(r.length)if(e.entityType.autoGeneratedKeyType!==fe.None)t.generateTempKeyValue(e);else if(r.length===n.values.length)throw Error("Cannot attach an object to an EntityManager without first setting its key or setting its entityType 'AutoGeneratedKeyType' property to something other than 'None'")}function _(t,e){function n(){return Error("The EntityManager.getChanges() 'entityStates' parameter must either be null, an entityState or an array of entityStates")}if(!e)return null;if(Y.contains(e))e=[e];else{if(!Array.isArray(e))throw n();e.forEach(function(t){if(!Y.contains(t))throw n()})}return e}function b(t,e,n){var r=J(t,e.entityType);r.attachEntity(e,n),t._linkRelatedEntities(e)}function N(t,e,n){var r=e.entityType.navigationProperties;r.forEach(function(r){var i=e.getProperty(r.name);if(r.isScalar){if(!i)return;t.attachEntity(i,n)}else i.forEach(function(e){t.attachEntity(e,n)})})}function O(t,e){try{var n=t.metadataStore,r=e.dataService||t.dataService;if(n.isEmpty()&&r.hasServerMetadata)throw Error("cannot execute _executeQueryCore until metadataStore is populated.");var i=e.queryOptions||t.queryOptions||ke.defaultInstance;if(i.fetchStrategy==Me.FromLocalCache)return re.fcall(function(){var n=t.executeQueryLocally(e);return{results:n,query:e}});var a=e._getJsonResultsAdapter&&e._getJsonResultsAdapter(t)||r.jsonResultsAdapter,o=$(e,n),s={query:e,entityManager:t,dataService:r,mergeStrategy:i.mergeStrategy,jsonResultsAdapter:a,refMap:{},deferredFns:[]},u=re.defer(),p=t.validationOptions.validateOnQuery,c=u.promise;return r.adapterInstance.executeQuery(t,o,function(n){var r=m(function(){var e={isLoading:t.isLoading};return t.isLoading=!0,t._pendingPubs=[],e},function(n){t.isLoading=n.isLoading,t._pendingPubs.forEach(function(t){t()}),t._pendingPubs=null,e=null,s=null,n.error&&u.reject(n.error)},function(){var t=a.extractResults(n);Array.isArray(t)||(t=[t]);var r=t.map(function(t){var e=C(t,s,{nodeType:"root"});return p&&e.entityAspect&&e.entityAspect.validateEntity(),e});return s.deferredFns.length>0&&s.deferredFns.forEach(function(t){t()}),{results:r,query:e,XHR:n.XHR,inlineCount:n.inlineCount}});u.resolve(r)},function(t){t&&(t.query=e),u.reject(t)}),c}catch(y){return y&&(y.query=e),re.reject(y)}}function C(t,e,n){n=n||{};var r=e.jsonResultsAdapter.visitNode(t,e,n);return e.query&&n.isTopLevel&&!r.entityType&&(r.entityType=e.query._getToEntityType&&e.query._getToEntityType(e.entityManager.metadataStore)),A(t,e,r)}function A(t,e,n,r){if(n.ignore||null==t)return null;if(n.nodeRefId){var i=x(n.nodeRefId,e);return"function"==typeof i?(e.deferredFns.push(function(){r(i)}),void 0):i}return n.entityType?M(t,e,n):(n.nodeId&&(e.refMap[n.nodeId]=t),"object"==typeof t?k(t,e):t)}function x(t,e){var n=e.refMap[t];return void 0===n?function(){return e.refMap[t]}:n}function M(t,e,n){t._$meta=n;var r=n.entityType;t.entityType=r;var i=e.entityManager,a=e.mergeStrategy,o=null==e.query,s=ne._fromRawEntity(t,r),u=i.findEntityByKey(s);if(u){if(o&&u.entityAspect.entityState.isDeleted())return i.detachEntity(u),u;var p=u.entityAspect.entityState;if(a===xe.OverwriteChanges||p.isUnchanged()){I(u,t,e),u.entityAspect.wasLoaded=!0,u.entityAspect.entityState=Y.Unchanged,u.entityAspect.originalValues={},u.entityAspect.propertyChanged.publish({entity:u,propertyName:null});var c=o?Z.MergeOnSave:Z.MergeOnQuery;i.entityChanged.publish({entityAction:c,entity:u}),p.isUnchanged||i._notifyStateChange(u,!1)}else D(e,u,t),r.navigationProperties.forEach(function(n){n.isScalar?F(t,n,e):K(t,n,e)})}else u=r._createEntityCore(),u.initializeFrom&&u.initializeFrom(t),I(u,t,e),u.entityAspect._postInitialize(),b(i,u,Y.Unchanged),u.entityAspect.wasLoaded=!0,i.entityChanged.publish({entityAction:Z.AttachOnQuery,entity:u});return u}function k(e,n){var r=n.entityManager,i=n.jsonResultsAdapter,a=r.metadataStore.namingConvention.serverPropertyNameToClient,o={};return t(e,function(t,e){var r=i.visitNode(e,n,{nodeType:"anonProp",propertyName:t});if(!r.ignore){var s=a(t);o[s]=Array.isArray(e)?e.map(function(e,a){return r=i.visitNode(e,n,{nodeType:"anonPropItem",propertyName:t}),A(e,n,r,function(t){o[s][a]=t()})}):A(e,n,r,function(t){o[s]=t()})}}),o}function I(t,e,n){D(n,t,e);var r=t.entityType;r.dataProperties.forEach(function(n){if(!n.isUnmapped){var r=e[n.nameOnServer];if(n.dataType===W.DateTime&&r)T(r)||(r=W.parseDateFromServer(r));else if(n.dataType==W.Binary)r&&void 0!==r.$value&&(r=r.$value);else if(n.isComplexProperty&&void 0!=r){var i=t.getProperty(n.name);n.dataType.dataProperties.forEach(function(t){i.setProperty(t.name,r[t.nameOnServer])})}n.isComplexProperty||t.setProperty(n.name,r)}}),r.navigationProperties.forEach(function(r){r.isScalar?j(r,t,e,n):V(r,t,e,n)})}function D(t,e,n){var r=n._$meta.nodeId;null!=r&&(t.refMap[r]=e)}function j(t,e,n,r){var i=F(n,t,r);null!=i&&("function"==typeof i?r.deferredFns.push(function(){i=i(),R(i,e,t)}):R(i,e,t))}function F(t,e,n){var r=t[e.nameOnServer];if(!r)return null;var i=C(r,n,{nodeType:"navProp",navigationProperty:e});return i}function R(t,e,n){if(t){var r=n.name,i=e.getProperty(r);if(i!=t){e.setProperty(r,t);var a=n.inverse;if(!a)return;if(a.isScalar)t.setProperty(a.name,e);else{var o=t.getProperty(a.name);o.push(e)}}}}function V(t,e,n,r){var i=K(n,t,r);if(null!=i){var a=t.inverse;if(a){var o=e.getProperty(t.name);o.wasLoaded=!0,i.forEach(function(t){"function"==typeof t?r.deferredFns.push(function(){t=t(),L(t,o,e,a)}):L(t,o,e,a)})}}}function K(t,e,n){var r=t[e.nameOnServer];if(!r)return null;if(!Array.isArray(r))return null;var i=r.map(function(t){return C(t,n,{nodeType:"navPropItem",navigationProperty:e})});return i}function L(t,e,n,r){if(t){var i=t.getProperty(r.name);i!==n&&(e.push(t),t.setProperty(r.name,n))}}function q(t){var e=t.filter(function(t){return t.entityAspect.isBeingSaved=!0,t.entityAspect.entityState.isModified()&&t.entityType.concurrencyProperties.length>0});0!==e.length&&e.forEach(function(t){t.entityType.concurrencyProperties.forEach(function(e){z(t,e)})})}function z(t,e){if(!t.entityAspect.originalValues[e.name]){var n=t.getProperty(e.name);if(n||(n=e.dataType.defaultValue),e.dataType.isNumeric)t.setProperty(e.name,n+1);else if(e.dataType===W.DateTime){for(var r=new Date,i=new Date;r==i;)i=new Date;t.setProperty(e.name,i)}else{if(e.dataType!==W.Guid){if(e.dataType===W.Binary)return;throw Error("Unable to update the value of concurrency property before saving: "+e.name)}t.setProperty(e.name,v())}}}function $(t,e){if(!t)throw Error("query cannot be empty");if("string"==typeof t)return t; if(t instanceof he)return t._toUri(e);throw Error("unable to recognize query parameter as either a string or an EntityQuery")}function J(t,e){var n=t._entityGroupMap[e.name];return n||(n=new Ae(t,e),t._entityGroupMap[e.name]=n),n}function H(t,e){var n=t.map(function(t){var n=X(t),r=null;t.entityType.autoGeneratedKeyType!==fe.None&&(r={propertyName:t.entityType.keyProperties[0].nameOnServer,autoGeneratedKeyType:t.entityType.autoGeneratedKeyType.name});var i=ee(t,e);return n.entityAspect={entityTypeName:t.entityType.name,entityState:t.entityAspect.entityState.name,originalValuesMap:i,autoGeneratedKey:r},n});return n}function X(t){var e={},n=t.entityType||t.complexType;return n.dataProperties.forEach(function(n){e[n.nameOnServer]=n.isComplexProperty?X(t.getProperty(n.name)):t.getProperty(n.name)}),e}function ee(e,n){var r=e.entityType||e.complexType,i=e.entityAspect||e.complexAspect,a=n.namingConvention.clientPropertyNameToServer,o={};return t(i.originalValues,function(t,e){var n=r.getProperty(t);o[a(t,n)]=e}),r.complexProperties.forEach(function(t){var r=e.getProperty(t.name),i=ee(r,n);w(i)||(o[a(t.name,t)]=i)}),o}function ie(){this.map={}}var ae=function(t){if(arguments.length>1)throw Error("The EntityManager ctor has a single optional argument that is either a 'serviceName' or a configuration object.");0===arguments.length?t={serviceName:""}:"string"==typeof t&&(t={serviceName:t}),U(t).whereParam("serviceName").isOptional().isString().whereParam("dataService").isOptional().isInstanceOf(se).whereParam("metadataStore").isInstanceOf(oe).isOptional().withDefault(new oe).whereParam("queryOptions").isInstanceOf(ke).isOptional().withDefault(ke.defaultInstance).whereParam("saveOptions").isInstanceOf(Ie).isOptional().withDefault(Ie.defaultInstance).whereParam("validationOptions").isInstanceOf(De).isOptional().withDefault(De.defaultInstance).whereParam("keyGeneratorCtor").isFunction().isOptional().withDefault(Oe).applyAll(this),t.serviceName&&(this.dataService=new se({serviceName:this.serviceName})),this.serviceName=this.dataService&&this.dataService.serviceName,this.entityChanged=new G("entityChanged_entityManager",this),this.hasChangesChanged=new G("hasChangesChanged_entityManager",this),this.clear()},ue=ae.prototype;return ue._$typeName="EntityManager",G.bubbleEvent(ue,null),ue.createEntity=function(t,e,n){n=n||Y.Added;var r=this.metadataStore.getEntityType(t).createEntity(e);return n!==Y.Detached&&this.attachEntity(r,n),r},ae.importEntities=function(t,e){var n=new Ce;return n.importEntities(t,e),n},ue.exportEntities=function(t){var e=s(this,t),n={metadataStore:this.metadataStore.exportMetadata(),dataService:this.dataService,saveOptions:this.saveOptions,queryOptions:this.queryOptions,validationOptions:this.validationOptions,tempKeys:e.tempKeys,entityGroupMap:e.entityGroupMap},r=JSON.stringify(n,null,Q.stringifyPad);return r},ue.importEntities=function(e,n){n=n||{},U(n).whereParam("mergeStrategy").isEnumOf(xe).isOptional().withDefault(this.queryOptions.mergeStrategy).applyAll(n);var r=this,i=JSON.parse(e);this.metadataStore.importMetadata(i.metadataStore),this.dataService=i.dataService&&se.fromJSON(i.dataService)||new se({serviceName:i.serviceName}),this.saveOptions=new Ie(i.saveOptions),this.queryOptions=ke.fromJSON(i.queryOptions),this.validationOptions=new De(i.validationOptions);var a={};return i.tempKeys.forEach(function(t){var e=ne.fromJSON(t,r.metadataStore);a[""+e]=r.keyGenerator.generateTempKeyValue(e.entityType)}),n.tempKeyMap=a,m(function(){r._pendingPubs=[]},function(){r._pendingPubs.forEach(function(t){t()}),r._pendingPubs=null},function(){t(i.entityGroupMap,function(t,e){var i=r.metadataStore.getEntityType(t,!0),a=J(r,i);f(a,e,n)})}),this},ue.clear=function(){t(this._entityGroupMap,function(t,e){e._clear()}),this._entityGroupMap={},this._unattachedChildrenMap=new ie,this.keyGenerator=new this.keyGeneratorCtor,this.entityChanged.publish({entityAction:Z.Clear}),this._hasChanges&&(this._hasChanges=!1,this.hasChangesChanged.publish({entityManager:this,hasChanges:!1}))},ue.setProperties=function(t){U(t).whereParam("serviceName").isString().isOptional().whereParam("dataService").isInstanceOf(se).isOptional().whereParam("queryOptions").isInstanceOf(ke).isOptional().whereParam("saveOptions").isInstanceOf(Ie).isOptional().whereParam("validationOptions").isInstanceOf(De).isOptional().whereParam("keyGeneratorCtor").isOptional().applyAll(this),t.serviceName&&(this.dataService=new se({serviceName:this.serviceName})),this.serviceName=this.dataService&&this.dataService.serviceName,t.keyGeneratorCtor&&(this.keyGenerator=new this.keyGeneratorCtor)},ue.createEmptyCopy=function(){var t=new ae({dataService:this.dataService,metadataStore:this.metadataStore,queryOptions:this.queryOptions,saveOptions:this.saveOptions,validationOptions:this.validationOptions,keyGeneratorCtor:this.keyGeneratorCtor});return t},ue.addEntity=function(t){return this.attachEntity(t,Y.Added)},ue.attachEntity=function(t,e){if(B(t,"entity").isRequired().check(),this.metadataStore._checkEntityType(t),e=B(e,"entityState").isEnumOf(Y).isOptional().check(Y.Unchanged),t.entityType.metadataStore!=this.metadataStore)throw Error("Cannot attach this entity because the EntityType and MetadataStore associated with this entity does not match this EntityManager's MetadataStore.");var n=t.entityAspect;n||(n=new te(t),n._postInitialize(t));var r=n.entityManager;if(r){if(r==this)return t;throw Error("This entity already belongs to another EntityManager")}var i=this;return d(this,"isLoading",!0,function(){e.isAdded()&&S(i,t),b(i,t,e),N(i,t,e)}),this.validationOptions.validateOnAttach&&t.entityAspect.validateEntity(),e.isUnchanged()||this._notifyStateChange(t,!0),this.entityChanged.publish({entityAction:Z.Attach,entity:t}),t},ue.detachEntity=function(t){B(t,"entity").isEntity().check();var e=t.entityAspect;if(!e)return!1;var n=e.entityGroup;if(!n)return!1;if(n.entityManager!==this)throw Error("This entity does not belong to this EntityManager.");return n.detachEntity(t),e._removeFromRelations(),this.entityChanged.publish({entityAction:Z.Detach,entity:t}),e._detach(),!0},ue.fetchMetadata=function(t,e){B(t,"callback").isFunction().isOptional().check(),B(e,"errorCallback").isFunction().isOptional().check();var n=this.metadataStore.fetchMetadata(this.dataService);return h(n,t,e)},ue.executeQuery=function(t,e,n){B(t,"query").isInstanceOf(he).or().isString().check(),B(e,"callback").isFunction().isOptional().check(),B(n,"errorCallback").isFunction().isOptional().check();var r;if(!this.dataService.hasServerMetadata||this.metadataStore.hasMetadataFor(this.dataService.serviceName))r=O(this,t);else{var i=this;r=this.fetchMetadata().then(function(){return O(i,t)}).fail(function(t){return re.reject(t)})}return h(r,e,n)},ue.executeQueryLocally=function(t){B(t,"query").isInstanceOf(he).check();var e,n=this.metadataStore,r=t._getFromEntityType(n,!0),i=J(this,r),a=t._toFilterFunction(r);if(a){var o=function(t){return t&&!t.entityAspect.entityState.isDeleted()&&a(t)};e=i._entities.filter(o)}else e=i._entities.filter(function(t){return t&&!t.entityAspect.entityState.isDeleted()});var s=t._toOrderByComparer(r);s&&e.sort(s);var u=t.skipCount;u&&(e=e.slice(u));var p=t.takeCount;p&&(e=e.slice(0,p));var c=t.selectClause;if(c){var y=c.toFunction();e=e.map(function(t){return y(t)})}return e},ue.saveChanges=function(t,n,r,i){B(t,"entities").isOptional().isArray().isEntity().check(),B(n,"saveOptions").isInstanceOf(Ie).isOptional().check(),B(r,"callback").isFunction().isOptional().check(),B(i,"errorCallback").isFunction().isOptional().check(),n=n||this.saveOptions||Ie.defaultInstance;var a=null==t,s=g(this,t);if(0==s.length){var u={entities:[],keyMappings:[]};return r&&r(u),re.resolve(u)}if(!n.allowConcurrentSaves){var p=s.some(function(t){return t.entityAspect.isBeingSaved});if(p){var c=Error("ConcurrentSaves not allowed - SaveOptions.allowConcurrentSaves is false");return i&&i(c),re.reject(c)}}if(this.validationOptions.validateOnSave){var y=s.filter(function(t){var e=t.entityAspect,n=e.entityState.isDeleted()||e.validateEntity();return!n});if(y.length>0){var l=Error("Validation error");return l.entitiesWithErrors=y,i&&i(l),re.reject(l)}}q(s);var f={entities:H(s,this.metadataStore),saveOptions:n},h=JSON.stringify(f),d=re.defer();this.dataService.adapterInstance.saveChanges(this,h,d.resolve,d.reject);var m=this;return d.promise.then(function(t){var n={entities:t.Entities,keyMappings:t.KeyMappings,XHR:t.XHR};P(m,n.keyMappings);var i={query:null,entityManager:m,jsonResultsAdapter:m.dataService.jsonResultsAdapter,mergeStrategy:xe.OverwriteChanges,refMap:{},deferredFns:[]},u=n.entities.map(function(t){return C(t,i,{nodeType:"root"})});return o(s,!1),m._hasChanges=a&&e(s,u)?!1:m._hasChangesCore(),m._hasChanges||m.hasChangesChanged.publish({entityManager:m,hasChanges:!1}),n.entities=u,r&&r(n),re.resolve(n)},function(t){return o(s,!1),i&&i(t),re.reject(t)})},ue.findEntityGroup=function(t){return B(t,"entityType").isInstanceOf(pe).check(),this._entityGroupMap[t.name]},ue.getEntityByKey=function(){var t=r(this,arguments).entityKey,e=this.findEntityGroup(t.entityType);return e?e.findEntityByKey(t):null},ue.fetchEntityByKey=function(){var t,e=r(this,arguments),n=e.entityKey,i=0===e.remainingArgs.length?!1:!!e.remainingArgs[0],a=!1;return i&&(t=this.getEntityByKey(n),a=t&&t.entityAspect.entityState.isDeleted(),a&&(t=null,this.queryOptions.mergeStrategy===xe.OverwriteChanges&&(a=!1))),t||a?re.resolve({entity:t,entityKey:n,fromCache:!0}):he.fromEntityKey(n).using(this).execute().then(function(e){return t=0===e.results.length?null:e.results[0],re.resolve({entity:t,entityKey:n,fromCache:!1})})},ue.findEntityByKey=function(t){return this.getEntityByKey(t)},ue.generateTempKeyValue=function(t){B(t,"entity").isEntity().check();var e=t.entityType,n=this.keyGenerator.generateTempKeyValue(e),r=e.keyProperties[0];return t.setProperty(r.name,n),t.entityAspect.hasTempKey=!0,n},ue.hasChanges=function(t){return this._hasChanges?void 0===t?this._hasChanges:this._hasChangesCore(t):!1},ue._hasChangesCore=function(t){t=n(this,t);var e=E(this,t);return e.some(function(t){return t.hasChanges()})},ue.getChanges=function(t){t=n(this,t);var e=[Y.Added,Y.Modified,Y.Deleted];return this._getEntitiesCore(t,e)},ue.rejectChanges=function(){if(!this._hasChanges)return[];var t=[Y.Added,Y.Modified,Y.Deleted],e=this._getEntitiesCore(null,t);return this._hasChanges=!1,e.forEach(function(t){t.entityAspect.rejectChanges()}),this.hasChangesChanged.publish({entityManager:this,hasChanges:!1}),e},ue.getEntities=function(t,e){return t=n(this,t),B(e,"entityStates").isOptional().isEnumOf(Y).or().isNonEmptyArray().isEnumOf(Y).check(),e&&(e=_(this,e)),this._getEntitiesCore(t,e)},ue._notifyStateChange=function(t,e){this.entityChanged.publish({entityAction:Z.EntityStateChange,entity:t}),e?this._hasChanges||(this._hasChanges=!0,this.hasChangesChanged.publish({entityManager:this,hasChanges:!0})):this._hasChanges&&(this._hasChanges=this._hasChangesCore(),this._hasChanges||this.hasChangesChanged.publish({entityManager:this,hasChanges:!1}))},ue._getEntitiesCore=function(t,e){var n,r=E(this,t);return r.forEach(function(t){if(t){var r=t.getEntities(e);n?n.push.apply(n,r):n=r}}),n||[]},ue._addUnattachedChild=function(t,e,n){var r=""+t,i=this._unattachedChildrenMap[r];i||(i=[],this._unattachedChildrenMap[r]=i),i.push(n)},ue._linkRelatedEntities=function(t){var e=this,n=t.entityAspect;d(e,"isLoading",!0,function(){var r=t.entityType,i=r.navigationProperties,a=e._unattachedChildrenMap;i.forEach(function(r){if(r.isScalar){var i=t.getProperty(r.name);if(i)return}var o=n.getParentKey(r);if(o){if(o._isEmpty())return;var s=e.findEntityByKey(o);s?t.setProperty(r.name,s):a.addChild(o,r,t)}else{var u=n.getKey(),p=r.inverse;if(!p)return;var c=a.getChildren(u,p);if(!c)return;if(r.isScalar){var y=c[0];t.setProperty(r.name,y),y.setProperty(p.name,t)}else{var l=t.getProperty(r.name);c.forEach(function(e){l.push(e),e.setProperty(p.name,t)})}a.removeChildren(u,r)}})})},ie.prototype.addChild=function(t,e,n){var r=this.getTuple(t,e);if(!r){var i=this.map[""+t];i||(i=[],this.map[""+t]=i),r={navigationProperty:e,children:[]},i.push(r)}r.children.push(n)},ie.prototype.removeChildren=function(t,e){var n=this.map[""+t];n&&(c(n,function(t){return t.navigationProperty===e}),n.length||delete this.map[""+t])},ie.prototype.getChildren=function(t,e){var n=this.getTuple(t,e);return n?n.children.filter(function(t){return!t.entityAspect.entityState.isDetached()}):null},ie.prototype.getTuple=function(t,e){var n=this.map[""+t];if(!n)return null;var r=u(n,function(t){return t.navigationProperty===e});return r},ae}(),Ae=function(){function t(t){if(t){if(1===t.length){var e=t[0];return function(t){return t?t.entityAspect.entityState===e:!1}}return function(e){return e?t.some(function(t){return e.entityAspect.entityState===t}):!1}}return function(t){return!!t}}var e=t([Y.Added,Y.Modified,Y.Deleted]),n=function(t,e){this.entityManager=t,this.entityType=e,this._indexMap={},this._entities=[],this._emptyIndexes=[]},r=n.prototype;return r.attachEntity=function(t,e){var n,r=t.entityAspect,i=r.getKey()._keyInGroup;if(n=this._indexMap[i],n>=0){if(this._entities[n]===t)return t;throw Error("This key is already attached: "+r.getKey())}return 0===this._emptyIndexes.length?n=this._entities.push(t)-1:(n=this._emptyIndexes.pop(),this._entities[n]=t),this._indexMap[i]=n,r.entityState=e,r.entityGroup=this,r.entityManager=this.entityManager,t},r.detachEntity=function(t){var e=t.entityAspect,n=e.getKey()._keyInGroup,r=this._indexMap[n];if(void 0===r)throw Error("internal error - entity cannot be found in group");return delete this._indexMap[n],this._emptyIndexes.push(r),this._entities[r]=null,t},r.findEntityByKey=function(t){var e;e=t instanceof ne?t._keyInGroup:ne.createKeyString(t);var n=this._indexMap[e];return void 0!==n?this._entities[n]:null},r.hasChanges=function(){return this._entities.some(e)},r.getEntities=function(e){var n=t(e),r=this._entities.filter(n);return r},r._clear=function(){this._entities.forEach(function(t){null!=t&&t.entityAspect._detach()}),this._entities=null,this._indexMap=null,this._emptyIndexes=null},r._fixupKey=function(t,e){var n=this._indexMap[t];if(void 0===n)throw Error("Internal Error in key fixup - unable to locate entity");var r=this._entities[n],i=r.entityType.keyProperties[0].name;r.setProperty(i,e),delete r.entityAspect.hasTempKey,delete this._indexMap[t],this._indexMap[e]=n},r._replaceKey=function(t,e){var n=this._indexMap[t._keyInGroup];delete this._indexMap[t._keyInGroup],this._indexMap[e._keyInGroup]=n},n}();V.EntityManager=Ce;var xe=function(){var t=new $("MergeStrategy");return t.PreserveChanges=t.addSymbol(),t.OverwriteChanges=t.addSymbol(),t.seal(),t}(),Me=function(){var t=new $("FetchStrategy");return t.FromServer=t.addSymbol(),t.FromLocalCache=t.addSymbol(),t.seal(),t}(),ke=function(){function t(t,e){return e&&U(e).whereParam("fetchStrategy").isEnumOf(Me).isOptional().whereParam("mergeStrategy").isEnumOf(xe).isOptional().applyAll(t),t}var e=function(e){this.fetchStrategy=Me.FromServer,this.mergeStrategy=xe.PreserveChanges,t(this,e)},n=e.prototype;return n._$typeName="QueryOptions",e.defaultInstance=new e,n.using=function(e){var n=new ke(this);return xe.contains(e)?e={mergeStrategy:e}:Me.contains(e)&&(e={fetchStrategy:e}),t(n,e)},n.setAsDefault=function(){return e.defaultInstance=this,this},n.toJSON=function(){return s(this)},e.fromJSON=function(t){return new ke({fetchStrategy:Me.fromName(t.fetchStrategy),mergeStrategy:xe.fromName(t.mergeStrategy)})},e}(),Ie=function(){var t=function(t){t=t||{},U(t).whereParam("allowConcurrentSaves").isBoolean().isOptional().withDefault(!1).whereParam("tag").isOptional().applyAll(this)},e=t.prototype;return e._$typeName="SaveOptions",e.setAsDefault=function(){return t.defaultInstance=this,this},t.defaultInstance=new t,t}(),De=function(){function t(t,e){return e&&U(e).whereParam("validateOnAttach").isBoolean().isOptional().whereParam("validateOnSave").isBoolean().isOptional().whereParam("validateOnQuery").isBoolean().isOptional().whereParam("validateOnPropertyChange").isBoolean().isOptional().applyAll(t),t}var e=function(e){this.validateOnAttach=!0,this.validateOnSave=!0,this.validateOnQuery=!1,this.validateOnPropertyChange=!0,t(this,e)},n=e.prototype;return n._$typeName="ValidationOptions",n.using=function(e){var n=new De(this);return t(n,e),n},n.setAsDefault=function(){return e.defaultInstance=this,this},e.defaultInstance=new e,e}();V.QueryOptions=ke,V.SaveOptions=Ie,V.ValidationOptions=De,V.FetchStrategy=Me,V.MergeStrategy=xe,function(t){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?t(require("breeze")):"function"==typeof define&&define.amd?V?t(V):define(["breeze"],t):t(V)}(function(t){var e,n=t.core,r=function(){this.name="jQuery",this.defaultSettings={}};r.prototype.initialize=function(){e=n.requireLib("jQuery","needed for 'ajax_jQuery' pluggin")},r.prototype.ajax=function(t){if(n.isEmpty(this.defaultSettings))e.ajax(t);else{var r=n.extend({},this.defaultSettings);n.extend(r,t),e.ajax(r)}},t.config.registerAdapter("ajax",r)}),function(t){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?t(require("breeze")):"function"==typeof define&&define.amd&&!V?define(["breeze"],t):t(V)}(function(t){function e(t){var e=t;return i.stringEndsWith(e,"/")&&(e=e.substr(0,e.length-1)),i.stringEndsWith(e,"/$metadata")||(e+="/$metadata"),e}function n(t){var e=Error(),n=t.response;if(e.message=n.statusText,e.statusText=n.statusText,e.status=n.statusCode,e.body=n.body,e.requestUri=n.requestUri,n.body)try{var r=JSON.parse(n.body);e.detail=r,e.message=r.error.message.value}catch(i){}return e}var r,i=t.core,a=t.EntityType,o=t.JsonResultsAdapter,s=function(){this.name="OData"};s.prototype.initialize=function(){r=i.requireLib("OData","Needed to support remote OData services"),r.jsonHandler.recognizeDates=!0},s.prototype.executeQuery=function(t,e,i,a){var o=t.serviceName+e;r.read(o,function(t){i({results:t.results,inlineCount:t.__count})},function(t){a&&a(n(t))})},s.prototype.fetchMetadata=function(t,i,a,o){var s=i.serviceName,u=e(s);r.read(u,function(e){if(!e||!e.dataServices){var n=Error("Metadata query failed for: "+u);onError?onError(n):a(n)}var r=e.dataServices.schema;t.hasMetadataFor(s)||(t._parseODataMetadata(s,r),t.addDataService(i)),a&&a(r)},function(t){var e=n(t);e.message="Metadata query failed for: "+u+"; "+(e.message||""),o&&o(e)},r.metadataHandler)},s.prototype.saveChanges=function(){throw Error("Breeze does not yet support saving thru OData")},s.prototype.jsonResultsAdapter=new o({name:"OData_default",visitNode:function(t,e,n){var r={};if(null!=t.__metadata){var o=a._getNormalizedTypeName(t.__metadata.type),s=o&&e.entityManager.metadataStore.getEntityType(o,!0);s&&s._mappedPropertiesCount===Object.keys(t).length-1&&(r.entityType=s)}var u=n.propertyName;return r.ignore=null!=t.__deferred||"__metadata"==u||"EntityKey"==u&&t.$type&&i.stringStartsWith(t.$type,"System.Data"),r}}),t.config.registerAdapter("dataService",s)}),function(t){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?t(require("breeze")):"function"==typeof define&&define.amd&&!V?define(["breeze"],t):t(V)}(function(t){function e(t){var e=t;return a.stringEndsWith(e,"/")&&(e=e.substr(0,e.length-1)),a.stringEndsWith(e,"/Metadata")||(e+="/Metadata"),e}function n(t,e,n){if(e){var i=r(t);n&&(i.message=n+"; "+ +i.message),e(i),t.onreadystatechange=null,t.abort=null}}function r(t){var e=Error();if(e.XHR=t,e.message=t.statusText,e.responseText=t.responseText,e.status=t.status,e.statusText=t.statusText,e.responseText)try{var n=JSON.parse(t.responseText);e.detail=n;var r=n.InnerException||n;e.message=r.ExceptionMessage||r.Message||t.responseText}catch(i){}return e}var i,a=t.core,o=t.EntityType,s=t.JsonResultsAdapter,u=function(){this.name="webApi"};u.prototype.checkForRecomposition=function(t){"ajax"===t.interfaceName&&t.isDefault&&this.initialize()},u.prototype.initialize=function(){if(i=t.config.getAdapterInstance("ajax"),!i)throw Error("Unable to initialize ajax for WebApi.");var e=i.ajax;if(!e)throw Error("Breeze was unable to find an 'ajax' adapter")},u.prototype.fetchMetadata=function(t,r,a,o){var s=r.serviceName,u=e(s);i.ajax({url:u,dataType:"json",success:function(e,n,i){var p=JSON.parse(e);if(!p)return o&&o(Error("Metadata query failed for: "+u)),void 0;var c=p.schema;return c?(t.hasMetadataFor(s)||(t._parseODataMetadata(s,c),t.addDataService(r)),a&&a(c),i.onreadystatechange=null,i.abort=null,void 0):(o&&o(Error("Metadata query failed for "+u+"; Unable to locate 'schema' member in metadata")),void 0)},error:function(t){n(t,o,"Metadata query failed for: "+u)}})},u.prototype.executeQuery=function(t,e,a,o){var s=t.serviceName+e;i.ajax({url:s,dataType:"json",success:function(t,e,n){try{var i=n.getResponseHeader("X-InlineCount");i&&(i=parseInt(i,10)),a({results:t,XHR:n,inlineCount:i}),n.onreadystatechange=null,n.abort=null}catch(s){var u=s instanceof Error?s:r(n);o&&o(u),n.onreadystatechange=null,n.abort=null}},error:function(t){n(t,o)}})},u.prototype.saveChanges=function(t,e,a,o){var s=t.serviceName+"SaveChanges";i.ajax({url:s,type:"POST",dataType:"json",contentType:"application/json",data:e,success:function(t,e,n){if(t.Error){var i=r(n);i.message=t.Error,o(i)}else t.XHR=n,a(t)},error:function(t){n(t,o)}})},u.prototype.jsonResultsAdapter=new s({name:"webApi_default",visitNode:function(t,e,n){var r=o._getNormalizedTypeName(t.$type),i=r&&e.entityManager.metadataStore.getEntityType(r,!0),a=n.propertyName,s=a&&"$"===a.substr(0,1);return{entityType:i,nodeId:t.$id,nodeRefId:t.$ref,ignore:s}}}),t.config.registerAdapter("dataService",u)}),function(t){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?t(require("breeze")):"function"==typeof define&&define.amd&&!V?define(["breeze"],t):t(V)}(function(t){var e=t.core;t.ComplexAspect;var n,r,i,a,o=Object.prototype.hasOwnProperty,s=function(){this.name="backbone"};s.prototype.initialize=function(){n=e.requireLib("Backbone"),r=e.requireLib("_;underscore"),i=n.Model.prototype.set,a=n.Model.prototype.get},s.prototype.createCtor=function(e){var r={};e.dataProperties.forEach(function(t){r[t.name]=t.defaultValue});var i=n.Model.extend({defaults:r,initialize:function(){if(e.navigationProperties){var r=this;e.navigationProperties.forEach(function(e){if(!e.isScalar){var i=t.makeRelationArray([],r,e);n.Model.prototype.set.call(r,e.name,i)}})}}});return i},s.prototype.getTrackablePropertyNames=function(t){var e=[];for(var n in t.attributes)e.push(n);return e},s.prototype.initializeEntityPrototype=function(t){t.getProperty=function(t){return this.get(t)},t.setProperty=function(t,e){return this.set(t,e),this},t.set=function(t,e,n){var s=this.entityAspect||this.complexAspect;if(!s)return i.call(this,t,e,n);var u,p,c,y=this,l=this.entityType||this.complexType;if(r.isObject(t)||null==t){if(u=t,n=e,!this._validate(u,n))return!1;for(c in u)if(o.call(u,c)){if(p=l.getProperty(c),null==p)throw Error("Unknown property: "+t);this._$interceptor(p,u[c],function(t){return 0===arguments.length?a.call(y,c):i.call(y,c,t,n)})}}else{if(u={},u[t]=e,n||(n={}),!this._validate(u,n))return!1;if(p=l.getProperty(t),null==p)throw Error("Unknown property: "+t);c=t,this._$interceptor(p,e,function(t){return 0===arguments.length?a.call(y,c):i.call(y,c,t,n)})}return this}},s.prototype.startTracking=function(r){if(!(r instanceof n.Model))throw Error("This entity is not an Backbone.Model instance");var o=r.entityType||r.complexType,s=r.attributes;o.dataProperties.forEach(function(t){if(t.isComplexProperty){var e=t.dataType._createInstanceCore(r,t.name);i.call(r,t.name,e)}else t.name in s?void 0===a.call(r,t.name)&&void 0!==t.defaultValue&&i.call(r,t.name,t.defaultValue):i.call(r,t.name,t.defaultValue)}),o.navigationProperties&&o.navigationProperties.forEach(function(n){var o;if(n.name in s){var u=a.call(r,n.name);if(n.isScalar){if(u&&!u.entityType)throw o=e.formatString("The value of the '%1' property for entityType: '%2' must be either null or another entity",n.name,r.entityType.name),Error(o)}else if(u){if(!u.parentEntity)throw o=e.formatString("The value of the '%1' property for entityType: '%2' must be either null or a Breeze relation array",n.name,r.entityType.name),Error(o)}else u=t.makeRelationArray([],r,n),i.call(r,n.name,u)}else n.isScalar?i.call(r,n.name,null):(u=t.makeRelationArray([],r,n),i.call(r,n.name,u))})},t.config.registerAdapter("modelLibrary",s)}),function(t){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?t(require("breeze")):"function"==typeof define&&define.amd&&!V?define(["breeze"],t):t(V)}(function(t){function e(t){var e=t.entityType||t.complexType;e.getProperties().forEach(function(e){var n=e.name;t[n]||Object.defineProperty(t,n,r(e))})}function n(t){var e=Object.getPrototypeOf(t);t._backingStore||(t._backingStore={});var n=e.entityType||e.complexType;return n.getProperties().forEach(function(e){var n=e.name;if(t.hasOwnProperty(n)){var r=t[n];delete t[n],t[n]=r}}),t._backingStore}function r(t){var e=t.name,n=function(t){return function(){return 0==arguments.length?t[e]:(t[e]=arguments[0],void 0)}};return{get:function(){var t=this._backingStore;if(t||(this._pendingSets.process(),t=this._backingStore))return t[e]},set:function(r){var i=this._backingStore;if(!i)return this._pendingSets.schedule(this,e,r),void 0;var a=n(i);this._$interceptor?this._$interceptor(t,r,a):a(r)},enumerable:!0,configurable:!0}}var i=t.core;t.ComplexAspect;var a=function(){this.name="backingStore"};a.prototype.initialize=function(){},a.prototype.getTrackablePropertyNames=function(t){var e=[];for(var n in t)if("_$typeName"!==n){var r=t[n];i.isFunction(r)||e.push(n)}return e},a.prototype.initializeEntityPrototype=function(t){t.getProperty=function(t){return this[t]},t.setProperty=function(t,e){if(!this._backingStore.hasOwnProperty(t))throw Error("Unknown property name:"+t);return this[t]=e,this},t.initializeFrom=function(t){var e=this;this.entityType.unmappedProperties.forEach(function(n){var r=n.name;t[r]=e[r]}),this._backingStore||(this._backingStore={})},t._pendingSets=[],t._pendingSets.schedule=function(t,e,n){if(this.push({entity:t,propName:e,value:n}),!this.isPending){this.isPending=!0;var r=this;setTimeout(function(){r.process()})}},t._pendingSets.process=function(){0!==this.length&&(this.forEach(function(t){t.entity._backingStore||(t.entity._backingStore={}),t.entity._backingStore[t.propName]=t.value}),this.length=0,this.isPending=!1)},e(t)},a.prototype.startTracking=function(e,r){r._pendingSets.process();var i=n(e),a=e.entityType||e.complexType;a.getProperties().forEach(function(n){var r=n.name,a=e[r];if(n.isDataProperty)if(n.isComplexProperty){var o=n.dataType._createInstanceCore(e,n.name);i[r]=o}else void 0===a&&(i[r]=n.defaultValue);else{if(!n.isNavigationProperty)throw Error("unknown property: "+r);if(void 0!==a)throw Error("Cannot assign a navigation property in an entity ctor.: "+n.Name);i[r]=n.isScalar?null:t.makeRelationArray([],e,n)}})},t.config.registerAdapter("modelLibrary",a)}),function(t){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?t(require("breeze")):"function"==typeof define&&define.amd&&!V?define(["breeze"],t):t(V)}(function(t){function e(t){t._koObj._suppressBreeze=!0}function n(t){var e=t.relationArray._koObj;e._suppressBreeze?e._suppressBreeze=!1:e.valueHasMutated()}var r,i=t.core,a=function(){this.name="ko"};a.prototype.initialize=function(){r=i.requireLib("ko","The Knockout library"),r.extenders.intercept=function(t,e){var n,i=e.instance,a=e.property;return n=t.splice?r.computed({read:t}):r.computed({read:t,write:function(e){return i._$interceptor(a,e,t),i}})}},a.prototype.getTrackablePropertyNames=function(t){var e=[];for(var n in t)if("entityType"!==n&&"_$typeName"!==n){var a=t[n];r.isObservable(a)?e.push(n):i.isFunction(a)||e.push(n)}return e},a.prototype.initializeEntityPrototype=function(t){t.getProperty=function(t){return this[t]()},t.setProperty=function(t,e){return this[t](e),this}},a.prototype.startTracking=function(i){var a=i.entityType||i.complexType;a.getProperties().sort(function(t,e){var n=t.isUnmapped?1:0,r=e.isUnmapped?1:0;return n-r}).forEach(function(a){var o,s=a.name,u=i[s];if(r.isObservable(u)){if(a.isNavigationProperty)throw Error("Cannot assign a navigation property in an entity ctor.: "+a.Name);o=u}else if(a.isDataProperty)a.isComplexProperty?u=a.dataType._createInstanceCore(i,a.name):void 0===u&&(u=a.defaultValue),o=r.observable(u);else{if(!a.isNavigationProperty)throw Error("unknown property: "+s);if(void 0!==u)throw Error("Cannot assign a navigation property in an entity ctor.: "+a.Name);a.isScalar?o=r.observable(null):(u=t.makeRelationArray([],i,a),o=r.observableArray(u),u._koObj=o,o.subscribe(e,null,"beforeChange"),u.arrayChanged.subscribe(n),o.equalityComparer=function(){throw Error("Collection navigation properties may NOT be set.")})}if(a.isNavigationProperty&&!a.isScalar)i[s]=o;else{var p=o.extend({intercept:{instance:i,property:a}});i[s]=p}})},t.config.registerAdapter("modelLibrary",a)}),V.config.initializeAdapterInstances({ajax:"jQuery",dataService:"webApi"});var je=window.ko;return!je&&window.require&&(je=window.require("ko")),je?V.config.initializeAdapterInstance("modelLibrary","ko"):V.config.initializeAdapterInstance("modelLibrary","backingStore"),this.window.breeze=V,V});
mival/cdnjs
ajax/libs/breezejs/1.2.5/breeze.min.js
JavaScript
mit
125,755
import Enumerator from '../enumerator'; /** `Promise.all` accepts an array of promises, and returns a new promise which is fulfilled with an array of fulfillment values for the passed promises, or rejected with the reason of the first passed promise to be rejected. It casts all elements of the passed iterable to promises as it runs this algorithm. Example: ```javascript var promise1 = resolve(1); var promise2 = resolve(2); var promise3 = resolve(3); var promises = [ promise1, promise2, promise3 ]; Promise.all(promises).then(function(array){ // The array here would be [ 1, 2, 3 ]; }); ``` If any of the `promises` given to `all` are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. For example: Example: ```javascript var promise1 = resolve(1); var promise2 = reject(new Error("2")); var promise3 = reject(new Error("3")); var promises = [ promise1, promise2, promise3 ]; Promise.all(promises).then(function(array){ // Code here never runs because there are rejected promises! }, function(error) { // error.message === "2" }); ``` @method all @static @param {Array} entries array of promises @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} promise that is fulfilled when all `promises` have been fulfilled, or rejected if any of them become rejected. @static */ export default function all(entries) { return new Enumerator(this, entries).promise; }
Vrturo/PTP
node_modules/gulp-autoprefixer/node_modules/postcss/node_modules/es6-promise/lib/es6-promise/promise/all.js
JavaScript
mit
1,571
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "\u4e0a\u5348", "\u4e0b\u5348" ], "DAY": [ "\u661f\u671f\u65e5", "\u661f\u671f\u4e00", "\u661f\u671f\u4e8c", "\u661f\u671f\u4e09", "\u661f\u671f\u56db", "\u661f\u671f\u4e94", "\u661f\u671f\u516d" ], "ERANAMES": [ "\u516c\u5143\u524d", "\u516c\u5143" ], "ERAS": [ "BC", "AD" ], "FIRSTDAYOFWEEK": 6, "MONTH": [ "1\u6708", "2\u6708", "3\u6708", "4\u6708", "5\u6708", "6\u6708", "7\u6708", "8\u6708", "9\u6708", "10\u6708", "11\u6708", "12\u6708" ], "SHORTDAY": [ "\u9031\u65e5", "\u9031\u4e00", "\u9031\u4e8c", "\u9031\u4e09", "\u9031\u56db", "\u9031\u4e94", "\u9031\u516d" ], "SHORTMONTH": [ "1\u6708", "2\u6708", "3\u6708", "4\u6708", "5\u6708", "6\u6708", "7\u6708", "8\u6708", "9\u6708", "10\u6708", "11\u6708", "12\u6708" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "y\u5e74M\u6708d\u65e5EEEE", "longDate": "y\u5e74M\u6708d\u65e5", "medium": "y\u5e74M\u6708d\u65e5 ah:mm:ss", "mediumDate": "y\u5e74M\u6708d\u65e5", "mediumTime": "ah:mm:ss", "short": "d/M/yy ah:mm", "shortDate": "d/M/yy", "shortTime": "ah:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "$", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "\u00a4-", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "zh-hk", "pluralCat": function(n, opt_precision) { return PLURAL_CATEGORY.OTHER;} }); }]);
gaearon/cdnjs
ajax/libs/angular.js/1.4.2/i18n/angular-locale_zh-hk.js
JavaScript
mit
2,293
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "\u4e0a\u5348", "\u4e0b\u5348" ], "DAY": [ "\u661f\u671f\u65e5", "\u661f\u671f\u4e00", "\u661f\u671f\u4e8c", "\u661f\u671f\u4e09", "\u661f\u671f\u56db", "\u661f\u671f\u4e94", "\u661f\u671f\u516d" ], "ERANAMES": [ "\u516c\u5143\u524d", "\u516c\u5143" ], "ERAS": [ "\u516c\u5143\u524d", "\u516c\u5143" ], "FIRSTDAYOFWEEK": 6, "MONTH": [ "\u4e00\u6708", "\u4e8c\u6708", "\u4e09\u6708", "\u56db\u6708", "\u4e94\u6708", "\u516d\u6708", "\u4e03\u6708", "\u516b\u6708", "\u4e5d\u6708", "\u5341\u6708", "\u5341\u4e00\u6708", "\u5341\u4e8c\u6708" ], "SHORTDAY": [ "\u5468\u65e5", "\u5468\u4e00", "\u5468\u4e8c", "\u5468\u4e09", "\u5468\u56db", "\u5468\u4e94", "\u5468\u516d" ], "SHORTMONTH": [ "1\u6708", "2\u6708", "3\u6708", "4\u6708", "5\u6708", "6\u6708", "7\u6708", "8\u6708", "9\u6708", "10\u6708", "11\u6708", "12\u6708" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "y\u5e74M\u6708d\u65e5EEEE", "longDate": "y\u5e74M\u6708d\u65e5", "medium": "y\u5e74M\u6708d\u65e5 ah:mm:ss", "mediumDate": "y\u5e74M\u6708d\u65e5", "mediumTime": "ah:mm:ss", "short": "yy/M/d ah:mm", "shortDate": "yy/M/d", "shortTime": "ah:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "\u00a5", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "\u00a4\u00a0-", "negSuf": "", "posPre": "\u00a4\u00a0", "posSuf": "" } ] }, "id": "zh-hans-cn", "pluralCat": function(n, opt_precision) { return PLURAL_CATEGORY.OTHER;} }); }]);
BitsyCode/cdnjs
ajax/libs/angular-i18n/1.4.3/angular-locale_zh-hans-cn.js
JavaScript
mit
2,410
/* Native method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max, nativeMin = Math.min; /** * Gets the view, applying any `transforms` to the `start` and `end` positions. * * @private * @param {number} start The start of the view. * @param {number} end The end of the view. * @param {Array} [transforms] The transformations to apply to the view. * @returns {Object} Returns an object containing the `start` and `end` * positions of the view. */ function getView(start, end, transforms) { var index = -1, length = transforms ? transforms.length : 0; while (++index < length) { var data = transforms[index], size = data.size; switch (data.type) { case 'drop': start += size; break; case 'dropRight': end -= size; break; case 'take': end = nativeMin(end, start + size); break; case 'takeRight': start = nativeMax(start, end - size); break; } } return { 'start': start, 'end': end }; } module.exports = getView;
aykutdemirel/law-site
node_modules/lodash/internal/getView.js
JavaScript
mit
1,041
/** * @license * Lodash <https://lodash.com/> * Copyright JS Foundation and other contributors <https://js.foundation/> * Released under MIT license <https://lodash.com/license> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ ;(function() { /** Used as a safe reference for `undefined` in pre-ES5 environments. */ var undefined; /** Used as the semantic version number. */ var VERSION = '4.17.4'; /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Error message constants. */ var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', FUNC_ERROR_TEXT = 'Expected a function'; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; /** Used as default options for `_.truncate`. */ var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = '...'; /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800, HOT_SPAN = 16; /** Used to indicate the type of lazy iteratees. */ var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 1.7976931348623157e+308, NAN = 0 / 0; /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; /** Used to associate wrap methods with their bit flags. */ var wrapFlags = [ ['ary', WRAP_ARY_FLAG], ['bind', WRAP_BIND_FLAG], ['bindKey', WRAP_BIND_KEY_FLAG], ['curry', WRAP_CURRY_FLAG], ['curryRight', WRAP_CURRY_RIGHT_FLAG], ['flip', WRAP_FLIP_FLAG], ['partial', WRAP_PARTIAL_FLAG], ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], ['rearg', WRAP_REARG_FLAG] ]; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', asyncTag = '[object AsyncFunction]', boolTag = '[object Boolean]', dateTag = '[object Date]', domExcTag = '[object DOMException]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', nullTag = '[object Null]', objectTag = '[object Object]', promiseTag = '[object Promise]', proxyTag = '[object Proxy]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', undefinedTag = '[object Undefined]', weakMapTag = '[object WeakMap]', weakSetTag = '[object WeakSet]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to match empty string literals in compiled template source. */ var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; /** Used to match HTML entities and HTML characters. */ var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, reUnescapedHtml = /[&<>"']/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); /** Used to match template delimiters. */ var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, reLeadingDot = /^\./, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source); /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g, reTrimStart = /^\s+/, reTrimEnd = /\s+$/; /** Used to match wrap detail comments. */ var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; /** Used to match words composed of alphanumeric characters. */ var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Used to match * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). */ var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** Used to match Latin Unicode letters (excluding mathematical operators). */ var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; /** Used to ensure capturing order of template delimiters. */ var reNoMatch = /($^)/; /** Used to match unescaped characters in compiled string literals. */ var reUnescapedString = /['\n\r\u2028\u2029\\]/g; /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f', reComboHalfMarksRange = '\\ufe20-\\ufe2f', rsComboSymbolsRange = '\\u20d0-\\u20ff', rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsDingbatRange = '\\u2700-\\u27bf', rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', rsPunctuationRange = '\\u2000-\\u206f', rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', rsVarRange = '\\ufe0e\\ufe0f', rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; /** Used to compose unicode capture groups. */ var rsApos = "['\u2019]", rsAstral = '[' + rsAstralRange + ']', rsBreak = '[' + rsBreakRange + ']', rsCombo = '[' + rsComboRange + ']', rsDigits = '\\d+', rsDingbat = '[' + rsDingbatRange + ']', rsLower = '[' + rsLowerRange + ']', rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsUpper = '[' + rsUpperRange + ']', rsZWJ = '\\u200d'; /** Used to compose unicode regexes. */ var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange + ']?', rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', rsOrdLower = '\\d*(?:(?:1st|2nd|3rd|(?![123])\\dth)\\b)', rsOrdUpper = '\\d*(?:(?:1ST|2ND|3RD|(?![123])\\dTH)\\b)', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match apostrophes. */ var reApos = RegExp(rsApos, 'g'); /** * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). */ var reComboMark = RegExp(rsCombo, 'g'); /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** Used to match complex or compound words. */ var reUnicodeWord = RegExp([ rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, rsUpper + '+' + rsOptContrUpper, rsOrdUpper, rsOrdLower, rsDigits, rsEmoji ].join('|'), 'g'); /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); /** Used to detect strings that need a more robust regexp to match words. */ var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; /** Used to assign default `context` object properties. */ var contextProps = [ 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' ]; /** Used to make template sourceURLs easier to identify. */ var templateCounter = -1; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; /** Used to map Latin Unicode letters to basic Latin letters. */ var deburredLetters = { // Latin-1 Supplement block. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', '\xc7': 'C', '\xe7': 'c', '\xd0': 'D', '\xf0': 'd', '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', '\xd1': 'N', '\xf1': 'n', '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', '\xc6': 'Ae', '\xe6': 'ae', '\xde': 'Th', '\xfe': 'th', '\xdf': 'ss', // Latin Extended-A block. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', '\u0134': 'J', '\u0135': 'j', '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', '\u0163': 't', '\u0165': 't', '\u0167': 't', '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', '\u0174': 'W', '\u0175': 'w', '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', '\u0132': 'IJ', '\u0133': 'ij', '\u0152': 'Oe', '\u0153': 'oe', '\u0149': "'n", '\u017f': 's' }; /** Used to map characters to HTML entities. */ var htmlEscapes = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }; /** Used to map HTML entities to characters. */ var htmlUnescapes = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#39;': "'" }; /** Used to escape characters for inclusion in compiled string literals. */ var stringEscapes = { '\\': '\\', "'": "'", '\n': 'n', '\r': 'r', '\u2028': 'u2028', '\u2029': 'u2029' }; /** Built-in method references without a dependency on `root`. */ var freeParseFloat = parseFloat, freeParseInt = parseInt; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); /* Node.js helper references. */ var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet = nodeUtil && nodeUtil.isSet, nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /*--------------------------------------------------------------------------*/ /** * Adds the key-value `pair` to `map`. * * @private * @param {Object} map The map to modify. * @param {Array} pair The key-value pair to add. * @returns {Object} Returns `map`. */ function addMapEntry(map, pair) { // Don't return `map.set` because it's not chainable in IE 11. map.set(pair[0], pair[1]); return map; } /** * Adds `value` to `set`. * * @private * @param {Object} set The set to modify. * @param {*} value The value to add. * @returns {Object} Returns `set`. */ function addSetEntry(set, value) { // Don't return `set.add` because it's not chainable in IE 11. set.add(value); return set; } /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } /** * A specialized version of `baseAggregator` for arrays. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function arrayAggregator(array, setter, iteratee, accumulator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { var value = array[index]; setter(accumulator, value, iteratee(value), array); } return accumulator; } /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } /** * A specialized version of `_.forEachRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEachRight(array, iteratee) { var length = array == null ? 0 : array.length; while (length--) { if (iteratee(array[length], length, array) === false) { break; } } return array; } /** * A specialized version of `_.every` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. */ function arrayEvery(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (!predicate(array[index], index, array)) { return false; } } return true; } /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && baseIndexOf(array, value, 0) > -1; } /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } /** * A specialized version of `_.reduceRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the last element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduceRight(array, iteratee, accumulator, initAccum) { var length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[--length]; } while (length--) { accumulator = iteratee(accumulator, array[length], length, array); } return accumulator; } /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * Gets the size of an ASCII `string`. * * @private * @param {string} string The string inspect. * @returns {number} Returns the string size. */ var asciiSize = baseProperty('length'); /** * Converts an ASCII `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function asciiToArray(string) { return string.split(''); } /** * Splits an ASCII `string` into an array of its words. * * @private * @param {string} The string to inspect. * @returns {Array} Returns the words of `string`. */ function asciiWords(string) { return string.match(reAsciiWord) || []; } /** * The base implementation of methods like `_.findKey` and `_.findLastKey`, * without support for iteratee shorthands, which iterates over `collection` * using `eachFunc`. * * @private * @param {Array|Object} collection The collection to inspect. * @param {Function} predicate The function invoked per iteration. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the found element or its key, else `undefined`. */ function baseFindKey(collection, predicate, eachFunc) { var result; eachFunc(collection, function(value, key, collection) { if (predicate(value, key, collection)) { result = key; return false; } }); return result; } /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); } /** * This function is like `baseIndexOf` except that it accepts a comparator. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @param {Function} comparator The comparator invoked per element. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOfWith(array, value, fromIndex, comparator) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (comparator(array[index], value)) { return index; } } return -1; } /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } /** * The base implementation of `_.mean` and `_.meanBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the mean. */ function baseMean(array, iteratee) { var length = array == null ? 0 : array.length; return length ? (baseSum(array, iteratee) / length) : NAN; } /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * The base implementation of `_.propertyOf` without support for deep paths. * * @private * @param {Object} object The object to query. * @returns {Function} Returns the new accessor function. */ function basePropertyOf(object) { return function(key) { return object == null ? undefined : object[key]; }; } /** * The base implementation of `_.reduce` and `_.reduceRight`, without support * for iteratee shorthands, which iterates over `collection` using `eachFunc`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initAccum Specify using the first or last element of * `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } /** * The base implementation of `_.sortBy` which uses `comparer` to define the * sort order of `array` and replaces criteria objects with their corresponding * values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } /** * The base implementation of `_.sum` and `_.sumBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { var current = iteratee(array[index]); if (current !== undefined) { result = result === undefined ? current : (result + current); } } return result; } /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } /** * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array * of key-value pairs for `object` corresponding to the property names of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the key-value pairs. */ function baseToPairs(object, props) { return arrayMap(props, function(key) { return [key, object[key]]; }); } /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return arrayMap(props, function(key) { return object[key]; }); } /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } /** * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the first unmatched string symbol. */ function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the last unmatched string symbol. */ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Gets the number of `placeholder` occurrences in `array`. * * @private * @param {Array} array The array to inspect. * @param {*} placeholder The placeholder to search for. * @returns {number} Returns the placeholder count. */ function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { if (array[length] === placeholder) { ++result; } } return result; } /** * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A * letters to basic Latin letters. * * @private * @param {string} letter The matched letter to deburr. * @returns {string} Returns the deburred letter. */ var deburrLetter = basePropertyOf(deburredLetters); /** * Used by `_.escape` to convert characters to HTML entities. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ var escapeHtmlChar = basePropertyOf(htmlEscapes); /** * Used by `_.template` to escape characters for inclusion in compiled string literals. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeStringChar(chr) { return '\\' + stringEscapes[chr]; } /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } /** * Checks if `string` contains Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a symbol is found, else `false`. */ function hasUnicode(string) { return reHasUnicode.test(string); } /** * Checks if `string` contains a word composed of Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a word is found, else `false`. */ function hasUnicodeWord(string) { return reHasUnicodeWord.test(string); } /** * Converts `iterator` to an array. * * @private * @param {Object} iterator The iterator to convert. * @returns {Array} Returns the converted array. */ function iteratorToArray(iterator) { var data, result = []; while (!(data = iterator.next()).done) { result.push(data.value); } return result; } /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value === placeholder || value === PLACEHOLDER) { array[index] = PLACEHOLDER; result[resIndex++] = index; } } return result; } /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } /** * Converts `set` to its value-value pairs. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the value-value pairs. */ function setToPairs(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = [value, value]; }); return result; } /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } /** * A specialized version of `_.lastIndexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictLastIndexOf(array, value, fromIndex) { var index = fromIndex + 1; while (index--) { if (array[index] === value) { return index; } } return index; } /** * Gets the number of symbols in `string`. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the string size. */ function stringSize(string) { return hasUnicode(string) ? unicodeSize(string) : asciiSize(string); } /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); } /** * Used by `_.unescape` to convert HTML entities to characters. * * @private * @param {string} chr The matched character to unescape. * @returns {string} Returns the unescaped character. */ var unescapeHtmlChar = basePropertyOf(htmlUnescapes); /** * Gets the size of a Unicode `string`. * * @private * @param {string} string The string inspect. * @returns {number} Returns the string size. */ function unicodeSize(string) { var result = reUnicode.lastIndex = 0; while (reUnicode.test(string)) { ++result; } return result; } /** * Converts a Unicode `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function unicodeToArray(string) { return string.match(reUnicode) || []; } /** * Splits a Unicode `string` into an array of its words. * * @private * @param {string} The string to inspect. * @returns {Array} Returns the words of `string`. */ function unicodeWords(string) { return string.match(reUnicodeWord) || []; } /*--------------------------------------------------------------------------*/ /** * Create a new pristine `lodash` function using the `context` object. * * @static * @memberOf _ * @since 1.1.0 * @category Util * @param {Object} [context=root] The context object. * @returns {Function} Returns a new `lodash` function. * @example * * _.mixin({ 'foo': _.constant('foo') }); * * var lodash = _.runInContext(); * lodash.mixin({ 'bar': lodash.constant('bar') }); * * _.isFunction(_.foo); * // => true * _.isFunction(_.bar); * // => false * * lodash.isFunction(lodash.foo); * // => false * lodash.isFunction(lodash.bar); * // => true * * // Create a suped-up `defer` in Node.js. * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; */ var runInContext = (function runInContext(context) { context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); /** Built-in constructor references. */ var Array = context.Array, Date = context.Date, Error = context.Error, Function = context.Function, Math = context.Math, Object = context.Object, RegExp = context.RegExp, String = context.String, TypeError = context.TypeError; /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = context['__core-js_shared__']; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to generate unique IDs. */ var idCounter = 0; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** Used to restore the original `_` reference in `_.noConflict`. */ var oldDash = root._; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Built-in value references. */ var Buffer = moduleExports ? context.Buffer : undefined, Symbol = context.Symbol, Uint8Array = context.Uint8Array, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, getPrototype = overArg(Object.getPrototypeOf, Object), objectCreate = Object.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, symIterator = Symbol ? Symbol.iterator : undefined, symToStringTag = Symbol ? Symbol.toStringTag : undefined; var defineProperty = (function() { try { var func = getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); /** Mocked built-ins. */ var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, ctxNow = Date && Date.now !== root.Date.now && Date.now, ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil, nativeFloor = Math.floor, nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, nativeIsFinite = context.isFinite, nativeJoin = arrayProto.join, nativeKeys = overArg(Object.keys, Object), nativeMax = Math.max, nativeMin = Math.min, nativeNow = Date.now, nativeParseInt = context.parseInt, nativeRandom = Math.random, nativeReverse = arrayProto.reverse; /* Built-in method references that are verified to be native. */ var DataView = getNative(context, 'DataView'), Map = getNative(context, 'Map'), Promise = getNative(context, 'Promise'), Set = getNative(context, 'Set'), WeakMap = getNative(context, 'WeakMap'), nativeCreate = getNative(Object, 'create'); /** Used to store function metadata. */ var metaMap = WeakMap && new WeakMap; /** Used to lookup unminified function names. */ var realNames = {}; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /*------------------------------------------------------------------------*/ /** * Creates a `lodash` object which wraps `value` to enable implicit method * chain sequences. Methods that operate on and return arrays, collections, * and functions can be chained together. Methods that retrieve a single value * or may return a primitive value will automatically end the chain sequence * and return the unwrapped value. Otherwise, the value must be unwrapped * with `_#value`. * * Explicit chain sequences, which must be unwrapped with `_#value`, may be * enabled using `_.chain`. * * The execution of chained methods is lazy, that is, it's deferred until * `_#value` is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. * Shortcut fusion is an optimization to merge iteratee calls; this avoids * the creation of intermediate arrays and can greatly reduce the number of * iteratee executions. Sections of a chain sequence qualify for shortcut * fusion if the section is applied to an array and iteratees accept only * one argument. The heuristic for whether a section qualifies for shortcut * fusion is subject to change. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, * `zipObject`, `zipObjectDeep`, and `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, * `upperFirst`, `value`, and `words` * * @name _ * @constructor * @category Seq * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2, 3]); * * // Returns an unwrapped value. * wrapped.reduce(_.add); * // => 6 * * // Returns a wrapped value. * var squares = wrapped.map(square); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { if (value instanceof LodashWrapper) { return value; } if (hasOwnProperty.call(value, '__wrapped__')) { return wrapperClone(value); } } return new LodashWrapper(value); } /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(proto) { if (!isObject(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable explicit method chain sequences. */ function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; this.__chain__ = !!chainAll; this.__index__ = 0; this.__values__ = undefined; } /** * By default, the template delimiters used by lodash are like those in * embedded Ruby (ERB) as well as ES2015 template strings. Change the * following template settings to use alternative delimiters. * * @static * @memberOf _ * @type {Object} */ lodash.templateSettings = { /** * Used to detect `data` property values to be HTML-escaped. * * @memberOf _.templateSettings * @type {RegExp} */ 'escape': reEscape, /** * Used to detect code to be evaluated. * * @memberOf _.templateSettings * @type {RegExp} */ 'evaluate': reEvaluate, /** * Used to detect `data` property values to inject. * * @memberOf _.templateSettings * @type {RegExp} */ 'interpolate': reInterpolate, /** * Used to reference the data object in the template text. * * @memberOf _.templateSettings * @type {string} */ 'variable': '', /** * Used to import variables into the compiled template. * * @memberOf _.templateSettings * @type {Object} */ 'imports': { /** * A reference to the `lodash` function. * * @memberOf _.templateSettings.imports * @type {Function} */ '_': lodash } }; // Ensure wrappers are instances of `baseLodash`. lodash.prototype = baseLodash.prototype; lodash.prototype.constructor = lodash; LodashWrapper.prototype = baseCreate(baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; /*------------------------------------------------------------------------*/ /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @constructor * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; this.__dir__ = 1; this.__filtered__ = false; this.__iteratees__ = []; this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = []; } /** * Creates a clone of the lazy wrapper object. * * @private * @name clone * @memberOf LazyWrapper * @returns {Object} Returns the cloned `LazyWrapper` object. */ function lazyClone() { var result = new LazyWrapper(this.__wrapped__); result.__actions__ = copyArray(this.__actions__); result.__dir__ = this.__dir__; result.__filtered__ = this.__filtered__; result.__iteratees__ = copyArray(this.__iteratees__); result.__takeCount__ = this.__takeCount__; result.__views__ = copyArray(this.__views__); return result; } /** * Reverses the direction of lazy iteration. * * @private * @name reverse * @memberOf LazyWrapper * @returns {Object} Returns the new reversed `LazyWrapper` object. */ function lazyReverse() { if (this.__filtered__) { var result = new LazyWrapper(this); result.__dir__ = -1; result.__filtered__ = true; } else { result = this.clone(); result.__dir__ *= -1; } return result; } /** * Extracts the unwrapped value from its lazy wrapper. * * @private * @name value * @memberOf LazyWrapper * @returns {*} Returns the unwrapped value. */ function lazyValue() { var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, this.__views__), start = view.start, end = view.end, length = end - start, index = isRight ? end : (start - 1), iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__); if (!isArr || (!isRight && arrLength == length && takeCount == length)) { return baseWrapperValue(array, this.__actions__); } var result = []; outer: while (length-- && resIndex < takeCount) { index += dir; var iterIndex = -1, value = array[index]; while (++iterIndex < iterLength) { var data = iteratees[iterIndex], iteratee = data.iteratee, type = data.type, computed = iteratee(value); if (type == LAZY_MAP_FLAG) { value = computed; } else if (!computed) { if (type == LAZY_FILTER_FLAG) { continue outer; } else { break outer; } } } result[resIndex++] = value; } return result; } // Ensure `LazyWrapper` is an instance of `baseLodash`. LazyWrapper.prototype = baseCreate(baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; /*------------------------------------------------------------------------*/ /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /*------------------------------------------------------------------------*/ /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /*------------------------------------------------------------------------*/ /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /*------------------------------------------------------------------------*/ /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]); } } /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; /*------------------------------------------------------------------------*/ /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; this.size = 0; } /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; /*------------------------------------------------------------------------*/ /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. isIndex(key, length) ))) { result.push(key); } } return result; } /** * A specialized version of `_.sample` for arrays. * * @private * @param {Array} array The array to sample. * @returns {*} Returns the random element. */ function arraySample(array) { var length = array.length; return length ? array[baseRandom(0, length - 1)] : undefined; } /** * A specialized version of `_.sampleSize` for arrays. * * @private * @param {Array} array The array to sample. * @param {number} n The number of elements to sample. * @returns {Array} Returns the random elements. */ function arraySampleSize(array, n) { return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); } /** * A specialized version of `_.shuffle` for arrays. * * @private * @param {Array} array The array to shuffle. * @returns {Array} Returns the new shuffled array. */ function arrayShuffle(array) { return shuffleSelf(copyArray(array)); } /** * This function is like `assignValue` except that it doesn't assign * `undefined` values. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignMergeValue(object, key, value) { if ((value !== undefined && !eq(object[key], value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * Aggregates elements of `collection` on `accumulator` with keys transformed * by `iteratee` and values set by `setter`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function baseAggregator(collection, setter, iteratee, accumulator) { baseEach(collection, function(value, key, collection) { setter(accumulator, value, iteratee(value), collection); }); return accumulator; } /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && copyObject(source, keys(source), object); } /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && copyObject(source, keysIn(source), object); } /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && defineProperty) { defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } /** * The base implementation of `_.at` without support for individual paths. * * @private * @param {Object} object The object to iterate over. * @param {string[]} paths The property paths to pick. * @returns {Array} Returns the picked elements. */ function baseAt(object, paths) { var index = -1, length = paths.length, result = Array(length), skip = object == null; while (++index < length) { result[index] = skip ? undefined : get(object, paths[index]); } return result; } /** * The base implementation of `_.clamp` which doesn't coerce arguments. * * @private * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. */ function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { number = number <= upper ? number : upper; } if (lower !== undefined) { number = number >= lower ? number : lower; } } return number; } /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return copyArray(value, result); } } else { var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; if (isBuffer(value)) { return cloneBuffer(value, isDeep); } if (tag == objectTag || tag == argsTag || (isFunc && !object)) { result = (isFlat || isFunc) ? {} : initCloneObject(value); if (!isDeep) { return isFlat ? copySymbolsIn(value, baseAssignIn(result, value)) : copySymbols(value, baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = initCloneByTag(value, tag, baseClone, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); var keysFunc = isFull ? (isFlat ? getAllKeysIn : getAllKeys) : (isFlat ? keysIn : keys); var props = isArr ? undefined : keysFunc(value); arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } /** * The base implementation of `_.conforms` which doesn't clone `source`. * * @private * @param {Object} source The object of property predicates to conform to. * @returns {Function} Returns the new spec function. */ function baseConforms(source) { var props = keys(source); return function(object) { return baseConformsTo(object, source, props); }; } /** * The base implementation of `_.conformsTo` which accepts `props` to check. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property predicates to conform to. * @returns {boolean} Returns `true` if `object` conforms, else `false`. */ function baseConformsTo(object, source, props) { var length = props.length; if (object == null) { return !length; } object = Object(object); while (length--) { var key = props[length], predicate = source[key], value = object[key]; if ((value === undefined && !(key in object)) || !predicate(value)) { return false; } } return true; } /** * The base implementation of `_.delay` and `_.defer` which accepts `args` * to provide to `func`. * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {Array} args The arguments to provide to `func`. * @returns {number|Object} Returns the timer id or timeout object. */ function baseDelay(func, wait, args) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return setTimeout(function() { func.apply(undefined, args); }, wait); } /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = arrayMap(values, baseUnary(iteratee)); } if (comparator) { includes = arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE) { includes = cacheHas; isCommon = false; values = new SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); /** * The base implementation of `_.forEachRight` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEachRight = createBaseEach(baseForOwnRight, true); /** * The base implementation of `_.every` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false` */ function baseEvery(collection, predicate) { var result = true; baseEach(collection, function(value, index, collection) { result = !!predicate(value, index, collection); return result; }); return result; } /** * The base implementation of methods like `_.max` and `_.min` which accepts a * `comparator` to determine the extremum value. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The iteratee invoked per iteration. * @param {Function} comparator The comparator used to compare values. * @returns {*} Returns the extremum value. */ function baseExtremum(array, iteratee, comparator) { var index = -1, length = array.length; while (++index < length) { var value = array[index], current = iteratee(value); if (current != null && (computed === undefined ? (current === current && !isSymbol(current)) : comparator(current, computed) )) { var computed = current, result = value; } } return result; } /** * The base implementation of `_.fill` without an iteratee call guard. * * @private * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. */ function baseFill(array, value, start, end) { var length = array.length; start = toInteger(start); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined || end > length) ? length : toInteger(end); if (end < 0) { end += length; } end = start > end ? 0 : toLength(end); while (start < end) { array[start++] = value; } return array; } /** * The base implementation of `_.filter` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); /** * This function is like `baseFor` except that it iterates over properties * in the opposite order. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseForRight = createBaseFor(true); /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys); } /** * The base implementation of `_.forOwnRight` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwnRight(object, iteratee) { return object && baseForRight(object, iteratee, keys); } /** * The base implementation of `_.functions` which creates an array of * `object` function property names filtered from `props`. * * @private * @param {Object} object The object to inspect. * @param {Array} props The property names to filter. * @returns {Array} Returns the function names. */ function baseFunctions(object, props) { return arrayFilter(props, function(key) { return isFunction(object[key]); }); } /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])]; } return (index && index == length) ? object : undefined; } /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } /** * The base implementation of `_.gt` which doesn't coerce arguments. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. */ function baseGt(value, other) { return value > other; } /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { return object != null && hasOwnProperty.call(object, key); } /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } /** * The base implementation of `_.inRange` which doesn't coerce arguments. * * @private * @param {number} number The number to check. * @param {number} start The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. */ function baseInRange(number, start, end) { return number >= nativeMin(start, end) && number < nativeMax(start, end); } /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = arrayMap(array, baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new SetCache(othIndex && array) : undefined; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.invert` and `_.invertBy` which inverts * `object` with values transformed by `iteratee` and set by `setter`. * * @private * @param {Object} object The object to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform values. * @param {Object} accumulator The initial inverted object. * @returns {Function} Returns `accumulator`. */ function baseInverter(object, setter, iteratee, accumulator) { baseForOwn(object, function(value, key, object) { setter(accumulator, iteratee(value), key, object); }); return accumulator; } /** * The base implementation of `_.invoke` without support for individual * method arguments. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {Array} args The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. */ function baseInvoke(object, path, args) { path = castPath(path, object); object = parent(object, path); var func = object == null ? object : object[toKey(last(path))]; return func == null ? undefined : apply(func, object, args); } /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } /** * The base implementation of `_.isArrayBuffer` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. */ function baseIsArrayBuffer(value) { return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; } /** * The base implementation of `_.isDate` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a date object, else `false`. */ function baseIsDate(value) { return isObjectLike(value) && baseGetTag(value) == dateTag; } /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } /** * The base implementation of `_.isMap` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. */ function baseIsMap(value) { return isObjectLike(value) && getTag(value) == mapTag; } /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result )) { return false; } } } return true; } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * The base implementation of `_.isRegExp` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. */ function baseIsRegExp(value) { return isObjectLike(value) && baseGetTag(value) == regexpTag; } /** * The base implementation of `_.isSet` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ function baseIsSet(value) { return isObjectLike(value) && getTag(value) == setTag; } /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity; } if (typeof value == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject(object)) { return nativeKeysIn(object); } var isProto = isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } /** * The base implementation of `_.lt` which doesn't coerce arguments. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. */ function baseLt(value, other) { return value < other; } /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || baseIsMatch(object, source, matchData); }; } /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); } return function(object) { var objValue = get(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); }; } /** * The base implementation of `_.merge` without support for multiple sources. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {number} srcIndex The index of `source`. * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } baseFor(source, function(srcValue, key) { if (isObject(srcValue)) { stack || (stack = new Stack); baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(object[key], srcValue, (key + ''), object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } assignMergeValue(object, key, newValue); } }, keysIn); } /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {number} srcIndex The index of `source`. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize assigned values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = object[key], srcValue = source[key], stacked = stack.get(srcValue); if (stacked) { assignMergeValue(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, (key + ''), object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { var isArr = isArray(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray(objValue)) { newValue = objValue; } else if (isArrayLikeObject(objValue)) { newValue = copyArray(objValue); } else if (isBuff) { isCommon = false; newValue = cloneBuffer(srcValue, true); } else if (isTyped) { isCommon = false; newValue = cloneTypedArray(srcValue, true); } else { newValue = []; } } else if (isPlainObject(srcValue) || isArguments(srcValue)) { newValue = objValue; if (isArguments(objValue)) { newValue = toPlainObject(objValue); } else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) { newValue = initCloneObject(srcValue); } } else { isCommon = false; } } if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack['delete'](srcValue); } assignMergeValue(object, key, newValue); } /** * The base implementation of `_.nth` which doesn't coerce arguments. * * @private * @param {Array} array The array to query. * @param {number} n The index of the element to return. * @returns {*} Returns the nth element of `array`. */ function baseNth(array, n) { var length = array.length; if (!length) { return; } n += n < 0 ? length : 0; return isIndex(n, length) ? array[n] : undefined; } /** * The base implementation of `_.orderBy` without param guards. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {string[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseOrderBy(collection, iteratees, orders) { var index = -1; iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(getIteratee())); var result = baseMap(collection, function(value, key, collection) { var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return baseSortBy(result, function(object, other) { return compareMultiple(object, other, orders); }); } /** * The base implementation of `_.pick` without support for individual * property identifiers. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @returns {Object} Returns the new object. */ function basePick(object, paths) { return basePickBy(object, paths, function(value, path) { return hasIn(object, path); }); } /** * The base implementation of `_.pickBy` without support for iteratee shorthands. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @param {Function} predicate The function invoked per property. * @returns {Object} Returns the new object. */ function basePickBy(object, paths, predicate) { var index = -1, length = paths.length, result = {}; while (++index < length) { var path = paths[index], value = baseGet(object, path); if (predicate(value, path)) { baseSet(result, castPath(path, object), value); } } return result; } /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return baseGet(object, path); }; } /** * The base implementation of `_.pullAllBy` without support for iteratee * shorthands. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. */ function basePullAll(array, values, iteratee, comparator) { var indexOf = comparator ? baseIndexOfWith : baseIndexOf, index = -1, length = values.length, seen = array; if (array === values) { values = copyArray(values); } if (iteratee) { seen = arrayMap(array, baseUnary(iteratee)); } while (++index < length) { var fromIndex = 0, value = values[index], computed = iteratee ? iteratee(value) : value; while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { if (seen !== array) { splice.call(seen, fromIndex, 1); } splice.call(array, fromIndex, 1); } } return array; } /** * The base implementation of `_.pullAt` without support for individual * indexes or capturing the removed elements. * * @private * @param {Array} array The array to modify. * @param {number[]} indexes The indexes of elements to remove. * @returns {Array} Returns `array`. */ function basePullAt(array, indexes) { var length = array ? indexes.length : 0, lastIndex = length - 1; while (length--) { var index = indexes[length]; if (length == lastIndex || index !== previous) { var previous = index; if (isIndex(index)) { splice.call(array, index, 1); } else { baseUnset(array, index); } } } return array; } /** * The base implementation of `_.random` without support for returning * floating-point numbers. * * @private * @param {number} lower The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the random number. */ function baseRandom(lower, upper) { return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); } /** * The base implementation of `_.range` and `_.rangeRight` which doesn't * coerce arguments. * * @private * @param {number} start The start of the range. * @param {number} end The end of the range. * @param {number} step The value to increment or decrement by. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the range of numbers. */ function baseRange(start, end, step, fromRight) { var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { result[fromRight ? length : ++index] = start; start += step; } return result; } /** * The base implementation of `_.repeat` which doesn't coerce arguments. * * @private * @param {string} string The string to repeat. * @param {number} n The number of times to repeat the string. * @returns {string} Returns the repeated string. */ function baseRepeat(string, n) { var result = ''; if (!string || n < 1 || n > MAX_SAFE_INTEGER) { return result; } // Leverage the exponentiation by squaring algorithm for a faster repeat. // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. do { if (n % 2) { result += string; } n = nativeFloor(n / 2); if (n) { string += string; } } while (n); return result; } /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { return setToString(overRest(func, start, identity), func + ''); } /** * The base implementation of `_.sample`. * * @private * @param {Array|Object} collection The collection to sample. * @returns {*} Returns the random element. */ function baseSample(collection) { return arraySample(values(collection)); } /** * The base implementation of `_.sampleSize` without param guards. * * @private * @param {Array|Object} collection The collection to sample. * @param {number} n The number of elements to sample. * @returns {Array} Returns the random elements. */ function baseSampleSize(collection, n) { var array = values(collection); return shuffleSelf(array, baseClamp(n, 0, array.length)); } /** * The base implementation of `_.set`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseSet(object, path, value, customizer) { if (!isObject(object)) { return object; } path = castPath(path, object); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = toKey(path[index]), newValue = value; if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : undefined; if (newValue === undefined) { newValue = isObject(objValue) ? objValue : (isIndex(path[index + 1]) ? [] : {}); } } assignValue(nested, key, newValue); nested = nested[key]; } return object; } /** * The base implementation of `setData` without support for hot loop shorting. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !metaMap ? identity : function(func, data) { metaMap.set(func, data); return func; }; /** * The base implementation of `setToString` without support for hot loop shorting. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var baseSetToString = !defineProperty ? identity : function(func, string) { return defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant(string), 'writable': true }); }; /** * The base implementation of `_.shuffle`. * * @private * @param {Array|Object} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. */ function baseShuffle(collection) { return shuffleSelf(values(collection)); } /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } /** * The base implementation of `_.some` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function baseSome(collection, predicate) { var result; baseEach(collection, function(value, index, collection) { result = predicate(value, index, collection); return !result; }); return !!result; } /** * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which * performs a binary search of `array` to determine the index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndex(array, value, retHighest) { var low = 0, high = array == null ? low : array.length; if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { while (low < high) { var mid = (low + high) >>> 1, computed = array[mid]; if (computed !== null && !isSymbol(computed) && (retHighest ? (computed <= value) : (computed < value))) { low = mid + 1; } else { high = mid; } } return high; } return baseSortedIndexBy(array, value, identity, retHighest); } /** * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` * which invokes `iteratee` for `value` and each element of `array` to compute * their sort ranking. The iteratee is invoked with one argument; (value). * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} iteratee The iteratee invoked per element. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndexBy(array, value, iteratee, retHighest) { value = iteratee(value); var low = 0, high = array == null ? 0 : array.length, valIsNaN = value !== value, valIsNull = value === null, valIsSymbol = isSymbol(value), valIsUndefined = value === undefined; while (low < high) { var mid = nativeFloor((low + high) / 2), computed = iteratee(array[mid]), othIsDefined = computed !== undefined, othIsNull = computed === null, othIsReflexive = computed === computed, othIsSymbol = isSymbol(computed); if (valIsNaN) { var setLow = retHighest || othIsReflexive; } else if (valIsUndefined) { setLow = othIsReflexive && (retHighest || othIsDefined); } else if (valIsNull) { setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); } else if (valIsSymbol) { setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); } else if (othIsNull || othIsSymbol) { setLow = false; } else { setLow = retHighest ? (computed <= value) : (computed < value); } if (setLow) { low = mid + 1; } else { high = mid; } } return nativeMin(high, MAX_ARRAY_INDEX); } /** * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseSortedUniq(array, iteratee) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; if (!index || !eq(computed, seen)) { var seen = computed; result[resIndex++] = value === 0 ? 0 : value; } } return result; } /** * The base implementation of `_.toNumber` which doesn't ensure correct * conversions of binary, hexadecimal, or octal string values. * * @private * @param {*} value The value to process. * @returns {number} Returns the number. */ function baseToNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } return +value; } /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray(value)) { // Recursively convert values (susceptible to call stack limits). return arrayMap(value, baseToString) + ''; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * The base implementation of `_.uniqBy` without support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseUniq(array, iteratee, comparator) { var index = -1, includes = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; if (comparator) { isCommon = false; includes = arrayIncludesWith; } else if (length >= LARGE_ARRAY_SIZE) { var set = iteratee ? null : createSet(array); if (set) { return setToArray(set); } isCommon = false; includes = cacheHas; seen = new SetCache; } else { seen = iteratee ? [] : result; } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer; } } if (iteratee) { seen.push(computed); } result.push(value); } else if (!includes(seen, computed, comparator)) { if (seen !== result) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.unset`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The property path to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ function baseUnset(object, path) { path = castPath(path, object); object = parent(object, path); return object == null || delete object[toKey(last(path))]; } /** * The base implementation of `_.update`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to update. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseUpdate(object, path, updater, customizer) { return baseSet(object, path, updater(baseGet(object, path)), customizer); } /** * The base implementation of methods like `_.dropWhile` and `_.takeWhile` * without support for iteratee shorthands. * * @private * @param {Array} array The array to query. * @param {Function} predicate The function invoked per iteration. * @param {boolean} [isDrop] Specify dropping elements instead of taking them. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the slice of `array`. */ function baseWhile(array, predicate, isDrop, fromRight) { var length = array.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {} return isDrop ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); } /** * The base implementation of `wrapperValue` which returns the result of * performing a sequence of actions on the unwrapped `value`, where each * successive action is supplied the return value of the previous. * * @private * @param {*} value The unwrapped value. * @param {Array} actions Actions to perform to resolve the unwrapped value. * @returns {*} Returns the resolved value. */ function baseWrapperValue(value, actions) { var result = value; if (result instanceof LazyWrapper) { result = result.value(); } return arrayReduce(actions, function(result, action) { return action.func.apply(action.thisArg, arrayPush([result], action.args)); }, result); } /** * The base implementation of methods like `_.xor`, without support for * iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of values. */ function baseXor(arrays, iteratee, comparator) { var length = arrays.length; if (length < 2) { return length ? baseUniq(arrays[0]) : []; } var index = -1, result = Array(length); while (++index < length) { var array = arrays[index], othIndex = -1; while (++othIndex < length) { if (othIndex != index) { result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); } } } return baseUniq(baseFlatten(result, 1), iteratee, comparator); } /** * This base implementation of `_.zipObject` which assigns values using `assignFunc`. * * @private * @param {Array} props The property identifiers. * @param {Array} values The property values. * @param {Function} assignFunc The function to assign values. * @returns {Object} Returns the new object. */ function baseZipObject(props, values, assignFunc) { var index = -1, length = props.length, valsLength = values.length, result = {}; while (++index < length) { var value = index < valsLength ? values[index] : undefined; assignFunc(result, props[index], value); } return result; } /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array|Object} Returns the cast array-like object. */ function castArrayLikeObject(value) { return isArrayLikeObject(value) ? value : []; } /** * Casts `value` to `identity` if it's not a function. * * @private * @param {*} value The value to inspect. * @returns {Function} Returns cast function. */ function castFunction(value) { return typeof value == 'function' ? value : identity; } /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray(value)) { return value; } return isKey(value, object) ? [value] : stringToPath(toString(value)); } /** * A `baseRest` alias which can be replaced with `identity` by module * replacement plugins. * * @private * @type {Function} * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ var castRest = baseRest; /** * Casts `array` to a slice if it's needed. * * @private * @param {Array} array The array to inspect. * @param {number} start The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the cast slice. */ function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return (!start && end >= length) ? array : baseSlice(array, start, end); } /** * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). * * @private * @param {number|Object} id The timer id or timeout object of the timer to clear. */ var clearTimeout = ctxClearTimeout || function(id) { return root.clearTimeout(id); }; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array(result).set(new Uint8Array(arrayBuffer)); return result; } /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } /** * Creates a clone of `map`. * * @private * @param {Object} map The map to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned map. */ function cloneMap(map, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(mapToArray(map), CLONE_DEEP_FLAG) : mapToArray(map); return arrayReduce(array, addMapEntry, new map.constructor); } /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } /** * Creates a clone of `set`. * * @private * @param {Object} set The set to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned set. */ function cloneSet(set, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(setToArray(set), CLONE_DEEP_FLAG) : setToArray(set); return arrayReduce(array, addSetEntry, new set.constructor); } /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } /** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; } /** * Used by `_.orderBy` to compare multiple properties of a value to another * and stable sort them. * * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, * specify an order of "desc" for descending or "asc" for ascending sort order * of corresponding values. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {boolean[]|string[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == 'desc' ? -1 : 1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[holders[argsIndex]] = args[argsIndex]; } } while (rangeLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } } return result; } /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { baseAssignValue(object, key, newValue); } else { assignValue(object, key, newValue); } } return object; } /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return copyObject(source, getSymbols(source), object); } /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return copyObject(source, getSymbolsIn(source), object); } /** * Creates a function like `_.groupBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} [initializer] The accumulator object initializer. * @returns {Function} Returns the new aggregator function. */ function createAggregator(setter, initializer) { return function(collection, iteratee) { var func = isArray(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; return func(collection, setter, getIteratee(iteratee, 2), accumulator); }; } /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } /** * Creates a function that wraps `func` to invoke it with the optional `this` * binding of `thisArg`. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new wrapped function. */ function createBind(func, bitmask, thisArg) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments); } return wrapper; } /** * Creates a function like `_.lowerFirst`. * * @private * @param {string} methodName The name of the `String` case method to use. * @returns {Function} Returns the new case function. */ function createCaseFirst(methodName) { return function(string) { string = toString(string); var strSymbols = hasUnicode(string) ? stringToArray(string) : undefined; var chr = strSymbols ? strSymbols[0] : string.charAt(0); var trailing = strSymbols ? castSlice(strSymbols, 1).join('') : string.slice(1); return chr[methodName]() + trailing; }; } /** * Creates a function like `_.camelCase`. * * @private * @param {Function} callback The function to combine each word. * @returns {Function} Returns the new compounder function. */ function createCompounder(callback) { return function(string) { return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); }; } /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtor(Ctor) { return function() { // Use a `switch` statement to work with class constructors. See // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject(result) ? result : thisBinding; }; } /** * Creates a function that wraps `func` to enable currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {number} arity The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createCurry(func, bitmask, arity) { var Ctor = createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length); } var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return apply(fn, this, args); } return wrapper; } /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} findIndexFunc The function to find the collection index. * @returns {Function} Returns the new find function. */ function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike(collection)) { var iteratee = getIteratee(predicate, 3); collection = keys(collection); predicate = function(key) { return iteratee(iterable[key], key, iterable); }; } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; }; } /** * Creates a `_.flow` or `_.flowRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new flow function. */ function createFlow(fromRight) { return flatRest(function(funcs) { var length = funcs.length, index = length, prereq = LodashWrapper.prototype.thru; if (fromRight) { funcs.reverse(); } while (index--) { var func = funcs[index]; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (prereq && !wrapper && getFuncName(func) == 'wrapper') { var wrapper = new LodashWrapper([], true); } } index = wrapper ? index : length; while (++index < length) { func = funcs[index]; var funcName = getFuncName(func), data = funcName == 'wrapper' ? getData(func) : undefined; if (data && isLaziable(data[0]) && data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && !data[4].length && data[9] == 1 ) { wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); } else { wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func); } } return function() { var args = arguments, value = args[0]; if (wrapper && args.length == 1 && isArray(value)) { return wrapper.plant(value).value(); } var index = 0, result = length ? funcs[index].apply(this, args) : value; while (++index < length) { result = funcs[index].call(this, result); } return result; }; }); } /** * Creates a function that wraps `func` to invoke it with optional `this` * binding of `thisArg`, partial application, and currying. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided * to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG, isBindKey = bitmask & WRAP_BIND_KEY_FLAG, isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined : createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index]; } if (isCurried) { var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder); } if (partials) { args = composeArgs(args, partials, holders, isCurried); } if (partialsRight) { args = composeArgsRight(args, partialsRight, holdersRight, isCurried); } length -= holdersCount; if (isCurried && length < arity) { var newHolders = replaceHolders(args, placeholder); return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length ); } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = reorder(args, argPos); } else if (isFlip && length > 1) { args.reverse(); } if (isAry && ary < length) { args.length = ary; } if (this && this !== root && this instanceof wrapper) { fn = Ctor || createCtor(fn); } return fn.apply(thisBinding, args); } return wrapper; } /** * Creates a function like `_.invertBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} toIteratee The function to resolve iteratees. * @returns {Function} Returns the new inverter function. */ function createInverter(setter, toIteratee) { return function(object, iteratee) { return baseInverter(object, setter, toIteratee(iteratee), {}); }; } /** * Creates a function that performs a mathematical operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @param {number} [defaultValue] The value used for `undefined` arguments. * @returns {Function} Returns the new mathematical operation function. */ function createMathOperation(operator, defaultValue) { return function(value, other) { var result; if (value === undefined && other === undefined) { return defaultValue; } if (value !== undefined) { result = value; } if (other !== undefined) { if (result === undefined) { return other; } if (typeof value == 'string' || typeof other == 'string') { value = baseToString(value); other = baseToString(other); } else { value = baseToNumber(value); other = baseToNumber(other); } result = operator(value, other); } return result; }; } /** * Creates a function like `_.over`. * * @private * @param {Function} arrayFunc The function to iterate over iteratees. * @returns {Function} Returns the new over function. */ function createOver(arrayFunc) { return flatRest(function(iteratees) { iteratees = arrayMap(iteratees, baseUnary(getIteratee())); return baseRest(function(args) { var thisArg = this; return arrayFunc(iteratees, function(iteratee) { return apply(iteratee, thisArg, args); }); }); }); } /** * Creates the padding for `string` based on `length`. The `chars` string * is truncated if the number of characters exceeds `length`. * * @private * @param {number} length The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padding for `string`. */ function createPadding(length, chars) { chars = chars === undefined ? ' ' : baseToString(chars); var charsLength = chars.length; if (charsLength < 2) { return charsLength ? baseRepeat(chars, length) : chars; } var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); return hasUnicode(chars) ? castSlice(stringToArray(result), 0, length).join('') : result.slice(0, length); } /** * Creates a function that wraps `func` to invoke it with the `this` binding * of `thisArg` and `partials` prepended to the arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to * the new function. * @returns {Function} Returns the new wrapped function. */ function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return apply(fn, isBind ? thisArg : this, args); } return wrapper; } /** * Creates a `_.range` or `_.rangeRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new range function. */ function createRange(fromRight) { return function(start, end, step) { if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { end = step = undefined; } // Ensure the sign of `-0` is preserved. start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); return baseRange(start, end, step, fromRight); }; } /** * Creates a function that performs a relational operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @returns {Function} Returns the new relational operation function. */ function createRelationalOperation(operator) { return function(value, other) { if (!(typeof value == 'string' && typeof other == 'string')) { value = toNumber(value); other = toNumber(other); } return operator(value, other); }; } /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {Function} wrapFunc The function to create the `func` wrapper. * @param {*} placeholder The placeholder value. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined, newData); if (isLaziable(func)) { setData(result, newData); } result.placeholder = placeholder; return setWrapToString(result, func, bitmask); } /** * Creates a function like `_.round`. * * @private * @param {string} methodName The name of the `Math` method to use when rounding. * @returns {Function} Returns the new round function. */ function createRound(methodName) { var func = Math[methodName]; return function(number, precision) { number = toNumber(number); precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); if (precision) { // Shift with exponential notation to avoid floating-point issues. // See [MDN](https://mdn.io/round#Examples) for more details. var pair = (toString(number) + 'e').split('e'), value = func(pair[0] + 'e' + (+pair[1] + precision)); pair = (toString(value) + 'e').split('e'); return +(pair[0] + 'e' + (+pair[1] - precision)); } return func(number); }; } /** * Creates a set object of `values`. * * @private * @param {Array} values The values to add to the set. * @returns {Object} Returns the new set. */ var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { return new Set(values); }; /** * Creates a `_.toPairs` or `_.toPairsIn` function. * * @private * @param {Function} keysFunc The function to get the keys of a given object. * @returns {Function} Returns the new pairs function. */ function createToPairs(keysFunc) { return function(object) { var tag = getTag(object); if (tag == mapTag) { return mapToArray(object); } if (tag == setTag) { return setToPairs(object); } return baseToPairs(object, keysFunc(object)); }; } /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * 512 - `_.flip` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); partials = holders = undefined; } ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); arity = arity === undefined ? arity : toInteger(arity); length -= holders ? holders.length : 0; if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : getData(func); var newData = [ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity ]; if (data) { mergeData(newData, data); } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] === undefined ? (isBindKey ? 0 : func.length) : nativeMax(newData[9] - length, 0); if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); } if (!bitmask || bitmask == WRAP_BIND_FLAG) { var result = createBind(func, bitmask, thisArg); } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { result = createCurry(func, bitmask, arity); } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { result = createPartial(func, bitmask, thisArg, partials); } else { result = createHybrid.apply(undefined, newData); } var setter = data ? baseSetData : setData; return setWrapToString(setter(result, newData), func, bitmask); } /** * Used by `_.defaults` to customize its `_.assignIn` use to assign properties * of source objects to the destination object for all destination properties * that resolve to `undefined`. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to assign. * @param {Object} object The parent object of `objValue`. * @returns {*} Returns the value to assign. */ function customDefaultsAssignIn(objValue, srcValue, key, object) { if (objValue === undefined || (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { return srcValue; } return objValue; } /** * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source * objects into destination objects that are passed thru. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to merge. * @param {Object} object The parent object of `objValue`. * @param {Object} source The parent object of `srcValue`. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. * @returns {*} Returns the value to assign. */ function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { if (isObject(objValue) && isObject(srcValue)) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, objValue); baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); stack['delete'](srcValue); } return objValue; } /** * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain * objects. * * @private * @param {*} value The value to inspect. * @param {string} key The key of the property to inspect. * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. */ function customOmitClone(value) { return isPlainObject(value) ? undefined : value; } /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function(othValue, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } /** * A specialized version of `baseRest` which flattens the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ function flatRest(func) { return setToString(overRest(func, undefined, flatten), func + ''); } /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return baseGetAllKeys(object, keysIn, getSymbolsIn); } /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !metaMap ? noop : function(func) { return metaMap.get(func); }; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = (func.name + ''), array = realNames[result], length = hasOwnProperty.call(realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } /** * Gets the argument placeholder value for `func`. * * @private * @param {Function} func The function to inspect. * @returns {*} Returns the placeholder value. */ function getHolder(func) { var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; return object.placeholder; } /** * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, * this function returns the custom method, otherwise it returns `baseIteratee`. * If arguments are provided, the chosen function is invoked with them and * its result is returned. * * @private * @param {*} [value] The value to convert to an iteratee. * @param {number} [arity] The arity of the created iteratee. * @returns {Function} Returns the chosen function or its result. */ function getIteratee() { var result = lodash.iteratee || iteratee; result = result === iteratee ? baseIteratee : result; return arguments.length ? result(arguments[0], arguments[1]) : result; } /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, isStrictComparable(value)]; } return result; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { var result = []; while (object) { arrayPush(result, getSymbols(object)); object = getPrototype(object); } return result; }; /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } /** * Gets the view, applying any `transforms` to the `start` and `end` positions. * * @private * @param {number} start The start of the view. * @param {number} end The end of the view. * @param {Array} transforms The transformations to apply to the view. * @returns {Object} Returns an object containing the `start` and `end` * positions of the view. */ function getView(start, end, transforms) { var index = -1, length = transforms.length; while (++index < length) { var data = transforms[index], size = data.size; switch (data.type) { case 'drop': start += size; break; case 'dropRight': end -= size; break; case 'take': end = nativeMin(end, start + size); break; case 'takeRight': start = nativeMax(start, end - size); break; } } return { 'start': start, 'end': end }; } /** * Extracts wrapper details from the `source` body comment. * * @private * @param {string} source The source to inspect. * @returns {Array} Returns the wrapper details. */ function getWrapDetails(source) { var match = source.match(reWrapDetails); return match ? match[1].split(reSplitDetails) : []; } /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); } /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !isPrototype(object)) ? baseCreate(getPrototype(object)) : {}; } /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, cloneFunc, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return cloneArrayBuffer(object); case boolTag: case dateTag: return new Ctor(+object); case dataViewTag: return cloneDataView(object, isDeep); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: return cloneTypedArray(object, isDeep); case mapTag: return cloneMap(object, isDeep, cloneFunc); case numberTag: case stringTag: return new Ctor(object); case regexpTag: return cloneRegExp(object); case setTag: return cloneSet(object, isDeep, cloneFunc); case symbolTag: return cloneSymbol(object); } } /** * Inserts wrapper `details` in a comment at the top of the `source` body. * * @private * @param {string} source The source to modify. * @returns {Array} details The details to insert. * @returns {string} Returns the modified source. */ function insertWrapDetails(source, details) { var length = details.length; if (!length) { return source; } var lastIndex = length - 1; details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; details = details.join(length > 2 ? ', ' : ' '); return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq(object[index], value); } return false; } /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, * else `false`. */ function isLaziable(func) { var funcName = getFuncName(func), other = lodash[funcName]; if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { return false; } if (func === other) { return true; } var data = getData(other); return !!data && func === data[0]; } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } /** * Checks if `func` is capable of being masked. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `func` is maskable, else `false`. */ var isMaskable = coreJsData ? isFunction : stubFalse; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers used to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and * `_.rearg` modify function arguments, making the order in which they are * executed important, preventing the merging of metadata. However, we make * an exception for a safe combined case where curried functions have `_.ary` * and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); var isCombo = ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & WRAP_BIND_FLAG) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? composeArgs(partials, value, source[4]) : value; data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = value; } // Use source `ary` if it's smaller. if (srcBitmask & WRAP_ARY_FLAG) { data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return apply(func, this, otherArgs); }; } /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); } /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array); while (length--) { var index = indexes[length]; array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity * function to avoid garbage collection pauses in V8. See * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = shortOut(baseSetData); /** * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @returns {number|Object} Returns the timer id or timeout object. */ var setTimeout = ctxSetTimeout || function(func, wait) { return root.setTimeout(func, wait); }; /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = shortOut(baseSetToString); /** * Sets the `toString` method of `wrapper` to mimic the source of `reference` * with wrapper details in a comment at the top of the source body. * * @private * @param {Function} wrapper The function to modify. * @param {Function} reference The reference function. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Function} Returns `wrapper`. */ function setWrapToString(wrapper, reference, bitmask) { var source = (reference + ''); return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); } /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } /** * A specialized version of `_.shuffle` which mutates and sets the size of `array`. * * @private * @param {Array} array The array to shuffle. * @param {number} [size=array.length] The size of `array`. * @returns {Array} Returns `array`. */ function shuffleSelf(array, size) { var index = -1, length = array.length, lastIndex = length - 1; size = size === undefined ? length : size; while (++index < size) { var rand = baseRandom(index, lastIndex), value = array[rand]; array[rand] = array[index]; array[index] = value; } array.length = size; return array; } /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoizeCapped(function(string) { var result = []; if (reLeadingDot.test(string)) { result.push(''); } string.replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /** * Updates wrapper `details` based on `bitmask` flags. * * @private * @returns {Array} details The details to modify. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Array} Returns `details`. */ function updateWrapDetails(details, bitmask) { arrayEach(wrapFlags, function(pair) { var value = '_.' + pair[0]; if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { details.push(value); } }); return details.sort(); } /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { if (wrapper instanceof LazyWrapper) { return wrapper.clone(); } var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } /*------------------------------------------------------------------------*/ /** * Creates an array of elements split into groups the length of `size`. * If `array` can't be split evenly, the final chunk will be the remaining * elements. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to process. * @param {number} [size=1] The length of each chunk * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the new array of chunks. * @example * * _.chunk(['a', 'b', 'c', 'd'], 2); * // => [['a', 'b'], ['c', 'd']] * * _.chunk(['a', 'b', 'c', 'd'], 3); * // => [['a', 'b', 'c'], ['d']] */ function chunk(array, size, guard) { if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { size = 1; } else { size = nativeMax(toInteger(size), 0); } var length = array == null ? 0 : array.length; if (!length || size < 1) { return []; } var index = 0, resIndex = 0, result = Array(nativeCeil(length / size)); while (index < length) { result[resIndex++] = baseSlice(array, index, (index += size)); } return result; } /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value) { result[resIndex++] = value; } } return result; } /** * Creates a new array concatenating `array` with any additional arrays * and/or values. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to concatenate. * @param {...*} [values] The values to concatenate. * @returns {Array} Returns the new concatenated array. * @example * * var array = [1]; * var other = _.concat(array, 2, [3], [[4]]); * * console.log(other); * // => [1, 2, 3, [4]] * * console.log(array); * // => [1] */ function concat() { var length = arguments.length; if (!length) { return []; } var args = Array(length - 1), array = arguments[0], index = length; while (index--) { args[index - 1] = arguments[index]; } return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); } /** * Creates an array of `array` values not included in the other given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.without, _.xor * @example * * _.difference([2, 1], [2, 3]); * // => [1] */ var difference = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : []; }); /** * This method is like `_.difference` except that it accepts `iteratee` which * is invoked for each element of `array` and `values` to generate the criterion * by which they're compared. The order and references of result values are * determined by the first array. The iteratee is invoked with one argument: * (value). * * **Note:** Unlike `_.pullAllBy`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [1.2] * * // The `_.property` iteratee shorthand. * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var differenceBy = baseRest(function(array, values) { var iteratee = last(values); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) : []; }); /** * This method is like `_.difference` except that it accepts `comparator` * which is invoked to compare elements of `array` to `values`. The order and * references of result values are determined by the first array. The comparator * is invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `_.pullAllWith`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); * // => [{ 'x': 2, 'y': 1 }] */ var differenceWith = baseRest(function(array, values) { var comparator = last(values); if (isArrayLikeObject(comparator)) { comparator = undefined; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) : []; }); /** * Creates a slice of `array` with `n` elements dropped from the beginning. * * @static * @memberOf _ * @since 0.5.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.drop([1, 2, 3]); * // => [2, 3] * * _.drop([1, 2, 3], 2); * // => [3] * * _.drop([1, 2, 3], 5); * // => [] * * _.drop([1, 2, 3], 0); * // => [1, 2, 3] */ function drop(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with `n` elements dropped from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.dropRight([1, 2, 3]); * // => [1, 2] * * _.dropRight([1, 2, 3], 2); * // => [1] * * _.dropRight([1, 2, 3], 5); * // => [] * * _.dropRight([1, 2, 3], 0); * // => [1, 2, 3] */ function dropRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); n = length - n; return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` excluding elements dropped from the end. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.dropRightWhile(users, function(o) { return !o.active; }); * // => objects for ['barney'] * * // The `_.matches` iteratee shorthand. * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['barney', 'fred'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropRightWhile(users, ['active', false]); * // => objects for ['barney'] * * // The `_.property` iteratee shorthand. * _.dropRightWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropRightWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), true, true) : []; } /** * Creates a slice of `array` excluding elements dropped from the beginning. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.dropWhile(users, function(o) { return !o.active; }); * // => objects for ['pebbles'] * * // The `_.matches` iteratee shorthand. * _.dropWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['fred', 'pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropWhile(users, ['active', false]); * // => objects for ['pebbles'] * * // The `_.property` iteratee shorthand. * _.dropWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), true) : []; } /** * Fills elements of `array` with `value` from `start` up to, but not * including, `end`. * * **Note:** This method mutates `array`. * * @static * @memberOf _ * @since 3.2.0 * @category Array * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.fill(array, 'a'); * console.log(array); * // => ['a', 'a', 'a'] * * _.fill(Array(3), 2); * // => [2, 2, 2] * * _.fill([4, 6, 8, 10], '*', 1, 3); * // => [4, '*', '*', 10] */ function fill(array, value, start, end) { var length = array == null ? 0 : array.length; if (!length) { return []; } if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { start = 0; end = length; } return baseFill(array, value, start, end); } /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(o) { return o.user == 'barney'; }); * // => 0 * * // The `_.matches` iteratee shorthand. * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // The `_.matchesProperty` iteratee shorthand. * _.findIndex(users, ['active', false]); * // => 0 * * // The `_.property` iteratee shorthand. * _.findIndex(users, 'active'); * // => 2 */ function findIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseFindIndex(array, getIteratee(predicate, 3), index); } /** * This method is like `_.findIndex` except that it iterates over elements * of `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); * // => 2 * * // The `_.matches` iteratee shorthand. * _.findLastIndex(users, { 'user': 'barney', 'active': true }); * // => 0 * * // The `_.matchesProperty` iteratee shorthand. * _.findLastIndex(users, ['active', false]); * // => 2 * * // The `_.property` iteratee shorthand. * _.findLastIndex(users, 'active'); * // => 0 */ function findLastIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = length - 1; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = fromIndex < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); } return baseFindIndex(array, getIteratee(predicate, 3), index, true); } /** * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, [3, [4]], 5]]); * // => [1, 2, [3, [4]], 5] */ function flatten(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, 1) : []; } /** * Recursively flattens `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flattenDeep([1, [2, [3, [4]], 5]]); * // => [1, 2, 3, 4, 5] */ function flattenDeep(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, INFINITY) : []; } /** * Recursively flatten `array` up to `depth` times. * * @static * @memberOf _ * @since 4.4.0 * @category Array * @param {Array} array The array to flatten. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * var array = [1, [2, [3, [4]], 5]]; * * _.flattenDepth(array, 1); * // => [1, 2, [3, [4]], 5] * * _.flattenDepth(array, 2); * // => [1, 2, 3, [4], 5] */ function flattenDepth(array, depth) { var length = array == null ? 0 : array.length; if (!length) { return []; } depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(array, depth); } /** * The inverse of `_.toPairs`; this method returns an object composed * from key-value `pairs`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} pairs The key-value pairs. * @returns {Object} Returns the new object. * @example * * _.fromPairs([['a', 1], ['b', 2]]); * // => { 'a': 1, 'b': 2 } */ function fromPairs(pairs) { var index = -1, length = pairs == null ? 0 : pairs.length, result = {}; while (++index < length) { var pair = pairs[index]; result[pair[0]] = pair[1]; } return result; } /** * Gets the first element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @alias first * @category Array * @param {Array} array The array to query. * @returns {*} Returns the first element of `array`. * @example * * _.head([1, 2, 3]); * // => 1 * * _.head([]); * // => undefined */ function head(array) { return (array && array.length) ? array[0] : undefined; } /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // Search from the `fromIndex`. * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ function indexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseIndexOf(array, value, index); } /** * Gets all but the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.initial([1, 2, 3]); * // => [1, 2] */ function initial(array) { var length = array == null ? 0 : array.length; return length ? baseSlice(array, 0, -1) : []; } /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [2, 3]); * // => [2] */ var intersection = baseRest(function(arrays) { var mapped = arrayMap(arrays, castArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped) : []; }); /** * This method is like `_.intersection` except that it accepts `iteratee` * which is invoked for each element of each `arrays` to generate the criterion * by which they're compared. The order and references of result values are * determined by the first array. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [2.1] * * // The `_.property` iteratee shorthand. * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }] */ var intersectionBy = baseRest(function(arrays) { var iteratee = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); if (iteratee === last(mapped)) { iteratee = undefined; } else { mapped.pop(); } return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped, getIteratee(iteratee, 2)) : []; }); /** * This method is like `_.intersection` except that it accepts `comparator` * which is invoked to compare elements of `arrays`. The order and references * of result values are determined by the first array. The comparator is * invoked with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.intersectionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }] */ var intersectionWith = baseRest(function(arrays) { var comparator = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); comparator = typeof comparator == 'function' ? comparator : undefined; if (comparator) { mapped.pop(); } return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped, undefined, comparator) : []; }); /** * Converts all elements in `array` into a string separated by `separator`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to convert. * @param {string} [separator=','] The element separator. * @returns {string} Returns the joined string. * @example * * _.join(['a', 'b', 'c'], '~'); * // => 'a~b~c' */ function join(array, separator) { return array == null ? '' : nativeJoin.call(array, separator); } /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined; } /** * This method is like `_.indexOf` except that it iterates over elements of * `array` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.lastIndexOf([1, 2, 1, 2], 2); * // => 3 * * // Search from the `fromIndex`. * _.lastIndexOf([1, 2, 1, 2], 2, 2); * // => 1 */ function lastIndexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = length; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); } return value === value ? strictLastIndexOf(array, value, index) : baseFindIndex(array, baseIsNaN, index, true); } /** * Gets the element at index `n` of `array`. If `n` is negative, the nth * element from the end is returned. * * @static * @memberOf _ * @since 4.11.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=0] The index of the element to return. * @returns {*} Returns the nth element of `array`. * @example * * var array = ['a', 'b', 'c', 'd']; * * _.nth(array, 1); * // => 'b' * * _.nth(array, -2); * // => 'c'; */ function nth(array, n) { return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; } /** * Removes all given values from `array` using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` * to remove elements from an array by predicate. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {...*} [values] The values to remove. * @returns {Array} Returns `array`. * @example * * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * * _.pull(array, 'a', 'c'); * console.log(array); * // => ['b', 'b'] */ var pull = baseRest(pullAll); /** * This method is like `_.pull` except that it accepts an array of values to remove. * * **Note:** Unlike `_.difference`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @returns {Array} Returns `array`. * @example * * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * * _.pullAll(array, ['a', 'c']); * console.log(array); * // => ['b', 'b'] */ function pullAll(array, values) { return (array && array.length && values && values.length) ? basePullAll(array, values) : array; } /** * This method is like `_.pullAll` except that it accepts `iteratee` which is * invoked for each element of `array` and `values` to generate the criterion * by which they're compared. The iteratee is invoked with one argument: (value). * * **Note:** Unlike `_.differenceBy`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; * * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); * console.log(array); * // => [{ 'x': 2 }] */ function pullAllBy(array, values, iteratee) { return (array && array.length && values && values.length) ? basePullAll(array, values, getIteratee(iteratee, 2)) : array; } /** * This method is like `_.pullAll` except that it accepts `comparator` which * is invoked to compare elements of `array` to `values`. The comparator is * invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `_.differenceWith`, this method mutates `array`. * * @static * @memberOf _ * @since 4.6.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; * * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); * console.log(array); * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] */ function pullAllWith(array, values, comparator) { return (array && array.length && values && values.length) ? basePullAll(array, values, undefined, comparator) : array; } /** * Removes elements from `array` corresponding to `indexes` and returns an * array of removed elements. * * **Note:** Unlike `_.at`, this method mutates `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to modify. * @param {...(number|number[])} [indexes] The indexes of elements to remove. * @returns {Array} Returns the new array of removed elements. * @example * * var array = ['a', 'b', 'c', 'd']; * var pulled = _.pullAt(array, [1, 3]); * * console.log(array); * // => ['a', 'c'] * * console.log(pulled); * // => ['b', 'd'] */ var pullAt = flatRest(function(array, indexes) { var length = array == null ? 0 : array.length, result = baseAt(array, indexes); basePullAt(array, arrayMap(indexes, function(index) { return isIndex(index, length) ? +index : index; }).sort(compareAscending)); return result; }); /** * Removes all elements from `array` that `predicate` returns truthy for * and returns an array of the removed elements. The predicate is invoked * with three arguments: (value, index, array). * * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` * to pull elements from an array by value. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new array of removed elements. * @example * * var array = [1, 2, 3, 4]; * var evens = _.remove(array, function(n) { * return n % 2 == 0; * }); * * console.log(array); * // => [1, 3] * * console.log(evens); * // => [2, 4] */ function remove(array, predicate) { var result = []; if (!(array && array.length)) { return result; } var index = -1, indexes = [], length = array.length; predicate = getIteratee(predicate, 3); while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result.push(value); indexes.push(index); } } basePullAt(array, indexes); return result; } /** * Reverses `array` so that the first element becomes the last, the second * element becomes the second to last, and so on. * * **Note:** This method mutates `array` and is based on * [`Array#reverse`](https://mdn.io/Array/reverse). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.reverse(array); * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function reverse(array) { return array == null ? array : nativeReverse.call(array); } /** * Creates a slice of `array` from `start` up to, but not including, `end`. * * **Note:** This method is used instead of * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are * returned. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function slice(array, start, end) { var length = array == null ? 0 : array.length; if (!length) { return []; } if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { start = 0; end = length; } else { start = start == null ? 0 : toInteger(start); end = end === undefined ? length : toInteger(end); } return baseSlice(array, start, end); } /** * Uses a binary search to determine the lowest index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedIndex([30, 50], 40); * // => 1 */ function sortedIndex(array, value) { return baseSortedIndex(array, value); } /** * This method is like `_.sortedIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var objects = [{ 'x': 4 }, { 'x': 5 }]; * * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); * // => 0 * * // The `_.property` iteratee shorthand. * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); * // => 0 */ function sortedIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); } /** * This method is like `_.indexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedIndexOf([4, 5, 5, 5, 6], 5); * // => 1 */ function sortedIndexOf(array, value) { var length = array == null ? 0 : array.length; if (length) { var index = baseSortedIndex(array, value); if (index < length && eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.sortedIndex` except that it returns the highest * index at which `value` should be inserted into `array` in order to * maintain its sort order. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedLastIndex([4, 5, 5, 5, 6], 5); * // => 4 */ function sortedLastIndex(array, value) { return baseSortedIndex(array, value, true); } /** * This method is like `_.sortedLastIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var objects = [{ 'x': 4 }, { 'x': 5 }]; * * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); * // => 1 * * // The `_.property` iteratee shorthand. * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); * // => 1 */ function sortedLastIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); } /** * This method is like `_.lastIndexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); * // => 3 */ function sortedLastIndexOf(array, value) { var length = array == null ? 0 : array.length; if (length) { var index = baseSortedIndex(array, value, true) - 1; if (eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.uniq` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniq([1, 1, 2]); * // => [1, 2] */ function sortedUniq(array) { return (array && array.length) ? baseSortedUniq(array) : []; } /** * This method is like `_.uniqBy` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); * // => [1.1, 2.3] */ function sortedUniqBy(array, iteratee) { return (array && array.length) ? baseSortedUniq(array, getIteratee(iteratee, 2)) : []; } /** * Gets all but the first element of `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.tail([1, 2, 3]); * // => [2, 3] */ function tail(array) { var length = array == null ? 0 : array.length; return length ? baseSlice(array, 1, length) : []; } /** * Creates a slice of `array` with `n` elements taken from the beginning. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.take([1, 2, 3]); * // => [1] * * _.take([1, 2, 3], 2); * // => [1, 2] * * _.take([1, 2, 3], 5); * // => [1, 2, 3] * * _.take([1, 2, 3], 0); * // => [] */ function take(array, n, guard) { if (!(array && array.length)) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` with `n` elements taken from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.takeRight([1, 2, 3]); * // => [3] * * _.takeRight([1, 2, 3], 2); * // => [2, 3] * * _.takeRight([1, 2, 3], 5); * // => [1, 2, 3] * * _.takeRight([1, 2, 3], 0); * // => [] */ function takeRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); n = length - n; return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with elements taken from the end. Elements are * taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.takeRightWhile(users, function(o) { return !o.active; }); * // => objects for ['fred', 'pebbles'] * * // The `_.matches` iteratee shorthand. * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeRightWhile(users, ['active', false]); * // => objects for ['fred', 'pebbles'] * * // The `_.property` iteratee shorthand. * _.takeRightWhile(users, 'active'); * // => [] */ function takeRightWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), false, true) : []; } /** * Creates a slice of `array` with elements taken from the beginning. Elements * are taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.takeWhile(users, function(o) { return !o.active; }); * // => objects for ['barney', 'fred'] * * // The `_.matches` iteratee shorthand. * _.takeWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeWhile(users, ['active', false]); * // => objects for ['barney', 'fred'] * * // The `_.property` iteratee shorthand. * _.takeWhile(users, 'active'); * // => [] */ function takeWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3)) : []; } /** * Creates an array of unique values, in order, from all given arrays using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of combined values. * @example * * _.union([2], [1, 2]); * // => [2, 1] */ var union = baseRest(function(arrays) { return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); }); /** * This method is like `_.union` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which uniqueness is computed. Result values are chosen from the first * array in which the value occurs. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * _.unionBy([2.1], [1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ var unionBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); }); /** * This method is like `_.union` except that it accepts `comparator` which * is invoked to compare elements of `arrays`. Result values are chosen from * the first array in which the value occurs. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.unionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var unionWith = baseRest(function(arrays) { var comparator = last(arrays); comparator = typeof comparator == 'function' ? comparator : undefined; return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); }); /** * Creates a duplicate-free version of an array, using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons, in which only the first occurrence of each element * is kept. The order of result values is determined by the order they occur * in the array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniq([2, 1, 2]); * // => [2, 1] */ function uniq(array) { return (array && array.length) ? baseUniq(array) : []; } /** * This method is like `_.uniq` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * uniqueness is computed. The order of result values is determined by the * order they occur in the array. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniqBy([2.1, 1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ function uniqBy(array, iteratee) { return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; } /** * This method is like `_.uniq` except that it accepts `comparator` which * is invoked to compare elements of `array`. The order of result values is * determined by the order they occur in the array.The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.uniqWith(objects, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] */ function uniqWith(array, comparator) { comparator = typeof comparator == 'function' ? comparator : undefined; return (array && array.length) ? baseUniq(array, undefined, comparator) : []; } /** * This method is like `_.zip` except that it accepts an array of grouped * elements and creates an array regrouping the elements to their pre-zip * configuration. * * @static * @memberOf _ * @since 1.2.0 * @category Array * @param {Array} array The array of grouped elements to process. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); * // => [['a', 1, true], ['b', 2, false]] * * _.unzip(zipped); * // => [['a', 'b'], [1, 2], [true, false]] */ function unzip(array) { if (!(array && array.length)) { return []; } var length = 0; array = arrayFilter(array, function(group) { if (isArrayLikeObject(group)) { length = nativeMax(group.length, length); return true; } }); return baseTimes(length, function(index) { return arrayMap(array, baseProperty(index)); }); } /** * This method is like `_.unzip` except that it accepts `iteratee` to specify * how regrouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {Array} array The array of grouped elements to process. * @param {Function} [iteratee=_.identity] The function to combine * regrouped values. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip([1, 2], [10, 20], [100, 200]); * // => [[1, 10, 100], [2, 20, 200]] * * _.unzipWith(zipped, _.add); * // => [3, 30, 300] */ function unzipWith(array, iteratee) { if (!(array && array.length)) { return []; } var result = unzip(array); if (iteratee == null) { return result; } return arrayMap(result, function(group) { return apply(iteratee, undefined, group); }); } /** * Creates an array excluding all given values using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.pull`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...*} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.xor * @example * * _.without([2, 1, 2, 3], 1, 2); * // => [3] */ var without = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, values) : []; }); /** * Creates an array of unique values that is the * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) * of the given arrays. The order of result values is determined by the order * they occur in the arrays. * * @static * @memberOf _ * @since 2.4.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.without * @example * * _.xor([2, 1], [2, 3]); * // => [1, 3] */ var xor = baseRest(function(arrays) { return baseXor(arrayFilter(arrays, isArrayLikeObject)); }); /** * This method is like `_.xor` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which by which they're compared. The order of result values is determined * by the order they occur in the arrays. The iteratee is invoked with one * argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [1.2, 3.4] * * // The `_.property` iteratee shorthand. * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var xorBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); }); /** * This method is like `_.xor` except that it accepts `comparator` which is * invoked to compare elements of `arrays`. The order of result values is * determined by the order they occur in the arrays. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.xorWith(objects, others, _.isEqual); * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var xorWith = baseRest(function(arrays) { var comparator = last(arrays); comparator = typeof comparator == 'function' ? comparator : undefined; return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); }); /** * Creates an array of grouped elements, the first of which contains the * first elements of the given arrays, the second of which contains the * second elements of the given arrays, and so on. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zip(['a', 'b'], [1, 2], [true, false]); * // => [['a', 1, true], ['b', 2, false]] */ var zip = baseRest(unzip); /** * This method is like `_.fromPairs` except that it accepts two arrays, * one of property identifiers and one of corresponding values. * * @static * @memberOf _ * @since 0.4.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObject(['a', 'b'], [1, 2]); * // => { 'a': 1, 'b': 2 } */ function zipObject(props, values) { return baseZipObject(props || [], values || [], assignValue); } /** * This method is like `_.zipObject` except that it supports property paths. * * @static * @memberOf _ * @since 4.1.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } */ function zipObjectDeep(props, values) { return baseZipObject(props || [], values || [], baseSet); } /** * This method is like `_.zip` except that it accepts `iteratee` to specify * how grouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @param {Function} [iteratee=_.identity] The function to combine * grouped values. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { * return a + b + c; * }); * // => [111, 222] */ var zipWith = baseRest(function(arrays) { var length = arrays.length, iteratee = length > 1 ? arrays[length - 1] : undefined; iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; return unzipWith(arrays, iteratee); }); /*------------------------------------------------------------------------*/ /** * Creates a `lodash` wrapper instance that wraps `value` with explicit method * chain sequences enabled. The result of such sequences must be unwrapped * with `_#value`. * * @static * @memberOf _ * @since 1.3.0 * @category Seq * @param {*} value The value to wrap. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'pebbles', 'age': 1 } * ]; * * var youngest = _ * .chain(users) * .sortBy('age') * .map(function(o) { * return o.user + ' is ' + o.age; * }) * .head() * .value(); * // => 'pebbles is 1' */ function chain(value) { var result = lodash(value); result.__chain__ = true; return result; } /** * This method invokes `interceptor` and returns `value`. The interceptor * is invoked with one argument; (value). The purpose of this method is to * "tap into" a method chain sequence in order to modify intermediate results. * * @static * @memberOf _ * @since 0.1.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns `value`. * @example * * _([1, 2, 3]) * .tap(function(array) { * // Mutate input array. * array.pop(); * }) * .reverse() * .value(); * // => [2, 1] */ function tap(value, interceptor) { interceptor(value); return value; } /** * This method is like `_.tap` except that it returns the result of `interceptor`. * The purpose of this method is to "pass thru" values replacing intermediate * results in a method chain sequence. * * @static * @memberOf _ * @since 3.0.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns the result of `interceptor`. * @example * * _(' abc ') * .chain() * .trim() * .thru(function(value) { * return [value]; * }) * .value(); * // => ['abc'] */ function thru(value, interceptor) { return interceptor(value); } /** * This method is the wrapper version of `_.at`. * * @name at * @memberOf _ * @since 1.0.0 * @category Seq * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _(object).at(['a[0].b.c', 'a[1]']).value(); * // => [3, 4] */ var wrapperAt = flatRest(function(paths) { var length = paths.length, start = length ? paths[0] : 0, value = this.__wrapped__, interceptor = function(object) { return baseAt(object, paths); }; if (length > 1 || this.__actions__.length || !(value instanceof LazyWrapper) || !isIndex(start)) { return this.thru(interceptor); } value = value.slice(start, +start + (length ? 1 : 0)); value.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); return new LodashWrapper(value, this.__chain__).thru(function(array) { if (length && !array.length) { array.push(undefined); } return array; }); }); /** * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. * * @name chain * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * // A sequence without explicit chaining. * _(users).head(); * // => { 'user': 'barney', 'age': 36 } * * // A sequence with explicit chaining. * _(users) * .chain() * .head() * .pick('user') * .value(); * // => { 'user': 'barney' } */ function wrapperChain() { return chain(this); } /** * Executes the chain sequence and returns the wrapped result. * * @name commit * @memberOf _ * @since 3.2.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2]; * var wrapped = _(array).push(3); * * console.log(array); * // => [1, 2] * * wrapped = wrapped.commit(); * console.log(array); * // => [1, 2, 3] * * wrapped.last(); * // => 3 * * console.log(array); * // => [1, 2, 3] */ function wrapperCommit() { return new LodashWrapper(this.value(), this.__chain__); } /** * Gets the next value on a wrapped object following the * [iterator protocol](https://mdn.io/iteration_protocols#iterator). * * @name next * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the next iterator value. * @example * * var wrapped = _([1, 2]); * * wrapped.next(); * // => { 'done': false, 'value': 1 } * * wrapped.next(); * // => { 'done': false, 'value': 2 } * * wrapped.next(); * // => { 'done': true, 'value': undefined } */ function wrapperNext() { if (this.__values__ === undefined) { this.__values__ = toArray(this.value()); } var done = this.__index__ >= this.__values__.length, value = done ? undefined : this.__values__[this.__index__++]; return { 'done': done, 'value': value }; } /** * Enables the wrapper to be iterable. * * @name Symbol.iterator * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the wrapper object. * @example * * var wrapped = _([1, 2]); * * wrapped[Symbol.iterator]() === wrapped; * // => true * * Array.from(wrapped); * // => [1, 2] */ function wrapperToIterator() { return this; } /** * Creates a clone of the chain sequence planting `value` as the wrapped value. * * @name plant * @memberOf _ * @since 3.2.0 * @category Seq * @param {*} value The value to plant. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2]).map(square); * var other = wrapped.plant([3, 4]); * * other.value(); * // => [9, 16] * * wrapped.value(); * // => [1, 4] */ function wrapperPlant(value) { var result, parent = this; while (parent instanceof baseLodash) { var clone = wrapperClone(parent); clone.__index__ = 0; clone.__values__ = undefined; if (result) { previous.__wrapped__ = clone; } else { result = clone; } var previous = clone; parent = parent.__wrapped__; } previous.__wrapped__ = value; return result; } /** * This method is the wrapper version of `_.reverse`. * * **Note:** This method mutates the wrapped array. * * @name reverse * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2, 3]; * * _(array).reverse().value() * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function wrapperReverse() { var value = this.__wrapped__; if (value instanceof LazyWrapper) { var wrapped = value; if (this.__actions__.length) { wrapped = new LazyWrapper(this); } wrapped = wrapped.reverse(); wrapped.__actions__.push({ 'func': thru, 'args': [reverse], 'thisArg': undefined }); return new LodashWrapper(wrapped, this.__chain__); } return this.thru(reverse); } /** * Executes the chain sequence to resolve the unwrapped value. * * @name value * @memberOf _ * @since 0.1.0 * @alias toJSON, valueOf * @category Seq * @returns {*} Returns the resolved unwrapped value. * @example * * _([1, 2, 3]).value(); * // => [1, 2, 3] */ function wrapperValue() { return baseWrapperValue(this.__wrapped__, this.__actions__); } /*------------------------------------------------------------------------*/ /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the number of times the key was returned by `iteratee`. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.5.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.countBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': 1, '6': 2 } * * // The `_.property` iteratee shorthand. * _.countBy(['one', 'two', 'three'], 'length'); * // => { '3': 2, '5': 1 } */ var countBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { ++result[key]; } else { baseAssignValue(result, key, 1); } }); /** * Checks if `predicate` returns truthy for **all** elements of `collection`. * Iteration is stopped once `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index|key, collection). * * **Note:** This method returns `true` for * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of * elements of empty collections. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. * @example * * _.every([true, 1, null, 'yes'], Boolean); * // => false * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.every(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.every(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.every(users, 'active'); * // => false */ function every(collection, predicate, guard) { var func = isArray(collection) ? arrayEvery : baseEvery; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * **Note:** Unlike `_.remove`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.reject * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.filter(users, { 'age': 36, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.filter(users, 'active'); * // => objects for ['barney'] */ function filter(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.find(users, function(o) { return o.age < 40; }); * // => object for 'barney' * * // The `_.matches` iteratee shorthand. * _.find(users, { 'age': 1, 'active': true }); * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.find(users, ['active', false]); * // => object for 'fred' * * // The `_.property` iteratee shorthand. * _.find(users, 'active'); * // => object for 'barney' */ var find = createFind(findIndex); /** * This method is like `_.find` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=collection.length-1] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * _.findLast([1, 2, 3, 4], function(n) { * return n % 2 == 1; * }); * // => 3 */ var findLast = createFind(findLastIndex); /** * Creates a flattened array of values by running each element in `collection` * thru `iteratee` and flattening the mapped results. The iteratee is invoked * with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [n, n]; * } * * _.flatMap([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMap(collection, iteratee) { return baseFlatten(map(collection, iteratee), 1); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDeep([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMapDeep(collection, iteratee) { return baseFlatten(map(collection, iteratee), INFINITY); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results up to `depth` times. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDepth([1, 2], duplicate, 2); * // => [[1, 1], [2, 2]] */ function flatMapDepth(collection, iteratee, depth) { depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(map(collection, iteratee), depth); } /** * Iterates over elements of `collection` and invokes `iteratee` for each element. * The iteratee is invoked with three arguments: (value, index|key, collection). * Iteratee functions may exit iteration early by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" * property are iterated like arrays. To avoid this behavior use `_.forIn` * or `_.forOwn` for object iteration. * * @static * @memberOf _ * @since 0.1.0 * @alias each * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEachRight * @example * * _.forEach([1, 2], function(value) { * console.log(value); * }); * // => Logs `1` then `2`. * * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forEach(collection, iteratee) { var func = isArray(collection) ? arrayEach : baseEach; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.forEach` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @alias eachRight * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEach * @example * * _.forEachRight([1, 2], function(value) { * console.log(value); * }); * // => Logs `2` then `1`. */ function forEachRight(collection, iteratee) { var func = isArray(collection) ? arrayEachRight : baseEachRight; return func(collection, getIteratee(iteratee, 3)); } /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The order of grouped values * is determined by the order they occur in `collection`. The corresponding * value of each key is an array of elements responsible for generating the * key. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.groupBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': [4.2], '6': [6.1, 6.3] } * * // The `_.property` iteratee shorthand. * _.groupBy(['one', 'two', 'three'], 'length'); * // => { '3': ['one', 'two'], '5': ['three'] } */ var groupBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { result[key].push(value); } else { baseAssignValue(result, key, [value]); } }); /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * * _.includes('abcd', 'bc'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike(collection) ? collection : values(collection); fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax(length + fromIndex, 0); } return isString(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && baseIndexOf(collection, value, fromIndex) > -1); } /** * Invokes the method at `path` of each element in `collection`, returning * an array of the results of each invoked method. Any additional arguments * are provided to each invoked method. If `path` is a function, it's invoked * for, and `this` bound to, each element in `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array|Function|string} path The path of the method to invoke or * the function invoked per iteration. * @param {...*} [args] The arguments to invoke each method with. * @returns {Array} Returns the array of results. * @example * * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); * // => [[1, 5, 7], [1, 2, 3]] * * _.invokeMap([123, 456], String.prototype.split, ''); * // => [['1', '2', '3'], ['4', '5', '6']] */ var invokeMap = baseRest(function(collection, path, args) { var index = -1, isFunc = typeof path == 'function', result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value) { result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); }); return result; }); /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the last element responsible for generating the key. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * var array = [ * { 'dir': 'left', 'code': 97 }, * { 'dir': 'right', 'code': 100 } * ]; * * _.keyBy(array, function(o) { * return String.fromCharCode(o.code); * }); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } * * _.keyBy(array, 'dir'); * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } */ var keyBy = createAggregator(function(result, value, key) { baseAssignValue(result, key, value); }); /** * Creates an array of values by running each element in `collection` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new mapped array. * @example * * function square(n) { * return n * n; * } * * _.map([4, 8], square); * // => [16, 64] * * _.map({ 'a': 4, 'b': 8 }, square); * // => [16, 64] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // The `_.property` iteratee shorthand. * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee) { var func = isArray(collection) ? arrayMap : baseMap; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.sortBy` except that it allows specifying the sort * orders of the iteratees to sort by. If `orders` is unspecified, all values * are sorted in ascending order. Otherwise, specify an order of "desc" for * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] * The iteratees to sort by. * @param {string[]} [orders] The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 36 } * ]; * * // Sort by `user` in ascending order and by `age` in descending order. * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return []; } if (!isArray(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } orders = guard ? undefined : orders; if (!isArray(orders)) { orders = orders == null ? [] : [orders]; } return baseOrderBy(collection, iteratees, orders); } /** * Creates an array of elements split into two groups, the first of which * contains elements `predicate` returns truthy for, the second of which * contains elements `predicate` returns falsey for. The predicate is * invoked with one argument: (value). * * @static * @memberOf _ * @since 3.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the array of grouped elements. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true }, * { 'user': 'pebbles', 'age': 1, 'active': false } * ]; * * _.partition(users, function(o) { return o.active; }); * // => objects for [['fred'], ['barney', 'pebbles']] * * // The `_.matches` iteratee shorthand. * _.partition(users, { 'age': 1, 'active': false }); * // => objects for [['pebbles'], ['barney', 'fred']] * * // The `_.matchesProperty` iteratee shorthand. * _.partition(users, ['active', false]); * // => objects for [['barney', 'pebbles'], ['fred']] * * // The `_.property` iteratee shorthand. * _.partition(users, 'active'); * // => objects for [['fred'], ['barney', 'pebbles']] */ var partition = createAggregator(function(result, value, key) { result[key ? 0 : 1].push(value); }, function() { return [[], []]; }); /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` thru `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not given, the first element of `collection` is used as the initial * value. The iteratee is invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, * and `sortBy` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduceRight * @example * * _.reduce([1, 2], function(sum, n) { * return sum + n; * }, 0); * // => 3 * * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * return result; * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) */ function reduce(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); } /** * This method is like `_.reduce` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduce * @example * * var array = [[0, 1], [2, 3], [4, 5]]; * * _.reduceRight(array, function(flattened, other) { * return flattened.concat(other); * }, []); * // => [4, 5, 2, 3, 0, 1] */ function reduceRight(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); } /** * The opposite of `_.filter`; this method returns the elements of `collection` * that `predicate` does **not** return truthy for. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.filter * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true } * ]; * * _.reject(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.reject(users, { 'age': 40, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.reject(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.reject(users, 'active'); * // => objects for ['barney'] */ function reject(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, negate(getIteratee(predicate, 3))); } /** * Gets a random element from `collection`. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @returns {*} Returns the random element. * @example * * _.sample([1, 2, 3, 4]); * // => 2 */ function sample(collection) { var func = isArray(collection) ? arraySample : baseSample; return func(collection); } /** * Gets `n` random elements at unique keys from `collection` up to the * size of `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @param {number} [n=1] The number of elements to sample. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the random elements. * @example * * _.sampleSize([1, 2, 3], 2); * // => [3, 1] * * _.sampleSize([1, 2, 3], 4); * // => [2, 3, 1] */ function sampleSize(collection, n, guard) { if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { n = 1; } else { n = toInteger(n); } var func = isArray(collection) ? arraySampleSize : baseSampleSize; return func(collection, n); } /** * Creates an array of shuffled values, using a version of the * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. * @example * * _.shuffle([1, 2, 3, 4]); * // => [4, 1, 3, 2] */ function shuffle(collection) { var func = isArray(collection) ? arrayShuffle : baseShuffle; return func(collection); } /** * Gets the size of `collection` by returning its length for array-like * values or the number of own enumerable string keyed properties for objects. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @returns {number} Returns the collection size. * @example * * _.size([1, 2, 3]); * // => 3 * * _.size({ 'a': 1, 'b': 2 }); * // => 2 * * _.size('pebbles'); * // => 7 */ function size(collection) { if (collection == null) { return 0; } if (isArrayLike(collection)) { return isString(collection) ? stringSize(collection) : collection.length; } var tag = getTag(collection); if (tag == mapTag || tag == setTag) { return collection.size; } return baseKeys(collection).length; } /** * Checks if `predicate` returns truthy for **any** element of `collection`. * Iteration is stopped once `predicate` returns truthy. The predicate is * invoked with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. * @example * * _.some([null, 0, 'yes', false], Boolean); * // => true * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.some(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.some(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.some(users, 'active'); * // => true */ function some(collection, predicate, guard) { var func = isArray(collection) ? arraySome : baseSome; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, getIteratee(predicate, 3)); } /** * Creates an array of elements, sorted in ascending order by the results of * running each element in a collection thru each iteratee. This method * performs a stable sort, that is, it preserves the original sort order of * equal elements. The iteratees are invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {...(Function|Function[])} [iteratees=[_.identity]] * The iteratees to sort by. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 34 } * ]; * * _.sortBy(users, [function(o) { return o.user; }]); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] * * _.sortBy(users, ['user', 'age']); * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] */ var sortBy = baseRest(function(collection, iteratees) { if (collection == null) { return []; } var length = iteratees.length; if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { iteratees = []; } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { iteratees = [iteratees[0]]; } return baseOrderBy(collection, baseFlatten(iteratees, 1), []); }); /*------------------------------------------------------------------------*/ /** * Gets the timestamp of the number of milliseconds that have elapsed since * the Unix epoch (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ * @since 2.4.0 * @category Date * @returns {number} Returns the timestamp. * @example * * _.defer(function(stamp) { * console.log(_.now() - stamp); * }, _.now()); * // => Logs the number of milliseconds it took for the deferred invocation. */ var now = ctxNow || function() { return root.Date.now(); }; /*------------------------------------------------------------------------*/ /** * The opposite of `_.before`; this method creates a function that invokes * `func` once it's called `n` or more times. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {number} n The number of calls before `func` is invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var saves = ['profile', 'settings']; * * var done = _.after(saves.length, function() { * console.log('done saving!'); * }); * * _.forEach(saves, function(type) { * asyncSave({ 'type': type, 'complete': done }); * }); * // => Logs 'done saving!' after the two async saves have completed. */ function after(n, func) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n < 1) { return func.apply(this, arguments); } }; } /** * Creates a function that invokes `func`, with up to `n` arguments, * ignoring any additional arguments. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @param {number} [n=func.length] The arity cap. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.ary(parseInt, 1)); * // => [6, 8, 10] */ function ary(func, n, guard) { n = guard ? undefined : n; n = (func && n == null) ? func.length : n; return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); } /** * Creates a function that invokes `func`, with the `this` binding and arguments * of the created function, while it's called less than `n` times. Subsequent * calls to the created function return the result of the last `func` invocation. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {number} n The number of calls at which `func` is no longer invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * jQuery(element).on('click', _.before(5, addContactToList)); * // => Allows adding up to 4 contacts to the list. */ function before(n, func) { var result; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n > 0) { result = func.apply(this, arguments); } if (n <= 1) { func = undefined; } return result; }; } /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and `partials` prepended to the arguments it receives. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" * property of bound functions. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * function greet(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // Bound with placeholders. * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = baseRest(function(func, thisArg, partials) { var bitmask = WRAP_BIND_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bind)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(func, bitmask, thisArg, partials, holders); }); /** * Creates a function that invokes the method at `object[key]` with `partials` * prepended to the arguments it receives. * * This method differs from `_.bind` by allowing bound functions to reference * methods that may be redefined or don't yet exist. See * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) * for more details. * * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * @static * @memberOf _ * @since 0.10.0 * @category Function * @param {Object} object The object to invoke the method on. * @param {string} key The key of the method. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var object = { * 'user': 'fred', * 'greet': function(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * }; * * var bound = _.bindKey(object, 'greet', 'hi'); * bound('!'); * // => 'hi fred!' * * object.greet = function(greeting, punctuation) { * return greeting + 'ya ' + this.user + punctuation; * }; * * bound('!'); * // => 'hiya fred!' * * // Bound with placeholders. * var bound = _.bindKey(object, 'greet', _, '!'); * bound('hi'); * // => 'hiya fred!' */ var bindKey = baseRest(function(object, key, partials) { var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bindKey)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(key, bitmask, object, partials, holders); }); /** * Creates a function that accepts arguments of `func` and either invokes * `func` returning its result, if at least `arity` number of arguments have * been provided, or returns a function that accepts the remaining `func` * arguments, and so on. The arity of `func` may be specified if `func.length` * is not sufficient. * * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 2.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curry(abc); * * curried(1)(2)(3); * // => [1, 2, 3] * * curried(1, 2)(3); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(1)(_, 3)(2); * // => [1, 2, 3] */ function curry(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curry.placeholder; return result; } /** * This method is like `_.curry` except that arguments are applied to `func` * in the manner of `_.partialRight` instead of `_.partial`. * * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curryRight(abc); * * curried(3)(2)(1); * // => [1, 2, 3] * * curried(2, 3)(1); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(3)(1, _)(2); * // => [1, 2, 3] */ function curryRight(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curryRight.placeholder; return result; } /** * Creates a debounced function that delays invoking `func` until after `wait` * milliseconds have elapsed since the last time the debounced function was * invoked. The debounced function comes with a `cancel` method to cancel * delayed `func` invocations and a `flush` method to immediately invoke them. * Provide `options` to indicate whether `func` should be invoked on the * leading and/or trailing edge of the `wait` timeout. The `func` is invoked * with the last arguments provided to the debounced function. Subsequent * calls to the debounced function return the result of the last `func` * invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the debounced function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.debounce` and `_.throttle`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to debounce. * @param {number} [wait=0] The number of milliseconds to delay. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=false] * Specify invoking on the leading edge of the timeout. * @param {number} [options.maxWait] * The maximum time `func` is allowed to be delayed before it's invoked. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * // Avoid costly calculations while the window size is in flux. * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); * * // Invoke `sendMail` when clicked, debouncing subsequent calls. * jQuery(element).on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * })); * * // Ensure `batchLog` is invoked once after 1 second of debounced calls. * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); * var source = new EventSource('/stream'); * jQuery(source).on('message', debounced); * * // Cancel the trailing debounced invocation. * jQuery(window).on('popstate', debounced.cancel); */ function debounce(func, wait, options) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } wait = toNumber(wait) || 0; if (isObject(options)) { leading = !!options.leading; maxing = 'maxWait' in options; maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; trailing = 'trailing' in options ? !!options.trailing : trailing; } function invokeFunc(time) { var args = lastArgs, thisArg = lastThis; lastArgs = lastThis = undefined; lastInvokeTime = time; result = func.apply(thisArg, args); return result; } function leadingEdge(time) { // Reset any `maxWait` timer. lastInvokeTime = time; // Start the timer for the trailing edge. timerId = setTimeout(timerExpired, wait); // Invoke the leading edge. return leading ? invokeFunc(time) : result; } function remainingWait(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result = wait - timeSinceLastCall; return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result; } function shouldInvoke(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; // Either this is the first call, activity has stopped and we're at the // trailing edge, the system time has gone backwards and we're treating // it as the trailing edge, or we've hit the `maxWait` limit. return (lastCallTime === undefined || (timeSinceLastCall >= wait) || (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); } function timerExpired() { var time = now(); if (shouldInvoke(time)) { return trailingEdge(time); } // Restart the timer. timerId = setTimeout(timerExpired, remainingWait(time)); } function trailingEdge(time) { timerId = undefined; // Only invoke if we have `lastArgs` which means `func` has been // debounced at least once. if (trailing && lastArgs) { return invokeFunc(time); } lastArgs = lastThis = undefined; return result; } function cancel() { if (timerId !== undefined) { clearTimeout(timerId); } lastInvokeTime = 0; lastArgs = lastCallTime = lastThis = timerId = undefined; } function flush() { return timerId === undefined ? result : trailingEdge(now()); } function debounced() { var time = now(), isInvoking = shouldInvoke(time); lastArgs = arguments; lastThis = this; lastCallTime = time; if (isInvoking) { if (timerId === undefined) { return leadingEdge(lastCallTime); } if (maxing) { // Handle invocations in a tight loop. timerId = setTimeout(timerExpired, wait); return invokeFunc(lastCallTime); } } if (timerId === undefined) { timerId = setTimeout(timerExpired, wait); } return result; } debounced.cancel = cancel; debounced.flush = flush; return debounced; } /** * Defers invoking the `func` until the current call stack has cleared. Any * additional arguments are provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to defer. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.defer(function(text) { * console.log(text); * }, 'deferred'); * // => Logs 'deferred' after one millisecond. */ var defer = baseRest(function(func, args) { return baseDelay(func, 1, args); }); /** * Invokes `func` after `wait` milliseconds. Any additional arguments are * provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.delay(function(text) { * console.log(text); * }, 1000, 'later'); * // => Logs 'later' after one second. */ var delay = baseRest(function(func, wait, args) { return baseDelay(func, toNumber(wait) || 0, args); }); /** * Creates a function that invokes `func` with arguments reversed. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to flip arguments for. * @returns {Function} Returns the new flipped function. * @example * * var flipped = _.flip(function() { * return _.toArray(arguments); * }); * * flipped('a', 'b', 'c', 'd'); * // => ['d', 'c', 'b', 'a'] */ function flip(func) { return createWrap(func, WRAP_FLIP_FLAG); } /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = MapCache; /** * Creates a function that negates the result of the predicate `func`. The * `func` predicate is invoked with the `this` binding and arguments of the * created function. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} predicate The predicate to negate. * @returns {Function} Returns the new negated function. * @example * * function isEven(n) { * return n % 2 == 0; * } * * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); * // => [1, 3, 5] */ function negate(predicate) { if (typeof predicate != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return function() { var args = arguments; switch (args.length) { case 0: return !predicate.call(this); case 1: return !predicate.call(this, args[0]); case 2: return !predicate.call(this, args[0], args[1]); case 3: return !predicate.call(this, args[0], args[1], args[2]); } return !predicate.apply(this, args); }; } /** * Creates a function that is restricted to invoking `func` once. Repeat calls * to the function return the value of the first invocation. The `func` is * invoked with the `this` binding and arguments of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var initialize = _.once(createApplication); * initialize(); * initialize(); * // => `createApplication` is invoked once */ function once(func) { return before(2, func); } /** * Creates a function that invokes `func` with its arguments transformed. * * @static * @since 4.0.0 * @memberOf _ * @category Function * @param {Function} func The function to wrap. * @param {...(Function|Function[])} [transforms=[_.identity]] * The argument transforms. * @returns {Function} Returns the new function. * @example * * function doubled(n) { * return n * 2; * } * * function square(n) { * return n * n; * } * * var func = _.overArgs(function(x, y) { * return [x, y]; * }, [square, doubled]); * * func(9, 3); * // => [81, 6] * * func(10, 5); * // => [100, 10] */ var overArgs = castRest(function(func, transforms) { transforms = (transforms.length == 1 && isArray(transforms[0])) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); var funcsLength = transforms.length; return baseRest(function(args) { var index = -1, length = nativeMin(args.length, funcsLength); while (++index < length) { args[index] = transforms[index].call(this, args[index]); } return apply(func, this, args); }); }); /** * Creates a function that invokes `func` with `partials` prepended to the * arguments it receives. This method is like `_.bind` except it does **not** * alter the `this` binding. * * The `_.partial.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 0.2.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var sayHelloTo = _.partial(greet, 'hello'); * sayHelloTo('fred'); * // => 'hello fred' * * // Partially applied with placeholders. * var greetFred = _.partial(greet, _, 'fred'); * greetFred('hi'); * // => 'hi fred' */ var partial = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partial)); return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); }); /** * This method is like `_.partial` except that partially applied arguments * are appended to the arguments it receives. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 1.0.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // Partially applied with placeholders. * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partialRight)); return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); }); /** * Creates a function that invokes `func` with arguments arranged according * to the specified `indexes` where the argument value at the first index is * provided as the first argument, the argument value at the second index is * provided as the second argument, and so on. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to rearrange arguments for. * @param {...(number|number[])} indexes The arranged argument indexes. * @returns {Function} Returns the new function. * @example * * var rearged = _.rearg(function(a, b, c) { * return [a, b, c]; * }, [2, 0, 1]); * * rearged('b', 'c', 'a') * // => ['a', 'b', 'c'] */ var rearg = flatRest(function(func, indexes) { return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); }); /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as * an array. * * **Note:** This method is based on the * [rest parameter](https://mdn.io/rest_parameters). * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. * @example * * var say = _.rest(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function rest(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start === undefined ? start : toInteger(start); return baseRest(func, start); } /** * Creates a function that invokes `func` with the `this` binding of the * create function and an array of arguments much like * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). * * **Note:** This method is based on the * [spread operator](https://mdn.io/spread_operator). * * @static * @memberOf _ * @since 3.2.0 * @category Function * @param {Function} func The function to spread arguments over. * @param {number} [start=0] The start position of the spread. * @returns {Function} Returns the new function. * @example * * var say = _.spread(function(who, what) { * return who + ' says ' + what; * }); * * say(['fred', 'hello']); * // => 'fred says hello' * * var numbers = Promise.all([ * Promise.resolve(40), * Promise.resolve(36) * ]); * * numbers.then(_.spread(function(x, y) { * return x + y; * })); * // => a Promise of 76 */ function spread(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start == null ? 0 : nativeMax(toInteger(start), 0); return baseRest(function(args) { var array = args[start], otherArgs = castSlice(args, 0, start); if (array) { arrayPush(otherArgs, array); } return apply(func, this, otherArgs); }); } /** * Creates a throttled function that only invokes `func` at most once per * every `wait` milliseconds. The throttled function comes with a `cancel` * method to cancel delayed `func` invocations and a `flush` method to * immediately invoke them. Provide `options` to indicate whether `func` * should be invoked on the leading and/or trailing edge of the `wait` * timeout. The `func` is invoked with the last arguments provided to the * throttled function. Subsequent calls to the throttled function return the * result of the last `func` invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the throttled function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.throttle` and `_.debounce`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to throttle. * @param {number} [wait=0] The number of milliseconds to throttle invocations to. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=true] * Specify invoking on the leading edge of the timeout. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new throttled function. * @example * * // Avoid excessively updating the position while scrolling. * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); * * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); * jQuery(element).on('click', throttled); * * // Cancel the trailing throttled invocation. * jQuery(window).on('popstate', throttled.cancel); */ function throttle(func, wait, options) { var leading = true, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (isObject(options)) { leading = 'leading' in options ? !!options.leading : leading; trailing = 'trailing' in options ? !!options.trailing : trailing; } return debounce(func, wait, { 'leading': leading, 'maxWait': wait, 'trailing': trailing }); } /** * Creates a function that accepts up to one argument, ignoring any * additional arguments. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.unary(parseInt)); * // => [6, 8, 10] */ function unary(func) { return ary(func, 1); } /** * Creates a function that provides `value` to `wrapper` as its first * argument. Any additional arguments provided to the function are appended * to those provided to the `wrapper`. The wrapper is invoked with the `this` * binding of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {*} value The value to wrap. * @param {Function} [wrapper=identity] The wrapper function. * @returns {Function} Returns the new function. * @example * * var p = _.wrap(_.escape, function(func, text) { * return '<p>' + func(text) + '</p>'; * }); * * p('fred, barney, & pebbles'); * // => '<p>fred, barney, &amp; pebbles</p>' */ function wrap(value, wrapper) { return partial(castFunction(wrapper), value); } /*------------------------------------------------------------------------*/ /** * Casts `value` as an array if it's not one. * * @static * @memberOf _ * @since 4.4.0 * @category Lang * @param {*} value The value to inspect. * @returns {Array} Returns the cast array. * @example * * _.castArray(1); * // => [1] * * _.castArray({ 'a': 1 }); * // => [{ 'a': 1 }] * * _.castArray('abc'); * // => ['abc'] * * _.castArray(null); * // => [null] * * _.castArray(undefined); * // => [undefined] * * _.castArray(); * // => [] * * var array = [1, 2, 3]; * console.log(_.castArray(array) === array); * // => true */ function castArray() { if (!arguments.length) { return []; } var value = arguments[0]; return isArray(value) ? value : [value]; } /** * Creates a shallow clone of `value`. * * **Note:** This method is loosely based on the * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) * and supports cloning arrays, array buffers, booleans, date objects, maps, * numbers, `Object` objects, regexes, sets, strings, symbols, and typed * arrays. The own enumerable properties of `arguments` objects are cloned * as plain objects. An empty object is returned for uncloneable values such * as error objects, functions, DOM nodes, and WeakMaps. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to clone. * @returns {*} Returns the cloned value. * @see _.cloneDeep * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var shallow = _.clone(objects); * console.log(shallow[0] === objects[0]); * // => true */ function clone(value) { return baseClone(value, CLONE_SYMBOLS_FLAG); } /** * This method is like `_.clone` except that it accepts `customizer` which * is invoked to produce the cloned value. If `customizer` returns `undefined`, * cloning is handled by the method instead. The `customizer` is invoked with * up to four arguments; (value [, index|key, object, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the cloned value. * @see _.cloneDeepWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(false); * } * } * * var el = _.cloneWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 0 */ function cloneWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); } /** * This method is like `_.clone` except that it recursively clones `value`. * * @static * @memberOf _ * @since 1.0.0 * @category Lang * @param {*} value The value to recursively clone. * @returns {*} Returns the deep cloned value. * @see _.clone * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var deep = _.cloneDeep(objects); * console.log(deep[0] === objects[0]); * // => false */ function cloneDeep(value) { return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); } /** * This method is like `_.cloneWith` except that it recursively clones `value`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to recursively clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the deep cloned value. * @see _.cloneWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(true); * } * } * * var el = _.cloneDeepWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 20 */ function cloneDeepWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); } /** * Checks if `object` conforms to `source` by invoking the predicate * properties of `source` with the corresponding property values of `object`. * * **Note:** This method is equivalent to `_.conforms` when `source` is * partially applied. * * @static * @memberOf _ * @since 4.14.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property predicates to conform to. * @returns {boolean} Returns `true` if `object` conforms, else `false`. * @example * * var object = { 'a': 1, 'b': 2 }; * * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); * // => true * * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); * // => false */ function conformsTo(object, source) { return source == null || baseConformsTo(object, source, keys(source)); } /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } /** * Checks if `value` is greater than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. * @see _.lt * @example * * _.gt(3, 1); * // => true * * _.gt(3, 3); * // => false * * _.gt(1, 3); * // => false */ var gt = createRelationalOperation(baseGt); /** * Checks if `value` is greater than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than or equal to * `other`, else `false`. * @see _.lte * @example * * _.gte(3, 1); * // => true * * _.gte(3, 3); * // => true * * _.gte(1, 3); * // => false */ var gte = createRelationalOperation(function(value, other) { return value >= other; }); /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is classified as an `ArrayBuffer` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. * @example * * _.isArrayBuffer(new ArrayBuffer(2)); * // => true * * _.isArrayBuffer(new Array(2)); * // => false */ var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } /** * Checks if `value` is classified as a boolean primitive or object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. * @example * * _.isBoolean(false); * // => true * * _.isBoolean(null); * // => false */ function isBoolean(value) { return value === true || value === false || (isObjectLike(value) && baseGetTag(value) == boolTag); } /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; /** * Checks if `value` is classified as a `Date` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a date object, else `false`. * @example * * _.isDate(new Date); * // => true * * _.isDate('Mon April 23 2012'); * // => false */ var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; /** * Checks if `value` is likely a DOM element. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. * @example * * _.isElement(document.body); * // => true * * _.isElement('<body>'); * // => false */ function isElement(value) { return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); } /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } if (isArrayLike(value) && (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer(value) || isTypedArray(value) || isArguments(value))) { return !value.length; } var tag = getTag(value); if (tag == mapTag || tag == setTag) { return !value.size; } if (isPrototype(value)) { return !baseKeys(value).length; } for (var key in value) { if (hasOwnProperty.call(value, key)) { return false; } } return true; } /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return baseIsEqual(value, other); } /** * This method is like `_.isEqual` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with up to * six arguments: (objValue, othValue [, index|key, object, other, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, othValue) { * if (isGreeting(objValue) && isGreeting(othValue)) { * return true; * } * } * * var array = ['hello', 'goodbye']; * var other = ['hi', 'goodbye']; * * _.isEqualWith(array, other, customizer); * // => true */ function isEqualWith(value, other, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; var result = customizer ? customizer(value, other) : undefined; return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; } /** * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, * `SyntaxError`, `TypeError`, or `URIError` object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an error object, else `false`. * @example * * _.isError(new Error); * // => true * * _.isError(Error); * // => false */ function isError(value) { if (!isObjectLike(value)) { return false; } var tag = baseGetTag(value); return tag == errorTag || tag == domExcTag || (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); } /** * Checks if `value` is a finite primitive number. * * **Note:** This method is based on * [`Number.isFinite`](https://mdn.io/Number/isFinite). * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. * @example * * _.isFinite(3); * // => true * * _.isFinite(Number.MIN_VALUE); * // => true * * _.isFinite(Infinity); * // => false * * _.isFinite('3'); * // => false */ function isFinite(value) { return typeof value == 'number' && nativeIsFinite(value); } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } /** * Checks if `value` is an integer. * * **Note:** This method is based on * [`Number.isInteger`](https://mdn.io/Number/isInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an integer, else `false`. * @example * * _.isInteger(3); * // => true * * _.isInteger(Number.MIN_VALUE); * // => false * * _.isInteger(Infinity); * // => false * * _.isInteger('3'); * // => false */ function isInteger(value) { return typeof value == 'number' && value == toInteger(value); } /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } /** * Checks if `value` is classified as a `Map` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. * @example * * _.isMap(new Map); * // => true * * _.isMap(new WeakMap); * // => false */ var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; /** * Performs a partial deep comparison between `object` and `source` to * determine if `object` contains equivalent property values. * * **Note:** This method is equivalent to `_.matches` when `source` is * partially applied. * * Partial comparisons will match empty array and empty object `source` * values against any array or object value, respectively. See `_.isEqual` * for a list of supported value comparisons. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * var object = { 'a': 1, 'b': 2 }; * * _.isMatch(object, { 'b': 2 }); * // => true * * _.isMatch(object, { 'b': 1 }); * // => false */ function isMatch(object, source) { return object === source || baseIsMatch(object, source, getMatchData(source)); } /** * This method is like `_.isMatch` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with five * arguments: (objValue, srcValue, index|key, object, source). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, srcValue) { * if (isGreeting(objValue) && isGreeting(srcValue)) { * return true; * } * } * * var object = { 'greeting': 'hello' }; * var source = { 'greeting': 'hi' }; * * _.isMatchWith(object, source, customizer); * // => true */ function isMatchWith(object, source, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseIsMatch(object, source, getMatchData(source), customizer); } /** * Checks if `value` is `NaN`. * * **Note:** This method is based on * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for * `undefined` and other non-number values. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some // ActiveX objects in IE. return isNumber(value) && value != +value; } /** * Checks if `value` is a pristine native function. * * **Note:** This method can't reliably detect native functions in the presence * of the core-js package because core-js circumvents this kind of detection. * Despite multiple requests, the core-js maintainer has made it clear: any * attempt to fix the detection will be obstructed. As a result, we're left * with little choice but to throw an error. Unfortunately, this also affects * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), * which rely on core-js. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (isMaskable(value)) { throw new Error(CORE_ERROR_TEXT); } return baseIsNative(value); } /** * Checks if `value` is `null`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `null`, else `false`. * @example * * _.isNull(null); * // => true * * _.isNull(void 0); * // => false */ function isNull(value) { return value === null; } /** * Checks if `value` is `null` or `undefined`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is nullish, else `false`. * @example * * _.isNil(null); * // => true * * _.isNil(void 0); * // => true * * _.isNil(NaN); * // => false */ function isNil(value) { return value == null; } /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a number, else `false`. * @example * * _.isNumber(3); * // => true * * _.isNumber(Number.MIN_VALUE); * // => true * * _.isNumber(Infinity); * // => true * * _.isNumber('3'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike(value) && baseGetTag(value) == numberTag); } /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || baseGetTag(value) != objectTag) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } /** * Checks if `value` is classified as a `RegExp` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. * @example * * _.isRegExp(/abc/); * // => true * * _.isRegExp('/abc/'); * // => false */ var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; /** * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 * double precision number which isn't the result of a rounded unsafe integer. * * **Note:** This method is based on * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. * @example * * _.isSafeInteger(3); * // => true * * _.isSafeInteger(Number.MIN_VALUE); * // => false * * _.isSafeInteger(Infinity); * // => false * * _.isSafeInteger('3'); * // => false */ function isSafeInteger(value) { return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is classified as a `Set` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. * @example * * _.isSet(new Set); * // => true * * _.isSet(new WeakSet); * // => false */ var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && baseGetTag(value) == symbolTag); } /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; /** * Checks if `value` is `undefined`. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } /** * Checks if `value` is classified as a `WeakMap` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. * @example * * _.isWeakMap(new WeakMap); * // => true * * _.isWeakMap(new Map); * // => false */ function isWeakMap(value) { return isObjectLike(value) && getTag(value) == weakMapTag; } /** * Checks if `value` is classified as a `WeakSet` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. * @example * * _.isWeakSet(new WeakSet); * // => true * * _.isWeakSet(new Set); * // => false */ function isWeakSet(value) { return isObjectLike(value) && baseGetTag(value) == weakSetTag; } /** * Checks if `value` is less than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. * @see _.gt * @example * * _.lt(1, 3); * // => true * * _.lt(3, 3); * // => false * * _.lt(3, 1); * // => false */ var lt = createRelationalOperation(baseLt); /** * Checks if `value` is less than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than or equal to * `other`, else `false`. * @see _.gte * @example * * _.lte(1, 3); * // => true * * _.lte(3, 3); * // => true * * _.lte(3, 1); * // => false */ var lte = createRelationalOperation(function(value, other) { return value <= other; }); /** * Converts `value` to an array. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {Array} Returns the converted array. * @example * * _.toArray({ 'a': 1, 'b': 2 }); * // => [1, 2] * * _.toArray('abc'); * // => ['a', 'b', 'c'] * * _.toArray(1); * // => [] * * _.toArray(null); * // => [] */ function toArray(value) { if (!value) { return []; } if (isArrayLike(value)) { return isString(value) ? stringToArray(value) : copyArray(value); } if (symIterator && value[symIterator]) { return iteratorToArray(value[symIterator]()); } var tag = getTag(value), func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); return func(value); } /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber(value); if (value === INFINITY || value === -INFINITY) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } /** * Converts `value` to an integer suitable for use as the length of an * array-like object. * * **Note:** This method is based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toLength(3.2); * // => 3 * * _.toLength(Number.MIN_VALUE); * // => 0 * * _.toLength(Infinity); * // => 4294967295 * * _.toLength('3.2'); * // => 3 */ function toLength(value) { return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; } /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } /** * Converts `value` to a plain object flattening inherited enumerable string * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return copyObject(value, keysIn(value)); } /** * Converts `value` to a safe integer. A safe integer can be compared and * represented correctly. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toSafeInteger(3.2); * // => 3 * * _.toSafeInteger(Number.MIN_VALUE); * // => 0 * * _.toSafeInteger(Infinity); * // => 9007199254740991 * * _.toSafeInteger('3.2'); * // => 3 */ function toSafeInteger(value) { return value ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) : (value === 0 ? value : 0); } /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } /*------------------------------------------------------------------------*/ /** * Assigns own enumerable string keyed properties of source objects to the * destination object. Source objects are applied from left to right. * Subsequent sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object` and is loosely based on * [`Object.assign`](https://mdn.io/Object/assign). * * @static * @memberOf _ * @since 0.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assignIn * @example * * function Foo() { * this.a = 1; * } * * function Bar() { * this.c = 3; * } * * Foo.prototype.b = 2; * Bar.prototype.d = 4; * * _.assign({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'c': 3 } */ var assign = createAssigner(function(object, source) { if (isPrototype(source) || isArrayLike(source)) { copyObject(source, keys(source), object); return; } for (var key in source) { if (hasOwnProperty.call(source, key)) { assignValue(object, key, source[key]); } } }); /** * This method is like `_.assign` except that it iterates over own and * inherited source properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extend * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assign * @example * * function Foo() { * this.a = 1; * } * * function Bar() { * this.c = 3; * } * * Foo.prototype.b = 2; * Bar.prototype.d = 4; * * _.assignIn({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } */ var assignIn = createAssigner(function(object, source) { copyObject(source, keysIn(source), object); }); /** * This method is like `_.assignIn` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extendWith * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignInWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keysIn(source), object, customizer); }); /** * This method is like `_.assign` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignInWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keys(source), object, customizer); }); /** * Creates an array of values corresponding to `paths` of `object`. * * @static * @memberOf _ * @since 1.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Array} Returns the picked values. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _.at(object, ['a[0].b.c', 'a[1]']); * // => [3, 4] */ var at = flatRest(baseAt); /** * Creates an object that inherits from the `prototype` object. If a * `properties` object is given, its own enumerable string keyed properties * are assigned to the created object. * * @static * @memberOf _ * @since 2.3.0 * @category Object * @param {Object} prototype The object to inherit from. * @param {Object} [properties] The properties to assign to the object. * @returns {Object} Returns the new object. * @example * * function Shape() { * this.x = 0; * this.y = 0; * } * * function Circle() { * Shape.call(this); * } * * Circle.prototype = _.create(Shape.prototype, { * 'constructor': Circle * }); * * var circle = new Circle; * circle instanceof Circle; * // => true * * circle instanceof Shape; * // => true */ function create(prototype, properties) { var result = baseCreate(prototype); return properties == null ? result : baseAssign(result, properties); } /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to `undefined`. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaultsDeep * @example * * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var defaults = baseRest(function(args) { args.push(undefined, customDefaultsAssignIn); return apply(assignInWith, undefined, args); }); /** * This method is like `_.defaults` except that it recursively assigns * default properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaults * @example * * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); * // => { 'a': { 'b': 2, 'c': 3 } } */ var defaultsDeep = baseRest(function(args) { args.push(undefined, customDefaultsMerge); return apply(mergeWith, undefined, args); }); /** * This method is like `_.find` except that it returns the key of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Object * @param {Object} object The object to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findKey(users, function(o) { return o.age < 40; }); * // => 'barney' (iteration order is not guaranteed) * * // The `_.matches` iteratee shorthand. * _.findKey(users, { 'age': 1, 'active': true }); * // => 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.findKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findKey(users, 'active'); * // => 'barney' */ function findKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); } /** * This method is like `_.findKey` except that it iterates over elements of * a collection in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findLastKey(users, function(o) { return o.age < 40; }); * // => returns 'pebbles' assuming `_.findKey` returns 'barney' * * // The `_.matches` iteratee shorthand. * _.findLastKey(users, { 'age': 36, 'active': true }); * // => 'barney' * * // The `_.matchesProperty` iteratee shorthand. * _.findLastKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findLastKey(users, 'active'); * // => 'pebbles' */ function findLastKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); } /** * Iterates over own and inherited enumerable string keyed properties of an * object and invokes `iteratee` for each property. The iteratee is invoked * with three arguments: (value, key, object). Iteratee functions may exit * iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forInRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forIn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). */ function forIn(object, iteratee) { return object == null ? object : baseFor(object, getIteratee(iteratee, 3), keysIn); } /** * This method is like `_.forIn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forIn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forInRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. */ function forInRight(object, iteratee) { return object == null ? object : baseForRight(object, getIteratee(iteratee, 3), keysIn); } /** * Iterates over own enumerable string keyed properties of an object and * invokes `iteratee` for each property. The iteratee is invoked with three * arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwnRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forOwn(object, iteratee) { return object && baseForOwn(object, getIteratee(iteratee, 3)); } /** * This method is like `_.forOwn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwnRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. */ function forOwnRight(object, iteratee) { return object && baseForOwnRight(object, getIteratee(iteratee, 3)); } /** * Creates an array of function property names from own enumerable properties * of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functionsIn * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functions(new Foo); * // => ['a', 'b'] */ function functions(object) { return object == null ? [] : baseFunctions(object, keys(object)); } /** * Creates an array of function property names from own and inherited * enumerable properties of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functions * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functionsIn(new Foo); * // => ['a', 'b', 'c'] */ function functionsIn(object) { return object == null ? [] : baseFunctions(object, keysIn(object)); } /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } /** * Checks if `path` is a direct property of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': 2 } }; * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b'); * // => true * * _.has(object, ['a', 'b']); * // => true * * _.has(other, 'a'); * // => false */ function has(object, path) { return object != null && hasPath(object, path, baseHas); } /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn); } /** * Creates an object composed of the inverted keys and values of `object`. * If `object` contains duplicate values, subsequent values overwrite * property assignments of previous values. * * @static * @memberOf _ * @since 0.7.0 * @category Object * @param {Object} object The object to invert. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invert(object); * // => { '1': 'c', '2': 'b' } */ var invert = createInverter(function(result, value, key) { result[value] = key; }, constant(identity)); /** * This method is like `_.invert` except that the inverted object is generated * from the results of running each element of `object` thru `iteratee`. The * corresponding inverted value of each inverted key is an array of keys * responsible for generating the inverted value. The iteratee is invoked * with one argument: (value). * * @static * @memberOf _ * @since 4.1.0 * @category Object * @param {Object} object The object to invert. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invertBy(object); * // => { '1': ['a', 'c'], '2': ['b'] } * * _.invertBy(object, function(value) { * return 'group' + value; * }); * // => { 'group1': ['a', 'c'], 'group2': ['b'] } */ var invertBy = createInverter(function(result, value, key) { if (hasOwnProperty.call(result, value)) { result[value].push(key); } else { result[value] = [key]; } }, getIteratee); /** * Invokes the method at `path` of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {...*} [args] The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. * @example * * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; * * _.invoke(object, 'a[0].b.c.slice', 1, 3); * // => [2, 3] */ var invoke = baseRest(baseInvoke); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } /** * The opposite of `_.mapValues`; this method creates an object with the * same values as `object` and keys generated by running each own enumerable * string keyed property of `object` thru `iteratee`. The iteratee is invoked * with three arguments: (value, key, object). * * @static * @memberOf _ * @since 3.8.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapValues * @example * * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { * return key + value; * }); * // => { 'a1': 1, 'b2': 2 } */ function mapKeys(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, iteratee(value, key, object), value); }); return result; } /** * Creates an object with the same keys as `object` and values generated * by running each own enumerable string keyed property of `object` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, key, object). * * @static * @memberOf _ * @since 2.4.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapKeys * @example * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * _.mapValues(users, function(o) { return o.age; }); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) * * // The `_.property` iteratee shorthand. * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ function mapValues(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, key, iteratee(value, key, object)); }); return result; } /** * This method is like `_.assign` except that it recursively merges own and * inherited enumerable string keyed properties of source objects into the * destination object. Source properties that resolve to `undefined` are * skipped if a destination value exists. Array and plain object properties * are merged recursively. Other objects and value types are overridden by * assignment. Source objects are applied from left to right. Subsequent * sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 0.5.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var object = { * 'a': [{ 'b': 2 }, { 'd': 4 }] * }; * * var other = { * 'a': [{ 'c': 3 }, { 'e': 5 }] * }; * * _.merge(object, other); * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ var merge = createAssigner(function(object, source, srcIndex) { baseMerge(object, source, srcIndex); }); /** * This method is like `_.merge` except that it accepts `customizer` which * is invoked to produce the merged values of the destination and source * properties. If `customizer` returns `undefined`, merging is handled by the * method instead. The `customizer` is invoked with six arguments: * (objValue, srcValue, key, object, source, stack). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} customizer The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * function customizer(objValue, srcValue) { * if (_.isArray(objValue)) { * return objValue.concat(srcValue); * } * } * * var object = { 'a': [1], 'b': [2] }; * var other = { 'a': [3], 'b': [4] }; * * _.mergeWith(object, other, customizer); * // => { 'a': [1, 3], 'b': [2, 4] } */ var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { baseMerge(object, source, srcIndex, customizer); }); /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable property paths of `object` that are not omitted. * * **Note:** This method is considerably slower than `_.pick`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to omit. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ var omit = flatRest(function(object, paths) { var result = {}; if (object == null) { return result; } var isDeep = false; paths = arrayMap(paths, function(path) { path = castPath(path, object); isDeep || (isDeep = path.length > 1); return path; }); copyObject(object, getAllKeysIn(object), result); if (isDeep) { result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); } var length = paths.length; while (length--) { baseUnset(result, paths[length]); } return result; }); /** * The opposite of `_.pickBy`; this method creates an object composed of * the own and inherited enumerable string keyed properties of `object` that * `predicate` doesn't return truthy for. The predicate is invoked with two * arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omitBy(object, _.isNumber); * // => { 'b': '2' } */ function omitBy(object, predicate) { return pickBy(object, negate(getIteratee(predicate))); } /** * Creates an object composed of the picked `object` properties. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ var pick = flatRest(function(object, paths) { return object == null ? {} : basePick(object, paths); }); /** * Creates an object composed of the `object` properties `predicate` returns * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ function pickBy(object, predicate) { if (object == null) { return {}; } var props = arrayMap(getAllKeysIn(object), function(prop) { return [prop]; }); predicate = getIteratee(predicate); return basePickBy(object, props, function(value, path) { return predicate(value, path[0]); }); } /** * This method is like `_.get` except that if the resolved value is a * function it's invoked with the `this` binding of its parent object and * its result is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to resolve. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; * * _.result(object, 'a[0].b.c1'); * // => 3 * * _.result(object, 'a[0].b.c2'); * // => 4 * * _.result(object, 'a[0].b.c3', 'default'); * // => 'default' * * _.result(object, 'a[0].b.c3', _.constant('default')); * // => 'default' */ function result(object, path, defaultValue) { path = castPath(path, object); var index = -1, length = path.length; // Ensure the loop is entered when path is empty. if (!length) { length = 1; object = undefined; } while (++index < length) { var value = object == null ? undefined : object[toKey(path[index])]; if (value === undefined) { index = length; value = defaultValue; } object = isFunction(value) ? value.call(object) : value; } return object; } /** * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, * it's created. Arrays are created for missing index properties while objects * are created for all other missing properties. Use `_.setWith` to customize * `path` creation. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.set(object, 'a[0].b.c', 4); * console.log(object.a[0].b.c); * // => 4 * * _.set(object, ['x', '0', 'y', 'z'], 5); * console.log(object.x[0].y.z); * // => 5 */ function set(object, path, value) { return object == null ? object : baseSet(object, path, value); } /** * This method is like `_.set` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.setWith(object, '[0][1]', 'a', Object); * // => { '0': { '1': 'a' } } */ function setWith(object, path, value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseSet(object, path, value, customizer); } /** * Creates an array of own enumerable string keyed-value pairs for `object` * which can be consumed by `_.fromPairs`. If `object` is a map or set, its * entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entries * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairs(new Foo); * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) */ var toPairs = createToPairs(keys); /** * Creates an array of own and inherited enumerable string keyed-value pairs * for `object` which can be consumed by `_.fromPairs`. If `object` is a map * or set, its entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entriesIn * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairsIn(new Foo); * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) */ var toPairsIn = createToPairs(keysIn); /** * An alternative to `_.reduce`; this method transforms `object` to a new * `accumulator` object which is the result of running each of its own * enumerable string keyed properties thru `iteratee`, with each invocation * potentially mutating the `accumulator` object. If `accumulator` is not * provided, a new object with the same `[[Prototype]]` will be used. The * iteratee is invoked with four arguments: (accumulator, value, key, object). * Iteratee functions may exit iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 1.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The custom accumulator value. * @returns {*} Returns the accumulated value. * @example * * _.transform([2, 3, 4], function(result, n) { * result.push(n *= n); * return n % 2 == 0; * }, []); * // => [4, 9] * * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } */ function transform(object, iteratee, accumulator) { var isArr = isArray(object), isArrLike = isArr || isBuffer(object) || isTypedArray(object); iteratee = getIteratee(iteratee, 4); if (accumulator == null) { var Ctor = object && object.constructor; if (isArrLike) { accumulator = isArr ? new Ctor : []; } else if (isObject(object)) { accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; } else { accumulator = {}; } } (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { return iteratee(accumulator, value, index, object); }); return accumulator; } /** * Removes the property at `path` of `object`. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. * @example * * var object = { 'a': [{ 'b': { 'c': 7 } }] }; * _.unset(object, 'a[0].b.c'); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; * * _.unset(object, ['a', '0', 'b', 'c']); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; */ function unset(object, path) { return object == null ? true : baseUnset(object, path); } /** * This method is like `_.set` except that accepts `updater` to produce the * value to set. Use `_.updateWith` to customize `path` creation. The `updater` * is invoked with one argument: (value). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.update(object, 'a[0].b.c', function(n) { return n * n; }); * console.log(object.a[0].b.c); * // => 9 * * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); * console.log(object.x[0].y.z); * // => 0 */ function update(object, path, updater) { return object == null ? object : baseUpdate(object, path, castFunction(updater)); } /** * This method is like `_.update` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.updateWith(object, '[0][1]', _.constant('a'), Object); * // => { '0': { '1': 'a' } } */ function updateWith(object, path, updater, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); } /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object == null ? [] : baseValues(object, keys(object)); } /** * Creates an array of the own and inherited enumerable string keyed property * values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.valuesIn(new Foo); * // => [1, 2, 3] (iteration order is not guaranteed) */ function valuesIn(object) { return object == null ? [] : baseValues(object, keysIn(object)); } /*------------------------------------------------------------------------*/ /** * Clamps `number` within the inclusive `lower` and `upper` bounds. * * @static * @memberOf _ * @since 4.0.0 * @category Number * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. * @example * * _.clamp(-10, -5, 5); * // => -5 * * _.clamp(10, -5, 5); * // => 5 */ function clamp(number, lower, upper) { if (upper === undefined) { upper = lower; lower = undefined; } if (upper !== undefined) { upper = toNumber(upper); upper = upper === upper ? upper : 0; } if (lower !== undefined) { lower = toNumber(lower); lower = lower === lower ? lower : 0; } return baseClamp(toNumber(number), lower, upper); } /** * Checks if `n` is between `start` and up to, but not including, `end`. If * `end` is not specified, it's set to `start` with `start` then set to `0`. * If `start` is greater than `end` the params are swapped to support * negative ranges. * * @static * @memberOf _ * @since 3.3.0 * @category Number * @param {number} number The number to check. * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. * @see _.range, _.rangeRight * @example * * _.inRange(3, 2, 4); * // => true * * _.inRange(4, 8); * // => true * * _.inRange(4, 2); * // => false * * _.inRange(2, 2); * // => false * * _.inRange(1.2, 2); * // => true * * _.inRange(5.2, 4); * // => false * * _.inRange(-3, -2, -6); * // => true */ function inRange(number, start, end) { start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } number = toNumber(number); return baseInRange(number, start, end); } /** * Produces a random number between the inclusive `lower` and `upper` bounds. * If only one argument is provided a number between `0` and the given number * is returned. If `floating` is `true`, or either `lower` or `upper` are * floats, a floating-point number is returned instead of an integer. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @memberOf _ * @since 0.7.0 * @category Number * @param {number} [lower=0] The lower bound. * @param {number} [upper=1] The upper bound. * @param {boolean} [floating] Specify returning a floating-point number. * @returns {number} Returns the random number. * @example * * _.random(0, 5); * // => an integer between 0 and 5 * * _.random(5); * // => also an integer between 0 and 5 * * _.random(5, true); * // => a floating-point number between 0 and 5 * * _.random(1.2, 5.2); * // => a floating-point number between 1.2 and 5.2 */ function random(lower, upper, floating) { if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { upper = floating = undefined; } if (floating === undefined) { if (typeof upper == 'boolean') { floating = upper; upper = undefined; } else if (typeof lower == 'boolean') { floating = lower; lower = undefined; } } if (lower === undefined && upper === undefined) { lower = 0; upper = 1; } else { lower = toFinite(lower); if (upper === undefined) { upper = lower; lower = 0; } else { upper = toFinite(upper); } } if (lower > upper) { var temp = lower; lower = upper; upper = temp; } if (floating || lower % 1 || upper % 1) { var rand = nativeRandom(); return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); } return baseRandom(lower, upper); } /*------------------------------------------------------------------------*/ /** * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the camel cased string. * @example * * _.camelCase('Foo Bar'); * // => 'fooBar' * * _.camelCase('--foo-bar--'); * // => 'fooBar' * * _.camelCase('__FOO_BAR__'); * // => 'fooBar' */ var camelCase = createCompounder(function(result, word, index) { word = word.toLowerCase(); return result + (index ? capitalize(word) : word); }); /** * Converts the first character of `string` to upper case and the remaining * to lower case. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to capitalize. * @returns {string} Returns the capitalized string. * @example * * _.capitalize('FRED'); * // => 'Fred' */ function capitalize(string) { return upperFirst(toString(string).toLowerCase()); } /** * Deburrs `string` by converting * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) * letters to basic Latin letters and removing * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to deburr. * @returns {string} Returns the deburred string. * @example * * _.deburr('déjà vu'); * // => 'deja vu' */ function deburr(string) { string = toString(string); return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); } /** * Checks if `string` ends with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=string.length] The position to search up to. * @returns {boolean} Returns `true` if `string` ends with `target`, * else `false`. * @example * * _.endsWith('abc', 'c'); * // => true * * _.endsWith('abc', 'b'); * // => false * * _.endsWith('abc', 'b', 2); * // => true */ function endsWith(string, target, position) { string = toString(string); target = baseToString(target); var length = string.length; position = position === undefined ? length : baseClamp(toInteger(position), 0, length); var end = position; position -= target.length; return position >= 0 && string.slice(position, end) == target; } /** * Converts the characters "&", "<", ">", '"', and "'" in `string` to their * corresponding HTML entities. * * **Note:** No other characters are escaped. To escape additional * characters use a third-party library like [_he_](https://mths.be/he). * * Though the ">" character is escaped for symmetry, characters like * ">" and "/" don't need escaping in HTML and have no special meaning * unless they're part of a tag or unquoted attribute value. See * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) * (under "semi-related fun fact") for more details. * * When working with HTML you should always * [quote attribute values](http://wonko.com/post/html-escaping) to reduce * XSS vectors. * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escape('fred, barney, & pebbles'); * // => 'fred, barney, &amp; pebbles' */ function escape(string) { string = toString(string); return (string && reHasUnescapedHtml.test(string)) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string; } /** * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https://lodash\.com/\)' */ function escapeRegExp(string) { string = toString(string); return (string && reHasRegExpChar.test(string)) ? string.replace(reRegExpChar, '\\$&') : string; } /** * Converts `string` to * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the kebab cased string. * @example * * _.kebabCase('Foo Bar'); * // => 'foo-bar' * * _.kebabCase('fooBar'); * // => 'foo-bar' * * _.kebabCase('__FOO_BAR__'); * // => 'foo-bar' */ var kebabCase = createCompounder(function(result, word, index) { return result + (index ? '-' : '') + word.toLowerCase(); }); /** * Converts `string`, as space separated words, to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the lower cased string. * @example * * _.lowerCase('--Foo-Bar--'); * // => 'foo bar' * * _.lowerCase('fooBar'); * // => 'foo bar' * * _.lowerCase('__FOO_BAR__'); * // => 'foo bar' */ var lowerCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + word.toLowerCase(); }); /** * Converts the first character of `string` to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.lowerFirst('Fred'); * // => 'fred' * * _.lowerFirst('FRED'); * // => 'fRED' */ var lowerFirst = createCaseFirst('toLowerCase'); /** * Pads `string` on the left and right sides if it's shorter than `length`. * Padding characters are truncated if they can't be evenly divided by `length`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.pad('abc', 8); * // => ' abc ' * * _.pad('abc', 8, '_-'); * // => '_-abc_-_' * * _.pad('abc', 3); * // => 'abc' */ function pad(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; if (!length || strLength >= length) { return string; } var mid = (length - strLength) / 2; return ( createPadding(nativeFloor(mid), chars) + string + createPadding(nativeCeil(mid), chars) ); } /** * Pads `string` on the right side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padEnd('abc', 6); * // => 'abc ' * * _.padEnd('abc', 6, '_-'); * // => 'abc_-_' * * _.padEnd('abc', 3); * // => 'abc' */ function padEnd(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return (length && strLength < length) ? (string + createPadding(length - strLength, chars)) : string; } /** * Pads `string` on the left side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padStart('abc', 6); * // => ' abc' * * _.padStart('abc', 6, '_-'); * // => '_-_abc' * * _.padStart('abc', 3); * // => 'abc' */ function padStart(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return (length && strLength < length) ? (createPadding(length - strLength, chars) + string) : string; } /** * Converts `string` to an integer of the specified radix. If `radix` is * `undefined` or `0`, a `radix` of `10` is used unless `value` is a * hexadecimal, in which case a `radix` of `16` is used. * * **Note:** This method aligns with the * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. * * @static * @memberOf _ * @since 1.1.0 * @category String * @param {string} string The string to convert. * @param {number} [radix=10] The radix to interpret `value` by. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {number} Returns the converted integer. * @example * * _.parseInt('08'); * // => 8 * * _.map(['6', '08', '10'], _.parseInt); * // => [6, 8, 10] */ function parseInt(string, radix, guard) { if (guard || radix == null) { radix = 0; } else if (radix) { radix = +radix; } return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); } /** * Repeats the given string `n` times. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to repeat. * @param {number} [n=1] The number of times to repeat the string. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the repeated string. * @example * * _.repeat('*', 3); * // => '***' * * _.repeat('abc', 2); * // => 'abcabc' * * _.repeat('abc', 0); * // => '' */ function repeat(string, n, guard) { if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { n = 1; } else { n = toInteger(n); } return baseRepeat(toString(string), n); } /** * Replaces matches for `pattern` in `string` with `replacement`. * * **Note:** This method is based on * [`String#replace`](https://mdn.io/String/replace). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to modify. * @param {RegExp|string} pattern The pattern to replace. * @param {Function|string} replacement The match replacement. * @returns {string} Returns the modified string. * @example * * _.replace('Hi Fred', 'Fred', 'Barney'); * // => 'Hi Barney' */ function replace() { var args = arguments, string = toString(args[0]); return args.length < 3 ? string : string.replace(args[1], args[2]); } /** * Converts `string` to * [snake case](https://en.wikipedia.org/wiki/Snake_case). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the snake cased string. * @example * * _.snakeCase('Foo Bar'); * // => 'foo_bar' * * _.snakeCase('fooBar'); * // => 'foo_bar' * * _.snakeCase('--FOO-BAR--'); * // => 'foo_bar' */ var snakeCase = createCompounder(function(result, word, index) { return result + (index ? '_' : '') + word.toLowerCase(); }); /** * Splits `string` by `separator`. * * **Note:** This method is based on * [`String#split`](https://mdn.io/String/split). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to split. * @param {RegExp|string} separator The separator pattern to split by. * @param {number} [limit] The length to truncate results to. * @returns {Array} Returns the string segments. * @example * * _.split('a-b-c', '-', 2); * // => ['a', 'b'] */ function split(string, separator, limit) { if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { separator = limit = undefined; } limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; if (!limit) { return []; } string = toString(string); if (string && ( typeof separator == 'string' || (separator != null && !isRegExp(separator)) )) { separator = baseToString(separator); if (!separator && hasUnicode(string)) { return castSlice(stringToArray(string), 0, limit); } } return string.split(separator, limit); } /** * Converts `string` to * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). * * @static * @memberOf _ * @since 3.1.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the start cased string. * @example * * _.startCase('--foo-bar--'); * // => 'Foo Bar' * * _.startCase('fooBar'); * // => 'Foo Bar' * * _.startCase('__FOO_BAR__'); * // => 'FOO BAR' */ var startCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + upperFirst(word); }); /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, * else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString(string); position = position == null ? 0 : baseClamp(toInteger(position), 0, string.length); target = baseToString(target); return string.slice(position, position + target.length) == target; } /** * Creates a compiled template function that can interpolate data properties * in "interpolate" delimiters, HTML-escape interpolated data properties in * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data * properties may be accessed as free variables in the template. If a setting * object is given, it takes precedence over `_.templateSettings` values. * * **Note:** In the development build `_.template` utilizes * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) * for easier debugging. * * For more information on precompiling templates see * [lodash's custom builds documentation](https://lodash.com/custom-builds). * * For more information on Chrome extension sandboxes see * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The template string. * @param {Object} [options={}] The options object. * @param {RegExp} [options.escape=_.templateSettings.escape] * The HTML "escape" delimiter. * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] * The "evaluate" delimiter. * @param {Object} [options.imports=_.templateSettings.imports] * An object to import into the template as free variables. * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] * The "interpolate" delimiter. * @param {string} [options.sourceURL='lodash.templateSources[n]'] * The sourceURL of the compiled template. * @param {string} [options.variable='obj'] * The data object variable name. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the compiled template function. * @example * * // Use the "interpolate" delimiter to create a compiled template. * var compiled = _.template('hello <%= user %>!'); * compiled({ 'user': 'fred' }); * // => 'hello fred!' * * // Use the HTML "escape" delimiter to escape data property values. * var compiled = _.template('<b><%- value %></b>'); * compiled({ 'value': '<script>' }); * // => '<b>&lt;script&gt;</b>' * * // Use the "evaluate" delimiter to execute JavaScript and generate HTML. * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>'); * compiled({ 'users': ['fred', 'barney'] }); * // => '<li>fred</li><li>barney</li>' * * // Use the internal `print` function in "evaluate" delimiters. * var compiled = _.template('<% print("hello " + user); %>!'); * compiled({ 'user': 'barney' }); * // => 'hello barney!' * * // Use the ES template literal delimiter as an "interpolate" delimiter. * // Disable support by replacing the "interpolate" delimiter. * var compiled = _.template('hello ${ user }!'); * compiled({ 'user': 'pebbles' }); * // => 'hello pebbles!' * * // Use backslashes to treat delimiters as plain text. * var compiled = _.template('<%= "\\<%- value %\\>" %>'); * compiled({ 'value': 'ignored' }); * // => '<%- value %>' * * // Use the `imports` option to import `jQuery` as `jq`. * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>'; * var compiled = _.template(text, { 'imports': { 'jq': jQuery } }); * compiled({ 'users': ['fred', 'barney'] }); * // => '<li>fred</li><li>barney</li>' * * // Use the `sourceURL` option to specify a custom sourceURL for the template. * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' }); * compiled(data); * // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector. * * // Use the `variable` option to ensure a with-statement isn't used in the compiled template. * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' }); * compiled.source; * // => function(data) { * // var __t, __p = ''; * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!'; * // return __p; * // } * * // Use custom template delimiters. * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g; * var compiled = _.template('hello {{ user }}!'); * compiled({ 'user': 'mustache' }); * // => 'hello mustache!' * * // Use the `source` property to inline compiled templates for meaningful * // line numbers in error messages and stack traces. * fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\ * var JST = {\ * "main": ' + _.template(mainText).source + '\ * };\ * '); */ function template(string, options, guard) { // Based on John Resig's `tmpl` implementation // (http://ejohn.org/blog/javascript-micro-templating/) // and Laura Doktorova's doT.js (https://github.com/olado/doT). var settings = lodash.templateSettings; if (guard && isIterateeCall(string, options, guard)) { options = undefined; } string = toString(string); options = assignInWith({}, options, settings, customDefaultsAssignIn); var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn), importsKeys = keys(imports), importsValues = baseValues(imports, importsKeys); var isEscaping, isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '"; // Compile the regexp to match each delimiter. var reDelimiters = RegExp( (options.escape || reNoMatch).source + '|' + interpolate.source + '|' + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' + (options.evaluate || reNoMatch).source + '|$' , 'g'); // Use a sourceURL for easier debugging. var sourceURL = '//# sourceURL=' + ('sourceURL' in options ? options.sourceURL : ('lodash.templateSources[' + (++templateCounter) + ']') ) + '\n'; string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { interpolateValue || (interpolateValue = esTemplateValue); // Escape characters that can't be included in string literals. source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar); // Replace delimiters with snippets. if (escapeValue) { isEscaping = true; source += "' +\n__e(" + escapeValue + ") +\n'"; } if (evaluateValue) { isEvaluating = true; source += "';\n" + evaluateValue + ";\n__p += '"; } if (interpolateValue) { source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; } index = offset + match.length; // The JS engine embedded in Adobe products needs `match` returned in // order to produce the correct `offset` value. return match; }); source += "';\n"; // If `variable` is not specified wrap a with-statement around the generated // code to add the data object to the top of the scope chain. var variable = options.variable; if (!variable) { source = 'with (obj) {\n' + source + '\n}\n'; } // Cleanup code by stripping empty strings. source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source) .replace(reEmptyStringMiddle, '$1') .replace(reEmptyStringTrailing, '$1;'); // Frame code as the function body. source = 'function(' + (variable || 'obj') + ') {\n' + (variable ? '' : 'obj || (obj = {});\n' ) + "var __t, __p = ''" + (isEscaping ? ', __e = _.escape' : '' ) + (isEvaluating ? ', __j = Array.prototype.join;\n' + "function print() { __p += __j.call(arguments, '') }\n" : ';\n' ) + source + 'return __p\n}'; var result = attempt(function() { return Function(importsKeys, sourceURL + 'return ' + source) .apply(undefined, importsValues); }); // Provide the compiled function's source by its `toString` method or // the `source` property as a convenience for inlining compiled templates. result.source = source; if (isError(result)) { throw result; } return result; } /** * Converts `string`, as a whole, to lower case just like * [String#toLowerCase](https://mdn.io/toLowerCase). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the lower cased string. * @example * * _.toLower('--Foo-Bar--'); * // => '--foo-bar--' * * _.toLower('fooBar'); * // => 'foobar' * * _.toLower('__FOO_BAR__'); * // => '__foo_bar__' */ function toLower(value) { return toString(value).toLowerCase(); } /** * Converts `string`, as a whole, to upper case just like * [String#toUpperCase](https://mdn.io/toUpperCase). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the upper cased string. * @example * * _.toUpper('--foo-bar--'); * // => '--FOO-BAR--' * * _.toUpper('fooBar'); * // => 'FOOBAR' * * _.toUpper('__foo_bar__'); * // => '__FOO_BAR__' */ function toUpper(value) { return toString(value).toUpperCase(); } /** * Removes leading and trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trim(' abc '); * // => 'abc' * * _.trim('-_-abc-_-', '_-'); * // => 'abc' * * _.map([' foo ', ' bar '], _.trim); * // => ['foo', 'bar'] */ function trim(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrim, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), chrSymbols = stringToArray(chars), start = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1; return castSlice(strSymbols, start, end).join(''); } /** * Removes trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trimEnd(' abc '); * // => ' abc' * * _.trimEnd('-_-abc-_-', '_-'); * // => '-_-abc' */ function trimEnd(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrimEnd, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), end = charsEndIndex(strSymbols, stringToArray(chars)) + 1; return castSlice(strSymbols, 0, end).join(''); } /** * Removes leading whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trimStart(' abc '); * // => 'abc ' * * _.trimStart('-_-abc-_-', '_-'); * // => 'abc-_-' */ function trimStart(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrimStart, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), start = charsStartIndex(strSymbols, stringToArray(chars)); return castSlice(strSymbols, start).join(''); } /** * Truncates `string` if it's longer than the given maximum string length. * The last characters of the truncated string are replaced with the omission * string which defaults to "...". * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to truncate. * @param {Object} [options={}] The options object. * @param {number} [options.length=30] The maximum string length. * @param {string} [options.omission='...'] The string to indicate text is omitted. * @param {RegExp|string} [options.separator] The separator pattern to truncate to. * @returns {string} Returns the truncated string. * @example * * _.truncate('hi-diddly-ho there, neighborino'); * // => 'hi-diddly-ho there, neighbo...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'length': 24, * 'separator': ' ' * }); * // => 'hi-diddly-ho there,...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'length': 24, * 'separator': /,? +/ * }); * // => 'hi-diddly-ho there...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'omission': ' [...]' * }); * // => 'hi-diddly-ho there, neig [...]' */ function truncate(string, options) { var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION; if (isObject(options)) { var separator = 'separator' in options ? options.separator : separator; length = 'length' in options ? toInteger(options.length) : length; omission = 'omission' in options ? baseToString(options.omission) : omission; } string = toString(string); var strLength = string.length; if (hasUnicode(string)) { var strSymbols = stringToArray(string); strLength = strSymbols.length; } if (length >= strLength) { return string; } var end = length - stringSize(omission); if (end < 1) { return omission; } var result = strSymbols ? castSlice(strSymbols, 0, end).join('') : string.slice(0, end); if (separator === undefined) { return result + omission; } if (strSymbols) { end += (result.length - end); } if (isRegExp(separator)) { if (string.slice(end).search(separator)) { var match, substring = result; if (!separator.global) { separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g'); } separator.lastIndex = 0; while ((match = separator.exec(substring))) { var newEnd = match.index; } result = result.slice(0, newEnd === undefined ? end : newEnd); } } else if (string.indexOf(baseToString(separator), end) != end) { var index = result.lastIndexOf(separator); if (index > -1) { result = result.slice(0, index); } } return result + omission; } /** * The inverse of `_.escape`; this method converts the HTML entities * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to * their corresponding characters. * * **Note:** No other HTML entities are unescaped. To unescape additional * HTML entities use a third-party library like [_he_](https://mths.be/he). * * @static * @memberOf _ * @since 0.6.0 * @category String * @param {string} [string=''] The string to unescape. * @returns {string} Returns the unescaped string. * @example * * _.unescape('fred, barney, &amp; pebbles'); * // => 'fred, barney, & pebbles' */ function unescape(string) { string = toString(string); return (string && reHasEscapedHtml.test(string)) ? string.replace(reEscapedHtml, unescapeHtmlChar) : string; } /** * Converts `string`, as space separated words, to upper case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the upper cased string. * @example * * _.upperCase('--foo-bar'); * // => 'FOO BAR' * * _.upperCase('fooBar'); * // => 'FOO BAR' * * _.upperCase('__foo_bar__'); * // => 'FOO BAR' */ var upperCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + word.toUpperCase(); }); /** * Converts the first character of `string` to upper case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.upperFirst('fred'); * // => 'Fred' * * _.upperFirst('FRED'); * // => 'FRED' */ var upperFirst = createCaseFirst('toUpperCase'); /** * Splits `string` into an array of its words. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {RegExp|string} [pattern] The pattern to match words. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the words of `string`. * @example * * _.words('fred, barney, & pebbles'); * // => ['fred', 'barney', 'pebbles'] * * _.words('fred, barney, & pebbles', /[^, ]+/g); * // => ['fred', 'barney', '&', 'pebbles'] */ function words(string, pattern, guard) { string = toString(string); pattern = guard ? undefined : pattern; if (pattern === undefined) { return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); } return string.match(pattern) || []; } /*------------------------------------------------------------------------*/ /** * Attempts to invoke `func`, returning either the result or the caught error * object. Any additional arguments are provided to `func` when it's invoked. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Function} func The function to attempt. * @param {...*} [args] The arguments to invoke `func` with. * @returns {*} Returns the `func` result or error object. * @example * * // Avoid throwing errors for invalid selectors. * var elements = _.attempt(function(selector) { * return document.querySelectorAll(selector); * }, '>_>'); * * if (_.isError(elements)) { * elements = []; * } */ var attempt = baseRest(function(func, args) { try { return apply(func, undefined, args); } catch (e) { return isError(e) ? e : new Error(e); } }); /** * Binds methods of an object to the object itself, overwriting the existing * method. * * **Note:** This method doesn't set the "length" property of bound functions. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {Object} object The object to bind and assign the bound methods to. * @param {...(string|string[])} methodNames The object method names to bind. * @returns {Object} Returns `object`. * @example * * var view = { * 'label': 'docs', * 'click': function() { * console.log('clicked ' + this.label); * } * }; * * _.bindAll(view, ['click']); * jQuery(element).on('click', view.click); * // => Logs 'clicked docs' when clicked. */ var bindAll = flatRest(function(object, methodNames) { arrayEach(methodNames, function(key) { key = toKey(key); baseAssignValue(object, key, bind(object[key], object)); }); return object; }); /** * Creates a function that iterates over `pairs` and invokes the corresponding * function of the first predicate to return truthy. The predicate-function * pairs are invoked with the `this` binding and arguments of the created * function. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {Array} pairs The predicate-function pairs. * @returns {Function} Returns the new composite function. * @example * * var func = _.cond([ * [_.matches({ 'a': 1 }), _.constant('matches A')], * [_.conforms({ 'b': _.isNumber }), _.constant('matches B')], * [_.stubTrue, _.constant('no match')] * ]); * * func({ 'a': 1, 'b': 2 }); * // => 'matches A' * * func({ 'a': 0, 'b': 1 }); * // => 'matches B' * * func({ 'a': '1', 'b': '2' }); * // => 'no match' */ function cond(pairs) { var length = pairs == null ? 0 : pairs.length, toIteratee = getIteratee(); pairs = !length ? [] : arrayMap(pairs, function(pair) { if (typeof pair[1] != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return [toIteratee(pair[0]), pair[1]]; }); return baseRest(function(args) { var index = -1; while (++index < length) { var pair = pairs[index]; if (apply(pair[0], this, args)) { return apply(pair[1], this, args); } } }); } /** * Creates a function that invokes the predicate properties of `source` with * the corresponding property values of a given object, returning `true` if * all predicates return truthy, else `false`. * * **Note:** The created function is equivalent to `_.conformsTo` with * `source` partially applied. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {Object} source The object of property predicates to conform to. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 2, 'b': 1 }, * { 'a': 1, 'b': 2 } * ]; * * _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } })); * // => [{ 'a': 1, 'b': 2 }] */ function conforms(source) { return baseConforms(baseClone(source, CLONE_DEEP_FLAG)); } /** * Creates a function that returns `value`. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {*} value The value to return from the new function. * @returns {Function} Returns the new constant function. * @example * * var objects = _.times(2, _.constant({ 'a': 1 })); * * console.log(objects); * // => [{ 'a': 1 }, { 'a': 1 }] * * console.log(objects[0] === objects[1]); * // => true */ function constant(value) { return function() { return value; }; } /** * Checks `value` to determine whether a default value should be returned in * its place. The `defaultValue` is returned if `value` is `NaN`, `null`, * or `undefined`. * * @static * @memberOf _ * @since 4.14.0 * @category Util * @param {*} value The value to check. * @param {*} defaultValue The default value. * @returns {*} Returns the resolved value. * @example * * _.defaultTo(1, 10); * // => 1 * * _.defaultTo(undefined, 10); * // => 10 */ function defaultTo(value, defaultValue) { return (value == null || value !== value) ? defaultValue : value; } /** * Creates a function that returns the result of invoking the given functions * with the `this` binding of the created function, where each successive * invocation is supplied the return value of the previous. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {...(Function|Function[])} [funcs] The functions to invoke. * @returns {Function} Returns the new composite function. * @see _.flowRight * @example * * function square(n) { * return n * n; * } * * var addSquare = _.flow([_.add, square]); * addSquare(1, 2); * // => 9 */ var flow = createFlow(); /** * This method is like `_.flow` except that it creates a function that * invokes the given functions from right to left. * * @static * @since 3.0.0 * @memberOf _ * @category Util * @param {...(Function|Function[])} [funcs] The functions to invoke. * @returns {Function} Returns the new composite function. * @see _.flow * @example * * function square(n) { * return n * n; * } * * var addSquare = _.flowRight([square, _.add]); * addSquare(1, 2); * // => 9 */ var flowRight = createFlow(true); /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } /** * Creates a function that invokes `func` with the arguments of the created * function. If `func` is a property name, the created function returns the * property value for a given element. If `func` is an array or object, the * created function returns `true` for elements that contain the equivalent * source properties, otherwise it returns `false`. * * @static * @since 4.0.0 * @memberOf _ * @category Util * @param {*} [func=_.identity] The value to convert to a callback. * @returns {Function} Returns the callback. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true })); * // => [{ 'user': 'barney', 'age': 36, 'active': true }] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, _.iteratee(['user', 'fred'])); * // => [{ 'user': 'fred', 'age': 40 }] * * // The `_.property` iteratee shorthand. * _.map(users, _.iteratee('user')); * // => ['barney', 'fred'] * * // Create custom iteratee shorthands. * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) { * return !_.isRegExp(func) ? iteratee(func) : function(string) { * return func.test(string); * }; * }); * * _.filter(['abc', 'def'], /ef/); * // => ['def'] */ function iteratee(func) { return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG)); } /** * Creates a function that performs a partial deep comparison between a given * object and `source`, returning `true` if the given object has equivalent * property values, else `false`. * * **Note:** The created function is equivalent to `_.isMatch` with `source` * partially applied. * * Partial comparisons will match empty array and empty object `source` * values against any array or object value, respectively. See `_.isEqual` * for a list of supported value comparisons. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 1, 'b': 2, 'c': 3 }, * { 'a': 4, 'b': 5, 'c': 6 } * ]; * * _.filter(objects, _.matches({ 'a': 4, 'c': 6 })); * // => [{ 'a': 4, 'b': 5, 'c': 6 }] */ function matches(source) { return baseMatches(baseClone(source, CLONE_DEEP_FLAG)); } /** * Creates a function that performs a partial deep comparison between the * value at `path` of a given object to `srcValue`, returning `true` if the * object value is equivalent, else `false`. * * **Note:** Partial comparisons will match empty array and empty object * `srcValue` values against any array or object value, respectively. See * `_.isEqual` for a list of supported value comparisons. * * @static * @memberOf _ * @since 3.2.0 * @category Util * @param {Array|string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 1, 'b': 2, 'c': 3 }, * { 'a': 4, 'b': 5, 'c': 6 } * ]; * * _.find(objects, _.matchesProperty('a', 4)); * // => { 'a': 4, 'b': 5, 'c': 6 } */ function matchesProperty(path, srcValue) { return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG)); } /** * Creates a function that invokes the method at `path` of a given object. * Any additional arguments are provided to the invoked method. * * @static * @memberOf _ * @since 3.7.0 * @category Util * @param {Array|string} path The path of the method to invoke. * @param {...*} [args] The arguments to invoke the method with. * @returns {Function} Returns the new invoker function. * @example * * var objects = [ * { 'a': { 'b': _.constant(2) } }, * { 'a': { 'b': _.constant(1) } } * ]; * * _.map(objects, _.method('a.b')); * // => [2, 1] * * _.map(objects, _.method(['a', 'b'])); * // => [2, 1] */ var method = baseRest(function(path, args) { return function(object) { return baseInvoke(object, path, args); }; }); /** * The opposite of `_.method`; this method creates a function that invokes * the method at a given path of `object`. Any additional arguments are * provided to the invoked method. * * @static * @memberOf _ * @since 3.7.0 * @category Util * @param {Object} object The object to query. * @param {...*} [args] The arguments to invoke the method with. * @returns {Function} Returns the new invoker function. * @example * * var array = _.times(3, _.constant), * object = { 'a': array, 'b': array, 'c': array }; * * _.map(['a[2]', 'c[0]'], _.methodOf(object)); * // => [2, 0] * * _.map([['a', '2'], ['c', '0']], _.methodOf(object)); * // => [2, 0] */ var methodOf = baseRest(function(object, args) { return function(path) { return baseInvoke(object, path, args); }; }); /** * Adds all own enumerable string keyed function properties of a source * object to the destination object. If `object` is a function, then methods * are added to its prototype as well. * * **Note:** Use `_.runInContext` to create a pristine `lodash` function to * avoid conflicts caused by modifying the original. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {Function|Object} [object=lodash] The destination object. * @param {Object} source The object of functions to add. * @param {Object} [options={}] The options object. * @param {boolean} [options.chain=true] Specify whether mixins are chainable. * @returns {Function|Object} Returns `object`. * @example * * function vowels(string) { * return _.filter(string, function(v) { * return /[aeiou]/i.test(v); * }); * } * * _.mixin({ 'vowels': vowels }); * _.vowels('fred'); * // => ['e'] * * _('fred').vowels().value(); * // => ['e'] * * _.mixin({ 'vowels': vowels }, { 'chain': false }); * _('fred').vowels(); * // => ['e'] */ function mixin(object, source, options) { var props = keys(source), methodNames = baseFunctions(source, props); if (options == null && !(isObject(source) && (methodNames.length || !props.length))) { options = source; source = object; object = this; methodNames = baseFunctions(source, keys(source)); } var chain = !(isObject(options) && 'chain' in options) || !!options.chain, isFunc = isFunction(object); arrayEach(methodNames, function(methodName) { var func = source[methodName]; object[methodName] = func; if (isFunc) { object.prototype[methodName] = function() { var chainAll = this.__chain__; if (chain || chainAll) { var result = object(this.__wrapped__), actions = result.__actions__ = copyArray(this.__actions__); actions.push({ 'func': func, 'args': arguments, 'thisArg': object }); result.__chain__ = chainAll; return result; } return func.apply(object, arrayPush([this.value()], arguments)); }; } }); return object; } /** * Reverts the `_` variable to its previous value and returns a reference to * the `lodash` function. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @returns {Function} Returns the `lodash` function. * @example * * var lodash = _.noConflict(); */ function noConflict() { if (root._ === this) { root._ = oldDash; } return this; } /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop() { // No operation performed. } /** * Creates a function that gets the argument at index `n`. If `n` is negative, * the nth argument from the end is returned. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {number} [n=0] The index of the argument to return. * @returns {Function} Returns the new pass-thru function. * @example * * var func = _.nthArg(1); * func('a', 'b', 'c', 'd'); * // => 'b' * * var func = _.nthArg(-2); * func('a', 'b', 'c', 'd'); * // => 'c' */ function nthArg(n) { n = toInteger(n); return baseRest(function(args) { return baseNth(args, n); }); } /** * Creates a function that invokes `iteratees` with the arguments it receives * and returns their results. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [iteratees=[_.identity]] * The iteratees to invoke. * @returns {Function} Returns the new function. * @example * * var func = _.over([Math.max, Math.min]); * * func(1, 2, 3, 4); * // => [4, 1] */ var over = createOver(arrayMap); /** * Creates a function that checks if **all** of the `predicates` return * truthy when invoked with the arguments it receives. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [predicates=[_.identity]] * The predicates to check. * @returns {Function} Returns the new function. * @example * * var func = _.overEvery([Boolean, isFinite]); * * func('1'); * // => true * * func(null); * // => false * * func(NaN); * // => false */ var overEvery = createOver(arrayEvery); /** * Creates a function that checks if **any** of the `predicates` return * truthy when invoked with the arguments it receives. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [predicates=[_.identity]] * The predicates to check. * @returns {Function} Returns the new function. * @example * * var func = _.overSome([Boolean, isFinite]); * * func('1'); * // => true * * func(null); * // => true * * func(NaN); * // => false */ var overSome = createOver(arraySome); /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); } /** * The opposite of `_.property`; this method creates a function that returns * the value at a given path of `object`. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Object} object The object to query. * @returns {Function} Returns the new accessor function. * @example * * var array = [0, 1, 2], * object = { 'a': array, 'b': array, 'c': array }; * * _.map(['a[2]', 'c[0]'], _.propertyOf(object)); * // => [2, 0] * * _.map([['a', '2'], ['c', '0']], _.propertyOf(object)); * // => [2, 0] */ function propertyOf(object) { return function(path) { return object == null ? undefined : baseGet(object, path); }; } /** * Creates an array of numbers (positive and/or negative) progressing from * `start` up to, but not including, `end`. A step of `-1` is used if a negative * `start` is specified without an `end` or `step`. If `end` is not specified, * it's set to `start` with `start` then set to `0`. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the range of numbers. * @see _.inRange, _.rangeRight * @example * * _.range(4); * // => [0, 1, 2, 3] * * _.range(-4); * // => [0, -1, -2, -3] * * _.range(1, 5); * // => [1, 2, 3, 4] * * _.range(0, 20, 5); * // => [0, 5, 10, 15] * * _.range(0, -4, -1); * // => [0, -1, -2, -3] * * _.range(1, 4, 0); * // => [1, 1, 1] * * _.range(0); * // => [] */ var range = createRange(); /** * This method is like `_.range` except that it populates values in * descending order. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the range of numbers. * @see _.inRange, _.range * @example * * _.rangeRight(4); * // => [3, 2, 1, 0] * * _.rangeRight(-4); * // => [-3, -2, -1, 0] * * _.rangeRight(1, 5); * // => [4, 3, 2, 1] * * _.rangeRight(0, 20, 5); * // => [15, 10, 5, 0] * * _.rangeRight(0, -4, -1); * // => [-3, -2, -1, 0] * * _.rangeRight(1, 4, 0); * // => [1, 1, 1] * * _.rangeRight(0); * // => [] */ var rangeRight = createRange(true); /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } /** * This method returns a new empty object. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Object} Returns the new empty object. * @example * * var objects = _.times(2, _.stubObject); * * console.log(objects); * // => [{}, {}] * * console.log(objects[0] === objects[1]); * // => false */ function stubObject() { return {}; } /** * This method returns an empty string. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {string} Returns the empty string. * @example * * _.times(2, _.stubString); * // => ['', ''] */ function stubString() { return ''; } /** * This method returns `true`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `true`. * @example * * _.times(2, _.stubTrue); * // => [true, true] */ function stubTrue() { return true; } /** * Invokes the iteratee `n` times, returning an array of the results of * each invocation. The iteratee is invoked with one argument; (index). * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {number} n The number of times to invoke `iteratee`. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the array of results. * @example * * _.times(3, String); * // => ['0', '1', '2'] * * _.times(4, _.constant(0)); * // => [0, 0, 0, 0] */ function times(n, iteratee) { n = toInteger(n); if (n < 1 || n > MAX_SAFE_INTEGER) { return []; } var index = MAX_ARRAY_LENGTH, length = nativeMin(n, MAX_ARRAY_LENGTH); iteratee = getIteratee(iteratee); n -= MAX_ARRAY_LENGTH; var result = baseTimes(length, iteratee); while (++index < n) { iteratee(index); } return result; } /** * Converts `value` to a property path array. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {*} value The value to convert. * @returns {Array} Returns the new property path array. * @example * * _.toPath('a.b.c'); * // => ['a', 'b', 'c'] * * _.toPath('a[0].b.c'); * // => ['a', '0', 'b', 'c'] */ function toPath(value) { if (isArray(value)) { return arrayMap(value, toKey); } return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value))); } /** * Generates a unique ID. If `prefix` is given, the ID is appended to it. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {string} [prefix=''] The value to prefix the ID with. * @returns {string} Returns the unique ID. * @example * * _.uniqueId('contact_'); * // => 'contact_104' * * _.uniqueId(); * // => '105' */ function uniqueId(prefix) { var id = ++idCounter; return toString(prefix) + id; } /*------------------------------------------------------------------------*/ /** * Adds two numbers. * * @static * @memberOf _ * @since 3.4.0 * @category Math * @param {number} augend The first number in an addition. * @param {number} addend The second number in an addition. * @returns {number} Returns the total. * @example * * _.add(6, 4); * // => 10 */ var add = createMathOperation(function(augend, addend) { return augend + addend; }, 0); /** * Computes `number` rounded up to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round up. * @param {number} [precision=0] The precision to round up to. * @returns {number} Returns the rounded up number. * @example * * _.ceil(4.006); * // => 5 * * _.ceil(6.004, 2); * // => 6.01 * * _.ceil(6040, -2); * // => 6100 */ var ceil = createRound('ceil'); /** * Divide two numbers. * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {number} dividend The first number in a division. * @param {number} divisor The second number in a division. * @returns {number} Returns the quotient. * @example * * _.divide(6, 4); * // => 1.5 */ var divide = createMathOperation(function(dividend, divisor) { return dividend / divisor; }, 1); /** * Computes `number` rounded down to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round down. * @param {number} [precision=0] The precision to round down to. * @returns {number} Returns the rounded down number. * @example * * _.floor(4.006); * // => 4 * * _.floor(0.046, 2); * // => 0.04 * * _.floor(4060, -2); * // => 4000 */ var floor = createRound('floor'); /** * Computes the maximum value of `array`. If `array` is empty or falsey, * `undefined` is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @returns {*} Returns the maximum value. * @example * * _.max([4, 2, 8, 6]); * // => 8 * * _.max([]); * // => undefined */ function max(array) { return (array && array.length) ? baseExtremum(array, identity, baseGt) : undefined; } /** * This method is like `_.max` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * the value is ranked. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {*} Returns the maximum value. * @example * * var objects = [{ 'n': 1 }, { 'n': 2 }]; * * _.maxBy(objects, function(o) { return o.n; }); * // => { 'n': 2 } * * // The `_.property` iteratee shorthand. * _.maxBy(objects, 'n'); * // => { 'n': 2 } */ function maxBy(array, iteratee) { return (array && array.length) ? baseExtremum(array, getIteratee(iteratee, 2), baseGt) : undefined; } /** * Computes the mean of the values in `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @returns {number} Returns the mean. * @example * * _.mean([4, 2, 8, 6]); * // => 5 */ function mean(array) { return baseMean(array, identity); } /** * This method is like `_.mean` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be averaged. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the mean. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.meanBy(objects, function(o) { return o.n; }); * // => 5 * * // The `_.property` iteratee shorthand. * _.meanBy(objects, 'n'); * // => 5 */ function meanBy(array, iteratee) { return baseMean(array, getIteratee(iteratee, 2)); } /** * Computes the minimum value of `array`. If `array` is empty or falsey, * `undefined` is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @returns {*} Returns the minimum value. * @example * * _.min([4, 2, 8, 6]); * // => 2 * * _.min([]); * // => undefined */ function min(array) { return (array && array.length) ? baseExtremum(array, identity, baseLt) : undefined; } /** * This method is like `_.min` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * the value is ranked. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {*} Returns the minimum value. * @example * * var objects = [{ 'n': 1 }, { 'n': 2 }]; * * _.minBy(objects, function(o) { return o.n; }); * // => { 'n': 1 } * * // The `_.property` iteratee shorthand. * _.minBy(objects, 'n'); * // => { 'n': 1 } */ function minBy(array, iteratee) { return (array && array.length) ? baseExtremum(array, getIteratee(iteratee, 2), baseLt) : undefined; } /** * Multiply two numbers. * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {number} multiplier The first number in a multiplication. * @param {number} multiplicand The second number in a multiplication. * @returns {number} Returns the product. * @example * * _.multiply(6, 4); * // => 24 */ var multiply = createMathOperation(function(multiplier, multiplicand) { return multiplier * multiplicand; }, 1); /** * Computes `number` rounded to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round. * @param {number} [precision=0] The precision to round to. * @returns {number} Returns the rounded number. * @example * * _.round(4.006); * // => 4 * * _.round(4.006, 2); * // => 4.01 * * _.round(4060, -2); * // => 4100 */ var round = createRound('round'); /** * Subtract two numbers. * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {number} minuend The first number in a subtraction. * @param {number} subtrahend The second number in a subtraction. * @returns {number} Returns the difference. * @example * * _.subtract(6, 4); * // => 2 */ var subtract = createMathOperation(function(minuend, subtrahend) { return minuend - subtrahend; }, 0); /** * Computes the sum of the values in `array`. * * @static * @memberOf _ * @since 3.4.0 * @category Math * @param {Array} array The array to iterate over. * @returns {number} Returns the sum. * @example * * _.sum([4, 2, 8, 6]); * // => 20 */ function sum(array) { return (array && array.length) ? baseSum(array, identity) : 0; } /** * This method is like `_.sum` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be summed. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the sum. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.sumBy(objects, function(o) { return o.n; }); * // => 20 * * // The `_.property` iteratee shorthand. * _.sumBy(objects, 'n'); * // => 20 */ function sumBy(array, iteratee) { return (array && array.length) ? baseSum(array, getIteratee(iteratee, 2)) : 0; } /*------------------------------------------------------------------------*/ // Add methods that return wrapped values in chain sequences. lodash.after = after; lodash.ary = ary; lodash.assign = assign; lodash.assignIn = assignIn; lodash.assignInWith = assignInWith; lodash.assignWith = assignWith; lodash.at = at; lodash.before = before; lodash.bind = bind; lodash.bindAll = bindAll; lodash.bindKey = bindKey; lodash.castArray = castArray; lodash.chain = chain; lodash.chunk = chunk; lodash.compact = compact; lodash.concat = concat; lodash.cond = cond; lodash.conforms = conforms; lodash.constant = constant; lodash.countBy = countBy; lodash.create = create; lodash.curry = curry; lodash.curryRight = curryRight; lodash.debounce = debounce; lodash.defaults = defaults; lodash.defaultsDeep = defaultsDeep; lodash.defer = defer; lodash.delay = delay; lodash.difference = difference; lodash.differenceBy = differenceBy; lodash.differenceWith = differenceWith; lodash.drop = drop; lodash.dropRight = dropRight; lodash.dropRightWhile = dropRightWhile; lodash.dropWhile = dropWhile; lodash.fill = fill; lodash.filter = filter; lodash.flatMap = flatMap; lodash.flatMapDeep = flatMapDeep; lodash.flatMapDepth = flatMapDepth; lodash.flatten = flatten; lodash.flattenDeep = flattenDeep; lodash.flattenDepth = flattenDepth; lodash.flip = flip; lodash.flow = flow; lodash.flowRight = flowRight; lodash.fromPairs = fromPairs; lodash.functions = functions; lodash.functionsIn = functionsIn; lodash.groupBy = groupBy; lodash.initial = initial; lodash.intersection = intersection; lodash.intersectionBy = intersectionBy; lodash.intersectionWith = intersectionWith; lodash.invert = invert; lodash.invertBy = invertBy; lodash.invokeMap = invokeMap; lodash.iteratee = iteratee; lodash.keyBy = keyBy; lodash.keys = keys; lodash.keysIn = keysIn; lodash.map = map; lodash.mapKeys = mapKeys; lodash.mapValues = mapValues; lodash.matches = matches; lodash.matchesProperty = matchesProperty; lodash.memoize = memoize; lodash.merge = merge; lodash.mergeWith = mergeWith; lodash.method = method; lodash.methodOf = methodOf; lodash.mixin = mixin; lodash.negate = negate; lodash.nthArg = nthArg; lodash.omit = omit; lodash.omitBy = omitBy; lodash.once = once; lodash.orderBy = orderBy; lodash.over = over; lodash.overArgs = overArgs; lodash.overEvery = overEvery; lodash.overSome = overSome; lodash.partial = partial; lodash.partialRight = partialRight; lodash.partition = partition; lodash.pick = pick; lodash.pickBy = pickBy; lodash.property = property; lodash.propertyOf = propertyOf; lodash.pull = pull; lodash.pullAll = pullAll; lodash.pullAllBy = pullAllBy; lodash.pullAllWith = pullAllWith; lodash.pullAt = pullAt; lodash.range = range; lodash.rangeRight = rangeRight; lodash.rearg = rearg; lodash.reject = reject; lodash.remove = remove; lodash.rest = rest; lodash.reverse = reverse; lodash.sampleSize = sampleSize; lodash.set = set; lodash.setWith = setWith; lodash.shuffle = shuffle; lodash.slice = slice; lodash.sortBy = sortBy; lodash.sortedUniq = sortedUniq; lodash.sortedUniqBy = sortedUniqBy; lodash.split = split; lodash.spread = spread; lodash.tail = tail; lodash.take = take; lodash.takeRight = takeRight; lodash.takeRightWhile = takeRightWhile; lodash.takeWhile = takeWhile; lodash.tap = tap; lodash.throttle = throttle; lodash.thru = thru; lodash.toArray = toArray; lodash.toPairs = toPairs; lodash.toPairsIn = toPairsIn; lodash.toPath = toPath; lodash.toPlainObject = toPlainObject; lodash.transform = transform; lodash.unary = unary; lodash.union = union; lodash.unionBy = unionBy; lodash.unionWith = unionWith; lodash.uniq = uniq; lodash.uniqBy = uniqBy; lodash.uniqWith = uniqWith; lodash.unset = unset; lodash.unzip = unzip; lodash.unzipWith = unzipWith; lodash.update = update; lodash.updateWith = updateWith; lodash.values = values; lodash.valuesIn = valuesIn; lodash.without = without; lodash.words = words; lodash.wrap = wrap; lodash.xor = xor; lodash.xorBy = xorBy; lodash.xorWith = xorWith; lodash.zip = zip; lodash.zipObject = zipObject; lodash.zipObjectDeep = zipObjectDeep; lodash.zipWith = zipWith; // Add aliases. lodash.entries = toPairs; lodash.entriesIn = toPairsIn; lodash.extend = assignIn; lodash.extendWith = assignInWith; // Add methods to `lodash.prototype`. mixin(lodash, lodash); /*------------------------------------------------------------------------*/ // Add methods that return unwrapped values in chain sequences. lodash.add = add; lodash.attempt = attempt; lodash.camelCase = camelCase; lodash.capitalize = capitalize; lodash.ceil = ceil; lodash.clamp = clamp; lodash.clone = clone; lodash.cloneDeep = cloneDeep; lodash.cloneDeepWith = cloneDeepWith; lodash.cloneWith = cloneWith; lodash.conformsTo = conformsTo; lodash.deburr = deburr; lodash.defaultTo = defaultTo; lodash.divide = divide; lodash.endsWith = endsWith; lodash.eq = eq; lodash.escape = escape; lodash.escapeRegExp = escapeRegExp; lodash.every = every; lodash.find = find; lodash.findIndex = findIndex; lodash.findKey = findKey; lodash.findLast = findLast; lodash.findLastIndex = findLastIndex; lodash.findLastKey = findLastKey; lodash.floor = floor; lodash.forEach = forEach; lodash.forEachRight = forEachRight; lodash.forIn = forIn; lodash.forInRight = forInRight; lodash.forOwn = forOwn; lodash.forOwnRight = forOwnRight; lodash.get = get; lodash.gt = gt; lodash.gte = gte; lodash.has = has; lodash.hasIn = hasIn; lodash.head = head; lodash.identity = identity; lodash.includes = includes; lodash.indexOf = indexOf; lodash.inRange = inRange; lodash.invoke = invoke; lodash.isArguments = isArguments; lodash.isArray = isArray; lodash.isArrayBuffer = isArrayBuffer; lodash.isArrayLike = isArrayLike; lodash.isArrayLikeObject = isArrayLikeObject; lodash.isBoolean = isBoolean; lodash.isBuffer = isBuffer; lodash.isDate = isDate; lodash.isElement = isElement; lodash.isEmpty = isEmpty; lodash.isEqual = isEqual; lodash.isEqualWith = isEqualWith; lodash.isError = isError; lodash.isFinite = isFinite; lodash.isFunction = isFunction; lodash.isInteger = isInteger; lodash.isLength = isLength; lodash.isMap = isMap; lodash.isMatch = isMatch; lodash.isMatchWith = isMatchWith; lodash.isNaN = isNaN; lodash.isNative = isNative; lodash.isNil = isNil; lodash.isNull = isNull; lodash.isNumber = isNumber; lodash.isObject = isObject; lodash.isObjectLike = isObjectLike; lodash.isPlainObject = isPlainObject; lodash.isRegExp = isRegExp; lodash.isSafeInteger = isSafeInteger; lodash.isSet = isSet; lodash.isString = isString; lodash.isSymbol = isSymbol; lodash.isTypedArray = isTypedArray; lodash.isUndefined = isUndefined; lodash.isWeakMap = isWeakMap; lodash.isWeakSet = isWeakSet; lodash.join = join; lodash.kebabCase = kebabCase; lodash.last = last; lodash.lastIndexOf = lastIndexOf; lodash.lowerCase = lowerCase; lodash.lowerFirst = lowerFirst; lodash.lt = lt; lodash.lte = lte; lodash.max = max; lodash.maxBy = maxBy; lodash.mean = mean; lodash.meanBy = meanBy; lodash.min = min; lodash.minBy = minBy; lodash.stubArray = stubArray; lodash.stubFalse = stubFalse; lodash.stubObject = stubObject; lodash.stubString = stubString; lodash.stubTrue = stubTrue; lodash.multiply = multiply; lodash.nth = nth; lodash.noConflict = noConflict; lodash.noop = noop; lodash.now = now; lodash.pad = pad; lodash.padEnd = padEnd; lodash.padStart = padStart; lodash.parseInt = parseInt; lodash.random = random; lodash.reduce = reduce; lodash.reduceRight = reduceRight; lodash.repeat = repeat; lodash.replace = replace; lodash.result = result; lodash.round = round; lodash.runInContext = runInContext; lodash.sample = sample; lodash.size = size; lodash.snakeCase = snakeCase; lodash.some = some; lodash.sortedIndex = sortedIndex; lodash.sortedIndexBy = sortedIndexBy; lodash.sortedIndexOf = sortedIndexOf; lodash.sortedLastIndex = sortedLastIndex; lodash.sortedLastIndexBy = sortedLastIndexBy; lodash.sortedLastIndexOf = sortedLastIndexOf; lodash.startCase = startCase; lodash.startsWith = startsWith; lodash.subtract = subtract; lodash.sum = sum; lodash.sumBy = sumBy; lodash.template = template; lodash.times = times; lodash.toFinite = toFinite; lodash.toInteger = toInteger; lodash.toLength = toLength; lodash.toLower = toLower; lodash.toNumber = toNumber; lodash.toSafeInteger = toSafeInteger; lodash.toString = toString; lodash.toUpper = toUpper; lodash.trim = trim; lodash.trimEnd = trimEnd; lodash.trimStart = trimStart; lodash.truncate = truncate; lodash.unescape = unescape; lodash.uniqueId = uniqueId; lodash.upperCase = upperCase; lodash.upperFirst = upperFirst; // Add aliases. lodash.each = forEach; lodash.eachRight = forEachRight; lodash.first = head; mixin(lodash, (function() { var source = {}; baseForOwn(lodash, function(func, methodName) { if (!hasOwnProperty.call(lodash.prototype, methodName)) { source[methodName] = func; } }); return source; }()), { 'chain': false }); /*------------------------------------------------------------------------*/ /** * The semantic version number. * * @static * @memberOf _ * @type {string} */ lodash.VERSION = VERSION; // Assign default placeholders. arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) { lodash[methodName].placeholder = lodash; }); // Add `LazyWrapper` methods for `_.drop` and `_.take` variants. arrayEach(['drop', 'take'], function(methodName, index) { LazyWrapper.prototype[methodName] = function(n) { n = n === undefined ? 1 : nativeMax(toInteger(n), 0); var result = (this.__filtered__ && !index) ? new LazyWrapper(this) : this.clone(); if (result.__filtered__) { result.__takeCount__ = nativeMin(n, result.__takeCount__); } else { result.__views__.push({ 'size': nativeMin(n, MAX_ARRAY_LENGTH), 'type': methodName + (result.__dir__ < 0 ? 'Right' : '') }); } return result; }; LazyWrapper.prototype[methodName + 'Right'] = function(n) { return this.reverse()[methodName](n).reverse(); }; }); // Add `LazyWrapper` methods that accept an `iteratee` value. arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) { var type = index + 1, isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG; LazyWrapper.prototype[methodName] = function(iteratee) { var result = this.clone(); result.__iteratees__.push({ 'iteratee': getIteratee(iteratee, 3), 'type': type }); result.__filtered__ = result.__filtered__ || isFilter; return result; }; }); // Add `LazyWrapper` methods for `_.head` and `_.last`. arrayEach(['head', 'last'], function(methodName, index) { var takeName = 'take' + (index ? 'Right' : ''); LazyWrapper.prototype[methodName] = function() { return this[takeName](1).value()[0]; }; }); // Add `LazyWrapper` methods for `_.initial` and `_.tail`. arrayEach(['initial', 'tail'], function(methodName, index) { var dropName = 'drop' + (index ? '' : 'Right'); LazyWrapper.prototype[methodName] = function() { return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1); }; }); LazyWrapper.prototype.compact = function() { return this.filter(identity); }; LazyWrapper.prototype.find = function(predicate) { return this.filter(predicate).head(); }; LazyWrapper.prototype.findLast = function(predicate) { return this.reverse().find(predicate); }; LazyWrapper.prototype.invokeMap = baseRest(function(path, args) { if (typeof path == 'function') { return new LazyWrapper(this); } return this.map(function(value) { return baseInvoke(value, path, args); }); }); LazyWrapper.prototype.reject = function(predicate) { return this.filter(negate(getIteratee(predicate))); }; LazyWrapper.prototype.slice = function(start, end) { start = toInteger(start); var result = this; if (result.__filtered__ && (start > 0 || end < 0)) { return new LazyWrapper(result); } if (start < 0) { result = result.takeRight(-start); } else if (start) { result = result.drop(start); } if (end !== undefined) { end = toInteger(end); result = end < 0 ? result.dropRight(-end) : result.take(end - start); } return result; }; LazyWrapper.prototype.takeRightWhile = function(predicate) { return this.reverse().takeWhile(predicate).reverse(); }; LazyWrapper.prototype.toArray = function() { return this.take(MAX_ARRAY_LENGTH); }; // Add `LazyWrapper` methods to `lodash.prototype`. baseForOwn(LazyWrapper.prototype, function(func, methodName) { var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), isTaker = /^(?:head|last)$/.test(methodName), lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName], retUnwrapped = isTaker || /^find/.test(methodName); if (!lodashFunc) { return; } lodash.prototype[methodName] = function() { var value = this.__wrapped__, args = isTaker ? [1] : arguments, isLazy = value instanceof LazyWrapper, iteratee = args[0], useLazy = isLazy || isArray(value); var interceptor = function(value) { var result = lodashFunc.apply(lodash, arrayPush([value], args)); return (isTaker && chainAll) ? result[0] : result; }; if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) { // Avoid lazy use if the iteratee has a "length" value other than `1`. isLazy = useLazy = false; } var chainAll = this.__chain__, isHybrid = !!this.__actions__.length, isUnwrapped = retUnwrapped && !chainAll, onlyLazy = isLazy && !isHybrid; if (!retUnwrapped && useLazy) { value = onlyLazy ? value : new LazyWrapper(this); var result = func.apply(value, args); result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); return new LodashWrapper(result, chainAll); } if (isUnwrapped && onlyLazy) { return func.apply(this, args); } result = this.thru(interceptor); return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result; }; }); // Add `Array` methods to `lodash.prototype`. arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) { var func = arrayProto[methodName], chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru', retUnwrapped = /^(?:pop|shift)$/.test(methodName); lodash.prototype[methodName] = function() { var args = arguments; if (retUnwrapped && !this.__chain__) { var value = this.value(); return func.apply(isArray(value) ? value : [], args); } return this[chainName](function(value) { return func.apply(isArray(value) ? value : [], args); }); }; }); // Map minified method names to their real names. baseForOwn(LazyWrapper.prototype, function(func, methodName) { var lodashFunc = lodash[methodName]; if (lodashFunc) { var key = (lodashFunc.name + ''), names = realNames[key] || (realNames[key] = []); names.push({ 'name': methodName, 'func': lodashFunc }); } }); realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG).name] = [{ 'name': 'wrapper', 'func': undefined }]; // Add methods to `LazyWrapper`. LazyWrapper.prototype.clone = lazyClone; LazyWrapper.prototype.reverse = lazyReverse; LazyWrapper.prototype.value = lazyValue; // Add chain sequence methods to the `lodash` wrapper. lodash.prototype.at = wrapperAt; lodash.prototype.chain = wrapperChain; lodash.prototype.commit = wrapperCommit; lodash.prototype.next = wrapperNext; lodash.prototype.plant = wrapperPlant; lodash.prototype.reverse = wrapperReverse; lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; // Add lazy aliases. lodash.prototype.first = lodash.prototype.head; if (symIterator) { lodash.prototype[symIterator] = wrapperToIterator; } return lodash; }); /*--------------------------------------------------------------------------*/ // Export lodash. var _ = runInContext(); // Some AMD build optimizers, like r.js, check for condition patterns like: if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { // Expose Lodash on the global object to prevent errors when Lodash is // loaded by a script tag in the presence of an AMD loader. // See http://requirejs.org/docs/errors.html#mismatch for more details. // Use `_.noConflict` to remove Lodash from the global object. root._ = _; // Define as an anonymous module so, through path mapping, it can be // referenced as the "underscore" module. define(function() { return _; }); } // Check for `exports` after `define` in case a build optimizer adds it. else if (freeModule) { // Export for Node.js. (freeModule.exports = _)._ = _; // Export for CommonJS support. freeExports._ = _; } else { // Export to the global object. root._ = _; } }.call(this));
kplusgithub/interactivemap2
node_modules/babel-helper-define-map/node_modules/lodash/lodash.js
JavaScript
mit
539,590
/*! tablesorter Grouping widget - updated 3/7/2014 (core v2.15.6) * Requires tablesorter v2.8+ and jQuery 1.7+ * by Rob Garrison */ /*jshint browser:true, jquery:true, unused:false */ /*global jQuery: false */ ;(function($){ "use strict"; var ts = $.tablesorter; ts.grouping = { types : { number : function(c, $column, txt, num, group){ var value, word; if (num > 1 && txt !== '') { if ($column.hasClass(ts.css.sortAsc)) { value = Math.floor(parseFloat(txt)/num) * num; return value > parseFloat(group || 0) ? value : parseFloat(group || 0); } else { value = Math.ceil(parseFloat(txt)/num) * num; return value < parseFloat(group || num) - value ? parseFloat(group || num) - value : value; } } else { word = (txt + '').match(/\d+/g); return word && word.length >= num ? word[num - 1] : txt || ''; } }, separator : function(c, $column, txt, num){ var word = (txt + '').split(c.widgetOptions.group_separator); return $.trim(word && num > 0 && word.length >= num ? word[(num || 1) - 1] : ''); }, word : function(c, $column, txt, num){ var word = (txt + ' ').match(/\w+/g); return word && word.length >= num ? word[num - 1] : txt || ''; }, letter : function(c, $column, txt, num){ return txt ? (txt + ' ').substring(0, num) : ''; }, date : function(c, $column, txt, part, group){ var wo = c.widgetOptions, time = new Date(txt || ''), hours = time.getHours(); return part === 'year' ? time.getFullYear() : part === 'month' ? wo.group_months[time.getMonth()] : part === 'day' ? wo.group_months[time.getMonth()] + ' ' + time.getDate() : part === 'week' ? wo.group_week[time.getDay()] : part === 'time' ? ('00' + (hours > 12 ? hours - 12 : hours === 0 ? hours + 12 : hours)).slice(-2) + ':' + ('00' + time.getMinutes()).slice(-2) + ' ' + ('00' + wo.group_time[hours >= 12 ? 1 : 0]).slice(-2) : wo.group_dateString(time); } }, update : function(table, c, wo){ if ($.isEmptyObject(c.cache)) { return; } var rowIndex, tbodyIndex, currentGroup, $rows, groupClass, grouping, time, cache, saveName, direction, lang = wo.grouping_language, group = '', savedGroup = false, column = c.sortList[0] ? c.sortList[0][0] : -1; c.$table .find('tr.group-hidden').removeClass('group-hidden').end() .find('tr.group-header').remove(); if (wo.group_collapsible) { // clear pager saved spacer height (in case the rows are collapsed) c.$table.data('pagerSavedHeight', 0); } if (column >= 0 && !c.$headers.filter('[data-column="' + column + '"]:last').hasClass('group-false')) { if (c.debug){ time = new Date(); } wo.group_currentGroup = ''; // save current groups wo.group_currentGroups = {}; // group class finds "group-{word/separator/letter/number/date/false}-{optional:#/year/month/day/week/time}" groupClass = (c.$headers.filter('[data-column="' + column + '"]:last').attr('class') || '').match(/(group-\w+(-\w+)?)/g); // grouping = [ 'group', '{word/separator/letter/number/date/false}', '{#/year/month/day/week/time}' ] grouping = groupClass ? groupClass[0].split('-') : ['group','letter',1]; // default to letter 1 // save current grouping if (wo.group_collapsible && wo.group_saveGroups && ts.storage) { wo.group_currentGroups = ts.storage( table, 'tablesorter-groups' ) || {}; // include direction when grouping numbers > 1 (reversed direction shows different range values) direction = (grouping[1] === 'number' && grouping[2] > 1) ? 'dir' + c.sortList[0][1] : ''; // combine column, sort direction & grouping as save key saveName = wo.group_currentGroup = '' + column + direction + grouping.join(''); if (!wo.group_currentGroups[saveName]) { wo.group_currentGroups[saveName] = []; } else { savedGroup = true; } } for (tbodyIndex = 0; tbodyIndex < c.$tbodies.length; tbodyIndex++) { cache = c.cache[tbodyIndex].normalized; group = ''; // clear grouping across tbodies $rows = c.$tbodies.eq(tbodyIndex).children('tr').not('.' + c.cssChildRow); for (rowIndex = 0; rowIndex < $rows.length; rowIndex++) { if ( $rows.eq(rowIndex).is(':visible') ) { // fixes #438 if (ts.grouping.types[grouping[1]]) { currentGroup = cache[rowIndex] ? ts.grouping.types[grouping[1]]( c, c.$headers.filter('[data-column="' + column + '"]:last'), cache[rowIndex][column], /date/.test(groupClass) ? grouping[2] : parseInt(grouping[2] || 1, 10) || 1, group, lang ) : currentGroup; if (group !== currentGroup) { group = currentGroup; // show range if number > 1 if (grouping[1] === 'number' && grouping[2] > 1 && currentGroup !== '') { currentGroup += ' - ' + (parseInt(currentGroup, 10) + ((parseInt(grouping[2],10) - 1) * (c.$headers.filter('[data-column="' + column + '"]:last').hasClass(ts.css.sortAsc) ? 1 : -1))); } if ($.isFunction(wo.group_formatter)) { currentGroup = wo.group_formatter((currentGroup || '').toString(), column, table, c, wo) || currentGroup; } $rows.eq(rowIndex).before('<tr class="group-header ' + c.selectorRemove.slice(1) + '" unselectable="on"><td colspan="' + c.columns + '">' + (wo.group_collapsible ? '<i/>' : '') + '<span class="group-name">' + currentGroup + '</span><span class="group-count"></span></td></tr>'); if (wo.group_saveGroups && !savedGroup && wo.group_collapsed && wo.group_collapsible) { // all groups start collapsed wo.group_currentGroups[wo.group_currentGroup].push(currentGroup); } } } } } } c.$table.find('tr.group-header') .bind('selectstart', false) .each(function(){ var isHidden, $label, name, $row = $(this), $rows = $row.nextUntil('tr.group-header').filter(':visible'); if (wo.group_count || $.isFunction(wo.group_callback)) { $label = $row.find('.group-count'); if ($label.length) { if (wo.group_count) { $label.html( wo.group_count.replace(/\{num\}/g, $rows.length) ); } if ($.isFunction(wo.group_callback)) { wo.group_callback($row.find('td'), $rows, column, table); } } } if (wo.group_saveGroups && wo.group_currentGroups[wo.group_currentGroup].length) { name = $row.find('.group-name').text().toLowerCase(); isHidden = $.inArray( name, wo.group_currentGroups[wo.group_currentGroup] ) > -1; $row.toggleClass('collapsed', isHidden); $rows.toggleClass('group-hidden', isHidden); } else if (wo.group_collapsed && wo.group_collapsible) { $row.addClass('collapsed'); $rows.addClass('group-hidden'); } }); c.$table.trigger(wo.group_complete); if (c.debug) { $.tablesorter.benchmark("Applying groups widget: ", time); } } }, bindEvents : function(table, c, wo){ if (wo.group_collapsible) { wo.group_currentGroups = []; // .on() requires jQuery 1.7+ c.$table.on('click toggleGroup', 'tr.group-header', function(event){ event.stopPropagation(); var isCollapsed, $groups, indx, $this = $(this), name = $this.find('.group-name').text().toLowerCase(); // use shift-click to toggle ALL groups if (event.type === 'click' && event.shiftKey) { $this.siblings('.group-header').trigger('toggleGroup'); } $this.toggleClass('collapsed'); // nextUntil requires jQuery 1.4+ $this.nextUntil('tr.group-header').toggleClass('group-hidden', $this.hasClass('collapsed') ); // save collapsed groups if (wo.group_saveGroups && ts.storage) { $groups = c.$table.find('.group-header'); isCollapsed = $this.hasClass('collapsed'); if (!wo.group_currentGroups[wo.group_currentGroup]) { wo.group_currentGroups[wo.group_currentGroup] = []; } if (isCollapsed && wo.group_currentGroup) { wo.group_currentGroups[wo.group_currentGroup].push( name ); } else if (wo.group_currentGroup) { indx = $.inArray( name, wo.group_currentGroups[wo.group_currentGroup] ); if (indx > -1) { wo.group_currentGroups[wo.group_currentGroup].splice( indx, 1 ); } } ts.storage( table, 'tablesorter-groups', wo.group_currentGroups ); } }); } $(wo.group_saveReset).on('click', function(){ ts.grouping.clearSavedGroups(table); }); c.$table.on('pagerChange.tsgrouping', function(){ ts.grouping.update(table, c, wo); }); }, clearSavedGroups: function(table){ if (table && ts.storage) { ts.storage(table, 'tablesorter-groups', ''); ts.grouping.update(table, table.config, table.config.widgetOptions); } } }; ts.addWidget({ id: 'group', priority: 100, options: { group_collapsible : true, // make the group header clickable and collapse the rows below it. group_collapsed : false, // start with all groups collapsed group_saveGroups : true, // remember collapsed groups group_saveReset : null, // element to clear saved collapsed groups group_count : ' ({num})', // if not false, the "{num}" string is replaced with the number of rows in the group group_separator : '-', // group name separator; used when group-separator-# class is used. group_formatter : null, // function(txt, column, table, c, wo) { return txt; } group_callback : null, // function($cell, $rows, column, table){}, callback allowing modification of the group header labels group_complete : 'groupingComplete', // event triggered on the table when the grouping widget has finished work // change these default date names based on your language preferences group_months : [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ], group_week : [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ], group_time : [ 'AM', 'PM' ], // this function is used when "group-date" is set to create the date string // you can just return date, date.toLocaleString(), date.toLocaleDateString() or d.toLocaleTimeString() // reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Conversion_getter group_dateString : function(date) { return date.toLocaleString(); } }, init: function(table, thisWidget, c, wo){ ts.grouping.bindEvents(table, c, wo); }, format: function(table, c, wo) { ts.grouping.update(table, c, wo); }, remove : function(table, c, wo){ c.$table .off('click', 'tr.group-header') .off('pagerChange.tsgrouping') .find('.group-hidden').removeClass('group-hidden').end() .find('tr.group-header').remove(); } }); })(jQuery);
schoren/cdnjs
ajax/libs/jquery.tablesorter/2.17.5/js/widgets/widget-grouping.js
JavaScript
mit
10,654
def eat(item): if item == "lava": strength = 0 elif item == "grapes": strength = 1 elif item == "peanuts": strength = 2 elif item == "shoes": strength = 3 elif item == "bear liver": strength = 4 elif item == "mud": strength = 5 elif item == "toe nails": strength = 6 elif item == "finger nails": strength = 7 elif item == "tuna": strength = 8 elif item == "eternity": strength = 9 elif item == "fried rice": strength = 10 else: strength = random.randint(0,10) return strength * random.random() # this sets he values of differnt foods ######################################################################### def getAttackValue(): # sets the function name as getattackvalue number = int(raw_input("Type attack value (0-99): ")) #gets user input for the variable number if number > 99 or number < 0: # uses boolean to compare the user input to 0 and 99 number = random.randint(0, 99) #sets the range for the random generator ff attackValue = float(number)/100 #sets the variable attack value to a float value out of 100 return attackValue #returns attackValue #################################################################### def wrestle(playerStrength, enemyStrength, playerAttackValue): targetValue = random.random() playerAttackResult = playerStrength + abs(playerAttackValue - targetValue) enemyAttackResult = enemyStrength + targetValue if playerAttackResult > enemyAttackResult: return True else: return False def resultTemplate(playerStrength, enemyStrength, result): if result == True: msg = "wins" else: msg = "loses" return """ Player strength: {} Enemy strength: {} Player {}! """.format(playerStrength, enemyStrength, msg) ######################################################################### def main(): playerFood = raw_input("What do you want to eat? ") enemy1Food = raw_input("What does enemy 1 eat? ") enemy2Food = raw_input("What does enemy 2 eat? ") playerStrength = eat(playerFood) enemy1Strength = eat(enemy1Food) enemy2Strength = eat(enemy2Food) playerAttackValue1 = getAttackValue() result1 = wrestle(playerStrength, enemy1Strength, playerAttackValue1) playerAttackValue2 = getAttackValue() result2 = wrestle(playerStrength, enemy2Strength, playerAttackValue2) output = """ You ate {}. Enemy 1 ate {}. Enemy 2 ate {}. """.format(playerFood, enemy1Food, enemy2Food) output += resultTemplate(playerStrength, enemy1Strength, result1) output += resultTemplate(playerStrength, enemy2Strength, result2) print output ############################################################################### #it is possible to win but as the target value is random and target value can be any number you have a very small chance of winning
joshua2352-cmis/joshua2352-cmis-cs2
returnvalues.py
Python
cc0-1.0
2,985
<!DOCTYPE html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="Expires" content="-1"> <meta http-equiv="Pragma" content="no-cache"> <meta http-equiv="Cache-Control" content="no-cache"> <title>105年第十四任總統副總統及第九屆立法委員選舉</title> <link href="../css/style.css" rel="stylesheet" type="text/css"> <link href="../css/style2.css" rel="stylesheet" type="text/css"> <script type="text/javascript" src="../js/ftiens4.js"></script> <script type="text/javascript" src="../js/ua.js"></script> <script type="text/javascript" src="../js/func.js"></script> <script type="text/javascript" src="../js/treeP1.js"></script> <script type="text/javascript" src="../js/refresh.js"></script> </head> <body id="main-body"> <div id="main-header"> <div id="main-top"> <a class="main-top-logo" href="#">中央選舉委員會</a> <ul class="main-top-list"> <li class="main-top-item"><a class="main-top-link main-top-link-home" href="../index.html">回首頁</a></li> <li class="main-top-item"><a class="main-top-link main-top-link-cec" href="http://2016.cec.gov.tw">中選會網站</a></li> <li class="main-top-item"><a class="main-top-link main-top-link-english" href="../../en/index.html">English</a></li> </ul> </div> </div> <div id="main-wrap"> <div id="main-banner"> <div class="slideshow"> <img src="../img/main_bg_1.jpg" width="1024" height="300" alt="background" title="background"> </div> <div class="main-deco"></div> <div class="main-title"></div> <a class="main-pvpe main-pvpe-current" href="../IDX/indexP1.html">總統副總統選舉</a> <a class="main-le" href="../IDX/indexT.html">立法委員選舉</a> </div> <div id="main-container"> <div id="main-content"> <table width="1024" border="1" cellpadding="0" cellspacing="0"> <tr> <td width="180" valign="top"> <div id="divMenu"> <table border="0"> <tr> <td><a style="text-decoration:none;color:silver" href="http://www.treemenu.net/" target=_blank></a></td> </tr> </table> <span class="TreeviewSpanArea"> <script>initializeDocument()</script> <noscript>請開啟Javascript功能</noscript> </span> </div> </td> <td width="796" valign="top"> <div id="divContent"> <!-- 修改區塊 --> <table width="100%" border="0" cellpadding="0" cellspacing="4"> <tr> <td><img src="../images/search.png" alt="候選人得票數" title="候選人得票數">&nbsp;<b>總統副總統選舉&nbsp;候選人在 基隆市 安樂區得票數&nbsp;</b></td> </tr> <tr valign="bottom"> <td> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr valign="bottom"> <td class="fontNumber">&nbsp;<img src="../images/nav.gif" alt="候選組數" title="候選組數">&nbsp;<img src="../images/nav.gif" alt="候選組數" title="候選組數">&nbsp;候選組數:3&nbsp;&nbsp;<img src="../images/nav.gif" alt="應選組數" title="應選組數">&nbsp;<img src="../images/nav.gif" alt="應選組數" title="應選組數">&nbsp;應選組數:1</td> <td align="right"> <select name="selector_order" class="selectC" tabindex="1" id="orderBy" onChange="changeOrder();"> <option value="n">依號次排序</option> <option value="s">依得票排序</option> </select> </td> </tr> </table> </td> </tr> <tr valign="top"> <td> <table width="100%" border="0" cellpadding="6" cellspacing="1" class="tableT"> <tr class="trHeaderT"> <td>註記</td> <td>號次</td> <td><table><tr><td>總統</td><td rowspan=2> 候選人姓名</td></tr><td>副總統</td></table></td> <td>性別</td> <td>得票數</td> <td>得票率%</td> <td>登記方式</td> </tr> <tr class="trT"> <td>&nbsp;</td> <td>1</td> <td>朱立倫<br>王如玄</td> <td>男<br>女</td> <td class="tdAlignRight">15,160</td> <td class="tdAlignRight">35.9191</td> <td>中國國民黨&nbsp; 推薦</td> </tr> <tr class="trT"> <td>◎</td> <td>2</td> <td>蔡英文<br>陳建仁</td> <td>女<br>男</td> <td class="tdAlignRight">20,205</td> <td class="tdAlignRight">47.8723</td> <td>民主進步黨&nbsp; 推薦</td> </tr> <tr class="trT"> <td>&nbsp;</td> <td>3</td> <td>宋楚瑜<br>徐欣瑩</td> <td>男<br>女</td> <td class="tdAlignRight">6,841</td> <td class="tdAlignRight">16.2086</td> <td>親民黨&nbsp; 推薦</td> </tr> <tr class="trFooterT"> <td colspan="7" align="right">投開票所數 已送/應送:&nbsp;48/48&nbsp;</td> </tr> </table> </td> </tr> <tr valign="top"> <td> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="10"></td> <td valign="top" class="fontNote"> <table> <tr> <td>註記說明:</td> <td align="center">◎</td> <td>自然當選</td> </tr> <tr> <td></td> <td align="center">?</td> <td>同票待抽籤</td> </tr> </table> </td> <td valign="top" class="fontTimer"><img src="../images/clock2.png" alt="Sat, 16 Jan 2016 23:15:12 +0800" title="Sat, 16 Jan 2016 23:15:12 +0800">&nbsp;資料更新時間:&nbsp;01/16&nbsp;23:15:06&nbsp;<br>(網頁每3分鐘自動更新一次)</td> </tr> <tr> <td colspan="3" class="fontNote"></td> </tr> </table> </td> </tr> </table> <!-- 修改區塊 --> </div> </td> </tr> </table> </div> <div class="main-footer"></div> <div id="divFooter" align=center>[中央選舉委員會] </div> <!--main-content--> </div><!--main-container--> </div><!--END main-wrap--> <script>setOrder();</script> <script>setMenuScrollPosY();</script> </body> </html>
gugod/vote-watch-2016
data/president/n712000500000000/20160116152503/page.html
HTML
cc0-1.0
6,576
#!/usr/bin/env python """ Fetch a single tweet as JSON using its id. """ from __future__ import print_function import os import sys import json import twarc import argparse e = os.environ.get parser = argparse.ArgumentParser("tweet.py") parser.add_argument('tweet_id', action="store", help="Tweet ID") parser.add_argument("--consumer_key", action="store", default=e('CONSUMER_KEY'), help="Twitter API consumer key") parser.add_argument("--consumer_secret", action="store", default=e('CONSUMER_SECRET'), help="Twitter API consumer secret") parser.add_argument("--access_token", action="store", default=e('ACCESS_TOKEN'), help="Twitter API access key") parser.add_argument("--access_token_secret", action="store", default=e('ACCESS_TOKEN_SECRET'), help="Twitter API access token secret") args = parser.parse_args() tw = twarc.Twarc(args.consumer_key, args.consumer_secret, args.access_token, args.access_token_secret) tweet = tw.get('https://api.twitter.com/1.1/statuses/show/%s.json' % args.tweet_id) print(json.dumps(tweet.json(), indent=2))
ericscartier/twarc
utils/tweet.py
Python
cc0-1.0
1,208
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin'); var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixin); var _svgIcon = require('../../svg-icon'); var _svgIcon2 = _interopRequireDefault(_svgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var CommunicationStayCurrentLandscape = _react2.default.createClass({ displayName: 'CommunicationStayCurrentLandscape', mixins: [_reactAddonsPureRenderMixin2.default], render: function render() { return _react2.default.createElement( _svgIcon2.default, this.props, _react2.default.createElement('path', { d: 'M1.01 7L1 17c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2H3c-1.1 0-1.99.9-1.99 2zM19 7v10H5V7h14z' }) ); } }); exports.default = CommunicationStayCurrentLandscape; module.exports = exports['default'];
DocWave/Doc-tor
node_modules/material-ui/lib/svg-icons/communication/stay-current-landscape.js
JavaScript
cc0-1.0
1,068
/*************************************************************************** * @file strvec.cpp * @author Alan.W * @date 05 JAN 2014 * @remark 16 Feb 2014 : emplace_back added ***************************************************************************/ #include "strvec.h" #include <memory> //! copy constructor StrVec::StrVec(const StrVec &s) { /** * @brief newData is a pair of pointers pointing to newly allocated and copied * range : [b, e) */ std::pair<std::string*, std::string*> newData = alloc_n_copy(s.begin(), s.end()); element = newData.first; first_free = cap = newData.second; } /** * @brief constructor taking initializer_list<string> * for ex 13.40 * @param l */ StrVec::StrVec(std::initializer_list<std::string> l) { //! allocate memory as large as l.size() std::string * const newData = alloc.allocate(l.size()); //! copy elements from l to the address allocated auto p = newData; for(const auto &s : l) alloc.construct(p++, s); //! build the data structure element = newData; first_free = cap = element + l.size(); } //! operator = StrVec& StrVec::operator =(const StrVec& rhs) { //! allocate and copy first to protect against self-assignment std::pair<std::string*, std::string*> newData = alloc_n_copy(rhs.begin(), rhs.end()); //! destroy and deallocate free(); element = newData.first; first_free = cap = newData.second; return *this; } //! destructor StrVec::~StrVec() { free(); } /** * @brief allocate new room if nessary and push back the new string * @param s new string */ void StrVec::push_back(const std::string& s) { chk_n_alloc(); alloc.construct(first_free++, s); } /** * @brief preallocate enough memory for specified number of elements * @param n number of elements required * @note this function is implemented refering to StrVec::reallocate(). */ void StrVec::reserve(std::size_t n) { //! if the n is too small, just ignore it. if(n <= capacity()) return; //! allocate and move old ones into the new address. wy_alloc_n_move(n); } /** * @brief Resizes to the specified number of elements. * @param n Number of elements the %vector should contain. * * This function will resize it to the specified * number of elements. If the number is smaller than the * current size it is truncated, otherwise * default constructed elements are appended. */ void StrVec::resize(std::size_t n) { resize(n,std::string()); } /** * @brief Resizes it to the specified number of elements. * @param __new_size Number of elements it should contain. * @param __x Data with which new elements should be populated. * * This function will resize it to the specified * number of elements. If the number is smaller than the * current size the it is truncated, otherwise * the it is extended and new elements are populated with * given data. */ void StrVec::resize(std::size_t n, const std::string &s) { if(n < size()) { //! destroy the range : [element+n, first_free) using destructor for(auto p = element + n; p != first_free; /* empty */) alloc.destroy(p++); //! move frist_free point to the new address element + n first_free = element + n; } else if( n > size() ) { for(auto i = size(); i != n; ++i) push_back(std::string(s)); } } /** * @brief Double the capacity and using std::move move the original strings to the newly * allocated memory */ void StrVec::reallocate() { //! calculate the new capacity required. std::size_t newCapacity = size() ? 2 * size() : 1; //! allocate and move old ones into the new address. wy_alloc_n_move(newCapacity); } /** * @brief allocate new space for the given range and copy them into it * @param b * @param e * @return a pair of pointers pointing to [first element , one past the last) in the new space */ std::pair<std::string *, std::string *> StrVec::alloc_n_copy(std::string *b, std::string *e) { //! calculate the size needed and allocate space accordingly std::string* data = alloc.allocate(e - b); return { data, std::uninitialized_copy(b, e, data) }; //! ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ //! which copies the range [first,last) into the space of which //! the starting address p_data is pointing to. //! This function returns a pointer pointing to one past the last element. } /** * @brief destroy the elements and deallocate the space previously allocated. */ void StrVec::free() { if(element) // if not nullptr { //! destory it in reverse order. for(auto p = first_free; p != element; /* empty */) alloc.destroy(--p); alloc.deallocate(element, capacity()); } } /** * @brief allocate memory for spicified number of elements * @param n * @note it's user's responsibility to ensure that @param n is greater than * the current capacity. */ void StrVec::wy_alloc_n_move(std::size_t n) { std::size_t newCapacity = n; std::string* newData = alloc.allocate(newCapacity); std::string* dest = newData; std::string* elem = element; //! move the old to newly allocated space. for(std::size_t i = 0; i != size(); ++i) alloc.construct(dest++, std::move(*elem++)); free(); //! update data structure element = newData; first_free = dest; cap = element + newCapacity; }
jieniyimiao/CppPrimer
ch16/ex16.58.59/strvec.cpp
C++
cc0-1.0
5,695
/* * Copyright (C) 2008 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. */ package com.google.zxing.client.android; import android.content.ActivityNotFoundException; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.provider.Browser; import com.google.zxing.BarcodeFormat; import com.google.zxing.Result; import com.google.zxing.client.android.camera.CameraManager; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import com.google.zxing.FakeR; import java.util.Collection; /** * This class handles all the messaging which comprises the state machine for capture. * * @author dswitkin@google.com (Daniel Switkin) */ public final class CaptureActivityHandler extends Handler { private static final String TAG = CaptureActivityHandler.class.getSimpleName(); private final CaptureActivity activity; private final DecodeThread decodeThread; private State state; private final CameraManager cameraManager; private enum State { PREVIEW, SUCCESS, DONE } private static FakeR fakeR; CaptureActivityHandler(CaptureActivity activity, Collection<BarcodeFormat> decodeFormats, String characterSet, CameraManager cameraManager) { fakeR = new FakeR(activity); this.activity = activity; decodeThread = new DecodeThread(activity, decodeFormats, characterSet, new ViewfinderResultPointCallback(activity.getViewfinderView())); decodeThread.start(); state = State.SUCCESS; // Start ourselves capturing previews and decoding. this.cameraManager = cameraManager; cameraManager.startPreview(); restartPreviewAndDecode(); } @Override public void handleMessage(Message message) { if (message.what == fakeR.getId("id", "restart_preview")) { Log.d(TAG, "Got restart preview message"); restartPreviewAndDecode(); } else if (message.what == fakeR.getId("id", "decode_succeeded")) { Log.d(TAG, "Got decode succeeded message"); state = State.SUCCESS; Bundle bundle = message.getData(); Bitmap barcode = bundle == null ? null : (Bitmap) bundle.getParcelable(DecodeThread.BARCODE_BITMAP); activity.handleDecode((Result) message.obj, barcode); } else if (message.what == fakeR.getId("id", "decode_failed")) { // We're decoding as fast as possible, so when one decode fails, start another. state = State.PREVIEW; cameraManager.requestPreviewFrame(decodeThread.getHandler(), fakeR.getId("id", "decode")); } else if (message.what == fakeR.getId("id", "return_scan_result")) { Log.d(TAG, "Got return scan result message"); activity.setResult(Activity.RESULT_OK, (Intent) message.obj); activity.finish(); } else if (message.what == fakeR.getId("id", "launch_product_query")) { Log.d(TAG, "Got product query message"); String url = (String) message.obj; Intent intent = new Intent(Intent.ACTION_VIEW); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); intent.setData(Uri.parse(url)); ResolveInfo resolveInfo = activity.getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY); String browserPackageName = null; if (resolveInfo.activityInfo != null) { browserPackageName = resolveInfo.activityInfo.packageName; Log.d(TAG, "Using browser in package " + browserPackageName); } // Needed for default Android browser only apparently if ("com.android.browser".equals(browserPackageName)) { intent.setPackage(browserPackageName); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra(Browser.EXTRA_APPLICATION_ID, browserPackageName); } try { activity.startActivity(intent); } catch (ActivityNotFoundException anfe) { Log.w(TAG, "Can't find anything to handle VIEW of URI " + url); } } } public void quitSynchronously() { state = State.DONE; cameraManager.stopPreview(); Message quit = Message.obtain(decodeThread.getHandler(), fakeR.getId("id", "quit")); quit.sendToTarget(); try { // Wait at most half a second; should be enough time, and onPause() will timeout quickly decodeThread.join(500L); } catch (InterruptedException e) { // continue } // Be absolutely sure we don't send any queued up messages removeMessages(fakeR.getId("id", "decode_succeeded")); removeMessages(fakeR.getId("id", "decode_failed")); } private void restartPreviewAndDecode() { if (state == State.SUCCESS) { state = State.PREVIEW; cameraManager.requestPreviewFrame(decodeThread.getHandler(), fakeR.getId("id", "decode")); activity.drawViewfinder(); } } }
TorranceLearning/xAPI-Gnome
plugins/phonegap-plugin-barcodescanner/src/android/LibraryProject/src/com/google/zxing/client/android/CaptureActivityHandler.java
Java
cc0-1.0
5,583
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Form Validation : CodeIgniter User Guide</title> <style type='text/css' media='all'>@import url('../userguide.css');</style> <link rel='stylesheet' type='text/css' media='all' href='../userguide.css' /> <script type="text/javascript" src="../nav/nav.js"></script> <script type="text/javascript" src="../nav/prototype.lite.js"></script> <script type="text/javascript" src="../nav/moo.fx.js"></script> <script type="text/javascript" src="../nav/user_guide_menu.js"></script> <meta http-equiv='expires' content='-1' /> <meta http-equiv= 'pragma' content='no-cache' /> <meta name='robots' content='all' /> <meta name='author' content='ExpressionEngine Dev Team' /> <meta name='description' content='CodeIgniter User Guide' /> </head> <body> <!-- START NAVIGATION --> <div id="nav"><div id="nav_inner"><script type="text/javascript">create_menu('../');</script></div></div> <div id="nav2"><a name="top"></a><a href="javascript:void(0);" onclick="myHeight.toggle();"><img src="../images/nav_toggle_darker.jpg" width="154" height="43" border="0" title="Toggle Table of Contents" alt="Toggle Table of Contents" /></a></div> <div id="masthead"> <table cellpadding="0" cellspacing="0" border="0" style="width:100%"> <tr> <td><h1>CodeIgniter User Guide Version 2.2.0</h1></td> <td id="breadcrumb_right"><a href="../toc.html">Table of Contents Page</a></td> </tr> </table> </div> <!-- END NAVIGATION --> <!-- START BREADCRUMB --> <table cellpadding="0" cellspacing="0" border="0" style="width:100%"> <tr> <td id="breadcrumb"> <a href="http://codeigniter.com/">CodeIgniter Home</a> &nbsp;&#8250;&nbsp; <a href="../index.html">User Guide Home</a> &nbsp;&#8250;&nbsp; Form Validation </td> <td id="searchbox"><form method="get" action="http://www.google.com/search"><input type="hidden" name="as_sitesearch" id="as_sitesearch" value="ellislab.com/codeigniter/user-guide/" />Search User Guide&nbsp; <input type="text" class="input" style="width:200px;" name="q" id="q" size="31" maxlength="255" value="" />&nbsp;<input type="submit" class="submit" name="sa" value="Go" /></form></td> </tr> </table> <!-- END BREADCRUMB --> <br clear="all" /> <!-- START CONTENT --> <div id="content"> <h1>Form Validation</h1> <p>CodeIgniter provides a comprehensive form validation and data prepping class that helps minimize the amount of code you'll write.</p> <ul> <li><a href="#overview">Overview</a></li> <li><a href="#tutorial">Form Validation Tutorial</a> <ul> <li><a href="#theform">The Form</a></li> <li><a href="#thesuccesspage">The Success Page</a></li> <li><a href="#thecontroller">The Controller</a></li> <li><a href="#validationrules">Setting Validation Rules</a></li> <li><a href="#validationrulesasarray">Setting Validation Rules Using an Array</a></li> <li><a href="#cascadingrules">Cascading Rules</a></li> <li><a href="#preppingdata">Prepping Data</a></li> <li><a href="#repopulatingform">Re-populating the Form</a></li> <li><a href="#callbacks">Callbacks</a></li> <li><a href="#settingerrors">Setting Error Messages</a></li> <li><a href="#errordelimiters">Changing the Error Delimiters</a></li> <li><a href="#translatingfn">Translating Field Names</a></li> <li><a href="#individualerrors">Showing Errors Individually</a></li> <li><a href="#savingtoconfig">Saving Sets of Validation Rules to a Config File</a></li> <li><a href="#arraysasfields">Using Arrays as Field Names</a></li> </ul> </li> <li><a href="#rulereference">Rule Reference</a></li> <li><a href="#preppingreference">Prepping Reference</a></li> <li><a href="#functionreference">Function Reference</a></li> <li><a href="#helperreference">Helper Reference</a></li> </ul> <p>&nbsp;</p> <a name="overview"></a> <h1>Overview</h1> <p>Before explaining CodeIgniter's approach to data validation, let's describe the ideal scenario:</p> <ol> <li>A form is displayed.</li> <li>You fill it in and submit it.</li> <li>If you submitted something invalid, or perhaps missed a required item, the form is redisplayed containing your data along with an error message describing the problem.</li> <li>This process continues until you have submitted a valid form.</li> </ol> <p>On the receiving end, the script must:</p> <ol> <li>Check for required data.</li> <li>Verify that the data is of the correct type, and meets the correct criteria. For example, if a username is submitted it must be validated to contain only permitted characters. It must be of a minimum length, and not exceed a maximum length. The username can't be someone else's existing username, or perhaps even a reserved word. Etc.</li> <li>Sanitize the data for security.</li> <li>Pre-format the data if needed (Does the data need to be trimmed? HTML encoded? Etc.)</li> <li>Prep the data for insertion in the database.</li> </ol> <p>Although there is nothing terribly complex about the above process, it usually requires a significant amount of code, and to display error messages, various control structures are usually placed within the form HTML. Form validation, while simple to create, is generally very messy and tedious to implement.</p> <p>&nbsp;</p> <a name="tutorial"></a> <h1>Form Validation Tutorial</h1> <p>What follows is a "hands on" tutorial for implementing CodeIgniters Form Validation.</p> <p>In order to implement form validation you'll need three things:</p> <ol> <li>A <a href="../general/views.html">View</a> file containing a form.</li> <li>A View file containing a "success" message to be displayed upon successful submission.</li> <li>A <a href="../general/controllers.html">controller</a> function to receive and process the submitted data.</li> </ol> <p>Let's create those three things, using a member sign-up form as the example.</p> <a name="theform"></a> <h2>The Form</h2> <p>Using a text editor, create a form called <dfn>myform.php</dfn>. In it, place this code and save it to your <samp>applications/views/</samp> folder:</p> <textarea class="textarea" style="width:100%" cols="50" rows="30">&lt;html> &lt;head> &lt;title>My Form&lt;/title> &lt;/head> &lt;body> &lt;?php echo validation_errors(); ?> &lt;?php echo form_open('form'); ?> &lt;h5>Username&lt;/h5> &lt;input type="text" name="username" value="" size="50" /> &lt;h5>Password&lt;/h5> &lt;input type="text" name="password" value="" size="50" /> &lt;h5>Password Confirm&lt;/h5> &lt;input type="text" name="passconf" value="" size="50" /> &lt;h5>Email Address&lt;/h5> &lt;input type="text" name="email" value="" size="50" /> &lt;div>&lt;input type="submit" value="Submit" />&lt;/div> &lt;/form> &lt;/body> &lt;/html> </textarea> <a name="thesuccesspage"></a> <h2>The Success Page</h2> <p>Using a text editor, create a form called <dfn>formsuccess.php</dfn>. In it, place this code and save it to your <samp>applications/views/</samp> folder:</p> <textarea class="textarea" style="width:100%" cols="50" rows="14"> &lt;html> &lt;head> &lt;title>My Form&lt;/title> &lt;/head> &lt;body> &lt;h3>Your form was successfully submitted!&lt;/h3> &lt;p>&lt;?php echo anchor('form', 'Try it again!'); ?>&lt;/p> &lt;/body> &lt;/html> </textarea> <a name="thecontroller"></a> <h2>The Controller</h2> <p>Using a text editor, create a controller called <dfn>form.php</dfn>. In it, place this code and save it to your <samp>applications/controllers/</samp> folder:</p> <textarea class="textarea" style="width:100%" cols="50" rows="21">&lt;?php class Form extends CI_Controller { function index() { $this->load->helper(array('form', 'url')); $this->load->library('form_validation'); if ($this->form_validation->run() == FALSE) { $this->load->view('myform'); } else { $this->load->view('formsuccess'); } } } ?></textarea> <h2>Try it!</h2> <p>To try your form, visit your site using a URL similar to this one:</p> <code>example.com/index.php/<var>form</var>/</code> <p><dfn>If you submit the form you should simply see the form reload. That's because you haven't set up any validation rules yet.</dfn></p> <p><strong>Since you haven't told the Form Validation class to validate anything yet, it returns <kbd>FALSE</kbd> (boolean false) by default. The <samp>run()</samp> function only returns <kbd>TRUE</kbd> if it has successfully applied your rules without any of them failing.</strong></p> <h2>Explanation</h2> <p>You'll notice several things about the above pages:</p> <p>The <dfn>form</dfn> (myform.php) is a standard web form with a couple exceptions:</p> <ol> <li>It uses a <dfn>form helper</dfn> to create the form opening. Technically, this isn't necessary. You could create the form using standard HTML. However, the benefit of using the helper is that it generates the action URL for you, based on the URL in your config file. This makes your application more portable in the event your URLs change.</li> <li>At the top of the form you'll notice the following function call: <code>&lt;?php echo validation_errors(); ?&gt;</code> <p>This function will return any error messages sent back by the validator. If there are no messages it returns an empty string.</p> </li> </ol> <p>The <dfn>controller</dfn> (form.php) has one function: <dfn>index()</dfn>. This function initializes the validation class and loads the <var>form helper</var> and <var>URL helper</var> used by your view files. It also <samp>runs</samp> the validation routine. Based on whether the validation was successful it either presents the form or the success page.</p> <a name="validationrules"></a> <h2>Setting Validation Rules</h2> <p>CodeIgniter lets you set as many validation rules as you need for a given field, cascading them in order, and it even lets you prep and pre-process the field data at the same time. To set validation rules you will use the <dfn>set_rules()</dfn> function:</p> <code>$this->form_validation->set_rules();</code> <p>The above function takes <strong>three</strong> parameters as input:</p> <ol> <li>The field name - the exact name you've given the form field.</li> <li>A "human" name for this field, which will be inserted into the error message. For example, if your field is named "user" you might give it a human name of "Username". <strong>Note:</strong> If you would like the field name to be stored in a language file, please see <a href="#translatingfn">Translating Field Names</a>.</li> <li>The validation rules for this form field.</li> </ol> <p><br />Here is an example. In your <dfn>controller</dfn> (form.php), add this code just below the validation initialization function:</p> <code> $this->form_validation->set_rules('username', 'Username', 'required');<br /> $this->form_validation->set_rules('password', 'Password', 'required');<br /> $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');<br /> $this->form_validation->set_rules('email', 'Email', 'required');<br /> </code> <p>Your controller should now look like this:</p> <textarea class="textarea" style="width:100%" cols="50" rows="28">&lt;?php class Form extends CI_Controller { function index() { $this->load->helper(array('form', 'url')); $this->load->library('form_validation'); $this->form_validation->set_rules('username', 'Username', 'required'); $this->form_validation->set_rules('password', 'Password', 'required'); $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required'); $this->form_validation->set_rules('email', 'Email', 'required'); if ($this->form_validation->run() == FALSE) { $this->load->view('myform'); } else { $this->load->view('formsuccess'); } } } ?></textarea> <p><dfn>Now submit the form with the fields blank and you should see the error messages. If you submit the form with all the fields populated you'll see your success page.</dfn></p> <p class="important"><strong>Note:</strong> The form fields are not yet being re-populated with the data when there is an error. We'll get to that shortly.</p> <a name="validationrulesasarray"></a> <h2>Setting Rules Using an Array</h2> <p>Before moving on it should be noted that the rule setting function can be passed an array if you prefer to set all your rules in one action. If you use this approach you must name your array keys as indicated:</p> <code> $config = array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'field'&nbsp;&nbsp;&nbsp;=> 'username', <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'label'&nbsp;&nbsp;&nbsp;=> 'Username', <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'rules'&nbsp;&nbsp;&nbsp;=> 'required'<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;),<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'field'&nbsp;&nbsp;&nbsp;=> 'password', <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'label'&nbsp;&nbsp;&nbsp;=> 'Password', <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'rules'&nbsp;&nbsp;&nbsp;=> 'required'<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;),<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'field'&nbsp;&nbsp;&nbsp;=> 'passconf', <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'label'&nbsp;&nbsp;&nbsp;=> 'Password Confirmation', <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'rules'&nbsp;&nbsp;&nbsp;=> 'required'<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;),&nbsp;&nbsp;&nbsp;<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'field'&nbsp;&nbsp;&nbsp;=> 'email', <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'label'&nbsp;&nbsp;&nbsp;=> 'Email', <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'rules'&nbsp;&nbsp;&nbsp;=> 'required'<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;)<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;);<br /> <br /> $this->form_validation->set_rules($config); </code> <a name="cascadingrules"></a> <h2>Cascading Rules</h2> <p>CodeIgniter lets you pipe multiple rules together. Let's try it. Change your rules in the third parameter of rule setting function, like this:</p> <code> $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]|is_unique[users.username]');<br /> $this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]');<br /> $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');<br /> $this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');<br /> </code> <p>The above code sets the following rules:</p> <ol> <li>The username field be no shorter than 5 characters and no longer than 12.</li> <li>The password field must match the password confirmation field.</li> <li>The email field must contain a valid email address.</li> </ol> <p>Give it a try! Submit your form without the proper data and you'll see new error messages that correspond to your new rules. There are numerous rules available which you can read about in the validation reference.</p> <a name="preppingdata"></a> <h2>Prepping Data</h2> <p>In addition to the validation functions like the ones we used above, you can also prep your data in various ways. For example, you can set up rules like this:</p> <code> $this->form_validation->set_rules('username', 'Username', '<kbd>trim</kbd>|required|min_length[5]|max_length[12]|<kbd>xss_clean</kbd>');<br /> $this->form_validation->set_rules('password', 'Password', '<kbd>trim</kbd>|required|matches[passconf]|<kbd>md5</kbd>');<br /> $this->form_validation->set_rules('passconf', 'Password Confirmation', '<kbd>trim</kbd>|required');<br /> $this->form_validation->set_rules('email', 'Email', '<kbd>trim</kbd>|required|valid_email');<br /> </code> <p>In the above example, we are "trimming" the fields, converting the password to MD5, and running the username through the "xss_clean" function, which removes malicious data.</p> <p><strong>Any native PHP function that accepts one parameter can be used as a rule, like <dfn>htmlspecialchars</dfn>, <dfn>trim</dfn>, <dfn>MD5</dfn>, etc.</strong></p> <p><strong>Note:</strong> You will generally want to use the prepping functions <strong>after</strong> the validation rules so if there is an error, the original data will be shown in the form.</p> <a name="repopulatingform"></a> <h2>Re-populating the form</h2> <p>Thus far we have only been dealing with errors. It's time to repopulate the form field with the submitted data. CodeIgniter offers several helper functions that permit you to do this. The one you will use most commonly is:</p> <code>set_value('field name')</code> <p>Open your <dfn>myform.php</dfn> view file and update the <strong>value</strong> in each field using the <dfn>set_value()</dfn> function:</p> <p><strong>Don't forget to include each field name in the <dfn>set_value()</dfn> functions!</strong></p> <textarea class="textarea" style="width:100%" cols="50" rows="30"> &lt;html> &lt;head> &lt;title>My Form&lt;/title> &lt;/head> &lt;body> &lt;?php echo validation_errors(); ?> &lt;?php echo form_open('form'); ?> &lt;h5>Username&lt;/h5> &lt;input type="text" name="username" value="&lt;?php echo set_value('username'); ?>" size="50" /> &lt;h5>Password&lt;/h5> &lt;input type="text" name="password" value="&lt;?php echo set_value('password'); ?>" size="50" /> &lt;h5>Password Confirm&lt;/h5> &lt;input type="text" name="passconf" value="&lt;?php echo set_value('passconf'); ?>" size="50" /> &lt;h5>Email Address&lt;/h5> &lt;input type="text" name="email" value="&lt;?php echo set_value('email'); ?>" size="50" /> &lt;div>&lt;input type="submit" value="Submit" />&lt;/div> &lt;/form> &lt;/body> &lt;/html> </textarea> <p><dfn>Now reload your page and submit the form so that it triggers an error. Your form fields should now be re-populated</dfn></p> <p class="important"><strong>Note:</strong> The <a href="#functionreference">Function Reference</a> section below contains functions that permit you to re-populate &lt;select> menus, radio buttons, and checkboxes.</p> <p><strong>Important Note:</strong> If you use an array as the name of a form field, you must supply it as an array to the function. Example:</p> <code>&lt;input type="text" name="<kbd>colors[]</kbd>" value="&lt;?php echo set_value('<kbd>colors[]</kbd>'); ?>" size="50" /></code> <p>For more info please see the <a href="#arraysasfields">Using Arrays as Field Names</a> section below.</p> <a name="callbacks"></a> <h2>Callbacks: Your own Validation Functions</h2> <p>The validation system supports callbacks to your own validation functions. This permits you to extend the validation class to meet your needs. For example, if you need to run a database query to see if the user is choosing a unique username, you can create a callback function that does that. Let's create a example of this.</p> <p>In your controller, change the "username" rule to this:</p> <code>$this->form_validation->set_rules('username', 'Username', '<kbd>callback_username_check</kbd>');</code> <p>Then add a new function called <dfn>username_check</dfn> to your controller. Here's how your controller should now look:</p> <textarea class="textarea" style="width:100%" cols="50" rows="40">&lt;?php class Form extends CI_Controller { public function index() { $this->load->helper(array('form', 'url')); $this->load->library('form_validation'); $this->form_validation->set_rules('username', 'Username', 'callback_username_check'); $this->form_validation->set_rules('password', 'Password', 'required'); $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required'); $this->form_validation->set_rules('email', 'Email', 'required|is_unique[users.email]'); if ($this->form_validation->run() == FALSE) { $this->load->view('myform'); } else { $this->load->view('formsuccess'); } } public function username_check($str) { if ($str == 'test') { $this->form_validation->set_message('username_check', 'The %s field can not be the word "test"'); return FALSE; } else { return TRUE; } } } ?></textarea> <p><dfn>Reload your form and submit it with the word "test" as the username. You can see that the form field data was passed to your callback function for you to process.</dfn></p> <p>To invoke a callback just put the function name in a rule, with "callback_" as the rule <strong>prefix</strong>. If you need to receive an extra parameter in your callback function, just add it normally after the function name between square brackets, as in: "callback_foo<strong>[bar]</strong>", then it will be passed as the second argument of your callback function.</p> <p><strong>Note:</strong> You can also process the form data that is passed to your callback and return it. If your callback returns anything other than a boolean TRUE/FALSE it is assumed that the data is your newly processed form data.</p> <a name="settingerrors"></a> <h2>Setting Error Messages</h2> <p>All of the native error messages are located in the following language file: <dfn>language/english/form_validation_lang.php</dfn></p> <p>To set your own custom message you can either edit that file, or use the following function:</p> <code>$this->form_validation->set_message('<var>rule</var>', '<var>Error Message</var>');</code> <p>Where <var>rule</var> corresponds to the name of a particular rule, and <var>Error Message</var> is the text you would like displayed.</p> <p>If you include <dfn>%s</dfn> in your error string, it will be replaced with the "human" name you used for your field when you set your rules.</p> <p>In the "callback" example above, the error message was set by passing the name of the function:</p> <code>$this->form_validation->set_message('username_check')</code> <p>You can also override any error message found in the language file. For example, to change the message for the "required" rule you will do this:</p> <code>$this->form_validation->set_message('required', 'Your custom message here');</code> <a name="translatingfn"></a> <h2>Translating Field Names</h2> <p>If you would like to store the "human" name you passed to the <dfn>set_rules()</dfn> function in a language file, and therefore make the name able to be translated, here's how:</p> <p>First, prefix your "human" name with <dfn>lang:</dfn>, as in this example:</p> <code> $this->form_validation->set_rules('first_name', '<kbd>lang:</kbd>first_name', 'required');<br /> </code> <p>Then, store the name in one of your language file arrays (without the prefix):</p> <code>$lang['first_name'] = 'First Name';</code> <p><strong>Note:</strong> If you store your array item in a language file that is not loaded automatically by CI, you'll need to remember to load it in your controller using:</p> <code>$this->lang->load('file_name');</code> <p>See the <a href="language.html">Language Class</a> page for more info regarding language files.</p> <a name="errordelimiters"></a> <h2>Changing the Error Delimiters</h2> <p>By default, the Form Validation class adds a paragraph tag (&lt;p&gt;) around each error message shown. You can either change these delimiters globally or individually.</p> <ol> <li><strong>Changing delimiters Globally</strong> <p>To globally change the error delimiters, in your controller function, just after loading the Form Validation class, add this:</p> <code>$this->form_validation->set_error_delimiters('<kbd>&lt;div class="error"></kbd>', '<kbd>&lt;/div></kbd>');</code> <p>In this example, we've switched to using div tags.</p> </li> <li><strong>Changing delimiters Individually</strong> <p>Each of the two error generating functions shown in this tutorial can be supplied their own delimiters as follows:</p> <code>&lt;?php echo form_error('field name', '<kbd>&lt;div class="error"></kbd>', '<kbd>&lt;/div></kbd>'); ?></code> <p>Or:</p> <code>&lt;?php echo validation_errors('<kbd>&lt;div class="error"></kbd>', '<kbd>&lt;/div></kbd>'); ?></code> </li> </ol> <a name="individualerrors"></a> <h2>Showing Errors Individually</h2> <p>If you prefer to show an error message next to each form field, rather than as a list, you can use the <dfn>form_error()</dfn> function.</p> <p>Try it! Change your form so that it looks like this:</p> <textarea class="textarea" style="width:100%" cols="50" rows="18"> &lt;h5>Username&lt;/h5> &lt;?php echo form_error('username'); ?> &lt;input type="text" name="username" value="&lt;?php echo set_value('username'); ?>" size="50" /> &lt;h5>Password&lt;/h5> &lt;?php echo form_error('password'); ?> &lt;input type="text" name="password" value="&lt;?php echo set_value('password'); ?>" size="50" /> &lt;h5>Password Confirm&lt;/h5> &lt;?php echo form_error('passconf'); ?> &lt;input type="text" name="passconf" value="&lt;?php echo set_value('passconf'); ?>" size="50" /> &lt;h5>Email Address&lt;/h5> &lt;?php echo form_error('email'); ?> &lt;input type="text" name="email" value="&lt;?php echo set_value('email'); ?>" size="50" /> </textarea> <p>If there are no errors, nothing will be shown. If there is an error, the message will appear.</p> <p><strong>Important Note:</strong> If you use an array as the name of a form field, you must supply it as an array to the function. Example:</p> <code>&lt;?php echo form_error('<kbd>options[size]</kbd>'); ?><br /> &lt;input type="text" name="<kbd>options[size]</kbd>" value="&lt;?php echo set_value("<kbd>options[size]</kbd>"); ?>" size="50" /> </code> <p>For more info please see the <a href="#arraysasfields">Using Arrays as Field Names</a> section below.</p> <p>&nbsp;</p> <a name="savingtoconfig"></a> <h1>Saving Sets of Validation Rules to a Config File</h1> <p>A nice feature of the Form Validation class is that it permits you to store all your validation rules for your entire application in a config file. You can organize these rules into "groups". These groups can either be loaded automatically when a matching controller/function is called, or you can manually call each set as needed.</p> <h3>How to save your rules</h3> <p>To store your validation rules, simply create a file named <kbd>form_validation.php</kbd> in your <dfn>application/config/</dfn> folder. In that file you will place an array named <kbd>$config</kbd> with your rules. As shown earlier, the validation array will have this prototype:</p> <code> $config = array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'field'&nbsp;&nbsp;&nbsp;=> 'username', <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'label'&nbsp;&nbsp;&nbsp;=> 'Username', <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'rules'&nbsp;&nbsp;&nbsp;=> 'required'<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;),<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'field'&nbsp;&nbsp;&nbsp;=> 'password', <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'label'&nbsp;&nbsp;&nbsp;=> 'Password', <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'rules'&nbsp;&nbsp;&nbsp;=> 'required'<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;),<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'field'&nbsp;&nbsp;&nbsp;=> 'passconf', <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'label'&nbsp;&nbsp;&nbsp;=> 'Password Confirmation', <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'rules'&nbsp;&nbsp;&nbsp;=> 'required'<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;),&nbsp;&nbsp;&nbsp;<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'field'&nbsp;&nbsp;&nbsp;=> 'email', <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'label'&nbsp;&nbsp;&nbsp;=> 'Email', <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'rules'&nbsp;&nbsp;&nbsp;=> 'required'<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;)<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;);<br /> </code> <p><dfn>Your validation rule file will be loaded automatically and used when you call the run() function.</dfn></p> <p class="important">Please note that you MUST name your array $config.</p> <h3>Creating Sets of Rules</h3> <p>In order to organize your rules into "sets" requires that you place them into "sub arrays". Consider the following example, showing two sets of rules. We've arbitrarily called these two rules "signup" and "email". You can name your rules anything you want:</p> <code>$config = array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'<kbd>signup</kbd>' => array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'field' => 'username',<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'label' => 'Username',<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'rules' => 'required'<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;),<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'field' => 'password',<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'label' => 'Password',<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'rules' => 'required'<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;),<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'field' => 'passconf',<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'label' => 'PasswordConfirmation',<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'rules' => 'required'<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;),<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'field' => 'email',<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'label' => 'Email',<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'rules' => 'required'<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;)<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;),<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'<kbd>email</kbd>' => array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'field' => 'emailaddress',<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'label' => 'EmailAddress',<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'rules' => 'required|valid_email'<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;),<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'field' => 'name',<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'label' => 'Name',<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'rules' => 'required|alpha'<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;),<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'field' => 'title',<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'label' => 'Title',<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'rules' => 'required'<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;),<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'field' => 'message',<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'label' => 'MessageBody',<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'rules' => 'required'<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;)<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;);<br /> </code> <h3>Calling a Specific Rule Group</h3> <p>In order to call a specific group you will pass its name to the <kbd>run()</kbd> function. For example, to call the <kbd>signup</kbd> rule you will do this:</p> <code> if ($this->form_validation->run('<kbd>signup</kbd>') == FALSE)<br /> {<br /> &nbsp;&nbsp;&nbsp;$this->load->view('myform');<br /> }<br /> else<br /> {<br /> &nbsp;&nbsp;&nbsp;$this->load->view('formsuccess');<br /> }<br /> </code> <h3>Associating a Controller Function with a Rule Group</h3> <p>An alternate (and more automatic) method of calling a rule group is to name it according to the controller class/function you intend to use it with. For example, let's say you have a controller named <kbd>Member</kbd> and a function named <kbd>signup</kbd>. Here's what your class might look like:</p> <code> &lt;?php<br /><br /> class <kbd>Member</kbd> extends CI_Controller {<br /> <br /> &nbsp;&nbsp;&nbsp;function <kbd>signup</kbd>()<br /> &nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$this->load->library('form_validation');<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if ($this->form_validation->run() == FALSE)<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$this->load->view('myform');<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;else<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$this->load->view('formsuccess');<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br /> &nbsp;&nbsp;&nbsp;}<br /> }<br /> ?></code> <p>In your validation config file, you will name your rule group <kbd>member/signup</kbd>:</p> <code>$config = array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'<kbd>member/signup</kbd>' => array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'field' => 'username',<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'label' => 'Username',<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'rules' => 'required'<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;),<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'field' => 'password',<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'label' => 'Password',<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'rules' => 'required'<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;),<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'field' => 'passconf',<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'label' => 'PasswordConfirmation',<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'rules' => 'required'<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;),<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;array(<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'field' => 'email',<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'label' => 'Email',<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'rules' => 'required'<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;)<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;)<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;);<br /> </code> <p><dfn>When a rule group is named identically to a controller class/function it will be used automatically when the run() function is invoked from that class/function.</dfn></p> <p>&nbsp;</p> <a name="arraysasfields"></a> <h1>Using Arrays as Field Names</h1> <p>The Form Validation class supports the use of arrays as field names. Consider this example:</p> <code>&lt;input type="text" name="<kbd>options[]</kbd>" value="" size="50" /></code> <p>If you do use an array as a field name, you must use the EXACT array name in the <a href="#helperreference">Helper Functions</a> that require the field name, and as your Validation Rule field name.</p> <p>For example, to set a rule for the above field you would use:</p> <code>$this->form_validation->set_rules('<kbd>options[]</kbd>', 'Options', 'required');</code> <p>Or, to show an error for the above field you would use:</p> <code>&lt;?php echo form_error('<kbd>options[]</kbd>'); ?></code> <p>Or to re-populate the field you would use:</p> <code>&lt;input type="text" name="<kbd>options[]</kbd>" value="<kbd>&lt;?php echo set_value('<kbd>options[]</kbd>'); ?></kbd>" size="50" /></code> <p>You can use multidimensional arrays as field names as well. For example:</p> <code>&lt;input type="text" name="<kbd>options[size]</kbd>" value="" size="50" /></code> <p>Or even:</p> <code>&lt;input type="text" name="<kbd>sports[nba][basketball]</kbd>" value="" size="50" /></code> <p>As with our first example, you must use the exact array name in the helper functions:</p> <code>&lt;?php echo form_error('<kbd>sports[nba][basketball]</kbd>'); ?></code> <p>If you are using checkboxes (or other fields) that have multiple options, don't forget to leave an empty bracket after each option, so that all selections will be added to the POST array:</p> <code> &lt;input type="checkbox" name="<kbd>options[]</kbd>" value="red" /><br /> &lt;input type="checkbox" name="<kbd>options[]</kbd>" value="blue" /><br /> &lt;input type="checkbox" name="<kbd>options[]</kbd>" value="green" /> </code> <p>Or if you use a multidimensional array:</p> <code> &lt;input type="checkbox" name="<kbd>options[color][]</kbd>" value="red" /><br /> &lt;input type="checkbox" name="<kbd>options[color][]</kbd>" value="blue" /><br /> &lt;input type="checkbox" name="<kbd>options[color][]</kbd>" value="green" /> </code> <p>When you use a helper function you'll include the bracket as well:</p> <code>&lt;?php echo form_error('<kbd>options[color][]</kbd>'); ?></code> <p>&nbsp;</p> <a name="rulereference"></a> <h1>Rule Reference</h1> <p>The following is a list of all the native rules that are available to use:</p> <table cellpadding="0" cellspacing="1" border="0" style="width:100%" class="tableborder"> <tr> <th>Rule</th> <th>Parameter</th> <th>Description</th> <th>Example</th> </tr> <tr> <td class="td"><strong>required</strong></td> <td class="td">No</td> <td class="td">Returns FALSE if the form element is empty.</td> <td class="td">&nbsp;</td> </tr> <tr> <td class="td"><strong>matches</strong></td> <td class="td">Yes</td> <td class="td">Returns FALSE if the form element does not match the one in the parameter.</td> <td class="td">matches[form_item]</td> </tr> <tr> <td class="td"><strong>is_unique</strong></td> <td class="td">Yes</td> <td class="td">Returns FALSE if the form element is not unique to the table and field name in the parameter.</td> <td class="td">is_unique[table.field]</td> </tr> <tr> <td class="td"><strong>min_length</strong></td> <td class="td">Yes</td> <td class="td">Returns FALSE if the form element is shorter then the parameter value.</td> <td class="td">min_length[6]</td> </tr> <tr> <td class="td"><strong>max_length</strong></td> <td class="td">Yes</td> <td class="td">Returns FALSE if the form element is longer then the parameter value.</td> <td class="td">max_length[12]</td> </tr> <tr> <td class="td"><strong>exact_length</strong></td> <td class="td">Yes</td> <td class="td">Returns FALSE if the form element is not exactly the parameter value.</td> <td class="td">exact_length[8]</td> </tr> <tr> <td class="td"><strong>greater_than</strong></td> <td class="td">Yes</td> <td class="td">Returns FALSE if the form element is less than the parameter value or not numeric.</td> <td class="td">greater_than[8]</td> </tr> <tr> <td class="td"><strong>less_than</strong></td> <td class="td">Yes</td> <td class="td">Returns FALSE if the form element is greater than the parameter value or not numeric.</td> <td class="td">less_than[8]</td> </tr> <tr> <td class="td"><strong>alpha</strong></td> <td class="td">No</td> <td class="td">Returns FALSE if the form element contains anything other than alphabetical characters.</td> <td class="td">&nbsp;</td> </tr> <tr> <td class="td"><strong>alpha_numeric</strong></td> <td class="td">No</td> <td class="td">Returns FALSE if the form element contains anything other than alpha-numeric characters.</td> <td class="td">&nbsp;</td> </tr> <tr> <td class="td"><strong>alpha_dash</strong></td> <td class="td">No</td> <td class="td">Returns FALSE if the form element contains anything other than alpha-numeric characters, underscores or dashes.</td> <td class="td">&nbsp;</td> </tr> <tr> <td class="td"><strong>numeric</strong></td> <td class="td">No</td> <td class="td">Returns FALSE if the form element contains anything other than numeric characters.</td> <td class="td">&nbsp;</td> </tr> <tr> <td class="td"><strong>integer</strong></td> <td class="td">No</td> <td class="td">Returns FALSE if the form element contains anything other than an integer.</td> <td class="td">&nbsp;</td> </tr> <tr> <td class="td"><strong>decimal</strong></td> <td class="td">No</td> <td class="td">Returns FALSE if the form element contains anything other than a decimal number.</td> <td class="td">&nbsp;</td> </tr> <tr> <td class="td"><strong>is_natural</strong></td> <td class="td">No</td> <td class="td">Returns FALSE if the form element contains anything other than a natural number: 0, 1, 2, 3, etc.</td> <td class="td">&nbsp;</td> </tr> <tr> <td class="td"><strong>is_natural_no_zero</strong></td> <td class="td">No</td> <td class="td">Returns FALSE if the form element contains anything other than a natural number, but not zero: 1, 2, 3, etc.</td> <td class="td">&nbsp;</td> </tr> <tr> <td class="td"><strong>valid_email</strong></td> <td class="td">No</td> <td class="td">Returns FALSE if the form element does not contain a valid email address.</td> <td class="td">&nbsp;</td> </tr> <tr> <td class="td"><strong>valid_emails</strong></td> <td class="td">No</td> <td class="td">Returns FALSE if any value provided in a comma separated list is not a valid email.</td> <td class="td">&nbsp;</td> </tr> <tr> <td class="td"><strong>valid_ip</strong></td> <td class="td">No</td> <td class="td">Returns FALSE if the supplied IP is not valid. Accepts an optional parameter of "IPv4" or "IPv6" to specify an IP format.</td> <td class="td">&nbsp;</td> </tr> <tr> <td class="td"><strong>valid_base64</strong></td> <td class="td">No</td> <td class="td">Returns FALSE if the supplied string contains anything other than valid Base64 characters.</td> <td class="td">&nbsp;</td> </tr> </table> <p><strong>Note:</strong> These rules can also be called as discrete functions. For example:</p> <code>$this->form_validation->required($string);</code> <p class="important"><strong>Note:</strong> You can also use any native PHP functions that permit one parameter.</p> <p>&nbsp;</p> <a name="preppingreference"></a> <h1>Prepping Reference</h1> <p>The following is a list of all the prepping functions that are available to use:</p> <table cellpadding="0" cellspacing="1" border="0" style="width:100%" class="tableborder"> <tr> <th>Name</th> <th>Parameter</th> <th>Description</th> </tr><tr> <td class="td"><strong>xss_clean</strong></td> <td class="td">No</td> <td class="td">Runs the data through the XSS filtering function, described in the <a href="input.html">Input Class</a> page.</td> </tr><tr> <td class="td"><strong>prep_for_form</strong></td> <td class="td">No</td> <td class="td">Converts special characters so that HTML data can be shown in a form field without breaking it.</td> </tr><tr> <td class="td"><strong>prep_url</strong></td> <td class="td">No</td> <td class="td">Adds "http://" to URLs if missing.</td> </tr><tr> <td class="td"><strong>strip_image_tags</strong></td> <td class="td">No</td> <td class="td">Strips the HTML from image tags leaving the raw URL.</td> </tr><tr> <td class="td"><strong>encode_php_tags</strong></td> <td class="td">No</td> <td class="td">Converts PHP tags to entities.</td> </tr> </table> <p class="important"><strong>Note:</strong> You can also use any native PHP functions that permit one parameter, like <kbd>trim</kbd>, <kbd>htmlspecialchars</kbd>, <kbd>urldecode</kbd>, etc.</p> <p>&nbsp;</p> <a name="functionreference"></a> <h1>Function Reference</h1> <p>The following functions are intended for use in your controller functions.</p> <h2>$this->form_validation->set_rules();</h2> <p>Permits you to set validation rules, as described in the tutorial sections above:</p> <ul> <li><a href="#validationrules">Setting Validation Rules</a></li> <li><a href="#savingtoconfig">Saving Groups of Validation Rules to a Config File</a></li> </ul> <h2>$this->form_validation->run();</h2> <p>Runs the validation routines. Returns boolean TRUE on success and FALSE on failure. You can optionally pass the name of the validation group via the function, as described in: <a href="#savingtoconfig">Saving Groups of Validation Rules to a Config File</a>.</p> <h2>$this->form_validation->set_message();</h2> <p>Permits you to set custom error messages. See <a href="#settingerrors">Setting Error Messages</a> above.</p> <p>&nbsp;</p> <a name="helperreference"></a> <h1>Helper Reference</h1> <p>The following helper functions are available for use in the view files containing your forms. Note that these are procedural functions, so they <strong>do not</strong> require you to prepend them with $this->form_validation.</p> <h2>form_error()</h2> <p>Shows an individual error message associated with the field name supplied to the function. Example:</p> <code>&lt;?php echo form_error('username'); ?></code> <p>The error delimiters can be optionally specified. See the <a href="#errordelimiters">Changing the Error Delimiters</a> section above.</p> <h2>validation_errors()</h2> <p>Shows all error messages as a string: Example:</p> <code>&lt;?php echo validation_errors(); ?></code> <p>The error delimiters can be optionally specified. See the <a href="#errordelimiters">Changing the Error Delimiters</a> section above.</p> <h2>set_value()</h2> <p>Permits you to set the value of an input form or textarea. You must supply the field name via the first parameter of the function. The second (optional) parameter allows you to set a default value for the form. Example:</p> <code>&lt;input type="text" name="quantity" value="<dfn>&lt;?php echo set_value('quantity', '0'); ?></dfn>" size="50" /></code> <p>The above form will show "0" when loaded for the first time.</p> <h2>set_select()</h2> <p>If you use a <dfn>&lt;select></dfn> menu, this function permits you to display the menu item that was selected. The first parameter must contain the name of the select menu, the second parameter must contain the value of each item, and the third (optional) parameter lets you set an item as the default (use boolean TRUE/FALSE).</p> <p>Example:</p> <code> &lt;select name="myselect"><br /> &lt;option value="one" <dfn>&lt;?php echo set_select('myselect', 'one', TRUE); ?></dfn> >One&lt;/option><br /> &lt;option value="two" <dfn>&lt;?php echo set_select('myselect', 'two'); ?></dfn> >Two&lt;/option><br /> &lt;option value="three" <dfn>&lt;?php echo set_select('myselect', 'three'); ?></dfn> >Three&lt;/option><br /> &lt;/select> </code> <h2>set_checkbox()</h2> <p>Permits you to display a checkbox in the state it was submitted. The first parameter must contain the name of the checkbox, the second parameter must contain its value, and the third (optional) parameter lets you set an item as the default (use boolean TRUE/FALSE). Example:</p> <code>&lt;input type="checkbox" name="mycheck[]" value="1" <dfn>&lt;?php echo set_checkbox('mycheck[]', '1'); ?></dfn> /><br /> &lt;input type="checkbox" name="mycheck[]" value="2" <dfn>&lt;?php echo set_checkbox('mycheck[]', '2'); ?></dfn> /></code> <h2>set_radio()</h2> <p>Permits you to display radio buttons in the state they were submitted. This function is identical to the <strong>set_checkbox()</strong> function above.</p> <code>&lt;input type="radio" name="myradio" value="1" <dfn>&lt;?php echo set_radio('myradio', '1', TRUE); ?></dfn> /><br /> &lt;input type="radio" name="myradio" value="2" <dfn>&lt;?php echo set_radio('myradio', '2'); ?></dfn> /></code> </div> <!-- END CONTENT --> <div id="footer"> <p> Previous Topic:&nbsp;&nbsp;<a href="file_uploading.html">File Uploading Class</a> &nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp; <a href="#top">Top of Page</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp; <a href="../index.html">User Guide Home</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp; Next Topic:&nbsp;&nbsp;<a href="ftp.html">FTP Class</a> </p> <p><a href="http://codeigniter.com">CodeIgniter</a> &nbsp;&middot;&nbsp; Copyright &#169; 2006 - 2014 &nbsp;&middot;&nbsp; <a href="http://ellislab.com/">EllisLab, Inc.</a></p> </div> </body> </html>
SrimalPriyanga/epos-system
user_guide/libraries/form_validation.html
HTML
cc0-1.0
65,206
var baseRest = require('./_baseRest'), createWrap = require('./_createWrap'), getHolder = require('./_getHolder'), replaceHolders = require('./_replaceHolders'); /** Used to compose bitmasks for function metadata. */ var BIND_FLAG = 1, PARTIAL_FLAG = 32; /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and `partials` prepended to the arguments it receives. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" * property of bound functions. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * function greet(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // Bound with placeholders. * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = baseRest(function(func, thisArg, partials) { var bitmask = BIND_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bind)); bitmask |= PARTIAL_FLAG; } return createWrap(func, bitmask, thisArg, partials, holders); }); // Assign default placeholders. bind.placeholder = {}; module.exports = bind;
skinsshark/skinsshark.github.io
node_modules/babel-preset-es2015/node_modules/babel-plugin-transform-es2015-block-scoping/node_modules/lodash/bind.js
JavaScript
cc0-1.0
1,674
%% Machine Learning Online Class - Exercise 3 | Part 1: One-vs-all % Instructions % ------------ % % This file contains code that helps you get started on the % linear exercise. You will need to complete the following functions % in this exericse: % % lrCostFunction.m (logistic regression cost function) % oneVsAll.m % predictOneVsAll.m % predict.m % % For this exercise, you will not need to change any code in this file, % or any other files other than those mentioned above. % %% Initialization clear ; close all; clc %% Setup the parameters you will use for this part of the exercise input_layer_size = 400; % 20x20 Input Images of Digits num_labels = 10; % 10 labels, from 1 to 10 % (note that we have mapped "0" to label 10) %% =========== Part 1: Loading and Visualizing Data ============= % We start the exercise by first loading and visualizing the dataset. % You will be working with a dataset that contains handwritten digits. % % Load Training Data fprintf('Loading and Visualizing Data ...\n') load('ex3data1.mat'); % training data stored in arrays X, y m = size(X, 1); % Randomly select 100 data points to display rand_indices = randperm(m); sel = X(rand_indices(1:100), :); displayData(sel); fprintf('Program paused. Press enter to continue.\n'); pause; %% ============ Part 2: Vectorize Logistic Regression ============ % In this part of the exercise, you will reuse your logistic regression % code from the last exercise. You task here is to make sure that your % regularized logistic regression implementation is vectorized. After % that, you will implement one-vs-all classification for the handwritten % digit dataset. % fprintf('\nTraining One-vs-All Logistic Regression...\n') lambda = 0.1; [all_theta] = oneVsAll(X, y, num_labels, lambda); fprintf('Program paused. Press enter to continue.\n'); pause; %% ================ Part 3: Predict for One-Vs-All ================ % After ... pred = predictOneVsAll(all_theta, X); fprintf('\nTraining Set Accuracy: %f\n', mean(double(pred == y)) * 100);
mardurhack/machine_learning_coursera
ml-008/week4/mlclass-ex3-008/old_solutions/ex3.m
Matlab
cc0-1.0
2,108
!function(a,b){"object"==typeof exports&&"undefined"!=typeof module?b(require("../moment")):"function"==typeof define&&define.amd?define(["moment"],b):b(a.moment)}(this,function(a){"use strict"; //! moment.js locale configuration //! locale : belarusian (be) //! author : Dmitry Demidov : https://github.com/demidov91 //! author: Praleska: http://praleska.pro/ //! Author : Menelion Elensúle : https://github.com/Oire function b(a,b){var c=a.split("_");return b%10===1&&b%100!==11?c[0]:b%10>=2&&4>=b%10&&(10>b%100||b%100>=20)?c[1]:c[2]}function c(a,c,d){var e={mm:c?"хвіліна_хвіліны_хвілін":"хвіліну_хвіліны_хвілін",hh:c?"гадзіна_гадзіны_гадзін":"гадзіну_гадзіны_гадзін",dd:"дзень_дні_дзён",MM:"месяц_месяцы_месяцаў",yy:"год_гады_гадоў"};return"m"===d?c?"хвіліна":"хвіліну":"h"===d?c?"гадзіна":"гадзіну":a+" "+b(e[d],+a)}function d(a,b){var c={nominative:"студзень_люты_сакавік_красавік_травень_чэрвень_ліпень_жнівень_верасень_кастрычнік_лістапад_снежань".split("_"),accusative:"студзеня_лютага_сакавіка_красавіка_траўня_чэрвеня_ліпеня_жніўня_верасня_кастрычніка_лістапада_снежня".split("_")},d=/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/.test(b)?"accusative":"nominative";return c[d][a.month()]}function e(a,b){var c={nominative:"нядзеля_панядзелак_аўторак_серада_чацвер_пятніца_субота".split("_"),accusative:"нядзелю_панядзелак_аўторак_сераду_чацвер_пятніцу_суботу".split("_")},d=/\[ ?[Вв] ?(?:мінулую|наступную)? ?\] ?dddd/.test(b)?"accusative":"nominative";return c[d][a.day()]} //! moment.js locale configuration //! locale : breton (br) //! author : Jean-Baptiste Le Duigou : https://github.com/jbleduigou function f(a,b,c){var d={mm:"munutenn",MM:"miz",dd:"devezh"};return a+" "+i(d[c],a)}function g(a){switch(h(a)){case 1:case 3:case 4:case 5:case 9:return a+" bloaz";default:return a+" vloaz"}}function h(a){return a>9?h(a%10):a}function i(a,b){return 2===b?j(a):a}function j(a){var b={m:"v",b:"v",d:"z"};return void 0===b[a.charAt(0)]?a:b[a.charAt(0)]+a.substring(1)} //! moment.js locale configuration //! locale : bosnian (bs) //! author : Nedim Cholich : https://github.com/frontyard //! based on (hr) translation by Bojan Marković function k(a,b,c){var d=a+" ";switch(c){case"m":return b?"jedna minuta":"jedne minute";case"mm":return d+=1===a?"minuta":2===a||3===a||4===a?"minute":"minuta";case"h":return b?"jedan sat":"jednog sata";case"hh":return d+=1===a?"sat":2===a||3===a||4===a?"sata":"sati";case"dd":return d+=1===a?"dan":"dana";case"MM":return d+=1===a?"mjesec":2===a||3===a||4===a?"mjeseca":"mjeseci";case"yy":return d+=1===a?"godina":2===a||3===a||4===a?"godine":"godina"}}function l(a){return a>1&&5>a&&1!==~~(a/10)}function m(a,b,c,d){var e=a+" ";switch(c){case"s":return b||d?"pár sekund":"pár sekundami";case"m":return b?"minuta":d?"minutu":"minutou";case"mm":return b||d?e+(l(a)?"minuty":"minut"):e+"minutami";break;case"h":return b?"hodina":d?"hodinu":"hodinou";case"hh":return b||d?e+(l(a)?"hodiny":"hodin"):e+"hodinami";break;case"d":return b||d?"den":"dnem";case"dd":return b||d?e+(l(a)?"dny":"dní"):e+"dny";break;case"M":return b||d?"měsíc":"měsícem";case"MM":return b||d?e+(l(a)?"měsíce":"měsíců"):e+"měsíci";break;case"y":return b||d?"rok":"rokem";case"yy":return b||d?e+(l(a)?"roky":"let"):e+"lety"}} //! moment.js locale configuration //! locale : austrian german (de-at) //! author : lluchs : https://github.com/lluchs //! author: Menelion Elensúle: https://github.com/Oire //! author : Martin Groller : https://github.com/MadMG function n(a,b,c,d){var e={m:["eine Minute","einer Minute"],h:["eine Stunde","einer Stunde"],d:["ein Tag","einem Tag"],dd:[a+" Tage",a+" Tagen"],M:["ein Monat","einem Monat"],MM:[a+" Monate",a+" Monaten"],y:["ein Jahr","einem Jahr"],yy:[a+" Jahre",a+" Jahren"]};return b?e[c][0]:e[c][1]} //! moment.js locale configuration //! locale : german (de) //! author : lluchs : https://github.com/lluchs //! author: Menelion Elensúle: https://github.com/Oire function o(a,b,c,d){var e={m:["eine Minute","einer Minute"],h:["eine Stunde","einer Stunde"],d:["ein Tag","einem Tag"],dd:[a+" Tage",a+" Tagen"],M:["ein Monat","einem Monat"],MM:[a+" Monate",a+" Monaten"],y:["ein Jahr","einem Jahr"],yy:[a+" Jahre",a+" Jahren"]};return b?e[c][0]:e[c][1]} //! moment.js locale configuration //! locale : estonian (et) //! author : Henry Kehlmann : https://github.com/madhenry //! improvements : Illimar Tambek : https://github.com/ragulka function p(a,b,c,d){var e={s:["mõne sekundi","mõni sekund","paar sekundit"],m:["ühe minuti","üks minut"],mm:[a+" minuti",a+" minutit"],h:["ühe tunni","tund aega","üks tund"],hh:[a+" tunni",a+" tundi"],d:["ühe päeva","üks päev"],M:["kuu aja","kuu aega","üks kuu"],MM:[a+" kuu",a+" kuud"],y:["ühe aasta","aasta","üks aasta"],yy:[a+" aasta",a+" aastat"]};return b?e[c][2]?e[c][2]:e[c][1]:d?e[c][0]:e[c][1]}function q(a,b,c,d){var e="";switch(c){case"s":return d?"muutaman sekunnin":"muutama sekunti";case"m":return d?"minuutin":"minuutti";case"mm":e=d?"minuutin":"minuuttia";break;case"h":return d?"tunnin":"tunti";case"hh":e=d?"tunnin":"tuntia";break;case"d":return d?"päivän":"päivä";case"dd":e=d?"päivän":"päivää";break;case"M":return d?"kuukauden":"kuukausi";case"MM":e=d?"kuukauden":"kuukautta";break;case"y":return d?"vuoden":"vuosi";case"yy":e=d?"vuoden":"vuotta"}return e=r(a,d)+" "+e}function r(a,b){return 10>a?b?Aa[a]:za[a]:a} //! moment.js locale configuration //! locale : hrvatski (hr) //! author : Bojan Marković : https://github.com/bmarkovic function s(a,b,c){var d=a+" ";switch(c){case"m":return b?"jedna minuta":"jedne minute";case"mm":return d+=1===a?"minuta":2===a||3===a||4===a?"minute":"minuta";case"h":return b?"jedan sat":"jednog sata";case"hh":return d+=1===a?"sat":2===a||3===a||4===a?"sata":"sati";case"dd":return d+=1===a?"dan":"dana";case"MM":return d+=1===a?"mjesec":2===a||3===a||4===a?"mjeseca":"mjeseci";case"yy":return d+=1===a?"godina":2===a||3===a||4===a?"godine":"godina"}}function t(a,b,c,d){var e=a;switch(c){case"s":return d||b?"néhány másodperc":"néhány másodperce";case"m":return"egy"+(d||b?" perc":" perce");case"mm":return e+(d||b?" perc":" perce");case"h":return"egy"+(d||b?" óra":" órája");case"hh":return e+(d||b?" óra":" órája");case"d":return"egy"+(d||b?" nap":" napja");case"dd":return e+(d||b?" nap":" napja");case"M":return"egy"+(d||b?" hónap":" hónapja");case"MM":return e+(d||b?" hónap":" hónapja");case"y":return"egy"+(d||b?" év":" éve");case"yy":return e+(d||b?" év":" éve")}return""}function u(a){return(a?"":"[múlt] ")+"["+Fa[this.day()]+"] LT[-kor]"} //! moment.js locale configuration //! locale : Armenian (hy-am) //! author : Armendarabyan : https://github.com/armendarabyan function v(a,b){var c={nominative:"հունվար_փետրվար_մարտ_ապրիլ_մայիս_հունիս_հուլիս_օգոստոս_սեպտեմբեր_հոկտեմբեր_նոյեմբեր_դեկտեմբեր".split("_"),accusative:"հունվարի_փետրվարի_մարտի_ապրիլի_մայիսի_հունիսի_հուլիսի_օգոստոսի_սեպտեմբերի_հոկտեմբերի_նոյեմբերի_դեկտեմբերի".split("_")},d=/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/.test(b)?"accusative":"nominative";return c[d][a.month()]}function w(a,b){var c="հնվ_փտր_մրտ_ապր_մյս_հնս_հլս_օգս_սպտ_հկտ_նմբ_դկտ".split("_");return c[a.month()]}function x(a,b){var c="կիրակի_երկուշաբթի_երեքշաբթի_չորեքշաբթի_հինգշաբթի_ուրբաթ_շաբաթ".split("_");return c[a.day()]} //! moment.js locale configuration //! locale : icelandic (is) //! author : Hinrik Örn Sigurðsson : https://github.com/hinrik function y(a){return a%100===11?!0:a%10===1?!1:!0}function z(a,b,c,d){var e=a+" ";switch(c){case"s":return b||d?"nokkrar sekúndur":"nokkrum sekúndum";case"m":return b?"mínúta":"mínútu";case"mm":return y(a)?e+(b||d?"mínútur":"mínútum"):b?e+"mínúta":e+"mínútu";case"hh":return y(a)?e+(b||d?"klukkustundir":"klukkustundum"):e+"klukkustund";case"d":return b?"dagur":d?"dag":"degi";case"dd":return y(a)?b?e+"dagar":e+(d?"daga":"dögum"):b?e+"dagur":e+(d?"dag":"degi");case"M":return b?"mánuður":d?"mánuð":"mánuði";case"MM":return y(a)?b?e+"mánuðir":e+(d?"mánuði":"mánuðum"):b?e+"mánuður":e+(d?"mánuð":"mánuði");case"y":return b||d?"ár":"ári";case"yy":return y(a)?e+(b||d?"ár":"árum"):e+(b||d?"ár":"ári")}} //! moment.js locale configuration //! locale : Georgian (ka) //! author : Irakli Janiashvili : https://github.com/irakli-janiashvili function A(a,b){var c={nominative:"იანვარი_თებერვალი_მარტი_აპრილი_მაისი_ივნისი_ივლისი_აგვისტო_სექტემბერი_ოქტომბერი_ნოემბერი_დეკემბერი".split("_"),accusative:"იანვარს_თებერვალს_მარტს_აპრილის_მაისს_ივნისს_ივლისს_აგვისტს_სექტემბერს_ოქტომბერს_ნოემბერს_დეკემბერს".split("_")},d=/D[oD] *MMMM?/.test(b)?"accusative":"nominative";return c[d][a.month()]}function B(a,b){var c={nominative:"კვირა_ორშაბათი_სამშაბათი_ოთხშაბათი_ხუთშაბათი_პარასკევი_შაბათი".split("_"),accusative:"კვირას_ორშაბათს_სამშაბათს_ოთხშაბათს_ხუთშაბათს_პარასკევს_შაბათს".split("_")},d=/(წინა|შემდეგ)/.test(b)?"accusative":"nominative";return c[d][a.day()]} //! moment.js locale configuration //! locale : Luxembourgish (lb) //! author : mweimerskirch : https://github.com/mweimerskirch, David Raison : https://github.com/kwisatz function C(a,b,c,d){var e={m:["eng Minutt","enger Minutt"],h:["eng Stonn","enger Stonn"],d:["een Dag","engem Dag"],M:["ee Mount","engem Mount"],y:["ee Joer","engem Joer"]};return b?e[c][0]:e[c][1]}function D(a){var b=a.substr(0,a.indexOf(" "));return F(b)?"a "+a:"an "+a}function E(a){var b=a.substr(0,a.indexOf(" "));return F(b)?"viru "+a:"virun "+a}function F(a){if(a=parseInt(a,10),isNaN(a))return!1;if(0>a)return!0;if(10>a)return a>=4&&7>=a?!0:!1;if(100>a){var b=a%10,c=a/10;return F(0===b?c:b)}if(1e4>a){for(;a>=10;)a/=10;return F(a)}return a/=1e3,F(a)}function G(a,b,c,d){return b?"kelios sekundės":d?"kelių sekundžių":"kelias sekundes"}function H(a,b){var c={nominative:"sausis_vasaris_kovas_balandis_gegužė_birželis_liepa_rugpjūtis_rugsėjis_spalis_lapkritis_gruodis".split("_"),accusative:"sausio_vasario_kovo_balandžio_gegužės_birželio_liepos_rugpjūčio_rugsėjo_spalio_lapkričio_gruodžio".split("_")},d=/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/.test(b)?"accusative":"nominative";return c[d][a.month()]}function I(a,b,c,d){return b?K(c)[0]:d?K(c)[1]:K(c)[2]}function J(a){return a%10===0||a>10&&20>a}function K(a){return Ga[a].split("_")}function L(a,b,c,d){var e=a+" ";return 1===a?e+I(a,b,c[0],d):b?e+(J(a)?K(c)[1]:K(c)[0]):d?e+K(c)[1]:e+(J(a)?K(c)[1]:K(c)[2])}function M(a,b){var c=-1===b.indexOf("dddd HH:mm"),d=Ha[a.day()];return c?d:d.substring(0,d.length-2)+"į"}function N(a,b,c){return c?b%10===1&&11!==b?a[2]:a[3]:b%10===1&&11!==b?a[0]:a[1]}function O(a,b,c){return a+" "+N(Ia[c],a,b)}function P(a,b,c){return N(Ia[c],a,b)}function Q(a,b){return b?"dažas sekundes":"dažām sekundēm"}function R(a){return 5>a%10&&a%10>1&&~~(a/10)%10!==1}function S(a,b,c){var d=a+" ";switch(c){case"m":return b?"minuta":"minutę";case"mm":return d+(R(a)?"minuty":"minut");case"h":return b?"godzina":"godzinę";case"hh":return d+(R(a)?"godziny":"godzin");case"MM":return d+(R(a)?"miesiące":"miesięcy");case"yy":return d+(R(a)?"lata":"lat")}} //! moment.js locale configuration //! locale : romanian (ro) //! author : Vlad Gurdiga : https://github.com/gurdiga //! author : Valentin Agachi : https://github.com/avaly function T(a,b,c){var d={mm:"minute",hh:"ore",dd:"zile",MM:"luni",yy:"ani"},e=" ";return(a%100>=20||a>=100&&a%100===0)&&(e=" de "),a+e+d[c]} //! moment.js locale configuration //! locale : russian (ru) //! author : Viktorminator : https://github.com/Viktorminator //! Author : Menelion Elensúle : https://github.com/Oire function U(a,b){var c=a.split("_");return b%10===1&&b%100!==11?c[0]:b%10>=2&&4>=b%10&&(10>b%100||b%100>=20)?c[1]:c[2]}function V(a,b,c){var d={mm:b?"минута_минуты_минут":"минуту_минуты_минут",hh:"час_часа_часов",dd:"день_дня_дней",MM:"месяц_месяца_месяцев",yy:"год_года_лет"};return"m"===c?b?"минута":"минуту":a+" "+U(d[c],+a)}function W(a,b){var c={nominative:"январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь".split("_"),accusative:"января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря".split("_")},d=/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/.test(b)?"accusative":"nominative";return c[d][a.month()]}function X(a,b){var c={nominative:"янв_фев_март_апр_май_июнь_июль_авг_сен_окт_ноя_дек".split("_"),accusative:"янв_фев_мар_апр_мая_июня_июля_авг_сен_окт_ноя_дек".split("_")},d=/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/.test(b)?"accusative":"nominative";return c[d][a.month()]}function Y(a,b){var c={nominative:"воскресенье_понедельник_вторник_среда_четверг_пятница_суббота".split("_"),accusative:"воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу".split("_")},d=/\[ ?[Вв] ?(?:прошлую|следующую|эту)? ?\] ?dddd/.test(b)?"accusative":"nominative";return c[d][a.day()]}function Z(a){return a>1&&5>a}function $(a,b,c,d){var e=a+" ";switch(c){case"s":return b||d?"pár sekúnd":"pár sekundami";case"m":return b?"minúta":d?"minútu":"minútou";case"mm":return b||d?e+(Z(a)?"minúty":"minút"):e+"minútami";break;case"h":return b?"hodina":d?"hodinu":"hodinou";case"hh":return b||d?e+(Z(a)?"hodiny":"hodín"):e+"hodinami";break;case"d":return b||d?"deň":"dňom";case"dd":return b||d?e+(Z(a)?"dni":"dní"):e+"dňami";break;case"M":return b||d?"mesiac":"mesiacom";case"MM":return b||d?e+(Z(a)?"mesiace":"mesiacov"):e+"mesiacmi";break;case"y":return b||d?"rok":"rokom";case"yy":return b||d?e+(Z(a)?"roky":"rokov"):e+"rokmi"}} //! moment.js locale configuration //! locale : slovenian (sl) //! author : Robert Sedovšek : https://github.com/sedovsek function _(a,b,c,d){var e=a+" ";switch(c){case"s":return b||d?"nekaj sekund":"nekaj sekundami";case"m":return b?"ena minuta":"eno minuto";case"mm":return e+=1===a?b?"minuta":"minuto":2===a?b||d?"minuti":"minutama":5>a?b||d?"minute":"minutami":b||d?"minut":"minutami";case"h":return b?"ena ura":"eno uro";case"hh":return e+=1===a?b?"ura":"uro":2===a?b||d?"uri":"urama":5>a?b||d?"ure":"urami":b||d?"ur":"urami";case"d":return b||d?"en dan":"enim dnem";case"dd":return e+=1===a?b||d?"dan":"dnem":2===a?b||d?"dni":"dnevoma":b||d?"dni":"dnevi";case"M":return b||d?"en mesec":"enim mesecem";case"MM":return e+=1===a?b||d?"mesec":"mesecem":2===a?b||d?"meseca":"mesecema":5>a?b||d?"mesece":"meseci":b||d?"mesecev":"meseci";case"y":return b||d?"eno leto":"enim letom";case"yy":return e+=1===a?b||d?"leto":"letom":2===a?b||d?"leti":"letoma":5>a?b||d?"leta":"leti":b||d?"let":"leti"}}function aa(a,b,c,d){var e={s:["viensas secunds","'iensas secunds"],m:["'n míut","'iens míut"],mm:[a+" míuts"," "+a+" míuts"],h:["'n þora","'iensa þora"],hh:[a+" þoras"," "+a+" þoras"],d:["'n ziua","'iensa ziua"],dd:[a+" ziuas"," "+a+" ziuas"],M:["'n mes","'iens mes"],MM:[a+" mesen"," "+a+" mesen"],y:["'n ar","'iens ar"],yy:[a+" ars"," "+a+" ars"]};return d?e[c][0]:b?e[c][0]:e[c][1].trim()} //! moment.js locale configuration //! locale : ukrainian (uk) //! author : zemlanin : https://github.com/zemlanin //! Author : Menelion Elensúle : https://github.com/Oire function ba(a,b){var c=a.split("_");return b%10===1&&b%100!==11?c[0]:b%10>=2&&4>=b%10&&(10>b%100||b%100>=20)?c[1]:c[2]}function ca(a,b,c){var d={mm:"хвилина_хвилини_хвилин",hh:"година_години_годин",dd:"день_дні_днів",MM:"місяць_місяці_місяців",yy:"рік_роки_років"};return"m"===c?b?"хвилина":"хвилину":"h"===c?b?"година":"годину":a+" "+ba(d[c],+a)}function da(a,b){var c={nominative:"січень_лютий_березень_квітень_травень_червень_липень_серпень_вересень_жовтень_листопад_грудень".split("_"),accusative:"січня_лютого_березня_квітня_травня_червня_липня_серпня_вересня_жовтня_листопада_грудня".split("_")},d=/D[oD]? *MMMM?/.test(b)?"accusative":"nominative";return c[d][a.month()]}function ea(a,b){var c={nominative:"неділя_понеділок_вівторок_середа_четвер_п’ятниця_субота".split("_"),accusative:"неділю_понеділок_вівторок_середу_четвер_п’ятницю_суботу".split("_"),genitive:"неділі_понеділка_вівторка_середи_четверга_п’ятниці_суботи".split("_")},d=/(\[[ВвУу]\]) ?dddd/.test(b)?"accusative":/\[?(?:минулої|наступної)? ?\] ?dddd/.test(b)?"genitive":"nominative";return c[d][a.day()]}function fa(a){return function(){return a+"о"+(11===this.hours()?"б":"")+"] LT"}} //! moment.js locale configuration //! locale : afrikaans (af) //! author : Werner Mollentze : https://github.com/wernerm var ga=(a.defineLocale("af",{months:"Januarie_Februarie_Maart_April_Mei_Junie_Julie_Augustus_September_Oktober_November_Desember".split("_"),monthsShort:"Jan_Feb_Mar_Apr_Mei_Jun_Jul_Aug_Sep_Okt_Nov_Des".split("_"),weekdays:"Sondag_Maandag_Dinsdag_Woensdag_Donderdag_Vrydag_Saterdag".split("_"),weekdaysShort:"Son_Maa_Din_Woe_Don_Vry_Sat".split("_"),weekdaysMin:"So_Ma_Di_Wo_Do_Vr_Sa".split("_"),meridiemParse:/vm|nm/i,isPM:function(a){return/^nm$/i.test(a)},meridiem:function(a,b,c){return 12>a?c?"vm":"VM":c?"nm":"NM"},longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[Vandag om] LT",nextDay:"[Môre om] LT",nextWeek:"dddd [om] LT",lastDay:"[Gister om] LT",lastWeek:"[Laas] dddd [om] LT",sameElse:"L"},relativeTime:{future:"oor %s",past:"%s gelede",s:"'n paar sekondes",m:"'n minuut",mm:"%d minute",h:"'n uur",hh:"%d ure",d:"'n dag",dd:"%d dae",M:"'n maand",MM:"%d maande",y:"'n jaar",yy:"%d jaar"},ordinalParse:/\d{1,2}(ste|de)/,ordinal:function(a){return a+(1===a||8===a||a>=20?"ste":"de")},week:{dow:1,doy:4}}),a.defineLocale("ar-ma",{months:"يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"),monthsShort:"يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"),weekdays:"الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"),weekdaysShort:"احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت".split("_"),weekdaysMin:"ح_ن_ث_ر_خ_ج_س".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[اليوم على الساعة] LT",nextDay:"[غدا على الساعة] LT",nextWeek:"dddd [على الساعة] LT",lastDay:"[أمس على الساعة] LT",lastWeek:"dddd [على الساعة] LT",sameElse:"L"},relativeTime:{future:"في %s",past:"منذ %s",s:"ثوان",m:"دقيقة",mm:"%d دقائق",h:"ساعة",hh:"%d ساعات",d:"يوم",dd:"%d أيام",M:"شهر",MM:"%d أشهر",y:"سنة",yy:"%d سنوات"},week:{dow:6,doy:12}}),{1:"١",2:"٢",3:"٣",4:"٤",5:"٥",6:"٦",7:"٧",8:"٨",9:"٩",0:"٠"}),ha={"١":"1","٢":"2","٣":"3","٤":"4","٥":"5","٦":"6","٧":"7","٨":"8","٩":"9","٠":"0"},ia=(a.defineLocale("ar-sa",{months:"يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر".split("_"),monthsShort:"يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر".split("_"),weekdays:"الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"),weekdaysShort:"أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت".split("_"),weekdaysMin:"ح_ن_ث_ر_خ_ج_س".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},meridiemParse:/ص|م/,isPM:function(a){return"م"===a},meridiem:function(a,b,c){return 12>a?"ص":"م"},calendar:{sameDay:"[اليوم على الساعة] LT",nextDay:"[غدا على الساعة] LT",nextWeek:"dddd [على الساعة] LT",lastDay:"[أمس على الساعة] LT",lastWeek:"dddd [على الساعة] LT",sameElse:"L"},relativeTime:{future:"في %s",past:"منذ %s",s:"ثوان",m:"دقيقة",mm:"%d دقائق",h:"ساعة",hh:"%d ساعات",d:"يوم",dd:"%d أيام",M:"شهر",MM:"%d أشهر",y:"سنة",yy:"%d سنوات"},preparse:function(a){return a.replace(/[١٢٣٤٥٦٧٨٩٠]/g,function(a){return ha[a]}).replace(/،/g,",")},postformat:function(a){return a.replace(/\d/g,function(a){return ga[a]}).replace(/,/g,"،")},week:{dow:6,doy:12}}),a.defineLocale("ar-tn",{months:"جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر".split("_"),monthsShort:"جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر".split("_"),weekdays:"الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"),weekdaysShort:"أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت".split("_"),weekdaysMin:"ح_ن_ث_ر_خ_ج_س".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[اليوم على الساعة] LT",nextDay:"[غدا على الساعة] LT",nextWeek:"dddd [على الساعة] LT",lastDay:"[أمس على الساعة] LT",lastWeek:"dddd [على الساعة] LT",sameElse:"L"},relativeTime:{future:"في %s",past:"منذ %s",s:"ثوان",m:"دقيقة",mm:"%d دقائق",h:"ساعة",hh:"%d ساعات",d:"يوم",dd:"%d أيام",M:"شهر",MM:"%d أشهر",y:"سنة",yy:"%d سنوات"},week:{dow:1,doy:4}}),{1:"١",2:"٢",3:"٣",4:"٤",5:"٥",6:"٦",7:"٧",8:"٨",9:"٩",0:"٠"}),ja={"١":"1","٢":"2","٣":"3","٤":"4","٥":"5","٦":"6","٧":"7","٨":"8","٩":"9","٠":"0"},ka=function(a){return 0===a?0:1===a?1:2===a?2:a%100>=3&&10>=a%100?3:a%100>=11?4:5},la={s:["أقل من ثانية","ثانية واحدة",["ثانيتان","ثانيتين"],"%d ثوان","%d ثانية","%d ثانية"],m:["أقل من دقيقة","دقيقة واحدة",["دقيقتان","دقيقتين"],"%d دقائق","%d دقيقة","%d دقيقة"],h:["أقل من ساعة","ساعة واحدة",["ساعتان","ساعتين"],"%d ساعات","%d ساعة","%d ساعة"],d:["أقل من يوم","يوم واحد",["يومان","يومين"],"%d أيام","%d يومًا","%d يوم"],M:["أقل من شهر","شهر واحد",["شهران","شهرين"],"%d أشهر","%d شهرا","%d شهر"],y:["أقل من عام","عام واحد",["عامان","عامين"],"%d أعوام","%d عامًا","%d عام"]},ma=function(a){return function(b,c,d,e){var f=ka(b),g=la[a][ka(b)];return 2===f&&(g=g[c?0:1]),g.replace(/%d/i,b)}},na=["كانون الثاني يناير","شباط فبراير","آذار مارس","نيسان أبريل","أيار مايو","حزيران يونيو","تموز يوليو","آب أغسطس","أيلول سبتمبر","تشرين الأول أكتوبر","تشرين الثاني نوفمبر","كانون الأول ديسمبر"],oa=(a.defineLocale("ar",{months:na,monthsShort:na,weekdays:"الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"),weekdaysShort:"أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت".split("_"),weekdaysMin:"ح_ن_ث_ر_خ_ج_س".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"D/‏M/‏YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},meridiemParse:/ص|م/,isPM:function(a){return"م"===a},meridiem:function(a,b,c){return 12>a?"ص":"م"},calendar:{sameDay:"[اليوم عند الساعة] LT",nextDay:"[غدًا عند الساعة] LT",nextWeek:"dddd [عند الساعة] LT",lastDay:"[أمس عند الساعة] LT",lastWeek:"dddd [عند الساعة] LT",sameElse:"L"},relativeTime:{future:"بعد %s",past:"منذ %s",s:ma("s"),m:ma("m"),mm:ma("m"),h:ma("h"),hh:ma("h"),d:ma("d"),dd:ma("d"),M:ma("M"),MM:ma("M"),y:ma("y"),yy:ma("y")},preparse:function(a){return a.replace(/\u200f/g,"").replace(/[١٢٣٤٥٦٧٨٩٠]/g,function(a){return ja[a]}).replace(/،/g,",")},postformat:function(a){return a.replace(/\d/g,function(a){return ia[a]}).replace(/,/g,"،")},week:{dow:6,doy:12}}),{1:"-inci",5:"-inci",8:"-inci",70:"-inci",80:"-inci",2:"-nci",7:"-nci",20:"-nci",50:"-nci",3:"-üncü",4:"-üncü",100:"-üncü",6:"-ncı",9:"-uncu",10:"-uncu",30:"-uncu",60:"-ıncı",90:"-ıncı"}),pa=(a.defineLocale("az",{months:"yanvar_fevral_mart_aprel_may_iyun_iyul_avqust_sentyabr_oktyabr_noyabr_dekabr".split("_"),monthsShort:"yan_fev_mar_apr_may_iyn_iyl_avq_sen_okt_noy_dek".split("_"),weekdays:"Bazar_Bazar ertəsi_Çərşənbə axşamı_Çərşənbə_Cümə axşamı_Cümə_Şənbə".split("_"),weekdaysShort:"Baz_BzE_ÇAx_Çər_CAx_Cüm_Şən".split("_"),weekdaysMin:"Bz_BE_ÇA_Çə_CA_Cü_Şə".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[bugün saat] LT",nextDay:"[sabah saat] LT",nextWeek:"[gələn həftə] dddd [saat] LT",lastDay:"[dünən] LT",lastWeek:"[keçən həftə] dddd [saat] LT",sameElse:"L"},relativeTime:{future:"%s sonra",past:"%s əvvəl",s:"birneçə saniyyə",m:"bir dəqiqə",mm:"%d dəqiqə",h:"bir saat",hh:"%d saat",d:"bir gün",dd:"%d gün",M:"bir ay",MM:"%d ay",y:"bir il",yy:"%d il"},meridiemParse:/gecə|səhər|gündüz|axşam/,isPM:function(a){return/^(gündüz|axşam)$/.test(a)},meridiem:function(a,b,c){return 4>a?"gecə":12>a?"səhər":17>a?"gündüz":"axşam"},ordinalParse:/\d{1,2}-(ıncı|inci|nci|üncü|ncı|uncu)/,ordinal:function(a){if(0===a)return a+"-ıncı";var b=a%10,c=a%100-b,d=a>=100?100:null;return a+(oa[b]||oa[c]||oa[d])},week:{dow:1,doy:7}}),a.defineLocale("be",{months:d,monthsShort:"студ_лют_сак_крас_трав_чэрв_ліп_жнів_вер_каст_ліст_снеж".split("_"),weekdays:e,weekdaysShort:"нд_пн_ат_ср_чц_пт_сб".split("_"),weekdaysMin:"нд_пн_ат_ср_чц_пт_сб".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY г.",LLL:"D MMMM YYYY г., HH:mm",LLLL:"dddd, D MMMM YYYY г., HH:mm"},calendar:{sameDay:"[Сёння ў] LT",nextDay:"[Заўтра ў] LT",lastDay:"[Учора ў] LT",nextWeek:function(){return"[У] dddd [ў] LT"},lastWeek:function(){switch(this.day()){case 0:case 3:case 5:case 6:return"[У мінулую] dddd [ў] LT";case 1:case 2:case 4:return"[У мінулы] dddd [ў] LT"}},sameElse:"L"},relativeTime:{future:"праз %s",past:"%s таму",s:"некалькі секунд",m:c,mm:c,h:c,hh:c,d:"дзень",dd:c,M:"месяц",MM:c,y:"год",yy:c},meridiemParse:/ночы|раніцы|дня|вечара/,isPM:function(a){return/^(дня|вечара)$/.test(a)},meridiem:function(a,b,c){return 4>a?"ночы":12>a?"раніцы":17>a?"дня":"вечара"},ordinalParse:/\d{1,2}-(і|ы|га)/,ordinal:function(a,b){switch(b){case"M":case"d":case"DDD":case"w":case"W":return a%10!==2&&a%10!==3||a%100===12||a%100===13?a+"-ы":a+"-і";case"D":return a+"-га";default:return a}},week:{dow:1,doy:7}}),a.defineLocale("bg",{months:"януари_февруари_март_април_май_юни_юли_август_септември_октомври_ноември_декември".split("_"),monthsShort:"янр_фев_мар_апр_май_юни_юли_авг_сеп_окт_ное_дек".split("_"),weekdays:"неделя_понеделник_вторник_сряда_четвъртък_петък_събота".split("_"),weekdaysShort:"нед_пон_вто_сря_чет_пет_съб".split("_"),weekdaysMin:"нд_пн_вт_ср_чт_пт_сб".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"D.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY H:mm",LLLL:"dddd, D MMMM YYYY H:mm"},calendar:{sameDay:"[Днес в] LT",nextDay:"[Утре в] LT",nextWeek:"dddd [в] LT",lastDay:"[Вчера в] LT",lastWeek:function(){switch(this.day()){case 0:case 3:case 6:return"[В изминалата] dddd [в] LT";case 1:case 2:case 4:case 5:return"[В изминалия] dddd [в] LT"}},sameElse:"L"},relativeTime:{future:"след %s",past:"преди %s",s:"няколко секунди",m:"минута",mm:"%d минути",h:"час",hh:"%d часа",d:"ден",dd:"%d дни",M:"месец",MM:"%d месеца",y:"година",yy:"%d години"},ordinalParse:/\d{1,2}-(ев|ен|ти|ви|ри|ми)/,ordinal:function(a){var b=a%10,c=a%100;return 0===a?a+"-ев":0===c?a+"-ен":c>10&&20>c?a+"-ти":1===b?a+"-ви":2===b?a+"-ри":7===b||8===b?a+"-ми":a+"-ти"},week:{dow:1,doy:7}}),{1:"১",2:"২",3:"৩",4:"৪",5:"৫",6:"৬",7:"৭",8:"৮",9:"৯",0:"০"}),qa={"১":"1","২":"2","৩":"3","৪":"4","৫":"5","৬":"6","৭":"7","৮":"8","৯":"9","০":"0"},ra=(a.defineLocale("bn",{months:"জানুয়ারী_ফেবুয়ারী_মার্চ_এপ্রিল_মে_জুন_জুলাই_অগাস্ট_সেপ্টেম্বর_অক্টোবর_নভেম্বর_ডিসেম্বর".split("_"),monthsShort:"জানু_ফেব_মার্চ_এপর_মে_জুন_জুল_অগ_সেপ্ট_অক্টো_নভ_ডিসেম্".split("_"),weekdays:"রবিবার_সোমবার_মঙ্গলবার_বুধবার_বৃহস্পত্তিবার_শুক্রুবার_শনিবার".split("_"),weekdaysShort:"রবি_সোম_মঙ্গল_বুধ_বৃহস্পত্তি_শুক্রু_শনি".split("_"),weekdaysMin:"রব_সম_মঙ্গ_বু_ব্রিহ_শু_শনি".split("_"),longDateFormat:{LT:"A h:mm সময়",LTS:"A h:mm:ss সময়",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, A h:mm সময়",LLLL:"dddd, D MMMM YYYY, A h:mm সময়"},calendar:{sameDay:"[আজ] LT",nextDay:"[আগামীকাল] LT",nextWeek:"dddd, LT",lastDay:"[গতকাল] LT",lastWeek:"[গত] dddd, LT",sameElse:"L"},relativeTime:{future:"%s পরে",past:"%s আগে",s:"কএক সেকেন্ড",m:"এক মিনিট",mm:"%d মিনিট",h:"এক ঘন্টা",hh:"%d ঘন্টা",d:"এক দিন",dd:"%d দিন",M:"এক মাস",MM:"%d মাস",y:"এক বছর",yy:"%d বছর"},preparse:function(a){return a.replace(/[১২৩৪৫৬৭৮৯০]/g,function(a){return qa[a]})},postformat:function(a){return a.replace(/\d/g,function(a){return pa[a]})},meridiemParse:/রাত|সকাল|দুপুর|বিকেল|রাত/,isPM:function(a){return/^(দুপুর|বিকেল|রাত)$/.test(a)},meridiem:function(a,b,c){return 4>a?"রাত":10>a?"সকাল":17>a?"দুপুর":20>a?"বিকেল":"রাত"},week:{dow:0,doy:6}}),{1:"༡",2:"༢",3:"༣",4:"༤",5:"༥",6:"༦",7:"༧",8:"༨",9:"༩",0:"༠"}),sa={"༡":"1","༢":"2","༣":"3","༤":"4","༥":"5","༦":"6","༧":"7","༨":"8","༩":"9","༠":"0"},ta=(a.defineLocale("bo",{months:"ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ".split("_"),monthsShort:"ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ".split("_"),weekdays:"གཟའ་ཉི་མ་_གཟའ་ཟླ་བ་_གཟའ་མིག་དམར་_གཟའ་ལྷག་པ་_གཟའ་ཕུར་བུ_གཟའ་པ་སངས་_གཟའ་སྤེན་པ་".split("_"),weekdaysShort:"ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་".split("_"),weekdaysMin:"ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་".split("_"),longDateFormat:{LT:"A h:mm",LTS:"A h:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, A h:mm",LLLL:"dddd, D MMMM YYYY, A h:mm"},calendar:{sameDay:"[དི་རིང] LT",nextDay:"[སང་ཉིན] LT",nextWeek:"[བདུན་ཕྲག་རྗེས་མ], LT",lastDay:"[ཁ་སང] LT",lastWeek:"[བདུན་ཕྲག་མཐའ་མ] dddd, LT",sameElse:"L"},relativeTime:{future:"%s ལ་",past:"%s སྔན་ལ",s:"ལམ་སང",m:"སྐར་མ་གཅིག",mm:"%d སྐར་མ",h:"ཆུ་ཚོད་གཅིག",hh:"%d ཆུ་ཚོད",d:"ཉིན་གཅིག",dd:"%d ཉིན་",M:"ཟླ་བ་གཅིག",MM:"%d ཟླ་བ",y:"ལོ་གཅིག",yy:"%d ལོ"},preparse:function(a){return a.replace(/[༡༢༣༤༥༦༧༨༩༠]/g,function(a){return sa[a]})},postformat:function(a){return a.replace(/\d/g,function(a){return ra[a]})},meridiemParse:/མཚན་མོ|ཞོགས་ཀས|ཉིན་གུང|དགོང་དག|མཚན་མོ/,isPM:function(a){return/^(ཉིན་གུང|དགོང་དག|མཚན་མོ)$/.test(a)},meridiem:function(a,b,c){return 4>a?"མཚན་མོ":10>a?"ཞོགས་ཀས":17>a?"ཉིན་གུང":20>a?"དགོང་དག":"མཚན་མོ"},week:{dow:0,doy:6}}),a.defineLocale("br",{months:"Genver_C'hwevrer_Meurzh_Ebrel_Mae_Mezheven_Gouere_Eost_Gwengolo_Here_Du_Kerzu".split("_"),monthsShort:"Gen_C'hwe_Meu_Ebr_Mae_Eve_Gou_Eos_Gwe_Her_Du_Ker".split("_"),weekdays:"Sul_Lun_Meurzh_Merc'her_Yaou_Gwener_Sadorn".split("_"),weekdaysShort:"Sul_Lun_Meu_Mer_Yao_Gwe_Sad".split("_"),weekdaysMin:"Su_Lu_Me_Mer_Ya_Gw_Sa".split("_"),longDateFormat:{LT:"h[e]mm A",LTS:"h[e]mm:ss A",L:"DD/MM/YYYY",LL:"D [a viz] MMMM YYYY",LLL:"D [a viz] MMMM YYYY h[e]mm A",LLLL:"dddd, D [a viz] MMMM YYYY h[e]mm A"},calendar:{sameDay:"[Hiziv da] LT",nextDay:"[Warc'hoazh da] LT",nextWeek:"dddd [da] LT",lastDay:"[Dec'h da] LT",lastWeek:"dddd [paset da] LT",sameElse:"L"},relativeTime:{future:"a-benn %s",past:"%s 'zo",s:"un nebeud segondennoù",m:"ur vunutenn",mm:f,h:"un eur",hh:"%d eur",d:"un devezh",dd:f,M:"ur miz",MM:f,y:"ur bloaz",yy:g},ordinalParse:/\d{1,2}(añ|vet)/,ordinal:function(a){var b=1===a?"añ":"vet";return a+b},week:{dow:1,doy:4}}),a.defineLocale("bs",{months:"januar_februar_mart_april_maj_juni_juli_august_septembar_oktobar_novembar_decembar".split("_"),monthsShort:"jan._feb._mar._apr._maj._jun._jul._aug._sep._okt._nov._dec.".split("_"),weekdays:"nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota".split("_"),weekdaysShort:"ned._pon._uto._sri._čet._pet._sub.".split("_"),weekdaysMin:"ne_po_ut_sr_če_pe_su".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD. MM. YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd, D. MMMM YYYY H:mm"},calendar:{sameDay:"[danas u] LT",nextDay:"[sutra u] LT",nextWeek:function(){switch(this.day()){case 0:return"[u] [nedjelju] [u] LT";case 3:return"[u] [srijedu] [u] LT";case 6:return"[u] [subotu] [u] LT";case 1:case 2:case 4:case 5:return"[u] dddd [u] LT"}},lastDay:"[jučer u] LT",lastWeek:function(){switch(this.day()){case 0:case 3:return"[prošlu] dddd [u] LT";case 6:return"[prošle] [subote] [u] LT";case 1:case 2:case 4:case 5:return"[prošli] dddd [u] LT"}},sameElse:"L"},relativeTime:{future:"za %s",past:"prije %s",s:"par sekundi",m:k,mm:k,h:k,hh:k,d:"dan",dd:k,M:"mjesec",MM:k,y:"godinu",yy:k},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:7}}),a.defineLocale("ca",{months:"gener_febrer_març_abril_maig_juny_juliol_agost_setembre_octubre_novembre_desembre".split("_"),monthsShort:"gen._febr._mar._abr._mai._jun._jul._ag._set._oct._nov._des.".split("_"),weekdays:"diumenge_dilluns_dimarts_dimecres_dijous_divendres_dissabte".split("_"),weekdaysShort:"dg._dl._dt._dc._dj._dv._ds.".split("_"),weekdaysMin:"Dg_Dl_Dt_Dc_Dj_Dv_Ds".split("_"),longDateFormat:{LT:"H:mm",LTS:"LT:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY H:mm",LLLL:"dddd D MMMM YYYY H:mm"},calendar:{sameDay:function(){return"[avui a "+(1!==this.hours()?"les":"la")+"] LT"},nextDay:function(){return"[demà a "+(1!==this.hours()?"les":"la")+"] LT"},nextWeek:function(){return"dddd [a "+(1!==this.hours()?"les":"la")+"] LT"},lastDay:function(){return"[ahir a "+(1!==this.hours()?"les":"la")+"] LT"},lastWeek:function(){return"[el] dddd [passat a "+(1!==this.hours()?"les":"la")+"] LT"},sameElse:"L"},relativeTime:{future:"en %s",past:"fa %s",s:"uns segons",m:"un minut",mm:"%d minuts",h:"una hora",hh:"%d hores",d:"un dia",dd:"%d dies",M:"un mes",MM:"%d mesos",y:"un any",yy:"%d anys"},ordinalParse:/\d{1,2}(r|n|t|è|a)/,ordinal:function(a,b){var c=1===a?"r":2===a?"n":3===a?"r":4===a?"t":"è";return("w"===b||"W"===b)&&(c="a"),a+c},week:{dow:1,doy:4}}),"leden_únor_březen_duben_květen_červen_červenec_srpen_září_říjen_listopad_prosinec".split("_")),ua="led_úno_bře_dub_kvě_čvn_čvc_srp_zář_říj_lis_pro".split("_"),va=(a.defineLocale("cs",{months:ta,monthsShort:ua,monthsParse:function(a,b){var c,d=[];for(c=0;12>c;c++)d[c]=new RegExp("^"+a[c]+"$|^"+b[c]+"$","i");return d}(ta,ua),weekdays:"neděle_pondělí_úterý_středa_čtvrtek_pátek_sobota".split("_"),weekdaysShort:"ne_po_út_st_čt_pá_so".split("_"),weekdaysMin:"ne_po_út_st_čt_pá_so".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd D. MMMM YYYY H:mm"},calendar:{sameDay:"[dnes v] LT",nextDay:"[zítra v] LT",nextWeek:function(){switch(this.day()){case 0:return"[v neděli v] LT";case 1:case 2:return"[v] dddd [v] LT";case 3:return"[ve středu v] LT";case 4:return"[ve čtvrtek v] LT";case 5:return"[v pátek v] LT";case 6:return"[v sobotu v] LT"}},lastDay:"[včera v] LT",lastWeek:function(){switch(this.day()){case 0:return"[minulou neděli v] LT";case 1:case 2:return"[minulé] dddd [v] LT";case 3:return"[minulou středu v] LT";case 4:case 5:return"[minulý] dddd [v] LT";case 6:return"[minulou sobotu v] LT"}},sameElse:"L"},relativeTime:{future:"za %s",past:"před %s",s:m,m:m,mm:m,h:m,hh:m,d:m,dd:m,M:m,MM:m,y:m,yy:m},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),a.defineLocale("cv",{months:"кӑрлач_нарӑс_пуш_ака_май_ҫӗртме_утӑ_ҫурла_авӑн_юпа_чӳк_раштав".split("_"),monthsShort:"кӑр_нар_пуш_ака_май_ҫӗр_утӑ_ҫур_авн_юпа_чӳк_раш".split("_"),weekdays:"вырсарникун_тунтикун_ытларикун_юнкун_кӗҫнерникун_эрнекун_шӑматкун".split("_"),weekdaysShort:"выр_тун_ытл_юн_кӗҫ_эрн_шӑм".split("_"),weekdaysMin:"вр_тн_ыт_юн_кҫ_эр_шм".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD-MM-YYYY",LL:"YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ]",LLL:"YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm",LLLL:"dddd, YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm"},calendar:{sameDay:"[Паян] LT [сехетре]",nextDay:"[Ыран] LT [сехетре]",lastDay:"[Ӗнер] LT [сехетре]",nextWeek:"[Ҫитес] dddd LT [сехетре]",lastWeek:"[Иртнӗ] dddd LT [сехетре]",sameElse:"L"},relativeTime:{future:function(a){var b=/сехет$/i.exec(a)?"рен":/ҫул$/i.exec(a)?"тан":"ран";return a+b},past:"%s каялла",s:"пӗр-ик ҫеккунт",m:"пӗр минут",mm:"%d минут",h:"пӗр сехет",hh:"%d сехет",d:"пӗр кун",dd:"%d кун",M:"пӗр уйӑх",MM:"%d уйӑх",y:"пӗр ҫул",yy:"%d ҫул"},ordinalParse:/\d{1,2}-мӗш/,ordinal:"%d-мӗш",week:{dow:1,doy:7}}),a.defineLocale("cy",{months:"Ionawr_Chwefror_Mawrth_Ebrill_Mai_Mehefin_Gorffennaf_Awst_Medi_Hydref_Tachwedd_Rhagfyr".split("_"),monthsShort:"Ion_Chwe_Maw_Ebr_Mai_Meh_Gor_Aws_Med_Hyd_Tach_Rhag".split("_"),weekdays:"Dydd Sul_Dydd Llun_Dydd Mawrth_Dydd Mercher_Dydd Iau_Dydd Gwener_Dydd Sadwrn".split("_"),weekdaysShort:"Sul_Llun_Maw_Mer_Iau_Gwe_Sad".split("_"),weekdaysMin:"Su_Ll_Ma_Me_Ia_Gw_Sa".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[Heddiw am] LT",nextDay:"[Yfory am] LT",nextWeek:"dddd [am] LT",lastDay:"[Ddoe am] LT",lastWeek:"dddd [diwethaf am] LT",sameElse:"L"},relativeTime:{future:"mewn %s",past:"%s yn ôl",s:"ychydig eiliadau",m:"munud",mm:"%d munud",h:"awr",hh:"%d awr",d:"diwrnod",dd:"%d diwrnod",M:"mis",MM:"%d mis",y:"blwyddyn",yy:"%d flynedd"},ordinalParse:/\d{1,2}(fed|ain|af|il|ydd|ed|eg)/,ordinal:function(a){var b=a,c="",d=["","af","il","ydd","ydd","ed","ed","ed","fed","fed","fed","eg","fed","eg","eg","fed","eg","eg","fed","eg","fed"];return b>20?c=40===b||50===b||60===b||80===b||100===b?"fed":"ain":b>0&&(c=d[b]),a+c},week:{dow:1,doy:4}}),a.defineLocale("da",{months:"januar_februar_marts_april_maj_juni_juli_august_september_oktober_november_december".split("_"),monthsShort:"jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec".split("_"),weekdays:"søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag".split("_"),weekdaysShort:"søn_man_tir_ons_tor_fre_lør".split("_"),weekdaysMin:"sø_ma_ti_on_to_fr_lø".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY HH:mm",LLLL:"dddd [d.] D. MMMM YYYY HH:mm"},calendar:{sameDay:"[I dag kl.] LT",nextDay:"[I morgen kl.] LT",nextWeek:"dddd [kl.] LT",lastDay:"[I går kl.] LT",lastWeek:"[sidste] dddd [kl] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"%s siden",s:"få sekunder",m:"et minut",mm:"%d minutter",h:"en time",hh:"%d timer",d:"en dag",dd:"%d dage",M:"en måned",MM:"%d måneder",y:"et år",yy:"%d år"},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),a.defineLocale("de-at",{months:"Jänner_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember".split("_"),monthsShort:"Jän._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.".split("_"),weekdays:"Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag".split("_"),weekdaysShort:"So._Mo._Di._Mi._Do._Fr._Sa.".split("_"),weekdaysMin:"So_Mo_Di_Mi_Do_Fr_Sa".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY HH:mm",LLLL:"dddd, D. MMMM YYYY HH:mm"},calendar:{sameDay:"[Heute um] LT [Uhr]",sameElse:"L",nextDay:"[Morgen um] LT [Uhr]",nextWeek:"dddd [um] LT [Uhr]",lastDay:"[Gestern um] LT [Uhr]",lastWeek:"[letzten] dddd [um] LT [Uhr]"},relativeTime:{future:"in %s",past:"vor %s",s:"ein paar Sekunden",m:n,mm:"%d Minuten",h:n,hh:"%d Stunden",d:n,dd:n,M:n,MM:n,y:n,yy:n},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),a.defineLocale("de",{months:"Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember".split("_"),monthsShort:"Jan._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.".split("_"),weekdays:"Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag".split("_"),weekdaysShort:"So._Mo._Di._Mi._Do._Fr._Sa.".split("_"),weekdaysMin:"So_Mo_Di_Mi_Do_Fr_Sa".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY HH:mm",LLLL:"dddd, D. MMMM YYYY HH:mm"},calendar:{sameDay:"[Heute um] LT [Uhr]",sameElse:"L",nextDay:"[Morgen um] LT [Uhr]",nextWeek:"dddd [um] LT [Uhr]",lastDay:"[Gestern um] LT [Uhr]",lastWeek:"[letzten] dddd [um] LT [Uhr]"},relativeTime:{future:"in %s",past:"vor %s",s:"ein paar Sekunden",m:o,mm:"%d Minuten",h:o,hh:"%d Stunden",d:o,dd:o,M:o,MM:o,y:o,yy:o},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),a.defineLocale("el",{monthsNominativeEl:"Ιανουάριος_Φεβρουάριος_Μάρτιος_Απρίλιος_Μάιος_Ιούνιος_Ιούλιος_Αύγουστος_Σεπτέμβριος_Οκτώβριος_Νοέμβριος_Δεκέμβριος".split("_"),monthsGenitiveEl:"Ιανουαρίου_Φεβρουαρίου_Μαρτίου_Απριλίου_Μαΐου_Ιουνίου_Ιουλίου_Αυγούστου_Σεπτεμβρίου_Οκτωβρίου_Νοεμβρίου_Δεκεμβρίου".split("_"),months:function(a,b){return/D/.test(b.substring(0,b.indexOf("MMMM")))?this._monthsGenitiveEl[a.month()]:this._monthsNominativeEl[a.month()]},monthsShort:"Ιαν_Φεβ_Μαρ_Απρ_Μαϊ_Ιουν_Ιουλ_Αυγ_Σεπ_Οκτ_Νοε_Δεκ".split("_"),weekdays:"Κυριακή_Δευτέρα_Τρίτη_Τετάρτη_Πέμπτη_Παρασκευή_Σάββατο".split("_"),weekdaysShort:"Κυρ_Δευ_Τρι_Τετ_Πεμ_Παρ_Σαβ".split("_"),weekdaysMin:"Κυ_Δε_Τρ_Τε_Πε_Πα_Σα".split("_"),meridiem:function(a,b,c){return a>11?c?"μμ":"ΜΜ":c?"πμ":"ΠΜ"},isPM:function(a){return"μ"===(a+"").toLowerCase()[0]},meridiemParse:/[ΠΜ]\.?Μ?\.?/i,longDateFormat:{LT:"h:mm A",LTS:"h:mm:ss A",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY h:mm A",LLLL:"dddd, D MMMM YYYY h:mm A"},calendarEl:{sameDay:"[Σήμερα {}] LT",nextDay:"[Αύριο {}] LT",nextWeek:"dddd [{}] LT",lastDay:"[Χθες {}] LT",lastWeek:function(){switch(this.day()){case 6:return"[το προηγούμενο] dddd [{}] LT";default:return"[την προηγούμενη] dddd [{}] LT"}},sameElse:"L"},calendar:function(a,b){var c=this._calendarEl[a],d=b&&b.hours();return"function"==typeof c&&(c=c.apply(b)),c.replace("{}",d%12===1?"στη":"στις")},relativeTime:{future:"σε %s",past:"%s πριν",s:"λίγα δευτερόλεπτα",m:"ένα λεπτό",mm:"%d λεπτά",h:"μία ώρα",hh:"%d ώρες",d:"μία μέρα",dd:"%d μέρες",M:"ένας μήνας",MM:"%d μήνες",y:"ένας χρόνος",yy:"%d χρόνια"},ordinalParse:/\d{1,2}η/,ordinal:"%dη",week:{dow:1,doy:4}}),a.defineLocale("en-au",{months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),monthsShort:"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),weekdaysShort:"Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),weekdaysMin:"Su_Mo_Tu_We_Th_Fr_Sa".split("_"),longDateFormat:{LT:"h:mm A",LTS:"h:mm:ss A",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY h:mm A",LLLL:"dddd, D MMMM YYYY h:mm A"},calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},ordinalParse:/\d{1,2}(st|nd|rd|th)/,ordinal:function(a){var b=a%10,c=1===~~(a%100/10)?"th":1===b?"st":2===b?"nd":3===b?"rd":"th";return a+c},week:{dow:1,doy:4}}),a.defineLocale("en-ca",{months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),monthsShort:"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),weekdaysShort:"Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),weekdaysMin:"Su_Mo_Tu_We_Th_Fr_Sa".split("_"),longDateFormat:{LT:"h:mm A",LTS:"h:mm:ss A",L:"YYYY-MM-DD",LL:"D MMMM, YYYY",LLL:"D MMMM, YYYY h:mm A",LLLL:"dddd, D MMMM, YYYY h:mm A"},calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},ordinalParse:/\d{1,2}(st|nd|rd|th)/,ordinal:function(a){var b=a%10,c=1===~~(a%100/10)?"th":1===b?"st":2===b?"nd":3===b?"rd":"th";return a+c}}),a.defineLocale("en-gb",{months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),monthsShort:"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),weekdaysShort:"Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),weekdaysMin:"Su_Mo_Tu_We_Th_Fr_Sa".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},ordinalParse:/\d{1,2}(st|nd|rd|th)/,ordinal:function(a){var b=a%10,c=1===~~(a%100/10)?"th":1===b?"st":2===b?"nd":3===b?"rd":"th";return a+c},week:{dow:1,doy:4}}),a.defineLocale("eo",{months:"januaro_februaro_marto_aprilo_majo_junio_julio_aŭgusto_septembro_oktobro_novembro_decembro".split("_"),monthsShort:"jan_feb_mar_apr_maj_jun_jul_aŭg_sep_okt_nov_dec".split("_"),weekdays:"Dimanĉo_Lundo_Mardo_Merkredo_Ĵaŭdo_Vendredo_Sabato".split("_"),weekdaysShort:"Dim_Lun_Mard_Merk_Ĵaŭ_Ven_Sab".split("_"),weekdaysMin:"Di_Lu_Ma_Me_Ĵa_Ve_Sa".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY-MM-DD",LL:"D[-an de] MMMM, YYYY",LLL:"D[-an de] MMMM, YYYY HH:mm",LLLL:"dddd, [la] D[-an de] MMMM, YYYY HH:mm"},meridiemParse:/[ap]\.t\.m/i,isPM:function(a){return"p"===a.charAt(0).toLowerCase()},meridiem:function(a,b,c){return a>11?c?"p.t.m.":"P.T.M.":c?"a.t.m.":"A.T.M."},calendar:{sameDay:"[Hodiaŭ je] LT",nextDay:"[Morgaŭ je] LT",nextWeek:"dddd [je] LT",lastDay:"[Hieraŭ je] LT",lastWeek:"[pasinta] dddd [je] LT",sameElse:"L"},relativeTime:{future:"je %s",past:"antaŭ %s",s:"sekundoj",m:"minuto",mm:"%d minutoj",h:"horo",hh:"%d horoj",d:"tago",dd:"%d tagoj",M:"monato",MM:"%d monatoj",y:"jaro",yy:"%d jaroj"},ordinalParse:/\d{1,2}a/,ordinal:"%da",week:{dow:1,doy:7}}),"Ene._Feb._Mar._Abr._May._Jun._Jul._Ago._Sep._Oct._Nov._Dic.".split("_")),wa="Ene_Feb_Mar_Abr_May_Jun_Jul_Ago_Sep_Oct_Nov_Dic".split("_"),xa=(a.defineLocale("es",{months:"Enero_Febrero_Marzo_Abril_Mayo_Junio_Julio_Agosto_Septiembre_Octubre_Noviembre_Diciembre".split("_"),monthsShort:function(a,b){return/-MMM-/.test(b)?wa[a.month()]:va[a.month()]},weekdays:"Domingo_Lunes_Martes_Miércoles_Jueves_Viernes_Sábado".split("_"),weekdaysShort:"Dom._Lun._Mar._Mié._Jue._Vie._Sáb.".split("_"),weekdaysMin:"Do_Lu_Ma_Mi_Ju_Vi_Sá".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD/MM/YYYY",LL:"D [de] MMMM [de] YYYY",LLL:"D [de] MMMM [de] YYYY H:mm",LLLL:"dddd, D [de] MMMM [de] YYYY H:mm"},calendar:{sameDay:function(){return"[hoy a la"+(1!==this.hours()?"s":"")+"] LT"},nextDay:function(){return"[mañana a la"+(1!==this.hours()?"s":"")+"] LT"},nextWeek:function(){return"dddd [a la"+(1!==this.hours()?"s":"")+"] LT"},lastDay:function(){return"[ayer a la"+(1!==this.hours()?"s":"")+"] LT"},lastWeek:function(){return"[el] dddd [pasado a la"+(1!==this.hours()?"s":"")+"] LT"},sameElse:"L"},relativeTime:{future:"en %s",past:"hace %s",s:"unos segundos",m:"un minuto",mm:"%d minutos",h:"una hora",hh:"%d horas",d:"un día",dd:"%d días",M:"un mes",MM:"%d meses",y:"un año",yy:"%d años"},ordinalParse:/\d{1,2}º/,ordinal:"%dº",week:{dow:1,doy:4}}),a.defineLocale("et",{months:"jaanuar_veebruar_märts_aprill_mai_juuni_juuli_august_september_oktoober_november_detsember".split("_"),monthsShort:"jaan_veebr_märts_apr_mai_juuni_juuli_aug_sept_okt_nov_dets".split("_"),weekdays:"pühapäev_esmaspäev_teisipäev_kolmapäev_neljapäev_reede_laupäev".split("_"),weekdaysShort:"P_E_T_K_N_R_L".split("_"),weekdaysMin:"P_E_T_K_N_R_L".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd, D. MMMM YYYY H:mm"},calendar:{sameDay:"[Täna,] LT",nextDay:"[Homme,] LT",nextWeek:"[Järgmine] dddd LT",lastDay:"[Eile,] LT",lastWeek:"[Eelmine] dddd LT",sameElse:"L"},relativeTime:{future:"%s pärast",past:"%s tagasi",s:p,m:p,mm:p,h:p,hh:p,d:p,dd:"%d päeva",M:p,MM:p,y:p,yy:p},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),a.defineLocale("eu",{months:"urtarrila_otsaila_martxoa_apirila_maiatza_ekaina_uztaila_abuztua_iraila_urria_azaroa_abendua".split("_"),monthsShort:"urt._ots._mar._api._mai._eka._uzt._abu._ira._urr._aza._abe.".split("_"),weekdays:"igandea_astelehena_asteartea_asteazkena_osteguna_ostirala_larunbata".split("_"),weekdaysShort:"ig._al._ar._az._og._ol._lr.".split("_"),weekdaysMin:"ig_al_ar_az_og_ol_lr".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY-MM-DD",LL:"YYYY[ko] MMMM[ren] D[a]",LLL:"YYYY[ko] MMMM[ren] D[a] HH:mm",LLLL:"dddd, YYYY[ko] MMMM[ren] D[a] HH:mm",l:"YYYY-M-D",ll:"YYYY[ko] MMM D[a]",lll:"YYYY[ko] MMM D[a] HH:mm",llll:"ddd, YYYY[ko] MMM D[a] HH:mm"},calendar:{sameDay:"[gaur] LT[etan]",nextDay:"[bihar] LT[etan]",nextWeek:"dddd LT[etan]",lastDay:"[atzo] LT[etan]",lastWeek:"[aurreko] dddd LT[etan]",sameElse:"L"},relativeTime:{future:"%s barru",past:"duela %s",s:"segundo batzuk",m:"minutu bat",mm:"%d minutu",h:"ordu bat",hh:"%d ordu",d:"egun bat",dd:"%d egun",M:"hilabete bat",MM:"%d hilabete",y:"urte bat",yy:"%d urte"},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:7}}),{1:"۱",2:"۲",3:"۳",4:"۴",5:"۵",6:"۶",7:"۷", 8:"۸",9:"۹",0:"۰"}),ya={"۱":"1","۲":"2","۳":"3","۴":"4","۵":"5","۶":"6","۷":"7","۸":"8","۹":"9","۰":"0"},za=(a.defineLocale("fa",{months:"ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر".split("_"),monthsShort:"ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر".split("_"),weekdays:"یک‌شنبه_دوشنبه_سه‌شنبه_چهارشنبه_پنج‌شنبه_جمعه_شنبه".split("_"),weekdaysShort:"یک‌شنبه_دوشنبه_سه‌شنبه_چهارشنبه_پنج‌شنبه_جمعه_شنبه".split("_"),weekdaysMin:"ی_د_س_چ_پ_ج_ش".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},meridiemParse:/قبل از ظهر|بعد از ظهر/,isPM:function(a){return/بعد از ظهر/.test(a)},meridiem:function(a,b,c){return 12>a?"قبل از ظهر":"بعد از ظهر"},calendar:{sameDay:"[امروز ساعت] LT",nextDay:"[فردا ساعت] LT",nextWeek:"dddd [ساعت] LT",lastDay:"[دیروز ساعت] LT",lastWeek:"dddd [پیش] [ساعت] LT",sameElse:"L"},relativeTime:{future:"در %s",past:"%s پیش",s:"چندین ثانیه",m:"یک دقیقه",mm:"%d دقیقه",h:"یک ساعت",hh:"%d ساعت",d:"یک روز",dd:"%d روز",M:"یک ماه",MM:"%d ماه",y:"یک سال",yy:"%d سال"},preparse:function(a){return a.replace(/[۰-۹]/g,function(a){return ya[a]}).replace(/،/g,",")},postformat:function(a){return a.replace(/\d/g,function(a){return xa[a]}).replace(/,/g,"،")},ordinalParse:/\d{1,2}م/,ordinal:"%dم",week:{dow:6,doy:12}}),"nolla yksi kaksi kolme neljä viisi kuusi seitsemän kahdeksan yhdeksän".split(" ")),Aa=["nolla","yhden","kahden","kolmen","neljän","viiden","kuuden",za[7],za[8],za[9]],Ba=(a.defineLocale("fi",{months:"tammikuu_helmikuu_maaliskuu_huhtikuu_toukokuu_kesäkuu_heinäkuu_elokuu_syyskuu_lokakuu_marraskuu_joulukuu".split("_"),monthsShort:"tammi_helmi_maalis_huhti_touko_kesä_heinä_elo_syys_loka_marras_joulu".split("_"),weekdays:"sunnuntai_maanantai_tiistai_keskiviikko_torstai_perjantai_lauantai".split("_"),weekdaysShort:"su_ma_ti_ke_to_pe_la".split("_"),weekdaysMin:"su_ma_ti_ke_to_pe_la".split("_"),longDateFormat:{LT:"HH.mm",LTS:"HH.mm.ss",L:"DD.MM.YYYY",LL:"Do MMMM[ta] YYYY",LLL:"Do MMMM[ta] YYYY, [klo] HH.mm",LLLL:"dddd, Do MMMM[ta] YYYY, [klo] HH.mm",l:"D.M.YYYY",ll:"Do MMM YYYY",lll:"Do MMM YYYY, [klo] HH.mm",llll:"ddd, Do MMM YYYY, [klo] HH.mm"},calendar:{sameDay:"[tänään] [klo] LT",nextDay:"[huomenna] [klo] LT",nextWeek:"dddd [klo] LT",lastDay:"[eilen] [klo] LT",lastWeek:"[viime] dddd[na] [klo] LT",sameElse:"L"},relativeTime:{future:"%s päästä",past:"%s sitten",s:q,m:q,mm:q,h:q,hh:q,d:q,dd:q,M:q,MM:q,y:q,yy:q},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),a.defineLocale("fo",{months:"januar_februar_mars_apríl_mai_juni_juli_august_september_oktober_november_desember".split("_"),monthsShort:"jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"),weekdays:"sunnudagur_mánadagur_týsdagur_mikudagur_hósdagur_fríggjadagur_leygardagur".split("_"),weekdaysShort:"sun_mán_týs_mik_hós_frí_ley".split("_"),weekdaysMin:"su_má_tý_mi_hó_fr_le".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D. MMMM, YYYY HH:mm"},calendar:{sameDay:"[Í dag kl.] LT",nextDay:"[Í morgin kl.] LT",nextWeek:"dddd [kl.] LT",lastDay:"[Í gjár kl.] LT",lastWeek:"[síðstu] dddd [kl] LT",sameElse:"L"},relativeTime:{future:"um %s",past:"%s síðani",s:"fá sekund",m:"ein minutt",mm:"%d minuttir",h:"ein tími",hh:"%d tímar",d:"ein dagur",dd:"%d dagar",M:"ein mánaði",MM:"%d mánaðir",y:"eitt ár",yy:"%d ár"},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),a.defineLocale("fr-ca",{months:"janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"),monthsShort:"janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"),weekdays:"dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"),weekdaysShort:"dim._lun._mar._mer._jeu._ven._sam.".split("_"),weekdaysMin:"Di_Lu_Ma_Me_Je_Ve_Sa".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY-MM-DD",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[Aujourd'hui à] LT",nextDay:"[Demain à] LT",nextWeek:"dddd [à] LT",lastDay:"[Hier à] LT",lastWeek:"dddd [dernier à] LT",sameElse:"L"},relativeTime:{future:"dans %s",past:"il y a %s",s:"quelques secondes",m:"une minute",mm:"%d minutes",h:"une heure",hh:"%d heures",d:"un jour",dd:"%d jours",M:"un mois",MM:"%d mois",y:"un an",yy:"%d ans"},ordinalParse:/\d{1,2}(er|e)/,ordinal:function(a){return a+(1===a?"er":"e")}}),a.defineLocale("fr",{months:"janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"),monthsShort:"janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"),weekdays:"dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"),weekdaysShort:"dim._lun._mar._mer._jeu._ven._sam.".split("_"),weekdaysMin:"Di_Lu_Ma_Me_Je_Ve_Sa".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[Aujourd'hui à] LT",nextDay:"[Demain à] LT",nextWeek:"dddd [à] LT",lastDay:"[Hier à] LT",lastWeek:"dddd [dernier à] LT",sameElse:"L"},relativeTime:{future:"dans %s",past:"il y a %s",s:"quelques secondes",m:"une minute",mm:"%d minutes",h:"une heure",hh:"%d heures",d:"un jour",dd:"%d jours",M:"un mois",MM:"%d mois",y:"un an",yy:"%d ans"},ordinalParse:/\d{1,2}(er|)/,ordinal:function(a){return a+(1===a?"er":"")},week:{dow:1,doy:4}}),"jan._feb._mrt._apr._mai_jun._jul._aug._sep._okt._nov._des.".split("_")),Ca="jan_feb_mrt_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"),Da=(a.defineLocale("fy",{months:"jannewaris_febrewaris_maart_april_maaie_juny_july_augustus_septimber_oktober_novimber_desimber".split("_"),monthsShort:function(a,b){return/-MMM-/.test(b)?Ca[a.month()]:Ba[a.month()]},weekdays:"snein_moandei_tiisdei_woansdei_tongersdei_freed_sneon".split("_"),weekdaysShort:"si._mo._ti._wo._to._fr._so.".split("_"),weekdaysMin:"Si_Mo_Ti_Wo_To_Fr_So".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD-MM-YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[hjoed om] LT",nextDay:"[moarn om] LT",nextWeek:"dddd [om] LT",lastDay:"[juster om] LT",lastWeek:"[ôfrûne] dddd [om] LT",sameElse:"L"},relativeTime:{future:"oer %s",past:"%s lyn",s:"in pear sekonden",m:"ien minút",mm:"%d minuten",h:"ien oere",hh:"%d oeren",d:"ien dei",dd:"%d dagen",M:"ien moanne",MM:"%d moannen",y:"ien jier",yy:"%d jierren"},ordinalParse:/\d{1,2}(ste|de)/,ordinal:function(a){return a+(1===a||8===a||a>=20?"ste":"de")},week:{dow:1,doy:4}}),a.defineLocale("gl",{months:"Xaneiro_Febreiro_Marzo_Abril_Maio_Xuño_Xullo_Agosto_Setembro_Outubro_Novembro_Decembro".split("_"),monthsShort:"Xan._Feb._Mar._Abr._Mai._Xuñ._Xul._Ago._Set._Out._Nov._Dec.".split("_"),weekdays:"Domingo_Luns_Martes_Mércores_Xoves_Venres_Sábado".split("_"),weekdaysShort:"Dom._Lun._Mar._Mér._Xov._Ven._Sáb.".split("_"),weekdaysMin:"Do_Lu_Ma_Mé_Xo_Ve_Sá".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY H:mm",LLLL:"dddd D MMMM YYYY H:mm"},calendar:{sameDay:function(){return"[hoxe "+(1!==this.hours()?"ás":"á")+"] LT"},nextDay:function(){return"[mañá "+(1!==this.hours()?"ás":"á")+"] LT"},nextWeek:function(){return"dddd ["+(1!==this.hours()?"ás":"a")+"] LT"},lastDay:function(){return"[onte "+(1!==this.hours()?"á":"a")+"] LT"},lastWeek:function(){return"[o] dddd [pasado "+(1!==this.hours()?"ás":"a")+"] LT"},sameElse:"L"},relativeTime:{future:function(a){return"uns segundos"===a?"nuns segundos":"en "+a},past:"hai %s",s:"uns segundos",m:"un minuto",mm:"%d minutos",h:"unha hora",hh:"%d horas",d:"un día",dd:"%d días",M:"un mes",MM:"%d meses",y:"un ano",yy:"%d anos"},ordinalParse:/\d{1,2}º/,ordinal:"%dº",week:{dow:1,doy:7}}),a.defineLocale("he",{months:"ינואר_פברואר_מרץ_אפריל_מאי_יוני_יולי_אוגוסט_ספטמבר_אוקטובר_נובמבר_דצמבר".split("_"),monthsShort:"ינו׳_פבר׳_מרץ_אפר׳_מאי_יוני_יולי_אוג׳_ספט׳_אוק׳_נוב׳_דצמ׳".split("_"),weekdays:"ראשון_שני_שלישי_רביעי_חמישי_שישי_שבת".split("_"),weekdaysShort:"א׳_ב׳_ג׳_ד׳_ה׳_ו׳_ש׳".split("_"),weekdaysMin:"א_ב_ג_ד_ה_ו_ש".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D [ב]MMMM YYYY",LLL:"D [ב]MMMM YYYY HH:mm",LLLL:"dddd, D [ב]MMMM YYYY HH:mm",l:"D/M/YYYY",ll:"D MMM YYYY",lll:"D MMM YYYY HH:mm",llll:"ddd, D MMM YYYY HH:mm"},calendar:{sameDay:"[היום ב־]LT",nextDay:"[מחר ב־]LT",nextWeek:"dddd [בשעה] LT",lastDay:"[אתמול ב־]LT",lastWeek:"[ביום] dddd [האחרון בשעה] LT",sameElse:"L"},relativeTime:{future:"בעוד %s",past:"לפני %s",s:"מספר שניות",m:"דקה",mm:"%d דקות",h:"שעה",hh:function(a){return 2===a?"שעתיים":a+" שעות"},d:"יום",dd:function(a){return 2===a?"יומיים":a+" ימים"},M:"חודש",MM:function(a){return 2===a?"חודשיים":a+" חודשים"},y:"שנה",yy:function(a){return 2===a?"שנתיים":a%10===0&&10!==a?a+" שנה":a+" שנים"}}}),{1:"१",2:"२",3:"३",4:"४",5:"५",6:"६",7:"७",8:"८",9:"९",0:"०"}),Ea={"१":"1","२":"2","३":"3","४":"4","५":"5","६":"6","७":"7","८":"8","९":"9","०":"0"},Fa=(a.defineLocale("hi",{months:"जनवरी_फ़रवरी_मार्च_अप्रैल_मई_जून_जुलाई_अगस्त_सितम्बर_अक्टूबर_नवम्बर_दिसम्बर".split("_"),monthsShort:"जन._फ़र._मार्च_अप्रै._मई_जून_जुल._अग._सित._अक्टू._नव._दिस.".split("_"),weekdays:"रविवार_सोमवार_मंगलवार_बुधवार_गुरूवार_शुक्रवार_शनिवार".split("_"),weekdaysShort:"रवि_सोम_मंगल_बुध_गुरू_शुक्र_शनि".split("_"),weekdaysMin:"र_सो_मं_बु_गु_शु_श".split("_"),longDateFormat:{LT:"A h:mm बजे",LTS:"A h:mm:ss बजे",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, A h:mm बजे",LLLL:"dddd, D MMMM YYYY, A h:mm बजे"},calendar:{sameDay:"[आज] LT",nextDay:"[कल] LT",nextWeek:"dddd, LT",lastDay:"[कल] LT",lastWeek:"[पिछले] dddd, LT",sameElse:"L"},relativeTime:{future:"%s में",past:"%s पहले",s:"कुछ ही क्षण",m:"एक मिनट",mm:"%d मिनट",h:"एक घंटा",hh:"%d घंटे",d:"एक दिन",dd:"%d दिन",M:"एक महीने",MM:"%d महीने",y:"एक वर्ष",yy:"%d वर्ष"},preparse:function(a){return a.replace(/[१२३४५६७८९०]/g,function(a){return Ea[a]})},postformat:function(a){return a.replace(/\d/g,function(a){return Da[a]})},meridiemParse:/रात|सुबह|दोपहर|शाम/,meridiemHour:function(a,b){return 12===a&&(a=0),"रात"===b?4>a?a:a+12:"सुबह"===b?a:"दोपहर"===b?a>=10?a:a+12:"शाम"===b?a+12:void 0},meridiem:function(a,b,c){return 4>a?"रात":10>a?"सुबह":17>a?"दोपहर":20>a?"शाम":"रात"},week:{dow:0,doy:6}}),a.defineLocale("hr",{months:"siječanj_veljača_ožujak_travanj_svibanj_lipanj_srpanj_kolovoz_rujan_listopad_studeni_prosinac".split("_"),monthsShort:"sij._velj._ožu._tra._svi._lip._srp._kol._ruj._lis._stu._pro.".split("_"),weekdays:"nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota".split("_"),weekdaysShort:"ned._pon._uto._sri._čet._pet._sub.".split("_"),weekdaysMin:"ne_po_ut_sr_če_pe_su".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD. MM. YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd, D. MMMM YYYY H:mm"},calendar:{sameDay:"[danas u] LT",nextDay:"[sutra u] LT",nextWeek:function(){switch(this.day()){case 0:return"[u] [nedjelju] [u] LT";case 3:return"[u] [srijedu] [u] LT";case 6:return"[u] [subotu] [u] LT";case 1:case 2:case 4:case 5:return"[u] dddd [u] LT"}},lastDay:"[jučer u] LT",lastWeek:function(){switch(this.day()){case 0:case 3:return"[prošlu] dddd [u] LT";case 6:return"[prošle] [subote] [u] LT";case 1:case 2:case 4:case 5:return"[prošli] dddd [u] LT"}},sameElse:"L"},relativeTime:{future:"za %s",past:"prije %s",s:"par sekundi",m:s,mm:s,h:s,hh:s,d:"dan",dd:s,M:"mjesec",MM:s,y:"godinu",yy:s},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:7}}),"vasárnap hétfőn kedden szerdán csütörtökön pénteken szombaton".split(" ")),Ga=(a.defineLocale("hu",{months:"január_február_március_április_május_június_július_augusztus_szeptember_október_november_december".split("_"),monthsShort:"jan_feb_márc_ápr_máj_jún_júl_aug_szept_okt_nov_dec".split("_"),weekdays:"vasárnap_hétfő_kedd_szerda_csütörtök_péntek_szombat".split("_"),weekdaysShort:"vas_hét_kedd_sze_csüt_pén_szo".split("_"),weekdaysMin:"v_h_k_sze_cs_p_szo".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"YYYY.MM.DD.",LL:"YYYY. MMMM D.",LLL:"YYYY. MMMM D. H:mm",LLLL:"YYYY. MMMM D., dddd H:mm"},meridiemParse:/de|du/i,isPM:function(a){return"u"===a.charAt(1).toLowerCase()},meridiem:function(a,b,c){return 12>a?c===!0?"de":"DE":c===!0?"du":"DU"},calendar:{sameDay:"[ma] LT[-kor]",nextDay:"[holnap] LT[-kor]",nextWeek:function(){return u.call(this,!0)},lastDay:"[tegnap] LT[-kor]",lastWeek:function(){return u.call(this,!1)},sameElse:"L"},relativeTime:{future:"%s múlva",past:"%s",s:t,m:t,mm:t,h:t,hh:t,d:t,dd:t,M:t,MM:t,y:t,yy:t},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:7}}),a.defineLocale("hy-am",{months:v,monthsShort:w,weekdays:x,weekdaysShort:"կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ".split("_"),weekdaysMin:"կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY թ.",LLL:"D MMMM YYYY թ., HH:mm",LLLL:"dddd, D MMMM YYYY թ., HH:mm"},calendar:{sameDay:"[այսօր] LT",nextDay:"[վաղը] LT",lastDay:"[երեկ] LT",nextWeek:function(){return"dddd [օրը ժամը] LT"},lastWeek:function(){return"[անցած] dddd [օրը ժամը] LT"},sameElse:"L"},relativeTime:{future:"%s հետո",past:"%s առաջ",s:"մի քանի վայրկյան",m:"րոպե",mm:"%d րոպե",h:"ժամ",hh:"%d ժամ",d:"օր",dd:"%d օր",M:"ամիս",MM:"%d ամիս",y:"տարի",yy:"%d տարի"},meridiemParse:/գիշերվա|առավոտվա|ցերեկվա|երեկոյան/,isPM:function(a){return/^(ցերեկվա|երեկոյան)$/.test(a)},meridiem:function(a){return 4>a?"գիշերվա":12>a?"առավոտվա":17>a?"ցերեկվա":"երեկոյան"},ordinalParse:/\d{1,2}|\d{1,2}-(ին|րդ)/,ordinal:function(a,b){switch(b){case"DDD":case"w":case"W":case"DDDo":return 1===a?a+"-ին":a+"-րդ";default:return a}},week:{dow:1,doy:7}}),a.defineLocale("id",{months:"Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_November_Desember".split("_"),monthsShort:"Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nov_Des".split("_"),weekdays:"Minggu_Senin_Selasa_Rabu_Kamis_Jumat_Sabtu".split("_"),weekdaysShort:"Min_Sen_Sel_Rab_Kam_Jum_Sab".split("_"),weekdaysMin:"Mg_Sn_Sl_Rb_Km_Jm_Sb".split("_"),longDateFormat:{LT:"HH.mm",LTS:"HH.mm.ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY [pukul] HH.mm",LLLL:"dddd, D MMMM YYYY [pukul] HH.mm"},meridiemParse:/pagi|siang|sore|malam/,meridiemHour:function(a,b){return 12===a&&(a=0),"pagi"===b?a:"siang"===b?a>=11?a:a+12:"sore"===b||"malam"===b?a+12:void 0},meridiem:function(a,b,c){return 11>a?"pagi":15>a?"siang":19>a?"sore":"malam"},calendar:{sameDay:"[Hari ini pukul] LT",nextDay:"[Besok pukul] LT",nextWeek:"dddd [pukul] LT",lastDay:"[Kemarin pukul] LT",lastWeek:"dddd [lalu pukul] LT",sameElse:"L"},relativeTime:{future:"dalam %s",past:"%s yang lalu",s:"beberapa detik",m:"semenit",mm:"%d menit",h:"sejam",hh:"%d jam",d:"sehari",dd:"%d hari",M:"sebulan",MM:"%d bulan",y:"setahun",yy:"%d tahun"},week:{dow:1,doy:7}}),a.defineLocale("is",{months:"janúar_febrúar_mars_apríl_maí_júní_júlí_ágúst_september_október_nóvember_desember".split("_"),monthsShort:"jan_feb_mar_apr_maí_jún_júl_ágú_sep_okt_nóv_des".split("_"),weekdays:"sunnudagur_mánudagur_þriðjudagur_miðvikudagur_fimmtudagur_föstudagur_laugardagur".split("_"),weekdaysShort:"sun_mán_þri_mið_fim_fös_lau".split("_"),weekdaysMin:"Su_Má_Þr_Mi_Fi_Fö_La".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD/MM/YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY [kl.] H:mm",LLLL:"dddd, D. MMMM YYYY [kl.] H:mm"},calendar:{sameDay:"[í dag kl.] LT",nextDay:"[á morgun kl.] LT",nextWeek:"dddd [kl.] LT",lastDay:"[í gær kl.] LT",lastWeek:"[síðasta] dddd [kl.] LT",sameElse:"L"},relativeTime:{future:"eftir %s",past:"fyrir %s síðan",s:z,m:z,mm:z,h:"klukkustund",hh:z,d:z,dd:z,M:z,MM:z,y:z,yy:z},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),a.defineLocale("it",{months:"gennaio_febbraio_marzo_aprile_maggio_giugno_luglio_agosto_settembre_ottobre_novembre_dicembre".split("_"),monthsShort:"gen_feb_mar_apr_mag_giu_lug_ago_set_ott_nov_dic".split("_"),weekdays:"Domenica_Lunedì_Martedì_Mercoledì_Giovedì_Venerdì_Sabato".split("_"),weekdaysShort:"Dom_Lun_Mar_Mer_Gio_Ven_Sab".split("_"),weekdaysMin:"D_L_Ma_Me_G_V_S".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[Oggi alle] LT",nextDay:"[Domani alle] LT",nextWeek:"dddd [alle] LT",lastDay:"[Ieri alle] LT",lastWeek:function(){switch(this.day()){case 0:return"[la scorsa] dddd [alle] LT";default:return"[lo scorso] dddd [alle] LT"}},sameElse:"L"},relativeTime:{future:function(a){return(/^[0-9].+$/.test(a)?"tra":"in")+" "+a},past:"%s fa",s:"alcuni secondi",m:"un minuto",mm:"%d minuti",h:"un'ora",hh:"%d ore",d:"un giorno",dd:"%d giorni",M:"un mese",MM:"%d mesi",y:"un anno",yy:"%d anni"},ordinalParse:/\d{1,2}º/,ordinal:"%dº",week:{dow:1,doy:4}}),a.defineLocale("ja",{months:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日".split("_"),weekdaysShort:"日_月_火_水_木_金_土".split("_"),weekdaysMin:"日_月_火_水_木_金_土".split("_"),longDateFormat:{LT:"Ah時m分",LTS:"Ah時m分s秒",L:"YYYY/MM/DD",LL:"YYYY年M月D日",LLL:"YYYY年M月D日Ah時m分",LLLL:"YYYY年M月D日Ah時m分 dddd"},meridiemParse:/午前|午後/i,isPM:function(a){return"午後"===a},meridiem:function(a,b,c){return 12>a?"午前":"午後"},calendar:{sameDay:"[今日] LT",nextDay:"[明日] LT",nextWeek:"[来週]dddd LT",lastDay:"[昨日] LT",lastWeek:"[前週]dddd LT",sameElse:"L"},relativeTime:{future:"%s後",past:"%s前",s:"数秒",m:"1分",mm:"%d分",h:"1時間",hh:"%d時間",d:"1日",dd:"%d日",M:"1ヶ月",MM:"%dヶ月",y:"1年",yy:"%d年"}}),a.defineLocale("jv",{months:"Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_Nopember_Desember".split("_"),monthsShort:"Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nop_Des".split("_"),weekdays:"Minggu_Senen_Seloso_Rebu_Kemis_Jemuwah_Septu".split("_"),weekdaysShort:"Min_Sen_Sel_Reb_Kem_Jem_Sep".split("_"),weekdaysMin:"Mg_Sn_Sl_Rb_Km_Jm_Sp".split("_"),longDateFormat:{LT:"HH.mm",LTS:"HH.mm.ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY [pukul] HH.mm",LLLL:"dddd, D MMMM YYYY [pukul] HH.mm"},meridiemParse:/enjing|siyang|sonten|ndalu/,meridiemHour:function(a,b){return 12===a&&(a=0),"enjing"===b?a:"siyang"===b?a>=11?a:a+12:"sonten"===b||"ndalu"===b?a+12:void 0},meridiem:function(a,b,c){return 11>a?"enjing":15>a?"siyang":19>a?"sonten":"ndalu"},calendar:{sameDay:"[Dinten puniko pukul] LT",nextDay:"[Mbenjang pukul] LT",nextWeek:"dddd [pukul] LT",lastDay:"[Kala wingi pukul] LT",lastWeek:"dddd [kepengker pukul] LT",sameElse:"L"},relativeTime:{future:"wonten ing %s",past:"%s ingkang kepengker",s:"sawetawis detik",m:"setunggal menit",mm:"%d menit",h:"setunggal jam",hh:"%d jam",d:"sedinten",dd:"%d dinten",M:"sewulan",MM:"%d wulan",y:"setaun",yy:"%d taun"},week:{dow:1,doy:7}}),a.defineLocale("ka",{months:A,monthsShort:"იან_თებ_მარ_აპრ_მაი_ივნ_ივლ_აგვ_სექ_ოქტ_ნოე_დეკ".split("_"),weekdays:B,weekdaysShort:"კვი_ორშ_სამ_ოთხ_ხუთ_პარ_შაბ".split("_"),weekdaysMin:"კვ_ორ_სა_ოთ_ხუ_პა_შა".split("_"),longDateFormat:{LT:"h:mm A",LTS:"h:mm:ss A",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY h:mm A",LLLL:"dddd, D MMMM YYYY h:mm A"},calendar:{sameDay:"[დღეს] LT[-ზე]",nextDay:"[ხვალ] LT[-ზე]",lastDay:"[გუშინ] LT[-ზე]",nextWeek:"[შემდეგ] dddd LT[-ზე]",lastWeek:"[წინა] dddd LT-ზე",sameElse:"L"},relativeTime:{future:function(a){return/(წამი|წუთი|საათი|წელი)/.test(a)?a.replace(/ი$/,"ში"):a+"ში"},past:function(a){return/(წამი|წუთი|საათი|დღე|თვე)/.test(a)?a.replace(/(ი|ე)$/,"ის წინ"):/წელი/.test(a)?a.replace(/წელი$/,"წლის წინ"):void 0},s:"რამდენიმე წამი",m:"წუთი",mm:"%d წუთი",h:"საათი",hh:"%d საათი",d:"დღე",dd:"%d დღე",M:"თვე",MM:"%d თვე",y:"წელი",yy:"%d წელი"},ordinalParse:/0|1-ლი|მე-\d{1,2}|\d{1,2}-ე/,ordinal:function(a){return 0===a?a:1===a?a+"-ლი":20>a||100>=a&&a%20===0||a%100===0?"მე-"+a:a+"-ე"},week:{dow:1,doy:7}}),a.defineLocale("km",{months:"មករា_កុម្ភៈ_មិនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ".split("_"),monthsShort:"មករា_កុម្ភៈ_មិនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ".split("_"),weekdays:"អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍".split("_"),weekdaysShort:"អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍".split("_"),weekdaysMin:"អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[ថ្ងៃនៈ ម៉ោង] LT",nextDay:"[ស្អែក ម៉ោង] LT",nextWeek:"dddd [ម៉ោង] LT",lastDay:"[ម្សិលមិញ ម៉ោង] LT",lastWeek:"dddd [សប្តាហ៍មុន] [ម៉ោង] LT",sameElse:"L"},relativeTime:{future:"%sទៀត",past:"%sមុន",s:"ប៉ុន្មានវិនាទី",m:"មួយនាទី",mm:"%d នាទី",h:"មួយម៉ោង",hh:"%d ម៉ោង",d:"មួយថ្ងៃ",dd:"%d ថ្ងៃ",M:"មួយខែ",MM:"%d ខែ",y:"មួយឆ្នាំ",yy:"%d ឆ្នាំ"},week:{dow:1,doy:4}}),a.defineLocale("ko",{months:"1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"),monthsShort:"1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"),weekdays:"일요일_월요일_화요일_수요일_목요일_금요일_토요일".split("_"),weekdaysShort:"일_월_화_수_목_금_토".split("_"),weekdaysMin:"일_월_화_수_목_금_토".split("_"),longDateFormat:{LT:"A h시 m분",LTS:"A h시 m분 s초",L:"YYYY.MM.DD",LL:"YYYY년 MMMM D일",LLL:"YYYY년 MMMM D일 A h시 m분",LLLL:"YYYY년 MMMM D일 dddd A h시 m분"},calendar:{sameDay:"오늘 LT",nextDay:"내일 LT",nextWeek:"dddd LT",lastDay:"어제 LT",lastWeek:"지난주 dddd LT",sameElse:"L"},relativeTime:{future:"%s 후",past:"%s 전",s:"몇초",ss:"%d초",m:"일분",mm:"%d분",h:"한시간",hh:"%d시간",d:"하루",dd:"%d일",M:"한달",MM:"%d달",y:"일년",yy:"%d년"},ordinalParse:/\d{1,2}일/,ordinal:"%d일",meridiemParse:/오전|오후/,isPM:function(a){return"오후"===a},meridiem:function(a,b,c){return 12>a?"오전":"오후"}}),a.defineLocale("lb",{months:"Januar_Februar_Mäerz_Abrëll_Mee_Juni_Juli_August_September_Oktober_November_Dezember".split("_"),monthsShort:"Jan._Febr._Mrz._Abr._Mee_Jun._Jul._Aug._Sept._Okt._Nov._Dez.".split("_"),weekdays:"Sonndeg_Méindeg_Dënschdeg_Mëttwoch_Donneschdeg_Freideg_Samschdeg".split("_"),weekdaysShort:"So._Mé._Dë._Më._Do._Fr._Sa.".split("_"),weekdaysMin:"So_Mé_Dë_Më_Do_Fr_Sa".split("_"),longDateFormat:{LT:"H:mm [Auer]",LTS:"H:mm:ss [Auer]",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm [Auer]",LLLL:"dddd, D. MMMM YYYY H:mm [Auer]"},calendar:{sameDay:"[Haut um] LT",sameElse:"L",nextDay:"[Muer um] LT",nextWeek:"dddd [um] LT",lastDay:"[Gëschter um] LT",lastWeek:function(){switch(this.day()){case 2:case 4:return"[Leschten] dddd [um] LT";default:return"[Leschte] dddd [um] LT"}}},relativeTime:{future:D,past:E,s:"e puer Sekonnen",m:C,mm:"%d Minutten",h:C,hh:"%d Stonnen",d:C,dd:"%d Deeg",M:C,MM:"%d Méint",y:C,yy:"%d Joer"},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),{m:"minutė_minutės_minutę",mm:"minutės_minučių_minutes",h:"valanda_valandos_valandą",hh:"valandos_valandų_valandas",d:"diena_dienos_dieną",dd:"dienos_dienų_dienas",M:"mėnuo_mėnesio_mėnesį",MM:"mėnesiai_mėnesių_mėnesius",y:"metai_metų_metus",yy:"metai_metų_metus"}),Ha="sekmadienis_pirmadienis_antradienis_trečiadienis_ketvirtadienis_penktadienis_šeštadienis".split("_"),Ia=(a.defineLocale("lt",{months:H,monthsShort:"sau_vas_kov_bal_geg_bir_lie_rgp_rgs_spa_lap_grd".split("_"),weekdays:M,weekdaysShort:"Sek_Pir_Ant_Tre_Ket_Pen_Šeš".split("_"),weekdaysMin:"S_P_A_T_K_Pn_Š".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY-MM-DD",LL:"YYYY [m.] MMMM D [d.]",LLL:"YYYY [m.] MMMM D [d.], HH:mm [val.]",LLLL:"YYYY [m.] MMMM D [d.], dddd, HH:mm [val.]",l:"YYYY-MM-DD",ll:"YYYY [m.] MMMM D [d.]",lll:"YYYY [m.] MMMM D [d.], HH:mm [val.]",llll:"YYYY [m.] MMMM D [d.], ddd, HH:mm [val.]"},calendar:{sameDay:"[Šiandien] LT",nextDay:"[Rytoj] LT",nextWeek:"dddd LT",lastDay:"[Vakar] LT",lastWeek:"[Praėjusį] dddd LT",sameElse:"L"},relativeTime:{future:"po %s",past:"prieš %s",s:G,m:I,mm:L,h:I,hh:L,d:I,dd:L,M:I,MM:L,y:I,yy:L},ordinalParse:/\d{1,2}-oji/,ordinal:function(a){return a+"-oji"},week:{dow:1,doy:4}}),{m:"minūtes_minūtēm_minūte_minūtes".split("_"),mm:"minūtes_minūtēm_minūte_minūtes".split("_"),h:"stundas_stundām_stunda_stundas".split("_"),hh:"stundas_stundām_stunda_stundas".split("_"),d:"dienas_dienām_diena_dienas".split("_"),dd:"dienas_dienām_diena_dienas".split("_"),M:"mēneša_mēnešiem_mēnesis_mēneši".split("_"),MM:"mēneša_mēnešiem_mēnesis_mēneši".split("_"),y:"gada_gadiem_gads_gadi".split("_"),yy:"gada_gadiem_gads_gadi".split("_")}),Ja=(a.defineLocale("lv",{months:"janvāris_februāris_marts_aprīlis_maijs_jūnijs_jūlijs_augusts_septembris_oktobris_novembris_decembris".split("_"),monthsShort:"jan_feb_mar_apr_mai_jūn_jūl_aug_sep_okt_nov_dec".split("_"),weekdays:"svētdiena_pirmdiena_otrdiena_trešdiena_ceturtdiena_piektdiena_sestdiena".split("_"),weekdaysShort:"Sv_P_O_T_C_Pk_S".split("_"),weekdaysMin:"Sv_P_O_T_C_Pk_S".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY.",LL:"YYYY. [gada] D. MMMM",LLL:"YYYY. [gada] D. MMMM, HH:mm",LLLL:"YYYY. [gada] D. MMMM, dddd, HH:mm"},calendar:{sameDay:"[Šodien pulksten] LT",nextDay:"[Rīt pulksten] LT",nextWeek:"dddd [pulksten] LT",lastDay:"[Vakar pulksten] LT",lastWeek:"[Pagājušā] dddd [pulksten] LT",sameElse:"L"},relativeTime:{future:"pēc %s",past:"pirms %s",s:Q,m:P,mm:O,h:P,hh:O,d:P,dd:O,M:P,MM:O,y:P,yy:O},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),{words:{m:["jedan minut","jednog minuta"],mm:["minut","minuta","minuta"],h:["jedan sat","jednog sata"],hh:["sat","sata","sati"],dd:["dan","dana","dana"],MM:["mjesec","mjeseca","mjeseci"],yy:["godina","godine","godina"]},correctGrammaticalCase:function(a,b){return 1===a?b[0]:a>=2&&4>=a?b[1]:b[2]},translate:function(a,b,c){var d=Ja.words[c];return 1===c.length?b?d[0]:d[1]:a+" "+Ja.correctGrammaticalCase(a,d)}}),Ka=(a.defineLocale("me",{months:["januar","februar","mart","april","maj","jun","jul","avgust","septembar","oktobar","novembar","decembar"],monthsShort:["jan.","feb.","mar.","apr.","maj","jun","jul","avg.","sep.","okt.","nov.","dec."],weekdays:["nedjelja","ponedjeljak","utorak","srijeda","četvrtak","petak","subota"],weekdaysShort:["ned.","pon.","uto.","sri.","čet.","pet.","sub."],weekdaysMin:["ne","po","ut","sr","če","pe","su"],longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD. MM. YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd, D. MMMM YYYY H:mm"},calendar:{sameDay:"[danas u] LT",nextDay:"[sjutra u] LT",nextWeek:function(){switch(this.day()){case 0:return"[u] [nedjelju] [u] LT";case 3:return"[u] [srijedu] [u] LT";case 6:return"[u] [subotu] [u] LT";case 1:case 2:case 4:case 5:return"[u] dddd [u] LT"}},lastDay:"[juče u] LT",lastWeek:function(){var a=["[prošle] [nedjelje] [u] LT","[prošlog] [ponedjeljka] [u] LT","[prošlog] [utorka] [u] LT","[prošle] [srijede] [u] LT","[prošlog] [četvrtka] [u] LT","[prošlog] [petka] [u] LT","[prošle] [subote] [u] LT"];return a[this.day()]},sameElse:"L"},relativeTime:{future:"za %s",past:"prije %s",s:"nekoliko sekundi",m:Ja.translate,mm:Ja.translate,h:Ja.translate,hh:Ja.translate,d:"dan",dd:Ja.translate,M:"mjesec",MM:Ja.translate,y:"godinu",yy:Ja.translate},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:7}}),a.defineLocale("mk",{months:"јануари_февруари_март_април_мај_јуни_јули_август_септември_октомври_ноември_декември".split("_"),monthsShort:"јан_фев_мар_апр_мај_јун_јул_авг_сеп_окт_ное_дек".split("_"),weekdays:"недела_понеделник_вторник_среда_четврток_петок_сабота".split("_"),weekdaysShort:"нед_пон_вто_сре_чет_пет_саб".split("_"),weekdaysMin:"нe_пo_вт_ср_че_пе_сa".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"D.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY H:mm",LLLL:"dddd, D MMMM YYYY H:mm"},calendar:{sameDay:"[Денес во] LT",nextDay:"[Утре во] LT",nextWeek:"dddd [во] LT",lastDay:"[Вчера во] LT",lastWeek:function(){switch(this.day()){case 0:case 3:case 6:return"[Во изминатата] dddd [во] LT";case 1:case 2:case 4:case 5:return"[Во изминатиот] dddd [во] LT"}},sameElse:"L"},relativeTime:{future:"после %s",past:"пред %s",s:"неколку секунди",m:"минута",mm:"%d минути",h:"час",hh:"%d часа",d:"ден",dd:"%d дена",M:"месец",MM:"%d месеци",y:"година",yy:"%d години"},ordinalParse:/\d{1,2}-(ев|ен|ти|ви|ри|ми)/,ordinal:function(a){var b=a%10,c=a%100;return 0===a?a+"-ев":0===c?a+"-ен":c>10&&20>c?a+"-ти":1===b?a+"-ви":2===b?a+"-ри":7===b||8===b?a+"-ми":a+"-ти"},week:{dow:1,doy:7}}),a.defineLocale("ml",{months:"ജനുവരി_ഫെബ്രുവരി_മാർച്ച്_ഏപ്രിൽ_മേയ്_ജൂൺ_ജൂലൈ_ഓഗസ്റ്റ്_സെപ്റ്റംബർ_ഒക്ടോബർ_നവംബർ_ഡിസംബർ".split("_"),monthsShort:"ജനു._ഫെബ്രു._മാർ._ഏപ്രി._മേയ്_ജൂൺ_ജൂലൈ._ഓഗ._സെപ്റ്റ._ഒക്ടോ._നവം._ഡിസം.".split("_"),weekdays:"ഞായറാഴ്ച_തിങ്കളാഴ്ച_ചൊവ്വാഴ്ച_ബുധനാഴ്ച_വ്യാഴാഴ്ച_വെള്ളിയാഴ്ച_ശനിയാഴ്ച".split("_"),weekdaysShort:"ഞായർ_തിങ്കൾ_ചൊവ്വ_ബുധൻ_വ്യാഴം_വെള്ളി_ശനി".split("_"),weekdaysMin:"ഞാ_തി_ചൊ_ബു_വ്യാ_വെ_ശ".split("_"),longDateFormat:{LT:"A h:mm -നു",LTS:"A h:mm:ss -നു",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, A h:mm -നു",LLLL:"dddd, D MMMM YYYY, A h:mm -നു"},calendar:{sameDay:"[ഇന്ന്] LT",nextDay:"[നാളെ] LT",nextWeek:"dddd, LT",lastDay:"[ഇന്നലെ] LT",lastWeek:"[കഴിഞ്ഞ] dddd, LT",sameElse:"L"},relativeTime:{future:"%s കഴിഞ്ഞ്",past:"%s മുൻപ്",s:"അൽപ നിമിഷങ്ങൾ",m:"ഒരു മിനിറ്റ്",mm:"%d മിനിറ്റ്",h:"ഒരു മണിക്കൂർ",hh:"%d മണിക്കൂർ",d:"ഒരു ദിവസം",dd:"%d ദിവസം",M:"ഒരു മാസം",MM:"%d മാസം",y:"ഒരു വർഷം",yy:"%d വർഷം"},meridiemParse:/രാത്രി|രാവിലെ|ഉച്ച കഴിഞ്ഞ്|വൈകുന്നേരം|രാത്രി/i,isPM:function(a){return/^(ഉച്ച കഴിഞ്ഞ്|വൈകുന്നേരം|രാത്രി)$/.test(a)},meridiem:function(a,b,c){return 4>a?"രാത്രി":12>a?"രാവിലെ":17>a?"ഉച്ച കഴിഞ്ഞ്":20>a?"വൈകുന്നേരം":"രാത്രി"}}),{1:"१",2:"२",3:"३",4:"४",5:"५",6:"६",7:"७",8:"८",9:"९",0:"०"}),La={"१":"1","२":"2","३":"3","४":"4","५":"5","६":"6","७":"7","८":"8","९":"9","०":"0"},Ma=(a.defineLocale("mr",{months:"जानेवारी_फेब्रुवारी_मार्च_एप्रिल_मे_जून_जुलै_ऑगस्ट_सप्टेंबर_ऑक्टोबर_नोव्हेंबर_डिसेंबर".split("_"),monthsShort:"जाने._फेब्रु._मार्च._एप्रि._मे._जून._जुलै._ऑग._सप्टें._ऑक्टो._नोव्हें._डिसें.".split("_"),weekdays:"रविवार_सोमवार_मंगळवार_बुधवार_गुरूवार_शुक्रवार_शनिवार".split("_"),weekdaysShort:"रवि_सोम_मंगळ_बुध_गुरू_शुक्र_शनि".split("_"),weekdaysMin:"र_सो_मं_बु_गु_शु_श".split("_"),longDateFormat:{LT:"A h:mm वाजता",LTS:"A h:mm:ss वाजता",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, A h:mm वाजता",LLLL:"dddd, D MMMM YYYY, A h:mm वाजता"},calendar:{sameDay:"[आज] LT",nextDay:"[उद्या] LT",nextWeek:"dddd, LT",lastDay:"[काल] LT",lastWeek:"[मागील] dddd, LT",sameElse:"L"},relativeTime:{future:"%s नंतर",past:"%s पूर्वी",s:"सेकंद",m:"एक मिनिट",mm:"%d मिनिटे",h:"एक तास",hh:"%d तास",d:"एक दिवस",dd:"%d दिवस",M:"एक महिना",MM:"%d महिने",y:"एक वर्ष",yy:"%d वर्षे"},preparse:function(a){return a.replace(/[१२३४५६७८९०]/g,function(a){return La[a]})},postformat:function(a){return a.replace(/\d/g,function(a){return Ka[a]})},meridiemParse:/रात्री|सकाळी|दुपारी|सायंकाळी/,meridiemHour:function(a,b){return 12===a&&(a=0),"रात्री"===b?4>a?a:a+12:"सकाळी"===b?a:"दुपारी"===b?a>=10?a:a+12:"सायंकाळी"===b?a+12:void 0},meridiem:function(a,b,c){return 4>a?"रात्री":10>a?"सकाळी":17>a?"दुपारी":20>a?"सायंकाळी":"रात्री"},week:{dow:0,doy:6}}),a.defineLocale("ms-my",{months:"Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember".split("_"),monthsShort:"Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis".split("_"),weekdays:"Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu".split("_"),weekdaysShort:"Ahd_Isn_Sel_Rab_Kha_Jum_Sab".split("_"),weekdaysMin:"Ah_Is_Sl_Rb_Km_Jm_Sb".split("_"),longDateFormat:{LT:"HH.mm",LTS:"HH.mm.ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY [pukul] HH.mm",LLLL:"dddd, D MMMM YYYY [pukul] HH.mm"},meridiemParse:/pagi|tengahari|petang|malam/,meridiemHour:function(a,b){return 12===a&&(a=0),"pagi"===b?a:"tengahari"===b?a>=11?a:a+12:"petang"===b||"malam"===b?a+12:void 0},meridiem:function(a,b,c){return 11>a?"pagi":15>a?"tengahari":19>a?"petang":"malam"},calendar:{sameDay:"[Hari ini pukul] LT",nextDay:"[Esok pukul] LT",nextWeek:"dddd [pukul] LT",lastDay:"[Kelmarin pukul] LT",lastWeek:"dddd [lepas pukul] LT",sameElse:"L"},relativeTime:{future:"dalam %s",past:"%s yang lepas",s:"beberapa saat",m:"seminit",mm:"%d minit",h:"sejam",hh:"%d jam",d:"sehari",dd:"%d hari",M:"sebulan",MM:"%d bulan",y:"setahun",yy:"%d tahun"},week:{dow:1,doy:7}}),a.defineLocale("ms",{months:"Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember".split("_"),monthsShort:"Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis".split("_"),weekdays:"Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu".split("_"), weekdaysShort:"Ahd_Isn_Sel_Rab_Kha_Jum_Sab".split("_"),weekdaysMin:"Ah_Is_Sl_Rb_Km_Jm_Sb".split("_"),longDateFormat:{LT:"HH.mm",LTS:"HH.mm.ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY [pukul] HH.mm",LLLL:"dddd, D MMMM YYYY [pukul] HH.mm"},meridiemParse:/pagi|tengahari|petang|malam/,meridiemHour:function(a,b){return 12===a&&(a=0),"pagi"===b?a:"tengahari"===b?a>=11?a:a+12:"petang"===b||"malam"===b?a+12:void 0},meridiem:function(a,b,c){return 11>a?"pagi":15>a?"tengahari":19>a?"petang":"malam"},calendar:{sameDay:"[Hari ini pukul] LT",nextDay:"[Esok pukul] LT",nextWeek:"dddd [pukul] LT",lastDay:"[Kelmarin pukul] LT",lastWeek:"dddd [lepas pukul] LT",sameElse:"L"},relativeTime:{future:"dalam %s",past:"%s yang lepas",s:"beberapa saat",m:"seminit",mm:"%d minit",h:"sejam",hh:"%d jam",d:"sehari",dd:"%d hari",M:"sebulan",MM:"%d bulan",y:"setahun",yy:"%d tahun"},week:{dow:1,doy:7}}),{1:"၁",2:"၂",3:"၃",4:"၄",5:"၅",6:"၆",7:"၇",8:"၈",9:"၉",0:"၀"}),Na={"၁":"1","၂":"2","၃":"3","၄":"4","၅":"5","၆":"6","၇":"7","၈":"8","၉":"9","၀":"0"},Oa=(a.defineLocale("my",{months:"ဇန်နဝါရီ_ဖေဖော်ဝါရီ_မတ်_ဧပြီ_မေ_ဇွန်_ဇူလိုင်_သြဂုတ်_စက်တင်ဘာ_အောက်တိုဘာ_နိုဝင်ဘာ_ဒီဇင်ဘာ".split("_"),monthsShort:"ဇန်_ဖေ_မတ်_ပြီ_မေ_ဇွန်_လိုင်_သြ_စက်_အောက်_နို_ဒီ".split("_"),weekdays:"တနင်္ဂနွေ_တနင်္လာ_အင်္ဂါ_ဗုဒ္ဓဟူး_ကြာသပတေး_သောကြာ_စနေ".split("_"),weekdaysShort:"နွေ_လာ_ဂါ_ဟူး_ကြာ_သော_နေ".split("_"),weekdaysMin:"နွေ_လာ_ဂါ_ဟူး_ကြာ_သော_နေ".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[ယနေ.] LT [မှာ]",nextDay:"[မနက်ဖြန်] LT [မှာ]",nextWeek:"dddd LT [မှာ]",lastDay:"[မနေ.က] LT [မှာ]",lastWeek:"[ပြီးခဲ့သော] dddd LT [မှာ]",sameElse:"L"},relativeTime:{future:"လာမည့် %s မှာ",past:"လွန်ခဲ့သော %s က",s:"စက္ကန်.အနည်းငယ်",m:"တစ်မိနစ်",mm:"%d မိနစ်",h:"တစ်နာရီ",hh:"%d နာရီ",d:"တစ်ရက်",dd:"%d ရက်",M:"တစ်လ",MM:"%d လ",y:"တစ်နှစ်",yy:"%d နှစ်"},preparse:function(a){return a.replace(/[၁၂၃၄၅၆၇၈၉၀]/g,function(a){return Na[a]})},postformat:function(a){return a.replace(/\d/g,function(a){return Ma[a]})},week:{dow:1,doy:4}}),a.defineLocale("nb",{months:"januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember".split("_"),monthsShort:"jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"),weekdays:"søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag".split("_"),weekdaysShort:"søn_man_tirs_ons_tors_fre_lør".split("_"),weekdaysMin:"sø_ma_ti_on_to_fr_lø".split("_"),longDateFormat:{LT:"H.mm",LTS:"H.mm.ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY [kl.] H.mm",LLLL:"dddd D. MMMM YYYY [kl.] H.mm"},calendar:{sameDay:"[i dag kl.] LT",nextDay:"[i morgen kl.] LT",nextWeek:"dddd [kl.] LT",lastDay:"[i går kl.] LT",lastWeek:"[forrige] dddd [kl.] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"for %s siden",s:"noen sekunder",m:"ett minutt",mm:"%d minutter",h:"en time",hh:"%d timer",d:"en dag",dd:"%d dager",M:"en måned",MM:"%d måneder",y:"ett år",yy:"%d år"},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),{1:"१",2:"२",3:"३",4:"४",5:"५",6:"६",7:"७",8:"८",9:"९",0:"०"}),Pa={"१":"1","२":"2","३":"3","४":"4","५":"5","६":"6","७":"7","८":"8","९":"9","०":"0"},Qa=(a.defineLocale("ne",{months:"जनवरी_फेब्रुवरी_मार्च_अप्रिल_मई_जुन_जुलाई_अगष्ट_सेप्टेम्बर_अक्टोबर_नोभेम्बर_डिसेम्बर".split("_"),monthsShort:"जन._फेब्रु._मार्च_अप्रि._मई_जुन_जुलाई._अग._सेप्ट._अक्टो._नोभे._डिसे.".split("_"),weekdays:"आइतबार_सोमबार_मङ्गलबार_बुधबार_बिहिबार_शुक्रबार_शनिबार".split("_"),weekdaysShort:"आइत._सोम._मङ्गल._बुध._बिहि._शुक्र._शनि.".split("_"),weekdaysMin:"आइ._सो._मङ्_बु._बि._शु._श.".split("_"),longDateFormat:{LT:"Aको h:mm बजे",LTS:"Aको h:mm:ss बजे",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, Aको h:mm बजे",LLLL:"dddd, D MMMM YYYY, Aको h:mm बजे"},preparse:function(a){return a.replace(/[१२३४५६७८९०]/g,function(a){return Pa[a]})},postformat:function(a){return a.replace(/\d/g,function(a){return Oa[a]})},meridiemParse:/राती|बिहान|दिउँसो|बेलुका|साँझ|राती/,meridiemHour:function(a,b){return 12===a&&(a=0),"राती"===b?3>a?a:a+12:"बिहान"===b?a:"दिउँसो"===b?a>=10?a:a+12:"बेलुका"===b||"साँझ"===b?a+12:void 0},meridiem:function(a,b,c){return 3>a?"राती":10>a?"बिहान":15>a?"दिउँसो":18>a?"बेलुका":20>a?"साँझ":"राती"},calendar:{sameDay:"[आज] LT",nextDay:"[भोली] LT",nextWeek:"[आउँदो] dddd[,] LT",lastDay:"[हिजो] LT",lastWeek:"[गएको] dddd[,] LT",sameElse:"L"},relativeTime:{future:"%sमा",past:"%s अगाडी",s:"केही समय",m:"एक मिनेट",mm:"%d मिनेट",h:"एक घण्टा",hh:"%d घण्टा",d:"एक दिन",dd:"%d दिन",M:"एक महिना",MM:"%d महिना",y:"एक बर्ष",yy:"%d बर्ष"},week:{dow:1,doy:7}}),"jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.".split("_")),Ra="jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec".split("_"),Sa=(a.defineLocale("nl",{months:"januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december".split("_"),monthsShort:function(a,b){return/-MMM-/.test(b)?Ra[a.month()]:Qa[a.month()]},weekdays:"zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag".split("_"),weekdaysShort:"zo._ma._di._wo._do._vr._za.".split("_"),weekdaysMin:"Zo_Ma_Di_Wo_Do_Vr_Za".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD-MM-YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[vandaag om] LT",nextDay:"[morgen om] LT",nextWeek:"dddd [om] LT",lastDay:"[gisteren om] LT",lastWeek:"[afgelopen] dddd [om] LT",sameElse:"L"},relativeTime:{future:"over %s",past:"%s geleden",s:"een paar seconden",m:"één minuut",mm:"%d minuten",h:"één uur",hh:"%d uur",d:"één dag",dd:"%d dagen",M:"één maand",MM:"%d maanden",y:"één jaar",yy:"%d jaar"},ordinalParse:/\d{1,2}(ste|de)/,ordinal:function(a){return a+(1===a||8===a||a>=20?"ste":"de")},week:{dow:1,doy:4}}),a.defineLocale("nn",{months:"januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember".split("_"),monthsShort:"jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"),weekdays:"sundag_måndag_tysdag_onsdag_torsdag_fredag_laurdag".split("_"),weekdaysShort:"sun_mån_tys_ons_tor_fre_lau".split("_"),weekdaysMin:"su_må_ty_on_to_fr_lø".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[I dag klokka] LT",nextDay:"[I morgon klokka] LT",nextWeek:"dddd [klokka] LT",lastDay:"[I går klokka] LT",lastWeek:"[Føregåande] dddd [klokka] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"for %s sidan",s:"nokre sekund",m:"eit minutt",mm:"%d minutt",h:"ein time",hh:"%d timar",d:"ein dag",dd:"%d dagar",M:"ein månad",MM:"%d månader",y:"eit år",yy:"%d år"},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),"styczeń_luty_marzec_kwiecień_maj_czerwiec_lipiec_sierpień_wrzesień_październik_listopad_grudzień".split("_")),Ta="stycznia_lutego_marca_kwietnia_maja_czerwca_lipca_sierpnia_września_października_listopada_grudnia".split("_"),Ua=(a.defineLocale("pl",{months:function(a,b){return""===b?"("+Ta[a.month()]+"|"+Sa[a.month()]+")":/D MMMM/.test(b)?Ta[a.month()]:Sa[a.month()]},monthsShort:"sty_lut_mar_kwi_maj_cze_lip_sie_wrz_paź_lis_gru".split("_"),weekdays:"niedziela_poniedziałek_wtorek_środa_czwartek_piątek_sobota".split("_"),weekdaysShort:"nie_pon_wt_śr_czw_pt_sb".split("_"),weekdaysMin:"N_Pn_Wt_Śr_Cz_Pt_So".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[Dziś o] LT",nextDay:"[Jutro o] LT",nextWeek:"[W] dddd [o] LT",lastDay:"[Wczoraj o] LT",lastWeek:function(){switch(this.day()){case 0:return"[W zeszłą niedzielę o] LT";case 3:return"[W zeszłą środę o] LT";case 6:return"[W zeszłą sobotę o] LT";default:return"[W zeszły] dddd [o] LT"}},sameElse:"L"},relativeTime:{future:"za %s",past:"%s temu",s:"kilka sekund",m:S,mm:S,h:S,hh:S,d:"1 dzień",dd:"%d dni",M:"miesiąc",MM:S,y:"rok",yy:S},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),a.defineLocale("pt-br",{months:"Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro".split("_"),monthsShort:"Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez".split("_"),weekdays:"Domingo_Segunda-Feira_Terça-Feira_Quarta-Feira_Quinta-Feira_Sexta-Feira_Sábado".split("_"),weekdaysShort:"Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"),weekdaysMin:"Dom_2ª_3ª_4ª_5ª_6ª_Sáb".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D [de] MMMM [de] YYYY",LLL:"D [de] MMMM [de] YYYY [às] HH:mm",LLLL:"dddd, D [de] MMMM [de] YYYY [às] HH:mm"},calendar:{sameDay:"[Hoje às] LT",nextDay:"[Amanhã às] LT",nextWeek:"dddd [às] LT",lastDay:"[Ontem às] LT",lastWeek:function(){return 0===this.day()||6===this.day()?"[Último] dddd [às] LT":"[Última] dddd [às] LT"},sameElse:"L"},relativeTime:{future:"em %s",past:"%s atrás",s:"poucos segundos",m:"um minuto",mm:"%d minutos",h:"uma hora",hh:"%d horas",d:"um dia",dd:"%d dias",M:"um mês",MM:"%d meses",y:"um ano",yy:"%d anos"},ordinalParse:/\d{1,2}º/,ordinal:"%dº"}),a.defineLocale("pt",{months:"Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro".split("_"),monthsShort:"Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez".split("_"),weekdays:"Domingo_Segunda-Feira_Terça-Feira_Quarta-Feira_Quinta-Feira_Sexta-Feira_Sábado".split("_"),weekdaysShort:"Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"),weekdaysMin:"Dom_2ª_3ª_4ª_5ª_6ª_Sáb".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D [de] MMMM [de] YYYY",LLL:"D [de] MMMM [de] YYYY HH:mm",LLLL:"dddd, D [de] MMMM [de] YYYY HH:mm"},calendar:{sameDay:"[Hoje às] LT",nextDay:"[Amanhã às] LT",nextWeek:"dddd [às] LT",lastDay:"[Ontem às] LT",lastWeek:function(){return 0===this.day()||6===this.day()?"[Último] dddd [às] LT":"[Última] dddd [às] LT"},sameElse:"L"},relativeTime:{future:"em %s",past:"há %s",s:"segundos",m:"um minuto",mm:"%d minutos",h:"uma hora",hh:"%d horas",d:"um dia",dd:"%d dias",M:"um mês",MM:"%d meses",y:"um ano",yy:"%d anos"},ordinalParse:/\d{1,2}º/,ordinal:"%dº",week:{dow:1,doy:4}}),a.defineLocale("ro",{months:"ianuarie_februarie_martie_aprilie_mai_iunie_iulie_august_septembrie_octombrie_noiembrie_decembrie".split("_"),monthsShort:"ian._febr._mart._apr._mai_iun._iul._aug._sept._oct._nov._dec.".split("_"),weekdays:"duminică_luni_marți_miercuri_joi_vineri_sâmbătă".split("_"),weekdaysShort:"Dum_Lun_Mar_Mie_Joi_Vin_Sâm".split("_"),weekdaysMin:"Du_Lu_Ma_Mi_Jo_Vi_Sâ".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY H:mm",LLLL:"dddd, D MMMM YYYY H:mm"},calendar:{sameDay:"[azi la] LT",nextDay:"[mâine la] LT",nextWeek:"dddd [la] LT",lastDay:"[ieri la] LT",lastWeek:"[fosta] dddd [la] LT",sameElse:"L"},relativeTime:{future:"peste %s",past:"%s în urmă",s:"câteva secunde",m:"un minut",mm:T,h:"o oră",hh:T,d:"o zi",dd:T,M:"o lună",MM:T,y:"un an",yy:T},week:{dow:1,doy:7}}),a.defineLocale("ru",{months:W,monthsShort:X,weekdays:Y,weekdaysShort:"вс_пн_вт_ср_чт_пт_сб".split("_"),weekdaysMin:"вс_пн_вт_ср_чт_пт_сб".split("_"),monthsParse:[/^янв/i,/^фев/i,/^мар/i,/^апр/i,/^ма[й|я]/i,/^июн/i,/^июл/i,/^авг/i,/^сен/i,/^окт/i,/^ноя/i,/^дек/i],longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY г.",LLL:"D MMMM YYYY г., HH:mm",LLLL:"dddd, D MMMM YYYY г., HH:mm"},calendar:{sameDay:"[Сегодня в] LT",nextDay:"[Завтра в] LT",lastDay:"[Вчера в] LT",nextWeek:function(){return 2===this.day()?"[Во] dddd [в] LT":"[В] dddd [в] LT"},lastWeek:function(a){if(a.week()===this.week())return 2===this.day()?"[Во] dddd [в] LT":"[В] dddd [в] LT";switch(this.day()){case 0:return"[В прошлое] dddd [в] LT";case 1:case 2:case 4:return"[В прошлый] dddd [в] LT";case 3:case 5:case 6:return"[В прошлую] dddd [в] LT"}},sameElse:"L"},relativeTime:{future:"через %s",past:"%s назад",s:"несколько секунд",m:V,mm:V,h:"час",hh:V,d:"день",dd:V,M:"месяц",MM:V,y:"год",yy:V},meridiemParse:/ночи|утра|дня|вечера/i,isPM:function(a){return/^(дня|вечера)$/.test(a)},meridiem:function(a,b,c){return 4>a?"ночи":12>a?"утра":17>a?"дня":"вечера"},ordinalParse:/\d{1,2}-(й|го|я)/,ordinal:function(a,b){switch(b){case"M":case"d":case"DDD":return a+"-й";case"D":return a+"-го";case"w":case"W":return a+"-я";default:return a}},week:{dow:1,doy:7}}),a.defineLocale("si",{months:"ජනවාරි_පෙබරවාරි_මාර්තු_අප්‍රේල්_මැයි_ජූනි_ජූලි_අගෝස්තු_සැප්තැම්බර්_ඔක්තෝබර්_නොවැම්බර්_දෙසැම්බර්".split("_"),monthsShort:"ජන_පෙබ_මාර්_අප්_මැයි_ජූනි_ජූලි_අගෝ_සැප්_ඔක්_නොවැ_දෙසැ".split("_"),weekdays:"ඉරිදා_සඳුදා_අඟහරුවාදා_බදාදා_බ්‍රහස්පතින්දා_සිකුරාදා_සෙනසුරාදා".split("_"),weekdaysShort:"ඉරි_සඳු_අඟ_බදා_බ්‍රහ_සිකු_සෙන".split("_"),weekdaysMin:"ඉ_ස_අ_බ_බ්‍ර_සි_සෙ".split("_"),longDateFormat:{LT:"a h:mm",LTS:"a h:mm:ss",L:"YYYY/MM/DD",LL:"YYYY MMMM D",LLL:"YYYY MMMM D, a h:mm",LLLL:"YYYY MMMM D [වැනි] dddd, a h:mm:ss"},calendar:{sameDay:"[අද] LT[ට]",nextDay:"[හෙට] LT[ට]",nextWeek:"dddd LT[ට]",lastDay:"[ඊයේ] LT[ට]",lastWeek:"[පසුගිය] dddd LT[ට]",sameElse:"L"},relativeTime:{future:"%sකින්",past:"%sකට පෙර",s:"තත්පර කිහිපය",m:"මිනිත්තුව",mm:"මිනිත්තු %d",h:"පැය",hh:"පැය %d",d:"දිනය",dd:"දින %d",M:"මාසය",MM:"මාස %d",y:"වසර",yy:"වසර %d"},ordinalParse:/\d{1,2} වැනි/,ordinal:function(a){return a+" වැනි"},meridiem:function(a,b,c){return a>11?c?"ප.ව.":"පස් වරු":c?"පෙ.ව.":"පෙර වරු"}}),"január_február_marec_apríl_máj_jún_júl_august_september_október_november_december".split("_")),Va="jan_feb_mar_apr_máj_jún_júl_aug_sep_okt_nov_dec".split("_"),Wa=(a.defineLocale("sk",{months:Ua,monthsShort:Va,monthsParse:function(a,b){var c,d=[];for(c=0;12>c;c++)d[c]=new RegExp("^"+a[c]+"$|^"+b[c]+"$","i");return d}(Ua,Va),weekdays:"nedeľa_pondelok_utorok_streda_štvrtok_piatok_sobota".split("_"),weekdaysShort:"ne_po_ut_st_št_pi_so".split("_"),weekdaysMin:"ne_po_ut_st_št_pi_so".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd D. MMMM YYYY H:mm"},calendar:{sameDay:"[dnes o] LT",nextDay:"[zajtra o] LT",nextWeek:function(){switch(this.day()){case 0:return"[v nedeľu o] LT";case 1:case 2:return"[v] dddd [o] LT";case 3:return"[v stredu o] LT";case 4:return"[vo štvrtok o] LT";case 5:return"[v piatok o] LT";case 6:return"[v sobotu o] LT"}},lastDay:"[včera o] LT",lastWeek:function(){switch(this.day()){case 0:return"[minulú nedeľu o] LT";case 1:case 2:return"[minulý] dddd [o] LT";case 3:return"[minulú stredu o] LT";case 4:case 5:return"[minulý] dddd [o] LT";case 6:return"[minulú sobotu o] LT"}},sameElse:"L"},relativeTime:{future:"za %s",past:"pred %s",s:$,m:$,mm:$,h:$,hh:$,d:$,dd:$,M:$,MM:$,y:$,yy:$},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),a.defineLocale("sl",{months:"januar_februar_marec_april_maj_junij_julij_avgust_september_oktober_november_december".split("_"),monthsShort:"jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.".split("_"),weekdays:"nedelja_ponedeljek_torek_sreda_četrtek_petek_sobota".split("_"),weekdaysShort:"ned._pon._tor._sre._čet._pet._sob.".split("_"),weekdaysMin:"ne_po_to_sr_če_pe_so".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD. MM. YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd, D. MMMM YYYY H:mm"},calendar:{sameDay:"[danes ob] LT",nextDay:"[jutri ob] LT",nextWeek:function(){switch(this.day()){case 0:return"[v] [nedeljo] [ob] LT";case 3:return"[v] [sredo] [ob] LT";case 6:return"[v] [soboto] [ob] LT";case 1:case 2:case 4:case 5:return"[v] dddd [ob] LT"}},lastDay:"[včeraj ob] LT",lastWeek:function(){switch(this.day()){case 0:return"[prejšnjo] [nedeljo] [ob] LT";case 3:return"[prejšnjo] [sredo] [ob] LT";case 6:return"[prejšnjo] [soboto] [ob] LT";case 1:case 2:case 4:case 5:return"[prejšnji] dddd [ob] LT"}},sameElse:"L"},relativeTime:{future:"čez %s",past:"pred %s",s:_,m:_,mm:_,h:_,hh:_,d:_,dd:_,M:_,MM:_,y:_,yy:_},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:7}}),a.defineLocale("sq",{months:"Janar_Shkurt_Mars_Prill_Maj_Qershor_Korrik_Gusht_Shtator_Tetor_Nëntor_Dhjetor".split("_"),monthsShort:"Jan_Shk_Mar_Pri_Maj_Qer_Kor_Gus_Sht_Tet_Nën_Dhj".split("_"),weekdays:"E Diel_E Hënë_E Martë_E Mërkurë_E Enjte_E Premte_E Shtunë".split("_"),weekdaysShort:"Die_Hën_Mar_Mër_Enj_Pre_Sht".split("_"),weekdaysMin:"D_H_Ma_Më_E_P_Sh".split("_"),meridiemParse:/PD|MD/,isPM:function(a){return"M"===a.charAt(0)},meridiem:function(a,b,c){return 12>a?"PD":"MD"},longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[Sot në] LT",nextDay:"[Nesër në] LT",nextWeek:"dddd [në] LT",lastDay:"[Dje në] LT",lastWeek:"dddd [e kaluar në] LT",sameElse:"L"},relativeTime:{future:"në %s",past:"%s më parë",s:"disa sekonda",m:"një minutë",mm:"%d minuta",h:"një orë",hh:"%d orë",d:"një ditë",dd:"%d ditë",M:"një muaj",MM:"%d muaj",y:"një vit",yy:"%d vite"},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),{words:{m:["један минут","једне минуте"],mm:["минут","минуте","минута"],h:["један сат","једног сата"],hh:["сат","сата","сати"],dd:["дан","дана","дана"],MM:["месец","месеца","месеци"],yy:["година","године","година"]},correctGrammaticalCase:function(a,b){return 1===a?b[0]:a>=2&&4>=a?b[1]:b[2]},translate:function(a,b,c){var d=Wa.words[c];return 1===c.length?b?d[0]:d[1]:a+" "+Wa.correctGrammaticalCase(a,d)}}),Xa=(a.defineLocale("sr-cyrl",{months:["јануар","фебруар","март","април","мај","јун","јул","август","септембар","октобар","новембар","децембар"],monthsShort:["јан.","феб.","мар.","апр.","мај","јун","јул","авг.","сеп.","окт.","нов.","дец."],weekdays:["недеља","понедељак","уторак","среда","четвртак","петак","субота"],weekdaysShort:["нед.","пон.","уто.","сре.","чет.","пет.","суб."],weekdaysMin:["не","по","ут","ср","че","пе","су"],longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD. MM. YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd, D. MMMM YYYY H:mm"},calendar:{sameDay:"[данас у] LT",nextDay:"[сутра у] LT",nextWeek:function(){switch(this.day()){case 0:return"[у] [недељу] [у] LT";case 3:return"[у] [среду] [у] LT";case 6:return"[у] [суботу] [у] LT";case 1:case 2:case 4:case 5:return"[у] dddd [у] LT"}},lastDay:"[јуче у] LT",lastWeek:function(){var a=["[прошле] [недеље] [у] LT","[прошлог] [понедељка] [у] LT","[прошлог] [уторка] [у] LT","[прошле] [среде] [у] LT","[прошлог] [четвртка] [у] LT","[прошлог] [петка] [у] LT","[прошле] [суботе] [у] LT"];return a[this.day()]},sameElse:"L"},relativeTime:{future:"за %s",past:"пре %s",s:"неколико секунди",m:Wa.translate,mm:Wa.translate,h:Wa.translate,hh:Wa.translate,d:"дан",dd:Wa.translate,M:"месец",MM:Wa.translate,y:"годину",yy:Wa.translate},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:7}}),{words:{m:["jedan minut","jedne minute"],mm:["minut","minute","minuta"],h:["jedan sat","jednog sata"],hh:["sat","sata","sati"],dd:["dan","dana","dana"],MM:["mesec","meseca","meseci"],yy:["godina","godine","godina"]},correctGrammaticalCase:function(a,b){return 1===a?b[0]:a>=2&&4>=a?b[1]:b[2]},translate:function(a,b,c){var d=Xa.words[c];return 1===c.length?b?d[0]:d[1]:a+" "+Xa.correctGrammaticalCase(a,d)}}),Ya=(a.defineLocale("sr",{months:["januar","februar","mart","april","maj","jun","jul","avgust","septembar","oktobar","novembar","decembar"],monthsShort:["jan.","feb.","mar.","apr.","maj","jun","jul","avg.","sep.","okt.","nov.","dec."],weekdays:["nedelja","ponedeljak","utorak","sreda","četvrtak","petak","subota"],weekdaysShort:["ned.","pon.","uto.","sre.","čet.","pet.","sub."],weekdaysMin:["ne","po","ut","sr","če","pe","su"],longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD. MM. YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd, D. MMMM YYYY H:mm"},calendar:{sameDay:"[danas u] LT",nextDay:"[sutra u] LT",nextWeek:function(){switch(this.day()){case 0:return"[u] [nedelju] [u] LT";case 3:return"[u] [sredu] [u] LT";case 6:return"[u] [subotu] [u] LT";case 1:case 2:case 4:case 5:return"[u] dddd [u] LT"}},lastDay:"[juče u] LT",lastWeek:function(){var a=["[prošle] [nedelje] [u] LT","[prošlog] [ponedeljka] [u] LT","[prošlog] [utorka] [u] LT","[prošle] [srede] [u] LT","[prošlog] [četvrtka] [u] LT","[prošlog] [petka] [u] LT","[prošle] [subote] [u] LT"];return a[this.day()]},sameElse:"L"},relativeTime:{future:"za %s",past:"pre %s",s:"nekoliko sekundi",m:Xa.translate,mm:Xa.translate,h:Xa.translate,hh:Xa.translate,d:"dan",dd:Xa.translate,M:"mesec",MM:Xa.translate,y:"godinu",yy:Xa.translate},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:7}}),a.defineLocale("sv",{months:"januari_februari_mars_april_maj_juni_juli_augusti_september_oktober_november_december".split("_"),monthsShort:"jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec".split("_"),weekdays:"söndag_måndag_tisdag_onsdag_torsdag_fredag_lördag".split("_"),weekdaysShort:"sön_mån_tis_ons_tor_fre_lör".split("_"),weekdaysMin:"sö_må_ti_on_to_fr_lö".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY-MM-DD",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[Idag] LT",nextDay:"[Imorgon] LT",lastDay:"[Igår] LT",nextWeek:"[På] dddd LT",lastWeek:"[I] dddd[s] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"för %s sedan",s:"några sekunder",m:"en minut",mm:"%d minuter",h:"en timme",hh:"%d timmar",d:"en dag",dd:"%d dagar",M:"en månad",MM:"%d månader",y:"ett år",yy:"%d år"},ordinalParse:/\d{1,2}(e|a)/,ordinal:function(a){var b=a%10,c=1===~~(a%100/10)?"e":1===b?"a":2===b?"a":"e";return a+c},week:{dow:1,doy:4}}),a.defineLocale("ta",{months:"ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்".split("_"),monthsShort:"ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்".split("_"),weekdays:"ஞாயிற்றுக்கிழமை_திங்கட்கிழமை_செவ்வாய்கிழமை_புதன்கிழமை_வியாழக்கிழமை_வெள்ளிக்கிழமை_சனிக்கிழமை".split("_"),weekdaysShort:"ஞாயிறு_திங்கள்_செவ்வாய்_புதன்_வியாழன்_வெள்ளி_சனி".split("_"),weekdaysMin:"ஞா_தி_செ_பு_வி_வெ_ச".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, HH:mm",LLLL:"dddd, D MMMM YYYY, HH:mm"},calendar:{sameDay:"[இன்று] LT",nextDay:"[நாளை] LT",nextWeek:"dddd, LT",lastDay:"[நேற்று] LT",lastWeek:"[கடந்த வாரம்] dddd, LT",sameElse:"L"},relativeTime:{future:"%s இல்",past:"%s முன்",s:"ஒரு சில விநாடிகள்",m:"ஒரு நிமிடம்",mm:"%d நிமிடங்கள்",h:"ஒரு மணி நேரம்",hh:"%d மணி நேரம்",d:"ஒரு நாள்",dd:"%d நாட்கள்",M:"ஒரு மாதம்",MM:"%d மாதங்கள்",y:"ஒரு வருடம்",yy:"%d ஆண்டுகள்"},ordinalParse:/\d{1,2}வது/,ordinal:function(a){return a+"வது"},meridiemParse:/யாமம்|வைகறை|காலை|நண்பகல்|எற்பாடு|மாலை/,meridiem:function(a,b,c){return 2>a?" யாமம்":6>a?" வைகறை":10>a?" காலை":14>a?" நண்பகல்":18>a?" எற்பாடு":22>a?" மாலை":" யாமம்"},meridiemHour:function(a,b){return 12===a&&(a=0),"யாமம்"===b?2>a?a:a+12:"வைகறை"===b||"காலை"===b?a:"நண்பகல்"===b&&a>=10?a:a+12},week:{dow:0,doy:6}}),a.defineLocale("th",{months:"มกราคม_กุมภาพันธ์_มีนาคม_เมษายน_พฤษภาคม_มิถุนายน_กรกฎาคม_สิงหาคม_กันยายน_ตุลาคม_พฤศจิกายน_ธันวาคม".split("_"),monthsShort:"มกรา_กุมภา_มีนา_เมษา_พฤษภา_มิถุนา_กรกฎา_สิงหา_กันยา_ตุลา_พฤศจิกา_ธันวา".split("_"),weekdays:"อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัสบดี_ศุกร์_เสาร์".split("_"),weekdaysShort:"อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัส_ศุกร์_เสาร์".split("_"),weekdaysMin:"อา._จ._อ._พ._พฤ._ศ._ส.".split("_"),longDateFormat:{LT:"H นาฬิกา m นาที",LTS:"H นาฬิกา m นาที s วินาที",L:"YYYY/MM/DD",LL:"D MMMM YYYY",LLL:"D MMMM YYYY เวลา H นาฬิกา m นาที",LLLL:"วันddddที่ D MMMM YYYY เวลา H นาฬิกา m นาที"},meridiemParse:/ก่อนเที่ยง|หลังเที่ยง/,isPM:function(a){return"หลังเที่ยง"===a},meridiem:function(a,b,c){return 12>a?"ก่อนเที่ยง":"หลังเที่ยง"},calendar:{sameDay:"[วันนี้ เวลา] LT",nextDay:"[พรุ่งนี้ เวลา] LT",nextWeek:"dddd[หน้า เวลา] LT",lastDay:"[เมื่อวานนี้ เวลา] LT",lastWeek:"[วัน]dddd[ที่แล้ว เวลา] LT",sameElse:"L"},relativeTime:{future:"อีก %s",past:"%sที่แล้ว",s:"ไม่กี่วินาที",m:"1 นาที",mm:"%d นาที",h:"1 ชั่วโมง",hh:"%d ชั่วโมง",d:"1 วัน",dd:"%d วัน",M:"1 เดือน",MM:"%d เดือน",y:"1 ปี",yy:"%d ปี"}}),a.defineLocale("tl-ph",{months:"Enero_Pebrero_Marso_Abril_Mayo_Hunyo_Hulyo_Agosto_Setyembre_Oktubre_Nobyembre_Disyembre".split("_"),monthsShort:"Ene_Peb_Mar_Abr_May_Hun_Hul_Ago_Set_Okt_Nob_Dis".split("_"),weekdays:"Linggo_Lunes_Martes_Miyerkules_Huwebes_Biyernes_Sabado".split("_"),weekdaysShort:"Lin_Lun_Mar_Miy_Huw_Biy_Sab".split("_"),weekdaysMin:"Li_Lu_Ma_Mi_Hu_Bi_Sab".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"MM/D/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY HH:mm",LLLL:"dddd, MMMM DD, YYYY HH:mm"},calendar:{sameDay:"[Ngayon sa] LT",nextDay:"[Bukas sa] LT",nextWeek:"dddd [sa] LT",lastDay:"[Kahapon sa] LT",lastWeek:"dddd [huling linggo] LT",sameElse:"L"},relativeTime:{future:"sa loob ng %s",past:"%s ang nakalipas",s:"ilang segundo",m:"isang minuto",mm:"%d minuto",h:"isang oras",hh:"%d oras",d:"isang araw",dd:"%d araw",M:"isang buwan",MM:"%d buwan",y:"isang taon",yy:"%d taon"},ordinalParse:/\d{1,2}/,ordinal:function(a){return a},week:{dow:1,doy:4}}),{1:"'inci",5:"'inci",8:"'inci",70:"'inci",80:"'inci",2:"'nci",7:"'nci",20:"'nci",50:"'nci",3:"'üncü",4:"'üncü",100:"'üncü",6:"'ncı",9:"'uncu",10:"'uncu",30:"'uncu",60:"'ıncı",90:"'ıncı"});a.defineLocale("tr",{months:"Ocak_Şubat_Mart_Nisan_Mayıs_Haziran_Temmuz_Ağustos_Eylül_Ekim_Kasım_Aralık".split("_"),monthsShort:"Oca_Şub_Mar_Nis_May_Haz_Tem_Ağu_Eyl_Eki_Kas_Ara".split("_"),weekdays:"Pazar_Pazartesi_Salı_Çarşamba_Perşembe_Cuma_Cumartesi".split("_"),weekdaysShort:"Paz_Pts_Sal_Çar_Per_Cum_Cts".split("_"),weekdaysMin:"Pz_Pt_Sa_Ça_Pe_Cu_Ct".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[bugün saat] LT",nextDay:"[yarın saat] LT",nextWeek:"[haftaya] dddd [saat] LT",lastDay:"[dün] LT",lastWeek:"[geçen hafta] dddd [saat] LT",sameElse:"L"},relativeTime:{future:"%s sonra",past:"%s önce",s:"birkaç saniye",m:"bir dakika",mm:"%d dakika",h:"bir saat",hh:"%d saat",d:"bir gün",dd:"%d gün",M:"bir ay",MM:"%d ay",y:"bir yıl",yy:"%d yıl"},ordinalParse:/\d{1,2}'(inci|nci|üncü|ncı|uncu|ıncı)/,ordinal:function(a){if(0===a)return a+"'ıncı";var b=a%10,c=a%100-b,d=a>=100?100:null;return a+(Ya[b]||Ya[c]||Ya[d])},week:{dow:1,doy:7}}),a.defineLocale("tzl",{months:"Januar_Fevraglh_Març_Avrïu_Mai_Gün_Julia_Guscht_Setemvar_Listopäts_Noemvar_Zecemvar".split("_"),monthsShort:"Jan_Fev_Mar_Avr_Mai_Gün_Jul_Gus_Set_Lis_Noe_Zec".split("_"),weekdays:"Súladi_Lúneçi_Maitzi_Márcuri_Xhúadi_Viénerçi_Sáturi".split("_"),weekdaysShort:"Súl_Lún_Mai_Már_Xhú_Vié_Sát".split("_"),weekdaysMin:"Sú_Lú_Ma_Má_Xh_Vi_Sá".split("_"),longDateFormat:{LT:"HH.mm",LTS:"LT.ss",L:"DD.MM.YYYY",LL:"D. MMMM [dallas] YYYY",LLL:"D. MMMM [dallas] YYYY LT",LLLL:"dddd, [li] D. MMMM [dallas] YYYY LT"},meridiem:function(a,b,c){return a>11?c?"d'o":"D'O":c?"d'a":"D'A"},calendar:{sameDay:"[oxhi à] LT",nextDay:"[demà à] LT",nextWeek:"dddd [à] LT",lastDay:"[ieiri à] LT",lastWeek:"[sür el] dddd [lasteu à] LT",sameElse:"L"},relativeTime:{future:"osprei %s",past:"ja%s",s:aa,m:aa,mm:aa,h:aa,hh:aa,d:aa,dd:aa,M:aa,MM:aa,y:aa,yy:aa},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),a.defineLocale("tzm-latn",{months:"innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir".split("_"),monthsShort:"innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir".split("_"),weekdays:"asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas".split("_"),weekdaysShort:"asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas".split("_"),weekdaysMin:"asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[asdkh g] LT",nextDay:"[aska g] LT",nextWeek:"dddd [g] LT",lastDay:"[assant g] LT",lastWeek:"dddd [g] LT",sameElse:"L"},relativeTime:{future:"dadkh s yan %s",past:"yan %s",s:"imik",m:"minuḍ",mm:"%d minuḍ",h:"saɛa",hh:"%d tassaɛin",d:"ass",dd:"%d ossan",M:"ayowr",MM:"%d iyyirn",y:"asgas",yy:"%d isgasn"},week:{dow:6,doy:12}}),a.defineLocale("tzm",{months:"ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ".split("_"),monthsShort:"ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ".split("_"),weekdays:"ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ".split("_"),weekdaysShort:"ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ".split("_"),weekdaysMin:"ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[ⴰⵙⴷⵅ ⴴ] LT",nextDay:"[ⴰⵙⴽⴰ ⴴ] LT",nextWeek:"dddd [ⴴ] LT",lastDay:"[ⴰⵚⴰⵏⵜ ⴴ] LT",lastWeek:"dddd [ⴴ] LT",sameElse:"L"},relativeTime:{future:"ⴷⴰⴷⵅ ⵙ ⵢⴰⵏ %s",past:"ⵢⴰⵏ %s",s:"ⵉⵎⵉⴽ",m:"ⵎⵉⵏⵓⴺ",mm:"%d ⵎⵉⵏⵓⴺ",h:"ⵙⴰⵄⴰ",hh:"%d ⵜⴰⵙⵙⴰⵄⵉⵏ",d:"ⴰⵙⵙ",dd:"%d oⵙⵙⴰⵏ",M:"ⴰⵢoⵓⵔ",MM:"%d ⵉⵢⵢⵉⵔⵏ",y:"ⴰⵙⴳⴰⵙ",yy:"%d ⵉⵙⴳⴰⵙⵏ"},week:{dow:6,doy:12}}),a.defineLocale("uk",{months:da,monthsShort:"січ_лют_бер_квіт_трав_черв_лип_серп_вер_жовт_лист_груд".split("_"),weekdays:ea,weekdaysShort:"нд_пн_вт_ср_чт_пт_сб".split("_"),weekdaysMin:"нд_пн_вт_ср_чт_пт_сб".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY р.",LLL:"D MMMM YYYY р., HH:mm",LLLL:"dddd, D MMMM YYYY р., HH:mm"},calendar:{sameDay:fa("[Сьогодні "),nextDay:fa("[Завтра "),lastDay:fa("[Вчора "),nextWeek:fa("[У] dddd ["),lastWeek:function(){switch(this.day()){case 0:case 3:case 5:case 6:return fa("[Минулої] dddd [").call(this);case 1:case 2:case 4:return fa("[Минулого] dddd [").call(this)}},sameElse:"L"},relativeTime:{future:"за %s",past:"%s тому",s:"декілька секунд",m:ca,mm:ca,h:"годину",hh:ca,d:"день",dd:ca,M:"місяць",MM:ca,y:"рік",yy:ca},meridiemParse:/ночі|ранку|дня|вечора/,isPM:function(a){return/^(дня|вечора)$/.test(a)},meridiem:function(a,b,c){return 4>a?"ночі":12>a?"ранку":17>a?"дня":"вечора"},ordinalParse:/\d{1,2}-(й|го)/,ordinal:function(a,b){switch(b){case"M":case"d":case"DDD":case"w":case"W":return a+"-й";case"D":return a+"-го";default:return a}},week:{dow:1,doy:7}}),a.defineLocale("uz",{months:"январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь".split("_"),monthsShort:"янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек".split("_"),weekdays:"Якшанба_Душанба_Сешанба_Чоршанба_Пайшанба_Жума_Шанба".split("_"),weekdaysShort:"Якш_Душ_Сеш_Чор_Пай_Жум_Шан".split("_"),weekdaysMin:"Як_Ду_Се_Чо_Па_Жу_Ша".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"D MMMM YYYY, dddd HH:mm"},calendar:{sameDay:"[Бугун соат] LT [да]",nextDay:"[Эртага] LT [да]",nextWeek:"dddd [куни соат] LT [да]",lastDay:"[Кеча соат] LT [да]",lastWeek:"[Утган] dddd [куни соат] LT [да]",sameElse:"L"},relativeTime:{future:"Якин %s ичида",past:"Бир неча %s олдин",s:"фурсат",m:"бир дакика",mm:"%d дакика",h:"бир соат",hh:"%d соат",d:"бир кун",dd:"%d кун",M:"бир ой",MM:"%d ой",y:"бир йил",yy:"%d йил"},week:{dow:1,doy:7}}),a.defineLocale("vi",{months:"tháng 1_tháng 2_tháng 3_tháng 4_tháng 5_tháng 6_tháng 7_tháng 8_tháng 9_tháng 10_tháng 11_tháng 12".split("_"),monthsShort:"Th01_Th02_Th03_Th04_Th05_Th06_Th07_Th08_Th09_Th10_Th11_Th12".split("_"),weekdays:"chủ nhật_thứ hai_thứ ba_thứ tư_thứ năm_thứ sáu_thứ bảy".split("_"),weekdaysShort:"CN_T2_T3_T4_T5_T6_T7".split("_"),weekdaysMin:"CN_T2_T3_T4_T5_T6_T7".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM [năm] YYYY",LLL:"D MMMM [năm] YYYY HH:mm",LLLL:"dddd, D MMMM [năm] YYYY HH:mm",l:"DD/M/YYYY",ll:"D MMM YYYY",lll:"D MMM YYYY HH:mm",llll:"ddd, D MMM YYYY HH:mm"},calendar:{sameDay:"[Hôm nay lúc] LT",nextDay:"[Ngày mai lúc] LT",nextWeek:"dddd [tuần tới lúc] LT",lastDay:"[Hôm qua lúc] LT",lastWeek:"dddd [tuần rồi lúc] LT",sameElse:"L"},relativeTime:{future:"%s tới",past:"%s trước",s:"vài giây",m:"một phút",mm:"%d phút",h:"một giờ",hh:"%d giờ",d:"một ngày",dd:"%d ngày",M:"một tháng",MM:"%d tháng",y:"một năm",yy:"%d năm"},ordinalParse:/\d{1,2}/,ordinal:function(a){return a},week:{dow:1,doy:4}}),a.defineLocale("zh-cn",{months:"一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"), weekdays:"星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"),weekdaysShort:"周日_周一_周二_周三_周四_周五_周六".split("_"),weekdaysMin:"日_一_二_三_四_五_六".split("_"),longDateFormat:{LT:"Ah点mm分",LTS:"Ah点m分s秒",L:"YYYY-MM-DD",LL:"YYYY年MMMD日",LLL:"YYYY年MMMD日Ah点mm分",LLLL:"YYYY年MMMD日ddddAh点mm分",l:"YYYY-MM-DD",ll:"YYYY年MMMD日",lll:"YYYY年MMMD日Ah点mm分",llll:"YYYY年MMMD日ddddAh点mm分"},meridiemParse:/凌晨|早上|上午|中午|下午|晚上/,meridiemHour:function(a,b){return 12===a&&(a=0),"凌晨"===b||"早上"===b||"上午"===b?a:"下午"===b||"晚上"===b?a+12:a>=11?a:a+12},meridiem:function(a,b,c){var d=100*a+b;return 600>d?"凌晨":900>d?"早上":1130>d?"上午":1230>d?"中午":1800>d?"下午":"晚上"},calendar:{sameDay:function(){return 0===this.minutes()?"[今天]Ah[点整]":"[今天]LT"},nextDay:function(){return 0===this.minutes()?"[明天]Ah[点整]":"[明天]LT"},lastDay:function(){return 0===this.minutes()?"[昨天]Ah[点整]":"[昨天]LT"},nextWeek:function(){var b,c;return b=a().startOf("week"),c=this.unix()-b.unix()>=604800?"[下]":"[本]",0===this.minutes()?c+"dddAh点整":c+"dddAh点mm"},lastWeek:function(){var b,c;return b=a().startOf("week"),c=this.unix()<b.unix()?"[上]":"[本]",0===this.minutes()?c+"dddAh点整":c+"dddAh点mm"},sameElse:"LL"},ordinalParse:/\d{1,2}(日|月|周)/,ordinal:function(a,b){switch(b){case"d":case"D":case"DDD":return a+"日";case"M":return a+"月";case"w":case"W":return a+"周";default:return a}},relativeTime:{future:"%s内",past:"%s前",s:"几秒",m:"1 分钟",mm:"%d 分钟",h:"1 小时",hh:"%d 小时",d:"1 天",dd:"%d 天",M:"1 个月",MM:"%d 个月",y:"1 年",yy:"%d 年"},week:{dow:1,doy:4}}),a.defineLocale("zh-tw",{months:"一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"),weekdaysShort:"週日_週一_週二_週三_週四_週五_週六".split("_"),weekdaysMin:"日_一_二_三_四_五_六".split("_"),longDateFormat:{LT:"Ah點mm分",LTS:"Ah點m分s秒",L:"YYYY年MMMD日",LL:"YYYY年MMMD日",LLL:"YYYY年MMMD日Ah點mm分",LLLL:"YYYY年MMMD日ddddAh點mm分",l:"YYYY年MMMD日",ll:"YYYY年MMMD日",lll:"YYYY年MMMD日Ah點mm分",llll:"YYYY年MMMD日ddddAh點mm分"},meridiemParse:/早上|上午|中午|下午|晚上/,meridiemHour:function(a,b){return 12===a&&(a=0),"早上"===b||"上午"===b?a:"中午"===b?a>=11?a:a+12:"下午"===b||"晚上"===b?a+12:void 0},meridiem:function(a,b,c){var d=100*a+b;return 900>d?"早上":1130>d?"上午":1230>d?"中午":1800>d?"下午":"晚上"},calendar:{sameDay:"[今天]LT",nextDay:"[明天]LT",nextWeek:"[下]ddddLT",lastDay:"[昨天]LT",lastWeek:"[上]ddddLT",sameElse:"L"},ordinalParse:/\d{1,2}(日|月|週)/,ordinal:function(a,b){switch(b){case"d":case"D":case"DDD":return a+"日";case"M":return a+"月";case"w":case"W":return a+"週";default:return a}},relativeTime:{future:"%s內",past:"%s前",s:"幾秒",m:"一分鐘",mm:"%d分鐘",h:"一小時",hh:"%d小時",d:"一天",dd:"%d天",M:"一個月",MM:"%d個月",y:"一年",yy:"%d年"}})});
gholevas/mongomulch
assets/plugins/moment/min/locales.min.js
JavaScript
cc0-1.0
135,173
// Load modules var Url = require('url'); var Code = require('code'); var Hawk = require('../lib'); var Lab = require('lab'); // Declare internals var internals = {}; // Test shortcuts var lab = exports.lab = Lab.script(); var describe = lab.experiment; var it = lab.test; var expect = Code.expect; describe('Hawk', function () { var credentialsFunc = function (id, callback) { var credentials = { id: id, key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', algorithm: (id === '1' ? 'sha1' : 'sha256'), user: 'steve' }; return callback(null, credentials); }; it('generates a header then successfully parse it (configuration)', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials1) { req.authorization = Hawk.client.header(Url.parse('http://example.com:8080/resource/4?filter=a'), req.method, { credentials: credentials1, ext: 'some-app-data' }).field; expect(req.authorization).to.exist(); Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); done(); }); }); }); it('generates a header then successfully parse it (node request)', function (done) { var req = { method: 'POST', url: '/resource/4?filter=a', headers: { host: 'example.com:8080', 'content-type': 'text/plain;x=y' } }; var payload = 'some not so random text'; credentialsFunc('123456', function (err, credentials1) { var reqHeader = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] }); req.headers.authorization = reqHeader.field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true); var res = { headers: { 'content-type': 'text/plain' } }; res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' }); expect(res.headers['server-authorization']).to.exist(); expect(Hawk.client.authenticate(res, credentials2, artifacts, { payload: 'some reply' })).to.equal(true); done(); }); }); }); it('generates a header then successfully parse it (absolute request uri)', function (done) { var req = { method: 'POST', url: 'http://example.com:8080/resource/4?filter=a', headers: { host: 'example.com:8080', 'content-type': 'text/plain;x=y' } }; var payload = 'some not so random text'; credentialsFunc('123456', function (err, credentials1) { var reqHeader = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] }); req.headers.authorization = reqHeader.field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true); var res = { headers: { 'content-type': 'text/plain' } }; res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' }); expect(res.headers['server-authorization']).to.exist(); expect(Hawk.client.authenticate(res, credentials2, artifacts, { payload: 'some reply' })).to.equal(true); done(); }); }); }); it('generates a header then successfully parse it (no server header options)', function (done) { var req = { method: 'POST', url: '/resource/4?filter=a', headers: { host: 'example.com:8080', 'content-type': 'text/plain;x=y' } }; var payload = 'some not so random text'; credentialsFunc('123456', function (err, credentials1) { var reqHeader = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] }); req.headers.authorization = reqHeader.field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true); var res = { headers: { 'content-type': 'text/plain' } }; res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts); expect(res.headers['server-authorization']).to.exist(); expect(Hawk.client.authenticate(res, credentials2, artifacts)).to.equal(true); done(); }); }); }); it('generates a header then fails to parse it (missing server header hash)', function (done) { var req = { method: 'POST', url: '/resource/4?filter=a', headers: { host: 'example.com:8080', 'content-type': 'text/plain;x=y' } }; var payload = 'some not so random text'; credentialsFunc('123456', function (err, credentials1) { var reqHeader = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] }); req.headers.authorization = reqHeader.field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true); var res = { headers: { 'content-type': 'text/plain' } }; res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts); expect(res.headers['server-authorization']).to.exist(); expect(Hawk.client.authenticate(res, credentials2, artifacts, { payload: 'some reply' })).to.equal(false); done(); }); }); }); it('generates a header then successfully parse it (with hash)', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials1) { req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, payload: 'hola!', ext: 'some-app-data' }).field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); done(); }); }); }); it('generates a header then successfully parse it then validate payload', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials1) { req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, payload: 'hola!', ext: 'some-app-data' }).field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(Hawk.server.authenticatePayload('hola!', credentials2, artifacts)).to.be.true(); expect(Hawk.server.authenticatePayload('hello!', credentials2, artifacts)).to.be.false(); done(); }); }); }); it('generates a header then successfully parses and validates payload', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials1) { req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, payload: 'hola!', ext: 'some-app-data' }).field; Hawk.server.authenticate(req, credentialsFunc, { payload: 'hola!' }, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); done(); }); }); }); it('generates a header then successfully parse it (app)', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials1) { req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', app: 'asd23ased' }).field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(artifacts.app).to.equal('asd23ased'); done(); }); }); }); it('generates a header then successfully parse it (app, dlg)', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials1) { req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', app: 'asd23ased', dlg: '23434szr3q4d' }).field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(artifacts.app).to.equal('asd23ased'); expect(artifacts.dlg).to.equal('23434szr3q4d'); done(); }); }); }); it('generates a header then fail authentication due to bad hash', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials1) { req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, payload: 'hola!', ext: 'some-app-data' }).field; Hawk.server.authenticate(req, credentialsFunc, { payload: 'byebye!' }, function (err, credentials2, artifacts) { expect(err).to.exist(); expect(err.output.payload.message).to.equal('Bad payload hash'); done(); }); }); }); it('generates a header for one resource then fail to authenticate another', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials1) { req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data' }).field; req.url = '/something/else'; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.exist(); expect(credentials2).to.exist(); done(); }); }); }); });
margaretgodowns/gulp-practice
node_modules/hawk/test/index.js
JavaScript
cc0-1.0
14,472
/** * Copyright (c) 2016 committers of YAKINDU and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * committers of YAKINDU - initial API and implementation */ package org.yakindu.sct.generator.core.library; /** * * @author andreas muelder - Initial contribution and API * */ public interface ICoreLibraryConstants { String LIBRARY_NAME = "Core"; String OUTLET_FEATURE = "Outlet"; String OUTLET_FEATURE_TARGET_PROJECT = "targetProject"; String OUTLET_FEATURE_TARGET_FOLDER = "targetFolder"; String OUTLET_FEATURE_LIBRARY_TARGET_FOLDER = "libraryTargetFolder"; String OUTLET_FEATURE_API_TARGET_FOLDER = "apiTargetFolder"; String OUTLET_FEATURE_SKIP_LIBRARY_FILES = "skipLibraryFiles"; String LICENSE_HEADER = "LicenseHeader"; String LICENSE_TEXT = "licenseText"; String LICENSE_STANDARD_TEXT = "/** Generated by YAKINDU Statechart Tools code generator. */"; String DEBUG_FEATURE = "Debug"; String DEBUG_FEATURE_DUMP_SEXEC = "dumpSexec"; String FUNCTION_INLINING_FEATURE = "FunctionInlining"; String FUNCTION_INLINING_FEATURE_INLINE_REACTIONS = "inlineReactions"; String FUNCTION_INLINING_FEATURE_INLINE_ENTRY_ACTIONS = "inlineEntryActions"; String FUNCTION_INLINING_FEATURE_INLINE_ENTER_SEQUENCES = "inlineEnterSequences"; String FUNCTION_INLINING_FEATURE_INLINE_EXIT_ACTIONS = "inlineExitActions"; String FUNCTION_INLINING_FEATURE_INLINE_EXIT_SEQUENCES = "inlineExitSequences"; String FUNCTION_INLINING_FEATURE_INLINE_CHOICES = "inlineChoices"; String FUNCTION_INLINING_FEATURE_INLINE_ENTRIES = "inlineEntries"; String FUNCTION_INLINING_FEATURE_INLINE_ENTER_REGION = "inlineEnterRegion"; String FUNCTION_INLINING_FEATURE_INLINE_EXIT_REGION = "inlineExitRegion"; }
Yakindu/statecharts
plugins/org.yakindu.sct.generator.core/src/org/yakindu/sct/generator/core/library/ICoreLibraryConstants.java
Java
epl-1.0
1,929
/******************************************************************************* * Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.testing.oxm.inheritance.typetests; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.eclipse.persistence.testing.oxm.inheritance.typetests.any.ContactAsAnyNestedTestCases; import org.eclipse.persistence.testing.oxm.inheritance.typetests.any.collection.ContactsAsAnyNestedTestCases; import org.eclipse.persistence.testing.oxm.inheritance.typetests.compositecollection.AddressesAsNestedNoRefClassTestCases; import org.eclipse.persistence.testing.oxm.inheritance.typetests.compositecollection.AddressesAsNestedTestCases; import org.eclipse.persistence.testing.oxm.inheritance.typetests.compositecollection.AddressesAsNestedWithCdnAddressNoDefaultRootTypeXsiTestsCases; import org.eclipse.persistence.testing.oxm.inheritance.typetests.compositecollection.AddressesAsNestedWithCdnAddressXsiNoRefClassTestCases; import org.eclipse.persistence.testing.oxm.inheritance.typetests.compositecollection.AddressesAsNestedWithCdnAddressXsiTestCases; import org.eclipse.persistence.testing.oxm.inheritance.typetests.compositecollection.CanadianAddressAsRefClassTestCases; import org.eclipse.persistence.testing.oxm.inheritance.typetests.compositecollection.CanadianAddressesAsNestedNoRefClassTestCases; import org.eclipse.persistence.testing.oxm.inheritance.typetests.compositecollection.CanadianAddressesAsNestedTestCases; import org.eclipse.persistence.testing.oxm.inheritance.typetests.compositecollection.ContactsAsNestedNoRefClassTestCases; import org.eclipse.persistence.testing.oxm.inheritance.typetests.compositecollection.ContactsAsNestedTestCases; import org.eclipse.persistence.testing.oxm.inheritance.typetests.compositecollection.ContactsAsNestedWithAddressXsiNoRefClassTestCases; import org.eclipse.persistence.testing.oxm.inheritance.typetests.compositecollection.ContactsAsNestedWithAddressXsiTestCases; import org.eclipse.persistence.testing.oxm.inheritance.typetests.compositecollection.ContactsAsNestedWithCdnAddressXsiNoRefClassTestCases; import org.eclipse.persistence.testing.oxm.inheritance.typetests.compositecollection.ContactsAsNestedWithCdnAddressXsiTestCases; public class TypeTestSuite extends TestCase { public TypeTestSuite(String name) { super(name); } public static Test suite() { TestSuite suite = new TestSuite("Type Test Suite"); try { // --------------------- basic tests --------------------- // use case #1-1 suite.addTestSuite(ContactAsRootTestCases.class); // use case #1-2 suite.addTestSuite(ContactAsRootWithAddressXsiTestCases.class); // use case #2-1 suite.addTestSuite(ContactAsNestedTestCases.class); // use case #2-2 suite.addTestSuite(ContactAsNestedWithAddressXsiTestCases.class); // use case #2-3 suite.addTestSuite(ContactAsNestedWithCdnAddressXsiTestCases.class); // use case #3-1 suite.addTestSuite(AddressAsNestedTestCases.class); // use case #3-2 suite.addTestSuite(AddressAsNestedWithCdnAddressXsiTestCases.class); // use case #4-1 suite.addTestSuite(CanadianAddressAsNestedTestCases.class); // use case #5-1 suite.addTestSuite(XmlRootWithContactXsiTestCases.class); // additional test #1-1 suite.addTestSuite(ContactAsCdnAddressTestCases.class); // additional test #1-2 suite.addTestSuite(ContactAsNestedCdnAddressTestCases.class); // --------------------- collection cases --------------------- suite.addTestSuite(ContactsAsNestedTestCases.class); suite.addTestSuite(ContactsAsNestedWithAddressXsiTestCases.class); suite.addTestSuite(ContactsAsNestedWithCdnAddressXsiTestCases.class); suite.addTestSuite(AddressesAsNestedTestCases.class); suite.addTestSuite(AddressesAsNestedWithCdnAddressXsiTestCases.class); suite.addTestSuite(CanadianAddressesAsNestedTestCases.class); // --------------------- any cases --------------------- suite.addTestSuite(ContactAsAnyNestedTestCases.class); suite.addTestSuite(ContactsAsAnyNestedTestCases.class); // --------------------- not yet supported --------------------- // use case #1-3 //suite.addTestSuite(CanadianAddressAsRootTestCases.class); suite.addTestSuite(AddressesAsNestedWithCdnAddressNoDefaultRootTypeXsiTestsCases.class); //no ref class tests suite.addTestSuite(AddressAsNestedNoRefClassTestCases.class); suite.addTestSuite(AddressAsNestedWithCdnAddressXsiNoRefClassTestCases.class); suite.addTestSuite(CanadianAddressAsNestedNoRefClassTestCases.class); suite.addTestSuite(ContactAsNestedCdnAddressNoRefClassTestCases.class); suite.addTestSuite(ContactAsNestedNoRefClassTestCases.class); suite.addTestSuite(ContactAsNestedWithAddressXsiNoRefClassTestCases.class); suite.addTestSuite(ContactAsNestedWithCdnAddressXsiNoRefTestCases.class); suite.addTestSuite(AddressesAsNestedNoRefClassTestCases.class); suite.addTestSuite(AddressesAsNestedWithCdnAddressXsiNoRefClassTestCases.class); suite.addTestSuite(CanadianAddressesAsNestedNoRefClassTestCases.class); suite.addTestSuite(ContactsAsNestedNoRefClassTestCases.class); suite.addTestSuite(ContactsAsNestedWithAddressXsiNoRefClassTestCases.class); suite.addTestSuite(ContactsAsNestedWithCdnAddressXsiNoRefClassTestCases.class); suite.addTestSuite(CanadianAddressAsRefClassTestCases.class); } catch (Exception e) { e.printStackTrace(); } return suite; } public static void main(String[] args) { String[] arguments = { "-c", "org.eclipse.persistence.testing.oxm.inheritance.typetests.TypeTestSuite" }; junit.textui.TestRunner.main(arguments); } }
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/oxm/inheritance/typetests/TypeTestSuite.java
Java
epl-1.0
6,970
/** */ package org.nasdanika.amur.it.js.provider; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.ui.celleditor.ExtendedComboBoxCellEditor; import org.eclipse.emf.edit.provider.ComposeableAdapterFactory; import org.eclipse.emf.edit.provider.IEditingDomainItemProvider; import org.eclipse.emf.edit.provider.IItemLabelProvider; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor; import org.eclipse.emf.edit.provider.IItemPropertySource; import org.eclipse.emf.edit.provider.IStructuredItemContentProvider; import org.eclipse.emf.edit.provider.ITreeItemContentProvider; import org.eclipse.emf.edit.provider.ItemPropertyDescriptor; import org.eclipse.emf.edit.provider.ItemPropertyDescriptor.PropertyValueWrapper; import org.eclipse.emf.edit.provider.ViewerNotification; import org.eclipse.jface.viewers.CellEditor; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.swt.widgets.Composite; import org.nasdanika.amur.it.js.AbstractNode; import org.nasdanika.amur.it.js.Connection; import org.nasdanika.amur.it.js.JsPackage; import org.nasdanika.amur.it.js.Connection.PortInfo; import org.nasdanika.amur.Component; import org.nasdanika.amur.ImplementationType; import org.nasdanika.common.Activator; import org.nasdanika.common.CustomItemPropertyDescriptor; import org.nasdanika.common.ResolvingItemPropertyDescriptor; /** * This is the item provider adapter for a {@link org.nasdanika.amur.it.js.Connection} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class ConnectionItemProvider extends ComponentItemProvider implements IEditingDomainItemProvider, IStructuredItemContentProvider, ITreeItemContentProvider, IItemLabelProvider, IItemPropertySource { static class PortsComboBoxPropertyDescriptor extends ResolvingItemPropertyDescriptor implements CustomItemPropertyDescriptor { private boolean forSource; // private ILabelProvider labelProvider = new LabelProvider() { // // public String getText(Object element) { // for (PortInfo p: portsList(element)) { // // } // return String.valueOf(element); // }; // }; PortsComboBoxPropertyDescriptor(IItemPropertyDescriptor master, boolean forSource) { super(master); this.forSource = forSource; } @Override public IItemLabelProvider getLabelProvider(final Object obj) { final IItemLabelProvider superLabelProvider = super.getLabelProvider(obj); return new IItemLabelProvider() { @Override public String getText(Object val) { if (val instanceof PortInfo) { return ((PortInfo) val).getName(); } else if (val instanceof String) { for (PortInfo p: portsList(obj)) { if (p.getId().equals(val)) { return p.getName(); } } } else if (val instanceof PropertyValueWrapper) { return getText(((PropertyValueWrapper) val).getEditableValue(null)); } return superLabelProvider.getText(val); } @Override public Object getImage(Object object) { return superLabelProvider.getImage(object); } }; } @Override public CellEditor createPropertyEditor(Composite composite, ILabelProvider editLabelProvider, Object object) { return new ExtendedComboBoxCellEditor( composite, portsList(object), editLabelProvider, true) { @Override public Object doGetValue() { Object ret = super.doGetValue(); return ret==null ? null : ((PortInfo) ret).getId(); } @Override public void doSetValue(Object value) { if (value!=null) { for (Object obj: list) { if (value.equals(((PortInfo) obj).getId())) { super.doSetValue(obj); return; } } } super.doSetValue(null); } }; } private List<PortInfo> portsList(Object object) { PortInfo[] ret = null; org.nasdanika.amur.Connection connection = (org.nasdanika.amur.Connection) ((Connection) object).getOwner(); if (forSource) { ImplementationType implementationType = ((Component) connection.getSource()).getImplementationType(); if (implementationType instanceof AbstractNode) { ret = ((AbstractNode) implementationType).getOutputPorts(connection); } } else { ImplementationType implementationType = ((Component) connection.getTarget()).getImplementationType(); if (implementationType instanceof AbstractNode) { ret = ((AbstractNode) implementationType).getInputPorts(connection); } } return ret == null ? Collections.<PortInfo>emptyList() : Arrays.asList(ret); } @Override public ILabelProvider getLabelProvider(ILabelProvider superLabelProvider) { return null; } } /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ConnectionItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ @Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { if (itemPropertyDescriptors.get(object) == null) { super.getPropertyDescriptors(object); addSourcePortPropertyDescriptor(object); addTargetPortPropertyDescriptor(object); addSourceNamePropertyDescriptor(object); addTargetNamePropertyDescriptor(object); } return itemPropertyDescriptors.get(object); } /** * This adds a property descriptor for the Source Port feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ protected void addSourcePortPropertyDescriptor(Object object) { ItemPropertyDescriptor ipd = createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_Connection_sourcePort_feature"), getString("_UI_PropertyDescriptor_description", "_UI_Connection_sourcePort_feature", "_UI_Connection_type"), JsPackage.Literals.CONNECTION__SOURCE_PORT, true, false, false, Activator.getImageDescriptor("icons/fugue/icons/socket.png"), getString("_UI_SourcePropertyCategory"), null); itemPropertyDescriptors.get(object).add(new PortsComboBoxPropertyDescriptor(ipd, true)); } /** * This adds a property descriptor for the Source Name feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ protected void addSourceNamePropertyDescriptor(Object object) { itemPropertyDescriptors.get(object).add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_Connection_sourceName_feature"), getString("_UI_PropertyDescriptor_description", "_UI_Connection_sourceName_feature", "_UI_Connection_type"), JsPackage.Literals.CONNECTION__SOURCE_NAME, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, getString("_UI_SourcePropertyCategory"), null)); } /** * This adds a property descriptor for the Target Port feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ protected void addTargetPortPropertyDescriptor(Object object) { ItemPropertyDescriptor ipd = createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_Connection_targetPort_feature"), getString("_UI_PropertyDescriptor_description", "_UI_Connection_targetPort_feature", "_UI_Connection_type"), JsPackage.Literals.CONNECTION__TARGET_PORT, true, false, false, Activator.getImageDescriptor("icons/fugue/icons/socket.png"), getString("_UI_TargetPropertyCategory"), null); itemPropertyDescriptors.get(object).add (new PortsComboBoxPropertyDescriptor(ipd, false)); } /** * This adds a property descriptor for the Target Name feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ protected void addTargetNamePropertyDescriptor(Object object) { itemPropertyDescriptors.get(object).add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_Connection_targetName_feature"), getString("_UI_PropertyDescriptor_description", "_UI_Connection_targetName_feature", "_UI_Connection_type"), JsPackage.Literals.CONNECTION__TARGET_NAME, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, getString("_UI_TargetPropertyCategory"), null)); } /** * This returns Connection.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/Connection")); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected boolean shouldComposeCreationImage() { return true; } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getText(Object object) { String label = ((Connection)object).getName(); return label == null || label.length() == 0 ? getString("_UI_Connection_type") : getString("_UI_Connection_type") + " " + label; } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); switch (notification.getFeatureID(Connection.class)) { case JsPackage.CONNECTION__SOURCE_PORT: case JsPackage.CONNECTION__SOURCE_NAME: case JsPackage.CONNECTION__TARGET_PORT: case JsPackage.CONNECTION__TARGET_NAME: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true)); return; } super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); } }
Nasdanika/amur-it-js
org.nasdanika.amur.it.js.edit/src/org/nasdanika/amur/it/js/provider/ConnectionItemProvider.java
Java
epl-1.0
10,838
/** */ package hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Less Or Equal Than</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.LessOrEqualThan#getLeftOperand <em>Left Operand</em>}</li> * <li>{@link hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.LessOrEqualThan#getRightOperand <em>Right Operand</em>}</li> * </ul> * * @see hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.LogiclanguagePackage#getLessOrEqualThan() * @model * @generated */ public interface LessOrEqualThan extends PrimitiveRelation { /** * Returns the value of the '<em><b>Left Operand</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Left Operand</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Left Operand</em>' containment reference. * @see #setLeftOperand(Term) * @see hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.LogiclanguagePackage#getLessOrEqualThan_LeftOperand() * @model containment="true" * @generated */ Term getLeftOperand(); /** * Sets the value of the '{@link hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.LessOrEqualThan#getLeftOperand <em>Left Operand</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Left Operand</em>' containment reference. * @see #getLeftOperand() * @generated */ void setLeftOperand(Term value); /** * Returns the value of the '<em><b>Right Operand</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Right Operand</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Right Operand</em>' containment reference. * @see #setRightOperand(Term) * @see hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.LogiclanguagePackage#getLessOrEqualThan_RightOperand() * @model containment="true" * @generated */ Term getRightOperand(); /** * Sets the value of the '{@link hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.LessOrEqualThan#getRightOperand <em>Right Operand</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Right Operand</em>' containment reference. * @see #getRightOperand() * @generated */ void setRightOperand(Term value); } // LessOrEqualThan
viatra/VIATRA-Generator
Framework/hu.bme.mit.inf.dslreasoner.logic.model/ecore-gen/hu/bme/mit/inf/dslreasoner/logic/model/logiclanguage/LessOrEqualThan.java
Java
epl-1.0
2,823
/* $Id: sfputd.c,v 1.4 2011/01/25 16:30:50 ellson Exp $ $Revision: 1.4 $ */ /* vim:set shiftwidth=4 ts=8: */ /************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ *************************************************************************/ #include "sfhdr.h" /* Write out a floating point value in a portable format ** ** Written by Kiem-Phong Vo. */ #if __STD_C int _sfputd(Sfio_t * f, Sfdouble_t v) #else int _sfputd(f, v) Sfio_t *f; Sfdouble_t v; #endif { #define N_ARRAY (16*sizeof(Sfdouble_t)) reg ssize_t n, w; reg uchar *s, *ends; int exp; uchar c[N_ARRAY]; double x; SFMTXSTART(f, -1); if (f->mode != SF_WRITE && _sfmode(f, SF_WRITE, 0) < 0) SFMTXRETURN(f, -1); SFLOCK(f, 0); /* get the sign of v */ if (v < 0.) { v = -v; n = 1; } else n = 0; #if !_ast_fltmax_double /* don't know how to do these yet */ if (v > SF_MAXDOUBLE && !_has_expfuncs) { SFOPEN(f, 0); SFMTXRETURN(f, -1); } #endif /* make the magnitude of v < 1 */ if (v != 0.) v = frexp(v, &exp); else exp = 0; /* code the sign of v and exp */ if ((w = exp) < 0) { n |= 02; w = -w; } /* write out the signs and the exp */ SFOPEN(f, 0); if (sfputc(f, n) < 0 || (w = sfputu(f, w)) < 0) SFMTXRETURN(f, -1); SFLOCK(f, 0); w += 1; s = (ends = &c[0]) + sizeof(c); while (s > ends) { /* get 2^SF_PRECIS precision at a time */ n = (int) (x = ldexp(v, SF_PRECIS)); *--s = n | SF_MORE; v = x - n; if (v <= 0.) break; } /* last byte is not SF_MORE */ ends = &c[0] + sizeof(c) - 1; *ends &= ~SF_MORE; /* write out coded bytes */ n = ends - s + 1; w = SFWRITE(f, (Void_t *) s, n) == n ? w + n : -1; SFOPEN(f, 0); SFMTXRETURN(f, w); }
tomgr/graphviz-cmake
lib/sfio/sfputd.c
C
epl-1.0
2,152
/* Licensed Materials - Property of IBM Restricted Materials of IBM" Copyright 2008,2009 Chris J Arges Everton Constantino Tom Gall IBM Corp, All Rights Reserved US Government Users Restricted Rights - Use Duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp */ #include <string.h> #include <stdio.h> #include <errno.h> #include <libcop.h> int main(int argc, char **argv) { int fail = 0, n_tests = 10, i; long rndValue; cop_session_t *session; /* Here we use an asynchronous call using session*/ errno = 0; for (i = 0; i < n_tests; i++) { session = cop_create_random_session(COMPLETION_STORE); session = cop_commit_session(session); rndValue = cop_get_rnd(session); if( errno ) { printf("RND Error: %d \n", errno); fail++; errno=0; } printf("Seed returned is %x, errno=%x\n", rndValue, errno); cop_free_session(session); } printf("=== %s: %d/%d failures ===\n", argv[0], fail, 1); return fail; }
mkravetz/libcopl
libcop/test/rndtest003.c
C
epl-1.0
1,044
/****************************************************************************** * Copyright (c) 2000-2015 Ericsson Telecom AB * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package org.eclipse.titan.regressiontests.library; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import junit.framework.AssertionFailedError; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.titan.designer.consoles.TITANDebugConsole; /** * This class stores library functions to help writing test that involve markers without actual Eclipse knowledge. * */ public final class MarkerHandlingLibrary { private MarkerHandlingLibrary() { throw new UnsupportedOperationException(); } /** * Does a blind equivalency check of the provided marker attribute maps, meaning that all "known to be usefully" attributes are compared. * <p> * If the attributes don't match exactly it is considered to be an assertion failure. * * @param attributeMap1 the first map of attributes * @param attributeMap2 the second map of attributes * */ public static void blindMarkerEquivencyCheck(final Map<?, ?> attributeMap1, final Map<?, ?> attributeMap2) { assertNotNull(attributeMap1); assertNotNull(attributeMap2); try { assertEquals(attributeMap1.get(IMarker.SEVERITY), attributeMap2.get(IMarker.SEVERITY)); assertEquals(attributeMap1.get(IMarker.MESSAGE), attributeMap2.get(IMarker.MESSAGE)); assertEquals(attributeMap1.get(IMarker.LOCATION), attributeMap2.get(IMarker.LOCATION)); assertEquals(attributeMap1.get(IMarker.PRIORITY), attributeMap2.get(IMarker.PRIORITY)); assertEquals(attributeMap1.get(IMarker.LINE_NUMBER), attributeMap2.get(IMarker.LINE_NUMBER)); assertEquals(attributeMap1.get(IMarker.CHAR_START), attributeMap2.get(IMarker.CHAR_START)); assertEquals(attributeMap1.get(IMarker.CHAR_END), attributeMap2.get(IMarker.CHAR_END)); assertEquals(attributeMap1.get(IMarker.TRANSIENT), attributeMap2.get(IMarker.TRANSIENT)); } catch (AssertionFailedError e) { System.out.println("Not equivalent markers: "); System.out.println(MarkerHandlingLibrary.printErrorMessageAndAttributes(null, " ", attributeMap1)); System.out.println(MarkerHandlingLibrary.printErrorMessageAndAttributes(null, " ", attributeMap2)); throw e; } } /** * Compares the second provided attribute map the first. * The comparison asserts an error if the second attribute map does not have an attribute present in the first one. * Or when the value of the attributes is not the same. * <p> * If the attributes don't match exactly it is considered to be an assertion failure. * * @param attributeMap1 the first map of attributes * @param attributeMap2 the second map of attributes * */ public static void controlledMarkerEquivencyCheck(final Map<?, ?> attributeMap1, final Map<?, ?> attributeMap2) { assertNotNull(attributeMap1); assertNotNull(attributeMap2); if (attributeMap1.containsKey(IMarker.SEVERITY)) { assertEquals(attributeMap1.get(IMarker.SEVERITY), attributeMap2.get(IMarker.SEVERITY)); } if (attributeMap1.containsKey(IMarker.MESSAGE)) { assertEquals(attributeMap1.get(IMarker.MESSAGE), attributeMap2.get(IMarker.MESSAGE)); } if (attributeMap1.containsKey(IMarker.LOCATION)) { assertEquals(attributeMap1.get(IMarker.LOCATION), attributeMap2.get(IMarker.LOCATION)); } if (attributeMap1.containsKey(IMarker.PRIORITY)) { assertEquals(attributeMap1.get(IMarker.PRIORITY), attributeMap2.get(IMarker.PRIORITY)); } if (attributeMap1.containsKey(IMarker.LINE_NUMBER)) { assertEquals(attributeMap1.get(IMarker.LINE_NUMBER), attributeMap2.get(IMarker.LINE_NUMBER)); } if (attributeMap1.containsKey(IMarker.CHAR_START)) { assertEquals(attributeMap1.get(IMarker.CHAR_START), attributeMap2.get(IMarker.CHAR_START)); } if (attributeMap1.containsKey(IMarker.CHAR_END)) { assertEquals(attributeMap1.get(IMarker.CHAR_END), attributeMap2.get(IMarker.CHAR_END)); } if (attributeMap1.containsKey(IMarker.TRANSIENT)) { assertEquals(attributeMap1.get(IMarker.TRANSIENT), attributeMap2.get(IMarker.TRANSIENT)); } } /** * Transform the provided markers from their IMarker form (as seen in Eclipse), into a map of lists that can be used easier and safer in the testing process. * The actual steps: * <ul> * <li> puts the provided markers into a list. * <li> sorts this list. * <li> splits the list into a map according the IResource the markers are assigned to, but places only the attributes of the elements in this map. * </ul> * * @param inputMarkers the list of markers used as input. * * @return * */ public static Map<IResource, List<Map<?, ?>>> transformMarkers(final IMarker[] inputMarkers) throws CoreException { assertNotNull(inputMarkers); Map<IResource, List<Map<?, ?>>> resultMap = new HashMap<IResource, List<Map<?, ?>>>(); IMarker tempMarker; IResource tempresource; List<IMarker> tempSortingList = Arrays.asList(inputMarkers); Collections.sort(tempSortingList, new Comparator<IMarker>() { @Override public int compare(final IMarker o1, final IMarker o2) { Map<?, ?> attributeMap1; Map<?, ?> attributeMap2; try { attributeMap1 = o1.getAttributes(); attributeMap2 = o2.getAttributes(); } catch (CoreException e) { return 0; } if (attributeMap1.containsKey(IMarker.LINE_NUMBER) && attributeMap2.containsKey(IMarker.LINE_NUMBER)) { int lineNumber1 = ((Integer) attributeMap1.get(IMarker.LINE_NUMBER)).intValue(); int lineNumber2 = ((Integer) attributeMap2.get(IMarker.LINE_NUMBER)).intValue(); if (lineNumber1 < lineNumber2) { return -1; } else if (lineNumber1 > lineNumber2) { return 1; } } String message1 = (String) attributeMap1.get(IMarker.MESSAGE); String message2 = (String) attributeMap2.get(IMarker.MESSAGE); int result = message1.compareTo(message2); if (result != 0) { return result; } if (attributeMap1.containsKey(IMarker.CHAR_START) && attributeMap2.containsKey(IMarker.CHAR_START)) { int lineNumber1 = ((Integer) attributeMap1.get(IMarker.CHAR_START)).intValue(); int lineNumber2 = ((Integer) attributeMap2.get(IMarker.CHAR_START)).intValue(); if (lineNumber1 < lineNumber2) { return -1; } else if (lineNumber1 > lineNumber2) { return 1; } } if (attributeMap1.containsKey(IMarker.CHAR_END) && attributeMap2.containsKey(IMarker.CHAR_END)) { int lineNumber1 = ((Integer) attributeMap1.get(IMarker.CHAR_END)).intValue(); int lineNumber2 = ((Integer) attributeMap2.get(IMarker.CHAR_END)).intValue(); if (lineNumber1 < lineNumber2) { return -1; } else if (lineNumber1 > lineNumber2) { return 1; } } return 0; } }); List<Map<?, ?>> tempArray; for (int i = 0; i < tempSortingList.size(); i++) { tempMarker = tempSortingList.get(i); tempresource = tempMarker.getResource(); if (tempMarker.exists()) { if (resultMap.containsKey(tempresource)) { tempArray = resultMap.get(tempresource); tempArray.add(tempMarker.getAttributes()); } else { tempArray = new ArrayList<Map<?, ?>>(); tempArray.add(tempMarker.getAttributes()); resultMap.put(tempresource, tempArray); } } } return resultMap; } /** * Prints the messages contained in the provided markers into a StringBuffer. * * @param markers the markers containing the messages to be printed. * * @return the StringBuffer object containing the extracted messages. * */ public static StringBuilder printMarkerMessages(final HashMap<IResource, ArrayList<Map<?, ?>>> markers) { StringBuilder builder = new StringBuilder(); assertNotNull(markers); for (IResource resource : markers.keySet()) { builder.append("In resource `").append(resource.toString()).append("':\n"); ArrayList<Map<?, ?>> markerList = markers.get(resource); assertNotNull(markerList); Map<?, ?> tempAttributes; for (int i = 0; i < markerList.size(); i++) { tempAttributes = markerList.get(i); builder.append(" ").append(tempAttributes.get(IMarker.MESSAGE)).append("\n"); } } return builder; } /** * Prints attributes contained in the provided markers and believed to be of importance into a StringBuffer. * * @param the prefix used to indent the output * @param marker the marker to be printed. * * @return the StringBuffer object containing the extracted messages. * */ public static StringBuilder printErrorMessageAndAttributes(final StringBuilder builder, final String prefix, final Map<?, ?> marker) { StringBuilder internalBuilder; if (builder == null) { internalBuilder = new StringBuilder(); } else { internalBuilder = builder; } assertNotNull(marker); internalBuilder.append(prefix); if (marker.containsKey(IMarker.SEVERITY)) { internalBuilder.append("severity: "); switch(((Integer) marker.get(IMarker.SEVERITY)).intValue()) { case IMarker.SEVERITY_ERROR: internalBuilder.append("ERROR"); break; case IMarker.SEVERITY_WARNING: internalBuilder.append("WARNING"); break; case IMarker.SEVERITY_INFO: internalBuilder.append("INFORMATION"); break; default: fail("Unknown severity value: " + ((Integer) marker.get(IMarker.SEVERITY)).intValue()); } internalBuilder.append("\t "); } if (marker.containsKey(IMarker.PRIORITY)) { internalBuilder.append("priority: "); switch(((Integer) marker.get(IMarker.PRIORITY)).intValue()) { case IMarker.PRIORITY_HIGH: internalBuilder.append("HIGH"); break; case IMarker.PRIORITY_NORMAL: internalBuilder.append("NORMAL"); break; case IMarker.PRIORITY_LOW: internalBuilder.append("LOW"); break; default: fail("Unknown priority value: " + ((Integer) marker.get(IMarker.PRIORITY)).intValue()); } internalBuilder.append("\t "); } if (marker.containsKey(IMarker.LINE_NUMBER)) { internalBuilder.append("in line: ").append(marker.get(IMarker.LINE_NUMBER)).append("\t "); } if (marker.containsKey(IMarker.CHAR_START) && marker.containsKey(IMarker.CHAR_END)) { internalBuilder.append("in position: ").append(marker.get(IMarker.CHAR_START)).append(" - ").append(marker.get(IMarker.CHAR_END)).append("\t "); } internalBuilder.append(marker.get(IMarker.MESSAGE)); return internalBuilder; } /** * Prints attributes contained in the provided markers and believed to be of importance into a StringBuffer. * * @param markers the markers containing the messages to be printed. * * @return the StringBuffer object containing the extracted messages. * */ public static StringBuilder printErrorMessagesAndAttributes(final Map<IResource, ArrayList<Map<?, ?>>> markers) { StringBuilder builder = new StringBuilder(); assertNotNull(markers); for (IResource resource : markers.keySet()) { builder.append("In resource `").append(resource.toString()).append("':\n"); ArrayList<Map<?, ?>> markerList = markers.get(resource); assertNotNull(markerList); Map<?, ?> tempAttributes; for (int i = 0; i < markerList.size(); i++) { tempAttributes = markerList.get(i); builder.append(" "); if (tempAttributes.containsKey(IMarker.SEVERITY)) { builder.append("severity: "); switch(((Integer) tempAttributes.get(IMarker.SEVERITY)).intValue()) { case IMarker.SEVERITY_ERROR: builder.append("ERROR"); break; case IMarker.SEVERITY_WARNING: builder.append("WARNING"); break; case IMarker.SEVERITY_INFO: builder.append("INFORMATION"); break; default: fail("Unknown severity value: " + ((Integer) tempAttributes.get(IMarker.SEVERITY)).intValue()); } builder.append("\t "); } if (tempAttributes.containsKey(IMarker.PRIORITY)) { builder.append("priority: "); switch(((Integer) tempAttributes.get(IMarker.PRIORITY)).intValue()) { case IMarker.PRIORITY_HIGH: builder.append("HIGH"); break; case IMarker.PRIORITY_NORMAL: builder.append("NORMAL"); break; case IMarker.PRIORITY_LOW: builder.append("LOW"); break; default: fail("Unknown priority value: " + ((Integer) tempAttributes.get(IMarker.PRIORITY)).intValue()); } builder.append("\t "); } if (tempAttributes.containsKey(IMarker.LINE_NUMBER)) { builder.append("in line: ").append(tempAttributes.get(IMarker.LINE_NUMBER)).append("\t "); } if (tempAttributes.containsKey(IMarker.CHAR_START) && tempAttributes.containsKey(IMarker.CHAR_END)) { builder.append("in position: ").append(tempAttributes.get(IMarker.CHAR_START)).append(" - ").append(tempAttributes.get(IMarker.CHAR_END)).append("\t "); } builder.append(tempAttributes.get(IMarker.MESSAGE)).append("\n"); } } return builder; } /** * Traverses the list of attributes provided to find the first one that can match a given pattern. * If it is found it will be removed from the list. * * @param markers the list of marker attributes to traverse. * @param marker the marker that is expected to be on the list at the right place * @param hardCheck indicates if the function stops the execution or not if the required marker is found * * */ public static void searchNDestroyFittingMarker(final List<Map<?, ?>> markers, final Map<?, ?> marker, final boolean hardCheck) { assertNotNull(markers); assertNotNull(marker); String message = (String) marker.get(IMarker.MESSAGE); int lineNum = (Integer) marker.get(IMarker.LINE_NUMBER); int severity = (Integer) marker.get(IMarker.SEVERITY); Map<?, ?> attributes; for (int i = markers.size() - 1; i >= 0; i--) { attributes = markers.get(i); assertNotNull(attributes); if ((attributes.containsKey(IMarker.LINE_NUMBER) && (Integer) attributes.get(IMarker.LINE_NUMBER) == lineNum) && ((String) attributes.get(IMarker.MESSAGE)).equals(message) && ((Integer) attributes.get(IMarker.SEVERITY) == severity) ) { markers.remove(i); return; } } if (hardCheck) { fail("The required Marker - ".concat(" (").concat(message).concat(")").concat(" - was not found at the expected location: ".concat(new Integer(lineNum).toString()))); } else { TITANDebugConsole.println( "The required Marker - ".concat(" (").concat(message).concat(")").concat(" - was not found at the expected location: ".concat(new Integer(lineNum).toString()))); } } /** * Prints a non empty marker array to the standard output. Can be used to detect unchecked markers. * * @param source the source file name of the markers in the array * @param markerArray the markers to be left * * @return none * */ public static void printMarkerArray(final String source, final List<Map<?, ?>> markerArray) { if (markerArray.isEmpty()) { return; } System.out.println("The following messages did not checked in " + source + " :"); for (Iterator<Map<?, ?>> iterator = markerArray.iterator(); iterator.hasNext();) { System.out.println(printErrorMessageAndAttributes(null, " ", iterator.next())); } } }
alovassy/titan.EclipsePlug-ins
org.eclipse.titan.regressiontests/src/org/eclipse/titan/regressiontests/library/MarkerHandlingLibrary.java
Java
epl-1.0
15,944
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en-us" xml:lang="en-us"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="copyright" content="(C) Copyright 2010" /> <meta name="DC.rights.owner" content="(C) Copyright 2010" /> <meta name="DC.Type" content="cxxStruct" /> <meta name="DC.Title" content="CMTPTypeCompoundBase::TElementInfo" /> <meta name="DC.Format" content="XHTML" /> <meta name="DC.Identifier" content="GUID-D489FB8A-A7D0-31F7-9A3C-40C599FE2B83" /> <title> CMTPTypeCompoundBase::TElementInfo </title> <link type="text/css" rel="stylesheet" href="css/common.css" media="screen"/> <link type="text/css" rel="stylesheet" href="css/sdl.css" media="screen"/> <!--[if IE]> <link href="css/iefix.css" rel="stylesheet" type="text/css" media="screen" /> <![endif]--> <meta name="keywords" content="api" /> <link rel="stylesheet" type="text/css" href="cxxref.css" /> </head> <body class="cxxref" id="GUID-D489FB8A-A7D0-31F7-9A3C-40C599FE2B83"> <a name="GUID-D489FB8A-A7D0-31F7-9A3C-40C599FE2B83"> <!-- --> </a> <?php include_once (CURRENT_SKIN_PATH.'/sdl_header.html'); ?> <div id="sdl_container"> <div id="leftMenu"> <div id="expandcontractdiv"> <a id="collapseTree" href="javascript:tree.collapseAll()"> Collapse all </a> <a id="index" href="index.html"> Symbian^3 Application Developer Library </a> </div> <iframe style="border:none" height="800" width="300" src="index-toc.html"></iframe> <div id="treeDiv1"> &#160; </div> <script type="text/javascript"> var currentIconMode = 0; window.name="id2518338 id2518347 id2420140 id2583077 id2583237 id2583242 id2583293 "; YAHOO.util.Event.onDOMReady(buildTree, this,true); </script> </div> <div id="sdl_content"> <div class="breadcrumb"> <a href="index.html" title="Symbian^3 Application Developer Library"> Symbian^3 Application Developer Library </a> &gt; </div> <h1 class="topictitle1"> CMTPTypeCompoundBase::TElementInfo Struct Reference </h1> <table class="signature"> <tr> <td> struct CMTPTypeCompoundBase::TElementInfo </td> </tr> </table> <div class="section"> <div> <p> Defines the MTP compound data type element meta data. </p> </div> </div> <div class="section member-index"> <table border="0" class="member-index"> <thead> <tr> <th colspan="2"> Public Attributes </th> </tr> </thead> <tbody> <tr> <td align="right" valign="top"> <a href="GUID-FC2F2B93-3D18-3BCC-9FD6-6BC6B240B667.html"> TInt </a> </td> <td> <a href="#GUID-D25DA4B3-04B3-35B0-8DC6-2896A0F1AB35"> iChunkId </a> </td> </tr> <tr class="bg"> <td align="right" valign="top"> <a href="GUID-23559F9F-0C80-3C76-A6E5-B61606D7E324.html"> TMTPTypeFlatBase::TElementInfo </a> </td> <td> <a href="#GUID-31AB6F09-84CB-3E5F-AE2C-0C3D0182A374"> iFlatChunkInfo </a> </td> </tr> <tr> <td align="right" valign="top"> <a href="GUID-FC2F2B93-3D18-3BCC-9FD6-6BC6B240B667.html"> TInt </a> </td> <td> <a href="#GUID-526B86D5-31B9-38FC-94E2-D577F8281241"> iType </a> </td> </tr> </tbody> </table> </div> <h1 class="pageHeading topictitle1"> Member Data Documentation </h1> <div class="nested1" id="GUID-D25DA4B3-04B3-35B0-8DC6-2896A0F1AB35"> <a name="GUID-D25DA4B3-04B3-35B0-8DC6-2896A0F1AB35"> <!-- --> </a> <h2 class="topictitle2"> TInt iChunkId </h2> <table class="signature"> <tr> <td> <a href="GUID-FC2F2B93-3D18-3BCC-9FD6-6BC6B240B667.html"> TInt </a> </td> <td> iChunkId </td> </tr> </table> <div class="section"> <div> <p> The element's chunk identifier (sequence number). </p> </div> </div> </div> <div class="nested1" id="GUID-31AB6F09-84CB-3E5F-AE2C-0C3D0182A374"> <a name="GUID-31AB6F09-84CB-3E5F-AE2C-0C3D0182A374"> <!-- --> </a> <h2 class="topictitle2"> TMTPTypeFlatBase::TElementInfo iFlatChunkInfo </h2> <table class="signature"> <tr> <td> <a href="GUID-23559F9F-0C80-3C76-A6E5-B61606D7E324.html"> TMTPTypeFlatBase::TElementInfo </a> </td> <td> iFlatChunkInfo </td> </tr> </table> <div class="section"> <div> <p> <a href="GUID-E2830E95-5E11-30F4-AF47-33017B446E01.html#GUID-E2830E95-5E11-30F4-AF47-33017B446E01"> RMTPTypeCompoundFlatChunk </a> element specific meta data. </p> </div> </div> </div> <div class="nested1" id="GUID-526B86D5-31B9-38FC-94E2-D577F8281241"> <a name="GUID-526B86D5-31B9-38FC-94E2-D577F8281241"> <!-- --> </a> <h2 class="topictitle2"> TInt iType </h2> <table class="signature"> <tr> <td> <a href="GUID-FC2F2B93-3D18-3BCC-9FD6-6BC6B240B667.html"> TInt </a> </td> <td> iType </td> </tr> </table> <div class="section"> <div> <p> The element's MTP type identifier. </p> </div> </div> </div> <p class="copyright">Copyright &#169;2010 Nokia Corporation and/or its subsidiary(-ies).<br /> All rights reserved. Unless otherwise stated, these materials are provided under the terms of the <a href=" http://www.eclipse.org/legal/epl-v10.html"> Eclipse Public License v1.0</a>.</p> </div> </div> <?php include_once (CURRENT_SKIN_PATH.'/sdl_footer.html'); ?> </body> </html>
warlordh/fork_Symbian
sdk/GUID-D489FB8A-A7D0-31F7-9A3C-40C599FE2B83.html
HTML
epl-1.0
6,164
/** */ package org.tetrabox.minijava.xminijava.miniJava; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>State</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link org.tetrabox.minijava.xminijava.miniJava.State#getRootFrame <em>Root Frame</em>}</li> * <li>{@link org.tetrabox.minijava.xminijava.miniJava.State#getObjectsHeap <em>Objects Heap</em>}</li> * <li>{@link org.tetrabox.minijava.xminijava.miniJava.State#getOutputStream <em>Output Stream</em>}</li> * <li>{@link org.tetrabox.minijava.xminijava.miniJava.State#getArraysHeap <em>Arrays Heap</em>}</li> * </ul> * * @see org.tetrabox.minijava.xminijava.miniJava.MiniJavaPackage#getState() * @model * @generated */ public interface State extends EObject { /** * Returns the value of the '<em><b>Root Frame</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Root Frame</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Root Frame</em>' containment reference. * @see #setRootFrame(Frame) * @see org.tetrabox.minijava.xminijava.miniJava.MiniJavaPackage#getState_RootFrame() * @model containment="true" * @generated */ Frame getRootFrame(); /** * Sets the value of the '{@link org.tetrabox.minijava.xminijava.miniJava.State#getRootFrame <em>Root Frame</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Root Frame</em>' containment reference. * @see #getRootFrame() * @generated */ void setRootFrame(Frame value); /** * Returns the value of the '<em><b>Objects Heap</b></em>' containment reference list. * The list contents are of type {@link org.tetrabox.minijava.xminijava.miniJava.ObjectInstance}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Objects Heap</em>' containment reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Objects Heap</em>' containment reference list. * @see org.tetrabox.minijava.xminijava.miniJava.MiniJavaPackage#getState_ObjectsHeap() * @model containment="true" * @generated */ EList<ObjectInstance> getObjectsHeap(); /** * Returns the value of the '<em><b>Output Stream</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Output Stream</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Output Stream</em>' containment reference. * @see #setOutputStream(OutputStream) * @see org.tetrabox.minijava.xminijava.miniJava.MiniJavaPackage#getState_OutputStream() * @model containment="true" * @generated */ OutputStream getOutputStream(); /** * Sets the value of the '{@link org.tetrabox.minijava.xminijava.miniJava.State#getOutputStream <em>Output Stream</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Output Stream</em>' containment reference. * @see #getOutputStream() * @generated */ void setOutputStream(OutputStream value); /** * Returns the value of the '<em><b>Arrays Heap</b></em>' containment reference list. * The list contents are of type {@link org.tetrabox.minijava.xminijava.miniJava.ArrayInstance}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Arrays Heap</em>' containment reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Arrays Heap</em>' containment reference list. * @see org.tetrabox.minijava.xminijava.miniJava.MiniJavaPackage#getState_ArraysHeap() * @model containment="true" * @generated */ EList<ArrayInstance> getArraysHeap(); /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @model * @generated */ Frame findCurrentFrame(); /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @model * @generated */ Context findCurrentContext(); /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @model * @generated */ void println(String string); /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @model * @generated */ void pushNewContext(); /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @model * @generated */ void popCurrentContext(); /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @model * @generated */ void pushNewFrame(ObjectInstance receiver, Call c, Context newContext); /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @model * @generated */ void popCurrentFrame(); } // State
tetrabox/minijava
plugins/org.tetrabox.minijava.xminijava/src/org/tetrabox/minijava/xminijava/miniJava/State.java
Java
epl-1.0
5,026
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Assailed</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content="CSJM"> <!-- Le styles --> <link href="/bootstrap/css/bootstrap.css" rel="stylesheet"> <style type="text/css"> body { padding-top: 60px; padding-bottom: 40px; } </style> <link href="/bootstrap/css/bootstrap-responsive.css" rel="stylesheet"> <!-- HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="/bootstrap/js/html5shiv.js"></script> <![endif]--> <!-- Fav and touch icons --> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/bootstrap/ico/apple-touch-icon-144-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="/bootstrap/ico/apple-touch-icon-114-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="/bootstrap/ico/apple-touch-icon-72-precomposed.png"> <link rel="apple-touch-icon-precomposed" href="/bootstrap/ico/apple-touch-icon-57-precomposed.png"> <link rel="shortcut icon" href="/bootstrap/ico/favicon.png"> </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="brand" href="#">Project name</a> <div class="nav-collapse collapse"> <ul class="nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#about">About</a></li> <li><a href="#contact">Contact</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li class="divider"></li> <li class="nav-header">Nav header</li> <li><a href="#">Separated link</a></li> <li><a href="#">One more separated link</a></li> </ul> </li> </ul> <form class="navbar-form pull-right"> <input class="span2" type="text" placeholder="Email"> <input class="span2" type="password" placeholder="Password"> <button type="submit" class="btn">Sign in</button> </form> </div><!--/.nav-collapse --> </div> </div> </div> <div class="container"> <!-- Main hero unit for a primary marketing message or call to action --> <div class="hero-unit"> <form action="/thanks/" method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> </div> <!-- What is a carousel? --> <div id="myCarousel" class="carousel slide"> <ol class="carousel-indicators"> <li data-target="#myCarousel" data-slide-to="0" class="active"></li> <li data-target="#myCarousel" data-slide-to="1"></li> <li data-target="#myCarousel" data-slide-to="2"></li> </ol> <!-- Carousel items --> <div class="carousel-inner"> <div class="active item">…</div> <div class="item">…</div> <div class="item">…</div> </div> <!-- Carousel nav --> <a class="carousel-control left" href="#myCarousel" data-slide="prev">&lsaquo;</a> <a class="carousel-control right" href="#myCarousel" data-slide="next">&rsaquo;</a> </div> <!-- Example row of columns --> <div class="row"> <div class="span4"> <h2>Heading</h2> <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p> <p><a class="btn" href="#">View details &raquo;</a></p> </div> <div class="span4"> <h2>Heading</h2> <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p> <p><a class="btn" href="#">View details &raquo;</a></p> </div> <div class="span4"> <h2>Heading</h2> <p>Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.</p> <p><a class="btn" href="#">View details &raquo;</a></p> </div> </div> <hr> <footer> <p>&copy; Company 2013</p> </footer> </div> <!-- /container --> <!-- Le javascript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <script src="/bootstrap/js/bootstrap.js"></script> </body> </html>
kariefury/pyDev-Django-GAE
templates/hello/idea_form.html
HTML
epl-1.0
5,774
// $Id: UMLModelElementNameDocument.java 41 2010-04-03 20:04:12Z marcusvnac $ // Copyright (c) 1996-2006 The Regents of the University of California. All // Rights Reserved. Permission to use, copy, modify, and distribute this // software and its documentation without fee, and without a written // agreement is hereby granted, provided that the above copyright notice // and this paragraph appear in all copies. This software program and // documentation are copyrighted by The Regents of the University of // California. The software program and documentation are supplied "AS // IS", without any accompanying services from The Regents. The Regents // does not warrant that the operation of the program will be // uninterrupted or error-free. The end-user understands that the program // was developed for research purposes and is advised not to rely // exclusively on the program for any reason. IN NO EVENT SHALL THE // UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, // SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, // ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF // THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE // PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF // CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, // UPDATES, ENHANCEMENTS, OR MODIFICATIONS. package org.argouml.uml.ui.foundation.core; import org.argouml.model.Model; import org.argouml.uml.ui.UMLPlainTextDocument; /** * @since Oct 10, 2002 * @author jaap.branderhorst@xs4all.nl */ public class UMLModelElementNameDocument extends UMLPlainTextDocument { /** * Constructor for UMLModelElementNameDocument. */ public UMLModelElementNameDocument() { super("name"); } /* * @see org.argouml.uml.ui.UMLPlainTextDocument#setProperty(java.lang.String) */ protected void setProperty(String text) { Model.getCoreHelper().setName(getTarget(), text); } /* * @see org.argouml.uml.ui.UMLPlainTextDocument#getProperty() */ protected String getProperty() { return Model.getFacade().getName(getTarget()); } }
kopl/misc
JaMoPP Performance Test/testcode/argouml-usecase-variant/src/org/argouml/uml/ui/foundation/core/UMLModelElementNameDocument.java
Java
epl-1.0
2,465
package org.python.pydev.ast.codecompletion; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.python.pydev.ast.codecompletion.ProposalsComparator; import org.python.pydev.shared_core.code_completion.ICompletionProposalHandle; import junit.framework.TestCase; public class ProposalsComparatorTest extends TestCase { private static class Dummy1 implements ICompletionProposal, ICompletionProposalHandle { private String string; public Dummy1(String string) { this.string = string; } @Override public void apply(IDocument document) { } @Override public Point getSelection(IDocument document) { return null; } @Override public String getAdditionalProposalInfo() { return null; } @Override public String getDisplayString() { return this.string; } @Override public Image getImage() { return null; } @Override public IContextInformation getContextInformation() { return null; } } public void testProposalsComparator() { ProposalsComparator proposalsComparator = new ProposalsComparator("foo", null); // alphabetical (ignore case) assertEquals(1, proposalsComparator.compare(new Dummy1("bar"), new Dummy1("aBar"))); assertEquals(-1, proposalsComparator.compare(new Dummy1("abar"), new Dummy1("Bar"))); // _ is always the last assertEquals(1, proposalsComparator.compare(new Dummy1("_bar"), new Dummy1("abar"))); assertEquals(-1, proposalsComparator.compare(new Dummy1("Zbar"), new Dummy1("_bar"))); } }
fabioz/Pydev
plugins/org.python.pydev/tests_completions/org/python/pydev/ast/codecompletion/ProposalsComparatorTest.java
Java
epl-1.0
1,934
/******************************************************************************* * Copyright (c) 2006, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jface.window; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; /** * Default implementation of ToolTip that provides an iconofied label with font * and color controls by subclass. * * @since 3.3 */ public class DefaultToolTip extends ToolTip { private String text; private Color backgroundColor; private Font font; private Image backgroundImage; private Color foregroundColor; private Image image; private int style = SWT.SHADOW_NONE; /** * Create new instance which add TooltipSupport to the widget * * @param control the control on whose action the tooltip is shown */ public DefaultToolTip(Control control) { super(control); } /** * Create new instance which add TooltipSupport to the widget * * @param control the control to which the tooltip is bound * @param style style passed to control tooltip behaviour * @param manualActivation <code>true</code> if the activation is done manually using * {@link #show(Point)} * @see #RECREATE * @see #NO_RECREATE */ public DefaultToolTip(Control control, int style, boolean manualActivation) { super(control, style, manualActivation); } /** * Creates the content are of the the tooltip. By default this creates a * CLabel to display text. To customize the text Subclasses may override the * following methods * <ul> * <li>{@link #getStyle(Event)}</li> * <li>{@link #getBackgroundColor(Event)}</li> * <li>{@link #getForegroundColor(Event)}</li> * <li>{@link #getFont(Event)}</li> * <li>{@link #getImage(Event)}</li> * <li>{@link #getText(Event)}</li> * <li>{@link #getBackgroundImage(Event)}</li> * </ul> * * @param event * the event that triggered the activation of the tooltip * @param parent * the parent of the content area * @return the content area created */ @Override protected Composite createToolTipContentArea(Event event, Composite parent) { Image image = getImage(event); Image bgImage = getBackgroundImage(event); String text = getText(event); Color fgColor = getForegroundColor(event); Color bgColor = getBackgroundColor(event); Font font = getFont(event); CLabel label = new CLabel(parent, getStyle(event)); if (text != null) { label.setText(text); } if (image != null) { label.setImage(image); } if (fgColor != null) { label.setForeground(fgColor); } if (bgColor != null) { label.setBackground(bgColor); } if (bgImage != null) { label.setBackgroundImage(image); } if (font != null) { label.setFont(font); } return label; } /** * The style used to create the {@link CLabel} in the default implementation * * @param event * the event triggered the popup of the tooltip * @return the style */ protected int getStyle(Event event) { return style; } /** * The {@link Image} displayed in the {@link CLabel} in the default * implementation implementation * * @param event * the event triggered the popup of the tooltip * @return the {@link Image} or <code>null</code> if no image should be * displayed */ protected Image getImage(Event event) { return image; } /** * The foreground {@link Color} used by {@link CLabel} in the default * implementation * * @param event * the event triggered the popup of the tooltip * @return the {@link Color} or <code>null</code> if default foreground * color should be used */ protected Color getForegroundColor(Event event) { return (foregroundColor == null) ? event.widget.getDisplay() .getSystemColor(SWT.COLOR_INFO_FOREGROUND) : foregroundColor; } /** * The background {@link Color} used by {@link CLabel} in the default * implementation * * @param event * the event triggered the popup of the tooltip * @return the {@link Color} or <code>null</code> if default background * color should be used */ protected Color getBackgroundColor(Event event) { return (backgroundColor == null) ? event.widget.getDisplay() .getSystemColor(SWT.COLOR_INFO_BACKGROUND) : backgroundColor; } /** * The background {@link Image} used by {@link CLabel} in the default * implementation * * @param event * the event triggered the popup of the tooltip * @return the {@link Image} or <code>null</code> if no image should be * displayed in the background */ protected Image getBackgroundImage(Event event) { return backgroundImage; } /** * The {@link Font} used by {@link CLabel} in the default implementation * * @param event * the event triggered the popup of the tooltip * @return the {@link Font} or <code>null</code> if the default font * should be used */ protected Font getFont(Event event) { return font; } /** * The text displayed in the {@link CLabel} in the default implementation * * @param event * the event triggered the popup of the tooltip * @return the text or <code>null</code> if no text has to be displayed */ protected String getText(Event event) { return text; } /** * The background {@link Image} used by {@link CLabel} in the default * implementation * * @param backgroundColor * the {@link Color} or <code>null</code> if default background * color ({@link SWT#COLOR_INFO_BACKGROUND}) should be used */ public void setBackgroundColor(Color backgroundColor) { this.backgroundColor = backgroundColor; } /** * The background {@link Image} used by {@link CLabel} in the default * implementation * * @param backgroundImage * the {@link Image} or <code>null</code> if no image should be * displayed in the background */ public void setBackgroundImage(Image backgroundImage) { this.backgroundImage = backgroundImage; } /** * The {@link Font} used by {@link CLabel} in the default implementation * * @param font * the {@link Font} or <code>null</code> if the default font * should be used */ public void setFont(Font font) { this.font = font; } /** * The foreground {@link Color} used by {@link CLabel} in the default * implementation * * @param foregroundColor * the {@link Color} or <code>null</code> if default foreground * color should be used */ public void setForegroundColor(Color foregroundColor) { this.foregroundColor = foregroundColor; } /** * The {@link Image} displayed in the {@link CLabel} in the default * implementation implementation * * @param image * the {@link Image} or <code>null</code> if no image should be * displayed */ public void setImage(Image image) { this.image = image; } /** * The style used to create the {@link CLabel} in the default implementation * * @param style * the event triggered the popup of the tooltip */ public void setStyle(int style) { this.style = style; } /** * The text displayed in the {@link CLabel} in the default implementation * * @param text * the text or <code>null</code> if no text has to be displayed */ public void setText(String text) { this.text = text; } }
ControlSystemStudio/org.csstudio.iter
plugins/org.eclipse.jface/src/org/eclipse/jface/window/DefaultToolTip.java
Java
epl-1.0
8,091
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.config.manager.impl.jmx; import javax.management.InstanceAlreadyExistsException; import javax.management.ObjectName; import org.opendaylight.controller.config.api.jmx.ObjectNameUtil; public interface ServiceReferenceRegistrator extends AutoCloseable { public String getNullableTransactionName(); ServiceReferenceJMXRegistration registerMBean(ServiceReferenceMXBeanImpl object, ObjectName on) throws InstanceAlreadyExistsException; @Override void close(); public static class ServiceReferenceJMXRegistration implements AutoCloseable { private final InternalJMXRegistration registration; ServiceReferenceJMXRegistration(InternalJMXRegistration registration) { this.registration = registration; } @Override public void close() { registration.close(); } } public static interface ServiceReferenceTransactionRegistratorFactory { public ServiceReferenceRegistrator create(); } public static class ServiceReferenceRegistratorImpl implements ServiceReferenceRegistrator { private final InternalJMXRegistrator currentJMXRegistrator; private final String nullableTransactionName; public ServiceReferenceRegistratorImpl(NestableJMXRegistrator parentRegistrator, String nullableTransactionName){ currentJMXRegistrator = parentRegistrator.createChild(); this.nullableTransactionName = nullableTransactionName; } public String getNullableTransactionName() { return nullableTransactionName; } public ServiceReferenceJMXRegistration registerMBean(ServiceReferenceMXBeanImpl object, ObjectName on) throws InstanceAlreadyExistsException { String actualTransactionName = ObjectNameUtil.getTransactionName(on); boolean broken = false; broken |= (nullableTransactionName == null) != (actualTransactionName == null); broken |= (nullableTransactionName != null) && nullableTransactionName.equals(actualTransactionName) == false; if (broken) { throw new IllegalArgumentException("Transaction name mismatch between expected " + nullableTransactionName + ", got " + actualTransactionName + " in " + on); } if (ObjectNameUtil.isServiceReference(on) == false) { throw new IllegalArgumentException("Invalid type of " + on); } return new ServiceReferenceJMXRegistration(currentJMXRegistrator.registerMBean(object, on)); } @Override public void close() { currentJMXRegistrator.close(); } public static interface ServiceReferenceTransactionRegistratorFactory { public ServiceReferenceRegistrator create(); } } public static class ServiceReferenceTransactionRegistratorFactoryImpl implements ServiceReferenceTransactionRegistratorFactory { private final NestableJMXRegistrator parentRegistrator; private final String nullableTransactionName; public ServiceReferenceTransactionRegistratorFactoryImpl(TransactionModuleJMXRegistrator parentRegistrator, String nullableTransactionName) { this.parentRegistrator = parentRegistrator; this.nullableTransactionName = nullableTransactionName; } public ServiceReferenceTransactionRegistratorFactoryImpl(BaseJMXRegistrator baseJMXRegistrator) { this.parentRegistrator = baseJMXRegistrator; this.nullableTransactionName = null; } public ServiceReferenceRegistrator create() { return new ServiceReferenceRegistratorImpl(parentRegistrator, nullableTransactionName); } } }
inocybe/odl-controller
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReferenceRegistrator.java
Java
epl-1.0
4,300
/** */ package gluemodel.CIM.IEC61970.Informative.InfWork.util; import gluemodel.CIM.Element; import gluemodel.CIM.IEC61968.Common.ActivityRecord; import gluemodel.CIM.IEC61968.Common.Document; import gluemodel.CIM.IEC61968.Common.Location; import gluemodel.CIM.IEC61970.Core.IdentifiedObject; import gluemodel.CIM.IEC61970.Informative.InfAssets.ProcedureDataSet; import gluemodel.CIM.IEC61970.Informative.InfCommon.ScheduledEvent; import gluemodel.CIM.IEC61970.Informative.InfWork.*; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.util.Switch; /** * <!-- begin-user-doc --> * The <b>Switch</b> for the model's inheritance hierarchy. * It supports the call {@link #doSwitch(EObject) doSwitch(object)} * to invoke the <code>caseXXX</code> method for each class of the model, * starting with the actual class of the object * and proceeding up the inheritance hierarchy * until a non-null result is returned, * which is the result of the switch. * <!-- end-user-doc --> * @see gluemodel.CIM.IEC61970.Informative.InfWork.InfWorkPackage * @generated */ public class InfWorkSwitch<T> extends Switch<T> { /** * The cached model package * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static InfWorkPackage modelPackage; /** * Creates an instance of the switch. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public InfWorkSwitch() { if (modelPackage == null) { modelPackage = InfWorkPackage.eINSTANCE; } } /** * Checks whether this is a switch for the given package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param ePackage the package in question. * @return whether this is a switch for the given package. * @generated */ @Override protected boolean isSwitchFor(EPackage ePackage) { return ePackage == modelPackage; } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ @Override protected T doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { case InfWorkPackage.WORK_FLOW_STEP: { WorkFlowStep workFlowStep = (WorkFlowStep)theEObject; T result = caseWorkFlowStep(workFlowStep); if (result == null) result = caseIdentifiedObject(workFlowStep); if (result == null) result = caseElement(workFlowStep); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.WORK_COST_DETAIL: { WorkCostDetail workCostDetail = (WorkCostDetail)theEObject; T result = caseWorkCostDetail(workCostDetail); if (result == null) result = caseDocument(workCostDetail); if (result == null) result = caseIdentifiedObject(workCostDetail); if (result == null) result = caseElement(workCostDetail); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.USAGE: { Usage usage = (Usage)theEObject; T result = caseUsage(usage); if (result == null) result = caseIdentifiedObject(usage); if (result == null) result = caseElement(usage); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.WORK_COST_SUMMARY: { WorkCostSummary workCostSummary = (WorkCostSummary)theEObject; T result = caseWorkCostSummary(workCostSummary); if (result == null) result = caseDocument(workCostSummary); if (result == null) result = caseIdentifiedObject(workCostSummary); if (result == null) result = caseElement(workCostSummary); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.MISC_COST_ITEM: { MiscCostItem miscCostItem = (MiscCostItem)theEObject; T result = caseMiscCostItem(miscCostItem); if (result == null) result = caseIdentifiedObject(miscCostItem); if (result == null) result = caseElement(miscCostItem); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.CU_ALLOWABLE_ACTION: { CUAllowableAction cuAllowableAction = (CUAllowableAction)theEObject; T result = caseCUAllowableAction(cuAllowableAction); if (result == null) result = caseIdentifiedObject(cuAllowableAction); if (result == null) result = caseElement(cuAllowableAction); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.COST_TYPE: { CostType costType = (CostType)theEObject; T result = caseCostType(costType); if (result == null) result = caseIdentifiedObject(costType); if (result == null) result = caseElement(costType); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.CU_MATERIAL_ITEM: { CUMaterialItem cuMaterialItem = (CUMaterialItem)theEObject; T result = caseCUMaterialItem(cuMaterialItem); if (result == null) result = caseIdentifiedObject(cuMaterialItem); if (result == null) result = caseElement(cuMaterialItem); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.ASSIGNMENT: { Assignment assignment = (Assignment)theEObject; T result = caseAssignment(assignment); if (result == null) result = caseDocument(assignment); if (result == null) result = caseIdentifiedObject(assignment); if (result == null) result = caseElement(assignment); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.DESIGN: { Design design = (Design)theEObject; T result = caseDesign(design); if (result == null) result = caseDocument(design); if (result == null) result = caseIdentifiedObject(design); if (result == null) result = caseElement(design); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.BUSINESS_CASE: { BusinessCase businessCase = (BusinessCase)theEObject; T result = caseBusinessCase(businessCase); if (result == null) result = caseDocument(businessCase); if (result == null) result = caseIdentifiedObject(businessCase); if (result == null) result = caseElement(businessCase); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.EQUIPMENT_ITEM: { EquipmentItem equipmentItem = (EquipmentItem)theEObject; T result = caseEquipmentItem(equipmentItem); if (result == null) result = caseIdentifiedObject(equipmentItem); if (result == null) result = caseElement(equipmentItem); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.ONE_CALL_REQUEST: { OneCallRequest oneCallRequest = (OneCallRequest)theEObject; T result = caseOneCallRequest(oneCallRequest); if (result == null) result = caseDocument(oneCallRequest); if (result == null) result = caseIdentifiedObject(oneCallRequest); if (result == null) result = caseElement(oneCallRequest); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.LABOR_ITEM: { LaborItem laborItem = (LaborItem)theEObject; T result = caseLaborItem(laborItem); if (result == null) result = caseIdentifiedObject(laborItem); if (result == null) result = caseElement(laborItem); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.PROJECT: { Project project = (Project)theEObject; T result = caseProject(project); if (result == null) result = caseDocument(project); if (result == null) result = caseIdentifiedObject(project); if (result == null) result = caseElement(project); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.ACCESS_PERMIT: { AccessPermit accessPermit = (AccessPermit)theEObject; T result = caseAccessPermit(accessPermit); if (result == null) result = caseDocument(accessPermit); if (result == null) result = caseIdentifiedObject(accessPermit); if (result == null) result = caseElement(accessPermit); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.INSPECTION_DATA_SET: { InspectionDataSet inspectionDataSet = (InspectionDataSet)theEObject; T result = caseInspectionDataSet(inspectionDataSet); if (result == null) result = caseProcedureDataSet(inspectionDataSet); if (result == null) result = caseDocument(inspectionDataSet); if (result == null) result = caseIdentifiedObject(inspectionDataSet); if (result == null) result = caseElement(inspectionDataSet); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.REGULATION: { Regulation regulation = (Regulation)theEObject; T result = caseRegulation(regulation); if (result == null) result = caseDocument(regulation); if (result == null) result = caseIdentifiedObject(regulation); if (result == null) result = caseElement(regulation); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.SHIFT_PATTERN: { ShiftPattern shiftPattern = (ShiftPattern)theEObject; T result = caseShiftPattern(shiftPattern); if (result == null) result = caseIdentifiedObject(shiftPattern); if (result == null) result = caseElement(shiftPattern); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.NON_STANDARD_ITEM: { NonStandardItem nonStandardItem = (NonStandardItem)theEObject; T result = caseNonStandardItem(nonStandardItem); if (result == null) result = caseDocument(nonStandardItem); if (result == null) result = caseIdentifiedObject(nonStandardItem); if (result == null) result = caseElement(nonStandardItem); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.WORK_LOCATION: { WorkLocation workLocation = (WorkLocation)theEObject; T result = caseWorkLocation(workLocation); if (result == null) result = caseLocation(workLocation); if (result == null) result = caseIdentifiedObject(workLocation); if (result == null) result = caseElement(workLocation); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.DESIGN_LOCATION_CU: { DesignLocationCU designLocationCU = (DesignLocationCU)theEObject; T result = caseDesignLocationCU(designLocationCU); if (result == null) result = caseIdentifiedObject(designLocationCU); if (result == null) result = caseElement(designLocationCU); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.DESIGN_LOCATION: { DesignLocation designLocation = (DesignLocation)theEObject; T result = caseDesignLocation(designLocation); if (result == null) result = caseIdentifiedObject(designLocation); if (result == null) result = caseElement(designLocation); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.CU_LABOR_CODE: { CULaborCode cuLaborCode = (CULaborCode)theEObject; T result = caseCULaborCode(cuLaborCode); if (result == null) result = caseIdentifiedObject(cuLaborCode); if (result == null) result = caseElement(cuLaborCode); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.CONDITION_FACTOR: { ConditionFactor conditionFactor = (ConditionFactor)theEObject; T result = caseConditionFactor(conditionFactor); if (result == null) result = caseIdentifiedObject(conditionFactor); if (result == null) result = caseElement(conditionFactor); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.CU_WORK_EQUIPMENT_ITEM: { CUWorkEquipmentItem cuWorkEquipmentItem = (CUWorkEquipmentItem)theEObject; T result = caseCUWorkEquipmentItem(cuWorkEquipmentItem); if (result == null) result = caseIdentifiedObject(cuWorkEquipmentItem); if (result == null) result = caseElement(cuWorkEquipmentItem); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.QUALIFICATION_REQUIREMENT: { QualificationRequirement qualificationRequirement = (QualificationRequirement)theEObject; T result = caseQualificationRequirement(qualificationRequirement); if (result == null) result = caseIdentifiedObject(qualificationRequirement); if (result == null) result = caseElement(qualificationRequirement); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.CU_CONTRACTOR_ITEM: { CUContractorItem cuContractorItem = (CUContractorItem)theEObject; T result = caseCUContractorItem(cuContractorItem); if (result == null) result = caseIdentifiedObject(cuContractorItem); if (result == null) result = caseElement(cuContractorItem); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.MATERIAL_ITEM: { MaterialItem materialItem = (MaterialItem)theEObject; T result = caseMaterialItem(materialItem); if (result == null) result = caseIdentifiedObject(materialItem); if (result == null) result = caseElement(materialItem); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.PROPERTY_UNIT: { PropertyUnit propertyUnit = (PropertyUnit)theEObject; T result = casePropertyUnit(propertyUnit); if (result == null) result = caseIdentifiedObject(propertyUnit); if (result == null) result = caseElement(propertyUnit); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.COMPATIBLE_UNIT: { CompatibleUnit compatibleUnit = (CompatibleUnit)theEObject; T result = caseCompatibleUnit(compatibleUnit); if (result == null) result = caseDocument(compatibleUnit); if (result == null) result = caseIdentifiedObject(compatibleUnit); if (result == null) result = caseElement(compatibleUnit); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.WORK_TASK: { WorkTask workTask = (WorkTask)theEObject; T result = caseWorkTask(workTask); if (result == null) result = caseDocument(workTask); if (result == null) result = caseIdentifiedObject(workTask); if (result == null) result = caseElement(workTask); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.TYPE_MATERIAL: { TypeMaterial typeMaterial = (TypeMaterial)theEObject; T result = caseTypeMaterial(typeMaterial); if (result == null) result = caseDocument(typeMaterial); if (result == null) result = caseIdentifiedObject(typeMaterial); if (result == null) result = caseElement(typeMaterial); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.CAPABILITY: { Capability capability = (Capability)theEObject; T result = caseCapability(capability); if (result == null) result = caseIdentifiedObject(capability); if (result == null) result = caseElement(capability); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.CU_ASSET: { CUAsset cuAsset = (CUAsset)theEObject; T result = caseCUAsset(cuAsset); if (result == null) result = caseIdentifiedObject(cuAsset); if (result == null) result = caseElement(cuAsset); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.CONTRACTOR_ITEM: { ContractorItem contractorItem = (ContractorItem)theEObject; T result = caseContractorItem(contractorItem); if (result == null) result = caseIdentifiedObject(contractorItem); if (result == null) result = caseElement(contractorItem); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.INFO_QUESTION: { InfoQuestion infoQuestion = (InfoQuestion)theEObject; T result = caseInfoQuestion(infoQuestion); if (result == null) result = caseDocument(infoQuestion); if (result == null) result = caseIdentifiedObject(infoQuestion); if (result == null) result = caseElement(infoQuestion); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.WORK_STATUS_ENTRY: { WorkStatusEntry workStatusEntry = (WorkStatusEntry)theEObject; T result = caseWorkStatusEntry(workStatusEntry); if (result == null) result = caseActivityRecord(workStatusEntry); if (result == null) result = caseIdentifiedObject(workStatusEntry); if (result == null) result = caseElement(workStatusEntry); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.APPOINTMENT: { Appointment appointment = (Appointment)theEObject; T result = caseAppointment(appointment); if (result == null) result = caseScheduledEvent(appointment); if (result == null) result = caseIdentifiedObject(appointment); if (result == null) result = caseElement(appointment); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.MAINTENANCE_DATA_SET: { MaintenanceDataSet maintenanceDataSet = (MaintenanceDataSet)theEObject; T result = caseMaintenanceDataSet(maintenanceDataSet); if (result == null) result = caseProcedureDataSet(maintenanceDataSet); if (result == null) result = caseDocument(maintenanceDataSet); if (result == null) result = caseIdentifiedObject(maintenanceDataSet); if (result == null) result = caseElement(maintenanceDataSet); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.CU_GROUP: { CUGroup cuGroup = (CUGroup)theEObject; T result = caseCUGroup(cuGroup); if (result == null) result = caseIdentifiedObject(cuGroup); if (result == null) result = caseElement(cuGroup); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.CREW: { Crew crew = (Crew)theEObject; T result = caseCrew(crew); if (result == null) result = caseIdentifiedObject(crew); if (result == null) result = caseElement(crew); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.REQUEST: { Request request = (Request)theEObject; T result = caseRequest(request); if (result == null) result = caseDocument(request); if (result == null) result = caseIdentifiedObject(request); if (result == null) result = caseElement(request); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.OVERHEAD_COST: { OverheadCost overheadCost = (OverheadCost)theEObject; T result = caseOverheadCost(overheadCost); if (result == null) result = caseIdentifiedObject(overheadCost); if (result == null) result = caseElement(overheadCost); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.DIAGNOSIS_DATA_SET: { DiagnosisDataSet diagnosisDataSet = (DiagnosisDataSet)theEObject; T result = caseDiagnosisDataSet(diagnosisDataSet); if (result == null) result = caseProcedureDataSet(diagnosisDataSet); if (result == null) result = caseDocument(diagnosisDataSet); if (result == null) result = caseIdentifiedObject(diagnosisDataSet); if (result == null) result = caseElement(diagnosisDataSet); if (result == null) result = defaultCase(theEObject); return result; } case InfWorkPackage.CU_LABOR_ITEM: { CULaborItem cuLaborItem = (CULaborItem)theEObject; T result = caseCULaborItem(cuLaborItem); if (result == null) result = caseIdentifiedObject(cuLaborItem); if (result == null) result = caseElement(cuLaborItem); if (result == null) result = defaultCase(theEObject); return result; } default: return defaultCase(theEObject); } } /** * Returns the result of interpreting the object as an instance of '<em>Work Flow Step</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Work Flow Step</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseWorkFlowStep(WorkFlowStep object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Work Cost Detail</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Work Cost Detail</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseWorkCostDetail(WorkCostDetail object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Usage</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Usage</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseUsage(Usage object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Work Cost Summary</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Work Cost Summary</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseWorkCostSummary(WorkCostSummary object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Misc Cost Item</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Misc Cost Item</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseMiscCostItem(MiscCostItem object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>CU Allowable Action</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>CU Allowable Action</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseCUAllowableAction(CUAllowableAction object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Cost Type</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Cost Type</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseCostType(CostType object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>CU Material Item</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>CU Material Item</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseCUMaterialItem(CUMaterialItem object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Assignment</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Assignment</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseAssignment(Assignment object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Design</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Design</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseDesign(Design object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Business Case</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Business Case</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseBusinessCase(BusinessCase object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Equipment Item</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Equipment Item</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseEquipmentItem(EquipmentItem object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>One Call Request</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>One Call Request</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseOneCallRequest(OneCallRequest object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Labor Item</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Labor Item</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseLaborItem(LaborItem object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Project</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Project</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseProject(Project object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Access Permit</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Access Permit</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseAccessPermit(AccessPermit object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Inspection Data Set</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Inspection Data Set</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseInspectionDataSet(InspectionDataSet object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Regulation</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Regulation</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseRegulation(Regulation object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Shift Pattern</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Shift Pattern</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseShiftPattern(ShiftPattern object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Non Standard Item</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Non Standard Item</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseNonStandardItem(NonStandardItem object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Work Location</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Work Location</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseWorkLocation(WorkLocation object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Design Location CU</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Design Location CU</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseDesignLocationCU(DesignLocationCU object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Design Location</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Design Location</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseDesignLocation(DesignLocation object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>CU Labor Code</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>CU Labor Code</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseCULaborCode(CULaborCode object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Condition Factor</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Condition Factor</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseConditionFactor(ConditionFactor object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>CU Work Equipment Item</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>CU Work Equipment Item</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseCUWorkEquipmentItem(CUWorkEquipmentItem object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Qualification Requirement</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Qualification Requirement</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseQualificationRequirement(QualificationRequirement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>CU Contractor Item</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>CU Contractor Item</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseCUContractorItem(CUContractorItem object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Material Item</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Material Item</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseMaterialItem(MaterialItem object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Property Unit</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Property Unit</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casePropertyUnit(PropertyUnit object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Compatible Unit</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Compatible Unit</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseCompatibleUnit(CompatibleUnit object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Work Task</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Work Task</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseWorkTask(WorkTask object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Type Material</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Type Material</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseTypeMaterial(TypeMaterial object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Capability</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Capability</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseCapability(Capability object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>CU Asset</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>CU Asset</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseCUAsset(CUAsset object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Contractor Item</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Contractor Item</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseContractorItem(ContractorItem object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Info Question</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Info Question</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseInfoQuestion(InfoQuestion object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Work Status Entry</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Work Status Entry</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseWorkStatusEntry(WorkStatusEntry object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Appointment</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Appointment</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseAppointment(Appointment object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Maintenance Data Set</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Maintenance Data Set</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseMaintenanceDataSet(MaintenanceDataSet object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>CU Group</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>CU Group</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseCUGroup(CUGroup object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Crew</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Crew</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseCrew(Crew object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Request</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Request</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseRequest(Request object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Overhead Cost</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Overhead Cost</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseOverheadCost(OverheadCost object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Diagnosis Data Set</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Diagnosis Data Set</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseDiagnosisDataSet(DiagnosisDataSet object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>CU Labor Item</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>CU Labor Item</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseCULaborItem(CULaborItem object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Element</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Element</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseElement(Element object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Identified Object</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Identified Object</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseIdentifiedObject(IdentifiedObject object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Document</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Document</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseDocument(Document object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Procedure Data Set</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Procedure Data Set</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseProcedureDataSet(ProcedureDataSet object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Location</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Location</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseLocation(Location object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Activity Record</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Activity Record</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseActivityRecord(ActivityRecord object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Scheduled Event</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Scheduled Event</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseScheduledEvent(ScheduledEvent object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>EObject</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch, but this is the last case anyway. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>EObject</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) * @generated */ @Override public T defaultCase(EObject object) { return null; } } //InfWorkSwitch
SvenPeldszus/rgse.ttc17.emoflon.tgg
rgse.ttc17.metamodels.src/src/gluemodel/CIM/IEC61970/Informative/InfWork/util/InfWorkSwitch.java
Java
epl-1.0
49,834
package es.optsicom.lib.expresults.db; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import javax.persistence.EntityManager; import es.optsicom.lib.expresults.util.PropertiesManager; /** * * @author mica */ public class MySQLDBManager extends DBManager { private static final Logger log = Logger.getLogger(MySQLDBManager.class.getName()); private static final String DB_SCHEMA_DEFAULT_NAME = "optsicom2"; private static final String OPTSICOM_DB = "optsicom.db"; private static final String DB_HOST = "host"; private static final String DB_PORT = "port"; private static final String DB_USER = "user"; private static final String DB_PASSWORD = "password"; private static final String DB_SCHEMA = "schema"; private final String host; private final int port; private final String user; private final String password; private final String database; private enum DbRegenerationMode { // do not generate DDL; no schema is generated. NONE, // create DDL for all tables; drop all existing tables DROP_AND_CREATE_TABLES, // create DDL for non-existent tables; leave existing tables unchanged CREATE_TABLES } public MySQLDBManager() throws SQLException { this(false); } public MySQLDBManager(boolean create) throws SQLException { this(OPTSICOM_DB, create); } public MySQLDBManager(String host, int port, String user, String pass, String database) throws SQLException { this(host, port, user, pass, database, false); } public MySQLDBManager(String host, int port, String user, String password, String database, boolean create) throws SQLException { this.host = host; this.port = port; this.user = user; this.password = password; this.database = database; if (create) { createDatabase(); } connect(); } public MySQLDBManager(String db, boolean create) throws SQLException { PropertiesManager pm = PropertiesManager.getInstance(); db += "."; this.host = pm.getProperty(db + DB_HOST); this.port = Integer.parseInt(pm.getProperty(db + DB_PORT)); this.user = pm.getProperty(db + DB_USER); this.password = pm.getProperty(db + DB_PASSWORD); this.database = (pm.getProperty(db + DB_SCHEMA) != null) ? pm.getProperty(db + DB_SCHEMA) : DB_SCHEMA_DEFAULT_NAME; log.info(host + ":" + port + ":" + user + ":" + password + ":" + database); // TODO: fix this, createDatabase do not work // if (create) { // createDatabase(); // } connect(); } public MySQLDBManager(String db) throws SQLException { this(db, true); } private void createDatabase() { Map<String, String> properties = new HashMap<String, String>(); properties.put("eclipselink.jdbc.url", "jdbc:mysql://" + host + ":" + port + "/" + database); properties.put("eclipselink.jdbc.driver", "com.mysql.cj.jdbc.Driver"); properties.put("eclipselink.logging.level", "WARNING"); properties.put("eclipselink.target-database", "MYSQL"); properties.put("eclipselink.jdbc.user", user); properties.put("eclipselink.jdbc.password", password); // DbRegenerationMode dbRegenerationModeEnum = // DbRegenerationMode.DROP_AND_CREATE_TABLES; DbRegenerationMode dbRegenerationModeEnum = DbRegenerationMode.CREATE_TABLES; String dbRegenerationMode = getRegenerationModeString(dbRegenerationModeEnum); properties.put("eclipselink.ddl-generation", dbRegenerationMode); // properties.put("toplink.ddl-generation.output-mode", "database"); // This property creates dll file in disk properties.put("eclipselink.ddl-generation.output-mode", "both"); entityManagerFactory = javax.persistence.Persistence.createEntityManagerFactory("optsicom", properties); // try { // entityManagerFactory.createEntityManager().createQuery("SELECT e FROM // EXPERIMENT e"); // } catch(IllegalArgumentException e) { // log.info("Database doesn't exist. Creating it."); // // entityManagerFactory.close(); // // // Try to create the tables // dbRegenerationModeEnum = DbRegenerationMode.CREATE_TABLES; // // dbRegenerationMode = // getRegenerationModeString(dbRegenerationModeEnum); // // properties.put("eclipselink.ddl-generation", dbRegenerationMode); // // //properties.put("toplink.ddl-generation.output-mode", "database"); // // entityManagerFactory = javax.persistence.Persistence // .createEntityManagerFactory("optsicom", properties); // } log.info("Created database: " + entityManagerFactory.getProperties().get("eclipselink.jdbc.url")); entityManagerFactory.close(); } /** * JPA LogLevel. Values:<br/> * <ul> * <li>OFF: This setting disables the generation of the log output. You may * want to set logging to OFF during production to avoid the overhead of * logging.</li> * <li>SEVERE: This level enables reporting of failure cases only. Usually, * if the failure occurs, the application stops.</li> * <li>WARNING: This level enables logging of issues that have a potential * to cause problems. For example, a setting that is picked by the * application and not by the user.</li> * <li>INFO This level enables the standard output. The contents of this * output is very limited.</li> * <li>CONFIG: This level enables logging of such configuration details as * your database login information and some metadata information. You may * want to use the CONFIG log level at deployment time.</li> * <li>FINE: This level enables logging of the first level of the debugging * information and SQL. You may want to use this log level during debugging * and testing, but not at production.</li> * <li>FINER: This level enables logging of more debugging information than * the FINE setting. For example, the transaction information is logged at * this level. You may want to use this log level during debugging and * testing, but not at production.</li> * <li>FINEST: This level enables logging of more debugging information than * the FINER setting, such as a very detailed information about certain * features (for example, sequencing). You may want to use this log level * during debugging and testing, but not at production.</li> * </ul> * * @throws SQLException */ @Override protected void connect() throws SQLException { Map<String, String> properties = new HashMap<String, String>(); properties.put("eclipselink.jdbc.url", "jdbc:mysql://" + host + ":" + port + "/" + database); properties.put("eclipselink.jdbc.driver", "com.mysql.cj.jdbc.Driver"); properties.put("eclipselink.logging.level", "WARNING"); properties.put("eclipselink.target-database", "MYSQL"); properties.put("eclipselink.jdbc.user", user); properties.put("eclipselink.jdbc.password", password); // DbRegenerationMode dbRegenerationModeEnum = // DbRegenerationMode.DROP_AND_CREATE_TABLES; DbRegenerationMode dbRegenerationModeEnum = DbRegenerationMode.CREATE_TABLES; String dbRegenerationMode = getRegenerationModeString(dbRegenerationModeEnum); properties.put("eclipselink.ddl-generation", dbRegenerationMode); // properties.put("toplink.ddl-generation.output-mode", "database"); // This property creates dll file in disk properties.put("eclipselink.ddl-generation.output-mode", "both"); entityManagerFactory = javax.persistence.Persistence.createEntityManagerFactory("optsicom", properties); // try { // entityManagerFactory.createEntityManager().createQuery("SELECT e FROM // EXPERIMENT e"); // } catch(IllegalArgumentException e) { // log.info("Database doesn't exist. Creating it."); // // entityManagerFactory.close(); // // // Try to create the tables // dbRegenerationModeEnum = DbRegenerationMode.CREATE_TABLES; // // dbRegenerationMode = // getRegenerationModeString(dbRegenerationModeEnum); // // properties.put("eclipselink.ddl-generation", dbRegenerationMode); // // //properties.put("toplink.ddl-generation.output-mode", "database"); // // entityManagerFactory = javax.persistence.Persistence // .createEntityManagerFactory("optsicom", properties); // } log.info("Connected to database: " + entityManagerFactory.getProperties().get("eclipselink.jdbc.url")); } private String getRegenerationModeString(DbRegenerationMode dbRegenerationModeEnum) { String dbRegenerationMode = null; switch (dbRegenerationModeEnum) { case NONE: dbRegenerationMode = "none"; break; case CREATE_TABLES: dbRegenerationMode = "create-tables"; break; case DROP_AND_CREATE_TABLES: dbRegenerationMode = "drop-and-create-tables"; break; } return dbRegenerationMode; } @Override public EntityManager createEntityManager() { return entityManagerFactory.createEntityManager(); } }
codeurjc/optsicom-framework
es.optsicom.lib.analysis/src/main/java/es/optsicom/lib/expresults/db/MySQLDBManager.java
Java
epl-1.0
8,702
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ package org.apache.cxf.interceptor; import java.io.OutputStream; import java.io.Writer; import java.util.ResourceBundle; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.apache.cxf.common.i18n.BundleUtils; import org.apache.cxf.message.Message; import org.apache.cxf.phase.AbstractPhaseInterceptor; import org.apache.cxf.phase.Phase; import org.apache.cxf.staxutils.StaxUtils; import com.ibm.websphere.ras.annotation.Sensitive; import com.ibm.websphere.ras.annotation.Trivial; public class StaxOutEndingInterceptor extends AbstractPhaseInterceptor<Message> { private static final ResourceBundle BUNDLE = BundleUtils.getBundle(StaxOutEndingInterceptor.class); private String outStreamHolder; private String writerHolder; @Trivial public StaxOutEndingInterceptor(String outStreamHolder) { this(outStreamHolder, null); } @Trivial public StaxOutEndingInterceptor(String outStreamHolder, String writerHolder) { super(Phase.PRE_STREAM_ENDING); getAfter().add(AttachmentOutInterceptor.AttachmentOutEndingInterceptor.class.getName()); this.outStreamHolder = outStreamHolder; this.writerHolder = writerHolder; } public void handleMessage(@Sensitive Message message) throws Fault { try { XMLStreamWriter xtw = message.getContent(XMLStreamWriter.class); if (xtw != null) { try { xtw.writeEndDocument(); xtw.flush(); } finally { StaxUtils.close(xtw); } } OutputStream os = (OutputStream)message.get(outStreamHolder); if (os != null) { message.setContent(OutputStream.class, os); } if (writerHolder != null) { Writer w = (Writer)message.get(writerHolder); if (w != null) { message.setContent(Writer.class, w); } } message.removeContent(XMLStreamWriter.class); } catch (XMLStreamException e) { throw new Fault(new org.apache.cxf.common.i18n.Message("STAX_WRITE_EXC", BUNDLE), e); } } }
OpenLiberty/open-liberty
dev/com.ibm.ws.org.apache.cxf.cxf.api.2.6.2/src/org/apache/cxf/interceptor/StaxOutEndingInterceptor.java
Java
epl-1.0
3,089
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.config.yangjmxgenerator.plugin; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import org.opendaylight.controller.config.spi.ModuleFactory; import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry; import org.opendaylight.controller.config.yangjmxgenerator.PackageTranslator; import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry; import org.opendaylight.controller.config.yangjmxgenerator.TypeProviderWrapper; import org.opendaylight.yangtools.sal.binding.yang.types.TypeProviderImpl; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang2sources.spi.CodeGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.impl.StaticLoggerBinder; /** * This class interfaces with yang-maven-plugin. Gets parsed yang modules in * {@link SchemaContext}, and parameters form the plugin configuration, and * writes service interfaces and/or modules. */ public class JMXGenerator implements CodeGenerator { static final String NAMESPACE_TO_PACKAGE_DIVIDER = "=="; static final String NAMESPACE_TO_PACKAGE_PREFIX = "namespaceToPackage"; static final String MODULE_FACTORY_FILE_BOOLEAN = "moduleFactoryFile"; private PackageTranslator packageTranslator; private final CodeWriter codeWriter; private static final Logger logger = LoggerFactory .getLogger(JMXGenerator.class); private Map<String, String> namespaceToPackageMapping; private File resourceBaseDir; private File projectBaseDir; private boolean generateModuleFactoryFile = true; public JMXGenerator() { this.codeWriter = new FreeMarkerCodeWriterImpl(); } public JMXGenerator(CodeWriter codeWriter) { this.codeWriter = codeWriter; } @Override public Collection<File> generateSources(SchemaContext context, File outputBaseDir, Set<Module> yangModulesInCurrentMavenModule) { Preconditions.checkArgument(context != null, "Null context received"); Preconditions.checkArgument(outputBaseDir != null, "Null outputBaseDir received"); Preconditions .checkArgument(namespaceToPackageMapping != null && !namespaceToPackageMapping.isEmpty(), "No namespace to package mapping provided in additionalConfiguration"); packageTranslator = new PackageTranslator(namespaceToPackageMapping); if (!outputBaseDir.exists()) outputBaseDir.mkdirs(); GeneratedFilesTracker generatedFiles = new GeneratedFilesTracker(); // create SIE structure qNamesToSIEs Map<QName, ServiceInterfaceEntry> qNamesToSIEs = new HashMap<>(); Map<IdentitySchemaNode, ServiceInterfaceEntry> knownSEITracker = new HashMap<>(); for (Module module : context.getModules()) { String packageName = packageTranslator.getPackageName(module); Map<QName, ServiceInterfaceEntry> namesToSIEntries = ServiceInterfaceEntry .create(module, packageName, knownSEITracker); for (Entry<QName, ServiceInterfaceEntry> sieEntry : namesToSIEntries .entrySet()) { // merge value into qNamesToSIEs if (qNamesToSIEs.containsKey(sieEntry.getKey()) == false) { qNamesToSIEs.put(sieEntry.getKey(), sieEntry.getValue()); } else { throw new IllegalStateException( "Cannot add two SIE with same qname " + sieEntry.getValue()); } } if (yangModulesInCurrentMavenModule.contains(module)) { // write this sie to disk for (ServiceInterfaceEntry sie : namesToSIEntries.values()) { try { generatedFiles.addFile(codeWriter.writeSie(sie, outputBaseDir)); } catch (Exception e) { throw new RuntimeException( "Error occurred during SIE source generate phase", e); } } } } File mainBaseDir = concatFolders(projectBaseDir, "src", "main", "java"); Preconditions.checkNotNull(resourceBaseDir, "resource base dir attribute was null"); StringBuffer fullyQualifiedNamesOfFactories = new StringBuffer(); // create MBEs for (Module module : yangModulesInCurrentMavenModule) { String packageName = packageTranslator.getPackageName(module); Map<String /* MB identity local name */, ModuleMXBeanEntry> namesToMBEs = ModuleMXBeanEntry .create(module, qNamesToSIEs, context, new TypeProviderWrapper(new TypeProviderImpl(context)), packageName); for (Entry<String, ModuleMXBeanEntry> mbeEntry : namesToMBEs .entrySet()) { ModuleMXBeanEntry mbe = mbeEntry.getValue(); try { List<File> files1 = codeWriter.writeMbe(mbe, outputBaseDir, mainBaseDir, resourceBaseDir); generatedFiles.addFile(files1); } catch (Exception e) { throw new RuntimeException( "Error occurred during MBE source generate phase", e); } fullyQualifiedNamesOfFactories.append(mbe .getFullyQualifiedName(mbe.getStubFactoryName())); fullyQualifiedNamesOfFactories.append("\n"); } } // create ModuleFactory file if needed if (fullyQualifiedNamesOfFactories.length() > 0 && generateModuleFactoryFile) { File serviceLoaderFile = JMXGenerator.concatFolders( resourceBaseDir, "META-INF", "services", ModuleFactory.class.getName()); // if this file does not exist, create empty file serviceLoaderFile.getParentFile().mkdirs(); try { serviceLoaderFile.createNewFile(); FileUtils.write(serviceLoaderFile, fullyQualifiedNamesOfFactories.toString()); } catch (IOException e) { String message = "Cannot write to " + serviceLoaderFile; logger.error(message); throw new RuntimeException(message, e); } } return generatedFiles.getFiles(); } static File concatFolders(File projectBaseDir, String... folderNames) { StringBuilder b = new StringBuilder(); for (String folder : folderNames) { b.append(folder); b.append(File.separator); } return new File(projectBaseDir, b.toString()); } @Override public void setAdditionalConfig(Map<String, String> additionalCfg) { if (logger != null) logger.debug(getClass().getCanonicalName(), ": Additional configuration received: ", additionalCfg.toString()); this.namespaceToPackageMapping = extractNamespaceMapping(additionalCfg); this.generateModuleFactoryFile = extractModuleFactoryBoolean(additionalCfg); } private boolean extractModuleFactoryBoolean( Map<String, String> additionalCfg) { String bool = additionalCfg.get(MODULE_FACTORY_FILE_BOOLEAN); if (bool == null) return true; if (bool.equals("false")) return false; return true; } @Override public void setLog(Log log) { StaticLoggerBinder.getSingleton().setMavenLog(log); } private static Map<String, String> extractNamespaceMapping( Map<String, String> additionalCfg) { Map<String, String> namespaceToPackage = Maps.newHashMap(); for (String key : additionalCfg.keySet()) { if (key.startsWith(NAMESPACE_TO_PACKAGE_PREFIX)) { String mapping = additionalCfg.get(key); NamespaceMapping mappingResolved = extractNamespaceMapping(mapping); namespaceToPackage.put(mappingResolved.namespace, mappingResolved.packageName); } } return namespaceToPackage; } static Pattern namespaceMappingPattern = Pattern.compile("(.+)" + NAMESPACE_TO_PACKAGE_DIVIDER + "(.+)"); private static NamespaceMapping extractNamespaceMapping(String mapping) { Matcher matcher = namespaceMappingPattern.matcher(mapping); Preconditions .checkArgument(matcher.matches(), String.format("Namespace to package mapping:%s is in invalid " + "format, requested format is: %s", mapping, namespaceMappingPattern)); return new NamespaceMapping(matcher.group(1), matcher.group(2)); } private static class NamespaceMapping { public NamespaceMapping(String namespace, String packagename) { this.namespace = namespace; this.packageName = packagename; } private final String namespace, packageName; } @Override public void setResourceBaseDir(File resourceDir) { this.resourceBaseDir = resourceDir; } @Override public void setMavenProject(MavenProject project) { this.projectBaseDir = project.getBasedir(); if (logger != null) logger.debug(getClass().getCanonicalName(), " project base dir: ", projectBaseDir); } @VisibleForTesting static class GeneratedFilesTracker { private final Set<File> files = Sets.newHashSet(); void addFile(File file) { if (files.contains(file)) { List<File> undeletedFiles = Lists.newArrayList(); for (File presentFile : files) { if (presentFile.delete() == false) { undeletedFiles.add(presentFile); } } if (undeletedFiles.isEmpty() == false) { logger.error( "Illegal state occurred: Unable to delete already generated files, undeleted files: {}", undeletedFiles); } throw new IllegalStateException( "Name conflict in generated files, file" + file + " present twice"); } files.add(file); } void addFile(Collection<File> files) { for (File file : files) { addFile(file); } } public Set<File> getFiles() { return files; } } }
yuyf10/opendaylight-controller
opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGenerator.java
Java
epl-1.0
12,033
/* * Copyright (c) 2012-2018 Red Hat, Inc. * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.multiuser.keycloak.server; import static java.nio.charset.StandardCharsets.UTF_8; import static javax.ws.rs.HttpMethod.POST; import static org.eclipse.che.multiuser.keycloak.shared.KeycloakConstants.*; import com.google.common.base.Strings; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import org.eclipse.che.api.core.ApiException; import org.eclipse.che.api.core.ServerException; import org.eclipse.che.api.core.notification.EventService; import org.eclipse.che.api.core.rest.HttpJsonRequestFactory; import org.eclipse.che.api.user.server.event.BeforeUserRemovedEvent; import org.eclipse.che.commons.annotation.Nullable; import org.eclipse.che.commons.lang.IoUtil; import org.eclipse.che.core.db.cascade.CascadeEventSubscriber; import org.eclipse.che.inject.ConfigurationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Remove user from Keycloak server on {@link * org.eclipse.che.api.user.server.event.BeforeUserRemovedEvent}. Turn on with {@code * che.keycloak.cascade_user_removal_enabled} property. * * <p>For correct work need to set keycloak admin credentials via {@code * che.keycloak.admin_username} and {@code che.keycloak.admin_password} properties. */ @Singleton public class KeycloakUserRemover { private static final Logger LOG = LoggerFactory.getLogger(KeycloakUserRemover.class); private final String keycloakUser; private final String keycloakPassword; private final HttpJsonRequestFactory requestFactory; private String keycloakRemoveUserUrl; private String keycloakTokenEndpoint; @Inject public KeycloakUserRemover( @Nullable @Named("che.keycloak.cascade_user_removal_enabled") boolean userRemovalEnabled, @Nullable @Named("che.keycloak.admin_username") String keycloakUser, @Nullable @Named("che.keycloak.admin_password") String keycloakPassword, KeycloakSettings keycloakSettings, OIDCInfo oidcInfo, HttpJsonRequestFactory requestFactory) { this.keycloakUser = keycloakUser; this.keycloakPassword = keycloakPassword; this.requestFactory = requestFactory; if (userRemovalEnabled) { String serverUrl = oidcInfo.getAuthServerURL(); if (serverUrl == null) { throw new ConfigurationException( AUTH_SERVER_URL_SETTING + " or " + AUTH_SERVER_URL_INTERNAL_SETTING + " is not configured"); } String realm = keycloakSettings.get().get(REALM_SETTING); if (realm == null) { throw new ConfigurationException(REALM_SETTING + " is not configured"); } if (Strings.isNullOrEmpty(keycloakUser) || Strings.isNullOrEmpty(keycloakPassword)) { throw new ConfigurationException("Keycloak administrator username or password not set."); } this.keycloakTokenEndpoint = serverUrl + "/realms/master/protocol/openid-connect/token"; this.keycloakRemoveUserUrl = serverUrl + "/admin/realms/" + realm + "/users/"; } } /** * Remove user from Keycloak server by given user id. * * @param userId the user if to remove * @throws ServerException when can't remove user from Keycloak */ public void removeUserFromKeycloak(String userId) throws ServerException { try { String token = requestToken(); int responseCode = requestFactory .fromUrl(keycloakRemoveUserUrl + userId) .setAuthorizationHeader("Bearer " + token) .useDeleteMethod() .request() .getResponseCode(); if (responseCode != 204) { throw new ServerException("Can't remove user from Keycloak. UserId:" + userId); } } catch (IOException | ApiException e) { LOG.warn("Exception during removing user from Keycloak", e); throw new ServerException("Exception during removing user from Keycloak", e); } } private String requestToken() throws ServerException { String accessToken = ""; HttpURLConnection http = null; try { http = (HttpURLConnection) new URL(keycloakTokenEndpoint).openConnection(); http.setConnectTimeout(60000); http.setReadTimeout(60000); http.setRequestMethod(POST); http.setAllowUserInteraction(false); http.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED); http.setInstanceFollowRedirects(true); http.setDoOutput(true); StringBuilder sb = new StringBuilder(); sb.append("grant_type=password") .append("&username=") .append(keycloakUser) .append("&password=") .append(keycloakPassword) .append("&client_id=admin-cli"); try (OutputStream output = http.getOutputStream()) { output.write(sb.toString().getBytes(UTF_8)); } if (http.getResponseCode() != 200) { throw new ServerException( "Cannot get Keycloak access token. Server response: " + keycloakTokenEndpoint + " " + http.getResponseCode() + IoUtil.readStream(http.getErrorStream())); } final BufferedReader response = new BufferedReader(new InputStreamReader(http.getInputStream(), UTF_8)); JsonParser jsonParser = new JsonParser(); JsonElement jsonElement = jsonParser.parse(response); JsonObject asJsonObject = jsonElement.getAsJsonObject(); if (asJsonObject.has("access_token")) { accessToken = asJsonObject.get("access_token").getAsString(); } } catch (IOException | JsonSyntaxException ex) { LOG.error(ex.getMessage(), ex); throw new ServerException("Cannot get Keycloak access token.", ex); } finally { if (http != null) { http.disconnect(); } } return accessToken; } @Singleton public static class RemoveUserListener extends CascadeEventSubscriber<BeforeUserRemovedEvent> { @Inject private EventService eventService; @Inject private KeycloakUserRemover keycloakUserRemover; @Inject @Nullable @Named("che.keycloak.cascade_user_removal_enabled") boolean userRemovalEnabled; @PostConstruct public void subscribe() { if (userRemovalEnabled) { eventService.subscribe(this, BeforeUserRemovedEvent.class); } } @PreDestroy public void unsubscribe() { if (userRemovalEnabled) { eventService.unsubscribe(this, BeforeUserRemovedEvent.class); } } @Override public void onCascadeEvent(BeforeUserRemovedEvent event) throws Exception { keycloakUserRemover.removeUserFromKeycloak(event.getUser().getId()); } } }
codenvy/che
multiuser/keycloak/che-multiuser-keycloak-user-remover/src/main/java/org/eclipse/che/multiuser/keycloak/server/KeycloakUserRemover.java
Java
epl-1.0
7,509
/******************************************************************************* * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.wst.jsdt.internal.ui.text.java; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jface.text.contentassist.IContextInformationExtension; import org.eclipse.jface.text.link.LinkedModeModel; import org.eclipse.jface.text.link.LinkedModeUI; import org.eclipse.jface.text.link.LinkedPosition; import org.eclipse.jface.text.link.LinkedPositionGroup; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.texteditor.link.EditorLinkedModeUI; import org.eclipse.wst.jsdt.core.CompletionProposal; import org.eclipse.wst.jsdt.core.IType; import org.eclipse.wst.jsdt.core.JavaScriptModelException; import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin; import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorHighlightingSynchronizer; import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor; import org.eclipse.wst.jsdt.ui.text.java.JavaContentAssistInvocationContext; /** * Proposal for generic types. * <p> * Only used when compliance is set to 5.0 or higher. * </p> */ public final class LazyGenericTypeProposal extends LazyJavaTypeCompletionProposal { /** Triggers for types. Do not modify. */ private final static char[] GENERIC_TYPE_TRIGGERS= new char[] { '.', '\t', '[', '(', '<', ' ' }; /** * Short-lived context information object for generic types. Currently, these * are only created after inserting a type proposal, as core doesn't give us * the correct type proposal from within SomeType<|>. */ private static class ContextInformation implements IContextInformation, IContextInformationExtension { private final String fInformationDisplayString; private final String fContextDisplayString; private final Image fImage; private final int fPosition; ContextInformation(LazyGenericTypeProposal proposal) { // don't cache the proposal as content assistant // might hang on to the context info fContextDisplayString= proposal.getDisplayString(); fInformationDisplayString= computeContextString(proposal); fImage= proposal.getImage(); fPosition= proposal.getReplacementOffset() + proposal.getReplacementString().indexOf('<') + 1; } /* * @see org.eclipse.jface.text.contentassist.IContextInformation#getContextDisplayString() */ public String getContextDisplayString() { return fContextDisplayString; } /* * @see org.eclipse.jface.text.contentassist.IContextInformation#getImage() */ public Image getImage() { return fImage; } /* * @see org.eclipse.jface.text.contentassist.IContextInformation#getInformationDisplayString() */ public String getInformationDisplayString() { return fInformationDisplayString; } private String computeContextString(LazyGenericTypeProposal proposal) { try { TypeArgumentProposal[] proposals= proposal.computeTypeArgumentProposals(); if (proposals.length == 0) return null; StringBuffer buf= new StringBuffer(); for (int i= 0; i < proposals.length; i++) { buf.append(proposals[i].getDisplayName()); if (i < proposals.length - 1) buf.append(", "); //$NON-NLS-1$ } return buf.toString(); } catch (JavaScriptModelException e) { return null; } } /* * @see org.eclipse.jface.text.contentassist.IContextInformationExtension#getContextInformationPosition() */ public int getContextInformationPosition() { return fPosition; } /* * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (obj instanceof ContextInformation) { ContextInformation ci= (ContextInformation) obj; return getContextInformationPosition() == ci.getContextInformationPosition() && getInformationDisplayString().equals(ci.getInformationDisplayString()); } return false; } } private static final class TypeArgumentProposal { private final boolean fIsAmbiguous; private final String fProposal; private final String fTypeDisplayName; TypeArgumentProposal(String proposal, boolean ambiguous, String typeDisplayName) { fIsAmbiguous= ambiguous; fProposal= proposal; fTypeDisplayName= typeDisplayName; } public String getDisplayName() { return fTypeDisplayName; } boolean isAmbiguous() { return fIsAmbiguous; } String getProposals() { return fProposal; } public String toString() { return fProposal; } } private IRegion fSelectedRegion; // initialized by apply() private TypeArgumentProposal[] fTypeArgumentProposals; public LazyGenericTypeProposal(CompletionProposal typeProposal, JavaContentAssistInvocationContext context) { super(typeProposal, context); } /* * @see ICompletionProposalExtension#apply(IDocument, char) */ public void apply(IDocument document, char trigger, int offset) { if (shouldAppendArguments(document, offset, trigger)) { try { TypeArgumentProposal[] typeArgumentProposals= computeTypeArgumentProposals(); if (typeArgumentProposals.length > 0) { int[] offsets= new int[typeArgumentProposals.length]; int[] lengths= new int[typeArgumentProposals.length]; StringBuffer buffer= createParameterList(typeArgumentProposals, offsets, lengths); // set the generic type as replacement string boolean insertClosingParenthesis= trigger == '(' && autocloseBrackets(); if (insertClosingParenthesis) updateReplacementWithParentheses(buffer); super.setReplacementString(buffer.toString()); // add import & remove package, update replacement offset super.apply(document, '\0', offset); if (getTextViewer() != null) { if (hasAmbiguousProposals(typeArgumentProposals)) { adaptOffsets(offsets, buffer); installLinkedMode(document, offsets, lengths, typeArgumentProposals, insertClosingParenthesis); } else { if (insertClosingParenthesis) setUpLinkedMode(document, ')'); else fSelectedRegion= new Region(getReplacementOffset() + getReplacementString().length(), 0); } } return; } } catch (JavaScriptModelException e) { // log and continue JavaScriptPlugin.log(e); } } // default is to use the super implementation // reasons: // - not a parameterized type, // - already followed by <type arguments> // - proposal type does not inherit from expected type super.apply(document, trigger, offset); } /* * @see org.eclipse.wst.jsdt.internal.ui.text.java.LazyJavaTypeCompletionProposal#computeTriggerCharacters() */ protected char[] computeTriggerCharacters() { return GENERIC_TYPE_TRIGGERS; } /** * Adapt the parameter offsets to any modification of the replacement * string done by <code>apply</code>. For example, applying the proposal * may add an import instead of inserting the fully qualified name. * <p> * This assumes that modifications happen only at the beginning of the * replacement string and do not touch the type arguments list. * </p> * * @param offsets the offsets to modify * @param buffer the original replacement string */ private void adaptOffsets(int[] offsets, StringBuffer buffer) { String replacementString= getReplacementString(); int delta= buffer.length() - replacementString.length(); // due to using an import instead of package for (int i= 0; i < offsets.length; i++) { offsets[i]-= delta; } } /** * Computes the type argument proposals for this type proposals. If there is * an expected type binding that is a super type of the proposed type, the * wildcard type arguments of the proposed type that can be mapped through * to type the arguments of the expected type binding are bound accordingly. * <p> * For type arguments that cannot be mapped to arguments in the expected * type, or if there is no expected type, the upper bound of the type * argument is proposed. * </p> * <p> * The argument proposals have their <code>isAmbiguos</code> flag set to * <code>false</code> if the argument can be mapped to a non-wildcard type * argument in the expected type, otherwise the proposal is ambiguous. * </p> * * @return the type argument proposals for the proposed type * @throws JavaScriptModelException if accessing the java model fails */ private TypeArgumentProposal[] computeTypeArgumentProposals() throws JavaScriptModelException { if (fTypeArgumentProposals == null) { IType type= (IType) getJavaElement(); if (type == null) return new TypeArgumentProposal[0]; return new TypeArgumentProposal[0]; } return fTypeArgumentProposals; } /** * Returns <code>true</code> if type arguments should be appended when * applying this proposal, <code>false</code> if not (for example if the * document already contains a type argument list after the insertion point. * * @param document the document * @param offset the insertion offset * @param trigger the trigger character * @return <code>true</code> if arguments should be appended */ private boolean shouldAppendArguments(IDocument document, int offset, char trigger) { /* * No argument list if there were any special triggers (for example a period to qualify an * inner type). */ if (trigger != '\0' && trigger != '<' && trigger != '(') return false; /* No argument list if the completion is empty (already within the argument list). */ char[] completion= fProposal.getCompletion(); if (completion.length == 0) return false; /* No argument list if there already is a generic signature behind the name. */ try { IRegion region= document.getLineInformationOfOffset(offset); String line= document.get(region.getOffset(), region.getLength()); int index= offset - region.getOffset(); while (index != line.length() && Character.isUnicodeIdentifierPart(line.charAt(index))) ++index; if (index == line.length()) return true; char ch= line.charAt(index); return ch != '<'; } catch (BadLocationException e) { return true; } } private StringBuffer createParameterList(TypeArgumentProposal[] typeArguments, int[] offsets, int[] lengths) { StringBuffer buffer= new StringBuffer(); buffer.append(getReplacementString()); FormatterPrefs prefs= getFormatterPrefs(); final char LESS= '<'; final char GREATER= '>'; if (prefs.beforeOpeningBracket) buffer.append(SPACE); buffer.append(LESS); if (prefs.afterOpeningBracket) buffer.append(SPACE); StringBuffer separator= new StringBuffer(3); if (prefs.beforeTypeArgumentComma) separator.append(SPACE); separator.append(COMMA); if (prefs.afterTypeArgumentComma) separator.append(SPACE); for (int i= 0; i != typeArguments.length; i++) { if (i != 0) buffer.append(separator); offsets[i]= buffer.length(); buffer.append(typeArguments[i]); lengths[i]= buffer.length() - offsets[i]; } if (prefs.beforeClosingBracket) buffer.append(SPACE); buffer.append(GREATER); return buffer; } private void installLinkedMode(IDocument document, int[] offsets, int[] lengths, TypeArgumentProposal[] typeArgumentProposals, boolean withParentheses) { int replacementOffset= getReplacementOffset(); String replacementString= getReplacementString(); try { LinkedModeModel model= new LinkedModeModel(); for (int i= 0; i != offsets.length; i++) { if (typeArgumentProposals[i].isAmbiguous()) { LinkedPositionGroup group= new LinkedPositionGroup(); group.addPosition(new LinkedPosition(document, replacementOffset + offsets[i], lengths[i])); model.addGroup(group); } } if (withParentheses) { LinkedPositionGroup group= new LinkedPositionGroup(); group.addPosition(new LinkedPosition(document, replacementOffset + getCursorPosition(), 0)); model.addGroup(group); } model.forceInstall(); JavaEditor editor= getJavaEditor(); if (editor != null) { model.addLinkingListener(new EditorHighlightingSynchronizer(editor)); } LinkedModeUI ui= new EditorLinkedModeUI(model, getTextViewer()); ui.setExitPolicy(new ExitPolicy(withParentheses ? ')' : '>', document)); ui.setExitPosition(getTextViewer(), replacementOffset + replacementString.length(), 0, Integer.MAX_VALUE); ui.setDoContextInfo(true); ui.enter(); fSelectedRegion= ui.getSelectedRegion(); } catch (BadLocationException e) { JavaScriptPlugin.log(e); openErrorDialog(e); } } private boolean hasAmbiguousProposals(TypeArgumentProposal[] typeArgumentProposals) { boolean hasAmbiguousProposals= false; for (int i= 0; i < typeArgumentProposals.length; i++) { if (typeArgumentProposals[i].isAmbiguous()) { hasAmbiguousProposals= true; break; } } return hasAmbiguousProposals; } /** * Returns the currently active java editor, or <code>null</code> if it * cannot be determined. * * @return the currently active java editor, or <code>null</code> */ private JavaEditor getJavaEditor() { IEditorPart part= JavaScriptPlugin.getActivePage().getActiveEditor(); if (part instanceof JavaEditor) return (JavaEditor) part; else return null; } /* * @see ICompletionProposal#getSelection(IDocument) */ public Point getSelection(IDocument document) { if (fSelectedRegion == null) return super.getSelection(document); return new Point(fSelectedRegion.getOffset(), fSelectedRegion.getLength()); } private void openErrorDialog(BadLocationException e) { Shell shell= getTextViewer().getTextWidget().getShell(); MessageDialog.openError(shell, JavaTextMessages.FilledArgumentNamesMethodProposal_error_msg, e.getMessage()); } /* * @see org.eclipse.wst.jsdt.internal.ui.text.java.LazyJavaCompletionProposal#computeContextInformation() */ protected IContextInformation computeContextInformation() { try { if (hasParameters()) { TypeArgumentProposal[] proposals= computeTypeArgumentProposals(); if (hasAmbiguousProposals(proposals)) return new ContextInformation(this); } } catch (JavaScriptModelException e) { } return super.computeContextInformation(); } protected int computeCursorPosition() { if (fSelectedRegion != null) return fSelectedRegion.getOffset() - getReplacementOffset(); return super.computeCursorPosition(); } private boolean hasParameters() { IType type= (IType) getJavaElement(); if (type == null) return false; return false; } }
boniatillo-com/PhaserEditor
source/thirdparty/jsdt/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/LazyGenericTypeProposal.java
Java
epl-1.0
15,206
package io.liveoak.scripts.scheduled.manager; import org.jboss.msc.service.Service; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.jboss.msc.value.InjectedValue; import org.quartz.Scheduler; /** * @author <a href="mailto:mwringe@redhat.com">Matt Wringe</a> */ public class ScheduleManagerService implements Service<ScheduleManager> { private ScheduleManager manager; @Override public void start(StartContext startContext) throws StartException { this.manager = new ScheduleManager(schedulerInjector.getValue(), scheduledScriptManagerInjector.getValue()); } @Override public void stop(StopContext stopContext) { manager = null; } @Override public ScheduleManager getValue() throws IllegalStateException, IllegalArgumentException { return manager; } public InjectedValue<Scheduler> schedulerInjector = new InjectedValue<>(); public InjectedValue<ScheduledScriptManager> scheduledScriptManagerInjector = new InjectedValue<>(); }
kyroskoh/liveoak
modules/scripts-scheduled/src/main/java/io/liveoak/scripts/scheduled/manager/ScheduleManagerService.java
Java
epl-1.0
1,102
/**************************************************************************** * Copyright (c) 2006-2008 Jeremy Dowdall * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Jeremy Dowdall <jeremyd@aspencloud.com> - initial API and implementation * Wim Jongman - https://bugs.eclipse.org/bugs/show_bug.cgi?id=362181 * Scott Klein - https://bugs.eclipse.org/bugs/show_bug.cgi?id=370605 * Baruch Youssin - https://bugs.eclipse.org/bugs/show_bug.cgi?id=261414 *****************************************************************************/ package org.eclipse.nebula.widgets.cdatetime; import java.text.AttributedCharacterIterator; import java.text.CharacterIterator; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.text.DateFormat.Field; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import org.eclipse.nebula.cwt.base.BaseCombo; import org.eclipse.nebula.cwt.v.VButton; import org.eclipse.nebula.cwt.v.VCanvas; import org.eclipse.nebula.cwt.v.VGridLayout; import org.eclipse.nebula.cwt.v.VLabel; import org.eclipse.nebula.cwt.v.VLayout; import org.eclipse.nebula.cwt.v.VNative; import org.eclipse.nebula.cwt.v.VPanel; import org.eclipse.nebula.cwt.v.VTracker; import org.eclipse.nebula.widgets.cdatetime.CDT.PickerPart; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTException; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Spinner; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.TypedListener; /** * The CDateTime provides both textual and graphical means selecting a date.<br/> * As with other combo type widgets, there are three basic styles: * <ul> * <li>Text only (default)</li> * <li>Graphical only (CDT.SIMPLE)</li> * <li>Combo - a text selector with a drop-down graphical selector * (CDT.DROP_DOWN)</li> * </ul> * <p> * Styles are set using the constants provided in the CDT class. * </p> * * @see CDT */ public class CDateTime extends BaseCombo { /** * A simple class used for editing a field numerically. */ private class EditField { private String buffer; private int digits; private int count = 0; EditField(int digits, int initialValue) { this.digits = digits; buffer = Integer.toString(initialValue); } /** * Adds a character if it is a digit; in case the field exceeds its capacity, the oldest character is * dropped from the buffer. Non-digits are dropped. * @param c * @return true if the new character is a digit and with its addition the active field * reaches or exceeds its capacity, false otherwise */ boolean addChar(char c) { if (Character.isDigit(c)) { buffer = (count > 0) ? buffer : ""; //$NON-NLS-1$ buffer += String.valueOf(c); if (buffer.length() > digits) { buffer = buffer.substring(buffer.length() - digits, buffer.length()); } } return (++count > (digits - 1)); } int getValue() { return Integer.parseInt(buffer); } void removeLastCharacter() { if (buffer.length() > 0) { buffer = buffer.substring(0, buffer.length() - 1); count--; } } void reset() { count = 0; } public String toString() { if (buffer.length() < digits) { char[] ca = new char[digits - buffer.length()]; Arrays.fill(ca, '0'); buffer = String.valueOf(ca).concat(buffer); } return buffer; } } /** * The layout used for a "basic" CDateTime - when it is neither of style * SIMPLE or DROP_DOWN - with style of SPINNER.<br> * Note that there is a spinner, but no button for this style. */ class SpinnerLayout extends VLayout { protected Point computeSize(VPanel panel, int wHint, int hHint, boolean flushCache) { Point size = text.computeSize(SWT.DEFAULT, SWT.DEFAULT); Rectangle sRect = spinner.getControl().computeTrim(0, 0, 0, 0); int sWidth = sRect.x + sRect.width - (2 * spinner.getControl().getBorderWidth()) + 1; size.x += sWidth; size.x++; size.y += textMarginHeight; if (wHint != SWT.DEFAULT) { size.x = Math.min(size.x, wHint); } if (hHint != SWT.DEFAULT) { size.y = Math.min(size.y, hHint); } return size; } protected void layout(VPanel panel, boolean flushCache) { Rectangle cRect = panel.getClientArea(); if (cRect.isEmpty()) return; Point tSize = text.getControl().computeSize(SWT.DEFAULT, SWT.DEFAULT); tSize.y += textMarginHeight; spinner.setBounds(cRect.x, cRect.y, cRect.width, tSize.y); Rectangle sRect = spinner.getControl().computeTrim(0, 0, 0, 0); int sWidth = sRect.x + sRect.width - (2 * spinner.getControl().getBorderWidth()) + 1; tSize.x = cRect.width - sWidth; text.setBounds(cRect.x, cRect.y + getBorderWidth(), tSize.x, tSize.y); } } private static final int FIELD_NONE = -1; private static final int DISCARD = 0; private static final int WRAP = 1; private static final int BLOCK = 2; private static int convertStyle(int style) { int rstyle = SWT.NONE; if ((style & CDT.DROP_DOWN) != 0) { rstyle |= SWT.DROP_DOWN; } if ((style & CDT.SIMPLE) != 0) { rstyle |= SWT.SIMPLE; } if ((style & CDT.READ_ONLY) != 0) { rstyle |= SWT.READ_ONLY; } if ((style & CDT.BUTTON_LEFT) != 0) { rstyle |= SWT.LEFT; } if ((style & CDT.TEXT_LEAD) != 0) { rstyle |= SWT.LEAD; } if ((style & CDT.BORDER) != 0) { rstyle |= SWT.BORDER; } if (win32) { rstyle |= SWT.DOUBLE_BUFFERED; } return rstyle; } VPanel picker; VNative<Spinner> spinner; boolean internalFocusShift = false; boolean rightClick = false; private Date cancelDate; private Calendar calendar; private DateFormat df; Locale locale; TimeZone timezone; Field[] field; int activeField; private boolean tabStops = false; // Store these values so that the style can be reset automatically // to update everything if/when the locale is changed int style; String pattern = null; int format = -1; private CDateTimePainter painter; /** * Delegates events to their appropriate handler */ Listener textListener = new Listener() { public void handleEvent(Event event) { switch (event.type) { case SWT.FocusIn: rightClick = false; if (internalFocusShift) { if (activeField < 0) { fieldFirst(); updateText(); } } else { if (VTracker.getLastTraverse() == SWT.TRAVERSE_TAB_PREVIOUS) { fieldLast(); } else { fieldFirst(); } updateText(); } break; case SWT.FocusOut: if (!rightClick && !internalFocusShift) { commitEditField(); updateText(); } break; case SWT.KeyDown: handleKey(event); break; case SWT.MouseDown: if (event.button == 1) { fieldFromTextSelection(); } else if (event.button == 2) { fieldNext(); } else if (event.button == 3) { rightClick = true; } break; case SWT.MouseWheel: if (event.count > 0) { fieldAdjust(1); } else { fieldAdjust(-1); } event.doit = false; break; case SWT.MouseUp: if (event.button == 1) { fieldFromTextSelection(); } break; case SWT.Traverse: handleTraverse(event); break; case SWT.Verify: verify(event); break; } } }; private Point textSelectionOffset = new Point(0, 0); // x = selOffset start, // y = selOffset // amount private EditField editField; private String[] separator; private int[] calendarFields; private boolean isTime; private boolean isDate; // private boolean isNull = true; private String nullText = null; private boolean defaultNullText = true; private boolean singleSelection; // private boolean dragSelection; private Date[] selection = new Date[0]; private boolean scrollable = true; CDateTimeBuilder builder; VPanel pickerPanel; private TimeZone[] allowedTimezones; /** * Constructs a new instance of this class given its parent and a style * value describing its behavior and appearance. The current date and the * system's default locale are used. * * @param parent * a widget which will be the parent of the new instance (cannot * be null) * @param style * the style of widget to construct */ public CDateTime(Composite parent, int style) { super(parent, convertStyle(style)); init(style); } /** * Adds the listener to the collection of listeners who will be notified * when the receiver's selection changes, by sending it one of the messages * defined in the <code>SelectionListener</code> interface. * <p> * <code>widgetSelected</code> is called when the selection (date/time) * changes. <code>widgetDefaultSelected</code> is when ENTER is pressed the * text box. * </p> * The event's data field will contain the newly selected Date object.<br> * The event's detail field will contain which Calendar Field was changed * * @param listener * the listener which should be notified * @exception IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been * disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> * @see SelectionListener * @see #removeSelectionListener * @see SelectionEvent */ public void addSelectionListener(SelectionListener listener) { if (listener != null) { TypedListener typedListener = new TypedListener(listener); addListener(SWT.Selection, typedListener); addListener(SWT.DefaultSelection, typedListener); } } /** * Adds the textListener for the appropriate SWT events to handle * incrementing fields. */ protected void addTextListener() { removeTextListener(); Text control = text.getControl(); control.addListener(SWT.FocusIn, textListener); control.addListener(SWT.FocusOut, textListener); control.addListener(SWT.KeyDown, textListener); control.addListener(SWT.MouseDown, textListener); control.addListener(SWT.MouseWheel, textListener); control.addListener(SWT.MouseUp, textListener); control.addListener(SWT.Verify, textListener); text.addListener(SWT.Traverse, textListener); } /** * If a field is being edited (via keyboard), set the edit value to the * active field of the calendar. Reset the count of the EditField so that a * subsequent key press will overwrite its contents; * * @return true if the commit was successfull (the value was valid for the * field) or there was no commit to be made (editField is null), * false otherwise */ private boolean commitEditField() { if (editField != null) { int cf = getCalendarField(); int val = editField.getValue(); editField.reset(); if (cf == Calendar.MONTH) { val--; } return fieldSet(cf, val, DISCARD); } return true; } /** * If style is neither SIMPLE or DROP_DOWN, then this method simply returns, * otherwise it creates the picker. */ private void createPicker() { if (isSimple()) { pickerPanel = panel; setContent(panel.getComposite()); } else if (isDropDown()) { disposePicker(); Shell shell = getContentShell(); int style = (isSimple() ? SWT.NONE : SWT.BORDER) | SWT.DOUBLE_BUFFERED; VCanvas canvas = new VCanvas(shell, style); pickerPanel = canvas.getPanel(); pickerPanel.setWidget(canvas); VGridLayout layout = new VGridLayout(); layout.marginHeight = 0; layout.marginWidth = 0; layout.verticalSpacing = 1; pickerPanel.setLayout(layout); setContent(pickerPanel.getComposite()); canvas.addListener(SWT.KeyDown, new Listener() { public void handleEvent(Event event) { if (SWT.ESC == event.keyCode) { event.doit = false; if (selection.length > 0 && selection[0] != cancelDate) { setSelection(cancelDate); fireSelectionChanged(); } setOpen(false); } } }); if (field.length > 1 || isTime) { createPickerToolbar(pickerPanel); } } if (isDate) { DatePicker dp = new DatePicker(this); dp.setScrollable(scrollable); dp.setFields(calendarFields); dp.updateView(); picker = dp; } else if (isTime) { if ((style & CDT.CLOCK_DISCRETE) != 0) { DiscreteTimePicker dtp = new DiscreteTimePicker(this); dtp.setFields(calendarFields); dtp.updateView(); picker = dtp; } else { AnalogTimePicker atp = new AnalogTimePicker(this); atp.setFields(calendarFields); atp.updateView(); picker = atp; } } if (isDropDown()) { picker.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false)); } } private void createPickerToolbar(VPanel parent) { VPanel tb = new VPanel(parent, SWT.NONE); VGridLayout layout = new VGridLayout(3, false); layout.marginHeight = 0; layout.marginWidth = 0; layout.horizontalSpacing = 2; tb.setLayout(layout); tb.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false)); tb.setData(CDT.PickerPart, PickerPart.Toolbar); VButton b = new VButton(tb, SWT.OK | SWT.NO_FOCUS); b.setData(CDT.PickerPart, PickerPart.OkButton); b.setToolTipText(Resources.getString("accept.text", locale)); //$NON-NLS-1$ b.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false)); b.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { setOpen(false); } }); b = new VButton(tb, SWT.CANCEL | SWT.NO_FOCUS); b.setData(CDT.PickerPart, PickerPart.CancelButton); b.setToolTipText(Resources.getString("cancel.text", locale)); //$NON-NLS-1$ b.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false)); b.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { setSelection(cancelDate); fireSelectionChanged(); setOpen(false); } }); b = new VButton(tb, SWT.NO_FOCUS); b.setData(CDT.PickerPart, PickerPart.ClearButton); b.setText(Resources.getString("clear.text", locale)); //$NON-NLS-1$ b.setToolTipText(Resources.getString("clear.text", locale)); //$NON-NLS-1$ b.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false)); b.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { setOpen(false); setSelection(null); fireSelectionChanged(); } }); VLabel sep = new VLabel(parent, SWT.SEPARATOR | SWT.HORIZONTAL); sep.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false)); } // void deselect(Date date) { // if(date != null && isSelected(date)) { // Date[] tmp = new Date[selection.length - 1]; // for(int i = 0, j = 0; i < selection.length; i++) { // if(!selection[i].equals(date)) { // tmp[j++] = selection[i]; // } // } // setSelection(tmp); // } // } // // void deselectAll() { // setSelectedDates((Date[]) null); // } private void disposePicker() { if (content != null) { if (picker != null) { picker.dispose(); picker = null; } if (isDropDown()) { Control c = content; setContent(null); c.dispose(); if (contentShell != null) { Display.getDefault().asyncExec(new Runnable() { public void run() { if (contentShell != null && !contentShell.isDisposed()) { contentShell.dispose(); contentShell = null; } } }); } } } } /** * Adds the given amount to the active field, if there is one */ void fieldAdjust(int amount) { if (!hasSelection()) { setSelection(calendar.getTime()); fireSelectionChanged(); } else { int cf = getCalendarField(); if (cf >= 0) { fieldRoll(cf, amount, WRAP); } } } void fieldFirst() { // If the user has opted to have the user be able to // change time zones then allow the next field to be the // time zone field if (this.allowedTimezones == null) { if (Calendar.ZONE_OFFSET == getCalendarField(field[0])) { setActiveField(1); } else { setActiveField(0); } } else { // allowed time zones have been set, so let the user edit it setActiveField(0); } } /** * Sets the active field from the select of the text box */ void fieldFromTextSelection() { if (!hasSelection()) { // setActiveField(FIELD_ALL); fieldNext(); } else { Point sel = text.getControl().getSelection(); AttributedCharacterIterator aci = df .formatToCharacterIterator(calendar.getTime()); if (sel.x > textSelectionOffset.x) sel.x += textSelectionOffset.y; aci.setIndex(sel.x); Object[] oa = aci.getAttributes().keySet().toArray(); if (oa.length == 0 && sel.x > 0) { sel.x -= 1; aci.setIndex(sel.x); oa = aci.getAttributes().keySet().toArray(); } if (oa.length > 0) { for (int i = 0; i < field.length; i++) { if (oa[0].equals(field[i])) { // If the user has opted to have the user be able to // change time zones then allow the next field to be the // time zone field if (this.allowedTimezones == null) { if (Calendar.ZONE_OFFSET != getCalendarField(field[i])) { setActiveField(i); } } else { // allowed time zones have been set, so let the user // edit it setActiveField(i); } break; } } updateText(); } } } void fieldLast() { // If the user has opted to have the user be able to change // time zones then allow the next field to be the time zone field if (this.allowedTimezones == null) { if (Calendar.ZONE_OFFSET == getCalendarField(field[field.length - 1])) { setActiveField(field.length - 2); } else { setActiveField(field.length - 1); } } else { // allowed time zones have been set, so let the user edit it setActiveField(field.length - 1); } } /** * Sets the active field to the next field; wraps if necessary and sets to * last field if there is no current active field */ void fieldNext() { fieldNext(false); } /** * Sets the active field to the next field; wraps if necessary and sets to * last field if there is no current active field * * @param If * true, the text update will be asynchronous (for changes to * text selection) */ void fieldNext(boolean async) { if (activeField >= 0 && activeField < field.length - 1) { // If the user has opted to have the user be able to change // time zones then allow the next field to be the time zone field if (this.allowedTimezones == null) { if (Calendar.ZONE_OFFSET == getCalendarField(field[activeField + 1])) { if (activeField < field.length - 2) { setActiveField(activeField + 2); } else { setActiveField(0); } } else { setActiveField(activeField + 1); } } else { // allowed time zones have been set, so let the user edit it setActiveField(activeField + 1); } } else { // If the user has opted to have the user be able to change // time zones then allow the next field to be the time zone field if (this.allowedTimezones == null) { if (Calendar.ZONE_OFFSET == getCalendarField(field[0])) { setActiveField(1); } else { setActiveField(0); } } else { // allowed time zones have been set, so let the user edit it setActiveField(0); } } updateText(async); } /** * Sets the active field to the previous field; wraps if necessary and sets * to first field if there is no current active field */ private void fieldPrev() { fieldPrev(false); } /** * Sets the active field to the previous field; wraps if necessary and sets * to first field if there is no current active field * * @param If * true, the text update will be asynchronous (for changes to * text selection) */ void fieldPrev(boolean async) { if (activeField > 0 && activeField < field.length) { // If the user has opted to have the user be able to change // time zones then allow the next field to be the time zone field if (this.allowedTimezones == null) { if (Calendar.ZONE_OFFSET == getCalendarField(field[activeField - 1])) { if (activeField > 1) { setActiveField(activeField - 2); } else { setActiveField(field.length - 1); } } else { setActiveField(activeField - 1); } } else { // allowed time zones have been set, so let the user edit it setActiveField(activeField - 1); } } else { // If the user has opted to have the user be able to change // time zones then allow the next field to be the time zone field if (this.allowedTimezones == null) { if (Calendar.ZONE_OFFSET == getCalendarField(field[field.length - 1])) { setActiveField(field.length - 2); } else { setActiveField(field.length - 1); } } else { // allowed time zones have been set, so let the user edit it setActiveField(field.length - 1); } } updateText(async); } private boolean fieldRoll(final int calendarField, final int rollAmount, final int style) { if (!getEditable()) { return false; } if (calendarField == Calendar.ZONE_OFFSET && this.allowedTimezones != null) { boolean timeZoneSet = false; for (int idx = 0; idx < this.allowedTimezones.length; idx++) { TimeZone activeTimeZone = this.getTimeZone(); if (activeTimeZone.getID() == this.allowedTimezones[idx] .getID()) { if (rollAmount < 0) { if (idx == 0) { this.setTimeZone(this.allowedTimezones[this.allowedTimezones.length - 1]); } else { this.setTimeZone(this.allowedTimezones[idx - 1]); } } else if (rollAmount > 0) { if (idx == this.allowedTimezones.length - 1) { this.setTimeZone(this.allowedTimezones[0]); } else { this.setTimeZone(this.allowedTimezones[idx + 1]); } } timeZoneSet = true; break; } } if (!timeZoneSet) { this.setTimeZone(this.allowedTimezones[0]); } } else { calendar.roll(calendarField, rollAmount); } if (selection.length > 0) { selection[0] = calendar.getTime(); } updateText(); updatePicker(); fireSelectionChanged(calendarField); return true; } /** * Sets the given calendar field to the given value.<br> * <b>NOTE:</b> This is NOT the active field but a field in the "calendar" * variable. * * @param calendarField * the field of calendar to set * @param value * the value to set it to * @param style * the of set to perform; if the value is valid for the given * calendarField then this has no affect, otherwise it will take * an action according to this style int: * <ul> * <li>DISCARD: the value will be discarded and the method * returns without performing and action</li> * <li>WRAP: if value is higher than its maximum it will be set * to its minimum, and visa versa</li> * <li>BLOCK: if value is higher than its maximum it will be set * to its maximum, and visa versa</li> * </ul> * @return true if the field was set, false otherwise (as is possible with a * DISCARD style) */ private boolean fieldSet(int calendarField, int value, int style) { if (!getEditable()) { return false; } if (calendarField >= 0) { if (value > calendar.getActualMaximum(calendarField)) { if (style == DISCARD) { return false; } else if (style == WRAP) { value = calendar.getActualMinimum(calendarField); } else if (style == BLOCK) { value = calendar.getActualMaximum(calendarField); } } else if (value < calendar.getActualMinimum(calendarField)) { if (style == DISCARD) { return false; } else if (style == WRAP) { value = calendar.getActualMaximum(calendarField); } else if (style == BLOCK) { value = calendar.getActualMinimum(calendarField); } } calendar.set(calendarField, value); if (selection.length > 0) { selection[0] = calendar.getTime(); } updateText(); updatePicker(); fireSelectionChanged(calendarField); } return true; } /** * <p> * Notifies listeners that the selection for this CDateTime has changed * </p> * <p> * This will fire both a regular selection event, and a default selection * event. * </p> * <p> * The data field is populated by {@link #getSelectedDates()}. * </p> */ void fireSelectionChanged() { fireSelectionChanged(false); } void fireSelectionChanged(boolean defaultSelection) { if (defaultSelection && isOpen()) { setOpen(false); } Event event = new Event(); event.data = getSelection(); notifyListeners(SWT.Selection, event); if (defaultSelection) { notifyListeners(SWT.DefaultSelection, event); } } /** * <p> * Notifies listeners that a field of the selected date for this CDateTime * has changed * </p> * <p> * Note that this is only valid when {@link #singleSelection} is true, and * will only fire a regular selection event (not a default selection event) * </p> * <p> * The data field is populated by {@link #getSelection()} and the detail * field holds the field which was changed. * </p> * * @param field * the Calendar Field which caused the change, or -1 if * <code>setTime</code> was called (thus setting all Calendar * Fields) */ void fireSelectionChanged(int field) { Event event = new Event(); event.data = getSelection(); event.detail = field; if (this.field.length == 1) { if (isOpen()) { setOpen(false); } notifyListeners(SWT.Selection, event); notifyListeners(SWT.DefaultSelection, event); } else { notifyListeners(SWT.Selection, event); } } VButton getButtonWidget() { return button; } /** * Gets the calendar field corresponding to the active field, if there is * one. * * @return an int representing the calendar field, -1 if there isn't one. */ int getCalendarField() { return hasField(activeField) ? getCalendarField(field[activeField]) : -1; } int getCalendarField(Field field) { int cf = field.getCalendarField(); if (cf < 0) { if (field.toString().indexOf("hour 1") > -1) { //$NON-NLS-1$ cf = Calendar.HOUR; } else if (field.toString().contains("zone")) { //$NON-NLS-1$ cf = Calendar.ZONE_OFFSET; } } return cf; } Calendar getCalendarInstance() { return getCalendarInstance(calendar.getTimeInMillis()); } /** * <p> * <b>WARNING: Experimental API - this method may be removed in future * versions</b> * </p> * Get a new instance of Calendar that is initialized with the timezone and * locale of this CDateTime, and set to the given date. * * @param date * the date that the Calendar will be set to, or null for the * current system time * @return a new instance of Calendar */ public Calendar getCalendarInstance(Date date) { if (date == null) { return getCalendarInstance(System.currentTimeMillis()); } else { return getCalendarInstance(date.getTime()); } } /** * <p> * <b>WARNING: Experimental API - this method may be removed in future * versions</b> * </p> * Get a new instance of Calendar that is initialized with the timezone and * locale of this CDateTime, and set to the given date. * * @param date * the date, in millis, that the Calendar will be set to * @return a new instance of Calendar */ public Calendar getCalendarInstance(long date) { Calendar cal = Calendar.getInstance(timezone, locale); cal.setTimeInMillis(date); return cal; } Date getCalendarTime() { return calendar.getTime(); } long getCalendarTimeInMillis() { return calendar.getTimeInMillis(); } public boolean getEditable() { return !panel.hasStyle(SWT.READ_ONLY); } /** * The locale currently in use by this CDateTime. * * @return the locale * @see #setLocale(Locale) */ public Locale getLocale() { return locale; } /** * Get the text which will be shown when the selection is set to null. Note * that this will be equal to the default null text for the given locale * unless the null text has been explicitly set using * {@link #setNullText(String)} * * @return the text shown when the selection is null * @see #setNullText(String) */ public String getNullText() { if (nullText == null) { if (isDate) { return Resources.getString("null_text.date", locale); //$NON-NLS-1$ } else { return Resources.getString("null_text.time", locale); //$NON-NLS-1$ } } return nullText; } CDateTimePainter getPainter() { if (painter == null) { setPainter(new CDateTimePainter()); } return painter; } /** * Get the pattern of this CDateTime as used to set its format. If the * format was NOT set using <code>setFormat(String)</code> this will return * <code>null</code>. * * @return the pattern, null if there isn't one * @see SimpleDateFormat * @see #setFormat(int) * @see #setPattern(String) */ public String getPattern() { return pattern; } /** * Get the current selection of this CDateTime widget, or null if there is * no selection. * * @return the current selection */ public Date getSelection() { return hasSelection() ? selection[0] : null; } public int getStyle() { return style; } public String getText() { return checkText() ? text.getText() : null; } VNative<Text> getTextWidget() { return text; } /** * The timezone currently in use by this CDateTime. * * @return the timezone * @see #setTimeZone(String) * @see #setTimeZone(TimeZone) */ public TimeZone getTimeZone() { return timezone; } /** * The Key event handler * * @param event * the event */ void handleKey(Event event) { if (event.stateMask != 0) { return; } if ('\r' == event.keyCode || SWT.KEYPAD_CR == event.keyCode) { fireSelectionChanged(true); } else if (SWT.BS == event.keyCode || SWT.DEL == event.keyCode) { event.doit = false; setSelection((Date) null); fireSelectionChanged(); } else if (!hasField(activeField) && !hasSelection()) { event.doit = false; } else { switch (event.keyCode) { case '-': case SWT.KEYPAD_SUBTRACT: fieldAdjust(-1); break; case '=': case '+': case SWT.KEYPAD_ADD: fieldAdjust(1); break; case SWT.BS: if (editField != null) editField.removeLastCharacter(); break; case SWT.ARROW_DOWN: fieldAdjust(-1); updateText(true); break; case SWT.ARROW_UP: fieldAdjust(1); updateText(true); break; case SWT.ARROW_LEFT: fieldPrev(true); break; case SWT.ARROW_RIGHT: fieldNext(true); break; default: if (hasField(activeField) && activeField + 1 < separator.length && String.valueOf(event.character).equals( separator[activeField + 1])) { fieldNext(); } else if (!hasSelection() && String.valueOf(event.character).matches("[0-9]")) { fieldAdjust(0); fieldFirst(); } } } } /** * The Travers event handler. Note that ARROW_UP and ARROW_DOWN are handled * in the <code>handleKey</code> method. * * @param event * the event */ void handleTraverse(Event event) { boolean allowTimeZoneEdit = this.allowedTimezones != null; switch (event.detail) { case SWT.TRAVERSE_ARROW_NEXT: if (event.keyCode == SWT.ARROW_RIGHT) { fieldNext(); } else if (event.keyCode == SWT.ARROW_DOWN) { fieldAdjust(-1); } break; case SWT.TRAVERSE_ARROW_PREVIOUS: if (event.keyCode == SWT.ARROW_LEFT) { fieldPrev(); } else if (event.keyCode == SWT.ARROW_UP) { fieldAdjust(1); } break; case SWT.CR: fieldNext(); fireSelectionChanged(); break; case SWT.TRAVERSE_TAB_NEXT: if (tabStops && hasSelection()) { // if we are at the last field, allow the tab out of the control // the last field is also considered to be the 2nd to last if // the last is a time zone // we now check if the control allows time zone editing if (activeField == field.length - 1 || ((activeField == field.length - 2) && (Calendar.ZONE_OFFSET == getCalendarField(field[field.length - 1])) && (!allowTimeZoneEdit))) { event.doit = true; } else { event.doit = false; if (activeField < 0) { fieldPrev(); } else { fieldNext(); } } } break; case SWT.TRAVERSE_TAB_PREVIOUS: if (tabStops && hasSelection()) { // if we are at the 1st field, allow the tab out of the control // the 1st field is also considered to the the 2nd if the 1st // is a time zone if (activeField == 0 || ((activeField == 1) && (Calendar.ZONE_OFFSET == getCalendarField(field[0])) && (!allowTimeZoneEdit))) { event.doit = true; } else { event.doit = false; if (activeField < 0) { fieldNext(); } else { fieldPrev(); } } } break; default: } } /** * Determines if the given field number is backed by a real field. * * @param field * the field number to check * @return true if the given field number corresponds to a field in the * field array */ private boolean hasField(int field) { return field >= 0 && field <= this.field.length; } /** * Return true if this CDateTime has one or more dates selected; * * @return true if a date is selected, false otherwise */ public boolean hasSelection() { return selection.length > 0; } private void init(int style) { this.style = style; locale = Locale.getDefault(); try { timezone = TimeZone.getDefault(); } catch (Exception e) { timezone = TimeZone.getTimeZone("GMT"); //$NON-NLS-1$ } calendar = Calendar.getInstance(this.timezone, this.locale); calendar.setTime(new Date()); tabStops = (style & CDT.TAB_FIELDS) != 0; singleSelection = ((style & CDT.SIMPLE) == 0) || ((style & CDT.MULTI) == 0); setFormat(style); if (!isSimple()) { if (isDropDown()) { if ((style & CDT.BUTTON_AUTO) != 0) { setButtonVisibility(BaseCombo.BUTTON_AUTO); } else { setButtonVisibility(BaseCombo.BUTTON_ALWAYS); } } else { setButtonVisibility(BaseCombo.BUTTON_NEVER); if ((style & CDT.SPINNER) != 0) { int sStyle = SWT.VERTICAL; if (gtk && ((style & CDT.BORDER) != 0)) { sStyle |= SWT.BORDER; } spinner = VNative.create(Spinner.class, panel, sStyle); if (win32) { spinner.setBackground(text.getControl().getBackground()); } spinner.getControl().setMinimum(0); spinner.getControl().setMaximum(50); spinner.getControl().setDigits(1); spinner.getControl().setIncrement(1); spinner.getControl().setPageIncrement(1); spinner.getControl().setSelection(25); spinner.getControl().addFocusListener(new FocusAdapter() { public void focusGained(FocusEvent e) { internalFocusShift = true; setFocus(); internalFocusShift = false; } }); spinner.getControl().addMouseListener(new MouseAdapter() { public void mouseDown(MouseEvent e) { if (e.button == 2) { fieldNext(); } } }); spinner.getControl().addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (VTracker.getMouseDownButton() != 2) { if (spinner.getControl().getSelection() > 25) { fieldAdjust(1); } else { fieldAdjust(-1); } spinner.getControl().setSelection(25); } } }); panel.setLayout(new SpinnerLayout()); } } updateText(); activeField = -5; setActiveField(FIELD_NONE); if (checkText()) { addTextListener(); } } } boolean isSelected(Date date) { for (Date d : selection) { if (d.equals(date)) { return true; } } return false; } boolean isSingleSelection() { return singleSelection; } /** * Determine whether the provided field is the most * <b>precise</b> field. According to the used pattern, e.g. * <ul> * <li>dd.mm.yyyy * <li>MMMM yyyy * <li>yyyy * </ul> * the date picker provides the panels for selecting a day, month or year * respectively. The panel should close itself and set the selection in * the CDateTime field when the user selects the most precise field. * The constants from the {@link Calendar} class may be used to determine * the most precise field: * <ul> * <li>{@link Calendar#YEAR} -> 1 * <li>{@link Calendar#MONTH} -> 2 * <li>{@link Calendar#DATE} -> 5 * </ul> * e.g. the <i>highest</i> constant is the closing field. * @param calendarField The calendar field identifying a pattern field * @return true if the highest pattern field */ boolean isClosingField(int calendarField) { // find the "highest" constant in the pattern fields int i = Integer.MIN_VALUE; for (Field f : field) { i = Math.max(i, f.getCalendarField()); } // compare the highest constant with the field if ( i == calendarField) { return true; } return false; } @Override protected void postClose(Shell popup) { disposePicker(); } /** * Removes the listener from the collection of listeners who will be * notified when the receiver's selection changes. * * @param listener * the listener which should no longer be notified * @exception IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been * disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> * @see SelectionListener * @see #addSelectionListener */ public void removeSelectionListener(SelectionListener listener) { if (listener != null) { TypedListener l = new TypedListener(listener); removeListener(SWT.Selection, l); removeListener(SWT.DefaultSelection, l); } } /** * Removes the textListener for the appropriate SWT events to handle * incrementing fields. */ protected void removeTextListener() { Text control = text.getControl(); control.removeListener(SWT.KeyDown, textListener); control.removeListener(SWT.MouseDown, textListener); control.removeListener(SWT.MouseWheel, textListener); control.removeListener(SWT.MouseUp, textListener); control.removeListener(SWT.Verify, textListener); text.removeListener(SWT.Traverse, textListener); } // void select(Date date) { // if(date != null) { // Date[] tmp = new Date[selection.length + 1]; // System.arraycopy(selection, 0, tmp, 1, selection.length); // tmp[0] = date; // setSelectedDates(tmp); // } // } // // void select(Date date1, Date date2, int field, int increment) { // if(date1 != null && date2 != null) { // Date start = date1.before(date2) ? date1 : date2; // Date end = date1.before(date2) ? date2 : date1; // List<Date> tmp = new ArrayList<Date>(); // Calendar cal = getCalendarInstance(start); // while(cal.getTime().before(end)) { // tmp.add(cal.getTime()); // cal.add(field, increment); // } // tmp.add(cal.getTime()); // if(start == date2) { // Collections.reverse(tmp); // } // setSelectedDates(tmp.toArray(new Date[tmp.size()])); // } // } /** * Sets the active field, which may or may not be a real field (it may also * be <code>FIELD_NONE</code>) * * @param field * the field to be set active * @see CDateTime#hasField(int) */ private void setActiveField(int field) { if (activeField != field) { commitEditField(); editField = null; activeField = field; } } /** * <p> * <b>WARNING: Experimental API - this method may be removed in future * versions</b> * </p> * Sets the builder that this CDateTime widget will use to build its * graphical selector to the given builder, or to a default builder if the * given builder is null. * * @param builder * the builder to use, or null to use a default builder */ public void setBuilder(CDateTimeBuilder builder) { this.builder = builder; if (picker != null) { disposePicker(); createPicker(); } } /* * (non-Javadoc) * * @see * org.eclipse.nebula.cwt.base.BaseCombo#setButtonImage(org.eclipse.swt. * graphics.Image) */ public void setButtonImage(Image image) { super.setButtonImage(image); } @Override protected boolean setContentFocus() { if (checkPicker()) { internalFocusShift = true; boolean result = picker.setFocus(); internalFocusShift = false; return result; } return false; } /* * (non-Javadoc) * * @see org.eclipse.nebula.cwt.base.BaseCombo#setEditable(boolean) */ public void setEditable(boolean editable) { super.setEditable(editable); if (checkPicker()) { if (picker instanceof DatePicker) { ((DatePicker) picker).setEditable(editable); } else { picker.setActivatable(editable); } } } private boolean checkPicker() { return picker != null && !picker.isDisposed(); } /** * Set the date and time format of this CDateTime uses style constants which * correspond to the various forms of DateFormat.getXxxInstance(int). <dt> * <b>Valid Styles:</b></dt> <dd>DATE_SHORT, DATE_MEDIUM, DATE_LONG, * TIME_SHORT, TIME_MEDIUM</dd> * <p> * Styles are bitwise OR'ed together, but only one "DATE" and one "TIME" may * be set at a time. * </p> * Examples:<br> * </code>setFormat(CDT.DATE_LONG);</code><br /> * </code>setFormat(CDT.DATE_SHORT | CDT.TIME_MEDIUM);</code><br /> * * @param format * the bitwise OR'ed Date and Time format to be set * @throws IllegalArgumentException * @see #getPattern() * @see #setPattern(String) */ public void setFormat(int format) throws IllegalArgumentException { int dateStyle = (format & CDT.DATE_SHORT) != 0 ? DateFormat.SHORT : (format & CDT.DATE_MEDIUM) != 0 ? DateFormat.MEDIUM : (format & CDT.DATE_LONG) != 0 ? DateFormat.LONG : -1; int timeStyle = (format & CDT.TIME_SHORT) != 0 ? DateFormat.SHORT : (format & CDT.TIME_MEDIUM) != 0 ? DateFormat.MEDIUM : -1; String str = null; if (dateStyle != -1 && timeStyle != -1) { str = ((SimpleDateFormat) DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale)).toPattern(); } else if (dateStyle != -1) { str = ((SimpleDateFormat) DateFormat.getDateInstance(dateStyle, locale)).toPattern(); } else if (timeStyle != -1) { str = ((SimpleDateFormat) DateFormat.getTimeInstance(timeStyle, locale)).toPattern(); } else if (pattern == null) { // first call, so set to default format = CDT.DATE_SHORT; str = ((SimpleDateFormat) DateFormat.getDateInstance( DateFormat.SHORT, locale)).toPattern(); } if (str != null) { this.format = format; setPattern(str); } } /** * Sets the Locale to be used by this CDateTime and causes all affected * attributes to be updated<br> * If the provided locale is the same as the current locale then this method * simply returns. If the provided Locale is null then this CDateTime will * use the system's default locale.<br> * If this <code>CDateTime</code> is of style <code>DROP_DOWN</code> then * the associated <code>CDateTime</code> will be set to the same locale. * * @param locale * the Locale, or null to use the system's default * @see #getLocale() */ public void setLocale(Locale locale) { if (locale == null) locale = Locale.getDefault(); if (!this.locale.equals(locale)) { this.locale = locale; if (format > 0) { setFormat(format); } else { setPattern(pattern); } updateNullText(); } } protected void setModifyEventProperties(Event e) { e.data = calendar.getTime(); } /** * Set the text to be shown when the selection is null. Passing null into * this method will cause the CDateTime widget to use a default null text * for the given locale. * * @param text */ public void setNullText(String text) { defaultNullText = false; nullText = text; updateText(); } public void setOpen(boolean open) { setOpen(open, null); } public void setOpen(boolean open, Runnable callback) { if (open) { cancelDate = getSelection(); createPicker(); } else { cancelDate = null; } super.setOpen(open, callback); if (hasSelection()) { show(getSelection()); } } /** * <p> * <b>WARNING: Experimental API - this method may be removed in future * versions</b> * </p> * Sets the painter that this CDateTime widget will use to paint its * graphical selector to the given painter, or to a default painter if the * given painter is null. * * @param painter * the painter to use, or null to use a default painter */ public void setPainter(CDateTimePainter painter) { if (painter != null) { painter.setCDateTime(this); } this.painter = painter; } /** * Set the style of this CDateTime to work with dates and / or times as * determined by the given pattern. This will set the fields shown in the * text box and, if <code>DROP_DOWN</code> style is set, the fields of the * drop down component.<br> * This method is backed by an implementation of SimpleDateFormat, and as * such, any string pattern which is valid for SimpleDateFormat may be used. * Examples (US Locale):<br> * </code>setPattern("MM/dd/yyyy h:mm a");</code><br /> * </code>setPattern("'Meeting @' h:mm a 'on' EEEE, MMM dd, yyyy");</code><br /> * * @param pattern * the pattern to use, if it is invalid, the original is restored * @throws IllegalArgumentException * @see SimpleDateFormat * @see #getPattern() * @see #setFormat(int) */ public void setPattern(String pattern) throws IllegalArgumentException { this.allowedTimezones = null; if (isOpen()) { setOpen(false); } df = new SimpleDateFormat(pattern, locale); df.setTimeZone(timezone); if (updateFields()) { this.pattern = pattern; this.format = -1; boolean wasDate = isDate; boolean wasTime = isTime; isDate = isTime = false; calendarFields = new int[field.length]; for (int i = 0; i < calendarFields.length; i++) { calendarFields[i] = getCalendarField(field[i]); switch (calendarFields[i]) { case Calendar.AM_PM: case Calendar.HOUR: case Calendar.HOUR_OF_DAY: case Calendar.MILLISECOND: case Calendar.MINUTE: case Calendar.SECOND: case Calendar.ZONE_OFFSET: isTime = true; break; case Calendar.DAY_OF_MONTH: case Calendar.DAY_OF_WEEK: case Calendar.DAY_OF_WEEK_IN_MONTH: case Calendar.DAY_OF_YEAR: case Calendar.ERA: case Calendar.MONTH: case Calendar.WEEK_OF_MONTH: case Calendar.WEEK_OF_YEAR: case Calendar.YEAR: isDate = true; break; default: break; } } if (checkButton() && ((isDate != wasDate) || (isTime != wasTime))) { if (defaultButtonImage) { if (isDate && isTime) { doSetButtonImage(Resources.getIconCalendarClock()); } else if (isDate) { doSetButtonImage(Resources.getIconCalendar()); } else { doSetButtonImage(Resources.getIconClock()); } } updateNullText(); } if (checkText()) { updateText(); } if (isSimple()) { disposePicker(); createPicker(); } } else { throw new IllegalArgumentException( "Problem setting pattern: \"" + pattern + "\""); //$NON-NLS-1$ //$NON-NLS-2$ } } void setScrollable(boolean scrollable) { this.scrollable = scrollable; if (isSimple() && !scrollable) { if (picker != null && picker instanceof DatePicker) { updatePicker(); } } } /** * Set the selection for this CDateTime to that of the provided * <code>Date</code> object.<br> * * @param selection * the new selection, or null to clear the selection */ public void setSelection(Date selection) { if (getEditable()) { if (selection == null) { this.selection = new Date[0]; } else { this.selection = new Date[] { selection }; } } if (singleSelection && this.selection.length > 0) { show(selection); } else { updateText(); updatePicker(); } } /** * Sets the timezone to the timezone specified by the given zoneID, or to * the system default if the given zoneID is null. If the give zoneID cannot * be understood, then the timezone will be set to GMT. * * @param zoneID * the id of the timezone to use, or null to use the system * default * @see #setTimeZone(TimeZone) */ public void setTimeZone(String zoneID) { if (zoneID == null) { setTimeZone((TimeZone) null); } else { setTimeZone(TimeZone.getTimeZone(zoneID)); } } /** * Sets the timezone to the given timezone, or to the system's default * timezone if the given timezone is null. * * @param zone * the timezone to use, or null to use the system default * @see #setTimeZone(String) */ public void setTimeZone(TimeZone zone) { if (zone == null) { timezone = TimeZone.getDefault(); } if (!this.timezone.equals(zone)) { this.timezone = zone; calendar.setTimeZone(this.timezone); df.setTimeZone(this.timezone); updateText(); } } /** * Shows the given date if it can be shown by the selector. In other words, * for graphical selectors such as a calendar, the visible range of time is * moved so that the given date is visible. * * @param date * the date to show */ public void show(Date date) { if (date == null) { calendar.setTime(new Date()); } else { calendar.setTime(date); } updateText(); updatePicker(); } /** * Show the selection if it can be shown by the selector. Has no affect if * there is no selection. * * @see #show(Date) */ public void showSelection() { if (selection.length > 0) { show(selection[0]); } } @Override public String toString() { return getClass().getSimpleName() + " {" + getCalendarTime() + "}"; //$NON-NLS-1$ //$NON-NLS-2$ } /** * inspects all of the calendar fields in the <code>field</code> array to * determine what style is appropriate and then sets that style to the * picker using the setPickerStyle method.<br> */ private boolean updateFields() { Field[] bak = new Field[(field == null) ? 0 : field.length]; if (bak.length > 0) System.arraycopy(field, 0, bak, 0, field.length); AttributedCharacterIterator aci = df.formatToCharacterIterator(calendar .getTime()); field = new Field[aci.getAllAttributeKeys().size()]; separator = new String[field.length + 1]; // there can be a separator // before and after int i = 0; Object last = null; for (char c = aci.first(); c != CharacterIterator.DONE; c = aci.next()) { Object[] oa = aci.getAttributes().keySet().toArray(); if (oa.length > 0) { if (oa[0] != last && i < field.length) { if (getCalendarField((Field) oa[0]) < 0) { if (bak.length > 0) { field = new Field[bak.length]; System.arraycopy(bak, 0, field, 0, bak.length); } return false; } else { field[i] = (Field) oa[0]; last = oa[0]; } i++; } } else { if (separator[i] == null) separator[i] = String.valueOf(c); } } df.setLenient(false); setActiveField(FIELD_NONE); return true; } private void updateNullText() { if (defaultNullText) { if (isDate) { nullText = Resources.getString("null_text.date", locale); //$NON-NLS-1$ } else { nullText = Resources.getString("null_text.time", locale); //$NON-NLS-1$ } if (!hasSelection()) { updateText(); } } } /** * tell the picker to update its view of the selection and reference time */ private void updatePicker() { if (picker != null) { if (picker instanceof DatePicker) { ((DatePicker) picker).updateView(); } else if (picker instanceof AnalogTimePicker) { ((AnalogTimePicker) picker).updateView(); } else if (picker instanceof DiscreteTimePicker) { ((DiscreteTimePicker) picker).updateView(); } } } /** * This is the only way that text is set to the text box.<br> * The selection of the text in the text box is also set here (the active field is selected) as * well as if a field is being edited, it's "edit text" is inserted for * display. * The <code>getSelection</code> property of CDateTime remains unchanged. */ private void updateText() { updateText(false); } /** * This is the only way that text is set to the text box.<br> * The selection of the text in the text box is also set here (the active field is selected) as * well as if a field is being edited, it's "edit text" is inserted for * display. * The <code>getSelection</code> property of CDateTime remains unchanged. * * @param async * If true, this operation will be performed asynchronously (for * changes to text selection) */ private void updateText(boolean async) { // TODO: save previous state and only update on changes...? String buffer = hasSelection() ? df.format(getSelection()) : getNullText(); int s0 = 0; int s1 = 0; if (!hasSelection()) { s0 = 0; s1 = buffer.length(); } else if (activeField >= 0 && activeField < field.length) { AttributedCharacterIterator aci = df .formatToCharacterIterator(getSelection()); for (char c = aci.first(); c != CharacterIterator.DONE; c = aci .next()) { if (aci.getAttribute(field[activeField]) != null) { s0 = aci.getRunStart(); s1 = aci.getRunLimit(); if (editField != null) { String str = editField.toString(); buffer = buffer.substring(0, s0) + str + buffer.substring(s1); int oldS1 = s1; s1 = s0 + str.length(); textSelectionOffset.x = Math.min(oldS1, s1); textSelectionOffset.y = (oldS1 - s0) - str.length(); } else { textSelectionOffset.x = buffer.length() + 1; textSelectionOffset.y = 0; } break; } } } else { setActiveField(FIELD_NONE); } final String string = buffer; final int selStart = s0; final int selEnd = s1; Runnable runnable = new Runnable() { public void run() { if ((text != null) && (!text.isDisposed())) { if (!string.equals(text.getText())) { text.getControl().removeListener(SWT.Verify, textListener); text.setText(string); text.getControl().addListener(SWT.Verify, textListener); } text.getControl().setSelection(selStart, selEnd); } } }; if (async) { getDisplay().asyncExec(runnable); } else { getDisplay().syncExec(runnable); } } /** * The Verify Event handler.<br> * <b>EVERYTHING</b> is blocked via this handler (Event.doit is set to * false). Depending upon the input, a course of action is determined and * the displayed text is updated via the <code>updateText()</code> method. * <br> * This method implements the following logic: * If the event is a paste, the pasted text is parsed for the entire date/time selection; * if this parse is successful, the result is committed to the selection property and is displayed; * otherwise, it is discarded. One-character pastes are discarded without parsing. * When user types characters one by one, all non-digits are discarded (if they have effects, they * have already been processed by other event handlers) while digits are added to * <code>this.editField</code> without affecting the selection. * Once <code>this.editField</code> reaches its capacity for * the active field, its contents are attempted to be committed. * If the commit is successful, focus switches to the next field of CDateTime. * Otherwise, the contents of <code>this.editField</code> * are discarded and the previous value of the selection (before user started typing * in this field) is restored; focus stays in the same field. * <b>Example:</b> if the seconds field contains "23", and user types 8 in the seconds field, * "08" is shown on screen while getSelection still returns 23. If user types 9 after that, * the field reaches its capacity, the attempt to commit 89 seconds fails, and 23 gets restored * on screen. * * @param e * the event * @see CDateTime#updateText() */ void verify(Event e) { e.doit = false; if (field.length == 0 || activeField == FIELD_NONE) return; char c = e.character; if (((e.text.length() == 1) && String.valueOf(c).equals(e.text) && Character .isDigit(c)) || (e.text.length() > 1)) { if (e.text.length() == 1) { if (editField == null) { int cf = getCalendarField(); if (cf >= 0) { int digits; switch (cf) { case Calendar.YEAR: digits = 4; break; case Calendar.DAY_OF_YEAR: digits = 3; break; case Calendar.AM_PM: case Calendar.DAY_OF_WEEK: case Calendar.ERA: digits = 1; break; case Calendar.MILLISECOND: digits = 3; break; default: digits = 2; } editField = new EditField(digits, calendar.get(cf)); } else { return; } } if (editField.addChar(c)) { if (commitEditField()) { fieldNext(); } else { editField = null; if (selection.length > 0) { selection[0] = calendar.getTime(); } updateText(); } } if (selection.length > 0) { selection[0] = calendar.getTime(); } updatePicker(); } else { try { setSelection(df.parse(e.text)); fireSelectionChanged(); } catch (ParseException pe) { // do nothing } } } updateText(); } /** * @param pattern * @param allowedTimeZones * @throws IllegalArgumentException */ public void setPattern(final String pattern, final TimeZone[] allowedTimeZones) throws IllegalArgumentException { this.setPattern(pattern); if (pattern.indexOf('z') != -1) { this.allowedTimezones = allowedTimeZones; } } }
debrief/debrief
org.eclipse.nebula.widgets.cdatetime/src/org/eclipse/nebula/widgets/cdatetime/CDateTime.java
Java
epl-1.0
61,447
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>12. Naming Conventions</title><link rel="stylesheet" type="text/css" href="docbook-xsl.css" /><meta name="generator" content="DocBook XSL Stylesheets V1.78.1" /><link rel="home" href="index.html" title="TACTIC Setup" /><link rel="up" href="index.html" title="TACTIC Setup" /><link rel="prev" href="ar01s11.html" title="11. Views Configuration" /><link rel="next" href="ar01s13.html" title="13. Project Workflow Introduction" /></head><body><div class="navheader"><table width="100%" summary="Navigation header"><tr><td width="20%" align="left"><a accesskey="p" href="ar01s11.html">Prev</a> </td><th width="60%" align="center"> </th><td width="20%" align="right"> <a accesskey="n" href="ar01s13.html">Next</a></td></tr></table><hr /></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="_naming_conventions"></a>12. Naming Conventions</h2></div></div></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a id="_project_automation_file_naming"></a>12.1. Project Automation - File Naming</h3></div></div></div><p><span class="inlinemediaobject"><img src="media/project-automation_naming.png" alt="image" /></span></p><p>The naming page provides a way of controlling directory and file naming conventions through a simple expression language . Each naming entry can contain a directory naming and/or file naming. It is designed that so that a relatively non-technical user can create custom naming conventions for various sTypes.</p><p>The relative path expression language is a simple language, but in order to understand it you must know the basic components that generally make up a naming convention. The expression language allows access to almost any data in TACTIC. The keywords which are the most relevant in naming conventions are as follows:</p><div class="informaltable"><table cellpadding="4px" style="border-collapse: collapse;border-top: 3px solid #527bbd; border-bottom: 3px solid #527bbd; border-left: 3px solid #527bbd; border-right: 3px solid #527bbd; " width="100%"><colgroup><col class="col_1" /><col class="col_2" /></colgroup><tbody><tr><td style="border-right: 1px solid #527bbd; border-bottom: 1px solid #527bbd; " align="left" valign="top"><p><span class="strong"><strong>parent:</strong></span></p></td><td style="border-bottom: 1px solid #527bbd; " align="left" valign="top"><p>The parent sObject to the current sObject defined by the search type attribute</p></td></tr><tr><td style="border-right: 1px solid #527bbd; border-bottom: 1px solid #527bbd; " align="left" valign="top"><p><span class="strong"><strong>sObject:</strong></span></p></td><td style="border-bottom: 1px solid #527bbd; " align="left" valign="top"><p>The actual sObject which is being referenced</p></td></tr><tr><td style="border-right: 1px solid #527bbd; border-bottom: 1px solid #527bbd; " align="left" valign="top"><p><span class="strong"><strong>snapshot:</strong></span></p></td><td style="border-bottom: 1px solid #527bbd; " align="left" valign="top"><p>The child snapshot generated or being referenced for the naming convention. This contains the context and version information.</p></td></tr><tr><td style="border-right: 1px solid #527bbd; border-bottom: 1px solid #527bbd; " align="left" valign="top"><p><span class="strong"><strong>file:</strong></span></p></td><td style="border-bottom: 1px solid #527bbd; " align="left" valign="top"><p>The file object pertinent to the check-in. This allows for reference to the original file name or extension.</p></td></tr><tr><td style="border-right: 1px solid #527bbd; border-bottom: 1px solid #527bbd; " align="left" valign="top"><p><span class="strong"><strong>login:</strong></span></p></td><td style="border-bottom: 1px solid #527bbd; " align="left" valign="top"><p>The user who is carrying out the check-in or check-out.</p></td></tr><tr><td style="border-right: 1px solid #527bbd; " align="left" valign="top"><p><span class="strong"><strong>user:</strong></span></p></td><td style="" align="left" valign="top"><p>The user who is carrying out the check-in or check-out.</p></td></tr></tbody></table></div><p>The properties of these Search Objects are used to build up the naming convention.</p><p>A simple example of a relative path is as follows:</p><pre class="screen">{project.code}/sequence/{parent.code}/{sobject.code}/{snapshot.context}/maya</pre><p>which after translation could be translated into:</p><pre class="screen">sample3d/sequence/XG/XG001/model/maya</pre><p>This expression is explicit in that every variable scopes the object that the attribute comes from.</p><p>Another example is for a file name:</p><pre class="screen">{sobject.code}_{snapshot.context}_v{snapshot.version}.{ext}</pre><p>This can be translated into: <code class="literal">chr001_model_v001.ma</code> upon expansion.</p><p>The @GET(sobejct.code) or @GET(sobject.sthpw/snapshot.version) TACTIC expression language syntax can be used instead; however, the original keyword approach is more readable. In case you do decide to use the TEL syntax, here are the equivalents:</p><p>{basefile} = {$BASEFILE}</p><p>{ext} = {$EXT}</p><p>{project.code} = {$PROJECT}</p><p>{login} = {$LOGIN}</p><p>It is important to note that you can’t fix TEL syntax with the keyword syntax in the same field of a naming entry.</p><p><span class="strong"><strong>3.0 Defaults</strong></span></p><p>TACTIC will fall back on the default convention which would be represented by the following expression. These defaults are slightly different from previous versions:</p><pre class="screen"> {project.code}/{search_type}/{sobject.code}/{context}</pre><pre class="screen"> {file.name}_{context}_v{version}.{ext}</pre><p>Checking in the file <span class="strong"><strong><span class="emphasis"><em>characterFile.ma</em></span></strong></span> would create the following file and directory structure:</p><pre class="screen">sample3d/characters/chr001/publish/characterFile_v001.ma</pre><p><span class="strong"><strong>Assumptions</strong></span></p><p>Various assumptions have been made about which attributes are attached to which SObjects. It is often the case that the context is composed of a number of parts that are of interest to a naming convention.</p><p>For example, it is conceivable to have a context named: "model/hi". However, you may wish to break this up in a specific way in your naming convention. This is accomplished using [] notation common to many programming languages.</p><p>The following notation could be used for a directory using this: which could be translated into</p><pre class="screen"> {code}/{context[0]}/maya/{context[1]}</pre><pre class="screen"> chr001/model/maya/hi</pre><p>To insert a naming convention expression, load a <span class="strong"><strong>Naming</strong></span> view and click the Insert button to insert a new set of expressions.</p><p>A Naming Convention sObject has specific properties which are used to either define the convention or act as conditions to define if the convention should be used for the given checkin. When Inserting, fill in the following options:</p><div class="informaltable"><table cellpadding="4px" style="border-collapse: collapse;border-top: 3px solid #527bbd; border-bottom: 3px solid #527bbd; border-left: 3px solid #527bbd; border-right: 3px solid #527bbd; " width="100%"><colgroup><col class="col_1" /><col class="col_2" /></colgroup><tbody><tr><td style="border-right: 1px solid #527bbd; border-bottom: 1px solid #527bbd; " align="left" valign="top"><p><span class="strong"><strong>Search Type</strong></span></p></td><td style="border-bottom: 1px solid #527bbd; " align="left" valign="top"><p>The search_type to associate the naming convention to.</p></td></tr><tr><td style="border-right: 1px solid #527bbd; border-bottom: 1px solid #527bbd; " align="left" valign="top"><p><span class="strong"><strong>Snapshot Type</strong></span></p></td><td style="border-bottom: 1px solid #527bbd; " align="left" valign="top"><p>The snapshot type of the checkin to use as a condition (default for most TACTIC check-ins is <span class="emphasis"><em>file</em></span>. Default for directory checkin using the General Checkin Widget is <span class="emphasis"><em>dir</em></span>. Since this is a more advanced attribute, it is hidden by default)</p></td></tr><tr><td style="border-right: 1px solid #527bbd; border-bottom: 1px solid #527bbd; " align="left" valign="top"><p><span class="strong"><strong>Context</strong></span></p></td><td style="border-bottom: 1px solid #527bbd; " align="left" valign="top"><p>The snapshot context of the checkin to use as a condition (default checkin when there is no pipeline is <span class="emphasis"><em>publish</em></span>)</p></td></tr><tr><td style="border-right: 1px solid #527bbd; border-bottom: 1px solid #527bbd; " align="left" valign="top"><p><span class="strong"><strong>Dir Naming</strong></span></p></td><td style="border-bottom: 1px solid #527bbd; " align="left" valign="top"><p>The expression entry for the directory naming convention</p></td></tr><tr><td style="border-right: 1px solid #527bbd; border-bottom: 1px solid #527bbd; " align="left" valign="top"><p><span class="strong"><strong>File Naming</strong></span></p></td><td style="border-bottom: 1px solid #527bbd; " align="left" valign="top"><p>The expression entry for the file naming convention</p></td></tr><tr><td style="border-right: 1px solid #527bbd; border-bottom: 1px solid #527bbd; " align="left" valign="top"><p><span class="strong"><strong>Sandbox Dir Naming</strong></span></p></td><td style="border-bottom: 1px solid #527bbd; " align="left" valign="top"><p>The expression entry for the user sandbox directory naming convention</p></td></tr><tr><td style="border-right: 1px solid #527bbd; border-bottom: 1px solid #527bbd; " align="left" valign="top"><p><span class="strong"><strong>Latest versionless</strong></span></p></td><td style="border-bottom: 1px solid #527bbd; " align="left" valign="top"><p>If set to true(checked), every time a check-in is created, a latest version of the main file will be created as well. If you want to always have a file that refers to the latest version of a model you can use this feature by calling it {sobject.code}_{context}_latest.{ext}. The latest version exists as copy by default. To make it a symlink, set the project setting versionless_mode to <span class="emphasis"><em>symlink</em></span>. Note: If this is checked, you need to have an entry in the naming table just for this versionless case in addition to the usual one for regular check-ins.</p></td></tr><tr><td style="border-right: 1px solid #527bbd; border-bottom: 1px solid #527bbd; " align="left" valign="top"><p><span class="strong"><strong>Current versionless</strong></span></p></td><td style="border-bottom: 1px solid #527bbd; " align="left" valign="top"><p>If set to true(checked), every time a check-in is created, a current version of the main file will be created as well. If you want to always have a file that refers to the latest version of a model you can use this feature by calling it {sobject.code}_{context}_latest.{ext}. The latest version exists as copy by default. To make it a symlink, set the project setting versionless_mode to <span class="emphasis"><em>symlink</em></span>. Note: If this is checked, you need to have an entry in the naming table just for this versionless case in addition to the usual one for regular check-ins.</p></td></tr><tr><td style="border-right: 1px solid #527bbd; border-bottom: 1px solid #527bbd; " align="left" valign="top"><p><span class="strong"><strong>Manual version</strong></span></p></td><td style="border-bottom: 1px solid #527bbd; " align="left" valign="top"><p>If set to true(checked), the incoming file name can dictate what the version of the checked-in snapshot appears as. For intance, if the incoming file name is dessert_v005.jpg, the version will appear as version 5. Another example is sun_V0030.0010.jpg. The version will appear as version 30. It tries to recognize the number immediately after the v or V in the file name. Zero or negative numbers are ignored. If such a version already exists, the check-in will throw an error</p></td></tr><tr><td style="border-right: 1px solid #527bbd; " align="left" valign="top"><p><span class="strong"><strong>Condition</strong></span></p></td><td style="" align="left" valign="top"><p>It can be set up so that differnet naming is adopted based on a particular attribute of the sObject. For instance, for the sType prod/asset, one can assign 2 naming entries. The default naming where the condition is left blank is adopted in most circumstance. The second special naming is adopted when the category attribute equals <span class="emphasis"><em>vehicle</em></span> by using this expression @GET(.category) ==<span class="emphasis"><em>vehicle</em></span>.</p></td></tr></tbody></table></div><p><span class="strong"><strong>Example A</strong></span></p><p>In the following example, the file is being checked in withe general <span class="emphasis"><em>publish</em></span> context</p><p><span class="strong"><strong>File:</strong></span> <span class="emphasis"><em>characterFile.ma</em></span></p><p><span class="strong"><strong>Checkin Context:</strong></span> publish</p><p><span class="strong"><strong>Desired output:</strong></span> sample3d/characters/character001/character001_publish_v001.ma:</p><pre class="screen"> {project.code}/{parent.title}/{sobject.code}</pre><pre class="screen"> {sobject.code}_{snapshot.context}_v{snapshot.version}.{ext}</pre><p><span class="strong"><strong>Example B</strong></span></p><p>In the following example, the shot RC_001_001 is part of the parent sequence RC_001 and is checked in with an <span class="emphasis"><em>animation</em></span> context. This will also use the short hand expressions</p><p><span class="strong"><strong>File:</strong></span> shotFile.ma</p><p><span class="strong"><strong>Checkin context:</strong></span> animation</p><p>*Desired output:*sample3d/shot/RC_001/RC_001_001/scenes/RC_001_001_animation_v001.ma</p><pre class="screen"> {project.code}/shot/{parent.code}/{sobject.code}/scenes</pre><pre class="screen"> {sobject.code}_{snapshot.context}_v{snapshot.version}.{ext}</pre><p><span class="strong"><strong>Example C</strong></span></p><p>In the following example, the desired file location is at the project folder level to accommodate a cross-project library of files.</p><p><span class="strong"><strong>File:</strong></span> artFile.png</p><p><span class="strong"><strong>Checkin context:</strong></span> publish</p><p><span class="strong"><strong>Desired output:</strong></span> general/art001/art001_publish_v001.png</p><pre class="screen"> general/{sobject.code}</pre><pre class="screen"> {sobject.code}_{snapshot.context}_v(snapshot.version}.{ext}</pre><p><span class="strong"><strong>Example D</strong></span></p><p>In the following example, a context and subcontext are used for checking in to a final process for an art asset</p><p><span class="strong"><strong>File:</strong></span> artFileFinal.psd</p><p><span class="strong"><strong>Checkin context/subcontext:</strong></span> final/colourA</p><p><span class="strong"><strong>Desired Output:</strong></span> finals/art001/final/photoshop/colourA/art001_final_colourA_v001.psd</p><pre class="screen"> finals/{sobject.code}/{snapshot.context[0]}/photoshop/{snapshot.context[1]}</pre><pre class="screen"> {sobject.code}_{snapshot.context[0]}_{snapshot.context[1]}_v{snapshot.version}.{ext}</pre><p><span class="strong"><strong>Example E</strong></span></p><p>In the following example, the shot RC_001_001 is part of the parent sequence RC_001 and is checked in with an <span class="emphasis"><em>animation</em></span> context. Also when a user checks out the sandbox, files should be organized into a user folder.</p><p><span class="strong"><strong>File:</strong></span> shotFile.ma</p><p><span class="strong"><strong>Checkin context:</strong></span> animation</p><p><span class="strong"><strong>Desired Repo output:</strong></span> sample3d/shot/RC_001/RC_001_001/scenes/RC_001_001_animation_v001.ma</p><p><span class="strong"><strong>Desired Sandbox output:</strong></span> sample3d/albert/shot/RC_001/RC_001_001/scenes/RC_001_001_animation_v001.ma</p><pre class="screen"> {project.code}/shot/{parent.code}/{sobject.code}/scenes</pre><pre class="screen"> {project.code}/{login.login}/shot/{parent.code}/{sobject.code}/scenes</pre><pre class="screen"> {sobject.code}_{snapshot.context}_v{snapshot.version}.{ext}</pre><p><span class="strong"><strong>Example F</strong></span></p><p>In the following example, the shot RC_001_001 is part of the parent sequence RC_001 and is checked in with an <span class="emphasis"><em>animation</em></span> context. Also when a user checks out the sandbox, files should be organized into a user folder. Since we also want to define a latest versionless, we need a second entry with the same information, and with the latest_versionless check-box checked. In this example we are putting the versionless file in the same directory, but you can put it in a different one if desired.</p><p><span class="strong"><strong>File:</strong></span> shotFile.ma</p><p><span class="strong"><strong>Checkin context:</strong></span> animation</p><p><span class="strong"><strong>Desired Repo output:</strong></span> sample3d/shot/RC_001/RC_001_001/scenes/RC_001_001_animation_v001.ma</p><p><span class="strong"><strong>Desired Repo latest versionless output:</strong></span> sample3d/shot/RC_001/RC_001_001/scenes/RC_001_001_animation_latest.ma</p><p><span class="strong"><strong>Desired Sandbox output:</strong></span> sample3d/albert/shot/RC_001/RC_001_001/scenes/RC_001_001_animation_v001.ma</p><p>Entry 1</p><pre class="screen"> {project.code}/shot/{parent.code}/{sobject.code}/scenes</pre><pre class="screen"> {project.code}/{login.login}/shot/{parent.code}/{sobject.code}/scenes</pre><pre class="screen"> {sobject.code}_{snapshot.context}_v{snapshot.version}.{ext}</pre><p>Entry 2</p><pre class="screen"> {project.code}/shot/{parent.code}/{sobject.code}/scenes</pre><pre class="screen"> {project.code}/{login.login}/shot/{parent.code}/{sobject.code}/scenes</pre><pre class="screen"> {sobject.code}_{snapshot.context}_latest.{ext}</pre><pre class="screen"> true</pre><p><span class="strong"><strong>Example G</strong></span></p><p>In the following example, a texture file is checked in under shot RC_001_001. Also when a user checks out the sandbox, files should be organized into a user folder. Since we also want to define a current versionless, we need a second entry with the same information, and with the current_versionless check-box checked. In this example, we are retaining the original file name</p><p><span class="strong"><strong>File:</strong></span> shotFile.ma</p><p><span class="strong"><strong>Checkin context:</strong></span> animation</p><p><span class="strong"><strong>Desired Repo output:</strong></span> sample3d/shot/RC_001/RC_001_001/texture/my_tree_texture.jpg</p><p><span class="strong"><strong>Desired Repo latest versionless output:</strong></span> sample3d/shot/RC_001/RC_001_001/texture/my_tree_texture_CURRENT.jpg</p><p><span class="strong"><strong>Desired Sandbox output:</strong></span> sample3d/albert/shot/RC_001/RC_001_001/scenes/my_tree_texture.jpg</p><p>Entry 1</p><pre class="screen"> {project.code}/shot/{parent.code}/{sobject.code}/textures</pre><pre class="screen"> {project.code}/{login.login}/shot/{parent.code}/{sobject.code}/textures</pre><pre class="screen"> {basefile}.{ext}</pre><p>Entry 2</p><pre class="screen"> {project.code}/shot/{parent.code}/{sobject.code}/textures</pre><pre class="screen"> {project.code}/{login.login}/shot/{parent.code}/{sobject.code}/textures</pre><pre class="screen"> {basefile}_CURRENT.{ext}</pre><pre class="screen"> true</pre><p><span class="strong"><strong>Example H</strong></span></p><p>In the following example, asset file name is made up of asset_code, context, and version by default. If the asset’s category is <span class="emphasis"><em>2D</em></span> , we will add this category as a suffix to the name</p><p><span class="strong"><strong>File:</strong></span> my_chr001.jpg</p><p><span class="strong"><strong>Checkin context:</strong></span> model</p><p><span class="strong"><strong>Desired Repo output:</strong></span> sample3d/asset/chr001/chr001_model_v001.jpg</p><p><span class="strong"><strong>Second Desired Repo output:</strong></span> sample3d/asset/chr003/chr003_model_v001_2D.jpg</p><p><span class="strong"><strong>Desired Sandbox output:</strong></span> sample3d/dan/asset/chr001/my_chr001.jpg</p><p>Entry 1</p><pre class="screen"> {project.code}/asset/{sobject.code}</pre><pre class="screen"> {project.code}/{login.login}/asset/{sobject.code}</pre><pre class="screen"> {sobject.code}_{context}_{version}.{ext}</pre><p>Entry 2</p><pre class="screen"> {project.code}/asset/{sobject.code}</pre><pre class="screen"> {project.code}/{login.login}/asset/{sobject.code}</pre><pre class="screen"> {sobject.code}_{context}_{version}_{sobject.category}.{ext}</pre><pre class="screen"> @GET(.category)=='2D'</pre><p><span class="strong"><strong>Example I</strong></span></p><p>In the following example, the <span class="emphasis"><em>Checkin Type</em></span> is set to be (auto), to use the filename as the subcontext.</p><p>The checkin type "(main)", uses the process as context.</p><p>The checkin type "(strict)" could also be available as a checkin type.</p><p><span class="strong"><strong>File:</strong></span> shotFile.ma</p><p><span class="strong"><strong>Checkin context:</strong></span> design/shotFile.ma</p><p>*Desired Repo output:*finals/art001/photoshop/design/shotFile.ma</p><pre class="screen"> finals/{sobject.code}/photoshop/{snapshot.context}</pre><pre class="screen"> (auto)</pre><pre class="screen"> {sobject.code}_{snapshot.context}_v{snapshot.version}.{ext}</pre><p><span class="strong"><strong>Example J - keywords: snapshot and file</strong></span></p><p>The following is an example of the proper way to use the special keywords <span class="strong"><strong>snapshot</strong></span> and <span class="strong"><strong>file</strong></span> in an expression to retrieve the snapshot and file object for a checkin:</p><pre class="screen">{@GET(snapshot.context)}</pre><pre class="screen">{@GET(file.type)}</pre><p>Notice that the syntax for these particular expressions deviates from the syntax of typical TACTIC expressions.</p><p>In the example below, {$PROJECT} is used to replace {project.code}.</p><p>Below is an example using these expressions of a file being checked in with the general <span class="emphasis"><em>publish</em></span> context:</p><p><span class="strong"><strong>File:</strong></span> <span class="emphasis"><em>source_art_v0001.jpg</em></span></p><p><span class="strong"><strong>Checkin Context:</strong></span> publish</p><p><span class="strong"><strong>Desired output:</strong></span> sample3d/chr/chr001/publish</p><pre class="screen"> {$PROJECT}/chr/{@GET(.code)}/{@GET(snapshot.context)}</pre><pre class="screen"> source_art_v{@GET(snapshot.context).version,%04.d}.{@GET(file.type)}</pre><p><span class="strong"><strong>Example K - Combination of TACTIC expression language syntax and the original keyword approach</strong></span></p><p>The following is an example of directory naming using the TACTIC expression language syntax and the original keyword approach. It will also use expression language syntax to specify the condition.</p><pre class="screen">{@GET(snapshot.process)}</pre><pre class="screen">{@GET(file.name)}</pre><p>Notice that the syntax for these particular expressions deviates from the syntax of typical TACTIC expressions.</p><p>In the example below, the keyword approach {project.code}, can be used with expression language {@GET(.code)}.</p><p>Below is an example using these expressions of a file being checked in with the process <span class="emphasis"><em>finish</em></span>, the <span class="emphasis"><em>Condition</em></span> entry defines a specific category called <span class="emphasis"><em>2D</em></span> and the <span class="emphasis"><em>Context</em></span> entry will only allow you to check in the files that have the process design:</p><p><span class="strong"><strong>File:</strong></span> <span class="emphasis"><em>source_art_v001.jpg</em></span></p><p><span class="strong"><strong>Checkin Context:</strong></span> design</p><p><span class="strong"><strong>Desired output:</strong></span> sample3d/chr001/design</p><pre class="screen"> {project.code}/{@GET(.code)}/{@GET(snapshot.process)}</pre><pre class="screen"> Design/*</pre><pre class="screen"> {project.code}/{login.login}/asset/{sobject.code}</pre><pre class="screen"> {@GET(file.name).version,%03.d}.{@GET(file.type)}</pre><pre class="screen"> @GET(.category)=='2D'</pre></div></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="ar01s11.html">Prev</a> </td><td width="20%" align="center"> </td><td width="40%" align="right"> <a accesskey="n" href="ar01s13.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top"> </td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top"> </td></tr></table></div></body></html>
mwx1993/TACTIC
doc/book/doc/doc_tactic-setup/html/ar01s12.html
HTML
epl-1.0
25,671
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.4.2_11) on Mon Jul 12 21:37:49 CEST 2010 --> <TITLE> ResourceHandler (Apache FOP 1.0 API) </TITLE> <META NAME="keywords" CONTENT="org.apache.fop.render.ps.ResourceHandler class"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="ResourceHandler (Apache FOP 1.0 API)"; } </SCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/ResourceHandler.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> fop 1.0</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../org/apache/fop/render/ps/PSTranscoder.html" title="class in org.apache.fop.render.ps"><B>PREV CLASS</B></A>&nbsp; &nbsp;NEXT CLASS</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ResourceHandler.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> org.apache.fop.render.ps</FONT> <BR> Class ResourceHandler</H2> <PRE> java.lang.Object <IMG SRC="../../../../../resources/inherit.gif" ALT="extended by"><B>org.apache.fop.render.ps.ResourceHandler</B> </PRE> <DL> <DT><B>All Implemented Interfaces:</B> <DD>org.apache.xmlgraphics.ps.dsc.DSCParserConstants, <A HREF="../../../../../org/apache/fop/render/ps/PSSupportedFlavors.html" title="interface in org.apache.fop.render.ps">PSSupportedFlavors</A></DD> </DL> <HR> <DL> <DT>public class <B>ResourceHandler</B><DT>extends java.lang.Object<DT>implements org.apache.xmlgraphics.ps.dsc.DSCParserConstants, <A HREF="../../../../../org/apache/fop/render/ps/PSSupportedFlavors.html" title="interface in org.apache.fop.render.ps">PSSupportedFlavors</A></DL> <P> This class is used when two-pass production is used to generate the PostScript file (setting "optimize-resources"). It uses the DSC parser from XML Graphics Commons to go over the temporary file generated by the PSRenderer and adds all used fonts and images as resources to the PostScript file. <P> <P> <HR> <P> <!-- ======== NESTED CLASS SUMMARY ======== --> <!-- =========== FIELD SUMMARY =========== --> <A NAME="field_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> <B>Field Summary</B></FONT></TD> </TR> </TABLE> &nbsp;<A NAME="fields_inherited_from_class_org.apache.xmlgraphics.ps.dsc.DSCParserConstants"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TD><B>Fields inherited from interface org.apache.xmlgraphics.ps.dsc.DSCParserConstants</B></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>COMMENT, DSC_COMMENT, EOF, HEADER_COMMENT, LINE</CODE></TD> </TR> </TABLE> &nbsp;<A NAME="fields_inherited_from_class_org.apache.fop.render.ps.PSSupportedFlavors"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TD><B>Fields inherited from interface org.apache.fop.render.ps.<A HREF="../../../../../org/apache/fop/render/ps/PSSupportedFlavors.html" title="interface in org.apache.fop.render.ps">PSSupportedFlavors</A></B></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><A HREF="../../../../../org/apache/fop/render/ps/PSSupportedFlavors.html#LEVEL_2_FLAVORS_FORM">LEVEL_2_FLAVORS_FORM</A>, <A HREF="../../../../../org/apache/fop/render/ps/PSSupportedFlavors.html#LEVEL_2_FLAVORS_INLINE">LEVEL_2_FLAVORS_INLINE</A>, <A HREF="../../../../../org/apache/fop/render/ps/PSSupportedFlavors.html#LEVEL_3_FLAVORS_FORM">LEVEL_3_FLAVORS_FORM</A>, <A HREF="../../../../../org/apache/fop/render/ps/PSSupportedFlavors.html#LEVEL_3_FLAVORS_INLINE">LEVEL_3_FLAVORS_INLINE</A></CODE></TD> </TR> </TABLE> &nbsp; <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../../org/apache/fop/render/ps/ResourceHandler.html#ResourceHandler(org.apache.fop.apps.FOUserAgent, org.apache.fop.fonts.FontInfo, org.apache.xmlgraphics.ps.dsc.ResourceTracker, java.util.Map)">ResourceHandler</A></B>(<A HREF="../../../../../org/apache/fop/apps/FOUserAgent.html" title="class in org.apache.fop.apps">FOUserAgent</A>&nbsp;userAgent, <A HREF="../../../../../org/apache/fop/fonts/FontInfo.html" title="class in org.apache.fop.fonts">FontInfo</A>&nbsp;fontInfo, org.apache.xmlgraphics.ps.dsc.ResourceTracker&nbsp;resTracker, java.util.Map&nbsp;formResources)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Main constructor.</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> <B>Method Summary</B></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/fop/render/ps/ResourceHandler.html#process(java.io.InputStream, java.io.OutputStream, int, java.awt.geom.Rectangle2D)">process</A></B>(java.io.InputStream&nbsp;in, java.io.OutputStream&nbsp;out, int&nbsp;pageCount, java.awt.geom.Rectangle2D&nbsp;documentBoundingBox)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Rewrites the temporary PostScript file generated by PSRenderer adding all needed resources (fonts and images).</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TD><B>Methods inherited from class java.lang.Object</B></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ============ FIELD DETAIL =========== --> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=1><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TD> </TR> </TABLE> <A NAME="ResourceHandler(org.apache.fop.apps.FOUserAgent, org.apache.fop.fonts.FontInfo, org.apache.xmlgraphics.ps.dsc.ResourceTracker, java.util.Map)"><!-- --></A><H3> ResourceHandler</H3> <PRE> public <B>ResourceHandler</B>(<A HREF="../../../../../org/apache/fop/apps/FOUserAgent.html" title="class in org.apache.fop.apps">FOUserAgent</A>&nbsp;userAgent, <A HREF="../../../../../org/apache/fop/fonts/FontInfo.html" title="class in org.apache.fop.fonts">FontInfo</A>&nbsp;fontInfo, org.apache.xmlgraphics.ps.dsc.ResourceTracker&nbsp;resTracker, java.util.Map&nbsp;formResources)</PRE> <DL> <DD>Main constructor. <P> <DT><B>Parameters:</B><DD><CODE>userAgent</CODE> - the FO user agent<DD><CODE>fontInfo</CODE> - the font information<DD><CODE>resTracker</CODE> - the resource tracker to use<DD><CODE>formResources</CODE> - Contains all forms used by this document (maintained by PSRenderer)</DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=1><FONT SIZE="+2"> <B>Method Detail</B></FONT></TD> </TR> </TABLE> <A NAME="process(java.io.InputStream, java.io.OutputStream, int, java.awt.geom.Rectangle2D)"><!-- --></A><H3> process</H3> <PRE> public void <B>process</B>(java.io.InputStream&nbsp;in, java.io.OutputStream&nbsp;out, int&nbsp;pageCount, java.awt.geom.Rectangle2D&nbsp;documentBoundingBox) throws org.apache.xmlgraphics.ps.dsc.DSCException, java.io.IOException</PRE> <DL> <DD>Rewrites the temporary PostScript file generated by PSRenderer adding all needed resources (fonts and images). <P> <DD><DL> </DL> </DD> <DD><DL> <DT><B>Parameters:</B><DD><CODE>in</CODE> - the InputStream for the temporary PostScript file<DD><CODE>out</CODE> - the OutputStream to write the finished file to<DD><CODE>pageCount</CODE> - the number of pages (given here because PSRenderer writes an "(atend)")<DD><CODE>documentBoundingBox</CODE> - the document's bounding box (given here because PSRenderer writes an "(atend)") <DT><B>Throws:</B> <DD><CODE>org.apache.xmlgraphics.ps.dsc.DSCException</CODE> - If there's an error in the DSC structure of the PS file <DD><CODE>java.io.IOException</CODE> - In case of an I/O error</DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/ResourceHandler.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> fop 1.0</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../org/apache/fop/render/ps/PSTranscoder.html" title="class in org.apache.fop.render.ps"><B>PREV CLASS</B></A>&nbsp; &nbsp;NEXT CLASS</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ResourceHandler.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright 1999-2010 The Apache Software Foundation. All Rights Reserved. </BODY> </HTML>
theanuradha/debrief
contribs/fop-1.0/javadocs/org/apache/fop/render/ps/ResourceHandler.html
HTML
epl-1.0
14,965
########################################################### # # Copyright (c) 2005, Southpaw Technology # All Rights Reserved # # PROPRIETARY INFORMATION. This software is proprietary to # Southpaw Technology, and is not to be reproduced, transmitted, # or disclosed in any way without written permission. # # # import tacticenv from pyasm.security import * from sql import * from search import * from transaction import * import unittest class RelationshipTest(unittest.TestCase): def setUp(my): # start batch environment Batch() from pyasm.biz import Project Project.set_project("unittest") def test_all(my): my.transaction = Transaction.get(create=True) try: my._test_parent_child() my._test_related() finally: my.transaction.rollback() def _test_parent_child(my): search = Search("unittest/person") persons = search.get_sobjects() person = persons[0] # create a task manually task = SearchType.create("sthpw/task") task.set_sobject_value(person) task.commit() # test get parent parent = task.get_parent() my.assertEquals( parent.get_code(), person.get_code() ) # create another task task = SearchType.create("sthpw/task") task.set_sobject_value(person) task.commit() # get the children children = person.get_all_children("sthpw/task") my.assertEquals( 2, len(children) ) # set the parent task = SearchType.create("sthpw/task") task.set_parent(person) task.commit() # get the children children = person.get_all_children("sthpw/task") my.assertEquals( 3, len(children) ) # parent search key parent_key = task.get_parent_search_key() my.assertEquals(person.get_search_key(), parent_key) def _test_related(my): search = Search("unittest/person") persons = search.get_sobjects() person = persons[1] # create another task for i in range(0, 4): task = SearchType.create("sthpw/task") task.set_sobject_value(person) task.commit() # create another note for i in range(0, 3): task = SearchType.create("sthpw/note") task.set_sobject_value(person) task.commit() tasks = person.get_related_sobjects("sthpw/task") my.assertEquals( 4, len(tasks) ) notes = person.get_related_sobjects("sthpw/note") my.assertEquals( 3, len(notes) ) if __name__ == "__main__": unittest.main()
talha81/TACTIC-DEV
src/pyasm/search/relationship_test.py
Python
epl-1.0
2,722
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.testing.oxm.xmlroot.simple; import junit.textui.TestRunner; import org.eclipse.persistence.oxm.XMLRoot; import org.w3c.dom.Document; public class XMLRootNoPrefixTestCases extends XMLRootSimpleTestCases { private final static String XML_RESOURCE = "org/eclipse/persistence/testing/oxm/xmlroot/simple/employee-no-prefix.xml"; private final static String CONTROL_ELEMENT_NAME = "ns0:employee-name"; private final static String CONTROL_ELEMENT_NAME_NO_PREFIX = "employee-name"; public XMLRootNoPrefixTestCases(String name) throws Exception { super(name); } public static void main(String[] args) { String[] arguments = { "-c", "org.eclipse.persistence.testing.oxm.xmlroot.simple.XMLRootNoPrefixTestCases" }; TestRunner.main(arguments); } public Object getReadControlObject() { XMLRoot xmlRoot = new XMLRoot(); xmlRoot.setLocalName(CONTROL_ELEMENT_NAME); xmlRoot.setNamespaceURI(CONTROL_NAMESPACE_URI); xmlRoot.setObject(CONTROL_OBJECT); return xmlRoot; } public Object getWriteControlObject() { XMLRoot xmlRoot = new XMLRoot(); xmlRoot.setLocalName(CONTROL_ELEMENT_NAME_NO_PREFIX); xmlRoot.setNamespaceURI(CONTROL_NAMESPACE_URI); xmlRoot.setObject(CONTROL_OBJECT); return xmlRoot; } public String getXMLResource() { return XML_RESOURCE; } public Document getWriteControlDocument() { return getControlDocument(); } }
gameduell/eclipselink.runtime
moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/oxm/xmlroot/simple/XMLRootNoPrefixTestCases.java
Java
epl-1.0
2,257
/** * Copyright (c) 2005-2012 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Eclipse Public License (EPL). * Please see the license.txt included with this distribution for details. * Any modifications to this file must keep this entire header intact. */ package org.python.pydev.parser.visitors; import java.util.List; import org.python.pydev.parser.jython.ISpecialStr; import org.python.pydev.parser.jython.SimpleNode; import org.python.pydev.parser.jython.ast.Attribute; import org.python.pydev.parser.jython.ast.ImportFrom; import org.python.pydev.parser.jython.ast.VisitorBase; public class FindLastLineVisitor extends VisitorBase { private SimpleNode lastNode; private ISpecialStr lastSpecialStr; @Override protected Object unhandled_node(SimpleNode node) throws Exception { this.lastNode = node; check(this.lastNode.specialsBefore); check(this.lastNode.specialsAfter); return null; } @Override public Object visitAttribute(Attribute node) throws Exception { check(node.specialsBefore); if (node.attr != null) node.attr.accept(this); if (node.value != null) node.value.accept(this); check(node.specialsAfter); return null; } private void check(List<Object> specials) { if (specials == null) { return; } for (Object obj : specials) { if (obj instanceof ISpecialStr) { if (lastSpecialStr == null || lastSpecialStr.getBeginLine() <= ((ISpecialStr) obj).getBeginLine()) { lastSpecialStr = (ISpecialStr) obj; } } } } @Override public Object visitImportFrom(ImportFrom node) throws Exception { if (node.module != null) { unhandled_node(node.module); node.module.accept(this); } if (node.names != null) { for (int i = 0; i < node.names.length; i++) { if (node.names[i] != null) { unhandled_node(node.names[i]); node.names[i].accept(this); } } } unhandled_node(node); return null; } @Override public void traverse(SimpleNode node) throws Exception { node.traverse(this); } public SimpleNode getLastNode() { return lastNode; } public ISpecialStr getLastSpecialStr() { return lastSpecialStr; } }
akurtakov/Pydev
plugins/org.python.pydev.parser/src/org/python/pydev/parser/visitors/FindLastLineVisitor.java
Java
epl-1.0
2,527
/** * Copyright (c) 2010-2016, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.systeminfo.internal; import java.util.ArrayList; import java.util.Arrays; import java.util.Dictionary; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.hyperic.sigar.FileSystem; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarProxy; import org.hyperic.sigar.SigarProxyCache; import org.hyperic.sigar.ptql.ProcessFinder; import org.openhab.binding.systeminfo.SysteminfoBindingProvider; import org.openhab.core.binding.AbstractActiveBinding; import org.openhab.core.items.Item; import org.openhab.core.library.types.DecimalType; import org.openhab.core.library.types.StringType; import org.openhab.core.types.State; import org.openhab.core.types.UnDefType; import org.osgi.service.cm.ConfigurationException; import org.osgi.service.cm.ManagedService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Binding for system and process information gathering. * * @author Pauli Anttila * @since 1.3.0 */ public class SysteminfoBinding extends AbstractActiveBinding<SysteminfoBindingProvider>implements ManagedService { private static final Logger logger = LoggerFactory.getLogger(SysteminfoBinding.class); /** the interval to find new refresh candidates (defaults to 1000 milliseconds) */ private int granularity = 1000; /** the unit to measure keyfacts (defaults to 'M') */ private char units = 'M'; private Map<String, Long> lastUpdateMap = new HashMap<String, Long>(); private static Sigar sigarImpl; private static SigarProxy sigar; @Override public void activate() { } @Override public void deactivate() { sigar = null; sigarImpl = null; } /** * @{inheritDoc */ @Override protected long getRefreshInterval() { return granularity; } /** * @{inheritDoc */ @Override protected String getName() { return "Systeminfo Refresh Service"; } /** * @{inheritDoc */ @Override protected void execute() { for (SysteminfoBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { int refreshInterval = provider.getRefreshInterval(itemName); Long lastUpdateTimeStamp = lastUpdateMap.get(itemName); if (lastUpdateTimeStamp == null) { lastUpdateTimeStamp = 0L; } long age = System.currentTimeMillis() - lastUpdateTimeStamp; boolean needsUpdate = age >= refreshInterval; if (needsUpdate) { logger.debug("item '{}' is about to be refreshed now", itemName); SysteminfoCommandType commmandType = provider.getCommandType(itemName); Class<? extends Item> itemType = provider.getItemType(itemName); String target = provider.getTarget(itemName); State state = getData(commmandType, itemType, target); if (state != null) { eventPublisher.postUpdate(itemName, state); } else { logger.error("No response received from command '{}'", commmandType); } lastUpdateMap.put(itemName, System.currentTimeMillis()); } } } } private State getData(SysteminfoCommandType commandType, Class<? extends Item> itemType, String target) { State state = UnDefType.UNDEF; long pid; try { switch (commandType) { case LOAD_AVERAGE_1MIN: state = new DecimalType(sigar.getLoadAverage()[0]); break; case LOAD_AVERAGE_5MIN: state = new DecimalType(sigar.getLoadAverage()[1]); break; case LOAD_AVERAGE_15MIN: state = new DecimalType(sigar.getLoadAverage()[2]); break; case CPU_COMBINED: state = new DecimalType(sigar.getCpuPerc().getCombined() * 100); break; case CPU_USER: state = new DecimalType(sigar.getCpuPerc().getUser() * 100); break; case CPU_SYSTEM: state = new DecimalType(sigar.getCpuPerc().getSys() * 100); break; case CPU_NICE: state = new DecimalType(sigar.getCpuPerc().getNice() * 100); break; case CPU_WAIT: state = new DecimalType(sigar.getCpuPerc().getWait() * 100); break; case UPTIME: state = new DecimalType(sigar.getUptime().getUptime()); break; case UPTIME_FORMATTED: state = new StringType(getElapsedTime((long) sigar.getUptime().getUptime())); break; case MEM_FREE_PERCENT: state = new DecimalType(sigar.getMem().getFreePercent()); break; case MEM_USED_PERCENT: state = new DecimalType(sigar.getMem().getUsedPercent()); break; case MEM_FREE: state = new DecimalType(formatBytes(sigar.getMem().getFree(), units)); break; case MEM_USED: state = new DecimalType(formatBytes(sigar.getMem().getUsed(), units)); break; case MEM_ACTUAL_FREE: state = new DecimalType(formatBytes(sigar.getMem().getActualFree(), units)); break; case MEM_ACTUAL_USED: state = new DecimalType(formatBytes(sigar.getMem().getActualUsed(), units)); break; case MEM_TOTAL: state = new DecimalType(formatBytes(sigar.getMem().getTotal(), units)); break; case SWAP_FREE: state = new DecimalType(formatBytes(sigar.getSwap().getFree(), units)); break; case SWAP_TOTAL: state = new DecimalType(formatBytes(sigar.getSwap().getTotal(), units)); break; case SWAP_USED: state = new DecimalType(formatBytes(sigar.getSwap().getUsed(), units)); break; case SWAP_PAGE_IN: state = new DecimalType(formatBytes(sigar.getSwap().getPageIn(), units)); break; case SWAP_PAGE_OUT: state = new DecimalType(formatBytes(sigar.getSwap().getPageOut(), units)); break; case NET_RX_BYTES: state = new DecimalType(formatBytes(sigar.getNetInterfaceStat(target).getRxBytes(), units)); break; case NET_TX_BYTES: state = new DecimalType(formatBytes(sigar.getNetInterfaceStat(target).getTxBytes(), units)); break; case DISK_READS: state = new DecimalType(sigar.getDiskUsage(target).getReads()); break; case DISK_WRITES: state = new DecimalType(sigar.getDiskUsage(target).getWrites()); break; case DISK_READ_BYTES: state = new DecimalType(formatBytes(sigar.getDiskUsage(target).getReadBytes(), units)); break; case DISK_WRITE_BYTES: state = new DecimalType(formatBytes(sigar.getDiskUsage(target).getWriteBytes(), units)); break; case FS_USED: state = new DecimalType(formatBytes(sigar.getFileSystemUsage(target).getUsed() * 1024, units)); break; case FS_FREE: state = new DecimalType(formatBytes(sigar.getFileSystemUsage(target).getFree() * 1024, units)); break; case FS_TOTAL: state = new DecimalType(formatBytes(sigar.getFileSystemUsage(target).getTotal() * 1024, units)); break; case FS_USE_PERCENT: state = new DecimalType(sigar.getFileSystemUsage(target).getUsePercent() * 100); break; case FS_FILES: state = new DecimalType(sigar.getFileSystemUsage(target).getFiles()); break; case FS_FREE_FILES: state = new DecimalType(sigar.getFileSystemUsage(target).getFreeFiles()); break; case DIR_USAGE: state = new DecimalType(formatBytes(sigar.getDirUsage(target).getDiskUsage(), units)); break; case DIR_FILES: state = new DecimalType(sigar.getDirUsage(target).getFiles()); break; case PROCESS_REAL_MEM: pid = getPid(target); state = new DecimalType(formatBytes(sigar.getProcMem(pid).getResident(), units)); break; case PROCESS_VIRTUAL_MEM: pid = getPid(target); state = new DecimalType(formatBytes(sigar.getProcMem(pid).getSize(), units)); break; case PROCESS_CPU_PERCENT: pid = getPid(target); state = new DecimalType(sigar.getProcCpu(pid).getPercent() * 100); break; case PROCESS_CPU_SYSTEM: pid = getPid(target); state = new DecimalType(sigar.getProcCpu(pid).getSys()); break; case PROCESS_CPU_USER: pid = getPid(target); state = new DecimalType(sigar.getProcCpu(pid).getUser()); break; case PROCESS_CPU_TOTAL: pid = getPid(target); state = new DecimalType(sigar.getProcCpu(pid).getTotal()); break; case PROCESS_UPTIME: pid = getPid(target); state = new DecimalType(getProcessUptime(pid)); break; case PROCESS_UPTIME_FORMATTED: pid = getPid(target); state = new StringType(getElapsedTime(getProcessUptime(pid))); break; default: break; } } catch (SigarException e) { logger.error("Error occured while reading KPI's", e); } return state; } private long getProcessUptime(long pid) throws SigarException { long processStartTime = sigar.getProcTime(pid).getStartTime(); long currentTime = System.currentTimeMillis(); return (currentTime - processStartTime) / 1000; } private long getPid(String processName) throws SigarException { long pid; ProcessFinder processFinder = new ProcessFinder(sigarImpl); String query; if (processName.equals("$$")) { pid = sigar.getPid(); logger.debug("Return own pid {}", pid); return pid; } else if (processName.startsWith("*")) { query = "State.Name.sw=" + processName.replace("*", ""); } else if (processName.endsWith("*")) { query = "State.Name.ew=" + processName.replace("*", ""); } else if (processName.startsWith("=")) { query = "State.Name.eq=" + processName.replace("=", ""); } else if (processName.startsWith("#")) { query = processName.replace("#", ""); } else { query = "State.Name.ct=" + processName; } logger.debug("Query pid by '{}'", query); pid = processFinder.findSingleProcess(query); logger.debug("Return pid {}", pid); return pid; } private static String getElapsedTime(long sec) { final int SECOND = 1; final int MINUTE = 60 * SECOND; final int HOUR = 60 * MINUTE; final int DAY = 24 * HOUR; StringBuffer text = new StringBuffer(""); if (sec > DAY) { if (sec < (2 * DAY)) { text.append(sec / DAY).append(" day "); } else { text.append(sec / DAY).append(" days "); } sec %= DAY; } text.append(sec / HOUR).append(":"); sec %= HOUR; text.append(String.format("%02d", sec / MINUTE)); return text.toString(); } private double formatBytes(double value, char units) { double retval = 0; switch (units) { case 'K': retval = value / 1024; break; case 'M': retval = value / (1024 * 1024); break; case 'G': retval = value / (1024 * 1024 * 1024); break; case 'B': default: retval = value; break; } return retval; } protected void addBindingProvider(SysteminfoBindingProvider bindingProvider) { super.addBindingProvider(bindingProvider); } protected void removeBindingProvider(SysteminfoBindingProvider bindingProvider) { super.removeBindingProvider(bindingProvider); } /** * {@inheritDoc} */ @Override public void updated(Dictionary<String, ?> config) throws ConfigurationException { if (config != null) { String granularityString = (String) config.get("granularity"); if (StringUtils.isNotBlank(granularityString)) { granularity = Integer.parseInt(granularityString); } logger.debug("Granularity: {} ms", granularity); String tmp = (String) config.get("units"); if (StringUtils.isNotBlank(tmp)) { if (tmp.length() != 1) { throw new ConfigurationException("units", "Illegal units length"); } if (!tmp.matches("[BKMGT]")) { throw new ConfigurationException("units", "Illegal units"); } units = tmp.charAt(0); } logger.debug("Using units: {}", units); } initializeSystemMonitor(); setProperlyConfigured(true); } private void initializeSystemMonitor() { if (sigarImpl == null) { sigarImpl = new Sigar(); } if (sigar == null) { sigar = SigarProxyCache.newInstance(sigarImpl, 1000); } logger.info("Using Sigar version {}", Sigar.VERSION_STRING); try { String[] interfaces = sigar.getNetInterfaceList(); logger.debug("valid net interfaces: {}", Arrays.toString(interfaces)); FileSystem[] filesystems = sigar.getFileSystemList(); logger.debug("file systems: {}", Arrays.toString(filesystems)); List<String> disks = new ArrayList<String>(); for (int i = 0; i < filesystems.length; i++) { FileSystem fs = filesystems[i]; if (fs.getType() == FileSystem.TYPE_LOCAL_DISK) { disks.add(fs.getDevName()); } } logger.debug("valid disk names: {}", Arrays.toString(disks.toArray())); } catch (SigarException e) { logger.error("System monitor error: {}", e); } } }
steintore/openhab
bundles/binding/org.openhab.binding.systeminfo/src/main/java/org/openhab/binding/systeminfo/internal/SysteminfoBinding.java
Java
epl-1.0
16,250
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/> <title>About</title> </head> <body lang="EN-US"> <h2>About This Content</h2> <h3>Third Party Content</h3> <ul> <li><a href="https://github.com/beowulfe/HAP-Java">HAP-Java</a>: Homekit protocol implementation, under MIT license</li> <li><a href="http://connect2id.com/products/nimbus-srp">Nimbusds SRP6A</a>: Secure Remote Password library, dependency of HAP-Java, under Apache 2.0 license</li> <li><a href="http://netty.io">Netty</a>: Socket handling, dependency of HAP-Java, under Apache 2.0 license</li> <li><a href="https://jsonp.java.net">JSONP</a>: API and Glassfish implementation for JSR-353, dependency of HAP-Java, under GPLv2 or CDDL 1.1 license</li> <li><a href="https://github.com/str4d/ed25519-java">ed25519-java</a>: Java implementation of the Edwards-curve Digital Signature Algorithm, dependency of HAP-Java, under CC0 1.0 license</li> <li><a href="https://www.bouncycastle.org">Bouncycastle</a>: General purpose cryptography library, dependency of HAP-Java, under MIT license</li> <li><a href="https://code.google.com/archive/p/curve25519-java/">curve25519-java</a>: Java implementation of the Diffie-Hellman key agreement scheme, dependency of HAP_Java, under Apache 2.0 license</li> </ul> </body> </html>
georgeerhan/openhab2-addons
addons/io/org.openhab.io.homekit/about.html
HTML
epl-1.0
1,490
/** * Copyright (c) 2010-2016, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.harmonyhub.internal; import java.util.HashMap; import java.util.Map; /** * HarmonyHubBindingType is a {@link Enum} of possible binding types that an item can be configured for. * * @author Dan Cunningham * @since 1.7.0 */ public enum HarmonyHubBindingType { CurrentActivity("currentActivity", HarmonyHubBindingDirection.BOTH), StartActivity("start", HarmonyHubBindingDirection.OUT), PressButton("press", HarmonyHubBindingDirection.OUT); /** * String used in the binding config */ private String label; /** * Direction that this command goes */ private HarmonyHubBindingDirection direction; /** * helper map retrieve HarmonyHubBindingType by it's label */ private static Map<String, HarmonyHubBindingType> labelToHarmonyHubBindingType; HarmonyHubBindingType(String label, HarmonyHubBindingDirection direction) { this.label = label; this.direction = direction; } /** * init our internal map */ private static void initMapping() { labelToHarmonyHubBindingType = new HashMap<String, HarmonyHubBindingType>(); for (HarmonyHubBindingType h : values()) { labelToHarmonyHubBindingType.put(h.label, h); } } /** * Returns the {@link String} label used in bindings configurations * * @return */ public String getLabel() { return label; } public HarmonyHubBindingDirection getDirection() { return direction; } public static HarmonyHubBindingType getHarmonyHubBindingType(String label) { if (labelToHarmonyHubBindingType == null) { initMapping(); } return labelToHarmonyHubBindingType.get(label); } public static String PatternString() { StringBuilder sb = null; for (HarmonyHubBindingType h : values()) { if (sb == null) { sb = new StringBuilder(h.label); } else { sb.append("|").append(h.label); } } return sb.toString(); } @Override public String toString() { return getLabel(); } }
SwissKid/openhab
bundles/binding/org.openhab.binding.harmonyhub/src/main/java/org/openhab/binding/harmonyhub/internal/HarmonyHubBindingType.java
Java
epl-1.0
2,504
/** * Copyright (c) 2010-2016, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.openenergymonitor.protocol; import java.util.HashMap; import java.util.Map.Entry; import org.openhab.binding.openenergymonitor.protocol.OpenEnergyMonitorParserRule.DataType; /** * Class for parse data packets from Open Energy Monitor devices. * * @author Pauli Anttila * @since 1.4.0 */ public class OpenEnergyMonitorDataParser { private HashMap<String, OpenEnergyMonitorParserRule> parsingRules = null; public OpenEnergyMonitorDataParser(HashMap<String, OpenEnergyMonitorParserRule> parsingRules) { this.parsingRules = parsingRules; } /** * Method to parse Open Energy Monitoring device datagram to variables by defined parsing rules. * * @param data datagram from Open Energy Monitoring device * * @return Hash table which contains all parsed variables. */ public HashMap<String, Number> parseData(byte[] data) { HashMap<String, Number> variables = new HashMap<String, Number>(); byte address = data[0]; for (Entry<String, OpenEnergyMonitorParserRule> entry : parsingRules.entrySet()) { OpenEnergyMonitorParserRule rule = entry.getValue(); if (rule.getAddress() == address) { Number obj = convertTo(rule.getDataType(), getBytes(rule.getParseBytes(), data)); variables.put(entry.getKey(), obj); } } return variables; } private byte[] getBytes(int[] byteIndexes, byte[] data) { byte[] bytes = new byte[byteIndexes.length]; for (int i = 0; i < byteIndexes.length; i++) { bytes[i] = data[byteIndexes[i]]; } return bytes; } private Number convertTo(DataType dataType, byte[] data) { Number val = null; switch (dataType) { case DOUBLE: val = toDouble(data); break; case FLOAT: val = toFloat(data); break; case S16: val = toShort(data); break; case S32: val = toInt(data); break; case S64: val = toLong(data); break; case S8: val = toByte(data); break; case U16: val = (int) (toShort(data) & 0xFFFF); break; case U32: val = (long) (toInt(data) & 0xFFFFFFFFL); break; case U8: val = (short) (toByte(data) & 0xFF); break; } return val; } public static byte toByte(byte[] data) { return (data == null || data.length == 0) ? 0x0 : data[0]; } public static short toShort(byte[] data) { // if (data == null || data.length != 2) return 0x0; return (short) ((0xff & data[0]) << 8 | (0xff & data[1]) << 0); } public static char toChar(byte[] data) { // if (data == null || data.length != 2) return 0x0; return (char) ((0xff & data[0]) << 8 | (0xff & data[1]) << 0); } public static int toInt(byte[] data) { // if (data == null || data.length != 4) return 0x0; return (0xff & data[0]) << 24 | (0xff & data[1]) << 16 | (0xff & data[2]) << 8 | (0xff & data[3]) << 0; } public static long toLong(byte[] data) { // if (data == null || data.length != 8) return 0x0; return (long) (0xff & data[0]) << 56 | (long) (0xff & data[1]) << 48 | (long) (0xff & data[2]) << 40 | (long) (0xff & data[3]) << 32 | (long) (0xff & data[4]) << 24 | (long) (0xff & data[5]) << 16 | (long) (0xff & data[6]) << 8 | (long) (0xff & data[7]) << 0; } public static float toFloat(byte[] data) { // if (data == null || data.length != 4) return 0x0; return Float.intBitsToFloat(toInt(data)); } public static double toDouble(byte[] data) { // if (data == null || data.length != 8) return 0x0; return Double.longBitsToDouble(toLong(data)); } public static boolean toBoolean(byte[] data) { return data[0] != 0x00; } }
coolweb/openhab
bundles/binding/org.openhab.binding.openenergymonitor/src/main/java/org/openhab/binding/openenergymonitor/protocol/OpenEnergyMonitorDataParser.java
Java
epl-1.0
4,513
/** * Copyright (c) 2010-2016, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.homematic.internal.config.binding; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.openhab.binding.homematic.internal.config.BindingAction; import org.openhab.binding.homematic.internal.converter.state.Converter; /** * Class with the variable bindingConfig parsed from an item file. * * @author Gerhard Riegler * @since 1.5.0 */ public class VariableConfig extends ValueBindingConfig { private String name; public VariableConfig(String name) { this.name = name; } /** * Creates a variable config from the binding parser. */ public VariableConfig(String name, Converter<?> converter, BindingAction action, boolean forceUpdate, double delay) { this.name = name; this.converter = converter; this.action = action; this.forceUpdate = forceUpdate; this.delay = delay; } /** * Returns the name of the variable. */ public String getName() { return name; } /** * {@inheritDoc} */ @Override public int hashCode() { return new HashCodeBuilder().append(name).append(this.getClass().getName()).toHashCode(); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof VariableConfig)) { return false; } VariableConfig comp = (VariableConfig) obj; return new EqualsBuilder().append(name, comp.getName()) .append(this.getClass().getName(), comp.getClass().getName()).isEquals(); } /** * {@inheritDoc} */ @Override public String toString() { ToStringBuilder tsb = new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE); tsb.append("name", name); if (converter != null) { tsb.append("converter", converter); } if (action != null) { tsb.append("action", action); } if (forceUpdate) { tsb.append("forceUpdate", forceUpdate); } if (delay > 0.0) { tsb.append("delay", delay); } return tsb.toString(); } }
taupinfada/openhab
bundles/binding/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/config/binding/VariableConfig.java
Java
epl-1.0
2,676
/* // This software is subject to the terms of the Eclipse Public License v1.0 // Agreement, available at the following URL: // http://www.eclipse.org/legal/epl-v10.html. // You must accept the terms of that agreement to use this software. // // Copyright (c) 2002-2014 Pentaho Corporation.. All rights reserved. */ package mondrian.spi.impl; import java.sql.*; import java.util.Calendar; import java.util.List; /** * Implementation of {@link mondrian.spi.Dialect} for the Microsoft Access * database (also called the JET Engine). * * @author jhyde * @since Nov 23, 2008 */ public class AccessDialect extends JdbcDialectImpl { public static final JdbcDialectFactory FACTORY = new JdbcDialectFactory( AccessDialect.class, DatabaseProduct.ACCESS); /** * Creates an AccessDialect. * * @param connection Connection */ public AccessDialect(Connection connection) throws SQLException { super(connection); } public String toUpper(String expr) { return "UCASE(" + expr + ")"; } public String caseWhenElse(String cond, String thenExpr, String elseExpr) { return "IIF(" + cond + "," + thenExpr + "," + elseExpr + ")"; } protected void quoteDateLiteral( StringBuilder buf, String value, Date date) { // Access accepts #01/23/2008# but not SQL:2003 format. buf.append("#"); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); buf.append(calendar.get(Calendar.MONTH) + 1); buf.append("/"); buf.append(calendar.get(Calendar.DAY_OF_MONTH)); buf.append("/"); buf.append(calendar.get(Calendar.YEAR)); buf.append("#"); } @Override protected String generateOrderByNulls( String expr, boolean ascending, boolean collateNullsLast) { if (collateNullsLast) { if (ascending) { return "Iif(" + expr + " IS NULL, 1, 0), " + expr + " ASC"; } else { return "Iif(" + expr + " IS NULL, 1, 0), " + expr + " DESC"; } } else { if (ascending) { return "Iif(" + expr + " IS NULL, 0, 1), " + expr + " ASC"; } else { return "Iif(" + expr + " IS NULL, 0, 1), " + expr + " DESC"; } } } public boolean requiresUnionOrderByExprToBeInSelectClause() { return true; } public boolean allowsCountDistinct() { return false; } public String generateInline( List<String> columnNames, List<String> columnTypes, List<String[]> valueList) { // Fall back to using the FoodMart 'days' table, because // Access SQL has no way to generate values not from a table. return generateInlineGeneric( columnNames, columnTypes, valueList, " from `days` where `day` = 1", false); } } // End AccessDialect.java
lgrill-pentaho/mondrian
src/main/mondrian/spi/impl/AccessDialect.java
Java
epl-1.0
3,020
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.0.4-master-a6f3676 */ !function(e,r,t){"use strict";function a(e,a,i){function n(e){return e.attr("aria-valuemin",0),e.attr("aria-valuemax",100),e.attr("role","progressbar"),s}function s(n,s,v){function f(){v.$observe("value",function(e){var r=d(e);s.attr("aria-valuenow",r),C()==c&&g(r)}),v.$observe("mdMode",function(e){switch(e){case c:case u:x.removeClass("ng-hide"),b&&x.removeClass(b),x.addClass(b="md-mode-"+e);break;default:b&&x.removeClass(b),x.addClass("ng-hide"),b=t}})}function p(){M.css({width:100*w()+"px",height:100*w()+"px"}),M.children().eq(0).css($({transform:a.supplant("translate(-50%, -50%) scale( {0} )",[w()])}))}function h(){if(r.isUndefined(v.mdMode)){var e=r.isDefined(v.value),t=e?c:u,n="Auto-adding the missing md-mode='{0}' to the ProgressCircular element";i.debug(a.supplant(n,[t])),s.attr("md-mode",t),v.mdMode=t}}function g(e){if(C()){q=q||r.element(s[0].querySelector(".md-left > .md-half-circle")),y=y||r.element(s[0].querySelector(".md-right > .md-half-circle")),D=D||r.element(s[0].querySelector(".md-gap"));var t=o({borderBottomColor:50>=e?"transparent !important":"",transition:50>=e?"":"borderBottomColor 0.1s linear"}),i=o({transition:50>=e?"transform 0.1s linear":"",transform:a.supplant("rotate({0}deg)",[50>=e?135:(e-50)/50*180+135])}),n=o({transition:e>=50?"transform 0.1s linear":"",transform:a.supplant("rotate({0}deg)",[e>=50?45:e/50*180-135])});q.css($(i)),y.css($(n)),D.css($(t))}}function w(){if(!v.mdDiameter)return l;var e=/([0-9]*)%/.exec(v.mdDiameter),r=Math.max(0,e&&e[1]/100||parseFloat(v.mdDiameter));return r>1?r/m:r}function C(){var e=(v.mdMode||"").trim();if(e)switch(e){case c:case u:break;default:e=t}return e}e(s);var b,M=s,x=r.element(s.children()[0]),$=a.dom.animator.toCss;s.attr("md-mode",C()),p(),h(),f();var q,y,D}function d(e){return Math.max(0,Math.min(e||0,100))}function o(e){for(var r in e)e.hasOwnProperty(r)&&""==e[r]&&delete e[r];return e}var m=100,l=.5,c="determinate",u="indeterminate";return{restrict:"E",scope:!0,template:'<div class="md-scale-wrapper"><div class="md-spinner-wrapper"><div class="md-inner"><div class="md-gap"></div><div class="md-left"><div class="md-half-circle"></div></div><div class="md-right"><div class="md-half-circle"></div></div></div></div></div>',compile:n}}r.module("material.components.progressCircular",["material.core"]).directive("mdProgressCircular",a),a.$inject=["$mdTheming","$mdUtil","$log"]}(window,window.angular);
SweProject2016/Frontend
bower_components/angular-material/modules/js/progressCircular/progressCircular.min.js
JavaScript
epl-1.0
2,528
package org.junit.experimental.theories.internal; import static java.util.Collections.emptyList; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.junit.experimental.theories.ParameterSignature; import org.junit.experimental.theories.ParameterSupplier; import org.junit.experimental.theories.ParametersSuppliedBy; import org.junit.experimental.theories.PotentialAssignment; import org.junit.experimental.theories.PotentialAssignment.CouldNotGenerateValueException; import org.junit.runners.model.TestClass; /** * A potentially incomplete list of value assignments for a method's formal * parameters */ public class Assignments { private final List<PotentialAssignment> assigned; private final List<ParameterSignature> unassigned; private final TestClass clazz; private Assignments(List<PotentialAssignment> assigned, List<ParameterSignature> unassigned, TestClass clazz) { this.unassigned = unassigned; this.assigned = assigned; this.clazz = clazz; } /** * Returns a new assignment list for {@code testMethod}, with no params * assigned. */ public static Assignments allUnassigned(Method testMethod, TestClass testClass) { List<ParameterSignature> signatures; signatures = ParameterSignature.signatures(testClass .getOnlyConstructor()); signatures.addAll(ParameterSignature.signatures(testMethod)); return new Assignments(new ArrayList<PotentialAssignment>(), signatures, testClass); } public boolean isComplete() { return unassigned.isEmpty(); } public ParameterSignature nextUnassigned() { return unassigned.get(0); } public Assignments assignNext(PotentialAssignment source) { List<PotentialAssignment> potentialAssignments = new ArrayList<PotentialAssignment>(assigned); potentialAssignments.add(source); return new Assignments(potentialAssignments, unassigned.subList(1, unassigned.size()), clazz); } public Object[] getActualValues(int start, int stop) throws CouldNotGenerateValueException { Object[] values = new Object[stop - start]; for (int i = start; i < stop; i++) { values[i - start] = assigned.get(i).getValue(); } return values; } public List<PotentialAssignment> potentialsForNextUnassigned() throws Throwable { ParameterSignature unassigned = nextUnassigned(); List<PotentialAssignment> assignments = getSupplier(unassigned).getValueSources(unassigned); if (assignments.isEmpty()) { assignments = generateAssignmentsFromTypeAlone(unassigned); } return assignments; } private List<PotentialAssignment> generateAssignmentsFromTypeAlone(ParameterSignature unassigned) { Class<?> paramType = unassigned.getType(); if (paramType.isEnum()) { return new EnumSupplier(paramType).getValueSources(unassigned); } else if (paramType.equals(Boolean.class) || paramType.equals(boolean.class)) { return new BooleanSupplier().getValueSources(unassigned); } else { return emptyList(); } } private ParameterSupplier getSupplier(ParameterSignature unassigned) throws Exception { ParametersSuppliedBy annotation = unassigned .findDeepAnnotation(ParametersSuppliedBy.class); if (annotation != null) { return buildParameterSupplierFromClass(annotation.value()); } else { return new AllMembersSupplier(clazz); } } private ParameterSupplier buildParameterSupplierFromClass( Class<? extends ParameterSupplier> cls) throws Exception { Constructor<?>[] supplierConstructors = cls.getConstructors(); for (Constructor<?> constructor : supplierConstructors) { Class<?>[] parameterTypes = constructor.getParameterTypes(); if (parameterTypes.length == 1 && parameterTypes[0].equals(TestClass.class)) { return (ParameterSupplier) constructor.newInstance(clazz); } } return cls.newInstance(); } public Object[] getConstructorArguments() throws CouldNotGenerateValueException { return getActualValues(0, getConstructorParameterCount()); } public Object[] getMethodArguments() throws CouldNotGenerateValueException { return getActualValues(getConstructorParameterCount(), assigned.size()); } public Object[] getAllArguments() throws CouldNotGenerateValueException { return getActualValues(0, assigned.size()); } private int getConstructorParameterCount() { List<ParameterSignature> signatures = ParameterSignature .signatures(clazz.getOnlyConstructor()); int constructorParameterCount = signatures.size(); return constructorParameterCount; } public Object[] getArgumentStrings(boolean nullsOk) throws CouldNotGenerateValueException { Object[] values = new Object[assigned.size()]; for (int i = 0; i < values.length; i++) { values[i] = assigned.get(i).getDescription(); } return values; } }
remus32/junit
src/main/java/org/junit/experimental/theories/internal/Assignments.java
Java
epl-1.0
5,467
/** * Copyright (c) 2010-2015, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.zwave.internal.protocol.commandclass; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.openhab.binding.zwave.internal.config.ZWaveDbCommandClass; import org.openhab.binding.zwave.internal.protocol.SerialMessage; import org.openhab.binding.zwave.internal.protocol.SerialMessage.SerialMessageClass; import org.openhab.binding.zwave.internal.protocol.SerialMessage.SerialMessagePriority; import org.openhab.binding.zwave.internal.protocol.SerialMessage.SerialMessageType; import org.openhab.binding.zwave.internal.protocol.ZWaveController; import org.openhab.binding.zwave.internal.protocol.ZWaveEndpoint; import org.openhab.binding.zwave.internal.protocol.ZWaveNode; import org.openhab.binding.zwave.internal.protocol.event.ZWaveCommandClassValueEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamOmitField; /** * Handles the Thermostat FanState command class. * @author Dan Cunningham * @since 1.6.0 */ @XStreamAlias("thermostatFanStateCommandClass") public class ZWaveThermostatFanStateCommandClass extends ZWaveCommandClass implements ZWaveGetCommands, ZWaveCommandClassDynamicState { @XStreamOmitField private static final Logger logger = LoggerFactory.getLogger(ZWaveThermostatFanStateCommandClass.class); private static final byte THERMOSTAT_FAN_STATE_GET = 0x2; private static final byte THERMOSTAT_FAN_STATE_REPORT = 0x3; private final Set<FanStateType> fanStateTypes = new HashSet<FanStateType>(); @XStreamOmitField private boolean dynamicDone = false; private boolean isGetSupported = true; /** * Creates a new instance of the ZWaveThermostatFanStateCommandClass class. * @param node the node this command class belongs to * @param controller the controller to use * @param endpoint the endpoint this Command class belongs to */ public ZWaveThermostatFanStateCommandClass(ZWaveNode node, ZWaveController controller, ZWaveEndpoint endpoint) { super(node, controller, endpoint); } /** * {@inheritDoc} */ @Override public CommandClass getCommandClass() { return CommandClass.THERMOSTAT_FAN_STATE; } /** * {@inheritDoc} */ @Override public int getMaxVersion() { return 2; } /** * {@inheritDoc} */ @Override public void handleApplicationCommandRequest(SerialMessage serialMessage, int offset, int endpoint) { logger.debug("NODE {}: Received Thermostat Fan State Request", this.getNode().getNodeId()); int command = serialMessage.getMessagePayloadByte(offset); switch (command) { case THERMOSTAT_FAN_STATE_REPORT: logger.trace("NODE {}: Process Thermostat Fan State Report", this.getNode().getNodeId()); processThermostatFanStateReport(serialMessage, offset, endpoint); break; default: logger.warn("NODE {}: Unsupported Command {} for command class {} ({}).", this.getNode().getNodeId(), command, this.getCommandClass().getLabel(), this.getCommandClass().getKey()); } } /** * Processes a THERMOSTAT_FAN_STATE_REPORT message. * @param serialMessage the incoming message to process. * @param offset the offset position from which to start message processing. * @param endpoint the endpoint or instance number this message is meant for. */ protected void processThermostatFanStateReport(SerialMessage serialMessage, int offset, int endpoint) { int value = serialMessage.getMessagePayloadByte(offset + 1); logger.debug("NODE {}: Thermostat fan state report value = {}", this.getNode().getNodeId(), value); FanStateType fanStateType = FanStateType.getFanStateType(value); if (fanStateType == null) { logger.error("NODE {}: Unknown fan state Type = {}, ignoring report.", this.getNode().getNodeId(), value); return; } // fanState type seems to be supported, add it to the list. if(!fanStateTypes.contains(fanStateType)) fanStateTypes.add(fanStateType); dynamicDone = true; logger.debug("NODE {}: Thermostat fan state Report value = {}", this.getNode().getNodeId(), fanStateType.getLabel()); ZWaveCommandClassValueEvent zEvent = new ZWaveCommandClassValueEvent(this.getNode().getNodeId(), endpoint, this.getCommandClass(), value); this.getController().notifyEventListeners(zEvent); } /** * {@inheritDoc} */ @Override public Collection<SerialMessage> getDynamicValues(boolean refresh) { // TODO (or question for Dan from Chris) - shouldn't this iterate through all fan modes? ArrayList<SerialMessage> result = new ArrayList<SerialMessage>(); if(refresh == true || dynamicDone == false) { result.add(getValueMessage()); } return result; } /** * {@inheritDoc} */ @Override public SerialMessage getValueMessage() { if(isGetSupported == false) { logger.debug("NODE {}: Node doesn't support get requests", this.getNode().getNodeId()); return null; } logger.debug("NODE {}: Creating new message for application command THERMOSTAT_FAN_STATE_GET", this.getNode().getNodeId()); SerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); byte[] payload = { (byte) this.getNode().getNodeId(), 2, (byte) getCommandClass().getKey(), THERMOSTAT_FAN_STATE_GET }; result.setMessagePayload(payload); return result; } @Override public boolean setOptions (ZWaveDbCommandClass options) { if(options.isGetSupported != null) { isGetSupported = options.isGetSupported; } return true; } /** * Z-Wave FanStateType enumeration. The fanState type indicates the type * of fanState that is reported. * @author Dan Cunningham * @since 1.6.0 */ @XStreamAlias("fanStateType") public enum FanStateType { IDLE(0,"Idle"), RUNNING(1,"Running"), RUNNING_HIGH(2,"Running High"), State_3(3,"State 3"), State_4(4,"State 4"), State_5(5,"State 5"), State_6(6,"State 6"), State_7(7,"State 7"), // Undefined states. May be used in the future. State_8(8,"State 8"), State_9(9,"State 9"), State_10(10,"State 10"), State_11(11,"State 11"), State_12(12,"State 12"), State_13(12,"State 13"), State_14(14,"State 14"), State_15(15,"State 15"); /** * A mapping between the integer code and its corresponding fanState type * to facilitate lookup by code. */ private static Map<Integer, FanStateType> codeToFanStateTypeMapping; private int key; private String label; private FanStateType(int key, String label) { this.key = key; this.label = label; } private static void initMapping() { codeToFanStateTypeMapping = new HashMap<Integer, FanStateType>(); for (FanStateType s : values()) { codeToFanStateTypeMapping.put(s.key, s); } } /** * Lookup function based on the fanState type code. * Returns null if the code does not exist. * @param i the code to lookup * @return enumeration value of the fanState type. */ public static FanStateType getFanStateType(int i) { if (codeToFanStateTypeMapping == null) { initMapping(); } return codeToFanStateTypeMapping.get(i); } /** * @return the key */ public int getKey() { return key; } /** * @return the label */ public String getLabel() { return label; } } }
elifesy/openhab
bundles/binding/org.openhab.binding.zwave/src/main/java/org/openhab/binding/zwave/internal/protocol/commandclass/ZWaveThermostatFanStateCommandClass.java
Java
epl-1.0
7,823
package org.junit.internal.runners.statements; import org.junit.internal.AssumptionViolatedException; import org.junit.runners.model.Statement; public class ExpectException extends Statement { private final Statement next; private final Class<? extends Throwable> expected; public ExpectException(Statement next, Class<? extends Throwable> expected) { this.next = next; this.expected = expected; } @Override public void evaluate() throws Exception { boolean complete = false; try { next.evaluate(); complete = true; } catch (AssumptionViolatedException e) { throw e; } catch (Throwable e) { if (!expected.isAssignableFrom(e.getClass())) { String message = "Unexpected exception, expected<" + expected.getName() + "> but was<" + e.getClass().getName() + ">"; throw new Exception(message, e); } } if (complete) { throw new AssertionError("Expected exception: " + expected.getName()); } } }
AxelMonroyX/junit4
src/main/java/org/junit/internal/runners/statements/ExpectException.java
Java
epl-1.0
1,163
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Include the {@link shared.make_timestamp.php} plugin */ require_once $smarty->_get_plugin_filepath('shared', 'make_timestamp'); /** * Smarty date_format modifier plugin * * Type: modifier<br> * Name: date_format<br> * Purpose: format datestamps via strftime<br> * Input:<br> * - string: input date string * - format: strftime format for output * - default_date: default date if $string is empty * @link http://smarty.php.net/manual/en/language.modifier.date.format.php * date_format (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @param string * @param string * @return string|void * @uses smarty_make_timestamp() */ function smarty_modifier_date_format($string, $format = '%b %e, %Y', $default_date = '') { if ($string != '') { $timestamp = smarty_make_timestamp($string); } elseif ($default_date != '') { $timestamp = smarty_make_timestamp($default_date); } else { return; } if (DIRECTORY_SEPARATOR == '\\') { $_win_from = array('%D', '%h', '%n', '%r', '%R', '%t', '%T'); $_win_to = array('%m/%d/%y', '%b', "\n", '%I:%M:%S %p', '%H:%M', "\t", '%H:%M:%S'); if (strpos($format, '%e') !== false) { $_win_from[] = '%e'; $_win_to[] = sprintf('%\' 2d', date('j', $timestamp)); } if (strpos($format, '%l') !== false) { $_win_from[] = '%l'; $_win_to[] = sprintf('%\' 2d', date('h', $timestamp)); } $format = str_replace($_win_from, $_win_to, $format); } return strftime($format, $timestamp); } /* vim: set expandtab: */ ?>
tangboss888/yifu
crm/include/Smarty/plugins/modifier.date_format.php
PHP
epl-1.0
1,782
/** * Copyright (c) 2010-2015, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.weather.internal.provider; import org.openhab.binding.weather.internal.model.ProviderName; import org.openhab.binding.weather.internal.parser.JsonWeatherParser; /** * OpenWeatherMap weather provider. * * @author Gerhard Riegler * @since 1.6.0 */ public class OpenWeatherMapProvider extends AbstractWeatherProvider { private static final String URL = "http://api.openweathermap.org/data/2.5/weather?lat=[LATITUDE]&lon=[LONGITUDE]&lang=[LANGUAGE]&mode=json&units=metric&APPID=[API_KEY]"; private static final String FORECAST = "http://api.openweathermap.org/data/2.5/forecast/daily?lat=[LATITUDE]&lon=[LONGITUDE]&lang=[LANGUAGE]&cnt=5&mode=json&units=metric&APPID=[API_KEY]"; public OpenWeatherMapProvider() { super(new JsonWeatherParser()); } /** * {@inheritDoc} */ @Override public ProviderName getProviderName() { return ProviderName.OPENWEATHERMAP; } /** * {@inheritDoc} */ @Override protected String getWeatherUrl() { return URL; } /** * {@inheritDoc} */ @Override protected String getForecastUrl() { return FORECAST; } }
saydulk/openhab
bundles/binding/org.openhab.binding.weather/src/main/java/org/openhab/binding/weather/internal/provider/OpenWeatherMapProvider.java
Java
epl-1.0
1,410
/** * Copyright (c) 2010-2015, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.pioneeravr.internal; import java.util.Dictionary; import java.util.Enumeration; import java.util.EventObject; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.openhab.binding.pioneeravr.PioneerAvrBindingProvider; import org.openhab.binding.pioneeravr.internal.ipcontrolprotocol.IpControl; import org.openhab.binding.pioneeravr.internal.ipcontrolprotocol.IpControlCommand; import org.openhab.binding.pioneeravr.internal.ipcontrolprotocol.IpControlCommandRef; import org.openhab.binding.pioneeravr.internal.ipcontrolprotocol.IpControlDisplayInformation; import org.openhab.core.binding.AbstractBinding; import org.openhab.core.binding.BindingChangeListener; import org.openhab.core.binding.BindingProvider; import org.openhab.core.items.Item; import org.openhab.core.library.items.DimmerItem; import org.openhab.core.library.items.NumberItem; import org.openhab.core.library.items.RollershutterItem; import org.openhab.core.library.items.StringItem; import org.openhab.core.library.items.SwitchItem; import org.openhab.core.library.types.DecimalType; import org.openhab.core.library.types.OnOffType; import org.openhab.core.library.types.PercentType; import org.openhab.core.library.types.StringType; import org.openhab.core.types.Command; import org.openhab.core.types.State; import org.openhab.core.types.UnDefType; import org.osgi.service.cm.ConfigurationException; import org.osgi.service.cm.ManagedService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Binding listening to openHAB event bus and send commands to pioneerav devices when certain * commands are received. * * @author Rainer Ostendorf * @author based on the Onkyo binding by Pauli Anttila and others * @since 1.4.0 */ public class PioneerAvrBinding extends AbstractBinding<PioneerAvrBindingProvider> implements ManagedService, BindingChangeListener, PioneerAvrEventListener { private static final Logger logger = LoggerFactory.getLogger(PioneerAvrBinding.class); protected static final String ADVANCED_COMMAND_KEY = "#"; protected static final String WILDCARD_COMMAND_KEY = "*"; /** RegEx to validate a config <code>'^(.*?)\\.(host|port|checkconn)$'</code> */ private static final Pattern EXTRACT_CONFIG_PATTERN = Pattern.compile("^(.*?)\\.(host|port|checkconn)$"); /** pioneerav receiver default tcp port */ private final static int DEFAULT_PORT = IpControl.DEFAULT_IPCONTROL_PORT; /** Map table to store all available receivers configured by the user */ protected Map<String, DeviceConfig> deviceConfigCache = null; public PioneerAvrBinding() { } public void activate() { logger.debug("Activate"); } public void deactivate() { logger.debug("Deactivate"); closeAllConnections(); } /** * {@inheritDoc} */ @Override public void bindingChanged(BindingProvider provider, String itemName) { logger.debug("bindingChanged {}", itemName); initializeItem(itemName); } /** * @{inheritDoc */ @Override protected void internalReceiveCommand(String itemName, Command command) { if (itemName != null) { PioneerAvrBindingProvider provider = findFirstMatchingBindingProvider(itemName, command.toString()); if (provider == null) { logger.warn("Doesn't find matching binding provider [itemName={}, command={}]", itemName, command); return; } logger.debug( "Received command (item='{}', state='{}', class='{}')", new Object[] { itemName, command.toString(), command.getClass().toString() }); String tmp = provider.getDeviceCommand(itemName, command.toString()); if (tmp == null) { tmp = provider.getDeviceCommand(itemName, WILDCARD_COMMAND_KEY); } String[] commandParts = tmp.split(":"); String deviceId = commandParts[0]; String deviceCmd = commandParts[1]; DeviceConfig device = deviceConfigCache.get(deviceId); PioneerAvrConnection remoteController = device.getConnection(); if (device != null && remoteController != null) { if (deviceCmd.startsWith(ADVANCED_COMMAND_KEY)) { // advanced command deviceCmd = deviceCmd.replace(ADVANCED_COMMAND_KEY, ""); if (deviceCmd.contains("%")) { deviceCmd = convertOpenHabCommandToDeviceCommand( command, deviceCmd); } } else { // normal command IpControlCommand cmd = IpControlCommand.valueOf(deviceCmd); deviceCmd = cmd.getCommand(); if (deviceCmd.contains("%")) { deviceCmd = convertOpenHabCommandToDeviceCommand( command, deviceCmd); } } if (deviceCmd != null) { remoteController.send(deviceCmd); } else { logger.warn("Cannot convert value '{}' to IpControl format", command); } } else { logger.warn("Cannot find connection details for device id '{}'", deviceId); } } } /** * Convert OpenHAB commmand to pioneer avr receiver command. * * @param command the openhab command to send * @param cmdTemplate the format string to used for converting the command * * @return the receiver command string */ private String convertOpenHabCommandToDeviceCommand( Command command, String cmdTemplate ) { String deviceCmd = null; if (command instanceof OnOffType) { deviceCmd = String.format(cmdTemplate, command == OnOffType.ON ? 1: 0); } else if (command instanceof StringType) { deviceCmd = String.format(cmdTemplate, command); } else if (command instanceof PercentType) { // when settings the volume as percent, we need to map it if( cmdTemplate.equals( IpControlCommand.VOLUME_SET.getCommand() ) ) { Integer percentValue = convertPercentToVolume(((DecimalType) command).intValue()); deviceCmd = String.format(cmdTemplate, percentValue ); } else { deviceCmd = String.format(cmdTemplate, ((DecimalType) command).intValue()); } } else if (command instanceof DecimalType) { deviceCmd = String.format(cmdTemplate, ((DecimalType) command).intValue()); } return deviceCmd; } /** * Find the first matching {@link PioneerAvrBindingProvider} according to * <code>itemName</code>. * * @param itemName * * @return the matching binding provider or <code>null</code> if no binding * provider could be found */ private PioneerAvrBindingProvider findFirstMatchingBindingProvider(String itemName, String command) { PioneerAvrBindingProvider firstMatchingProvider = null; for (PioneerAvrBindingProvider provider : this.providers) { String tmp = provider.getDeviceCommand(itemName, command.toString()); if (tmp != null) { firstMatchingProvider = provider; break; } } if (firstMatchingProvider == null) { for (PioneerAvrBindingProvider provider : this.providers) { String tmp = provider.getDeviceCommand(itemName, WILDCARD_COMMAND_KEY); if (tmp != null) { firstMatchingProvider = provider; break; } } } return firstMatchingProvider; } /** * @{inheritDoc */ @Override public void updated(Dictionary<String, ?> config) throws ConfigurationException { logger.debug("Configuration updated, config {}", config != null ? true : false); if (config != null) { Enumeration<String> keys = config.keys(); if ( deviceConfigCache == null ) { deviceConfigCache = new HashMap<String, DeviceConfig>(); } while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); // the config-key enumeration contains additional keys that we // don't want to process here ... if ("service.pid".equals(key)) { continue; } Matcher matcher = EXTRACT_CONFIG_PATTERN.matcher(key); if (!matcher.matches()) { logger.debug("given config key '" + key + "' does not follow the expected pattern '<id>.<host|port|checkconn>'"); continue; } matcher.reset(); matcher.find(); String deviceId = matcher.group(1); DeviceConfig deviceConfig = deviceConfigCache.get(deviceId); if (deviceConfig == null) { deviceConfig = new DeviceConfig(deviceId); deviceConfigCache.put(deviceId, deviceConfig); } String configKey = matcher.group(2); String value = (String) config.get(key); if ("host".equals(configKey)) { deviceConfig.host = value; } else if ("port".equals(configKey)) { deviceConfig.port = Integer.valueOf(value); } else if ("checkconn".equals(configKey)) { if( value.equals("0") ) deviceConfig.connectionCheckActive = false; else deviceConfig.connectionCheckActive = true; } else { throw new ConfigurationException(configKey, "the given configKey '" + configKey + "' is unknown"); } } // open connection to all receivers for (String device : deviceConfigCache.keySet()) { PioneerAvrConnection connection = deviceConfigCache.get(device).getConnection(); if (connection != null) { connection.openConnection(); connection.addEventListener(this); } } for (PioneerAvrBindingProvider provider : this.providers) { for (String itemName : provider.getItemNames()) { initializeItem(itemName); } } } } private void closeAllConnections() { if (deviceConfigCache != null) { for (String device : deviceConfigCache.keySet()) { PioneerAvrConnection connection = deviceConfigCache.get(device).getConnection(); if (connection != null) { connection.closeConnection(); connection.removeEventListener(this); } } deviceConfigCache = null; } } /** * Find receiver from device caache by ip address. * * @param ip * @return */ private DeviceConfig findDevice(String ip) { for (String device : deviceConfigCache.keySet()) { DeviceConfig deviceConfig = deviceConfigCache.get(device); if (deviceConfig != null) { if (deviceConfig.getHost().equals(ip)) { return deviceConfig; } } } return null; } @Override public void statusUpdateReceived(EventObject event, String ip, String data) { // find correct device from device cache DeviceConfig deviceConfig = findDevice(ip); if (deviceConfig != null) { logger.debug("Received status update '{}' from device {}", data, deviceConfig.host); for (PioneerAvrBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { // Update all items which refer to command HashMap<String, String> values = provider.getDeviceCommands(itemName); for (String cmd : values.keySet()) { String[] commandParts = values.get(cmd).split(":"); String deviceCmd = commandParts[1]; boolean match = false; if( deviceCmd.startsWith(ADVANCED_COMMAND_KEY) ) { // we currently have no info about the expected response string // of a user configured "advanced" command, so skip this item continue; } try { String commandResponse = IpControlCommand.valueOf(deviceCmd).getResponse(); // when no respone is expected, the response string is empty if( !commandResponse.isEmpty() ) { // compare response from network with response in enum if (data.startsWith(commandResponse)) { match = true; } } } catch (Exception e) { logger.error("Unregonized command '" + deviceCmd + "'", e); } if (match) { Class<? extends Item> itemType = provider.getItemType(itemName); State v = convertDeviceValueToOpenHabState(itemType, data, IpControlCommand.valueOf(deviceCmd) ); eventPublisher.postUpdate(itemName, v); break; } } } } } } /** * Convert receiver value to OpenHAB state. * * @param itemType * @param data * * @return */ private State convertDeviceValueToOpenHabState(Class<? extends Item> itemType, String data, IpControlCommand cmdType) { State state = UnDefType.UNDEF; try { int index; // cut off the leading response identifier to get the payload string String payloadSubstring = data.substring( cmdType.getResponse().length() ); // if the response consisted just of the response-identifier and had // no further value attached handle it as boolean of value 1 // this is used e.g. when switch items are used for selecting the source. // the selected source will then be set to "ON" if( payloadSubstring.length() == 0) payloadSubstring = "1"; // special case for display info query: convert to human readable string if( cmdType.getCommandRef() == IpControlCommandRef.DISPLAY_INFO_QUERY ) { IpControlDisplayInformation displayInfo = new IpControlDisplayInformation( payloadSubstring ); payloadSubstring = displayInfo.getInfoText(); logger.debug("DisplayInfo: converted value '{}' to string '{}'", data, payloadSubstring ); } if (itemType == SwitchItem.class) { index = Integer.parseInt(payloadSubstring); state = (index == 0) ? OnOffType.ON : OnOffType.OFF; // according to Spec: 0=ON, 1=OFF! } else if (itemType == DimmerItem.class) { if( cmdType.getCommandRef().getCommand() == IpControlCommandRef.VOLUME_QUERY.getCommand() || cmdType.getCommandRef().getCommand() == IpControlCommandRef.VOLUME_SET.getCommand()) { index = convertVolumeToPercent( Integer.parseInt(payloadSubstring) ); } else { index = Integer.parseInt(payloadSubstring); } state = new PercentType(index); } else if (itemType == NumberItem.class) { index = Integer.parseInt(payloadSubstring); state = new DecimalType(index); } else if (itemType == RollershutterItem.class) { index = Integer.parseInt(payloadSubstring); state = new PercentType(index); } else if (itemType == StringItem.class) { state = new StringType(payloadSubstring); } } catch (Exception e) { logger.debug("Cannot convert value '{}' to data type {}", data, itemType); } return state; } /** * map the receiver volume values to percent values * * receiver volume 0 is -80db and 0% * receiver volume 185 is +12dB and 100% (at least for zone 1) * * @param volume the receiver volume value * */ private Integer convertVolumeToPercent( Integer volume ) { Integer percent = Math.round( (volume*100)/185 ); logger.debug("converted volume '" + volume.toString() + "' to '" + percent.toString() + "%'" ); return percent; } /** * map percent values to receiver volumes * * receiver volume 0 is -80db and 0% * receiver volume 185 is +12dB and 100% (at least for zone 1) * * @param volume the receiver volume value * */ private Integer convertPercentToVolume( Integer percent ) { Integer volume = Math.round( (percent*185)/100 ); logger.debug("converted " + percent.toString() + "% to volume " + volume.toString() ); return volume; } /** * Initialize item value. Method send query to receiver if init query is configured to binding item configuration * * @param itemType * */ private void initializeItem(String itemName) { for (PioneerAvrBindingProvider provider : providers) { String initCmd = provider.getItemInitCommand(itemName); if (initCmd != null) { logger.debug("Initialize item {}", itemName); String[] commandParts = initCmd.split(":"); String deviceId = commandParts[0]; String deviceCmd = commandParts[1]; DeviceConfig device = deviceConfigCache.get(deviceId); PioneerAvrConnection remoteController = device.getConnection(); if (device != null && remoteController != null) { if (deviceCmd.startsWith(ADVANCED_COMMAND_KEY)) { deviceCmd = deviceCmd.replace(ADVANCED_COMMAND_KEY, ""); } else { IpControlCommand cmd = IpControlCommand.valueOf(deviceCmd); deviceCmd = cmd.getCommand(); } remoteController.send(deviceCmd); } else { logger.warn( "Cannot find connection details for device id '{}'", deviceId); } } } } /** * Internal data structure which carries the connection details of one * device (there could be several) */ static class DeviceConfig { String host; int port = DEFAULT_PORT; PioneerAvrConnection connection = null; String deviceId; Boolean connectionCheckActive; public DeviceConfig(String deviceId) { this.deviceId = deviceId; connectionCheckActive = true; // by default, the conn check is active } public String getHost(){ return host; } public int getPort(){ return port; } @Override public String toString() { return "Device [id=" + deviceId + ", host=" + host + ", port=" + port + "]"; } PioneerAvrConnection getConnection() { if (connection == null) { connection = new PioneerAvrConnection(host, port, connectionCheckActive); } return connection; } } }
magcode/openhab
bundles/binding/org.openhab.binding.pioneeravr/src/main/java/org/openhab/binding/pioneeravr/internal/PioneerAvrBinding.java
Java
epl-1.0
17,772
/* * Copyright (c) OSGi Alliance (2004, 2008). All Rights Reserved. * * 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. */ package info.dmtree.notification; import info.dmtree.DmtException; import info.dmtree.DmtSession; /** * NotificationService enables sending aynchronous notifications to a management * server. The implementation of <code>NotificationService</code> should * register itself in the OSGi service registry as a service. * * @version $Revision: 5673 $ */ public interface NotificationService { /** * Sends a notification to a named principal. It is the responsibility of * the <code>NotificationService</code> to route the notification to the * given principal using the registered * {@link info.dmtree.notification.spi.RemoteAlertSender} services. * <p> * In remotely initiated sessions the principal name identifies the remote * server that created the session, this can be obtained using the session's * {@link DmtSession#getPrincipal getPrincipal} call. * <p> * The principal name may be omitted if the client does not know the * principal name. Even in this case the routing might be possible if the * Notification Service finds an appropriate default destination (for * example if it is only connected to one protocol adapter, which is only * connected to one management server). * <p> * Since sending the notification and receiving acknowledgment for it is * potentially a very time-consuming operation, notifications are sent * asynchronously. This method should attempt to ensure that the * notification can be sent successfully, and should throw an exception if * it detects any problems. If the method returns without error, the * notification is accepted for sending and the implementation must make a * best-effort attempt to deliver it. * <p> * In case the notification is an asynchronous response to a previous * {@link DmtSession#execute(String, String, String) execute} command, a * correlation identifier can be specified to provide the association * between the execute and the notification. * <p> * In order to send a notification using this method, the caller must have * an <code>AlertPermission</code> with a target string matching the * specified principal name. If the <code>principal</code> parameter is * <code>null</code> (the principal name is not known), the target of the * <code>AlertPermission</code> must be &quot;*&quot;. * <p> * When this method is called with all its parameters <code>null</code> or 0 * (except <code>principal</code>), it should send a protocol * specific default notification to initiate a management session. For * example, in case of OMA DM this is alert 1201 "Client Initiated Session". * The <code>principal</code> parameter can be used to determine the * recipient of the session initiation request. * * @param principal the principal name which is the recipient of this * notification, can be <code>null</code> * @param code the alert code, can be 0 if not needed * @param correlator optional field that contains the correlation identifier * of an associated exec command, can be <code>null</code> if not * needed * @param items the data of the alert items carried in this alert, can be * <code>null</code> or empty if not needed * @throws DmtException with the following possible error codes: * <ul> * <li><code>UNAUTHORIZED</code> when the remote server rejected * the request due to insufficient authorization * <li><code>ALERT_NOT_ROUTED</code> when the alert can not be * routed to the given principal * <li><code>REMOTE_ERROR</code> in case of communication * problems between the device and the destination * <li><code>COMMAND_FAILED</code> for unspecified errors * encountered while attempting to complete the command * <li><code>FEATURE_NOT_SUPPORTED</code> if the underlying * management protocol doesn't support asynchronous notifications * </ul> * @throws SecurityException if the caller does not have the required * <code>AlertPermission</code> with a target matching the * <code>principal</code> parameter, as described above */ void sendNotification(String principal, int code, String correlator, AlertItem[] items) throws DmtException; }
lbchen/odl-mod
opendaylight/northbound/switchmanager/target/enunciate-scratch/enunciate74449087363307455027571/OSGI-OPT/src/info/dmtree/notification/NotificationService.java
Java
epl-1.0
5,147
/* * Copyright (c) 2007-2008 Atheros Communications Inc. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* */ /* Module Name : zdusb.c */ /* */ /* Abstract */ /* This module contains plug and play handling for USB device driver*/ /* */ /* NOTES */ /* Platform dependent. */ /* */ /************************************************************************/ #ifdef MODVERSIONS #include <linux/modversions.h> #endif #include <linux/module.h> #include <linux/slab.h> #include <linux/usb.h> #include "usbdrv.h" #include "zdusb.h" int zfLnxAllocAllUrbs(struct usbdrv_private *macp); void zfLnxFreeAllUrbs(struct usbdrv_private *macp); void zfLnxUnlinkAllUrbs(struct usbdrv_private *macp); MODULE_AUTHOR("Atheros Communications"); MODULE_DESCRIPTION("Atheros 802.11n Wireless LAN adapter"); MODULE_LICENSE("Dual BSD/GPL"); static const char driver_name[] = "Otus"; /* table of devices that work with this driver */ static const struct usb_device_id zd1221_ids[] = { { USB_DEVICE(VENDOR_ATHR, PRODUCT_AR9170) }, { USB_DEVICE(VENDOR_DLINK, PRODUCT_DWA160A) }, { USB_DEVICE(VENDOR_NETGEAR, PRODUCT_WNDA3100) }, { USB_DEVICE(VENDOR_NETGEAR, PRODUCT_WN111v2) }, { } /* Terminating entry */ }; MODULE_DEVICE_TABLE(usb, zd1221_ids); extern u8_t zfLnxInitSetup(struct net_device *dev, struct usbdrv_private *macp); extern int usbdrv_close(struct net_device *dev); extern u8_t zfLnxClearStructs(struct net_device *dev); extern int zfWdsClose(struct net_device *dev); extern int zfUnregisterWdsDev(struct net_device* parentDev, u16_t wdsId); extern int zfLnxVapClose(struct net_device *dev); extern int zfLnxUnregisterVapDev(struct net_device* parentDev, u16_t vapId); /* WDS */ extern struct zsWdsStruct wds[ZM_WDS_PORT_NUMBER]; /* VAP */ extern struct zsVapStruct vap[ZM_VAP_PORT_NUMBER]; static int zfLnxProbe(struct usb_interface *interface, const struct usb_device_id *id) { struct usb_device *dev = interface_to_usbdev(interface); struct net_device *net = NULL; struct usbdrv_private *macp = NULL; int vendor_id, product_id; int result = 0; usb_get_dev(dev); vendor_id = dev->descriptor.idVendor; product_id = dev->descriptor.idProduct; #ifdef HMAC_DEBUG printk(KERN_NOTICE "vendor_id = %04x\n", vendor_id); printk(KERN_NOTICE "product_id = %04x\n", product_id); if (dev->speed == USB_SPEED_HIGH) printk(KERN_NOTICE "USB 2.0 Host\n"); else printk(KERN_NOTICE "USB 1.1 Host\n"); #endif macp = kzalloc(sizeof(struct usbdrv_private), GFP_KERNEL); if (!macp) { printk(KERN_ERR "out of memory allocating device structure\n"); result = -ENOMEM; goto fail; } net = alloc_etherdev(0); if (net == NULL) { printk(KERN_ERR "zfLnxProbe: Not able to alloc etherdev struct\n"); result = -ENOMEM; goto fail1; } strcpy(net->name, "ath%d"); net->ml_priv = macp; //kernel 2.6 macp->udev = dev; macp->device = net; /* set up the endpoint information */ /* check out the endpoints */ macp->interface = interface; //init_waitqueue_head(&macp->regSet_wait); //init_waitqueue_head(&macp->iorwRsp_wait); //init_waitqueue_head(&macp->term_wait); if (!zfLnxAllocAllUrbs(macp)) { result = -ENOMEM; goto fail2; } if (!zfLnxInitSetup(net, macp)) { result = -EIO; goto fail3; } else { usb_set_intfdata(interface, macp); SET_NETDEV_DEV(net, &interface->dev); if (register_netdev(net) != 0) { usb_set_intfdata(interface, NULL); goto fail3; } } netif_carrier_off(net); goto done; fail3: zfLnxFreeAllUrbs(macp); fail2: free_netdev(net); //kernel 2.6 fail1: kfree(macp); fail: usb_put_dev(dev); macp = NULL; done: return result; } static void zfLnxDisconnect(struct usb_interface *interface) { struct usbdrv_private *macp = (struct usbdrv_private *) usb_get_intfdata(interface); printk(KERN_DEBUG "zfLnxDisconnect\n"); if (!macp) { printk(KERN_ERR "unregistering non-existant device\n"); return; } if (macp->driver_isolated) { if (macp->device->flags & IFF_UP) usbdrv_close(macp->device); } #if 0 /* Close WDS */ //zfWdsClose(wds[0].dev); /* Unregister WDS */ //zfUnregisterWdsDev(macp->device, 0); /* Close VAP */ zfLnxVapClose(vap[0].dev); /* Unregister VAP */ zfLnxUnregisterVapDev(macp->device, 0); #endif zfLnxClearStructs(macp->device); unregister_netdev(macp->device); usb_put_dev(interface_to_usbdev(interface)); //printk(KERN_ERR "3. zfLnxUnlinkAllUrbs\n"); //zfLnxUnlinkAllUrbs(macp); /* Free network interface */ free_netdev(macp->device); zfLnxFreeAllUrbs(macp); //zfLnxClearStructs(macp->device); kfree(macp); macp = NULL; usb_set_intfdata(interface, NULL); } static struct usb_driver zd1221_driver = { .name = driver_name, .probe = zfLnxProbe, .disconnect = zfLnxDisconnect, .id_table = zd1221_ids, }; int __init zfLnxIinit(void) { printk(KERN_NOTICE "%s - version %s\n", DRIVER_NAME, VERSIONID); return usb_register(&zd1221_driver); } void __exit zfLnxExit(void) { usb_deregister(&zd1221_driver); } module_init(zfLnxIinit); module_exit(zfLnxExit);
PrasannaC/Galaxy_Fit_s5670-msm7x27_kernel
drivers/staging/otus/zdusb.c
C
gpl-2.0
6,607
/* * Copyright (C) The Weather Channel, Inc. 2002. All Rights Reserved. * Copyright 2005 Stephane Marchesin * * The Weather Channel (TM) funded Tungsten Graphics to develop the * initial release of the Radeon 8500 driver under the XFree86 license. * This notice must be preserved. * * 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 (including the next * paragraph) 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 AND/OR THEIR SUPPLIERS 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. * * Authors: * Keith Whitwell <keith@tungstengraphics.com> */ #include "drmP.h" #include "drm.h" #include "drm_sarea.h" #include "nouveau_drv.h" static struct mem_block * split_block(struct mem_block *p, uint64_t start, uint64_t size, struct drm_file *file_priv) { /* Maybe cut off the start of an existing block */ if (start > p->start) { struct mem_block *newblock = kmalloc(sizeof(*newblock), GFP_KERNEL); if (!newblock) goto out; newblock->start = start; newblock->size = p->size - (start - p->start); newblock->file_priv = NULL; newblock->next = p->next; newblock->prev = p; p->next->prev = newblock; p->next = newblock; p->size -= newblock->size; p = newblock; } /* Maybe cut off the end of an existing block */ if (size < p->size) { struct mem_block *newblock = kmalloc(sizeof(*newblock), GFP_KERNEL); if (!newblock) goto out; newblock->start = start + size; newblock->size = p->size - size; newblock->file_priv = NULL; newblock->next = p->next; newblock->prev = p; p->next->prev = newblock; p->next = newblock; p->size = size; } out: /* Our block is in the middle */ p->file_priv = file_priv; return p; } struct mem_block * nouveau_mem_alloc_block(struct mem_block *heap, uint64_t size, int align2, struct drm_file *file_priv, int tail) { struct mem_block *p; uint64_t mask = (1 << align2) - 1; if (!heap) return NULL; if (tail) { list_for_each_prev(p, heap) { uint64_t start = ((p->start + p->size) - size) & ~mask; if (p->file_priv == NULL && start >= p->start && start + size <= p->start + p->size) return split_block(p, start, size, file_priv); } } else { list_for_each(p, heap) { uint64_t start = (p->start + mask) & ~mask; if (p->file_priv == NULL && start + size <= p->start + p->size) return split_block(p, start, size, file_priv); } } return NULL; } void nouveau_mem_free_block(struct mem_block *p) { p->file_priv = NULL; /* Assumes a single contiguous range. Needs a special file_priv in * 'heap' to stop it being subsumed. */ if (p->next->file_priv == NULL) { struct mem_block *q = p->next; p->size += q->size; p->next = q->next; p->next->prev = p; kfree(q); } if (p->prev->file_priv == NULL) { struct mem_block *q = p->prev; q->size += p->size; q->next = p->next; q->next->prev = q; kfree(p); } } /* Initialize. How to check for an uninitialized heap? */ int nouveau_mem_init_heap(struct mem_block **heap, uint64_t start, uint64_t size) { struct mem_block *blocks = kmalloc(sizeof(*blocks), GFP_KERNEL); if (!blocks) return -ENOMEM; *heap = kmalloc(sizeof(**heap), GFP_KERNEL); if (!*heap) { kfree(blocks); return -ENOMEM; } blocks->start = start; blocks->size = size; blocks->file_priv = NULL; blocks->next = blocks->prev = *heap; memset(*heap, 0, sizeof(**heap)); (*heap)->file_priv = (struct drm_file *) -1; (*heap)->next = (*heap)->prev = blocks; return 0; } /* * Free all blocks associated with the releasing file_priv */ void nouveau_mem_release(struct drm_file *file_priv, struct mem_block *heap) { struct mem_block *p; if (!heap || !heap->next) return; list_for_each(p, heap) { if (p->file_priv == file_priv) p->file_priv = NULL; } /* Assumes a single contiguous range. Needs a special file_priv in * 'heap' to stop it being subsumed. */ list_for_each(p, heap) { while ((p->file_priv == NULL) && (p->next->file_priv == NULL) && (p->next != heap)) { struct mem_block *q = p->next; p->size += q->size; p->next = q->next; p->next->prev = p; kfree(q); } } } /* * NV10-NV40 tiling helpers */ static void nv10_mem_set_region_tiling(struct drm_device *dev, int i, uint32_t addr, uint32_t size, uint32_t pitch) { struct drm_nouveau_private *dev_priv = dev->dev_private; struct nouveau_fifo_engine *pfifo = &dev_priv->engine.fifo; struct nouveau_fb_engine *pfb = &dev_priv->engine.fb; struct nouveau_pgraph_engine *pgraph = &dev_priv->engine.graph; struct nouveau_tile_reg *tile = &dev_priv->tile.reg[i]; tile->addr = addr; tile->size = size; tile->used = !!pitch; nouveau_fence_unref((void **)&tile->fence); if (!pfifo->cache_flush(dev)) return; pfifo->reassign(dev, false); pfifo->cache_flush(dev); pfifo->cache_pull(dev, false); nouveau_wait_for_idle(dev); pgraph->set_region_tiling(dev, i, addr, size, pitch); pfb->set_region_tiling(dev, i, addr, size, pitch); pfifo->cache_pull(dev, true); pfifo->reassign(dev, true); } struct nouveau_tile_reg * nv10_mem_set_tiling(struct drm_device *dev, uint32_t addr, uint32_t size, uint32_t pitch) { struct drm_nouveau_private *dev_priv = dev->dev_private; struct nouveau_fb_engine *pfb = &dev_priv->engine.fb; struct nouveau_tile_reg *tile = dev_priv->tile.reg, *found = NULL; int i; spin_lock(&dev_priv->tile.lock); for (i = 0; i < pfb->num_tiles; i++) { if (tile[i].used) /* Tile region in use. */ continue; if (tile[i].fence && !nouveau_fence_signalled(tile[i].fence, NULL)) /* Pending tile region. */ continue; if (max(tile[i].addr, addr) < min(tile[i].addr + tile[i].size, addr + size)) /* Kill an intersecting tile region. */ nv10_mem_set_region_tiling(dev, i, 0, 0, 0); if (pitch && !found) { /* Free tile region. */ nv10_mem_set_region_tiling(dev, i, addr, size, pitch); found = &tile[i]; } } spin_unlock(&dev_priv->tile.lock); return found; } void nv10_mem_expire_tiling(struct drm_device *dev, struct nouveau_tile_reg *tile, struct nouveau_fence *fence) { if (fence) { /* Mark it as pending. */ tile->fence = fence; nouveau_fence_ref(fence); } tile->used = false; } /* * NV50 VM helpers */ int nv50_mem_vm_bind_linear(struct drm_device *dev, uint64_t virt, uint32_t size, uint32_t flags, uint64_t phys) { struct drm_nouveau_private *dev_priv = dev->dev_private; struct nouveau_gpuobj *pgt; unsigned block; int i; virt = ((virt - dev_priv->vm_vram_base) >> 16) << 1; size = (size >> 16) << 1; phys |= ((uint64_t)flags << 32); phys |= 1; if (dev_priv->vram_sys_base) { phys += dev_priv->vram_sys_base; phys |= 0x30; } dev_priv->engine.instmem.prepare_access(dev, true); while (size) { unsigned offset_h = upper_32_bits(phys); unsigned offset_l = lower_32_bits(phys); unsigned pte, end; for (i = 7; i >= 0; i--) { block = 1 << (i + 1); if (size >= block && !(virt & (block - 1))) break; } offset_l |= (i << 7); phys += block << 15; size -= block; while (block) { pgt = dev_priv->vm_vram_pt[virt >> 14]; pte = virt & 0x3ffe; end = pte + block; if (end > 16384) end = 16384; block -= (end - pte); virt += (end - pte); while (pte < end) { nv_wo32(dev, pgt, pte++, offset_l); nv_wo32(dev, pgt, pte++, offset_h); } } } dev_priv->engine.instmem.finish_access(dev); nv_wr32(dev, 0x100c80, 0x00050001); if (!nv_wait(0x100c80, 0x00000001, 0x00000000)) { NV_ERROR(dev, "timeout: (0x100c80 & 1) == 0 (2)\n"); NV_ERROR(dev, "0x100c80 = 0x%08x\n", nv_rd32(dev, 0x100c80)); return -EBUSY; } nv_wr32(dev, 0x100c80, 0x00000001); if (!nv_wait(0x100c80, 0x00000001, 0x00000000)) { NV_ERROR(dev, "timeout: (0x100c80 & 1) == 0 (2)\n"); NV_ERROR(dev, "0x100c80 = 0x%08x\n", nv_rd32(dev, 0x100c80)); return -EBUSY; } nv_wr32(dev, 0x100c80, 0x00040001); if (!nv_wait(0x100c80, 0x00000001, 0x00000000)) { NV_ERROR(dev, "timeout: (0x100c80 & 1) == 0 (2)\n"); NV_ERROR(dev, "0x100c80 = 0x%08x\n", nv_rd32(dev, 0x100c80)); return -EBUSY; } nv_wr32(dev, 0x100c80, 0x00060001); if (!nv_wait(0x100c80, 0x00000001, 0x00000000)) { NV_ERROR(dev, "timeout: (0x100c80 & 1) == 0 (2)\n"); NV_ERROR(dev, "0x100c80 = 0x%08x\n", nv_rd32(dev, 0x100c80)); return -EBUSY; } return 0; } void nv50_mem_vm_unbind(struct drm_device *dev, uint64_t virt, uint32_t size) { struct drm_nouveau_private *dev_priv = dev->dev_private; struct nouveau_gpuobj *pgt; unsigned pages, pte, end; virt -= dev_priv->vm_vram_base; pages = (size >> 16) << 1; dev_priv->engine.instmem.prepare_access(dev, true); while (pages) { pgt = dev_priv->vm_vram_pt[virt >> 29]; pte = (virt & 0x1ffe0000ULL) >> 15; end = pte + pages; if (end > 16384) end = 16384; pages -= (end - pte); virt += (end - pte) << 15; while (pte < end) nv_wo32(dev, pgt, pte++, 0); } dev_priv->engine.instmem.finish_access(dev); nv_wr32(dev, 0x100c80, 0x00050001); if (!nv_wait(0x100c80, 0x00000001, 0x00000000)) { NV_ERROR(dev, "timeout: (0x100c80 & 1) == 0 (2)\n"); NV_ERROR(dev, "0x100c80 = 0x%08x\n", nv_rd32(dev, 0x100c80)); return; } nv_wr32(dev, 0x100c80, 0x00000001); if (!nv_wait(0x100c80, 0x00000001, 0x00000000)) { NV_ERROR(dev, "timeout: (0x100c80 & 1) == 0 (2)\n"); NV_ERROR(dev, "0x100c80 = 0x%08x\n", nv_rd32(dev, 0x100c80)); return; } nv_wr32(dev, 0x100c80, 0x00040001); if (!nv_wait(0x100c80, 0x00000001, 0x00000000)) { NV_ERROR(dev, "timeout: (0x100c80 & 1) == 0 (2)\n"); NV_ERROR(dev, "0x100c80 = 0x%08x\n", nv_rd32(dev, 0x100c80)); return; } nv_wr32(dev, 0x100c80, 0x00060001); if (!nv_wait(0x100c80, 0x00000001, 0x00000000)) { NV_ERROR(dev, "timeout: (0x100c80 & 1) == 0 (2)\n"); NV_ERROR(dev, "0x100c80 = 0x%08x\n", nv_rd32(dev, 0x100c80)); } } /* * Cleanup everything */ void nouveau_mem_takedown(struct mem_block **heap) { struct mem_block *p; if (!*heap) return; for (p = (*heap)->next; p != *heap;) { struct mem_block *q = p; p = p->next; kfree(q); } kfree(*heap); *heap = NULL; } void nouveau_mem_close(struct drm_device *dev) { struct drm_nouveau_private *dev_priv = dev->dev_private; nouveau_bo_unpin(dev_priv->vga_ram); nouveau_bo_ref(NULL, &dev_priv->vga_ram); ttm_bo_device_release(&dev_priv->ttm.bdev); nouveau_ttm_global_release(dev_priv); if (drm_core_has_AGP(dev) && dev->agp && drm_core_check_feature(dev, DRIVER_MODESET)) { struct drm_agp_mem *entry, *tempe; /* Remove AGP resources, but leave dev->agp intact until drv_cleanup is called. */ list_for_each_entry_safe(entry, tempe, &dev->agp->memory, head) { if (entry->bound) drm_unbind_agp(entry->memory); drm_free_agp(entry->memory, entry->pages); kfree(entry); } INIT_LIST_HEAD(&dev->agp->memory); if (dev->agp->acquired) drm_agp_release(dev); dev->agp->acquired = 0; dev->agp->enabled = 0; } if (dev_priv->fb_mtrr) { drm_mtrr_del(dev_priv->fb_mtrr, drm_get_resource_start(dev, 1), drm_get_resource_len(dev, 1), DRM_MTRR_WC); dev_priv->fb_mtrr = 0; } } static uint32_t nouveau_mem_detect_nv04(struct drm_device *dev) { uint32_t boot0 = nv_rd32(dev, NV03_BOOT_0); if (boot0 & 0x00000100) return (((boot0 >> 12) & 0xf) * 2 + 2) * 1024 * 1024; switch (boot0 & NV03_BOOT_0_RAM_AMOUNT) { case NV04_BOOT_0_RAM_AMOUNT_32MB: return 32 * 1024 * 1024; case NV04_BOOT_0_RAM_AMOUNT_16MB: return 16 * 1024 * 1024; case NV04_BOOT_0_RAM_AMOUNT_8MB: return 8 * 1024 * 1024; case NV04_BOOT_0_RAM_AMOUNT_4MB: return 4 * 1024 * 1024; } return 0; } static uint32_t nouveau_mem_detect_nforce(struct drm_device *dev) { struct drm_nouveau_private *dev_priv = dev->dev_private; struct pci_dev *bridge; uint32_t mem; bridge = pci_get_bus_and_slot(0, PCI_DEVFN(0, 1)); if (!bridge) { NV_ERROR(dev, "no bridge device\n"); return 0; } if (dev_priv->flags & NV_NFORCE) { pci_read_config_dword(bridge, 0x7C, &mem); return (uint64_t)(((mem >> 6) & 31) + 1)*1024*1024; } else if (dev_priv->flags & NV_NFORCE2) { pci_read_config_dword(bridge, 0x84, &mem); return (uint64_t)(((mem >> 4) & 127) + 1)*1024*1024; } NV_ERROR(dev, "impossible!\n"); return 0; } /* returns the amount of FB ram in bytes */ int nouveau_mem_detect(struct drm_device *dev) { struct drm_nouveau_private *dev_priv = dev->dev_private; if (dev_priv->card_type == NV_04) { dev_priv->vram_size = nouveau_mem_detect_nv04(dev); } else if (dev_priv->flags & (NV_NFORCE | NV_NFORCE2)) { dev_priv->vram_size = nouveau_mem_detect_nforce(dev); } else { dev_priv->vram_size = nv_rd32(dev, NV04_FIFO_DATA); dev_priv->vram_size &= NV10_FIFO_DATA_RAM_AMOUNT_MB_MASK; if (dev_priv->chipset == 0xaa || dev_priv->chipset == 0xac) dev_priv->vram_sys_base = nv_rd32(dev, 0x100e10); dev_priv->vram_sys_base <<= 12; } NV_INFO(dev, "Detected %dMiB VRAM\n", (int)(dev_priv->vram_size >> 20)); if (dev_priv->vram_sys_base) { NV_INFO(dev, "Stolen system memory at: 0x%010llx\n", dev_priv->vram_sys_base); } if (dev_priv->vram_size) return 0; return -ENOMEM; } #if __OS_HAS_AGP static void nouveau_mem_reset_agp(struct drm_device *dev) { uint32_t saved_pci_nv_1, saved_pci_nv_19, pmc_enable; saved_pci_nv_1 = nv_rd32(dev, NV04_PBUS_PCI_NV_1); saved_pci_nv_19 = nv_rd32(dev, NV04_PBUS_PCI_NV_19); /* clear busmaster bit */ nv_wr32(dev, NV04_PBUS_PCI_NV_1, saved_pci_nv_1 & ~0x4); /* clear SBA and AGP bits */ nv_wr32(dev, NV04_PBUS_PCI_NV_19, saved_pci_nv_19 & 0xfffff0ff); /* power cycle pgraph, if enabled */ pmc_enable = nv_rd32(dev, NV03_PMC_ENABLE); if (pmc_enable & NV_PMC_ENABLE_PGRAPH) { nv_wr32(dev, NV03_PMC_ENABLE, pmc_enable & ~NV_PMC_ENABLE_PGRAPH); nv_wr32(dev, NV03_PMC_ENABLE, nv_rd32(dev, NV03_PMC_ENABLE) | NV_PMC_ENABLE_PGRAPH); } /* and restore (gives effect of resetting AGP) */ nv_wr32(dev, NV04_PBUS_PCI_NV_19, saved_pci_nv_19); nv_wr32(dev, NV04_PBUS_PCI_NV_1, saved_pci_nv_1); } #endif int nouveau_mem_init_agp(struct drm_device *dev) { #if __OS_HAS_AGP struct drm_nouveau_private *dev_priv = dev->dev_private; struct drm_agp_info info; struct drm_agp_mode mode; int ret; if (nouveau_noagp) return 0; nouveau_mem_reset_agp(dev); if (!dev->agp->acquired) { ret = drm_agp_acquire(dev); if (ret) { NV_ERROR(dev, "Unable to acquire AGP: %d\n", ret); return ret; } } ret = drm_agp_info(dev, &info); if (ret) { NV_ERROR(dev, "Unable to get AGP info: %d\n", ret); return ret; } /* see agp.h for the AGPSTAT_* modes available */ mode.mode = info.mode; ret = drm_agp_enable(dev, mode); if (ret) { NV_ERROR(dev, "Unable to enable AGP: %d\n", ret); return ret; } dev_priv->gart_info.type = NOUVEAU_GART_AGP; dev_priv->gart_info.aper_base = info.aperture_base; dev_priv->gart_info.aper_size = info.aperture_size; #endif return 0; } int nouveau_mem_init(struct drm_device *dev) { struct drm_nouveau_private *dev_priv = dev->dev_private; struct ttm_bo_device *bdev = &dev_priv->ttm.bdev; int ret, dma_bits = 32; dev_priv->fb_phys = drm_get_resource_start(dev, 1); dev_priv->gart_info.type = NOUVEAU_GART_NONE; if (dev_priv->card_type >= NV_50 && pci_dma_supported(dev->pdev, DMA_BIT_MASK(40))) dma_bits = 40; ret = pci_set_dma_mask(dev->pdev, DMA_BIT_MASK(dma_bits)); if (ret) { NV_ERROR(dev, "Error setting DMA mask: %d\n", ret); return ret; } ret = nouveau_ttm_global_init(dev_priv); if (ret) return ret; ret = ttm_bo_device_init(&dev_priv->ttm.bdev, dev_priv->ttm.bo_global_ref.ref.object, &nouveau_bo_driver, DRM_FILE_PAGE_OFFSET, dma_bits <= 32 ? true : false); if (ret) { NV_ERROR(dev, "Error initialising bo driver: %d\n", ret); return ret; } INIT_LIST_HEAD(&dev_priv->ttm.bo_list); spin_lock_init(&dev_priv->ttm.bo_list_lock); spin_lock_init(&dev_priv->tile.lock); dev_priv->fb_available_size = dev_priv->vram_size; dev_priv->fb_mappable_pages = dev_priv->fb_available_size; if (dev_priv->fb_mappable_pages > drm_get_resource_len(dev, 1)) dev_priv->fb_mappable_pages = drm_get_resource_len(dev, 1); dev_priv->fb_mappable_pages >>= PAGE_SHIFT; /* remove reserved space at end of vram from available amount */ dev_priv->fb_available_size -= dev_priv->ramin_rsvd_vram; dev_priv->fb_aper_free = dev_priv->fb_available_size; /* mappable vram */ ret = ttm_bo_init_mm(bdev, TTM_PL_VRAM, dev_priv->fb_available_size >> PAGE_SHIFT); if (ret) { NV_ERROR(dev, "Failed VRAM mm init: %d\n", ret); return ret; } ret = nouveau_bo_new(dev, NULL, 256*1024, 0, TTM_PL_FLAG_VRAM, 0, 0, true, true, &dev_priv->vga_ram); if (ret == 0) ret = nouveau_bo_pin(dev_priv->vga_ram, TTM_PL_FLAG_VRAM); if (ret) { NV_WARN(dev, "failed to reserve VGA memory\n"); nouveau_bo_ref(NULL, &dev_priv->vga_ram); } /* GART */ #if !defined(__powerpc__) && !defined(__ia64__) if (drm_device_is_agp(dev) && dev->agp) { ret = nouveau_mem_init_agp(dev); if (ret) NV_ERROR(dev, "Error initialising AGP: %d\n", ret); } #endif if (dev_priv->gart_info.type == NOUVEAU_GART_NONE) { ret = nouveau_sgdma_init(dev); if (ret) { NV_ERROR(dev, "Error initialising PCI(E): %d\n", ret); return ret; } } NV_INFO(dev, "%d MiB GART (aperture)\n", (int)(dev_priv->gart_info.aper_size >> 20)); dev_priv->gart_info.aper_free = dev_priv->gart_info.aper_size; ret = ttm_bo_init_mm(bdev, TTM_PL_TT, dev_priv->gart_info.aper_size >> PAGE_SHIFT); if (ret) { NV_ERROR(dev, "Failed TT mm init: %d\n", ret); return ret; } dev_priv->fb_mtrr = drm_mtrr_add(drm_get_resource_start(dev, 1), drm_get_resource_len(dev, 1), DRM_MTRR_WC); return 0; }
pranaysahith/android_kernel_msm_beni
drivers/gpu/drm/nouveau/nouveau_mem.c
C
gpl-2.0
18,594
/* * File: drivers/input/keyboard/bf54x-keys.c * Based on: * Author: Michael Hennerich <hennerich@blackfin.uclinux.org> * * Created: * Description: keypad driver for Analog Devices Blackfin BF54x Processors * * * Modified: * Copyright 2007-2008 Analog Devices Inc. * * Bugs: Enter bugs at http://blackfin.uclinux.org/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see the file COPYING, or write * to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <linux/module.h> #include <linux/fs.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/slab.h> #include <linux/sched.h> #include <linux/pm.h> #include <linux/sysctl.h> #include <linux/proc_fs.h> #include <linux/delay.h> #include <linux/platform_device.h> #include <linux/input.h> #include <asm/portmux.h> #include <mach/bf54x_keys.h> #define DRV_NAME "bf54x-keys" #define TIME_SCALE 100 /* 100 ns */ #define MAX_MULT (0xFF * TIME_SCALE) #define MAX_RC 8 /* Max Row/Col */ static const u16 per_rows[] = { P_KEY_ROW7, P_KEY_ROW6, P_KEY_ROW5, P_KEY_ROW4, P_KEY_ROW3, P_KEY_ROW2, P_KEY_ROW1, P_KEY_ROW0, 0 }; static const u16 per_cols[] = { P_KEY_COL7, P_KEY_COL6, P_KEY_COL5, P_KEY_COL4, P_KEY_COL3, P_KEY_COL2, P_KEY_COL1, P_KEY_COL0, 0 }; struct bf54x_kpad { struct input_dev *input; int irq; unsigned short lastkey; unsigned short *keycode; struct timer_list timer; unsigned int keyup_test_jiffies; unsigned short kpad_msel; unsigned short kpad_prescale; unsigned short kpad_ctl; }; static inline int bfin_kpad_find_key(struct bf54x_kpad *bf54x_kpad, struct input_dev *input, u16 keyident) { u16 i; for (i = 0; i < input->keycodemax; i++) if (bf54x_kpad->keycode[i + input->keycodemax] == keyident) return bf54x_kpad->keycode[i]; return -1; } static inline void bfin_keycodecpy(unsigned short *keycode, const unsigned int *pdata_kc, unsigned short keymapsize) { unsigned int i; for (i = 0; i < keymapsize; i++) { keycode[i] = pdata_kc[i] & 0xffff; keycode[i + keymapsize] = pdata_kc[i] >> 16; } } static inline u16 bfin_kpad_get_prescale(u32 timescale) { u32 sclk = get_sclk(); return ((((sclk / 1000) * timescale) / 1024) - 1); } static inline u16 bfin_kpad_get_keypressed(struct bf54x_kpad *bf54x_kpad) { return (bfin_read_KPAD_STAT() & KPAD_PRESSED); } static inline void bfin_kpad_clear_irq(void) { bfin_write_KPAD_STAT(0xFFFF); bfin_write_KPAD_ROWCOL(0xFFFF); } static void bfin_kpad_timer(unsigned long data) { struct platform_device *pdev = (struct platform_device *) data; struct bf54x_kpad *bf54x_kpad = platform_get_drvdata(pdev); if (bfin_kpad_get_keypressed(bf54x_kpad)) { /* Try again later */ mod_timer(&bf54x_kpad->timer, jiffies + bf54x_kpad->keyup_test_jiffies); return; } input_report_key(bf54x_kpad->input, bf54x_kpad->lastkey, 0); input_sync(bf54x_kpad->input); /* Clear IRQ Status */ bfin_kpad_clear_irq(); enable_irq(bf54x_kpad->irq); } static irqreturn_t bfin_kpad_isr(int irq, void *dev_id) { struct platform_device *pdev = dev_id; struct bf54x_kpad *bf54x_kpad = platform_get_drvdata(pdev); struct input_dev *input = bf54x_kpad->input; int key; u16 rowcol = bfin_read_KPAD_ROWCOL(); key = bfin_kpad_find_key(bf54x_kpad, input, rowcol); input_report_key(input, key, 1); input_sync(input); if (bfin_kpad_get_keypressed(bf54x_kpad)) { disable_irq_nosync(bf54x_kpad->irq); bf54x_kpad->lastkey = key; mod_timer(&bf54x_kpad->timer, jiffies + bf54x_kpad->keyup_test_jiffies); } else { input_report_key(input, key, 0); input_sync(input); bfin_kpad_clear_irq(); } return IRQ_HANDLED; } static int bfin_kpad_probe(struct platform_device *pdev) { struct bf54x_kpad *bf54x_kpad; struct bfin_kpad_platform_data *pdata = dev_get_platdata(&pdev->dev); struct input_dev *input; int i, error; if (!pdata->rows || !pdata->cols || !pdata->keymap) { dev_err(&pdev->dev, "no rows, cols or keymap from pdata\n"); return -EINVAL; } if (!pdata->keymapsize || pdata->keymapsize > (pdata->rows * pdata->cols)) { dev_err(&pdev->dev, "invalid keymapsize\n"); return -EINVAL; } bf54x_kpad = kzalloc(sizeof(struct bf54x_kpad), GFP_KERNEL); if (!bf54x_kpad) return -ENOMEM; platform_set_drvdata(pdev, bf54x_kpad); /* Allocate memory for keymap followed by private LUT */ bf54x_kpad->keycode = kmalloc(pdata->keymapsize * sizeof(unsigned short) * 2, GFP_KERNEL); if (!bf54x_kpad->keycode) { error = -ENOMEM; goto out; } if (!pdata->debounce_time || pdata->debounce_time > MAX_MULT || !pdata->coldrive_time || pdata->coldrive_time > MAX_MULT) { dev_warn(&pdev->dev, "invalid platform debounce/columndrive time\n"); bfin_write_KPAD_MSEL(0xFF0); /* Default MSEL */ } else { bfin_write_KPAD_MSEL( ((pdata->debounce_time / TIME_SCALE) & DBON_SCALE) | (((pdata->coldrive_time / TIME_SCALE) << 8) & COLDRV_SCALE)); } if (!pdata->keyup_test_interval) bf54x_kpad->keyup_test_jiffies = msecs_to_jiffies(50); else bf54x_kpad->keyup_test_jiffies = msecs_to_jiffies(pdata->keyup_test_interval); if (peripheral_request_list((u16 *)&per_rows[MAX_RC - pdata->rows], DRV_NAME)) { dev_err(&pdev->dev, "requesting peripherals failed\n"); error = -EFAULT; goto out0; } if (peripheral_request_list((u16 *)&per_cols[MAX_RC - pdata->cols], DRV_NAME)) { dev_err(&pdev->dev, "requesting peripherals failed\n"); error = -EFAULT; goto out1; } bf54x_kpad->irq = platform_get_irq(pdev, 0); if (bf54x_kpad->irq < 0) { error = -ENODEV; goto out2; } error = request_irq(bf54x_kpad->irq, bfin_kpad_isr, 0, DRV_NAME, pdev); if (error) { dev_err(&pdev->dev, "unable to claim irq %d\n", bf54x_kpad->irq); goto out2; } input = input_allocate_device(); if (!input) { error = -ENOMEM; goto out3; } bf54x_kpad->input = input; input->name = pdev->name; input->phys = "bf54x-keys/input0"; input->dev.parent = &pdev->dev; input_set_drvdata(input, bf54x_kpad); input->id.bustype = BUS_HOST; input->id.vendor = 0x0001; input->id.product = 0x0001; input->id.version = 0x0100; input->keycodesize = sizeof(unsigned short); input->keycodemax = pdata->keymapsize; input->keycode = bf54x_kpad->keycode; bfin_keycodecpy(bf54x_kpad->keycode, pdata->keymap, pdata->keymapsize); /* setup input device */ __set_bit(EV_KEY, input->evbit); if (pdata->repeat) __set_bit(EV_REP, input->evbit); for (i = 0; i < input->keycodemax; i++) if (bf54x_kpad->keycode[i] <= KEY_MAX) __set_bit(bf54x_kpad->keycode[i], input->keybit); __clear_bit(KEY_RESERVED, input->keybit); error = input_register_device(input); if (error) { dev_err(&pdev->dev, "unable to register input device\n"); goto out4; } /* Init Keypad Key Up/Release test timer */ setup_timer(&bf54x_kpad->timer, bfin_kpad_timer, (unsigned long) pdev); bfin_write_KPAD_PRESCALE(bfin_kpad_get_prescale(TIME_SCALE)); bfin_write_KPAD_CTL((((pdata->cols - 1) << 13) & KPAD_COLEN) | (((pdata->rows - 1) << 10) & KPAD_ROWEN) | (2 & KPAD_IRQMODE)); bfin_write_KPAD_CTL(bfin_read_KPAD_CTL() | KPAD_EN); device_init_wakeup(&pdev->dev, 1); return 0; out4: input_free_device(input); out3: free_irq(bf54x_kpad->irq, pdev); out2: peripheral_free_list((u16 *)&per_cols[MAX_RC - pdata->cols]); out1: peripheral_free_list((u16 *)&per_rows[MAX_RC - pdata->rows]); out0: kfree(bf54x_kpad->keycode); out: kfree(bf54x_kpad); return error; } static int bfin_kpad_remove(struct platform_device *pdev) { struct bfin_kpad_platform_data *pdata = dev_get_platdata(&pdev->dev); struct bf54x_kpad *bf54x_kpad = platform_get_drvdata(pdev); del_timer_sync(&bf54x_kpad->timer); free_irq(bf54x_kpad->irq, pdev); input_unregister_device(bf54x_kpad->input); peripheral_free_list((u16 *)&per_rows[MAX_RC - pdata->rows]); peripheral_free_list((u16 *)&per_cols[MAX_RC - pdata->cols]); kfree(bf54x_kpad->keycode); kfree(bf54x_kpad); return 0; } #ifdef CONFIG_PM static int bfin_kpad_suspend(struct platform_device *pdev, pm_message_t state) { struct bf54x_kpad *bf54x_kpad = platform_get_drvdata(pdev); bf54x_kpad->kpad_msel = bfin_read_KPAD_MSEL(); bf54x_kpad->kpad_prescale = bfin_read_KPAD_PRESCALE(); bf54x_kpad->kpad_ctl = bfin_read_KPAD_CTL(); if (device_may_wakeup(&pdev->dev)) enable_irq_wake(bf54x_kpad->irq); return 0; } static int bfin_kpad_resume(struct platform_device *pdev) { struct bf54x_kpad *bf54x_kpad = platform_get_drvdata(pdev); bfin_write_KPAD_MSEL(bf54x_kpad->kpad_msel); bfin_write_KPAD_PRESCALE(bf54x_kpad->kpad_prescale); bfin_write_KPAD_CTL(bf54x_kpad->kpad_ctl); if (device_may_wakeup(&pdev->dev)) disable_irq_wake(bf54x_kpad->irq); return 0; } #else # define bfin_kpad_suspend NULL # define bfin_kpad_resume NULL #endif static struct platform_driver bfin_kpad_device_driver = { .driver = { .name = DRV_NAME, }, .probe = bfin_kpad_probe, .remove = bfin_kpad_remove, .suspend = bfin_kpad_suspend, .resume = bfin_kpad_resume, }; module_platform_driver(bfin_kpad_device_driver); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Michael Hennerich <hennerich@blackfin.uclinux.org>"); MODULE_DESCRIPTION("Keypad driver for BF54x Processors"); MODULE_ALIAS("platform:bf54x-keys");
groeck/linux
drivers/input/keyboard/bf54x-keys.c
C
gpl-2.0
9,900
/* * Intel MID Resistive Touch Screen Driver * * Copyright (C) 2008 Intel Corp * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * Questions/Comments/Bug fixes to Sreedhara (sreedhara.ds@intel.com) * Ramesh Agarwal (ramesh.agarwal@intel.com) * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * TODO: * review conversion of r/m/w sequences */ #include <linux/module.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/err.h> #include <linux/param.h> #include <linux/slab.h> #include <linux/platform_device.h> #include <linux/irq.h> #include <linux/delay.h> #include <asm/intel_scu_ipc.h> #include <linux/device.h> /* PMIC Interrupt registers */ #define PMIC_REG_ID1 0x00 /* PMIC ID1 register */ /* PMIC Interrupt registers */ #define PMIC_REG_INT 0x04 /* PMIC interrupt register */ #define PMIC_REG_MINT 0x05 /* PMIC interrupt mask register */ /* ADC Interrupt registers */ #define PMIC_REG_ADCINT 0x5F /* ADC interrupt register */ #define PMIC_REG_MADCINT 0x60 /* ADC interrupt mask register */ /* ADC Control registers */ #define PMIC_REG_ADCCNTL1 0x61 /* ADC control register */ /* ADC Channel Selection registers */ #define PMICADDR0 0xA4 #define END_OF_CHANNEL 0x1F /* ADC Result register */ #define PMIC_REG_ADCSNS0H 0x64 /* ADC channels for touch screen */ #define MRST_TS_CHAN10 0xA /* Touch screen X+ connection */ #define MRST_TS_CHAN11 0xB /* Touch screen X- connection */ #define MRST_TS_CHAN12 0xC /* Touch screen Y+ connection */ #define MRST_TS_CHAN13 0xD /* Touch screen Y- connection */ /* Touch screen channel BIAS constants */ #define MRST_XBIAS 0x20 #define MRST_YBIAS 0x40 #define MRST_ZBIAS 0x80 /* Touch screen coordinates */ #define MRST_X_MIN 10 #define MRST_X_MAX 1024 #define MRST_X_FUZZ 5 #define MRST_Y_MIN 10 #define MRST_Y_MAX 1024 #define MRST_Y_FUZZ 5 #define MRST_PRESSURE_MIN 0 #define MRST_PRESSURE_NOMINAL 50 #define MRST_PRESSURE_MAX 100 #define WAIT_ADC_COMPLETION 10 /* msec */ /* PMIC ADC round robin delays */ #define ADC_LOOP_DELAY0 0x0 /* Continuous loop */ #define ADC_LOOP_DELAY1 0x1 /* 4.5 ms approximate */ /* PMIC Vendor Identifiers */ #define PMIC_VENDOR_FS 0 /* PMIC vendor FreeScale */ #define PMIC_VENDOR_MAXIM 1 /* PMIC vendor MAXIM */ #define PMIC_VENDOR_NEC 2 /* PMIC vendor NEC */ #define MRSTOUCH_MAX_CHANNELS 32 /* Maximum ADC channels */ /* Touch screen device structure */ struct mrstouch_dev { struct device *dev; /* device associated with touch screen */ struct input_dev *input; char phys[32]; u16 asr; /* Address selection register */ int irq; unsigned int vendor; /* PMIC vendor */ unsigned int rev; /* PMIC revision */ int (*read_prepare)(struct mrstouch_dev *tsdev); int (*read)(struct mrstouch_dev *tsdev, u16 *x, u16 *y, u16 *z); int (*read_finish)(struct mrstouch_dev *tsdev); }; /*************************** NEC and Maxim Interface ************************/ static int mrstouch_nec_adc_read_prepare(struct mrstouch_dev *tsdev) { return intel_scu_ipc_update_register(PMIC_REG_MADCINT, 0, 0x20); } /* * Enables PENDET interrupt. */ static int mrstouch_nec_adc_read_finish(struct mrstouch_dev *tsdev) { int err; err = intel_scu_ipc_update_register(PMIC_REG_MADCINT, 0x20, 0x20); if (!err) err = intel_scu_ipc_update_register(PMIC_REG_ADCCNTL1, 0, 0x05); return err; } /* * Reads PMIC ADC touch screen result * Reads ADC storage registers for higher 7 and lower 3 bits and * converts the two readings into a single value and turns off gain bit */ static int mrstouch_ts_chan_read(u16 offset, u16 chan, u16 *vp, u16 *vm) { int err; u16 result; u32 res; result = PMIC_REG_ADCSNS0H + offset; if (chan == MRST_TS_CHAN12) result += 4; err = intel_scu_ipc_ioread32(result, &res); if (err) return err; /* Mash the bits up */ *vp = (res & 0xFF) << 3; /* Highest 7 bits */ *vp |= (res >> 8) & 0x07; /* Lower 3 bits */ *vp &= 0x3FF; res >>= 16; *vm = (res & 0xFF) << 3; /* Highest 7 bits */ *vm |= (res >> 8) & 0x07; /* Lower 3 bits */ *vm &= 0x3FF; return 0; } /* * Enables X, Y and Z bias values * Enables YPYM for X channels and XPXM for Y channels */ static int mrstouch_ts_bias_set(uint offset, uint bias) { int count; u16 chan, start; u16 reg[4]; u8 data[4]; chan = PMICADDR0 + offset; start = MRST_TS_CHAN10; for (count = 0; count <= 3; count++) { reg[count] = chan++; data[count] = bias | (start + count); } return intel_scu_ipc_writev(reg, data, 4); } /* To read touch screen channel values */ static int mrstouch_nec_adc_read(struct mrstouch_dev *tsdev, u16 *x, u16 *y, u16 *z) { int err; u16 xm, ym, zm; /* configure Y bias for X channels */ err = mrstouch_ts_bias_set(tsdev->asr, MRST_YBIAS); if (err) goto ipc_error; msleep(WAIT_ADC_COMPLETION); /* read x+ and x- channels */ err = mrstouch_ts_chan_read(tsdev->asr, MRST_TS_CHAN10, x, &xm); if (err) goto ipc_error; /* configure x bias for y channels */ err = mrstouch_ts_bias_set(tsdev->asr, MRST_XBIAS); if (err) goto ipc_error; msleep(WAIT_ADC_COMPLETION); /* read y+ and y- channels */ err = mrstouch_ts_chan_read(tsdev->asr, MRST_TS_CHAN12, y, &ym); if (err) goto ipc_error; /* configure z bias for x and y channels */ err = mrstouch_ts_bias_set(tsdev->asr, MRST_ZBIAS); if (err) goto ipc_error; msleep(WAIT_ADC_COMPLETION); /* read z+ and z- channels */ err = mrstouch_ts_chan_read(tsdev->asr, MRST_TS_CHAN10, z, &zm); if (err) goto ipc_error; return 0; ipc_error: dev_err(tsdev->dev, "ipc error during adc read\n"); return err; } /*************************** Freescale Interface ************************/ static int mrstouch_fs_adc_read_prepare(struct mrstouch_dev *tsdev) { int err, count; u16 chan; u16 reg[5]; u8 data[5]; /* Stop the ADC */ err = intel_scu_ipc_update_register(PMIC_REG_MADCINT, 0x00, 0x02); if (err) goto ipc_error; chan = PMICADDR0 + tsdev->asr; /* Set X BIAS */ for (count = 0; count <= 3; count++) { reg[count] = chan++; data[count] = 0x2A; } reg[count] = chan++; /* Dummy */ data[count] = 0; err = intel_scu_ipc_writev(reg, data, 5); if (err) goto ipc_error; msleep(WAIT_ADC_COMPLETION); /* Set Y BIAS */ for (count = 0; count <= 3; count++) { reg[count] = chan++; data[count] = 0x4A; } reg[count] = chan++; /* Dummy */ data[count] = 0; err = intel_scu_ipc_writev(reg, data, 5); if (err) goto ipc_error; msleep(WAIT_ADC_COMPLETION); /* Set Z BIAS */ err = intel_scu_ipc_iowrite32(chan + 2, 0x8A8A8A8A); if (err) goto ipc_error; msleep(WAIT_ADC_COMPLETION); return 0; ipc_error: dev_err(tsdev->dev, "ipc error during %s\n", __func__); return err; } static int mrstouch_fs_adc_read(struct mrstouch_dev *tsdev, u16 *x, u16 *y, u16 *z) { int err; u16 result; u16 reg[4]; u8 data[4]; result = PMIC_REG_ADCSNS0H + tsdev->asr; reg[0] = result + 4; reg[1] = result + 5; reg[2] = result + 16; reg[3] = result + 17; err = intel_scu_ipc_readv(reg, data, 4); if (err) goto ipc_error; *x = data[0] << 3; /* Higher 7 bits */ *x |= data[1] & 0x7; /* Lower 3 bits */ *x &= 0x3FF; *y = data[2] << 3; /* Higher 7 bits */ *y |= data[3] & 0x7; /* Lower 3 bits */ *y &= 0x3FF; /* Read Z value */ reg[0] = result + 28; reg[1] = result + 29; err = intel_scu_ipc_readv(reg, data, 4); if (err) goto ipc_error; *z = data[0] << 3; /* Higher 7 bits */ *z |= data[1] & 0x7; /* Lower 3 bits */ *z &= 0x3FF; return 0; ipc_error: dev_err(tsdev->dev, "ipc error during %s\n", __func__); return err; } static int mrstouch_fs_adc_read_finish(struct mrstouch_dev *tsdev) { int err, count; u16 chan; u16 reg[5]; u8 data[5]; /* Clear all TS channels */ chan = PMICADDR0 + tsdev->asr; for (count = 0; count <= 4; count++) { reg[count] = chan++; data[count] = 0; } err = intel_scu_ipc_writev(reg, data, 5); if (err) goto ipc_error; for (count = 0; count <= 4; count++) { reg[count] = chan++; data[count] = 0; } err = intel_scu_ipc_writev(reg, data, 5); if (err) goto ipc_error; err = intel_scu_ipc_iowrite32(chan + 2, 0x00000000); if (err) goto ipc_error; /* Start ADC */ err = intel_scu_ipc_update_register(PMIC_REG_MADCINT, 0x02, 0x02); if (err) goto ipc_error; return 0; ipc_error: dev_err(tsdev->dev, "ipc error during %s\n", __func__); return err; } static void mrstouch_report_event(struct input_dev *input, unsigned int x, unsigned int y, unsigned int z) { if (z > MRST_PRESSURE_NOMINAL) { /* Pen touched, report button touch and coordinates */ input_report_key(input, BTN_TOUCH, 1); input_report_abs(input, ABS_X, x); input_report_abs(input, ABS_Y, y); } else { input_report_key(input, BTN_TOUCH, 0); } input_report_abs(input, ABS_PRESSURE, z); input_sync(input); } /* PENDET interrupt handler */ static irqreturn_t mrstouch_pendet_irq(int irq, void *dev_id) { struct mrstouch_dev *tsdev = dev_id; u16 x, y, z; /* * Should we lower thread priority? Probably not, since we are * not spinning but sleeping... */ if (tsdev->read_prepare(tsdev)) goto out; do { if (tsdev->read(tsdev, &x, &y, &z)) break; mrstouch_report_event(tsdev->input, x, y, z); } while (z > MRST_PRESSURE_NOMINAL); tsdev->read_finish(tsdev); out: return IRQ_HANDLED; } /* Utility to read PMIC ID */ static int mrstouch_read_pmic_id(uint *vendor, uint *rev) { int err; u8 r; err = intel_scu_ipc_ioread8(PMIC_REG_ID1, &r); if (err) return err; *vendor = r & 0x7; *rev = (r >> 3) & 0x7; return 0; } /* * Parse ADC channels to find end of the channel configured by other ADC user * NEC and MAXIM requires 4 channels and FreeScale needs 18 channels */ static int mrstouch_chan_parse(struct mrstouch_dev *tsdev) { int found = 0; int err, i; u8 r8; for (i = 0; i < MRSTOUCH_MAX_CHANNELS; i++) { err = intel_scu_ipc_ioread8(PMICADDR0 + i, &r8); if (err) return err; if (r8 == END_OF_CHANNEL) { found = i; break; } } if (tsdev->vendor == PMIC_VENDOR_FS) { if (found > MRSTOUCH_MAX_CHANNELS - 18) return -ENOSPC; } else { if (found > MRSTOUCH_MAX_CHANNELS - 4) return -ENOSPC; } return found; } /* * Writes touch screen channels to ADC address selection registers */ static int mrstouch_ts_chan_set(uint offset) { u16 chan; int ret, count; chan = PMICADDR0 + offset; for (count = 0; count <= 3; count++) { ret = intel_scu_ipc_iowrite8(chan++, MRST_TS_CHAN10 + count); if (ret) return ret; } return intel_scu_ipc_iowrite8(chan++, END_OF_CHANNEL); } /* Initialize ADC */ static int mrstouch_adc_init(struct mrstouch_dev *tsdev) { int err, start; u8 ra, rm; err = mrstouch_read_pmic_id(&tsdev->vendor, &tsdev->rev); if (err) { dev_err(tsdev->dev, "Unable to read PMIC id\n"); return err; } switch (tsdev->vendor) { case PMIC_VENDOR_NEC: case PMIC_VENDOR_MAXIM: tsdev->read_prepare = mrstouch_nec_adc_read_prepare; tsdev->read = mrstouch_nec_adc_read; tsdev->read_finish = mrstouch_nec_adc_read_finish; break; case PMIC_VENDOR_FS: tsdev->read_prepare = mrstouch_fs_adc_read_prepare; tsdev->read = mrstouch_fs_adc_read; tsdev->read_finish = mrstouch_fs_adc_read_finish; break; default: dev_err(tsdev->dev, "Unsupported touchscreen: %d\n", tsdev->vendor); return -ENXIO; } start = mrstouch_chan_parse(tsdev); if (start < 0) { dev_err(tsdev->dev, "Unable to parse channels\n"); return start; } tsdev->asr = start; /* * ADC power on, start, enable PENDET and set loop delay * ADC loop delay is set to 4.5 ms approximately * Loop delay more than this results in jitter in adc readings * Setting loop delay to 0 (continuous loop) in MAXIM stops PENDET * interrupt generation sometimes. */ if (tsdev->vendor == PMIC_VENDOR_FS) { ra = 0xE0 | ADC_LOOP_DELAY0; rm = 0x5; } else { /* NEC and MAXIm not consistent with loop delay 0 */ ra = 0xE0 | ADC_LOOP_DELAY1; rm = 0x0; /* configure touch screen channels */ err = mrstouch_ts_chan_set(tsdev->asr); if (err) return err; } err = intel_scu_ipc_update_register(PMIC_REG_ADCCNTL1, ra, 0xE7); if (err) return err; err = intel_scu_ipc_update_register(PMIC_REG_MADCINT, rm, 0x03); if (err) return err; return 0; } /* Probe function for touch screen driver */ static int mrstouch_probe(struct platform_device *pdev) { struct mrstouch_dev *tsdev; struct input_dev *input; int err; int irq; irq = platform_get_irq(pdev, 0); if (irq < 0) { dev_err(&pdev->dev, "no interrupt assigned\n"); return -EINVAL; } tsdev = devm_kzalloc(&pdev->dev, sizeof(struct mrstouch_dev), GFP_KERNEL); if (!tsdev) { dev_err(&pdev->dev, "unable to allocate memory\n"); return -ENOMEM; } input = devm_input_allocate_device(&pdev->dev); if (!input) { dev_err(&pdev->dev, "unable to allocate input device\n"); return -ENOMEM; } tsdev->dev = &pdev->dev; tsdev->input = input; tsdev->irq = irq; snprintf(tsdev->phys, sizeof(tsdev->phys), "%s/input0", dev_name(tsdev->dev)); err = mrstouch_adc_init(tsdev); if (err) { dev_err(&pdev->dev, "ADC initialization failed\n"); return err; } input->name = "mrst_touchscreen"; input->phys = tsdev->phys; input->dev.parent = tsdev->dev; input->id.vendor = tsdev->vendor; input->id.version = tsdev->rev; input->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS); input->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH); input_set_abs_params(tsdev->input, ABS_X, MRST_X_MIN, MRST_X_MAX, MRST_X_FUZZ, 0); input_set_abs_params(tsdev->input, ABS_Y, MRST_Y_MIN, MRST_Y_MAX, MRST_Y_FUZZ, 0); input_set_abs_params(tsdev->input, ABS_PRESSURE, MRST_PRESSURE_MIN, MRST_PRESSURE_MAX, 0, 0); err = devm_request_threaded_irq(&pdev->dev, tsdev->irq, NULL, mrstouch_pendet_irq, IRQF_ONESHOT, "mrstouch", tsdev); if (err) { dev_err(tsdev->dev, "unable to allocate irq\n"); return err; } err = input_register_device(tsdev->input); if (err) { dev_err(tsdev->dev, "unable to register input device\n"); return err; } return 0; } static struct platform_driver mrstouch_driver = { .driver = { .name = "pmic_touch", }, .probe = mrstouch_probe, }; module_platform_driver(mrstouch_driver); MODULE_AUTHOR("Sreedhara Murthy. D.S, sreedhara.ds@intel.com"); MODULE_DESCRIPTION("Intel Moorestown Resistive Touch Screen Driver"); MODULE_LICENSE("GPL");
heukelum/linux
drivers/input/touchscreen/intel-mid-touch.c
C
gpl-2.0
15,084
/* * arizona-spi.c -- Arizona SPI bus interface * * Copyright 2012 Wolfson Microelectronics plc * * Author: Mark Brown <broonie@opensource.wolfsonmicro.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/err.h> #include <linux/module.h> #include <linux/pm_runtime.h> #include <linux/regmap.h> #include <linux/regulator/consumer.h> #include <linux/slab.h> #include <linux/spi/spi.h> #include <linux/mfd/arizona/core.h> #include "arizona.h" static int arizona_spi_probe(struct spi_device *spi) { const struct spi_device_id *id = spi_get_device_id(spi); struct arizona *arizona; const struct regmap_config *regmap_config; int ret; switch (id->driver_data) { #ifdef CONFIG_MFD_WM5102 case WM5102: regmap_config = &wm5102_spi_regmap; break; #endif #ifdef CONFIG_MFD_WM5110 case WM5110: regmap_config = &wm5110_spi_regmap; break; #endif default: dev_err(&spi->dev, "Unknown device type %ld\n", id->driver_data); return -EINVAL; } arizona = devm_kzalloc(&spi->dev, sizeof(*arizona), GFP_KERNEL); if (arizona == NULL) return -ENOMEM; arizona->regmap = devm_regmap_init_spi(spi, regmap_config); if (IS_ERR(arizona->regmap)) { ret = PTR_ERR(arizona->regmap); dev_err(&spi->dev, "Failed to allocate register map: %d\n", ret); return ret; } arizona->type = id->driver_data; arizona->dev = &spi->dev; arizona->irq = spi->irq; return arizona_dev_init(arizona); } static int arizona_spi_remove(struct spi_device *spi) { struct arizona *arizona = spi_get_drvdata(spi); arizona_dev_exit(arizona); return 0; } static const struct spi_device_id arizona_spi_ids[] = { { "wm5102", WM5102 }, { "wm5110", WM5110 }, { }, }; MODULE_DEVICE_TABLE(spi, arizona_spi_ids); static struct spi_driver arizona_spi_driver = { .driver = { .name = "arizona", .owner = THIS_MODULE, .pm = &arizona_pm_ops, }, .probe = arizona_spi_probe, .remove = arizona_spi_remove, .id_table = arizona_spi_ids, }; module_spi_driver(arizona_spi_driver); MODULE_DESCRIPTION("Arizona SPI bus interface"); MODULE_AUTHOR("Mark Brown <broonie@opensource.wolfsonmicro.com>"); MODULE_LICENSE("GPL");
h113331pp/kernel-3.10.17
drivers/mfd/arizona-spi.c
C
gpl-2.0
2,285
/* * This file is part of wl18xx * * Copyright (C) 2011 Texas Instruments Inc. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * */ #include "../wlcore/wlcore.h" #include "../wlcore/cmd.h" #include "../wlcore/debug.h" #include "../wlcore/acx.h" #include "../wlcore/tx.h" #include "wl18xx.h" #include "tx.h" static void wl18xx_get_last_tx_rate(struct wl1271 *wl, struct ieee80211_vif *vif, u8 band, struct ieee80211_tx_rate *rate) { u8 fw_rate = wl->fw_status->counters.tx_last_rate; if (fw_rate > CONF_HW_RATE_INDEX_MAX) { wl1271_error("last Tx rate invalid: %d", fw_rate); rate->idx = 0; rate->flags = 0; return; } if (fw_rate <= CONF_HW_RATE_INDEX_54MBPS) { rate->idx = fw_rate; if (band == IEEE80211_BAND_5GHZ) rate->idx -= CONF_HW_RATE_INDEX_6MBPS; rate->flags = 0; } else { rate->flags = IEEE80211_TX_RC_MCS; rate->idx = fw_rate - CONF_HW_RATE_INDEX_MCS0; /* SGI modifier is counted as a separate rate */ if (fw_rate >= CONF_HW_RATE_INDEX_MCS7_SGI) (rate->idx)--; if (fw_rate == CONF_HW_RATE_INDEX_MCS15_SGI) (rate->idx)--; /* this also covers the 40Mhz SGI case (= MCS15) */ if (fw_rate == CONF_HW_RATE_INDEX_MCS7_SGI || fw_rate == CONF_HW_RATE_INDEX_MCS15_SGI) rate->flags |= IEEE80211_TX_RC_SHORT_GI; if (fw_rate > CONF_HW_RATE_INDEX_MCS7_SGI && vif) { struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); if (wlvif->channel_type == NL80211_CHAN_HT40MINUS || wlvif->channel_type == NL80211_CHAN_HT40PLUS) { /* adjustment needed for range 0-7 */ rate->idx -= 8; rate->flags |= IEEE80211_TX_RC_40_MHZ_WIDTH; } } } } static void wl18xx_tx_complete_packet(struct wl1271 *wl, u8 tx_stat_byte) { struct ieee80211_tx_info *info; struct sk_buff *skb; int id = tx_stat_byte & WL18XX_TX_STATUS_DESC_ID_MASK; bool tx_success; /* check for id legality */ if (unlikely(id >= wl->num_tx_desc || wl->tx_frames[id] == NULL)) { wl1271_warning("illegal id in tx completion: %d", id); return; } /* a zero bit indicates Tx success */ tx_success = !(tx_stat_byte & BIT(WL18XX_TX_STATUS_STAT_BIT_IDX)); skb = wl->tx_frames[id]; info = IEEE80211_SKB_CB(skb); if (wl12xx_is_dummy_packet(wl, skb)) { wl1271_free_tx_id(wl, id); return; } /* update the TX status info */ if (tx_success && !(info->flags & IEEE80211_TX_CTL_NO_ACK)) info->flags |= IEEE80211_TX_STAT_ACK; /* * first pass info->control.vif while it's valid, and then fill out * the info->status structures */ wl18xx_get_last_tx_rate(wl, info->control.vif, info->band, &info->status.rates[0]); info->status.rates[0].count = 1; /* no data about retries */ info->status.ack_signal = -1; if (!tx_success) wl->stats.retry_count++; /* * TODO: update sequence number for encryption? seems to be * unsupported for now. needed for recovery with encryption. */ /* remove private header from packet */ skb_pull(skb, sizeof(struct wl1271_tx_hw_descr)); /* remove TKIP header space if present */ if ((wl->quirks & WLCORE_QUIRK_TKIP_HEADER_SPACE) && info->control.hw_key && info->control.hw_key->cipher == WLAN_CIPHER_SUITE_TKIP) { int hdrlen = ieee80211_get_hdrlen_from_skb(skb); memmove(skb->data + WL1271_EXTRA_SPACE_TKIP, skb->data, hdrlen); skb_pull(skb, WL1271_EXTRA_SPACE_TKIP); } wl1271_debug(DEBUG_TX, "tx status id %u skb 0x%p success %d", id, skb, tx_success); /* return the packet to the stack */ skb_queue_tail(&wl->deferred_tx_queue, skb); queue_work(wl->freezable_wq, &wl->netstack_work); wl1271_free_tx_id(wl, id); } void wl18xx_tx_immediate_complete(struct wl1271 *wl) { struct wl18xx_fw_status_priv *status_priv = (struct wl18xx_fw_status_priv *)wl->fw_status->priv; struct wl18xx_priv *priv = wl->priv; u8 i; /* nothing to do here */ if (priv->last_fw_rls_idx == status_priv->fw_release_idx) return; /* freed Tx descriptors */ wl1271_debug(DEBUG_TX, "last released desc = %d, current idx = %d", priv->last_fw_rls_idx, status_priv->fw_release_idx); if (status_priv->fw_release_idx >= WL18XX_FW_MAX_TX_STATUS_DESC) { wl1271_error("invalid desc release index %d", status_priv->fw_release_idx); WARN_ON(1); return; } for (i = priv->last_fw_rls_idx; i != status_priv->fw_release_idx; i = (i + 1) % WL18XX_FW_MAX_TX_STATUS_DESC) { wl18xx_tx_complete_packet(wl, status_priv->released_tx_desc[i]); wl->tx_results_count++; } priv->last_fw_rls_idx = status_priv->fw_release_idx; }
Alucard24/Alucard-Kernel-LG-G5
drivers/net/wireless/ti/wl18xx/tx.c
C
gpl-2.0
5,087
/* * su.c: Small serial driver for keyboard/mouse interface on sparc32/PCI * * Copyright (C) 1997 Eddie C. Dost (ecd@skynet.be) * Copyright (C) 1998-1999 Pete Zaitcev (zaitcev@yahoo.com) * * This is mainly a variation of 8250.c, credits go to authors mentioned * therein. In fact this driver should be merged into the generic 8250.c * infrastructure perhaps using a 8250_sparc.c module. * * Fixed to use tty_get_baud_rate(). * Theodore Ts'o <tytso@mit.edu>, 2001-Oct-12 * * Converted to new 2.5.x UART layer. * David S. Miller (davem@davemloft.net), 2002-Jul-29 */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/spinlock.h> #include <linux/errno.h> #include <linux/tty.h> #include <linux/tty_flip.h> #include <linux/major.h> #include <linux/string.h> #include <linux/ptrace.h> #include <linux/ioport.h> #include <linux/circ_buf.h> #include <linux/serial.h> #include <linux/sysrq.h> #include <linux/console.h> #include <linux/slab.h> #ifdef CONFIG_SERIO #include <linux/serio.h> #endif #include <linux/serial_reg.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/of_device.h> #include <asm/io.h> #include <asm/irq.h> #include <asm/prom.h> #include <asm/setup.h> #if defined(CONFIG_SERIAL_SUNSU_CONSOLE) && defined(CONFIG_MAGIC_SYSRQ) #define SUPPORT_SYSRQ #endif #include <linux/serial_core.h> #include <linux/sunserialcore.h> /* We are on a NS PC87303 clocked with 24.0 MHz, which results * in a UART clock of 1.8462 MHz. */ #define SU_BASE_BAUD (1846200 / 16) enum su_type { SU_PORT_NONE, SU_PORT_MS, SU_PORT_KBD, SU_PORT_PORT }; static char *su_typev[] = { "su(???)", "su(mouse)", "su(kbd)", "su(serial)" }; struct serial_uart_config { char *name; int dfl_xmit_fifo_size; int flags; }; /* * Here we define the default xmit fifo size used for each type of UART. */ static const struct serial_uart_config uart_config[] = { { "unknown", 1, 0 }, { "8250", 1, 0 }, { "16450", 1, 0 }, { "16550", 1, 0 }, { "16550A", 16, UART_CLEAR_FIFO | UART_USE_FIFO }, { "Cirrus", 1, 0 }, { "ST16650", 1, UART_CLEAR_FIFO | UART_STARTECH }, { "ST16650V2", 32, UART_CLEAR_FIFO | UART_USE_FIFO | UART_STARTECH }, { "TI16750", 64, UART_CLEAR_FIFO | UART_USE_FIFO }, { "Startech", 1, 0 }, { "16C950/954", 128, UART_CLEAR_FIFO | UART_USE_FIFO }, { "ST16654", 64, UART_CLEAR_FIFO | UART_USE_FIFO | UART_STARTECH }, { "XR16850", 128, UART_CLEAR_FIFO | UART_USE_FIFO | UART_STARTECH }, { "RSA", 2048, UART_CLEAR_FIFO | UART_USE_FIFO } }; struct uart_sunsu_port { struct uart_port port; unsigned char acr; unsigned char ier; unsigned short rev; unsigned char lcr; unsigned int lsr_break_flag; unsigned int cflag; /* Probing information. */ enum su_type su_type; unsigned int type_probed; /* XXX Stupid */ unsigned long reg_size; #ifdef CONFIG_SERIO struct serio serio; int serio_open; #endif }; static unsigned int serial_in(struct uart_sunsu_port *up, int offset) { offset <<= up->port.regshift; switch (up->port.iotype) { case UPIO_HUB6: outb(up->port.hub6 - 1 + offset, up->port.iobase); return inb(up->port.iobase + 1); case UPIO_MEM: return readb(up->port.membase + offset); default: return inb(up->port.iobase + offset); } } static void serial_out(struct uart_sunsu_port *up, int offset, int value) { #ifndef CONFIG_SPARC64 /* * MrCoffee has weird schematics: IRQ4 & P10(?) pins of SuperIO are * connected with a gate then go to SlavIO. When IRQ4 goes tristated * gate outputs a logical one. Since we use level triggered interrupts * we have lockup and watchdog reset. We cannot mask IRQ because * keyboard shares IRQ with us (Word has it as Bob Smelik's design). * This problem is similar to what Alpha people suffer, see serial.c. */ if (offset == UART_MCR) value |= UART_MCR_OUT2; #endif offset <<= up->port.regshift; switch (up->port.iotype) { case UPIO_HUB6: outb(up->port.hub6 - 1 + offset, up->port.iobase); outb(value, up->port.iobase + 1); break; case UPIO_MEM: writeb(value, up->port.membase + offset); break; default: outb(value, up->port.iobase + offset); } } /* * We used to support using pause I/O for certain machines. We * haven't supported this for a while, but just in case it's badly * needed for certain old 386 machines, I've left these #define's * in.... */ #define serial_inp(up, offset) serial_in(up, offset) #define serial_outp(up, offset, value) serial_out(up, offset, value) /* * For the 16C950 */ static void serial_icr_write(struct uart_sunsu_port *up, int offset, int value) { serial_out(up, UART_SCR, offset); serial_out(up, UART_ICR, value); } #if 0 /* Unused currently */ static unsigned int serial_icr_read(struct uart_sunsu_port *up, int offset) { unsigned int value; serial_icr_write(up, UART_ACR, up->acr | UART_ACR_ICRRD); serial_out(up, UART_SCR, offset); value = serial_in(up, UART_ICR); serial_icr_write(up, UART_ACR, up->acr); return value; } #endif #ifdef CONFIG_SERIAL_8250_RSA /* * Attempts to turn on the RSA FIFO. Returns zero on failure. * We set the port uart clock rate if we succeed. */ static int __enable_rsa(struct uart_sunsu_port *up) { unsigned char mode; int result; mode = serial_inp(up, UART_RSA_MSR); result = mode & UART_RSA_MSR_FIFO; if (!result) { serial_outp(up, UART_RSA_MSR, mode | UART_RSA_MSR_FIFO); mode = serial_inp(up, UART_RSA_MSR); result = mode & UART_RSA_MSR_FIFO; } if (result) up->port.uartclk = SERIAL_RSA_BAUD_BASE * 16; return result; } static void enable_rsa(struct uart_sunsu_port *up) { if (up->port.type == PORT_RSA) { if (up->port.uartclk != SERIAL_RSA_BAUD_BASE * 16) { spin_lock_irq(&up->port.lock); __enable_rsa(up); spin_unlock_irq(&up->port.lock); } if (up->port.uartclk == SERIAL_RSA_BAUD_BASE * 16) serial_outp(up, UART_RSA_FRR, 0); } } /* * Attempts to turn off the RSA FIFO. Returns zero on failure. * It is unknown why interrupts were disabled in here. However, * the caller is expected to preserve this behaviour by grabbing * the spinlock before calling this function. */ static void disable_rsa(struct uart_sunsu_port *up) { unsigned char mode; int result; if (up->port.type == PORT_RSA && up->port.uartclk == SERIAL_RSA_BAUD_BASE * 16) { spin_lock_irq(&up->port.lock); mode = serial_inp(up, UART_RSA_MSR); result = !(mode & UART_RSA_MSR_FIFO); if (!result) { serial_outp(up, UART_RSA_MSR, mode & ~UART_RSA_MSR_FIFO); mode = serial_inp(up, UART_RSA_MSR); result = !(mode & UART_RSA_MSR_FIFO); } if (result) up->port.uartclk = SERIAL_RSA_BAUD_BASE_LO * 16; spin_unlock_irq(&up->port.lock); } } #endif /* CONFIG_SERIAL_8250_RSA */ static inline void __stop_tx(struct uart_sunsu_port *p) { if (p->ier & UART_IER_THRI) { p->ier &= ~UART_IER_THRI; serial_out(p, UART_IER, p->ier); } } static void sunsu_stop_tx(struct uart_port *port) { struct uart_sunsu_port *up = (struct uart_sunsu_port *) port; __stop_tx(up); /* * We really want to stop the transmitter from sending. */ if (up->port.type == PORT_16C950) { up->acr |= UART_ACR_TXDIS; serial_icr_write(up, UART_ACR, up->acr); } } static void sunsu_start_tx(struct uart_port *port) { struct uart_sunsu_port *up = (struct uart_sunsu_port *) port; if (!(up->ier & UART_IER_THRI)) { up->ier |= UART_IER_THRI; serial_out(up, UART_IER, up->ier); } /* * Re-enable the transmitter if we disabled it. */ if (up->port.type == PORT_16C950 && up->acr & UART_ACR_TXDIS) { up->acr &= ~UART_ACR_TXDIS; serial_icr_write(up, UART_ACR, up->acr); } } static void sunsu_stop_rx(struct uart_port *port) { struct uart_sunsu_port *up = (struct uart_sunsu_port *) port; up->ier &= ~UART_IER_RLSI; up->port.read_status_mask &= ~UART_LSR_DR; serial_out(up, UART_IER, up->ier); } static void sunsu_enable_ms(struct uart_port *port) { struct uart_sunsu_port *up = (struct uart_sunsu_port *) port; unsigned long flags; spin_lock_irqsave(&up->port.lock, flags); up->ier |= UART_IER_MSI; serial_out(up, UART_IER, up->ier); spin_unlock_irqrestore(&up->port.lock, flags); } static void receive_chars(struct uart_sunsu_port *up, unsigned char *status) { struct tty_port *port = &up->port.state->port; unsigned char ch, flag; int max_count = 256; int saw_console_brk = 0; do { ch = serial_inp(up, UART_RX); flag = TTY_NORMAL; up->port.icount.rx++; if (unlikely(*status & (UART_LSR_BI | UART_LSR_PE | UART_LSR_FE | UART_LSR_OE))) { /* * For statistics only */ if (*status & UART_LSR_BI) { *status &= ~(UART_LSR_FE | UART_LSR_PE); up->port.icount.brk++; if (up->port.cons != NULL && up->port.line == up->port.cons->index) saw_console_brk = 1; /* * We do the SysRQ and SAK checking * here because otherwise the break * may get masked by ignore_status_mask * or read_status_mask. */ if (uart_handle_break(&up->port)) goto ignore_char; } else if (*status & UART_LSR_PE) up->port.icount.parity++; else if (*status & UART_LSR_FE) up->port.icount.frame++; if (*status & UART_LSR_OE) up->port.icount.overrun++; /* * Mask off conditions which should be ingored. */ *status &= up->port.read_status_mask; if (up->port.cons != NULL && up->port.line == up->port.cons->index) { /* Recover the break flag from console xmit */ *status |= up->lsr_break_flag; up->lsr_break_flag = 0; } if (*status & UART_LSR_BI) { flag = TTY_BREAK; } else if (*status & UART_LSR_PE) flag = TTY_PARITY; else if (*status & UART_LSR_FE) flag = TTY_FRAME; } if (uart_handle_sysrq_char(&up->port, ch)) goto ignore_char; if ((*status & up->port.ignore_status_mask) == 0) tty_insert_flip_char(port, ch, flag); if (*status & UART_LSR_OE) /* * Overrun is special, since it's reported * immediately, and doesn't affect the current * character. */ tty_insert_flip_char(port, 0, TTY_OVERRUN); ignore_char: *status = serial_inp(up, UART_LSR); } while ((*status & UART_LSR_DR) && (max_count-- > 0)); if (saw_console_brk) sun_do_break(); } static void transmit_chars(struct uart_sunsu_port *up) { struct circ_buf *xmit = &up->port.state->xmit; int count; if (up->port.x_char) { serial_outp(up, UART_TX, up->port.x_char); up->port.icount.tx++; up->port.x_char = 0; return; } if (uart_tx_stopped(&up->port)) { sunsu_stop_tx(&up->port); return; } if (uart_circ_empty(xmit)) { __stop_tx(up); return; } count = up->port.fifosize; do { serial_out(up, UART_TX, xmit->buf[xmit->tail]); xmit->tail = (xmit->tail + 1) & (UART_XMIT_SIZE - 1); up->port.icount.tx++; if (uart_circ_empty(xmit)) break; } while (--count > 0); if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS) uart_write_wakeup(&up->port); if (uart_circ_empty(xmit)) __stop_tx(up); } static void check_modem_status(struct uart_sunsu_port *up) { int status; status = serial_in(up, UART_MSR); if ((status & UART_MSR_ANY_DELTA) == 0) return; if (status & UART_MSR_TERI) up->port.icount.rng++; if (status & UART_MSR_DDSR) up->port.icount.dsr++; if (status & UART_MSR_DDCD) uart_handle_dcd_change(&up->port, status & UART_MSR_DCD); if (status & UART_MSR_DCTS) uart_handle_cts_change(&up->port, status & UART_MSR_CTS); wake_up_interruptible(&up->port.state->port.delta_msr_wait); } static irqreturn_t sunsu_serial_interrupt(int irq, void *dev_id) { struct uart_sunsu_port *up = dev_id; unsigned long flags; unsigned char status; spin_lock_irqsave(&up->port.lock, flags); do { status = serial_inp(up, UART_LSR); if (status & UART_LSR_DR) receive_chars(up, &status); check_modem_status(up); if (status & UART_LSR_THRE) transmit_chars(up); spin_unlock_irqrestore(&up->port.lock, flags); tty_flip_buffer_push(&up->port.state->port); spin_lock_irqsave(&up->port.lock, flags); } while (!(serial_in(up, UART_IIR) & UART_IIR_NO_INT)); spin_unlock_irqrestore(&up->port.lock, flags); return IRQ_HANDLED; } /* Separate interrupt handling path for keyboard/mouse ports. */ static void sunsu_change_speed(struct uart_port *port, unsigned int cflag, unsigned int iflag, unsigned int quot); static void sunsu_change_mouse_baud(struct uart_sunsu_port *up) { unsigned int cur_cflag = up->cflag; int quot, new_baud; up->cflag &= ~CBAUD; up->cflag |= suncore_mouse_baud_cflag_next(cur_cflag, &new_baud); quot = up->port.uartclk / (16 * new_baud); sunsu_change_speed(&up->port, up->cflag, 0, quot); } static void receive_kbd_ms_chars(struct uart_sunsu_port *up, int is_break) { do { unsigned char ch = serial_inp(up, UART_RX); /* Stop-A is handled by drivers/char/keyboard.c now. */ if (up->su_type == SU_PORT_KBD) { #ifdef CONFIG_SERIO serio_interrupt(&up->serio, ch, 0); #endif } else if (up->su_type == SU_PORT_MS) { int ret = suncore_mouse_baud_detection(ch, is_break); switch (ret) { case 2: sunsu_change_mouse_baud(up); /* fallthru */ case 1: break; case 0: #ifdef CONFIG_SERIO serio_interrupt(&up->serio, ch, 0); #endif break; }; } } while (serial_in(up, UART_LSR) & UART_LSR_DR); } static irqreturn_t sunsu_kbd_ms_interrupt(int irq, void *dev_id) { struct uart_sunsu_port *up = dev_id; if (!(serial_in(up, UART_IIR) & UART_IIR_NO_INT)) { unsigned char status = serial_inp(up, UART_LSR); if ((status & UART_LSR_DR) || (status & UART_LSR_BI)) receive_kbd_ms_chars(up, (status & UART_LSR_BI) != 0); } return IRQ_HANDLED; } static unsigned int sunsu_tx_empty(struct uart_port *port) { struct uart_sunsu_port *up = (struct uart_sunsu_port *) port; unsigned long flags; unsigned int ret; spin_lock_irqsave(&up->port.lock, flags); ret = serial_in(up, UART_LSR) & UART_LSR_TEMT ? TIOCSER_TEMT : 0; spin_unlock_irqrestore(&up->port.lock, flags); return ret; } static unsigned int sunsu_get_mctrl(struct uart_port *port) { struct uart_sunsu_port *up = (struct uart_sunsu_port *) port; unsigned char status; unsigned int ret; status = serial_in(up, UART_MSR); ret = 0; if (status & UART_MSR_DCD) ret |= TIOCM_CAR; if (status & UART_MSR_RI) ret |= TIOCM_RNG; if (status & UART_MSR_DSR) ret |= TIOCM_DSR; if (status & UART_MSR_CTS) ret |= TIOCM_CTS; return ret; } static void sunsu_set_mctrl(struct uart_port *port, unsigned int mctrl) { struct uart_sunsu_port *up = (struct uart_sunsu_port *) port; unsigned char mcr = 0; if (mctrl & TIOCM_RTS) mcr |= UART_MCR_RTS; if (mctrl & TIOCM_DTR) mcr |= UART_MCR_DTR; if (mctrl & TIOCM_OUT1) mcr |= UART_MCR_OUT1; if (mctrl & TIOCM_OUT2) mcr |= UART_MCR_OUT2; if (mctrl & TIOCM_LOOP) mcr |= UART_MCR_LOOP; serial_out(up, UART_MCR, mcr); } static void sunsu_break_ctl(struct uart_port *port, int break_state) { struct uart_sunsu_port *up = (struct uart_sunsu_port *) port; unsigned long flags; spin_lock_irqsave(&up->port.lock, flags); if (break_state == -1) up->lcr |= UART_LCR_SBC; else up->lcr &= ~UART_LCR_SBC; serial_out(up, UART_LCR, up->lcr); spin_unlock_irqrestore(&up->port.lock, flags); } static int sunsu_startup(struct uart_port *port) { struct uart_sunsu_port *up = (struct uart_sunsu_port *) port; unsigned long flags; int retval; if (up->port.type == PORT_16C950) { /* Wake up and initialize UART */ up->acr = 0; serial_outp(up, UART_LCR, 0xBF); serial_outp(up, UART_EFR, UART_EFR_ECB); serial_outp(up, UART_IER, 0); serial_outp(up, UART_LCR, 0); serial_icr_write(up, UART_CSR, 0); /* Reset the UART */ serial_outp(up, UART_LCR, 0xBF); serial_outp(up, UART_EFR, UART_EFR_ECB); serial_outp(up, UART_LCR, 0); } #ifdef CONFIG_SERIAL_8250_RSA /* * If this is an RSA port, see if we can kick it up to the * higher speed clock. */ enable_rsa(up); #endif /* * Clear the FIFO buffers and disable them. * (they will be reenabled in set_termios()) */ if (uart_config[up->port.type].flags & UART_CLEAR_FIFO) { serial_outp(up, UART_FCR, UART_FCR_ENABLE_FIFO); serial_outp(up, UART_FCR, UART_FCR_ENABLE_FIFO | UART_FCR_CLEAR_RCVR | UART_FCR_CLEAR_XMIT); serial_outp(up, UART_FCR, 0); } /* * Clear the interrupt registers. */ (void) serial_inp(up, UART_LSR); (void) serial_inp(up, UART_RX); (void) serial_inp(up, UART_IIR); (void) serial_inp(up, UART_MSR); /* * At this point, there's no way the LSR could still be 0xff; * if it is, then bail out, because there's likely no UART * here. */ if (!(up->port.flags & UPF_BUGGY_UART) && (serial_inp(up, UART_LSR) == 0xff)) { printk("ttyS%d: LSR safety check engaged!\n", up->port.line); return -ENODEV; } if (up->su_type != SU_PORT_PORT) { retval = request_irq(up->port.irq, sunsu_kbd_ms_interrupt, IRQF_SHARED, su_typev[up->su_type], up); } else { retval = request_irq(up->port.irq, sunsu_serial_interrupt, IRQF_SHARED, su_typev[up->su_type], up); } if (retval) { printk("su: Cannot register IRQ %d\n", up->port.irq); return retval; } /* * Now, initialize the UART */ serial_outp(up, UART_LCR, UART_LCR_WLEN8); spin_lock_irqsave(&up->port.lock, flags); up->port.mctrl |= TIOCM_OUT2; sunsu_set_mctrl(&up->port, up->port.mctrl); spin_unlock_irqrestore(&up->port.lock, flags); /* * Finally, enable interrupts. Note: Modem status interrupts * are set via set_termios(), which will be occurring imminently * anyway, so we don't enable them here. */ up->ier = UART_IER_RLSI | UART_IER_RDI; serial_outp(up, UART_IER, up->ier); if (up->port.flags & UPF_FOURPORT) { unsigned int icp; /* * Enable interrupts on the AST Fourport board */ icp = (up->port.iobase & 0xfe0) | 0x01f; outb_p(0x80, icp); (void) inb_p(icp); } /* * And clear the interrupt registers again for luck. */ (void) serial_inp(up, UART_LSR); (void) serial_inp(up, UART_RX); (void) serial_inp(up, UART_IIR); (void) serial_inp(up, UART_MSR); return 0; } static void sunsu_shutdown(struct uart_port *port) { struct uart_sunsu_port *up = (struct uart_sunsu_port *) port; unsigned long flags; /* * Disable interrupts from this port */ up->ier = 0; serial_outp(up, UART_IER, 0); spin_lock_irqsave(&up->port.lock, flags); if (up->port.flags & UPF_FOURPORT) { /* reset interrupts on the AST Fourport board */ inb((up->port.iobase & 0xfe0) | 0x1f); up->port.mctrl |= TIOCM_OUT1; } else up->port.mctrl &= ~TIOCM_OUT2; sunsu_set_mctrl(&up->port, up->port.mctrl); spin_unlock_irqrestore(&up->port.lock, flags); /* * Disable break condition and FIFOs */ serial_out(up, UART_LCR, serial_inp(up, UART_LCR) & ~UART_LCR_SBC); serial_outp(up, UART_FCR, UART_FCR_ENABLE_FIFO | UART_FCR_CLEAR_RCVR | UART_FCR_CLEAR_XMIT); serial_outp(up, UART_FCR, 0); #ifdef CONFIG_SERIAL_8250_RSA /* * Reset the RSA board back to 115kbps compat mode. */ disable_rsa(up); #endif /* * Read data port to reset things. */ (void) serial_in(up, UART_RX); free_irq(up->port.irq, up); } static void sunsu_change_speed(struct uart_port *port, unsigned int cflag, unsigned int iflag, unsigned int quot) { struct uart_sunsu_port *up = (struct uart_sunsu_port *) port; unsigned char cval, fcr = 0; unsigned long flags; switch (cflag & CSIZE) { case CS5: cval = 0x00; break; case CS6: cval = 0x01; break; case CS7: cval = 0x02; break; default: case CS8: cval = 0x03; break; } if (cflag & CSTOPB) cval |= 0x04; if (cflag & PARENB) cval |= UART_LCR_PARITY; if (!(cflag & PARODD)) cval |= UART_LCR_EPAR; #ifdef CMSPAR if (cflag & CMSPAR) cval |= UART_LCR_SPAR; #endif /* * Work around a bug in the Oxford Semiconductor 952 rev B * chip which causes it to seriously miscalculate baud rates * when DLL is 0. */ if ((quot & 0xff) == 0 && up->port.type == PORT_16C950 && up->rev == 0x5201) quot ++; if (uart_config[up->port.type].flags & UART_USE_FIFO) { if ((up->port.uartclk / quot) < (2400 * 16)) fcr = UART_FCR_ENABLE_FIFO | UART_FCR_TRIGGER_1; #ifdef CONFIG_SERIAL_8250_RSA else if (up->port.type == PORT_RSA) fcr = UART_FCR_ENABLE_FIFO | UART_FCR_TRIGGER_14; #endif else fcr = UART_FCR_ENABLE_FIFO | UART_FCR_TRIGGER_8; } if (up->port.type == PORT_16750) fcr |= UART_FCR7_64BYTE; /* * Ok, we're now changing the port state. Do it with * interrupts disabled. */ spin_lock_irqsave(&up->port.lock, flags); /* * Update the per-port timeout. */ uart_update_timeout(port, cflag, (port->uartclk / (16 * quot))); up->port.read_status_mask = UART_LSR_OE | UART_LSR_THRE | UART_LSR_DR; if (iflag & INPCK) up->port.read_status_mask |= UART_LSR_FE | UART_LSR_PE; if (iflag & (BRKINT | PARMRK)) up->port.read_status_mask |= UART_LSR_BI; /* * Characteres to ignore */ up->port.ignore_status_mask = 0; if (iflag & IGNPAR) up->port.ignore_status_mask |= UART_LSR_PE | UART_LSR_FE; if (iflag & IGNBRK) { up->port.ignore_status_mask |= UART_LSR_BI; /* * If we're ignoring parity and break indicators, * ignore overruns too (for real raw support). */ if (iflag & IGNPAR) up->port.ignore_status_mask |= UART_LSR_OE; } /* * ignore all characters if CREAD is not set */ if ((cflag & CREAD) == 0) up->port.ignore_status_mask |= UART_LSR_DR; /* * CTS flow control flag and modem status interrupts */ up->ier &= ~UART_IER_MSI; if (UART_ENABLE_MS(&up->port, cflag)) up->ier |= UART_IER_MSI; serial_out(up, UART_IER, up->ier); if (uart_config[up->port.type].flags & UART_STARTECH) { serial_outp(up, UART_LCR, 0xBF); serial_outp(up, UART_EFR, cflag & CRTSCTS ? UART_EFR_CTS :0); } serial_outp(up, UART_LCR, cval | UART_LCR_DLAB);/* set DLAB */ serial_outp(up, UART_DLL, quot & 0xff); /* LS of divisor */ serial_outp(up, UART_DLM, quot >> 8); /* MS of divisor */ if (up->port.type == PORT_16750) serial_outp(up, UART_FCR, fcr); /* set fcr */ serial_outp(up, UART_LCR, cval); /* reset DLAB */ up->lcr = cval; /* Save LCR */ if (up->port.type != PORT_16750) { if (fcr & UART_FCR_ENABLE_FIFO) { /* emulated UARTs (Lucent Venus 167x) need two steps */ serial_outp(up, UART_FCR, UART_FCR_ENABLE_FIFO); } serial_outp(up, UART_FCR, fcr); /* set fcr */ } up->cflag = cflag; spin_unlock_irqrestore(&up->port.lock, flags); } static void sunsu_set_termios(struct uart_port *port, struct ktermios *termios, struct ktermios *old) { unsigned int baud, quot; /* * Ask the core to calculate the divisor for us. */ baud = uart_get_baud_rate(port, termios, old, 0, port->uartclk/16); quot = uart_get_divisor(port, baud); sunsu_change_speed(port, termios->c_cflag, termios->c_iflag, quot); } static void sunsu_release_port(struct uart_port *port) { } static int sunsu_request_port(struct uart_port *port) { return 0; } static void sunsu_config_port(struct uart_port *port, int flags) { struct uart_sunsu_port *up = (struct uart_sunsu_port *) port; if (flags & UART_CONFIG_TYPE) { /* * We are supposed to call autoconfig here, but this requires * splitting all the OBP probing crap from the UART probing. * We'll do it when we kill sunsu.c altogether. */ port->type = up->type_probed; /* XXX */ } } static int sunsu_verify_port(struct uart_port *port, struct serial_struct *ser) { return -EINVAL; } static const char * sunsu_type(struct uart_port *port) { int type = port->type; if (type >= ARRAY_SIZE(uart_config)) type = 0; return uart_config[type].name; } static struct uart_ops sunsu_pops = { .tx_empty = sunsu_tx_empty, .set_mctrl = sunsu_set_mctrl, .get_mctrl = sunsu_get_mctrl, .stop_tx = sunsu_stop_tx, .start_tx = sunsu_start_tx, .stop_rx = sunsu_stop_rx, .enable_ms = sunsu_enable_ms, .break_ctl = sunsu_break_ctl, .startup = sunsu_startup, .shutdown = sunsu_shutdown, .set_termios = sunsu_set_termios, .type = sunsu_type, .release_port = sunsu_release_port, .request_port = sunsu_request_port, .config_port = sunsu_config_port, .verify_port = sunsu_verify_port, }; #define UART_NR 4 static struct uart_sunsu_port sunsu_ports[UART_NR]; static int nr_inst; /* Number of already registered ports */ #ifdef CONFIG_SERIO static DEFINE_SPINLOCK(sunsu_serio_lock); static int sunsu_serio_write(struct serio *serio, unsigned char ch) { struct uart_sunsu_port *up = serio->port_data; unsigned long flags; int lsr; spin_lock_irqsave(&sunsu_serio_lock, flags); do { lsr = serial_in(up, UART_LSR); } while (!(lsr & UART_LSR_THRE)); /* Send the character out. */ serial_out(up, UART_TX, ch); spin_unlock_irqrestore(&sunsu_serio_lock, flags); return 0; } static int sunsu_serio_open(struct serio *serio) { struct uart_sunsu_port *up = serio->port_data; unsigned long flags; int ret; spin_lock_irqsave(&sunsu_serio_lock, flags); if (!up->serio_open) { up->serio_open = 1; ret = 0; } else ret = -EBUSY; spin_unlock_irqrestore(&sunsu_serio_lock, flags); return ret; } static void sunsu_serio_close(struct serio *serio) { struct uart_sunsu_port *up = serio->port_data; unsigned long flags; spin_lock_irqsave(&sunsu_serio_lock, flags); up->serio_open = 0; spin_unlock_irqrestore(&sunsu_serio_lock, flags); } #endif /* CONFIG_SERIO */ static void sunsu_autoconfig(struct uart_sunsu_port *up) { unsigned char status1, status2, scratch, scratch2, scratch3; unsigned char save_lcr, save_mcr; unsigned long flags; if (up->su_type == SU_PORT_NONE) return; up->type_probed = PORT_UNKNOWN; up->port.iotype = UPIO_MEM; spin_lock_irqsave(&up->port.lock, flags); if (!(up->port.flags & UPF_BUGGY_UART)) { /* * Do a simple existence test first; if we fail this, there's * no point trying anything else. * * 0x80 is used as a nonsense port to prevent against false * positives due to ISA bus float. The assumption is that * 0x80 is a non-existent port; which should be safe since * include/asm/io.h also makes this assumption. */ scratch = serial_inp(up, UART_IER); serial_outp(up, UART_IER, 0); #ifdef __i386__ outb(0xff, 0x080); #endif scratch2 = serial_inp(up, UART_IER); serial_outp(up, UART_IER, 0x0f); #ifdef __i386__ outb(0, 0x080); #endif scratch3 = serial_inp(up, UART_IER); serial_outp(up, UART_IER, scratch); if (scratch2 != 0 || scratch3 != 0x0F) goto out; /* We failed; there's nothing here */ } save_mcr = serial_in(up, UART_MCR); save_lcr = serial_in(up, UART_LCR); /* * Check to see if a UART is really there. Certain broken * internal modems based on the Rockwell chipset fail this * test, because they apparently don't implement the loopback * test mode. So this test is skipped on the COM 1 through * COM 4 ports. This *should* be safe, since no board * manufacturer would be stupid enough to design a board * that conflicts with COM 1-4 --- we hope! */ if (!(up->port.flags & UPF_SKIP_TEST)) { serial_outp(up, UART_MCR, UART_MCR_LOOP | 0x0A); status1 = serial_inp(up, UART_MSR) & 0xF0; serial_outp(up, UART_MCR, save_mcr); if (status1 != 0x90) goto out; /* We failed loopback test */ } serial_outp(up, UART_LCR, 0xBF); /* set up for StarTech test */ serial_outp(up, UART_EFR, 0); /* EFR is the same as FCR */ serial_outp(up, UART_LCR, 0); serial_outp(up, UART_FCR, UART_FCR_ENABLE_FIFO); scratch = serial_in(up, UART_IIR) >> 6; switch (scratch) { case 0: up->port.type = PORT_16450; break; case 1: up->port.type = PORT_UNKNOWN; break; case 2: up->port.type = PORT_16550; break; case 3: up->port.type = PORT_16550A; break; } if (up->port.type == PORT_16550A) { /* Check for Startech UART's */ serial_outp(up, UART_LCR, UART_LCR_DLAB); if (serial_in(up, UART_EFR) == 0) { up->port.type = PORT_16650; } else { serial_outp(up, UART_LCR, 0xBF); if (serial_in(up, UART_EFR) == 0) up->port.type = PORT_16650V2; } } if (up->port.type == PORT_16550A) { /* Check for TI 16750 */ serial_outp(up, UART_LCR, save_lcr | UART_LCR_DLAB); serial_outp(up, UART_FCR, UART_FCR_ENABLE_FIFO | UART_FCR7_64BYTE); scratch = serial_in(up, UART_IIR) >> 5; if (scratch == 7) { /* * If this is a 16750, and not a cheap UART * clone, then it should only go into 64 byte * mode if the UART_FCR7_64BYTE bit was set * while UART_LCR_DLAB was latched. */ serial_outp(up, UART_FCR, UART_FCR_ENABLE_FIFO); serial_outp(up, UART_LCR, 0); serial_outp(up, UART_FCR, UART_FCR_ENABLE_FIFO | UART_FCR7_64BYTE); scratch = serial_in(up, UART_IIR) >> 5; if (scratch == 6) up->port.type = PORT_16750; } serial_outp(up, UART_FCR, UART_FCR_ENABLE_FIFO); } serial_outp(up, UART_LCR, save_lcr); if (up->port.type == PORT_16450) { scratch = serial_in(up, UART_SCR); serial_outp(up, UART_SCR, 0xa5); status1 = serial_in(up, UART_SCR); serial_outp(up, UART_SCR, 0x5a); status2 = serial_in(up, UART_SCR); serial_outp(up, UART_SCR, scratch); if ((status1 != 0xa5) || (status2 != 0x5a)) up->port.type = PORT_8250; } up->port.fifosize = uart_config[up->port.type].dfl_xmit_fifo_size; if (up->port.type == PORT_UNKNOWN) goto out; up->type_probed = up->port.type; /* XXX */ /* * Reset the UART. */ #ifdef CONFIG_SERIAL_8250_RSA if (up->port.type == PORT_RSA) serial_outp(up, UART_RSA_FRR, 0); #endif serial_outp(up, UART_MCR, save_mcr); serial_outp(up, UART_FCR, (UART_FCR_ENABLE_FIFO | UART_FCR_CLEAR_RCVR | UART_FCR_CLEAR_XMIT)); serial_outp(up, UART_FCR, 0); (void)serial_in(up, UART_RX); serial_outp(up, UART_IER, 0); out: spin_unlock_irqrestore(&up->port.lock, flags); } static struct uart_driver sunsu_reg = { .owner = THIS_MODULE, .driver_name = "sunsu", .dev_name = "ttyS", .major = TTY_MAJOR, }; static int sunsu_kbd_ms_init(struct uart_sunsu_port *up) { int quot, baud; #ifdef CONFIG_SERIO struct serio *serio; #endif if (up->su_type == SU_PORT_KBD) { up->cflag = B1200 | CS8 | CLOCAL | CREAD; baud = 1200; } else { up->cflag = B4800 | CS8 | CLOCAL | CREAD; baud = 4800; } quot = up->port.uartclk / (16 * baud); sunsu_autoconfig(up); if (up->port.type == PORT_UNKNOWN) return -ENODEV; printk("%s: %s port at %llx, irq %u\n", up->port.dev->of_node->full_name, (up->su_type == SU_PORT_KBD) ? "Keyboard" : "Mouse", (unsigned long long) up->port.mapbase, up->port.irq); #ifdef CONFIG_SERIO serio = &up->serio; serio->port_data = up; serio->id.type = SERIO_RS232; if (up->su_type == SU_PORT_KBD) { serio->id.proto = SERIO_SUNKBD; strlcpy(serio->name, "sukbd", sizeof(serio->name)); } else { serio->id.proto = SERIO_SUN; serio->id.extra = 1; strlcpy(serio->name, "sums", sizeof(serio->name)); } strlcpy(serio->phys, (!(up->port.line & 1) ? "su/serio0" : "su/serio1"), sizeof(serio->phys)); serio->write = sunsu_serio_write; serio->open = sunsu_serio_open; serio->close = sunsu_serio_close; serio->dev.parent = up->port.dev; serio_register_port(serio); #endif sunsu_change_speed(&up->port, up->cflag, 0, quot); sunsu_startup(&up->port); return 0; } /* * ------------------------------------------------------------ * Serial console driver * ------------------------------------------------------------ */ #ifdef CONFIG_SERIAL_SUNSU_CONSOLE #define BOTH_EMPTY (UART_LSR_TEMT | UART_LSR_THRE) /* * Wait for transmitter & holding register to empty */ static __inline__ void wait_for_xmitr(struct uart_sunsu_port *up) { unsigned int status, tmout = 10000; /* Wait up to 10ms for the character(s) to be sent. */ do { status = serial_in(up, UART_LSR); if (status & UART_LSR_BI) up->lsr_break_flag = UART_LSR_BI; if (--tmout == 0) break; udelay(1); } while ((status & BOTH_EMPTY) != BOTH_EMPTY); /* Wait up to 1s for flow control if necessary */ if (up->port.flags & UPF_CONS_FLOW) { tmout = 1000000; while (--tmout && ((serial_in(up, UART_MSR) & UART_MSR_CTS) == 0)) udelay(1); } } static void sunsu_console_putchar(struct uart_port *port, int ch) { struct uart_sunsu_port *up = (struct uart_sunsu_port *)port; wait_for_xmitr(up); serial_out(up, UART_TX, ch); } /* * Print a string to the serial port trying not to disturb * any possible real use of the port... */ static void sunsu_console_write(struct console *co, const char *s, unsigned int count) { struct uart_sunsu_port *up = &sunsu_ports[co->index]; unsigned long flags; unsigned int ier; int locked = 1; local_irq_save(flags); if (up->port.sysrq) { locked = 0; } else if (oops_in_progress) { locked = spin_trylock(&up->port.lock); } else spin_lock(&up->port.lock); /* * First save the UER then disable the interrupts */ ier = serial_in(up, UART_IER); serial_out(up, UART_IER, 0); uart_console_write(&up->port, s, count, sunsu_console_putchar); /* * Finally, wait for transmitter to become empty * and restore the IER */ wait_for_xmitr(up); serial_out(up, UART_IER, ier); if (locked) spin_unlock(&up->port.lock); local_irq_restore(flags); } /* * Setup initial baud/bits/parity. We do two things here: * - construct a cflag setting for the first su_open() * - initialize the serial port * Return non-zero if we didn't find a serial port. */ static int __init sunsu_console_setup(struct console *co, char *options) { static struct ktermios dummy; struct ktermios termios; struct uart_port *port; printk("Console: ttyS%d (SU)\n", (sunsu_reg.minor - 64) + co->index); if (co->index > nr_inst) return -ENODEV; port = &sunsu_ports[co->index].port; /* * Temporary fix. */ spin_lock_init(&port->lock); /* Get firmware console settings. */ sunserial_console_termios(co, port->dev->of_node); memset(&termios, 0, sizeof(struct ktermios)); termios.c_cflag = co->cflag; port->mctrl |= TIOCM_DTR; port->ops->set_termios(port, &termios, &dummy); return 0; } static struct console sunsu_console = { .name = "ttyS", .write = sunsu_console_write, .device = uart_console_device, .setup = sunsu_console_setup, .flags = CON_PRINTBUFFER, .index = -1, .data = &sunsu_reg, }; /* * Register console. */ static inline struct console *SUNSU_CONSOLE(void) { return &sunsu_console; } #else #define SUNSU_CONSOLE() (NULL) #define sunsu_serial_console_init() do { } while (0) #endif static enum su_type su_get_type(struct device_node *dp) { struct device_node *ap = of_find_node_by_path("/aliases"); if (ap) { const char *keyb = of_get_property(ap, "keyboard", NULL); const char *ms = of_get_property(ap, "mouse", NULL); if (keyb) { if (dp == of_find_node_by_path(keyb)) return SU_PORT_KBD; } if (ms) { if (dp == of_find_node_by_path(ms)) return SU_PORT_MS; } } return SU_PORT_PORT; } static int su_probe(struct platform_device *op) { struct device_node *dp = op->dev.of_node; struct uart_sunsu_port *up; struct resource *rp; enum su_type type; bool ignore_line; int err; type = su_get_type(dp); if (type == SU_PORT_PORT) { if (nr_inst >= UART_NR) return -EINVAL; up = &sunsu_ports[nr_inst]; } else { up = kzalloc(sizeof(*up), GFP_KERNEL); if (!up) return -ENOMEM; } up->port.line = nr_inst; spin_lock_init(&up->port.lock); up->su_type = type; rp = &op->resource[0]; up->port.mapbase = rp->start; up->reg_size = resource_size(rp); up->port.membase = of_ioremap(rp, 0, up->reg_size, "su"); if (!up->port.membase) { if (type != SU_PORT_PORT) kfree(up); return -ENOMEM; } up->port.irq = op->archdata.irqs[0]; up->port.dev = &op->dev; up->port.type = PORT_UNKNOWN; up->port.uartclk = (SU_BASE_BAUD * 16); err = 0; if (up->su_type == SU_PORT_KBD || up->su_type == SU_PORT_MS) { err = sunsu_kbd_ms_init(up); if (err) { of_iounmap(&op->resource[0], up->port.membase, up->reg_size); kfree(up); return err; } dev_set_drvdata(&op->dev, up); nr_inst++; return 0; } up->port.flags |= UPF_BOOT_AUTOCONF; sunsu_autoconfig(up); err = -ENODEV; if (up->port.type == PORT_UNKNOWN) goto out_unmap; up->port.ops = &sunsu_pops; ignore_line = false; if (!strcmp(dp->name, "rsc-console") || !strcmp(dp->name, "lom-console")) ignore_line = true; sunserial_console_match(SUNSU_CONSOLE(), dp, &sunsu_reg, up->port.line, ignore_line); err = uart_add_one_port(&sunsu_reg, &up->port); if (err) goto out_unmap; dev_set_drvdata(&op->dev, up); nr_inst++; return 0; out_unmap: of_iounmap(&op->resource[0], up->port.membase, up->reg_size); return err; } static int su_remove(struct platform_device *op) { struct uart_sunsu_port *up = dev_get_drvdata(&op->dev); bool kbdms = false; if (up->su_type == SU_PORT_MS || up->su_type == SU_PORT_KBD) kbdms = true; if (kbdms) { #ifdef CONFIG_SERIO serio_unregister_port(&up->serio); #endif } else if (up->port.type != PORT_UNKNOWN) uart_remove_one_port(&sunsu_reg, &up->port); if (up->port.membase) of_iounmap(&op->resource[0], up->port.membase, up->reg_size); if (kbdms) kfree(up); dev_set_drvdata(&op->dev, NULL); return 0; } static const struct of_device_id su_match[] = { { .name = "su", }, { .name = "su_pnp", }, { .name = "serial", .compatible = "su", }, { .type = "serial", .compatible = "su", }, {}, }; MODULE_DEVICE_TABLE(of, su_match); static struct platform_driver su_driver = { .driver = { .name = "su", .owner = THIS_MODULE, .of_match_table = su_match, }, .probe = su_probe, .remove = su_remove, }; static int __init sunsu_init(void) { struct device_node *dp; int err; int num_uart = 0; for_each_node_by_name(dp, "su") { if (su_get_type(dp) == SU_PORT_PORT) num_uart++; } for_each_node_by_name(dp, "su_pnp") { if (su_get_type(dp) == SU_PORT_PORT) num_uart++; } for_each_node_by_name(dp, "serial") { if (of_device_is_compatible(dp, "su")) { if (su_get_type(dp) == SU_PORT_PORT) num_uart++; } } for_each_node_by_type(dp, "serial") { if (of_device_is_compatible(dp, "su")) { if (su_get_type(dp) == SU_PORT_PORT) num_uart++; } } if (num_uart) { err = sunserial_register_minors(&sunsu_reg, num_uart); if (err) return err; } err = platform_driver_register(&su_driver); if (err && num_uart) sunserial_unregister_minors(&sunsu_reg, num_uart); return err; } static void __exit sunsu_exit(void) { platform_driver_unregister(&su_driver); if (sunsu_reg.nr) sunserial_unregister_minors(&sunsu_reg, sunsu_reg.nr); } module_init(sunsu_init); module_exit(sunsu_exit); MODULE_AUTHOR("Eddie C. Dost, Peter Zaitcev, and David S. Miller"); MODULE_DESCRIPTION("Sun SU serial port driver"); MODULE_VERSION("2.0"); MODULE_LICENSE("GPL");
tvall43/linux-stable
drivers/tty/serial/sunsu.c
C
gpl-2.0
38,681
/* * An implementation of key value pair (KVP) functionality for Linux. * * * Copyright (C) 2010, Novell, Inc. * Author : K. Y. Srinivasan <ksrinivasan@novell.com> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or * NON INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ #include <sys/types.h> #include <sys/socket.h> #include <sys/poll.h> #include <sys/utsname.h> #include <linux/types.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <arpa/inet.h> #include <linux/connector.h> #include <linux/netlink.h> #include <sys/socket.h> #include <ifaddrs.h> #include <netdb.h> #include <syslog.h> /* * KYS: TODO. Need to register these in the kernel. * * The following definitions are shared with the in-kernel component; do not * change any of this without making the corresponding changes in * the KVP kernel component. */ #define CN_KVP_IDX 0x9 /* MSFT KVP functionality */ #define CN_KVP_VAL 0x1 /* This supports queries from the kernel */ #define CN_KVP_USER_VAL 0x2 /* This supports queries from the user */ /* * KVP protocol: The user mode component first registers with the * the kernel component. Subsequently, the kernel component requests, data * for the specified keys. In response to this message the user mode component * fills in the value corresponding to the specified key. We overload the * sequence field in the cn_msg header to define our KVP message types. * * We use this infrastructure for also supporting queries from user mode * application for state that may be maintained in the KVP kernel component. * * XXXKYS: Have a shared header file between the user and kernel (TODO) */ enum kvp_op { KVP_REGISTER = 0, /* Register the user mode component*/ KVP_KERNEL_GET, /*Kernel is requesting the value for the specified key*/ KVP_KERNEL_SET, /*Kernel is providing the value for the specified key*/ KVP_USER_GET, /*User is requesting the value for the specified key*/ KVP_USER_SET /*User is providing the value for the specified key*/ }; #define HV_KVP_EXCHANGE_MAX_KEY_SIZE 512 #define HV_KVP_EXCHANGE_MAX_VALUE_SIZE 2048 struct hv_ku_msg { __u32 kvp_index; __u8 kvp_key[HV_KVP_EXCHANGE_MAX_KEY_SIZE]; /* Key name */ __u8 kvp_value[HV_KVP_EXCHANGE_MAX_VALUE_SIZE]; /* Key value */ }; enum key_index { FullyQualifiedDomainName = 0, IntegrationServicesVersion, /*This key is serviced in the kernel*/ NetworkAddressIPv4, NetworkAddressIPv6, OSBuildNumber, OSName, OSMajorVersion, OSMinorVersion, OSVersion, ProcessorArchitecture }; /* * End of shared definitions. */ static char kvp_send_buffer[4096]; static char kvp_recv_buffer[4096]; static struct sockaddr_nl addr; static char *os_name = ""; static char *os_major = ""; static char *os_minor = ""; static char *processor_arch; static char *os_build; static char *lic_version; static struct utsname uts_buf; void kvp_get_os_info(void) { FILE *file; char *p, buf[512]; uname(&uts_buf); os_build = uts_buf.release; processor_arch= uts_buf.machine; file = fopen("/etc/SuSE-release", "r"); if (file != NULL) goto kvp_osinfo_found; file = fopen("/etc/redhat-release", "r"); if (file != NULL) goto kvp_osinfo_found; /* * Add code for other supported platforms. */ /* * We don't have information about the os. */ os_name = uts_buf.sysname; return; kvp_osinfo_found: /* up to three lines */ p = fgets(buf, sizeof(buf), file); if (p) { p = strchr(buf, '\n'); if (p) *p = '\0'; p = strdup(buf); if (!p) goto done; os_name = p; /* second line */ p = fgets(buf, sizeof(buf), file); if (p) { p = strchr(buf, '\n'); if (p) *p = '\0'; p = strdup(buf); if (!p) goto done; os_major = p; /* third line */ p = fgets(buf, sizeof(buf), file); if (p) { p = strchr(buf, '\n'); if (p) *p = '\0'; p = strdup(buf); if (p) os_minor = p; } } } done: fclose(file); return; } static int kvp_get_ip_address(int family, char *buffer, int length) { struct ifaddrs *ifap; struct ifaddrs *curp; int ipv4_len = strlen("255.255.255.255") + 1; int ipv6_len = strlen("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")+1; int offset = 0; const char *str; char tmp[50]; int error = 0; /* * On entry into this function, the buffer is capable of holding the * maximum key value (2048 bytes). */ if (getifaddrs(&ifap)) { strcpy(buffer, "getifaddrs failed\n"); return 1; } curp = ifap; while (curp != NULL) { if ((curp->ifa_addr != NULL) && (curp->ifa_addr->sa_family == family)) { if (family == AF_INET) { struct sockaddr_in *addr = (struct sockaddr_in *) curp->ifa_addr; str = inet_ntop(family, &addr->sin_addr, tmp, 50); if (str == NULL) { strcpy(buffer, "inet_ntop failed\n"); error = 1; goto getaddr_done; } if (offset == 0) strcpy(buffer, tmp); else strcat(buffer, tmp); strcat(buffer, ";"); offset += strlen(str) + 1; if ((length - offset) < (ipv4_len + 1)) goto getaddr_done; } else { /* * We only support AF_INET and AF_INET6 * and the list of addresses is separated by a ";". */ struct sockaddr_in6 *addr = (struct sockaddr_in6 *) curp->ifa_addr; str = inet_ntop(family, &addr->sin6_addr.s6_addr, tmp, 50); if (str == NULL) { strcpy(buffer, "inet_ntop failed\n"); error = 1; goto getaddr_done; } if (offset == 0) strcpy(buffer, tmp); else strcat(buffer, tmp); strcat(buffer, ";"); offset += strlen(str) + 1; if ((length - offset) < (ipv6_len + 1)) goto getaddr_done; } } curp = curp->ifa_next; } getaddr_done: freeifaddrs(ifap); return error; } static int kvp_get_domain_name(char *buffer, int length) { struct addrinfo hints, *info ; gethostname(buffer, length); int error = 0; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; /*Get only ipv4 addrinfo. */ hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_CANONNAME; error = getaddrinfo(buffer, "http", &hints, &info); if (error != 0) { strcpy(buffer, "getaddrinfo failed\n"); error = 1; goto get_domain_done; } strcpy(buffer, info->ai_canonname); get_domain_done: freeaddrinfo(info); return error; } static int netlink_send(int fd, struct cn_msg *msg) { struct nlmsghdr *nlh; unsigned int size; struct msghdr message; char buffer[64]; struct iovec iov[2]; size = NLMSG_SPACE(sizeof(struct cn_msg) + msg->len); nlh = (struct nlmsghdr *)buffer; nlh->nlmsg_seq = 0; nlh->nlmsg_pid = getpid(); nlh->nlmsg_type = NLMSG_DONE; nlh->nlmsg_len = NLMSG_LENGTH(size - sizeof(*nlh)); nlh->nlmsg_flags = 0; iov[0].iov_base = nlh; iov[0].iov_len = sizeof(*nlh); iov[1].iov_base = msg; iov[1].iov_len = size; memset(&message, 0, sizeof(message)); message.msg_name = &addr; message.msg_namelen = sizeof(addr); message.msg_iov = iov; message.msg_iovlen = 2; return sendmsg(fd, &message, 0); } int main(void) { int fd, len, sock_opt; int error; struct cn_msg *message; struct pollfd pfd; struct nlmsghdr *incoming_msg; struct cn_msg *incoming_cn_msg; struct hv_ku_msg *hv_msg; char *p; char *key_value; char *key_name; daemon(1, 0); openlog("KVP", 0, LOG_USER); syslog(LOG_INFO, "KVP starting; pid is:%d", getpid()); /* * Retrieve OS release information. */ kvp_get_os_info(); fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR); if (fd < 0) { syslog(LOG_ERR, "netlink socket creation failed; error:%d", fd); exit(-1); } addr.nl_family = AF_NETLINK; addr.nl_pad = 0; addr.nl_pid = 0; addr.nl_groups = CN_KVP_IDX; error = bind(fd, (struct sockaddr *)&addr, sizeof(addr)); if (error < 0) { syslog(LOG_ERR, "bind failed; error:%d", error); close(fd); exit(-1); } sock_opt = addr.nl_groups; setsockopt(fd, 270, 1, &sock_opt, sizeof(sock_opt)); /* * Register ourselves with the kernel. */ message = (struct cn_msg *)kvp_send_buffer; message->id.idx = CN_KVP_IDX; message->id.val = CN_KVP_VAL; message->seq = KVP_REGISTER; message->ack = 0; message->len = 0; len = netlink_send(fd, message); if (len < 0) { syslog(LOG_ERR, "netlink_send failed; error:%d", len); close(fd); exit(-1); } pfd.fd = fd; while (1) { pfd.events = POLLIN; pfd.revents = 0; poll(&pfd, 1, -1); len = recv(fd, kvp_recv_buffer, sizeof(kvp_recv_buffer), 0); if (len < 0) { syslog(LOG_ERR, "recv failed; error:%d", len); close(fd); return -1; } incoming_msg = (struct nlmsghdr *)kvp_recv_buffer; incoming_cn_msg = (struct cn_msg *)NLMSG_DATA(incoming_msg); switch (incoming_cn_msg->seq) { case KVP_REGISTER: /* * Driver is registering with us; stash away the version * information. */ p = (char *)incoming_cn_msg->data; lic_version = malloc(strlen(p) + 1); if (lic_version) { strcpy(lic_version, p); syslog(LOG_INFO, "KVP LIC Version: %s", lic_version); } else { syslog(LOG_ERR, "malloc failed"); } continue; case KVP_KERNEL_GET: break; default: continue; } hv_msg = (struct hv_ku_msg *)incoming_cn_msg->data; key_name = (char *)hv_msg->kvp_key; key_value = (char *)hv_msg->kvp_value; switch (hv_msg->kvp_index) { case FullyQualifiedDomainName: kvp_get_domain_name(key_value, HV_KVP_EXCHANGE_MAX_VALUE_SIZE); strcpy(key_name, "FullyQualifiedDomainName"); break; case IntegrationServicesVersion: strcpy(key_name, "IntegrationServicesVersion"); strcpy(key_value, lic_version); break; case NetworkAddressIPv4: kvp_get_ip_address(AF_INET, key_value, HV_KVP_EXCHANGE_MAX_VALUE_SIZE); strcpy(key_name, "NetworkAddressIPv4"); break; case NetworkAddressIPv6: kvp_get_ip_address(AF_INET6, key_value, HV_KVP_EXCHANGE_MAX_VALUE_SIZE); strcpy(key_name, "NetworkAddressIPv6"); break; case OSBuildNumber: strcpy(key_value, os_build); strcpy(key_name, "OSBuildNumber"); break; case OSName: strcpy(key_value, os_name); strcpy(key_name, "OSName"); break; case OSMajorVersion: strcpy(key_value, os_major); strcpy(key_name, "OSMajorVersion"); break; case OSMinorVersion: strcpy(key_value, os_minor); strcpy(key_name, "OSMinorVersion"); break; case OSVersion: strcpy(key_value, os_build); strcpy(key_name, "OSVersion"); break; case ProcessorArchitecture: strcpy(key_value, processor_arch); strcpy(key_name, "ProcessorArchitecture"); break; default: strcpy(key_value, "Unknown Key"); /* * We use a null key name to terminate enumeration. */ strcpy(key_name, ""); break; } /* * Send the value back to the kernel. The response is * already in the receive buffer. Update the cn_msg header to * reflect the key value that has been added to the message */ incoming_cn_msg->id.idx = CN_KVP_IDX; incoming_cn_msg->id.val = CN_KVP_VAL; incoming_cn_msg->seq = KVP_USER_SET; incoming_cn_msg->ack = 0; incoming_cn_msg->len = sizeof(struct hv_ku_msg); len = netlink_send(fd, incoming_cn_msg); if (len < 0) { syslog(LOG_ERR, "net_link send failed; error:%d", len); exit(-1); } } }
lolhi/at1-Kernel
drivers/staging/hv/tools/hv_kvp_daemon.c
C
gpl-2.0
11,766
/* * xfrm4_policy.c * * Changes: * Kazunori MIYAZAWA @USAGI * YOSHIFUJI Hideaki @USAGI * Split up af-specific portion * */ #include <linux/err.h> #include <linux/kernel.h> #include <linux/inetdevice.h> #include <linux/if_tunnel.h> #include <net/dst.h> #include <net/xfrm.h> #include <net/ip.h> static struct xfrm_policy_afinfo xfrm4_policy_afinfo; static struct dst_entry *__xfrm4_dst_lookup(struct net *net, struct flowi4 *fl4, int tos, const xfrm_address_t *saddr, const xfrm_address_t *daddr) { struct rtable *rt; memset(fl4, 0, sizeof(*fl4)); fl4->daddr = daddr->a4; fl4->flowi4_tos = tos; if (saddr) fl4->saddr = saddr->a4; rt = __ip_route_output_key(net, fl4); if (!IS_ERR(rt)) return &rt->dst; return ERR_CAST(rt); } static struct dst_entry *xfrm4_dst_lookup(struct net *net, int tos, const xfrm_address_t *saddr, const xfrm_address_t *daddr) { struct flowi4 fl4; return __xfrm4_dst_lookup(net, &fl4, tos, saddr, daddr); } static int xfrm4_get_saddr(struct net *net, xfrm_address_t *saddr, xfrm_address_t *daddr) { struct dst_entry *dst; struct flowi4 fl4; dst = __xfrm4_dst_lookup(net, &fl4, 0, NULL, daddr); if (IS_ERR(dst)) return -EHOSTUNREACH; saddr->a4 = fl4.saddr; dst_release(dst); return 0; } static int xfrm4_get_tos(const struct flowi *fl) { return IPTOS_RT_MASK & fl->u.ip4.flowi4_tos; /* Strip ECN bits */ } static int xfrm4_init_path(struct xfrm_dst *path, struct dst_entry *dst, int nfheader_len) { return 0; } static int xfrm4_fill_dst(struct xfrm_dst *xdst, struct net_device *dev, const struct flowi *fl) { struct rtable *rt = (struct rtable *)xdst->route; const struct flowi4 *fl4 = &fl->u.ip4; xdst->u.rt.rt_key_dst = fl4->daddr; xdst->u.rt.rt_key_src = fl4->saddr; xdst->u.rt.rt_key_tos = fl4->flowi4_tos; xdst->u.rt.rt_route_iif = fl4->flowi4_iif; xdst->u.rt.rt_iif = fl4->flowi4_iif; xdst->u.rt.rt_oif = fl4->flowi4_oif; xdst->u.rt.rt_mark = fl4->flowi4_mark; xdst->u.rt.rt_uid = fl4->flowi4_uid; xdst->u.dst.dev = dev; dev_hold(dev); xdst->u.rt.peer = rt->peer; if (rt->peer) atomic_inc(&rt->peer->refcnt); /* Sheit... I remember I did this right. Apparently, * it was magically lost, so this code needs audit */ xdst->u.rt.rt_flags = rt->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST | RTCF_LOCAL); xdst->u.rt.rt_type = rt->rt_type; xdst->u.rt.rt_src = rt->rt_src; xdst->u.rt.rt_dst = rt->rt_dst; xdst->u.rt.rt_gateway = rt->rt_gateway; xdst->u.rt.rt_spec_dst = rt->rt_spec_dst; return 0; } static void _decode_session4(struct sk_buff *skb, struct flowi *fl, int reverse) { const struct iphdr *iph = ip_hdr(skb); u8 *xprth = skb_network_header(skb) + iph->ihl * 4; struct flowi4 *fl4 = &fl->u.ip4; memset(fl4, 0, sizeof(struct flowi4)); fl4->flowi4_mark = skb->mark; if (!ip_is_fragment(iph)) { switch (iph->protocol) { case IPPROTO_UDP: case IPPROTO_UDPLITE: case IPPROTO_TCP: case IPPROTO_SCTP: case IPPROTO_DCCP: if (xprth + 4 < skb->data || pskb_may_pull(skb, xprth + 4 - skb->data)) { __be16 *ports = (__be16 *)xprth; fl4->fl4_sport = ports[!!reverse]; fl4->fl4_dport = ports[!reverse]; } break; case IPPROTO_ICMP: if (pskb_may_pull(skb, xprth + 2 - skb->data)) { u8 *icmp = xprth; fl4->fl4_icmp_type = icmp[0]; fl4->fl4_icmp_code = icmp[1]; } break; case IPPROTO_ESP: if (pskb_may_pull(skb, xprth + 4 - skb->data)) { __be32 *ehdr = (__be32 *)xprth; fl4->fl4_ipsec_spi = ehdr[0]; } break; case IPPROTO_AH: if (pskb_may_pull(skb, xprth + 8 - skb->data)) { __be32 *ah_hdr = (__be32*)xprth; fl4->fl4_ipsec_spi = ah_hdr[1]; } break; case IPPROTO_COMP: if (pskb_may_pull(skb, xprth + 4 - skb->data)) { __be16 *ipcomp_hdr = (__be16 *)xprth; fl4->fl4_ipsec_spi = htonl(ntohs(ipcomp_hdr[1])); } break; case IPPROTO_GRE: if (pskb_may_pull(skb, xprth + 12 - skb->data)) { __be16 *greflags = (__be16 *)xprth; __be32 *gre_hdr = (__be32 *)xprth; if (greflags[0] & GRE_KEY) { if (greflags[0] & GRE_CSUM) gre_hdr++; fl4->fl4_gre_key = gre_hdr[1]; } } break; default: fl4->fl4_ipsec_spi = 0; break; } } fl4->flowi4_proto = iph->protocol; fl4->daddr = reverse ? iph->saddr : iph->daddr; fl4->saddr = reverse ? iph->daddr : iph->saddr; fl4->flowi4_tos = iph->tos; } static inline int xfrm4_garbage_collect(struct dst_ops *ops) { struct net *net = container_of(ops, struct net, xfrm.xfrm4_dst_ops); xfrm4_policy_afinfo.garbage_collect(net); return (dst_entries_get_slow(ops) > ops->gc_thresh * 2); } static void xfrm4_update_pmtu(struct dst_entry *dst, u32 mtu) { struct xfrm_dst *xdst = (struct xfrm_dst *)dst; struct dst_entry *path = xdst->route; path->ops->update_pmtu(path, mtu); } static void xfrm4_dst_destroy(struct dst_entry *dst) { struct xfrm_dst *xdst = (struct xfrm_dst *)dst; dst_destroy_metrics_generic(dst); if (likely(xdst->u.rt.peer)) inet_putpeer(xdst->u.rt.peer); xfrm_dst_destroy(xdst); } static void xfrm4_dst_ifdown(struct dst_entry *dst, struct net_device *dev, int unregister) { if (!unregister) return; xfrm_dst_ifdown(dst, dev); } static struct dst_ops xfrm4_dst_ops = { .family = AF_INET, .protocol = cpu_to_be16(ETH_P_IP), .gc = xfrm4_garbage_collect, .update_pmtu = xfrm4_update_pmtu, .cow_metrics = dst_cow_metrics_generic, .destroy = xfrm4_dst_destroy, .ifdown = xfrm4_dst_ifdown, .local_out = __ip_local_out, .gc_thresh = 1024, }; static struct xfrm_policy_afinfo xfrm4_policy_afinfo = { .family = AF_INET, .dst_ops = &xfrm4_dst_ops, .dst_lookup = xfrm4_dst_lookup, .get_saddr = xfrm4_get_saddr, .decode_session = _decode_session4, .get_tos = xfrm4_get_tos, .init_path = xfrm4_init_path, .fill_dst = xfrm4_fill_dst, .blackhole_route = ipv4_blackhole_route, }; #ifdef CONFIG_SYSCTL static struct ctl_table xfrm4_policy_table[] = { { .procname = "xfrm4_gc_thresh", .data = &init_net.xfrm.xfrm4_dst_ops.gc_thresh, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { } }; static struct ctl_table_header *sysctl_hdr; #endif static void __init xfrm4_policy_init(void) { xfrm_policy_register_afinfo(&xfrm4_policy_afinfo); } static void __exit xfrm4_policy_fini(void) { #ifdef CONFIG_SYSCTL if (sysctl_hdr) unregister_net_sysctl_table(sysctl_hdr); #endif xfrm_policy_unregister_afinfo(&xfrm4_policy_afinfo); } void __init xfrm4_init(int rt_max_size) { /* * Select a default value for the gc_thresh based on the main route * table hash size. It seems to me the worst case scenario is when * we have ipsec operating in transport mode, in which we create a * dst_entry per socket. The xfrm gc algorithm starts trying to remove * entries at gc_thresh, and prevents new allocations as 2*gc_thresh * so lets set an initial xfrm gc_thresh value at the rt_max_size/2. * That will let us store an ipsec connection per route table entry, * and start cleaning when were 1/2 full */ xfrm4_dst_ops.gc_thresh = rt_max_size/2; dst_entries_init(&xfrm4_dst_ops); xfrm4_state_init(); xfrm4_policy_init(); #ifdef CONFIG_SYSCTL sysctl_hdr = register_net_sysctl_table(&init_net, net_ipv4_ctl_path, xfrm4_policy_table); #endif }
xboxfanj/android_kernel_oneplus_one
net/ipv4/xfrm4_policy.c
C
gpl-2.0
7,382
/* * imx-pcm-dma-mx2.c -- ALSA Soc Audio Layer * * Copyright 2009 Sascha Hauer <s.hauer@pengutronix.de> * * This code is based on code copyrighted by Freescale, * Liam Girdwood, Javier Martin and probably others. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. */ #include <linux/platform_device.h> #include <linux/dmaengine.h> #include <linux/types.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/soc.h> #include <sound/dmaengine_pcm.h> #include "imx-pcm.h" static bool filter(struct dma_chan *chan, void *param) { struct snd_dmaengine_dai_dma_data *dma_data = param; if (!imx_dma_is_general_purpose(chan)) return false; chan->private = dma_data->filter_data; return true; } static const struct snd_pcm_hardware imx_pcm_hardware = { .info = SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_MMAP_VALID | SNDRV_PCM_INFO_PAUSE | SNDRV_PCM_INFO_RESUME, .formats = SNDRV_PCM_FMTBIT_S16_LE, .rate_min = 8000, .channels_min = 2, .channels_max = 2, .buffer_bytes_max = IMX_SSI_DMABUF_SIZE, .period_bytes_min = 128, .period_bytes_max = 65535, /* Limited by SDMA engine */ .periods_min = 2, .periods_max = 255, .fifo_size = 0, }; static const struct snd_dmaengine_pcm_config imx_dmaengine_pcm_config = { .pcm_hardware = &imx_pcm_hardware, .prepare_slave_config = snd_dmaengine_pcm_prepare_slave_config, .compat_filter_fn = filter, .prealloc_buffer_size = IMX_SSI_DMABUF_SIZE, }; int imx_pcm_dma_init(struct platform_device *pdev) { return snd_dmaengine_pcm_register(&pdev->dev, &imx_dmaengine_pcm_config, SND_DMAENGINE_PCM_FLAG_NO_RESIDUE | SND_DMAENGINE_PCM_FLAG_NO_DT | SND_DMAENGINE_PCM_FLAG_COMPAT); } void imx_pcm_dma_exit(struct platform_device *pdev) { snd_dmaengine_pcm_unregister(&pdev->dev); }
andrea2107/android_kernel_xiaomi_hermes
sound/soc/fsl/imx-pcm-dma.c
C
gpl-2.0
2,037
/* * Driver for * Maxim MAX16065/MAX16066 12-Channel/8-Channel, Flash-Configurable * System Managers with Nonvolatile Fault Registers * Maxim MAX16067/MAX16068 6-Channel, Flash-Configurable System Managers * with Nonvolatile Fault Registers * Maxim MAX16070/MAX16071 12-Channel/8-Channel, Flash-Configurable System * Monitors with Nonvolatile Fault Registers * * Copyright (C) 2011 Ericsson AB. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/err.h> #include <linux/slab.h> #include <linux/i2c.h> #include <linux/hwmon.h> #include <linux/hwmon-sysfs.h> #include <linux/jiffies.h> enum chips { max16065, max16066, max16067, max16068, max16070, max16071 }; /* * Registers */ #define MAX16065_ADC(x) ((x) * 2) #define MAX16065_CURR_SENSE 0x18 #define MAX16065_CSP_ADC 0x19 #define MAX16065_FAULT(x) (0x1b + (x)) #define MAX16065_SCALE(x) (0x43 + (x)) #define MAX16065_CURR_CONTROL 0x47 #define MAX16065_LIMIT(l, x) (0x48 + (l) + (x) * 3) /* * l: limit * 0: min/max * 1: crit * 2: lcrit * x: ADC index */ #define MAX16065_SW_ENABLE 0x73 #define MAX16065_WARNING_OV (1 << 3) /* Set if secondary threshold is OV warning */ #define MAX16065_CURR_ENABLE (1 << 0) #define MAX16065_NUM_LIMIT 3 #define MAX16065_NUM_ADC 12 /* maximum number of ADC channels */ static const int max16065_num_adc[] = { [max16065] = 12, [max16066] = 8, [max16067] = 6, [max16068] = 6, [max16070] = 12, [max16071] = 8, }; static const bool max16065_have_secondary[] = { [max16065] = true, [max16066] = true, [max16067] = false, [max16068] = false, [max16070] = true, [max16071] = true, }; static const bool max16065_have_current[] = { [max16065] = true, [max16066] = true, [max16067] = false, [max16068] = false, [max16070] = true, [max16071] = true, }; struct max16065_data { enum chips type; struct device *hwmon_dev; struct mutex update_lock; bool valid; unsigned long last_updated; /* in jiffies */ int num_adc; bool have_current; int curr_gain; /* limits are in mV */ int limit[MAX16065_NUM_LIMIT][MAX16065_NUM_ADC]; int range[MAX16065_NUM_ADC + 1];/* voltage range */ int adc[MAX16065_NUM_ADC + 1]; /* adc values (raw) including csp_adc */ int curr_sense; int fault[2]; }; static const int max16065_adc_range[] = { 5560, 2780, 1390, 0 }; static const int max16065_csp_adc_range[] = { 7000, 14000 }; /* ADC registers have 10 bit resolution. */ static inline int ADC_TO_MV(int adc, int range) { return (adc * range) / 1024; } /* * Limit registers have 8 bit resolution and match upper 8 bits of ADC * registers. */ static inline int LIMIT_TO_MV(int limit, int range) { return limit * range / 256; } static inline int MV_TO_LIMIT(int mv, int range) { return clamp_val(DIV_ROUND_CLOSEST(mv * 256, range), 0, 255); } static inline int ADC_TO_CURR(int adc, int gain) { return adc * 1400000 / (gain * 255); } /* * max16065_read_adc() * * Read 16 bit value from <reg>, <reg+1>. * Upper 8 bits are in <reg>, lower 2 bits are in bits 7:6 of <reg+1>. */ static int max16065_read_adc(struct i2c_client *client, int reg) { int rv; rv = i2c_smbus_read_word_swapped(client, reg); if (unlikely(rv < 0)) return rv; return rv >> 6; } static struct max16065_data *max16065_update_device(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct max16065_data *data = i2c_get_clientdata(client); mutex_lock(&data->update_lock); if (time_after(jiffies, data->last_updated + HZ) || !data->valid) { int i; for (i = 0; i < data->num_adc; i++) data->adc[i] = max16065_read_adc(client, MAX16065_ADC(i)); if (data->have_current) { data->adc[MAX16065_NUM_ADC] = max16065_read_adc(client, MAX16065_CSP_ADC); data->curr_sense = i2c_smbus_read_byte_data(client, MAX16065_CURR_SENSE); } for (i = 0; i < DIV_ROUND_UP(data->num_adc, 8); i++) data->fault[i] = i2c_smbus_read_byte_data(client, MAX16065_FAULT(i)); data->last_updated = jiffies; data->valid = 1; } mutex_unlock(&data->update_lock); return data; } static ssize_t max16065_show_alarm(struct device *dev, struct device_attribute *da, char *buf) { struct sensor_device_attribute_2 *attr2 = to_sensor_dev_attr_2(da); struct max16065_data *data = max16065_update_device(dev); int val = data->fault[attr2->nr]; if (val < 0) return val; val &= (1 << attr2->index); if (val) i2c_smbus_write_byte_data(to_i2c_client(dev), MAX16065_FAULT(attr2->nr), val); return snprintf(buf, PAGE_SIZE, "%d\n", !!val); } static ssize_t max16065_show_input(struct device *dev, struct device_attribute *da, char *buf) { struct sensor_device_attribute *attr = to_sensor_dev_attr(da); struct max16065_data *data = max16065_update_device(dev); int adc = data->adc[attr->index]; if (unlikely(adc < 0)) return adc; return snprintf(buf, PAGE_SIZE, "%d\n", ADC_TO_MV(adc, data->range[attr->index])); } static ssize_t max16065_show_current(struct device *dev, struct device_attribute *da, char *buf) { struct max16065_data *data = max16065_update_device(dev); if (unlikely(data->curr_sense < 0)) return data->curr_sense; return snprintf(buf, PAGE_SIZE, "%d\n", ADC_TO_CURR(data->curr_sense, data->curr_gain)); } static ssize_t max16065_set_limit(struct device *dev, struct device_attribute *da, const char *buf, size_t count) { struct sensor_device_attribute_2 *attr2 = to_sensor_dev_attr_2(da); struct i2c_client *client = to_i2c_client(dev); struct max16065_data *data = i2c_get_clientdata(client); unsigned long val; int err; int limit; err = kstrtoul(buf, 10, &val); if (unlikely(err < 0)) return err; limit = MV_TO_LIMIT(val, data->range[attr2->index]); mutex_lock(&data->update_lock); data->limit[attr2->nr][attr2->index] = LIMIT_TO_MV(limit, data->range[attr2->index]); i2c_smbus_write_byte_data(client, MAX16065_LIMIT(attr2->nr, attr2->index), limit); mutex_unlock(&data->update_lock); return count; } static ssize_t max16065_show_limit(struct device *dev, struct device_attribute *da, char *buf) { struct sensor_device_attribute_2 *attr2 = to_sensor_dev_attr_2(da); struct i2c_client *client = to_i2c_client(dev); struct max16065_data *data = i2c_get_clientdata(client); return snprintf(buf, PAGE_SIZE, "%d\n", data->limit[attr2->nr][attr2->index]); } /* Construct a sensor_device_attribute structure for each register */ /* Input voltages */ static SENSOR_DEVICE_ATTR(in0_input, S_IRUGO, max16065_show_input, NULL, 0); static SENSOR_DEVICE_ATTR(in1_input, S_IRUGO, max16065_show_input, NULL, 1); static SENSOR_DEVICE_ATTR(in2_input, S_IRUGO, max16065_show_input, NULL, 2); static SENSOR_DEVICE_ATTR(in3_input, S_IRUGO, max16065_show_input, NULL, 3); static SENSOR_DEVICE_ATTR(in4_input, S_IRUGO, max16065_show_input, NULL, 4); static SENSOR_DEVICE_ATTR(in5_input, S_IRUGO, max16065_show_input, NULL, 5); static SENSOR_DEVICE_ATTR(in6_input, S_IRUGO, max16065_show_input, NULL, 6); static SENSOR_DEVICE_ATTR(in7_input, S_IRUGO, max16065_show_input, NULL, 7); static SENSOR_DEVICE_ATTR(in8_input, S_IRUGO, max16065_show_input, NULL, 8); static SENSOR_DEVICE_ATTR(in9_input, S_IRUGO, max16065_show_input, NULL, 9); static SENSOR_DEVICE_ATTR(in10_input, S_IRUGO, max16065_show_input, NULL, 10); static SENSOR_DEVICE_ATTR(in11_input, S_IRUGO, max16065_show_input, NULL, 11); static SENSOR_DEVICE_ATTR(in12_input, S_IRUGO, max16065_show_input, NULL, 12); /* Input voltages lcrit */ static SENSOR_DEVICE_ATTR_2(in0_lcrit, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 2, 0); static SENSOR_DEVICE_ATTR_2(in1_lcrit, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 2, 1); static SENSOR_DEVICE_ATTR_2(in2_lcrit, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 2, 2); static SENSOR_DEVICE_ATTR_2(in3_lcrit, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 2, 3); static SENSOR_DEVICE_ATTR_2(in4_lcrit, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 2, 4); static SENSOR_DEVICE_ATTR_2(in5_lcrit, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 2, 5); static SENSOR_DEVICE_ATTR_2(in6_lcrit, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 2, 6); static SENSOR_DEVICE_ATTR_2(in7_lcrit, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 2, 7); static SENSOR_DEVICE_ATTR_2(in8_lcrit, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 2, 8); static SENSOR_DEVICE_ATTR_2(in9_lcrit, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 2, 9); static SENSOR_DEVICE_ATTR_2(in10_lcrit, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 2, 10); static SENSOR_DEVICE_ATTR_2(in11_lcrit, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 2, 11); /* Input voltages crit */ static SENSOR_DEVICE_ATTR_2(in0_crit, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 1, 0); static SENSOR_DEVICE_ATTR_2(in1_crit, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 1, 1); static SENSOR_DEVICE_ATTR_2(in2_crit, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 1, 2); static SENSOR_DEVICE_ATTR_2(in3_crit, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 1, 3); static SENSOR_DEVICE_ATTR_2(in4_crit, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 1, 4); static SENSOR_DEVICE_ATTR_2(in5_crit, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 1, 5); static SENSOR_DEVICE_ATTR_2(in6_crit, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 1, 6); static SENSOR_DEVICE_ATTR_2(in7_crit, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 1, 7); static SENSOR_DEVICE_ATTR_2(in8_crit, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 1, 8); static SENSOR_DEVICE_ATTR_2(in9_crit, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 1, 9); static SENSOR_DEVICE_ATTR_2(in10_crit, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 1, 10); static SENSOR_DEVICE_ATTR_2(in11_crit, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 1, 11); /* Input voltages min */ static SENSOR_DEVICE_ATTR_2(in0_min, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 0, 0); static SENSOR_DEVICE_ATTR_2(in1_min, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 0, 1); static SENSOR_DEVICE_ATTR_2(in2_min, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 0, 2); static SENSOR_DEVICE_ATTR_2(in3_min, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 0, 3); static SENSOR_DEVICE_ATTR_2(in4_min, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 0, 4); static SENSOR_DEVICE_ATTR_2(in5_min, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 0, 5); static SENSOR_DEVICE_ATTR_2(in6_min, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 0, 6); static SENSOR_DEVICE_ATTR_2(in7_min, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 0, 7); static SENSOR_DEVICE_ATTR_2(in8_min, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 0, 8); static SENSOR_DEVICE_ATTR_2(in9_min, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 0, 9); static SENSOR_DEVICE_ATTR_2(in10_min, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 0, 10); static SENSOR_DEVICE_ATTR_2(in11_min, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 0, 11); /* Input voltages max */ static SENSOR_DEVICE_ATTR_2(in0_max, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 0, 0); static SENSOR_DEVICE_ATTR_2(in1_max, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 0, 1); static SENSOR_DEVICE_ATTR_2(in2_max, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 0, 2); static SENSOR_DEVICE_ATTR_2(in3_max, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 0, 3); static SENSOR_DEVICE_ATTR_2(in4_max, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 0, 4); static SENSOR_DEVICE_ATTR_2(in5_max, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 0, 5); static SENSOR_DEVICE_ATTR_2(in6_max, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 0, 6); static SENSOR_DEVICE_ATTR_2(in7_max, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 0, 7); static SENSOR_DEVICE_ATTR_2(in8_max, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 0, 8); static SENSOR_DEVICE_ATTR_2(in9_max, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 0, 9); static SENSOR_DEVICE_ATTR_2(in10_max, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 0, 10); static SENSOR_DEVICE_ATTR_2(in11_max, S_IWUSR | S_IRUGO, max16065_show_limit, max16065_set_limit, 0, 11); /* alarms */ static SENSOR_DEVICE_ATTR_2(in0_alarm, S_IRUGO, max16065_show_alarm, NULL, 0, 0); static SENSOR_DEVICE_ATTR_2(in1_alarm, S_IRUGO, max16065_show_alarm, NULL, 0, 1); static SENSOR_DEVICE_ATTR_2(in2_alarm, S_IRUGO, max16065_show_alarm, NULL, 0, 2); static SENSOR_DEVICE_ATTR_2(in3_alarm, S_IRUGO, max16065_show_alarm, NULL, 0, 3); static SENSOR_DEVICE_ATTR_2(in4_alarm, S_IRUGO, max16065_show_alarm, NULL, 0, 4); static SENSOR_DEVICE_ATTR_2(in5_alarm, S_IRUGO, max16065_show_alarm, NULL, 0, 5); static SENSOR_DEVICE_ATTR_2(in6_alarm, S_IRUGO, max16065_show_alarm, NULL, 0, 6); static SENSOR_DEVICE_ATTR_2(in7_alarm, S_IRUGO, max16065_show_alarm, NULL, 0, 7); static SENSOR_DEVICE_ATTR_2(in8_alarm, S_IRUGO, max16065_show_alarm, NULL, 1, 0); static SENSOR_DEVICE_ATTR_2(in9_alarm, S_IRUGO, max16065_show_alarm, NULL, 1, 1); static SENSOR_DEVICE_ATTR_2(in10_alarm, S_IRUGO, max16065_show_alarm, NULL, 1, 2); static SENSOR_DEVICE_ATTR_2(in11_alarm, S_IRUGO, max16065_show_alarm, NULL, 1, 3); /* Current and alarm */ static SENSOR_DEVICE_ATTR(curr1_input, S_IRUGO, max16065_show_current, NULL, 0); static SENSOR_DEVICE_ATTR_2(curr1_alarm, S_IRUGO, max16065_show_alarm, NULL, 1, 4); /* * Finally, construct an array of pointers to members of the above objects, * as required for sysfs_create_group() */ static struct attribute *max16065_basic_attributes[] = { &sensor_dev_attr_in0_input.dev_attr.attr, &sensor_dev_attr_in0_lcrit.dev_attr.attr, &sensor_dev_attr_in0_crit.dev_attr.attr, &sensor_dev_attr_in0_alarm.dev_attr.attr, &sensor_dev_attr_in1_input.dev_attr.attr, &sensor_dev_attr_in1_lcrit.dev_attr.attr, &sensor_dev_attr_in1_crit.dev_attr.attr, &sensor_dev_attr_in1_alarm.dev_attr.attr, &sensor_dev_attr_in2_input.dev_attr.attr, &sensor_dev_attr_in2_lcrit.dev_attr.attr, &sensor_dev_attr_in2_crit.dev_attr.attr, &sensor_dev_attr_in2_alarm.dev_attr.attr, &sensor_dev_attr_in3_input.dev_attr.attr, &sensor_dev_attr_in3_lcrit.dev_attr.attr, &sensor_dev_attr_in3_crit.dev_attr.attr, &sensor_dev_attr_in3_alarm.dev_attr.attr, &sensor_dev_attr_in4_input.dev_attr.attr, &sensor_dev_attr_in4_lcrit.dev_attr.attr, &sensor_dev_attr_in4_crit.dev_attr.attr, &sensor_dev_attr_in4_alarm.dev_attr.attr, &sensor_dev_attr_in5_input.dev_attr.attr, &sensor_dev_attr_in5_lcrit.dev_attr.attr, &sensor_dev_attr_in5_crit.dev_attr.attr, &sensor_dev_attr_in5_alarm.dev_attr.attr, &sensor_dev_attr_in6_input.dev_attr.attr, &sensor_dev_attr_in6_lcrit.dev_attr.attr, &sensor_dev_attr_in6_crit.dev_attr.attr, &sensor_dev_attr_in6_alarm.dev_attr.attr, &sensor_dev_attr_in7_input.dev_attr.attr, &sensor_dev_attr_in7_lcrit.dev_attr.attr, &sensor_dev_attr_in7_crit.dev_attr.attr, &sensor_dev_attr_in7_alarm.dev_attr.attr, &sensor_dev_attr_in8_input.dev_attr.attr, &sensor_dev_attr_in8_lcrit.dev_attr.attr, &sensor_dev_attr_in8_crit.dev_attr.attr, &sensor_dev_attr_in8_alarm.dev_attr.attr, &sensor_dev_attr_in9_input.dev_attr.attr, &sensor_dev_attr_in9_lcrit.dev_attr.attr, &sensor_dev_attr_in9_crit.dev_attr.attr, &sensor_dev_attr_in9_alarm.dev_attr.attr, &sensor_dev_attr_in10_input.dev_attr.attr, &sensor_dev_attr_in10_lcrit.dev_attr.attr, &sensor_dev_attr_in10_crit.dev_attr.attr, &sensor_dev_attr_in10_alarm.dev_attr.attr, &sensor_dev_attr_in11_input.dev_attr.attr, &sensor_dev_attr_in11_lcrit.dev_attr.attr, &sensor_dev_attr_in11_crit.dev_attr.attr, &sensor_dev_attr_in11_alarm.dev_attr.attr, NULL }; static struct attribute *max16065_current_attributes[] = { &sensor_dev_attr_in12_input.dev_attr.attr, &sensor_dev_attr_curr1_input.dev_attr.attr, &sensor_dev_attr_curr1_alarm.dev_attr.attr, NULL }; static struct attribute *max16065_min_attributes[] = { &sensor_dev_attr_in0_min.dev_attr.attr, &sensor_dev_attr_in1_min.dev_attr.attr, &sensor_dev_attr_in2_min.dev_attr.attr, &sensor_dev_attr_in3_min.dev_attr.attr, &sensor_dev_attr_in4_min.dev_attr.attr, &sensor_dev_attr_in5_min.dev_attr.attr, &sensor_dev_attr_in6_min.dev_attr.attr, &sensor_dev_attr_in7_min.dev_attr.attr, &sensor_dev_attr_in8_min.dev_attr.attr, &sensor_dev_attr_in9_min.dev_attr.attr, &sensor_dev_attr_in10_min.dev_attr.attr, &sensor_dev_attr_in11_min.dev_attr.attr, NULL }; static struct attribute *max16065_max_attributes[] = { &sensor_dev_attr_in0_max.dev_attr.attr, &sensor_dev_attr_in1_max.dev_attr.attr, &sensor_dev_attr_in2_max.dev_attr.attr, &sensor_dev_attr_in3_max.dev_attr.attr, &sensor_dev_attr_in4_max.dev_attr.attr, &sensor_dev_attr_in5_max.dev_attr.attr, &sensor_dev_attr_in6_max.dev_attr.attr, &sensor_dev_attr_in7_max.dev_attr.attr, &sensor_dev_attr_in8_max.dev_attr.attr, &sensor_dev_attr_in9_max.dev_attr.attr, &sensor_dev_attr_in10_max.dev_attr.attr, &sensor_dev_attr_in11_max.dev_attr.attr, NULL }; static const struct attribute_group max16065_basic_group = { .attrs = max16065_basic_attributes, }; static const struct attribute_group max16065_current_group = { .attrs = max16065_current_attributes, }; static const struct attribute_group max16065_min_group = { .attrs = max16065_min_attributes, }; static const struct attribute_group max16065_max_group = { .attrs = max16065_max_attributes, }; static void max16065_cleanup(struct i2c_client *client) { sysfs_remove_group(&client->dev.kobj, &max16065_max_group); sysfs_remove_group(&client->dev.kobj, &max16065_min_group); sysfs_remove_group(&client->dev.kobj, &max16065_current_group); sysfs_remove_group(&client->dev.kobj, &max16065_basic_group); } static int max16065_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct i2c_adapter *adapter = client->adapter; struct max16065_data *data; int i, j, val, ret; bool have_secondary; /* true if chip has secondary limits */ bool secondary_is_max = false; /* secondary limits reflect max */ if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA | I2C_FUNC_SMBUS_READ_WORD_DATA)) return -ENODEV; data = devm_kzalloc(&client->dev, sizeof(*data), GFP_KERNEL); if (unlikely(!data)) return -ENOMEM; i2c_set_clientdata(client, data); mutex_init(&data->update_lock); data->num_adc = max16065_num_adc[id->driver_data]; data->have_current = max16065_have_current[id->driver_data]; have_secondary = max16065_have_secondary[id->driver_data]; if (have_secondary) { val = i2c_smbus_read_byte_data(client, MAX16065_SW_ENABLE); if (unlikely(val < 0)) return val; secondary_is_max = val & MAX16065_WARNING_OV; } /* Read scale registers, convert to range */ for (i = 0; i < DIV_ROUND_UP(data->num_adc, 4); i++) { val = i2c_smbus_read_byte_data(client, MAX16065_SCALE(i)); if (unlikely(val < 0)) return val; for (j = 0; j < 4 && i * 4 + j < data->num_adc; j++) { data->range[i * 4 + j] = max16065_adc_range[(val >> (j * 2)) & 0x3]; } } /* Read limits */ for (i = 0; i < MAX16065_NUM_LIMIT; i++) { if (i == 0 && !have_secondary) continue; for (j = 0; j < data->num_adc; j++) { val = i2c_smbus_read_byte_data(client, MAX16065_LIMIT(i, j)); if (unlikely(val < 0)) return val; data->limit[i][j] = LIMIT_TO_MV(val, data->range[j]); } } /* Register sysfs hooks */ for (i = 0; i < data->num_adc * 4; i++) { /* Do not create sysfs entry if channel is disabled */ if (!data->range[i / 4]) continue; ret = sysfs_create_file(&client->dev.kobj, max16065_basic_attributes[i]); if (unlikely(ret)) goto out; } if (have_secondary) { struct attribute **attr = secondary_is_max ? max16065_max_attributes : max16065_min_attributes; for (i = 0; i < data->num_adc; i++) { if (!data->range[i]) continue; ret = sysfs_create_file(&client->dev.kobj, attr[i]); if (unlikely(ret)) goto out; } } if (data->have_current) { val = i2c_smbus_read_byte_data(client, MAX16065_CURR_CONTROL); if (unlikely(val < 0)) { ret = val; goto out; } if (val & MAX16065_CURR_ENABLE) { /* * Current gain is 6, 12, 24, 48 based on values in * bit 2,3. */ data->curr_gain = 6 << ((val >> 2) & 0x03); data->range[MAX16065_NUM_ADC] = max16065_csp_adc_range[(val >> 1) & 0x01]; ret = sysfs_create_group(&client->dev.kobj, &max16065_current_group); if (unlikely(ret)) goto out; } else { data->have_current = false; } } data->hwmon_dev = hwmon_device_register(&client->dev); if (unlikely(IS_ERR(data->hwmon_dev))) { ret = PTR_ERR(data->hwmon_dev); goto out; } return 0; out: max16065_cleanup(client); return ret; } static int max16065_remove(struct i2c_client *client) { struct max16065_data *data = i2c_get_clientdata(client); hwmon_device_unregister(data->hwmon_dev); max16065_cleanup(client); return 0; } static const struct i2c_device_id max16065_id[] = { { "max16065", max16065 }, { "max16066", max16066 }, { "max16067", max16067 }, { "max16068", max16068 }, { "max16070", max16070 }, { "max16071", max16071 }, { } }; MODULE_DEVICE_TABLE(i2c, max16065_id); /* This is the driver that will be inserted */ static struct i2c_driver max16065_driver = { .driver = { .name = "max16065", }, .probe = max16065_probe, .remove = max16065_remove, .id_table = max16065_id, }; module_i2c_driver(max16065_driver); MODULE_AUTHOR("Guenter Roeck <linux@roeck-us.net>"); MODULE_DESCRIPTION("MAX16065 driver"); MODULE_LICENSE("GPL");
frenkowski/Tyrannus_Kernel_MM
drivers/hwmon/max16065.c
C
gpl-2.0
22,665
/* * net/sched/cls_flow.c Generic flow classifier * * Copyright (c) 2007, 2008 Patrick McHardy <kaber@trash.net> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/list.h> #include <linux/jhash.h> #include <linux/random.h> #include <linux/pkt_cls.h> #include <linux/skbuff.h> #include <linux/in.h> #include <linux/ip.h> #include <linux/ipv6.h> #include <linux/if_vlan.h> #include <linux/slab.h> #include <linux/module.h> #include <net/pkt_cls.h> #include <net/ip.h> #include <net/route.h> #include <net/flow_keys.h> #if defined(CONFIG_NF_CONNTRACK) || defined(CONFIG_NF_CONNTRACK_MODULE) #include <net/netfilter/nf_conntrack.h> #endif struct flow_head { struct list_head filters; }; struct flow_filter { struct list_head list; struct tcf_exts exts; struct tcf_ematch_tree ematches; struct timer_list perturb_timer; u32 perturb_period; u32 handle; u32 nkeys; u32 keymask; u32 mode; u32 mask; u32 xor; u32 rshift; u32 addend; u32 divisor; u32 baseclass; u32 hashrnd; }; static const struct tcf_ext_map flow_ext_map = { .action = TCA_FLOW_ACT, .police = TCA_FLOW_POLICE, }; static inline u32 addr_fold(void *addr) { unsigned long a = (unsigned long)addr; return (a & 0xFFFFFFFF) ^ (BITS_PER_LONG > 32 ? a >> 32 : 0); } static u32 flow_get_src(const struct sk_buff *skb, const struct flow_keys *flow) { if (flow->src) return ntohl(flow->src); return addr_fold(skb->sk); } static u32 flow_get_dst(const struct sk_buff *skb, const struct flow_keys *flow) { if (flow->dst) return ntohl(flow->dst); return addr_fold(skb_dst(skb)) ^ (__force u16)skb->protocol; } static u32 flow_get_proto(const struct sk_buff *skb, const struct flow_keys *flow) { return flow->ip_proto; } static u32 flow_get_proto_src(const struct sk_buff *skb, const struct flow_keys *flow) { if (flow->ports) return ntohs(flow->port16[0]); return addr_fold(skb->sk); } static u32 flow_get_proto_dst(const struct sk_buff *skb, const struct flow_keys *flow) { if (flow->ports) return ntohs(flow->port16[1]); return addr_fold(skb_dst(skb)) ^ (__force u16)skb->protocol; } static u32 flow_get_iif(const struct sk_buff *skb) { return skb->skb_iif; } static u32 flow_get_priority(const struct sk_buff *skb) { return skb->priority; } static u32 flow_get_mark(const struct sk_buff *skb) { return skb->mark; } static u32 flow_get_nfct(const struct sk_buff *skb) { #if defined(CONFIG_NF_CONNTRACK) || defined(CONFIG_NF_CONNTRACK_MODULE) return addr_fold(skb->nfct); #else return 0; #endif } #if defined(CONFIG_NF_CONNTRACK) || defined(CONFIG_NF_CONNTRACK_MODULE) #define CTTUPLE(skb, member) \ ({ \ enum ip_conntrack_info ctinfo; \ const struct nf_conn *ct = nf_ct_get(skb, &ctinfo); \ if (ct == NULL) \ goto fallback; \ ct->tuplehash[CTINFO2DIR(ctinfo)].tuple.member; \ }) #else #define CTTUPLE(skb, member) \ ({ \ goto fallback; \ 0; \ }) #endif static u32 flow_get_nfct_src(const struct sk_buff *skb, const struct flow_keys *flow) { switch (skb->protocol) { case htons(ETH_P_IP): return ntohl(CTTUPLE(skb, src.u3.ip)); case htons(ETH_P_IPV6): return ntohl(CTTUPLE(skb, src.u3.ip6[3])); } fallback: return flow_get_src(skb, flow); } static u32 flow_get_nfct_dst(const struct sk_buff *skb, const struct flow_keys *flow) { switch (skb->protocol) { case htons(ETH_P_IP): return ntohl(CTTUPLE(skb, dst.u3.ip)); case htons(ETH_P_IPV6): return ntohl(CTTUPLE(skb, dst.u3.ip6[3])); } fallback: return flow_get_dst(skb, flow); } static u32 flow_get_nfct_proto_src(const struct sk_buff *skb, const struct flow_keys *flow) { return ntohs(CTTUPLE(skb, src.u.all)); fallback: return flow_get_proto_src(skb, flow); } static u32 flow_get_nfct_proto_dst(const struct sk_buff *skb, const struct flow_keys *flow) { return ntohs(CTTUPLE(skb, dst.u.all)); fallback: return flow_get_proto_dst(skb, flow); } static u32 flow_get_rtclassid(const struct sk_buff *skb) { #ifdef CONFIG_IP_ROUTE_CLASSID if (skb_dst(skb)) return skb_dst(skb)->tclassid; #endif return 0; } static u32 flow_get_skuid(const struct sk_buff *skb) { if (skb->sk && skb->sk->sk_socket && skb->sk->sk_socket->file) { kuid_t skuid = skb->sk->sk_socket->file->f_cred->fsuid; return from_kuid(&init_user_ns, skuid); } return 0; } static u32 flow_get_skgid(const struct sk_buff *skb) { if (skb->sk && skb->sk->sk_socket && skb->sk->sk_socket->file) { kgid_t skgid = skb->sk->sk_socket->file->f_cred->fsgid; return from_kgid(&init_user_ns, skgid); } return 0; } static u32 flow_get_vlan_tag(const struct sk_buff *skb) { u16 uninitialized_var(tag); if (vlan_get_tag(skb, &tag) < 0) return 0; return tag & VLAN_VID_MASK; } static u32 flow_get_rxhash(struct sk_buff *skb) { return skb_get_rxhash(skb); } static u32 flow_key_get(struct sk_buff *skb, int key, struct flow_keys *flow) { switch (key) { case FLOW_KEY_SRC: return flow_get_src(skb, flow); case FLOW_KEY_DST: return flow_get_dst(skb, flow); case FLOW_KEY_PROTO: return flow_get_proto(skb, flow); case FLOW_KEY_PROTO_SRC: return flow_get_proto_src(skb, flow); case FLOW_KEY_PROTO_DST: return flow_get_proto_dst(skb, flow); case FLOW_KEY_IIF: return flow_get_iif(skb); case FLOW_KEY_PRIORITY: return flow_get_priority(skb); case FLOW_KEY_MARK: return flow_get_mark(skb); case FLOW_KEY_NFCT: return flow_get_nfct(skb); case FLOW_KEY_NFCT_SRC: return flow_get_nfct_src(skb, flow); case FLOW_KEY_NFCT_DST: return flow_get_nfct_dst(skb, flow); case FLOW_KEY_NFCT_PROTO_SRC: return flow_get_nfct_proto_src(skb, flow); case FLOW_KEY_NFCT_PROTO_DST: return flow_get_nfct_proto_dst(skb, flow); case FLOW_KEY_RTCLASSID: return flow_get_rtclassid(skb); case FLOW_KEY_SKUID: return flow_get_skuid(skb); case FLOW_KEY_SKGID: return flow_get_skgid(skb); case FLOW_KEY_VLAN_TAG: return flow_get_vlan_tag(skb); case FLOW_KEY_RXHASH: return flow_get_rxhash(skb); default: WARN_ON(1); return 0; } } #define FLOW_KEYS_NEEDED ((1 << FLOW_KEY_SRC) | \ (1 << FLOW_KEY_DST) | \ (1 << FLOW_KEY_PROTO) | \ (1 << FLOW_KEY_PROTO_SRC) | \ (1 << FLOW_KEY_PROTO_DST) | \ (1 << FLOW_KEY_NFCT_SRC) | \ (1 << FLOW_KEY_NFCT_DST) | \ (1 << FLOW_KEY_NFCT_PROTO_SRC) | \ (1 << FLOW_KEY_NFCT_PROTO_DST)) static int flow_classify(struct sk_buff *skb, const struct tcf_proto *tp, struct tcf_result *res) { struct flow_head *head = tp->root; struct flow_filter *f; u32 keymask; u32 classid; unsigned int n, key; int r; list_for_each_entry(f, &head->filters, list) { u32 keys[FLOW_KEY_MAX + 1]; struct flow_keys flow_keys; if (!tcf_em_tree_match(skb, &f->ematches, NULL)) continue; keymask = f->keymask; if (keymask & FLOW_KEYS_NEEDED) skb_flow_dissect(skb, &flow_keys); for (n = 0; n < f->nkeys; n++) { key = ffs(keymask) - 1; keymask &= ~(1 << key); keys[n] = flow_key_get(skb, key, &flow_keys); } if (f->mode == FLOW_MODE_HASH) classid = jhash2(keys, f->nkeys, f->hashrnd); else { classid = keys[0]; classid = (classid & f->mask) ^ f->xor; classid = (classid >> f->rshift) + f->addend; } if (f->divisor) classid %= f->divisor; res->class = 0; res->classid = TC_H_MAKE(f->baseclass, f->baseclass + classid); r = tcf_exts_exec(skb, &f->exts, res); if (r < 0) continue; return r; } return -1; } static void flow_perturbation(unsigned long arg) { struct flow_filter *f = (struct flow_filter *)arg; get_random_bytes(&f->hashrnd, 4); if (f->perturb_period) mod_timer(&f->perturb_timer, jiffies + f->perturb_period); } static const struct nla_policy flow_policy[TCA_FLOW_MAX + 1] = { [TCA_FLOW_KEYS] = { .type = NLA_U32 }, [TCA_FLOW_MODE] = { .type = NLA_U32 }, [TCA_FLOW_BASECLASS] = { .type = NLA_U32 }, [TCA_FLOW_RSHIFT] = { .type = NLA_U32 }, [TCA_FLOW_ADDEND] = { .type = NLA_U32 }, [TCA_FLOW_MASK] = { .type = NLA_U32 }, [TCA_FLOW_XOR] = { .type = NLA_U32 }, [TCA_FLOW_DIVISOR] = { .type = NLA_U32 }, [TCA_FLOW_ACT] = { .type = NLA_NESTED }, [TCA_FLOW_POLICE] = { .type = NLA_NESTED }, [TCA_FLOW_EMATCHES] = { .type = NLA_NESTED }, [TCA_FLOW_PERTURB] = { .type = NLA_U32 }, }; static int flow_change(struct net *net, struct sk_buff *in_skb, struct tcf_proto *tp, unsigned long base, u32 handle, struct nlattr **tca, unsigned long *arg) { struct flow_head *head = tp->root; struct flow_filter *f; struct nlattr *opt = tca[TCA_OPTIONS]; struct nlattr *tb[TCA_FLOW_MAX + 1]; struct tcf_exts e; struct tcf_ematch_tree t; unsigned int nkeys = 0; unsigned int perturb_period = 0; u32 baseclass = 0; u32 keymask = 0; u32 mode; int err; if (opt == NULL) return -EINVAL; err = nla_parse_nested(tb, TCA_FLOW_MAX, opt, flow_policy); if (err < 0) return err; if (tb[TCA_FLOW_BASECLASS]) { baseclass = nla_get_u32(tb[TCA_FLOW_BASECLASS]); if (TC_H_MIN(baseclass) == 0) return -EINVAL; } if (tb[TCA_FLOW_KEYS]) { keymask = nla_get_u32(tb[TCA_FLOW_KEYS]); nkeys = hweight32(keymask); if (nkeys == 0) return -EINVAL; if (fls(keymask) - 1 > FLOW_KEY_MAX) return -EOPNOTSUPP; if ((keymask & (FLOW_KEY_SKUID|FLOW_KEY_SKGID)) && sk_user_ns(NETLINK_CB(in_skb).sk) != &init_user_ns) return -EOPNOTSUPP; } err = tcf_exts_validate(net, tp, tb, tca[TCA_RATE], &e, &flow_ext_map); if (err < 0) return err; err = tcf_em_tree_validate(tp, tb[TCA_FLOW_EMATCHES], &t); if (err < 0) goto err1; f = (struct flow_filter *)*arg; if (f != NULL) { err = -EINVAL; if (f->handle != handle && handle) goto err2; mode = f->mode; if (tb[TCA_FLOW_MODE]) mode = nla_get_u32(tb[TCA_FLOW_MODE]); if (mode != FLOW_MODE_HASH && nkeys > 1) goto err2; if (mode == FLOW_MODE_HASH) perturb_period = f->perturb_period; if (tb[TCA_FLOW_PERTURB]) { if (mode != FLOW_MODE_HASH) goto err2; perturb_period = nla_get_u32(tb[TCA_FLOW_PERTURB]) * HZ; } } else { err = -EINVAL; if (!handle) goto err2; if (!tb[TCA_FLOW_KEYS]) goto err2; mode = FLOW_MODE_MAP; if (tb[TCA_FLOW_MODE]) mode = nla_get_u32(tb[TCA_FLOW_MODE]); if (mode != FLOW_MODE_HASH && nkeys > 1) goto err2; if (tb[TCA_FLOW_PERTURB]) { if (mode != FLOW_MODE_HASH) goto err2; perturb_period = nla_get_u32(tb[TCA_FLOW_PERTURB]) * HZ; } if (TC_H_MAJ(baseclass) == 0) baseclass = TC_H_MAKE(tp->q->handle, baseclass); if (TC_H_MIN(baseclass) == 0) baseclass = TC_H_MAKE(baseclass, 1); err = -ENOBUFS; f = kzalloc(sizeof(*f), GFP_KERNEL); if (f == NULL) goto err2; f->handle = handle; f->mask = ~0U; get_random_bytes(&f->hashrnd, 4); f->perturb_timer.function = flow_perturbation; f->perturb_timer.data = (unsigned long)f; init_timer_deferrable(&f->perturb_timer); } tcf_exts_change(tp, &f->exts, &e); tcf_em_tree_change(tp, &f->ematches, &t); tcf_tree_lock(tp); if (tb[TCA_FLOW_KEYS]) { f->keymask = keymask; f->nkeys = nkeys; } f->mode = mode; if (tb[TCA_FLOW_MASK]) f->mask = nla_get_u32(tb[TCA_FLOW_MASK]); if (tb[TCA_FLOW_XOR]) f->xor = nla_get_u32(tb[TCA_FLOW_XOR]); if (tb[TCA_FLOW_RSHIFT]) f->rshift = nla_get_u32(tb[TCA_FLOW_RSHIFT]); if (tb[TCA_FLOW_ADDEND]) f->addend = nla_get_u32(tb[TCA_FLOW_ADDEND]); if (tb[TCA_FLOW_DIVISOR]) f->divisor = nla_get_u32(tb[TCA_FLOW_DIVISOR]); if (baseclass) f->baseclass = baseclass; f->perturb_period = perturb_period; del_timer(&f->perturb_timer); if (perturb_period) mod_timer(&f->perturb_timer, jiffies + perturb_period); if (*arg == 0) list_add_tail(&f->list, &head->filters); tcf_tree_unlock(tp); *arg = (unsigned long)f; return 0; err2: tcf_em_tree_destroy(tp, &t); err1: tcf_exts_destroy(tp, &e); return err; } static void flow_destroy_filter(struct tcf_proto *tp, struct flow_filter *f) { del_timer_sync(&f->perturb_timer); tcf_exts_destroy(tp, &f->exts); tcf_em_tree_destroy(tp, &f->ematches); kfree(f); } static int flow_delete(struct tcf_proto *tp, unsigned long arg) { struct flow_filter *f = (struct flow_filter *)arg; tcf_tree_lock(tp); list_del(&f->list); tcf_tree_unlock(tp); flow_destroy_filter(tp, f); return 0; } static int flow_init(struct tcf_proto *tp) { struct flow_head *head; head = kzalloc(sizeof(*head), GFP_KERNEL); if (head == NULL) return -ENOBUFS; INIT_LIST_HEAD(&head->filters); tp->root = head; return 0; } static void flow_destroy(struct tcf_proto *tp) { struct flow_head *head = tp->root; struct flow_filter *f, *next; list_for_each_entry_safe(f, next, &head->filters, list) { list_del(&f->list); flow_destroy_filter(tp, f); } kfree(head); } static unsigned long flow_get(struct tcf_proto *tp, u32 handle) { struct flow_head *head = tp->root; struct flow_filter *f; list_for_each_entry(f, &head->filters, list) if (f->handle == handle) return (unsigned long)f; return 0; } static void flow_put(struct tcf_proto *tp, unsigned long f) { } static int flow_dump(struct tcf_proto *tp, unsigned long fh, struct sk_buff *skb, struct tcmsg *t) { struct flow_filter *f = (struct flow_filter *)fh; struct nlattr *nest; if (f == NULL) return skb->len; t->tcm_handle = f->handle; nest = nla_nest_start(skb, TCA_OPTIONS); if (nest == NULL) goto nla_put_failure; if (nla_put_u32(skb, TCA_FLOW_KEYS, f->keymask) || nla_put_u32(skb, TCA_FLOW_MODE, f->mode)) goto nla_put_failure; if (f->mask != ~0 || f->xor != 0) { if (nla_put_u32(skb, TCA_FLOW_MASK, f->mask) || nla_put_u32(skb, TCA_FLOW_XOR, f->xor)) goto nla_put_failure; } if (f->rshift && nla_put_u32(skb, TCA_FLOW_RSHIFT, f->rshift)) goto nla_put_failure; if (f->addend && nla_put_u32(skb, TCA_FLOW_ADDEND, f->addend)) goto nla_put_failure; if (f->divisor && nla_put_u32(skb, TCA_FLOW_DIVISOR, f->divisor)) goto nla_put_failure; if (f->baseclass && nla_put_u32(skb, TCA_FLOW_BASECLASS, f->baseclass)) goto nla_put_failure; if (f->perturb_period && nla_put_u32(skb, TCA_FLOW_PERTURB, f->perturb_period / HZ)) goto nla_put_failure; if (tcf_exts_dump(skb, &f->exts, &flow_ext_map) < 0) goto nla_put_failure; #ifdef CONFIG_NET_EMATCH if (f->ematches.hdr.nmatches && tcf_em_tree_dump(skb, &f->ematches, TCA_FLOW_EMATCHES) < 0) goto nla_put_failure; #endif nla_nest_end(skb, nest); if (tcf_exts_dump_stats(skb, &f->exts, &flow_ext_map) < 0) goto nla_put_failure; return skb->len; nla_put_failure: nlmsg_trim(skb, nest); return -1; } static void flow_walk(struct tcf_proto *tp, struct tcf_walker *arg) { struct flow_head *head = tp->root; struct flow_filter *f; list_for_each_entry(f, &head->filters, list) { if (arg->count < arg->skip) goto skip; if (arg->fn(tp, (unsigned long)f, arg) < 0) { arg->stop = 1; break; } skip: arg->count++; } } static struct tcf_proto_ops cls_flow_ops __read_mostly = { .kind = "flow", .classify = flow_classify, .init = flow_init, .destroy = flow_destroy, .change = flow_change, .delete = flow_delete, .get = flow_get, .put = flow_put, .dump = flow_dump, .walk = flow_walk, .owner = THIS_MODULE, }; static int __init cls_flow_init(void) { return register_tcf_proto_ops(&cls_flow_ops); } static void __exit cls_flow_exit(void) { unregister_tcf_proto_ops(&cls_flow_ops); } module_init(cls_flow_init); module_exit(cls_flow_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Patrick McHardy <kaber@trash.net>"); MODULE_DESCRIPTION("TC flow classifier");
webconnme/kernel
net/sched/cls_flow.c
C
gpl-2.0
15,797
/* * audio.c -- Audio gadget driver * * Copyright (C) 2008 Bryan Wu <cooloney@kernel.org> * Copyright (C) 2008 Analog Devices, Inc * * Enter bugs at http://blackfin.uclinux.org/ * * Licensed under the GPL-2 or later. */ /* #define VERBOSE_DEBUG */ #include <linux/kernel.h> #include <linux/utsname.h> #include "u_audio.h" #define DRIVER_DESC "Linux USB Audio Gadget" #define DRIVER_VERSION "Dec 18, 2008" /*-------------------------------------------------------------------------*/ /* * Kbuild is not very cooperative with respect to linking separately * compiled library objects into one module. So for now we won't use * separate compilation ... ensuring init/exit sections work to shrink * the runtime footprint, and giving us at least some parts of what * a "gcc --combine ... part1.c part2.c part3.c ... " build would. */ #include "composite.c" #include "usbstring.c" #include "config.c" #include "epautoconf.c" #include "u_audio.c" #include "f_audio.c" /*-------------------------------------------------------------------------*/ /* DO NOT REUSE THESE IDs with a protocol-incompatible driver!! Ever!! * Instead: allocate your own, using normal USB-IF procedures. */ /* Thanks to Linux Foundation for donating this product ID. */ #define AUDIO_VENDOR_NUM 0x1d6b /* Linux Foundation */ #define AUDIO_PRODUCT_NUM 0x0101 /* Linux-USB Audio Gadget */ /*-------------------------------------------------------------------------*/ static struct usb_device_descriptor device_desc = { .bLength = sizeof device_desc, .bDescriptorType = USB_DT_DEVICE, .bcdUSB = __constant_cpu_to_le16(0x200), .bDeviceClass = USB_CLASS_PER_INTERFACE, .bDeviceSubClass = 0, .bDeviceProtocol = 0, /* .bMaxPacketSize0 = f(hardware) */ /* Vendor and product id defaults change according to what configs * we support. (As does bNumConfigurations.) These values can * also be overridden by module parameters. */ .idVendor = __constant_cpu_to_le16(AUDIO_VENDOR_NUM), .idProduct = __constant_cpu_to_le16(AUDIO_PRODUCT_NUM), /* .bcdDevice = f(hardware) */ /* .iManufacturer = DYNAMIC */ /* .iProduct = DYNAMIC */ /* NO SERIAL NUMBER */ .bNumConfigurations = 1, }; static struct usb_otg_descriptor otg_descriptor = { .bLength = sizeof otg_descriptor, .bDescriptorType = USB_DT_OTG, /* REVISIT SRP-only hardware is possible, although * it would not be called "OTG" ... */ .bmAttributes = USB_OTG_SRP | USB_OTG_HNP, }; static const struct usb_descriptor_header *otg_desc[] = { (struct usb_descriptor_header *) &otg_descriptor, NULL, }; /*-------------------------------------------------------------------------*/ static int __init audio_do_config(struct usb_configuration *c) { /* FIXME alloc iConfiguration string, set it in c->strings */ if (gadget_is_otg(c->cdev->gadget)) { c->descriptors = otg_desc; c->bmAttributes |= USB_CONFIG_ATT_WAKEUP; } audio_bind_config(c); return 0; } static struct usb_configuration audio_config_driver = { .label = DRIVER_DESC, .bConfigurationValue = 1, /* .iConfiguration = DYNAMIC */ .bmAttributes = USB_CONFIG_ATT_SELFPOWER, }; /*-------------------------------------------------------------------------*/ static int __init audio_bind(struct usb_composite_dev *cdev) { int gcnum; int status; gcnum = usb_gadget_controller_number(cdev->gadget); if (gcnum >= 0) device_desc.bcdDevice = cpu_to_le16(0x0300 | gcnum); else { ERROR(cdev, "controller '%s' not recognized; trying %s\n", cdev->gadget->name, audio_config_driver.label); device_desc.bcdDevice = __constant_cpu_to_le16(0x0300 | 0x0099); } /* device descriptor strings: manufacturer, product */ snprintf(manufacturer, sizeof manufacturer, "%s %s with %s", init_utsname()->sysname, init_utsname()->release, cdev->gadget->name); status = usb_string_id(cdev); if (status < 0) goto fail; strings_dev[STRING_MANUFACTURER_IDX].id = status; device_desc.iManufacturer = status; status = usb_string_id(cdev); if (status < 0) goto fail; strings_dev[STRING_PRODUCT_IDX].id = status; device_desc.iProduct = status; status = usb_add_config(cdev, &audio_config_driver, audio_do_config); if (status < 0) goto fail; INFO(cdev, "%s, version: %s\n", DRIVER_DESC, DRIVER_VERSION); return 0; fail: return status; } static int __exit audio_unbind(struct usb_composite_dev *cdev) { gaudio_cleanup(); return 0; } static struct usb_composite_driver audio_driver = { .name = "g_audio", .dev = &device_desc, .strings = audio_strings, .unbind = __exit_p(audio_unbind), }; static int __init init(void) { return usb_composite_probe(&audio_driver, audio_bind); } module_init(init); static void __exit cleanup(void) { usb_composite_unregister(&audio_driver); } module_exit(cleanup); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_AUTHOR("Bryan Wu <cooloney@kernel.org>"); MODULE_LICENSE("GPL");
TeamJB/kernel_samsung_i9300
drivers/usb/gadget/audio.c
C
gpl-2.0
4,895
/* * Lockless get_user_pages_fast for MIPS * * Copyright (C) 2008 Nick Piggin * Copyright (C) 2008 Novell Inc. * Copyright (C) 2011 Ralf Baechle */ #include <linux/sched.h> #include <linux/mm.h> #include <linux/vmstat.h> #include <linux/highmem.h> #include <linux/swap.h> #include <linux/hugetlb.h> #include <asm/pgtable.h> static inline pte_t gup_get_pte(pte_t *ptep) { #if defined(CONFIG_64BIT_PHYS_ADDR) && defined(CONFIG_CPU_MIPS32) pte_t pte; retry: pte.pte_low = ptep->pte_low; smp_rmb(); pte.pte_high = ptep->pte_high; smp_rmb(); if (unlikely(pte.pte_low != ptep->pte_low)) goto retry; return pte; #else return ACCESS_ONCE(*ptep); #endif } static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end, int write, struct page **pages, int *nr) { pte_t *ptep = pte_offset_map(&pmd, addr); do { pte_t pte = gup_get_pte(ptep); struct page *page; if (!pte_present(pte) || pte_special(pte) || (write && !pte_write(pte))) { pte_unmap(ptep); return 0; } VM_BUG_ON(!pfn_valid(pte_pfn(pte))); page = pte_page(pte); get_page(page); SetPageReferenced(page); pages[*nr] = page; (*nr)++; } while (ptep++, addr += PAGE_SIZE, addr != end); pte_unmap(ptep - 1); return 1; } static inline void get_head_page_multiple(struct page *page, int nr) { VM_BUG_ON(page != compound_head(page)); VM_BUG_ON(page_count(page) == 0); atomic_add(nr, &page->_count); SetPageReferenced(page); } static int gup_huge_pmd(pmd_t pmd, unsigned long addr, unsigned long end, int write, struct page **pages, int *nr) { pte_t pte = *(pte_t *)&pmd; struct page *head, *page; int refs; if (write && !pte_write(pte)) return 0; /* hugepages are never "special" */ VM_BUG_ON(pte_special(pte)); VM_BUG_ON(!pfn_valid(pte_pfn(pte))); refs = 0; head = pte_page(pte); page = head + ((addr & ~PMD_MASK) >> PAGE_SHIFT); do { VM_BUG_ON(compound_head(page) != head); pages[*nr] = page; if (PageTail(page)) get_huge_page_tail(page); (*nr)++; page++; refs++; } while (addr += PAGE_SIZE, addr != end); get_head_page_multiple(head, refs); return 1; } static int gup_pmd_range(pud_t pud, unsigned long addr, unsigned long end, int write, struct page **pages, int *nr) { unsigned long next; pmd_t *pmdp; pmdp = pmd_offset(&pud, addr); do { pmd_t pmd = *pmdp; next = pmd_addr_end(addr, end); /* * The pmd_trans_splitting() check below explains why * pmdp_splitting_flush has to flush the tlb, to stop * this gup-fast code from running while we set the * splitting bit in the pmd. Returning zero will take * the slow path that will call wait_split_huge_page() * if the pmd is still in splitting state. gup-fast * can't because it has irq disabled and * wait_split_huge_page() would never return as the * tlb flush IPI wouldn't run. */ if (pmd_none(pmd) || pmd_trans_splitting(pmd)) return 0; if (unlikely(pmd_huge(pmd))) { if (!gup_huge_pmd(pmd, addr, next, write, pages,nr)) return 0; } else { if (!gup_pte_range(pmd, addr, next, write, pages,nr)) return 0; } } while (pmdp++, addr = next, addr != end); return 1; } static int gup_huge_pud(pud_t pud, unsigned long addr, unsigned long end, int write, struct page **pages, int *nr) { pte_t pte = *(pte_t *)&pud; struct page *head, *page; int refs; if (write && !pte_write(pte)) return 0; /* hugepages are never "special" */ VM_BUG_ON(pte_special(pte)); VM_BUG_ON(!pfn_valid(pte_pfn(pte))); refs = 0; head = pte_page(pte); page = head + ((addr & ~PUD_MASK) >> PAGE_SHIFT); do { VM_BUG_ON(compound_head(page) != head); pages[*nr] = page; (*nr)++; page++; refs++; } while (addr += PAGE_SIZE, addr != end); get_head_page_multiple(head, refs); return 1; } static int gup_pud_range(pgd_t pgd, unsigned long addr, unsigned long end, int write, struct page **pages, int *nr) { unsigned long next; pud_t *pudp; pudp = pud_offset(&pgd, addr); do { pud_t pud = *pudp; next = pud_addr_end(addr, end); if (pud_none(pud)) return 0; if (unlikely(pud_huge(pud))) { if (!gup_huge_pud(pud, addr, next, write, pages,nr)) return 0; } else { if (!gup_pmd_range(pud, addr, next, write, pages,nr)) return 0; } } while (pudp++, addr = next, addr != end); return 1; } /* * Like get_user_pages_fast() except its IRQ-safe in that it won't fall * back to the regular GUP. */ int __get_user_pages_fast(unsigned long start, int nr_pages, int write, struct page **pages) { struct mm_struct *mm = current->mm; unsigned long addr, len, end; unsigned long next; unsigned long flags; pgd_t *pgdp; int nr = 0; start &= PAGE_MASK; addr = start; len = (unsigned long) nr_pages << PAGE_SHIFT; end = start + len; if (unlikely(!access_ok(write ? VERIFY_WRITE : VERIFY_READ, (void __user *)start, len))) return 0; /* * XXX: batch / limit 'nr', to avoid large irq off latency * needs some instrumenting to determine the common sizes used by * important workloads (eg. DB2), and whether limiting the batch * size will decrease performance. * * It seems like we're in the clear for the moment. Direct-IO is * the main guy that batches up lots of get_user_pages, and even * they are limited to 64-at-a-time which is not so many. */ /* * This doesn't prevent pagetable teardown, but does prevent * the pagetables and pages from being freed. * * So long as we atomically load page table pointers versus teardown, * we can follow the address down to the page and take a ref on it. */ local_irq_save(flags); pgdp = pgd_offset(mm, addr); do { pgd_t pgd = *pgdp; next = pgd_addr_end(addr, end); if (pgd_none(pgd)) break; if (!gup_pud_range(pgd, addr, next, write, pages, &nr)) break; } while (pgdp++, addr = next, addr != end); local_irq_restore(flags); return nr; } /** * get_user_pages_fast() - pin user pages in memory * @start: starting user address * @nr_pages: number of pages from start to pin * @write: whether pages will be written to * @pages: array that receives pointers to the pages pinned. * Should be at least nr_pages long. * * Attempt to pin user pages in memory without taking mm->mmap_sem. * If not successful, it will fall back to taking the lock and * calling get_user_pages(). * * Returns number of pages pinned. This may be fewer than the number * requested. If nr_pages is 0 or negative, returns 0. If no pages * were pinned, returns -errno. */ int get_user_pages_fast(unsigned long start, int nr_pages, int write, struct page **pages) { struct mm_struct *mm = current->mm; unsigned long addr, len, end; unsigned long next; pgd_t *pgdp; int ret, nr = 0; start &= PAGE_MASK; addr = start; len = (unsigned long) nr_pages << PAGE_SHIFT; end = start + len; if (end < start) goto slow_irqon; /* XXX: batch / limit 'nr' */ local_irq_disable(); pgdp = pgd_offset(mm, addr); do { pgd_t pgd = *pgdp; next = pgd_addr_end(addr, end); if (pgd_none(pgd)) goto slow; if (!gup_pud_range(pgd, addr, next, write, pages, &nr)) goto slow; } while (pgdp++, addr = next, addr != end); local_irq_enable(); VM_BUG_ON(nr != (end - start) >> PAGE_SHIFT); return nr; slow: local_irq_enable(); slow_irqon: /* Try to get the remaining pages with get_user_pages */ start += nr << PAGE_SHIFT; pages += nr; down_read(&mm->mmap_sem); ret = get_user_pages(current, mm, start, (end - start) >> PAGE_SHIFT, write, 0, pages, NULL); up_read(&mm->mmap_sem); /* Have to be a bit careful with return values */ if (nr > 0) { if (ret < 0) ret = nr; else ret += nr; } return ret; }
junkie2100/android_kernel_zte_quantum
arch/mips/mm/gup.c
C
gpl-2.0
7,647
/* * iovec manipulation routines. * * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Fixes: * Andrew Lunn : Errors in iovec copying. * Pedro Roque : Added memcpy_fromiovecend and * csum_..._fromiovecend. * Andi Kleen : fixed error handling for 2.1 * Alexey Kuznetsov: 2.1 optimisations * Andi Kleen : Fix csum*fromiovecend for IPv6. */ #include <linux/errno.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/net.h> #include <linux/in6.h> #include <asm/uaccess.h> #include <asm/byteorder.h> #include <net/checksum.h> #include <net/sock.h> /* * Verify iovec. The caller must ensure that the iovec is big enough * to hold the message iovec. * * Save time not doing access_ok. copy_*_user will make this work * in any case. */ int verify_iovec(struct msghdr *m, struct iovec *iov, struct sockaddr *address, int mode) { int size, ct, err; if (m->msg_namelen) { if (mode == VERIFY_READ) { void __user *namep; namep = (void __user __force *) m->msg_name; err = move_addr_to_kernel(namep, m->msg_namelen, address); if (err < 0) return err; } m->msg_name = address; } else { m->msg_name = NULL; } size = m->msg_iovlen * sizeof(struct iovec); if (copy_from_user(iov, (void __user __force *) m->msg_iov, size)) return -EFAULT; m->msg_iov = iov; err = 0; for (ct = 0; ct < m->msg_iovlen; ct++) { size_t len = iov[ct].iov_len; if (len > INT_MAX - err) { len = INT_MAX - err; iov[ct].iov_len = len; } err += len; } return err; } /* * Copy kernel to iovec. Returns -EFAULT on error. * * Note: this modifies the original iovec. */ int memcpy_toiovec(struct iovec *iov, unsigned char *kdata, int len) { while (len > 0) { if (iov->iov_len) { int copy = min_t(unsigned int, iov->iov_len, len); if (copy_to_user(iov->iov_base, kdata, copy)) return -EFAULT; kdata += copy; len -= copy; iov->iov_len -= copy; iov->iov_base += copy; } iov++; } return 0; } EXPORT_SYMBOL(memcpy_toiovec); /* * Copy kernel to iovec. Returns -EFAULT on error. */ int memcpy_toiovecend(const struct iovec *iov, unsigned char *kdata, int offset, int len) { int copy; for (; len > 0; ++iov) { /* Skip over the finished iovecs */ if (unlikely(offset >= iov->iov_len)) { offset -= iov->iov_len; continue; } copy = min_t(unsigned int, iov->iov_len - offset, len); if (copy_to_user(iov->iov_base + offset, kdata, copy)) return -EFAULT; offset = 0; kdata += copy; len -= copy; } return 0; } EXPORT_SYMBOL(memcpy_toiovecend); /* * Copy iovec to kernel. Returns -EFAULT on error. * * Note: this modifies the original iovec. */ int memcpy_fromiovec(unsigned char *kdata, struct iovec *iov, int len) { while (len > 0) { if (iov->iov_len) { int copy = min_t(unsigned int, len, iov->iov_len); if (copy_from_user(kdata, iov->iov_base, copy)) return -EFAULT; len -= copy; kdata += copy; iov->iov_base += copy; iov->iov_len -= copy; } iov++; } return 0; } EXPORT_SYMBOL(memcpy_fromiovec); /* * Copy iovec from kernel. Returns -EFAULT on error. */ int memcpy_fromiovecend(unsigned char *kdata, const struct iovec *iov, int offset, int len) { /* Skip over the finished iovecs */ while (offset >= iov->iov_len) { offset -= iov->iov_len; iov++; } while (len > 0) { u8 __user *base = iov->iov_base + offset; int copy = min_t(unsigned int, len, iov->iov_len - offset); offset = 0; if (copy_from_user(kdata, base, copy)) return -EFAULT; len -= copy; kdata += copy; iov++; } return 0; } EXPORT_SYMBOL(memcpy_fromiovecend); /* * And now for the all-in-one: copy and checksum from a user iovec * directly to a datagram * Calls to csum_partial but the last must be in 32 bit chunks * * ip_build_xmit must ensure that when fragmenting only the last * call to this function will be unaligned also. */ int csum_partial_copy_fromiovecend(unsigned char *kdata, struct iovec *iov, int offset, unsigned int len, __wsum *csump) { __wsum csum = *csump; int partial_cnt = 0, err = 0; /* Skip over the finished iovecs */ while (offset >= iov->iov_len) { offset -= iov->iov_len; iov++; } while (len > 0) { u8 __user *base = iov->iov_base + offset; int copy = min_t(unsigned int, len, iov->iov_len - offset); offset = 0; /* There is a remnant from previous iov. */ if (partial_cnt) { int par_len = 4 - partial_cnt; /* iov component is too short ... */ if (par_len > copy) { if (copy_from_user(kdata, base, copy)) goto out_fault; kdata += copy; base += copy; partial_cnt += copy; len -= copy; iov++; if (len) continue; *csump = csum_partial(kdata - partial_cnt, partial_cnt, csum); goto out; } if (copy_from_user(kdata, base, par_len)) goto out_fault; csum = csum_partial(kdata - partial_cnt, 4, csum); kdata += par_len; base += par_len; copy -= par_len; len -= par_len; partial_cnt = 0; } if (len > copy) { partial_cnt = copy % 4; if (partial_cnt) { copy -= partial_cnt; if (copy_from_user(kdata + copy, base + copy, partial_cnt)) goto out_fault; } } if (copy) { csum = csum_and_copy_from_user(base, kdata, copy, csum, &err); if (err) goto out; } len -= copy + partial_cnt; kdata += copy + partial_cnt; iov++; } *csump = csum; out: return err; out_fault: err = -EFAULT; goto out; } EXPORT_SYMBOL(csum_partial_copy_fromiovecend);
zaclimon/android_kernel_samsung_aries
net/core/iovec.c
C
gpl-2.0
5,755
/***************************************************************************** * * Copyright (C) 2008 Cedric Bregardis <cedric.bregardis@free.fr> and * Jean-Christian Hassler <jhassler@free.fr> * * This file is part of the Audiowerk2 ALSA driver * * The Audiowerk2 ALSA driver is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2. * * The Audiowerk2 ALSA driver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with the Audiowerk2 ALSA driver; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * *****************************************************************************/ #include <linux/init.h> #include <linux/pci.h> #include <linux/dma-mapping.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/delay.h> #include <linux/io.h> #include <sound/core.h> #include <sound/initval.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/control.h> #include "saa7146.h" #include "aw2-saa7146.h" MODULE_AUTHOR("Cedric Bregardis <cedric.bregardis@free.fr>, " "Jean-Christian Hassler <jhassler@free.fr>"); MODULE_DESCRIPTION("Emagic Audiowerk 2 sound driver"); MODULE_LICENSE("GPL"); /********************************* * DEFINES ********************************/ #define CTL_ROUTE_ANALOG 0 #define CTL_ROUTE_DIGITAL 1 /********************************* * TYPEDEFS ********************************/ /* hardware definition */ static struct snd_pcm_hardware snd_aw2_playback_hw = { .info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_MMAP_VALID), .formats = SNDRV_PCM_FMTBIT_S16_LE, .rates = SNDRV_PCM_RATE_44100, .rate_min = 44100, .rate_max = 44100, .channels_min = 2, .channels_max = 4, .buffer_bytes_max = 32768, .period_bytes_min = 4096, .period_bytes_max = 32768, .periods_min = 1, .periods_max = 1024, }; static struct snd_pcm_hardware snd_aw2_capture_hw = { .info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_MMAP_VALID), .formats = SNDRV_PCM_FMTBIT_S16_LE, .rates = SNDRV_PCM_RATE_44100, .rate_min = 44100, .rate_max = 44100, .channels_min = 2, .channels_max = 2, .buffer_bytes_max = 32768, .period_bytes_min = 4096, .period_bytes_max = 32768, .periods_min = 1, .periods_max = 1024, }; struct aw2_pcm_device { struct snd_pcm *pcm; unsigned int stream_number; struct aw2 *chip; }; struct aw2 { struct snd_aw2_saa7146 saa7146; struct pci_dev *pci; int irq; spinlock_t reg_lock; struct mutex mtx; unsigned long iobase_phys; void __iomem *iobase_virt; struct snd_card *card; struct aw2_pcm_device device_playback[NB_STREAM_PLAYBACK]; struct aw2_pcm_device device_capture[NB_STREAM_CAPTURE]; }; /********************************* * FUNCTION DECLARATIONS ********************************/ static int __init alsa_card_aw2_init(void); static void __exit alsa_card_aw2_exit(void); static int snd_aw2_dev_free(struct snd_device *device); static int __devinit snd_aw2_create(struct snd_card *card, struct pci_dev *pci, struct aw2 **rchip); static int __devinit snd_aw2_probe(struct pci_dev *pci, const struct pci_device_id *pci_id); static void __devexit snd_aw2_remove(struct pci_dev *pci); static int snd_aw2_pcm_playback_open(struct snd_pcm_substream *substream); static int snd_aw2_pcm_playback_close(struct snd_pcm_substream *substream); static int snd_aw2_pcm_capture_open(struct snd_pcm_substream *substream); static int snd_aw2_pcm_capture_close(struct snd_pcm_substream *substream); static int snd_aw2_pcm_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *hw_params); static int snd_aw2_pcm_hw_free(struct snd_pcm_substream *substream); static int snd_aw2_pcm_prepare_playback(struct snd_pcm_substream *substream); static int snd_aw2_pcm_prepare_capture(struct snd_pcm_substream *substream); static int snd_aw2_pcm_trigger_playback(struct snd_pcm_substream *substream, int cmd); static int snd_aw2_pcm_trigger_capture(struct snd_pcm_substream *substream, int cmd); static snd_pcm_uframes_t snd_aw2_pcm_pointer_playback(struct snd_pcm_substream *substream); static snd_pcm_uframes_t snd_aw2_pcm_pointer_capture(struct snd_pcm_substream *substream); static int __devinit snd_aw2_new_pcm(struct aw2 *chip); static int snd_aw2_control_switch_capture_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo); static int snd_aw2_control_switch_capture_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol); static int snd_aw2_control_switch_capture_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol); /********************************* * VARIABLES ********************************/ static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP; module_param_array(index, int, NULL, 0444); MODULE_PARM_DESC(index, "Index value for Audiowerk2 soundcard."); module_param_array(id, charp, NULL, 0444); MODULE_PARM_DESC(id, "ID string for the Audiowerk2 soundcard."); module_param_array(enable, bool, NULL, 0444); MODULE_PARM_DESC(enable, "Enable Audiowerk2 soundcard."); static DEFINE_PCI_DEVICE_TABLE(snd_aw2_ids) = { {PCI_VENDOR_ID_PHILIPS, PCI_DEVICE_ID_PHILIPS_SAA7146, 0, 0, 0, 0, 0}, {0} }; MODULE_DEVICE_TABLE(pci, snd_aw2_ids); /* pci_driver definition */ static struct pci_driver driver = { .name = "Emagic Audiowerk 2", .id_table = snd_aw2_ids, .probe = snd_aw2_probe, .remove = __devexit_p(snd_aw2_remove), }; /* operators for playback PCM alsa interface */ static struct snd_pcm_ops snd_aw2_playback_ops = { .open = snd_aw2_pcm_playback_open, .close = snd_aw2_pcm_playback_close, .ioctl = snd_pcm_lib_ioctl, .hw_params = snd_aw2_pcm_hw_params, .hw_free = snd_aw2_pcm_hw_free, .prepare = snd_aw2_pcm_prepare_playback, .trigger = snd_aw2_pcm_trigger_playback, .pointer = snd_aw2_pcm_pointer_playback, }; /* operators for capture PCM alsa interface */ static struct snd_pcm_ops snd_aw2_capture_ops = { .open = snd_aw2_pcm_capture_open, .close = snd_aw2_pcm_capture_close, .ioctl = snd_pcm_lib_ioctl, .hw_params = snd_aw2_pcm_hw_params, .hw_free = snd_aw2_pcm_hw_free, .prepare = snd_aw2_pcm_prepare_capture, .trigger = snd_aw2_pcm_trigger_capture, .pointer = snd_aw2_pcm_pointer_capture, }; static struct snd_kcontrol_new aw2_control __devinitdata = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "PCM Capture Route", .index = 0, .access = SNDRV_CTL_ELEM_ACCESS_READWRITE, .private_value = 0xffff, .info = snd_aw2_control_switch_capture_info, .get = snd_aw2_control_switch_capture_get, .put = snd_aw2_control_switch_capture_put }; /********************************* * FUNCTION IMPLEMENTATIONS ********************************/ /* initialization of the module */ static int __init alsa_card_aw2_init(void) { snd_printdd(KERN_DEBUG "aw2: Load aw2 module\n"); return pci_register_driver(&driver); } /* clean up the module */ static void __exit alsa_card_aw2_exit(void) { snd_printdd(KERN_DEBUG "aw2: Unload aw2 module\n"); pci_unregister_driver(&driver); } module_init(alsa_card_aw2_init); module_exit(alsa_card_aw2_exit); /* component-destructor */ static int snd_aw2_dev_free(struct snd_device *device) { struct aw2 *chip = device->device_data; /* Free hardware */ snd_aw2_saa7146_free(&chip->saa7146); /* release the irq */ if (chip->irq >= 0) free_irq(chip->irq, (void *)chip); /* release the i/o ports & memory */ if (chip->iobase_virt) iounmap(chip->iobase_virt); pci_release_regions(chip->pci); /* disable the PCI entry */ pci_disable_device(chip->pci); /* release the data */ kfree(chip); return 0; } /* chip-specific constructor */ static int __devinit snd_aw2_create(struct snd_card *card, struct pci_dev *pci, struct aw2 **rchip) { struct aw2 *chip; int err; static struct snd_device_ops ops = { .dev_free = snd_aw2_dev_free, }; *rchip = NULL; /* initialize the PCI entry */ err = pci_enable_device(pci); if (err < 0) return err; pci_set_master(pci); /* check PCI availability (32bit DMA) */ if ((pci_set_dma_mask(pci, DMA_BIT_MASK(32)) < 0) || (pci_set_consistent_dma_mask(pci, DMA_BIT_MASK(32)) < 0)) { printk(KERN_ERR "aw2: Impossible to set 32bit mask DMA\n"); pci_disable_device(pci); return -ENXIO; } chip = kzalloc(sizeof(*chip), GFP_KERNEL); if (chip == NULL) { pci_disable_device(pci); return -ENOMEM; } /* initialize the stuff */ chip->card = card; chip->pci = pci; chip->irq = -1; /* (1) PCI resource allocation */ err = pci_request_regions(pci, "Audiowerk2"); if (err < 0) { pci_disable_device(pci); kfree(chip); return err; } chip->iobase_phys = pci_resource_start(pci, 0); chip->iobase_virt = ioremap_nocache(chip->iobase_phys, pci_resource_len(pci, 0)); if (chip->iobase_virt == NULL) { printk(KERN_ERR "aw2: unable to remap memory region"); pci_release_regions(pci); pci_disable_device(pci); kfree(chip); return -ENOMEM; } /* (2) initialization of the chip hardware */ snd_aw2_saa7146_setup(&chip->saa7146, chip->iobase_virt); if (request_irq(pci->irq, snd_aw2_saa7146_interrupt, IRQF_SHARED, "Audiowerk2", chip)) { printk(KERN_ERR "aw2: Cannot grab irq %d\n", pci->irq); iounmap(chip->iobase_virt); pci_release_regions(chip->pci); pci_disable_device(chip->pci); kfree(chip); return -EBUSY; } chip->irq = pci->irq; err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops); if (err < 0) { free_irq(chip->irq, (void *)chip); iounmap(chip->iobase_virt); pci_release_regions(chip->pci); pci_disable_device(chip->pci); kfree(chip); return err; } snd_card_set_dev(card, &pci->dev); *rchip = chip; printk(KERN_INFO "Audiowerk 2 sound card (saa7146 chipset) detected and " "managed\n"); return 0; } /* constructor */ static int __devinit snd_aw2_probe(struct pci_dev *pci, const struct pci_device_id *pci_id) { static int dev; struct snd_card *card; struct aw2 *chip; int err; /* (1) Continue if device is not enabled, else inc dev */ if (dev >= SNDRV_CARDS) return -ENODEV; if (!enable[dev]) { dev++; return -ENOENT; } /* (2) Create card instance */ err = snd_card_create(index[dev], id[dev], THIS_MODULE, 0, &card); if (err < 0) return err; /* (3) Create main component */ err = snd_aw2_create(card, pci, &chip); if (err < 0) { snd_card_free(card); return err; } /* initialize mutex */ mutex_init(&chip->mtx); /* init spinlock */ spin_lock_init(&chip->reg_lock); /* (4) Define driver ID and name string */ strcpy(card->driver, "aw2"); strcpy(card->shortname, "Audiowerk2"); sprintf(card->longname, "%s with SAA7146 irq %i", card->shortname, chip->irq); /* (5) Create other components */ snd_aw2_new_pcm(chip); /* (6) Register card instance */ err = snd_card_register(card); if (err < 0) { snd_card_free(card); return err; } /* (7) Set PCI driver data */ pci_set_drvdata(pci, card); dev++; return 0; } /* destructor */ static void __devexit snd_aw2_remove(struct pci_dev *pci) { snd_card_free(pci_get_drvdata(pci)); pci_set_drvdata(pci, NULL); } /* open callback */ static int snd_aw2_pcm_playback_open(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; snd_printdd(KERN_DEBUG "aw2: Playback_open\n"); runtime->hw = snd_aw2_playback_hw; return 0; } /* close callback */ static int snd_aw2_pcm_playback_close(struct snd_pcm_substream *substream) { return 0; } static int snd_aw2_pcm_capture_open(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; snd_printdd(KERN_DEBUG "aw2: Capture_open\n"); runtime->hw = snd_aw2_capture_hw; return 0; } /* close callback */ static int snd_aw2_pcm_capture_close(struct snd_pcm_substream *substream) { /* TODO: something to do ? */ return 0; } /* hw_params callback */ static int snd_aw2_pcm_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *hw_params) { return snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params)); } /* hw_free callback */ static int snd_aw2_pcm_hw_free(struct snd_pcm_substream *substream) { return snd_pcm_lib_free_pages(substream); } /* prepare callback for playback */ static int snd_aw2_pcm_prepare_playback(struct snd_pcm_substream *substream) { struct aw2_pcm_device *pcm_device = snd_pcm_substream_chip(substream); struct aw2 *chip = pcm_device->chip; struct snd_pcm_runtime *runtime = substream->runtime; unsigned long period_size, buffer_size; mutex_lock(&chip->mtx); period_size = snd_pcm_lib_period_bytes(substream); buffer_size = snd_pcm_lib_buffer_bytes(substream); snd_aw2_saa7146_pcm_init_playback(&chip->saa7146, pcm_device->stream_number, runtime->dma_addr, period_size, buffer_size); /* Define Interrupt callback */ snd_aw2_saa7146_define_it_playback_callback(pcm_device->stream_number, (snd_aw2_saa7146_it_cb) snd_pcm_period_elapsed, (void *)substream); mutex_unlock(&chip->mtx); return 0; } /* prepare callback for capture */ static int snd_aw2_pcm_prepare_capture(struct snd_pcm_substream *substream) { struct aw2_pcm_device *pcm_device = snd_pcm_substream_chip(substream); struct aw2 *chip = pcm_device->chip; struct snd_pcm_runtime *runtime = substream->runtime; unsigned long period_size, buffer_size; mutex_lock(&chip->mtx); period_size = snd_pcm_lib_period_bytes(substream); buffer_size = snd_pcm_lib_buffer_bytes(substream); snd_aw2_saa7146_pcm_init_capture(&chip->saa7146, pcm_device->stream_number, runtime->dma_addr, period_size, buffer_size); /* Define Interrupt callback */ snd_aw2_saa7146_define_it_capture_callback(pcm_device->stream_number, (snd_aw2_saa7146_it_cb) snd_pcm_period_elapsed, (void *)substream); mutex_unlock(&chip->mtx); return 0; } /* playback trigger callback */ static int snd_aw2_pcm_trigger_playback(struct snd_pcm_substream *substream, int cmd) { int status = 0; struct aw2_pcm_device *pcm_device = snd_pcm_substream_chip(substream); struct aw2 *chip = pcm_device->chip; spin_lock(&chip->reg_lock); switch (cmd) { case SNDRV_PCM_TRIGGER_START: snd_aw2_saa7146_pcm_trigger_start_playback(&chip->saa7146, pcm_device-> stream_number); break; case SNDRV_PCM_TRIGGER_STOP: snd_aw2_saa7146_pcm_trigger_stop_playback(&chip->saa7146, pcm_device-> stream_number); break; default: status = -EINVAL; } spin_unlock(&chip->reg_lock); return status; } /* capture trigger callback */ static int snd_aw2_pcm_trigger_capture(struct snd_pcm_substream *substream, int cmd) { int status = 0; struct aw2_pcm_device *pcm_device = snd_pcm_substream_chip(substream); struct aw2 *chip = pcm_device->chip; spin_lock(&chip->reg_lock); switch (cmd) { case SNDRV_PCM_TRIGGER_START: snd_aw2_saa7146_pcm_trigger_start_capture(&chip->saa7146, pcm_device-> stream_number); break; case SNDRV_PCM_TRIGGER_STOP: snd_aw2_saa7146_pcm_trigger_stop_capture(&chip->saa7146, pcm_device-> stream_number); break; default: status = -EINVAL; } spin_unlock(&chip->reg_lock); return status; } /* playback pointer callback */ static snd_pcm_uframes_t snd_aw2_pcm_pointer_playback(struct snd_pcm_substream *substream) { struct aw2_pcm_device *pcm_device = snd_pcm_substream_chip(substream); struct aw2 *chip = pcm_device->chip; unsigned int current_ptr; /* get the current hardware pointer */ struct snd_pcm_runtime *runtime = substream->runtime; current_ptr = snd_aw2_saa7146_get_hw_ptr_playback(&chip->saa7146, pcm_device->stream_number, runtime->dma_area, runtime->buffer_size); return bytes_to_frames(substream->runtime, current_ptr); } /* capture pointer callback */ static snd_pcm_uframes_t snd_aw2_pcm_pointer_capture(struct snd_pcm_substream *substream) { struct aw2_pcm_device *pcm_device = snd_pcm_substream_chip(substream); struct aw2 *chip = pcm_device->chip; unsigned int current_ptr; /* get the current hardware pointer */ struct snd_pcm_runtime *runtime = substream->runtime; current_ptr = snd_aw2_saa7146_get_hw_ptr_capture(&chip->saa7146, pcm_device->stream_number, runtime->dma_area, runtime->buffer_size); return bytes_to_frames(substream->runtime, current_ptr); } /* create a pcm device */ static int __devinit snd_aw2_new_pcm(struct aw2 *chip) { struct snd_pcm *pcm_playback_ana; struct snd_pcm *pcm_playback_num; struct snd_pcm *pcm_capture; struct aw2_pcm_device *pcm_device; int err = 0; /* Create new Alsa PCM device */ err = snd_pcm_new(chip->card, "Audiowerk2 analog playback", 0, 1, 0, &pcm_playback_ana); if (err < 0) { printk(KERN_ERR "aw2: snd_pcm_new error (0x%X)\n", err); return err; } /* Creation ok */ pcm_device = &chip->device_playback[NUM_STREAM_PLAYBACK_ANA]; /* Set PCM device name */ strcpy(pcm_playback_ana->name, "Analog playback"); /* Associate private data to PCM device */ pcm_playback_ana->private_data = pcm_device; /* set operators of PCM device */ snd_pcm_set_ops(pcm_playback_ana, SNDRV_PCM_STREAM_PLAYBACK, &snd_aw2_playback_ops); /* store PCM device */ pcm_device->pcm = pcm_playback_ana; /* give base chip pointer to our internal pcm device structure */ pcm_device->chip = chip; /* Give stream number to PCM device */ pcm_device->stream_number = NUM_STREAM_PLAYBACK_ANA; /* pre-allocation of buffers */ /* Preallocate continuous pages. */ err = snd_pcm_lib_preallocate_pages_for_all(pcm_playback_ana, SNDRV_DMA_TYPE_DEV, snd_dma_pci_data (chip->pci), 64 * 1024, 64 * 1024); if (err) printk(KERN_ERR "aw2: snd_pcm_lib_preallocate_pages_for_all " "error (0x%X)\n", err); err = snd_pcm_new(chip->card, "Audiowerk2 digital playback", 1, 1, 0, &pcm_playback_num); if (err < 0) { printk(KERN_ERR "aw2: snd_pcm_new error (0x%X)\n", err); return err; } /* Creation ok */ pcm_device = &chip->device_playback[NUM_STREAM_PLAYBACK_DIG]; /* Set PCM device name */ strcpy(pcm_playback_num->name, "Digital playback"); /* Associate private data to PCM device */ pcm_playback_num->private_data = pcm_device; /* set operators of PCM device */ snd_pcm_set_ops(pcm_playback_num, SNDRV_PCM_STREAM_PLAYBACK, &snd_aw2_playback_ops); /* store PCM device */ pcm_device->pcm = pcm_playback_num; /* give base chip pointer to our internal pcm device structure */ pcm_device->chip = chip; /* Give stream number to PCM device */ pcm_device->stream_number = NUM_STREAM_PLAYBACK_DIG; /* pre-allocation of buffers */ /* Preallocate continuous pages. */ err = snd_pcm_lib_preallocate_pages_for_all(pcm_playback_num, SNDRV_DMA_TYPE_DEV, snd_dma_pci_data (chip->pci), 64 * 1024, 64 * 1024); if (err) printk(KERN_ERR "aw2: snd_pcm_lib_preallocate_pages_for_all error " "(0x%X)\n", err); err = snd_pcm_new(chip->card, "Audiowerk2 capture", 2, 0, 1, &pcm_capture); if (err < 0) { printk(KERN_ERR "aw2: snd_pcm_new error (0x%X)\n", err); return err; } /* Creation ok */ pcm_device = &chip->device_capture[NUM_STREAM_CAPTURE_ANA]; /* Set PCM device name */ strcpy(pcm_capture->name, "Capture"); /* Associate private data to PCM device */ pcm_capture->private_data = pcm_device; /* set operators of PCM device */ snd_pcm_set_ops(pcm_capture, SNDRV_PCM_STREAM_CAPTURE, &snd_aw2_capture_ops); /* store PCM device */ pcm_device->pcm = pcm_capture; /* give base chip pointer to our internal pcm device structure */ pcm_device->chip = chip; /* Give stream number to PCM device */ pcm_device->stream_number = NUM_STREAM_CAPTURE_ANA; /* pre-allocation of buffers */ /* Preallocate continuous pages. */ err = snd_pcm_lib_preallocate_pages_for_all(pcm_capture, SNDRV_DMA_TYPE_DEV, snd_dma_pci_data (chip->pci), 64 * 1024, 64 * 1024); if (err) printk(KERN_ERR "aw2: snd_pcm_lib_preallocate_pages_for_all error " "(0x%X)\n", err); /* Create control */ err = snd_ctl_add(chip->card, snd_ctl_new1(&aw2_control, chip)); if (err < 0) { printk(KERN_ERR "aw2: snd_ctl_add error (0x%X)\n", err); return err; } return 0; } static int snd_aw2_control_switch_capture_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { static char *texts[2] = { "Analog", "Digital" }; uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED; uinfo->count = 1; uinfo->value.enumerated.items = 2; if (uinfo->value.enumerated.item >= uinfo->value.enumerated.items) { uinfo->value.enumerated.item = uinfo->value.enumerated.items - 1; } strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]); return 0; } static int snd_aw2_control_switch_capture_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct aw2 *chip = snd_kcontrol_chip(kcontrol); if (snd_aw2_saa7146_is_using_digital_input(&chip->saa7146)) ucontrol->value.enumerated.item[0] = CTL_ROUTE_DIGITAL; else ucontrol->value.enumerated.item[0] = CTL_ROUTE_ANALOG; return 0; } static int snd_aw2_control_switch_capture_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct aw2 *chip = snd_kcontrol_chip(kcontrol); int changed = 0; int is_disgital = snd_aw2_saa7146_is_using_digital_input(&chip->saa7146); if (((ucontrol->value.integer.value[0] == CTL_ROUTE_DIGITAL) && !is_disgital) || ((ucontrol->value.integer.value[0] == CTL_ROUTE_ANALOG) && is_disgital)) { snd_aw2_saa7146_use_digital_input(&chip->saa7146, !is_disgital); changed = 1; } return changed; }
KDGDev/meizu-mx-kernel
sound/pci/aw2/aw2-alsa.c
C
gpl-2.0
22,465
/* * arch/sh/drivers/dma/dma-sysfs.c * * sysfs interface for SH DMA API * * Copyright (C) 2004 - 2006 Paul Mundt * * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/sysdev.h> #include <linux/platform_device.h> #include <linux/err.h> #include <linux/string.h> #include <asm/dma.h> static struct sysdev_class dma_sysclass = { .name = "dma", }; static ssize_t dma_show_devices(struct sys_device *dev, struct sysdev_attribute *attr, char *buf) { ssize_t len = 0; int i; for (i = 0; i < MAX_DMA_CHANNELS; i++) { struct dma_info *info = get_dma_info(i); struct dma_channel *channel = get_dma_channel(i); if (unlikely(!info) || !channel) continue; len += sprintf(buf + len, "%2d: %14s %s\n", channel->chan, info->name, channel->dev_id); } return len; } static SYSDEV_ATTR(devices, S_IRUGO, dma_show_devices, NULL); static int __init dma_sysclass_init(void) { int ret; ret = sysdev_class_register(&dma_sysclass); if (unlikely(ret)) return ret; return sysfs_create_file(&dma_sysclass.kset.kobj, &attr_devices.attr); } postcore_initcall(dma_sysclass_init); static ssize_t dma_show_dev_id(struct sys_device *dev, struct sysdev_attribute *attr, char *buf) { struct dma_channel *channel = to_dma_channel(dev); return sprintf(buf, "%s\n", channel->dev_id); } static ssize_t dma_store_dev_id(struct sys_device *dev, struct sysdev_attribute *attr, const char *buf, size_t count) { struct dma_channel *channel = to_dma_channel(dev); strcpy(channel->dev_id, buf); return count; } static SYSDEV_ATTR(dev_id, S_IRUGO | S_IWUSR, dma_show_dev_id, dma_store_dev_id); static ssize_t dma_store_config(struct sys_device *dev, struct sysdev_attribute *attr, const char *buf, size_t count) { struct dma_channel *channel = to_dma_channel(dev); unsigned long config; config = simple_strtoul(buf, NULL, 0); dma_configure_channel(channel->vchan, config); return count; } static SYSDEV_ATTR(config, S_IWUSR, NULL, dma_store_config); static ssize_t dma_show_mode(struct sys_device *dev, struct sysdev_attribute *attr, char *buf) { struct dma_channel *channel = to_dma_channel(dev); return sprintf(buf, "0x%08x\n", channel->mode); } static ssize_t dma_store_mode(struct sys_device *dev, struct sysdev_attribute *attr, const char *buf, size_t count) { struct dma_channel *channel = to_dma_channel(dev); channel->mode = simple_strtoul(buf, NULL, 0); return count; } static SYSDEV_ATTR(mode, S_IRUGO | S_IWUSR, dma_show_mode, dma_store_mode); #define dma_ro_attr(field, fmt) \ static ssize_t dma_show_##field(struct sys_device *dev, \ struct sysdev_attribute *attr, char *buf)\ { \ struct dma_channel *channel = to_dma_channel(dev); \ return sprintf(buf, fmt, channel->field); \ } \ static SYSDEV_ATTR(field, S_IRUGO, dma_show_##field, NULL); dma_ro_attr(count, "0x%08x\n"); dma_ro_attr(flags, "0x%08lx\n"); int dma_create_sysfs_files(struct dma_channel *chan, struct dma_info *info) { struct sys_device *dev = &chan->dev; char name[16]; int ret; dev->id = chan->vchan; dev->cls = &dma_sysclass; ret = sysdev_register(dev); if (ret) return ret; ret |= sysdev_create_file(dev, &attr_dev_id); ret |= sysdev_create_file(dev, &attr_count); ret |= sysdev_create_file(dev, &attr_mode); ret |= sysdev_create_file(dev, &attr_flags); ret |= sysdev_create_file(dev, &attr_config); if (unlikely(ret)) { dev_err(&info->pdev->dev, "Failed creating attrs\n"); return ret; } snprintf(name, sizeof(name), "dma%d", chan->chan); return sysfs_create_link(&info->pdev->dev.kobj, &dev->kobj, name); } void dma_remove_sysfs_files(struct dma_channel *chan, struct dma_info *info) { struct sys_device *dev = &chan->dev; char name[16]; sysdev_remove_file(dev, &attr_dev_id); sysdev_remove_file(dev, &attr_count); sysdev_remove_file(dev, &attr_mode); sysdev_remove_file(dev, &attr_flags); sysdev_remove_file(dev, &attr_config); snprintf(name, sizeof(name), "dma%d", chan->chan); sysfs_remove_link(&info->pdev->dev.kobj, name); sysdev_unregister(dev); }
bhundven/android_kernel_samsung_galaxys4gmtd
arch/sh/drivers/dma/dma-sysfs.c
C
gpl-2.0
4,293
/* * Copyright (C) 2008,2009,2010,2011 Imagination Technologies Ltd. * * Meta 2 enhanced mode MMU handling code. * */ #include <linux/mm.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/io.h> #include <linux/bootmem.h> #include <linux/syscore_ops.h> #include <asm/mmu.h> #include <asm/mmu_context.h> unsigned long mmu_read_first_level_page(unsigned long vaddr) { unsigned int cpu = hard_processor_id(); unsigned long offset, linear_base, linear_limit; unsigned int phys0; pgd_t *pgd, entry; if (is_global_space(vaddr)) vaddr &= ~0x80000000; offset = vaddr >> PGDIR_SHIFT; phys0 = metag_in32(mmu_phys0_addr(cpu)); /* Top bit of linear base is always zero. */ linear_base = (phys0 >> PGDIR_SHIFT) & 0x1ff; /* Limit in the range 0 (4MB) to 9 (2GB). */ linear_limit = 1 << ((phys0 >> 8) & 0xf); linear_limit += linear_base; /* * If offset is below linear base or above the limit then no * mapping exists. */ if (offset < linear_base || offset > linear_limit) return 0; offset -= linear_base; pgd = (pgd_t *)mmu_get_base(); entry = pgd[offset]; return pgd_val(entry); } unsigned long mmu_read_second_level_page(unsigned long vaddr) { return __builtin_meta2_cacherd((void *)(vaddr & PAGE_MASK)); } unsigned long mmu_get_base(void) { unsigned int cpu = hard_processor_id(); unsigned long stride; stride = cpu * LINSYSMEMTnX_STRIDE; /* * Bits 18:2 of the MMCU_TnLocal_TABLE_PHYS1 register should be * used as an offset to the start of the top-level pgd table. */ stride += (metag_in32(mmu_phys1_addr(cpu)) & 0x7fffc); if (is_global_space(PAGE_OFFSET)) stride += LINSYSMEMTXG_OFFSET; return LINSYSMEMT0L_BASE + stride; } #define FIRST_LEVEL_MASK 0xffffffc0 #define SECOND_LEVEL_MASK 0xfffff000 #define SECOND_LEVEL_ALIGN 64 static void repriv_mmu_tables(void) { unsigned long phys0_addr; unsigned int g; /* * Check that all the mmu table regions are priv protected, and if not * fix them and emit a warning. If we left them without priv protection * then userland processes would have access to a 2M window into * physical memory near where the page tables are. */ phys0_addr = MMCU_T0LOCAL_TABLE_PHYS0; for (g = 0; g < 2; ++g) { unsigned int t, phys0; unsigned long flags; for (t = 0; t < 4; ++t) { __global_lock2(flags); phys0 = metag_in32(phys0_addr); if ((phys0 & _PAGE_PRESENT) && !(phys0 & _PAGE_PRIV)) { pr_warn("Fixing priv protection on T%d %s MMU table region\n", t, g ? "global" : "local"); phys0 |= _PAGE_PRIV; metag_out32(phys0, phys0_addr); } __global_unlock2(flags); phys0_addr += MMCU_TnX_TABLE_PHYSX_STRIDE; } phys0_addr += MMCU_TXG_TABLE_PHYSX_OFFSET - 4*MMCU_TnX_TABLE_PHYSX_STRIDE; } } #ifdef CONFIG_METAG_SUSPEND_MEM static void mmu_resume(void) { /* * If a full suspend to RAM has happened then the original bad MMU table * priv may have been restored, so repriv them again. */ repriv_mmu_tables(); } #else #define mmu_resume NULL #endif /* CONFIG_METAG_SUSPEND_MEM */ static struct syscore_ops mmu_syscore_ops = { .resume = mmu_resume, }; void __init mmu_init(unsigned long mem_end) { unsigned long entry, addr; pgd_t *p_swapper_pg_dir; #ifdef CONFIG_KERNEL_4M_PAGES unsigned long mem_size = mem_end - PAGE_OFFSET; unsigned int pages = DIV_ROUND_UP(mem_size, 1 << 22); unsigned int second_level_entry = 0; unsigned long *second_level_table; #endif /* * Now copy over any MMU pgd entries already in the mmu page tables * over to our root init process (swapper_pg_dir) map. This map is * then inherited by all other processes, which means all processes * inherit a map of the kernel space. */ addr = META_MEMORY_BASE; entry = pgd_index(META_MEMORY_BASE); p_swapper_pg_dir = pgd_offset_k(0) + entry; while (entry < (PTRS_PER_PGD - pgd_index(META_MEMORY_BASE))) { unsigned long pgd_entry; /* copy over the current MMU value */ pgd_entry = mmu_read_first_level_page(addr); pgd_val(*p_swapper_pg_dir) = pgd_entry; p_swapper_pg_dir++; addr += PGDIR_SIZE; entry++; } #ifdef CONFIG_KERNEL_4M_PAGES /* * At this point we can also map the kernel with 4MB pages to * reduce TLB pressure. */ second_level_table = alloc_bootmem_pages(SECOND_LEVEL_ALIGN * pages); addr = PAGE_OFFSET; entry = pgd_index(PAGE_OFFSET); p_swapper_pg_dir = pgd_offset_k(0) + entry; while (pages > 0) { unsigned long phys_addr, second_level_phys; pte_t *pte = (pte_t *)&second_level_table[second_level_entry]; phys_addr = __pa(addr); second_level_phys = __pa(pte); pgd_val(*p_swapper_pg_dir) = ((second_level_phys & FIRST_LEVEL_MASK) | _PAGE_SZ_4M | _PAGE_PRESENT); pte_val(*pte) = ((phys_addr & SECOND_LEVEL_MASK) | _PAGE_PRESENT | _PAGE_DIRTY | _PAGE_ACCESSED | _PAGE_WRITE | _PAGE_CACHEABLE | _PAGE_KERNEL); p_swapper_pg_dir++; addr += PGDIR_SIZE; /* Second level pages must be 64byte aligned. */ second_level_entry += (SECOND_LEVEL_ALIGN / sizeof(unsigned long)); pages--; } load_pgd(swapper_pg_dir, hard_processor_id()); flush_tlb_all(); #endif repriv_mmu_tables(); register_syscore_ops(&mmu_syscore_ops); }
kaneawk/android_kernel_motorola_msm8996
arch/metag/mm/mmu-meta2.c
C
gpl-2.0
5,214
/* * arch/arm/mach-ks8695/devices.c * * Copyright (C) 2006 Andrew Victor * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <asm/mach/arch.h> #include <asm/mach/map.h> #include <linux/platform_device.h> #include <mach/irqs.h> #include <mach/regs-wan.h> #include <mach/regs-lan.h> #include <mach/regs-hpna.h> #include <mach/regs-switch.h> #include <mach/regs-misc.h> /* -------------------------------------------------------------------- * Ethernet * -------------------------------------------------------------------- */ static u64 eth_dmamask = 0xffffffffUL; static struct resource ks8695_wan_resources[] = { [0] = { .start = KS8695_WAN_PA, .end = KS8695_WAN_PA + 0x00ff, .flags = IORESOURCE_MEM, }, [1] = { .name = "WAN RX", .start = KS8695_IRQ_WAN_RX_STATUS, .end = KS8695_IRQ_WAN_RX_STATUS, .flags = IORESOURCE_IRQ, }, [2] = { .name = "WAN TX", .start = KS8695_IRQ_WAN_TX_STATUS, .end = KS8695_IRQ_WAN_TX_STATUS, .flags = IORESOURCE_IRQ, }, [3] = { .name = "WAN Link", .start = KS8695_IRQ_WAN_LINK, .end = KS8695_IRQ_WAN_LINK, .flags = IORESOURCE_IRQ, }, [4] = { .name = "WAN PHY", .start = KS8695_MISC_PA, .end = KS8695_MISC_PA + 0x1f, .flags = IORESOURCE_MEM, }, }; static struct platform_device ks8695_wan_device = { .name = "ks8695_ether", .id = 0, .dev = { .dma_mask = &eth_dmamask, .coherent_dma_mask = 0xffffffff, }, .resource = ks8695_wan_resources, .num_resources = ARRAY_SIZE(ks8695_wan_resources), }; static struct resource ks8695_lan_resources[] = { [0] = { .start = KS8695_LAN_PA, .end = KS8695_LAN_PA + 0x00ff, .flags = IORESOURCE_MEM, }, [1] = { .name = "LAN RX", .start = KS8695_IRQ_LAN_RX_STATUS, .end = KS8695_IRQ_LAN_RX_STATUS, .flags = IORESOURCE_IRQ, }, [2] = { .name = "LAN TX", .start = KS8695_IRQ_LAN_TX_STATUS, .end = KS8695_IRQ_LAN_TX_STATUS, .flags = IORESOURCE_IRQ, }, [3] = { .name = "LAN SWITCH", .start = KS8695_SWITCH_PA, .end = KS8695_SWITCH_PA + 0x4f, .flags = IORESOURCE_MEM, }, }; static struct platform_device ks8695_lan_device = { .name = "ks8695_ether", .id = 1, .dev = { .dma_mask = &eth_dmamask, .coherent_dma_mask = 0xffffffff, }, .resource = ks8695_lan_resources, .num_resources = ARRAY_SIZE(ks8695_lan_resources), }; static struct resource ks8695_hpna_resources[] = { [0] = { .start = KS8695_HPNA_PA, .end = KS8695_HPNA_PA + 0x00ff, .flags = IORESOURCE_MEM, }, [1] = { .name = "HPNA RX", .start = KS8695_IRQ_HPNA_RX_STATUS, .end = KS8695_IRQ_HPNA_RX_STATUS, .flags = IORESOURCE_IRQ, }, [2] = { .name = "HPNA TX", .start = KS8695_IRQ_HPNA_TX_STATUS, .end = KS8695_IRQ_HPNA_TX_STATUS, .flags = IORESOURCE_IRQ, }, }; static struct platform_device ks8695_hpna_device = { .name = "ks8695_ether", .id = 2, .dev = { .dma_mask = &eth_dmamask, .coherent_dma_mask = 0xffffffff, }, .resource = ks8695_hpna_resources, .num_resources = ARRAY_SIZE(ks8695_hpna_resources), }; void __init ks8695_add_device_wan(void) { platform_device_register(&ks8695_wan_device); } void __init ks8695_add_device_lan(void) { platform_device_register(&ks8695_lan_device); } void __init ks8696_add_device_hpna(void) { platform_device_register(&ks8695_hpna_device); } /* -------------------------------------------------------------------- * Watchdog * -------------------------------------------------------------------- */ static struct platform_device ks8695_wdt_device = { .name = "ks8695_wdt", .id = -1, .num_resources = 0, }; static void __init ks8695_add_device_watchdog(void) { platform_device_register(&ks8695_wdt_device); } /* -------------------------------------------------------------------- * LEDs * -------------------------------------------------------------------- */ #if defined(CONFIG_LEDS) short ks8695_leds_cpu = -1; short ks8695_leds_timer = -1; void __init ks8695_init_leds(u8 cpu_led, u8 timer_led) { /* Enable GPIO to access the LEDs */ gpio_direction_output(cpu_led, 1); gpio_direction_output(timer_led, 1); ks8695_leds_cpu = cpu_led; ks8695_leds_timer = timer_led; } #else void __init ks8695_init_leds(u8 cpu_led, u8 timer_led) {} #endif /* -------------------------------------------------------------------- */ /* * These devices are always present and don't need any board-specific * setup. */ static int __init ks8695_add_standard_devices(void) { ks8695_add_device_watchdog(); return 0; } arch_initcall(ks8695_add_standard_devices);
1DeMaCr/android_kernel_samsung_codina
arch/arm/mach-ks8695/devices.c
C
gpl-2.0
5,114
/* * linux/arch/arm/mach-pxa/pxa3xx.c * * code specific to pxa3xx aka Monahans * * Copyright (C) 2006 Marvell International Ltd. * * 2007-09-02: eric miao <eric.miao@marvell.com> * initial version * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/pm.h> #include <linux/platform_device.h> #include <linux/irq.h> #include <linux/io.h> #include <linux/syscore_ops.h> #include <linux/i2c/pxa-i2c.h> #include <asm/mach/map.h> #include <asm/suspend.h> #include <mach/hardware.h> #include <mach/pxa3xx-regs.h> #include <mach/reset.h> #include <mach/ohci.h> #include <mach/pm.h> #include <mach/dma.h> #include <mach/smemc.h> #include <mach/irqs.h> #include "generic.h" #include "devices.h" #include "clock.h" #define PECR_IE(n) ((1 << ((n) * 2)) << 28) #define PECR_IS(n) ((1 << ((n) * 2)) << 29) static DEFINE_PXA3_CKEN(pxa3xx_ffuart, FFUART, 14857000, 1); static DEFINE_PXA3_CKEN(pxa3xx_btuart, BTUART, 14857000, 1); static DEFINE_PXA3_CKEN(pxa3xx_stuart, STUART, 14857000, 1); static DEFINE_PXA3_CKEN(pxa3xx_i2c, I2C, 32842000, 0); static DEFINE_PXA3_CKEN(pxa3xx_udc, UDC, 48000000, 5); static DEFINE_PXA3_CKEN(pxa3xx_usbh, USBH, 48000000, 0); static DEFINE_PXA3_CKEN(pxa3xx_u2d, USB2, 48000000, 0); static DEFINE_PXA3_CKEN(pxa3xx_keypad, KEYPAD, 32768, 0); static DEFINE_PXA3_CKEN(pxa3xx_ssp1, SSP1, 13000000, 0); static DEFINE_PXA3_CKEN(pxa3xx_ssp2, SSP2, 13000000, 0); static DEFINE_PXA3_CKEN(pxa3xx_ssp3, SSP3, 13000000, 0); static DEFINE_PXA3_CKEN(pxa3xx_ssp4, SSP4, 13000000, 0); static DEFINE_PXA3_CKEN(pxa3xx_pwm0, PWM0, 13000000, 0); static DEFINE_PXA3_CKEN(pxa3xx_pwm1, PWM1, 13000000, 0); static DEFINE_PXA3_CKEN(pxa3xx_mmc1, MMC1, 19500000, 0); static DEFINE_PXA3_CKEN(pxa3xx_mmc2, MMC2, 19500000, 0); static DEFINE_PXA3_CKEN(pxa3xx_gpio, GPIO, 13000000, 0); static DEFINE_CK(pxa3xx_lcd, LCD, &clk_pxa3xx_hsio_ops); static DEFINE_CK(pxa3xx_smemc, SMC, &clk_pxa3xx_smemc_ops); static DEFINE_CK(pxa3xx_camera, CAMERA, &clk_pxa3xx_hsio_ops); static DEFINE_CK(pxa3xx_ac97, AC97, &clk_pxa3xx_ac97_ops); static DEFINE_CLK(pxa3xx_pout, &clk_pxa3xx_pout_ops, 13000000, 70); static struct clk_lookup pxa3xx_clkregs[] = { INIT_CLKREG(&clk_pxa3xx_pout, NULL, "CLK_POUT"), /* Power I2C clock is always on */ INIT_CLKREG(&clk_dummy, "pxa3xx-pwri2c.1", NULL), INIT_CLKREG(&clk_pxa3xx_lcd, "pxa2xx-fb", NULL), INIT_CLKREG(&clk_pxa3xx_camera, NULL, "CAMCLK"), INIT_CLKREG(&clk_pxa3xx_ac97, NULL, "AC97CLK"), INIT_CLKREG(&clk_pxa3xx_ffuart, "pxa2xx-uart.0", NULL), INIT_CLKREG(&clk_pxa3xx_btuart, "pxa2xx-uart.1", NULL), INIT_CLKREG(&clk_pxa3xx_stuart, "pxa2xx-uart.2", NULL), INIT_CLKREG(&clk_pxa3xx_stuart, "pxa2xx-ir", "UARTCLK"), INIT_CLKREG(&clk_pxa3xx_i2c, "pxa2xx-i2c.0", NULL), INIT_CLKREG(&clk_pxa3xx_udc, "pxa27x-udc", NULL), INIT_CLKREG(&clk_pxa3xx_usbh, "pxa27x-ohci", NULL), INIT_CLKREG(&clk_pxa3xx_u2d, "pxa3xx-u2d", NULL), INIT_CLKREG(&clk_pxa3xx_keypad, "pxa27x-keypad", NULL), INIT_CLKREG(&clk_pxa3xx_ssp1, "pxa27x-ssp.0", NULL), INIT_CLKREG(&clk_pxa3xx_ssp2, "pxa27x-ssp.1", NULL), INIT_CLKREG(&clk_pxa3xx_ssp3, "pxa27x-ssp.2", NULL), INIT_CLKREG(&clk_pxa3xx_ssp4, "pxa27x-ssp.3", NULL), INIT_CLKREG(&clk_pxa3xx_pwm0, "pxa27x-pwm.0", NULL), INIT_CLKREG(&clk_pxa3xx_pwm1, "pxa27x-pwm.1", NULL), INIT_CLKREG(&clk_pxa3xx_mmc1, "pxa2xx-mci.0", NULL), INIT_CLKREG(&clk_pxa3xx_mmc2, "pxa2xx-mci.1", NULL), INIT_CLKREG(&clk_pxa3xx_smemc, "pxa2xx-pcmcia", NULL), INIT_CLKREG(&clk_pxa3xx_gpio, "pxa-gpio", NULL), INIT_CLKREG(&clk_dummy, "sa1100-rtc", NULL), }; #ifdef CONFIG_PM #define ISRAM_START 0x5c000000 #define ISRAM_SIZE SZ_256K static void __iomem *sram; static unsigned long wakeup_src; /* * Enter a standby mode (S0D1C2 or S0D2C2). Upon wakeup, the dynamic * memory controller has to be reinitialised, so we place some code * in the SRAM to perform this function. * * We disable FIQs across the standby - otherwise, we might receive a * FIQ while the SDRAM is unavailable. */ static void pxa3xx_cpu_standby(unsigned int pwrmode) { extern const char pm_enter_standby_start[], pm_enter_standby_end[]; void (*fn)(unsigned int) = (void __force *)(sram + 0x8000); memcpy_toio(sram + 0x8000, pm_enter_standby_start, pm_enter_standby_end - pm_enter_standby_start); AD2D0SR = ~0; AD2D1SR = ~0; AD2D0ER = wakeup_src; AD2D1ER = 0; ASCR = ASCR; ARSR = ARSR; local_fiq_disable(); fn(pwrmode); local_fiq_enable(); AD2D0ER = 0; AD2D1ER = 0; } /* * NOTE: currently, the OBM (OEM Boot Module) binary comes along with * PXA3xx development kits assumes that the resuming process continues * with the address stored within the first 4 bytes of SDRAM. The PSPR * register is used privately by BootROM and OBM, and _must_ be set to * 0x5c014000 for the moment. */ static void pxa3xx_cpu_pm_suspend(void) { volatile unsigned long *p = (volatile void *)0xc0000000; unsigned long saved_data = *p; #ifndef CONFIG_IWMMXT u64 acc0; asm volatile("mra %Q0, %R0, acc0" : "=r" (acc0)); #endif extern int pxa3xx_finish_suspend(unsigned long); /* resuming from D2 requires the HSIO2/BOOT/TPM clocks enabled */ CKENA |= (1 << CKEN_BOOT) | (1 << CKEN_TPM); CKENB |= 1 << (CKEN_HSIO2 & 0x1f); /* clear and setup wakeup source */ AD3SR = ~0; AD3ER = wakeup_src; ASCR = ASCR; ARSR = ARSR; PCFR |= (1u << 13); /* L1_DIS */ PCFR &= ~((1u << 12) | (1u << 1)); /* L0_EN | SL_ROD */ PSPR = 0x5c014000; /* overwrite with the resume address */ *p = virt_to_phys(cpu_resume); cpu_suspend(0, pxa3xx_finish_suspend); *p = saved_data; AD3ER = 0; #ifndef CONFIG_IWMMXT asm volatile("mar acc0, %Q0, %R0" : "=r" (acc0)); #endif } static void pxa3xx_cpu_pm_enter(suspend_state_t state) { /* * Don't sleep if no wakeup sources are defined */ if (wakeup_src == 0) { printk(KERN_ERR "Not suspending: no wakeup sources\n"); return; } switch (state) { case PM_SUSPEND_STANDBY: pxa3xx_cpu_standby(PXA3xx_PM_S0D2C2); break; case PM_SUSPEND_MEM: pxa3xx_cpu_pm_suspend(); break; } } static int pxa3xx_cpu_pm_valid(suspend_state_t state) { return state == PM_SUSPEND_MEM || state == PM_SUSPEND_STANDBY; } static struct pxa_cpu_pm_fns pxa3xx_cpu_pm_fns = { .valid = pxa3xx_cpu_pm_valid, .enter = pxa3xx_cpu_pm_enter, }; static void __init pxa3xx_init_pm(void) { sram = ioremap(ISRAM_START, ISRAM_SIZE); if (!sram) { printk(KERN_ERR "Unable to map ISRAM: disabling standby/suspend\n"); return; } /* * Since we copy wakeup code into the SRAM, we need to ensure * that it is preserved over the low power modes. Note: bit 8 * is undocumented in the developer manual, but must be set. */ AD1R |= ADXR_L2 | ADXR_R0; AD2R |= ADXR_L2 | ADXR_R0; AD3R |= ADXR_L2 | ADXR_R0; /* * Clear the resume enable registers. */ AD1D0ER = 0; AD2D0ER = 0; AD2D1ER = 0; AD3ER = 0; pxa_cpu_pm_fns = &pxa3xx_cpu_pm_fns; } static int pxa3xx_set_wake(struct irq_data *d, unsigned int on) { unsigned long flags, mask = 0; switch (d->irq) { case IRQ_SSP3: mask = ADXER_MFP_WSSP3; break; case IRQ_MSL: mask = ADXER_WMSL0; break; case IRQ_USBH2: case IRQ_USBH1: mask = ADXER_WUSBH; break; case IRQ_KEYPAD: mask = ADXER_WKP; break; case IRQ_AC97: mask = ADXER_MFP_WAC97; break; case IRQ_USIM: mask = ADXER_WUSIM0; break; case IRQ_SSP2: mask = ADXER_MFP_WSSP2; break; case IRQ_I2C: mask = ADXER_MFP_WI2C; break; case IRQ_STUART: mask = ADXER_MFP_WUART3; break; case IRQ_BTUART: mask = ADXER_MFP_WUART2; break; case IRQ_FFUART: mask = ADXER_MFP_WUART1; break; case IRQ_MMC: mask = ADXER_MFP_WMMC1; break; case IRQ_SSP: mask = ADXER_MFP_WSSP1; break; case IRQ_RTCAlrm: mask = ADXER_WRTC; break; case IRQ_SSP4: mask = ADXER_MFP_WSSP4; break; case IRQ_TSI: mask = ADXER_WTSI; break; case IRQ_USIM2: mask = ADXER_WUSIM1; break; case IRQ_MMC2: mask = ADXER_MFP_WMMC2; break; case IRQ_NAND: mask = ADXER_MFP_WFLASH; break; case IRQ_USB2: mask = ADXER_WUSB2; break; case IRQ_WAKEUP0: mask = ADXER_WEXTWAKE0; break; case IRQ_WAKEUP1: mask = ADXER_WEXTWAKE1; break; case IRQ_MMC3: mask = ADXER_MFP_GEN12; break; default: return -EINVAL; } local_irq_save(flags); if (on) wakeup_src |= mask; else wakeup_src &= ~mask; local_irq_restore(flags); return 0; } #else static inline void pxa3xx_init_pm(void) {} #define pxa3xx_set_wake NULL #endif static void pxa_ack_ext_wakeup(struct irq_data *d) { PECR |= PECR_IS(d->irq - IRQ_WAKEUP0); } static void pxa_mask_ext_wakeup(struct irq_data *d) { pxa_mask_irq(d); PECR &= ~PECR_IE(d->irq - IRQ_WAKEUP0); } static void pxa_unmask_ext_wakeup(struct irq_data *d) { pxa_unmask_irq(d); PECR |= PECR_IE(d->irq - IRQ_WAKEUP0); } static int pxa_set_ext_wakeup_type(struct irq_data *d, unsigned int flow_type) { if (flow_type & IRQ_TYPE_EDGE_RISING) PWER |= 1 << (d->irq - IRQ_WAKEUP0); if (flow_type & IRQ_TYPE_EDGE_FALLING) PWER |= 1 << (d->irq - IRQ_WAKEUP0 + 2); return 0; } static struct irq_chip pxa_ext_wakeup_chip = { .name = "WAKEUP", .irq_ack = pxa_ack_ext_wakeup, .irq_mask = pxa_mask_ext_wakeup, .irq_unmask = pxa_unmask_ext_wakeup, .irq_set_type = pxa_set_ext_wakeup_type, }; static void __init pxa_init_ext_wakeup_irq(int (*fn)(struct irq_data *, unsigned int)) { int irq; for (irq = IRQ_WAKEUP0; irq <= IRQ_WAKEUP1; irq++) { irq_set_chip_and_handler(irq, &pxa_ext_wakeup_chip, handle_edge_irq); set_irq_flags(irq, IRQF_VALID); } pxa_ext_wakeup_chip.irq_set_wake = fn; } void __init pxa3xx_init_irq(void) { /* enable CP6 access */ u32 value; __asm__ __volatile__("mrc p15, 0, %0, c15, c1, 0\n": "=r"(value)); value |= (1 << 6); __asm__ __volatile__("mcr p15, 0, %0, c15, c1, 0\n": :"r"(value)); pxa_init_irq(56, pxa3xx_set_wake); pxa_init_ext_wakeup_irq(pxa3xx_set_wake); } static struct map_desc pxa3xx_io_desc[] __initdata = { { /* Mem Ctl */ .virtual = (unsigned long)SMEMC_VIRT, .pfn = __phys_to_pfn(PXA3XX_SMEMC_BASE), .length = 0x00200000, .type = MT_DEVICE } }; void __init pxa3xx_map_io(void) { pxa_map_io(); iotable_init(ARRAY_AND_SIZE(pxa3xx_io_desc)); pxa3xx_get_clk_frequency_khz(1); } /* * device registration specific to PXA3xx. */ void __init pxa3xx_set_i2c_power_info(struct i2c_pxa_platform_data *info) { pxa_register_device(&pxa3xx_device_i2c_power, info); } static struct platform_device *devices[] __initdata = { &pxa_device_gpio, &pxa27x_device_udc, &pxa_device_pmu, &pxa_device_i2s, &pxa_device_asoc_ssp1, &pxa_device_asoc_ssp2, &pxa_device_asoc_ssp3, &pxa_device_asoc_ssp4, &pxa_device_asoc_platform, &sa1100_device_rtc, &pxa_device_rtc, &pxa27x_device_ssp1, &pxa27x_device_ssp2, &pxa27x_device_ssp3, &pxa3xx_device_ssp4, &pxa27x_device_pwm0, &pxa27x_device_pwm1, }; static int __init pxa3xx_init(void) { int ret = 0; if (cpu_is_pxa3xx()) { reset_status = ARSR; /* * clear RDH bit every time after reset * * Note: the last 3 bits DxS are write-1-to-clear so carefully * preserve them here in case they will be referenced later */ ASCR &= ~(ASCR_RDH | ASCR_D1S | ASCR_D2S | ASCR_D3S); clkdev_add_table(pxa3xx_clkregs, ARRAY_SIZE(pxa3xx_clkregs)); if ((ret = pxa_init_dma(IRQ_DMA, 32))) return ret; pxa3xx_init_pm(); register_syscore_ops(&pxa_irq_syscore_ops); register_syscore_ops(&pxa3xx_mfp_syscore_ops); register_syscore_ops(&pxa3xx_clock_syscore_ops); ret = platform_add_devices(devices, ARRAY_SIZE(devices)); } return ret; } postcore_initcall(pxa3xx_init);
Validus-Kernel/android_kernel_oneplus_msm8974
arch/arm/mach-pxa/pxa3xx.c
C
gpl-2.0
11,752
/*! * jQuery UI Selectable 1.11.4 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/selectable/ */ !function(a){"function"==typeof define&&define.amd?define(["jquery","./core","./mouse","./widget"],a):a(jQuery)}(function(a){return a.widget("ui.selectable",a.ui.mouse,{version:"1.11.4",options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch",selected:null,selecting:null,start:null,stop:null,unselected:null,unselecting:null},_create:function(){var b,c=this;this.element.addClass("ui-selectable"),this.dragged=!1,this.refresh=function(){b=a(c.options.filter,c.element[0]),b.addClass("ui-selectee"),b.each(function(){var b=a(this),c=b.offset();a.data(this,"selectable-item",{element:this,$element:b,left:c.left,top:c.top,right:c.left+b.outerWidth(),bottom:c.top+b.outerHeight(),startselected:!1,selected:b.hasClass("ui-selected"),selecting:b.hasClass("ui-selecting"),unselecting:b.hasClass("ui-unselecting")})})},this.refresh(),this.selectees=b.addClass("ui-selectee"),this._mouseInit(),this.helper=a("<div class='ui-selectable-helper'></div>")},_destroy:function(){this.selectees.removeClass("ui-selectee").removeData("selectable-item"),this.element.removeClass("ui-selectable ui-selectable-disabled"),this._mouseDestroy()},_mouseStart:function(b){var c=this,d=this.options;this.opos=[b.pageX,b.pageY],this.options.disabled||(this.selectees=a(d.filter,this.element[0]),this._trigger("start",b),a(d.appendTo).append(this.helper),this.helper.css({left:b.pageX,top:b.pageY,width:0,height:0}),d.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var d=a.data(this,"selectable-item");d.startselected=!0,b.metaKey||b.ctrlKey||(d.$element.removeClass("ui-selected"),d.selected=!1,d.$element.addClass("ui-unselecting"),d.unselecting=!0,c._trigger("unselecting",b,{unselecting:d.element}))}),a(b.target).parents().addBack().each(function(){var d,e=a.data(this,"selectable-item");return e?(d=!b.metaKey&&!b.ctrlKey||!e.$element.hasClass("ui-selected"),e.$element.removeClass(d?"ui-unselecting":"ui-selected").addClass(d?"ui-selecting":"ui-unselecting"),e.unselecting=!d,e.selecting=d,e.selected=d,d?c._trigger("selecting",b,{selecting:e.element}):c._trigger("unselecting",b,{unselecting:e.element}),!1):void 0}))},_mouseDrag:function(b){if(this.dragged=!0,!this.options.disabled){var c,d=this,e=this.options,f=this.opos[0],g=this.opos[1],h=b.pageX,i=b.pageY;return f>h&&(c=h,h=f,f=c),g>i&&(c=i,i=g,g=c),this.helper.css({left:f,top:g,width:h-f,height:i-g}),this.selectees.each(function(){var c=a.data(this,"selectable-item"),j=!1;c&&c.element!==d.element[0]&&("touch"===e.tolerance?j=!(c.left>h||c.right<f||c.top>i||c.bottom<g):"fit"===e.tolerance&&(j=c.left>f&&c.right<h&&c.top>g&&c.bottom<i),j?(c.selected&&(c.$element.removeClass("ui-selected"),c.selected=!1),c.unselecting&&(c.$element.removeClass("ui-unselecting"),c.unselecting=!1),c.selecting||(c.$element.addClass("ui-selecting"),c.selecting=!0,d._trigger("selecting",b,{selecting:c.element}))):(c.selecting&&((b.metaKey||b.ctrlKey)&&c.startselected?(c.$element.removeClass("ui-selecting"),c.selecting=!1,c.$element.addClass("ui-selected"),c.selected=!0):(c.$element.removeClass("ui-selecting"),c.selecting=!1,c.startselected&&(c.$element.addClass("ui-unselecting"),c.unselecting=!0),d._trigger("unselecting",b,{unselecting:c.element}))),c.selected&&(b.metaKey||b.ctrlKey||c.startselected||(c.$element.removeClass("ui-selected"),c.selected=!1,c.$element.addClass("ui-unselecting"),c.unselecting=!0,d._trigger("unselecting",b,{unselecting:c.element})))))}),!1}},_mouseStop:function(b){var c=this;return this.dragged=!1,a(".ui-unselecting",this.element[0]).each(function(){var d=a.data(this,"selectable-item");d.$element.removeClass("ui-unselecting"),d.unselecting=!1,d.startselected=!1,c._trigger("unselected",b,{unselected:d.element})}),a(".ui-selecting",this.element[0]).each(function(){var d=a.data(this,"selectable-item");d.$element.removeClass("ui-selecting").addClass("ui-selected"),d.selecting=!1,d.selected=!0,d.startselected=!0,c._trigger("selected",b,{selected:d.element})}),this._trigger("stop",b),this.helper.remove(),!1}})});
Webovation/WordPress-Starter-Theme
wp-includes/js/jquery/ui/selectable.min.js
JavaScript
gpl-2.0
4,264
/* * Handle mapping of the flash memory access routines * on TQM8xxL based devices. * * based on rpxlite.c * * Copyright(C) 2001 Kirk Lee <kirk@hpc.ee.ntu.edu.tw> * * This code is GPLed * */ /* * According to TQM8xxL hardware manual, TQM8xxL series have * following flash memory organisations: * | capacity | | chip type | | bank0 | | bank1 | * 2MiB 512Kx16 2MiB 0 * 4MiB 1Mx16 4MiB 0 * 8MiB 1Mx16 4MiB 4MiB * Thus, we choose CONFIG_MTD_CFI_I2 & CONFIG_MTD_CFI_B4 at * kernel configuration. */ #include <linux/module.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/mtd/mtd.h> #include <linux/mtd/map.h> #include <linux/mtd/partitions.h> #include <asm/io.h> #define FLASH_ADDR 0x40000000 #define FLASH_SIZE 0x00800000 #define FLASH_BANK_MAX 4 // trivial struct to describe partition information struct mtd_part_def { int nums; unsigned char *type; struct mtd_partition* mtd_part; }; //static struct mtd_info *mymtd; static struct mtd_info* mtd_banks[FLASH_BANK_MAX]; static struct map_info* map_banks[FLASH_BANK_MAX]; static struct mtd_part_def part_banks[FLASH_BANK_MAX]; static unsigned long num_banks; static void __iomem *start_scan_addr; /* * Here are partition information for all known TQM8xxL series devices. * See include/linux/mtd/partitions.h for definition of the mtd_partition * structure. * * The *_max_flash_size is the maximum possible mapped flash size which * is not necessarily the actual flash size. It must correspond to the * value specified in the mapping definition defined by the * "struct map_desc *_io_desc" for the corresponding machine. */ /* Currently, TQM8xxL has up to 8MiB flash */ static unsigned long tqm8xxl_max_flash_size = 0x00800000; /* partition definition for first flash bank * (cf. "drivers/char/flash_config.c") */ static struct mtd_partition tqm8xxl_partitions[] = { { .name = "ppcboot", .offset = 0x00000000, .size = 0x00020000, /* 128KB */ .mask_flags = MTD_WRITEABLE, /* force read-only */ }, { .name = "kernel", /* default kernel image */ .offset = 0x00020000, .size = 0x000e0000, .mask_flags = MTD_WRITEABLE, /* force read-only */ }, { .name = "user", .offset = 0x00100000, .size = 0x00100000, }, { .name = "initrd", .offset = 0x00200000, .size = 0x00200000, } }; /* partition definition for second flash bank */ static struct mtd_partition tqm8xxl_fs_partitions[] = { { .name = "cramfs", .offset = 0x00000000, .size = 0x00200000, }, { .name = "jffs", .offset = 0x00200000, .size = 0x00200000, //.size = MTDPART_SIZ_FULL, } }; static int __init init_tqm_mtd(void) { int idx = 0, ret = 0; unsigned long flash_addr, flash_size, mtd_size = 0; /* pointer to TQM8xxL board info data */ bd_t *bd = (bd_t *)__res; flash_addr = bd->bi_flashstart; flash_size = bd->bi_flashsize; //request maximum flash size address space start_scan_addr = ioremap(flash_addr, flash_size); if (!start_scan_addr) { printk(KERN_WARNING "%s:Failed to ioremap address:0x%x\n", __func__, flash_addr); return -EIO; } for (idx = 0 ; idx < FLASH_BANK_MAX ; idx++) { if(mtd_size >= flash_size) break; printk(KERN_INFO "%s: chip probing count %d\n", __func__, idx); map_banks[idx] = kzalloc(sizeof(struct map_info), GFP_KERNEL); if(map_banks[idx] == NULL) { ret = -ENOMEM; /* FIXME: What if some MTD devices were probed already? */ goto error_mem; } map_banks[idx]->name = kmalloc(16, GFP_KERNEL); if (!map_banks[idx]->name) { ret = -ENOMEM; /* FIXME: What if some MTD devices were probed already? */ goto error_mem; } sprintf(map_banks[idx]->name, "TQM8xxL%d", idx); map_banks[idx]->size = flash_size; map_banks[idx]->bankwidth = 4; simple_map_init(map_banks[idx]); map_banks[idx]->virt = start_scan_addr; map_banks[idx]->phys = flash_addr; /* FIXME: This looks utterly bogus, but I'm trying to preserve the behaviour of the original (shown here)... map_banks[idx]->map_priv_1 = start_scan_addr + ((idx > 0) ? (mtd_banks[idx-1] ? mtd_banks[idx-1]->size : 0) : 0); */ if (idx && mtd_banks[idx-1]) { map_banks[idx]->virt += mtd_banks[idx-1]->size; map_banks[idx]->phys += mtd_banks[idx-1]->size; } //start to probe flash chips mtd_banks[idx] = do_map_probe("cfi_probe", map_banks[idx]); if (mtd_banks[idx]) { mtd_banks[idx]->owner = THIS_MODULE; mtd_size += mtd_banks[idx]->size; num_banks++; printk(KERN_INFO "%s: bank%d, name:%s, size:%dbytes \n", __func__, num_banks, mtd_banks[idx]->name, mtd_banks[idx]->size); } } /* no supported flash chips found */ if (!num_banks) { printk(KERN_NOTICE "TQM8xxL: No support flash chips found!\n"); ret = -ENXIO; goto error_mem; } /* * Select Static partition definitions */ part_banks[0].mtd_part = tqm8xxl_partitions; part_banks[0].type = "Static image"; part_banks[0].nums = ARRAY_SIZE(tqm8xxl_partitions); part_banks[1].mtd_part = tqm8xxl_fs_partitions; part_banks[1].type = "Static file system"; part_banks[1].nums = ARRAY_SIZE(tqm8xxl_fs_partitions); for(idx = 0; idx < num_banks ; idx++) { if (part_banks[idx].nums == 0) printk(KERN_NOTICE "TQM flash%d: no partition info available, registering whole flash at once\n", idx); else printk(KERN_NOTICE "TQM flash%d: Using %s partition definition\n", idx, part_banks[idx].type); mtd_device_register(mtd_banks[idx], part_banks[idx].mtd_part, part_banks[idx].nums); } return 0; error_mem: for(idx = 0 ; idx < FLASH_BANK_MAX ; idx++) { if(map_banks[idx] != NULL) { kfree(map_banks[idx]->name); map_banks[idx]->name = NULL; kfree(map_banks[idx]); map_banks[idx] = NULL; } } error: iounmap(start_scan_addr); return ret; } static void __exit cleanup_tqm_mtd(void) { unsigned int idx = 0; for(idx = 0 ; idx < num_banks ; idx++) { /* destroy mtd_info previously allocated */ if (mtd_banks[idx]) { mtd_device_unregister(mtd_banks[idx]); map_destroy(mtd_banks[idx]); } /* release map_info not used anymore */ kfree(map_banks[idx]->name); kfree(map_banks[idx]); } if (start_scan_addr) { iounmap(start_scan_addr); start_scan_addr = 0; } } module_init(init_tqm_mtd); module_exit(cleanup_tqm_mtd); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Kirk Lee <kirk@hpc.ee.ntu.edu.tw>"); MODULE_DESCRIPTION("MTD map driver for TQM8xxL boards");
DirtyUnicorns/android_kernel_motorola_msm8226
drivers/mtd/maps/tqm8xxl.c
C
gpl-2.0
6,508
/********************************************************************* * * Filename: ircomm_core.c * Version: 1.0 * Description: IrCOMM service interface * Status: Experimental. * Author: Dag Brattli <dagb@cs.uit.no> * Created at: Sun Jun 6 20:37:34 1999 * Modified at: Tue Dec 21 13:26:41 1999 * Modified by: Dag Brattli <dagb@cs.uit.no> * * Copyright (c) 1999 Dag Brattli, All Rights Reserved. * Copyright (c) 2000-2003 Jean Tourrilhes <jt@hpl.hp.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ********************************************************************/ #include <linux/module.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/init.h> #include <linux/slab.h> #include <net/irda/irda.h> #include <net/irda/irmod.h> #include <net/irda/irlmp.h> #include <net/irda/iriap.h> #include <net/irda/irttp.h> #include <net/irda/irias_object.h> #include <net/irda/ircomm_event.h> #include <net/irda/ircomm_lmp.h> #include <net/irda/ircomm_ttp.h> #include <net/irda/ircomm_param.h> #include <net/irda/ircomm_core.h> static int __ircomm_close(struct ircomm_cb *self); static void ircomm_control_indication(struct ircomm_cb *self, struct sk_buff *skb, int clen); #ifdef CONFIG_PROC_FS extern struct proc_dir_entry *proc_irda; static int ircomm_seq_open(struct inode *, struct file *); static const struct file_operations ircomm_proc_fops = { .owner = THIS_MODULE, .open = ircomm_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; #endif /* CONFIG_PROC_FS */ hashbin_t *ircomm = NULL; static int __init ircomm_init(void) { ircomm = hashbin_new(HB_LOCK); if (ircomm == NULL) { IRDA_ERROR("%s(), can't allocate hashbin!\n", __func__); return -ENOMEM; } #ifdef CONFIG_PROC_FS { struct proc_dir_entry *ent; ent = proc_create("ircomm", 0, proc_irda, &ircomm_proc_fops); if (!ent) { printk(KERN_ERR "ircomm_init: can't create /proc entry!\n"); return -ENODEV; } } #endif /* CONFIG_PROC_FS */ IRDA_MESSAGE("IrCOMM protocol (Dag Brattli)\n"); return 0; } static void __exit ircomm_cleanup(void) { IRDA_DEBUG(2, "%s()\n", __func__ ); hashbin_delete(ircomm, (FREE_FUNC) __ircomm_close); #ifdef CONFIG_PROC_FS remove_proc_entry("ircomm", proc_irda); #endif /* CONFIG_PROC_FS */ } /* * Function ircomm_open (client_notify) * * Start a new IrCOMM instance * */ struct ircomm_cb *ircomm_open(notify_t *notify, __u8 service_type, int line) { struct ircomm_cb *self = NULL; int ret; IRDA_DEBUG(2, "%s(), service_type=0x%02x\n", __func__ , service_type); IRDA_ASSERT(ircomm != NULL, return NULL;); self = kzalloc(sizeof(struct ircomm_cb), GFP_ATOMIC); if (self == NULL) return NULL; self->notify = *notify; self->magic = IRCOMM_MAGIC; /* Check if we should use IrLMP or IrTTP */ if (service_type & IRCOMM_3_WIRE_RAW) { self->flow_status = FLOW_START; ret = ircomm_open_lsap(self); } else ret = ircomm_open_tsap(self); if (ret < 0) { kfree(self); return NULL; } self->service_type = service_type; self->line = line; hashbin_insert(ircomm, (irda_queue_t *) self, line, NULL); ircomm_next_state(self, IRCOMM_IDLE); return self; } EXPORT_SYMBOL(ircomm_open); /* * Function ircomm_close_instance (self) * * Remove IrCOMM instance * */ static int __ircomm_close(struct ircomm_cb *self) { IRDA_DEBUG(2, "%s()\n", __func__ ); /* Disconnect link if any */ ircomm_do_event(self, IRCOMM_DISCONNECT_REQUEST, NULL, NULL); /* Remove TSAP */ if (self->tsap) { irttp_close_tsap(self->tsap); self->tsap = NULL; } /* Remove LSAP */ if (self->lsap) { irlmp_close_lsap(self->lsap); self->lsap = NULL; } self->magic = 0; kfree(self); return 0; } /* * Function ircomm_close (self) * * Closes and removes the specified IrCOMM instance * */ int ircomm_close(struct ircomm_cb *self) { struct ircomm_cb *entry; IRDA_ASSERT(self != NULL, return -EIO;); IRDA_ASSERT(self->magic == IRCOMM_MAGIC, return -EIO;); IRDA_DEBUG(0, "%s()\n", __func__ ); entry = hashbin_remove(ircomm, self->line, NULL); IRDA_ASSERT(entry == self, return -1;); return __ircomm_close(self); } EXPORT_SYMBOL(ircomm_close); /* * Function ircomm_connect_request (self, service_type) * * Impl. of this function is differ from one of the reference. This * function does discovery as well as sending connect request * */ int ircomm_connect_request(struct ircomm_cb *self, __u8 dlsap_sel, __u32 saddr, __u32 daddr, struct sk_buff *skb, __u8 service_type) { struct ircomm_info info; int ret; IRDA_DEBUG(2 , "%s()\n", __func__ ); IRDA_ASSERT(self != NULL, return -1;); IRDA_ASSERT(self->magic == IRCOMM_MAGIC, return -1;); self->service_type= service_type; info.dlsap_sel = dlsap_sel; info.saddr = saddr; info.daddr = daddr; ret = ircomm_do_event(self, IRCOMM_CONNECT_REQUEST, skb, &info); return ret; } EXPORT_SYMBOL(ircomm_connect_request); /* * Function ircomm_connect_indication (self, qos, skb) * * Notify user layer about the incoming connection * */ void ircomm_connect_indication(struct ircomm_cb *self, struct sk_buff *skb, struct ircomm_info *info) { IRDA_DEBUG(2, "%s()\n", __func__ ); /* * If there are any data hiding in the control channel, we must * deliver it first. The side effect is that the control channel * will be removed from the skb */ if (self->notify.connect_indication) self->notify.connect_indication(self->notify.instance, self, info->qos, info->max_data_size, info->max_header_size, skb); else { IRDA_DEBUG(0, "%s(), missing handler\n", __func__ ); } } /* * Function ircomm_connect_response (self, userdata, max_sdu_size) * * User accepts connection * */ int ircomm_connect_response(struct ircomm_cb *self, struct sk_buff *userdata) { int ret; IRDA_ASSERT(self != NULL, return -1;); IRDA_ASSERT(self->magic == IRCOMM_MAGIC, return -1;); IRDA_DEBUG(4, "%s()\n", __func__ ); ret = ircomm_do_event(self, IRCOMM_CONNECT_RESPONSE, userdata, NULL); return ret; } EXPORT_SYMBOL(ircomm_connect_response); /* * Function connect_confirm (self, skb) * * Notify user layer that the link is now connected * */ void ircomm_connect_confirm(struct ircomm_cb *self, struct sk_buff *skb, struct ircomm_info *info) { IRDA_DEBUG(4, "%s()\n", __func__ ); if (self->notify.connect_confirm ) self->notify.connect_confirm(self->notify.instance, self, info->qos, info->max_data_size, info->max_header_size, skb); else { IRDA_DEBUG(0, "%s(), missing handler\n", __func__ ); } } /* * Function ircomm_data_request (self, userdata) * * Send IrCOMM data to peer device * */ int ircomm_data_request(struct ircomm_cb *self, struct sk_buff *skb) { int ret; IRDA_DEBUG(4, "%s()\n", __func__ ); IRDA_ASSERT(self != NULL, return -EFAULT;); IRDA_ASSERT(self->magic == IRCOMM_MAGIC, return -EFAULT;); IRDA_ASSERT(skb != NULL, return -EFAULT;); ret = ircomm_do_event(self, IRCOMM_DATA_REQUEST, skb, NULL); return ret; } EXPORT_SYMBOL(ircomm_data_request); /* * Function ircomm_data_indication (self, skb) * * Data arrived, so deliver it to user * */ void ircomm_data_indication(struct ircomm_cb *self, struct sk_buff *skb) { IRDA_DEBUG(4, "%s()\n", __func__ ); IRDA_ASSERT(skb->len > 0, return;); if (self->notify.data_indication) self->notify.data_indication(self->notify.instance, self, skb); else { IRDA_DEBUG(0, "%s(), missing handler\n", __func__ ); } } /* * Function ircomm_process_data (self, skb) * * Data arrived which may contain control channel data * */ void ircomm_process_data(struct ircomm_cb *self, struct sk_buff *skb) { int clen; IRDA_ASSERT(skb->len > 0, return;); clen = skb->data[0]; /* * Input validation check: a stir4200/mcp2150 combinations sometimes * results in frames with clen > remaining packet size. These are * illegal; if we throw away just this frame then it seems to carry on * fine */ if (unlikely(skb->len < (clen + 1))) { IRDA_DEBUG(2, "%s() throwing away illegal frame\n", __func__ ); return; } /* * If there are any data hiding in the control channel, we must * deliver it first. The side effect is that the control channel * will be removed from the skb */ if (clen > 0) ircomm_control_indication(self, skb, clen); /* Remove control channel from data channel */ skb_pull(skb, clen+1); if (skb->len) ircomm_data_indication(self, skb); else { IRDA_DEBUG(4, "%s(), data was control info only!\n", __func__ ); } } /* * Function ircomm_control_request (self, params) * * Send control data to peer device * */ int ircomm_control_request(struct ircomm_cb *self, struct sk_buff *skb) { int ret; IRDA_DEBUG(2, "%s()\n", __func__ ); IRDA_ASSERT(self != NULL, return -EFAULT;); IRDA_ASSERT(self->magic == IRCOMM_MAGIC, return -EFAULT;); IRDA_ASSERT(skb != NULL, return -EFAULT;); ret = ircomm_do_event(self, IRCOMM_CONTROL_REQUEST, skb, NULL); return ret; } EXPORT_SYMBOL(ircomm_control_request); /* * Function ircomm_control_indication (self, skb) * * Data has arrived on the control channel * */ static void ircomm_control_indication(struct ircomm_cb *self, struct sk_buff *skb, int clen) { IRDA_DEBUG(2, "%s()\n", __func__ ); /* Use udata for delivering data on the control channel */ if (self->notify.udata_indication) { struct sk_buff *ctrl_skb; /* We don't own the skb, so clone it */ ctrl_skb = skb_clone(skb, GFP_ATOMIC); if (!ctrl_skb) return; /* Remove data channel from control channel */ skb_trim(ctrl_skb, clen+1); self->notify.udata_indication(self->notify.instance, self, ctrl_skb); /* Drop reference count - * see ircomm_tty_control_indication(). */ dev_kfree_skb(ctrl_skb); } else { IRDA_DEBUG(0, "%s(), missing handler\n", __func__ ); } } /* * Function ircomm_disconnect_request (self, userdata, priority) * * User layer wants to disconnect the IrCOMM connection * */ int ircomm_disconnect_request(struct ircomm_cb *self, struct sk_buff *userdata) { struct ircomm_info info; int ret; IRDA_DEBUG(2, "%s()\n", __func__ ); IRDA_ASSERT(self != NULL, return -1;); IRDA_ASSERT(self->magic == IRCOMM_MAGIC, return -1;); ret = ircomm_do_event(self, IRCOMM_DISCONNECT_REQUEST, userdata, &info); return ret; } EXPORT_SYMBOL(ircomm_disconnect_request); /* * Function disconnect_indication (self, skb) * * Tell user that the link has been disconnected * */ void ircomm_disconnect_indication(struct ircomm_cb *self, struct sk_buff *skb, struct ircomm_info *info) { IRDA_DEBUG(2, "%s()\n", __func__ ); IRDA_ASSERT(info != NULL, return;); if (self->notify.disconnect_indication) { self->notify.disconnect_indication(self->notify.instance, self, info->reason, skb); } else { IRDA_DEBUG(0, "%s(), missing handler\n", __func__ ); } } /* * Function ircomm_flow_request (self, flow) * * * */ void ircomm_flow_request(struct ircomm_cb *self, LOCAL_FLOW flow) { IRDA_DEBUG(2, "%s()\n", __func__ ); IRDA_ASSERT(self != NULL, return;); IRDA_ASSERT(self->magic == IRCOMM_MAGIC, return;); if (self->service_type == IRCOMM_3_WIRE_RAW) return; irttp_flow_request(self->tsap, flow); } EXPORT_SYMBOL(ircomm_flow_request); #ifdef CONFIG_PROC_FS static void *ircomm_seq_start(struct seq_file *seq, loff_t *pos) { struct ircomm_cb *self; loff_t off = 0; spin_lock_irq(&ircomm->hb_spinlock); for (self = (struct ircomm_cb *) hashbin_get_first(ircomm); self != NULL; self = (struct ircomm_cb *) hashbin_get_next(ircomm)) { if (off++ == *pos) break; } return self; } static void *ircomm_seq_next(struct seq_file *seq, void *v, loff_t *pos) { ++*pos; return (void *) hashbin_get_next(ircomm); } static void ircomm_seq_stop(struct seq_file *seq, void *v) { spin_unlock_irq(&ircomm->hb_spinlock); } static int ircomm_seq_show(struct seq_file *seq, void *v) { const struct ircomm_cb *self = v; IRDA_ASSERT(self->magic == IRCOMM_MAGIC, return -EINVAL; ); if(self->line < 0x10) seq_printf(seq, "ircomm%d", self->line); else seq_printf(seq, "irlpt%d", self->line - 0x10); seq_printf(seq, " state: %s, slsap_sel: %#02x, dlsap_sel: %#02x, mode:", ircomm_state[ self->state], self->slsap_sel, self->dlsap_sel); if(self->service_type & IRCOMM_3_WIRE_RAW) seq_printf(seq, " 3-wire-raw"); if(self->service_type & IRCOMM_3_WIRE) seq_printf(seq, " 3-wire"); if(self->service_type & IRCOMM_9_WIRE) seq_printf(seq, " 9-wire"); if(self->service_type & IRCOMM_CENTRONICS) seq_printf(seq, " Centronics"); seq_putc(seq, '\n'); return 0; } static const struct seq_operations ircomm_seq_ops = { .start = ircomm_seq_start, .next = ircomm_seq_next, .stop = ircomm_seq_stop, .show = ircomm_seq_show, }; static int ircomm_seq_open(struct inode *inode, struct file *file) { return seq_open(file, &ircomm_seq_ops); } #endif /* CONFIG_PROC_FS */ MODULE_AUTHOR("Dag Brattli <dag@brattli.net>"); MODULE_DESCRIPTION("IrCOMM protocol"); MODULE_LICENSE("GPL"); module_init(ircomm_init); module_exit(ircomm_cleanup);
davidevinavil/Acer_S500_kernel
net/irda/ircomm/ircomm_core.c
C
gpl-2.0
13,958
/* * arch/sh/boards/dreamcast/setup.c * * Hardware support for the Sega Dreamcast. * * Copyright (c) 2001, 2002 M. R. Brown <mrbrown@linuxdc.org> * Copyright (c) 2002, 2003, 2004 Paul Mundt <lethal@linux-sh.org> * * This file is part of the LinuxDC project (www.linuxdc.org) * * Released under the terms of the GNU GPL v2.0. * * This file originally bore the message (with enclosed-$): * Id: setup_dc.c,v 1.5 2001/05/24 05:09:16 mrbrown Exp * SEGA Dreamcast support */ #include <linux/sched.h> #include <linux/kernel.h> #include <linux/param.h> #include <linux/interrupt.h> #include <linux/init.h> #include <linux/irq.h> #include <linux/device.h> #include <asm/io.h> #include <asm/irq.h> #include <asm/rtc.h> #include <asm/machvec.h> #include <mach/sysasic.h> static void __init dreamcast_setup(char **cmdline_p) { board_time_init = aica_time_init; } static struct sh_machine_vector mv_dreamcast __initmv = { .mv_name = "Sega Dreamcast", .mv_setup = dreamcast_setup, .mv_irq_demux = systemasic_irq_demux, .mv_init_irq = systemasic_irq_init, };
h8rift/android_kernel_htc_m4
arch/sh/boards/mach-dreamcast/setup.c
C
gpl-2.0
1,071
/* * Copyright (c) 1998-2015 Caucho Technology -- all rights reserved * * This file is part of Baratine(TM) * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Baratine is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Baratine is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Baratine; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.v5.kraken.cluster; import java.util.Arrays; import java.util.Objects; import com.caucho.v5.bartender.BartenderSystem; import com.caucho.v5.bartender.ServerBartender; import com.caucho.v5.bartender.pod.NodePodAmp; import com.caucho.v5.bartender.pod.PodBartender; import com.caucho.v5.kraken.table.ClusterServiceKraken; import com.caucho.v5.kraken.table.TableKraken; import com.caucho.v5.kraken.table.TablePod; import com.caucho.v5.kraken.table.TablePodNodeAmp; /** * Backup for the distributed cache */ public class TablePodNode implements TablePodNodeAmp { private final PodBartender _pod; private final int _nodeIndex; // private boolean _isSelf; private PodKraken _podKraken; private TablePodNodeStartup _state; private TablePod _table; private ServerBartender _serverSelf; private boolean _isSelf; private String[] _servers; public TablePodNode(TablePod tablePod, PodKraken podManager, PodBartender pod, int nodeIndex) { _table = tablePod; _podKraken = podManager; _pod = pod; _nodeIndex = nodeIndex; // boolean isSelf = false; _serverSelf = BartenderSystem.current().serverSelf(); _isSelf = calculateIsSelf(); _state = new TablePodNodeStartup(this); updateNodeState(); } public TableKraken getTable() { return _table.getTable(); } /** * Returns the index of the shard. */ public int index() { return _nodeIndex; } public NodePodAmp getPodNode() { return _pod.getNode(_nodeIndex); } private NodePodAmp getNode() { return _pod.getNode(_nodeIndex); } private ServerBartender getServerSelf() { return _serverSelf; } /** * Returns true if the current server handles the node values. */ public boolean isSelf() { return _isSelf; } public void onUpdate() { if (updateNodeState()) { _state = new TablePodNodeStartup(this); } if (! isStartComplete()) { // XXX: //_table.addStartupNode(this); } } private boolean updateNodeState() { _isSelf = calculateIsSelf(); NodePodAmp podNode = getNode(); String []servers = new String[podNode.serverCount()]; for (int i = 0; i < servers.length; i++) { ServerBartender server = podNode.server(i); if (server != null) { servers[i] = server.getId(); } } String []oldServers = _servers; _servers = servers; if (! _isSelf) { return false; } if (oldServers == null || ! Arrays.equals(oldServers, servers)) { return true; } return false; } private boolean calculateIsSelf() { NodePodAmp podNode = getNode(); for (int i = 0; i < podNode.serverCount(); i++) { ServerBartender server = podNode.server(i); if (_serverSelf.equals(server)) { return true; } } return false; } public int getReplicateSize() { return getNode().serverCount(); } /** * @return */ public boolean isSelfDataValid() { return isSelf() && isStartComplete(); } /** * Returns true if the current server has valid data. */ public boolean isNodeLocalValid() { /* System.out.println("ISF: " + isSelf() + " " + isStartComplete() + " " + BartenderSystem.getCurrentSelfServer() + " " + this); */ return isSelfDataValid(); // return isSelf(); } /** * The local node is the primary owner for the pod data. * * This is a dynamic value. If the local node is the secondary, and the * true primary is down, this will return true until the primary is back up. */ public boolean isSelfOwner() { return getNode().isServerOwner(getServerSelf()); } /** * The local node has a copy of the pod data. */ public boolean isSelfCopy() { return getNode().isServerCopy(getServerSelf()); } /** * The local node is the primary owner for the pod data. * * This is a static value. This will return false if the local node is the * secondary, even if the primary is down. * true primary is down, this will return true until the primary is back up. */ public boolean isSelfPrimary() { return getNode().isServerPrimary(getServerSelf()); } public ServerBartender getOwner() { return getNode().owner(); } /** * The data for the local node is synchronized with the cluster. This will * be false during startup or resharding until the copies are available. */ public boolean isLocalValid() { return isStartComplete(); } /* public boolean isNodeLocal() { return isSelf(); } */ public boolean isServerOwner(ServerBartender server) { return getNode().isServerOwner(server); } public ServerBartender getServer(int index) { return getNode().server(index); } public ClusterServiceKraken getProxy(int index) { ClusterServiceKraken proxy = _podKraken.getProxy(getNode().server(index)); Objects.requireNonNull(proxy); return proxy; } public void invoke(NodeTableContext nodeContext) { NodePodAmp podNode = getNode(); while (true) { int index = nodeContext.getIndex(); if (podNode.serverCount() <= index) { nodeContext.fallthru(); nodeContext.close(); return; } nodeContext.setIndex(index + 1); ServerBartender server = podNode.server(index); if (server == null || ! server.isUp()) { continue; } if (server.isSelf()) { continue; } ClusterServiceKraken proxy = getProxy(index); nodeContext.invoke(proxy); if (nodeContext.isSingleRequest()) { nodeContext.close(); return; } } } public boolean isStartComplete() { return _state.isComplete() || ! isSelf(); } boolean startRequestUpdates(TablePod tablePod, long startupLastUpdateTime) { return _state.startRequestUpdates(tablePod, startupLastUpdateTime); } public boolean isStartFailed() { return _state.isFailed(); } public void clearStartFailure() { _state.clearFailure(); } @Override public String toString() { return getClass().getSimpleName() + "[" + _table.getName() + "," + getNode() + "]"; } abstract static class NodeTableContext { private int _index; final int getIndex() { return _index; } public boolean isSingleRequest() { return true; } final void setIndex(int index) { _index = index; } abstract void invoke(ClusterServiceKraken proxy); /** * All servers have been sent the message. For a get(), this is a failure. * For a put(), it's completion of normal operation. */ abstract void fallthru(); public void close() { } } }
baratine/baratine
framework/src/main/java/com/caucho/v5/kraken/cluster/TablePodNode.java
Java
gpl-2.0
8,095
/* Copyright Statement: * * (C) 2005-2016 MediaTek Inc. All rights reserved. * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein * is confidential and proprietary to MediaTek Inc. ("MediaTek") and/or its licensors. * Without the prior written permission of MediaTek and/or its licensors, * any reproduction, modification, use or disclosure of MediaTek Software, * and information contained herein, in whole or in part, shall be strictly prohibited. * You may only use, reproduce, modify, or distribute (as applicable) MediaTek Software * if you have agreed to and been bound by the applicable license agreement with * MediaTek ("License Agreement") and been granted explicit permission to do so within * the License Agreement ("Permitted User"). If you are not a Permitted User, * please cease any access or use of MediaTek Software immediately. * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT MEDIATEK SOFTWARE RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR * SUPPLIED WITH MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND * CUMULATIVE LIABILITY WITH RESPECT TO MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE MEDIATEK SOFTWARE AT ISSUE, * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. */ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "FreeRTOS.h" #include "syslog.h" #include "hal_platform.h" #include "hal_eint.h" #include "hal_gpio.h" #include "msm.h" #ifdef MSM_PRINTF #define LOGE(fmt,arg...) printf(("[MSM EINT]: "fmt), ##arg) #define LOGW(fmt,arg...) printf(("[MSM EINT]: "fmt), ##arg) #define LOGI(fmt,arg...) printf(("[MSM EINT]: "fmt), ##arg) #else log_create_module(msm, PRINT_LEVEL_INFO); #define LOGE(fmt,arg...) LOG_E(msm, "[MSM EINT]: "fmt,##arg) #define LOGW(fmt,arg...) LOG_W(msm, "[MSM EINT]: "fmt,##arg) #define LOGI(fmt,arg...) LOG_I(msm ,"[MSM EINT]: "fmt,##arg) #endif #define MSM_EINT_SUPPORT_EVENT_HANDLE_NUMBER 10 typedef enum { MSM_EINT_MODEM_EXCETION = 0, MSM_EINT_HOST_WAKEUP, MSM_EINT_MAX_NUMBER } msm_eint_t; typedef struct msm_eint_context_struct { uint32_t mutex; uint32_t semaphore; uint32_t cb_count; msm_event_handler event_cb_list[MSM_EINT_SUPPORT_EVENT_HANDLE_NUMBER]; } msm_eint_context_struct; uint32_t g_msm_pin_config; uint32_t g_msm_exception_pin_parameter; static msm_eint_t msm_eint[] = {MSM_EINT_MODEM_EXCETION, MSM_EINT_HOST_WAKEUP,}; static msm_eint_context_struct msm_eint_cnt = {0}; extern msm_ret_t msm_gpio_init(void); static msm_ret_t msm_eint_init(); static msm_ret_t msm_eint_register_callback(msm_event_handler event_handler); static void msm_eint_callback(void *user_data); static msm_ret_t msm_eint_notify(msm_event_t event); static msm_ret_t msm_eint_trigger_wakeup_from_modem_init(void); static msm_ret_t msm_eint_notify_exception_from_modem_init(void); msm_ret_t msm_init(uint32_t pin_config, uint32_t exception_eint_mode_parameter) { g_msm_pin_config = pin_config; g_msm_exception_pin_parameter = exception_eint_mode_parameter; msm_eint_init(); return MSM_RET_OK; } msm_ret_t msm_register_callback(msm_event_handler event_handler) { return msm_eint_register_callback(event_handler); } static msm_ret_t msm_eint_init() { if (MSM_RET_OK != msm_eint_trigger_wakeup_from_modem_init()) { return MSM_RET_ERROR; } if (MSM_RET_OK != msm_eint_notify_exception_from_modem_init()) { return MSM_RET_ERROR; } LOGI("msm_eint_init, success \r\n"); return MSM_RET_OK; } msm_ret_t msm_eint_register_callback(msm_event_handler event_handler) { if (msm_eint_cnt.cb_count == MSM_EINT_SUPPORT_EVENT_HANDLE_NUMBER) return MSM_RET_ERROR; msm_eint_cnt.event_cb_list[msm_eint_cnt.cb_count] = event_handler; msm_eint_cnt.cb_count++; return MSM_RET_OK; } static msm_ret_t msm_eint_notify_exception_from_modem_init(void) { hal_eint_config_t eint_config; if (!(g_msm_pin_config & MSM_NOTITF_MODEM_EXCEPTION_PIN_SUPPORTED)){ return MSM_RET_OK; } hal_eint_mask(MODEM_EXCEPTION_EINT); if (g_msm_exception_pin_parameter & MSM_EXCEPTION_PIN_EDGE_TRIGGER) eint_config.trigger_mode = HAL_EINT_EDGE_RISING; else eint_config.trigger_mode = HAL_EINT_EDGE_FALLING; //eint_config.debounce_time = 1; eint_config.debounce_time = 10; if (HAL_EINT_STATUS_OK != hal_eint_init(MODEM_EXCEPTION_EINT, &eint_config)) { return MSM_RET_ERROR; } if (HAL_EINT_STATUS_OK != hal_eint_register_callback(MODEM_EXCEPTION_EINT, msm_eint_callback, &msm_eint[0])) { return MSM_RET_ERROR; } hal_eint_unmask(MODEM_EXCEPTION_EINT); LOGI("msm_eint_notify_exception_from_modem_init, success \r\n"); return MSM_RET_OK; } static msm_ret_t msm_eint_trigger_wakeup_from_modem_init(void) { hal_eint_config_t eint_config; if (!(g_msm_pin_config & MSM_NOTITF_MODEM_WAKEUP_PIN_SUPPORTED)){ return MSM_RET_OK; } hal_eint_mask(MODEM_WAKEUP_EINT); eint_config.trigger_mode = HAL_EINT_EDGE_RISING; //eint_config.debounce_time = 1; eint_config.debounce_time = 10; if (HAL_EINT_STATUS_OK != hal_eint_init(MODEM_WAKEUP_EINT, &eint_config)) { return MSM_RET_ERROR; } if (HAL_EINT_STATUS_OK != hal_eint_register_callback(MODEM_WAKEUP_EINT, msm_eint_callback, &msm_eint[1])) { return MSM_RET_ERROR; } hal_eint_unmask(MODEM_WAKEUP_EINT); LOGI("msm_eint_trigger_wakeup_from_modem_init, success \r\n"); return MSM_RET_OK; } static void msm_eint_callback(void *user_data) { msm_eint_t *eint = (msm_eint_t *)user_data; LOGI("msm_eint_callback eint: %d \r\n", *eint); if (*eint == msm_eint[0]) { hal_eint_mask(MODEM_EXCEPTION_EINT); msm_eint_notify(MSM_EVENT_EXCETION); hal_eint_unmask(MODEM_EXCEPTION_EINT); } else if (*eint == msm_eint[1]) { hal_eint_mask(MODEM_WAKEUP_EINT); msm_eint_notify(MSM_EVENT_WAKEUP); hal_eint_unmask(MODEM_WAKEUP_EINT); } } static msm_ret_t msm_eint_notify(msm_event_t event) { uint32_t i = 0; for (i = 0; i < msm_eint_cnt.cb_count; i++) { if (msm_eint_cnt.event_cb_list[i](event, NULL) == 1) break; } return MSM_RET_OK; }
flyingcys/rtthread-mtk_iot
bsp/mtk_iot/Libraries/middleware/MTK/sio/src/msm/msm_eint.c
C
gpl-2.0
7,471
/* * FitVids 1.0 * * Copyright 2011, Chris Coyier - http://css-tricks.com + Dave Rupert - http://daverupert.com * Credit to Thierry Koblentz - http://www.alistapart.com/articles/creating-intrinsic-ratios-for-video/ * Released under the WTFPL license - http://sam.zoy.org/wtfpl/ * * Date: Thu Sept 01 18:00:00 2011 -0500 */ (function( $ ){ $.fn.fitVids = function( options ) { var settings = { customSelector: null } var div = document.createElement('div'), ref = document.getElementsByTagName('base')[0] || document.getElementsByTagName('script')[0]; div.className = 'fit-vids-style'; div.innerHTML = '&shy;<style> \ .fluid-width-video-wrapper { \ width: 100%; \ position: relative; \ padding: 0; \ } \ \ .fluid-width-video-wrapper iframe, \ .fluid-width-video-wrapper object, \ .fluid-width-video-wrapper embed { \ position: absolute; \ top: 0; \ left: 0; \ width: 100%; \ height: 100%; \ } \ </style>'; ref.parentNode.insertBefore(div,ref); if ( options ) { $.extend( settings, options ); } return this.each(function(){ var selectors = [ "iframe[src*='player.vimeo.com']", "iframe[src*='www.youtube.com']", "iframe[src*='www.kickstarter.com']", "object", "embed" ]; if (settings.customSelector) { selectors.push(settings.customSelector); } var $allVideos = $(this).find(selectors.join(',')); $allVideos.each(function(){ var $this = $(this); if (this.tagName.toLowerCase() == 'embed' && $this.parent('object').length || $this.parent('.fluid-width-video-wrapper').length) { return; } var height = this.tagName.toLowerCase() == 'object' ? $this.attr('height') : $this.height(), aspectRatio = height / $this.width(); if(!$this.attr('id')){ var videoID = 'fitvid' + Math.floor(Math.random()*999999); $this.attr('id', videoID); } $this.wrap('<div class="fluid-width-video-wrapper"></div>').parent('.fluid-width-video-wrapper').css('padding-top', (aspectRatio * 100)+"%"); $this.removeAttr('height').removeAttr('width'); }); }); } })( jQuery );
qyom/pipstation
wp-content/themes/im-startup/assets/scripts/static/jquery/jquery.fitvids.js
JavaScript
gpl-2.0
2,632
#include "EditorOptionsGeneralEdit.h" #include "editor_config.h" #include "globals.h" #include "optionsconfig.h" EditorOptionsGeneralEdit::EditorOptionsGeneralEdit(wxWindow* parent) : EditorOptionsGeneralEditBase(parent) { ::wxPGPropertyBooleanUseCheckbox(m_pgMgrEdit->GetGrid()); OptionsConfigPtr options = EditorConfigST::Get()->GetOptions(); m_pgPropSmartCurly->SetValue(options->GetAutoAddMatchedCurlyBraces()); m_pgPropSmartParentheses->SetValue(options->GetAutoAddMatchedNormalBraces()); m_pgPropSmartQuotes->SetValue(options->GetAutoCompleteDoubleQuotes()); m_pgPropCopyLineEmptySelection->SetValue(options->GetCopyLineEmptySelection()); m_pgPropWrapBrackets->SetValue(options->IsWrapSelectionBrackets()); m_pgPropWrapQuotes->SetValue(options->IsWrapSelectionWithQuotes()); m_pgPropZoomUsingCtrlScroll->SetValue(options->IsMouseZoomEnabled()); m_pgPropCommentsIndented->SetValue(options->GetIndentedComments()); } EditorOptionsGeneralEdit::~EditorOptionsGeneralEdit() {} void EditorOptionsGeneralEdit::OnValueChanged(wxPropertyGridEvent& event) { // event.Skip(); } void EditorOptionsGeneralEdit::Save(OptionsConfigPtr options) { options->SetAutoAddMatchedCurlyBraces(m_pgPropSmartCurly->GetValue().GetBool()); options->SetAutoAddMatchedNormalBraces(m_pgPropSmartParentheses->GetValue().GetBool()); options->SetAutoCompleteDoubleQuotes(m_pgPropSmartQuotes->GetValue().GetBool()); options->SetCopyLineEmptySelection(m_pgPropCopyLineEmptySelection->GetValue().GetBool()); options->SetWrapSelectionBrackets(m_pgPropWrapBrackets->GetValue().GetBool()); options->SetWrapSelectionWithQuotes(m_pgPropWrapQuotes->GetValue().GetBool()); options->SetMouseZoomEnabled(m_pgPropZoomUsingCtrlScroll->GetValue().GetBool()); options->SetIndentedComments(m_pgPropCommentsIndented->GetValue().GetBool()); }
AJenbo/codelite
LiteEditor/EditorOptionsGeneralEdit.cpp
C++
gpl-2.0
1,880
/** * The Forgotten Server - a free and open-source MMORPG server emulator * Copyright (C) 2016 Mark Samman <mark.samman@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "otpch.h" #include "condition.h" #include "game.h" extern Game g_game; Condition::Condition(ConditionId_t _id, ConditionType_t _type, int32_t _ticks, bool _buff, uint32_t _subId) : subId(_subId), ticks(_ticks), conditionType(_type), id(_id), isBuff(_buff) { if (_ticks == -1) { endTime = std::numeric_limits<int64_t>::max(); } else { endTime = 0; } } bool Condition::setParam(ConditionParam_t param, int32_t value) { switch (param) { case CONDITION_PARAM_TICKS: { ticks = value; return true; } case CONDITION_PARAM_BUFF_SPELL: { isBuff = (value != 0); return true; } case CONDITION_PARAM_SUBID: { subId = value; return true; } default: { return false; } } } bool Condition::unserialize(PropStream& propStream) { uint8_t attr_type; while (propStream.read<uint8_t>(attr_type) && attr_type != CONDITIONATTR_END) { if (!unserializeProp(static_cast<ConditionAttr_t>(attr_type), propStream)) { return false; } } return true; } bool Condition::unserializeProp(ConditionAttr_t attr, PropStream& propStream) { switch (attr) { case CONDITIONATTR_TYPE: { int32_t value; if (!propStream.read<int32_t>(value)) { return false; } conditionType = static_cast<ConditionType_t>(value); return true; } case CONDITIONATTR_ID: { int32_t value; if (!propStream.read<int32_t>(value)) { return false; } id = static_cast<ConditionId_t>(value); return true; } case CONDITIONATTR_TICKS: { return propStream.read<int32_t>(ticks); } case CONDITIONATTR_ISBUFF: { uint8_t value; if (!propStream.read<uint8_t>(value)) { return false; } isBuff = (value != 0); return true; } case CONDITIONATTR_SUBID: { return propStream.read<uint32_t>(subId); } case CONDITIONATTR_END: return true; default: return false; } } void Condition::serialize(PropWriteStream& propWriteStream) { propWriteStream.write<uint8_t>(CONDITIONATTR_TYPE); propWriteStream.write<uint32_t>(conditionType); propWriteStream.write<uint8_t>(CONDITIONATTR_ID); propWriteStream.write<uint32_t>(id); propWriteStream.write<uint8_t>(CONDITIONATTR_TICKS); propWriteStream.write<uint32_t>(ticks); propWriteStream.write<uint8_t>(CONDITIONATTR_ISBUFF); propWriteStream.write<uint8_t>(isBuff); propWriteStream.write<uint8_t>(CONDITIONATTR_SUBID); propWriteStream.write<uint32_t>(subId); } void Condition::setTicks(int32_t newTicks) { ticks = newTicks; endTime = ticks + OTSYS_TIME(); } bool Condition::executeCondition(Creature*, int32_t interval) { if (ticks == -1) { return true; } //Not using set ticks here since it would reset endTime ticks = std::max<int32_t>(0, ticks - interval); return getEndTime() >= OTSYS_TIME(); } Condition* Condition::createCondition(ConditionId_t _id, ConditionType_t _type, int32_t _ticks, int32_t param/* = 0*/, bool _buff/* = false*/, uint32_t _subId/* = 0*/) { switch (_type) { case CONDITION_POISON: case CONDITION_FIRE: case CONDITION_ENERGY: case CONDITION_BLEEDING: return new ConditionDamage(_id, _type, _buff, _subId); case CONDITION_HASTE: case CONDITION_PARALYZE: return new ConditionSpeed(_id, _type, _ticks, _buff, _subId, param); case CONDITION_INVISIBLE: return new ConditionInvisible(_id, _type, _ticks, _buff, _subId); case CONDITION_OUTFIT: return new ConditionOutfit(_id, _type, _ticks, _buff, _subId); case CONDITION_LIGHT: return new ConditionLight(_id, _type, _ticks, _buff, _subId, param & 0xFF, (param & 0xFF00) >> 8); case CONDITION_REGENERATION: return new ConditionRegeneration(_id, _type, _ticks, _buff, _subId); case CONDITION_SOUL: return new ConditionSoul(_id, _type, _ticks, _buff, _subId); case CONDITION_ATTRIBUTES: return new ConditionAttributes(_id, _type, _ticks, _buff, _subId); case CONDITION_INFIGHT: case CONDITION_DRUNK: case CONDITION_EXHAUST_WEAPON: case CONDITION_EXHAUST_COMBAT: case CONDITION_EXHAUST_HEAL: case CONDITION_MUTED: case CONDITION_CHANNELMUTEDTICKS: case CONDITION_YELLTICKS: case CONDITION_PACIFIED: case CONDITION_MANASHIELD: return new ConditionGeneric(_id, _type, _ticks, _buff, _subId); default: return nullptr; } } Condition* Condition::createCondition(PropStream& propStream) { uint8_t attr; if (!propStream.read<uint8_t>(attr) || attr != CONDITIONATTR_TYPE) { return nullptr; } uint32_t _type; if (!propStream.read<uint32_t>(_type)) { return nullptr; } if (!propStream.read<uint8_t>(attr) || attr != CONDITIONATTR_ID) { return nullptr; } uint32_t _id; if (!propStream.read<uint32_t>(_id)) { return nullptr; } if (!propStream.read<uint8_t>(attr) || attr != CONDITIONATTR_TICKS) { return nullptr; } uint32_t _ticks; if (!propStream.read<uint32_t>(_ticks)) { return nullptr; } if (!propStream.read<uint8_t>(attr) || attr != CONDITIONATTR_ISBUFF) { return nullptr; } uint8_t _buff; if (!propStream.read<uint8_t>(_buff)) { return nullptr; } if (!propStream.read<uint8_t>(attr) || attr != CONDITIONATTR_SUBID) { return nullptr; } uint32_t _subId; if (!propStream.read<uint32_t>(_subId)) { return nullptr; } return createCondition(static_cast<ConditionId_t>(_id), static_cast<ConditionType_t>(_type), _ticks, 0, _buff != 0, _subId); } bool Condition::startCondition(Creature*) { if (ticks > 0) { endTime = ticks + OTSYS_TIME(); } return true; } bool Condition::isPersistent() const { if (ticks == -1) { return false; } if (!(id == CONDITIONID_DEFAULT || id == CONDITIONID_COMBAT)) { return false; } return true; } uint32_t Condition::getIcons() const { return 0; } bool Condition::updateCondition(const Condition* addCondition) { if (conditionType != addCondition->getType()) { return false; } if (ticks == -1 && addCondition->getTicks() > 0) { return false; } if (addCondition->getTicks() >= 0 && getEndTime() > (OTSYS_TIME() + addCondition->getTicks())) { return false; } return true; } ConditionGeneric::ConditionGeneric(ConditionId_t _id, ConditionType_t _type, int32_t _ticks, bool _buff, uint32_t _subId) : Condition(_id, _type, _ticks, _buff, _subId) { // } bool ConditionGeneric::startCondition(Creature* creature) { return Condition::startCondition(creature); } bool ConditionGeneric::executeCondition(Creature* creature, int32_t interval) { return Condition::executeCondition(creature, interval); } void ConditionGeneric::endCondition(Creature*) { // } void ConditionGeneric::addCondition(Creature*, const Condition* addCondition) { if (updateCondition(addCondition)) { setTicks(addCondition->getTicks()); } } uint32_t ConditionGeneric::getIcons() const { uint32_t icons = Condition::getIcons(); switch (conditionType) { case CONDITION_MANASHIELD: icons |= ICON_MANASHIELD; break; case CONDITION_INFIGHT: icons |= ICON_SWORDS; break; case CONDITION_DRUNK: icons |= ICON_DRUNK; break; default: break; } return icons; } ConditionAttributes::ConditionAttributes(ConditionId_t _id, ConditionType_t _type, int32_t _ticks, bool _buff, uint32_t _subId) : ConditionGeneric(_id, _type, _ticks, _buff, _subId), skills(), skillsPercent(), stats(), statsPercent() { currentSkill = 0; currentStat = 0; } void ConditionAttributes::addCondition(Creature* creature, const Condition* addCondition) { if (updateCondition(addCondition)) { setTicks(addCondition->getTicks()); const ConditionAttributes& conditionAttrs = static_cast<const ConditionAttributes&>(*addCondition); //Remove the old condition endCondition(creature); //Apply the new one memcpy(skills, conditionAttrs.skills, sizeof(skills)); memcpy(skillsPercent, conditionAttrs.skillsPercent, sizeof(skillsPercent)); memcpy(stats, conditionAttrs.stats, sizeof(stats)); memcpy(statsPercent, conditionAttrs.statsPercent, sizeof(statsPercent)); if (Player* player = creature->getPlayer()) { updatePercentSkills(player); updateSkills(player); updatePercentStats(player); updateStats(player); } } } bool ConditionAttributes::unserializeProp(ConditionAttr_t attr, PropStream& propStream) { if (attr == CONDITIONATTR_SKILLS) { return propStream.read<int32_t>(skills[currentSkill++]); } else if (attr == CONDITIONATTR_STATS) { return propStream.read<int32_t>(stats[currentStat++]); } return Condition::unserializeProp(attr, propStream); } void ConditionAttributes::serialize(PropWriteStream& propWriteStream) { Condition::serialize(propWriteStream); for (int32_t i = SKILL_FIRST; i <= SKILL_LAST; ++i) { propWriteStream.write<uint8_t>(CONDITIONATTR_SKILLS); propWriteStream.write<int32_t>(skills[i]); } for (int32_t i = STAT_FIRST; i <= STAT_LAST; ++i) { propWriteStream.write<uint8_t>(CONDITIONATTR_STATS); propWriteStream.write<int32_t>(stats[i]); } } bool ConditionAttributes::startCondition(Creature* creature) { if (!Condition::startCondition(creature)) { return false; } if (Player* player = creature->getPlayer()) { updatePercentSkills(player); updateSkills(player); updatePercentStats(player); updateStats(player); } return true; } void ConditionAttributes::updatePercentStats(Player* player) { for (int32_t i = STAT_FIRST; i <= STAT_LAST; ++i) { if (statsPercent[i] == 0) { continue; } switch (i) { case STAT_MAXHITPOINTS: stats[i] = static_cast<int32_t>(player->getMaxHealth() * ((statsPercent[i] - 100) / 100.f)); break; case STAT_MAXMANAPOINTS: stats[i] = static_cast<int32_t>(player->getMaxMana() * ((statsPercent[i] - 100) / 100.f)); break; case STAT_MAGICPOINTS: stats[i] = static_cast<int32_t>(player->getMagicLevel() * ((statsPercent[i] - 100) / 100.f)); break; } } } void ConditionAttributes::updateStats(Player* player) { bool needUpdateStats = false; for (int32_t i = STAT_FIRST; i <= STAT_LAST; ++i) { if (stats[i]) { needUpdateStats = true; player->setVarStats(static_cast<stats_t>(i), stats[i]); } } if (needUpdateStats) { player->sendStats(); } } void ConditionAttributes::updatePercentSkills(Player* player) { for (uint8_t i = SKILL_FIRST; i <= SKILL_LAST; ++i) { if (skillsPercent[i] == 0) { continue; } int32_t unmodifiedSkill = player->getBaseSkill(i); skills[i] = static_cast<int32_t>(unmodifiedSkill * ((skillsPercent[i] - 100) / 100.f)); } } void ConditionAttributes::updateSkills(Player* player) { bool needUpdateSkills = false; for (int32_t i = SKILL_FIRST; i <= SKILL_LAST; ++i) { if (skills[i]) { needUpdateSkills = true; player->setVarSkill(static_cast<skills_t>(i), skills[i]); } } if (needUpdateSkills) { player->sendSkills(); } } bool ConditionAttributes::executeCondition(Creature* creature, int32_t interval) { return ConditionGeneric::executeCondition(creature, interval); } void ConditionAttributes::endCondition(Creature* creature) { Player* player = creature->getPlayer(); if (player) { bool needUpdateSkills = false; for (int32_t i = SKILL_FIRST; i <= SKILL_LAST; ++i) { if (skills[i] || skillsPercent[i]) { needUpdateSkills = true; player->setVarSkill(static_cast<skills_t>(i), -skills[i]); } } if (needUpdateSkills) { player->sendSkills(); } bool needUpdateStats = false; for (int32_t i = STAT_FIRST; i <= STAT_LAST; ++i) { if (stats[i]) { needUpdateStats = true; player->setVarStats(static_cast<stats_t>(i), -stats[i]); } } if (needUpdateStats) { player->sendStats(); } } } bool ConditionAttributes::setParam(ConditionParam_t param, int32_t value) { bool ret = ConditionGeneric::setParam(param, value); switch (param) { case CONDITION_PARAM_SKILL_MELEE: { skills[SKILL_CLUB] = value; skills[SKILL_AXE] = value; skills[SKILL_SWORD] = value; return true; } case CONDITION_PARAM_SKILL_MELEEPERCENT: { skillsPercent[SKILL_CLUB] = value; skillsPercent[SKILL_AXE] = value; skillsPercent[SKILL_SWORD] = value; return true; } case CONDITION_PARAM_SKILL_FIST: { skills[SKILL_FIST] = value; return true; } case CONDITION_PARAM_SKILL_FISTPERCENT: { skillsPercent[SKILL_FIST] = value; return true; } case CONDITION_PARAM_SKILL_CLUB: { skills[SKILL_CLUB] = value; return true; } case CONDITION_PARAM_SKILL_CLUBPERCENT: { skillsPercent[SKILL_CLUB] = value; return true; } case CONDITION_PARAM_SKILL_SWORD: { skills[SKILL_SWORD] = value; return true; } case CONDITION_PARAM_SKILL_SWORDPERCENT: { skillsPercent[SKILL_SWORD] = value; return true; } case CONDITION_PARAM_SKILL_AXE: { skills[SKILL_AXE] = value; return true; } case CONDITION_PARAM_SKILL_AXEPERCENT: { skillsPercent[SKILL_AXE] = value; return true; } case CONDITION_PARAM_SKILL_DISTANCE: { skills[SKILL_DISTANCE] = value; return true; } case CONDITION_PARAM_SKILL_DISTANCEPERCENT: { skillsPercent[SKILL_DISTANCE] = value; return true; } case CONDITION_PARAM_SKILL_SHIELD: { skills[SKILL_SHIELD] = value; return true; } case CONDITION_PARAM_SKILL_SHIELDPERCENT: { skillsPercent[SKILL_SHIELD] = value; return true; } case CONDITION_PARAM_SKILL_FISHING: { skills[SKILL_FISHING] = value; return true; } case CONDITION_PARAM_SKILL_FISHINGPERCENT: { skillsPercent[SKILL_FISHING] = value; return true; } case CONDITION_PARAM_STAT_MAXHITPOINTS: { stats[STAT_MAXHITPOINTS] = value; return true; } case CONDITION_PARAM_STAT_MAXMANAPOINTS: { stats[STAT_MAXMANAPOINTS] = value; return true; } case CONDITION_PARAM_STAT_MAGICPOINTS: { stats[STAT_MAGICPOINTS] = value; return true; } case CONDITION_PARAM_STAT_MAXHITPOINTSPERCENT: { statsPercent[STAT_MAXHITPOINTS] = std::max<int32_t>(0, value); return true; } case CONDITION_PARAM_STAT_MAXMANAPOINTSPERCENT: { statsPercent[STAT_MAXMANAPOINTS] = std::max<int32_t>(0, value); return true; } case CONDITION_PARAM_STAT_MAGICPOINTSPERCENT: { statsPercent[STAT_MAGICPOINTS] = std::max<int32_t>(0, value); return true; } default: return ret; } } ConditionRegeneration::ConditionRegeneration(ConditionId_t _id, ConditionType_t _type, int32_t _ticks, bool _buff, uint32_t _subId) : ConditionGeneric(_id, _type, _ticks, _buff, _subId) { internalHealthTicks = 0; internalManaTicks = 0; healthTicks = 1000; manaTicks = 1000; healthGain = 0; manaGain = 0; } void ConditionRegeneration::addCondition(Creature*, const Condition* addCondition) { if (updateCondition(addCondition)) { setTicks(addCondition->getTicks()); const ConditionRegeneration& conditionRegen = static_cast<const ConditionRegeneration&>(*addCondition); healthTicks = conditionRegen.healthTicks; manaTicks = conditionRegen.manaTicks; healthGain = conditionRegen.healthGain; manaGain = conditionRegen.manaGain; } } bool ConditionRegeneration::unserializeProp(ConditionAttr_t attr, PropStream& propStream) { if (attr == CONDITIONATTR_HEALTHTICKS) { return propStream.read<uint32_t>(healthTicks); } else if (attr == CONDITIONATTR_HEALTHGAIN) { return propStream.read<uint32_t>(healthGain); } else if (attr == CONDITIONATTR_MANATICKS) { return propStream.read<uint32_t>(manaTicks); } else if (attr == CONDITIONATTR_MANAGAIN) { return propStream.read<uint32_t>(manaGain); } return Condition::unserializeProp(attr, propStream); } void ConditionRegeneration::serialize(PropWriteStream& propWriteStream) { Condition::serialize(propWriteStream); propWriteStream.write<uint8_t>(CONDITIONATTR_HEALTHTICKS); propWriteStream.write<uint32_t>(healthTicks); propWriteStream.write<uint8_t>(CONDITIONATTR_HEALTHGAIN); propWriteStream.write<uint32_t>(healthGain); propWriteStream.write<uint8_t>(CONDITIONATTR_MANATICKS); propWriteStream.write<uint32_t>(manaTicks); propWriteStream.write<uint8_t>(CONDITIONATTR_MANAGAIN); propWriteStream.write<uint32_t>(manaGain); } bool ConditionRegeneration::executeCondition(Creature* creature, int32_t interval) { internalHealthTicks += interval; internalManaTicks += interval; if (creature->getZone() != ZONE_PROTECTION) { if (internalHealthTicks >= healthTicks) { internalHealthTicks = 0; int32_t realHealthGain = creature->getHealth(); creature->changeHealth(healthGain); realHealthGain = creature->getHealth() - realHealthGain; if (isBuff && realHealthGain > 0) { Player* player = creature->getPlayer(); if (player) { std::string healString = std::to_string(realHealthGain) + (realHealthGain != 1 ? " hitpoints." : " hitpoint."); TextMessage message(MESSAGE_STATUS_SMALL, "You were healed for " + healString); player->sendTextMessage(message); std::ostringstream strHealthGain; strHealthGain << realHealthGain; g_game.addAnimatedText(strHealthGain.str(), player->getPosition(), TEXTCOLOR_MAYABLUE); SpectatorVec list; g_game.map.getSpectators(list, player->getPosition(), false, true); list.erase(player); if (!list.empty()) { message.type = MESSAGE_STATUS_SMALL; message.text = player->getName() + " was healed for " + healString; for (Creature* spectator : list) { spectator->getPlayer()->sendTextMessage(message); } } } } } if (internalManaTicks >= manaTicks) { internalManaTicks = 0; creature->changeMana(manaGain); } } return ConditionGeneric::executeCondition(creature, interval); } bool ConditionRegeneration::setParam(ConditionParam_t param, int32_t value) { bool ret = ConditionGeneric::setParam(param, value); switch (param) { case CONDITION_PARAM_HEALTHGAIN: healthGain = value; return true; case CONDITION_PARAM_HEALTHTICKS: healthTicks = value; return true; case CONDITION_PARAM_MANAGAIN: manaGain = value; return true; case CONDITION_PARAM_MANATICKS: manaTicks = value; return true; default: return ret; } } ConditionSoul::ConditionSoul(ConditionId_t _id, ConditionType_t _type, int32_t _ticks, bool _buff, uint32_t _subId) : ConditionGeneric(_id, _type, _ticks, _buff, _subId) { internalSoulTicks = 0; soulTicks = 0; soulGain = 0; } void ConditionSoul::addCondition(Creature*, const Condition* addCondition) { if (updateCondition(addCondition)) { setTicks(addCondition->getTicks()); const ConditionSoul& conditionSoul = static_cast<const ConditionSoul&>(*addCondition); soulTicks = conditionSoul.soulTicks; soulGain = conditionSoul.soulGain; } } bool ConditionSoul::unserializeProp(ConditionAttr_t attr, PropStream& propStream) { if (attr == CONDITIONATTR_SOULGAIN) { return propStream.read<uint32_t>(soulGain); } else if (attr == CONDITIONATTR_SOULTICKS) { return propStream.read<uint32_t>(soulTicks); } return Condition::unserializeProp(attr, propStream); } void ConditionSoul::serialize(PropWriteStream& propWriteStream) { Condition::serialize(propWriteStream); propWriteStream.write<uint8_t>(CONDITIONATTR_SOULGAIN); propWriteStream.write<uint32_t>(soulGain); propWriteStream.write<uint8_t>(CONDITIONATTR_SOULTICKS); propWriteStream.write<uint32_t>(soulTicks); } bool ConditionSoul::executeCondition(Creature* creature, int32_t interval) { internalSoulTicks += interval; if (Player* player = creature->getPlayer()) { if (player->getZone() != ZONE_PROTECTION) { if (internalSoulTicks >= soulTicks) { internalSoulTicks = 0; player->changeSoul(soulGain); } } } return ConditionGeneric::executeCondition(creature, interval); } bool ConditionSoul::setParam(ConditionParam_t param, int32_t value) { bool ret = ConditionGeneric::setParam(param, value); switch (param) { case CONDITION_PARAM_SOULGAIN: soulGain = value; return true; case CONDITION_PARAM_SOULTICKS: soulTicks = value; return true; default: return ret; } } ConditionDamage::ConditionDamage(ConditionId_t _id, ConditionType_t _type, bool _buff, uint32_t _subId) : Condition(_id, _type, 0, _buff, _subId) { delayed = false; forceUpdate = false; field = false; owner = 0; minDamage = 0; maxDamage = 0; startDamage = 0; periodDamage = 0; periodDamageTick = 0; tickInterval = 2000; } bool ConditionDamage::setParam(ConditionParam_t param, int32_t value) { bool ret = Condition::setParam(param, value); switch (param) { case CONDITION_PARAM_OWNER: owner = value; return true; case CONDITION_PARAM_FORCEUPDATE: forceUpdate = (value != 0); return true; case CONDITION_PARAM_DELAYED: delayed = (value != 0); return true; case CONDITION_PARAM_MAXVALUE: maxDamage = std::abs(value); break; case CONDITION_PARAM_MINVALUE: minDamage = std::abs(value); break; case CONDITION_PARAM_STARTVALUE: startDamage = std::abs(value); break; case CONDITION_PARAM_TICKINTERVAL: tickInterval = std::abs(value); break; case CONDITION_PARAM_PERIODICDAMAGE: periodDamage = value; break; case CONDITION_PARAM_FIELD: field = (value != 0); break; default: return false; } return ret; } bool ConditionDamage::unserializeProp(ConditionAttr_t attr, PropStream& propStream) { if (attr == CONDITIONATTR_DELAYED) { uint8_t value; if (!propStream.read<uint8_t>(value)) { return false; } delayed = (value != 0); return true; } else if (attr == CONDITIONATTR_PERIODDAMAGE) { return propStream.read<int32_t>(periodDamage); } else if (attr == CONDITIONATTR_OWNER) { return propStream.skip(4); } else if (attr == CONDITIONATTR_INTERVALDATA) { IntervalInfo damageInfo; if (!propStream.read<IntervalInfo>(damageInfo)) { return false; } damageList.push_back(damageInfo); if (ticks != -1) { setTicks(ticks + damageInfo.interval); } return true; } return Condition::unserializeProp(attr, propStream); } void ConditionDamage::serialize(PropWriteStream& propWriteStream) { Condition::serialize(propWriteStream); propWriteStream.write<uint8_t>(CONDITIONATTR_DELAYED); propWriteStream.write<uint8_t>(delayed); propWriteStream.write<uint8_t>(CONDITIONATTR_PERIODDAMAGE); propWriteStream.write<int32_t>(periodDamage); for (const IntervalInfo& intervalInfo : damageList) { propWriteStream.write<uint8_t>(CONDITIONATTR_INTERVALDATA); propWriteStream.write<IntervalInfo>(intervalInfo); } } bool ConditionDamage::updateCondition(const Condition* addCondition) { const ConditionDamage& conditionDamage = static_cast<const ConditionDamage&>(*addCondition); if (conditionDamage.doForceUpdate()) { return true; } if (ticks == -1 && conditionDamage.ticks > 0) { return false; } return conditionDamage.getTotalDamage() > getTotalDamage(); } bool ConditionDamage::addDamage(int32_t rounds, int32_t time, int32_t value) { time = std::max<int32_t>(time, EVENT_CREATURE_THINK_INTERVAL); if (rounds == -1) { //periodic damage periodDamage = value; setParam(CONDITION_PARAM_TICKINTERVAL, time); setParam(CONDITION_PARAM_TICKS, -1); return true; } if (periodDamage > 0) { return false; } //rounds, time, damage for (int32_t i = 0; i < rounds; ++i) { IntervalInfo damageInfo; damageInfo.interval = time; damageInfo.timeLeft = time; damageInfo.value = value; damageList.push_back(damageInfo); if (ticks != -1) { setTicks(ticks + damageInfo.interval); } } return true; } bool ConditionDamage::init() { if (periodDamage != 0) { return true; } if (damageList.empty()) { setTicks(0); int32_t amount = uniform_random(minDamage, maxDamage); if (amount != 0) { if (startDamage > maxDamage) { startDamage = maxDamage; } else if (startDamage == 0) { startDamage = std::max<int32_t>(1, std::ceil(amount / 20.0)); } std::list<int32_t> list; ConditionDamage::generateDamageList(amount, startDamage, list); for (int32_t value : list) { addDamage(1, tickInterval, -value); } } } return !damageList.empty(); } bool ConditionDamage::startCondition(Creature* creature) { if (!Condition::startCondition(creature)) { return false; } if (!init()) { return false; } if (!delayed) { int32_t damage; if (getNextDamage(damage)) { return doDamage(creature, damage); } } return true; } bool ConditionDamage::executeCondition(Creature* creature, int32_t interval) { if (periodDamage != 0) { periodDamageTick += interval; if (periodDamageTick >= tickInterval) { periodDamageTick = 0; doDamage(creature, periodDamage); } } else if (!damageList.empty()) { IntervalInfo& damageInfo = damageList.front(); bool bRemove = (ticks != -1); creature->onTickCondition(getType(), bRemove); damageInfo.timeLeft -= interval; if (damageInfo.timeLeft <= 0) { int32_t damage = damageInfo.value; if (bRemove) { damageList.pop_front(); } else { damageInfo.timeLeft = damageInfo.interval; } doDamage(creature, damage); } if (!bRemove) { if (ticks > 0) { endTime += interval; } interval = 0; } } return Condition::executeCondition(creature, interval); } bool ConditionDamage::getNextDamage(int32_t& damage) { if (periodDamage != 0) { damage = periodDamage; return true; } else if (!damageList.empty()) { IntervalInfo& damageInfo = damageList.front(); damage = damageInfo.value; if (ticks != -1) { damageList.pop_front(); } return true; } return false; } bool ConditionDamage::doDamage(Creature* creature, int32_t healthChange) { if (creature->isSuppress(getType())) { return true; } CombatDamage damage; damage.origin = ORIGIN_CONDITION; damage.primary.value = healthChange; damage.primary.type = Combat::ConditionToDamageType(conditionType); Creature* attacker = g_game.getCreatureByID(owner); if (!creature->isAttackable() || Combat::canDoCombat(attacker, creature) != RETURNVALUE_NOERROR) { if (!creature->isInGhostMode()) { g_game.addMagicEffect(creature->getPosition(), CONST_ME_POFF); } return false; } if (g_game.combatBlockHit(damage, attacker, creature, false, false, field)) { return false; } return g_game.combatChangeHealth(attacker, creature, damage); } void ConditionDamage::endCondition(Creature*) { // } void ConditionDamage::addCondition(Creature* creature, const Condition* addCondition) { if (addCondition->getType() != conditionType) { return; } if (!updateCondition(addCondition)) { return; } const ConditionDamage& conditionDamage = static_cast<const ConditionDamage&>(*addCondition); setTicks(addCondition->getTicks()); owner = conditionDamage.owner; maxDamage = conditionDamage.maxDamage; minDamage = conditionDamage.minDamage; startDamage = conditionDamage.startDamage; tickInterval = conditionDamage.tickInterval; periodDamage = conditionDamage.periodDamage; int32_t nextTimeLeft = tickInterval; if (!damageList.empty()) { //save previous timeLeft IntervalInfo& damageInfo = damageList.front(); nextTimeLeft = damageInfo.timeLeft; damageList.clear(); } damageList = conditionDamage.damageList; if (init()) { if (!damageList.empty()) { //restore last timeLeft IntervalInfo& damageInfo = damageList.front(); damageInfo.timeLeft = nextTimeLeft; } if (!delayed) { int32_t damage; if (getNextDamage(damage)) { doDamage(creature, damage); } } } } int32_t ConditionDamage::getTotalDamage() const { int32_t result; if (!damageList.empty()) { result = 0; for (const IntervalInfo& intervalInfo : damageList) { result += intervalInfo.value; } } else { result = minDamage + (maxDamage - minDamage) / 2; } return std::abs(result); } uint32_t ConditionDamage::getIcons() const { uint32_t icons = Condition::getIcons(); switch (conditionType) { case CONDITION_FIRE: icons |= ICON_BURN; break; case CONDITION_ENERGY: icons |= ICON_ENERGY; break; case CONDITION_POISON: icons |= ICON_POISON; break; default: break; } return icons; } void ConditionDamage::generateDamageList(int32_t amount, int32_t start, std::list<int32_t>& list) { amount = std::abs(amount); int32_t sum = 0; double x1, x2; for (int32_t i = start; i > 0; --i) { int32_t n = start + 1 - i; int32_t med = (n * amount) / start; do { sum += i; list.push_back(i); x1 = std::fabs(1.0 - ((static_cast<float>(sum)) + i) / med); x2 = std::fabs(1.0 - (static_cast<float>(sum) / med)); } while (x1 < x2); } } ConditionSpeed::ConditionSpeed(ConditionId_t _id, ConditionType_t _type, int32_t _ticks, bool _buff, uint32_t _subId, int32_t changeSpeed) : Condition(_id, _type, _ticks, _buff, _subId) { speedDelta = changeSpeed; mina = 0.0f; minb = 0.0f; maxa = 0.0f; maxb = 0.0f; } void ConditionSpeed::setFormulaVars(float _mina, float _minb, float _maxa, float _maxb) { mina = _mina; minb = _minb; maxa = _maxa; maxb = _maxb; } void ConditionSpeed::getFormulaValues(int32_t var, int32_t& min, int32_t& max) const { min = (var * mina) + minb; max = (var * maxa) + maxb; } bool ConditionSpeed::setParam(ConditionParam_t param, int32_t value) { Condition::setParam(param, value); if (param != CONDITION_PARAM_SPEED) { return false; } speedDelta = value; if (value > 0) { conditionType = CONDITION_HASTE; } else { conditionType = CONDITION_PARALYZE; } return true; } bool ConditionSpeed::unserializeProp(ConditionAttr_t attr, PropStream& propStream) { if (attr == CONDITIONATTR_SPEEDDELTA) { return propStream.read<int32_t>(speedDelta); } else if (attr == CONDITIONATTR_FORMULA_MINA) { return propStream.read<float>(mina); } else if (attr == CONDITIONATTR_FORMULA_MINB) { return propStream.read<float>(minb); } else if (attr == CONDITIONATTR_FORMULA_MAXA) { return propStream.read<float>(maxa); } else if (attr == CONDITIONATTR_FORMULA_MAXB) { return propStream.read<float>(maxb); } return Condition::unserializeProp(attr, propStream); } void ConditionSpeed::serialize(PropWriteStream& propWriteStream) { Condition::serialize(propWriteStream); propWriteStream.write<uint8_t>(CONDITIONATTR_SPEEDDELTA); propWriteStream.write<int32_t>(speedDelta); propWriteStream.write<uint8_t>(CONDITIONATTR_FORMULA_MINA); propWriteStream.write<float>(mina); propWriteStream.write<uint8_t>(CONDITIONATTR_FORMULA_MINB); propWriteStream.write<float>(minb); propWriteStream.write<uint8_t>(CONDITIONATTR_FORMULA_MAXA); propWriteStream.write<float>(maxa); propWriteStream.write<uint8_t>(CONDITIONATTR_FORMULA_MAXB); propWriteStream.write<float>(maxb); } bool ConditionSpeed::startCondition(Creature* creature) { if (!Condition::startCondition(creature)) { return false; } if (speedDelta == 0) { int32_t min, max; getFormulaValues(creature->getBaseSpeed(), min, max); speedDelta = uniform_random(min, max); } g_game.changeSpeed(creature, speedDelta); return true; } bool ConditionSpeed::executeCondition(Creature* creature, int32_t interval) { return Condition::executeCondition(creature, interval); } void ConditionSpeed::endCondition(Creature* creature) { g_game.changeSpeed(creature, -speedDelta); } void ConditionSpeed::addCondition(Creature* creature, const Condition* addCondition) { if (conditionType != addCondition->getType()) { return; } if (ticks == -1 && addCondition->getTicks() > 0) { return; } setTicks(addCondition->getTicks()); const ConditionSpeed& conditionSpeed = static_cast<const ConditionSpeed&>(*addCondition); int32_t oldSpeedDelta = speedDelta; speedDelta = conditionSpeed.speedDelta; mina = conditionSpeed.mina; maxa = conditionSpeed.maxa; minb = conditionSpeed.minb; maxb = conditionSpeed.maxb; if (speedDelta == 0) { int32_t min; int32_t max; getFormulaValues(creature->getBaseSpeed(), min, max); speedDelta = uniform_random(min, max); } int32_t newSpeedChange = (speedDelta - oldSpeedDelta); if (newSpeedChange != 0) { g_game.changeSpeed(creature, newSpeedChange); } } uint32_t ConditionSpeed::getIcons() const { uint32_t icons = Condition::getIcons(); switch (conditionType) { case CONDITION_HASTE: icons |= ICON_HASTE; break; case CONDITION_PARALYZE: icons |= ICON_PARALYZE; break; default: break; } return icons; } ConditionInvisible::ConditionInvisible(ConditionId_t _id, ConditionType_t _type, int32_t _ticks, bool _buff, uint32_t _subId) : ConditionGeneric(_id, _type, _ticks, _buff, _subId) { // } bool ConditionInvisible::startCondition(Creature* creature) { if (!Condition::startCondition(creature)) { return false; } g_game.internalCreatureChangeVisible(creature, false); return true; } void ConditionInvisible::endCondition(Creature* creature) { if (!creature->isInvisible()) { g_game.internalCreatureChangeVisible(creature, true); } } ConditionOutfit::ConditionOutfit(ConditionId_t _id, ConditionType_t _type, int32_t _ticks, bool _buff, uint32_t _subId) : Condition(_id, _type, _ticks, _buff, _subId) { // } void ConditionOutfit::setOutfit(const Outfit_t& outfit) { this->outfit = outfit; } bool ConditionOutfit::unserializeProp(ConditionAttr_t attr, PropStream& propStream) { if (attr == CONDITIONATTR_OUTFIT) { return propStream.read<Outfit_t>(outfit); } return Condition::unserializeProp(attr, propStream); } void ConditionOutfit::serialize(PropWriteStream& propWriteStream) { Condition::serialize(propWriteStream); propWriteStream.write<uint8_t>(CONDITIONATTR_OUTFIT); propWriteStream.write<Outfit_t>(outfit); } bool ConditionOutfit::startCondition(Creature* creature) { if (!Condition::startCondition(creature)) { return false; } g_game.internalCreatureChangeOutfit(creature, outfit); return true; } bool ConditionOutfit::executeCondition(Creature* creature, int32_t interval) { return Condition::executeCondition(creature, interval); } void ConditionOutfit::endCondition(Creature* creature) { g_game.internalCreatureChangeOutfit(creature, creature->getDefaultOutfit()); } void ConditionOutfit::addCondition(Creature* creature, const Condition* addCondition) { if (updateCondition(addCondition)) { setTicks(addCondition->getTicks()); const ConditionOutfit& conditionOutfit = static_cast<const ConditionOutfit&>(*addCondition); outfit = conditionOutfit.outfit; g_game.internalCreatureChangeOutfit(creature, outfit); } } ConditionLight::ConditionLight(ConditionId_t _id, ConditionType_t _type, int32_t _ticks, bool _buff, uint32_t _subId, uint8_t _lightlevel, uint8_t _lightcolor) : Condition(_id, _type, _ticks, _buff, _subId) { lightInfo.level = _lightlevel; lightInfo.color = _lightcolor; internalLightTicks = 0; lightChangeInterval = 0; } bool ConditionLight::startCondition(Creature* creature) { if (!Condition::startCondition(creature)) { return false; } internalLightTicks = 0; lightChangeInterval = ticks / lightInfo.level; creature->setCreatureLight(lightInfo); g_game.changeLight(creature); return true; } bool ConditionLight::executeCondition(Creature* creature, int32_t interval) { internalLightTicks += interval; if (internalLightTicks >= lightChangeInterval) { internalLightTicks = 0; LightInfo creatureLight; creature->getCreatureLight(creatureLight); if (creatureLight.level > 0) { --creatureLight.level; creature->setCreatureLight(creatureLight); g_game.changeLight(creature); } } return Condition::executeCondition(creature, interval); } void ConditionLight::endCondition(Creature* creature) { creature->setNormalCreatureLight(); g_game.changeLight(creature); } void ConditionLight::addCondition(Creature* creature, const Condition* addCondition) { if (updateCondition(addCondition)) { setTicks(addCondition->getTicks()); const ConditionLight& conditionLight = static_cast<const ConditionLight&>(*addCondition); lightInfo.level = conditionLight.lightInfo.level; lightInfo.color = conditionLight.lightInfo.color; lightChangeInterval = ticks / lightInfo.level; internalLightTicks = 0; creature->setCreatureLight(lightInfo); g_game.changeLight(creature); } } bool ConditionLight::setParam(ConditionParam_t param, int32_t value) { bool ret = Condition::setParam(param, value); if (ret) { return false; } switch (param) { case CONDITION_PARAM_LIGHT_LEVEL: lightInfo.level = value; return true; case CONDITION_PARAM_LIGHT_COLOR: lightInfo.color = value; return true; default: return false; } } bool ConditionLight::unserializeProp(ConditionAttr_t attr, PropStream& propStream) { if (attr == CONDITIONATTR_LIGHTCOLOR) { uint32_t value; if (!propStream.read<uint32_t>(value)) { return false; } lightInfo.color = value; return true; } else if (attr == CONDITIONATTR_LIGHTLEVEL) { uint32_t value; if (!propStream.read<uint32_t>(value)) { return false; } lightInfo.level = value; return true; } else if (attr == CONDITIONATTR_LIGHTTICKS) { return propStream.read<uint32_t>(internalLightTicks); } else if (attr == CONDITIONATTR_LIGHTINTERVAL) { return propStream.read<uint32_t>(lightChangeInterval); } return Condition::unserializeProp(attr, propStream); } void ConditionLight::serialize(PropWriteStream& propWriteStream) { Condition::serialize(propWriteStream); // TODO: color and level could be serialized as 8-bit if we can retain backwards // compatibility, but perhaps we should keep it like this in case they increase // in the future... propWriteStream.write<uint8_t>(CONDITIONATTR_LIGHTCOLOR); propWriteStream.write<uint32_t>(lightInfo.color); propWriteStream.write<uint8_t>(CONDITIONATTR_LIGHTLEVEL); propWriteStream.write<uint32_t>(lightInfo.level); propWriteStream.write<uint8_t>(CONDITIONATTR_LIGHTTICKS); propWriteStream.write<uint32_t>(internalLightTicks); propWriteStream.write<uint8_t>(CONDITIONATTR_LIGHTINTERVAL); propWriteStream.write<uint32_t>(lightChangeInterval); }
babymannen/theforgottenserver-7.4
src/condition.cpp
C++
gpl-2.0
38,497
/* LICENSE ------- Copyright 2005 Nullsoft, Inc. 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 Nullsoft 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 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. */ #include <windows.h> #include <commctrl.h> #include <math.h> #include "r_defs.h" #include "resource.h" #include "avs_eelif.h" #include "timing.h" #ifndef LASER #define C_THISCLASS C_DColorModClass #define MOD_NAME "Trans / Color Modifier" class C_THISCLASS : public C_RBASE { protected: public: C_THISCLASS(); virtual ~C_THISCLASS(); virtual int render(char visdata[2][2][576], int isBeat, int *framebuffer, int *fbout, int w, int h); virtual char *get_desc() { return MOD_NAME; } virtual HWND conf(HINSTANCE hInstance, HWND hwndParent); virtual void load_config(unsigned char *data, int len); virtual int save_config(unsigned char *data); RString effect_exp[4]; int m_recompute; int m_tab_valid; unsigned char m_tab[768]; int AVS_EEL_CONTEXTNAME; double *var_r, *var_g, *var_b, *var_beat; int inited; int codehandle[4]; int need_recompile; CRITICAL_SECTION rcs; }; #define PUT_INT(y) data[pos]=(y)&255; data[pos+1]=(y>>8)&255; data[pos+2]=(y>>16)&255; data[pos+3]=(y>>24)&255 #define GET_INT() (data[pos]|(data[pos+1]<<8)|(data[pos+2]<<16)|(data[pos+3]<<24)) void C_THISCLASS::load_config(unsigned char *data, int len) { int pos=0; if (data[pos] == 1) { pos++; load_string(effect_exp[0],data,pos,len); load_string(effect_exp[1],data,pos,len); load_string(effect_exp[2],data,pos,len); load_string(effect_exp[3],data,pos,len); } else { char buf[1025]; if (len-pos >= 1024) { memcpy(buf,data+pos,1024); pos+=1024; buf[1024]=0; effect_exp[3].assign(buf+768); buf[768]=0; effect_exp[2].assign(buf+512); buf[512]=0; effect_exp[1].assign(buf+256); buf[256]=0; effect_exp[0].assign(buf); } } if (len-pos >= 4) { m_recompute=GET_INT(); pos+=4; } } int C_THISCLASS::save_config(unsigned char *data) { int pos=0; data[pos++]=1; save_string(data,pos,effect_exp[0]); save_string(data,pos,effect_exp[1]); save_string(data,pos,effect_exp[2]); save_string(data,pos,effect_exp[3]); PUT_INT(m_recompute); pos+=4; return pos; } C_THISCLASS::C_THISCLASS() { AVS_EEL_INITINST(); InitializeCriticalSection(&rcs); need_recompile=1; m_recompute=1; memset(codehandle,0,sizeof(codehandle)); effect_exp[0].assign(""); effect_exp[1].assign(""); effect_exp[2].assign(""); effect_exp[3].assign(""); var_beat=0; m_tab_valid=0; } C_THISCLASS::~C_THISCLASS() { int x; for (x = 0; x < 4; x ++) { freeCode(codehandle[x]); codehandle[x]=0; } AVS_EEL_QUITINST(); DeleteCriticalSection(&rcs); } int C_THISCLASS::render(char visdata[2][2][576], int isBeat, int *framebuffer, int *fbout, int w, int h) { if (need_recompile) { EnterCriticalSection(&rcs); if (!var_beat || g_reset_vars_on_recompile) { clearVars(); var_r = registerVar("red"); var_g = registerVar("green"); var_b = registerVar("blue"); var_beat = registerVar("beat"); inited=0; } need_recompile=0; int x; for (x = 0; x < 4; x ++) { freeCode(codehandle[x]); codehandle[x]=compileCode(effect_exp[x].get()); } LeaveCriticalSection(&rcs); } if (isBeat&0x80000000) return 0; *var_beat=isBeat?1.0:0.0; if (codehandle[3] && !inited) { executeCode(codehandle[3],visdata); inited=1; } executeCode(codehandle[1],visdata); if (isBeat) executeCode(codehandle[2],visdata); if (m_recompute || !m_tab_valid) { int x; unsigned char *t=m_tab; for (x = 0; x < 256; x ++) { *var_r=*var_b=*var_g=x/255.0; executeCode(codehandle[0],visdata); int r=(int) (*var_r*255.0 + 0.5); int g=(int) (*var_g*255.0 + 0.5); int b=(int) (*var_b*255.0 + 0.5); if (r < 0) r=0; else if (r > 255)r=255; if (g < 0) g=0; else if (g > 255)g=255; if (b < 0) b=0; else if (b > 255)b=255; t[512]=r; t[256]=g; t[0]=b; t++; } m_tab_valid=1; } unsigned char *fb=(unsigned char *)framebuffer; int l=w*h; while (l--) { fb[0]=m_tab[fb[0]]; fb[1]=m_tab[(int)fb[1]+256]; fb[2]=m_tab[(int)fb[2]+512]; fb+=4; } return 0; } C_RBASE *R_DColorMod(char *desc) { if (desc) { strcpy(desc,MOD_NAME); return NULL; } return (C_RBASE *) new C_THISCLASS(); } typedef struct { char *name; char *init; char *point; char *frame; char *beat; int recompute; } presetType; static presetType presets[]= { // Name, Init, Level, Frame, Beat, Recalc {"4x Red Brightness, 2x Green, 1x Blue","","red=4*red; green=2*green;","","",0}, {"Solarization","","red=(min(1,red*2)-red)*2;\r\ngreen=red; blue=red;","","",0}, {"Double Solarization","","red=(min(1,red*2)-red)*2;\r\nred=(min(1,red*2)-red)*2;\r\ngreen=red; blue=red;","","",0}, {"Inverse Solarization (Soft)","","red=abs(red - .5) * 1.5;\r\ngreen=red; blue=red;","","",0}, {"Big Brightness on Beat","scale=1.0","red=red*scale;\r\ngreen=red; blue=red;","scale=0.07 + (scale*0.93)","scale=16",1}, {"Big Brightness on Beat (Interpolative)","c = 200; f = 0;","red = red * t;\r\ngreen=red;blue=red;","f = f + 1;\r\nt = (1.025 - (f / c)) * 5;","c = f;f = 0;",1}, {"Pulsing Brightness (Beat Interpolative)","c = 200; f = 0;","red = red * st;\r\ngreen=red;blue=red;","f = f + 1;\r\nt = (f * 2 * $PI) / c;\r\nst = sin(t) + 1;","c = f;f = 0;",1}, {"Rolling Solarization (Beat Interpolative)","c = 200; f = 0;","red=(min(1,red*st)-red)*st;\r\nred=(min(1,red*2)-red)*2;\r\ngreen=red; blue=red;","f = f + 1;\r\nt = (f * 2 * $PI) / c;\r\nst = ( sin(t) * .75 ) + 2;","c = f;f = 0;",1}, {"Rolling Tone (Beat Interpolative)","c = 200; f = 0;","red = red * st;\r\ngreen = green * ct;\r\nblue = (blue * 4 * ti) - red - green;","f = f + 1;\r\nt = (f * 2 * $PI) / c;\r\nti = (f / c);\r\nst = sin(t) + 1.5;\r\nct = cos(t) + 1.5;","c = f;f = 0;",1}, {"Random Inverse Tone (Switch on Beat)","","dd = red * 1.5;\r\nred = pow(dd, dr);\r\ngreen = pow(dd, dg);\r\nblue = pow(dd, db);","","token = rand(99) % 3;\r\ndr = if (equal(token, 0), -1, 1);\r\ndg = if (equal(token, 1), -1, 1);\r\ndb = if (equal(token, 2), -1, 1);",1}, }; static C_THISCLASS *g_this; static BOOL CALLBACK g_DlgProc(HWND hwndDlg, UINT uMsg, WPARAM wParam,LPARAM lParam) { static int isstart; switch (uMsg) { case WM_INITDIALOG: isstart=1; SetDlgItemText(hwndDlg,IDC_EDIT1,g_this->effect_exp[0].get()); SetDlgItemText(hwndDlg,IDC_EDIT2,g_this->effect_exp[1].get()); SetDlgItemText(hwndDlg,IDC_EDIT3,g_this->effect_exp[2].get()); SetDlgItemText(hwndDlg,IDC_EDIT4,g_this->effect_exp[3].get()); if (g_this->m_recompute) CheckDlgButton(hwndDlg,IDC_CHECK1,BST_CHECKED); isstart=0; return 1; case WM_COMMAND: if (LOWORD(wParam) == IDC_BUTTON1) { char *text="Color Modifier\0" "The color modifier allows you to modify the intensity of each color\r\n" "channel with respect to itself. For example, you could reverse the red\r\n" "channel, double the green channel, or half the blue channel.\r\n" "\r\n" "The code in the 'level' section should adjust the variables\r\n" "'red', 'green', and 'blue', whose value represent the channel\r\n" "intensity (0..1).\r\n" "Code in the 'frame' or 'level' sections can also use the variable\r\n" "'beat' to detect if it is currently a beat.\r\n" "\r\n" "Try loading an example via the 'Load Example' button for examples." ; compilerfunctionlist(hwndDlg,text); } if (LOWORD(wParam)==IDC_CHECK1) { g_this->m_recompute=IsDlgButtonChecked(hwndDlg,IDC_CHECK1)?1:0; } if (LOWORD(wParam) == IDC_BUTTON4) { RECT r; HMENU hMenu; MENUITEMINFO i={sizeof(i),}; hMenu=CreatePopupMenu(); int x; for (x = 0; x < sizeof(presets)/sizeof(presets[0]); x ++) { i.fMask=MIIM_TYPE|MIIM_DATA|MIIM_ID; i.fType=MFT_STRING; i.wID = x+16; i.dwTypeData=presets[x].name; i.cch=strlen(presets[x].name); InsertMenuItem(hMenu,x,TRUE,&i); } GetWindowRect(GetDlgItem(hwndDlg,IDC_BUTTON4),&r); x=TrackPopupMenu(hMenu,TPM_LEFTALIGN|TPM_TOPALIGN|TPM_RETURNCMD|TPM_RIGHTBUTTON|TPM_LEFTBUTTON|TPM_NONOTIFY,r.right,r.top,0,hwndDlg,NULL); if (x >= 16 && x < 16+sizeof(presets)/sizeof(presets[0])) { isstart=1; SetDlgItemText(hwndDlg,IDC_EDIT1,presets[x-16].point); SetDlgItemText(hwndDlg,IDC_EDIT2,presets[x-16].frame); SetDlgItemText(hwndDlg,IDC_EDIT3,presets[x-16].beat); SetDlgItemText(hwndDlg,IDC_EDIT4,presets[x-16].init); g_this->m_recompute=presets[x-16].recompute; CheckDlgButton(hwndDlg,IDC_CHECK1,g_this->m_recompute?BST_CHECKED:0); isstart=0; SendMessage(hwndDlg,WM_COMMAND,MAKEWPARAM(IDC_EDIT4,EN_CHANGE),0); } DestroyMenu(hMenu); } if (!isstart && HIWORD(wParam) == EN_CHANGE) { if (LOWORD(wParam) == IDC_EDIT1||LOWORD(wParam) == IDC_EDIT2||LOWORD(wParam) == IDC_EDIT3||LOWORD(wParam) == IDC_EDIT4) { EnterCriticalSection(&g_this->rcs); g_this->effect_exp[0].get_from_dlgitem(hwndDlg,IDC_EDIT1); g_this->effect_exp[1].get_from_dlgitem(hwndDlg,IDC_EDIT2); g_this->effect_exp[2].get_from_dlgitem(hwndDlg,IDC_EDIT3); g_this->effect_exp[3].get_from_dlgitem(hwndDlg,IDC_EDIT4); g_this->need_recompile=1; if (LOWORD(wParam) == IDC_EDIT4) g_this->inited = 0; g_this->m_tab_valid=0; LeaveCriticalSection(&g_this->rcs); } } return 0; } return 0; } HWND C_THISCLASS::conf(HINSTANCE hInstance, HWND hwndParent) { g_this = this; return CreateDialog(hInstance,MAKEINTRESOURCE(IDD_CFG_COLORMOD),hwndParent,g_DlgProc); } #else C_RBASE *R_DColorMod(char *desc) { return NULL; } #endif
Libvisual/libvisual-avs
avs_src/avs/vis_avs/r_dcolormod.cpp
C++
gpl-2.0
11,923
/***********************************************************************/ /* This file contains unpublished documentation and software */ /* proprietary to Cortina Systems Incorporated. Any use or disclosure, */ /* in whole or in part, of the information in this file without a */ /* written consent of an officer of Cortina Systems Incorporated is */ /* strictly prohibited. */ /* Copyright (c) 2010 by Cortina Systems Incorporated. */ /***********************************************************************/ /* * cs_vtable.c * * $Id$ * * It contains the implementation of vtable framework, which is abstract * entity that is used to maintain several FE entities at once. */ #include <linux/spinlock.h> #include "cs_core_vtable.h" #include "cs_vtable.h" #include "cs_fe.h" #include "cs_fe_mc.h" /* allocate a vtable by allocating its Classifier and SDB. Set up Classifier * according to the given classifier. Set up the default action according to * the given default action. * Input: 1) Pointer to classifier * 2) default action type * Return: Pointer to vtable if succeeds. Null, if otherwise. */ cs_vtable_t *cs_vtable_alloc(fe_class_entry_t *p_class, unsigned int def_act, unsigned int vtbl_type) { cs_vtable_t *new_table; fe_sdb_entry_t sdb_entry; int ret; new_table = kzalloc(sizeof(cs_vtable_t), GFP_ATOMIC); if (new_table == NULL) return NULL; new_table->uuflow_idx = 0xffff; new_table->bcflow_idx = 0xffff; new_table->umflow_idx = 0xffff; new_table->mcgid = MCG_INIT_MCGID; new_table->vtable_type = vtbl_type; spin_lock_init(&new_table->lock); /* alloc classifier and sdb entry */ ret = cs_fe_table_alloc_entry(FE_TABLE_SDB, &new_table->sdb_index, 0); if (ret != 0) { kfree(new_table); return NULL; } memset((void *)&sdb_entry, 0x0, sizeof(sdb_entry)); ret = cs_fe_table_set_entry(FE_TABLE_SDB, new_table->sdb_index, &sdb_entry); if (ret != 0) goto EXIT_FREE_SDB; ret = cs_fe_table_inc_entry_refcnt(FE_TABLE_SDB, new_table->sdb_index); if (ret != 0) goto EXIT_FREE_SDB; ret = cs_vtable_set_def_action(new_table, (CS_VTABLE_DEF_ACT_TYPE_UU | CS_VTABLE_DEF_ACT_TYPE_UM | CS_VTABLE_DEF_ACT_TYPE_BC), def_act); if (ret != 0) goto EXIT_FREE_SDB; /* Done setting SDB.. now move on to classifier */ p_class->sdb_idx = new_table->sdb_index; ret = cs_fe_table_alloc_entry(FE_TABLE_CLASS, &new_table->class_index, 0); if (ret != 0) goto EXIT_FREE_SDB; ret = cs_fe_table_set_entry(FE_TABLE_CLASS, new_table->class_index, p_class); if (ret != 0) goto EXIT_FREE_CLASS; ret = cs_fe_table_inc_entry_refcnt(FE_TABLE_CLASS, new_table->class_index); if (ret != 0) goto EXIT_FREE_CLASS; return new_table; EXIT_FREE_CLASS: cs_fe_table_del_entry_by_idx(FE_TABLE_CLASS, new_table->class_index, false); EXIT_FREE_SDB: cs_fe_table_del_entry_by_idx(FE_TABLE_SDB, new_table->sdb_index, false); kfree(new_table); return NULL; } /* cs_vtable_alloc */ /* free vtable. Need to release the Classifier, SDB, hash masks, and the * forwarding results used for default actions */ int cs_vtable_free(cs_vtable_t *table) { unsigned int uuflow_idx = 0xffff, bcflow_idx = 0xffff; int ret, i; fe_sdb_entry_t sdb_entry; if (table == NULL) return -1; spin_lock(&table->lock); ret = cs_fe_table_del_entry_by_idx(FE_TABLE_CLASS, table->class_index, false); if (ret != 0) printk("%s:%d:failed at deleting CLASS entry\n", __func__, __LINE__); ret = cs_fe_table_get_entry(FE_TABLE_SDB, table->sdb_index, &sdb_entry); if (ret != 0) printk("%s:%d:failed at getting CLASS entry\n", __func__, __LINE__); for (i = 0; i < 8; i++) { if (sdb_entry.sdb_tuple[i].enable == 1) { cs_fe_table_del_entry_by_idx(FE_TABLE_HASH_MASK, sdb_entry.sdb_tuple[i].mask_ptr, false); sdb_entry.sdb_tuple[i].enable = 0; sdb_entry.sdb_tuple[i].mask_ptr = 0; } } ret = cs_fe_table_del_entry_by_idx(FE_TABLE_SDB, table->sdb_index, false); if (ret != 0) { printk("%s:%d:failed at deleting SDB entry\n", __func__, __LINE__); spin_unlock(&table->lock); return ret; } if (table->uuflow_idx != 0xffff) { uuflow_idx = table->uuflow_idx; ret = cs_fe_fwdrslt_del_by_idx(table->uuflow_idx); if (ret != 0) printk("%s:%d:failed to delete uuflow idx %d\n", __func__, __LINE__, table->uuflow_idx); } if ((table->bcflow_idx != 0xffff) && (table->bcflow_idx != uuflow_idx)) { bcflow_idx = table->bcflow_idx; ret = cs_fe_fwdrslt_del_by_idx(table->bcflow_idx); if (ret != 0) printk("%s:%d:failed to delete bcflow idx %d\n", __func__, __LINE__, table->bcflow_idx); } if ((table->umflow_idx != 0xffff) && (table->umflow_idx != uuflow_idx) && (table->umflow_idx != bcflow_idx)) { ret = cs_fe_fwdrslt_del_by_idx(table->umflow_idx); if (ret != 0) printk("%s:%d:failed to delete umflow idx %d\n", __func__, __LINE__, table->umflow_idx); } if (IS_ARBITRARY_REPLICATION_MODE(table->mcgid)) cs_fe_free_mcg_vtable_id(MCG_VTABLE_ID(table->mcgid)); spin_unlock(&table->lock); return 0; } /* cs_vtable_free */ /* set up default action to the specific default action type */ int cs_vtable_set_def_action(cs_vtable_t *table, u8 def_act_type_mask, unsigned int def_act) { unsigned int voq_id = def_act; unsigned int fwdrslt_idx = 0, voqpol_idx = 0; unsigned int um_fwdrslt_idx = 0, um_voqpol_idx = 0; int ret; fe_fwd_result_entry_t fwdrslt_entry, um_fwdrslt_entry; fe_voq_pol_entry_t voqpol_entry, um_voqpol_entry; fe_sdb_entry_t sdb_entry; if (table == NULL) return -1; ret = cs_fe_table_get_entry(FE_TABLE_SDB, table->sdb_index, &sdb_entry); if (ret != 0) return ret; memset(&fwdrslt_entry, 0, sizeof(fwdrslt_entry)); memset(&voqpol_entry, 0, sizeof(voqpol_entry)); voqpol_entry.voq_base = voq_id; voqpol_entry.cos_nop = 0; ret = cs_fe_table_add_entry(FE_TABLE_VOQ_POLICER, &voqpol_entry, &voqpol_idx); if (ret != 0) return ret; fwdrslt_entry.dest.voq_policy = 1; fwdrslt_entry.dest.voq_pol_table_index = voqpol_idx; ret = cs_fe_table_add_entry(FE_TABLE_FWDRSLT, &fwdrslt_entry, &fwdrslt_idx); if (ret != 0) { cs_fe_table_del_entry_by_idx(FE_TABLE_VOQ_POLICER, voqpol_idx, false); return ret; } /* default action of umflow is to drop */ memset(&um_fwdrslt_entry, 0, sizeof(um_fwdrslt_entry)); memset(&um_voqpol_entry, 0, sizeof(um_voqpol_entry)); if (table->vtable_type == CORE_VTABLE_TYPE_ICMPV6) { um_fwdrslt_entry.dest.voq_policy = 1; um_fwdrslt_entry.dest.voq_pol_table_index = voqpol_idx; } else { um_fwdrslt_entry.act.drop = 1; } ret = cs_fe_table_add_entry(FE_TABLE_FWDRSLT, &um_fwdrslt_entry, &um_fwdrslt_idx); if (ret != 0) { // cs_fe_table_del_entry_by_idx(FE_TABLE_VOQ_POLICER, // um_voqpol_idx, false); return ret; } if (def_act_type_mask & CS_VTABLE_DEF_ACT_TYPE_UU) { sdb_entry.misc.uu_flowidx = fwdrslt_idx; table->uuflow_idx = fwdrslt_idx; } if (def_act_type_mask & CS_VTABLE_DEF_ACT_TYPE_UM) { sdb_entry.misc.um_flowidx = um_fwdrslt_idx; table->umflow_idx = um_fwdrslt_idx; } if (def_act_type_mask & CS_VTABLE_DEF_ACT_TYPE_BC) { sdb_entry.misc.bc_flowidx = fwdrslt_idx; table->bcflow_idx = fwdrslt_idx; } sdb_entry.misc.ttl_hop_limit_zero_discard_en = 1; ret = cs_fe_table_set_entry(FE_TABLE_SDB, table->sdb_index, &sdb_entry); if (ret != 0) { table->uuflow_idx = 0xffff; table->umflow_idx = 0xffff; table->bcflow_idx = 0xffff; cs_fe_table_del_entry_by_idx(FE_TABLE_FWDRSLT, fwdrslt_idx, false); } return ret; } /* cs_vtable_set_def_action */ /* add given hashmask to the vtable with the given priority. * Return the hashmask index if succeed. Else otherwise. */ int cs_vtable_add_hashmask(cs_vtable_t *table, fe_hash_mask_entry_t *hm_ptr, unsigned int priority, bool is_qos) { fe_sdb_entry_t sdb_entry; unsigned int start_idx, end_idx, check_start_idx, check_end_idx; unsigned int hash_mask_idx, iii, dst_idx = 0; bool f_new_hashmask = false, find_match = false, find_slot = false; int ret = 0; if ((table == NULL) || (hm_ptr == NULL)) return 0; if (is_qos == true) { start_idx = 6; end_idx = 7; check_start_idx = 0; check_end_idx = 5; } else { start_idx = 0; end_idx = 5; check_start_idx = 6; check_end_idx = 7; } /* 1) find or create a new hash mask */ ret = cs_fe_table_find_entry(FE_TABLE_HASH_MASK, hm_ptr, &hash_mask_idx, 0); if (ret == FE_TABLE_ENTRYNOTFOUND) { ret = cs_fe_table_add_entry(FE_TABLE_HASH_MASK, hm_ptr, &hash_mask_idx); if (ret != 0) return ret; f_new_hashmask = true; } if (ret != 0) return ret; /* 2) check if there is a place to insert in sdb */ /* for tuple insertion, we have to take care of the case that when we * are sharing the hashmask entry with another user. we have to make * sure the shared user is not our own tuples of other type, such that * same hash mask setting used in both FWD tuple and QoS tuple should * have different hash_index. If that's the case, we will need to create * a new one! Therefore, the step will be: * 1) going through the vtable, make sure there is no previous entry of * the same index and find the index where we are going to insert this * hashmask to. * 2) Then we compare this hashmask index with other hashmask index * used in this vtable.*/ spin_lock(&table->lock); ret = cs_fe_table_get_entry(FE_TABLE_SDB, table->sdb_index, &sdb_entry); if (ret != 0) goto EXIT_FREE_HASHMASK; for (iii = start_idx; iii <= end_idx; iii++) { if ((sdb_entry.sdb_tuple[iii].enable == 0) && (find_slot == false)) { find_slot = true; dst_idx = iii; } else if ((sdb_entry.sdb_tuple[iii].enable == 1) && (sdb_entry.sdb_tuple[iii].mask_ptr == hash_mask_idx)) { find_match = true; dst_idx = iii; break; } } if (find_match == true) { /* the same hash index has been inserted! If given priority is * not 0, then all we do here is updating the priority. */ if (priority != 0) { sdb_entry.sdb_tuple[dst_idx].priority = priority; ret = cs_fe_table_set_entry(FE_TABLE_SDB, table->sdb_index, &sdb_entry); } ret = (int)hash_mask_idx; goto EXIT_FREE_HASHMASK; } if (find_slot == false) { ret = -1; goto EXIT_FREE_HASHMASK; } /* at this point. we have already located the dst_index. * Now we need to search through the tuple of other type in the same * SDB to make sure we don't have duplicate. For example, if we are * inserting a hashmask index to tuple#0~5, we shouldn't have the same * hashmask index in tuple#6~7, or the hash will get confused. */ for (iii = check_start_idx; iii <= check_end_idx; iii++) { if ((f_new_hashmask == false) && (sdb_entry.sdb_tuple[iii].enable == 1) && (sdb_entry.sdb_tuple[iii].mask_ptr == hash_mask_idx)) { /* found a matching one. need to either find or create * a new hash mask. */ ret = cs_fe_table_find_entry(FE_TABLE_HASH_MASK, hm_ptr, &hash_mask_idx, hash_mask_idx + 1); if (ret == FE_TABLE_ENTRYNOTFOUND) { ret = cs_fe_table_alloc_entry( FE_TABLE_HASH_MASK, &hash_mask_idx, 0); if (ret != 0) goto EXIT_FREE_HASHMASK; f_new_hashmask = true; ret = cs_fe_table_set_entry(FE_TABLE_HASH_MASK, hash_mask_idx, (void*)hm_ptr); if (ret != 0) goto EXIT_FREE_HASHMASK; ret = cs_fe_table_inc_entry_refcnt( FE_TABLE_HASH_MASK, hash_mask_idx); if (ret != 0) goto EXIT_FREE_HASHMASK; } } } /* 3) update SDB */ /* now we have the proper hash_mask_idx and dst_idx. * We can perform the modification */ sdb_entry.sdb_tuple[dst_idx].mask_ptr = hash_mask_idx; sdb_entry.sdb_tuple[dst_idx].priority = (priority == 0) ? dst_idx : priority; sdb_entry.sdb_tuple[dst_idx].enable = 1; ret = cs_fe_table_set_entry(FE_TABLE_SDB, table->sdb_index, &sdb_entry); if (ret != 0) goto EXIT_FREE_HASHMASK; /* one thing that we didn't care is tuple priority conflict in the * same sdb. * Also, this logic is exposed to an issue, where when we have the same * hashmask entry in 2 different entries of table, there is a chance * that we might have two or more different hash mask pointed to the * same hash match info in the same tuple, but assuming when one * calculates hash value, the hash mask index is different. */ spin_unlock(&table->lock); if (f_new_hashmask == false) cs_fe_table_inc_entry_refcnt(FE_TABLE_HASH_MASK, hash_mask_idx); return (int)hash_mask_idx; EXIT_FREE_HASHMASK: spin_unlock(&table->lock); if (f_new_hashmask == true) cs_fe_table_del_entry_by_idx(FE_TABLE_HASH_MASK, hash_mask_idx, false); return ret; } /* cs_vtable_add_hashmask */ static inline int check_sdb_and_del_hashmask(unsigned int sdb_idx, unsigned int hm_idx, bool is_qos) { unsigned int start_idx, end_idx, iii; fe_sdb_entry_t sdb_entry; int ret; if (is_qos == true) { start_idx = 6; end_idx = 7; } else { start_idx = 0; end_idx = 5; } /* get the SDB info */ ret = cs_fe_table_get_entry(FE_TABLE_SDB, sdb_idx, &sdb_entry); if (ret != 0) return ret; for (iii = start_idx; iii <= end_idx; iii++) { if ((sdb_entry.sdb_tuple[iii].enable == 1) && (sdb_entry.sdb_tuple[iii].mask_ptr == hm_idx)) { /* found a matching one.. need to remove it from SDB */ sdb_entry.sdb_tuple[iii].enable = 0; sdb_entry.sdb_tuple[iii].mask_ptr = 0; sdb_entry.sdb_tuple[iii].priority = 0; ret = cs_fe_table_set_entry(FE_TABLE_SDB, sdb_idx, &sdb_entry); if (ret != 0) return ret; /* delete this hashmask entry */ ret = cs_fe_table_del_entry_by_idx(FE_TABLE_HASH_MASK, hm_idx, false); if (ret != 0) return ret; } } return 0; } /* check_sdb_and_del_hashmask */ /* find the matching hashmask from given vtable and delete it. * return 0 if succeeds (does not matter whether it really delets it or not, * but it makes sure there is no matching hash mask in the vtable). * Else otherwise */ int cs_vtable_del_hashmask(cs_vtable_t *table, fe_hash_mask_entry_t *hm_ptr, bool is_qos) { unsigned int hash_mask_idx, offset = 0; int ret = 0; if ((table == NULL) || (hm_ptr == NULL)) return -1; /* use a do-while look to find all the hash_mask_index with entries * that match the given hm_ptr */ do { ret = cs_fe_table_find_entry(FE_TABLE_HASH_MASK, hm_ptr, &hash_mask_idx, offset); if (ret == 0) { spin_lock(&table->lock); ret = check_sdb_and_del_hashmask(table->sdb_index, hash_mask_idx, is_qos); if (ret != 0) goto EXIT_DEL_TUPLE; spin_unlock(&table->lock); offset = hash_mask_idx + 1; } } while (ret == 0); return 0; EXIT_DEL_TUPLE: spin_unlock(&table->lock); return ret; } /* cs_vtable_del_hashmask */ /* delete the hash mask with hm_idx from vtable. * return 0 if succeeds, else otherwise. */ int cs_vtable_del_hashmask_by_idx(cs_vtable_t *table, u32 hm_idx, bool is_qos) { int ret; if (table == NULL) return -1; spin_lock(&table->lock); ret = check_sdb_and_del_hashmask(table->sdb_index, hm_idx, is_qos); spin_unlock(&table->lock); return ret; } /* cs_vtable_del_hashmask_by_idx */ /* delete all the hash mask associated with this vtable. */ int cs_vtable_del_hashmask_all(cs_vtable_t *table) { fe_sdb_entry_t sdb_entry; unsigned int iii, ret; if (table == NULL) return -1; spin_lock(&table->lock); ret = cs_fe_table_get_entry(FE_TABLE_SDB, table->sdb_index, &sdb_entry); if (ret != 0) { spin_unlock(&table->lock); return ret; } for (iii = 0; iii <= 7; iii++) { if (sdb_entry.sdb_tuple[iii].enable == 1) { /* delete this hashmask entry */ ret = cs_fe_table_del_entry_by_idx(FE_TABLE_HASH_MASK, sdb_entry.sdb_tuple[iii].mask_ptr, false); if (ret != 0) { /* we need to set SDB before quitting it, * bacause we might've deleted some mask */ cs_fe_table_set_entry(FE_TABLE_SDB, table->sdb_index, &sdb_entry); spin_unlock(&table->lock); return ret; } sdb_entry.sdb_tuple[iii].enable = 0; sdb_entry.sdb_tuple[iii].mask_ptr = 0; sdb_entry.sdb_tuple[iii].priority = 0; } } ret = cs_fe_table_set_entry(FE_TABLE_SDB, table->sdb_index, &sdb_entry); spin_unlock(&table->lock); return ret; } /* cs_vtable_del_hashmask_all */ /* find the hashmask index that matches the given hash mask entry in vtable */ int cs_vtable_get_hashmask_idx(cs_vtable_t *table, fe_hash_mask_entry_t *hm_ptr, bool is_qos) { unsigned int start_idx, end_idx; fe_hash_mask_entry_t curr_hm_entry; fe_sdb_entry_t sdb_entry; int ret, iii; if (table == NULL) return -1; if (is_qos == true) { start_idx = 6; end_idx = 7; } else { start_idx = 0; end_idx = 5; } spin_lock(&table->lock); ret = cs_fe_table_get_entry(FE_TABLE_SDB, table->sdb_index, &sdb_entry); if (ret != 0) { spin_unlock(&table->lock); return ret; } for (iii = start_idx; iii <= end_idx; iii++) { if (sdb_entry.sdb_tuple[iii].enable == 1) { ret = cs_fe_table_get_entry(FE_TABLE_HASH_MASK, sdb_entry.sdb_tuple[iii].mask_ptr, &curr_hm_entry); if (ret != 0) { spin_unlock(&table->lock); return ret; } if (memcmp(hm_ptr, &curr_hm_entry, sizeof(fe_hash_mask_entry_t)) == 0) { spin_unlock(&table->lock); return sdb_entry.sdb_tuple[iii].mask_ptr; } } } /* not found if reach here */ spin_unlock(&table->lock); return -1; } /* cs_vtable_get_hashmask_idx */ /* insert vtable to the chain by given the pointer to the new vtable, and the * previous table. It will insert the new vtable between previous vtable and * the next table of previous vtable */ int cs_vtable_insert_to_chain(cs_vtable_t *new_table, cs_vtable_t *prev_table) { cs_vtable_t *next_table, *tmp_table; fe_fwd_result_entry_t fwdrslt_entry; fe_voq_pol_entry_t voqpol_entry; fe_sdb_entry_t prev_sdb_entry, new_sdb_entry; fe_class_entry_t new_class_entry; int ret; unsigned int voqpol_idx, fwdrslt_idx; unsigned int tmp_mcgid, i; unsigned short mcgid_chk_lst[MCGID_BITS][2] = { {0, 0x101}, {0, 0x102}, {0, 0x104}, {0, 0x108}, {0, 0x110}, {0, 0x120}, {0, 0x140}, {0, 0x180} }; if ((new_table == NULL) || (prev_table == NULL)) return -1; next_table = prev_table->next; /* need to assign MCGID, update new_table's default flow forwarding */ /* * Update p_dst_class for MCGID. * Only need to consider "next vtable is port replication mode" case, * since arbitray replication mode is implemented in cs_vtable_alloc() */ if (new_table->mcgid == MCG_INIT_MCGID) { /* locate the first vtable in the chain */ tmp_table = prev_table; while (tmp_table->prev != NULL) { tmp_table = tmp_table->prev; } while (tmp_table) { tmp_mcgid = tmp_table->mcgid; if (IS_PORT_REPLICATION_MODE(tmp_mcgid)) { for (i = 0; i < MCGID_BITS; i++) { if (tmp_mcgid == mcgid_chk_lst[i][1]) { mcgid_chk_lst[i][0] = 1; break; } } } tmp_table = tmp_table->next; } /* assign an unused MCGID */ for (i = 0; i < MCGID_BITS; i++) { if (mcgid_chk_lst[i][0] == 0) { new_table->mcgid = mcgid_chk_lst[i][1]; break; } } if (i == MCGID_BITS) return -EPERM; /* no more unused MCGID */ } spin_lock(&prev_table->lock); spin_lock(&new_table->lock); ret = cs_fe_table_get_entry(FE_TABLE_SDB, prev_table->sdb_index, &prev_sdb_entry); if (ret != 0) { spin_unlock(&prev_table->lock); spin_unlock(&new_table->lock); return ret; } ret = cs_fe_table_get_entry(FE_TABLE_SDB, new_table->sdb_index, &new_sdb_entry); if (ret != 0) { spin_unlock(&prev_table->lock); spin_unlock(&new_table->lock); return ret; } ret = cs_fe_table_get_entry(FE_TABLE_CLASS, new_table->class_index, &new_class_entry); if (ret != 0) { spin_unlock(&prev_table->lock); spin_unlock(&new_table->lock); return ret; } memset(&fwdrslt_entry, 0, sizeof(fwdrslt_entry)); memset(&voqpol_entry, 0, sizeof(voqpol_entry)); voqpol_entry.voq_base = ROOT_PORT_VOQ_BASE; ret = cs_fe_table_add_entry(FE_TABLE_VOQ_POLICER, &voqpol_entry, &voqpol_idx); if (ret != 0) { spin_unlock(&prev_table->lock); spin_unlock(&new_table->lock); return ret; } fwdrslt_entry.dest.voq_pol_table_index = voqpol_idx; fwdrslt_entry.l2.mcgid_valid = 1; fwdrslt_entry.l2.mcgid = new_table->mcgid; ret = cs_fe_table_add_entry(FE_TABLE_FWDRSLT, &fwdrslt_entry, &fwdrslt_idx); if (ret != 0) goto FAIL_CLEAR_VOQPOL; /* now chaining software entity */ prev_table->next = new_table; new_table->next = prev_table; if (next_table != NULL) { new_table->next = next_table; next_table->prev = new_table; } /* * chaining vtable by * 1) set the new vtable's sdb->[uu/um/bc]_flowidx to the * prev vtable's sdb->[uu/um/bc]_flowidx. * 2) set the new vtable's classifier to include the MCGIC * 3) update the prev vtable's sdb->[uu/um/bc]_flowidx to the * new fwdrslt that's just created. */ /* step#1 */ new_sdb_entry.misc.uu_flowidx = prev_sdb_entry.misc.uu_flowidx; new_sdb_entry.misc.um_flowidx = prev_sdb_entry.misc.um_flowidx; new_sdb_entry.misc.bc_flowidx = prev_sdb_entry.misc.bc_flowidx; new_table->uuflow_idx = prev_sdb_entry.misc.uu_flowidx; new_table->umflow_idx = prev_sdb_entry.misc.um_flowidx; new_table->bcflow_idx = prev_sdb_entry.misc.bc_flowidx; ret |= cs_fe_table_set_entry(FE_TABLE_SDB, new_table->sdb_index, &new_sdb_entry); /* step#2 */ new_class_entry.port.mcgid = new_table->mcgid; ret |= cs_fe_table_set_entry(FE_TABLE_CLASS, new_table->class_index, &new_class_entry); /* step#3 */ prev_sdb_entry.misc.uu_flowidx = fwdrslt_idx; prev_sdb_entry.misc.um_flowidx = fwdrslt_idx; prev_sdb_entry.misc.bc_flowidx = fwdrslt_idx; ret = cs_fe_table_set_entry(FE_TABLE_SDB, prev_table->sdb_index, &prev_sdb_entry); if (ret != 0) { prev_table->uuflow_idx = 0xffff; prev_table->umflow_idx = 0xffff; prev_table->bcflow_idx = 0xffff; goto FAIL_CLEAR_FWDRSLT; } prev_table->uuflow_idx = fwdrslt_idx; prev_table->umflow_idx = fwdrslt_idx; prev_table->bcflow_idx = fwdrslt_idx; return 0; FAIL_CLEAR_FWDRSLT: cs_fe_table_del_entry_by_idx(FE_TABLE_FWDRSLT, fwdrslt_idx, false); FAIL_CLEAR_VOQPOL: cs_fe_table_del_entry_by_idx(FE_TABLE_VOQ_POLICER, voqpol_idx, false); spin_unlock(&prev_table->lock); spin_unlock(&new_table->lock); return ret; } /* cs_vtable_insert_to_chain */ /* remove the given vtable from the chain. It will make sure the rest of the * vtables in the chain still keep their linkage properly. * The simple logic here is swapping the default flow indices of curr and prev * vtables. */ int cs_vtable_remove_from_chain(cs_vtable_t *table) { cs_vtable_t *prev_table; int ret; fe_sdb_entry_t prev_sdb_entry, curr_sdb_entry; unsigned int uuflow_idx, umflow_idx, bcflow_idx; if ((table == NULL) || (table->prev == NULL)) return -1; prev_table = table->prev; spin_lock(&prev_table->lock); spin_lock(&table->lock); ret = cs_fe_table_get_entry(FE_TABLE_SDB, prev_table->sdb_index, &prev_sdb_entry); ret |= cs_fe_table_get_entry(FE_TABLE_SDB, table->sdb_index, &curr_sdb_entry); if (ret != 0) { spin_unlock(&prev_table->lock); spin_unlock(&table->lock); return ret; } /* swapping all the default flow indices */ uuflow_idx = prev_sdb_entry.misc.uu_flowidx; umflow_idx = prev_sdb_entry.misc.um_flowidx; bcflow_idx = prev_sdb_entry.misc.bc_flowidx; prev_table->uuflow_idx = table->uuflow_idx; prev_table->umflow_idx = table->umflow_idx; prev_table->bcflow_idx = table->bcflow_idx; prev_sdb_entry.misc.uu_flowidx = curr_sdb_entry.misc.uu_flowidx; prev_sdb_entry.misc.um_flowidx = curr_sdb_entry.misc.um_flowidx; prev_sdb_entry.misc.bc_flowidx = curr_sdb_entry.misc.bc_flowidx; table->uuflow_idx = uuflow_idx; table->umflow_idx = umflow_idx; table->bcflow_idx = bcflow_idx; curr_sdb_entry.misc.uu_flowidx = uuflow_idx; curr_sdb_entry.misc.um_flowidx = umflow_idx; curr_sdb_entry.misc.bc_flowidx = bcflow_idx; /* fix the link */ prev_table = table->next; if (table->next != NULL) table->next->prev = prev_table; table->next = table->prev = NULL; /* done swapping, now write it to FE table */ ret = cs_fe_table_set_entry(FE_TABLE_SDB, table->sdb_index, &curr_sdb_entry); ret |= cs_fe_table_set_entry(FE_TABLE_SDB, prev_table->sdb_index, &prev_sdb_entry); spin_unlock(&prev_table->lock); spin_unlock(&table->lock); return ret; } /* cs_vtable_remove_from_chain */ /* combine hash mask from src_table to dst_table. * Note: this API does not take care of duplicate hash mask indices * when merging. */ int cs_vtable_combine_vtable_hashmask(cs_vtable_t *dst_table, cs_vtable_t *src_table) { fe_sdb_entry_t dst_sdb_entry, src_sdb_entry; unsigned int dst_fwd_cnt = 0, src_fwd_cnt = 0; unsigned int dst_qos_cnt = 0, src_qos_cnt = 0; unsigned int iii, jjj, last_jjj; int ret; if ((dst_table == NULL) || (src_table == NULL)) return -1; spin_lock(&dst_table->lock); spin_lock(&src_table->lock); ret = cs_fe_table_get_entry(FE_TABLE_SDB, dst_table->sdb_index, &dst_sdb_entry); ret |= cs_fe_table_get_entry(FE_TABLE_SDB, src_table->sdb_index, &src_sdb_entry); if (ret != 0) { spin_unlock(&dst_table->lock); spin_unlock(&src_table->lock); return ret; } /* first count numbers of used hash mask tuple in both dst_table * and src_table for both fwd and qos type. */ for (iii = 0; iii <= 5; iii++) { if (dst_sdb_entry.sdb_tuple[iii].enable == 1) dst_fwd_cnt++; if (src_sdb_entry.sdb_tuple[iii].enable == 1) src_fwd_cnt++; } for (iii = 6; iii <= 7; iii++) { if (dst_sdb_entry.sdb_tuple[iii].enable == 1) dst_qos_cnt++; if (src_sdb_entry.sdb_tuple[iii].enable == 1) src_qos_cnt++; } if ((src_fwd_cnt > (6 - dst_fwd_cnt)) || (src_qos_cnt > (6 - dst_qos_cnt))) { /* there isn't enough space */ spin_unlock(&dst_table->lock); spin_unlock(&src_table->lock); return -1; } /* merge fwd hash mask tuple */ last_jjj = 0; for (iii = 0; iii <= 5; iii++) { if (src_sdb_entry.sdb_tuple[iii].enable == 1) { for (jjj = last_jjj; jjj <= 5; jjj++) { if (dst_sdb_entry.sdb_tuple[jjj].enable == 0) { dst_sdb_entry.sdb_tuple[jjj].enable = 1; dst_sdb_entry.sdb_tuple[jjj].mask_ptr = src_sdb_entry.sdb_tuple[iii]. mask_ptr; dst_sdb_entry.sdb_tuple[jjj].priority = src_sdb_entry.sdb_tuple[iii]. priority; last_jjj = jjj + 1; } } } } /* merge qos hash mask tuple */ last_jjj = 6; for (iii = 6; iii <= 7; iii++) { if (src_sdb_entry.sdb_tuple[iii].enable == 1) { for (jjj = last_jjj; jjj <= 7; jjj++) { if (dst_sdb_entry.sdb_tuple[jjj].enable == 0) { dst_sdb_entry.sdb_tuple[jjj].enable = 1; dst_sdb_entry.sdb_tuple[jjj].mask_ptr = src_sdb_entry.sdb_tuple[iii]. mask_ptr; dst_sdb_entry.sdb_tuple[jjj].priority = src_sdb_entry.sdb_tuple[iii]. priority; last_jjj = jjj + 1; } } } } spin_unlock(&dst_table->lock); spin_unlock(&src_table->lock); return 0; } /* cs_vtable_combine_vtable_hashmask */ /* return true, if there is still available space for inserting hashmask */ bool cs_vtable_has_avail_hashmask_space(cs_vtable_t *table, bool is_qos) { unsigned int start_idx, end_idx, iii; fe_sdb_entry_t sdb_entry; int ret; if (table == NULL) return -1; if (is_qos == true) { start_idx = 6; end_idx = 7; } else { start_idx = 0; end_idx = 5; } spin_lock(&table->lock); ret = cs_fe_table_get_entry(FE_TABLE_SDB, table->sdb_index, &sdb_entry); if (ret != 0) { spin_unlock(&table->lock); return ret; } for (iii = start_idx; iii <= end_idx; iii++) { if (sdb_entry.sdb_tuple[iii].enable == 0) { spin_unlock(&table->lock); return true; } } spin_unlock(&table->lock); return false; } /* cs_vtable_has_avail_hashmask_space */
futuretekinc/cortina-kernel-2.6.36
drivers/net/cs752x/src/core/cs_vtable.c
C
gpl-2.0
27,748
/** */ angular.module('service.balanceSheet', ['service.databaseInterface','service.Config','service.categoryInterface']).service('balanceSheet', ['dBInt','config','catInt',function(dBInt,config,catInt){ var balS = {}; balS.updateTable = {value:false}; balS.data = {data:[],dates:[]}; /** * This function updates the service variables bals.updateTable and bals.data * bals.data looks like {data:[Object,Object,..],dates[Date Object, Date Object,...]} * * The date objects in bals.data.dates are the months in the column, that is they are the * last 4 months in which data is available. * * The Objects in bals.data.data look like : * { tag:[{category1:[v11,..v1f]},...{category2:[v21,..v2f]}] * Here tag is one of the categorty tags. Each tag contains an array of objects which look like * {category1:[v11,..v1f]}. Here category belongs to tag. v is a float value. The ordering of * v corresponds in order extactly to the dates in bals.dates. That is v11 here is the sum of all * transactions of bals.data.dates[0] under category1 which belongs to the tag key. * */ balS.updateData = function(){ // workout the dates // Get the last 5 months var dates = dBInt.getLastNYearMonthsDates(4,['SAVER','NETBANK']); var accounts = config.returnAccountNames(); var tempData = []; var tempObject = {}; var currentRef = {}; var currentCatRef = {}; var tempValue = {}; // An array of database Elements var tempElArray = []; var sign = null; // An array of strings which are category names belonging to a specific tag. var categoryArrays = []; for( var tagName of config.returnTags().filter(function(x){return x !='Internal';}) ){ tempObject = {}; tempObject[tagName] = []; tempData.push(tempObject); // Get a reference to the data for this tag. Just for clode clarity currentRef = tempData[tempData.length -1][tagName]; // We will look at all categories. Later on modify for specific selections. categoryArrays = catInt.getCategoryNameByTag(tagName); categoryArrays.push("No Category"); for(var catName of categoryArrays ){ tempObject = {}; tempObject[catName] = []; currentRef.push(tempObject); currentCatRef = currentRef[currentRef.length -1][catName]; for(var date of dates){ tempValue = new BigDecimal("0.0"); for(var acc of accounts){ if( catName == "No Category" ){ // Handle the case where transactions have no categories if(tagName == 'Expenditure'){ sign = 'negative'; }else if (tagName == "Income"){ sign = 'positive'; } tempElArray = dBInt.filterData([date.getFullYear()],[date.getMonth()],acc,true,{sign:sign,incCat:[catName]}); }else{ tempElArray = dBInt.filterData([date.getFullYear()],[date.getMonth()],acc,false,{incCat:[catName]}); } // Consider adding in check code to ensure transactions are of the same sign. for(var el of tempElArray){ // Sum up the transactions for each month. tempValue = tempValue.add(el.value); } } currentCatRef.push(Math.abs(tempValue.floatValue().toFixed(0))); } } } balS.data.data = tempData; balS.data.dates = dates; }; return balS; }]);
mmihira/9mng
js/services/serviceBalanceSheet.js
JavaScript
gpl-2.0
3,996
#include "nxcCRC32.h" static const UInt32 crc32table[256] = { /* CRC polynomial 0xedb88320 */ 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d }; //////////////////////mls CRC //////////////////// /*! * nxcCRC32Initialize:Initialize CRC * \param *crc is the pointer to CRC32 value */ void nxcCRC32Initialize(UInt32 *crc) { *crc = 0xFFFFFFFF; } /*! * nxcCRC32Complete: last compute CRC * \param *crc is the pointer to CRC32 value */ void nxcCRC32Complete(UInt32 *crc) { *crc ^= 0xFFFFFFFF; } /* * nxcCRC32Generate: generate CRC table * \param *CRC is the pointer to CRC32 value * \param *buffer is the pointer to buffer needing to compute CRC32 * \param bufferLenght is the length of input buffer */ void nxcCRC32Generate(UInt32* CRC, void *buffer, UInt32 bufferLength) { UInt8 *buff = (UInt8*)buffer; UInt32 crc = *CRC; while (bufferLength--) { crc = crc32table[(crc ^ *buff++) & 0xFF] ^ (crc >> 8); } *CRC = crc; } /* * nxcCRC32Compute: compute CRC for input buffer * \param *buffer is the pointer to buffer needing to compute CRC32 * \param bufferLenght is the length of input buffer */ UInt32 nxcCRC32Compute(void *buffer, UInt32 bufferLength) { UInt32 result; nxcCRC32Initialize(&result); nxcCRC32Generate(&result, buffer, bufferLength); nxcCRC32Complete(&result); return(result); }
me-oss/me-mjpg_streamer_oss
plugins/input_mlsicam/nxcCRC32.c
C
gpl-2.0
4,492
/* This file is part of "xtrace" * Copyright (C) 2009,2010,2011 Bernhard R. Link * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <config.h> #include <assert.h> #include <errno.h> #include <stdint.h> #include <sys/types.h> #include <sys/time.h> #include <limits.h> #include <stdbool.h> #include <stdint.h> #include <stdarg.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/select.h> #include <unistd.h> #include <search.h> #include "xtrace.h" #include "parse.h" #include "stringlist.h" #include "translate.h" /* This parses an file to generate the description how packets look like. */ enum variable_type { vt_namespace = 0, vt_request, vt_response, vt_event, vt_setup, vt_type, vt_constants, vt_values, vt_struct, vt_COUNT }; static const char * const typename[vt_COUNT] = { "namespace", "request", "response", "event", "type", "constants", "values", "struct"}; static const struct base_type { const char *name; enum fieldtype type; unsigned int flags; int size; #define NEEDS_CONSTANTS 1 #define NEEDS_BITMASK 3 #define ALLOWS_CONSTANTS 4 #define USES_STORE 8 #define SETS_STORE 0x10 #define USES_FORMAT 0x20 #define SETS_FORMAT 0x40 #define ELEMENTARY 0x80 #define PUSHES 0x100 #define SETS_NEXT 0x200 #define NEEDS_STORE 0x400 } base_types [] = { { "BITMASK8", ft_BITMASK8, NEEDS_BITMASK|ELEMENTARY, 1}, { "BITMASK16", ft_BITMASK16, NEEDS_BITMASK|ELEMENTARY, 2}, { "BITMASK32", ft_BITMASK32, NEEDS_BITMASK|ELEMENTARY, 4}, { "ENUM8", ft_ENUM8, NEEDS_CONSTANTS|ELEMENTARY, 1}, { "ENUM16", ft_ENUM16, NEEDS_CONSTANTS|ELEMENTARY, 2}, { "ENUM32", ft_ENUM32, NEEDS_CONSTANTS|ELEMENTARY, 4}, { "CARD8", ft_CARD8, ALLOWS_CONSTANTS|ELEMENTARY, 1}, { "CARD16", ft_CARD16, ALLOWS_CONSTANTS|ELEMENTARY, 2}, { "CARD32", ft_CARD32, ALLOWS_CONSTANTS|ELEMENTARY, 4}, { "INT8", ft_INT8, ALLOWS_CONSTANTS|ELEMENTARY, 1}, { "INT16", ft_INT16, ALLOWS_CONSTANTS|ELEMENTARY, 2}, { "INT32", ft_INT32, ALLOWS_CONSTANTS|ELEMENTARY, 4}, { "UINT8", ft_UINT8, ALLOWS_CONSTANTS|ELEMENTARY, 1}, { "UINT16", ft_UINT16, ALLOWS_CONSTANTS|ELEMENTARY, 2}, { "UINT32", ft_UINT32, ALLOWS_CONSTANTS|ELEMENTARY, 4}, { "STRING8", ft_STRING8, USES_STORE|SETS_NEXT, 0}, { "LISTofCARD8", ft_LISTofCARD8, ALLOWS_CONSTANTS|USES_STORE|SETS_NEXT, 0}, { "LISTofCARD16", ft_LISTofCARD16, ALLOWS_CONSTANTS|USES_STORE|SETS_NEXT, 0}, { "LISTofCARD32", ft_LISTofCARD32, ALLOWS_CONSTANTS|USES_STORE|SETS_NEXT, 0}, { "LISTofUINT8", ft_LISTofUINT8, ALLOWS_CONSTANTS|USES_STORE|SETS_NEXT, 0}, { "LISTofUINT16", ft_LISTofUINT16, ALLOWS_CONSTANTS|USES_STORE|SETS_NEXT, 0}, { "LISTofUINT32", ft_LISTofUINT32, ALLOWS_CONSTANTS|USES_STORE|SETS_NEXT, 0}, { "LISTofINT8", ft_LISTofINT8, ALLOWS_CONSTANTS|USES_STORE|SETS_NEXT, 0}, { "LISTofINT16", ft_LISTofINT16, ALLOWS_CONSTANTS|USES_STORE|SETS_NEXT, 0}, { "LISTofINT32", ft_LISTofINT32, ALLOWS_CONSTANTS|USES_STORE|SETS_NEXT, 0}, { "EVENT", ft_EVENT, 0, 0}, { "ATOM", ft_ATOM, ALLOWS_CONSTANTS|ELEMENTARY, 4}, { "LISTofFormat", ft_LISTofFormat, USES_FORMAT|USES_STORE|SETS_NEXT, 0}, { "LISTofATOM", ft_LISTofATOM, ALLOWS_CONSTANTS|USES_STORE|SETS_NEXT, 0}, { "FORMAT8", ft_FORMAT8, SETS_FORMAT, 1}, { "BE32", ft_BE32, ALLOWS_CONSTANTS, 4}, { "FRACTION16_16", ft_FRACTION16_16, 0, 4}, { "FRACTION32_32", ft_FRACTION32_32, 0, 8}, { "UFRACTION32_32", ft_UFRACTION32_32, 0, 8}, { "INT32_32", ft_INT32_32, ELEMENTARY, 8}, { "FIXED", ft_FIXED, 0, 4}, { "FIXED1616", ft_FIXED, 0, 4}, { "FIXED3232", ft_FIXED3232, 0, 8}, { "LISTofFIXED", ft_LISTofFIXED, USES_STORE|SETS_NEXT, 0}, { "LISTofFIXED1616", ft_LISTofFIXED, USES_STORE|SETS_NEXT, 0}, { "LISTofFIXED3232", ft_LISTofFIXED3232, USES_STORE|SETS_NEXT, 0}, { "FLOAT32", ft_FLOAT32, 0, 4}, { "LISTofFLOAT32", ft_LISTofFLOAT32, USES_STORE|SETS_NEXT, 0}, { "PUSH8", ft_PUSH8, PUSHES, 1}, { "PUSH16", ft_PUSH16, PUSHES, 2}, { "PUSH32", ft_PUSH32, PUSHES, 4}, { "STORE8", ft_STORE8, SETS_STORE, 1}, { "STORE16", ft_STORE16, SETS_STORE, 2}, { "STORE32", ft_STORE32, SETS_STORE, 4}, { NULL, 0, 0, 0} }; /* some types are only implicitable buildable: */ static const struct base_type base_type_list_of_value = { "LISTofVALUE", ft_LISTofVALUE, NEEDS_STORE, 0}; static const struct base_type base_type_list_of_struct = { "LISTofStruct", ft_LISTofStruct, USES_STORE|SETS_NEXT, 0}; static const struct base_type base_type_list_of_varstruct = { "LISTofVarStruct", ft_LISTofVarStruct, USES_STORE|SETS_NEXT, 0}; static const struct base_type base_type_struct = { "Struct", ft_Struct, 0, -1}; //static const struct base_type base_type_varstruct = // { "VarStruct", ft_VarStruct, SETS_NEXT, 0}; #define C(td, f) ((td->flags & f) == f) struct typespec { const struct base_type *base_type; /* constants for most, unless values for LISTofVALUE, or struct for Struct and List */ struct variable *data; }; struct variable { enum variable_type type; int refcount; union { struct unfinished_parameter { struct unfinished_parameter *next; bool isspecial; union { struct { size_t offse; const char *name; struct typespec type; } regular; struct { enum fieldtype type; size_t offse; const char *condition; bool isjunction; struct unfinished_parameter *iftrue; const struct parameter *finalized; } special; }; } *parameter; struct { struct constant *constants; size_t size; bool bitmask; } c; struct unfinished_value { struct unfinished_value *next; unsigned long flag; const char *name; struct typespec type; } *values; struct typespec t; }; union parameter_option finalized; }; struct namespace { struct namespace *next; char *name; int refcount; char *extension; int num_requests; struct request_data { const char *name; int number; bool has_response; bool unsupported; bool special; int record_variables; struct variable *request, *response; } *requests; int num_events[event_COUNT]; struct event_data { const char *name; int number; bool unsupported; bool special; struct variable *event; } *events[event_COUNT]; int num_errors; const char **errors; struct variable *setup; void *variables[vt_COUNT]; /* namespaces that can be used without prefix: */ int used_count; struct namespace **used; }; struct varname { struct variable *variable; char name[]; }; static int compare_variables(const void *a, const void *b) { const char *v1 = a, *v2 = b; return strcmp(v1 + sizeof(struct varname), v2 + sizeof(struct varname)); } static void variable_unref(struct variable *v); static inline void typespec_done(struct typespec *t) { variable_unref(t->data); } static void typespec_copy(struct typespec *dst, const struct typespec *src) { *dst = *src; if( dst->data != NULL ) dst->data->refcount++; } static void parameter_free(struct unfinished_parameter *parameter) { while( parameter != NULL ) { struct unfinished_parameter *p = parameter; parameter = p->next; if( p->isspecial ) { parameter_free(p->special.iftrue); } else { typespec_done(&p->regular.type); } free(p); } } static void variable_unref(struct variable *v) { if( v == NULL ) return; assert( v->refcount > 0 ); if( -- (v->refcount) > 0 ) return; if( v->type == vt_values ) { while( v->values != NULL ) { struct unfinished_value *n = v->values->next; typespec_done(&v->values->type); free(v->values); v->values = n; } } else if( v->type == vt_constants ) { free(v->c.constants); } else if( v->type == vt_type ) { typespec_done(&v->t); } else if( v->type == vt_struct || v->type == vt_request || v->type == vt_setup || v->type == vt_response || v->type == vt_event ) { parameter_free(v->parameter); } else assert( v->type != v->type ); free(v); } #define namespace_unlock(n) do {if(n != NULL ){(n)->refcount--;}} while(0) struct parser { char buffer[300], *position, *last; struct namespace *namespaces; struct source_file { struct source_file *next; char *name; char *filename; FILE *file; long lineno; struct namespace *namespace; } *current; struct searchpath_entry { struct searchpath_entry *next; const char *dir; size_t len; } *searchpath; bool error; }; static void file_free(struct source_file *current) { while( current != NULL ) { struct source_file *n = current->next; free(current->name); free(current->filename); if( current->file != NULL ) (void)fclose(current->file); namespace_unlock(current->namespace); free(current); current = n; } } static void error(struct parser *parser, const char *fmt, ...) FORMAT(printf,2,3); static bool get_next_line(struct parser *parser, long firstline) { char *p; do { if( parser->error ) return false; parser->position = parser->buffer; parser->last = parser->buffer; if( fgets(parser->buffer, sizeof(parser->buffer), parser->current->file) == NULL ) { int e = ferror(parser->current->file); if( e != 0 ) { fprintf(stderr, "Error %d reading from file '%s': %s\n", e, parser->current->filename, strerror(e)); } else { if( firstline > 0 ) { error(parser, "Unexpected end of file (forgot END (awaited since %ld) and EOF?)", firstline+1); } error(parser, "Unexpected end of file (forgot EOF?)"); } parser->error = true; return false; } parser->current->lineno++; p = strchr(parser->buffer, '\0'); while( p-- > parser->buffer && ( *p == '\n' || *p == '\r' || *p == '\t' || *p == ' ' ) ) *p = '\0'; } while ( parser->buffer[0] == '#' || parser->buffer[0] == '\0' ); return true; } static bool file_done(struct parser *parser) { struct source_file *last_done, *first_unfinished; int i, e; if( parser->error ) return false; e = ferror(parser->current->file); if( e != 0 ) { fprintf(stderr, "Error %d reading from file '%s': %s\n", e, parser->current->filename, strerror(e)); parser->error = true; return false; } i = fclose(parser->current->file); parser->current->file = NULL; if( i != 0 ) { e = errno; fprintf(stderr, "Error %d reading from file '%s': %s\n", e, parser->current->filename, strerror(e)); parser->error = true; return false; } /* check if there is more to do: */ last_done = parser->current; while( last_done->next != NULL && last_done->next->file == NULL ) last_done = last_done->next; first_unfinished = last_done->next; if( first_unfinished == NULL ) return true; /* move the first not yet processed file to here: */ last_done->next = first_unfinished->next; first_unfinished->next = parser->current; parser->current = first_unfinished; return false; } static const char *get_const_token(struct parser *parser, bool optional) { char *p, *q; if( parser->error ) return NULL; p = parser->position; while( *p != '\0' && (*p == ' ' || *p == '\t') ) p++; parser->last = p; if( *p == '\0' ) { if( !optional ) error(parser, "unexpected end of line"); return NULL; } if( *p == '"' ) { q = p; p++; while( *p != '\0' && *p != '"' ) { if( *p == '\\' && p[1] != '\0' ) { p++; if( *p < '0' || *p > '7' ) *q++ = *p++; else { *q = *(p++) - '0'; if( *p >= '0' || *p <= '7' ) *q = *q * 8 + *(p++) - '0'; if( *p >= '0' || *p <= '7' ) *q = *q * 8 + *(p++) - '0'; q++; } } else { *q++ = *p++; } } if( *p != '"' ) { error(parser, "Unterminated string!"); return NULL; } *q = '\0'; p++; } else { while( *p != '\0' && *p != ' ' && *p != '\t' ) { if( *p == '#' ) { error(parser, "Unescaped '#'"); return NULL; } p++; } } while( *p != '\0' && (*p == ' ' || *p == '\t') ) *(p++) = '\0'; parser->position = p; return parser->last; } static void oom(struct parser *parser) { if( parser->error ) return; fputs("Out of memory!", stderr); parser->error = true; } static char *get_token(struct parser *parser, bool optional) { const char *v; char *p; v = get_const_token(parser, optional); if( v == NULL ) return NULL; p = strdup(v); if( p == NULL ) { oom(parser); } return p; } static char *get_token_with_len(struct parser *parser, size_t *l) { char *p; if( parser->error ) return NULL; p = parser->position; parser->last = p; if( *p == '\0' ) { error(parser, "unespected end of line"); return NULL; } while( *p != '\0' && *p != ' ' && *p != '\t' ) p++; *l = p - parser->last; while( *p != '\0' && (*p == ' ' || *p == '\t') ) *(p++) = '\0'; parser->position = p; return parser->last; } static void error(struct parser *parser, const char *fmt, ...) { va_list ap; if( parser->error ) return; parser->error = true; if( parser->last != NULL ) fprintf(stderr, "%s:%ld:%d: ", parser->current->filename, parser->current->lineno, (int)(1 + (parser->last - parser->buffer))); else fprintf(stderr, "%s:%ld: ", parser->current->filename, parser->current->lineno); va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fputc('\n', stderr); } static void no_more_arguments(struct parser *parser) { if( parser->position[0] != '\0' ) { parser->last = parser->position; error(parser, "End of line expected!"); } } void add_searchpath(struct parser *parser, const char *dir) { struct searchpath_entry **last; last = &parser->searchpath; while( *last != NULL ) last = &(*last)->next; *last = malloc(sizeof(struct searchpath_entry)); if( *last == NULL ) { oom(parser); return; } (*last)->next = NULL; (*last)->dir = dir; (*last)->len = strlen(dir); } static FILE *find_file(struct parser *parser, const char *name, char **filename_p) { size_t l = strlen(name); struct searchpath_entry *r; assert( parser->searchpath != NULL ); for( r = parser->searchpath ; r != NULL ; r = r->next ) { char *filename = NULL; FILE *f; filename = malloc(l + r->len + 2); if( filename == NULL ) { oom(parser); return NULL; } memcpy(filename, r->dir, r->len); filename[r->len] = '/'; memcpy(filename + r->len + 1, name, l + 1); f = fopen(filename, "r"); if( f != NULL ) { *filename_p = filename; return f; } free(filename); } fprintf(stderr, "Unable to find '%s' in search path!\n", name); parser->error = true; *filename_p = NULL; return NULL; } static void open_next_file(struct parser *parser, char *name) { struct source_file *current; if( name == NULL ) oom(parser); if( parser->error ) { free(name); return; } current = parser->current; while( current != NULL && strcmp(current->name, name) != 0 ) current = current->next; if( current != NULL ) { if( current->file != NULL ) error(parser, "Circular dependency! '%s' requested while parsing it!", name); free(name); return; } current = calloc(1, sizeof(*current)); if( current == NULL ) { oom(parser); free(name); return; } current->name = name; current->file = find_file(parser, name, &current->filename); if( current->file == NULL ) { int e = errno; error(parser, "Error %d opening '%s': %s", e, current->filename, strerror(e)); file_free(current); return; } current->lineno = 0; current->namespace = NULL; parser->position = NULL; parser->last = NULL; current->next = parser->current; parser->current = current; } static bool add_variable(struct parser *parser, const char *prefix, const char *name, const char **varname, struct variable *variable) { struct varname *v, **vv; size_t pl = strlen(prefix), l = strlen(name); struct namespace *namespace = parser->current->namespace; v = malloc(sizeof(struct varname) + l + pl + 1); if( v == NULL ) { oom(parser); return false; } memcpy(v->name, prefix, pl); memcpy(v->name + pl, name, l + 1); v->variable = NULL; vv = tsearch(v, &namespace->variables[variable->type], compare_variables); if( vv == NULL ) { free(v); oom(parser); return false; } if( *vv != v ) { // free(v); /* already defined */ return false; } if( varname != NULL ) *varname = v->name; v->variable = variable; variable->refcount ++; return true; } static struct variable *add_var(struct parser *parser, const char *prefix, const char *name, const char **varname, enum variable_type vt) { struct variable *variable; if( name == NULL ) return NULL; variable = calloc(1, sizeof(struct variable)); if( variable == NULL ) { oom(parser); return NULL; } variable->type = vt; if( add_variable(parser, prefix, name, varname, variable) ) return variable; error(parser, "%s '%s%s' already defined!", typename[vt], prefix, name); free(variable); return NULL; } static struct variable *find_variable(struct parser *parser, enum variable_type vt, const char *name) { struct varname **v; const char *e; int i; if( name == NULL ) return NULL; e = strchr(name, ':'); if( e != NULL ) { struct namespace *n; if( e[1] != ':' ) { error(parser, "Unexpected colon (':') in '%s'!", name); return NULL; } for( n = parser->namespaces ; n != NULL ; n = n->next ) { if( strncmp(n->name, name, e - name) != 0 ) continue; if( n->name[e-name] != '\0' ) continue; v = tfind(e + 2 - sizeof(struct varname), &n->variables[vt], compare_variables); if( v == NULL || *v == NULL ) { error(parser, "Unknown %s '%s' ('%s')!", typename[vt], name, e+2); return NULL; } else return (*v)->variable; } error(parser, "Unknown namespace '%.*s'", (int)(e-name), name); return NULL; } v = tfind(name - sizeof(struct varname), &parser->current->namespace->variables[vt], compare_variables); if( v != NULL && *v != NULL ) return (*v)->variable; // check imported namespaces for( i = 0 ; i < parser->current->namespace->used_count ; i++ ) { struct namespace *n = parser->current->namespace->used[i]; v = tfind(name - sizeof(struct varname), &n->variables[vt], compare_variables); if( v != NULL && *v != NULL ) return (*v)->variable; } error(parser, "Unknown %s %s!", typename[vt], name); return NULL; } #define command_is(name) l == sizeof(name)-1 && memcmp(command, name, sizeof(name)-1) == 0 static void parse_errors(struct parser *parser) { long first_line = parser->current->lineno; struct namespace *ns = parser->current->namespace; if( ns->num_errors != 0 || ns->errors != NULL ) { error(parser, "second ERRORS for namespace '%s'!", ns->name); return; } while( get_next_line(parser, first_line) ) { const char *name = get_const_token(parser, false); const char **n; if( strcmp(name, "END") == 0 ) { no_more_arguments(parser); return; } else if( strcmp(name, "EOF") == 0 ) { no_more_arguments(parser); error(parser, "Missing END (beginning at line %ld)", first_line); } no_more_arguments(parser); name = string_add(name); if( name == NULL ) { parser->error = true; return; } ns->num_errors++; n = realloc(ns->errors, ns->num_errors * sizeof(const char*)); if( n == NULL ) { oom(parser); return; } ns->errors = n; ns->errors[ns->num_errors - 1] = name; } error(parser, "missing END!"); } static unsigned long parse_number(struct parser *parser, const char *value) { char *e; unsigned long number = 0; if( parser->error ) return 0; assert( value != NULL ); if( value[0] == '$' ) { char *v; struct variable *var; const struct constant *c; e = strrchr(value, ':'); if( e == NULL || ( e > value && *(e-1) == ':' ) ) { error(parser, "Constants name and member must be separated with a single colon!"); return 0; } v = strndup(value + 1, e - (value+1)); if( v == NULL ) { oom(parser); return 0; } var = find_variable(parser, vt_constants, v); if( var == NULL ) { free(v); return 0; } for( c = var->c.constants ; c->name != NULL ; c++ ) { if( strcmp(c->name, e+1) == 0 ) { free(v); return c->value; } } error(parser, "Unable to find '%s' in constants %s!", e+1, v); free(v); return 0; } if( value[0] == '0' && value[1] == '\0' ) { e = (char*)value + 1; } else if( value[0] == '0' && value[1] == 'x' ) number = strtoll(value+2, &e, 16); else if( value[0] == '0' && value[1] == 'o' ) number = strtoll(value+2, &e, 8); else if( value[0] == '0' && value[1] == 'b' ) number = strtoll(value+2, &e, 2); else if( value[0] != '0' ) number = strtoll(value, &e, 10); else { error(parser, "Leading zeros in numbers are forbidden to avoid confusion!"); e = (char*)value; } if( e[0] == '<' && e[1] == '<' ) { char *ee; long long shift = strtoll(e + 2, &ee, 10); if( ee > e + 2 && shift >= 0 && shift < 32 ) { number = number << (unsigned long)shift; e = ee; } } if( *e != '\0' ) { error(parser, "Error parsing number!"); return 0; } return number; } static bool parse_typespec(struct parser *parser, struct typespec *t) { const char *type, *attribute; struct variable *tv; const struct base_type *td; memset(t, 0, sizeof(*t)); type = get_const_token(parser, false); if( parser->error ) { return false; } td = base_types; while( td->name != NULL && strcmp(td->name, type) != 0 ) td++; if( td->name != NULL ) { t->base_type = td; if( C(td, NEEDS_CONSTANTS) ) { struct variable *cv; attribute = get_const_token(parser, false); cv = find_variable(parser, vt_constants, attribute); if( cv == NULL ) return false; if( C(td, NEEDS_BITMASK) && ! cv->c.bitmask ) { error(parser, "Not-BITMASK constants %s used for bitmask!", attribute); } t->data = cv; cv->refcount++; } } else { tv = find_variable(parser, vt_type, type); if( tv == NULL ) return false; assert( tv->type == vt_type ); typespec_copy(t, &tv->t); } attribute = get_const_token(parser, true); if( attribute != NULL ) { if( strcmp(attribute, "constants") == 0 ) { if( !C(t->base_type, ALLOWS_CONSTANTS) ) { error(parser, "constants not allowed here!"); } else if( t->data != NULL ) { error(parser, "multiple constants not allowed!"); } else { struct variable *cv; attribute = get_const_token(parser, false); cv = find_variable(parser, vt_constants, attribute); if( cv == NULL ) return false; t->data = cv; cv->refcount++; } } else error(parser, "unknown type attribute!"); } no_more_arguments(parser); return !parser->error; } static struct unfinished_parameter *new_parameter_special(struct parser *parser, struct unfinished_parameter ***last_pp, enum fieldtype ft, size_t offse, const char *condition) { struct unfinished_parameter *n; if( parser->error ) return NULL; n = calloc(1, sizeof(struct unfinished_parameter)); if( n == NULL ) { oom(parser); return NULL; } n->isspecial = true; n->special.offse = offse; n->special.type = ft; /* NULL is termination condition */ if( condition == NULL ) n->special.condition = ""; else n->special.condition = condition; **last_pp = n; *last_pp = &n->next; return n; } /* here many things can still be checked: if nothing is accessed past the length in a struct, if things overlap, ... */ struct parameter_state { struct parameter_state *parent; struct unfinished_parameter *junction; size_t maxsize, minsize; bool store_set, store_used, format_set, sizemarker_set, nextmarker_set, nextmarker_at_end_of_packet; }; static void field_accessed(struct parser *parser, struct parameter_state *state, size_t ofs, size_t fieldlen) { if( ofs == (size_t)-1 ) return; if( ofs + fieldlen > state->minsize ) { if( ofs + fieldlen > state->maxsize ) { error(parser, "Accessing field past specified SIZE of %lu!", (unsigned long)state->maxsize); } state->minsize = ofs + fieldlen; } /* TODO: record here what areas are used to avoid overlaps and * gaps? */ } static bool parse_parameters(struct parser *parser, struct variable *variable, bool needsnextmarker) { long first_line = parser->current->lineno; struct parameter_state *state; struct unfinished_parameter *parameters = NULL, **last = &parameters; assert( variable->parameter == NULL ); state = calloc(1, sizeof(struct parameter_state)); if( state == NULL ) { oom(parser); return false; } state->maxsize = SIZE_MAX; while( get_next_line(parser, first_line) ) { const char *position, *name; unsigned long number; struct typespec type; position = get_const_token(parser, false); if( strcmp(position, "EOF") == 0 ) { error(parser, "Missing 'END' (closing block opened at line %ld)!", first_line + 1); break; } if( strcmp(position, "END") == 0 ) { no_more_arguments(parser); if( state->parent != NULL ) error(parser, "missing ELSE"); if( needsnextmarker && !state->nextmarker_set ) error(parser, "Missing NEXT (or LISTof...)!"); free(state); variable->parameter = parameters; return true; } if( strcmp(position, "ALIAS") == 0 ) { error(parser, "ALIAS is no longer a valid keyword!"); break; } if( strcmp(position, "ELSE") == 0 ) { struct parameter_state *s; if( state->parent == NULL ) error(parser, "ELSE without IF"); no_more_arguments(parser); if( needsnextmarker && !state->nextmarker_set ) error(parser, "Missing NEXT (or LISTof...)!"); last = &state->junction->next; s = state->parent; free(state); state = s; continue; } if( strcmp(position, "IF") == 0 || strcmp(position, "ELSEIF") == 0 ) { struct parameter_state *s; struct unfinished_parameter *i; const char *v, *condition; enum fieldtype ft; size_t fieldlen; bool inelseif = strcmp(position, "ELSEIF") == 0; if( inelseif ) { /* this is like an END here */ if( state->parent == NULL ) error(parser, "ELSEIF without IF"); if( needsnextmarker && !state->nextmarker_set ) error(parser, "Missing NEXT (or LISTof...)!"); } v = get_const_token(parser, false); if( strcmp(v, "STORED") == 0 ) number = (size_t)-1; // compare store value else number = parse_number(parser, v); v = get_const_token(parser, false); if( v == NULL ) break; if( strcmp(v, "ATOM") == 0 ) { ft = ft_IFATOM; v = get_const_token(parser, false); condition = string_add(v); fieldlen = 4; } else if( strcmp(v, "CARD8") == 0 ) { unsigned char c; ft = ft_IF8; v = get_const_token(parser, false); c = parse_number(parser, v); condition = string_add_l((const char*)&c, 1); fieldlen = 1; } else if( strcmp(v, "CARD16") == 0 ) { unsigned char c[2]; unsigned long l; ft = ft_IF16; v = get_const_token(parser, false); l = parse_number(parser, v); c[1] = l & 0xFF; c[0] = l >> 8; condition = string_add_l((const char*)c, 2); fieldlen = 2; } else if( strcmp(v, "CARD32") == 0 ) { unsigned char c[4]; unsigned long l; ft = ft_IF32; v = get_const_token(parser, false); l = parse_number(parser, v); c[3] = l & 0xFF; c[2] = (l >> 8) & 0xFF; c[1] = (l >> 16) & 0xFF; c[0] = l >> 24; condition = string_add_l((const char*)c, 4); fieldlen = 4; } else { error(parser, "unknown IF type '%s'!", v); break; } no_more_arguments(parser); field_accessed(parser, state, number, fieldlen); if( inelseif ) last = &state->junction->next; i = new_parameter_special(parser, &last, ft, number, condition); if( inelseif ) { s = state->parent; } else { s = state; state = malloc(sizeof(*state)); if( state == NULL ) { oom(parser); break; } } *state = *s; state->parent = s; state->junction = i; if( i != NULL ) { last = &i->special.iftrue; i->special.isjunction = true; } continue; } if( strcmp(position, "ROUND") == 0 ) { if( !state->nextmarker_set ) error(parser, "ROUND makes no sense if nextmarker not set!"); no_more_arguments(parser); new_parameter_special(parser, &last, ft_LASTMARKER, (size_t)-1 /* ROUND32 */, NULL ); continue; } if( strcmp(position, "GET") == 0 ) { const char *v; v = get_const_token(parser, false); number = parse_number(parser, v); no_more_arguments(parser); // TODO: remember what is needed for checking state->store_set = true; new_parameter_special(parser, &last, ft_GET, number, NULL); continue; } if( strcmp(position, "SET_COUNTER") == 0 ) { const char *v; v = get_const_token(parser, false); number = parse_number(parser, v); no_more_arguments(parser); state->store_set = true; new_parameter_special(parser, &last, ft_SET, number, NULL); continue; } if( strcmp(position, "DECREMENT_STORED") == 0 || strcmp(position, "DECREMENT_COUNT") == 0 ) { const char *v; if( !state->store_set ) { error(parser, "store variable must be set before it can be changed!"); } v = get_const_token(parser, false); number = parse_number(parser, v); no_more_arguments(parser); new_parameter_special(parser, &last, ft_DECREMENT_STORED, number, NULL); continue; } if( strcmp(position, "DIVIDE_COUNT") == 0) { const char *v; if( !state->store_set ) { error(parser, "store variable must be set before it can be changed!"); } v = get_const_token(parser, false); number = parse_number(parser, v); no_more_arguments(parser); new_parameter_special(parser, &last, ft_DIVIDE_STORED, number, NULL); continue; } if( strcmp(position, "RESET_COUNTER") == 0 ) { no_more_arguments(parser); state->store_set = false; state->store_used = false; new_parameter_special(parser, &last, ft_SET, INT_MAX, NULL); continue; } if( strcmp(position, "SIZE") == 0 ) { const char *v; //unsigned long t = 1; v = get_const_token(parser, false); if( v == NULL ) break; if( strcmp(v, "STORE") == 0 || strcmp(v, "COUNT") == 0 ) { if( !state->store_set ) error(parser, "store variable not yet set, so cannot be used!"); state->store_used = true; number = (size_t)-1; } else if( strcmp(v, "GET") == 0 ) { // TODO: check if stack can have something... number = parse_number(parser, v); if( number >= 30 ) { error(parser, "Absurd big stack index: %lu\n", number); continue; } number |= 0x80000000; } else { number = parse_number(parser, v); if( number > 65536 ) { error(parser, "Absurd big number for length of substructure: %lu\n", number); continue; } state->maxsize = number; if( state->minsize > state->maxsize ) { error(parser, "Setting size to %lu >= Data yet looked at up to %lu!", (unsigned long)state->maxsize, (unsigned long)state->minsize); continue; } } v = get_const_token(parser, true); if( v != NULL ) { if( strcmp(v, "TIMES") != 0 ) { error(parser, "Unexpected argument '%s'!", v); continue; } error(parser, "'TIMES' not yet supported!"); continue; //v = get_const_token(parser, false); //t = parse_number(parser, v); } no_more_arguments(parser); state->sizemarker_set = true; new_parameter_special(parser, &last, ft_SET_SIZE, number, NULL); continue; } if( strcmp(position, "NEXT") == 0 ) { const char *v; v = get_const_token(parser, false); number = parse_number(parser, v); no_more_arguments(parser); state->nextmarker_set = true; state->nextmarker_at_end_of_packet = false; new_parameter_special(parser, &last, ft_LASTMARKER, number, NULL); continue; } if( strcmp(position, "LATER") == 0 ) { if( state->nextmarker_at_end_of_packet ) error(parser, "LATER makes no sense after all-consuming LIST (i.e. list without limiting count)"); if( !state->nextmarker_set ) error(parser, "LATER needs a command setting nextmarker before!"); number = (size_t)-1; //OFS_LATER; } else number = parse_number(parser, position); name = get_const_token(parser, false); parse_typespec(parser, &type); if( parser->error ) { typespec_done(&type); break; } assert( type.base_type != NULL ); if( C(type.base_type, SETS_NEXT) ) state->nextmarker_set = true; if( C(type.base_type, NEEDS_STORE) && !state->store_set ) { error(parser, "This commands needs store variable set, but this does not seem to be the case!"); } if( C(type.base_type, USES_STORE) ) { if( !state->store_set ) { if( state->store_used ) error(parser, "store variable consumed and not ready here!"); state->nextmarker_at_end_of_packet = true; } state->store_set = false; state->store_used = true; } if( C(type.base_type, SETS_STORE) ) { state->store_set = true; state->store_used = false; } if( C(type.base_type, USES_FORMAT) && !state->format_set ) { error(parser, "Format variable not set!"); } if( C(type.base_type, SETS_FORMAT) ) { state->format_set = true; } if( C(type.base_type, PUSHES) ) { } name = string_add(name); if( name == NULL ) parser->error = true; *last = calloc(1, sizeof(struct unfinished_parameter)); if( *last == NULL ) oom(parser); if( parser->error ) { typespec_done(&type); break; } (*last)->isspecial = false; (*last)->regular.offse = number; (*last)->regular.name = string_add(name);; (*last)->regular.type = type; /* TODO: better size estimate for structs and for lists * where the counter was explicitly set */ field_accessed(parser, state, number, type.base_type->size); last = &(*last)->next; } error(parser, "missing END!"); parameter_free(parameters); while( state != NULL ) { struct parameter_state *s = state->parent; free(state); state = s; } return false; } static struct request_data *find_request(struct parser *parser, const char *name) { struct namespace *n = parser->current->namespace; int i; if( parser->error ) return NULL; if( n->requests == NULL || n->num_requests <= 0 ) return NULL; for( i = 0 ; i < n->num_requests ; i++ ) { struct request_data *r = &n->requests[i]; if( r->name == NULL ) continue; if( strcmp(name, r->name) == 0 ) return r; } return NULL; } static void parse_request(struct parser *parser, bool template) { const char *name, *attribute; struct variable *v = NULL; bool complete = false; struct request_data *request; long record = 0; name = get_const_token(parser, false); while( (attribute = get_const_token(parser, true)) != NULL ) { if( strcmp(attribute, "ALIASES") == 0 ) { const char *t = get_const_token(parser, false); v = find_variable(parser, vt_request, t); if( v == NULL ) return; } else if( strcmp(attribute, "TRANSFER") == 0 || strcmp(attribute, "transfer") == 0 ) { char *e; attribute = get_const_token(parser, false); if( attribute == NULL ) return; record = strtoll(attribute, &e, 10); if( *e != '\0' || record > 30 || record <= 0 ) error(parser, "Parse error: invalid number after 'transfer'!"); } else if( strncmp(attribute, "TRANSFER=", 9) == 0 || strncmp(attribute, "transfer=", 9) == 0 ) { char *e; record = strtoll(attribute + 9, &e, 10); if( *e != '\0' || record > 30 || record <= 0 ) error(parser, "Parse error: invalid number after 'transfer='!"); } else { error(parser, "Unknown REQUEST attribute '%s'!", attribute); return; } } if( v != NULL ) { complete = true; if( !add_variable(parser, "", name, &name, v) ) return; } else { v = add_var(parser, "", name, &name, vt_request); if( v == NULL ) return; } request = find_request(parser, name); if( template ) { if( request != NULL ) { error(parser, "'%s' is already listed in REQUESTS, thus cannot be a template!", name); return; } if( record > 0 ) { error(parser, "TRANSFER not possible for templated"); return; } } else { if( request == NULL ) { error(parser, "Unknow request '%s'! (Must be listed in REQUESTS or use templateREQUEST", name); return; } if( request->request != NULL ) { error(parser, "Multiple definition of request '%s::%s'!", parser->current->namespace->name, name); } if( request->unsupported ) { error(parser, "Unexpected definition of unsupported request '%s::%s'!", parser->current->namespace->name, name); } if( record > 0 ) { if( !request->has_response ) { error(parser, "TRANSFER only possible if it RESPONDS!"); return; } request->record_variables = record; } request->request = v; v->refcount ++; } if( !complete ) parse_parameters(parser, v, false); } static void parse_setup(struct parser *parser) { const char *attribute; struct variable *v = NULL; struct namespace *n = parser->current->namespace; assert( n != NULL ); if( n->extension != NULL || strcmp(n->name, "core") != 0 ) { error(parser, "'SETUP' only allowed in namespace 'core'!"); return; } if( n->setup != NULL ) { error(parser, "multiple 'SETUP' in the same namespace!"); return; } while( (attribute = get_const_token(parser, true)) != NULL ) { error(parser, "Unknown SETUP attribute '%s'!", attribute); return; } v = add_var(parser, "", "setup", NULL, vt_setup); if( v == NULL ) return; n->setup = v; v->refcount ++; parse_parameters(parser, v, false); } static void parse_response(struct parser *parser, bool template) { const char *name, *attribute; struct variable *v = NULL; bool complete = false; name = get_const_token(parser, false); while( (attribute = get_const_token(parser, true)) != NULL ) { if( strcmp(attribute, "ALIASES") == 0 ) { const char *t = get_const_token(parser, false); v = find_variable(parser, vt_response, t); if( v == NULL ) return; } else { error(parser, "Unknown RESPONSE attribute '%s'!", attribute); return; } } if( v != NULL ) { complete = true; if( !add_variable(parser, "", name, &name, v) ) return; } else { v = add_var(parser, "", name, &name, vt_response); if( v == NULL ) return; } if( ! template ) { struct request_data *request; request = find_request(parser, name); if( request == NULL ) return; if( !request->has_response ) { error(parser, "Unexpected response '%s' (must be listed in REQUESTS with RESPONDS!)", name); } if( request->response != NULL ) { error(parser, "Multiple definition of response '%s::%s'!", parser->current->namespace->name, name); } if( request->unsupported ) { error(parser, "Unexpected definition of unsupported response '%s::%s'!", parser->current->namespace->name, name); } request->response = v; v->refcount ++; } if( !complete ) parse_parameters(parser, v, false); } static struct event_data *find_event(struct parser *parser, enum event_type et, const char *name) { struct namespace *n = parser->current->namespace; struct event_data *e; int i, num = n->num_events[et]; if( parser->error ) return NULL; if( n->events[et] == NULL || num <= 0 ) { return NULL; } for( i = 0, e = n->events[et] ; i < num ; i++, e++ ) { if( e->name == NULL ) continue; if( strcmp(name, e->name) == 0 ) return e; } return NULL; } static void parse_events(struct parser *parser, enum event_type et) { struct namespace *n = parser->current->namespace; long firstline = parser->current->lineno; assert( n != NULL ); if( n->extension == NULL && strcmp(n->name, "core") != 0 ) { error(parser, "'%sEVENTS' only allowed in extension or namespace 'core'!", (et==event_xge)?"XG":""); return; } if( n->events[et] != NULL || n->num_events[et] != 0 ) { error(parser, "multiple '%sEVENTS' in the same namespace!", (et==event_xge)?"XG":""); return; } while( get_next_line(parser, firstline) ) { const char *name; const char *attribute; struct event_data event, *newevents; memset(&event, 0, sizeof(event)); /* TODO: allow excplicit setting */ event.number = n->num_events[et]; name = get_const_token(parser, false); if( name == NULL ) break; if( strcmp(name, "EOF") == 0 ) { error(parser, "Missing 'END' (expected since line %ld)!", firstline + 1); return; } if( strcmp(name, "END") == 0 ) { return; } if( strcmp(name, "UNKNOWN") == 0 ) { event.unsupported = true; event.name = NULL; } else { event.name = string_add(name); if( event.name == NULL ) { parser->error = true; return; } } while( (attribute = get_const_token(parser, true)) != NULL ) { if( strcmp(attribute, "SPECIAL") == 0 ) { if( event.name == NULL ) error(parser, "SPECIAL not possible with UNKNOWN!"); event.special = true; } else if( strcmp(attribute, "UNSUPPORTED") == 0 ) event.unsupported = true; else if( attribute[0] == '/' && attribute[1] == '*' ) { char *e; long l; if( attribute[2] == '\0' ) attribute = get_const_token(parser, false); else attribute += 2; if( attribute == NULL ) break; l = strtol(attribute, &e, 0); if( *e == '\0' ) attribute = get_const_token(parser, false); else attribute = e; if( attribute == NULL || attribute[0] != '*' || attribute[1] != '/' ) error(parser, "Parse error, '/*' only allowed as '/* number */'!"); else if( event.number != l ) error(parser, "Event '%s' is %d but asserted to be %ld", name, event.number, l); } else { error(parser, "Unexpected response attribute '%s'!", attribute); } } newevents = realloc(n->events[et], sizeof(struct event_data)*(n->num_events[et]+1)); if( newevents == NULL ) { oom(parser); break; } n->events[et] = newevents; newevents[n->num_events[et]] = event; n->num_events[et]++; } } static void parse_event(struct parser *parser, bool template, enum event_type et) { const char *name, *attribute; struct variable *v = NULL; bool complete = false; struct event_data *event; name = get_const_token(parser, false); while( (attribute = get_const_token(parser, true)) != NULL ) { if( strcmp(attribute, "ALIASES") == 0 ) { const char *t = get_const_token(parser, false); v = find_variable(parser, vt_event, t); if( v == NULL ) return; } else { error(parser, "Unknown EVENT attribute '%s'!", attribute); return; } } if( v != NULL ) { complete = true; if( !add_variable(parser, "", name, &name, v) ) return; } else { v = add_var(parser, "", name, &name, vt_event); if( v == NULL ) return; } event = find_event(parser, et, name); if( template ) { if( event != NULL ) { error(parser, "'%s' cannot be the name for a templateEvent as it is already the name for an event in EVENTS or XGEVENTS!\n", name); return; } } else { if( event == NULL ) { error(parser, "%sEVENT '%s' not listed in previous %sEVENTS!\n", (et == event_xge)?"XG":"", name, (et == event_xge)?"XG":""); return; } event->event = v; v->refcount ++; } if( !complete ) parse_parameters(parser, v, false); } static void add_namespace(struct parser *parser, const char *namespace, const char *extension ) { struct namespace *n; if( parser->error ) return; assert(parser->current != NULL ); assert(parser->current->namespace == NULL ); n = parser->namespaces; while( n != NULL && strcmp(n->name, namespace) != 0 ) n = n->next; if( n != NULL ) { if( n->extension != NULL && extension != NULL ) { error(parser, "Redefinition of extension in namespace '%s'!", namespace); return; } if( extension != NULL ) { n->extension = strdup(extension); if( n->extension == NULL ) { oom(parser); return; } } n->refcount++; parser->current->namespace = n; return; } n = calloc(1, sizeof(struct namespace)); if( n == NULL ) { oom(parser); return; } n->name = strdup(namespace); if( n->name == NULL ) { oom(parser); free(n); return; } if( extension != NULL ) { n->extension = strdup(extension); if( n->extension == NULL ) { oom(parser); free(n->name); free(n); return; } } n->refcount = 1; parser->current->namespace = n; n->next = parser->namespaces; parser->namespaces = n; } static void parse_struct(struct parser *parser, bool list) { const char *name, *modifier; bool have_length = false, isvariable = false; struct variable *v, *vl, *vt = NULL; struct unfinished_parameter *p; size_t length = 0; name = get_const_token(parser, false); v = add_var(parser, "", name, &name, vt_struct); vl = add_var(parser, "LISTof", name, NULL, vt_type); if( !v || !vl ) return; vl->t.data = v; v->refcount++; if( !list ) { vt = add_var(parser, "", name, NULL, vt_type); vt->t.data = v; v->refcount++; } while( (modifier = get_const_token(parser, have_length)) != NULL ) { if( strcmp(modifier, "variable") == 0 ) { if( have_length ) { error(parser, "variable keyword not allowed after length keyword!"); } if( !list ) { error(parser, "variable keyword not yet allowed for STRUCT, only for LIST!"); } isvariable = true; } else if( strcmp(modifier, "length") == 0 ) { if( isvariable ) error(parser, "variable STRUCTs have no length, use min-length instead!"); modifier = get_const_token(parser, false); length = parse_number(parser, modifier); have_length = true; } else if( strcmp(modifier, "min-length") == 0 ) { if( !isvariable ) error(parser, "min-length only allowed after variable keyword!"); modifier = get_const_token(parser, false); length = parse_number(parser, modifier); if( length == 0 ) { error(parser, "min-length 0 currently not supported to avoid endless loops.\nIf you find a case where it is needed, let me know."); } have_length = true; } else { error(parser, "Unknown attribute '%s'", modifier); } } if( !have_length ) { if( isvariable ) error(parser, "Missing min-length statement!"); else error(parser, "Missing length statement!"); } if( isvariable ) { vl->t.base_type = &base_type_list_of_varstruct; // if( !list ) // vt->t.base_type = &base_type_varstruct; } else { vl->t.base_type = &base_type_list_of_struct; if( !list ) vt->t.base_type = &base_type_struct; } parse_parameters(parser, v, isvariable); /* add (min-)length information: */ p = calloc(1, sizeof(*p)); if( p == NULL ) { oom(parser); return; } p->next = v->parameter; v->parameter = p; p->isspecial = true; p->special.offse = length; } static void parse_type(struct parser *parser) { const char *name; struct variable *v; name = get_const_token(parser, false); v = add_var(parser, "", name, &name, vt_type); if( v == NULL ) return; parse_typespec(parser, &v->t); } static void parse_requests(struct parser *parser) { struct namespace *n = parser->current->namespace; long firstline = parser->current->lineno; assert( n != NULL ); if( n->extension == NULL && strcmp(n->name, "core") != 0 ) { error(parser, "'REQUESTS' only allowed in extension or namespace 'core'!"); return; } if( n->requests != NULL || n->num_requests != 0 ) { error(parser, "multiple 'REQUESTS' in the same namespace!"); return; } while( get_next_line(parser, firstline) ) { const char *name; const char *attribute; struct request_data request, *r; memset(&request, 0, sizeof(request)); /* TODO: allow excplicit setting */ request.number = n->num_requests; name = get_const_token(parser, false); if( name == NULL ) break; if( strcmp(name, "EOF") == 0 ) { error(parser, "Missing 'END' (expected since line %ld)!", firstline + 1); return; } if( strcmp(name, "END") == 0 ) { return; } if( strcmp(name, "UNKNOWN") == 0 ) { request.unsupported = true; request.name = NULL; } else { request.name = string_add(name); if( request.name == NULL ) { parser->error = true; return; } } while( (attribute = get_const_token(parser, true)) != NULL ) { if( strcmp(attribute, "RESPONDS") == 0 ) request.has_response = true; else if( strcmp(attribute, "SPECIAL") == 0 ) { if( request.name == NULL ) error(parser, "SPECIAL not possible with UNKNOWN!"); request.special = true; } else if( strcmp(attribute, "UNSUPPORTED") == 0 ) request.unsupported = true; else if( attribute[0] == '/' && attribute[1] == '*' ) { char *e; long l; if( attribute[2] == '\0' ) attribute = get_const_token(parser, false); else attribute += 2; if( attribute == NULL ) break; l = strtol(attribute, &e, 0); if( *e == '\0' ) attribute = get_const_token(parser, false); else attribute = e; if( attribute == NULL || attribute[0] != '*' || attribute[1] != '/' ) error(parser, "Parse error, '/*' only allowed as '/* number */'!"); else if( request.number != l ) error(parser, "Request '%s' is %d but asserted to be %ld", name, request.number, l); } else { error(parser, "Unexpected response attribute '%s'!", attribute); } } r = realloc(n->requests, sizeof(struct request_data)*(n->num_requests+1)); if( r == NULL ) { oom(parser); break; } n->requests = r; r[n->num_requests] = request; n->num_requests++; } } static void parse_constants(struct parser *parser, bool bitmasks) { struct namespace *n = parser->current->namespace; long firstline = parser->current->lineno; const char *valuesname; size_t count = 0; struct constant *constants; struct variable *v; assert( n != NULL ); valuesname = get_const_token(parser, false); no_more_arguments(parser); v = add_var(parser, "", valuesname, &valuesname, vt_constants); if( v == NULL ) return; constants = malloc(sizeof(struct constant)*8); if( constants == NULL ) { oom(parser); return; } while( get_next_line(parser, firstline) ) { const char *value; const char *text; unsigned long number; int j; value = get_const_token(parser, false); if( value == NULL ) break; if( strcmp(value, "END") == 0 ) { struct constant *nc; nc = realloc(constants, sizeof(struct constant)*(count+1)); if( nc == NULL ) { oom(parser); break; } constants = nc; constants[count].name = NULL; constants[count].value = 0; v->c.constants = constants; v->c.size = sizeof(struct constant)*(count+1); v->c.bitmask = bitmasks; return; } if( strcmp(value, "EOF") == 0 ) { error(parser, "Missing 'END' (for values opened at %ld)!", firstline + 1); break; } number = parse_number(parser, value); text = get_const_token(parser, false); constants[count].value = number; no_more_arguments(parser); constants[count].name = string_add(text); if( bitmasks && constants[count].value == 0 ) error(parser, "Value 0 is not allowed in a BITMASK field!"); for( j = 0 ; (size_t)j < count ; j++ ) { if( constants[count].value == constants[j].value ) { error(parser, "'%s' and '%s' have the same value in '%s'\n", constants[count].name, constants[j].name, valuesname); } if( bitmasks && (constants[count].value && ~constants[j].value) == 0 ) { error(parser, "'%s' shadowed by '%s' in BITMASK '%s'\n", constants[count].name, constants[j].name, valuesname); } } count++; if( (count & 7) == 0 ) { struct constant *nc; nc = realloc(constants, sizeof(struct constant)*(count+8)); if( nc == NULL ) { oom(parser); break; } constants = nc; } } /* some error happened */ free(constants); } static void parse_values(struct parser *parser) { struct namespace *n = parser->current->namespace; long first_line = parser->current->lineno; const char *valuesname; struct variable *v, *lv; struct unfinished_value *values = NULL, **last_val = &values; assert( n != NULL ); valuesname = get_const_token(parser, false); no_more_arguments(parser); v = add_var(parser, "", valuesname, &valuesname, vt_values); lv = add_var(parser, "LISTof", valuesname, NULL, vt_type); if( v == NULL || lv == NULL ) return; lv->t.base_type = &base_type_list_of_value; lv->t.data = v; v->refcount++; v->values = NULL; while( get_next_line(parser, first_line) ) { struct unfinished_value *nv; const char *mask, *name; unsigned long number; struct typespec type; mask = get_const_token(parser, false); if( strcmp(mask, "EOF") == 0 ) { error(parser, "Missing 'END' (closing VALUES opened at line %ld)!", first_line + 1); break; } if( strcmp(mask, "END") == 0 ) { no_more_arguments(parser); if( values == NULL ) { error(parser, "Empty VALUES information!"); return; } v->values = values; return; } number = parse_number(parser, mask); name = get_const_token(parser, false); if( name == NULL ) break; name = string_add(name); if( name == NULL ) { parser->error = true; break; } memset(&type, 0, sizeof(type)); parse_typespec(parser, &type); /* LISTofVALUES only supports some types */ if( !C(type.base_type, ELEMENTARY) ) error(parser, "Only elementary types allowed in VALUES (%s is not)!", type.base_type->name); nv = malloc(sizeof(struct unfinished_value)); if( nv == NULL ) oom(parser); if( parser->error ) { typespec_done(&type); break; } nv->flag = number; nv->name = name; nv->type = type; nv->next = NULL; *last_val = nv; last_val = &nv->next; } error(parser, "missing END!"); while( values != NULL ) { struct unfinished_value *nv = values->next; typespec_done(&values->type); free(values); values = nv; } } static void parse_use(struct parser *parser) { const char *name; struct namespace *ns = parser->current->namespace; while( (name = get_const_token(parser, true)) != NULL ) { struct namespace *n, **nn = realloc(ns->used, sizeof(struct namespace*) * (ns->used_count+1)); if( nn == NULL ) { oom(parser); return; } ns->used = nn; for( n = parser->namespaces ; n != NULL ; n = n->next ) { if( strcmp(n->name, name) == 0 ) break; } // TODO: check if the used namespace is defined // in one of the needed files... ns->used[ns->used_count++] = n; if( n == NULL ) { error(parser, "Unknown namespace '%s'!", name); return; } } } static void check_namespace_complete(struct parser *parser) { struct namespace *n = parser->current->namespace; if( n->requests != NULL ) { int i; for( i = 0 ; i < n->num_requests ; i++ ) { const struct request_data *r = &n->requests[i]; if( r->name == NULL ) continue; if( !r->unsupported && r->request == NULL ) error(parser, "Expected 'REQUEST %s'!", r->name); if( !r->unsupported && r->has_response && r->response == NULL ) error(parser, "Expected 'RESPONSE %s'!", r->name); } } if( n->events[event_normal] != NULL ) { int i; for( i = 0 ; i < n->num_events[event_normal] ; i++ ) { const struct event_data *e = &n->events[event_normal][i]; if( e->name == NULL ) continue; if( !e->unsupported && e->event == NULL ) error(parser, "Missing 'EVENT %s'!", e->name); } } if( n->events[event_xge] != NULL ) { int i; for( i = 0 ; i < n->num_events[event_xge] ; i++ ) { const struct event_data *e = &n->events[event_xge][i]; if( e->name == NULL ) continue; if( !e->unsupported && e->event == NULL ) error(parser, "Missing 'XGEVENT %s'!", e->name); } } } struct parser *parser_init(void) { return calloc(1, sizeof(struct parser)); } bool translate(struct parser *parser, const char *name) { open_next_file(parser, strdup(name)); while( get_next_line(parser, -1) ) { size_t l; char *command; command = get_token_with_len(parser, &l); if( command == NULL ) break; if( command_is("EOF") ) { no_more_arguments(parser); if( parser->current->namespace != NULL ) { check_namespace_complete(parser); } if( file_done(parser) ) return true; } else if( command_is("NEEDS") ) { char *filename = get_token(parser, false); no_more_arguments(parser); open_next_file(parser, filename); } else if( command_is("EXTENSION") ) { if( parser->current->namespace != NULL ) error(parser, "Only one EXTENSION or NAMESPACE is allowed in each file!"); else { const char *extension, *n; extension = get_const_token(parser, false); n = get_const_token(parser, false); no_more_arguments(parser); add_namespace(parser, n, extension); } } else if( command_is("NAMESPACE") ) { if( parser->current->namespace != NULL ) error(parser, "Only one EXTENSION or NAMESPACE is allowed in each file!"); else { name = get_const_token(parser, false); no_more_arguments(parser); add_namespace(parser, name, NULL); } } else if( parser->current->namespace == NULL ) { error(parser, "First command must be EXTENSION or NAMESPACE!"); } else if( command_is("USE") ) { parse_use(parser); } else if( command_is("SETUP") ) { parse_setup(parser); } else if( command_is("REQUESTS") ) { parse_requests(parser); } else if( command_is("EVENTS") ) { parse_events(parser, event_normal); } else if( command_is("XGEVENTS") ) { parse_events(parser, event_xge); } else if( command_is("ERRORS") ) { parse_errors(parser); } else if( command_is("TYPE") ) { parse_type(parser); } else if( command_is("VALUES") ) { parse_values(parser); } else if( command_is("STRUCT") ) { parse_struct(parser, false); } else if( command_is("LIST") ) { parse_struct(parser, true); } else if( command_is("CONSTANTS") ) { parse_constants(parser, false); } else if( command_is("BITMASK") ) { parse_constants(parser, true); } else if( command_is("templateRESPONSE") ) { parse_response(parser, true); } else if( command_is("RESPONSE") ) { parse_response(parser, false); } else if( command_is("templateREQUEST") ) { parse_request(parser, true); } else if( command_is("REQUEST") ) { parse_request(parser, false); } else if( command_is("templateEVENT") ) { parse_event(parser, true, event_normal); } else if( command_is("EVENT") ) { parse_event(parser, false, event_normal); } else if( command_is("XGEVENT") ) { parse_event(parser, false, event_xge); } else { error(parser, "Unknown command '%s'\n", command); } } return false; } #ifdef HAVE_TDESTROY static void free_varname(void *nodep) { struct varname *vn = nodep; variable_unref(vn->variable); free(vn); } #endif bool parser_free(struct parser *parser) { bool success = !parser->error; file_free(parser->current); while( parser->namespaces != NULL ) { struct namespace *ns = parser->namespaces; parser->namespaces = ns->next; int i; #ifdef HAVE_TDESTROY enum variable_type vt; #endif assert( ns->refcount == 0 ); #ifdef HAVE_TDESTROY for( vt = 0 ; vt < vt_COUNT ; vt ++ ) { tdestroy(ns->variables[vt], free_varname); } #else #warning Not freeing some memory as your libc lacks tdestroy #endif free(ns->name); free(ns->extension); for( i = 0 ; i < ns->num_requests ; i++ ) { variable_unref(ns->requests[i].request); variable_unref(ns->requests[i].response); } free(ns->requests); for( i = 0 ; i < ns->num_events[event_normal] ; i++ ) { variable_unref(ns->events[event_normal][i].event); } for( i = 0 ; i < ns->num_events[event_xge] ; i++ ) { variable_unref(ns->events[event_xge][i].event); } if( ns->setup != NULL ) variable_unref(ns->setup); free(ns->events[event_normal]); free(ns->events[event_xge]); free(ns->errors); free(ns->used); free(ns); } while( parser->searchpath != NULL ) { struct searchpath_entry *e = parser->searchpath; parser->searchpath = e->next; free(e); } parser->current = NULL; free(parser); return success; } static void variable_finalize(struct parser *, struct variable *, union parameter_option *); static const struct parameter *parameter_finalize(struct parser *parser, struct unfinished_parameter *parameter) { struct unfinished_parameter *p; size_t count = 0; struct parameter *prepared, *f; const struct parameter *finalized; /* no need to do add empty ones all the time, just take the last one... */ static const struct parameter *empty = NULL; if( parameter == NULL && empty != NULL ) { return empty; } for( p = parameter ; p != NULL ; p = p->next ) { count++; assert( !p->isspecial || !p->special.isjunction || p->special.finalized != NULL ); } prepared = calloc(count + 1, sizeof(struct parameter)); if( prepared == NULL ) { oom(parser); return NULL; } for( f = prepared, p = parameter ; p != NULL ; p = p->next, f++ ) { assert( (size_t)(f - prepared) < count ); if( p->isspecial ) { f->offse = p->special.offse; f->name = p->special.condition; f->type = p->special.type; f->o.parameters = p->special.finalized; } else { f->offse = p->regular.offse; f->name = p->regular.name; f->type = p->regular.type.base_type->type; variable_finalize(parser, p->regular.type.data, &f->o); } } assert( (size_t)(f - prepared) == count ); finalized = finalize_data(prepared, (count + 1)*sizeof(struct parameter), __alignof__(struct parameter)); free(prepared); /* remember last terminator as next empty jump target */ empty = finalized; empty += count; return finalized; } static const struct parameter *parameters_finalize(struct parser *parser, struct variable *v) { struct unfinished_parameter *p, *todo, *startat; if( v == NULL ) return NULL; assert( v->type == vt_struct || v->type == vt_response || v->type == vt_setup || v->type == vt_request || v->type == vt_event ); if( v->finalized.parameters != NULL ) return v->finalized.parameters; do { todo = NULL; startat = v->parameter; p = startat; while( p != NULL ) { if( !p->isspecial ) { p = p->next; continue; } if( p->special.finalized != NULL ) { p = p->next; continue; } if( !p->special.isjunction ) { p = p->next; continue; } if( p->special.iftrue == NULL ) { /* empty branch still needs an end command, but no recursion for that */ p->special.finalized = parameter_finalize(parser, NULL); p = p->next; continue; } todo = p; startat = p->special.iftrue; p = startat; } if( todo != NULL ) { todo->special.finalized = parameter_finalize(parser, startat); } else { v->finalized.parameters = parameter_finalize(parser, startat); } } while( todo != NULL ); return v->finalized.parameters; } static const struct constant *constants_finalize(struct parser *parser, struct variable *v) { if( v == NULL ) return NULL; assert( v->type == vt_constants ); if( v->finalized.constants != NULL ) return v->finalized.constants; v->finalized.constants = finalize_data(v->c.constants, v->c.size, __alignof__(struct constant)); if( v->finalized.constants == NULL ) parser->error = true; return v->finalized.constants; } static inline const struct value *values_finalize(struct parser *parser, struct variable *v) { struct value *values; struct unfinished_value *uv; size_t i = 0, count = 0; if( v == NULL ) return NULL; assert( v->type == vt_values ); if( v->finalized.values != NULL ) return v->finalized.values; for( uv = v->values; uv != NULL ; uv = uv->next ) count++; values = calloc(count + 1, sizeof(struct value)); if( values == NULL ) { oom(parser); return NULL; } for( uv = v->values; uv != NULL ; uv = uv->next ) { assert( i < count); values[i].flag = uv->flag; values[i].name = uv->name; assert( C(uv->type.base_type, ELEMENTARY) ); values[i].type = uv->type.base_type->type; values[i].constants = constants_finalize( parser, uv->type.data); i++; } v->finalized.values = finalize_data(values, (count+1)*sizeof(struct value), __alignof__(struct value)); free(values); if( v->finalized.values == NULL ) parser->error = true; return v->finalized.values; } static void variable_finalize(struct parser *parser, struct variable *v, union parameter_option *o) { if( v == NULL ) { memset(o, 0, sizeof(union parameter_option)); } else if( v->type == vt_values ) { o->values = values_finalize(parser, v); } else if( v->type == vt_constants ) { o->constants = constants_finalize(parser, v); } else if( v->type == vt_struct || v->type == vt_response || v->type == vt_setup || v->type == vt_request || v->type == vt_event ) { o->parameters = parameters_finalize(parser, v); } else { memset(o, 0, sizeof(union parameter_option)); assert( v->type != v->type ); } } static const struct request *finalize_requests(struct parser *parser, struct namespace *ns, const struct parameter *unknownrequest, const struct parameter *unknownresponse) { struct request *rs; const struct request *f; int i; rs = calloc(ns->num_requests, sizeof(struct request)); if( rs == NULL ) { oom(parser); return NULL; } for( i = 0 ; i < ns->num_requests ; i++ ) { rs[i].name = ns->requests[i].name; if( ns->requests[i].unsupported ) { assert( ns->requests[i].request == NULL); rs[i].parameters = unknownrequest; } else { assert( ns->requests[i].request != NULL); rs[i].parameters = parameters_finalize(parser, ns->requests[i].request); } if( ns->requests[i].has_response ) { if( ns->requests[i].unsupported ) { assert( ns->requests[i].response == NULL); rs[i].answers = unknownresponse; } else { assert( ns->requests[i].response != NULL); rs[i].answers = parameters_finalize(parser, ns->requests[i].response); } } else assert( ns->requests[i].response == NULL); rs[i].record_variables = ns->requests[i].record_variables; if( !ns->requests[i].special ) continue; assert( rs[i].name != NULL ); if( strcmp(ns->name, "core") != 0 ) { fprintf(stderr, "No specials available in namespace '%s'!\n", ns->name); parser->error = true; } else if( strcmp(rs[i].name, "QueryExtension") == 0 ) { rs[i].request_func = requestQueryExtension; rs[i].reply_func = replyQueryExtension; } else if( strcmp(rs[i].name, "InternAtom") == 0 ) { /* atoms are not the only names, in the future that might be something general... */ rs[i].request_func = requestInternAtom; rs[i].reply_func = replyInternAtom; } else if( strcmp(rs[i].name, "ListFontsWithInfo") == 0 ) { /* this should be changed to a general approach */ rs[i].reply_func = replyListFontsWithInfo; } else if( strcmp(rs[i].name, "GetAtomName") == 0) { rs[i].request_func = requestGetAtomName; rs[i].reply_func = replyGetAtomName; } else { fprintf(stderr, "No specials available for '%s::%s'!\n", ns->name, rs[i].name); parser->error = true; } } f = finalize_data(rs, ns->num_requests * sizeof(struct request), __alignof__(struct request)); if( f == NULL ) parser->error = true; free(rs); return f; } static const struct event *finalize_events(struct parser *parser, struct namespace *ns, enum event_type et) { struct event *es; const struct event *f; int i; es = calloc(ns->num_events[et], sizeof(struct event)); if( es == NULL ) { oom(parser); return NULL; } for( i = 0 ; i < ns->num_events[et] ; i++ ) { es[i].name = ns->events[et][i].name; es[i].parameters = parameters_finalize(parser, ns->events[et][i].event); if( !ns->events[et][i].special ) continue; assert( es[i].name != NULL ); if( strcmp(ns->name, "ge") != 0 && strcmp(ns->name, "core") != 0) { fprintf(stderr, "No specials available in namespace '%s'!\n", ns->name); parser->error = true; } else if( strcmp(es[i].name, "Generic") == 0 ) { es[i].type = event_xge; } else { fprintf(stderr, "No specials available for '%s::%s'!\n", ns->name, es[i].name); parser->error = true; } } f = finalize_data(es, ns->num_events[et] * sizeof(struct event), __alignof__(struct event)); if( f == NULL ) parser->error = true; free(es); return f; } void finalize_everything(struct parser *parser) { struct extension *es, *e; size_t count = 0; struct namespace *ns, *core = NULL; struct variable *v; const struct parameter *unknownrequest, *unknownresponse; if( parser->error ) return; assert( extensions == NULL /* only to be called one time */ ); for( ns = parser->namespaces ; ns != NULL ; ns = ns->next ) { if( strcmp(ns->name, "core") == 0 ) core = ns; if( ns->extension != NULL ) count++; } if( core == NULL ) { fputs("No core namespace defined!\n", stderr); parser->error = true; return; } if( core->num_requests == 0 ) { fputs("No core requests defined!\n", stderr); parser->error = true; return; } if( core->num_events[event_normal] == 0 ) { fputs("No core events defined!\n", stderr); parser->error = true; return; } if( core->num_events[event_xge] != 0 ) { fputs("Generic Events (XGE) outside of extensions not yet supported!\n", stderr); parser->error = true; return; } if( core->num_errors == 0 ) { fputs("No core errors defined!\n", stderr); parser->error = true; return; } if( core->setup == NULL ) { fputs("No setup parser defined!\n", stderr); parser->error = true; return; } v = find_variable(parser, vt_request, "core::unknown"); unknownrequest = parameters_finalize(parser, v); v = find_variable(parser, vt_response, "core::unknown"); unknownresponse = parameters_finalize(parser, v); unexpected_reply = unknownresponse; if( parser->error ) return; if( count == 0 ) { num_extensions = count; extensions = NULL; return; } else { es = calloc(count, sizeof(struct extension)); if( es == NULL ) { oom(parser); return; } e = es; for( ns = parser->namespaces ; ns != NULL ; ns = ns->next ) { if( ns->extension == NULL ) continue; e->name = string_add(ns->extension); if( e->name == NULL ) parser->error = true; e->namelen = strlen(ns->extension); e->numsubrequests = ns->num_requests; e->subrequests = finalize_requests(parser, ns, unknownrequest, unknownresponse); e->numevents = ns->num_events[event_normal]; e->events = finalize_events(parser, ns, event_normal); e->numxgevents = ns->num_events[event_xge]; e->xgevents = finalize_events(parser, ns, event_xge); e->numerrors = ns->num_errors; e->errors = finalize_data(ns->errors, ns->num_errors*sizeof(const char*), __alignof__(const char*)); if( e->errors == NULL ) parser->error = true; e++; } assert( (size_t)(e-es) == count ); extensions = finalize_data(es, count*sizeof(struct extension), __alignof__(struct extension)); free(es); if( extensions == NULL ) { oom(parser); return; } num_extensions = count; } requests = finalize_requests(parser, core, unknownrequest, unknownresponse); num_requests = core->num_requests; events = finalize_events(parser, core, event_normal); num_events = core->num_events[event_normal]; errors = finalize_data(core->errors, core->num_errors*sizeof(const char*), __alignof__(const char*)); if( errors == NULL ) parser->error = true; num_errors = core->num_errors; setup_parameters = parameters_finalize(parser, core->setup); } /* int main() { bool success; struct parser *parser; stringlist_init(); parser = parser_init(parser); if( parser == NULL ) exit(EXIT_FAILURE); translate(&parser, "all.proto"); finalize_everything(parser); success = parser_free(parser); stringlist_done(); return success?EXIT_SUCCESS:EXIT_FAILURE; } */
deepfire/xtrace
translate.c
C
gpl-2.0
71,798