code stringlengths 2 1.05M | repo_name stringlengths 5 114 | path stringlengths 4 991 | language stringclasses 1 value | license stringclasses 15 values | size int32 2 1.05M |
|---|---|---|---|---|---|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M16.5 9c-.42 0-.83.04-1.24.11L2.4 3.6c-.66-.29-1.39.2-1.39.91L1 9.2c0 .47.33.88.78.98L10 12l-8.22 1.83c-.45.1-.78.5-.78.97l.01 4.68c0 .72.73 1.2 1.39.92l6.68-2.86C9.59 21.19 12.71 24 16.5 24c4.14 0 7.5-3.36 7.5-7.5S20.64 9 16.5 9zm0 13c-3.03 0-5.5-2.47-5.5-5.5s2.47-5.5 5.5-5.5 5.5 2.47 5.5 5.5-2.47 5.5-5.5 5.5z"
}, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M18.62 14.38c-.2-.2-.51-.2-.71 0l-1.41 1.41-1.41-1.41c-.2-.2-.51-.2-.71 0s-.2.51 0 .71l1.41 1.41-1.41 1.41c-.2.2-.2.51 0 .71.2.2.51.2.71 0l1.41-1.41 1.41 1.41c.2.2.51.2.71 0 .2-.2.2-.51 0-.71l-1.41-1.41 1.41-1.41c.2-.2.2-.52 0-.71z"
}, "1")], 'CancelScheduleSendRounded');
exports.default = _default; | oliviertassinari/material-ui | packages/mui-icons-material/lib/CancelScheduleSendRounded.js | JavaScript | mit | 1,091 |
(function() {
var content = '';
[
{ name: 'Device Name', value: window.device.name },
{ name: 'Device UUID', value: window.device.uuid },
{ name: 'Platform Name', value: window.device.platform },
{ name: 'Platform Version', value: window.device.version },
{ name: 'PhoneGap Version', value: window.device.phonegap }
].forEach(function(obj) {
content += '<li>' + obj.name +
'<p class="ui-li-aside ul-li-desc">' + obj.value + '</p>' +
'</li>';
});
$('#device ul[data-role="listview"]').html(content).listview('refresh');
})();
| aniket143/sbitapp | jQuery Mobile Kitchen Sink App/www/js/api/device.js | JavaScript | mit | 633 |
//>>built
define("dijit/nls/dijit-all_nb",{"dojo/nls/colors":{aliceblue:"bl\u00e5hvit",antiquewhite:"antikk hvit",aqua:"akva",aquamarine:"akvamarin",azure:"asur",beige:"beige",bisque:"gulrosa",black:"svart",blanchedalmond:"lys mandel",blue:"bl\u00e5",blueviolet:"bl\u00e5fiolett",brown:"brun",burlywood:"matt mellombrun",cadetblue:"m\u00f8rk gr\u00f8nnbl\u00e5",chartreuse:"l\u00f8vgr\u00f8nn",chocolate:"sjokolade",coral:"korall",cornflowerblue:"kornbl\u00e5",cornsilk:"cornsilk",crimson:"karmosinr\u00f8dt",cyan:"cyan",
darkblue:"m\u00f8rk bl\u00e5",darkcyan:"m\u00f8rk cyan",darkgoldenrod:"m\u00f8rk gyldenris",darkgray:"m\u00f8rk gr\u00e5",darkgreen:"m\u00f8rk gr\u00f8nn",darkgrey:"m\u00f8rk gr\u00e5",darkkhaki:"m\u00f8rk khaki",darkmagenta:"m\u00f8rk magenta",darkolivegreen:"m\u00f8rk olivengr\u00f8nn",darkorange:"m\u00f8rk oransje",darkorchid:"m\u00f8rk orkide",darkred:"m\u00f8rk r\u00f8d",darksalmon:"m\u00f8rk lakserosa",darkseagreen:"m\u00f8rk sj\u00f8gr\u00f8nn",darkslateblue:"m\u00f8rk skiferbl\u00e5",darkslategray:"m\u00f8rk skifergr\u00e5",
darkslategrey:"m\u00f8rk skifergr\u00e5",darkturquoise:"m\u00f8rk turkis",darkviolet:"m\u00f8rk fiolett",deeppink:"dyp rosa",deepskyblue:"dyp himmelbl\u00e5",dimgray:"m\u00f8rk m\u00f8rkegr\u00e5",dimgrey:"m\u00f8rk m\u00f8rkegr\u00e5",dodgerblue:"lys havbl\u00e5",firebrick:"mursteinsr\u00f8d",floralwhite:"blomsterhvit",forestgreen:"skoggr\u00f8nn",fuchsia:"fuksia",gainsboro:"lys lys gr\u00e5",ghostwhite:"egghvit",gold:"gull",goldenrod:"gyldenris",gray:"gr\u00e5",green:"gr\u00f8nn",greenyellow:"gulgr\u00f8nn",
grey:"gr\u00e5",honeydew:"gr\u00f8nnhvit",hotpink:"halvm\u00f8rk rosa",indianred:"rustr\u00f8d",indigo:"indigo",ivory:"elfenbenshvit",khaki:"khaki",lavender:"lavendel",lavenderblush:"lillahvit",lawngreen:"plengr\u00f8nn",lemonchiffon:"ferskenfarget",lightblue:"lys bl\u00e5",lightcoral:"lys korall",lightcyan:"lys cyan",lightgoldenrodyellow:"lys gyldenrisgul",lightgray:"lys gr\u00e5",lightgreen:"lys gr\u00f8nn",lightgrey:"lys gr\u00e5",lightpink:"lys rosa",lightsalmon:"lys lakserosa",lightseagreen:"lys sj\u00f8gr\u00f8nn",
lightskyblue:"lys himmelbl\u00e5",lightslategray:"lys skifergr\u00e5",lightslategrey:"lys skifergr\u00e5",lightsteelblue:"lys st\u00e5lbl\u00e5",lightyellow:"lys gul",lime:"lime",limegreen:"limegr\u00f8nn",linen:"lin",magenta:"magenta",maroon:"r\u00f8dbrun",mediumaquamarine:"middels akvamarin",mediumblue:"mellombl\u00e5",mediumorchid:"middels orkide",mediumpurple:"middels purpur",mediumseagreen:"middels sj\u00f8gr\u00f8nn",mediumslateblue:"middels skiferbl\u00e5",mediumspringgreen:"middels v\u00e5rgr\u00f8nn",
mediumturquoise:"middels turkis",mediumvioletred:"middels fiolettr\u00f8d",midnightblue:"midnattsbl\u00e5",mintcream:"mintkrem",mistyrose:"lys rosenr\u00f8d",moccasin:"lys gulbrun",navajowhite:"gulbrun",navy:"marinebl\u00e5",oldlace:"kniplingshvit",olive:"oliven",olivedrab:"middels olivengr\u00f8nn",orange:"oransje",orangered:"r\u00f8doransje",orchid:"orkide",palegoldenrod:"svak gyldenris",palegreen:"svak gr\u00f8nn",paleturquoise:"svak turkis",palevioletred:"svak fiolettr\u00f8d",papayawhip:"lys papaya",
peachpuff:"brunrosa",peru:"lys n\u00f8ttebrun",pink:"rosa",plum:"plommefarget",powderblue:"lys gr\u00f8nnbl\u00e5",purple:"purpur",red:"r\u00f8d",rosybrown:"brunlilla",royalblue:"kongebl\u00e5",saddlebrown:"m\u00f8rk n\u00f8ttebrun",salmon:"lakserosa",sandybrown:"sandbrun",seagreen:"sj\u00f8gr\u00f8nn",seashell:"skjellhvit",sienna:"n\u00f8ttebrun",silver:"s\u00f8lvfarget",skyblue:"himmelbl\u00e5",slateblue:"skiferbl\u00e5",slategray:"skifergr\u00e5",slategrey:"skifergr\u00e5",snow:"sn\u00f8hvit",
springgreen:"v\u00e5rgr\u00f8nn",steelblue:"st\u00e5lbl\u00e5",tan:"matt mellombrun",teal:"m\u00f8rk gr\u00f8nnbl\u00e5",thistle:"lys gr\u00e5lilla",tomato:"tomatr\u00f8d",transparent:"gjennomsiktig",turquoise:"turkis",violet:"fiolett",wheat:"varm sienna",white:"hvit",whitesmoke:"r\u00f8ykhvit",yellow:"gul",yellowgreen:"gulgr\u00f8nn",_localized:{}},"dijit/nls/loading":{loadingState:"Laster inn...",errorState:"Det oppsto en feil",_localized:{}},"dijit/nls/common":{buttonOk:"OK",buttonCancel:"Avbryt",
buttonSave:"Lagre",itemClose:"Lukk",_localized:{}},"dijit/_editor/nls/commands":{bold:"Fet",copy:"Kopier",cut:"Klipp ut","delete":"Slett",indent:"Innrykk",insertHorizontalRule:"Vannrett strek",insertOrderedList:"Nummerert liste",insertUnorderedList:"Punktliste",italic:"Kursiv",justifyCenter:"Midtstill",justifyFull:"Juster",justifyLeft:"Venstrejuster",justifyRight:"H\u00f8yrejuster",outdent:"Fjern innrykk",paste:"Lim inn",redo:"Gj\u00f8r om",removeFormat:"Fjern format",selectAll:"Velg alle",strikethrough:"Gjennomstreking",
subscript:"Senket skrift",superscript:"Hevet skrift",underline:"Understreking",undo:"Angre",unlink:"Fjern kobling",createLink:"Opprett kobling",toggleDir:"Bytt retning",insertImage:"Sett inn bilde",insertTable:"Sett inn/rediger tabell",toggleTableBorder:"Bytt tabellkant",deleteTable:"Slett tabell",tableProp:"Tabellegenskap",htmlToggle:"HTML-kilde",foreColor:"Forgrunnsfarge",hiliteColor:"Bakgrunnsfarge",plainFormatBlock:"Avsnittsstil",formatBlock:"Avsnittsstil",fontSize:"Skriftst\u00f8rrelse",fontName:"Skriftnavn",
tabIndent:"Tabulatorinnrykk",fullScreen:"Sl\u00e5 p\u00e5/av full skjerm",viewSource:"Vis HTML-kilde",print:"Skriv ut",newPage:"Ny side",systemShortcut:'Handlingen "${0}" er bare tilgjengelig i nettleseren ved hjelp av en tastatursnarvei. Bruk ${1}.',ctrlKey:"ctrl+${0}",appleKey:"\u2318${0}",_localized:{}},"dijit/form/nls/validate":{invalidMessage:"Den angitte verdien er ikke gyldig.",missingMessage:"Denne verdien er obligatorisk.",rangeMessage:"Denne verdien er utenfor gyldig omr\u00e5de.",_localized:{}},
"dijit/form/nls/ComboBox":{previousMessage:"Tidligere valg",nextMessage:"Flere valg",_localized:{}},"dijit/_editor/nls/FontChoice":{fontSize:"St\u00f8rrelse",fontName:"Skrift",formatBlock:"Format",serif:"serif","sans-serif":"sans-serif",monospace:"monospace",cursive:"kursiv",fantasy:"fantasi",noFormat:"Ingen",p:"Avsnitt",h1:"Overskrift",h2:"Undertittel",h3:"Under-undertittel",pre:"Forh\u00e5ndsformatert",1:"xx-liten",2:"x-liten",3:"liten",4:"middels",5:"stor",6:"x-stor",7:"xx-stor",_localized:{}},
"dojo/cldr/nls/number":{scientificFormat:"#E0","currencySpacing-afterCurrency-currencyMatch":"[:^S:]",infinity:"\u221e",superscriptingExponent:"\u00d7",list:";",percentSign:"%",minusSign:"\u2212","currencySpacing-beforeCurrency-surroundingMatch":"[:digit:]","decimalFormat-short":"000\u00a0bill","currencySpacing-afterCurrency-insertBetween":"\u00a0",nan:"NaN",plusSign:"+","currencySpacing-afterCurrency-surroundingMatch":"[:digit:]","currencySpacing-beforeCurrency-currencyMatch":"[:^S:]",currencyFormat:"\u00a4\u00a0#,##0.00",
perMille:"\u2030",group:"\u00a0",percentFormat:"#,##0\u00a0%","decimalFormat-long":"000 billioner",decimalFormat:"#,##0.###",decimal:",","currencySpacing-beforeCurrency-insertBetween":"\u00a0",exponential:"E",_localized:{}},"dojo/cldr/nls/currency":{USD_symbol:"USD",CAD_symbol:"CAD",GBP_symbol:"\u00a3",HKD_symbol:"HKD",JPY_symbol:"JPY",AUD_symbol:"AUD",CNY_symbol:"CNY",EUR_symbol:"\u20ac",HKD_displayName:"Hongkong-dollar",CHF_displayName:"sveitsiske franc",CAD_displayName:"kanadiske dollar",CNY_displayName:"kinesiske yuan",
AUD_displayName:"australske dollar",JPY_displayName:"japanske yen",USD_displayName:"amerikanske dollar",GBP_displayName:"britiske pund sterling",EUR_displayName:"euro",_localized:{}},"dojo/cldr/nls/gregorian":{"dateFormatItem-Ehm":"E h.mm a","days-standAlone-short":"s\u00f8. ma. ti. on. to. fr. l\u00f8.".split(" "),"months-format-narrow":"JFMAMJJASOND".split(""),"field-second-relative+0":"n\u00e5","quarters-standAlone-narrow":["1","2","3","4"],"field-weekday":"Ukedag","dateFormatItem-yQQQ":"QQQ y",
"dateFormatItem-yMEd":"E d.MM.y","field-wed-relative+0":"onsdag denne uken","field-wed-relative+1":"onsdag neste uke","dateFormatItem-GyMMMEd":"E d. MMM y G","dateFormatItem-MMMEd":"E d. MMM",eraNarrow:["f.Kr.","fvt.","e.Kr.","vt"],"field-tue-relative+-1":"tirsdag sist uke","days-format-short":"s\u00f8. ma. ti. on. to. fr. l\u00f8.".split(" "),"dateTimeFormats-appendItem-Day-Of-Week":"{0} {1}","dateFormat-long":"d. MMMM y","field-fri-relative+-1":"fredag sist uke","field-wed-relative+-1":"onsdag sist uke",
"months-format-wide":"januar februar mars april mai juni juli august september oktober november desember".split(" "),"dateTimeFormat-medium":"{1}, {0}","dayPeriods-format-wide-pm":"p.m.","dateFormat-full":"EEEE d. MMMM y","field-thu-relative+-1":"torsdag sist uke","dateFormatItem-Md":"d.M.","dayPeriods-format-abbr-am":"a.m.","dateTimeFormats-appendItem-Second":"{0} ({2}: {1})","dayPeriods-format-wide-noon":"noon","dateFormatItem-yMd":"d.M.y","field-era":"Tidsalder","dateFormatItem-yM":"M.y","months-standAlone-wide":"januar februar mars april mai juni juli august september oktober november desember".split(" "),
"timeFormat-short":"HH.mm","quarters-format-wide":["1. kvartal","2. kvartal","3. kvartal","4. kvartal"],"dateFormatItem-yQQQQ":"QQQQ y","timeFormat-long":"HH.mm.ss z","field-year":"\u00c5r","dateFormatItem-yMMM":"MMM y","dateTimeFormats-appendItem-Era":"{1} {0}","field-hour":"Time","months-format-abbr":"jan. feb. mar. apr. mai jun. jul. aug. sep. okt. nov. des.".split(" "),"field-sat-relative+0":"l\u00f8rdag denne uken","field-sat-relative+1":"l\u00f8rdag neste uke","timeFormat-full":"HH.mm.ss zzzz",
"dateTimeFormats-appendItem-Week":"{0} ({2}: {1})","field-day-relative+0":"i dag","field-thu-relative+0":"torsdag denne uken","field-day-relative+1":"i morgen","field-thu-relative+1":"torsdag neste uke","dateFormatItem-GyMMMd":"d. MMM y G","dateFormatItem-H":"HH","months-standAlone-abbr":"jan feb mar apr mai jun jul aug sep okt nov des".split(" "),"quarters-format-abbr":["K1","K2","K3","K4"],"quarters-standAlone-wide":["1. kvartal","2. kvartal","3. kvartal","4. kvartal"],"dateFormatItem-Gy":"y G",
"dateFormatItem-M":"L.","days-standAlone-wide":"s\u00f8ndag mandag tirsdag onsdag torsdag fredag l\u00f8rdag".split(" "),"dayPeriods-format-abbr-noon":"noon","timeFormat-medium":"HH.mm.ss","field-sun-relative+0":"s\u00f8ndag denne uken","dateFormatItem-Hm":"HH.mm","field-sun-relative+1":"s\u00f8ndag neste uke","quarters-standAlone-abbr":["K1","K2","K3","K4"],eraAbbr:["f.Kr.","e.Kr."],"field-minute":"Minutt","field-dayperiod":"AM/PM","days-standAlone-abbr":"s\u00f8. ma. ti. on. to. fr. l\u00f8.".split(" "),
"dateFormatItem-d":"d.","dateFormatItem-ms":"mm.ss","quarters-format-narrow":["1","2","3","4"],"field-day-relative+-1":"i g\u00e5r","dateTimeFormat-long":"{1} 'kl.' {0}","dayPeriods-format-narrow-am":"a","dateFormatItem-h":"h a","dateFormatItem-MMMd":"d. MMM","dateFormatItem-MEd":"E d.M","dateTimeFormat-full":"{1} {0}","field-fri-relative+0":"fredag denne uken","field-fri-relative+1":"fredag neste uke","field-day":"Dag","days-format-wide":"s\u00f8ndag mandag tirsdag onsdag torsdag fredag l\u00f8rdag".split(" "),
"field-zone":"Tidssone","months-standAlone-narrow":"JFMAMJJASOND".split(""),"dateFormatItem-y":"y","dateTimeFormats-appendItem-Day":"{0} ({2}: {1})","field-year-relative+-1":"I fjor","field-month-relative+-1":"Sist m\u00e5ned","dateTimeFormats-appendItem-Year":"{1} {0}","dateFormatItem-hm":"h.mm a","dateTimeFormats-appendItem-Hour":"{0} ({2}: {1})","dayPeriods-format-abbr-pm":"p.m.","days-format-abbr":"s\u00f8n. man. tir. ons. tor. fre. l\u00f8r.".split(" "),eraNames:["f.Kr.","e.Kr."],"dateFormatItem-yMMMd":"d. MMM y",
"days-format-narrow":"SMTOTFL".split(""),"field-month":"M\u00e5ned","days-standAlone-narrow":"SMTOTFL".split(""),"dateFormatItem-MMM":"LLL","field-tue-relative+0":"tirsdag denne uken","dateTimeFormats-appendItem-Quarter":"{0} ({2}: {1})","field-tue-relative+1":"tirsdag neste uke","dayPeriods-format-wide-am":"a.m.","dateTimeFormats-appendItem-Month":"{0} ({2}: {1})","dateTimeFormats-appendItem-Minute":"{0} ({2}: {1})","dateFormatItem-EHm":"E HH.mm","field-mon-relative+0":"mandag denne uken","field-mon-relative+1":"mandag neste uke",
"dateFormat-short":"dd.MM.yy","dateFormatItem-EHms":"E HH.mm.ss","dateFormatItem-Ehms":"E h.mm.ss a","dayPeriods-format-narrow-noon":"n","field-second":"Sekund","field-sat-relative+-1":"l\u00f8rdag sist uke","dateFormatItem-yMMMEd":"E d. MMM y","field-sun-relative+-1":"s\u00f8ndag sist uke","field-month-relative+0":"Denne m\u00e5neden","field-month-relative+1":"Neste m\u00e5ned","dateTimeFormats-appendItem-Timezone":"{0} {1}","dateFormatItem-Ed":"E d.","field-week":"Uke","dateFormat-medium":"d. MMM y",
"field-week-relative+-1":"Sist uke","field-year-relative+0":"Dette \u00e5ret","field-year-relative+1":"Neste \u00e5r","dayPeriods-format-narrow-pm":"p","dateTimeFormat-short":"{1}, {0}","dateFormatItem-Hms":"HH.mm.ss","dateFormatItem-hms":"h.mm.ss a","dateFormatItem-GyMMM":"MMM y G","field-mon-relative+-1":"mandag sist uke","field-week-relative+0":"Denne uken","field-week-relative+1":"Neste uke","dateFormatItem-yMM":"MM.y","dateFormatItem-MMdd":"d.M.","field-day-relative+2":"i overmorgen","field-day-relative+-2":"i forg\u00e5rs",
"dateFormatItem-yMMMM":"MMMM y",_localized:{}}}); | darklilium/Factigis_2 | arcgis_js_api/library/3.17/3.17compact/dijit/nls/dijit-all_nb.js | JavaScript | mit | 13,091 |
/**
* Created by Luke on 01/05/15.
*/
const APD_BASE = '/apd-api';
const apdRoute = (route, transformer) => `${APD_BASE}/${transformer(route)}`;
const endpoints = {
/**
* source: https://wiki.appnexus.com/display/api/API+Services
*/
ACCOUNT_RECOVERY_SERVICE: '/account-recovery',
AD_PROFILE_SERVICE: '/ad-profile',
AD_QUALITY_RULE_SERVICE: '/ad-quality-rule',
AD_SERVER_SERVICE: '/ad-server',
ADVERTISER_SERVICE: '/advertiser',
APP_INSTALLATION_SERVICE: '/app-installation',
AUTHENTICATION_SERVICE: '/auth',
BATCH_SEGMENT_SERVICE: '/batch-segment',
BRAND_COMPANY_SERVICE: '/brand-company',
BRAND_SERVICE: '/brand',
BROKER_SERVICE: '/broker',
BROWSER_SERVICE: '/browser',
CAMPAIGN_SERVICE: '/campaign',
CARRIER_SERVICE: '/carrier',
CATEGORY_SERVICE: '/category',
CITY_SERVICE: '/city',
CLICK_TRACKER_SERVICE: '/clicktracker',
CONTENT_CATEGORY_SERVICE: '/content-category',
COUNTRY_SERVICE: '/country',
CREATIVE_CUSTOM_REQUEST_TEMPLATE_SERVICE: '/creative-custom-request-template',
CREATIVE_CUSTOM_REQUEST_TEMPLATE_TYPE_SERVICE: '/creative-custom-request-template-type',
CREATIVE_FOLDER_SERVICE: '/creative-folder',
CREATIVE_FORMAT_SERVICE: '/creative-format',
CREATIVE_MACRO_CHECK_SERVICE: '/creative-macro-check',
CREATIVE_SEARCH_SERVICE: '/creative-search',
CREATIVE_SERVICE: '/creative',
CREATIVE_TEMPLATE_SERVICE: '/template',
CURRENCY_SERVICE: '/currency',
DEAL_BUYER_ACCESS_SERVICE: '/package-buyer-access',
DEAL_FROM_PACKAGE_SERVICE: '/deal-from-package',
DEAL_SERVICE: '/deal',
DEMOGRAPHIC_AREA_SERVICE: '/dma',
DEVELOPER_SERVICE: '/developer',
DEVICE_MAKE_SERVICE: '/device-make',
DEVICE_MODEL_SERVICE: '/device-model',
DOMAIN_AUDIT_STATUS_SERVICE: '/url-audit-search',
DOMAIN_LIST_SERVICE: '/domain-list',
EXTERNAL_INVENTORY_CODE_SERVICE: '/external-inv-code',
EXTRACT_CLICKTAGS_SERVICE: '/extract-click-tags',
FEED_STATUS_SERVICE: '/feed-status',
IMPRESSION_TRACKER_SERVICE: '/imptracker',
INSERTION_ORDER_SERVICE: '/insertion-order',
INVENTORY_ATTRIBUTE_SERVICE: '/inventory-attribute',
INVENTORY_GROUP_SERVICE: '/inventory-group',
INVENTORY_RESOLD_SERVICE: '/inventory-resold',
INVENTORY_SOURCE_SERVICE: '/inventory-source',
IP_RANGE_LIST_SERVICE: '/ip-range-list',
LABEL_SERVICE: '/label',
LANGUAGE_SERVICE: '/language',
LINE_ITEM_SERVICE: '/line-item',
LOG_LEVEL_DATA_SERVICE: '/siphon',
LOOKUP_SERVICE: '/lookup',
MANUAL_OFFER_RANKING_SERVICE: '/manual-offer-ranking',
MEDIA_SUBTYPE_SERVICE: '/media-subtype',
MEDIA_TYPE_SERVICE: '/media-type',
MEMBER_PROFILE_SERVICE: '/member-profile',
MEMBER_SERVICE: '/member',
MOBILE_APP_INSTANCE_LIST_SERVICE: '/mobile-app-instance-list',
MOBILE_APP_INSTANCE_SERVICE: '/mobile-app-instance',
MOBILE_APP_SERVICE: '/mobile-app',
MOBILE_APP_STORE_SERVICE: '/mobile-app-store',
OBJECT_LIMIT_SERVICE: '/object-limit',
OPERATING_SYSTEM_EXTENDED_SERVICE: '/operating-system-extended',
OPERATING_SYSTEM_FAMILY_SERVICE: '/operating-system-family',
OPERATING_SYSTEM_SERVICE: '/operating-system',
OPTIMIZATION_ZONE_SERVICE: '/optimization-zone',
PACKAGE_BUYER_ACCESS_SERVICE: '/package-buyer-access',
PACKAGE_SERVICE: '/package',
PAYMENT_RULE_SERVICE: '/payment-rule',
PIXEL_SERVICE: '/pixel',
PIXEL_TEMPLATE_SERVICE: '/pixel-template',
PLACEMENT_SERVICE: '/placement',
PLATFORM_MEMBER_SERVICE: '/platform-member',
PLUGIN_INSTANCE_SERVICE: '/plugin-instance',
PLUGIN_SERVICE: '/plugin',
PROFILE_SERVICE: '/profile',
PROFILE_SUMMARY_SERVICE: '/profile-summary',
PUBLISHER_SERVICE: '/publisher',
REGION_SERVICE: '/region',
REPORT_SERVICE: '/report',
REPORT_STATUS_SERVICE: '/report-status',
SAVED_REPORT_SERVICE: '/saved-report',
SEARCH_SERVICE: '/search',
SEGMENT_SERVICE: '/segment',
SIPHON_CONFIG_SERVICE: '/siphon-config',
SITE_SERVICE: '/site',
TAG_PARSER_SERVICE: '/tag-parser-job',
TECHNICAL_ATTRIBUTE_SERVICE: '/technical-attribute',
THIRD_PARTY_PAGE_ACCESS_SERVICE: '/thirdparty-pageaccess',
THIRD_PARTY_PIXEL_SERVICE: '/thirdparty-pixel',
TOWN_SERVICE: '/town',
USER_GROUP_PATTERN_SERVICE: '/usergroup-pattern',
USER_SERVICE: '/user',
USER_VERIFICATION_SERVICE: '/user-verification',
VISIBILITY_PROFILE_SERVICE: '/visibility-profile',
apd: {
members(id) {
const transform = route => `members/${id}/${route}`;
return {
UPLOAD_SERVICE: apdRoute('uploads', transform),
EVENT_SERVICE: apdRoute('events', transform),
};
},
BASE: APD_BASE,
},
};
export default endpoints;
| LukevdPalen/adnxs-api | src/Endpoints.js | JavaScript | mit | 4,574 |
angular.module('ngApp.directives.bbRating', [])
.directive('bbRating', function () {
var MAX = 5;
return {
restrict: 'AE',
replace: true,
scope: {
value: '='
},
templateUrl: 'bbRating/bbRating.tpl.html',
link: function(scope, el, attrs) {
scope.percents = Math.round(scope.value * 100 / MAX);
}
};
})
;
| d42f/swex | ngapp/components/bbRating/bbRating.js | JavaScript | mit | 351 |
define({
root: ({
instruction: "Create the content that displays in this widget.",
defaultContent: "Add text, links, and small graphics here.",
productVersion: "Product version: ",
kernelVersion: "Kernel version: "
}),
"ar": 1,
"bs": 1,
"ca": 1,
"cs": 1,
"da": 1,
"de": 1,
"el": 1,
"es": 1,
"et": 1,
"fi": 1,
"fr": 1,
"he": 1,
"hi": 1,
"hr": 1,
"hu": 1,
"it": 1,
"id": 1,
"ja": 1,
"ko": 1,
"lt": 1,
"lv": 1,
"nb": 1,
"nl": 1,
"pl": 1,
"pt-br": 1,
"pt-pt": 1,
"ro": 1,
"ru": 1,
"sl": 1,
"sr": 1,
"sv": 1,
"th": 1,
"tr": 1,
"uk": 1,
"vi": 1,
"zh-cn": 1,
"zh-hk": 1,
"zh-tw": 1
}); | tmcgee/cmv-wab-widgets | wab/2.14/widgets/About/setting/nls/strings.js | JavaScript | mit | 674 |
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2017 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define(['jquery.sap.global','sap/ui/core/library','./View'],function(q,l,V){"use strict";var a=l.mvc.ViewType;var T=V.extend("sap.ui.core.mvc.TemplateView",{metadata:{library:"sap.ui.core"}});(function(){sap.ui.templateview=function(i,v){return sap.ui.view(i,v,a.Template);};T._sType=a.Template;T.prototype.getControllerName=function(){return this._sControllerName;};T._getViewUrl=function(t){return q.sap.getModulePath(t,".view.tmpl");};T.prototype.initViewSettings=function(s){if(!s){throw new Error("mSettings must be given");}if(!s.viewName){throw new Error("No view name is given.");}this._oTemplate=sap.ui.template({id:this.getId(),src:T._getViewUrl(s.viewName)});this._sControllerName=this._oTemplate._sControllerName;this._oTemplate=this._oTemplate.createControl(undefined,undefined,this);this.addContent(this._oTemplate);};}());return T;});
| Hochfrequenz/aurelia-openui5-bridge | sample/vendor/openui5/sap/ui/core/mvc/TemplateView.js | JavaScript | mit | 1,043 |
'use strict';
exports.init = function(req, res, next){
var sigma = {};
var collections = ['User', 'Account', 'Admin', 'AdminGroup', 'AccountCategory', 'Status'];
var queries = [];
collections.forEach(function(el, i, arr) {
queries.push(function(done) {
req.app.db.models[el].count({}, function(err, count) {
if (err) {
return done(err, null);
}
sigma['count'+ el] = count;
done(null, el);
});
});
});
var asyncFinally = function(err, results) {
if (err) {
return next(err);
}
res.render('jade/admin/index.jade', sigma);
};
require('async').parallel(queries, asyncFinally);
};
| dsalunga/wikitruth | public/templates/jade/admin/index.js | JavaScript | mit | 678 |
import { UserAccount } from '@vue-storefront/core/modules/user/components/UserAccount'
// Component deprecated, now in User module
export default {
name: 'MyProfile',
mixins: [UserAccount]
}
| pkarw/vue-storefront | core/compatibility/components/blocks/MyAccount/MyProfile.js | JavaScript | mit | 197 |
const _ = require('lodash');
const testHelpers = require('@quoin/node-test-helpers');
const utils = require('./utils');
const expect = testHelpers.expect;
describe("lib/utils", () => {
it("should export an object", () => {
expect(utils).to.be.an('object');
});
it("should expose known properties", () => {
const clone = _.clone(utils);
testHelpers.verifyProperties(clone, 'function', [
'basicRender',
'createResource',
'debugReq',
'renderError',
'sendHal'
]);
testHelpers.verifyProperties(clone, 'string', [
'HAL_CONTENT_TYPE'
]);
expect(clone).to.deep.equal({});
});
});
| WarpWorks/studio | lib/utils.unit.test.js | JavaScript | mit | 723 |
var searchData=
[
['port_5ftypes_5fen',['PORT_TYPES_EN',['../_i_o_8h.html#aef5326c2f51b2d56b88ee83510957620',1,'IO.h']]],
['port_5ftypes_5fst',['PORT_TYPES_ST',['../_i_o_8h.html#abcc00397ac4ddbe16561385a7805311d',1,'IO.h']]]
];
| trex2000/Arobs-Academy | Doxygen Generated/html/search/typedefs_2.js | JavaScript | mit | 232 |
/**
* Dual licensed under the Apache License 2.0 and the MIT license.
* $Revision$ $Date: 2009-11-18 10:26:09 +0000 (Wed, 18 Nov 2009) $
*/
(function($) {
// Remap cometd JSON functions to jquery JSON functions
org.cometd.JSON.toJSON = $.toJSON;
org.cometd.JSON.fromJSON = $.secureEvalJSON;
function _setHeaders(xhr, headers) {
if (headers) {
for (var headerName in headers) {
if (headerName.toLowerCase() === 'content-type') {
continue;
}
xhr.setRequestHeader(headerName, headers[headerName]);
}
}
}
// The default cometd instance
$.cometd = new org.cometd.Cometd();
// Remap toolkit-specific transport calls
$.cometd.LongPollingTransport = function() {
this.xhrSend = function(packet) {
return $.ajax({
url: packet.url,
type: 'POST',
contentType: 'application/json',
data: packet.body,
beforeSend: function(xhr) {
_setHeaders(xhr, packet.headers);
//alert(packet.body);
// Returning false will abort the XHR send
return true;
},
success: packet.onSuccess,
error: function(xhr, reason, exception) {
packet.onError(reason, exception);
}
});
};
};
$.cometd.LongPollingTransport.prototype = new org.cometd.LongPollingTransport();
$.cometd.LongPollingTransport.prototype.constructor = $.cometd.LongPollingTransport;
$.cometd.CallbackPollingTransport = function() {
this.jsonpSend = function(packet) {
$.ajax({
url: packet.url,
type: 'GET',
dataType: 'jsonp',
jsonp: 'jsonp',
data: {
// In callback-polling, the content must be sent via the 'message' parameter
message: packet.body
},
beforeSend: function(xhr) {
_setHeaders(xhr, packet.headers);
// Returning false will abort the XHR send
return true;
},
success: packet.onSuccess,
error: function(xhr, reason, exception) {
packet.onError(reason, exception);
}
});
};
};
$.cometd.CallbackPollingTransport.prototype = new org.cometd.CallbackPollingTransport();
$.cometd.CallbackPollingTransport.prototype.constructor = $.cometd.CallbackPollingTransport;
$.cometd.registerTransport('long-polling', new $.cometd.LongPollingTransport());
$.cometd.registerTransport('callback-polling', new $.cometd.CallbackPollingTransport());
})(jQuery);
| Apathak-tba/ApathakMailTest | eSignal/OpenBeast/js/jquery.cometd.js | JavaScript | mit | 2,891 |
var global_navigation_data = [
{
"id": "downloads",
"items": [
{
"link": "http://software.opensuse.org/",
"image": "release-stable",
"title": "Última versión estable",
"desc": "Get the latest stable release of openSUSE"
},
{
"link": "http://software.opensuse.org/developer/",
"image": "release-devel",
"title": "Última versión de desarrollo",
"desc": "Descargue la última versión de desarrollo de openSUSE"
},
{
"link": "http://software.opensuse.org/",
"image": "packages",
"title": "Buscar paquetes",
"desc": "Buscar e instalar paquetes adicionales del openSUSE Build Service"
},
{
"link": "http://en.opensuse.org/Derivatives",
"image": "derivatives",
"title": "Derivados",
"desc": "Obtenga una de las distribuciones especializadas de openSUSE"
}
]
},
{
"id": "support",
"items": [
{
"link": "http://en.opensuse.org/Portal:Support",
"image": "help",
"title": "Ayuda",
"desc": "Ir al portal de ayuda"
},
{
"link": "http://doc.opensuse.org",
"image": "development-documentation",
"title": "Documentación ",
"desc": "Lea las guías y manuales"
},
{
"link": "http://en.opensuse.org/",
"image": "wiki",
"title": "Wiki",
"desc": "Leer y escribir artículos en nuestro Wiki"
},
{
"link": "http://tube.opensuse.org",
"image": "video",
"title": "Vídeo",
"desc": "Vea varias guías, vídeos y grabaciones de las charlas y presentaciones"
},
{
"link": "http://forums.opensuse.org/",
"image": "forums",
"title": "Foros",
"desc": "Participe en los foros"
},
{
"link": "http://en.opensuse.org/openSUSE:Mailing_lists",
"image": "lists",
"title": "Listas de correo",
"desc": "Suscríbase a las listas de correo y vea sus archivos"
},
{
"link": "http://en.opensuse.org/openSUSE:IRC_list",
"image": "irc",
"title": "Canales de IRC",
"desc": "Comuníquese en línea utilizando el Internet Relay Chat(IRC)"
}
]
},
{
"id": "community",
"items": [
{
"link": "http://connect.opensuse.org/",
"image": "users",
"title": "Connect",
"desc": "Connect with your openSUSE friends"
},
{
"link": "http://planet.opensuse.org/",
"image": "planet",
"title": "Planeta",
"desc": "Ver las entradas de blog agrupadas en un sitio"
},
{
"link": "http://news.opensuse.org/",
"image": "news",
"title": "Noticias",
"desc": "Ultimas noticias del equipo"
},
{
"link": "http://lizards.opensuse.org/",
"image": "lizards",
"title": "Lizards",
"desc": "Plataforma de blogs de los usuarios"
},
{
"link": "http://shop.opensuse.org/",
"image": "shop",
"title": "Tienda",
"desc": "¡Aquí hay ropa de openSUSE!"
}
]
},
{
"id": "development",
"items":
[
{
"link": "http://en.opensuse.org/Portal:Development",
"image": "developer",
"title": "Documentación para desarrolladores",
"desc": "Documentación para desarrolladores centralizada"
},
{
"link": "http://features.opensuse.org/",
"image": "features",
"title": "Prestaciones",
"desc": "Vote y trabaje en las nuevas prestaciones de openSUSE"
},
{
"link": "http://build.opensuse.org/",
"image": "buildservice",
"title": "Build Service",
"desc": "Cree, fabrique y mejore los paquetes"
},
{
"link": "http://bugs.opensuse.org/",
"image": "bugs",
"title": "Fallos",
"desc": "Informar de fallos usando Bugzilla"
},
{
"link": "http://susestudio.com",
"image": "studio",
"title": "SUSE Studio",
"desc": "Cree sus propias imágenes usando Studio "
}
]
}
];
| marguerite/bento | js/l10n/global-navigation-data-es.js | JavaScript | mit | 3,700 |
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See http://js.arcgis.com/3.17/esri/copyright.txt for details.
//>>built
define("esri/dijit/metadata/nls/es/i18nBase",{general:{cancel:"Cancelar",close:"Cerrar",none:"Ninguno",ok:"Aceptar",other:"Otro",stamp:"Estampar",now:"Ahora",choose:"Elige uno:"},editor:{noMetadata:"No hay metadatos para este elemento.",xmlViewOnly:"El editor no admite el tipo de metadatos asociado con este elemento. Los metadatos deben estar en formato para ArcGIS.",editorDialog:{caption:"Metadatos",captionPattern:"Metadatos para {title}"},primaryToolbar:{view:"Ver",viewXml:"Ver XML",edit:"Edici\u00f3n",
initializing:"Cargando...",startingEditor:"Iniciando editor...",loadingDocument:"Cargando documento...",updatingDocument:"Actualizando documento...",generatingView:"Generando vista...",errors:{errorGeneratingView:"Se ha producido un error al generar la vista.",errorLoadingDocument:"Se ha producido un error al cargar el documento."}},changesNotSaved:{prompt:"El documento tiene cambios que no se han guardado.",dialogTitle:"Cerrar editor de metadatos",closeButton:"Cerrar"},download:{caption:"Descargar",
dialogTitle:"Descargar",prompt:"Haz clic aqu\u00ed para descargar el archivo."},load:{caption:"Abierto",dialogTitle:"Abierto",typeTab:"Nuevo documento",fileTab:"Abrir archivo",templateTab:"Una plantilla",itemTab:"Tu elemento",filePrompt:"Selecciona un archivo XML de metadatos de ArcGIS. Los metadatos deben estar en formato para ArcGIS.",templatePrompt:"Crear metadatos",pullItem:"Rellena los metadatos con detalles del elemento.",importWarning:"El archivo seleccionado no parece estar en formato para ArcGIS. Los metadatos cargados deben estar en formato para ArcGIS.",
loading:"Cargando...",noMetadata:"Se pueden crear metadatos para este elemento seleccionado una de las siguientes opciones.",unrecognizedMetadata:"El editor no admite el tipo de metadatos asociado con este elemento. Se pueden crear metadatos compatibles seleccionando una de las siguientes opciones.",errorLoading:"Error al cargar.",warnings:{badFile:"El archivo seleccionado no pudo cargarse.",notAnXml:"El archivo seleccionado no es un archivo XML.",notSupported:"Este tipo de archivo no es compatible."}},
save:{caption:"Guardar",dialogTitle:"Guardar metadatos",working:"Guardando metadatos...",errorSaving:"Se ha producido un error y los metadatos no se han guardado.",saveDialog:{pushCaption:"Aplicar cambios al elemento"}},saveAndClose:{caption:"Guardar y cerrar"},saveDraft:{caption:"Guardar copia local",dialogTitle:"Guardar copia local"},validate:{caption:"Validar",dialogTitle:"Validaci\u00f3n",docIsValid:"El documento es v\u00e1lido."},del:{caption:"Eliminar",dialogTitle:"Eliminar metadatos",prompt:"\u00bfEst\u00e1s seguro de que deseas eliminar estos metadatos?",
working:"Eliminando metadatos...",errorDeleting:"Se ha producido un error y los metadatos no se han eliminado."},transform:{caption:"Transformar",dialogTitle:"Transformar en",prompt:"",working:"Transformando...",errorTransforming:"Se ha producido un error al transformar el documento."},errorDialog:{dialogTitle:"Se ha producido un error"}},arcgis:{portal:{metadataButton:{caption:"Metadatos"}}},calendar:{button:"Calendario...",title:"Calendario"},geoExtent:{button:"Establecer extensi\u00f3n geogr\u00e1fica...",
title:"Extensi\u00f3n geogr\u00e1fica",navigate:"Navegar",draw:"Dibujar un rect\u00e1ngulo",drawHint:"Mant\u00e9n presionado para comenzar y suelta para finalizar."},hints:{date:"(aaaa o aaaa-mm o aaaa-mm-dd)",dateTime:"(aaaa-mm-ddThh:mm:ss.sss[+-]hh:mm)",dateOrDateTime:"(aaaa o aaaa-mm o aaaa-mm-dd o aaaa-mm-ddThh:mm:ss.sss[+-]hh:mm)",delimitedTextArea:"(usa coma o l\u00ednea nueva para separar)",fgdcDate:"(aaaa o aaaa-mm o aaaa-mm-dd)",fgdcTime:"(hh:mm:ss.sss[+-]hh:mm)",integer:"(introduce un entero)",
latitude:"(grados decimales)",longitude:"(grados decimales)",number:"(introduce un n\u00famero)",numberGreaterThanZero:"(introduzca un n\u00famero \x3e 0)"},isoTopicCategoryCode:{caption:"Categor\u00eda de tema",boundaries:"L\u00edmites administrativos y pol\u00edticos",farming:"Agricultura y ganader\u00eda",climatologyMeteorologyAtmosphere:"Atm\u00f3sfera y clima",biota:"Biolog\u00eda y ecolog\u00eda",economy:"Negocios y econom\u00eda",planningCadastre:"Catastro",society:"Cultura, sociedad y demograf\u00eda",
elevation:"Elevaci\u00f3n y productos derivados",environment:"Medioambiente y protecci\u00f3n",structure:"Infraestructuras y estructuras",geoscientificInformation:"Geolog\u00eda y geof\u00edsica",health:"Salud humana y enfermedades",imageryBaseMapsEarthCover:"Im\u00e1genes y mapas base",inlandWaters:"Recursos de aguas continentales",location:"Ubicaciones y redes geod\u00e9sicas",intelligenceMilitary:"Asuntos militares",oceans:"Oc\u00e9anos y estuarios",transportation:"Redes de transporte",utilitiesCommunication:"Suministros y comunicaci\u00f3n"},
multiplicity:{moveElementDown:"Bajar la secci\u00f3n",moveElementUp:"Subir la secci\u00f3n",removeElement:"Eliminar la secci\u00f3n",repeatElement:"Repetir la secci\u00f3n"},optionalNode:{switchTip:"Incluir o excluir esta secci\u00f3n."},serviceTypes:{featureService:"Servicio de entidades",mapService:"Servicio de mapas",imageService:"Imagen Servicio",wms:"WMS",wfs:"WFS (servidor de entidades web)",wcs:"WCS"},validation:{pattern:"{label} - {message}",patternWithHint:"{label} - {message} {hint}",ok:"Aceptar",
empty:"Se requiere un valor.",date:"El valor debe ser una fecha.",integer:"El valor debe ser un entero.",number:"El valor debe ser un n\u00famero.",other:"Valor no v\u00e1lido."},validationPane:{clearMessages:"Borrar mensajes",prompt:"(Haz clic en cada mensaje a continuaci\u00f3n y proporciona la informaci\u00f3n requerida en el campo que se indique)"}}); | darklilium/Factigis_2 | arcgis_js_api/library/3.17/3.17compact/esri/dijit/metadata/nls/es/i18nBase.js | JavaScript | mit | 5,788 |
/* *
*
* (c) 2009-2019 Øystein Moseng
*
* Class that can keep track of elements added to DOM and clean them up on
* destroy.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../../parts/Globals.js';
var doc = H.win.document;
import U from '../../../parts/Utilities.js';
var extend = U.extend;
import HTMLUtilities from './htmlUtilities.js';
var removeElement = HTMLUtilities.removeElement;
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* @private
* @class
*/
var DOMElementProvider = function () {
this.elements = [];
};
extend(DOMElementProvider.prototype, {
/**
* Create an element and keep track of it for later removal.
* Same args as document.createElement
* @private
*/
createElement: function () {
var el = doc.createElement.apply(doc, arguments);
this.elements.push(el);
return el;
},
/**
* Destroy all created elements, removing them from the DOM.
* @private
*/
destroyCreatedElements: function () {
this.elements.forEach(function (element) {
removeElement(element);
});
this.elements = [];
}
});
export default DOMElementProvider;
| cdnjs/cdnjs | ajax/libs/highcharts/8.0.0/es-modules/modules/accessibility/utils/DOMElementProvider.js | JavaScript | mit | 1,299 |
import _extends from "@babel/runtime/helpers/extends";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
var _excluded = ["getRef", "content", "children", "onShownChange", "shown", "showDelay", "hideDelay"];
import { createScopedElement } from "../../lib/jsxRuntime";
import * as React from "react";
import { Popper } from "../Popper/Popper";
import { useEventListener } from "../../hooks/useEventListener";
import { useTimeout } from "../../hooks/useTimeout";
import { usePatchChildrenRef } from "../../hooks/usePatchChildrenRef";
import { useIsomorphicLayoutEffect } from "../../lib/useIsomorphicLayoutEffect";
export var HoverPopper = function HoverPopper(_ref) {
var getRef = _ref.getRef,
content = _ref.content,
children = _ref.children,
onShownChange = _ref.onShownChange,
_shown = _ref.shown,
showDelay = _ref.showDelay,
_ref$hideDelay = _ref.hideDelay,
hideDelay = _ref$hideDelay === void 0 ? 150 : _ref$hideDelay,
restProps = _objectWithoutProperties(_ref, _excluded);
var _React$useState = React.useState(_shown || false),
_React$useState2 = _slicedToArray(_React$useState, 2),
computedShown = _React$useState2[0],
setComputedShown = _React$useState2[1];
var shown = typeof _shown === "boolean" ? _shown : computedShown;
var setShown = function setShown(value) {
if (typeof _shown !== "boolean") {
setComputedShown(value);
}
typeof onShownChange === "function" && onShownChange(value);
};
var showTimeout = useTimeout(function () {
setShown(true);
}, showDelay);
var hideTimeout = useTimeout(function () {
setShown(false);
}, hideDelay);
var _usePatchChildrenRef = usePatchChildrenRef(children),
_usePatchChildrenRef2 = _slicedToArray(_usePatchChildrenRef, 2),
childRef = _usePatchChildrenRef2[0],
child = _usePatchChildrenRef2[1];
var onTargetEnter = function onTargetEnter() {
hideTimeout.clear();
showTimeout.set();
};
var onTargetLeave = function onTargetLeave() {
showTimeout.clear();
hideTimeout.set();
};
var targetEnterListener = useEventListener("pointerenter", onTargetEnter);
var targetLeaveListener = useEventListener("pointerleave", onTargetLeave);
useIsomorphicLayoutEffect(function () {
targetEnterListener.add(childRef.current);
targetLeaveListener.add(childRef.current);
}, []);
return createScopedElement(React.Fragment, null, child, shown && createScopedElement(Popper, _extends({}, restProps, {
onMouseOver: hideTimeout.clear,
onMouseOut: onTargetLeave,
getRef: getRef,
targetRef: childRef
}), content));
};
//# sourceMappingURL=HoverPopper.js.map | cdnjs/cdnjs | ajax/libs/vkui/4.24.0/cssm/components/HoverPopper/HoverPopper.js | JavaScript | mit | 2,780 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ValidationController = undefined;
var _dec, _class;
var _aureliaDependencyInjection = require('aurelia-dependency-injection');
var _validator = require('./validator');
var _validateTrigger = require('./validate-trigger');
var _propertyInfo = require('./property-info');
var ValidationController = exports.ValidationController = (_dec = (0, _aureliaDependencyInjection.inject)(_validator.Validator), _dec(_class = function () {
function ValidationController(validator) {
this.bindings = new Map();
this.renderers = [];
this.validateTrigger = _validateTrigger.validateTrigger.blur;
this.validator = validator;
}
ValidationController.prototype.addRenderer = function addRenderer(renderer) {
for (var _iterator = this.bindings.values(), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var _ref2 = _ref;
var target = _ref2.target;
var errors = _ref2.errors;
for (var i = 0, ii = errors.length; i < ii; i++) {
renderer.render(errors[i], target);
}
}
this.renderers.push(renderer);
};
ValidationController.prototype.removeRenderer = function removeRenderer(renderer) {
for (var _iterator2 = this.bindings.values(), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref3;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref3 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref3 = _i2.value;
}
var _ref4 = _ref3;
var target = _ref4.target;
var errors = _ref4.errors;
for (var i = 0, ii = errors.length; i < ii; i++) {
renderer.unrender(errors[i], target);
}
}
this.renderers.splice(this.renderers.indexOf(renderer), 1);
};
ValidationController.prototype.registerBinding = function registerBinding(binding, target) {
var rules = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];
var errors = [];
this.bindings.set(binding, { target: target, rules: rules, errors: errors });
};
ValidationController.prototype.unregisterBinding = function unregisterBinding(binding) {
this._resetBinding(binding);
this.bindings.delete(binding);
};
ValidationController.prototype.validate = function validate() {
var errors = [];
for (var _iterator3 = this.bindings.keys(), _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
var _ref5;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref5 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref5 = _i3.value;
}
var binding = _ref5;
errors.splice.apply(errors, [errors.length, 0].concat(this._validateBinding(binding)));
}
return errors;
};
ValidationController.prototype.reset = function reset() {
for (var _iterator4 = this.bindings.keys(), _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) {
var _ref6;
if (_isArray4) {
if (_i4 >= _iterator4.length) break;
_ref6 = _iterator4[_i4++];
} else {
_i4 = _iterator4.next();
if (_i4.done) break;
_ref6 = _i4.value;
}
var binding = _ref6;
this._resetBinding(binding);
}
};
ValidationController.prototype._renderError = function _renderError(error, target) {
var renderers = this.renderers;
var i = renderers.length;
while (i--) {
renderers[i].render(error, target);
}
};
ValidationController.prototype._unrenderError = function _unrenderError(error, target) {
var renderers = this.renderers;
var i = renderers.length;
while (i--) {
renderers[i].unrender(error, target);
}
};
ValidationController.prototype._updateErrors = function _updateErrors(errors, newErrors, target) {
var error = void 0;
while (error = errors.pop()) {
this._unrenderError(error, target);
}
for (var i = 0, ii = newErrors.length; i < ii; i++) {
error = newErrors[i];
errors.push(error);
this._renderError(error, target);
}
};
ValidationController.prototype._validateBinding = function _validateBinding(binding) {
var _bindings$get = this.bindings.get(binding);
var target = _bindings$get.target;
var rules = _bindings$get.rules;
var errors = _bindings$get.errors;
var _getPropertyInfo = (0, _propertyInfo.getPropertyInfo)(binding.sourceExpression, binding.source);
var object = _getPropertyInfo.object;
var property = _getPropertyInfo.property;
var newErrors = this.validator.validateProperty(object, property, rules);
this._updateErrors(errors, newErrors, target);
return errors;
};
ValidationController.prototype._resetBinding = function _resetBinding(binding) {
var _bindings$get2 = this.bindings.get(binding);
var target = _bindings$get2.target;
var errors = _bindings$get2.errors;
this._updateErrors(errors, [], target);
};
return ValidationController;
}()) || _class); | Zensavona/validation | dist/commonjs/validation-controller.js | JavaScript | cc0-1.0 | 5,608 |
define([
'redux',
'js/widgets/facet/actions',
'js/widgets/facet/reducers',
'js/widgets/facet/create_store',
'js/wraps/author_facet',
'js/bugutils/minimal_pubsub',
'react',
'react-dom',
], function(
Redux,
Actions,
Reducers,
createStore,
AuthorFacet,
MinSub,
React,
ReactDOM
) {
describe('FacetWidget', function() {
var sampleResponse = {
responseHeader: {
status: 0,
QTime: 18,
params: {
'facet.limit': '25',
q: 'author:"accomazzi,a"',
'facet.field': 'author_facet_hier',
fl: 'id',
'facet.prefix': '0/',
sort: 'date desc',
'facet.mincount': '1',
facet: 'true',
wt: 'json',
'facet.offset': '0',
},
},
response: {
numFound: 186,
start: 0,
docs: [
{
id: '11310415',
},
{
id: '11266285',
},
{
id: '11121250',
},
{
id: '11057812',
},
],
},
facet_counts: {
facet_queries: {},
facet_fields: {
author_facet_hier: [
'0/Accomazzi, A',
186,
'0/Kurtz, M',
151,
'0/Grant, C',
146,
'0/Murray, S',
142,
],
},
facet_dates: {},
facet_ranges: {},
},
};
afterEach(function() {
document.querySelector('#test').innerHTML = '';
});
it('should have the appropriate default state given individual widget presets', function() {
var store = createStore();
expect(JSON.stringify(store.getState())).to.eql(
JSON.stringify({
config: {
preprocessors: [],
hierMaxLevels: 1,
openByDefault: false,
},
state: {
open: false,
visible: 5,
selected: [],
},
pagination: {
finished: false,
},
children: [],
facets: {},
})
);
//now provide it with author config
var widget = AuthorFacet();
//ensure that the config object is located in each widget's store rather than on the widget object itself
expect(Object.keys(widget.store.getState())).to.eql([
'config',
'state',
'pagination',
'children',
'facets',
]);
expect(JSON.stringify(widget.store.getState())).to.eql(
JSON.stringify({
config: {
preprocessors: [],
hierMaxLevels: 2,
facetField: 'author_facet_hier',
openByDefault: true,
facetTitle: 'Authors',
logicOptions: {
single: ['limit to', 'exclude'],
multiple: ['and', 'or', 'exclude'],
},
},
state: {
open: false,
visible: 5,
selected: [],
},
pagination: {
finished: false,
},
children: [],
facets: {},
})
);
});
it('should handle data request and response events properly', function() {
var widget = AuthorFacet();
widget.store.dispatch(Actions().data_requested());
//only pagination "loading" key is changed
expect(
JSON.stringify(_.pick(widget.store.getState(), 'state', 'pagination'))
).to.eql(
JSON.stringify({
state: {
open: false,
visible: 5,
selected: [],
},
pagination: {
state: 'loading',
finished: false,
},
})
);
widget.store.dispatch(Actions().data_received(sampleResponse));
expect(JSON.stringify(widget.store.getState())).to.eql(
JSON.stringify({
config: {
preprocessors: [],
hierMaxLevels: 2,
facetField: 'author_facet_hier',
openByDefault: true,
facetTitle: 'Authors',
logicOptions: {
single: ['limit to', 'exclude'],
multiple: ['and', 'or', 'exclude'],
},
},
state: {
open: false,
visible: 5,
selected: [],
},
pagination: {
state: 'success',
finished: true,
},
children: [
'0/Accomazzi, A',
'0/Kurtz, M',
'0/Grant, C',
'0/Murray, S',
],
facets: {
'0/Accomazzi, A': {
name: 'Accomazzi, A',
value: '0/Accomazzi, A',
count: 186,
pagination: {
finished: false,
},
children: [],
state: {
open: false,
visible: 5,
selected: [],
},
},
'0/Kurtz, M': {
name: 'Kurtz, M',
value: '0/Kurtz, M',
count: 151,
pagination: {
finished: false,
},
children: [],
state: {
open: false,
visible: 5,
selected: [],
},
},
'0/Grant, C': {
name: 'Grant, C',
value: '0/Grant, C',
count: 146,
pagination: {
finished: false,
},
children: [],
state: {
open: false,
visible: 5,
selected: [],
},
},
'0/Murray, S': {
name: 'Murray, S',
value: '0/Murray, S',
count: 142,
pagination: {
finished: false,
},
children: [],
state: {
open: false,
visible: 5,
selected: [],
},
},
},
})
);
//now test fetching data for child facet
widget.store.dispatch(Actions().data_requested('0/Accomazzi, A'));
expect(
JSON.stringify(widget.store.getState().facets['0/Accomazzi, A'])
).to.eql(
JSON.stringify({
name: 'Accomazzi, A',
value: '0/Accomazzi, A',
count: 186,
pagination: {
state: 'loading',
finished: false,
},
children: [],
state: {
open: false,
visible: 5,
selected: [],
},
})
);
//test hierarchical facet data received
widget.store.dispatch(
Actions().data_received(sampleResponse, '0/Accomazzi, A')
);
expect(
JSON.stringify(widget.store.getState().facets['0/Accomazzi, A'])
).to.eql(
JSON.stringify({
name: 'Accomazzi, A',
value: '0/Accomazzi, A',
count: 186,
pagination: {
state: 'success',
finished: true,
},
children: [
'0/Accomazzi, A',
'0/Kurtz, M',
'0/Grant, C',
'0/Murray, S',
],
state: {
open: false,
visible: 5,
selected: [],
},
})
);
});
it('should only set the finished param in the pagination state if fewer facets return than were requested', function() {
var widget = AuthorFacet();
var shortResponse = _.cloneDeep(sampleResponse);
//should return only 5 facets instead of the requested 25
shortResponse.facet_counts.facet_fields.author_facet_hier = shortResponse.facet_counts.facet_fields.author_facet_hier.slice(
0,
10
);
widget.store.dispatch(Actions().data_received(shortResponse));
expect(JSON.stringify(widget.store.getState().pagination)).to.eql(
JSON.stringify({
state: 'success',
finished: true,
})
);
//finished = true got set bc response number was < 25
//now mock a longer response
var widget = AuthorFacet();
var longResponse = _.cloneDeep(sampleResponse);
//representing 25 responses
longResponse.facet_counts.facet_fields.author_facet_hier = _.range(
50
).map(function(n) {
if (n % 2 === 0) {
return '0/fake name';
} else {
return 5;
}
});
widget.store.dispatch(Actions().data_received(longResponse));
expect(JSON.stringify(widget.store.getState().pagination)).to.eql(
JSON.stringify({
state: 'success',
finished: false,
})
);
});
it("should mediate requests/responses through the widget's connection with pub sub", function() {
var longResponse = _.cloneDeep(sampleResponse);
//representing 25 responses
longResponse.facet_counts.facet_fields.author_facet_hier = _.range(
40
).map(function(n) {
if (n % 2 === 0) {
return '0/fake name';
} else {
return 5;
}
});
var minsub = new (MinSub.extend({
request: sinon.spy(),
}))({
verbose: false,
});
var widget = AuthorFacet({ debug: true });
widget.activate(minsub.beehive.getHardenedInstance());
//set in some initial data
widget.store.dispatch(widget.actions.data_received(longResponse));
//request
minsub.publish(
minsub.INVITING_REQUEST,
new minsub.T.QUERY({
q: 'star',
})
);
//initial data should be totally cleared
expect(Object.keys(widget.store.getState().facets).length).to.eql(0);
//request was made
expect(
JSON.stringify(minsub.request.args[0][0].get('query').toJSON())
).to.eql(
JSON.stringify({
q: ['star'],
facet: ['true'],
'facet.mincount': ['1'],
'facet.limit': [20],
fl: ['id'],
'facet.prefix': ['0/'],
'facet.field': ['author_facet_hier'],
'facet.offset': [0],
rows: [1],
})
);
//facet state was toggled open, since it's open by default
expect(widget.store.getState().state.open).to.be.true;
//response
widget.store.dispatch(widget.actions.data_received(longResponse));
//now test pagination
widget.store.dispatch(widget.actions.fetch_data());
expect(
JSON.stringify(minsub.request.args[1][0].get('query').toJSON())
).to.eql(
JSON.stringify({
q: ['star'],
facet: ['true'],
'facet.mincount': ['1'],
'facet.limit': [20],
fl: ['id'],
'facet.prefix': ['0/'],
'facet.field': ['author_facet_hier'],
'facet.offset': [20],
rows: [1],
})
);
});
it('should fetch the first set of facets automatically when facet or facet child is toggled for the first time', function() {
var store = createStore();
var actions = Actions();
actions.fetch_data = sinon.spy(function() {
return {
type: 'fake',
};
});
expect(actions.fetch_data.callCount).to.eql(0);
expect(store.getState().state).to.eql({
open: false,
visible: 5,
selected: [],
});
store.dispatch(actions.toggle_facet());
expect(actions.fetch_data.callCount).to.eql(1);
expect(store.getState().state).to.eql({
open: true,
visible: 5,
selected: [],
});
store.dispatch(actions.toggle_facet(false));
expect(store.getState().state).to.eql({
open: false,
visible: 5,
selected: [],
});
//now do the same thing, but this time with pre-loaded facets, nothing should be requested
store.dispatch(Actions().data_received(sampleResponse));
store.dispatch(actions.toggle_facet());
expect(store.getState().state).to.eql({
open: true,
visible: 5,
selected: [],
});
expect(actions.fetch_data.callCount).to.eql(1);
});
it('should have an action to totally reset the widget state while maintaining the individual widget config', function() {
var widget = AuthorFacet();
widget.store.dispatch(widget.actions.data_received(sampleResponse));
widget.store.dispatch(widget.actions.reset_state());
expect(JSON.stringify(widget.store.getState())).to.eql(
JSON.stringify({
config: {
preprocessors: [],
hierMaxLevels: 2,
facetField: 'author_facet_hier',
openByDefault: true,
facetTitle: 'Authors',
logicOptions: {
single: ['limit to', 'exclude'],
multiple: ['and', 'or', 'exclude'],
},
},
state: {
open: false,
visible: 5,
selected: [],
},
pagination: {
finished: false,
},
children: [],
facets: {},
})
);
});
it('should automatically open, load and select children of hierarchical facets when they are selected', function() {
var widget = AuthorFacet();
//happens in the view
$('#test').append(widget.render().el);
widget.store.dispatch(widget.actions.data_received(sampleResponse));
var hierarchicalResponse = _.cloneDeep(sampleResponse);
hierarchicalResponse.facet_counts.facet_fields.author_facet_hier = [
'1/Accomazzi, A/Accomazzi, Alberto',
5,
'1/Accomazzi, A/Accomazzi, A A',
10,
];
widget.store.dispatch(
widget.actions.data_received(hierarchicalResponse, '0/Accomazzi, A')
);
//should be closed by default
expect(
$('#test')
.find('.facet__icon:first')
.hasClass('facet__icon--closed')
).to.be.true;
expect(
$('#test')
.find('.facet__icon:first')
.hasClass('facet__icon--open')
).to.be.false;
//open
widget.store.dispatch(widget.actions.toggle_facet());
expect(
$('#test')
.find('.facet__icon:first')
.hasClass('facet__icon--closed')
).to.be.false;
expect(
$('#test')
.find('.facet__icon:first')
.hasClass('facet__icon--open')
).to.be.true;
expect(widget.store.getState().state.selected).to.eql([]);
widget.store.dispatch(widget.actions.select_facet('0/Accomazzi, A'));
expect(widget.store.getState().state.selected).to.eql([
'1/Accomazzi, A/Accomazzi, Alberto',
'1/Accomazzi, A/Accomazzi, A A',
'0/Accomazzi, A',
]);
//but logic dropdown should show as if only 1 choice were selected
expect(
$('#test')
.find('.facet__dropdown button')
.map(function(i, el) {
return el.textContent.trim();
})
.get()
).to.eql(['limit to', 'exclude']);
$('#test').empty();
});
it('should be able to submit facets', function() {
var widget = AuthorFacet();
widget.store.dispatch(widget.actions.data_received(sampleResponse));
widget.store.dispatch(widget.actions.select_facet('0/Accomazzi, A'));
expect(JSON.stringify(widget.store.getState().state)).to.eql(
JSON.stringify({
open: false,
visible: 5,
selected: ['0/Accomazzi, A'],
})
);
widget.store.dispatch(widget.actions.select_facet('0/Kurtz, M'));
expect(JSON.stringify(widget.store.getState().state)).to.eql(
JSON.stringify({
open: false,
visible: 5,
selected: ['0/Accomazzi, A', '0/Kurtz, M'],
})
);
widget.setCurrentQuery(
new MinSub.prototype.T.QUERY({
q: 'star',
})
);
widget.dispatchNewQuery = sinon.spy();
widget.store.dispatch(widget.actions.submit_filter('or'));
expect(JSON.stringify(widget.dispatchNewQuery.args[0][0])).to.eql(
JSON.stringify({
q: ['star'],
fq_author: [
'(author_facet_hier:"0/Accomazzi, A" OR author_facet_hier:"0/Kurtz, M")',
],
filter_author_facet_hier_fq_author: [
'OR',
'author_facet_hier:"0/Accomazzi, A"',
'author_facet_hier:"0/Kurtz, M"',
],
fq: ['{!type=aqp v=$fq_author}'],
})
);
});
it('should have a dropdown that shows the user the appropriate logic options', function() {
var widget = AuthorFacet();
var albertoResponse = _.cloneDeep(sampleResponse);
albertoResponse.facet_counts.facet_fields.author_facet_hier = albertoResponse.facet_counts.facet_fields.author_facet_hier.slice(
0,
2
);
widget.store.dispatch(widget.actions.data_received(albertoResponse));
//now mock a hierarchical child response
var hierarchicalResponse = _.cloneDeep(sampleResponse);
// generate a long list of fake sub alberto names
function randomString(len) {
var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
var s = '';
while (len > 0) {
s += alphabet[Math.floor(Math.random() * 26)];
len -= 1;
}
return s;
}
var hierNames = _.range(100).map(function(n, i) {
if (i % 2 !== 0) return 5;
return '1/Accomazzi, A/' + randomString(12);
});
hierarchicalResponse.facet_counts.facet_fields.author_facet_hier = hierNames;
widget.store.dispatch(
widget.actions.data_received(hierarchicalResponse, '0/Accomazzi, A')
);
$('#test').append(widget.render().el);
widget.store.dispatch(widget.actions.toggle_facet());
widget.store.dispatch(widget.actions.toggle_facet('0/Accomazzi, A'));
//mimicking the user pushing the 'more' button a bunch of times
widget.store.dispatch(widget.actions.increase_visible('0/Accomazzi, A'));
widget.store.dispatch(widget.actions.increase_visible('0/Accomazzi, A'));
widget.store.dispatch(widget.actions.increase_visible('0/Accomazzi, A'));
widget.store.dispatch(widget.actions.increase_visible('0/Accomazzi, A'));
//select 2 facets
Object.keys(widget.store.getState().facets)
.slice(2, 4)
.forEach(function(id) {
widget.store.dispatch(widget.actions.select_facet(id));
});
expect(
[].slice
.apply(document.querySelectorAll('.facet__dropdown button'))
.map(function(l) {
return l.textContent.trim();
})
).to.eql(['and', 'or', 'exclude']);
//select the parent (Just 'Alberto, A')
widget.store.dispatch(widget.actions.select_facet('0/Accomazzi, A'));
//this should select all the ~~VISIBLE~~ children
expect(
widget.store.getState().facets['0/Accomazzi, A'].state.visible
).to.eql(25);
expect(widget.store.getState().state.selected.length).to.eql(26);
expect(
[].slice
.apply(document.querySelectorAll('.facet__dropdown button'))
.map(function(l) {
return l.textContent.trim();
})
).to.eql(['limit to', 'exclude']);
// now showing 30 facets
widget.store.dispatch(widget.actions.increase_visible('0/Accomazzi, A'));
//now deselect one of the facets
Object.keys(widget.store.getState().facets)
.slice(2, 3)
.forEach(function(id) {
widget.store.dispatch(widget.actions.unselect_facet(id));
});
expect(document.querySelector('.facet__dropdown').textContent).to.eql(
'select no more than 25 facets at a time'
);
});
it('should only submit necessary facets on submit (for hierarchical facets, avoid sending children)', function() {
var widget = AuthorFacet();
widget.store.dispatch(widget.actions.data_received(sampleResponse));
//now mock a hierarchical child response
var hierarchicalResponse = _.cloneDeep(sampleResponse);
hierarchicalResponse.facet_counts.facet_fields.author_facet_hier = [
'1/Accomazzi, A/Accomazzi, Alberto',
5,
'1/Accomazzi, A/Accomazzi, A A',
10,
];
widget.store.dispatch(
widget.actions.data_received(hierarchicalResponse, '0/Accomazzi, A')
);
expect(widget.store.getState().facets['0/Accomazzi, A'].children).to.eql([
'1/Accomazzi, A/Accomazzi, Alberto',
'1/Accomazzi, A/Accomazzi, A A',
]);
widget.store.dispatch(widget.actions.select_facet('0/Accomazzi, A'));
//should contain parent AND children
expect(widget.store.getState().state.selected).to.eql([
'1/Accomazzi, A/Accomazzi, Alberto',
'1/Accomazzi, A/Accomazzi, A A',
'0/Accomazzi, A',
]);
widget.setCurrentQuery(
new MinSub.prototype.T.QUERY({
q: 'star',
})
);
widget.dispatchNewQuery = sinon.spy();
widget.submitFilter('and');
//only submitting parent
expect(JSON.stringify(widget.dispatchNewQuery.args[0][0])).to.eql(
JSON.stringify({
q: ['star'],
fq_author: ['(author_facet_hier:"0/Accomazzi, A")'],
filter_author_facet_hier_fq_author: [
'AND',
'author_facet_hier:"0/Accomazzi, A"',
],
fq: ['{!type=aqp v=$fq_author}'],
})
);
});
});
});
| adsabs/bumblebee | test/mocha/js/widgets/facet_widget.spec.js | JavaScript | gpl-2.0 | 21,732 |
//
// Copyright (c) 2012-2013, Peter Jekel
// All rights reserved.
//
// The Checkbox Tree (cbtree) is released under to following three licenses:
//
// 1 - BSD 2-Clause (http://thejekels.com/cbtree/LICENSE)
// 2 - The "New" BSD License (http://trac.dojotoolkit.org/browser/dojo/trunk/LICENSE#L13)
// 3 - The Academic Free License (http://trac.dojotoolkit.org/browser/dojo/trunk/LICENSE#L43)
//
define([], function () {
"use strict";
// module:
// cbtree/model/_base/Prologue
// summary:
var undef;
function Prologue (/*Object*/ object,/*Store.PutDirectives*/ options) {
// summary:
// This prologue method is added to the stores add and put methods as before
// advice to provide support for the 'parent' property of store objects and
// to add the store identifier. This method looks for two things:
//
// 1 - First, if the options parameter contains a "parent" property.
// 2 - Second, if the store has a "hierarchical" property.
//
// If the store has the 'hierarchical' property it is assumed the store
// will handle the assignment of the objects parent property otherwise
// this prologue method will take care of it onbehalf of the store.
//
// NOTE: The prologue method is executed in the context of the store thus
// the 'this' object is the store itself.
// object:
// The object to store.
// options:
// Additional metadata for storing the object which may include a 'parent'
// property.
// tag:
// Private, Advice
function setParentId(/*Object*/ object,/*Store.PutDirectives?*/ options) {
// summary:
// Set the parent property of a store object.
// object:
// The object to store.
// tag:
// Private
var objectId = this.getIdentity(object);
var parents = options.parent;
var parentId, np = [];
var undef, i;
if (parents instanceof Array) {
for (i=0; i<parents.length; i++) {
if (parentId = this.getIdentity(parents[i])) {
if (parentId != objectId && np.indexOf(parentId) == -1) {
np ? np.push(parentId) : np = [parentId];
}
}
}
} else {
if (parentId = this.getIdentity(parents)) {
if (parentId != objectId) {
np = parentId;
}
} else {
np = undef;
}
}
return np;
} /* end setParentId() */
if (options && options.parent && this.hierarchical !== true) {
object[this.parentProperty] = setParentId.call(this, object, options);
}
}
return Prologue;
});
| nextgis/nextgisbio | nextgisbio/static/js/lib/cbtree-v0.9.4-0/model/_base/Prologue.js | JavaScript | gpl-2.0 | 2,481 |
/**
* Created by Bozhidar on 23.12.2014
* Contains the login and create new user functionality
*/
"use strict";
var userEngine = require('../engine/core.userEngine'),
userValidations = require('../engine/core.engine.validations').userValidations;
exports.login = function(redisClient, secret){
return function(req, res){
console.log(req.body);
console.log(req.headers);
var loginInformation = req.body.loginInformation;
userEngine.login(loginInformation, redisClient)
.then(function(token){
res.json({ token: token });
res.status(200);
res.send(token);
})
.catch(function(err){
res.status(401);
res.send(err);
});
}
};
exports.createNewUser = function(req, res){
var userObject = req.body.user;
if(typeof userObject === 'undefined') {
res.status(500).send('Invalid user context');
}
if(userValidations.validatePassword(userObject['password']) === false){
res.status(500).send("Password is not secure enough!");
}
userEngine.createUser(userObject)
.then(function(context){
res.status(200).send("New user successfully created!");
})
.catch(function(error){
res.status(500).send('User failed to register');
});
}; | mvladimirova/Chronos-refactor | core/routes/login.js | JavaScript | gpl-2.0 | 1,386 |
var gId = '#dataGrid';
$(document).ready(function(){
//列表
$(gId).datagrid({
url:getUrlOpt(),
idField:'id',
fitColumns:true,
frozenColumns:[[
{field:'ck',checkbox:true}
]],
columns:[
getTableHeadOpt(),
getColumnsOpt()
],
pageSize:20,
rownumbers:true,
pagination:true,
loadMsg:'数据装载中...',
toolbar:getToolBarOpt()
});
//分页区
$(gId).datagrid('getPager').pagination(getPagerOpt());
//弹出框
$('#edit').dialog({
title:"添加或编辑栏位",
iconCls:'icon-edit',
closed:true,
modal:true,
draggable:true,
minimizable:false,
maximizable:false,
resizable:false,
toolbar:[{
text:'保存',
iconCls:'icon-save',
handler:function(){
editDataPage.submitForm();
}
}]
});
});
//获取表头参数
function getTableHeadOpt(){
var opt = [];
var operate = '';
opt.push({title:'基本信息',colspan:4});
if('' == todo){
opt.push(
{field:'opt',title:'操作',width:25,align:'left', rowspan:2,
formatter:function(value,rowData,rowIndex){
var html = '';
operate = '编辑';
if('' == todo){
html = '<a href="javascript:void(0)" onclick="editData(\''+rowData.id+'\');">'+operate+'</a>';
html += ' <a href="javascript:void(0)" onclick="deleteData(\''+rowData.id+'\');">删除</a>';
}
return html;
}
}
);
}
return opt;
}
//获取列头参数
function getColumnsOpt(){
var opt = [
{field:'columnNo',title:'栏位编号',width:20,align:'left'},
{field:'name',title:'栏位名称',width:25,align:'left'},
{field:'describes',title:'栏位描述',width:25,align:'left'},
{field:'remark',title:'备注',width:25,align:'left'}
];
return opt;
}
//Json加载数据路径
function getUrlOpt(){
var url = ctx+'/Promotecolumn_json!listJosn.do';
return url;
}
//添加工具条
function getToolBarOpt(){
var opt=[];
if($("#loginname").val()=='Admin'&&todo=='')
{
opt = [{
text:'新增',
iconCls:'icon-add',
handler:function(){
editData('');
}
}];
}
if('show' == todo){
opt = [{
text:'选择',
iconCls:'icon-ok',
handler:function(){
var rowArrs = $(gId).datagrid('getSelections');
if(rowArrs){
window.returnValue = rowArrs[0];
window.close();
}else{
alert('请选择');
}
}
}];
}
return opt;
}
//编辑数据
function editData(id){
var title='';
var url = ctx+'/promotecolumn!edit.do?1=1';
if(id != ''){
url += '&promotecolumn.id='+id;
}
$('#edit').window('open');
$('#editDataPage').attr('src',url);
}
function deleteData(id){
if(confirm('你确定要删除吗?')){
$.ajax({
type: "POST",
async: false,
cache: false,
url: ctx+"/promotecolumn!delete.do?1=1",
data: "promotecolumn.id=" + id,
success : function(returnData){
if(returnData == 'true'){
alert('删除成功!');
reloadDataGrid();
}else{
alert('删除失败!');
}
},
error : function(){
alert('系统错误!');
}
});
}
}
//重新加载
function reloadDataGrid(){
$(gId).datagrid('reload');
}
//搜索框检查用户是否按下‘回车键’,按下则调用搜索方法
function checkKey(){
if(event.keyCode=='13'){
searchData();
}
}
//搜索功能
function searchData(){
var code = $("#code").val();
var name = $("#name").val();
realoadGrid(code,name);
}
//清空
function cancelSearch(){
$("#code").val('');
$("#name").val('');
searchData();
}
//确定搜索时重新加载datagrid
function realoadGrid(code,name){
var queryParams = $(gId).datagrid('options').queryParams;
queryParams={"promotecolumn.columnNo":code,"promotecolumn.name":name};
$(gId).datagrid('options').queryParams = queryParams;
$(gId).datagrid('reload');
}
| shenzeyu/3dweb | src/main/webapp/scripts/store/promotecolumn/list_Promotecolumn.js | JavaScript | gpl-2.0 | 3,983 |
/*! jQuery UI - v1.10.4 - 2014-06-26
* http://jqueryui.com
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(e){e.datepicker.regional.ml={closeText:"ശരി",prevText:"മുന്നത്തെ",nextText:"അടുത്തത് ",currentText:"ഇന്ന്",monthNames:["ജനുവരി","ഫെബ്രുവരി","മാര്ച്ച്","ഏപ്രില്","മേയ്","ജൂണ്","ജൂലൈ","ആഗസ്റ്റ്","സെപ്റ്റംബര്","ഒക്ടോബര്","നവംബര്","ഡിസംബര്"],monthNamesShort:["ജനു","ഫെബ്","മാര്","ഏപ്രി","മേയ്","ജൂണ്","ജൂലാ","ആഗ","സെപ്","ഒക്ടോ","നവം","ഡിസ"],dayNames:["ഞായര്","തിങ്കള്","ചൊവ്വ","ബുധന്","വ്യാഴം","വെള്ളി","ശനി"],dayNamesShort:["ഞായ","തിങ്ക","ചൊവ്വ","ബുധ","വ്യാഴം","വെള്ളി","ശനി"],dayNamesMin:["ഞാ","തി","ചൊ","ബു","വ്യാ","വെ","ശ"],weekHeader:"ആ",dateFormat:"dd/mm/yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional.ml)}); | imie-source/POEC-N-02-SHARE | AJAX_IHM/avant_ajax/personneWeb/WebContent/jquery-ui-1.10.4.custom/development-bundle/ui/minified/i18n/jquery.ui.datepicker-ml.min.js | JavaScript | gpl-2.0 | 1,330 |
/*
Copyright (c) 2004-2008, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dojox.grid.compat._grid.publicEvents"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojox.grid.compat._grid.publicEvents"] = true;
dojo.provide("dojox.grid.compat._grid.publicEvents");
dojox.grid.publicEvents = {
// summary:
// VirtualGrid mixin that provides default implementations for grid events.
// description:
// Default ynthetic events dispatched for VirtualGrid. dojo.connect to events to
// retain default implementation or override them for custom handling.
// cellOverClass: String
// css class to apply to grid cells over which the cursor is placed.
cellOverClass: "dojoxGrid-cell-over",
onKeyEvent: function(e){
// summary: top level handler for Key Events
this.dispatchKeyEvent(e);
},
onContentEvent: function(e){
// summary: Top level handler for Content events
this.dispatchContentEvent(e);
},
onHeaderEvent: function(e){
// summary: Top level handler for header events
this.dispatchHeaderEvent(e);
},
onStyleRow: function(inRow){
// summary:
// Perform row styling on a given row. Called whenever row styling is updated.
//
// inRow: Object
// Object containing row state information: selected, true if the row is selcted; over:
// true of the mouse is over the row; odd: true if the row is odd. Use customClasses and
// customStyles to control row css classes and styles; both properties are strings.
//
// example: onStyleRow({ selected: true, over:true, odd:false })
with(inRow){
customClasses += (odd?" dojoxGrid-row-odd":"") + (selected?" dojoxGrid-row-selected":"") + (over?" dojoxGrid-row-over":"");
}
this.focus.styleRow(inRow);
this.edit.styleRow(inRow);
},
onKeyDown: function(e){
// summary:
// Grid key event handler. By default enter begins editing and applies edits, escape cancels and edit,
// tab, shift-tab, and arrow keys move grid cell focus.
if(e.altKey || e.ctrlKey || e.metaKey){
return;
}
var dk = dojo.keys;
switch(e.keyCode){
case dk.ESCAPE:
this.edit.cancel();
break;
case dk.ENTER:
if(!e.shiftKey){
var isEditing = this.edit.isEditing();
this.edit.apply();
if(!isEditing){
this.edit.setEditCell(this.focus.cell, this.focus.rowIndex);
}
}
break;
case dk.TAB:
this.focus[e.shiftKey ? 'previousKey' : 'nextKey'](e);
break;
case dk.LEFT_ARROW:
case dk.RIGHT_ARROW:
if(!this.edit.isEditing()){
dojo.stopEvent(e);
var offset = (e.keyCode == dk.LEFT_ARROW) ? 1 : -1;
if(dojo._isBodyLtr()){ offset *= -1; }
this.focus.move(0, offset);
}
break;
case dk.UP_ARROW:
if(!this.edit.isEditing() && this.focus.rowIndex != 0){
dojo.stopEvent(e);
this.focus.move(-1, 0);
}
break;
case dk.DOWN_ARROW:
if(!this.edit.isEditing() && this.focus.rowIndex+1 != this.model.count){
dojo.stopEvent(e);
this.focus.move(1, 0);
}
break;
case dk.PAGE_UP:
if(!this.edit.isEditing() && this.focus.rowIndex != 0){
dojo.stopEvent(e);
if(this.focus.rowIndex != this.scroller.firstVisibleRow+1){
this.focus.move(this.scroller.firstVisibleRow-this.focus.rowIndex, 0);
}else{
this.setScrollTop(this.scroller.findScrollTop(this.focus.rowIndex-1));
this.focus.move(this.scroller.firstVisibleRow-this.scroller.lastVisibleRow+1, 0);
}
}
break;
case dk.PAGE_DOWN:
if(!this.edit.isEditing() && this.focus.rowIndex+1 != this.model.count){
dojo.stopEvent(e);
if(this.focus.rowIndex != this.scroller.lastVisibleRow-1){
this.focus.move(this.scroller.lastVisibleRow-this.focus.rowIndex-1, 0);
}else{
this.setScrollTop(this.scroller.findScrollTop(this.focus.rowIndex+1));
this.focus.move(this.scroller.lastVisibleRow-this.scroller.firstVisibleRow-1, 0);
}
}
break;
}
},
onMouseOver: function(e){
// summary:
// Event fired when mouse is over the grid.
// e: Event
// Decorated event object contains reference to grid, cell, and rowIndex
e.rowIndex == -1 ? this.onHeaderCellMouseOver(e) : this.onCellMouseOver(e);
},
onMouseOut: function(e){
// summary:
// Event fired when mouse moves out of the grid.
// e: Event
// Decorated event object that contains reference to grid, cell, and rowIndex
e.rowIndex == -1 ? this.onHeaderCellMouseOut(e) : this.onCellMouseOut(e);
},
onMouseDown: function(e){
// summary:
// Event fired when mouse is down inside grid.
// e: Event
// Decorated event object that contains reference to grid, cell, and rowIndex
e.rowIndex == -1 ? this.onHeaderCellMouseDown(e) : this.onCellMouseDown(e);
},
onMouseOverRow: function(e){
// summary:
// Event fired when mouse is over any row (data or header).
// e: Event
// Decorated event object contains reference to grid, cell, and rowIndex
if(!this.rows.isOver(e.rowIndex)){
this.rows.setOverRow(e.rowIndex);
e.rowIndex == -1 ? this.onHeaderMouseOver(e) : this.onRowMouseOver(e);
}
},
onMouseOutRow: function(e){
// summary:
// Event fired when mouse moves out of any row (data or header).
// e: Event
// Decorated event object contains reference to grid, cell, and rowIndex
if(this.rows.isOver(-1)){
this.onHeaderMouseOut(e);
}else if(!this.rows.isOver(-2)){
this.rows.setOverRow(-2);
this.onRowMouseOut(e);
}
},
onMouseDownRow: function(e){
// summary:
// Event fired when mouse is down inside grid row
// e: Event
// Decorated event object that contains reference to grid, cell, and rowIndex
if(e.rowIndex != -1)
this.onRowMouseDown(e);
},
// cell events
onCellMouseOver: function(e){
// summary:
// Event fired when mouse is over a cell.
// e: Event
// Decorated event object contains reference to grid, cell, and rowIndex
dojo.addClass(e.cellNode, this.cellOverClass);
},
onCellMouseOut: function(e){
// summary:
// Event fired when mouse moves out of a cell.
// e: Event
// Decorated event object which contains reference to grid, cell, and rowIndex
dojo.removeClass(e.cellNode, this.cellOverClass);
},
onCellMouseDown: function(e){
// summary:
// Event fired when mouse is down in a header cell.
// e: Event
// Decorated event object which contains reference to grid, cell, and rowIndex
},
onCellClick: function(e){
// summary:
// Event fired when a cell is clicked.
// e: Event
// Decorated event object which contains reference to grid, cell, and rowIndex
this._click[0] = this._click[1];
this._click[1] = e;
if(!this.edit.isEditCell(e.rowIndex, e.cellIndex)){
this.focus.setFocusCell(e.cell, e.rowIndex);
}
this.onRowClick(e);
},
onCellDblClick: function(e){
// summary:
// Event fired when a cell is double-clicked.
// e: Event
// Decorated event object contains reference to grid, cell, and rowIndex
if(dojo.isIE){
this.edit.setEditCell(this._click[1].cell, this._click[1].rowIndex);
}else if(this._click[0].rowIndex != this._click[1].rowIndex){
this.edit.setEditCell(this._click[0].cell, this._click[0].rowIndex);
}else{
this.edit.setEditCell(e.cell, e.rowIndex);
}
this.onRowDblClick(e);
},
onCellContextMenu: function(e){
// summary:
// Event fired when a cell context menu is accessed via mouse right click.
// e: Event
// Decorated event object which contains reference to grid, cell, and rowIndex
this.onRowContextMenu(e);
},
onCellFocus: function(inCell, inRowIndex){
// summary:
// Event fired when a cell receives focus.
// inCell: Object
// Cell object containing properties of the grid column.
// inRowIndex: Integer
// Index of the grid row
this.edit.cellFocus(inCell, inRowIndex);
},
// row events
onRowClick: function(e){
// summary:
// Event fired when a row is clicked.
// e: Event
// Decorated event object which contains reference to grid, cell, and rowIndex
this.edit.rowClick(e);
this.selection.clickSelectEvent(e);
},
onRowDblClick: function(e){
// summary:
// Event fired when a row is double clicked.
// e: Event
// decorated event object which contains reference to grid, cell, and rowIndex
},
onRowMouseOver: function(e){
// summary:
// Event fired when mouse moves over a data row.
// e: Event
// Decorated event object which contains reference to grid, cell, and rowIndex
},
onRowMouseOut: function(e){
// summary:
// Event fired when mouse moves out of a data row.
// e: Event
// Decorated event object contains reference to grid, cell, and rowIndex
},
onRowMouseDown: function(e){
// summary:
// Event fired when mouse is down in a row.
// e: Event
// Decorated event object which contains reference to grid, cell, and rowIndex
},
onRowContextMenu: function(e){
// summary:
// Event fired when a row context menu is accessed via mouse right click.
// e: Event
// Decorated event object which contains reference to grid, cell, and rowIndex
dojo.stopEvent(e);
},
// header events
onHeaderMouseOver: function(e){
// summary:
// Event fired when mouse moves over the grid header.
// e: Event
// Decorated event object contains reference to grid, cell, and rowIndex
},
onHeaderMouseOut: function(e){
// summary:
// Event fired when mouse moves out of the grid header.
// e: Event
// Decorated event object which contains reference to grid, cell, and rowIndex
},
onHeaderCellMouseOver: function(e){
// summary:
// Event fired when mouse moves over a header cell.
// e: Event
// Decorated event object which contains reference to grid, cell, and rowIndex
dojo.addClass(e.cellNode, this.cellOverClass);
},
onHeaderCellMouseOut: function(e){
// summary:
// Event fired when mouse moves out of a header cell.
// e: Event
// Decorated event object which contains reference to grid, cell, and rowIndex
dojo.removeClass(e.cellNode, this.cellOverClass);
},
onHeaderCellMouseDown: function(e) {
// summary:
// Event fired when mouse is down in a header cell.
// e: Event
// Decorated event object which contains reference to grid, cell, and rowIndex
},
onHeaderClick: function(e){
// summary:
// Event fired when the grid header is clicked.
// e: Event
// Decorated event object which contains reference to grid, cell, and rowIndex
},
onHeaderCellClick: function(e){
// summary:
// Event fired when a header cell is clicked.
// e: Event
// Decorated event object which contains reference to grid, cell, and rowIndex
this.setSortIndex(e.cell.index);
this.onHeaderClick(e);
},
onHeaderDblClick: function(e){
// summary:
// Event fired when the grid header is double clicked.
// e: Event
// Decorated event object which contains reference to grid, cell, and rowIndex
},
onHeaderCellDblClick: function(e){
// summary:
// Event fired when a header cell is double clicked.
// e: Event
// Decorated event object which contains reference to grid, cell, and rowIndex
this.onHeaderDblClick(e);
},
onHeaderCellContextMenu: function(e){
// summary:
// Event fired when a header cell context menu is accessed via mouse right click.
// e: Event
// Decorated event object which contains reference to grid, cell, and rowIndex
this.onHeaderContextMenu(e);
},
onHeaderContextMenu: function(e){
// summary:
// Event fired when the grid header context menu is accessed via mouse right click.
// e: Event
// Decorated event object which contains reference to grid, cell, and rowIndex
dojo.stopEvent(e);
},
// editing
onStartEdit: function(inCell, inRowIndex){
// summary:
// Event fired when editing is started for a given grid cell
// inCell: Object
// Cell object containing properties of the grid column.
// inRowIndex: Integer
// Index of the grid row
},
onApplyCellEdit: function(inValue, inRowIndex, inFieldIndex){
// summary:
// Event fired when editing is applied for a given grid cell
// inValue: String
// Value from cell editor
// inRowIndex: Integer
// Index of the grid row
// inFieldIndex: Integer
// Index in the grid's data model
},
onCancelEdit: function(inRowIndex){
// summary:
// Event fired when editing is cancelled for a given grid cell
// inRowIndex: Integer
// Index of the grid row
},
onApplyEdit: function(inRowIndex){
// summary:
// Event fired when editing is applied for a given grid row
// inRowIndex: Integer
// Index of the grid row
},
onCanSelect: function(inRowIndex){
// summary:
// Event to determine if a grid row may be selected
// inRowIndex: Integer
// Index of the grid row
// returns: Boolean
// true if the row can be selected
return true;
},
onCanDeselect: function(inRowIndex){
// summary:
// Event to determine if a grid row may be deselected
// inRowIndex: Integer
// Index of the grid row
// returns: Boolean
// true if the row can be deselected
return true;
},
onSelected: function(inRowIndex){
// summary:
// Event fired when a grid row is selected
// inRowIndex: Integer
// Index of the grid row
this.updateRowStyles(inRowIndex);
},
onDeselected: function(inRowIndex){
// summary:
// Event fired when a grid row is deselected
// inRowIndex: Integer
// Index of the grid row
this.updateRowStyles(inRowIndex);
},
onSelectionChanged: function(){
}
}
}
| fedora-infra/packagedb | pkgdb/static/js/dojox/grid/compat/_grid/publicEvents.js | JavaScript | gpl-2.0 | 13,664 |
/*
* Ext JS Library 2.1
* Copyright(c) 2006-2008, Ext JS, LLC.
* licensing@extjs.com
*
* http://extjs.com/license
*/
Ext.onReady(function(){
var ds = new Ext.data.Store({
proxy: new Ext.data.ScriptTagProxy({
url: 'http://extjs.com/forum/topics-remote.php'
}),
reader: new Ext.data.JsonReader({
root: 'topics',
totalProperty: 'totalCount',
id: 'post_id'
}, [
{name: 'postId', mapping: 'post_id'},
{name: 'title', mapping: 'topic_title'},
{name: 'topicId', mapping: 'topic_id'},
{name: 'author', mapping: 'author'},
{name: 'lastPost', mapping: 'post_time', type: 'date', dateFormat: 'timestamp'},
{name: 'excerpt', mapping: 'post_text'}
]),
baseParams: {limit:20, forumId: 4}
});
// Custom rendering Template for the View
var resultTpl = new Ext.XTemplate(
'<tpl for=".">',
'<div class="search-item">',
'<h3><span>{lastPost:date("M j, Y")}<br />by {author}</span>',
'<a href="http://extjs.com/forum/showthread.php?t={topicId}&p={postId}" target="_blank">{title}</a></h3>',
'<p>{excerpt}</p>',
'</div></tpl>'
);
var panel = new Ext.Panel({
applyTo: 'search-panel',
title:'Forum Search',
height:300,
autoScroll:true,
items: new Ext.DataView({
tpl: resultTpl,
store: ds,
itemSelector: 'div.search-item'
}),
tbar: [
'Search: ', ' ',
new Ext.app.SearchField({
store: ds,
width:320
})
],
bbar: new Ext.PagingToolbar({
store: ds,
pageSize: 20,
displayInfo: true,
displayMsg: 'Topics {0} - {1} of {2}',
emptyMsg: "No topics to display"
})
});
ds.load({params:{start:0, limit:20, forumId: 4}});
});
| Kev/maybelater | static/ext-2.1/examples/form/custom.js | JavaScript | gpl-2.0 | 2,077 |
/**
* @file
* This file contain the javascript necessary to display google maps created
* using the WYSIWYG inline map token builder.
*/
(function ($) {
Drupal.behaviors.google_map_field_tokens = {
attach: function (context) {
var map_collection = Drupal.settings.gmf_token_maps;
var map = [];
for (var i = 0; i < map_collection.length; i++) {
var latlng = new google.maps.LatLng(map_collection[i]['lat'], map_collection[i]['lon']);
var mapOptions = {
zoom: parseInt(map_collection[i]['zoom']),
center: latlng,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Create the map and drop it into the relavent container.
map[i] = new google.maps.Map(document.getElementById("inline_google_map_field_"+parseInt(1000 + i)), mapOptions);
// Add the marker to the map.
marker = new google.maps.Marker({
position: latlng,
map: map[i],
});
}
}
};
})(jQuery);
| akendrick/PW | sites/all/modules/google_map_field/js/google_map_field_token_maps.js | JavaScript | gpl-2.0 | 1,038 |
/**
* Provides callback for saving destination file into it's source directory.
*
* This scripts exists to re-use for Gulp tasks that requires destination files
* to be placed into their source directory.
*/
export default function (file) {
return file.base;
}
| Niklan/Glisseo | STARTER_SCSS/scripts/utils/destinationToSource.js | JavaScript | gpl-2.0 | 269 |
import $ from 'jquery';
//------------------------------------------------
// Custom publish metabox.
//------------------------------------------------
// Handle the custom statuses.
let submitdiv = $('#themosisSubmitdiv'),
editButton = submitdiv.find('.edit-post-status'),
selectDiv = submitdiv.find('#post-status-select'),
selectTag = submitdiv.find('#post_status'),
statusLabel = submitdiv.find('#post-status-display'),
statusButtons = submitdiv.find('.save-post-status, .cancel-post-status'),
originalPublish = submitdiv.find('input#original_publish'),
publishButton = submitdiv.find('input#publish');
// Edit button
editButton.on('click', e =>
{
e.preventDefault();
// Show the select option list.
$(this).hide();
selectDiv.slideDown(200);
});
// Cancel button or OK buttons
statusButtons.on('click', function(e)
{
e.preventDefault();
let button = $(this);
// If 'ok' button, update label span with status label.
if (button.hasClass('save-post-status'))
{
// Grab selected label.
let selected = selectTag.find(':selected'),
label = selected.text(),
publishText = selected.data('publish');
// Update label text.
statusLabel.text(label);
// Update publish button.
// Check if 'draft'
if ('draft' === selected.val())
{
// Change value of the "original_publish" input.
originalPublish.val('auto-draft');
// Change publish button name attribute.
publishButton.attr('name', 'save');
}
// Change publish button text.
publishButton.val(publishText);
}
// If 'cancel' button, make sure to reset the select tag value.
if (button.hasClass('cancel-post-status'))
{
let selected = selectTag.find('option[selected="selected"]');
selectTag.val(selected.val());
}
// Show back edit button.
editButton.show();
// Close select statuses.
selectDiv.slideUp(200);
});
//------------------------------------------------
// Quick edit select tag.
//------------------------------------------------
import './quickedit'; | ramon-villain/framework-1 | src/Themosis/_assets/components/poststatus/poststatus.js | JavaScript | gpl-2.0 | 2,191 |
define(
({
label: "Katman",
show: "Göster",
actions: "Katman Alanlarını Yapılandır",
field: "Alan",
alias: "Takma Ad",
visible: "Görünür",
linkField: "Bağlantı Alanı",
noLayers: "Detay katmanı mevcut değil",
back: "Geri",
exportCSV: "CSV\'ye Aktarmaya İzin Ver",
restore: "Varsayılan değere geri yükle",
ok: "Tamam",
result: "Başarıyla kaydedildi",
warning: "Katmanı önce tabloda göstermek için işaretleyin.",
fieldCheckWarning: "En az bir alan seçilmelidir.",
unsupportQueryWarning: "Öznitelik Tablosu aracını görüntülemek için katmanın sorgu işlemini desteklemesi gerekir. Servisteki sorgu yeteneğinin açık olduğundan emin olun.",
unsupportQueryLayers: "Öznitelik Tablosu aracını görüntülemek için aşağıdaki katmanın sorgu işlemini desteklemesi gerekir. Hizmetteki sorgu özelliğinin açık olduğundan emin olun.",
fieldName: "Ad",
fieldAlias: "Takma Ad",
fieldVisibility: "Görünürlük",
fieldActions: "İşlemler"
})
); | johnaagudelo/ofertaquequieres | visor-oferta/widgets/AttributeTable/setting/nls/tr/strings.js | JavaScript | gpl-2.0 | 1,070 |
jQuery(document).ready(function($){
//Upload function
function initUpload(clone){
var itemToInit = null;
itemToInit = typeof clone !== 'undefined' ? clone : $('.shortcode-dynamic-item');
itemToInit.find('.redux-opts-upload').on('click',function( event ) {
var activeFileUploadContext = jQuery(this).parent();
var relid = jQuery(this).attr('rel-id');
event.preventDefault();
// if its not null, its broking custom_file_frame's onselect "activeFileUploadContext"
custom_file_frame = null;
// Create the media frame.
custom_file_frame = wp.media.frames.customHeader = wp.media({
// Set the title of the modal.
title: jQuery(this).data("choose"),
// Tell the modal to show only images. Ignore if want ALL
library: {
type: 'image'
},
// Customize the submit button.
button: {
// Set the text of the button.
text: jQuery(this).data("update")
}
});
custom_file_frame.on( "select", function() {
// Grab the selected attachment.
var attachment = custom_file_frame.state().get("selection").first();
// Update value of the targetfield input with the attachment url.
jQuery('.redux-opts-screenshot',activeFileUploadContext).attr('src', attachment.attributes.url);
jQuery('#' + relid ).val(attachment.attributes.url).trigger('change');
jQuery('.redux-opts-upload',activeFileUploadContext).hide();
jQuery('.redux-opts-screenshot',activeFileUploadContext).show();
jQuery('.redux-opts-upload-remove',activeFileUploadContext).show();
});
custom_file_frame.open();
});
itemToInit.find('.redux-opts-upload-remove').on('click', function( event ) {
var activeFileUploadContext = jQuery(this).parent();
var relid = jQuery(this).attr('rel-id');
event.preventDefault();
jQuery('#' + relid).val('');
jQuery(this).prev().fadeIn('slow');
jQuery('.redux-opts-screenshot',activeFileUploadContext).fadeOut('slow');
jQuery(this).fadeOut('slow');
});
}
$('input.popup-colorpicker').wpColorPicker({
palettes: ['#27CCC0', '#78cd6e', '#29c1e7', '#ae81f9', '#f78224', '#FF4629']
});
function calcPercent() {
var $output = $("<span>");
$output.addClass('output');
$("div.shortcode-options[data-name=bar_graph] .shortcode-dynamic-items > div:last-child .content.dd-percent").append($output);
$("[data-slider]").bind("slider:ready slider:changed", function (event, data) {
$(this).nextAll(".output:first").html(data.value + '%').attr('data-num',data.value);
});
}
calcPercent();
//The chosen one
$("select#nectar-shortcodes").chosen();
$('#shortcode-content textarea').val('');
function dynamic_items(){
var code = '';
var tabID = '1', barID = '1', clientID = '1', testimonialID = '1', toggleID = '1';
var tabContent, barPercent;
var toggleContent, toggleTitle, toggleColor;
var barTitle, barColor;
var clientImage, clientURL;
var testimonialName, testimonialQuote;
//tabs
if( $('.shortcode-options[data-name=tabbed_section]').is(':visible') ){
$('.shortcode-options[data-name=tabbed_section] .shortcode-dynamic-item-input').each(function(){
if( $(this).val() != '' ) {
tabContent = $(this).parent().parent().find('.shortcode-dynamic-item-text').val();
code += ' [tab title="'+$(this).val()+'" id="t'+tabID+'"] '+tabContent+' [/tab] ';
tabID++;
}
});
}
//toggles
else if( $('.shortcode-options[data-name=toggles]').is(':visible') ) {
$('.shortcode-options[data-name=toggles] .shortcode-dynamic-item').each(function(){
toggleTitle = $(this).find('.shortcode-dynamic-item-input:nth-child(1)').val();
toggleContent = ($(this).find('textarea').val().length != 0) ? $(this).find('textarea').val() : '';
toggleColor = $(this).find('select').val();
code += ' [toggle title="'+toggleTitle+'" color="' + toggleColor + '" id="b'+toggleID+'"] '+toggleContent+' [/toggle]';
toggleID++;
});
}
//bar graph
else if( $('.shortcode-options[data-name=bar_graph]').is(':visible') ) {
$('.shortcode-options[data-name=bar_graph] .shortcode-dynamic-item').each(function(){
barTitle = $(this).find('.shortcode-dynamic-item-input:nth-child(1)').val();
barPercent = (typeof $(this).find('.output').attr('data-num') != 'undefined') ? $(this).find('.output').attr('data-num') : '1';
barColor = $(this).find('select').val();
code += ' [bar title="'+barTitle+'" percent="' + barPercent + '" color="' + barColor + '" id="b'+barID+'"]';
barID++;
});
}
//clients
else if( $('#options-item.clients').is(':visible') ) {
$('#options-item.clients .shortcode-dynamic-item').each(function(){
clientImage = $(this).find('.redux-opts-screenshot:first').attr('src');
clientURL = ($(this).find('.shortcode-dynamic-item-input').val().length != 0) ? $(this).find('.shortcode-dynamic-item-input').val() : 'none';
code += ' [client image="'+clientImage+'" url="' + clientURL + '" id="c'+clientID+'"]';
clientID++;
});
}
//testimonials
else if( $('#options-item.testimonials').is(':visible') ) {
$('#options-item.testimonials .shortcode-dynamic-item').each(function(){
testimonialName = $(this).find('.shortcode-dynamic-item-input:nth-child(1)').val();
testimonialQuote = ($(this).find('textarea').val().length != 0) ? $(this).find('textarea').val() : '';
code += ' [testimonial name="'+testimonialName+'" quote="' + testimonialQuote + '" id="t'+testimonialID+'"]';
testimonialID++;
});
}
$('#shortcode-storage-d').html(code);
}
function directToEditor() {
var name = $('#nectar-shortcodes').val();
var content = '';
switch(name) {
case 'carousel':
content = '<br/>' +
'[item] content here [/item]<br/>' +
'[item] content here [/item]<br/>' +
'[item] content here [/item]<br/>' +
'[item] content here [/item]<br/>' +
'[/carousel]';
break;
case 'pricing_table':
var columnNum = 0;
var selectedColumnNum = $('#options-'+name+' input.attr:checked').val();
var columnHeader;
(typeof selectedColumnNum != 'undefined' && selectedColumnNum.length > 0) ? columnNum = selectedColumnNum : columnNum = 0;
for(var i=1;i<=columnNum;i++) {
if(i == 2) {
columnHeader = '[pricing_column title="Column '+i+'" highlight="true" highlight_reason="Most Popular" color="extra-color-1" price="'+100*i+'" currency_symbol="$" interval="Per Month" ]<br/>';
}
else{
columnHeader = '[pricing_column title="Column '+i+'" price="'+100*i+'" currency_symbol="$" interval="Per Month"]<br/>';
}
content += '<br/><br/>' +
columnHeader +
'<ul class="features">'+
'<li> Your text here </li>'+
'<li> Your text here </li>'+
'<li> Your text here </li>'+
'</ul>'+
'[button size="medium" url="#" text="Sign up now!" color="extra-color-1"]<br/>'+
'[/pricing_column]';
}
content += '<br/><br/>[/pricing_table]';
break;
}
//insert shortcode
window.wp.media.editor.insert( $('#shortcode-storage-o').text() + content);
$.magnificPopup.close();
//wipe out storage
$('#shortcode-storage-o, #shortcode-storage-d, #shortcode-storage-c').text('');
resetFileds();
return false;
}
function update_shortcode(ending){
var name = $('#nectar-shortcodes').val();
var dataType = $('#options-'+name).attr('data-type');
var extra_attrs = '', extra_attrs2 = '', extra_attrs3 = '', extra_attrs3b = '', extra_attrs4 = '';
ending = ending || '';
//take care of the dynamic events easier
dynamic_items();
//last check
var code = '['+name;
if( $('#options-'+name).attr('data-type')=='checkbox' ){
if($('#options-'+name+' input.last').attr('checked') == 'checked') ending = '_last';
}
code += ending;
//checkbox loop for extra attrs
$('#options-'+name+' input[type=checkbox]').each(function(){
if($(this).attr('checked') == 'checked' && $(this).attr('class') != 'last') extra_attrs += ' ' + $(this).attr('class')+'="true"';
});
code += extra_attrs;
//textarea loop for extra attrs
$('#options-'+name+' textarea:not("#shortcode_content")').each(function(){
extra_attrs2 += ' ' + $(this).attr('data-attrname')+'="'+ $(this).val() +'"';
});
if(dataType != 'dynamic') code += extra_attrs2;
//select loop for extra attrs
$('#options-'+name+' select:not(".dynamic-select, [multiple=multiple], .skip-processing")').each(function(){
extra_attrs3 += ' ' + $(this).attr('id')+'="' + $(this).attr('value') + '"';
});
code += extra_attrs3;
//multiselect loop for extra attrs
$('#options-'+name+' select[multiple=multiple]').each(function(){
var $categories = ($(this).val() != null && $(this).val().length > 0) ? $(this).val() : 'all';
extra_attrs3b += ' ' + $(this).attr('id')+'="' + $categories + '"';
});
code += extra_attrs3b;
//image upload loop for extra attrs
$('#options-'+name+' [data-name=image-upload] img.redux-opts-screenshot').each(function(){
extra_attrs4 += ' ' + $(this).attr('id')+'="' + $(this).attr('src') + '"';
});
code += extra_attrs4;
//input loop for extra attrs
$('#options-'+name+' input.attr:not(".skip-processing")').each(function(){
if( $(this).attr('type') == 'text' ){ code += ' '+ $(this).attr('data-attrname')+'="'+ $(this).val()+'"'; }
else { if($(this).attr('checked') == 'checked') code += ' '+ $(this).attr('data-attrname')+'="'+ $(this).val()+'"'; }
});
//color loop for extra attrs
$('#options-'+name+' input.popup-colorpicker').each(function(){
code += ' background_color="'+ $(this).val()+'"';
});
//take care of icon attrs
if(name == 'icon' && $('.icon-option i.selected').length > 0 ) code += ' image="'+ $('.icon-option i.selected').attr('class').split(' ')[0] +'"';
code += ']';
$('#shortcode-storage-o').html(code);
if( dataType!= 'dynamic') $('#shortcode-storage-d').text($('#shortcode-content textarea').val());
if( dataType != 'regular' && dataType != 'radios' && dataType != 'direct_to_editor') $('#shortcode-storage-c').html(' [/'+name+ending+']');
if( dataType == 'direct_to_editor') directToEditor();
}
//events
$('#add-shortcode').click(function(){
//column animation check (don't add the attrs when unnecessary)
var name = $('#nectar-shortcodes').val();
if(name == 'one_half' || name == 'one_third' || name == 'two_thirds' || name == 'one_fourth' || name == 'three_fourths' || name == 'one_sixth' || name == 'five_sixths' || name == 'one_whole') {
if( $('#options-'+name+' select').val() == 'None') {
$('#options-'+name+' select').addClass('skip-processing');
$('#options-'+name+' input[data-attrname="delay"]').addClass('skip-processing');
} else {
$('#options-'+name+' select').removeClass('skip-processing');
$('#options-'+name+' input[data-attrname="delay"]').removeClass('skip-processing');
}
}
var dataType = $('#options-'+name).attr('data-type');
update_shortcode();
if( dataType != 'direct_to_editor') {
var $shortcodeData = $('#shortcode-storage-o').text() + $('#shortcode-storage-d').text() + $('#shortcode-storage-c').text() ;
window.wp.media.editor.insert( $('#shortcode-storage-o').text() + $('#shortcode-storage-d').text() + $('#shortcode-storage-c').text() );
$.magnificPopup.close();
//wipe out storage
$('#shortcode-storage-o, #shortcode-storage-d, #shortcode-storage-c').text('');
resetFileds();
}
return false;
});
$('#nectar-shortcodes').change(function(){
$('.shortcode-options').hide();
$('#options-'+$(this).val()).show();
var dataType = $('#options-'+$(this).val()).attr('data-type');
if( dataType == 'checkbox' || dataType == 'simple' ){
$('#shortcode-content').show().find('textarea').val('');
}
else {
$('#shortcode-content textarea').val('').parent().parent().hide();
}
});
$('#options-box input[type="radio"]').click(function(){
if($(this).val() == 'custom'){
$('#custom-box-name').attr('data-attrname','style').addClass('attr');
$('#options-box input[type="radio"]').attr('data-attrname','temp').removeClass('attr');
}
else{
$('#options-box input[type="radio"]').attr('data-attrname','style').addClass('attr');
$('#custom-box-name').attr('data-attrname','temp').removeClass('attr');
}
});
////Dynamic item events
$('.add-list-item').click(function(){
if(!$(this).parent().find('.remove-list-item').is(':visible')) $(this).parent().find('.remove-list-item').show();
//clone item
var $clone = $(this).parent().find('.shortcode-dynamic-item:first').clone();
$clone.find('input[type=text],textarea').attr('value','');
//init ss if it's a bar graph
if( $clone.find('.percent').length > 0 ) {
$($clone).find('.slider, .output').remove();
$($clone).find('.percent').simpleSlider({
range: [1,100],
step: '1'
});
}
//init new upload button and clear image if it's an upload
if( $clone.find('.redux-opts-upload').length > 0 ) {
$clone.find('.redux-opts-screenshot').attr('src','');
$clone.find('.redux-opts-upload-remove').hide();
$clone.find('.redux-opts-upload').css('display','inline-block');
setTimeout(function(){ initUpload($clone) },200);
}
//append clone
$(this).prevAll('.shortcode-dynamic-items').append($clone);
if( $clone.find('.percent').length > 0 ) calcPercent();
return false;
});
$('body').on('click', '.remove-list-item', function(){
if($(this).parent().find('.shortcode-dynamic-item').length > 1){
$(this).parent().find('#options-item .shortcode-dynamic-item:last').remove();
dynamic_items();
}
if($(this).parent().find('.shortcode-dynamic-item').length == 1) $(this).hide();
return false;
});
//hide remove btn to start
$('.remove-list-item').hide();
$('body').on('keyup','.shortcode-dynamic-item-input, .shortcode-dynamic-item-text', function(){ dynamic_items(); });
$("body").on("input propertychange", '.shortcode-dynamic-item textarea', function(){ dynamic_items(); });
//icon selection
$('.icon-option i').click(function(){
$('.icon-option i').removeClass('selected');
$(this).addClass('selected');
});
//icon set selection
$('select[name="icon-set-select"]').change(function(){
var $selected_set = $(this).val();
$('.icon-option').hide();
$('.icon-option').next('.clear').hide();
$('.icon-option.'+$selected_set).stop(true,true).fadeIn();
$('.icon-option.'+$selected_set).next('.clear').show();
});
$('select[name="icon-set-select"]').trigger('change');
//starting category population
$('.starting_category').hide();
$('.starting_category').next('.clear').hide();
$('#options-nectar_portfolio #starting_category option:first').remove();
$('#options-nectar_portfolio #starting_category').prepend('<option value="default">Default</option>')
$('#options-nectar_portfolio #starting_category option:first').attr('selected','selected');
$('#options-nectar_portfolio #enable_sortable').click(function(){
var $this = $(this);
if ($this.is(':checked')) {
$('.starting_category').stop().slideDown();
$('.starting_category').next('.clear').stop().slideDown();
} else {
$('.starting_category').stop().slideUp();
$('.starting_category').next('.clear').stop().slideUp();
}
});
$("#options-nectar_portfolio #category").change(function(){
var selectedCats = $(this).val();
if(selectedCats == 'all') {
$('#options-nectar_portfolio #starting_category option').removeAttr('disabled').removeAttr('selected').show();
} else {
$('#options-nectar_portfolio #starting_category option:not([value="default"])').attr('disabled','disabled').removeAttr('selected').hide();
for(var i=0; i < selectedCats.length; i++){
$('#options-nectar_portfolio #starting_category option[value="' + selectedCats[i] + '"]').removeAttr('disabled').show();
}
$('#options-nectar_portfolio #starting_category option:not([disabled])').first().attr('selected','selected');
}
});
function resetFileds(){
//reset data
$('#nectar-sc-generator').find('input:text, input:password, input:file, textarea').val('');
$('#nectar-sc-generator').find('select:not(#nectar-shortcodes) option:first-child').attr("selected", "selected");
$('#nectar-sc-generator').find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
$('#nectar-sc-generator').find('.shortcode-options').each(function(){
$(this).find('.shortcode-dynamic-item').addClass('marked-for-removal');
$(this).find('.shortcode-dynamic-item:first').removeClass('marked-for-removal');
$(this).find('.shortcode-dynamic-item.marked-for-removal').remove();
});
$('#nectar-sc-generator').find('.redux-opts-screenshot').attr('src','');
$('#nectar-sc-generator').find('.redux-opts-upload-remove').hide();
$('#nectar-sc-generator').find('.redux-opts-upload').show();
$('#nectar-sc-generator').find('.wp-color-result').attr('style','');
//starting category population
$('.starting_category').hide();
$('.starting_category').next('.clear').hide();
}
}); | nathanyyl/Woo-Commerce | wp-content/themes/salient/nectar/tinymce/shortcode_generator/js/popup.js | JavaScript | gpl-2.0 | 18,727 |
jQuery.noConflict();
jQuery(document).ready(function($){
rsm_init_toolbar(jQuery);
rsm_init_suckerfish(jQuery);
jQuery('#rsm_operator').hide();
jQuery('#rsm_text_input').hide();
jQuery('#rsm_load_more_results').live('click', function(e){
e.preventDefault();
var limitstart = jQuery('#rsm_load_more_results').attr('rel');
rsm_get_items(jQuery, false, limitstart);
});
//check all the fields
jQuery('#checkAll').live('click',function(){
jQuery('input[name$="cid[]"]').attr('checked', this.checked);
});
$('#rsm_select_all_btn').click(function(){
var results = jQuery('#rsm_select_filter_subs').html();
if(jQuery('#rsm_select_all_btn').hasClass('rsm_all_selected')){
var btn_text = rsm_get_lang('RSM_SELECT_ALL_RESULTS').replace('%s',results);
jQuery('#rsm_select_all_btn').removeClass('rsm_all_selected').html(btn_text);
jQuery('#rsm_filtered_results').val(0);
}
else {
var btn_text = rsm_get_lang('RSM_DESELECT_ALL_RESULTS').replace('%s',results);
jQuery('#rsm_select_all_btn').addClass('rsm_all_selected').html(btn_text);
jQuery('#rsm_filtered_results').val(1);
}
});
// toolbars
function rsm_init_toolbar($)
{
$('#rsm_condition_and, #rsm_condition_or').click(function(e){
e.preventDefault();
var selected_condition = $(this).text();
$(this).parent().siblings().children('a').removeClass('rsm_tick');
$(this).parent().parent().parent().children('a').html(selected_condition);
$(this).attr('class', 'rsm_tick');
var condition = $('input[name="rsm_condition"]').val($(this).attr('rel'));
rsm_get_items($, false);
$('.rsm_filter_condition').each(function(i,span){
$(span).html(selected_condition);
});
})
$("#rsm_filter").click(function(e) {
e.preventDefault();
var current_published = $('#rsm_published .rsm_tick').attr('rel');
var current_list = $('#rsm_list .rsm_tick').attr('rel');
var current_field = $('#rsm_field .rsm_tick').attr('rel');
var current_operator = $('#rsm_operator .rsm_tick').attr('rel');
$('#rsm_condition > ul > li > a.rsm_tick').children('span.sf-sub-indicator').remove();
var current_condition = $('#rsm_condition > ul > li > a.rsm_tick').text();
var text = $('#rsm_filter_text').val();
var already_published = document.getElementsByName('rsm_published[]');
var already_lists = document.getElementsByName('rsm_lists[]');
var already_fields = document.getElementsByName('rsm_fields[]');
var already_operators = document.getElementsByName('rsm_operators[]');
var already_values = document.getElementsByName('rsm_values[]');
var already_condition = document.getElementsByName('rsm_condition');
for (var i=0; i<already_lists.length; i++)
{
if ($(already_published[i]).val() == current_published
&& $(already_lists[i]).val() == current_list
&& $(already_fields[i]).val() == current_field
&& $(already_operators[i]).val() == current_operator
&& $(already_values[i]).val() == text)
return;
}
var count_filters = $('#rsm_filters li').length;
var condition = (count_filters > 0 ? $('<span class="rsm_filter_condition">').empty().text(current_condition) : '');
var li = $('<li>');
var published = $('<span>').html($('#rsm_published > a').html());
var list = $('<span>').html($('#rsm_list > a').html()) ;
var field = $('#rsm_field ul li > a.rsm_tick').attr('rel') == 0 ? $('<span>').hide() : $('<span>').html($('#rsm_field > a').html());
var operator = $('#rsm_field ul li > a.rsm_tick').attr('rel') == 0 ? $('<span>').hide() : $('<span>').html($('#rsm_operator > a').html());
var value = $('#rsm_field ul li > a.rsm_tick').attr('rel') == 0 ? $('<span>').hide() : $('<strong>').text(text);
var close = $('<a>', {'href': 'javascript: void(0)', 'class': 'rsm_close'}).click(function(e) {
e.preventDefault();
$(this).parent('li').hide('highlight', 500, function() {
if($(this).prev().hasClass('rsm_filter_condition'))
$(this).prev().remove();
$(this).remove();
rsm_get_items($, false);
if (count_filters <= 2 && $('#rsm_clear_filters').length > 0) {
$('#rsm_clear_filters').remove();
}
if(count_filters == 1)
$('#rsm_condition').css('display', 'none');
if ($('#rsm_filters').children().first().hasClass('rsm_filter_condition'))
$('#rsm_filters').children().first().remove();
});
});
var input_published = $('<input>', {'type': 'hidden', 'name': 'rsm_published[]', 'value': current_published});
var input_lists = $('<input>', {'type': 'hidden', 'name': 'rsm_lists[]', 'value': current_list});
var input_fields = $('<input>', {'type': 'hidden', 'name': 'rsm_fields[]', 'value': current_field});
var input_operator = $('<input>', {'type': 'hidden', 'name': 'rsm_operators[]', 'value': current_operator});
var input_value = $('<input>', {'type': 'hidden', 'name': 'rsm_values[]', 'value': text});
if(count_filters > 0)
$('#rsm_filters').append(condition);
$('#rsm_filters').append(li.append(published, list, field, operator, value, close, input_published, input_lists, input_fields, input_operator, input_value));
$('#rsm_clear_filters').remove();
if (count_filters > 0)
$('#rsm_condition').css('display', 'block');
else
$('#rsm_condition').css('display', 'none');
if (count_filters >= 2)
{
var clear = $('<span>', {'id': 'rsm_clear_filters'}).html(rsm_get_lang('RSM_CLEAR_ALL_FILTERS')).click(function (e){
e.preventDefault();
$('#rsm_filters').children().hide('highlight', 500, function() { $(this).remove();});
rsm_get_items($, true);
$('#rsm_condition').css('display', 'none');
});
$('#rsm_filters').append(clear);
}
rsm_get_items($, false);
});
// use this to trigger the filtering when enter is pressed and the form is submitted
$("#rsm_filter_form").submit(function(e) {
e.preventDefault();
$('#rsm_filter').trigger('click');
});
// if there are any filters from the session, initialize the clicks
$('.rsm_close').live('click',function(e) {
e.preventDefault();
$(this).parent('li').hide('highlight', 500, function() {
if($(this).prev().hasClass('rsm_filter_condition'))
$(this).prev().remove();
$(this).remove();
rsm_get_items($, false);
// remove clear filters button if there are less than 3 filters applied
if ($('#rsm_filters li').length < 3 && $('#rsm_clear_filters').length > 0)
$('#rsm_clear_filters').remove();
// hide condition if it is displayed only one filter
if ($('#rsm_filters li').length < 2)
$('#rsm_condition').css('display', 'none');
// remove the or/and tag if it is the first element in the filter
if ($('#rsm_filters').children().first().hasClass('rsm_filter_condition'))
$('#rsm_filters').children().first().remove();
});
});
$('#rsm_clear_filters').click(function (e){
e.preventDefault();
$('#rsm_filters').children().hide('highlight', 500, function() { $(this).remove(); });
rsm_get_items($, true);
$('#rsm_condition').css('display', 'none');
});
}
// create suckerfish dropdowns
function rsm_init_suckerfish($)
{
$(".rsm_filter_toolbar > ul").children('li').each(function (i, el) {
maxwidth = 0;
$(el).children('ul').each(function (j, ul) {
$(ul).show();
$(ul).children('li').each (function (k, li) {
width = $(li).outerWidth();
if (width > maxwidth)
maxwidth = width;
});
$(ul).hide();
});
if (maxwidth > 0)
$(el).css('width', maxwidth + 'px');
});
$(".rsm_filter_toolbar ul").superfish();
// published
$('#rsm_published ul li a').click(function (e){
e.preventDefault();
$(".rsm_filter_toolbar ul").hideSuperfishUl();
$('#rsm_published > a').html($(this).html());
$('#rsm_published ul li a').removeClass('rsm_tick');
$(this).addClass('rsm_tick');
});
// lists
$('#rsm_list ul li a').click(function (e){
e.preventDefault();
$(".rsm_filter_toolbar ul").hideSuperfishUl();
$('#rsm_list > a').html($(this).html());
$('#rsm_list ul li a').removeClass('rsm_tick');
$(this).addClass('rsm_tick');
var ListId = $(this).attr('rel');
$.ajax({
type: 'POST',
url: "index.php?option=com_rsmail&task=jsonfields&action=filter_subscribers&IdList="+ListId,
dataType: 'html',
success: function(data) {
$('#rsm_field').show();
$('#rsm_field ul').empty();
jQuery.parseJSON(data).each(function(el,index){
$('#rsm_field ul').append('<li><a href="javascript: void(0);" rel="'+el.IdListFields+'" '+(el.IdListFields == 0 ? 'class="rsm_tick"' : '')+' >'+el.FieldName+'</a></li>');
});
$('#rsm_field > a').html($('#rsm_field li a.rsm_tick').html());
$('#rsm_filter_text').val('');
}
});
});
// fields
$('#rsm_field ul li a').live('click',function (e)
{
e.preventDefault();
$(".rsm_filter_toolbar ul").hideSuperfishUl();
$('#rsm_field > a').html($(this).html());
$('#rsm_field ul li a').removeClass('rsm_tick');
$(this).addClass('rsm_tick');
if($(this).attr('rel') == 0) {
$('#rsm_operator').hide();
$('#rsm_text_input').hide();
} else {
$('#rsm_operator').show();
$('#rsm_text_input').show();
}
});
// operator
$('#rsm_operator ul li a').click(function (e)
{
e.preventDefault();
$(".rsm_filter_toolbar ul").hideSuperfishUl();
$('#rsm_operator > a').html($(this).html());
$('#rsm_operator ul li a').removeClass('rsm_tick');
$(this).addClass('rsm_tick');
});
}
function rsm_get_items($, clear, more)
{
// parent container
var parent = $('#rsm_subscribers');
// clear contents
if (clear == true){ parent.empty(); }
var limitstart = 0;
if(more) limitstart = more;
$.ajax({
type: 'POST',
url: "index.php?option=com_rsmail&task=subscribers.ajax&limitstart="+limitstart,
data: rsm_get_items_filter($, clear, more),
dataType: 'json',
success: function(data){
// display subscribers
if(limitstart == 0) parent.html(data.layout);
else parent.append(data.layout);
// tooltip
var selector = jQuery('#rsm_subscribers .hasTip[title!=""]');
selector.each(function(index,img){var title = img.get('title'); if (title) { var parts = title.split('::', 2); img.store('tip:title', parts[0]); img.store('tip:text', parts[1]); } });
selector.each(function(index,el){ var JTooltips = new Tips(el, { maxTitleChars: 50, fixed: false}); });
var current_results = parseInt($('input[name="cid[]"]').length);
var total_results = parseInt(data.pagination.total);
var thelimit = parseInt(data.pagination.limit);
if (current_results >= total_results) {
$('#rsm_load_more_results').hide();
} else {
// calculate the number of subscribers that will be loaded
var difference = total_results - current_results;
var load_results = (difference > 0 && difference < thelimit ? difference : ( total_results > thelimit ? thelimit : 0));
$('#rsm_load_more_results').attr('rel', current_results);
$('#rsm_load_limit').text(load_results);
$('#rsm_load_more_results').show();
}
// update pagination info
$('#rsm_current_results').html(current_results);
$('#rsm_total_results').html(total_results);
$('#rsm_select_filter_subs').html(total_results);
}
});
}
function rsm_get_items_filter($, clear,more)
{
// rsm_published[]
// rsm_lists[]
// rsm_fields[]
// rsm_operators[]
// rsm_values[]
// delete all filters
if(clear){
$('input[name="rsm_published[]"]').remove();
$('input[name="rsm_lists[]"]').remove();
$('input[name="rsm_fields[]"]').remove();
$('input[name="rsm_operators[]"]').remove();
$('input[name="rsm_values[]"]').remove();
$('input[name="rsm_condition"]').val('AND');
}
var published = [];
$('input[name="rsm_published[]"]').each(function (index, el){
published.push($(el).val());
});
if (published.length == 0)
published = '';
var lists = [];
$('input[name="rsm_lists[]"]').each(function (index, el){
lists.push($(el).val());
});
if (lists.length == 0)
lists = '';
var fields = [];
$('input[name="rsm_fields[]"]').each(function (index, el){
fields.push($(el).val());
});
if (fields.length == 0)
fields = '';
var operators = [];
$('input[name="rsm_operators[]"]').each(function (index, el){
operators.push($(el).val());
});
if (operators.length == 0)
operators = '';
var values = [];
$('input[name="rsm_values[]"]').each(function (index, el){
values.push($(el).val());
});
if (values.length == 0)
values = '';
var condition = $('input[name="rsm_condition"]').val();
var data = {
'filter_published[]': published,
'filter_lists[]': lists,
'filter_fields[]': fields,
'filter_operators[]': operators,
'filter_values[]': values,
'filter_condition': condition,
};
return data;
}
}); | bundocba/amici | administrator/components/com_rsmail/assets/js/jquery.scripts.js | JavaScript | gpl-2.0 | 12,696 |
myjs_aftersave = function (data) {
if (data == "login_id_duplicate") {
warningDialog("登录名已经被使用");
return false;
}
return true;
}; | alucard263096/AMK | DoctorWeb/js/myjs/user.js | JavaScript | gpl-2.0 | 176 |
/*
* Copyright 2016 OICR
*
* 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.
*/
'use strict';
/**
* @ngdoc service
* @name dockstore.ui.ContainerService
* @description
* # ContainerService
* Service in the dockstore.ui.
*/
angular.module('dockstore.ui')
.service('OrganizationService', [
'$q',
'$http',
'WebService',
function ($q, $http, WebService) {
this.getGA4GHTools = function(organization) {
return $q(function(resolve, reject) {
$http({
method: 'GET',
url: WebService.API_URI + '/api/ga4gh/v1/extended/tools/' + organization
}).then(function(response) {
resolve(response.data);
}, function(response) {
reject(response);
});
});
};
this.getContainersByOrg = function(organization) {
return $q(function(resolve, reject) {
$http({
method: 'GET',
url: WebService.API_URI + '/api/ga4gh/v1/extended/containers/' + organization
}).then(function(response) {
resolve(response.data);
}, function(response) {
reject(response);
});
});
};
this.getWorkflowsByOrg = function(organization) {
return $q(function(resolve, reject) {
$http({
method: 'GET',
url: WebService.API_URI + '/api/ga4gh/v1/extended/workflows/' + organization
}).then(function(response) {
resolve(response.data);
}, function(response) {
reject(response);
});
});
};
this.getOrganizations = function() {
return $q(function(resolve, reject) {
$http({
method: 'GET',
url: WebService.API_URI + '/api/ga4gh/v1/extended/organizations'
}).then(function(response) {
resolve(response.data);
}, function(response) {
reject(response);
});
});
};
}]);
| CancerCollaboratory/dockstore-ui | app/scripts/services/organizationService.js | JavaScript | gpl-2.0 | 2,639 |
(function () {
var valoracion = function () {
return {
restrict: 'AE',
templateUrl: '/static/directivas/valoracion/tpl-valoracion.html',
scope: {
valor: '=',
max: '@',
soloLectura: '@'
},
link: function (scope, elem, attrs) {
function actualizar() {
if(!scope.valor)scope.valor=1;
scope.estrellas = [];
for (var i = 0; i < scope.max; i++) {
var estrella = {
marcada: (i < scope.valor)
};
scope.estrellas.push(estrella);
}
};
scope.marcar = function (indice) {
if (scope.soloLectura && scope.soloLectura === 'true') {
return;
}
scope.valor = indice + 1;
actualizar();
};
actualizar();
}
}
}
angular.module('abDirectivas')
.directive('abValoracion', valoracion);
}()); | EscuelaIt/Curso-angularjs-FS-2015 | 25-socket-io/client/static/directivas/valoracion/valoracion.js | JavaScript | gpl-2.0 | 1,160 |
/**
* roll.js
*
* A game where the bot will generate two random dices and award the sender with the points corresponding to the output.
*/
(function() {
var prizes = [];
/* Set default prices in the DB for the Panel */
$.getSetIniDbNumber('rollprizes', 'prizes_0', 4);
$.getSetIniDbNumber('rollprizes', 'prizes_1', 16);
$.getSetIniDbNumber('rollprizes', 'prizes_2', 36);
$.getSetIniDbNumber('rollprizes', 'prizes_3', 64);
$.getSetIniDbNumber('rollprizes', 'prizes_4', 100);
$.getSetIniDbNumber('rollprizes', 'prizes_5', 144);
/**
* @function loadPrizes
*/
function loadPrizes() {
prizes[0] = $.getSetIniDbNumber('rollprizes', 'prizes_0', 4);
prizes[1] = $.getSetIniDbNumber('rollprizes', 'prizes_1', 16);
prizes[2] = $.getSetIniDbNumber('rollprizes', 'prizes_2', 36);
prizes[3] = $.getSetIniDbNumber('rollprizes', 'prizes_3', 64);
prizes[4] = $.getSetIniDbNumber('rollprizes', 'prizes_4', 100);
prizes[5] = $.getSetIniDbNumber('rollprizes', 'prizes_5', 144);
}
/**
* @event command
*/
$.bind('command', function(event) {
var sender = event.getSender().toLowerCase(),
command = event.getCommand(),
args = event.getArgs(),
dice1,
dice2,
resultMessage;
/**
* @commandpath roll - Roll the dice for some points
*/
if (command.equalsIgnoreCase('roll')) {
/**
* @commandpath roll rewards [double 1's] [2's] [3's] [4's] [5's] [6's] - Set the reward for each set of doubles.
*/
if (args[0] !== undefined) {
if (args[0].equalsIgnoreCase('rewards')) {
if (args.length != 7) {
loadPrizes();
$.say($.whisperPrefix(sender) + $.lang.get('roll.rewards.usage', prizes.join(' ')));
return;
}
if (isNaN(args[1]) || isNaN(args[2]) || isNaN(args[3]) || isNaN(args[4]) || isNaN(args[5]) || isNaN(args[6])) {
loadPrizes();
$.say($.whisperPrefix(sender) + $.lang.get('roll.rewards.usage', prizes.join(' ')));
return;
}
$.say($.whisperPrefix(sender) + $.lang.get('roll.rewards.success'));
$.inidb.set('rollprizes', 'prizes_0', args[1]);
$.inidb.set('rollprizes', 'prizes_1', args[2]);
$.inidb.set('rollprizes', 'prizes_2', args[3]);
$.inidb.set('rollprizes', 'prizes_3', args[4]);
$.inidb.set('rollprizes', 'prizes_4', args[5]);
$.inidb.set('rollprizes', 'prizes_5', args[6]);
return;
}
}
dice1 = $.randRange(1, 6);
dice2 = $.randRange(1, 6);
resultMessage = $.lang.get('roll.rolled', $.resolveRank(sender), dice1, dice2);
if (dice1 == dice2) {
loadPrizes();
switch (dice1) {
case 1:
resultMessage += $.lang.get('roll.doubleone', $.getPointsString(prizes[dice1 - 1]));
break;
case 2:
resultMessage += $.lang.get('roll.doubletwo', $.getPointsString(prizes[dice1 - 1]));
break;
case 3:
resultMessage += $.lang.get('roll.doublethree', $.getPointsString(prizes[dice1 - 1]));
break;
case 4:
resultMessage += $.lang.get('roll.doublefour', $.getPointsString(prizes[dice1 - 1]));
break;
case 5:
resultMessage += $.lang.get('roll.doublefive', $.getPointsString(prizes[dice1 - 1]));
break;
case 6:
resultMessage += $.lang.get('roll.doublesix', $.getPointsString(prizes[dice1 - 1]));
break;
}
$.say(resultMessage + $.gameMessages.getWin(sender, 'roll'));
$.inidb.incr('points', sender, prizes[dice1 - 1]);
} else {
$.say(resultMessage + $.gameMessages.getLose(sender, 'roll'));
}
}
});
/**
* @event initReady
*/
$.bind('initReady', function() {
if ($.bot.isModuleEnabled('./games/roll.js')) {
$.registerChatCommand('./games/roll.js', 'roll');
$.registerChatSubcommand('roll', 'rewards', 1);
}
});
/**
* Warn the user if the points system is disabled and this is enabled.
*/
if ($.bot.isModuleEnabled('./games/roll.js') && !$.bot.isModuleEnabled('./systems/pointSystem.js')) {
$.log.error("Disabled. ./systems/pointSystem.js is not enabled.");
}
$.loadPrizes = loadPrizes;
})();
| stachu540/PhantomBot | javascript-source/games/roll.js | JavaScript | gpl-3.0 | 5,043 |
module.exports={A:{A:{"1":"B","2":"K D G E A hB"},B:{"1":"2 C d J M H I"},C:{"1":"0 1 2 3 4 6 7 8 F N K D G E A B C d J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z HB GB AB CB DB FB","2":"eB BB YB XB"},D:{"1":"0 1 2 3 4 6 7 8 K D G E A B C d J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z HB GB AB CB DB FB RB LB JB jB MB NB OB PB","2":"F N"},E:{"1":"5 K D G E A B C SB TB UB VB WB p ZB","2":"F N QB IB"},F:{"1":"0 1 5 6 9 C J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z p fB","2":"E B aB bB cB dB"},G:{"1":"G iB KB kB lB mB nB oB pB qB rB sB tB","2":"IB gB EB"},H:{"1":"uB"},I:{"1":"4 F yB EB zB 0B","2":"BB vB wB xB"},J:{"1":"A","2":"D"},K:{"1":"5 9 C L p","2":"A B"},L:{"1":"JB"},M:{"1":"3"},N:{"1":"B","2":"A"},O:{"1":"1B"},P:{"1":"F 2B 3B 4B 5B"},Q:{"1":"6B"},R:{"1":"7B"}},B:1,C:"hidden attribute"};
| hhkaos/awesome-arcgis | node_modules/caniuse-lite/data/features/hidden.js | JavaScript | gpl-3.0 | 913 |
'use strict';
/* globals define, app, ajaxify, utils, socket, templates */
define('forum/chats', ['components', 'string', 'sounds', 'forum/infinitescroll', 'translator'], function(components, S, sounds, infinitescroll, translator) {
var Chats = {
initialised: false
};
var newMessage = false;
Chats.init = function() {
var containerEl = $('.expanded-chat ul'),
env = utils.findBootstrapEnvironment();
if (!Chats.initialised) {
Chats.addSocketListeners();
Chats.addGlobalEventListeners();
}
Chats.addEventListeners();
if (env === 'md' || env === 'lg') {
Chats.resizeMainWindow();
}
Chats.scrollToBottom($('.expanded-chat ul'));
Chats.initialised = true;
};
Chats.getRecipientUid = function() {
return parseInt($('.expanded-chat').attr('data-uid'), 10);
};
Chats.isCurrentChat = function(uid) {
return Chats.getRecipientUid() === parseInt(uid, 10);
};
Chats.addEventListeners = function() {
var inputEl = $('.chat-input'),
sendEl = $('.expanded-chat button[data-action="send"]'),
popoutEl = $('[data-action="pop-out"]');
$('.chats-list').on('click', 'li', function(e) {
var env = utils.findBootstrapEnvironment();
if (env === 'xs' || env === 'sm') {
app.openChat($(this).attr('data-username'), $(this).attr('data-uid'));
} else {
ajaxify.go('chats/' + utils.slugify($(this).attr('data-username')));
}
});
inputEl.on('keypress', function(e) {
if(e.which === 13 && !e.shiftKey) {
Chats.sendMessage(Chats.getRecipientUid(), inputEl);
return false;
}
});
inputEl.on('keyup', function() {
var val = !!$(this).val();
if ((val && $(this).attr('data-typing') === 'true') || (!val && $(this).attr('data-typing') === 'false')) {
return;
}
Chats.notifyTyping(Chats.getRecipientUid(), val);
$(this).attr('data-typing', val);
});
sendEl.on('click', function(e) {
Chats.sendMessage(Chats.getRecipientUid(), inputEl);
return false;
});
popoutEl.on('click', function() {
var username = $('.expanded-chat').attr('data-username'),
uid = Chats.getRecipientUid(),
text = components.get('chat/input').val();
if (app.previousUrl && app.previousUrl.match(/chats/)) {
ajaxify.go('chats', function() {
app.openChat(username, uid);
}, true);
} else {
window.history.go(-1);
app.openChat(username, uid);
}
$(window).one('action:chat.loaded', function() {
components.get('chat/input').val(text);
});
});
$('.recent-chats').on('scroll', function() {
var $this = $(this);
var bottom = ($this[0].scrollHeight - $this.height()) * 0.9;
if ($this.scrollTop() > bottom) {
loadMoreRecentChats();
}
});
$('.expanded-chat [data-since]').on('click', function() {
var since = $(this).attr('data-since');
$('.expanded-chat [data-since]').removeClass('selected');
$(this).addClass('selected');
loadChatSince(since);
return false;
});
};
function loadChatSince(since) {
var uid = Chats.getRecipientUid();
if (!uid) {
return;
}
socket.emit('modules.chats.get', {touid: uid, since: since}, function(err, messages) {
var chatContent = $('.expanded-chat .chat-content');
chatContent.find('.chat-message').remove();
Chats.parseMessage(messages, onMessagesParsed);
});
}
Chats.addGlobalEventListeners = function() {
$(window).on('resize', Chats.resizeMainWindow);
$(window).on('mousemove keypress click', function() {
if (newMessage) {
var recipientUid = Chats.getRecipientUid();
if (recipientUid) {
socket.emit('modules.chats.markRead', recipientUid);
newMessage = false;
}
}
});
};
function onMessagesParsed(html) {
var newMessage = $(html),
chatContainer = $('.chat-content');
newMessage.appendTo(chatContainer);
newMessage.find('.timeago').timeago();
newMessage.find('img:not(.not-responsive)').addClass('img-responsive');
Chats.scrollToBottom($('.expanded-chat .chat-content'));
}
Chats.addSocketListeners = function() {
socket.on('event:chats.receive', function(data) {
var typingNotifEl = $('.user-typing'),
containerEl = $('.expanded-chat ul'),
lastSpeaker = parseInt(containerEl.find('.chat-message').last().attr('data-uid'), 10);
if (Chats.isCurrentChat(data.withUid)) {
newMessage = data.self === 0;
data.message.self = data.self;
data.message.newSet = lastSpeaker !== data.message.fromuid;
Chats.parseMessage(data.message, onMessagesParsed);
} else {
var contactEl = $('[component="chat/recent"] li[data-uid="' + data.withUid + '"]'),
userKey = data.withUid === data.message.fromuid ? 'fromUser' : 'toUser';
// Spawn a new contact if required
templates.parse('partials/chat_contact', {
uid: data.withUid,
username: data.message[userKey].username,
status: data.message[userKey].status,
picture: data.message[userKey].picture,
teaser: {
content: data.message.cleanedContent,
timestampISO: new Date(Date.now()).toISOString()
}
}, function(html) {
translator.translate(html, function(translatedHTML) {
if (contactEl.length) {
contactEl.replaceWith(translatedHTML);
} else {
$('[component="chat/recent"]').prepend(translatedHTML);
}
// Mark that contact list entry unread
$('.chats-list li[data-uid="' + data.withUid + '"]').addClass('unread').find('.timeago').timeago();
app.alternatingTitle('[[modules:chat.user_has_messaged_you, ' + data.message.fromUser.username + ']]');
});
});
}
});
socket.on('event:chats.userStartTyping', function(withUid) {
$('.chats-list li[data-uid="' + withUid + '"]').addClass('typing');
});
socket.on('event:chats.userStopTyping', function(withUid) {
$('.chats-list li[data-uid="' + withUid + '"]').removeClass('typing');
});
socket.on('event:user_status_change', function(data) {
app.updateUserStatus($('.chats-list [data-uid="' + data.uid + '"] [component="user/status"]'), data.status);
});
};
Chats.resizeMainWindow = function() {
var messagesList = $('.expanded-chat .chat-content');
if (messagesList.length) {
var margin = $('.expanded-chat ul').outerHeight(true) - $('.expanded-chat ul').height(),
inputHeight = $('.chat-input').outerHeight(true),
fromTop = messagesList.offset().top;
messagesList.height($(window).height() - (fromTop + inputHeight + (margin * 4)));
}
Chats.setActive();
};
Chats.notifyTyping = function(toUid, typing) {
socket.emit('modules.chats.user' + (typing ? 'Start' : 'Stop') + 'Typing', {
touid: toUid,
fromUid: app.user.uid
});
};
Chats.sendMessage = function(toUid, inputEl) {
var msg = inputEl.val();
if (msg.length > config.maximumChatMessageLength) {
return app.alertError('[[error:chat-message-too-long]]');
}
if (!msg.length) {
return;
}
inputEl.val('');
socket.emit('modules.chats.send', {
touid: toUid,
message: msg
}, function(err) {
if (err) {
if (err.message === '[[error:email-not-confirmed-chat]]') {
return app.showEmailConfirmWarning(err);
}
return app.alertError(err.message);
}
sounds.play('chat-outgoing');
Chats.notifyTyping(toUid, false);
});
};
Chats.scrollToBottom = function(containerEl) {
if (containerEl.length) {
containerEl.scrollTop(
containerEl[0].scrollHeight - containerEl.height()
);
}
};
Chats.setActive = function() {
var recipientUid = Chats.getRecipientUid();
if (recipientUid) {
socket.emit('modules.chats.markRead', recipientUid);
$('.expanded-chat input').focus();
}
$('.chats-list li').removeClass('bg-primary');
$('.chats-list li[data-uid="' + recipientUid + '"]').addClass('bg-primary');
};
Chats.parseMessage = function(data, callback) {
templates.parse('partials/chat_message' + (Array.isArray(data) ? 's' : ''), {
messages: data
}, callback);
};
function loadMoreRecentChats() {
var recentChats = $('.recent-chats');
if (recentChats.attr('loading')) {
return;
}
recentChats.attr('loading', 1);
socket.emit('modules.chats.getRecentChats', {
after: recentChats.attr('data-nextstart')
}, function(err, data) {
if (err) {
return app.alertError(err.message);
}
if (data && data.users.length) {
onRecentChatsLoaded(data.users, function() {
recentChats.removeAttr('loading');
recentChats.attr('data-nextstart', data.nextStart);
});
} else {
recentChats.removeAttr('loading');
}
});
}
function onRecentChatsLoaded(users, callback) {
users = users.filter(function(user) {
return !$('.recent-chats li[data-uid=' + user.uid + ']').length;
});
if (!users.length) {
return callback();
}
infinitescroll.parseAndTranslate('chats', 'chats', {chats: users}, function(html) {
$('.recent-chats').append(html);
callback();
});
}
return Chats;
});
| HorusGoul/NodeBB | public/src/client/chats.js | JavaScript | gpl-3.0 | 8,861 |
var mongoose = require('mongoose');
var objetosSchema = new mongoose.Schema({
nombre: String,
descripcion: String,
imagen: String
});
mongoose.model('objetos', objetosSchema); | lejacome/TranEspol | models/objetos.js | JavaScript | gpl-3.0 | 184 |
/*
* Copyright (C) 2010 Google 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 Google Inc. 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.
*/
WebInspector.CSSStyleModel = function()
{
}
WebInspector.CSSStyleModel.parseRuleArrayPayload = function(ruleArray)
{
var result = [];
for (var i = 0; i < ruleArray.length; ++i)
result.push(WebInspector.CSSRule.parsePayload(ruleArray[i]));
return result;
}
WebInspector.CSSStyleModel.prototype = {
getStylesAsync: function(nodeId, userCallback)
{
function callback(userCallback, error, payload)
{
if (error) {
if (userCallback)
userCallback(null);
return;
}
var result = {};
if ("inlineStyle" in payload)
result.inlineStyle = WebInspector.CSSStyleDeclaration.parsePayload(payload.inlineStyle);
result.computedStyle = WebInspector.CSSStyleDeclaration.parsePayload(payload.computedStyle);
result.matchedCSSRules = WebInspector.CSSStyleModel.parseRuleArrayPayload(payload.matchedCSSRules);
result.styleAttributes = {};
for (var name in payload.styleAttributes)
result.styleAttributes[name] = WebInspector.CSSStyleDeclaration.parsePayload(payload.styleAttributes[name]);
result.pseudoElements = [];
for (var i = 0; i < payload.pseudoElements.length; ++i) {
var entryPayload = payload.pseudoElements[i];
result.pseudoElements.push({ pseudoId: entryPayload.pseudoId, rules: WebInspector.CSSStyleModel.parseRuleArrayPayload(entryPayload.rules) });
}
result.inherited = [];
for (var i = 0; i < payload.inherited.length; ++i) {
var entryPayload = payload.inherited[i];
var entry = {};
if ("inlineStyle" in entryPayload)
entry.inlineStyle = WebInspector.CSSStyleDeclaration.parsePayload(entryPayload.inlineStyle);
if ("matchedCSSRules" in entryPayload)
entry.matchedCSSRules = WebInspector.CSSStyleModel.parseRuleArrayPayload(entryPayload.matchedCSSRules);
result.inherited.push(entry);
}
if (userCallback)
userCallback(result);
}
CSSAgent.getStylesForNode(nodeId, callback.bind(null, userCallback));
},
getComputedStyleAsync: function(nodeId, userCallback)
{
function callback(userCallback, error, stylePayload)
{
if (error)
userCallback(null);
else
userCallback(WebInspector.CSSStyleDeclaration.parsePayload(stylePayload));
}
CSSAgent.getComputedStyleForNode(nodeId, callback.bind(null, userCallback));
},
getInlineStyleAsync: function(nodeId, userCallback)
{
function callback(userCallback, error, stylePayload)
{
if (error)
userCallback(null);
else
userCallback(WebInspector.CSSStyleDeclaration.parsePayload(stylePayload));
}
CSSAgent.getInlineStyleForNode(nodeId, callback.bind(null, userCallback));
},
setRuleSelector: function(ruleId, nodeId, newSelector, successCallback, failureCallback)
{
function checkAffectsCallback(nodeId, successCallback, rulePayload, error, selectedNodeIds)
{
if (error)
return;
var doesAffectSelectedNode = (selectedNodeIds.indexOf(nodeId) >= 0);
var rule = WebInspector.CSSRule.parsePayload(rulePayload);
successCallback(rule, doesAffectSelectedNode);
this._styleSheetChanged(rule.id.styleSheetId, true);
}
function callback(nodeId, successCallback, failureCallback, error, newSelector, rulePayload)
{
// FIXME: looks like rulePayload is always null.
if (error)
failureCallback();
else
DOMAgent.querySelectorAll(nodeId, newSelector, true, checkAffectsCallback.bind(this, nodeId, successCallback, rulePayload));
}
CSSAgent.setRuleSelector(ruleId, newSelector, callback.bind(this, nodeId, successCallback, failureCallback, newSelector));
},
addRule: function(nodeId, selector, successCallback, failureCallback)
{
function checkAffectsCallback(nodeId, successCallback, rulePayload, error, selectedNodeIds)
{
var doesAffectSelectedNode = (selectedNodeIds.indexOf(nodeId) >= 0);
var rule = WebInspector.CSSRule.parsePayload(rulePayload);
successCallback(rule, doesAffectSelectedNode);
this._styleSheetChanged(rule.id.styleSheetId, true);
}
function callback(successCallback, failureCallback, selector, error, rulePayload)
{
if (error) {
// Invalid syntax for a selector
failureCallback();
} else
DOMAgent.querySelectorAll(nodeId, selector, true, checkAffectsCallback.bind(this, nodeId, successCallback, rulePayload));
}
CSSAgent.addRule(nodeId, selector, callback.bind(this, successCallback, failureCallback, selector));
},
_styleSheetChanged: function(styleSheetId, majorChange)
{
if (!majorChange || !styleSheetId)
return;
function callback(error, href, content)
{
if (error)
return;
var resource = WebInspector.resourceForURL(href);
if (resource && resource.type === WebInspector.Resource.Type.Stylesheet)
resource.setContent(content, this._onRevert.bind(this, styleSheetId));
}
CSSAgent.getStyleSheetText(styleSheetId, callback.bind(this));
},
_onRevert: function(styleSheetId, contentToRevertTo)
{
function callback(error, success)
{
if (error)
return;
this._styleSheetChanged(styleSheetId, true);
this.dispatchEventToListeners("stylesheet changed");
}
CSSAgent.setStyleSheetText(styleSheetId, contentToRevertTo, callback.bind(this));
}
}
WebInspector.CSSStyleModel.prototype.__proto__ = WebInspector.Object.prototype;
WebInspector.CSSStyleDeclaration = function(payload)
{
this.id = payload.styleId;
this.properties = payload.properties;
this._shorthandValues = payload.shorthandValues;
this._livePropertyMap = {}; // LIVE properties (source-based or style-based) : { name -> CSSProperty }
this._allProperties = []; // ALL properties: [ CSSProperty ]
this._longhandProperties = {}; // shorthandName -> [ CSSProperty ]
this.__disabledProperties = {}; // DISABLED properties: { index -> CSSProperty }
var payloadPropertyCount = payload.cssProperties.length;
var propertyIndex = 0;
for (var i = 0; i < payloadPropertyCount; ++i) {
var property = new WebInspector.CSSProperty.parsePayload(this, i, payload.cssProperties[i]);
this._allProperties.push(property);
if (property.disabled)
this.__disabledProperties[i] = property;
if (!property.active && !property.styleBased)
continue;
var name = property.name;
this[propertyIndex] = name;
this._livePropertyMap[name] = property;
// Index longhand properties.
if (property.shorthand) { // only for parsed
var longhands = this._longhandProperties[property.shorthand];
if (!longhands) {
longhands = [];
this._longhandProperties[property.shorthand] = longhands;
}
longhands.push(property);
}
++propertyIndex;
}
this.length = propertyIndex;
if ("cssText" in payload)
this.cssText = payload.cssText;
}
WebInspector.CSSStyleDeclaration.parsePayload = function(payload)
{
return new WebInspector.CSSStyleDeclaration(payload);
}
WebInspector.CSSStyleDeclaration.prototype = {
get allProperties()
{
return this._allProperties;
},
getLiveProperty: function(name)
{
return this._livePropertyMap[name];
},
getPropertyValue: function(name)
{
var property = this._livePropertyMap[name];
return property ? property.value : "";
},
getPropertyPriority: function(name)
{
var property = this._livePropertyMap[name];
return property ? property.priority : "";
},
getPropertyShorthand: function(name)
{
var property = this._livePropertyMap[name];
return property ? property.shorthand : "";
},
isPropertyImplicit: function(name)
{
var property = this._livePropertyMap[name];
return property ? property.implicit : "";
},
styleTextWithShorthands: function()
{
var cssText = "";
var foundProperties = {};
for (var i = 0; i < this.length; ++i) {
var individualProperty = this[i];
var shorthandProperty = this.getPropertyShorthand(individualProperty);
var propertyName = (shorthandProperty || individualProperty);
if (propertyName in foundProperties)
continue;
if (shorthandProperty) {
var value = this.getShorthandValue(shorthandProperty);
var priority = this.getShorthandPriority(shorthandProperty);
} else {
var value = this.getPropertyValue(individualProperty);
var priority = this.getPropertyPriority(individualProperty);
}
foundProperties[propertyName] = true;
cssText += propertyName + ": " + value;
if (priority)
cssText += " !" + priority;
cssText += "; ";
}
return cssText;
},
getLonghandProperties: function(name)
{
return this._longhandProperties[name] || [];
},
getShorthandValue: function(shorthandProperty)
{
var property = this.getLiveProperty(shorthandProperty);
return property ? property.value : this._shorthandValues[shorthandProperty];
},
getShorthandPriority: function(shorthandProperty)
{
var priority = this.getPropertyPriority(shorthandProperty);
if (priority)
return priority;
var longhands = this._longhandProperties[shorthandProperty];
return longhands ? this.getPropertyPriority(longhands[0]) : null;
},
propertyAt: function(index)
{
return (index < this.allProperties.length) ? this.allProperties[index] : null;
},
pastLastSourcePropertyIndex: function()
{
for (var i = this.allProperties.length - 1; i >= 0; --i) {
var property = this.allProperties[i];
if (property.active || property.disabled)
return i + 1;
}
return 0;
},
newBlankProperty: function()
{
return new WebInspector.CSSProperty(this, this.pastLastSourcePropertyIndex(), "", "", "", "active", true, false, false, "");
},
insertPropertyAt: function(index, name, value, userCallback)
{
function callback(userCallback, error, payload)
{
if (!userCallback)
return;
if (error)
userCallback(null);
else {
userCallback(WebInspector.CSSStyleDeclaration.parsePayload(payload));
WebInspector.cssModel._styleSheetChanged(this.id.styleSheetId, true);
}
}
CSSAgent.setPropertyText(this.id, index, name + ": " + value + ";", false, callback.bind(null, userCallback));
},
appendProperty: function(name, value, userCallback)
{
this.insertPropertyAt(this.allProperties.length, name, value, userCallback);
}
}
WebInspector.CSSRule = function(payload)
{
this.id = payload.ruleId;
this.selectorText = payload.selectorText;
this.sourceLine = payload.sourceLine;
this.sourceURL = payload.sourceURL;
this.origin = payload.origin;
this.style = WebInspector.CSSStyleDeclaration.parsePayload(payload.style);
this.style.parentRule = this;
this.selectorRange = payload.selectorRange;
}
WebInspector.CSSRule.parsePayload = function(payload)
{
return new WebInspector.CSSRule(payload);
}
WebInspector.CSSRule.prototype = {
get isUserAgent()
{
return this.origin === "user-agent";
},
get isUser()
{
return this.origin === "user";
},
get isViaInspector()
{
return this.origin === "inspector";
},
get isRegular()
{
return this.origin === "";
}
}
WebInspector.CSSProperty = function(ownerStyle, index, name, value, priority, status, parsedOk, implicit, shorthand, text)
{
this.ownerStyle = ownerStyle;
this.index = index;
this.name = name;
this.value = value;
this.priority = priority;
this.status = status;
this.parsedOk = parsedOk;
this.implicit = implicit;
this.shorthand = shorthand;
this.text = text;
}
WebInspector.CSSProperty.parsePayload = function(ownerStyle, index, payload)
{
// The following default field values are used in the payload:
// priority: ""
// parsedOk: true
// implicit: false
// status: "style"
// shorthandName: ""
var result = new WebInspector.CSSProperty(
ownerStyle, index, payload.name, payload.value, payload.priority || "", payload.status || "style", ("parsedOk" in payload) ? payload.parsedOk : true, !!payload.implicit, payload.shorthandName || "", payload.text);
return result;
}
WebInspector.CSSProperty.prototype = {
get propertyText()
{
if (this.text !== undefined)
return this.text;
if (this.name === "")
return "";
return this.name + ": " + this.value + (this.priority ? " !" + this.priority : "") + ";";
},
get isLive()
{
return this.active || this.styleBased;
},
get active()
{
return this.status === "active";
},
get styleBased()
{
return this.status === "style";
},
get inactive()
{
return this.status === "inactive";
},
get disabled()
{
return this.status === "disabled";
},
// Replaces "propertyName: propertyValue [!important];" in the stylesheet by an arbitrary propertyText.
setText: function(propertyText, majorChange, userCallback)
{
function enabledCallback(style)
{
if (style)
WebInspector.cssModel._styleSheetChanged(style.id.styleSheetId, majorChange);
if (userCallback)
userCallback(style);
}
function callback(error, stylePayload)
{
if (!error && stylePayload) {
this.text = propertyText;
var style = WebInspector.CSSStyleDeclaration.parsePayload(stylePayload);
var newProperty = style.allProperties[this.index];
if (newProperty && this.disabled && !propertyText.match(/^\s*$/)) {
newProperty.setDisabled(false, enabledCallback);
return;
} else
WebInspector.cssModel._styleSheetChanged(style.id.styleSheetId, majorChange);
if (userCallback)
userCallback(style);
} else {
if (userCallback)
userCallback(null);
}
}
if (!this.ownerStyle)
throw "No ownerStyle for property";
// An index past all the properties adds a new property to the style.
CSSAgent.setPropertyText(this.ownerStyle.id, this.index, propertyText, this.index < this.ownerStyle.pastLastSourcePropertyIndex(), callback.bind(this));
},
setValue: function(newValue, userCallback)
{
var text = this.name + ": " + newValue + (this.priority ? " !" + this.priority : "") + ";"
this.setText(text, userCallback);
},
setDisabled: function(disabled, userCallback)
{
if (!this.ownerStyle && userCallback)
userCallback(null);
if (disabled === this.disabled && userCallback)
userCallback(this.ownerStyle);
function callback(error, stylePayload)
{
if (!userCallback)
return;
if (error)
userCallback(null);
else {
var style = WebInspector.CSSStyleDeclaration.parsePayload(stylePayload);
userCallback(style);
WebInspector.cssModel._styleSheetChanged(this.ownerStyle.id.styleSheetId, false);
}
}
CSSAgent.toggleProperty(this.ownerStyle.id, this.index, disabled, callback.bind(this));
}
}
WebInspector.CSSStyleSheet = function(payload)
{
this.id = payload.styleSheetId;
this.sourceURL = payload.sourceURL;
this.title = payload.title;
this.disabled = payload.disabled;
this.rules = [];
this.styles = {};
for (var i = 0; i < payload.rules.length; ++i) {
var rule = WebInspector.CSSRule.parsePayload(payload.rules[i]);
this.rules.push(rule);
if (rule.style)
this.styles[rule.style.id] = rule.style;
}
if ("text" in payload)
this._text = payload.text;
}
WebInspector.CSSStyleSheet.createForId = function(styleSheetId, userCallback)
{
function callback(error, styleSheetPayload)
{
if (error)
userCallback(null);
else
userCallback(new WebInspector.CSSStyleSheet(styleSheetPayload));
}
CSSAgent.getStyleSheet(styleSheetId, callback.bind(this));
}
WebInspector.CSSStyleSheet.prototype = {
getText: function()
{
return this._text;
},
setText: function(newText, userCallback)
{
function callback(error, styleSheetPayload)
{
if (error)
userCallback(null);
else {
userCallback(new WebInspector.CSSStyleSheet(styleSheetPayload));
WebInspector.cssModel._styleSheetChanged(this.id, true);
}
}
CSSAgent.setStyleSheetText(this.id, newText, callback.bind(this));
}
}
| Alberto-Beralix/Beralix | i386-squashfs-root/usr/share/webkitgtk-3.0/webinspector/CSSStyleModel.js | JavaScript | gpl-3.0 | 19,784 |
(function($,window,WSU_THEME) {
$.extend( WSU_THEME, {
state:{
debug:false,
}
});
})(jQuery,window,jQuery.wsu_theme||(jQuery.wsu_theme={})); | washingtonstateuniversity/WSUMAGE-theme-base | skin/frontend/wsu_base/default/src/js/wsu_theme.state.js | JavaScript | gpl-3.0 | 149 |
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'./insert',
'mageUtils',
'jquery'
], function (Insert, utils, $) {
'use strict';
/**
* Get page actions element.
*
* @param {String} elem
* @param {String} actionsClass
* @returns {String}
*/
function getPageActions(elem, actionsClass) {
var el = document.createElement('div');
el.innerHTML = elem;
return el.getElementsByClassName(actionsClass)[0];
}
/**
* Return element without page actions toolbar
*
* @param {String} elem
* @param {String} actionsClass
* @returns {String}
*/
function removePageActions(elem, actionsClass) {
var el = document.createElement('div'),
actions;
el.innerHTML = elem;
actions = el.getElementsByClassName(actionsClass)[0];
el.removeChild(actions);
return el.innerHTML;
}
return Insert.extend({
defaults: {
externalFormName: '${ $.ns }.${ $.ns }',
pageActionsClass: 'page-actions',
actionsContainerClass: 'page-main-actions',
exports: {
prefix: '${ $.externalFormName }:selectorPrefix'
},
imports: {
toolbarSection: '${ $.toolbarContainer }:toolbarSection',
prefix: '${ $.toolbarContainer }:rootSelector',
messagesClass: '${ $.externalFormName }:messagesClass'
},
settings: {
ajax: {
ajaxSave: true,
exports: {
ajaxSave: '${ $.externalFormName }:ajaxSave'
},
imports: {
responseStatus: '${ $.externalFormName }:responseStatus',
responseData: '${ $.externalFormName }:responseData'
}
}
},
modules: {
externalForm: '${ $.externalFormName }'
}
},
/** @inheritdoc */
initObservable: function () {
return this._super()
.observe('responseStatus');
},
/** @inheritdoc */
initConfig: function (config) {
var defaults = this.constructor.defaults;
utils.extend(defaults, defaults.settings[config.formSubmitType] || {});
return this._super();
},
/** @inheritdoc*/
destroyInserted: function () {
if (this.isRendered && this.externalForm()) {
this.externalForm().delegate('destroy');
this.removeActions();
this.responseStatus(undefined);
this.responseData = {};
}
return this._super();
},
/** @inheritdoc */
onRender: function (data) {
var actions = getPageActions(data, this.pageActionsClass);
if (!data.length) {
return this;
}
data = removePageActions(data, this.pageActionsClass);
this.renderActions(actions);
this._super(data);
},
/**
* Insert actions in toolbar.
*
* @param {String} actions
*/
renderActions: function (actions) {
var $container = $('<div/>');
$container
.addClass(this.actionsContainerClass)
.append(actions);
this.formHeader = $container;
$(this.toolbarSection).append(this.formHeader);
},
/**
* Remove actions toolbar.
*/
removeActions: function () {
$(this.formHeader).siblings('.' + this.messagesClass).remove();
$(this.formHeader).remove();
this.formHeader = $();
},
/**
* Reset external form data.
*/
resetForm: function () {
if (this.externalSource()) {
this.externalSource().trigger('data.reset');
this.responseStatus(undefined);
}
}
});
});
| rajmahesh/magento2-master | vendor/magento/module-ui/view/base/web/js/form/components/insert-form.js | JavaScript | gpl-3.0 | 4,200 |
/**
* GaiaEHR (Electronic Health Records)
* Copyright (C) 2013 Certun, LLC.
*
* 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 3 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 <http://www.gnu.org/licenses/>.
*/
Ext.define('App.store.administration.Modules', {
model: 'App.model.administration.Modules',
extend: 'Ext.data.Store'
}); | gaiaehr/gaiaehr | app/store/administration/Modules.js | JavaScript | gpl-3.0 | 862 |
'use strict';
(function() {
var interpolationTests = [];
var cssAnimationsData = {
sharedStyle: null,
nextID: 0,
};
var expectNoInterpolation = {};
var neutralKeyframe = {};
function isNeutralKeyframe(keyframe) {
return keyframe === neutralKeyframe;
}
// For the CSS interpolation methods, we set the animation duration long
// enough that any advancement in time during the test is irrelevant in terms
// of the progress. We then set the delay to be negative half the duration, so
// we are immediately at the halfway point of the animation. Finally, we use
// an easing function that maps halfway to whatever progress we actually want.
var cssAnimationsInterpolation = {
name: 'CSS Animations',
supportsProperty: function() {return true;},
supportsValue: function() {return true;},
setup: function() {},
nonInterpolationExpectations: function(from, to) {
return expectFlip(from, to, 0.5);
},
interpolate: function(property, from, to, at, target) {
var id = cssAnimationsData.nextID++;
if (!cssAnimationsData.sharedStyle) {
cssAnimationsData.sharedStyle = createElement(document.body, 'style');
}
cssAnimationsData.sharedStyle.textContent += '' +
'@keyframes animation' + id + ' {' +
(isNeutralKeyframe(from) ? '' : `from {${property}:${from};}`) +
(isNeutralKeyframe(to) ? '' : `to {${property}:${to};}`) +
'}';
target.style.animationName = 'animation' + id;
target.style.animationDuration = '2e9s';
target.style.animationDelay = '-1e9s';
target.style.animationTimingFunction = createEasing(at);
},
};
var cssTransitionsInterpolation = {
name: 'CSS Transitions',
supportsProperty: function() {return true;},
supportsValue: function() {return true;},
setup: function(property, from, target) {
target.style.setProperty(property, isNeutralKeyframe(from) ? '' : from);
},
nonInterpolationExpectations: function(from, to) {
return expectFlip(from, to, -Infinity);
},
interpolate: function(property, from, to, at, target) {
// Force a style recalc on target to set the 'from' value.
getComputedStyle(target).left;
target.style.transitionDuration = '2e9s';
target.style.transitionDelay = '-1e9s';
target.style.transitionTimingFunction = createEasing(at);
target.style.transitionProperty = property;
target.style.setProperty(property, isNeutralKeyframe(to) ? '' : to);
},
};
var cssTransitionAllInterpolation = {
name: 'CSS Transitions with transition: all',
// The 'all' value doesn't cover custom properties.
supportsProperty: function(property) {return property.indexOf('--') !== 0;},
supportsValue: function() {return true;},
setup: function(property, from, target) {
target.style.setProperty(property, isNeutralKeyframe(from) ? '' : from);
},
nonInterpolationExpectations: function(from, to) {
return expectFlip(from, to, -Infinity);
},
interpolate: function(property, from, to, at, target) {
// Force a style recalc on target to set the 'from' value.
getComputedStyle(target).left;
target.style.transitionDuration = '2e9s';
target.style.transitionDelay = '-1e9s';
target.style.transitionTimingFunction = createEasing(at);
target.style.transitionProperty = 'all';
target.style.setProperty(property, isNeutralKeyframe(to) ? '' : to);
},
};
var webAnimationsInterpolation = {
name: 'Web Animations',
supportsProperty: function(property) {return true;},
supportsValue: function(value) {return value !== '';},
setup: function() {},
nonInterpolationExpectations: function(from, to) {
return expectFlip(from, to, 0.5);
},
interpolate: function(property, from, to, at, target) {
this.interpolateComposite(property, from, 'replace', to, 'replace', at, target);
},
interpolateComposite: function(property, from, fromComposite, to, toComposite, at, target) {
// Convert standard properties to camelCase.
if (!property.startsWith('--')) {
for (var i = property.length - 2; i > 0; --i) {
if (property[i] === '-') {
property = property.substring(0, i) + property[i + 1].toUpperCase() + property.substring(i + 2);
}
}
if (property === 'offset')
property = 'cssOffset';
}
var keyframes = [];
if (!isNeutralKeyframe(from)) {
keyframes.push({
offset: 0,
composite: fromComposite,
[property]: from,
});
}
if (!isNeutralKeyframe(to)) {
keyframes.push({
offset: 1,
composite: toComposite,
[property]: to,
});
}
var animation = target.animate(keyframes, {
fill: 'forwards',
duration: 1,
easing: createEasing(at),
});
animation.pause();
animation.currentTime = 0.5;
},
};
function expectFlip(from, to, flipAt) {
return [-0.3, 0, 0.3, 0.5, 0.6, 1, 1.5].map(function(at) {
return {
at: at,
expect: at < flipAt ? from : to
};
});
}
// Constructs a timing function which produces 'y' at x = 0.5
function createEasing(y) {
if (y == 0) {
return 'steps(1, end)';
}
if (y == 1) {
return 'steps(1, start)';
}
if (y == 0.5) {
return 'steps(2, end)';
}
// Approximate using a bezier.
var b = (8 * y - 1) / 6;
return 'cubic-bezier(0, ' + b + ', 1, ' + b + ')';
}
function createElement(parent, tag, text) {
var element = document.createElement(tag || 'div');
element.textContent = text || '';
parent.appendChild(element);
return element;
}
function createTargetContainer(parent, className) {
var targetContainer = createElement(parent);
targetContainer.classList.add('container');
var template = document.querySelector('#target-template');
if (template) {
targetContainer.appendChild(template.content.cloneNode(true));
}
var target = targetContainer.querySelector('.target') || targetContainer;
target.classList.add('target', className);
target.parentElement.classList.add('parent');
targetContainer.target = target;
return targetContainer;
}
function roundNumbers(value) {
return value.
// Round numbers to two decimal places.
replace(/-?\d*\.\d+(e-?\d+)?/g, function(n) {
return (parseFloat(n).toFixed(2)).
replace(/\.\d+/, function(m) {
return m.replace(/0+$/, '');
}).
replace(/\.$/, '').
replace(/^-0$/, '0');
});
}
var anchor = document.createElement('a');
function sanitizeUrls(value) {
var matches = value.match(/url\("([^#][^\)]*)"\)/g);
if (matches !== null) {
for (var i = 0; i < matches.length; ++i) {
var url = /url\("([^#][^\)]*)"\)/g.exec(matches[i])[1];
anchor.href = url;
anchor.pathname = '...' + anchor.pathname.substring(anchor.pathname.lastIndexOf('/'));
value = value.replace(matches[i], 'url(' + anchor.href + ')');
}
}
return value;
}
function normalizeValue(value) {
return roundNumbers(sanitizeUrls(value)).
// Place whitespace between tokens.
replace(/([\w\d.]+|[^\s])/g, '$1 ').
replace(/\s+/g, ' ');
}
function stringify(text) {
if (!text.includes("'")) {
return `'${text}'`;
}
return `"${text.replace('"', '\\"')}"`;
}
function keyframeText(keyframe) {
return isNeutralKeyframe(keyframe) ? 'neutral' : `[${keyframe}]`;
}
function keyframeCode(keyframe) {
return isNeutralKeyframe(keyframe) ? 'neutralKeyframe' : `${stringify(keyframe)}`;
}
function createInterpolationTestTargets(interpolationMethod, interpolationMethodContainer, interpolationTest) {
var property = interpolationTest.options.property;
var from = interpolationTest.options.from;
var to = interpolationTest.options.to;
var comparisonFunction = interpolationTest.options.comparisonFunction;
if ((interpolationTest.options.method && interpolationTest.options.method != interpolationMethod.name)
|| !interpolationMethod.supportsProperty(property)
|| !interpolationMethod.supportsValue(from)
|| !interpolationMethod.supportsValue(to)) {
return;
}
var testText = `${interpolationMethod.name}: property <${property}> from ${keyframeText(from)} to ${keyframeText(to)}`;
var testContainer = createElement(interpolationMethodContainer, 'div');
createElement(testContainer);
var expectations = interpolationTest.expectations;
if (expectations === expectNoInterpolation) {
expectations = interpolationMethod.nonInterpolationExpectations(from, to);
}
// Setup a standard equality function if an override is not provided.
if (!comparisonFunction) {
comparisonFunction = (actual, expected) => {
assert_equals(normalizeValue(actual), normalizeValue(expected));
};
}
return expectations.map(function(expectation) {
var actualTargetContainer = createTargetContainer(testContainer, 'actual');
var expectedTargetContainer = createTargetContainer(testContainer, 'expected');
if (!isNeutralKeyframe(expectation.expect)) {
expectedTargetContainer.target.style.setProperty(property, expectation.expect);
}
var target = actualTargetContainer.target;
interpolationMethod.setup(property, from, target);
target.interpolate = function() {
interpolationMethod.interpolate(property, from, to, expectation.at, target);
};
target.measure = function() {
var expectedValue = getComputedStyle(expectedTargetContainer.target).getPropertyValue(property);
test(function() {
if (from && from !== neutralKeyframe) {
assert_true(CSS.supports(property, from), '\'from\' value should be supported');
}
if (to && to !== neutralKeyframe) {
assert_true(CSS.supports(property, to), '\'to\' value should be supported');
}
if (typeof underlying !== 'undefined') {
assert_true(CSS.supports(property, underlying), '\'underlying\' value should be supported');
}
comparisonFunction(
getComputedStyle(target).getPropertyValue(property),
expectedValue);
}, `${testText} at (${expectation.at}) should be [${sanitizeUrls(expectedValue)}]`);
};
return target;
});
}
function createTestTargets(interpolationMethods, interpolationTests, container) {
var targets = [];
for (var interpolationMethod of interpolationMethods) {
var interpolationMethodContainer = createElement(container);
for (var interpolationTest of interpolationTests) {
[].push.apply(targets, createInterpolationTestTargets(interpolationMethod, interpolationMethodContainer, interpolationTest));
}
}
return targets;
}
function test_no_interpolation(options) {
test_interpolation(options, expectNoInterpolation);
}
function test_interpolation(options, expectations) {
interpolationTests.push({options, expectations});
var interpolationMethods = [
cssTransitionsInterpolation,
cssTransitionAllInterpolation,
cssAnimationsInterpolation,
webAnimationsInterpolation,
];
var container = createElement(document.body);
var targets = createTestTargets(interpolationMethods, interpolationTests, container);
// Separate interpolation and measurement into different phases to avoid O(n^2) of the number of targets.
for (var target of targets) {
target.interpolate();
}
for (var target of targets) {
target.measure();
}
container.remove();
interpolationTests = [];
}
window.test_interpolation = test_interpolation;
window.test_no_interpolation = test_no_interpolation;
window.neutralKeyframe = neutralKeyframe;
})();
| nnethercote/servo | tests/wpt/web-platform-tests/css/support/interpolation-testcommon.js | JavaScript | mpl-2.0 | 12,099 |
'use strict';
// Core node modules
var path = require('path');
// Third party libs
var when = require('when');
var activitiesDir = path.join(__dirname, '../../../src/activities');
// Return a function that behaves like getActivities. Taking no parameters and
// returning a promise that resolves to a list of activity objects. In this
// case, it'll be just the example.
module.exports = function() {
return when([{
slug: 'example',
directory: path.join(activitiesDir, 'example'),
configFile: path.join(activitiesDir, 'example/config.json'),
serverIndex: path.join(activitiesDir, 'example/index.js')
}]);
};
| councilforeconed/interactive-activities | test/server/mock/mock_getactivities.js | JavaScript | mpl-2.0 | 632 |
import React from 'react';
import ReactDOM from 'react-dom';
import Nested from './nested-component';
class Popup extends React.Component {
constructor(props) {
super(props);
this.state = {activeTab: null};
}
componentDidMount() {
// Get the active tab and store it in component state.
chrome.tabs.query({active: true}, tabs => {
this.setState({activeTab: tabs[0]});
});
}
render() {
const {activeTab} = this.state;
return (
<div>
<h1>React Component</h1>
<p>
This is an example of a popup UI in React.
</p>
<p>
Active tab: {activeTab ? activeTab.url : '[waiting for result]'}
</p>
<Nested />
</div>
);
}
}
ReactDOM.render(<Popup/>, document.getElementById('app'));
| matthewjwein/webextensions-examples | react-es6-popup/src/popup.js | JavaScript | mpl-2.0 | 801 |
(function() {
function mapConfig() {
return $(this).data('widget');
}
window.Dashboard = {
serializeColumn: function(col) {
return $('div.dashboard_column:nth-child('+col+') fieldset.widget').map(mapConfig).get();
},
serialize: function() {
return [
Dashboard.serializeColumn(1),
Dashboard.serializeColumn(2),
Dashboard.serializeColumn(3)
];
},
saveDashboard: function() {
var config = Dashboard.serialize();
console.log('Dashboard Change', config);
$.ajax({
type: 'PUT',
url: '/dashboard',
data: JSON.stringify({dashboard: config }),
contentType: 'application/json; charset=UTF-8',
processData: false,
dataType: 'json'
}).done(function(data, status, XHR) {
console.log('Success?', data);
}).fail(function(XHR, status, error) {
console.log('Fail!');
});
}
};
$(function() {
$('div.dashboard_column').sortable({
connectWith: 'div.dashboard_column',
distance: 5,
cursor: 'crosshair',
cancel: '.content',
update: function(e, ui) { if (ui.sender == null) Dashboard.saveDashboard(); }
});
});
})();
| OutOfOrder/HumbleBugs | app/assets/javascripts/controllers/dashboard.js | JavaScript | agpl-3.0 | 1,412 |
import * as _stats from './stats';
import * as _settings from './settings';
import * as _workspace from './workspace';
import * as _workspaceMeta from './workspace-meta';
import * as _environment from './environment';
import * as _cookieJar from './cookie-jar';
import * as _requestGroup from './request-group';
import * as _requestGroupMeta from './request-group-meta';
import * as _request from './request';
import * as _requestMeta from './request-meta';
import * as _response from './response';
import * as _oAuth2Token from './o-auth-2-token';
// Reference to each model
export const stats = _stats;
export const settings = _settings;
export const workspace = _workspace;
export const workspaceMeta = _workspaceMeta;
export const environment = _environment;
export const cookieJar = _cookieJar;
export const requestGroup = _requestGroup;
export const requestGroupMeta = _requestGroupMeta;
export const request = _request;
export const requestMeta = _requestMeta;
export const response = _response;
export const oAuth2Token = _oAuth2Token;
const _models = {
[stats.type]: stats,
[settings.type]: settings,
[workspace.type]: workspace,
[workspaceMeta.type]: workspaceMeta,
[environment.type]: environment,
[cookieJar.type]: cookieJar,
[requestGroup.type]: requestGroup,
[requestGroupMeta.type]: requestGroupMeta,
[request.type]: request,
[requestMeta.type]: requestMeta,
[response.type]: response,
[oAuth2Token.type]: oAuth2Token
};
export function all () {
return Object.keys(_models).map(type => _models[type]);
}
export function types () {
return all().map(model => model.type);
}
export function getModel (type) {
return _models[type] || null;
}
export function canDuplicate (type) {
const model = getModel(type);
return model ? model.canDuplicate : false;
}
export function getModelName (type, count = 1) {
const model = getModel(type);
if (!model) {
return 'Unknown';
} else if (count === 1) {
return model.name;
} else if (!model.name.match(/s$/)) {
// Add an 's' if it doesn't already end in one
return `${model.name}s`;
} else {
return model.name;
}
}
export function initModel (type, ...sources) {
const model = getModel(type);
// Define global default fields
const objectDefaults = Object.assign({
type: type,
_id: null,
parentId: null,
modified: Date.now(),
created: Date.now()
}, model.init());
// Make a new object
const fullObject = Object.assign({}, objectDefaults, ...sources);
// Migrate the model
// NOTE: Do migration before pruning because we might need to look at those fields
model.migrate(fullObject);
// Prune extra keys from doc
for (const key of Object.keys(fullObject)) {
if (!objectDefaults.hasOwnProperty(key)) {
delete fullObject[key];
}
}
return fullObject;
}
| PavanKu/insomnia | app/models/index.js | JavaScript | agpl-3.0 | 2,834 |
import CoreCooldownThroughputTracker, { BUILT_IN_SUMMARY_TYPES } from 'Parser/Core/Modules/CooldownThroughputTracker';
import SPELLS from 'common/SPELLS';
const debug = false;
class CooldownThroughputTracker extends CoreCooldownThroughputTracker {
static cooldownSpells = [
...CooldownThroughputTracker.cooldownSpells,
{
spell: SPELLS.SOUL_HARVEST_TALENT,
summary: [
BUILT_IN_SUMMARY_TYPES.DAMAGE,
],
},
];
//for the sake of completeness, typically none of these are used
static castCooldowns = [
{
spell: SPELLS.SUMMON_INFERNAL_UNTALENTED,
duration: 25,
summary: [
BUILT_IN_SUMMARY_TYPES.DAMAGE,
],
},
{
spell: SPELLS.SUMMON_DOOMGUARD_UNTALENTED,
duration: 25,
summary: [
BUILT_IN_SUMMARY_TYPES.DAMAGE,
],
},
{
spell: SPELLS.GRIMOIRE_IMP,
duration: 25,
summary: [
BUILT_IN_SUMMARY_TYPES.DAMAGE,
],
},
{
spell: SPELLS.GRIMOIRE_VOIDWALKER,
duration: 25,
summary: [
BUILT_IN_SUMMARY_TYPES.DAMAGE,
],
},
{
spell: SPELLS.GRIMOIRE_SUCCUBUS,
duration: 25,
summary: [
BUILT_IN_SUMMARY_TYPES.DAMAGE,
],
},
{
spell: SPELLS.GRIMOIRE_FELHUNTER,
duration: 25,
summary: [
BUILT_IN_SUMMARY_TYPES.DAMAGE,
],
},
];
on_byPlayer_cast(event) {
const spellId = event.ability.guid;
const cooldownSpell = this.constructor.castCooldowns.find(cooldownSpell => cooldownSpell.spell.id === spellId);
if (cooldownSpell) {
// adding the fixed cooldown, now we need to remove it from activeCooldowns too
const cooldown = this._addFixedCooldown(cooldownSpell, event.timestamp);
this.activeCooldowns.push(cooldown);
debug && console.log(`%cCooldown started: ${cooldownSpell.spell.name}`, 'color: green', cooldown);
}
// super.on_byPlayer_cast(event) would call trackEvent anyway
super.on_byPlayer_cast && super.on_byPlayer_cast(event);
}
_addFixedCooldown(cooldownSpell, timestamp) {
const cooldown = {
...cooldownSpell,
start: timestamp,
end: timestamp + cooldownSpell.duration * 1000,
events: [],
};
this.pastCooldowns.push(cooldown);
return cooldown;
}
// on_event() might be more accurate but it would be most likely called much more
trackEvent(event) {
this.activeCooldowns = this.activeCooldowns.filter(cooldown => !cooldown.end || event.timestamp < cooldown.end);
super.trackEvent(event);
}
on_byPlayerPet_damage(event) {
this.trackEvent(event);
}
}
export default CooldownThroughputTracker;
| enragednuke/WoWAnalyzer | src/Parser/Warlock/Affliction/Modules/Features/CooldownThroughputTracker.js | JavaScript | agpl-3.0 | 2,682 |
// Some content here.
var code = 'hello';
// This comment contains # multiple
// hash signs (#).
code = 'hello';
/**
* This is the first line of a function comment.
* This is the second line.
*/
function testFunction()
{
// Callback methods which are added by external objects.
this.callbacks = {};
}//end testFunction()
/**
* This is the first line of a class comment.
* This is the second line.
*/
myClass.prototype = {
/**
* This is the first line of a method comment.
* This is the second line.
*/
load: function(url, callback)
{
// Some code here.
}
};
// some code goes here!
/*
A longer comment goes here.
It spans multiple lines!!
Or does it?
*/
// 0This is a simple multi-line
// comment!
code = 'hello';
//This is not valid.
code = 'hello';
// Neither is this!
code = 'hello';
//
code = 'hello';
/** Neither is this! **/
code = 'hello';
/**
* This is the first line of a function comment.
* This is the second line.
*/
var myFunction = function() {
}
/**
* This is the first line of a function comment.
* This is the second line.
*/
myFunction = function() {
}
/**
* This is the first line of a function comment.
* This is the second line.
*/
myClass.myFunction = function() {
} | shashank19gaurav/tatoeba2 | tools/PHP_CodeSniffer-1.2.1/CodeSniffer/Standards/Squiz/Tests/Commenting/InlineCommentUnitTest.js | JavaScript | agpl-3.0 | 1,279 |
/*
* Copyright (C) 2012-2013 B3Partners B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Custom configuration object for HTML configuration
* @author <a href="mailto:roybraam@b3partners.nl">Roy Braam</a>
*/
Ext.define("viewer.components.CustomConfiguration",{
extend: "viewer.components.SelectionWindowConfig",
constructor: function (parentId, configObject, configPage) {
configObject.showLabelconfig =true;
viewer.components.CustomConfiguration.superclass.constructor.call(this, parentId, configObject, configPage);
this.createCheckBoxes(this.configObject.layers,{filterable: true});
var me = this;
this.form.add([{
xtype: 'checkbox',
fieldLabel: i18next.t('spatialfilter_config_0'),
inputValue: true,
name: 'applyDirect',
checked: this.configObject.applyDirect!==undefined? this.configObject.applyDirect : true,
//value: true,
labelWidth:me.labelWidth
},
{
xtype: 'checkbox',
fieldLabel: i18next.t('spatialfilter_config_1'),
inputValue: true,
name: 'multiGeometries',
checked: this.configObject.multiGeometries!==undefined? this.configObject.multiGeometries : false,
//value: false,
labelWidth:me.labelWidth
}
]);
},
getDefaultValues: function() {
return {
details: {
minWidth: 330,
minHeight: 270
}
};
}
});
| B3Partners/flamingo | viewer/src/main/webapp/viewer-html/components/SpatialFilter-config.js | JavaScript | agpl-3.0 | 2,265 |
'use strict';
/* jasmine specs for filters go here */
//
describe('filter', function () {
beforeEach(module('KMC.filters'));
describe('startFrom', function () {
it('should cut the beginging of a string by a set number of characters ', inject(function ($filter) {
var startFrom = $filter('startFrom');
expect(startFrom('CUTlongString', 3)).toEqual('longString');
}));
});
describe('range', function () {
it('should fill an array with numbers from lower to upper bounds (arguments) ', inject(function ($filter) {
var range = $filter('range');
expect(range([3])).toEqual([0, 1, 2]);
expect(range([1, 3])).toEqual([1, 2, 3]);
}));
});
describe('timeago', function () {
it('should use the timeago 3rd party to convert timestamps to nicely formated strings ', inject(function ($filter) {
var timeago = $filter('timeago');
var now = Math.round(+new Date()/1000);
expect(timeago(now)).toEqual('less than a minute ago');
var yesterday = (new Date().getTime()-(24*60*60*1000))/1000;
expect(timeago(yesterday)).toEqual('a day ago');
}));
});
describe('HTMLunsafe',function(){
it('should allow any HTML to pass though',inject(function($filter){
var htmlunsafe = $filter('HTMLunsafe');
var nastyInput = '<script >console.log("very nasty stuff");</script>';
var unsafe = htmlunsafe(nastyInput).$$unwrapTrustedValue();
expect(unsafe).toBe(nastyInput);
}));
});
});
| kaltura/player-studio | test/unit/filtersSpec.js | JavaScript | agpl-3.0 | 1,617 |
// --
// Copyright (C) 2001-2017 OTRS AG, http://otrs.com/
// --
// This software comes with ABSOLUTELY NO WARRANTY. For details, see
// the enclosed file COPYING for license information (AGPL). If you
// did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
// --
"use strict";
var Core = Core || {};
Core.Agent = Core.Agent || {};
/**
* @namespace Core.Agent.TicketAction
* @memberof Core.Agent
* @author OTRS AG
* @description
* This namespace contains functions for all ticket action popups.
*/
Core.Agent.TicketAction = (function (TargetNS) {
/**
* @private
* @name SerializeData
* @memberof Core.Agent.TicketAction
* @function
* @returns {String} A query string based on the given hash.
* @param {Object} Data - The data that should be serialized
* @description
* Converts a given hash into a query string.
*/
function SerializeData(Data) {
var QueryString = '';
$.each(Data, function (Key, Value) {
QueryString += ';' + encodeURIComponent(Key) + '=' + encodeURIComponent(Value);
});
return QueryString;
}
/**
* @private
* @name OpenCustomerUserAddressBook
* @memberof Core.Agent.TicketAction
* @function
* @param {String} RecipientField - The recipient field name to add the selected recipients in the correct field.
* @param {String} RecipientFieldLabel - The recipient field label for the output in the address book screen.
* @param {String} RecipientType - The recipient type for the diffrent screens.
* @description
* Open the AgentCustomerUserAddressBook screen.
*/
function OpenCustomerUserAddressBook(RecipientField, RecipientFieldLabel, RecipientType) {
var CustomerUserAddressBookIFrameURL, CustomerUserAddressBookIFrame;
CustomerUserAddressBookIFrameURL = Core.Config.Get('CGIHandle') + '?Action=AgentCustomerUserAddressBook;RecipientField=' + RecipientField + ';RecipientFieldLabel=' + RecipientFieldLabel + ';RecipientType=' + RecipientType;
CustomerUserAddressBookIFrameURL += SerializeData(Core.App.GetSessionInformation());
CustomerUserAddressBookIFrame = '<iframe class="TextOption CustomerUserAddressBook" src="' + CustomerUserAddressBookIFrameURL + '"></iframe>';
Core.UI.Dialog.ShowContentDialog(CustomerUserAddressBookIFrame, '', '10px', 'Center', true);
}
/**
* @private
* @name OpenCustomerDialog
* @memberof Core.Agent.TicketAction
* @function
* @description
* Open the CustomerDialog screen.
*/
function OpenCustomerDialog() {
var CustomerIFrameURL, CustomerIFrame;
CustomerIFrameURL = Core.Config.Get('CGIHandle') + '?Action=AdminCustomerUser;Nav=None;Subject=;What=';
CustomerIFrameURL += SerializeData(Core.App.GetSessionInformation());
CustomerIFrame = '<iframe class="TextOption Customer" src="' + CustomerIFrameURL + '"></iframe>';
Core.UI.Dialog.ShowContentDialog(CustomerIFrame, '', '10px', 'Center', true);
}
/**
* @private
* @name OpenCustomerIDSelection
* @memberof Core.Agent.TicketAction
* @function
* @description
* Open the CustomerIDSelectionDialog screen.
*/
function OpenCustomerIDSelection() {
var Data = {
Action: 'AgentCustomerSearch',
Subaction: 'AssignedCustomerIDs',
CustomerUserID: $('#SelectedCustomerUser').val(),
};
$('#SelectionCustomerIDAssigned').empty();
Core.AJAX.FunctionCall(Core.Config.Get('Baselink'), Data, function (Response) {
$.each(Response, function(Index, CustomerID) {
var CustomerIDOption = new Option(CustomerID, CustomerID);
// Overwrite option text, because of wrong html quoting of text content.
// (This is needed for IE.)
CustomerIDOption.innerHTML = CustomerID;
$('#SelectionCustomerIDAssigned').append(CustomerIDOption);
});
if (!$('#SelectionCustomerIDAssigned > option').length) {
$('#TemplateSelectionCustomerID fieldset:last').addClass('Hidden');
}
else {
$('#TemplateSelectionCustomerID fieldset:last').removeClass('Hidden');
}
Core.UI.Dialog.ShowContentDialog($('#TemplateSelectionCustomerID'), Core.Language.Translate('Select a customer ID to assign to this ticket'), '10px', 'Center', true);
Core.Agent.CustomerSearch.InitSimple($('#SelectionCustomerIDAll'));
$('#SelectionCustomerIDAssigned').val($('#CustomerID').val()).trigger('redraw.InputField').trigger('change');
$('#SelectionCustomerIDAll').on('select.Autocomplete', function() {
CloseCustomerIDSelection($(this).val());
});
$('#SelectionCustomerIDAssigned').on('change', function() {
CloseCustomerIDSelection($(this).val());
});
});
}
/**
* @private
* @name CloseCustomerIDSelection
* @memberof Core.Agent.TicketAction
* @function
* @param {String} CustomerID - The selected customer ID value.
* @description
* Close the customer ID selection dialog.
*/
function CloseCustomerIDSelection(CustomerID) {
$('#CustomerID').val(CustomerID);
$('#ShowCustomerID').html(CustomerID);
Core.UI.Dialog.CloseDialog($('.Dialog'));
}
/**
* @private
* @name MarkPrimaryCustomer
* @memberof Core.Agent.TicketAction
* @function
* @description
* Mark the primary customer.
*/
function MarkPrimaryCustomer() {
$('.CustomerContainer').children('div').each(function() {
var $InputObj = $(this).find('.CustomerTicketText'),
$RadioObj = $(this).find('.CustomerTicketRadio');
if ($RadioObj.prop('checked')) {
$InputObj.addClass('MainCustomer');
}
else {
$InputObj.removeClass('MainCustomer');
}
});
}
/**
* @name Init
* @memberof Core.Agent.TicketAction
* @function
* @description
* This function initializes the ticket action popups.
*/
TargetNS.Init = function () {
$('.OptionCustomerUserAddressBook').on('click', function () {
OpenCustomerUserAddressBook($(this).data('recipient-field'), $(this).data('recipient-field-label'), $(this).data('recipient-type'));
return false;
});
// Register event for customer dialog
$('#OptionCustomer').on('click', function () {
OpenCustomerDialog();
return false;
});
// Register the event for customer id selection dialog.
$('#SelectionCustomerID').on('click', function () {
OpenCustomerIDSelection();
return false;
});
// Deactivate the fields in the template.
Core.UI.InputFields.Deactivate($('#TemplateSelectionCustomerID'));
// Subscribe to the reloading of the CustomerInfo box to
// specially mark the primary customer
MarkPrimaryCustomer();
Core.App.Subscribe('Event.Agent.CustomerSearch.GetCustomerInfo.Callback', function() {
MarkPrimaryCustomer();
});
// Prevent form submit, if To, CC or Bcc are not correctly saved yet
// see http://bugs.otrs.org/show_bug.cgi?id=10022 for details
$('#submitRichText').on('click', function (Event) {
var ToCustomer = $('#ToCustomer').val() || '',
CcCustomer = $('#CcCustomer').val() || '',
BccCustomer = $('#BccCustomer').val() || '',
// only for AgentTicketPhone
FromCustomer = $('#FromCustomer').val() || '';
if (ToCustomer.length || CcCustomer.length || BccCustomer.length || FromCustomer.length) {
window.setTimeout(function () {
$('#submitRichText').trigger('click');
}, 100);
Event.preventDefault();
Event.stopPropagation();
return false;
}
});
// Subscribe to ToggleWidget event to handle special behaviour in ticket action screens
Core.App.Subscribe('Event.UI.ToggleWidget', function ($WidgetElement) {
if ($WidgetElement.attr('id') !== 'WidgetArticle') {
return;
}
// If widget is being expanded, activate checkbox to create article.
if ($WidgetElement.hasClass('Expanded')) {
$('#CreateArticle').prop('checked', true);
}
});
};
/**
* @name UpdateCustomer
* @memberof Core.Agent.TicketAction
* @function
* @param {String} Customer - The customer that was selected in the customer popup window.
* @description
* In some screens, the customer management dialog can be used as a borrowed view
* (iframe in a dialog). This function is used to take over the currently selected
* customer into the main window, closing the dialog.
*/
TargetNS.UpdateCustomer = function (Customer) {
var $UpdateForm = $('form[name=compose]', parent.document);
$UpdateForm
.find('#ExpandCustomerName').val('2')
.end()
.find('#PreSelectedCustomerUser').val(Customer)
.end()
.submit();
// Because we are in an iframe, we need to call the parent frames javascript function
// with a jQuery object which is in the parent frames context
parent.Core.UI.Dialog.CloseDialog($('.Dialog', parent.document));
};
/**
* @name SelectRadioButton
* @memberof Core.Agent.TicketAction
* @function
* @param {String} Value - The value attribute of the radio button to be selected.
* @param {String} Name - The name of the radio button to be selected.
* @description
* Selects a radio button by name and value.
*/
TargetNS.SelectRadioButton = function (Value, Name) {
$('input[type="radio"][name=' + Name + '][value=' + Value + ']').prop('checked', true);
};
/**
* @name ConfirmTemplateOverwrite
* @memberof Core.Agent.TicketAction
* @function
* @param {String} FieldName - The ID of the content field (textarea or RTE). ID without selector (#).
* @param {jQueryObject} $TemplateSelect - Selector of the dropdown element for the template selection.
* @param {Function} Callback - Callback function to execute if overwriting is confirmed.
* @description
* After a template was selected, this function lets the user confirm that all already existing content
* in the textarea or RTE will be overwritten with the template content.
*/
TargetNS.ConfirmTemplateOverwrite = function (FieldName, $TemplateSelect, Callback) {
var Content = '',
LastValue = $TemplateSelect.data('LastValue') || '';
// Fallback for non-richtext content
Content = $('#' + FieldName).val();
// get RTE content
if (typeof CKEDITOR !== 'undefined' && CKEDITOR.instances[FieldName]) {
Content = CKEDITOR.instances[FieldName].getData();
}
// if content already exists let user confirm to really overwrite that content with a template
if (
Content.length &&
!window.confirm(Core.Language.Translate('Setting a template will overwrite any text or attachment.') + ' ' + Core.Language.Translate('Do you really want to continue?')))
{
// if user cancels confirmation, reset template selection
$TemplateSelect.val(LastValue).trigger('redraw');
}
else if ($.isFunction(Callback)) {
Callback();
$TemplateSelect.data('LastValue', $TemplateSelect.val());
}
}
Core.Init.RegisterNamespace(TargetNS, 'APP_MODULE');
return TargetNS;
}(Core.Agent.TicketAction || {}));
| mburggraf/otrs | var/httpd/htdocs/js/Core.Agent.TicketAction.js | JavaScript | agpl-3.0 | 12,173 |
import SPELLS from 'common/SPELLS';
import { EventType } from 'parser/core/Events';
import EventsNormalizer from 'parser/core/EventsNormalizer';
const CAST_WINDOW = 100;
/**
* During the opener garrote casts seems to sometimes appear after the damage and energize event, as well as stealth being removed.
* Moving the cast even to just before the damage event should ensure that we are able to correctly track if the cast happened during stealth.
*
* @param {Array} events
* @returns {Array} Events possibly with some reordered.
*/
class GarroteNormalizer extends EventsNormalizer {
normalize(events) {
const fixedEvents = [];
events.forEach((event, eventIndex) => {
fixedEvents.push(event);
if (event.type === EventType.Cast && event.ability.guid === SPELLS.GARROTE.id) {
const castTimestamp = event.timestamp;
for (
let previousEventIndex = eventIndex;
previousEventIndex >= 0;
previousEventIndex -= 1
) {
const previousEvent = fixedEvents[previousEventIndex];
if (castTimestamp - previousEvent.timestamp > CAST_WINDOW) {
break;
}
if (
previousEvent.type === EventType.ResourceChange &&
previousEvent.ability.guid === SPELLS.GARROTE.id
) {
event.timestamp = previousEvent.timestamp;
fixedEvents.splice(eventIndex, 1);
fixedEvents.splice(previousEventIndex, 0, event);
event.__reordered = true;
break;
}
}
}
});
return fixedEvents;
}
}
export default GarroteNormalizer;
| Juko8/WoWAnalyzer | analysis/rogueassassination/src/normalizers/GarroteOpenerNormalizer.js | JavaScript | agpl-3.0 | 1,639 |
// Dimensions of sunburst.
var width = 750;
var height = 600;
var radius = Math.min(width, height) / 2;
// Breadcrumb dimensions: width, height, spacing, width of tip/tail.
var b = {
w: 75, h: 30, s: 3, t: 10
};
// Mapping of step names to colors.
//var colors = {
// "": "#5687d1",
// "1": "#7b615c",
// "2": "#de783b",
// "3": "#6ab975",
// "4": "#a173d1",
// "5": "#bbbbbb",
// "6": "#a173d1",
// "7": "#bbbbbb"
//};
var colors = d3.scale.linear()
.domain([0, 5, 100])
.range(["#00FF00", "#FF4400", "#FF0000"]);
// Total size of all segments; we set this later, after loading the data.
var totalSize = 0;
var vis = d3.select("#chart").append("svg:svg")
.attr("width", width)
.attr("height", height)
.append("svg:g")
.attr("id", "container")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var partition = d3.layout.partition()
.size([2 * Math.PI, radius * radius])
.value(function(d) { return d.size; });
var arc = d3.svg.arc()
.startAngle(function(d) {
return d.x;
})
.endAngle(function(d) {
return d.x + d.dx;
})
.innerRadius(function(d) {
return Math.sqrt(d.y);
})
.outerRadius(function(d) {
return Math.sqrt(d.y + d.dy);
});
// Use d3.text and d3.csv.parseRows so that we do not need to have a header
// row, and can receive the csv as an array of arrays.
d3.text("2005-2013_processed.csv", function(text) {
var csv = d3.csv.parseRows(text);
var json = buildHierarchy(csv);
createVisualization(json);
});
// Main function to draw and set up the visualization, once we have the data.
function createVisualization(json) {
// Basic setup of page elements.
// initializeBreadcrumbTrail();
// drawLegend();
// d3.select("#togglelegend").on("click", toggleLegend);
// Bounding circle underneath the sunburst, to make it easier to detect
// when the mouse leaves the parent g.
vis.append("svg:circle")
.attr("r", radius)
.style("opacity", 0);
// For efficiency, filter nodes to keep only those large enough to see.
var nodes = partition.nodes(json)
.filter(function(d) {
return (d.dx > 0.0005); // 0.005 radians = 0.29 degrees
});
var path = vis.data([json]).selectAll("path")
.data(nodes)
.enter().append("svg:path")
.attr("display", function(d) { return d.depth ? null : "none"; })
.attr("d", arc)
.attr("fill-rule", "evenodd")
.attr("stroke-opacity",0)
.style("fill", function(d) {
if(d.name == "")
return "#000000";
else {
// console.log(parseInt(d.name)+":"+colors(parseInt(d.name)));
return colors(parseInt(d.name));
}
})
.style("opacity", 1);
// .on("mouseover", mouseover);
// Add the mouseleave handler to the bounding circle.
// d3.select("#container").on("mouseleave", mouseleave);
// Get total size of the tree = value of root node from partition.
totalSize = path.node().__data__.value;
};
// Fade all but the current sequence, and show it in the breadcrumb trail.
//function mouseover(d) {
//
//// var percentage = (100 * d.value / totalSize).toPrecision(3);
// var percentageString = d.value;
//// if (percentage < 0.1) {
//// percentageString = "< 0.1%";
//// }
//
// d3.select("#percentage")
// .text(percentageString);
//
// d3.select("#explanation")
// .style("visibility", "");
//
// var sequenceArray = getAncestors(d);
// updateBreadcrumbs(sequenceArray, percentageString);
//
// // Fade all the segments.
// d3.selectAll("path")
// .style("opacity", 0.3);
//
// // Then highlight only those that are an ancestor of the current segment.
// vis.selectAll("path")
// .filter(function(node) {
// return (sequenceArray.indexOf(node) >= 0);
// })
// .style("opacity", 1);
//}
// Restore everything to full opacity when moving off the visualization.
//function mouseleave(d) {
//
// // Hide the breadcrumb trail
// d3.select("#trail")
// .style("visibility", "hidden");
//
// // Deactivate all segments during transition.
//// d3.selectAll("path").on("mouseover", null);
//
// // Transition each segment to full opacity and then reactivate it.
// d3.selectAll("path")
// .transition()
// .duration(1000)
// .style("opacity", 1)
// .each("end", function() {
// d3.select(this).on("mouseover", mouseover);
// });
//
// d3.select("#explanation")
// .style("visibility", "hidden");
//}
// Given a node in a partition layout, return an array of all of its ancestor
// nodes, highest first, but excluding the root.
function getAncestors(node) {
var path = [];
var current = node;
while (current.parent) {
path.unshift(current);
current = current.parent;
}
return path;
}
function initializeBreadcrumbTrail() {
// Add the svg area.
// var trail = d3.select("#sequence").append("svg:svg")
// .attr("width", width)
// .attr("height", 50)
// .attr("id", "trail");
// // Add the label at the end, for the percentage.
// trail.append("svg:text")
// .attr("id", "endlabel")
// .style("fill", "#000");
}
// Generate a string that describes the points of a breadcrumb polygon.
function breadcrumbPoints(d, i) {
var points = [];
points.push("0,0");
points.push(b.w + ",0");
points.push(b.w + b.t + "," + (b.h / 2));
points.push(b.w + "," + b.h);
points.push("0," + b.h);
if (i > 0) { // Leftmost breadcrumb; don't include 6th vertex.
points.push(b.t + "," + (b.h / 2));
}
return points.join(" ");
}
// Update the breadcrumb trail to show the current sequence and percentage.
function updateBreadcrumbs(nodeArray, percentageString) {
// Data join; key function combines name and depth (= position in sequence).
var g = d3.select("#trail")
.selectAll("g")
.data(nodeArray, function(d) { return d.name + d.depth; });
// Add breadcrumb and label for entering nodes.
var entering = g.enter().append("svg:g");
entering.append("svg:polygon")
.attr("points", breadcrumbPoints)
.style("fill", function(d) { return colors[d.name]; });
entering.append("svg:text")
.attr("x", (b.w + b.t) / 2)
.attr("y", b.h / 2)
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.text(function(d) { return d.name; });
// Set position for entering and updating nodes.
g.attr("transform", function(d, i) {
return "translate(" + i * (b.w + b.s) + ", 0)";
});
// Remove exiting nodes.
g.exit().remove();
// Now move and update the percentage at the end.
d3.select("#trail").select("#endlabel")
.attr("x", (nodeArray.length + 0.5) * (b.w + b.s))
.attr("y", b.h / 2)
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.text(percentageString);
// Make the breadcrumb trail visible, if it's hidden.
d3.select("#trail")
.style("visibility", "");
}
function drawLegend() {
// Dimensions of legend item: width, height, spacing, radius of rounded rect.
var li = {
w: 75, h: 30, s: 3, r: 3
};
var legend = d3.select("#legend").append("svg:svg")
.attr("width", li.w)
.attr("height", d3.keys(colors).length * (li.h + li.s));
var g = legend.selectAll("g")
.data(d3.entries(colors))
.enter().append("svg:g")
.attr("transform", function(d, i) {
return "translate(0," + i * (li.h + li.s) + ")";
});
g.append("svg:rect")
.attr("rx", li.r)
.attr("ry", li.r)
.attr("width", li.w)
.attr("height", li.h)
.style("fill", function(d) { return d.value; });
g.append("svg:text")
.attr("x", li.w / 2)
.attr("y", li.h / 2)
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.text(function(d) { return d.key; });
}
function toggleLegend() {
var legend = d3.select("#legend");
if (legend.style("visibility") == "hidden") {
legend.style("visibility", "");
} else {
legend.style("visibility", "hidden");
}
}
// Take a 2-column CSV and transform it into a hierarchical structure suitable
// for a partition layout. The first column is a sequence of step names, from
// root to leaf, separated by hyphens. The second column is a count of how
// often that sequence occurred.
function buildHierarchy(csv) {
var root = {"name": "root", "children": []};
for (var i = 0; i < csv.length; i++) {
for(var j = 0; j < 10; j ++){
}
var sequence = csv[i][0]+"-"+csv[i][1]+"-"+csv[i][2]+"-"+csv[i][3]+"-"+csv[i][4]+"-"+csv[i][5]+"-"+csv[i][6]+"-"+csv[i][7]+"-"+csv[i][8];
var size = +1;//csv[i][9];
if (isNaN(size)) { // e.g. if this is a header row
continue;
}
var parts = sequence.split("-");
var currentNode = root;
for (var j = 0; j < parts.length; j++) {
var children = currentNode["children"];
var nodeName = parts[j];
var childNode;
if (j + 1 < parts.length) {
// Not yet at the end of the sequence; move down the tree.
var foundChild = false;
for (var k = 0; k < children.length; k++) {
if (children[k]["name"] == nodeName) {
childNode = children[k];
// foundChild = true;
break;
}
}
// If we don't already have a child node for this branch, create it.
if (!foundChild) {
childNode = {"name": nodeName, "children": []};
children.push(childNode);
}
currentNode = childNode;
} else {
// Reached the end of the sequence; create a leaf node.
childNode = {"name": nodeName, "size": size};
children.push(childNode);
}
}
}
return root;
};
| MilletPu/airvis | src/main/webapp/js/otherdemos/rose/sequences_noInter.js | JavaScript | agpl-3.0 | 9,654 |
YUI.add('color-hsv', function (Y, NAME) {
/**
Color provides static methods for color conversion hsv values.
Y.Color.toHSV('f00'); // hsv(0, 100%, 100%)
Y.Color.toHSVA('rgb(255, 255, 0'); // hsva(60, 100%, 100%, 1)
@module color
@submodule color-hsv
@class HSV
@namespace Color
@since 3.8.0
**/
Color = {
/**
@static
@property REGEX_HSV
@type RegExp
@default /hsva?\(([.\d]*), ?([.\d]*)%, ?([.\d]*)%,? ?([.\d]*)?\)/
@since 3.8.0
**/
REGEX_HSV: /hsva?\(([.\d]*), ?([.\d]*)%, ?([.\d]*)%,? ?([.\d]*)?\)/,
/**
@static
@property STR_HSV
@type String
@default hsv({*}, {*}%, {*}%)
@since 3.8.0
**/
STR_HSV: 'hsv({*}, {*}%, {*}%)',
/**
@static
@property STR_HSVA
@type String
@default hsva({*}, {*}%, {*}%, {*})
@since 3.8.0
**/
STR_HSVA: 'hsva({*}, {*}%, {*}%, {*})',
/**
Converts provided color value to an HSV string.
@public
@method toHSV
@param {String} str
@return {String}
@since 3.8.0
**/
toHSV: function (str) {
var clr = Y.Color._convertTo(str, 'hsv');
return clr.toLowerCase();
},
/**
Converts provided color value to an HSVA string.
@public
@method toHSVA
@param {String} str
@return {String}
@since 3.8.0
**/
toHSVA: function (str) {
var clr = Y.Color._convertTo(str, 'hsva');
return clr.toLowerCase();
},
/**
Parses the RGB string into h, s, v values. Will return an Array
of values or an HSV string.
@protected
@method _rgbToHsv
@param {String} str
@param {Boolean} [toArray]
@return {String|Array}
@since 3.8.0
**/
_rgbToHsv: function (str, toArray) {
var h, s, v,
rgb = Y.Color.REGEX_RGB.exec(str),
r = rgb[1] / 255,
g = rgb[2] / 255,
b = rgb[3] / 255,
max = Math.max(r, g, b),
min = Math.min(r, g, b),
delta = max - min;
if (max === min) {
h = 0;
} else if (max === r) {
h = 60 * (g - b) / delta;
} else if (max === g) {
h = (60 * (b - r) / delta) + 120;
} else { // max === b
h = (60 * (r - g) / delta) + 240;
}
s = (max === 0) ? 0 : 1 - (min / max);
// ensure h is between 0 and 360
while (h < 0) {
h += 360;
}
h %= 360;
h = Math.round(h);
// saturation is percentage
s = Math.round(s * 100);
// value is percentage
v = Math.round(max * 100);
if (toArray) {
return [h, s, v];
}
return Y.Color.fromArray([h, s, v], Y.Color.TYPES.HSV);
},
/**
Parses the HSV string into r, b, g values. Will return an Array
of values or an RGB string.
@protected
@method _hsvToRgb
@param {String} str
@param {Boolean} [toArray]
@return {String|Array}
@since 3.8.0
**/
_hsvToRgb: function (str, toArray) {
var hsv = Y.Color.REGEX_HSV.exec(str),
h = parseInt(hsv[1], 10),
s = parseInt(hsv[2], 10) / 100, // 0 - 1
v = parseInt(hsv[3], 10) / 100, // 0 - 1
r,
g,
b,
i = Math.floor(h / 60) % 6,
f = (h / 60) - i,
p = v * (1 - s),
q = v * (1 - (s * f)),
t = v * (1 - (s * (1 - f)));
if (s === 0) {
r = v;
g = v;
b = v;
} else {
switch (i) {
case 0: r = v; g = t; b = p; break;
case 1: r = q; g = v; b = p; break;
case 2: r = p; g = v; b = t; break;
case 3: r = p; g = q; b = v; break;
case 4: r = t; g = p; b = v; break;
case 5: r = v; g = p; b = q; break;
}
}
r = Math.min(255, Math.round(r * 256));
g = Math.min(255, Math.round(g * 256));
b = Math.min(255, Math.round(b * 256));
if (toArray) {
return [r, g, b];
}
return Y.Color.fromArray([r, g, b], Y.Color.TYPES.RGB);
}
};
Y.Color = Y.mix(Color, Y.Color);
Y.Color.TYPES = Y.mix(Y.Color.TYPES, {'HSV':'hsv', 'HSVA':'hsva'});
Y.Color.CONVERTS = Y.mix(Y.Color.CONVERTS, {'hsv': 'toHSV', 'hsva': 'toHSVA'});
}, 'patched-v3.11.0', {"requires": ["color-base"]});
| FuadEfendi/lpotal | tomcat-7.0.57/webapps/ROOT/html/js/aui/color-hsv/color-hsv.js | JavaScript | lgpl-2.1 | 4,434 |
/**
* @author Gionatan Iasio <gionatan@sferalabs.cc>
* @copyright 2016 SferaLabs
* @license {@link http://sfera.sferalabs.cc/docs/sfera/license.html|LGPL License}
*/
/**
* Image component.
*
* @class Sfera.Components.Image
* @mixes Sfera.Behaviors.Visibility
* @mixes Sfera.Behaviors.Position
* @property {string} source - source url of the image
*/
Sfera.Components.create("Image", {
presets: ["Visibility", "Position", "Size"],
attributes: {
source: {
type: "string",
update: function() {
var c = this.component;
var e = c.element;
// no source, hide it
if (!this.value) {
e.innerHTML = "";
}
// svg
else if (this.value.indexOf(".svg") == this.value.length - 4) {
var req = new Sfera.Net.Request();
req.init();
req.onLoaded = function() {
var xml = req.getResponseXML();
c.svg = xml.getElementsByTagName("svg")[0];
e.innerHTML = "";
if (c.svg) {
e.appendChild(c.svg);
c.svg.style.width = c.getAttribute("width");
c.svg.style.height = c.getAttribute("height");
}
// done
req = null;
};
req.open(this.value);
}
// normal img
else {
e.innerHTML = "<img src='" + this.value + "' width='100%' height='100%'>";
}
}
}
},
init: function() {
this.svg = null;
},
onShow: function () {
if (this.svg) {
this.svg.style.width = this.getAttribute("width") + "px";
this.svg.style.height = this.getAttribute("height") + "px";
}
},
});
| sfera-labs/sfera-app-webapp | src/main/resources/webapp/components/image/image.js | JavaScript | lgpl-3.0 | 2,043 |
/* */
var isArguments = require('./isArguments'),
isArray = require('./isArray'),
isArrayLike = require('./isArrayLike'),
isFunction = require('./isFunction'),
isString = require('./isString');
var objectProto = Object.prototype;
var hasOwnProperty = objectProto.hasOwnProperty;
function isEmpty(value) {
if (isArrayLike(value) && (isArray(value) || isString(value) || isFunction(value.splice) || isArguments(value))) {
return !value.length;
}
for (var key in value) {
if (hasOwnProperty.call(value, key)) {
return false;
}
}
return true;
}
module.exports = isEmpty;
| EpitaJS/js-class-2016 | jspm_packages/npm/lodash@4.6.1/isEmpty.js | JavaScript | unlicense | 612 |
Bridge.assembly("TestProject", function ($asm, globals) {
"use strict";
var $m = Bridge.setMetadata,
$n = [];
$m("TestProject1.AliasUsing", function () { return {"att":1048577,"a":2,"m":[{"a":2,"n":".ctor","t":1,"sn":"ctor"}]}; }, $n);
$m("TestProject1.StaticUsing", function () { return {"att":1048577,"a":2,"m":[{"a":2,"n":".ctor","t":1,"sn":"ctor"}]}; }, $n);
});
| AndreyZM/Bridge | Compiler/TranslatorTests/TestProjects/25/Bridge/reference/TestProject1.meta.js | JavaScript | apache-2.0 | 393 |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('image', function(K) {
var self = this, name = 'image',
allowImageUpload = K.undef(self.allowImageUpload, true),
allowImageRemote = K.undef(self.allowImageRemote, true),
formatUploadUrl = K.undef(self.formatUploadUrl, false),
allowFileManager = K.undef(self.allowFileManager, false),
uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php'),
imageTabIndex = K.undef(self.imageTabIndex, 0),
imgPath = self.pluginsPath + 'image/images/',
extraParams = K.undef(self.extraFileUploadParams, {}),
filePostName = K.undef(self.filePostName, 'imgFile'),
fillDescAfterUploadImage = K.undef(self.fillDescAfterUploadImage, false),
lang = self.lang(name + '.');
self.plugin.imageDialog = function(options) {
var imageUrl = options.imageUrl,
imageWidth = K.undef(options.imageWidth, ''),
imageHeight = K.undef(options.imageHeight, ''),
imageTitle = K.undef(options.imageTitle, ''),
imageAlign = K.undef(options.imageAlign, ''),
showRemote = K.undef(options.showRemote, true),
showLocal = K.undef(options.showLocal, true),
tabIndex = K.undef(options.tabIndex, 0),
clickFn = options.clickFn;
var target = 'kindeditor_upload_iframe_' + new Date().getTime();
var hiddenElements = [];
for(var k in extraParams){
hiddenElements.push('<input type="hidden" name="' + k + '" value="' + extraParams[k] + '" />');
}
var html = [
'<div style="padding:20px;">',
//tabs
'<div class="tabs"></div>',
//remote image - start
'<div class="tab1" style="display:none;">',
//url
'<div class="ke-dialog-row">',
'<label for="remoteUrl" style="width:60px;font-size:10px;">' + lang.remoteUrl + '</label>',
'<input type="text" id="remoteUrl" class="ke-input-text" name="url" value="" style="width:200px;" /> ',
'<span class="ke-button-common ke-button-outer">',
'<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />',
'</span>',
'</div>',
//size
'<div class="ke-dialog-row">',
'<label for="remoteWidth" style="width:60px;font-size:10px;">' + lang.size + '</label>',
lang.width + ' <input type="text" id="remoteWidth" class="ke-input-text ke-input-number" name="width" value="" maxlength="4" /> ',
lang.height + ' <input type="text" class="ke-input-text ke-input-number" name="height" value="" maxlength="4" /> ',
'<img class="ke-refresh-btn" src="' + imgPath + 'refresh.png" width="16" height="16" alt="" style="cursor:pointer;" title="' + lang.resetSize + '" />',
'</div>',
//align
'<div class="ke-dialog-row">',
'<label style="width:60px;font-size:10px;">' + lang.align + '</label>',
'<input type="radio" name="align" class="ke-inline-block" value="" checked="checked" /> <img name="defaultImg" src="' + imgPath + 'align_top.gif" width="23" height="25" alt="" />',
' <input type="radio" name="align" class="ke-inline-block" value="left" /> <img name="leftImg" src="' + imgPath + 'align_left.gif" width="23" height="25" alt="" />',
' <input type="radio" name="align" class="ke-inline-block" value="right" /> <img name="rightImg" src="' + imgPath + 'align_right.gif" width="23" height="25" alt="" />',
'</div>',
//title
'<div class="ke-dialog-row">',
'<label for="remoteTitle" style="width:60px;font-size:10px;">' + lang.imgTitle + '</label>',
'<input type="text" id="remoteTitle" class="ke-input-text" name="title" value="" style="width:200px;" />',
'</div>',
'</div>',
//remote image - end
//local upload - start
'<div class="tab2" style="display:none;">',
'<iframe name="' + target + '" style="display:none;"></iframe>',
'<form class="ke-upload-area ke-form" method="post" enctype="multipart/form-data" target="' + target + '" action="' + K.addParam(uploadJson, 'dir=image') + '">',
//file
'<div class="ke-dialog-row">',
hiddenElements.join(''),
'<label style="width:60px;font-size:10px;">' + lang.localUrl + '</label>',
'<input type="text" name="localUrl" class="ke-input-text" tabindex="-1" style="width:200px;" readonly="true" /> ',
'<input type="button" class="ke-upload-button" value="' + lang.upload + '" />',
'</div>',
//size
'<div class="ke-dialog-row">',
'<label for="remoteWidth" style="width:60px;font-size:10px;">' + lang.size + '</label>',
lang.width + ' <input type="text" id="localWidth" class="ke-input-text ke-input-number" name="localWidth" value="" maxlength="4" /> ',
lang.height + ' <input type="text" id="localHeight" class="ke-input-text ke-input-number" name="localHeight" value="" maxlength="4" /> ',
'</div>',
'</form>',
'</div>',
//local upload - end
'</div>'
].join('');
var dialogWidth = showLocal || allowFileManager ? 450 : 400,
dialogHeight = showLocal && showRemote ? 300 : 250;
var dialog = self.createDialog({
name : name,
width : dialogWidth,
height : dialogHeight,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
// Bugfix: http://code.google.com/p/kindeditor/issues/detail?id=319
if (dialog.isLoading) {
return;
}
// insert local image
if (showLocal && showRemote && tabs && tabs.selectedIndex === 1 || !showRemote) {
if (uploadbutton.fileBox.val() == '') {
/*alert(self.lang('pleaseSelectFile'));*/
layer.alert(self.lang('pleaseSelectFile'), {
icon : 7
});
return;
}
dialog.showLoading(self.lang('uploadLoading'));
uploadbutton.submit();
localUrlBox.val('');
return;
}
// insert remote image
var url = K.trim(urlBox.val()),
width = widthBox.val(),
height = heightBox.val(),
title = titleBox.val(),
align = '';
alignBox.each(function() {
if (this.checked) {
align = this.value;
return false;
}
});
if (url == 'http://' || K.invalidUrl(url)) {
//alert(self.lang('invalidUrl'));
layer.alert(self.lang('invalidUrl'), {
icon : 7
});
urlBox[0].focus();
return;
}
if (!/^\d*$/.test(width)) {
//alert(self.lang('invalidWidth'));
layer.alert(self.lang('invalidWidth'), {
icon : 7
});
widthBox[0].focus();
return;
}
if (!/^\d*$/.test(height)) {
//alert(self.lang('invalidHeight'));
layer.alert(self.lang('invalidHeight'), {
icon : 7
});
heightBox[0].focus();
return;
}
clickFn.call(self, url, title, width, height, 0, align);
}
},
beforeRemove : function() {
viewServerBtn.unbind();
widthBox.unbind();
heightBox.unbind();
refreshBtn.unbind();
}
}),
div = dialog.div;
var urlBox = K('[name="url"]', div),
localUrlBox = K('[name="localUrl"]', div),
viewServerBtn = K('[name="viewServer"]', div),
widthBox = K('.tab1 [name="width"]', div),
heightBox = K('.tab1 [name="height"]', div),
refreshBtn = K('.ke-refresh-btn', div),
titleBox = K('.tab1 [name="title"]', div),
alignBox = K('.tab1 [name="align"]', div);
var tabs;
if (showRemote && showLocal) {
tabs = K.tabs({
src : K('.tabs', div),
afterSelect : function(i) {}
});
tabs.add({
title : lang.remoteImage,
panel : K('.tab1', div)
});
tabs.add({
title : lang.localImage,
panel : K('.tab2', div)
});
tabs.select(tabIndex);
} else if (showRemote) {
K('.tab1', div).show();
} else if (showLocal) {
K('.tab2', div).show();
}
//--2015-9-24-zhuagnqian-默认选中本地上传-
tabs.select(1);
var uploadbutton = K.uploadbutton({
button : K('.ke-upload-button', div)[0],
fieldName : filePostName,
form : K('.ke-form', div),
target : target,
width: 60,
afterUpload : function(data) {
dialog.hideLoading();
if (data.error === 0) {
var url = data.url;
if (formatUploadUrl) {
url = K.formatUrl(url, 'absolute');
}
if (self.afterUpload) {
self.afterUpload.call(self, url, data, name);
}
if (!fillDescAfterUploadImage) {
//--2015-9-24-zhuagnqian-增加本地上传图片大小功能-
var width=$("#localWidth").val();
var height=$("#localHeight").val();
if(!(parseInt(width)>0&&parseInt(height)>0)){
width= data.width;
height=data.height;
}
//------------
clickFn.call(self, url, data.title, width, height, data.border, data.align);
} else {
K(".ke-dialog-row #remoteUrl", div).val(url);
K(".ke-tabs-li", div)[0].click();
K(".ke-refresh-btn", div).click();
}
} else {
//alert(data.message);
layer.alert(data.message, {
icon : 7
});
}
},
afterError : function(html) {
dialog.hideLoading();
self.errorDialog(html);
}
});
uploadbutton.fileBox.change(function(e) {
localUrlBox.val(uploadbutton.fileBox.val());
});
if (allowFileManager) {
viewServerBtn.click(function(e) {
self.loadPlugin('filemanager', function() {
self.plugin.filemanagerDialog({
viewType : 'VIEW',
dirName : 'image',
clickFn : function(url, title) {
if (self.dialogs.length > 1) {
K('[name="url"]', div).val(url);
if (self.afterSelectFile) {
self.afterSelectFile.call(self, url);
}
self.hideDialog();
}
}
});
});
});
} else {
viewServerBtn.hide();
}
var originalWidth = 0, originalHeight = 0;
function setSize(width, height) {
widthBox.val(width);
heightBox.val(height);
originalWidth = width;
originalHeight = height;
}
refreshBtn.click(function(e) {
var tempImg = K('<img src="' + urlBox.val() + '" />', document).css({
position : 'absolute',
visibility : 'hidden',
top : 0,
left : '-1000px'
});
tempImg.bind('load', function() {
setSize(tempImg.width(), tempImg.height());
tempImg.remove();
});
K(document.body).append(tempImg);
});
widthBox.change(function(e) {
if (originalWidth > 0) {
heightBox.val(Math.round(originalHeight / originalWidth * parseInt(this.value, 10)));
}
});
heightBox.change(function(e) {
if (originalHeight > 0) {
widthBox.val(Math.round(originalWidth / originalHeight * parseInt(this.value, 10)));
}
});
urlBox.val(options.imageUrl);
setSize(options.imageWidth, options.imageHeight);
titleBox.val(options.imageTitle);
alignBox.each(function() {
if (this.value === options.imageAlign) {
this.checked = true;
return false;
}
});
if (showRemote && tabIndex === 0) {
urlBox[0].focus();
urlBox[0].select();
}
return dialog;
};
self.plugin.image = {
edit : function() {
var img = self.plugin.getSelectedImage();
self.plugin.imageDialog({
imageUrl : img ? img.attr('data-ke-src') : 'http://',
imageWidth : img ? img.width() : '',
imageHeight : img ? img.height() : '',
imageTitle : img ? img.attr('title') : '',
imageAlign : img ? img.attr('align') : '',
showRemote : allowImageRemote,
showLocal : allowImageUpload,
tabIndex: img ? 0 : imageTabIndex,
clickFn : function(url, title, width, height, border, align) {
if (img) {
img.attr('src', url);
img.attr('data-ke-src', url);
img.attr('width', width);
img.attr('height', height);
img.attr('title', title);
img.attr('align', align);
img.attr('alt', title);
} else {
self.exec('insertimage', url, title, width, height, border, align);
}
// Bugfix: [Firefox] 上传图片后,总是出现正在加载的样式,需要延迟执行hideDialog
setTimeout(function() {
self.hideDialog().focus();
}, 0);
}
});
},
'delete' : function() {
var target = self.plugin.getSelectedImage();
if (target.parent().name == 'a') {
target = target.parent();
}
target.remove();
// [IE] 删除图片后立即点击图片按钮出错
self.addBookmark();
}
};
self.clickToolbar(name, self.plugin.image.edit);
});
| mysisl/blade | src/main/webapp/static/kindeditor/plugins/image/image.js | JavaScript | apache-2.0 | 12,419 |
/**
* `tasks/config/uglify`
*
* ---------------------------------------------------------------
*
* Minify client-side JavaScript files using UglifyES.
*
* For more information, see:
* https://sailsjs.com/anatomy/tasks/config/uglify.js
*
*/
module.exports = function(grunt) {
grunt.config.set('uglify', {
dist: {
src: ['.tmp/public/concat/production.js'],
dest: '.tmp/public/min/production.min.js'
},
options: {
mangle: {
reserved: [
'AsyncFunction',
'SailsSocket',
'Promise',
'File',
'Location',
'RttcRefPlaceholder',
],
keep_fnames: true//eslint-disable-line
},
compress: {
keep_fnames: true//eslint-disable-line
}
}
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// This Grunt plugin is part of the default asset pipeline in Sails,
// so it's already been automatically loaded for you at this point.
//
// Of course, you can always remove this Grunt plugin altogether by
// deleting this file. But check this out: you can also use your
// _own_ custom version of this Grunt plugin.
//
// Here's how:
//
// 1. Install it as a local dependency of your Sails app:
// ```
// $ npm install grunt-contrib-uglify --save-dev --save-exact
// ```
//
//
// 2. Then uncomment the following code:
//
// ```
// // Load Grunt plugin from the node_modules/ folder.
// grunt.loadNpmTasks('grunt-contrib-uglify');
// ```
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
};
| Dmdv/WebPlayground | Sails/bugTracker/tasks/config/uglify.js | JavaScript | apache-2.0 | 1,612 |
import {List, Map, ListWrapper, MapWrapper} from 'facade/collection';
import {Element, DOM} from 'facade/dom';
import {int, isBlank, isPresent} from 'facade/lang';
import {AnnotatedType} from '../annotated_type';
import {Decorator} from '../../annotations/annotations';
import {Component} from '../../annotations/annotations';
import {Template} from '../../annotations/annotations';
import {ElementBinder} from '../element_binder';
import {ProtoElementInjector} from '../element_injector';
import {ProtoView} from '../view';
import {ASTWithSource} from 'change_detection/parser/ast';
/**
* Collects all data that is needed to process an element
* in the compile process. Fields are filled
* by the CompileSteps starting out with the pure HTMLElement.
*/
export class CompileElement {
element:Element;
_attrs:Map;
_classList:List;
textNodeBindings:Map;
propertyBindings:Map;
eventBindings:Map;
variableBindings:Map;
decoratorDirectives:List<AnnotatedType>;
templateDirective:AnnotatedType;
componentDirective:AnnotatedType;
isViewRoot:boolean;
hasBindings:boolean;
inheritedProtoView:ProtoView;
inheritedProtoElementInjector:ProtoElementInjector;
inheritedElementBinder:ElementBinder;
constructor(element:Element) {
this.element = element;
this._attrs = null;
this._classList = null;
this.textNodeBindings = null;
this.propertyBindings = null;
this.eventBindings = null;
this.variableBindings = null;
this.decoratorDirectives = null;
this.templateDirective = null;
this.componentDirective = null;
this.isViewRoot = false;
this.hasBindings = false;
// inherited down to children if they don't have
// an own protoView
this.inheritedProtoView = null;
// inherited down to children if they don't have
// an own protoElementInjector
this.inheritedProtoElementInjector = null;
// inherited down to children if they don't have
// an own elementBinder
this.inheritedElementBinder = null;
}
refreshAttrs() {
this._attrs = null;
}
attrs():Map<string,string> {
if (isBlank(this._attrs)) {
this._attrs = DOM.attributeMap(this.element);
}
return this._attrs;
}
refreshClassList() {
this._classList = null;
}
classList():List<string> {
if (isBlank(this._classList)) {
this._classList = ListWrapper.create();
var elClassList = DOM.classList(this.element);
for (var i = 0; i < elClassList.length; i++) {
ListWrapper.push(this._classList, elClassList[i]);
}
}
return this._classList;
}
addTextNodeBinding(indexInParent:int, expression:ASTWithSource) {
if (isBlank(this.textNodeBindings)) {
this.textNodeBindings = MapWrapper.create();
}
MapWrapper.set(this.textNodeBindings, indexInParent, expression);
}
addPropertyBinding(property:string, expression:ASTWithSource) {
if (isBlank(this.propertyBindings)) {
this.propertyBindings = MapWrapper.create();
}
MapWrapper.set(this.propertyBindings, property, expression);
}
addVariableBinding(contextName:string, templateName:string) {
if (isBlank(this.variableBindings)) {
this.variableBindings = MapWrapper.create();
}
MapWrapper.set(this.variableBindings, contextName, templateName);
}
addEventBinding(eventName:string, expression:ASTWithSource) {
if (isBlank(this.eventBindings)) {
this.eventBindings = MapWrapper.create();
}
MapWrapper.set(this.eventBindings, eventName, expression);
}
addDirective(directive:AnnotatedType) {
var annotation = directive.annotation;
if (annotation instanceof Decorator) {
if (isBlank(this.decoratorDirectives)) {
this.decoratorDirectives = ListWrapper.create();
}
ListWrapper.push(this.decoratorDirectives, directive);
} else if (annotation instanceof Template) {
this.templateDirective = directive;
} else if (annotation instanceof Component) {
this.componentDirective = directive;
}
}
}
| rtdkumar/angular | modules/core/src/compiler/pipeline/compile_element.js | JavaScript | apache-2.0 | 4,021 |
require('../lib/node_loader');
var AWS = require('../lib/core');
var Service = AWS.Service;
var apiLoader = AWS.apiLoader;
apiLoader.services['personalizeevents'] = {};
AWS.PersonalizeEvents = Service.defineService('personalizeevents', ['2018-03-22']);
Object.defineProperty(apiLoader.services['personalizeevents'], '2018-03-22', {
get: function get() {
var model = require('../apis/personalize-events-2018-03-22.min.json');
model.paginators = require('../apis/personalize-events-2018-03-22.paginators.json').pagination;
return model;
},
enumerable: true,
configurable: true
});
module.exports = AWS.PersonalizeEvents;
| aws/aws-sdk-js | clients/personalizeevents.js | JavaScript | apache-2.0 | 641 |
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2016 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.unified.CalendarLegendItem.
sap.ui.define(['jquery.sap.global', 'sap/ui/core/Element', './library'],
function(jQuery, Element, library) {
"use strict";
/**
* Constructor for a new CalendarLegendItem.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Item to be displayed in a CalendarLegend.
* @extends sap.ui.core.Element
* @version 1.42.8
*
* @constructor
* @public
* @since 1.24.0
* @alias sap.ui.unified.CalendarLegendItem
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var CalendarLegendItem = Element.extend("sap.ui.unified.CalendarLegendItem", /** @lends sap.ui.unified.CalendarLegendItem.prototype */ { metadata : {
library : "sap.ui.unified",
properties : {
/**
* Text to be displayed for the item.
*/
text : {type : "string", group : "Misc", defaultValue : null},
/**
* Type of the item.
* If not set the type is automatically determined from the order of the items in the CalendarLegend.
* @since 1.28.9
*/
type : {type : "sap.ui.unified.CalendarDayType", group : "Appearance", defaultValue : sap.ui.unified.CalendarDayType.None}
}
}});
///**
// * This file defines behavior for the control,
// */
//sap.ui.unified.CalendarLegendItem.prototype.init = function(){
// // do something for initialization...
//};
return CalendarLegendItem;
}, /* bExport= */ true);
| icgretethe/AwarenessApp | resources/sap/ui/unified/CalendarLegendItem-dbg.js | JavaScript | apache-2.0 | 1,762 |
/*
* Copyright (C) 2016 Acrolinx GmbH
*
* 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.
*
* For more information visit: http://www.acrolinx.com
*/
'use strict';
var _ = require('lodash');
var wrench = require('wrench');
/*jshint -W079 */
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
var xml2js = Promise.promisifyAll(require('xml2js'));
var violations = require('./violations');
function median(arr) {
arr = arr.slice(0);
var middle = (arr.length + 1) / 2,
sorted = _.sortBy(arr);
return (sorted.length % 2) ? sorted[middle - 1] : (sorted[middle - 1.5] + sorted[middle - 0.5]) / 2;
}
function aggregatedReportToText(aggregatedReport) {
return fs.readFileAsync('lib/template.txt')
.then(function (buffer) {
return buffer.toString();
}).then(_.template)
.then(function (compiledTemplate) {
return compiledTemplate(aggregatedReport);
});
}
module.exports = {
findScorecards: function (dir) {
var reportPattern = /.*_report\.xml$/i;
if (!fs.existsSync(dir)) {
return [];
}
return wrench.readdirSyncRecursive(dir).filter(function (f) {
return f && f[0] !== '.' && f.match(reportPattern);
}).map(function (f) {
return dir + '/' + f;
});
},
analyze: function(files, config) {
var aggregatedReport = {
summary: [],
errors: [],
files: [],
info: {},
checkedTermSets: []
};
var scores = [];
var scorecards = files || [];
config = config || {};
aggregatedReport.info.violationColumns = (config.badTermsets || []).concat('Quality Threshold');
aggregatedReport.summary.push({
key: 'Files',
value: scorecards.length
});
aggregatedReport.summary.push({
key: 'Critical Score Threshold',
value: config.qualityScoreThreshold
});
return Promise.all(scorecards.map(function (scorecard, index) {
console.log('Analyzing', index+1, scorecard);
return fs.readFileAsync(scorecard, 'utf8')
.then(function (xml) {
return xml2js.parseStringAsync(xml);
}).then(function (result) {
var reportBody = result.acrocheckReport.body[0];
var inputTextIdentifier = result.acrocheckReport.head[0].inputText[0].identifier[0].$;
var checkingStat = reportBody.statistics[0].checkingStats[0];
var checkingScope = checkingStat.checkingScope[0].$;
var checkedTermSets = result.acrocheckReport.head[0].checkingResources[0].termBanks[0].termBank || [];
aggregatedReport.checkedTermSets = _.uniq(aggregatedReport.checkedTermSets.concat(checkedTermSets));
var score = Number(checkingStat.resultStats[0].$.qualityScore);
scores.push(score);
aggregatedReport.files.push({
name: inputTextIdentifier.filename,
displayName: inputTextIdentifier.display_name,
url: reportBody.links[0].$.reportURL,
words: checkingScope.words,
sentences: checkingScope.sentences,
qualityScore: score,
isCritical: false,
message: '',
violations: [].concat(violations.checkScore(result, config.qualityScoreThreshold))
.concat(violations.checkTerminology(result, config.badTermsets)),
color: checkingStat.resultStats[0].$.projectQualityStatus
});
return aggregatedReport;
}).catch(function (err) {
console.error('Error analyzing file', scorecard, ':', err);
aggregatedReport.errors.push({
file: scorecard,
message: err
});
return Promise.resolve(aggregatedReport);
});
})).then(function () {
var criticalCount = aggregatedReport.files.filter(function (file) {
return file.violations.length > 0;
}).length;
aggregatedReport.summary.push({
key: 'Critical Files',
value: criticalCount
});
aggregatedReport.summary.push({
key: 'Critical Ratio',
value: Number((criticalCount/(scorecards.length)).toFixed(2))
});
aggregatedReport.summary.push({
key: 'Quality Min',
value: _.min(scores)
});
aggregatedReport.summary.push({
key: 'Quality Max',
value: _.max(scores)
});
aggregatedReport.summary.push({
key: 'Quality Average',
value: Number((_.mean(scores)).toFixed(2))
});
aggregatedReport.summary.push({
key: 'Quality Median',
value: median(scores)
});
return aggregatedReport;
});
},
write: function (aggregatedReport, filename) {
return aggregatedReportToText(aggregatedReport).then(function (txt) {
return fs.writeFileAsync(filename + '.txt', txt);
}).then(function () {
return fs.writeFileAsync(filename + '.json', JSON.stringify(aggregatedReport));
});
}
};
| acrolinx/acrolinx-scale | lib/scale.js | JavaScript | apache-2.0 | 5,429 |
(function (angular) {
"use strict";
angular.module('dashboard.track', [])
.controller('trackCtrl',['$scope', function ($scope) {
$scope.Text = 'Track page';
}]);
})(angular); | RLOpenCatalyst/core | client/cat3/src/partials/sections/dashboard/track/trackCtrl.js | JavaScript | apache-2.0 | 186 |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* @class
* Initializes a new instance of the PoolEnableAutoScaleOptions class.
* @constructor
* Additional parameters for the Pool_enableAutoScale operation.
*
* @member {number} [timeout] The maximum time that the server can spend
* processing the request, in seconds. The default is 30 seconds. Default
* value: 30 .
*
* @member {uuid} [clientRequestId] The caller-generated request identity, in
* the form of a GUID with no decoration such as curly braces, e.g.
* 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0.
*
* @member {boolean} [returnClientRequestId] Whether the server should return
* the client-request-id in the response. Default value: false .
*
* @member {date} [ocpDate] The time the request was issued. Client libraries
* typically set this to the current system clock time; set it explicitly if
* you are calling the REST API directly.
*
* @member {string} [ifMatch] An ETag value associated with the version of the
* resource known to the client. The operation will be performed only if the
* resource's current ETag on the service exactly matches the value specified
* by the client.
*
* @member {string} [ifNoneMatch] An ETag value associated with the version of
* the resource known to the client. The operation will be performed only if
* the resource's current ETag on the service does not match the value
* specified by the client.
*
* @member {date} [ifModifiedSince] A timestamp indicating the last modified
* time of the resource known to the client. The operation will be performed
* only if the resource on the service has been modified since the specified
* time.
*
* @member {date} [ifUnmodifiedSince] A timestamp indicating the last modified
* time of the resource known to the client. The operation will be performed
* only if the resource on the service has not been modified since the
* specified time.
*
*/
class PoolEnableAutoScaleOptions {
constructor() {
}
/**
* Defines the metadata of PoolEnableAutoScaleOptions
*
* @returns {object} metadata of PoolEnableAutoScaleOptions
*
*/
mapper() {
return {
required: false,
type: {
name: 'Composite',
className: 'PoolEnableAutoScaleOptions',
modelProperties: {
timeout: {
required: false,
defaultValue: 30,
type: {
name: 'Number'
}
},
clientRequestId: {
required: false,
type: {
name: 'String'
}
},
returnClientRequestId: {
required: false,
defaultValue: false,
type: {
name: 'Boolean'
}
},
ocpDate: {
required: false,
type: {
name: 'DateTimeRfc1123'
}
},
ifMatch: {
required: false,
type: {
name: 'String'
}
},
ifNoneMatch: {
required: false,
type: {
name: 'String'
}
},
ifModifiedSince: {
required: false,
type: {
name: 'DateTimeRfc1123'
}
},
ifUnmodifiedSince: {
required: false,
type: {
name: 'DateTimeRfc1123'
}
}
}
}
};
}
}
module.exports = PoolEnableAutoScaleOptions;
| begoldsm/azure-sdk-for-node | lib/services/batch/lib/models/poolEnableAutoScaleOptions.js | JavaScript | apache-2.0 | 3,796 |
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/
*/
// Tests that compatibility overrides are refreshed when showing the addon
// selection UI.
const PREF_GETADDONS_BYIDS = "extensions.getAddons.get.url";
const PREF_MIN_PLATFORM_COMPAT = "extensions.minCompatiblePlatformVersion";
var gTestAddon = null;
var gWin;
function waitForView(aView, aCallback) {
var view = gWin.document.getElementById(aView);
if (view.parentNode.selectedPanel == view) {
aCallback();
return;
}
view.addEventListener("ViewChanged", function() {
view.removeEventListener("ViewChanged", arguments.callee, false);
aCallback();
}, false);
}
function install_test_addon(aCallback) {
AddonManager.getInstallForURL(TESTROOT + "addons/browser_select_compatoverrides_1.xpi", function(aInstall) {
var listener = {
onInstallEnded: function() {
AddonManager.getAddonByID("addon1@tests.mozilla.org", function(addon) {
gTestAddon = addon;
aCallback();
});
}
};
aInstall.addListener(listener);
aInstall.install();
}, "application/x-xpinstall");
}
registerCleanupFunction(function() {
if (gWin)
gWin.close();
if (gTestAddon)
gTestAddon.uninstall();
Services.prefs.clearUserPref(PREF_MIN_PLATFORM_COMPAT);
});
function end_test() {
finish();
}
function test() {
waitForExplicitFinish();
Services.prefs.setCharPref(PREF_UPDATEURL, TESTROOT + "missing.rdf");
Services.prefs.setBoolPref(PREF_STRICT_COMPAT, false);
Services.prefs.setCharPref(PREF_MIN_PLATFORM_COMPAT, "0");
install_test_addon(run_next_test);
}
add_test(function() {
gWin = Services.ww.openWindow(null,
"chrome://mozapps/content/extensions/selectAddons.xul",
"",
"chrome,centerscreen,dialog,titlebar",
null);
waitForFocus(function() {
waitForView("select", run_next_test);
}, gWin);
});
add_test(function() {
for (var row = gWin.document.getElementById("select-rows").firstChild; row; row = row.nextSibling) {
if (row.localName == "separator")
continue;
if (row.id.substr(-18) != "@tests.mozilla.org")
continue;
is(row.id, "addon1@tests.mozilla.org", "Should get expected addon");
isnot(row.action, "incompatible", "Addon should not be incompatible");
gWin.close();
gWin = null;
run_next_test();
}
});
add_test(function() {
Services.prefs.setCharPref(PREF_GETADDONS_BYIDS, TESTROOT + "browser_select_compatoverrides.xml");
Services.prefs.setBoolPref(PREF_GETADDONS_CACHE_ENABLED, true);
gWin = Services.ww.openWindow(null,
"chrome://mozapps/content/extensions/selectAddons.xul",
"",
"chrome,centerscreen,dialog,titlebar",
null);
waitForFocus(function() {
waitForView("select", run_next_test);
}, gWin);
});
add_test(function() {
for (var row = gWin.document.getElementById("select-rows").firstChild; row; row = row.nextSibling) {
if (row.localName == "separator")
continue;
if (row.id.substr(-18) != "@tests.mozilla.org")
continue;
is(row.id, "addon1@tests.mozilla.org", "Should get expected addon");
is(row.action, "incompatible", "Addon should be incompatible");
run_next_test();
}
});
| sergecodd/FireFox-OS | B2G/gecko/toolkit/mozapps/extensions/test/browser/browser_select_compatoverrides.js | JavaScript | apache-2.0 | 3,468 |
// Copyright 2017 The Kubernetes 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.
import {actionbarViewName, stateName as chromeStateName} from '../../chrome/state';
import {breadcrumbsConfig} from '../../common/components/breadcrumbs/service';
import {stateName as storageClassList} from '../list/state';
import {stateName as parentState, stateUrl} from '../state';
import {ActionBarController} from './actionbar_controller';
import {StorageClassController} from './controller';
/**
* Config state object for the Storage Class detail view.
*
* @type {!ui.router.StateConfig}
*/
export const config = {
url: `${stateUrl}/:objectName`,
parent: parentState,
resolve: {
'storageClassResource': getStorageClassResource,
'storageClass': getStorageClass,
},
data: {
[breadcrumbsConfig]: {
'label': '{{$stateParams.objectName}}',
'parent': storageClassList,
},
},
views: {
'': {
controller: StorageClassController,
controllerAs: '$ctrl',
templateUrl: 'storageclass/detail/detail.html',
},
[`${actionbarViewName}@${chromeStateName}`]: {
controller: ActionBarController,
controllerAs: '$ctrl',
templateUrl: 'storageclass/detail/actionbar.html',
},
},
};
/**
* @param {!./../../common/resource/resourcedetail.StateParams} $stateParams
* @param {!angular.$resource} $resource
* @return {!angular.Resource}
* @ngInject
*/
export function getStorageClassResource($resource, $stateParams) {
return $resource(`api/v1/storageclass/${$stateParams.objectName}`);
}
/**
* @param {!angular.Resource} storageClassResource
* @return {!angular.$q.Promise}
* @ngInject
*/
export function getStorageClass(storageClassResource) {
return storageClassResource.get().$promise;
}
/**
* @param {!./../../common/resource/resourcedetail.StateParams} $stateParams
* @param {!angular.$resource} $resource
* @return {!angular.Resource}
* @ngInject
*/
export function storageClassPersistentVolumesResource($resource, $stateParams) {
return $resource(`api/v1/storageclass/${$stateParams.objectName}/persistentvolume`);
}
| kenan435/dashboard | src/app/frontend/storageclass/detail/stateconfig.js | JavaScript | apache-2.0 | 2,627 |
/*
* Copyright 2011-2020, The Trustees of Indiana University and Northwestern
* University. 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.
* --- END LICENSE_HEADER BLOCK ---
*/
import React from 'react';
import PropTypes from 'prop-types';
const ButtonCollectionListShowAll = ({
collectionsLength,
maxItems,
handleShowAll,
showAll
}) => {
if (collectionsLength > maxItems) {
return (
<button
aria-controls="collections-list-remaining-collections"
aria-expanded={showAll}
onClick={handleShowAll}
className="btn btn-link show-all"
role="button"
>
<i
className={`fa ${showAll ? 'fa-chevron-down' : 'fa-chevron-right'}`}
/>
{` Show ${showAll ? `less` : `${collectionsLength} items`}`}
</button>
);
}
return null;
};
ButtonCollectionListShowAll.propTypes = {
collectionsLength: PropTypes.number,
maxItems: PropTypes.number,
handleShowAll: PropTypes.func,
showAll: PropTypes.bool
};
export default ButtonCollectionListShowAll;
| nulib/avalon | app/javascript/components/collections/list/ButtonCollectionListShowAll.js | JavaScript | apache-2.0 | 1,564 |
define({
"viewer": {
"common": {
"close": "Sluiten",
"focusMainstage": "Stuur toetsenbordfocus naar media",
"expandImage": "Beeld vergroten"
},
"a11y": {
"skipToContent": "Overslaan naar content",
"headerAria": "Koptekst verhaal",
"panelAria": "Verhaalinhoud",
"mainStageAria": "Huidige verhaalinvoer media",
"logoLinkAria": "Logolink",
"toTop": "Ga naar eerste invoer",
"focusContent": "Terug naar inhoud",
"navAria": "Verhaalinvoer",
"toEntryAria": "Ga naar invoer %ENTRY_NUMBER%: %ENTRY_TITLE%",
"entryAria": "Invoer %ENTRY_NUMBER%: %ENTRY_TITLE%",
"loadingAria": "Verhaalinhoud wordt geladen",
"skipBelowContent": "Overslaan onder deze inhoud",
"skipBelowVideo": "Overslaan onder deze video",
"skipAboveContent": "Overslaan boven deze inhoud",
"skipAboveVideo": "Overslaan boven deze video",
"moreEntries": "Meer invoer"
},
"loading": {
"long": "Verhaal wordt gestart",
"long2": "Bedankt voor uw geduld",
"failButton": "Het verhaal opnieuw laden"
},
"signin": {
"title": "Verificatie is vereist",
"explainViewer": "Meld u aan met een account op %PORTAL_LINK% om toegang te krijgen tot het verhaal.",
"explainBuilder": "Meld u aan met een account op %PORTAL_LINK% om het verhaal te configureren."
},
"errors": {
"boxTitle": "Er is een fout opgetreden",
"invalidConfig": "Ongeldige configuratie",
"invalidConfigNoApp": "Webmapapplicatie-ID niet opgegeven in index.html.",
"invalidConfigNoAppDev": "Er is geen Web Mapping Application identifier opgegeven in URL parameters (?appid=). In ontwikkelingsmodus wordt de appid-configuratie in index.html genegeerd.",
"unspecifiedConfigOwner": "De gemachtigde eigenaar is niet geconfigureerd.",
"invalidConfigOwner": "De eigenaar van het verhaal is niet gemachtigd.",
"createMap": "Kan geen kaart creëren",
"invalidApp": "De %TPL_NAME% bestaat niet of is niet toegankelijk.",
"appLoadingFail": "Er is een probleem opgetreden. De %TPL_NAME% is niet correct geladen.",
"notConfiguredDesktop": "Het verhaal is nog niet geconfigureerd.",
"notConfiguredMobile": "De %TPL_NAME% builder wordt niet ondersteund op dit schermformaat. Pas indien mogelijk de grootte van uw browser aan voor toegang tot de builder of bouw uw verhaal op een apparaat met een groter scherm.",
"notConfiguredMobile2": "Draai uw apparaat een kwartslag om de %TPL_NAME% builder te gebruiken.",
"notAuthorized": "U bent niet gemachtigd om dit verhaal te openen",
"notAuthorizedBuilder": "U bent niet gemachtigd om %TPL_NAME% builder te gebruiken.",
"noBuilderIE": "De builder wordt niet ondersteund op eerdere versies van Internet Explorer dan versie %VERSION%. %UPGRADE%",
"noViewerIE": "Dit verhaal wordt niet ondersteund op eerdere versies van Internet Explorer dan versie %VERSION%. %UPGRADE%",
"noViewerIE2": "U probeert dit verhaal te bekijken met behulp van een oudere, niet-ondersteunde browser. Er kunnen functies niet werken of er kunnen andere onverwachte problemen ontstaan. Wij raden u aan te upgraden naar Internet Explorer 11 of een andere browser te gebruiken, zoals Chrome.",
"noViewerIE3": "In het najaar van 2017 zal dit verhaal niet meer laden op deze browser. Vanaf dat moment moet u een ondersteunde browser gebruiken om dit verhaal te bekijken.",
"upgradeBrowser": "<a href='http://browsehappy.com/' target='_blank'>Werk uw browser bij</a>.",
"mapLoadingFail": "Er is een probleem opgetreden. De kaart is niet correct geladen.",
"signOut": "Afmelden",
"attention": "Let op!"
},
"mainStage": {
"back": "Terug",
"errorDeleted": "Deze koppeling is niet actief (sectie is verwijderd)",
"errorNotPublished": "Deze koppeling is niet actief (sectie is niet gepubliceerd)"
},
"panel": {
"collapse": "Paneel samenvouwen",
"expand": "Paneel uitvouwen"
},
"mobileInfo": {
"legend": "Legenda",
"description": "Beschrijving",
"lblLegendMobileError": "Sorry, de legenda is niet beschikbaar. Laad het verhaal opnieuw.",
"lblLegendMobileErrorExplain": "De legenda is niet beschikbaar als het apparaat gedraaid is naar portretstand nadat het verhaal geladen is."
},
"mobileFooter": {
"swipeInvite": "Vegen om het verhaal te navigeren",
"lblNext": "Volgende",
"lblEnd": "U heeft het eind van het verhaal bereikt"
},
"headerFromCommon": {
"storymapsText": "Een Story Map",
"builderButton": "Bewerken",
"facebookTooltip": "Delen op Facebook",
"twitterTooltip": "Delen op Twitter",
"bitlyTooltip": "Ontvang een korte URL",
"templateTitle": "Titel voor template instellen",
"templateSubtitle": "Subtitel voor template instellen",
"share": "Delen",
"checking": "Controleren van uw verhaalcontent",
"fix": "Fouten in uw verhaal corrigeren",
"noerrors": "Geen problemen gedetecteerd",
"tooltipAutoplayDisabled": "Dit is niet beschikbaar in autoplaymodus.",
"notshared": "Verhaal niet gedeeld"
},
"mapFromCommon": {
"overview": "Overzichtskaart",
"legend": "Legenda",
"home": "Zoom Home"
},
"shareFromCommon": {
"copy": "Kopiëren",
"copied": "Gekopieerd",
"open": "Openen",
"embed": "Inbedden in webpagina",
"embedExplain": "Gebruik de volgende HTML-code om het verhaal in een webpagina in te sluiten.",
"size": "Grootte (breedte/hoogte):",
"autoplayLabel": "Autoplaymodus",
"autoplayExplain1": "Autoplaymodus speelt uw verhaal regelmatig af. Dit is ideaal voor een kiosk of monitor in een openbare ruimte, maar houd er rekening mee dat het verhaal in andere situaties moeilijker te lezen is. Deze functie wordt niet ondersteund op kleine schermen.",
"autoplayExplain2": "Wanneer deze modus actief is, kan het verhaal worden afgespeeld en gepauzeerd en kan de navigatiesnelheid worden aangepast.",
"linksupdated": "Links bijgewerkt!"
},
"locatorFromCommon": {
"error": "Locatie niet beschikbaar"
}
}
}); | Esri/map-series-storytelling-template-js | src/resources/tpl/viewer/nls/nl/template.js | JavaScript | apache-2.0 | 6,236 |
/**
* 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.
*/
import { combineReducers } from 'redux';
import messageToasts from 'src/components/MessageToasts/reducers';
import sqlLab from './sqlLab';
import localStorageUsageInKilobytes from './localStorageUsage';
import common from './common';
export default combineReducers({
sqlLab,
localStorageUsageInKilobytes,
messageToasts,
common,
});
| apache/incubator-superset | superset-frontend/src/SqlLab/reducers/index.js | JavaScript | apache-2.0 | 1,150 |
/*
Copyright 2019 Google LLC
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
https://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.
*/
var TruthTable = require("./TruthTable.js");
function Condition(element, parent) {
this.parent = parent;
this.element = element;
}
Condition.prototype.getExpression = function() {
return (
(this.element.childNodes &&
this.element.childNodes[0] &&
this.element.childNodes[0].nodeValue) ||
""
);
};
Condition.prototype.getMessages = function() {
return this.parent.getMessages();
};
Condition.prototype.getElement = function() {
return this.element;
};
Condition.prototype.getParent = function() {
return this.parent;
};
Condition.prototype.getLines = function(start, stop) {
return this.parent.getLines(start, stop);
};
Condition.prototype.getSource = function() {
if (!this.source) {
var start = this.element.lineNumber - 1,
stop = this.element.nextSibling.lineNumber - 1;
this.source = this.getLines(start, stop);
}
return this.source;
};
Condition.prototype.getTruthTable = function() {
if (!this.truthTable) {
this.truthTable = new TruthTable(this.getExpression());
}
return this.truthTable;
};
Condition.prototype.addMessage = function(msg) {
if (!msg.hasOwnProperty("entity")) {
msg.entity = this;
}
this.parent.addMessage(msg);
};
Condition.prototype.onConditions = function(pluginFunction, cb) {
pluginFunction(this, cb);
};
Condition.prototype.summarize = function() {
var summary = {};
summary.type = "Condition";
summary.condition = this.getExpression();
try {
summary.truthTable = this.getTruthTable();
} catch (e) {
//just swallow it
}
return summary;
};
//Public
module.exports = Condition;
| apigee/apigeelint | lib/package/Condition.js | JavaScript | apache-2.0 | 2,195 |
"use strict";
describe("View", function() {
var View = require("../../../lib/viewing/View");
var Backbone = require("../../../lib/application/Backbone");
var noop = require("../../../lib/util/noop");
it("overwrites delegateEvents", function() {
expect(View.prototype.delegateEvents).not.toBe(Backbone.View.prototype.delegateEvents);
});
it("overwrites undelegateEvents", function() {
expect(View.prototype.undelegateEvents).not.toBe(Backbone.View.prototype.undelegateEvents);
});
describe("Backbone events", function() {
var ExampleView;
var view;
beforeEach(function() {
ExampleView = View.extend({
events: {
"click .sample-element": "noop"
},
noop: noop
});
view = new ExampleView();
});
it("does not call delegateEvents", function() {
spyOn(Backbone.View.prototype, "delegateEvents");
view.delegateEvents();
expect(Backbone.View.prototype.delegateEvents).not.toHaveBeenCalled();
});
it("does not call undelegateEvents", function() {
spyOn(Backbone.View.prototype, "undelegateEvents");
view.undelegateEvents();
expect(Backbone.View.prototype.undelegateEvents).not.toHaveBeenCalled();
});
});
});
// ----------------------------------------------------------------------------
// Copyright (C) 2018 Bloomberg Finance L.P.
//
// 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.
//
// ----------------------------- END-OF-FILE ----------------------------------
| bloomberg/brisket | spec/server/viewing/ViewSpec.js | JavaScript | apache-2.0 | 2,157 |
<!--
// Function to validate EMail IDs
// Arguments : 1. mail : Value of the field containing Email or String Constant.
// Return Value: true if date is valid, false otherwise.
function isValidMail(mail)
{
m=new String(mail);
var mailLength=m.length
var totalDOT=0
var totalROUTE=0
var totalSPACE=0
// Should not beging with a '.' or '@'
if(m.charAt(0)=='@' || m.charAt(0) == '.')
{ return false; }
//
for(ctr=1;ctr<=mailLength;ctr++)
{ if (m.charAt(ctr)=='@') { totalROUTE++; }
if (m.charAt(ctr)=='.') { totalDOT++; }
if (m.charAt(ctr)==' ') { totalSPACE++; }
}
if (totalROUTE!=1) //Checking for Multiple @
{ return false; }
if(totalDOT<1) //Checking for Route Domain
{ return false; }
if(totalSPACE>0) //No Embeded Space
{ return false; }
//Checking for Invalid Characters
for(ctr=0;ctr<=mailLength;ctr++)
{
if (m.charAt(ctr)=='`') return false;
else if (m.charAt(ctr)=='!') return false;
else if (m.charAt(ctr)==' ') return false;
else if (m.charAt(ctr)=='#') return false;
else if (m.charAt(ctr)=='$') return false;
else if (m.charAt(ctr)=='%') return false;
else if (m.charAt(ctr)=='^') return false;
else if (m.charAt(ctr)=='&') return false;
else if (m.charAt(ctr)=='*') return false;
else if (m.charAt(ctr)=='(') return false;
else if (m.charAt(ctr)==')') return false;
else if (m.charAt(ctr)=='+') return false;
else if (m.charAt(ctr)=='=') return false;
else if (m.charAt(ctr)=='|') return false;
else if (m.charAt(ctr)=='\\') return false;
else if (m.charAt(ctr)=='{') return false;
else if (m.charAt(ctr)=='}') return false;
else if (m.charAt(ctr)=='[') return false;
else if (m.charAt(ctr)==']') return false;
else if (m.charAt(ctr)==':') return false;
else if (m.charAt(ctr)==';') return false;
else if (m.charAt(ctr)=='"') return false;
else if (m.charAt(ctr)=="'") return false;
else if (m.charAt(ctr)=='<') return false;
else if (m.charAt(ctr)=='>') return false;
else if (m.charAt(ctr)==',') return false;
else if (m.charAt(ctr)=='?') return false;
else if (m.charAt(ctr)=='/') return false;
}
return true;
}
//-->
| peter-watters/WebPortfolio | integra/airspeed/MailValidation.js | JavaScript | apache-2.0 | 2,169 |
/**
* Exports the {@link module:enyo/Scrollable~Scrollable} mixin.
*
* @wip
* @public
* @module enyo/Scrollable
*/
var
kind = require('../kind'),
utils = require('../utils'),
dom = require('../dom'),
dispatcher = require('../dispatcher');
var
Control = require('../Control'),
EventEmitter = require('../EventEmitter'),
ScrollMath = require('../ScrollMath');
var blockOptions = {
start: true,
end: true,
nearest: true,
farthest: true
};
function calcNodeVisibility (nodePos, nodeSize, scrollPos, scrollSize) {
return (nodePos >= scrollPos && nodePos + nodeSize <= scrollPos + scrollSize)
? 0
: nodePos - scrollPos > 0
? 1
: nodePos - scrollPos < 0
? -1
: 0;
}
/**
* Mix scrolling support into any Control that contains content suitable for scrolling.
*
* @mixin
* @wip
* @public
*/
var Scrollable = {
/**
* @private
*/
name: 'Scrollable',
/**
* An array of control definitions that will be instatiated with the scroller. Each object
* will be passed a `scroller` property that contains a reference to the scroller. The controls
* can register to receive scroll events from the scroller.
*
* @name scrollControls
* @type {Object[]}
* @default undefined
* @see module:enyo/NewThumb~NewThumb
* @public
* @memberof module:enyo/Scrollable~Scrollable
*/
/**
* Specifies how to horizontally scroll. Acceptable values are `'scroll'`, `'auto'`,
* `'hidden'`, and `'default'`. The precise effect of the setting is determined by the
* scroll strategy.
*
* @type {String}
* @default 'default'
* @public
*/
horizontal: 'default',
/**
* Specifies how to vertically scroll. Acceptable values are `'scroll'`, `'auto'`,
* `'hidden'`, and `'default'`. The precise effect of the setting is determined by the
* scroll strategy.
*
* @type {String}
* @default 'default'
* @public
*/
vertical: 'default',
/**
* The vertical scroll position.
*
* @type {Number}
* @default 0
* @public
*/
scrollTop: 0,
/**
* The horizontal scroll position.
*
* @type {Number}
* @default 0
* @public
*/
scrollLeft: 0,
/**
* Vestige of previous implementation -- should be eliminated and
* does not appear to be referenced, but leaving here for the moment
* to avoid accidental breakage.
*
* @private
*/
maxHeight: null,
/**
* Vestige of previous implementation -- should be eliminated, but
* currently still referenced.
*
* @private
*/
touch: true,
/**
* TODO: Document. Based on CSSOM View spec ().
* Options: 'smooth', 'instant', maybe 'auto'
* @see {@linkplain http://dev.w3.org/csswg/cssom-view/}
* @see {@linkplain https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView}
*
* @type {String}
* @default 'smooth'
* @public
*/
behavior: 'smooth',
/**
* TODO: Document. Based on CSSOM View spec (), but modified to add 'nearest' and
* 'farthest' to the possible values.
* Options: 'start', 'end', 'nearest', 'farthest'
* @see {@linkplain http://dev.w3.org/csswg/cssom-view/}
* @see {@linkplain https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView}
*
* @type {String}
* @default 'nearest'
* @public
*/
block: 'farthest',
/**
* Vestige of previous implementation -- should be eliminated and
* does not appear to be referenced, but leaving here for the moment
* to avoid accidental breakage.
*
* @private
*/
thumb: true,
/**
* If `true`, mouse wheel may be used to move the [scrollable]{@link module:enyo/Scrollable~Scrollable} control.
*
* @type {Boolean}
* @default true
* @public
*/
useMouseWheel: true,
/**
* This should ultimately be made public, but not sure it's fully baked so
* holding off for now.
*
* @private
*/
horizontalSnapIncrement: null,
/**
* This should ultimately be made public, but not sure it's fully baked so
* holding off for now.
*
* @private
*/
verticalSnapIncrement: null,
/**
* This should ultimately be made public, but not sure it's fully baked so
* holding off for now.
*
* @private
*/
suppressMouseEvents: false,
/**
* By default, {@link module:enyo/Scrollable~Scrollable} creates and
* uses a default instance of {@link module:enyo/ScrollMath~ScrollMath}, which
* is responsible for scroll physics.
*
* If you want to customize scroll physics, you can provide an object literal
* to the `scrollMath` property that will be used to create a
* {@link module:enyo/ScrollMath~ScrollMath} instance to your specifications.
* Make sure to include `kind: ScrollMath` in your object literal, along with
* whatever `ScrollMath` properties you want to set.
*
* @type {Object}
* @public
*/
scrollMath: {kind: ScrollMath},
/**
* This should ultimately be made public, but not sure it's fully baked so
* holding off for now.
*
* @private
*/
pageMultiplier: 1,
/**
* @private
*/
canScrollX: false,
/**
* @private
*/
canScrollY: false,
/**
* @private
*/
couldScrollX: false,
/**
* @private
*/
couldScrollY: false,
/**
* @private
*/
canScrollUp: false,
/**
* @private
*/
canScrollDown: false,
/**
* @private
*/
canScrollLeft: false,
/**
* @private
*/
canScrollRight: false,
/**
* @private
*/
velocity: 0,
/**
* @private
*/
topOffset: 0,
/**
* @private
*/
rightOffset: 0,
/**
* @private
*/
bottomOffset: 0,
/**
* @private
*/
leftOffset: 0,
/**
* @private
*/
mixins: [EventEmitter],
/**
* @private
*/
handlers: {
ondragstart: 'dragstart',
ondragfinish: 'dragfinish',
ondrag: 'drag',
onflick: 'flick',
ondown: 'down',
onmove: 'move',
onmousewheel: 'mousewheel',
onscroll: 'domScroll',
onScroll: 'scroll',
onScrollStart: 'scrollStart',
onScrollStop: 'scrollStop',
onShouldDrag: 'shouldDrag',
onStabilize: 'scroll'
},
events: {
onScrollStart: '',
onScroll: '',
onScrollStop: '',
onShouldDrag: ''
},
/**
* @private
*/
classes: 'enyo-scrollable enyo-fill',
/**
* @private
*/
create: kind.inherit(function (sup) {
return function() {
sup.apply(this, arguments);
var smc = [ utils.mixin(utils.clone(this.scrollMath), {name: 'scrollMath'}) ],
defProps = this.defaultProps;
this.defaultProps = {};
this.accessibilityPreventScroll = true;
this.createComponents(smc, {isChrome: true, owner: this});
if (this.scrollControls) {
this.createComponents(this.scrollControls, {isChrome: true, scroller: this});
}
this.defaultProps = defProps;
};
}),
/**
* @private
*/
destroy: kind.inherit(function (sup) {
return function () {
sup.apply(this, arguments);
if (this._suppressing) {
this._resumeMouseEvents();
}
};
}),
/**
* @private
*/
showingChangedHandler: kind.inherit(function (sup) {
return function (sender, event) {
// Calculate boundaries when shown, just in case
// anything has happened (like scroller contents changing)
// while we were hidden. We do this unconditionally since
// it's cheap to do it now and we avoid a lot of extra
// complexity by not trying to track whether we need it.
// May need to revisit this decision if related issues
// arise.
if (event.showing) {
this.calcBoundaries();
}
sup.apply(this, arguments);
if (!event.showing && this._suppressing) {
this._resumeMouseEvents();
}
};
}),
/**
* @private
*/
rendered: kind.inherit(function (sup) {
return function() {
sup.apply(this, arguments);
this.calcScrollNode();
this.calcBoundaries();
};
}),
/**
* @private
*/
horizontalSnapIncrementChanged: function() {
this.$.scrollMath.xSnapIncrement = this.horizontalSnapIncrement;
},
/**
* @private
*/
verticalSnapIncrementChanged: function() {
this.$.scrollMath.ySnapIncrement = this.verticalSnapIncrement;
},
/**
* @private
*/
horizontalChanged: function () {
var hEnabled = (this.hEnabled = (this.horizontal !== 'hidden'));
this.$.scrollMath.horizontal = hEnabled;
this.addRemoveClass('h-enabled', hEnabled);
this.emit('scrollabilityChanged');
},
/**
* @private
*/
verticalChanged: function () {
var vEnabled = (this.vEnabled = (this.vertical !== 'hidden'));
this.$.scrollMath.vertical = vEnabled;
this.addRemoveClass('v-enabled', vEnabled);
this.emit('scrollabilityChanged');
},
/**
* @private
*/
scrollTopChanged: function() {
this.$.scrollMath.setScrollY(-this.scrollTop);
},
/**
* @private
*/
scrollLeftChanged: function() {
this.$.scrollMath.setScrollX(-this.scrollLeft);
},
/**
* TODO: Document. Based on CSSOM View spec ()
* @see {@linkplain http://dev.w3.org/csswg/cssom-view/}
* @see {@linkplain https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView}
*
* @public
*/
scrollTo: function(x, y, opts) {
opts = opts || {};
opts.behavior = opts.behavior || this.behavior;
this.$.scrollMath.scrollTo(x, y, opts);
},
/**
* Leaving for legacy support; should use scrollToChild() instead
*
* @deprecated
* @public
*/
scrollToControl: function (control, opts) {
this.scrollToChild(control, opts);
},
/**
* Helper function for `scrollToChild()`
*
* May be overridden as needed by more specific implementations. This
* API is to be considered experimental and subject to change -- use at
* your own risk.
*
* @protected
*/
getChildOffsets: kind.inherit(function (sup) {
if (sup === utils.nop) {
return function (child, scrollBounds) {
var node = (child instanceof Control) ? child.hasNode() : child,
offsets = dom.getAbsoluteBounds(node),
viewportBounds = dom.getAbsoluteBounds(this.scrollNode);
offsets.right = document.body.offsetWidth - offsets.right;
viewportBounds.right = document.body.offsetWidth - viewportBounds.right;
// Make absolute controlBounds relative to scroll position
offsets.top += scrollBounds.top;
if (this.rtl) {
offsets.right += scrollBounds.left;
} else {
offsets.left += scrollBounds.left;
}
offsets.top = offsets.top - viewportBounds.top;
offsets.left = (this.rtl ? offsets.right : offsets.left) - (this.rtl ? viewportBounds.right : viewportBounds.left);
offsets.getMargin = function (side) {
return dom.getComputedBoxValue(node, 'margin', side);
};
return offsets;
};
}
else {
return sup;
}
}),
/**
* Helper function for `scrollToChild()`
*
* @private
*/
getTargetCoordinates: function (scrollBounds, offsets, opts) {
var block,
xDir,
yDir,
x,
y;
if (typeof opts === 'boolean') {
block = opts ? 'start' : 'end';
}
else if (typeof opts === 'object' && blockOptions[opts.block]) {
block = opts.block;
}
else {
block = this.block;
}
// 0: currently visible, 1: right of viewport, -1: left of viewport
xDir = calcNodeVisibility(offsets.left, offsets.width, scrollBounds.left, scrollBounds.clientWidth);
// 0: currently visible, 1: below viewport, -1: above viewport
yDir = calcNodeVisibility(offsets.top, offsets.height, scrollBounds.top, scrollBounds.clientHeight);
// If we're already scrolling and the direction the node is in is not the same as the direction we're scrolling,
// we need to recalculate based on where the scroller will end up, not where it is now. This is to handle the
// case where the node is currently visible but won't be once the scroller settles.
//
// NOTE: Currently setting block = 'nearest' whenever we make this correction to avoid some nasty jumpiness
// when 5-way moving horizontally in a vertically scrolling grid layout in Moonstone. Not sure this is the
// right fix.
if (this.isScrolling) {
if (this.xDir !== xDir) {
scrollBounds.left = this.destX;
xDir = calcNodeVisibility(offsets.left, offsets.width, scrollBounds.left, scrollBounds.clientWidth);
block = 'nearest';
}
if (this.yDir !== yDir) {
scrollBounds.top = this.destY;
yDir = calcNodeVisibility(offsets.top, offsets.height, scrollBounds.top, scrollBounds.clientHeight);
block = 'nearest';
}
}
switch (xDir) {
case 0:
x = this.scrollLeft;
break;
case 1:
// If control requested to be scrolled all the way to the viewport's left, or if the control
// is larger than the viewport, scroll to the control's left edge. Otherwise, scroll just
// far enough to get the control into view.
if (block === 'farthest' || block === 'start' || offsets.width > scrollBounds.clientWidth) {
x = offsets.left;
} else {
x = offsets.left - scrollBounds.clientWidth + offsets.width;
// If nodeStyle exists, add the _marginRight_ to the scroll value.
x += offsets.getMargin('right');
}
break;
case -1:
// If control requested to be scrolled all the way to the viewport's right, or if the control
// is larger than the viewport, scroll to the control's right edge. Otherwise, scroll just
// far enough to get the control into view.
if (block === 'farthest' || block === 'end' || offsets.width > scrollBounds.clientWidth) {
x = offsets.left - scrollBounds.clientWidth + offsets.width;
} else {
x = offsets.left;
// If nodeStyle exists, subtract the _marginLeft_ from the scroll value.
x -= offsets.getMargin('left');
}
break;
}
switch (yDir) {
case 0:
y = this.scrollTop;
break;
case 1:
// If control requested to be scrolled all the way to the viewport's top, or if the control
// is larger than the viewport, scroll to the control's top edge. Otherwise, scroll just
// far enough to get the control into view.
if (block === 'farthest' || block === 'start' || offsets.height > scrollBounds.clientHeight) {
y = offsets.top;
// If nodeStyle exists, subtract the _marginTop_ from the scroll value.
y -= offsets.getMargin('top');
} else {
y = offsets.top - scrollBounds.clientHeight + offsets.height;
// If nodeStyle exists, add the _marginBottom_ to the scroll value.
y += offsets.getMargin('bottom');
}
break;
case -1:
// If control requested to be scrolled all the way to the viewport's bottom, or if the control
// is larger than the viewport, scroll to the control's bottom edge. Otherwise, scroll just
// far enough to get the control into view.
if (block === 'farthest' || block === 'end' || offsets.height > scrollBounds.clientHeight) {
y = offsets.top - scrollBounds.clientHeight + offsets.height;
} else {
y = offsets.top;
// If nodeStyle exists, subtract the _marginBottom_ from the scroll value.
y -= offsets.getMargin('bottom');
}
break;
}
return {x: x, y: y, xDir: xDir, yDir: yDir};
},
/**
* Helper function for `scrollToChild()`
*
* May be overridden as needed by more specific implementations. This
* API is to be considered experimental and subject to change -- use at
* your own risk.
*
* @protected
*/
scrollToTarget: kind.inherit(function (sup) {
if (sup === utils.nop) {
return function (child, targetCoordinates, opts) {
this.scrollTo(targetCoordinates.x, targetCoordinates.y, opts);
};
}
else {
return sup;
}
}),
/**
* TODO: Document. Based on CSSOM View spec ()
* @see {@linkplain http://dev.w3.org/csswg/cssom-view/}
* @see {@linkplain https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView}
*
* @public
*/
scrollToChild: function(child, opts) {
var scrollBounds = this.getScrollBounds(),
offsets = this.getChildOffsets(child, scrollBounds),
coordinates = this.getTargetCoordinates(scrollBounds, offsets, opts);
this.scrollToTarget(child, coordinates, opts);
},
/**
* @public
*/
pageUp: function() {
this.paginate('up');
},
/**
* @public
*/
pageDown: function() {
this.paginate('down');
},
/**
* @public
*/
pageLeft: function() {
this.paginate('left');
},
/**
* @public
*/
pageRight: function() {
this.paginate('right');
},
/**
* Stops any active scroll movement.
*
* @param {Boolean} emit - Whether or not to fire the `onScrollStop` event.
* @public
*/
stop: function () {
var m = this.$.scrollMath;
if (m.isScrolling()) {
m.stop(true);
}
},
/**
* @private
*/
paginate: function(direction) {
var b = this.calcBoundaries(),
scrollYDelta = b.clientHeight * this.pageMultiplier,
scrollXDelta = b.clientWidth * this.pageMultiplier,
x = this.scrollLeft,
y = this.scrollTop;
switch (direction) {
case 'left':
x -= scrollXDelta;
break;
case 'up':
y -= scrollYDelta;
break;
case 'right':
x += scrollXDelta;
break;
case 'down':
y += scrollYDelta;
break;
}
x = Math.max(0, Math.min(x, b.maxLeft));
y = Math.max(0, Math.min(y, b.maxTop));
this.scrollTo(x, y);
},
/**
/* @private
*/
mousewheel: function (sender, e) {
if (this.useMouseWheel) {
if (!this.$.scrollMath.isScrolling()) {
this.calcBoundaries();
}
// TODO: Change this after newMousewheel becomes mousewheel
if (this.$.scrollMath.newMousewheel(e, {rtl: this.rtl})) {
e.preventDefault();
return true;
}
}
},
/**
* @private
*/
down: function (sender, e) {
var m = this.$.scrollMath;
if (m.isScrolling() && !m.isInOverScroll() && !this.isScrollControl(e.originator)) {
this.stop(true);
e.preventTap();
}
this.calcStartInfo();
},
/**
* @private
*/
dragstart: function (sender, e) {
if (this.touch) {
this.calcBoundaries();
// Ignore drags sent from multi-touch events
if(!this.dragDuringGesture && e.srcEvent.touches && e.srcEvent.touches.length > 1) {
return true;
}
// note: allow drags to propagate to parent scrollers via data returned in the shouldDrag event.
this.doShouldDrag(e);
this.dragging = (e.dragger == this || (!e.dragger && e.boundaryDragger == this));
if (this.dragging) {
if(this.preventDefault){
e.preventDefault();
}
// note: needed because show/hide changes
// the position so sync'ing is required when
// dragging begins (needed because show/hide does not trigger onscroll)
//this.syncScrollMath();
this.$.scrollMath.startDrag(e);
if (this.preventDragPropagation) {
return true;
}
}
}
},
/**
* @private
*/
drag: function (sender, e) {
if (this.touch) {
if (this.dragging) {
if(this.preventDefault){
e.preventDefault();
}
this.$.scrollMath.drag(e);
}
}
},
/**
* @private
*/
dragfinish: function (sender, e) {
if (this.touch) {
if (this.dragging) {
e.preventTap();
this.$.scrollMath.dragFinish();
this.dragging = false;
}
}
},
/**
* @private
*/
flick: function (sender, e) {
if (this.touch) {
var onAxis = Math.abs(e.xVelocity) > Math.abs(e.yVelocity) ? this.$.scrollMath.horizontal : this.$.scrollMath.vertical;
if (onAxis && this.dragging) {
this.$.scrollMath.flick(e);
return this.preventDragPropagation;
}
}
},
/**
* @private
*/
shouldDrag: function (sender, e) {
//this.calcAutoScrolling();
var requestV = e.vertical,
// canH = this.$.scrollMath.horizontal && !requestV,
// canV = this.$.scrollMath.vertical && requestV,
canH = this.$.scrollMath.canScrollX() && !requestV,
canV = this.$.scrollMath.canScrollY() && requestV,
down = e.dy < 0,
right = e.dx < 0,
oobV = (!down && this.startEdges.top || down && this.startEdges.bottom),
oobH = (!right && this.startEdges.left || right && this.startEdges.right);
// we would scroll if not at a boundary
if (!e.boundaryDragger && (canH || canV)) {
e.boundaryDragger = this;
}
// include boundary exclusion
if ((!oobV && canV) || (!oobH && canH)) {
e.dragger = this;
return true;
}
},
stabilize: function() {
this.$.scrollMath.stabilize();
},
/**
* @private
*/
scroll: kind.inherit(function (sup) {
return function(sender, event) {
var px = this.scrollLeft,
py = this.scrollTop,
pv = this.velocity,
x = this.scrollLeft = -sender.x,
y = this.scrollTop = -sender.y,
dx = px - x,
dy = py - y,
v = (dx * dx) + (dy * dy);
this.xDir = (dx < 0? 1: dx > 0? -1: 0);
this.yDir = (dy < 0? 1: dy > 0? -1: 0);
this.velocity = v;
this.acc = v > pv;
this.dec = v < pv;
this.destX = -sender.endX;
this.destY = -sender.endY;
this.updateScrollability(x, y);
// Experimental: suppress and resume mouse events
// based on veclocity and acceleration
this._manageMouseEvents();
sup.apply(this, arguments);
};
}),
/**
* @private
*/
updateScrollability: function(x, y) {
var m = this.$.scrollMath,
b = -m.bottomBoundary,
r = -m.rightBoundary,
c = (this.canScrollX !== this.couldScrollX) ||
(this.canScrollY !== this.couldScrollY);
if (this.canScrollY || this.couldScrollY) {
this.set('yPosRatio', y / b);
if (this.canScrollUp) {
if (y <= 0) {
this.canScrollUp = false;
c = true;
}
}
else {
if (y > 0) {
this.canScrollUp = true;
c = true;
}
}
if (this.canScrollDown) {
if (y >= b) {
this.canScrollDown = false;
c = true;
}
}
else {
if (y < b) {
this.canScrollDown = true;
c = true;
}
}
}
if (this.canScrollX || this.couldScrollX) {
this.set('xPosRatio', x / r);
if (this.canScrollLeft) {
if (x <= 0) {
this.canScrollLeft = false;
c = true;
}
}
else {
if (x > 0) {
this.canScrollLeft = true;
c = true;
}
}
if (this.canScrollRight) {
if (x >= r) {
this.canScrollRight = false;
c = true;
}
}
else {
if (x < r) {
this.canScrollRight = true;
c = true;
}
}
}
this.couldScrollX = this.canScrollX;
this.couldScrollY = this.canScrollY;
if (c) {
this.emit('scrollabilityChanged');
}
},
/**
* @private
*/
scrollStart: function () {
this.calcBoundaries();
this.isScrolling = true;
this.emit('stateChanged');
},
/**
* @private
*/
scrollStop: function () {
// TODO: Leaving this in to be safe...
// But we should already have resumed, due to
// velocity-sensitive logic in scroll().
// This whole scheme probably needs bullet-proofing.
if (!this.touch) {
this._resumeMouseEvents();
}
this.isScrolling = false;
this.emit('stateChanged');
},
/**
* @private
*/
_manageMouseEvents: function () {
// TODO: Experiment, make configurable
var t = 5,
v = this.velocity;
if (this._suppressing) {
if (this.dec && v < t) {
this._resumeMouseEvents();
}
}
// TODO: Can probably allow suppressing events when this.touch === true
// if we resume events on down so we can capture flicks and drags. Need
// to experiment.
else if (this.suppressMouseEvents && !this.touch) {
if (this.isScrolling && this.acc && v > t) {
this._suppressMouseEvents();
}
}
},
/**
* @private
*/
_suppressMouseEvents: function () {
// TODO: Create a dispatcher API for this
dispatcher.stopListening(document, 'mouseover');
dispatcher.stopListening(document, 'mouseout');
dispatcher.stopListening(document, 'mousemove');
this._suppressing = true;
},
/**
* @private
*/
_resumeMouseEvents: function () {
// TODO: Create a dispatcher API for this
dispatcher.listen(document, 'mouseover');
dispatcher.listen(document, 'mouseout');
dispatcher.listen(document, 'mousemove');
this._suppressing = false;
},
/**
* @private
*/
getScrollBounds: function () {
var s = this.getScrollSize(), cn = this.calcScrollNode();
var b = {
left: this.get('scrollLeft'),
top: this.get('scrollTop'),
clientHeight: cn ? cn.clientHeight : 0,
clientWidth: cn ? cn.clientWidth : 0,
height: s.height,
width: s.width
};
b.maxLeft = Math.max(0, b.width - b.clientWidth);
b.maxTop = Math.max(0, b.height - b.clientHeight);
this.cachedBounds = b;
return b;
},
/**
* @private
*/
getScrollSize: function () {
var n = this.calcScrollNode(),
w = this.getScrollWidth && this.getScrollWidth() || (n ? n.scrollWidth : 0),
h = this.getScrollHeight && this.getScrollHeight() || (n ? n.scrollHeight : 0);
return {width: w, height: h};
},
/**
* @private
*/
calcScrollNode: kind.inherit(function (sup) {
return function() {
return (this.scrollNode = sup.apply(this, arguments) || this.hasNode());
};
}),
/**
* @private
*/
calcStartInfo: function (bounds) {
var sb = bounds || this.getScrollBounds(),
y = this.scrollTop,
x = this.scrollLeft;
// this.canVertical = sb.maxTop > 0 && this.vertical !== 'hidden';
// this.canHorizontal = sb.maxLeft > 0 && this.horizontal !== 'hidden';
this.startEdges = {
top: y === 0,
bottom: y === sb.maxTop,
left: x === 0,
right: x === sb.maxLeft
};
},
/**
* @private
*/
calcBoundaries: function (bounds) {
var m = this.$.scrollMath,
b = bounds || this.getScrollBounds(),
width = b.width,
height = b.height,
clWidth = b.clientWidth,
clHeight = b.clientHeight,
rBound = clWidth - width,
bBound = clHeight - height,
xRatio = Math.min(1, clWidth / width),
yRatio = Math.min(1, clHeight / height),
cTop = Math.min(b.top, Math.max(0, -bBound)),
cLeft = Math.min(b.left, Math.max(0, -rBound));
m.rightBoundary = rBound;
m.bottomBoundary = bBound;
this.set('canScrollX', m.canScrollX());
this.set('canScrollY', m.canScrollY());
if (b.top !== cTop || b.left !== cLeft) {
b.left = cLeft;
b.top = cTop;
m.setScrollX(-cLeft);
m.setScrollY(-cTop);
this.scroll(m);
this.stop();
}
this.set('xSizeRatio', xRatio);
this.set('ySizeRatio', yRatio);
this.updateScrollability(cLeft, cTop);
return b;
},
// xSizeRatioChanged: function() {
// this.emit('metricsChanged', this.xSizeRatio);
// },
// ySizeRatioChanged: function() {
// this.emit('metricsChanged', this.ySizeRatio);
// },
xPosRatioChanged: function() {
this.emit('metricsChanged', this.xPosRatio);
},
yPosRatioChanged: function() {
this.emit('metricsChanged', this.yPosRatio);
},
// canScrollXChanged: function() {
// this.emit('scrollabilityChanged');
// },
// canScrollYChanged: function() {
// this.emit('scrollabilityChanged');
// }
/**
* Returns `true` if `control` is a scrolling child of this
* scrollable (an element within the Scrollable's scrolling
* region).
*
* (Currently, we assume that any child of the Scrollable that
* is not a scroll control is a scrolling child, but this
* is an implementation detail and could change if we
* determine that there's a more appropriate way to test.)
*
* Returns `false` if `control` is one of the Scrollable's
* scroll controls, or if `control` is not a child of the
* Scrollable at all.
*
* @param {module:enyo/Control~Control} control - The control to be tested
* @protected
*/
isScrollingChild: function (control) {
var c = control;
while (c && c !== this) {
if (c.scroller === this) {
return false;
}
c = c.parent;
}
return c === this;
},
/**
* Returns `true` if `control` is one of the Scrollable's
* scroll controls.
*
* @param {module:enyo/Control~Control} control - The control to be tested
* @protected
*/
isScrollControl: function (control) {
var c = control;
while (c && c !== this) {
if (c.scroller === this) {
return true;
}
c = c.parent;
}
return false;
}
};
module.exports = Scrollable;
| enyojs/enyo | src/Scrollable/Scrollable.js | JavaScript | apache-2.0 | 27,197 |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function () {
'use strict';
var module = angular.module('pnc.projects', [
'ui.router',
'pnc.common.restclient',
'pnc.common.directives',
'pnc.common.authentication',
'angularUtils.directives.uiBreadcrumbs'
]);
module.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
// NCL-2402 changed the module base URL, this redirect should
// be removed at some point in the future.
$urlRouterProvider.when(/^\/project\/.*/, function ($location) {
return $location.url().replace('/project/', '/projects/');
});
$stateProvider.state('projects', {
abstract: true,
url: '/projects',
views: {
'content@': {
templateUrl: 'common/templates/single-col.tmpl.html'
}
},
data: {
proxy: 'projects.list'
}
});
$stateProvider.state('projects.list', {
url: '',
templateUrl: 'projects/views/projects.list.html',
data: {
displayName: 'Projects'
},
controller: 'ProjectListController',
controllerAs: 'listCtrl',
resolve: {
projectList: function(ProjectDAO) {
return ProjectDAO.getAll().$promise;
}
}
});
$stateProvider.state('projects.detail', {
url: '/{projectId:int}',
templateUrl: 'projects/views/projects.detail.html',
data: {
displayName: '{{ projectDetail.name }}',
},
controller: 'ProjectDetailController',
controllerAs: 'detailCtrl',
resolve: {
projectDetail: function(ProjectDAO, $stateParams) {
return ProjectDAO.get({
projectId: $stateParams.projectId}).$promise;
}
}
});
$stateProvider.state('projects.detail.create-bc', {
url: '/create-bc',
templateUrl: 'projects/views/projects.detail.create-bc.html',
data: {
displayName: 'Create Build Config',
requireAuth: true
},
controller: 'CreateBCController',
controllerAs: 'ctrl',
resolve: {
projectDetail: function(ProjectDAO, $stateParams) {
return ProjectDAO.get({
projectId: $stateParams.projectId}).$promise;
}
}
});
$stateProvider.state('projects.create', {
url: '/create',
templateUrl: 'projects/views/projects.create.html',
data: {
displayName: 'Create Project',
requireAuth: true
},
controller: 'ProjectCreateController',
controllerAs: 'createCtrl'
});
}
]);
})();
| thauser/pnc | ui/app/projects/_projects.js | JavaScript | apache-2.0 | 3,420 |
/**
* @license Copyright 2016 The Lighthouse Authors. 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.
*/
'use strict';
const listAudits = require('./list-audits.js');
const listTraceCategories = require('./list-trace-categories.js');
module.exports = {
listAudits,
listTraceCategories,
};
| umaar/lighthouse | lighthouse-cli/commands/commands.js | JavaScript | apache-2.0 | 794 |
/* Copyright 2017 Mozilla Foundation
*
* 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.
*/
import {
CFFCompiler, CFFIndex, CFFParser, CFFStrings
} from '../../src/core/cff_parser';
import { SEAC_ANALYSIS_ENABLED } from '../../src/core/fonts';
import { Stream } from '../../src/core/stream';
describe('CFFParser', function() {
function createWithNullProto(obj) {
var result = Object.create(null);
for (var i in obj) {
result[i] = obj[i];
}
return result;
}
var fontData, parser, cff;
beforeAll(function (done) {
// This example font comes from the CFF spec:
// http://www.adobe.com/content/dam/Adobe/en/devnet/font/pdfs/5176.CFF.pdf
var exampleFont = '0100040100010101134142434445462b' +
'54696d65732d526f6d616e000101011f' +
'f81b00f81c02f81d03f819041c6f000d' +
'fb3cfb6efa7cfa1605e911b8f1120003' +
'01010813183030312e30303754696d65' +
'7320526f6d616e54696d657300000002' +
'010102030e0e7d99f92a99fb7695f773' +
'8b06f79a93fc7c8c077d99f85695f75e' +
'9908fb6e8cf87393f7108b09a70adf0b' +
'f78e14';
var fontArr = [];
for (var i = 0, ii = exampleFont.length; i < ii; i += 2) {
var hex = exampleFont.substr(i, 2);
fontArr.push(parseInt(hex, 16));
}
fontData = new Stream(fontArr);
done();
});
afterAll(function () {
fontData = null;
});
beforeEach(function (done) {
parser = new CFFParser(fontData, {}, SEAC_ANALYSIS_ENABLED);
cff = parser.parse();
done();
});
afterEach(function (done) {
parser = cff = null;
done();
});
it('parses header', function() {
var header = cff.header;
expect(header.major).toEqual(1);
expect(header.minor).toEqual(0);
expect(header.hdrSize).toEqual(4);
expect(header.offSize).toEqual(1);
});
it('parses name index', function() {
var names = cff.names;
expect(names.length).toEqual(1);
expect(names[0]).toEqual('ABCDEF+Times-Roman');
});
it('sanitizes name index', function() {
var index = new CFFIndex();
index.add(['['.charCodeAt(0), 'a'.charCodeAt(0)]);
var names = parser.parseNameIndex(index);
expect(names).toEqual(['_a']);
index = new CFFIndex();
var longName = [];
for (var i = 0; i < 129; i++) {
longName.push(0);
}
index.add(longName);
names = parser.parseNameIndex(index);
expect(names[0].length).toEqual(127);
});
it('parses string index', function() {
var strings = cff.strings;
expect(strings.count).toEqual(3);
expect(strings.get(0)).toEqual('.notdef');
expect(strings.get(391)).toEqual('001.007');
});
it('parses top dict', function() {
var topDict = cff.topDict;
// 391 version 392 FullName 393 FamilyName 389 Weight 28416 UniqueID
// -168 -218 1000 898 FontBBox 94 CharStrings 45 102 Private
expect(topDict.getByName('version')).toEqual(391);
expect(topDict.getByName('FullName')).toEqual(392);
expect(topDict.getByName('FamilyName')).toEqual(393);
expect(topDict.getByName('Weight')).toEqual(389);
expect(topDict.getByName('UniqueID')).toEqual(28416);
expect(topDict.getByName('FontBBox')).toEqual([-168, -218, 1000, 898]);
expect(topDict.getByName('CharStrings')).toEqual(94);
expect(topDict.getByName('Private')).toEqual([45, 102]);
});
it('refuses to add topDict key with invalid value (bug 1068432)',
function () {
var topDict = cff.topDict;
var defaultValue = topDict.getByName('UnderlinePosition');
topDict.setByKey(/* [12, 3] = */ 3075, [NaN]);
expect(topDict.getByName('UnderlinePosition')).toEqual(defaultValue);
});
it('ignores reserved commands in parseDict, and refuses to add privateDict ' +
'keys with invalid values (bug 1308536)', function () {
var bytes = new Uint8Array([
64, 39, 31, 30, 252, 114, 137, 115, 79, 30, 197, 119, 2, 99, 127, 6
]);
parser.bytes = bytes;
var topDict = cff.topDict;
topDict.setByName('Private', [bytes.length, 0]);
var parsePrivateDict = function () {
parser.parsePrivateDict(topDict);
};
expect(parsePrivateDict).not.toThrow();
var privateDict = topDict.privateDict;
expect(privateDict.getByName('BlueValues')).toBeNull();
});
it('parses a CharString having cntrmask', function() {
var bytes = new Uint8Array([0, 1, // count
1, // offsetSize
0, // offset[0]
38, // end
149, 149, 149, 149, 149, 149, 149, 149,
149, 149, 149, 149, 149, 149, 149, 149,
1, // hstem
149, 149, 149, 149, 149, 149, 149, 149,
149, 149, 149, 149, 149, 149, 149, 149,
3, // vstem
20, // cntrmask
22, 22, // fail if misparsed as hmoveto
14 // endchar
]);
parser.bytes = bytes;
var charStringsIndex = parser.parseIndex(0).obj;
var charStrings = parser.parseCharStrings(charStringsIndex).charStrings;
expect(charStrings.count).toEqual(1);
// shoudn't be sanitized
expect(charStrings.get(0).length).toEqual(38);
});
it('parses a CharString endchar with 4 args w/seac enabled', function() {
var parser = new CFFParser(fontData, {},
/* seacAnalysisEnabled = */ true);
parser.parse(); // cff
var bytes = new Uint8Array([0, 1, // count
1, // offsetSize
0, // offset[0]
237, 247, 22, 247, 72, 204, 247, 86, 14]);
parser.bytes = bytes;
var charStringsIndex = parser.parseIndex(0).obj;
var result = parser.parseCharStrings(charStringsIndex);
expect(result.charStrings.count).toEqual(1);
expect(result.charStrings.get(0).length).toEqual(1);
expect(result.seacs.length).toEqual(1);
expect(result.seacs[0].length).toEqual(4);
expect(result.seacs[0][0]).toEqual(130);
expect(result.seacs[0][1]).toEqual(180);
expect(result.seacs[0][2]).toEqual(65);
expect(result.seacs[0][3]).toEqual(194);
});
it('parses a CharString endchar with 4 args w/seac disabled', function() {
var parser = new CFFParser(fontData, {},
/* seacAnalysisEnabled = */ false);
parser.parse(); // cff
var bytes = new Uint8Array([0, 1, // count
1, // offsetSize
0, // offset[0]
237, 247, 22, 247, 72, 204, 247, 86, 14]);
parser.bytes = bytes;
var charStringsIndex = parser.parseIndex(0).obj;
var result = parser.parseCharStrings(charStringsIndex);
expect(result.charStrings.count).toEqual(1);
expect(result.charStrings.get(0).length).toEqual(9);
expect(result.seacs.length).toEqual(0);
});
it('parses a CharString endchar no args', function() {
var bytes = new Uint8Array([0, 1, // count
1, // offsetSize
0, // offset[0]
14]);
parser.bytes = bytes;
var charStringsIndex = parser.parseIndex(0).obj;
var result = parser.parseCharStrings(charStringsIndex);
expect(result.charStrings.count).toEqual(1);
expect(result.charStrings.get(0)[0]).toEqual(14);
expect(result.seacs.length).toEqual(0);
});
it('parses predefined charsets', function() {
var charset = parser.parseCharsets(0, 0, null, true);
expect(charset.predefined).toEqual(true);
});
it('parses charset format 0', function() {
// The first three bytes make the offset large enough to skip predefined.
var bytes = new Uint8Array([0x00, 0x00, 0x00,
0x00, // format
0x00, 0x02 // sid/cid
]);
parser.bytes = bytes;
var charset = parser.parseCharsets(3, 2, new CFFStrings(), false);
expect(charset.charset[1]).toEqual('exclam');
// CID font
charset = parser.parseCharsets(3, 2, new CFFStrings(), true);
expect(charset.charset[1]).toEqual(2);
});
it('parses charset format 1', function() {
// The first three bytes make the offset large enough to skip predefined.
var bytes = new Uint8Array([0x00, 0x00, 0x00,
0x01, // format
0x00, 0x08, // sid/cid start
0x01 // sid/cid left
]);
parser.bytes = bytes;
var charset = parser.parseCharsets(3, 2, new CFFStrings(), false);
expect(charset.charset).toEqual(['.notdef', 'quoteright', 'parenleft']);
// CID font
charset = parser.parseCharsets(3, 2, new CFFStrings(), true);
expect(charset.charset).toEqual(['.notdef', 8, 9]);
});
it('parses charset format 2', function() {
// format 2 is the same as format 1 but the left is card16
// The first three bytes make the offset large enough to skip predefined.
var bytes = new Uint8Array([0x00, 0x00, 0x00,
0x02, // format
0x00, 0x08, // sid/cid start
0x00, 0x01 // sid/cid left
]);
parser.bytes = bytes;
var charset = parser.parseCharsets(3, 2, new CFFStrings(), false);
expect(charset.charset).toEqual(['.notdef', 'quoteright', 'parenleft']);
// CID font
charset = parser.parseCharsets(3, 2, new CFFStrings(), true);
expect(charset.charset).toEqual(['.notdef', 8, 9]);
});
it('parses encoding format 0', function() {
// The first two bytes make the offset large enough to skip predefined.
var bytes = new Uint8Array([0x00, 0x00,
0x00, // format
0x01, // count
0x08 // start
]);
parser.bytes = bytes;
var encoding = parser.parseEncoding(2, {}, new CFFStrings(), null);
expect(encoding.encoding).toEqual(createWithNullProto({0x8: 1}));
});
it('parses encoding format 1', function() {
// The first two bytes make the offset large enough to skip predefined.
var bytes = new Uint8Array([0x00, 0x00,
0x01, // format
0x01, // num ranges
0x07, // range1 start
0x01 // range2 left
]);
parser.bytes = bytes;
var encoding = parser.parseEncoding(2, {}, new CFFStrings(), null);
expect(encoding.encoding).toEqual(
createWithNullProto({0x7: 0x01, 0x08: 0x02}));
});
it('parses fdselect format 0', function() {
var bytes = new Uint8Array([0x00, // format
0x00, // gid: 0 fd: 0
0x01 // gid: 1 fd: 1
]);
parser.bytes = bytes.slice();
var fdSelect = parser.parseFDSelect(0, 2);
expect(fdSelect.fdSelect).toEqual([0, 1]);
expect(fdSelect.raw).toEqual(bytes);
});
it('parses fdselect format 3', function() {
var bytes = new Uint8Array([0x03, // format
0x00, 0x02, // range count
0x00, 0x00, // first gid
0x09, // font dict 1 id
0x00, 0x02, // next gid
0x0a, // font dict 2 id
0x00, 0x04 // sentinel (last gid)
]);
parser.bytes = bytes.slice();
var fdSelect = parser.parseFDSelect(0, 4);
expect(fdSelect.fdSelect).toEqual([9, 9, 0xa, 0xa]);
expect(fdSelect.raw).toEqual(bytes);
});
it('parses invalid fdselect format 3 (bug 1146106)', function() {
var bytes = new Uint8Array([0x03, // format
0x00, 0x02, // range count
0x00, 0x01, // first gid (invalid)
0x09, // font dict 1 id
0x00, 0x02, // next gid
0x0a, // font dict 2 id
0x00, 0x04 // sentinel (last gid)
]);
parser.bytes = bytes.slice();
var fdSelect = parser.parseFDSelect(0, 4);
expect(fdSelect.fdSelect).toEqual([9, 9, 0xa, 0xa]);
bytes[3] = bytes[4] = 0x00; // The adjusted first range, first gid.
expect(fdSelect.raw).toEqual(bytes);
});
// TODO fdArray
});
describe('CFFCompiler', function() {
it('encodes integers', function() {
var c = new CFFCompiler();
// all the examples from the spec
expect(c.encodeInteger(0)).toEqual([0x8b]);
expect(c.encodeInteger(100)).toEqual([0xef]);
expect(c.encodeInteger(-100)).toEqual([0x27]);
expect(c.encodeInteger(1000)).toEqual([0xfa, 0x7c]);
expect(c.encodeInteger(-1000)).toEqual([0xfe, 0x7c]);
expect(c.encodeInteger(10000)).toEqual([0x1c, 0x27, 0x10]);
expect(c.encodeInteger(-10000)).toEqual([0x1c, 0xd8, 0xf0]);
expect(c.encodeInteger(100000)).toEqual([0x1d, 0x00, 0x01, 0x86, 0xa0]);
expect(c.encodeInteger(-100000)).toEqual([0x1d, 0xff, 0xfe, 0x79, 0x60]);
});
it('encodes floats', function() {
var c = new CFFCompiler();
expect(c.encodeFloat(-2.25)).toEqual([0x1e, 0xe2, 0xa2, 0x5f]);
expect(c.encodeFloat(5e-11)).toEqual([0x1e, 0x5c, 0x11, 0xff]);
});
// TODO a lot more compiler tests
});
| ydfzgyj/pdf.js | test/unit/cff_parser_spec.js | JavaScript | apache-2.0 | 14,372 |
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { mapToCssModules, tagPropType } from './utils';
const propTypes = {
tag: tagPropType,
className: PropTypes.any,
cssModule: PropTypes.object,
};
const defaultProps = {
tag: 'p'
};
const ListGroupItemText = (props) => {
const {
className,
cssModule,
tag: Tag,
...attributes
} = props;
const classes = mapToCssModules(classNames(
className,
'list-group-item-text'
), cssModule);
return (
<Tag {...attributes} className={classes} />
);
};
ListGroupItemText.propTypes = propTypes;
ListGroupItemText.defaultProps = defaultProps;
export default ListGroupItemText;
| GoogleCloudPlatform/prometheus-engine | third_party/prometheus_ui/base/web/ui/react-app/node_modules/reactstrap/src/ListGroupItemText.js | JavaScript | apache-2.0 | 719 |
/*!
Copyright (C) 2014 Google Inc., authors, and contributors <see AUTHORS file>
Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
Created By: dan@reciprocitylabs.com
Maintained By: dan@reciprocitylabs.com
*/
(function(can) {
var _mustache_path,
overdue_compute;
overdue_compute = can.compute(function(val) {
if (this.attr("status") === "Verified") {
return "";
}
var date = moment(this.attr("next_due_date") || this.attr("end_date"));
if(date && date.isBefore(new Date())){
return "overdue";
}
return "";
});
function refresh_attr(instance, attr){
if (instance.attr(attr).reify().selfLink) {
instance.attr(attr).reify().refresh();
}
}
function refresh_attr_wrap(attr){
return function(ev, instance) {
if (instance instanceof this) {
refresh_attr(instance, attr);
}
};
}
_mustache_path = GGRC.mustache_path + "/cycles";
can.Model.Cacheable("CMS.Models.Cycle", {
root_object: "cycle",
root_collection: "cycles",
category: "workflow",
findAll: "GET /api/cycles",
findOne: "GET /api/cycles/{id}",
create: "POST /api/cycles",
update: "PUT /api/cycles/{id}",
destroy: "DELETE /api/cycles/{id}",
attributes: {
workflow: "CMS.Models.Workflow.stub",
cycle_task_groups: "CMS.Models.CycleTaskGroup.stubs",
modified_by: "CMS.Models.Person.stub",
context: "CMS.Models.Context.stub"
},
tree_view_options: {
show_view: _mustache_path + "/tree.mustache",
header_view : _mustache_path + "/tree_header.mustache",
draw_children: true,
child_options: [
{
model: "CycleTaskGroup",
mapping: "cycle_task_groups",
allow_creating: false
}
]
},
init: function(){
var that = this;
this._super.apply(this, arguments);
this.bind("created", refresh_attr_wrap('workflow').bind(this));
this.bind("destroyed", function(ev, inst) {
if(inst instanceof that) {
can.each(inst.cycle_task_groups, function(cycle_task_group) {
if (!cycle_task_group) {
return;
}
cycle_task_group = cycle_task_group.reify();
can.trigger(cycle_task_group, "destroyed");
can.trigger(cycle_task_group.constructor, "destroyed", cycle_task_group);
});
}
});
}
}, {
init: function() {
var that = this;
this._super.apply(this, arguments);
this.bind("status", function(ev, newVal) {
if (newVal === 'Verified') {
new RefreshQueue().enqueue(this.workflow.reify()).trigger().then(function(wfs) {
return wfs[0].get_binding("owners").refresh_instances();
}).then(function(wf_owner_bindings) {
var current_user = CMS.Models.get_instance(GGRC.current_user);
if(~can.inArray(
current_user,
can.map(wf_owner_bindings, function(wf_owner_binding) {
return wf_owner_binding.instance;
})
)) {
that.refresh().then(function() {
if(that.attr("is_current")) {
that.attr("is_current", false);
that.save();
}
});
}
});
}
});
},
overdue: overdue_compute,
});
_mustache_path = GGRC.mustache_path + "/cycle_task_entries";
can.Model.Cacheable("CMS.Models.CycleTaskEntry", {
root_object: "cycle_task_entry",
root_collection: "cycle_task_entries",
category: "workflow",
findAll: "GET /api/cycle_task_entries",
findOne: "GET /api/cycle_task_entries/{id}",
create: "POST /api/cycle_task_entries",
update: "PUT /api/cycle_task_entries/{id}",
destroy: "DELETE /api/cycle_task_entries/{id}",
attributes: {
cycle_task_group_object_task: "CMS.Models.CycleTaskGroupObjectTask.stub",
modified_by: "CMS.Models.Person.stub",
context: "CMS.Models.Context.stub",
object_documents: "CMS.Models.ObjectDocument.stubs",
documents: "CMS.Models.Document.stubs",
cycle: "CMS.Models.Cycle.stub"
},
tree_view_options: {
show_view: _mustache_path + "/tree.mustache",
footer_view: _mustache_path + "/tree_footer.mustache",
child_options: [{
//0: Documents
model: "Document",
mapping: "documents",
show_view: _mustache_path + "/documents.mustache",
footer_view: _mustache_path + "/documents_footer.mustache"
}],
},
init: function(){
this._super.apply(this, arguments);
this.bind("created",
refresh_attr_wrap("cycle_task_group_object_task").bind(this));
this.validateNonBlank("description");
}
}, {
workflowFolder: function() {
return this.refresh_all('cycle', 'workflow').then(function(workflow){
if (workflow.has_binding('folders')) {
return workflow.refresh_all('folders').then(function(folders){
if (folders.length === 0) {
return null; // workflow folder has not been assigned
}
return folders[0].instance;
}, function(result) {
return result;
});
}
});
}
});
_mustache_path = GGRC.mustache_path + "/cycle_task_groups";
can.Model.Cacheable("CMS.Models.CycleTaskGroup", {
root_object: "cycle_task_group",
root_collection: "cycle_task_groups",
category: "workflow",
findAll: "GET /api/cycle_task_groups",
findOne: "GET /api/cycle_task_groups/{id}",
create: "POST /api/cycle_task_groups",
update: "PUT /api/cycle_task_groups/{id}",
destroy: "DELETE /api/cycle_task_groups/{id}",
attributes: {
cycle: "CMS.Models.Cycle.stub",
task_group: "CMS.Models.TaskGroup.stub",
cycle_task_group_tasks: "CMS.Models.CycleTaskGroupObjectTask.stubs",
modified_by: "CMS.Models.Person.stub",
context: "CMS.Models.Context.stub"
},
tree_view_options: {
sort_property: 'sort_index',
show_view: _mustache_path + "/tree.mustache",
//footer_view: _mustache_path + "/tree_footer.mustache",
draw_children: true,
child_options: [
{
title: 'Tasks',
model: "CycleTaskGroupObjectTask",
mapping: "cycle_task_group_tasks",
allow_creating: false
}
]
},
init: function() {
var that = this;
this._super.apply(this, arguments);
this.validateNonBlank("contact");
this.validateContact(["_transient.contact", "contact"]);
this.bind("updated", function(ev, instance) {
if (instance instanceof that) {
var dfd = instance.refresh_all_force('cycle', 'workflow');
dfd.then(function(){
return $.when(
instance.refresh_all_force('related_objects'),
instance.refresh_all_force('cycle_task_group_tasks')
);
});
}
});
this.bind("destroyed", function(ev, inst) {
if(inst instanceof that) {
can.each(inst.cycle_task_group_tasks, function(ctgt) {
if (!ctgt) {
return;
}
ctgt = ctgt.reify();
can.trigger(ctgt, "destroyed");
can.trigger(ctgt.constructor, "destroyed", ctgt);
});
}
});
}
}, {
overdue: overdue_compute
});
_mustache_path = GGRC.mustache_path + "/cycle_task_group_object_tasks";
can.Model.Cacheable("CMS.Models.CycleTaskGroupObjectTask", {
root_object: "cycle_task_group_object_task",
root_collection: "cycle_task_group_object_tasks",
category: "workflow",
findAll: "GET /api/cycle_task_group_object_tasks",
findOne: "GET /api/cycle_task_group_object_tasks/{id}",
create: "POST /api/cycle_task_group_object_tasks",
update: "PUT /api/cycle_task_group_object_tasks/{id}",
destroy: "DELETE /api/cycle_task_group_object_tasks/{id}",
title_singular: "Cycle Task",
attributes: {
cycle_task_group: "CMS.Models.CycleTaskGroup.stub",
task_group_task: "CMS.Models.TaskGroupTask.stub",
cycle_task_entries: "CMS.Models.CycleTaskEntry.stubs",
modified_by: "CMS.Models.Person.stub",
contact: "CMS.Models.Person.stub",
context: "CMS.Models.Context.stub",
cycle: "CMS.Models.Cycle.stub"
},
permalink_options: {
url: "<%= base.viewLink %>#current_widget/cycle/<%= instance.cycle.id %>/cycle_task_group/<%= instance.cycle_task_group.id %>/cycle_task_group_object_task/<%= instance.id %>",
base: "cycle:workflow"
},
info_pane_options: {
mapped_objects: {
model: can.Model.Cacheable,
mapping: 'info_related_objects',
show_view: GGRC.mustache_path + '/base_templates/subtree.mustache'
}
},
tree_view_options: {
sort_property: 'sort_index',
show_view: _mustache_path + "/tree.mustache",
attr_list: [
{attr_title: 'Title', attr_name: 'title'},
{attr_title: 'Workflow', attr_name: 'workflow', attr_sort_field: 'cycle.workflow.title'},
{attr_title: 'State', attr_name: 'status'},
{attr_title: 'Assignee', attr_name: 'assignee', attr_sort_field: 'contact.name|email'},
{attr_title: 'Start Date', attr_name: 'start_date'},
{attr_title: 'End Date', attr_name: 'end_date'},
{attr_title: 'Last Updated', attr_name: 'updated_at'}
],
display_attr_names: ['title', 'mapped_object', 'workflow'],
mandatory_attr_name: ['title'],
draw_children: true,
child_options: [
{
model: "CycleTaskEntry",
mapping: "cycle_task_entries",
allow_creating: true
},
{
model: can.Model.Cacheable,
mapping: 'info_related_objects',
allow_creating: true
}
]
},
init: function() {
var that = this;
this._super.apply(this, arguments);
this.validateNonBlank("title");
this.validateNonBlank("contact");
this.validateContact(["_transient.contact", "contact"]);
this.validate(['start_date', 'end_date'], function (newVal, prop) {
if (!(this.start_date && this.end_date)) {
return "Start and/or end date is invalid";
}
});
this.bind("updated", function (ev, instance) {
if (instance instanceof that) {
instance.refresh_all_force('related_objects').then(function (object) {
return instance.refresh_all_force('cycle_task_group', 'cycle', 'workflow');
});
}
});
}
}, {
overdue: overdue_compute,
workflow: function () {
return this.refresh_all('cycle', 'workflow').then(function (workflow) {
return workflow;
});
},
object: function () {
return this.refresh_all('task_group_object', 'object').then(function (object) {
return object;
});
},
response_options_csv: can.compute(function (val) {
if(val != null) {
this.attr("response_options", $.map(val.split(","), $.proxy("".trim.call, "".trim)));
} else {
return (this.attr("response_options") || []).join(", ");
}
}),
selected_response_options_csv: can.compute(function(val) {
if(val != null) {
this.attr("selected_response_options", $.map(val.split(","), $.proxy("".trim.call, "".trim)));
} else {
return (this.attr("selected_response_options") || []).join(", ");
}
}),
get_filter_vals: function () {
var filter_vals = can.Model.Cacheable.prototype.get_filter_vals;
var mappings = jQuery.extend({}, this.class.filter_mappings, {
'task title': 'title'
});
var vals = filter_vals.apply(this, [this.class.filter_keys, mappings]);
try {
vals['workflows'] = this.cycle.reify().workflow.reify().title;
} catch (e) {}
return vals;
}
});
})(window.can);
| prasannav7/ggrc-core | src/ggrc_workflows/assets/javascripts/models/cycle_models.js | JavaScript | apache-2.0 | 12,025 |
var leftMenuView = Ti.UI.createView({
backgroundColor:'white',
width: Ti.UI.FILL,
height: Ti.UI.FILL
});
var centerView = Ti.UI.createView({
backgroundColor:'white',
width: Ti.UI.FILL,
height: Ti.UI.FILL
});
var rightMenuView = Ti.UI.createView({
backgroundColor:'#ddd',
width: Ti.UI.FILL,
height: Ti.UI.FILL
});
// create a menu
var leftTableView = Ti.UI.createTableView({
font:{fontSize:12},
rowHeight:40,
data:[
{title:'Toggle Left View'},
{title:'Change Center Windowr'},
{title:'Default Window'}
]
});
leftMenuView.add(leftTableView);
leftTableView.addEventListener("click", function(e){
Ti.API.info("isAnyWindowOpen: " + drawer.isAnyWindowOpen());
switch(e.index){
case 0:
drawer.toggleLeftWindow(); //animate back to center
alert("You clicked " + e.rowData.title + ". Implement menu structure.. ");
break;
case 1:
drawer.setCenterWindow(Ti.UI.createView({backgroundColor:"red"}));
drawer.toggleLeftWindow(); //animate back to center
break;
case 2:
drawer.setCenterWindow(centerView);
drawer.toggleLeftWindow(); //animate back to center
break;
}
});
// Action Bar - FAKE example
var actionBar = Ti.UI.createView({
top:0,
height:"44dp",
backgroundColor:"#333"
});
var leftToolbarBtn = Ti.UI.createButton({
title:"Left",
left: "6dp",
backgroundColor:"transparent",
color: "#FFF"
});
leftToolbarBtn.addEventListener("click", function(){
drawer.toggleLeftWindow();
});
var rightToolbarBtn = Ti.UI.createButton({
title:"Right",
right: "6dp",
backgroundColor:"transparent",
color: "#FFF"
});
rightToolbarBtn.addEventListener("click", function(){
drawer.toggleRightWindow();
});
var centerLabel = Ti.UI.createLabel({
text:"NappDrawer",
font:{
fontSize:"14dp",
fontWeight:"bold"
},
color: "#FFF"
});
actionBar.add(leftToolbarBtn);
actionBar.add(rightToolbarBtn);
actionBar.add(centerLabel);
centerView.add(actionBar);
// create interface
var scrollView = Ti.UI.createScrollView({
layout:"vertical",
left:0,right:0,top:"44dp",
contentHeight:'auto',
contentWidth:"100%",
showVerticalScrollIndicator: true,
showHorizontalScrollIndicator: false
});
var slider = Ti.UI.createSlider({
top: "20dp", width: "280dp",
min: 0, max: 1,
value: 0.2
});
var label = Ti.UI.createLabel({
text: "Parallax: " + slider.value,
color:"#000",
top: "15dp"
});
slider.addEventListener('touchend', function(e) {
label.setText("Parallax: " + e.source.value);
drawer.setParallaxAmount(e.source.value);
});
scrollView.add(label);
scrollView.add(slider);
var gestureModeBtn = Ti.UI.createButton({title:"Gesture Mode: ALL", toggled:true, top:10});
gestureModeBtn.addEventListener("click", function(e){
if(!e.source.toggled){
var mode = "ALL";
drawer.setOpenDrawerGestureMode(NappDrawerModule.MODE_ALL);
} else {
var mode = "NONE";
drawer.setOpenDrawerGestureMode(NappDrawerModule.MODE_NONE);
}
gestureModeBtn.setTitle("Gesture Mode: " + mode);
e.source.toggled = !e.source.toggled;
});
scrollView.add(gestureModeBtn);
function updateSlider(value){
slider.value=value;
slider.fireEvent("touchend", {source:{value:value}});
}
// animation mode
var animationMode = 0;
var animationModeBtn = Ti.UI.createButton({
title:"Animation Mode: NONE",
top:10
});
var aniModeText;
animationModeBtn.addEventListener("click", function(e){
if(animationMode == 3){
animationMode = 0;
} else {
animationMode++;
}
switch(animationMode){
case 0:
drawer.setAnimationMode(NappDrawerModule.ANIMATION_NONE);
updateSlider(0.2);
aniModeText = "NONE";
break;
case 1:
drawer.setAnimationMode(NappDrawerModule.ANIMATION_SLIDEUP);
updateSlider(0);
aniModeText = "SLIDEUP";
break;
case 2:
drawer.setAnimationMode(NappDrawerModule.ANIMATION_ZOOM);
updateSlider(0);
aniModeText = "ZOOM";
break;
case 3:
drawer.setAnimationMode(NappDrawerModule.ANIMATION_SCALE);
updateSlider(0);
aniModeText = "SCALE";
break;
}
animationModeBtn.setTitle("Animation Mode: " + aniModeText);
});
scrollView.add(animationModeBtn);
centerView.add(scrollView);
// CREATE THE MODULE
var NappDrawerModule = require('dk.napp.drawer');
var drawer = NappDrawerModule.createDrawer({
fullscreen:false,
leftWindow: leftMenuView,
centerWindow: centerView,
rightWindow: rightMenuView,
fading: 0.2, // 0-1
parallaxAmount: 0.2, //0-1
shadowWidth:"40dp",
leftDrawerWidth: "200dp",
rightDrawerWidth: "200dp",
animationMode: NappDrawerModule.ANIMATION_NONE,
closeDrawerGestureMode: NappDrawerModule.MODE_MARGIN,
openDrawerGestureMode: NappDrawerModule.MODE_ALL
});
drawer.addEventListener("didChangeOffset", function(e){
//Ti.API.info("didChangeOffset: " + e.offset);
});
drawer.addEventListener("windowDidOpen", function(e){
if(e.window == NappDrawerModule.LEFT_WINDOW) {
Ti.API.info("windowDidOpen - LEFT DRAWER");
} else if (e.window == NappDrawerModule.RIGHT_WINDOW) {
Ti.API.info("windowDidOpen - RIGHT DRAWER");
}
});
drawer.addEventListener("windowDidClose", function(e){
Ti.API.info("windowDidClose");
});
// lets open it
drawer.open();
| vitorebatista/NgMobile | modules/android/dk.napp.drawer/1.0/example/app.js | JavaScript | apache-2.0 | 5,098 |
/*
* 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.
*/
module.exports = angular.module('trafficPortal.private.admin.profiles.list', [])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('trafficPortal.private.admin.profiles.list', {
url: '',
views: {
profilesContent: {
templateUrl: 'common/modules/table/profiles/table.profiles.tpl.html',
controller: 'TableProfilesController',
resolve: {
profiles: function(profileService) {
return profileService.getProfiles();
}
}
}
}
})
;
$urlRouterProvider.otherwise('/');
});
| naamashoresh/incubator-trafficcontrol | traffic_portal/app/src/modules/private/admin/profiles/list/index.js | JavaScript | apache-2.0 | 1,627 |
/**
* Copyright 2016 IBM Corp. 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.
*/
var TJBot = require('tjbot');
var config = require('./config');
var Twitter = require('twitter');
// obtain our credentials from config.js
var credentials = config.credentials;
// obtain user-specific config
var SENTIMENT_KEYWORD = config.sentiment_keyword;
var SENTIMENT_ANALYSIS_FREQUENCY_MSEC = config.sentiment_analysis_frequency_sec * 1000;
// these are the hardware capabilities that TJ needs for this recipe
var hardware = ['led'];
// set up TJBot's configuration
var tjConfig = {
log: {
level: 'verbose'
}
};
// instantiate our TJBot!
var tj = new TJBot(hardware, tjConfig, credentials);
// create the twitter client
var twitter = new Twitter({
consumer_key: credentials.twitter.consumer_key,
consumer_secret: credentials.twitter.consumer_secret,
access_token_key: credentials.twitter.access_token_key,
access_token_secret: credentials.twitter.access_token_secret
});
console.log("I am monitoring twitter for " + SENTIMENT_KEYWORD + ". It may take a few moments to collect enough tweets to analyze.");
// turn the LED off
tj.shine('off');
monitorTwitter();
// ---
var TWEETS = [];
var MAX_TWEETS = 100;
var CONFIDENCE_THRESHOLD = 0.5;
function monitorTwitter() {
// start the pulse to show we are thinking
tj.pulse('white', 1.5, 2.0);
// monitor twitter
twitter.stream('statuses/filter', {
track: SENTIMENT_KEYWORD
}, function(stream) {
stream.on('data', function(event) {
if (event && event.text) {
var tweet = event.text;
// Remove non-ascii characters (e.g chinese, japanese, arabic, etc.) and
// remove hyperlinks
tweet = tweet.replace(/[^\x00-\x7F]/g, "");
tweet = tweet.replace(/(?:https?|ftp):\/\/[\n\S]+/g, "");
// keep a buffer of MAX_TWEETS tweets for sentiment analysis
while (TWEETS.length >= MAX_TWEETS) {
TWEETS.shift();
}
TWEETS.push(tweet);
}
});
stream.on('error', function(error) {
console.log("\nAn error has occurred while connecting to Twitter. Please check your twitter credentials, and also refer to https://dev.twitter.com/overview/api/response-codes for more information on Twitter error codes.\n");
throw error;
});
});
// perform sentiment analysis every N seconds
setInterval(function() {
console.log("Performing sentiment analysis of the tweets");
shineFromTweetSentiment();
}, SENTIMENT_ANALYSIS_FREQUENCY_MSEC);
}
function shineFromTweetSentiment() {
// make sure we have at least 5 tweets to analyze, otherwise it
// is probably not enough.
if (TWEETS.length > 5) {
var text = TWEETS.join(' ');
console.log("Analyzing tone of " + TWEETS.length + " tweets");
tj.analyzeTone(text).then(function(tone) {
tone.document_tone.tone_categories.forEach(function(category) {
if (category.category_id == "emotion_tone") {
// find the emotion with the highest confidence
var max = category.tones.reduce(function(a, b) {
return (a.score > b.score) ? a : b;
});
// make sure we really are confident
if (max.score >= CONFIDENCE_THRESHOLD) {
// stop pulsing at this point, we are going to change color
if (tj.isPulsing()) {
tj.stopPulsing();
}
shineForEmotion(max.tone_id);
}
}
});
});
} else {
console.log("Not enough tweets collected to perform sentiment analysis");
}
}
function shineForEmotion(emotion) {
console.log("Current emotion around " + SENTIMENT_KEYWORD + " is " + emotion);
switch (emotion) {
case 'anger':
tj.shine('red');
break;
case 'joy':
tj.shine('yellow');
break;
case 'fear':
tj.shine('magenta');
break;
case 'disgust':
tj.shine('green');
break;
case 'sadness':
tj.shine('blue');
break;
default:
break;
}
}
| GorillaGorilla/tj-improvements | recipes/sentiment_analysis/sentiment.js | JavaScript | apache-2.0 | 4,941 |
import log from './utils/log';
/*
* @file extends.js
*
* A combination of node inherits and babel's inherits (after transpile).
* Both work the same but node adds `super_` to the subClass
* and Bable adds the superClass as __proto__. Both seem useful.
*/
const _inherits = function (subClass, superClass) {
if (typeof superClass !== 'function' && superClass !== null) {
throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) {
// node
subClass.super_ = superClass;
}
};
/*
* Function for subclassing using the same inheritance that
* videojs uses internally
* ```js
* var Button = videojs.getComponent('Button');
* ```
* ```js
* var MyButton = videojs.extends(Button, {
* constructor: function(player, options) {
* Button.call(this, player, options);
* },
* onClick: function() {
* // doSomething
* }
* });
* ```
*/
const extendsFn = function(superClass, subClassMethods={}) {
let subClass = function() {
superClass.apply(this, arguments);
};
let methods = {};
if (typeof subClassMethods === 'object') {
if (typeof subClassMethods.init === 'function') {
log.warn('Constructor logic via init() is deprecated; please use constructor() instead.');
subClassMethods.constructor = subClassMethods.init;
}
if (subClassMethods.constructor !== Object.prototype.constructor) {
subClass = subClassMethods.constructor;
}
methods = subClassMethods;
} else if (typeof subClassMethods === 'function') {
subClass = subClassMethods;
}
_inherits(subClass, superClass);
// Extend subObj's prototype with functions and other properties from props
for (var name in methods) {
if (methods.hasOwnProperty(name)) {
subClass.prototype[name] = methods[name];
}
}
return subClass;
};
export default extendsFn;
| heff/docs | videojs-src/extends.js | JavaScript | artistic-2.0 | 2,097 |
// Format function for the tooltip values column.
function makeGenerator(tooltip) {
return function tooltipGenerator(d) {
if (d === null) {
return '';
}
var table = d3.select(document.createElement("table"));
var theadEnter = table.selectAll("thead")
.data([d])
.enter().append("thead");
theadEnter.append("tr")
.append("td")
.attr("colspan", 3)
.append("strong")
.classed("x-value", true)
.html(tooltip.headerFormatter()(d.value));
var tbodyEnter = table.selectAll("tbody")
.data([d])
.enter().append("tbody");
var trowEnter = tbodyEnter.selectAll("tr")
.data(function(p) { return p.series})
.enter()
.append("tr")
.classed("highlight", function(p) { return p.highlight});
trowEnter.append("td")
.classed("legend-color-guide",true)
.append("div")
.style("background-color", function(p) { return p.color});
trowEnter.append("td")
.classed("key",true)
.classed("total",function(p) { return !!p.total})
.html(function(p, i) { return tooltip.keyFormatter()(p.key, i)});
trowEnter.append("td")
.classed("value",true)
.html(function(p,i) {
if (d.series.length > 15 && d.value !== p.data.x) {this.parentNode.style.display = "none";}
return tooltip.valueFormatter()(p.value,i,p)
});
trowEnter.filter(function (p,i) { return p.percent !== undefined }).append("td")
.classed("percent", true)
.html(function(p, i) { return "(" + d3.format('%')(p.percent) + ")" });
trowEnter.selectAll("td").each(function(p) {
if (p.highlight) {
var opacityScale = d3.scale.linear().domain([0,1]).range(["#fff",p.color]);
var opacity = 0.6;
d3.select(this)
.style("border-bottom-color", opacityScale(opacity))
.style("border-top-color", opacityScale(opacity))
;
}
});
var html = table.node().outerHTML;
if (d.footer !== undefined)
html += "<div class='footer'>" + d.footer + "</div>";
return html;
};
}
function drawYLine(chart, svg, line) {
var yScale = chart.yAxis.scale();
var yValue = line.value;
var margin = chart.margin();
var width = $(chart.container).width();
var height = $(chart.container).height();
d3.select(svg).append("text")
.attr("x", width - margin.right)
.attr("y", margin.top + yScale(yValue))
.classed("plotline_text", true)
.attr("style", "font-size: 10px")
.text(function(d) { return line.label.text});
d3.select(svg).append("line")
.style("stroke", line.color)
.style("stroke-width", line.width || "2.5px")
.classed("plotline", true)
.on("mouseover", line.events && line.events.mouseover)
.attr("x1", margin.left)
.attr("y1", margin.top + yScale(yValue))
.attr("x2", margin.left + width - margin.right)
.attr("y2", margin.top + yScale(yValue))
.append("text")
.text(function(d) { return line.label&& line.label.text});
}
function drawXLine(chart, svg, line) {
var xScale = chart.xAxis.scale();
var xValue = line.value;
var margin = chart.margin();
var width = $(chart.container).width();
var height = $(chart.container).height();
d3.select(svg).append("text")
.attr("x", margin.left + xScale(xValue) + 5)
.attr("y", margin.top + 10)
.classed("plotline_text", true)
.attr("style", "writing-mode: tb; font-size: 10px")
.text(function(d) { return line.label && line.label.text});
d3.select(svg).append("line")
.style("stroke", line.color)
.style("stroke-width", line.width || "2.5px")
.classed("plotline", true)
.on("mouseover", line.events && line.events.mouseover)
.attr("x1", margin.left + xScale(xValue))
.attr("y1", margin.top)
.attr("x2", margin.left + xScale(xValue))
.attr("y2", margin.top + height - margin.bottom - 100)
.append("text")
.text(function(d) { return line.label && line.label.text});
}
function formatWithSampleCount(d, i, p) {
if (p) {
var samples = p.samples;
if (p.data && p.data.samples) {
samples = p.data.samples;
}
if (p.point && p.point.samples) {
samples = p.point.samples;
}
if (_.isUndefined(samples)) {
return parseInt(d) + " (no samples)";
}
return "<b>" + d + "</b>" + " <i class='light'>(" + samples + " samples)</i>";
}
return d;
}
module.exports = {
tagName: "div",
className: "",
defaults: {
content: "default content"
},
client: function(highcharts_options) {
if (!highcharts_options) {
return
}
console.log("INITIALIZING NVD3 WITH DATA", highcharts_options);
var self = this;
var chartType = highcharts_options.chart.type;
var legend = true;
if (!_.isUndefined(highcharts_options.legend)) {
legend = highcharts_options.legend.enabled;
}
var show_x = true, show_y = true;
var skip_zero_values = false;
var plot_options = highcharts_options.plotOptions || {};
if (highcharts_options.yAxis) {
var show_y_axis = highcharts_options.yAxis.enabled;
if (!_.isUndefined(show_y_axis)) {
show_y = show_y_axis
} else {
if (highcharts_options.yAxis.labels) {
show_y_axis = highcharts_options.yAxis.labels.enabled;
}
if (!_.isUndefined(show_y_axis)) {
show_y = show_y_axis;
}
}
}
_.each(highcharts_options.series, function(s) {
s.values = s.data;
if (!s.key) {
s.key = s.name;
}
// customizations for display!
s.strokeWidth = 2;
if (s.dashStyle) {
s.key += " (compare)";
s.classed = 'dashed';
}
delete s.data;
if (chartType == 'bar' || chartType == 'column') {
var categories = highcharts_options.xAxis.categories;
_.each(s.values, function(v,i) {
v.series = i;
v.x = categories[i];
});
}
});
var customTimeFormat = function(d) {
return innerFormat(new Date(d));
};
var innerFormat = d3.time.format.multi([
["%I:%M", function(d) { return d.getMinutes(); }],
["%I %p", function(d) { return d.getHours(); }],
["%a %d", function(d) { return d.getDay() && d.getDate() != 1; }],
["%b %d", function(d) { return d.getDate() != 1; }],
["%B", function(d) { return d.getMonth(); }],
["%Y", function() { return true; }]
]);
var lightFormat = d3.time.format.multi([
["%a %d %I:%M %p", function() { return true; }]
]);
function bar_chart() {
if (highcharts_options.series.length > 1) {
return nv.models.multiBarChart()
.reduceXTicks(true)
.staggerLabels(true);
}
var show_labels = highcharts_options.series[0].length < 15;
legend = false;
return nv.models.discreteBarChart()
.rotateLabels(70)
.showXAxis(show_labels)
}
var svg = self.$el.find("svg")[0];
// now we need to switch on chart types
nv.addGraph(function() {
var CHARTS = {
'line' : function() {
skip_zero_values = true;
var chart;
if (highcharts_options.chart.zoomType == 'x') {
chart = nv.models.lineWithFocusChart()
.useInteractiveGuideline(true) //We want nice looking tooltips and a guideline!
chart.dispatch.on("renderEnd", _.throttle(function() {
drawPlotLines();
}, 50));
} else {
chart = nv.models.lineChart();
}
chart.xAxis
.showMaxMin(true)
// .rotateLabels(-45) // Want longer labels? Try rotating them to fit easier.
.ticks(10)
.tickPadding(10);
chart.x2Axis
.showMaxMin(true);
return chart;
},
'time' : function() {
var chart = nv.models.lineWithFocusChart()
.useInteractiveGuideline(true) //We want nice looking tooltips and a guideline!
.xScale(d3.time.scale());
console.dir(chart);
chart.dispatch.on("renderEnd", _.throttle(function() {
drawPlotLines();
drawFocusFilters();
}, 50));
chart.interactiveLayer.tooltip.valueFormatter(formatWithSampleCount);
chart.interactiveLayer.tooltip.contentGenerator(
makeGenerator(chart.interactiveLayer.tooltip));
var tsFormat = d3.time.format('%b %-d, %Y %I:%M%p');
chart.interactiveLayer.tooltip.headerFormatter(function (d) { return tsFormat(new Date(d)); });
chart.xAxis
.showMaxMin(false)
// .rotateLabels(-45) // Want longer labels? Try rotating them to fit easier.
.ticks(10)
.tickFormat(customTimeFormat)
.tickPadding(10);
chart.x2Axis
.showMaxMin(false)
.ticks(10)
.tickPadding(10)
.tickFormat(customTimeFormat);
drawFocusFilters();
return chart;
},
'time_scatter' : function() {
legend = false;
var chart = nv.models.scatterChart()
.interactiveUpdateDelay(0)
.pointRange([100, 150])
.color(function(d, i) {
return d.color || d3.scale.category10()[(i||0) % 10] })
.xScale(d3.time.scale())
chart.scatter.dispatch.on("elementClick", function(e) {
var details = "<pre class='sample_details'>" + JSON.stringify(e.point.result, null, 2) + "</pre>";
$C("modal", {title: "Sample details", body: details}, function(modal) {
modal.show();
});
});
var tsFormat = d3.time.format('%b %-d, %Y %I:%M%p');
chart.tooltip.contentGenerator(function (obj) {
var header = $("<div />").append(tsFormat(new Date(obj.value)));
var htmlEl = $("<div />");
htmlEl.append(header);
// TODO: fix to print the proper timestamp
htmlEl.append("<b>" + obj.point.name + "</b>");
return htmlEl.html();
})
chart.xAxis
.tickFormat(customTimeFormat);
chart.xAxis.ticks(5);
chart.pointShape("triangle-down");
return chart;
},
'scatter' : function() {
legend = highcharts_options.legend.enabled;
var chart = nv.models.scatterChart()
.interactiveUpdateDelay(100)
.duration(100)
chart.pointShape("diamond")
.pointRange([45, 50]);
chart.scatter.dispatch.on("elementClick", function(e) {
var details = "<pre class='sample_details'>" + JSON.stringify(e.point.result, null, 2) + "</pre>";
$C("modal", {title: "Sample details", body: details}, function(modal) {
modal.show();
});
});
chart.xAxis.ticks(5);
return chart;
},
'linearea' : function() {
var chart = nv.models.stackedAreaChart()
.useInteractiveGuideline(true);
chart.xAxis
.showMaxMin(false)
// .rotateLabels(-45) // Want longer labels? Try rotating them to fit easier.
.tickPadding(10);
return chart;
},
'area' : function() {
var chart = nv.models.stackedAreaChart()
.xScale(d3.time.scale())
.useInteractiveGuideline(true);
chart.interactiveLayer.tooltip.valueFormatter(formatWithSampleCount)
chart.xAxis
.showMaxMin(false)
// .rotateLabels(-45) // Want longer labels? Try rotating them to fit easier.
.tickFormat(function(d) { return customTimeFormat(new Date(d)); })
.tickPadding(10);
return chart;
},
'bar' : bar_chart,
'column' : bar_chart
}
chartCB = CHARTS[chartType] || CHARTS.line;
var chart = chartCB();
chart.duration(0);
var MAX_LEGEND_ITEMS = 20;
if (highcharts_options.series.length > MAX_LEGEND_ITEMS) {
legend = false;
}
chart
.showLegend(legend) //Show the legend, allowing users to turn on/off line series.
.x(function(d) {
return d.x || d[0] || 0;
})
.y(function(d) {
return d.y || d[1] || 0;
})
if (skip_zero_values) {
chart
.defined(function(d) {
if ((d.y || d[1]) == 0) {
return false;
}
return true;
})
}
chart
.showYAxis(show_y) //Show the y-axis
.showXAxis(show_x) //Show the x-axis
if (show_y) {
chart.yAxis //Chart y-axis settings
.tickFormat(d3.format('.02f'));
}
if (highcharts_options.xAxis && highcharts_options.xAxis.min) {
chart.forceX([highcharts_options.xAxis.min, highcharts_options.xAxis.max]);
chart.xDomain([highcharts_options.xAxis.min, highcharts_options.xAxis.max])
}
var y_axis_min = 0;
var y_axis_max = null;
if (highcharts_options.yAxis) {
if (highcharts_options.yAxis.min) {
y_axis_min = highcharts_options.yAxis.min;
}
if (highcharts_options.yAxis.max) {
y_axis_max = highcharts_options.yAxis.max;
}
}
chart.forceY([y_axis_min, y_axis_max]);
// here chart is your nvd3 model
/* Done setting the chart up? Time to render it!*/
var myData = highcharts_options.series;
var width = 1000;
var height = 500;
if (highcharts_options.width || highcharts_options.chart.width) {width = highcharts_options.width || highcharts_options.chart.width;}
if (highcharts_options.height || highcharts_options.chart.height) {height = highcharts_options.height || highcharts_options.chart.height;}
var container_width = $(self.$el).width();
var container_height = $(self.$el).height();
if (container_width < width) { width = container_width; }
if (container_height < container_height) { height = container_height; }
d3.select(svg)
.style({width: width, height: height});
d3.select(svg)
.datum(myData)
.call(chart);
if (plot_options.series && plot_options.series.marker && plot_options.series.marker.enabled) {
self.$el.addClass("draw-markers");
}
function drawFocusFilters() {
var focused_template = "<span <%= style_str %>'>start:</span> <b><%= start_date_str %></b><br /><span <%= style_str %>>end:</span> <b><%= end_date_str %> </b>";
var date_template_str = "<span style='width: 80px; display: inline-block;'> <%= date.toLocaleDateString()%> </span><span style='width: 80px; display: inline-block;'> <%= date.toLocaleTimeString()%> </span>";
var focusEl = self.$el.find(".focusfilter");
if (!focusEl.length) {
focusEl = $("<div class='focusfilter mtl mll box' ><div class='text lfloat' style='margin-left: 50px'/></div>");
focusEl.css("float", "left");
focusEl.css("font-size", "85%");
var clickEl = $("<a href='#' class='lfloat mll btn btn-primary'>add custom time filters</a>");
clickEl.on("click", function() {
var extents = chart.focus.brush.extent();
var start_date = new Date(extents[0]);
var end_date = new Date(extents[1]);
SF.controller().show_custom_time_inputs();
SF.controller().set_custom_time_inputs(start_date, end_date);
});
focusEl.append(clickEl);
self.$el.append(focusEl);
}
if (chart && chart.focus) {
var extents = chart.focus.brush.extent();
var start_date = new Date(extents[0]);
var end_date = new Date(extents[1]);
var start_date_str = _.template(date_template_str, { date: start_date });
var end_date_str = _.template(date_template_str, {date: end_date });
if (+start_date != +end_date) {
focusEl.find('.text').html(
_.template(focused_template, {
start_date_str: start_date_str,
end_date_str: end_date_str,
style_str: "style='width: 80px; display: inline-block;'" }
)
);
focusEl.show();
} else {
focusEl.hide();
}
}
}
function drawPlotLines() {
self.$el.find(".plotline, .plotline_text").remove();
if (highcharts_options.yAxis && highcharts_options.yAxis.plotLines) {
_.each(highcharts_options.yAxis.plotLines, function(pl) {
drawYLine(chart, svg, pl);
});
}
if (highcharts_options.xAxis && highcharts_options.xAxis.plotLines) {
_.each(highcharts_options.xAxis.plotLines, function(pl) {
drawXLine(chart, svg, pl);
});
}
}
drawPlotLines();
//Update the chart when window resizes.
nv.utils.windowResize(function() {
var container_width = $(self.$el).width();
var container_height = $(self.$el).height();
chart.width(container_width);
chart.height(container_height);
d3.select(svg)
.style({width: container_width, height: container_height});
// Draw new plot lines onto chart
chart.update();
drawPlotLines();
});
return chart;
});
}
};
| logV/snorkel.sf | snorkel/components/nvd3/nvd3.js | JavaScript | bsd-2-clause | 17,595 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: |
The String.prototype.lastIndexOf.length property has the attribute
ReadOnly
es5id: 15.5.4.8_A10
description: >
Checking if varying the String.prototype.lastIndexOf.length
property fails
includes: [propertyHelper.js]
---*/
//////////////////////////////////////////////////////////////////////////////
//CHECK#1
if (!(String.prototype.lastIndexOf.hasOwnProperty('length'))) {
$ERROR('#1: String.prototype.lastIndexOf.hasOwnProperty(\'length\') return true. Actual: ' + String.prototype.lastIndexOf.hasOwnProperty('length'));
}
//
//////////////////////////////////////////////////////////////////////////////
var __obj = String.prototype.lastIndexOf.length;
verifyNotWritable(String.prototype.lastIndexOf, "length", null, function() {
return "shifted";
});
//////////////////////////////////////////////////////////////////////////////
//CHECK#2
if (String.prototype.lastIndexOf.length !== __obj) {
$ERROR('#2: __obj = String.prototype.lastIndexOf.length; String.prototype.lastIndexOf.length = function(){return "shifted";}; String.prototype.lastIndexOf.length === __obj. Actual: ' + String.prototype.lastIndexOf.length);
}
//
//////////////////////////////////////////////////////////////////////////////
| sebastienros/jint | Jint.Tests.Test262/test/built-ins/String/prototype/lastIndexOf/S15.5.4.8_A10.js | JavaScript | bsd-2-clause | 1,378 |
/*
* Copyright (c) 2008-2016, Massachusetts Institute of Technology (MIT)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. Neither the name of the copyright holder 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 HOLDER 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.
*/
define(['ext', 'iweb/CoreModule', 'nics/modules/UserProfileModule'],
function(Ext, Core, UserProfile){
return Ext.define('modules.administration.OrganizationController', {
extend : 'Ext.app.ViewController',
alias: 'controller.organizationcontroller',
orgListTopic: 'nics.admin.orgs',
init: function(){
Core.EventManager.addListener(UserProfile.PROFILE_LOADED, this.loadUserProfile.bind(this));
Core.EventManager.addListener(this.orgListTopic, this.onLoadOrgs.bind(this));
Core.EventManager.addListener("nics.admin.org.clear", this.clearSelection.bind(this));
Core.EventManager.addListener("nics.admin.org.new", this.addNewOrgs.bind(this));
Core.EventManager.addListener("nics.org.orgtype.new", this.addOrgType.bind(this));
Core.EventManager.addListener("nics.org.orgtype.remove", this.removeOrgType.bind(this));
this.mediator = Core.Mediator.getInstance();
},
loadUserProfile: function(evt){
if(UserProfile.isSuperUser()){
this.url = Ext.String.format('{0}/orgs/{1}/all',
Core.Config.getProperty(UserProfile.REST_ENDPOINT),
UserProfile.getWorkspaceId());
this.lookupReference('orgFormPanel').lookupReference('newButton').setHidden(false);
this.lookupReference('orgFormPanel').lookupReference('submitButton').setDisabled(false);
}else{
this.url = Ext.String.format('{0}/orgs/{1}/admin?userId={2}',
Core.Config.getProperty(UserProfile.REST_ENDPOINT),
UserProfile.getWorkspaceId(), UserProfile.getUserId());
}
},
load: function(){
this.mediator.sendRequestMessage(this.url, this.orgListTopic);
},
addNewOrgs: function(evt, response){
if(response){
this.lookupReference('orgGrid').store.loadRawData(response, true);
}
},
onLoadOrgs: function(evt, response){
if(response && response.organizations){
this.lookupReference('orgGrid').store.loadRawData(response.organizations);
}
},
addOrgType: function(evt, response){
var grid = this.lookupReference('orgGrid');
var record = grid.store.getAt(grid.store.find("orgId", response.orgId));
if(record){
record.data.orgTypes.push({ orgtypeid: response.orgTypeId });
}
},
removeOrgType: function(evt, response){
var grid = this.lookupReference('orgGrid');
var record = grid.store.getAt(grid.store.find("orgId", response.orgId));
var match = Ext.Array.findBy(record.data.orgTypes,
function(orgType){
if(orgType.orgtypeid == response.orgTypeId){
return true;
}
});
record.data.orgTypes = Ext.Array.remove(record.data.orgTypes, match);
},
onSelectionChange: function(grid, selected, eOpts) {
if(selected[0]){
var panel = this.lookupReference('orgFormPanel');
var orgForm = panel.lookupReference('orgForm');
orgForm.getViewModel().set(selected[0].data);
panel.controller.updateView();
this.lookupReference('userView').getController().loadUsers(null, selected[0].data.orgId);
this.lookupReference('archiveView').getController().loadIncidents(null, selected[0].data.orgId);
}
},
clearSelection: function(){
this.lookupReference('orgGrid').getSelectionModel().deselectAll();
}
});
});
| tabordasolutions/nics-web | modules/administration/src/main/js/nics/modules/administration/OrganizationController.js | JavaScript | bsd-3-clause | 4,799 |
/**
* Openbiz App Module Frontend Main Package File
*
* APPBUILDER_ALLOW_OVERRIDE = YES // if you have manual modified this file please change APPBUILDER_ALLOW_OVERRIDE value to NO
*/
"use strict";
define(['./router'],
function(router){
return openbiz.Module.extend({
router: router
});
}); | openbiz/openbiz-appbuilder | templates/module/frontend/main-template.js | JavaScript | bsd-3-clause | 307 |
shouldBeTrue("successfullyParsed");
debug('<br><span class="pass">TEST COMPLETE</span>'); | amyvmiwei/chromium | webkit/data/layout_tests/chrome/fast/js/resources/js-test-post.js | JavaScript | bsd-3-clause | 89 |
/**
# Game Controller
Keeps track of keyboard and mouse state globally, so you don't have to.
*/
import b8r from '../source/b8r.js'
import { keycode } from '../source/b8r.keystroke.js'
const buttons = { mouseButtons: [] }
// const _gamepads = b8r.makeArray(navigator.getGamepads()).map(gamepad => gamepad || {});
const axes = {}
const gameController = {
keydown (evt) {
buttons[keycode(evt)] = true
return true
},
keyup (evt) {
buttons[keycode(evt)] = false
return true
},
mousedown (evt) {
buttons.mouseButtons[evt.button] = true
buttons.mouse = !!buttons.mouseButtons[0]
return true
},
mouseup (evt) {
buttons.mouseButtons[evt.button] = false
buttons.mouse = !!buttons.mouseButtons[0]
return true
},
mousemove (evt) {
axes.mouseX = evt.clientX
axes.mouseY = evt.clientY
axes.h = evt.clientX / window.innerWidth * 2 - 1
axes.v = evt.clientY / window.innerHeight * 2 - 1
return true
}
}
/*
window.addEventListener("gamepadconnected", evt => {
console.log('gamepad connected', evt.gamepad); // jshint ignore:line
_gamepads[evt.gamepad.index] = evt.gamepad;
});
window.addEventListener("gamepaddisconnected", evt => {
console.log('gamepad disconnected', evt.gamepad); // jshint ignore:line
_gamepads[evt.gamepad.index] = {};
});
*/
const _fauxGamepad = {
axes: [],
buttons: []
}
const gamepads = () => b8r.makeArray(navigator.getGamepads()).map(gamepad => gamepad || _fauxGamepad)
b8r.register('game-controller', gameController)
b8r.forEachKey(gameController, (_, eventType) => {
b8r.onAny(eventType, `game-controller.${eventType}`)
})
export { buttons, axes, gamepads }
| tonioloewald/Bind-O-Matic.js | lib/game-controller.js | JavaScript | bsd-3-clause | 1,678 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
cr.define('options', function() {
var OptionsPage = options.OptionsPage;
const ArrayDataModel = cr.ui.ArrayDataModel;
/////////////////////////////////////////////////////////////////////////////
// InternetOptions class:
/**
* Encapsulated handling of ChromeOS internet options page.
* @constructor
*/
function InternetOptions() {
OptionsPage.call(this, 'internet', templateData.internetPageTabTitle,
'internetPage');
}
cr.addSingletonGetter(InternetOptions);
// Inherit InternetOptions from OptionsPage.
InternetOptions.prototype = {
__proto__: OptionsPage.prototype,
/**
* Initializes InternetOptions page.
* Calls base class implementation to starts preference initialization.
*/
initializePage: function() {
OptionsPage.prototype.initializePage.call(this);
if (templateData.accessLocked) {
this.accesslocked = true;
}
options.internet.NetworkElement.decorate($('wired-list'));
$('wired-list').load(templateData.wiredList);
options.internet.NetworkElement.decorate($('wireless-list'));
$('wireless-list').load(templateData.wirelessList);
options.internet.NetworkElement.decorate($('vpn-list'));
$('vpn-list').load(templateData.vpnList);
options.internet.NetworkElement.decorate($('remembered-list'));
$('remembered-list').load(templateData.rememberedList);
this.updatePolicyIndicatorVisibility_();
options.internet.CellularPlanElement.decorate($('planList'));
$('wired-section').hidden = (templateData.wiredList.length == 0);
$('wireless-section').hidden = (templateData.wirelessList.length == 0);
$('vpn-section').hidden = (templateData.vpnList.length == 0);
$('remembered-section').hidden =
(templateData.rememberedList.length == 0);
InternetOptions.setupAttributes(templateData);
$('detailsInternetDismiss').addEventListener('click', function(event) {
InternetOptions.setDetails();
});
$('detailsInternetLogin').addEventListener('click', function(event) {
InternetOptions.setDetails();
InternetOptions.loginFromDetails();
});
$('detailsInternetDisconnect').addEventListener('click', function(event) {
InternetOptions.setDetails();
InternetOptions.disconnectNetwork();
});
$('activateDetails').addEventListener('click', function(event) {
InternetOptions.activateFromDetails();
});
$('enable-wifi').addEventListener('click', function(event) {
event.target.disabled = true;
chrome.send('enableWifi');
});
$('disable-wifi').addEventListener('click', function(event) {
event.target.disabled = true;
chrome.send('disableWifi');
});
$('enable-cellular').addEventListener('click', function(event) {
event.target.disabled = true;
chrome.send('enableCellular');
});
$('disable-cellular').addEventListener('click', function(event) {
event.target.disabled = true;
chrome.send('disableCellular');
});
$('change-proxy-button').addEventListener('click', function(event) {
OptionsPage.closeOverlay();
OptionsPage.showPageByName('proxy', false);
chrome.send('coreOptionsUserMetricsAction',
['Options_ShowProxySettings']);
});
$('buyplanDetails').addEventListener('click', function(event) {
chrome.send('buyDataPlan');
OptionsPage.closeOverlay();
});
$('viewAccountDetails').addEventListener('click', function(event) {
chrome.send('showMorePlanInfo');
OptionsPage.closeOverlay();
});
$('cellularApnUseDefault').addEventListener('click', function(event) {
var data = $('connectionState').data;
var apnSelector = $('selectApn');
if (data.userApnIndex != -1) {
apnSelector.remove(data.userApnIndex);
data.userApnIndex = -1;
}
if (data.providerApnList.value.length > 0) {
var iApn = 0;
data.apn.apn = data.providerApnList.value[iApn].apn;
data.apn.username = data.providerApnList.value[iApn].username;
data.apn.password = data.providerApnList.value[iApn].password;
chrome.send('setApn', [String(data.servicePath),
String(data.apn.apn),
String(data.apn.username),
String(data.apn.password)]);
apnSelector.selectedIndex = iApn;
data.selectedApn = iApn;
} else {
data.apn.apn = '';
data.apn.username = '';
data.apn.password = '';
apnSelector.selectedIndex = -1;
data.selectedApn = -1;
}
InternetOptions.prototype.updateHidden_(
cr.doc.querySelectorAll('.apn-list-view'),
false);
InternetOptions.prototype.updateHidden_(
cr.doc.querySelectorAll('.apn-details-view'),
true);
});
$('cellularApnSet').addEventListener('click', function(event) {
if ($('cellularApn').value == '')
return;
var data = $('connectionState').data;
var apnSelector = $('selectApn');
data.apn.apn = String($('cellularApn').value);
data.apn.username = String($('cellularApnUsername').value);
data.apn.password = String($('cellularApnPassword').value);
chrome.send('setApn', [String(data.servicePath),
String(data.apn.apn),
String(data.apn.username),
String(data.apn.password)]);
if (data.userApnIndex != -1) {
apnSelector.remove(data.userApnIndex);
data.userApnIndex = -1;
}
var option = document.createElement('option');
option.textContent = data.apn.apn;
option.value = -1;
option.selected = true;
apnSelector.add(option, apnSelector[apnSelector.length - 1]);
data.userApnIndex = apnSelector.length - 2
data.selectedApn = data.userApnIndex;
InternetOptions.prototype.updateHidden_(
cr.doc.querySelectorAll('.apn-list-view'),
false);
InternetOptions.prototype.updateHidden_(
cr.doc.querySelectorAll('.apn-details-view'),
true);
});
$('cellularApnCancel').addEventListener('click', function(event) {
$('selectApn').selectedIndex = $('connectionState').data.selectedApn;
InternetOptions.prototype.updateHidden_(
cr.doc.querySelectorAll('.apn-list-view'),
false);
InternetOptions.prototype.updateHidden_(
cr.doc.querySelectorAll('.apn-details-view'),
true);
});
$('selectApn').addEventListener('change', function(event) {
var data = $('connectionState').data;
var apnSelector = $('selectApn');
if (apnSelector[apnSelector.selectedIndex].value != -1) {
var apnList = data.providerApnList.value;
chrome.send('setApn', [String(data.servicePath),
String(apnList[apnSelector.selectedIndex].apn),
String(apnList[apnSelector.selectedIndex].username),
String(apnList[apnSelector.selectedIndex].password)
]);
data.selectedApn = apnSelector.selectedIndex;
} else if (apnSelector.selectedIndex == data.userApnIndex) {
chrome.send('setApn', [String(data.servicePath),
String(data.apn.apn),
String(data.apn.username),
String(data.apn.password)]);
data.selectedApn = apnSelector.selectedIndex;
} else {
$('cellularApn').value = data.apn.apn;
$('cellularApnUsername').value = data.apn.username;
$('cellularApnPassword').value = data.apn.password;
InternetOptions.prototype.updateHidden_(
cr.doc.querySelectorAll('.apn-list-view'),
true);
InternetOptions.prototype.updateHidden_(
cr.doc.querySelectorAll('.apn-details-view'),
false);
}
});
$('sim-card-lock-enabled').addEventListener('click', function(event) {
var newValue = $('sim-card-lock-enabled').checked;
// Leave value as is because user needs to enter PIN code first.
// When PIN will be entered and value changed,
// we'll update UI to reflect that change.
$('sim-card-lock-enabled').checked = !newValue;
chrome.send('setSimCardLock', [newValue]);
});
$('change-pin').addEventListener('click', function(event) {
chrome.send('changePin');
});
this.showNetworkDetails_();
},
showNetworkDetails_: function() {
var params = parseQueryParams(window.location);
var servicePath = params.servicePath;
var networkType = params.networkType;
if (!servicePath || !servicePath.length ||
!networkType || !networkType.length)
return;
var networkName = params.networkName;
if (networkName)
options.ProxyOptions.getInstance().setNetworkName(networkName);
chrome.send('buttonClickCallback',
[networkType, servicePath, "options"]);
},
updateHidden_: function(elements, hidden) {
for (var i = 0, el; el = elements[i]; i++) {
el.hidden = hidden;
}
},
/**
* Update internet page controls.
* @private
*/
updateControls_: function() {
accesslocked = this.accesslocked;
$('locked-network-banner').hidden = !accesslocked;
$('wireless-buttons').hidden = accesslocked;
$('wired-section').hidden = accesslocked;
$('wireless-section').hidden = accesslocked;
$('vpn-section').hidden = accesslocked;
$('remembered-section').hidden = accesslocked;
// Don't change hidden attribute on OptionsPage divs directly because it
// is used in supporting infrastructure now.
if (accesslocked && DetailsInternetPage.getInstance().visible)
this.closeOverlay();
},
/**
* Updates the policy indicator visibility. Space is only allocated for the
* policy indicators if there is at least one visible.
* @private
*/
updatePolicyIndicatorVisibility_: function() {
var page = $('internetPage');
if (page.querySelectorAll(
'.network-item > .controlled-setting-indicator[controlled-by]')
.length) {
page.classList.remove('hide-indicators');
} else {
page.classList.add('hide-indicators');
}
}
};
/**
* Whether access to this page is locked.
* @type {boolean}
*/
cr.defineProperty(InternetOptions, 'accesslocked', cr.PropertyKind.JS,
InternetOptions.prototype.updateControls_);
InternetOptions.loginFromDetails = function () {
var data = $('connectionState').data;
var servicePath = data.servicePath;
chrome.send('buttonClickCallback', [String(data.type),
servicePath,
'connect']);
OptionsPage.closeOverlay();
};
InternetOptions.disconnectNetwork = function () {
var data = $('connectionState').data;
var servicePath = data.servicePath;
chrome.send('buttonClickCallback', [String(data.type),
servicePath,
'disconnect']);
OptionsPage.closeOverlay();
};
InternetOptions.activateFromDetails = function () {
var data = $('connectionState').data;
var servicePath = data.servicePath;
if (data.type == options.internet.Constants.TYPE_CELLULAR) {
chrome.send('buttonClickCallback', [String(data.type),
String(servicePath),
'activate']);
}
OptionsPage.closeOverlay();
};
InternetOptions.setDetails = function () {
var data = $('connectionState').data;
var servicePath = data.servicePath;
if (data.type == options.internet.Constants.TYPE_WIFI) {
chrome.send('setPreferNetwork',
[String(servicePath),
$('preferNetworkWifi').checked ? "true" : "false"]);
chrome.send('setAutoConnect',
[String(servicePath),
$('autoConnectNetworkWifi').checked ? "true" : "false"]);
} else if (data.type == options.internet.Constants.TYPE_CELLULAR) {
chrome.send('setAutoConnect',
[String(servicePath),
$('autoConnectNetworkCellular').checked ? "true" : "false"]);
}
var ipConfigList = $('ipConfigList');
chrome.send('setIPConfig',[String(servicePath),
$('ipTypeDHCP').checked ? "true" : "false",
ipConfigList.dataModel.item(0).value,
ipConfigList.dataModel.item(1).value,
ipConfigList.dataModel.item(2).value,
ipConfigList.dataModel.item(3).value]);
OptionsPage.closeOverlay();
};
InternetOptions.setupAttributes = function(data) {
var buttons = $('wireless-buttons');
if (data.wifiEnabled) {
$('disable-wifi').disabled = data.wifiBusy;
$('disable-wifi').hidden = false;
$('enable-wifi').hidden = true;
} else {
$('enable-wifi').disabled = data.wifiBusy;
$('enable-wifi').hidden = false;
$('disable-wifi').hidden = true;
}
if (data.cellularAvailable) {
if (data.cellularEnabled) {
$('disable-cellular').disabled = data.cellularBusy;
$('disable-cellular').hidden = false;
$('enable-cellular').hidden = true;
} else {
$('enable-cellular').disabled = data.cellularBusy;
$('enable-cellular').hidden = false;
$('disable-cellular').hidden = true;
}
if (!AccountsOptions.currentUserIsOwner())
$('internet-owner-only-warning').hidden = false;
$('data-roaming').hidden = false;
} else {
$('enable-cellular').hidden = true;
$('disable-cellular').hidden = true;
$('data-roaming').hidden = true;
}
};
//
//Chrome callbacks
//
InternetOptions.refreshNetworkData = function (data) {
var self = InternetOptions.getInstance();
if (data.accessLocked) {
self.accesslocked = true;
return;
}
self.accesslocked = false;
$('wired-list').load(data.wiredList);
$('wireless-list').load(data.wirelessList);
$('vpn-list').load(data.vpnList);
$('remembered-list').load(data.rememberedList);
self.updatePolicyIndicatorVisibility_();
$('wired-section').hidden = (data.wiredList.length == 0);
$('wireless-section').hidden = (data.wirelessList.length == 0);
$('vpn-section').hidden = (data.vpnList.length == 0);
InternetOptions.setupAttributes(data);
$('remembered-section').hidden = (data.rememberedList.length == 0);
};
// TODO(xiyuan): This function seems belonging to DetailsInternetPage.
InternetOptions.updateCellularPlans = function (data) {
var detailsPage = DetailsInternetPage.getInstance();
detailsPage.cellplanloading = false;
if (data.plans && data.plans.length) {
detailsPage.nocellplan = false
detailsPage.hascellplan = true;
$('planList').load(data.plans);
} else {
detailsPage.nocellplan = true;
detailsPage.hascellplan = false;
}
detailsPage.hasactiveplan = !data.needsPlan;
detailsPage.activated = data.activated;
if (!data.activated)
$('detailsInternetLogin').hidden = true;
$('buyplanDetails').hidden = !data.showBuyButton;
$('activateDetails').hidden = !data.showActivateButton;
$('viewAccountDetails').hidden = !data.showViewAccountButton;
};
InternetOptions.updateSecurityTab = function(requirePin) {
$('sim-card-lock-enabled').checked = requirePin;
$('change-pin').hidden = !requirePin;
};
InternetOptions.showDetailedInfo = function (data) {
var detailsPage = DetailsInternetPage.getInstance();
// TODO(chocobo): Is this hack to cache the data here reasonable?
$('connectionState').data = data;
$('buyplanDetails').hidden = true;
$('activateDetails').hidden = true;
$('viewAccountDetails').hidden = true;
$('detailsInternetLogin').hidden = data.connected;
if (data.type == options.internet.Constants.TYPE_ETHERNET)
$('detailsInternetDisconnect').hidden = true;
else
$('detailsInternetDisconnect').hidden = !data.connected;
detailsPage.deviceConnected = data.deviceConnected;
detailsPage.connecting = data.connecting;
detailsPage.connected = data.connected;
if (data.connected) {
$('inetTitle').textContent = localStrings.getString('inetStatus');
} else {
$('inetTitle').textContent = localStrings.getString('inetConnect');
}
$('connectionState').textContent = data.connectionState;
var inetAddress = '';
var inetSubnetAddress = '';
var inetGateway = '';
var inetDns = '';
$('ipTypeDHCP').checked = true;
if (data.ipconfigStatic.value) {
inetAddress = data.ipconfigStatic.value.address;
inetSubnetAddress = data.ipconfigStatic.value.subnetAddress;
inetGateway = data.ipconfigStatic.value.gateway;
inetDns = data.ipconfigStatic.value.dns;
$('ipTypeStatic').checked = true;
} else if (data.ipconfigDHCP.value) {
inetAddress = data.ipconfigDHCP.value.address;
inetSubnetAddress = data.ipconfigDHCP.value.subnetAddress;
inetGateway = data.ipconfigDHCP.value.gateway;
inetDns = data.ipconfigDHCP.value.dns;
}
// Hide the dhcp/static radio if needed.
$('ipTypeDHCPDiv').hidden = !data.showStaticIPConfig;
$('ipTypeStaticDiv').hidden = !data.showStaticIPConfig;
// Hide change-proxy-button and change-proxy-section if not showing proxy.
$('change-proxy-button').hidden = !data.showProxy;
$('change-proxy-section').hidden = !data.showProxy;
var ipConfigList = $('ipConfigList');
ipConfigList.disabled =
$('ipTypeDHCP').checked || data.ipconfigStatic.controlledBy ||
!data.showStaticIPConfig;
options.internet.IPConfigList.decorate(ipConfigList);
ipConfigList.autoExpands = true;
var model = new ArrayDataModel([]);
model.push({
'property': 'inetAddress',
'name': localStrings.getString('inetAddress'),
'value': inetAddress,
});
model.push({
'property': 'inetSubnetAddress',
'name': localStrings.getString('inetSubnetAddress'),
'value': inetSubnetAddress,
});
model.push({
'property': 'inetGateway',
'name': localStrings.getString('inetGateway'),
'value': inetGateway,
});
model.push({
'property': 'inetDns',
'name': localStrings.getString('inetDns'),
'value': inetDns,
});
ipConfigList.dataModel = model;
$('ipTypeDHCP').addEventListener('click', function(event) {
// disable ipConfigList and switch back to dhcp values (if any)
if (data.ipconfigDHCP.value) {
var config = data.ipconfigDHCP.value;
ipConfigList.dataModel.item(0).value = config.address;
ipConfigList.dataModel.item(1).value = config.subnetAddress;
ipConfigList.dataModel.item(2).value = config.gateway;
ipConfigList.dataModel.item(3).value = config.dns;
}
ipConfigList.dataModel.updateIndex(0);
ipConfigList.dataModel.updateIndex(1);
ipConfigList.dataModel.updateIndex(2);
ipConfigList.dataModel.updateIndex(3);
// Unselect all so we don't keep the currently selected field editable.
ipConfigList.selectionModel.unselectAll();
ipConfigList.disabled = true;
});
$('ipTypeStatic').addEventListener('click', function(event) {
// enable ipConfigList
ipConfigList.disabled = false;
ipConfigList.focus();
ipConfigList.selectionModel.selectedIndex = 0;
});
if (data.hardwareAddress) {
$('hardwareAddress').textContent = data.hardwareAddress;
$('hardwareAddressRow').style.display = 'table-row';
} else {
// This is most likely a device without a hardware address.
$('hardwareAddressRow').style.display = 'none';
}
if (data.type == options.internet.Constants.TYPE_WIFI) {
OptionsPage.showTab($('wifiNetworkNavTab'));
detailsPage.wireless = true;
detailsPage.vpn = false;
detailsPage.ethernet = false;
detailsPage.cellular = false;
detailsPage.gsm = false;
detailsPage.shared = data.shared;
$('inetSsid').textContent = data.ssid;
detailsPage.showPreferred = data.showPreferred;
$('preferNetworkWifi').checked = data.preferred.value;
$('preferNetworkWifi').disabled = !data.remembered;
$('autoConnectNetworkWifi').checked = data.autoConnect.value;
$('autoConnectNetworkWifi').disabled = !data.remembered;
detailsPage.password = data.encrypted;
} else if(data.type == options.internet.Constants.TYPE_CELLULAR) {
if (!data.gsm)
OptionsPage.showTab($('cellularPlanNavTab'));
else
OptionsPage.showTab($('cellularConnNavTab'));
detailsPage.ethernet = false;
detailsPage.wireless = false;
detailsPage.vpn = false;
detailsPage.cellular = true;
if (data.carrierUrl) {
var a = $('carrierUrl');
if (!a) {
a = document.createElement('a');
$('serviceName').appendChild(a);
a.id = 'carrierUrl';
a.target = "_blank";
}
a.href = data.carrierUrl;
a.textContent = data.serviceName;
} else {
$('serviceName').textContent = data.serviceName;
}
$('networkTechnology').textContent = data.networkTechnology;
$('activationState').textContent = data.activationState;
$('roamingState').textContent = data.roamingState;
$('restrictedPool').textContent = data.restrictedPool;
$('errorState').textContent = data.errorState;
$('manufacturer').textContent = data.manufacturer;
$('modelId').textContent = data.modelId;
$('firmwareRevision').textContent = data.firmwareRevision;
$('hardwareRevision').textContent = data.hardwareRevision;
$('prlVersion').textContent = data.prlVersion;
$('meid').textContent = data.meid;
$('imei').textContent = data.imei;
$('mdn').textContent = data.mdn;
$('esn').textContent = data.esn;
$('min').textContent = data.min;
detailsPage.gsm = data.gsm;
if (data.gsm) {
$('operatorName').textContent = data.operatorName;
$('operatorCode').textContent = data.operatorCode;
$('imsi').textContent = data.imsi;
var apnSelector = $('selectApn');
// Clear APN lists, keep only last element that "other".
while (apnSelector.length != 1)
apnSelector.remove(0);
var otherOption = apnSelector[0];
data.selectedApn = -1;
data.userApnIndex = -1;
var apnList = data.providerApnList.value;
for (var i = 0; i < apnList.length; i++) {
var option = document.createElement('option');
var name = apnList[i].localizedName;
if (name == '' && apnList[i].name != '')
name = apnList[i].name;
if (name == '')
name = apnList[i].apn;
else
name = name + ' (' + apnList[i].apn + ')';
option.textContent = name;
option.value = i;
if ((data.apn.apn == apnList[i].apn &&
data.apn.username == apnList[i].username &&
data.apn.password == apnList[i].password) ||
(data.apn.apn == '' &&
data.lastGoodApn.apn == apnList[i].apn &&
data.lastGoodApn.username == apnList[i].username &&
data.lastGoodApn.password == apnList[i].password)) {
data.selectedApn = i;
}
// Insert new option before "other" option.
apnSelector.add(option, otherOption);
}
if (data.selectedApn == -1 && data.apn.apn != '') {
var option = document.createElement('option');
option.textContent = data.apn.apn;
option.value = -1;
apnSelector.add(option, otherOption);
data.selectedApn = apnSelector.length - 2;
data.userApnIndex = data.selectedApn;
}
apnSelector.selectedIndex = data.selectedApn;
InternetOptions.prototype.updateHidden_(
cr.doc.querySelectorAll('.apn-list-view'),
false);
InternetOptions.prototype.updateHidden_(
cr.doc.querySelectorAll('.apn-details-view'),
true);
InternetOptions.updateSecurityTab(data.simCardLockEnabled.value);
}
$('autoConnectNetworkCellular').checked = data.autoConnect.value;
$('autoConnectNetworkCellular').disabled = false;
$('buyplanDetails').hidden = !data.showBuyButton;
$('viewAccountDetails').hidden = !data.showViewAccountButton;
$('activateDetails').hidden = !data.showActivateButton;
if (data.showActivateButton) {
$('detailsInternetLogin').hidden = true;
}
detailsPage.hascellplan = false;
if (data.connected) {
detailsPage.nocellplan = false;
detailsPage.cellplanloading = true;
chrome.send('refreshCellularPlan', [data.servicePath])
} else {
detailsPage.nocellplan = true;
detailsPage.cellplanloading = false;
}
} else if (data.type == options.internet.Constants.TYPE_VPN) {
OptionsPage.showTab($('vpnNavTab'));
detailsPage.wireless = false;
detailsPage.vpn = true;
detailsPage.ethernet = false;
detailsPage.cellular = false;
detailsPage.gsm = false;
$('inetServiceName').textContent = data.service_name;
$('inetServerHostname').textContent = data.server_hostname;
$('inetProviderType').textContent = data.provider_type;
$('inetUsername').textContent = data.username;
} else {
OptionsPage.showTab($('internetNavTab'));
detailsPage.ethernet = true;
detailsPage.wireless = false;
detailsPage.vpn = false;
detailsPage.cellular = false;
detailsPage.gsm = false;
}
detailsPage.initializeControlledSettingIndicators(data)
// Don't show page name in address bar and in history to prevent people
// navigate here by hand and solve issue with page session restore.
OptionsPage.showPageByName('detailsInternetPage', false);
};
InternetOptions.invalidNetworkSettings = function () {
alert(localStrings.getString('invalidNetworkSettings'));
};
// Export
return {
InternetOptions: InternetOptions
};
});
| aYukiSekiguchi/ACCESS-Chromium | chrome/browser/resources/options/chromeos/internet_options.js | JavaScript | bsd-3-clause | 27,029 |
/**
* The Alert Component
*
* @module aui-alert
*/
var getClassName = A.getClassName,
CSS_CLOSE = getClassName('close'),
CSS_INFO = getClassName('alert', 'info'),
CSS_DISMISSABLE = getClassName('alert', 'dismissable');
/**
* A base class for Alert.
*
* Check the [live demo](http://alloyui.com/examples/alert/).
*
* @class A.Alert
* @extends Widget
* @uses A.WidgetCssClass, A.WidgetTransition
* @param {Object} config Object literal specifying widget configuration
* properties.
* @constructor
*/
A.Alert = A.Base.create('alert', A.Widget, [
A.WidgetCssClass,
A.WidgetStdMod,
A.WidgetTransition
], {
CONTENT_TEMPLATE: null,
_eventHandle: null,
/**
* Renders the Alert component instance. Lifecycle.
*
* @method renderUI
* @protected
*/
renderUI: function() {
this._uiSetCloseable(this.get('closeable'));
},
/**
* Binds the events on the Alert UI. Lifecycle.
*
* @method bindUI
* @protected
*/
bindUI: function() {
this.on('closeableChange', this._onCloseableChange);
this.after('visibleChange', this._afterVisibleChange);
},
/**
* Fires after visibility changes.
*
* @method _afterVisibleChange
* @param {EventFacade} event
* @protected
*/
_afterVisibleChange: function(event) {
if (!event.newVal && this.get('destroyOnHide')) {
A.soon(A.bind('destroy', this));
}
},
/**
* Handles close icon click event.
*
* @method _onClickBoundingBox
* @param {EventFacade} event
* @protected
*/
_onClickBoundingBox: function(event) {
if (event.target.test('.' + CSS_CLOSE)) {
this.hide();
}
},
/**
* Handles `closeable` events.
*
* @method _onCloseableChange
* @param {EventFacade} event
* @protected
*/
_onCloseableChange: function(event) {
this._uiSetCloseable(event.newVal);
},
/**
* Sets `closeable` UI.
*
* @method _uiSetCloseable
* @protected
*/
_uiSetCloseable: function(val) {
var boundingBox = this.get('boundingBox'),
closeableNode = this.get('closeableNode');
boundingBox.toggleClass(CSS_DISMISSABLE, val);
closeableNode.remove();
if (this._eventHandle) {
this._eventHandle.detach();
}
if (val) {
boundingBox.insert(closeableNode, 0);
this._eventHandle = boundingBox.on('click', this._onClickBoundingBox, this);
}
}
}, {
/**
* Static property used to define the default attribute
* configuration for the Alert.
*
* @property ATTRS
* @type Object
* @static
*/
ATTRS: {
/**
* Whether the alert can be closed.
*
* @attribute closeable
* @default true
* @type {Boolean}
*/
closeable: {
validator: A.Lang.isBoolean,
value: true
},
/**
* Node used to generate a close button.
*
* @attribute closeableNode
* @default `<button type="button" class="close">×</button>`
* @type {Node}
*/
closeableNode: {
valueFn: function() {
return A.Node.create('<button type="button" class="close">×</button>');
}
},
/**
* CSS class for alert.
*
* @attribute popoverCssClass
* @default A.getClassName('alert-info')
* @type {String}
*/
cssClass: {
value: CSS_INFO
},
/**
* Determine if Alert should be destroyed when hidden.
*
* @attribute destroyOnHide
* @default false
* @type Boolean
*/
destroyOnHide: {
validator: A.Lang.isBoolean,
value: false
}
},
/**
* Static property provides a string to identify the CSS prefix.
*
* @property CSS_PREFIX
* @type {String}
* @static
*/
CSS_PREFIX: 'alert',
/**
* Object hash, defining how closeableNode value have to be parsed from markup.
*
* @property HTML_PARSER
* @type Object
* @static
*/
HTML_PARSER: {
closeableNode: '.' + CSS_CLOSE
}
});
| adorjan/alloy-ui | src/aui-alert/js/aui-alert.js | JavaScript | bsd-3-clause | 4,409 |
(function() {
var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
templates['detail'] = template({"compiler":[8,">= 4.3.0"],"main":function(container,depth0,helpers,partials,data) {
var stack1, alias1=container.lambda, alias2=container.escapeExpression, alias3=depth0 != null ? depth0 : (container.nullContext || {}), alias4=container.hooks.helperMissing, lookupProperty = container.lookupProperty || function(parent, propertyName) {
if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {
return parent[propertyName];
}
return undefined
};
return "<table class=\"table table-bordered table-striped \">\n <tr><td class=\"col-xs-2\">Facility Name</td><td><strong>"
+ alias2(alias1(((stack1 = (depth0 != null ? lookupProperty(depth0,"Details") : depth0)) != null ? lookupProperty(stack1,"operation_name") : stack1), depth0))
+ "<strong></td></tr>\n <tr><td class=\"col-xs-2\">Facility Address</td><td><a title=\"Opens in Google Maps\" target=\"_blank\" href=\"https://www.google.com/maps/place/"
+ ((stack1 = (lookupProperty(helpers,"makeAddressString")||(depth0 && lookupProperty(depth0,"makeAddressString"))||alias4).call(alias3,(depth0 != null ? lookupProperty(depth0,"Details") : depth0),{"name":"makeAddressString","hash":{},"data":data,"loc":{"start":{"line":3,"column":140},"end":{"line":3,"column":171}}})) != null ? stack1 : "")
+ "\">"
+ ((stack1 = (lookupProperty(helpers,"makeAddressString")||(depth0 && lookupProperty(depth0,"makeAddressString"))||alias4).call(alias3,(depth0 != null ? lookupProperty(depth0,"Details") : depth0),{"name":"makeAddressString","hash":{},"data":data,"loc":{"start":{"line":3,"column":173},"end":{"line":3,"column":204}}})) != null ? stack1 : "")
+ "</a></td></tr>\n <tr><td class=\"col-xs-2\">Inspection Date</td><td>"
+ ((stack1 = (lookupProperty(helpers,"formatDate")||(depth0 && lookupProperty(depth0,"formatDate"))||alias4).call(alias3,((stack1 = (depth0 != null ? lookupProperty(depth0,"Details") : depth0)) != null ? lookupProperty(stack1,"date") : stack1),{"name":"formatDate","hash":{},"data":data,"loc":{"start":{"line":4,"column":51},"end":{"line":4,"column":80}}})) != null ? stack1 : "")
+ "</td></tr>\n <tr><td class=\"col-xs-2\">Critical violations</td><td>"
+ alias2(alias1(((stack1 = (depth0 != null ? lookupProperty(depth0,"Details") : depth0)) != null ? lookupProperty(stack1,"total_critical_violations") : stack1), depth0))
+ "</td></tr>\n <tr><td class=\"col-xs-2\">Critical & not corrected</td><td>"
+ alias2(alias1(((stack1 = (depth0 != null ? lookupProperty(depth0,"Details") : depth0)) != null ? lookupProperty(stack1,"total_crit_not_corrected") : stack1), depth0))
+ "</td></tr>\n <tr><td class=\"col-xs-2\">Inspection Details</td><td>"
+ ((stack1 = (lookupProperty(helpers,"highlightCritical")||(depth0 && lookupProperty(depth0,"highlightCritical"))||alias4).call(alias3,((stack1 = (depth0 != null ? lookupProperty(depth0,"Details") : depth0)) != null ? lookupProperty(stack1,"violations") : stack1),{"name":"highlightCritical","hash":{},"data":data,"loc":{"start":{"line":7,"column":54},"end":{"line":7,"column":96}}})) != null ? stack1 : "")
+ "</td></tr>\n</table>";
},"useData":true});
templates['list'] = template({"1":function(container,depth0,helpers,partials,data) {
var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName) {
if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {
return parent[propertyName];
}
return undefined
};
return "<h4>"
+ container.escapeExpression(container.lambda(((stack1 = (depth0 != null ? lookupProperty(depth0,"Places") : depth0)) != null ? lookupProperty(stack1,"title") : stack1), depth0))
+ "</h4>\n<table class=\"table table-striped table-bordered table-hover\">\n<thead>\n <tr>\n <th>Name</th>\n <th>Address</th>\n <th>City</th>\n <th>Date</th>\n </tr>\n</thead>\n<tbody>\n"
+ ((stack1 = lookupProperty(helpers,"each").call(depth0 != null ? depth0 : (container.nullContext || {}),((stack1 = (depth0 != null ? lookupProperty(depth0,"Places") : depth0)) != null ? lookupProperty(stack1,"places") : stack1),{"name":"each","hash":{},"fn":container.program(2, data, 0),"inverse":container.noop,"data":data,"loc":{"start":{"line":13,"column":1},"end":{"line":20,"column":10}}})) != null ? stack1 : "")
+ " </tbody>\n</table>\n";
},"2":function(container,depth0,helpers,partials,data) {
var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=container.hooks.helperMissing, alias3="function", alias4=container.escapeExpression, lookupProperty = container.lookupProperty || function(parent, propertyName) {
if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {
return parent[propertyName];
}
return undefined
};
return " <tr>\n <td class=\"col-xs-3\"><a class=\"details\" href=\""
+ ((stack1 = ((helper = (helper = lookupProperty(helpers,"getBaseUrl") || (depth0 != null ? lookupProperty(depth0,"getBaseUrl") : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"getBaseUrl","hash":{},"data":data,"loc":{"start":{"line":15,"column":49},"end":{"line":15,"column":65}}}) : helper))) != null ? stack1 : "")
+ "?id="
+ alias4(((helper = (helper = lookupProperty(helpers,"nys_health_operation_id") || (depth0 != null ? lookupProperty(depth0,"nys_health_operation_id") : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"nys_health_operation_id","hash":{},"data":data,"loc":{"start":{"line":15,"column":69},"end":{"line":15,"column":96}}}) : helper)))
+ "\">"
+ alias4(((helper = (helper = lookupProperty(helpers,"operation_name") || (depth0 != null ? lookupProperty(depth0,"operation_name") : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"operation_name","hash":{},"data":data,"loc":{"start":{"line":15,"column":98},"end":{"line":15,"column":116}}}) : helper)))
+ "</td>\n <td class=\"col-xs-3\">"
+ ((stack1 = (lookupProperty(helpers,"toTitleCase")||(depth0 && lookupProperty(depth0,"toTitleCase"))||alias2).call(alias1,(depth0 != null ? lookupProperty(depth0,"facility_address") : depth0),{"name":"toTitleCase","hash":{},"data":data,"loc":{"start":{"line":16,"column":24},"end":{"line":16,"column":58}}})) != null ? stack1 : "")
+ "</td>\n <td class=\"col-xs-3\">"
+ ((stack1 = (lookupProperty(helpers,"toTitleCase")||(depth0 && lookupProperty(depth0,"toTitleCase"))||alias2).call(alias1,(depth0 != null ? lookupProperty(depth0,"city") : depth0),{"name":"toTitleCase","hash":{},"data":data,"loc":{"start":{"line":17,"column":24},"end":{"line":17,"column":46}}})) != null ? stack1 : "")
+ "</td>\n <td class=\"col-xs-3\">"
+ ((stack1 = (lookupProperty(helpers,"formatDate")||(depth0 && lookupProperty(depth0,"formatDate"))||alias2).call(alias1,(depth0 != null ? lookupProperty(depth0,"date") : depth0),{"name":"formatDate","hash":{},"data":data,"loc":{"start":{"line":18,"column":24},"end":{"line":18,"column":45}}})) != null ? stack1 : "")
+ "</td>\n </tr>\n";
},"4":function(container,depth0,helpers,partials,data) {
return "<div class=\"alert alert-danger\" role=\"alert\">No results found</div>\n";
},"compiler":[8,">= 4.3.0"],"main":function(container,depth0,helpers,partials,data) {
var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName) {
if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {
return parent[propertyName];
}
return undefined
};
return ((stack1 = lookupProperty(helpers,"if").call(depth0 != null ? depth0 : (container.nullContext || {}),((stack1 = (depth0 != null ? lookupProperty(depth0,"Places") : depth0)) != null ? lookupProperty(stack1,"places") : stack1),{"name":"if","hash":{},"fn":container.program(1, data, 0),"inverse":container.program(4, data, 0),"data":data,"loc":{"start":{"line":1,"column":0},"end":{"line":25,"column":7}}})) != null ? stack1 : "");
},"useData":true});
})(); | OpenSyracuse/eatsafecny | assets/js/templates.js | JavaScript | bsd-3-clause | 8,263 |
/*
* information about range and zoom level for a dimension, to be used in visual tiles, data tiles and vis specs
*/
var DimInfo = Backbone.Model.extend({
/**
* @memberOf DimInfo
*/
setInfo : function(dim, zm, start, end){
var d = parseInt(dim);
if (d == NaN)
d = dim;
this.set("info", {dim: d, zoom:zm, startBin:start, endBin:end});
},
toString : function(){
var info = this.get("info");
return info.dim + "-" + info.startBin + "-" + info.endBin + "-" + info.zoom ;
},
setStartBin : function(s){
this.get("info").startBin = s;
},
getStartBin : function(){
return this.get("info").startBin;
},
setEndBin : function(e){
this.get("info").endBin = e;
},
getEndBin : function(){
return this.get("info").endBin;
},
setZoom : function(z){
this.get("info").zoom = z;
},
getZoom : function(){
return this.get("info").zoom;
},
setDim : function(d){
if (parseInt(d) == NaN)
this.get("info").dim = d;
else
this.get("info").dim = parseInt(d);
},
getDim : function(){
return this.get("info").dim;
},
//e.g.
// 212 - 233 : []
// 212 - 333 : [256]
// 212 - 433 : [256]
// 212 - 33 : [256, 0]
// 468 - 33 : [0]
getSpannedTileBorders: function(){
var info = this.get("info");
var binCnt = dataManager.get("metadata")[info.dim].totalBinCnt[info.zoom];
var binCntPerTile = dataManager.get("metadata")[info.dim].binsPerTile;
var startBin = this.getStartBin(); //Math.floor(this.getStartBin()/binCntPerTile) * binCntPerTile;
var endBin = this.getStartBin() > this.getEndBin() ? this.getEndBin() + binCnt : this.getEndBin();
var startBorder = (Math.floor(startBin/binCntPerTile) + 1) * binCntPerTile;
var endBorder = Math.floor(endBin/binCntPerTile) * binCntPerTile;
var tileRanges = [];
var tileInfo;
while (startBorder <= endBorder) {
if (startBorder >= binCnt - 1) {
startBorder = 0;
endBorder -= binCnt;
}
tileRanges.push(startBorder);
startBorder += binCntPerTile;
}
return tileRanges;
},
//returns an array, where each value is the start bin of a new tile
getTileBins : function() {
var info = this.get("info");
var binCnt = dataManager.get("metadata")[info.dim].totalBinCnt[info.zoom];
var binCntPerTile = dataManager.get("metadata")[info.dim].binsPerTile;
var startBin = Math.floor(this.getStartBin()/binCntPerTile) * binCntPerTile;
var endBin = this.getStartBin() > this.getEndBin() ? this.getEndBin() + binCnt : this.getEndBin();
var tileRanges = [];
var tileInfo;
if (binCnt/binCntPerTile <= 1) {
tileInfo = new DimInfo;
tileInfo.setInfo(info.dim, info.zoom, startBin, startBin + binCntPerTile - 1);
tileRanges.push(tileInfo);
} else {
while (startBin <= endBin) {
tileInfo = new DimInfo;
tileInfo.setInfo(info.dim, info.zoom, startBin, startBin + binCntPerTile - 1);
tileRanges.push(tileInfo);
if (startBin + binCntPerTile == binCnt) {
startBin = 0;
endBin -= binCnt;
} else {
startBin += binCntPerTile;
}
}
}
return tileRanges;
},
initialize : function() {
this.set("info", {});
},
}); | uwdata/imMens | webapp/WebContent/lib/spec/dimInfo.js | JavaScript | bsd-3-clause | 3,121 |
#! /usr/bin/env node
'use strict'
/* eslint-disable no-console */
var fs = require('fs')
var path = require('path')
var readline = require('readline')
var url = require('url')
var MetricNormalizer = require('../lib/metrics/normalizer')
var cwd = process.cwd()
var opts = null
if (arrayContainsAny(process.argv, '-h', '-?', '--help')) {
printHelp()
} else if (process.argv.length === 3) {
opts = {rules: null, urls: path.resolve(cwd, process.argv[2])}
} else if (process.argv.length === 4) {
opts = {
rules: path.resolve(cwd, process.argv[2]),
urls: path.resolve(cwd, process.argv[3])
}
} else {
printHelp()
}
run(opts)
function printHelp() {
console.log('Usage:')
console.log(' newrelic-naming-rules (-h|--help|-?)')
console.log(' newrelic-naming-rules [<rules>] <urls>')
console.log('')
console.log('Runs the configured naming rules against the given set of URLs')
console.log('and prints out the resulting normalized URLs.')
console.log('')
console.log('Parameters:')
console.log(' <rules>')
console.log(' Optional. A JSON file containing additional rules to apply')
console.log(' to the URLs. Should be in the form of an array of arrays:')
console.log(' [["pattern", "replacement"], [/pattern2/, "replacement2"]]')
console.log('')
console.log(' <urls>')
console.log(' A file containing URLs to test against the naming rules.')
console.log(' Should contain one URL per line, and only contain the path')
console.log(' without host or protocol:')
console.log(' /foo/bar')
console.log(' /foo/biz')
console.log(' /fiz/bang')
console.log('')
console.log(' -h|--help|-?')
console.log(' Optional. Prints this help message and exits.')
process.exit(0)
}
function run(opts) {
var config = require('../lib/config').initialize()
var runtimeRules = opts.rules ? require(opts.rules) : null
var appliedRules = []
// responsible for handling default rules provided by the server
var defaultNormalizer = loadDefaultNormalizer(config, runtimeRules)
// rules defined by user in local configuration file
var userNormalizer = loadUserNormalizer(config, runtimeRules)
defaultNormalizer.on('appliedRule', onAppliedRule)
userNormalizer.on('appliedRule', onAppliedRule)
var urlsFile = fs.createReadStream(opts.urls, {encoding: 'utf-8'})
var reader = readline.createInterface({input: urlsFile, output: null})
reader.on('line', function onUrlLine(urlLine) {
appliedRules = []
var parsedUrl = url.parse(urlLine)
var normalized = userNormalizer.normalize(parsedUrl.path)
if (!normalized.matched) {
normalized = defaultNormalizer.normalize(parsedUrl.path)
}
console.log(parsedUrl.path, ' => ', normalized.value)
if (appliedRules.length === 0) {
console.log('no rules matched')
} else {
for (var i = 0; i < appliedRules.length; i++) {
var match = appliedRules[i]
console.log(' %s: %s => %s (rule %s)', (i+1), match.original, match.normalized, match.rule.pattern)
}
}
console.log('')
})
urlsFile.on('end', function onUrlEnd() {
urlsFile.close()
reader.close()
})
function onAppliedRule(rule, newValue, oldValue) {
appliedRules.push({
rule: rule,
original: oldValue,
normalized: newValue
})
}
}
function loadDefaultNormalizer(config) {
// Load the normalizer.
var normalizer = new MetricNormalizer(config, 'URL')
// Add in the rules the collector would ship down.
normalizer.load([{
'match_expression':
'.*\\.(ace|arj|ini|txt|udl|plist|css|gif|ico|jpe?g|js|png|swf|woff|caf|' +
'aiff|m4v|mpe?g|mp3|mp4|mov)$',
'replacement': '/*.\\1',
'replace_all': false,
'each_segment': false,
'ignore': false,
'terminate_chain': true,
'eval_order': 1000
}, {
'match_expression': '^[0-9][0-9a-f_,.-]*$',
'replacement': '*',
'replace_all': false,
'each_segment': true,
'ignore': false,
'terminate_chain': false,
'eval_order': 1001
}, {
'match_expression': '^(.*)/[0-9][0-9a-f_,-]*\\.([0-9a-z][0-9a-z]*)$',
'replacement': '\\1/.*\\2',
'replace_all': false,
'each_segment': false,
'ignore': false,
'terminate_chain': false,
'eval_order': 1002
}])
return normalizer
}
function loadUserNormalizer(config, rules) {
// Load the normalizer.
var normalizer = new MetricNormalizer(config, 'user')
normalizer.loadFromConfig()
if (rules && rules.length) {
rules.forEach(function forEachRule(rule) {
// Add the rule like `API#addNamingRule` would.
normalizer.addSimple(rule[0], '/' + rule[1])
})
}
return normalizer
}
function arrayContainsAny(array) {
for (var i = 1; i < arguments.length; ++i) {
if (array.indexOf(arguments[i]) !== -1) {
return true
}
}
return false
}
| devierol/heroku-gjs | node_modules/newrelic/bin/test-naming-rules.js | JavaScript | bsd-3-clause | 4,868 |
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var Path = require("path");
var FS = require("fs");
var _ = require("lodash");
var component_1 = require("../../component");
var options_1 = require("../options");
var declaration_1 = require("../declaration");
var TypedocReader = TypedocReader_1 = (function (_super) {
__extends(TypedocReader, _super);
function TypedocReader() {
return _super.apply(this, arguments) || this;
}
TypedocReader.prototype.initialize = function () {
this.listenTo(this.owner, options_1.DiscoverEvent.DISCOVER, this.onDiscover, -100);
};
TypedocReader.prototype.onDiscover = function (event) {
if (TypedocReader_1.OPTIONS_KEY in event.data) {
this.load(event, Path.resolve(event.data[TypedocReader_1.OPTIONS_KEY]));
}
else if (this.application.isCLI) {
var file = Path.resolve('typedoc.js');
if (FS.existsSync(file)) {
this.load(event, file);
}
}
};
TypedocReader.prototype.load = function (event, optionFile) {
if (!FS.existsSync(optionFile)) {
event.addError('The option file %s does not exist.', optionFile);
return;
}
var data = require(optionFile);
if (typeof data == 'function') {
data = data(this.application);
}
if (!(typeof data == 'object')) {
event.addError('The option file %s could not be read, it must either export a function or an object.', optionFile);
}
else {
if (data.src) {
if (typeof data.src == 'string') {
event.inputFiles = [data.src];
}
else if (_.isArray(data.src)) {
event.inputFiles = data.src;
}
else {
event.addError('The property \'src\' of the option file %s must be a string or an array.', optionFile);
}
delete data.src;
}
_.defaultsDeep(event.data, data);
}
};
return TypedocReader;
}(options_1.OptionsComponent));
TypedocReader.OPTIONS_KEY = 'options';
__decorate([
component_1.Option({
name: TypedocReader_1.OPTIONS_KEY,
help: 'Specify a js option file that should be loaded. If not specified TypeDoc will look for \'typedoc.js\' in the current directory.',
type: declaration_1.ParameterType.String,
hint: declaration_1.ParameterHint.File
})
], TypedocReader.prototype, "options", void 0);
TypedocReader = TypedocReader_1 = __decorate([
component_1.Component({ name: "options:typedoc" })
], TypedocReader);
exports.TypedocReader = TypedocReader;
var TypedocReader_1;
//# sourceMappingURL=typedoc.js.map | MengjiaoH/UpSet-Phovea | node_modules/typedoc/dist/lib/utils/options/readers/typedoc.js | JavaScript | bsd-3-clause | 3,587 |
import express from 'express';
import BodyParser from 'body-parser';
import * as Middlewares from '../middlewares';
import Parse from 'parse/node';
import Config from '../Config';
import mime from 'mime';
export class FilesRouter {
expressRouter(options = {}) {
var router = express.Router();
router.get('/files/:appId/:filename', this.getHandler);
router.post('/files', function(req, res, next) {
next(new Parse.Error(Parse.Error.INVALID_FILE_NAME,
'Filename not provided.'));
});
router.post('/files/:filename',
Middlewares.allowCrossDomain,
BodyParser.raw({type: () => { return true; }, limit: options.maxUploadSize || '20mb'}), // Allow uploads without Content-Type, or with any Content-Type.
Middlewares.handleParseHeaders,
this.createHandler
);
router.delete('/files/:filename',
Middlewares.allowCrossDomain,
Middlewares.handleParseHeaders,
Middlewares.enforceMasterKeyAccess,
this.deleteHandler
);
return router;
}
getHandler(req, res) {
const config = new Config(req.params.appId);
const filesController = config.filesController;
const filename = req.params.filename;
const contentType = mime.lookup(filename);
if (isFileStreamable(req, filesController)) {
filesController.getFileStream(config, filename).then((stream) => {
handleFileStream(stream, req, res, contentType);
}).catch(() => {
res.status(404);
res.set('Content-Type', 'text/plain');
res.end('File not found.');
});
} else {
filesController.getFileData(config, filename).then((data) => {
res.status(200);
res.set('Content-Type', contentType);
res.set('Content-Length', data.length);
res.end(data);
}).catch(() => {
res.status(404);
res.set('Content-Type', 'text/plain');
res.end('File not found.');
});
}
}
createHandler(req, res, next) {
if (!req.body || !req.body.length) {
next(new Parse.Error(Parse.Error.FILE_SAVE_ERROR,
'Invalid file upload.'));
return;
}
if (req.params.filename.length > 128) {
next(new Parse.Error(Parse.Error.INVALID_FILE_NAME,
'Filename too long.'));
return;
}
if (!req.params.filename.match(/^[_a-zA-Z0-9][a-zA-Z0-9@\.\ ~_-]*$/)) {
next(new Parse.Error(Parse.Error.INVALID_FILE_NAME,
'Filename contains invalid characters.'));
return;
}
const filename = req.params.filename;
const contentType = req.get('Content-type');
const config = req.config;
const filesController = config.filesController;
filesController.createFile(config, filename, req.body, contentType).then((result) => {
res.status(201);
res.set('Location', result.url);
res.json(result);
}).catch(() => {
next(new Parse.Error(Parse.Error.FILE_SAVE_ERROR, 'Could not store file.'));
});
}
deleteHandler(req, res, next) {
const filesController = req.config.filesController;
filesController.deleteFile(req.config, req.params.filename).then(() => {
res.status(200);
// TODO: return useful JSON here?
res.end();
}).catch(() => {
next(new Parse.Error(Parse.Error.FILE_DELETE_ERROR,
'Could not delete file.'));
});
}
}
function isFileStreamable(req, filesController){
if (req.get('Range')) {
if (!(typeof filesController.adapter.getFileStream === 'function')) {
return false;
}
if (typeof filesController.adapter.constructor.name !== 'undefined') {
if (filesController.adapter.constructor.name == 'GridStoreAdapter') {
return true;
}
}
}
return false;
}
// handleFileStream is licenced under Creative Commons Attribution 4.0 International License (https://creativecommons.org/licenses/by/4.0/).
// Author: LEROIB at weightingformypizza (https://weightingformypizza.wordpress.com/2015/06/24/stream-html5-media-content-like-video-audio-from-mongodb-using-express-and-gridstore/).
function handleFileStream(stream, req, res, contentType) {
var buffer_size = 1024 * 1024;//1024Kb
// Range request, partiall stream the file
var parts = req.get('Range').replace(/bytes=/, "").split("-");
var partialstart = parts[0];
var partialend = parts[1];
var start = partialstart ? parseInt(partialstart, 10) : 0;
var end = partialend ? parseInt(partialend, 10) : stream.length - 1;
var chunksize = (end - start) + 1;
if (chunksize == 1) {
start = 0;
partialend = false;
}
if (!partialend) {
if (((stream.length - 1) - start) < (buffer_size)) {
end = stream.length - 1;
}else{
end = start + (buffer_size);
}
chunksize = (end - start) + 1;
}
if (start == 0 && end == 2) {
chunksize = 1;
}
res.writeHead(206, {
'Content-Range': 'bytes ' + start + '-' + end + '/' + stream.length,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': contentType,
});
stream.seek(start, function () {
// get gridFile stream
var gridFileStream = stream.stream(true);
var bufferAvail = 0;
var range = (end - start) + 1;
var totalbyteswanted = (end - start) + 1;
var totalbyteswritten = 0;
// write to response
gridFileStream.on('data', function (buff) {
bufferAvail += buff.length;
//Ok check if we have enough to cover our range
if (bufferAvail < range) {
//Not enough bytes to satisfy our full range
if (bufferAvail > 0) {
//Write full buffer
res.write(buff);
totalbyteswritten += buff.length;
range -= buff.length;
bufferAvail -= buff.length;
}
} else {
//Enough bytes to satisfy our full range!
if (bufferAvail > 0) {
const buffer = buff.slice(0,range);
res.write(buffer);
totalbyteswritten += buffer.length;
bufferAvail -= range;
}
}
if (totalbyteswritten >= totalbyteswanted) {
//totalbytes = 0;
stream.close();
res.end();
this.destroy();
}
});
});
}
| Isaack90/parse-server | src/Routers/FilesRouter.js | JavaScript | bsd-3-clause | 6,212 |
// Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
export const generatedProperties = [
{'name': '-webkit-border-horizontal-spacing', 'inherited': true},
{'name': '-webkit-border-image'},
{'name': '-webkit-border-vertical-spacing', 'inherited': true},
{'name': '-webkit-box-align', 'keywords': ['stretch', 'start', 'center', 'end', 'baseline']},
{'name': '-webkit-box-decoration-break', 'keywords': ['slice', 'clone']},
{'name': '-webkit-box-direction', 'inherited': true, 'keywords': ['normal', 'reverse']},
{'name': '-webkit-box-flex'},
{'name': '-webkit-box-ordinal-group'},
{'name': '-webkit-box-orient', 'keywords': ['horizontal', 'vertical']},
{'name': '-webkit-box-pack', 'keywords': ['start', 'center', 'end', 'justify']},
{'name': '-webkit-box-reflect'},
{'longhands': ['break-after'], 'name': '-webkit-column-break-after'},
{'longhands': ['break-before'], 'name': '-webkit-column-break-before'},
{'longhands': ['break-inside'], 'name': '-webkit-column-break-inside'},
{'name': '-webkit-font-smoothing', 'inherited': true},
{'name': '-webkit-highlight', 'inherited': true},
{'name': '-webkit-hyphenate-character', 'inherited': true},
{
'name': '-webkit-line-break',
'inherited': true,
'keywords': ['auto', 'loose', 'normal', 'strict', 'after-white-space', 'anywhere']
},
{'name': '-webkit-line-clamp'},
{'name': '-webkit-locale', 'inherited': true},
{
'longhands': [
'-webkit-mask-image', '-webkit-mask-position-x', '-webkit-mask-position-y', '-webkit-mask-size',
'-webkit-mask-repeat-x', '-webkit-mask-repeat-y', '-webkit-mask-origin', '-webkit-mask-clip'
],
'name': '-webkit-mask'
},
{
'longhands': [
'-webkit-mask-box-image-source', '-webkit-mask-box-image-slice', '-webkit-mask-box-image-width',
'-webkit-mask-box-image-outset', '-webkit-mask-box-image-repeat'
],
'name': '-webkit-mask-box-image'
},
{'name': '-webkit-mask-box-image-outset'},
{'name': '-webkit-mask-box-image-repeat'},
{'name': '-webkit-mask-box-image-slice'},
{'name': '-webkit-mask-box-image-source'},
{'name': '-webkit-mask-box-image-width'},
{'name': '-webkit-mask-clip'},
{'name': '-webkit-mask-composite'},
{'name': '-webkit-mask-image'},
{'name': '-webkit-mask-origin'},
{'longhands': ['-webkit-mask-position-x', '-webkit-mask-position-y'], 'name': '-webkit-mask-position'},
{'name': '-webkit-mask-position-x'},
{'name': '-webkit-mask-position-y'},
{'longhands': ['-webkit-mask-repeat-x', '-webkit-mask-repeat-y'], 'name': '-webkit-mask-repeat'},
{'name': '-webkit-mask-repeat-x'},
{'name': '-webkit-mask-repeat-y'},
{'name': '-webkit-mask-size'},
{'name': '-webkit-perspective-origin-x'},
{'name': '-webkit-perspective-origin-y'},
{'name': '-webkit-print-color-adjust', 'inherited': true, 'keywords': ['economy', 'exact']},
{'name': '-webkit-rtl-ordering', 'inherited': true, 'keywords': ['logical', 'visual']},
{'name': '-webkit-ruby-position', 'inherited': true, 'keywords': ['before', 'after']},
{'name': '-webkit-tap-highlight-color', 'inherited': true},
{'name': '-webkit-text-combine', 'inherited': true},
{'name': '-webkit-text-decorations-in-effect', 'inherited': true},
{'name': '-webkit-text-fill-color', 'inherited': true},
{'name': '-webkit-text-orientation', 'inherited': true},
{'name': '-webkit-text-security', 'inherited': true, 'keywords': ['none', 'disc', 'circle', 'square']},
{
'longhands': ['-webkit-text-stroke-width', '-webkit-text-stroke-color'],
'name': '-webkit-text-stroke',
'inherited': true
},
{'name': '-webkit-text-stroke-color', 'inherited': true},
{'name': '-webkit-text-stroke-width', 'inherited': true},
{'name': '-webkit-transform-origin-x'},
{'name': '-webkit-transform-origin-y'},
{'name': '-webkit-transform-origin-z'},
{'name': '-webkit-user-drag', 'keywords': ['auto', 'none', 'element']},
{
'name': '-webkit-user-modify',
'inherited': true,
'keywords': ['read-only', 'read-write', 'read-write-plaintext-only']
},
{'name': '-webkit-writing-mode', 'inherited': true},
{'name': 'accent-color', 'inherited': true, 'keywords': ['auto', 'currentcolor']},
{'name': 'additive-symbols'},
{'name': 'align-content'},
{'name': 'align-items'},
{'name': 'align-self'},
{
'name': 'alignment-baseline',
'keywords': [
'auto', 'baseline', 'alphabetic', 'ideographic', 'middle', 'central', 'mathematical', 'before-edge',
'text-before-edge', 'after-edge', 'text-after-edge', 'hanging'
]
},
{'name': 'all'},
{
'longhands': [
'animation-duration', 'animation-timing-function', 'animation-delay', 'animation-iteration-count',
'animation-direction', 'animation-fill-mode', 'animation-play-state', 'animation-name', 'animation-timeline'
],
'name': 'animation'
},
{'name': 'animation-delay'},
{'name': 'animation-direction', 'keywords': ['normal', 'reverse', 'alternate', 'alternate-reverse']},
{'name': 'animation-duration'},
{'name': 'animation-fill-mode', 'keywords': ['none', 'forwards', 'backwards', 'both']},
{'name': 'animation-iteration-count', 'keywords': ['infinite']},
{'name': 'animation-name', 'keywords': ['none']},
{'name': 'animation-play-state', 'keywords': ['running', 'paused']},
{'name': 'animation-timeline', 'keywords': ['none', 'auto']},
{
'name': 'animation-timing-function',
'keywords': [
'linear', 'ease', 'ease-in', 'ease-out', 'ease-in-out', 'jump-both', 'jump-end', 'jump-none', 'jump-start',
'step-start', 'step-end'
]
},
{'name': 'app-region', 'keywords': ['none', 'drag', 'no-drag']},
{'name': 'appearance'},
{'name': 'ascent-override'},
{'name': 'aspect-ratio', 'keywords': ['auto']},
{'name': 'backdrop-filter', 'keywords': ['none']},
{'name': 'backface-visibility', 'keywords': ['visible', 'hidden']},
{
'longhands': [
'background-image', 'background-position-x', 'background-position-y', 'background-size', 'background-repeat-x',
'background-repeat-y', 'background-attachment', 'background-origin', 'background-clip', 'background-color'
],
'name': 'background'
},
{'name': 'background-attachment', 'keywords': ['scroll', 'fixed', 'local']},
{
'name': 'background-blend-mode',
'keywords': [
'normal', 'multiply', 'screen', 'overlay', 'darken', 'lighten', 'color-dodge', 'color-burn', 'hard-light',
'soft-light', 'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity'
]
},
{'name': 'background-clip', 'keywords': ['border-box', 'padding-box', 'content-box']},
{'name': 'background-color', 'keywords': ['currentcolor']},
{'name': 'background-image', 'keywords': ['auto', 'none']},
{'name': 'background-origin', 'keywords': ['border-box', 'padding-box', 'content-box']},
{'longhands': ['background-position-x', 'background-position-y'], 'name': 'background-position'},
{'name': 'background-position-x'},
{'name': 'background-position-y'},
{'longhands': ['background-repeat-x', 'background-repeat-y'], 'name': 'background-repeat'},
{'name': 'background-repeat-x'},
{'name': 'background-repeat-y'},
{'name': 'background-size', 'keywords': ['auto', 'cover', 'contain']},
{'name': 'base-palette'},
{'name': 'baseline-shift', 'keywords': ['baseline', 'sub', 'super']},
{'name': 'block-size', 'keywords': ['auto']},
{
'longhands': [
'border-top-color', 'border-top-style', 'border-top-width', 'border-right-color', 'border-right-style',
'border-right-width', 'border-bottom-color', 'border-bottom-style', 'border-bottom-width', 'border-left-color',
'border-left-style', 'border-left-width', 'border-image-source', 'border-image-slice', 'border-image-width',
'border-image-outset', 'border-image-repeat'
],
'name': 'border'
},
{
'longhands': [
'border-block-start-color', 'border-block-start-style', 'border-block-start-width', 'border-block-end-color',
'border-block-end-style', 'border-block-end-width'
],
'name': 'border-block'
},
{'longhands': ['border-block-start-color', 'border-block-end-color'], 'name': 'border-block-color'},
{
'longhands': ['border-block-end-width', 'border-block-end-style', 'border-block-end-color'],
'name': 'border-block-end'
},
{'name': 'border-block-end-color'},
{'name': 'border-block-end-style'},
{'name': 'border-block-end-width'},
{
'longhands': ['border-block-start-width', 'border-block-start-style', 'border-block-start-color'],
'name': 'border-block-start'
},
{'name': 'border-block-start-color'},
{'name': 'border-block-start-style'},
{'name': 'border-block-start-width'},
{'longhands': ['border-block-start-style', 'border-block-end-style'], 'name': 'border-block-style'},
{'longhands': ['border-block-start-width', 'border-block-end-width'], 'name': 'border-block-width'},
{'longhands': ['border-bottom-width', 'border-bottom-style', 'border-bottom-color'], 'name': 'border-bottom'},
{'name': 'border-bottom-color', 'keywords': ['currentcolor']},
{'name': 'border-bottom-left-radius'},
{'name': 'border-bottom-right-radius'},
{
'name': 'border-bottom-style',
'keywords': ['none', 'hidden', 'inset', 'groove', 'outset', 'ridge', 'dotted', 'dashed', 'solid', 'double']
},
{'name': 'border-bottom-width', 'keywords': ['thin', 'medium', 'thick']},
{'name': 'border-collapse', 'inherited': true, 'keywords': ['separate', 'collapse']},
{
'longhands': ['border-top-color', 'border-right-color', 'border-bottom-color', 'border-left-color'],
'name': 'border-color'
},
{'name': 'border-end-end-radius'},
{'name': 'border-end-start-radius'},
{
'longhands': [
'border-image-source', 'border-image-slice', 'border-image-width', 'border-image-outset', 'border-image-repeat'
],
'name': 'border-image'
},
{'name': 'border-image-outset'},
{'name': 'border-image-repeat', 'keywords': ['stretch', 'repeat', 'round', 'space']},
{'name': 'border-image-slice'},
{'name': 'border-image-source', 'keywords': ['none']},
{'name': 'border-image-width', 'keywords': ['auto']},
{
'longhands': [
'border-inline-start-color', 'border-inline-start-style', 'border-inline-start-width', 'border-inline-end-color',
'border-inline-end-style', 'border-inline-end-width'
],
'name': 'border-inline'
},
{'longhands': ['border-inline-start-color', 'border-inline-end-color'], 'name': 'border-inline-color'},
{
'longhands': ['border-inline-end-width', 'border-inline-end-style', 'border-inline-end-color'],
'name': 'border-inline-end'
},
{'name': 'border-inline-end-color'},
{'name': 'border-inline-end-style'},
{'name': 'border-inline-end-width'},
{
'longhands': ['border-inline-start-width', 'border-inline-start-style', 'border-inline-start-color'],
'name': 'border-inline-start'
},
{'name': 'border-inline-start-color'},
{'name': 'border-inline-start-style'},
{'name': 'border-inline-start-width'},
{'longhands': ['border-inline-start-style', 'border-inline-end-style'], 'name': 'border-inline-style'},
{'longhands': ['border-inline-start-width', 'border-inline-end-width'], 'name': 'border-inline-width'},
{'longhands': ['border-left-width', 'border-left-style', 'border-left-color'], 'name': 'border-left'},
{'name': 'border-left-color', 'keywords': ['currentcolor']},
{
'name': 'border-left-style',
'keywords': ['none', 'hidden', 'inset', 'groove', 'outset', 'ridge', 'dotted', 'dashed', 'solid', 'double']
},
{'name': 'border-left-width', 'keywords': ['thin', 'medium', 'thick']},
{
'longhands': [
'border-top-left-radius', 'border-top-right-radius', 'border-bottom-right-radius', 'border-bottom-left-radius'
],
'name': 'border-radius'
},
{'longhands': ['border-right-width', 'border-right-style', 'border-right-color'], 'name': 'border-right'},
{'name': 'border-right-color', 'keywords': ['currentcolor']},
{
'name': 'border-right-style',
'keywords': ['none', 'hidden', 'inset', 'groove', 'outset', 'ridge', 'dotted', 'dashed', 'solid', 'double']
},
{'name': 'border-right-width', 'keywords': ['thin', 'medium', 'thick']},
{
'longhands': ['-webkit-border-horizontal-spacing', '-webkit-border-vertical-spacing'],
'name': 'border-spacing',
'inherited': true
},
{'name': 'border-start-end-radius'},
{'name': 'border-start-start-radius'},
{
'keywords': ['none'],
'longhands': ['border-top-style', 'border-right-style', 'border-bottom-style', 'border-left-style'],
'name': 'border-style'
},
{'longhands': ['border-top-width', 'border-top-style', 'border-top-color'], 'name': 'border-top'},
{'name': 'border-top-color', 'keywords': ['currentcolor']},
{'name': 'border-top-left-radius'},
{'name': 'border-top-right-radius'},
{
'name': 'border-top-style',
'keywords': ['none', 'hidden', 'inset', 'groove', 'outset', 'ridge', 'dotted', 'dashed', 'solid', 'double']
},
{'name': 'border-top-width', 'keywords': ['thin', 'medium', 'thick']},
{
'longhands': ['border-top-width', 'border-right-width', 'border-bottom-width', 'border-left-width'],
'name': 'border-width'
},
{'name': 'bottom', 'keywords': ['auto']},
{'name': 'box-shadow', 'keywords': ['none']},
{'name': 'box-sizing', 'keywords': ['content-box', 'border-box']},
{
'name': 'break-after',
'keywords': ['auto', 'avoid', 'avoid-column', 'avoid-page', 'column', 'left', 'page', 'recto', 'right', 'verso']
},
{
'name': 'break-before',
'keywords': ['auto', 'avoid', 'avoid-column', 'avoid-page', 'column', 'left', 'page', 'recto', 'right', 'verso']
},
{'name': 'break-inside', 'keywords': ['auto', 'avoid', 'avoid-column', 'avoid-page']},
{'name': 'buffered-rendering', 'keywords': ['auto', 'dynamic', 'static']},
{'name': 'caption-side', 'inherited': true, 'keywords': ['top', 'bottom']},
{'name': 'caret-color', 'inherited': true, 'keywords': ['auto', 'currentcolor']},
{'name': 'clear', 'keywords': ['none', 'left', 'right', 'both', 'inline-start', 'inline-end']},
{'name': 'clip', 'keywords': ['auto']},
{'name': 'clip-path', 'keywords': ['none']},
{'name': 'clip-rule', 'inherited': true, 'keywords': ['nonzero', 'evenodd']},
{'name': 'color', 'keywords': ['currentcolor'], 'inherited': true},
{'name': 'color-interpolation', 'inherited': true, 'keywords': ['auto', 'srgb', 'linearrgb']},
{'name': 'color-interpolation-filters', 'inherited': true, 'keywords': ['auto', 'srgb', 'linearrgb']},
{'name': 'color-rendering', 'inherited': true, 'keywords': ['auto', 'optimizespeed', 'optimizequality']},
{'name': 'color-scheme', 'inherited': true},
{'name': 'column-count', 'keywords': ['auto']},
{'name': 'column-fill', 'keywords': ['balance', 'auto']},
{'name': 'column-gap', 'keywords': ['normal']},
{'longhands': ['column-rule-width', 'column-rule-style', 'column-rule-color'], 'name': 'column-rule'},
{'name': 'column-rule-color', 'keywords': ['currentcolor']},
{
'name': 'column-rule-style',
'keywords': ['none', 'hidden', 'inset', 'groove', 'outset', 'ridge', 'dotted', 'dashed', 'solid', 'double']
},
{'name': 'column-rule-width', 'keywords': ['thin', 'medium', 'thick']},
{'name': 'column-span', 'keywords': ['none', 'all']},
{'name': 'column-width', 'keywords': ['auto']},
{'longhands': ['column-width', 'column-count'], 'name': 'columns'},
{
'name': 'contain',
'keywords': ['none', 'strict', 'content', 'size', 'layout', 'style', 'paint', 'inline-size', 'block-size']
},
{'name': 'contain-intrinsic-block-size'},
{'name': 'contain-intrinsic-height', 'keywords': ['auto', 'none']},
{'name': 'contain-intrinsic-inline-size'},
{'longhands': ['contain-intrinsic-width', 'contain-intrinsic-height'], 'name': 'contain-intrinsic-size'},
{'name': 'contain-intrinsic-width', 'keywords': ['auto', 'none']},
{'longhands': ['container-type', 'container-name'], 'name': 'container'},
{'name': 'container-name', 'keywords': ['none']},
{'name': 'container-type', 'keywords': ['none', 'block-size', 'inline-size', 'size']},
{'name': 'content'},
{'name': 'content-visibility', 'keywords': ['visible', 'auto', 'hidden', 'hidden-matchable']},
{'name': 'counter-increment', 'keywords': ['none']},
{'name': 'counter-reset', 'keywords': ['none']},
{'name': 'counter-set', 'keywords': ['none']},
{
'name': 'cursor',
'inherited': true,
'keywords': [
'auto', 'default', 'none', 'context-menu', 'help', 'pointer', 'progress', 'wait',
'cell', 'crosshair', 'text', 'vertical-text', 'alias', 'copy', 'move', 'no-drop',
'not-allowed', 'e-resize', 'n-resize', 'ne-resize', 'nw-resize', 's-resize', 'se-resize', 'sw-resize',
'w-resize', 'ew-resize', 'ns-resize', 'nesw-resize', 'nwse-resize', 'col-resize', 'row-resize', 'all-scroll',
'zoom-in', 'zoom-out', 'grab', 'grabbing'
]
},
{'name': 'cx'},
{'name': 'cy'},
{'name': 'd', 'keywords': ['none']},
{'name': 'descent-override'},
{'name': 'direction', 'inherited': true, 'keywords': ['ltr', 'rtl']},
{
'keywords': [
'inline',
'block',
'list-item',
'inline-block',
'table',
'inline-table',
'table-row-group',
'table-header-group',
'table-footer-group',
'table-row',
'table-column-group',
'table-column',
'table-cell',
'table-caption',
'-webkit-box',
'-webkit-inline-box',
'flex',
'inline-flex',
'grid',
'inline-grid',
'contents',
'flow-root',
'none'
],
'name': 'display'
},
{
'name': 'dominant-baseline',
'inherited': true,
'keywords': [
'auto', 'alphabetic', 'ideographic', 'middle', 'central', 'mathematical', 'hanging', 'use-script', 'no-change',
'reset-size', 'text-after-edge', 'text-before-edge'
]
},
{'name': 'empty-cells', 'inherited': true, 'keywords': ['show', 'hide']},
{'name': 'end'},
{'name': 'fallback'},
{'name': 'fill', 'inherited': true},
{'name': 'fill-opacity', 'inherited': true},
{'name': 'fill-rule', 'inherited': true, 'keywords': ['nonzero', 'evenodd']},
{'name': 'filter', 'keywords': ['none']},
{'longhands': ['flex-grow', 'flex-shrink', 'flex-basis'], 'name': 'flex'},
{'name': 'flex-basis', 'keywords': ['auto', 'fit-content', 'min-content', 'max-content', 'content']},
{'name': 'flex-direction', 'keywords': ['row', 'row-reverse', 'column', 'column-reverse']},
{'longhands': ['flex-direction', 'flex-wrap'], 'name': 'flex-flow'},
{'name': 'flex-grow'},
{'name': 'flex-shrink'},
{'name': 'flex-wrap', 'keywords': ['nowrap', 'wrap', 'wrap-reverse']},
{'name': 'float', 'keywords': ['none', 'left', 'right', 'inline-start', 'inline-end']},
{'name': 'flood-color', 'keywords': ['currentcolor']},
{'name': 'flood-opacity'},
{
'longhands': [
'font-style', 'font-variant-ligatures', 'font-variant-caps', 'font-variant-numeric', 'font-variant-east-asian',
'font-weight', 'font-stretch', 'font-size', 'line-height', 'font-family'
],
'name': 'font',
'inherited': true
},
{'name': 'font-display'},
{'name': 'font-family', 'inherited': true},
{'name': 'font-feature-settings', 'inherited': true, 'keywords': ['normal']},
{'name': 'font-kerning', 'inherited': true, 'keywords': ['auto', 'normal', 'none']},
{'name': 'font-optical-sizing', 'inherited': true, 'keywords': ['auto', 'none']},
{'inherited': true, 'keywords': ['normal', 'light', 'dark'], 'name': 'font-palette'},
{
'name': 'font-size',
'inherited': true,
'keywords': [
'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', 'xxx-large', 'larger', 'smaller',
'-webkit-xxx-large'
]
},
{'name': 'font-size-adjust', 'inherited': true, 'keywords': ['none']},
{
'name': 'font-stretch',
'inherited': true,
'keywords': [
'normal', 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'semi-expanded', 'expanded',
'extra-expanded', 'ultra-expanded'
]
},
{'name': 'font-style', 'inherited': true, 'keywords': ['normal', 'italic', 'oblique']},
{
'longhands': ['font-synthesis-weight', 'font-synthesis-style', 'font-synthesis-small-caps'],
'name': 'font-synthesis',
'inherited': true
},
{'name': 'font-synthesis-small-caps', 'inherited': true, 'keywords': ['auto', 'none']},
{'name': 'font-synthesis-style', 'inherited': true, 'keywords': ['auto', 'none']},
{'name': 'font-synthesis-weight', 'inherited': true, 'keywords': ['auto', 'none']},
{
'longhands': ['font-variant-ligatures', 'font-variant-caps', 'font-variant-numeric', 'font-variant-east-asian'],
'name': 'font-variant',
'inherited': true
},
{
'inherited': true,
'keywords': ['normal', 'small-caps', 'all-small-caps', 'petite-caps', 'all-petite-caps', 'unicase', 'titling-caps'],
'name': 'font-variant-caps'
},
{
'inherited': true,
'keywords': [
'normal', 'jis78', 'jis83', 'jis90', 'jis04', 'simplified', 'traditional', 'full-width', 'proportional-width',
'ruby'
],
'name': 'font-variant-east-asian'
},
{
'name': 'font-variant-ligatures',
'inherited': true,
'keywords': [
'normal', 'none', 'common-ligatures', 'no-common-ligatures', 'discretionary-ligatures',
'no-discretionary-ligatures', 'historical-ligatures', 'no-historical-ligatures', 'contextual', 'no-contextual'
]
},
{
'inherited': true,
'keywords': [
'normal', 'lining-nums', 'oldstyle-nums', 'proportional-nums', 'tabular-nums', 'diagonal-fractions',
'stacked-fractions', 'ordinal', 'slashed-zero'
],
'name': 'font-variant-numeric'
},
{'name': 'font-variation-settings', 'inherited': true, 'keywords': ['normal']},
{'name': 'font-weight', 'inherited': true, 'keywords': ['normal', 'bold', 'bolder', 'lighter']},
{'name': 'forced-color-adjust', 'inherited': true, 'keywords': ['auto', 'none', 'preserve-parent-color']},
{'longhands': ['row-gap', 'column-gap'], 'name': 'gap'},
{
'longhands': [
'grid-template-rows', 'grid-template-columns', 'grid-template-areas', 'grid-auto-flow', 'grid-auto-rows',
'grid-auto-columns'
],
'name': 'grid'
},
{'longhands': ['grid-row-start', 'grid-column-start', 'grid-row-end', 'grid-column-end'], 'name': 'grid-area'},
{'name': 'grid-auto-columns', 'keywords': ['auto', 'min-content', 'max-content']},
{'name': 'grid-auto-flow', 'keywords': ['row', 'column']},
{'name': 'grid-auto-rows', 'keywords': ['auto', 'min-content', 'max-content']},
{'longhands': ['grid-column-start', 'grid-column-end'], 'name': 'grid-column'},
{'name': 'grid-column-end', 'keywords': ['auto']},
{'longhands': ['column-gap'], 'name': 'grid-column-gap'},
{'name': 'grid-column-start', 'keywords': ['auto']},
{'longhands': ['row-gap', 'column-gap'], 'name': 'grid-gap'},
{'longhands': ['grid-row-start', 'grid-row-end'], 'name': 'grid-row'},
{'name': 'grid-row-end', 'keywords': ['auto']},
{'longhands': ['row-gap'], 'name': 'grid-row-gap'},
{'name': 'grid-row-start', 'keywords': ['auto']},
{'longhands': ['grid-template-rows', 'grid-template-columns', 'grid-template-areas'], 'name': 'grid-template'},
{'keywords': ['none'], 'name': 'grid-template-areas'},
{'name': 'grid-template-columns', 'keywords': ['none']},
{'name': 'grid-template-rows', 'keywords': ['none']},
{'name': 'height', 'keywords': ['auto', 'fit-content', 'min-content', 'max-content']},
{'name': 'hyphens', 'inherited': true, 'keywords': ['none', 'manual', 'auto']},
{'name': 'image-orientation', 'inherited': true},
{
'name': 'image-rendering',
'inherited': true,
'keywords': ['auto', 'optimizespeed', 'optimizequality', '-webkit-optimize-contrast', 'pixelated']
},
{'name': 'inherits'},
{'name': 'initial-value'},
{'name': 'inline-size', 'keywords': ['auto']},
{'longhands': ['top', 'right', 'bottom', 'left'], 'name': 'inset'},
{'longhands': ['inset-block-start', 'inset-block-end'], 'name': 'inset-block'},
{'name': 'inset-block-end'},
{'name': 'inset-block-start'},
{'longhands': ['inset-inline-start', 'inset-inline-end'], 'name': 'inset-inline'},
{'name': 'inset-inline-end'},
{'name': 'inset-inline-start'},
{'name': 'isolation', 'keywords': ['auto', 'isolate']},
{'name': 'justify-content'},
{'name': 'justify-items'},
{'name': 'justify-self'},
{'name': 'left', 'keywords': ['auto']},
{'inherited': true, 'keywords': ['normal'], 'name': 'letter-spacing'},
{'name': 'lighting-color', 'keywords': ['currentcolor']},
{'name': 'line-break', 'inherited': true, 'keywords': ['auto', 'loose', 'normal', 'strict', 'anywhere']},
{'name': 'line-gap-override'},
{'name': 'line-height', 'inherited': true, 'keywords': ['normal']},
{'name': 'line-height-step', 'inherited': true},
{
'longhands': ['list-style-position', 'list-style-image', 'list-style-type'],
'name': 'list-style',
'inherited': true
},
{'name': 'list-style-image', 'inherited': true, 'keywords': ['none']},
{'name': 'list-style-position', 'inherited': true, 'keywords': ['outside', 'inside']},
{
'name': 'list-style-type',
'inherited': true,
'keywords': ['disc', 'circle', 'square', 'disclosure-open', 'disclosure-closed', 'decimal', 'none']
},
{'longhands': ['margin-top', 'margin-right', 'margin-bottom', 'margin-left'], 'name': 'margin'},
{'longhands': ['margin-block-start', 'margin-block-end'], 'name': 'margin-block'},
{'name': 'margin-block-end', 'keywords': ['auto']},
{'name': 'margin-block-start', 'keywords': ['auto']},
{'name': 'margin-bottom', 'keywords': ['auto']},
{'longhands': ['margin-inline-start', 'margin-inline-end'], 'name': 'margin-inline'},
{'name': 'margin-inline-end', 'keywords': ['auto']},
{'name': 'margin-inline-start', 'keywords': ['auto']},
{'name': 'margin-left', 'keywords': ['auto']},
{'name': 'margin-right', 'keywords': ['auto']},
{'name': 'margin-top', 'keywords': ['auto']},
{'longhands': ['marker-start', 'marker-mid', 'marker-end'], 'name': 'marker', 'inherited': true},
{'name': 'marker-end', 'inherited': true, 'keywords': ['none']},
{'name': 'marker-mid', 'inherited': true, 'keywords': ['none']},
{'name': 'marker-start', 'inherited': true, 'keywords': ['none']},
{'name': 'mask'},
{'name': 'mask-type', 'keywords': ['luminance', 'alpha']},
{'name': 'math-depth', 'inherited': true},
{'name': 'math-shift', 'inherited': true, 'keywords': ['normal', 'compact']},
{'name': 'math-style', 'inherited': true, 'keywords': ['normal', 'compact']},
{'keywords': ['none'], 'name': 'max-block-size'},
{'name': 'max-height', 'keywords': ['none']},
{'keywords': ['none'], 'name': 'max-inline-size'},
{'name': 'max-width', 'keywords': ['none']},
{'name': 'max-zoom'},
{'name': 'min-block-size'},
{'name': 'min-height'},
{'name': 'min-inline-size'},
{'name': 'min-width'},
{'name': 'min-zoom'},
{
'name': 'mix-blend-mode',
'keywords': [
'normal', 'multiply', 'screen', 'overlay', 'darken', 'lighten', 'color-dodge', 'color-burn', 'hard-light',
'soft-light', 'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity', 'plus-lighter'
]
},
{'name': 'negative'},
{'name': 'object-fit', 'keywords': ['fill', 'contain', 'cover', 'none', 'scale-down']},
{'name': 'object-position'},
{
'longhands': ['offset-position', 'offset-path', 'offset-distance', 'offset-rotate', 'offset-anchor'],
'name': 'offset'
},
{'name': 'offset-anchor', 'keywords': ['auto']},
{'name': 'offset-distance'},
{'name': 'offset-path', 'keywords': ['none']},
{'name': 'offset-position', 'keywords': ['auto']},
{'name': 'offset-rotate', 'keywords': ['auto', 'reverse']},
{'name': 'opacity'},
{'name': 'order'},
{'name': 'orientation'},
{'name': 'origin-trial-test-property', 'keywords': ['normal', 'none']},
{'name': 'orphans', 'inherited': true},
{'longhands': ['outline-color', 'outline-style', 'outline-width'], 'name': 'outline'},
{'name': 'outline-color', 'keywords': ['currentcolor']},
{'name': 'outline-offset'},
{
'name': 'outline-style',
'keywords': ['none', 'hidden', 'inset', 'groove', 'outset', 'ridge', 'dotted', 'dashed', 'solid', 'double']
},
{'name': 'outline-width', 'keywords': ['thin', 'medium', 'thick']},
{'longhands': ['overflow-x', 'overflow-y'], 'name': 'overflow'},
{'name': 'overflow-anchor', 'inherited': false, 'keywords': ['visible', 'none', 'auto']},
{'name': 'overflow-block'},
{'name': 'overflow-clip-margin'},
{'name': 'overflow-inline'},
{'name': 'overflow-wrap', 'inherited': true, 'keywords': ['normal', 'break-word', 'anywhere']},
{'name': 'overflow-x', 'keywords': ['visible', 'hidden', 'scroll', 'auto', 'overlay', 'clip']},
{'name': 'overflow-y', 'keywords': ['visible', 'hidden', 'scroll', 'auto', 'overlay', 'clip']},
{'name': 'override-colors'},
{'longhands': ['overscroll-behavior-x', 'overscroll-behavior-y'], 'name': 'overscroll-behavior'},
{'name': 'overscroll-behavior-block'},
{'name': 'overscroll-behavior-inline'},
{'name': 'overscroll-behavior-x', 'keywords': ['auto', 'contain', 'none']},
{'name': 'overscroll-behavior-y', 'keywords': ['auto', 'contain', 'none']},
{'name': 'pad'},
{'longhands': ['padding-top', 'padding-right', 'padding-bottom', 'padding-left'], 'name': 'padding'},
{'longhands': ['padding-block-start', 'padding-block-end'], 'name': 'padding-block'},
{'name': 'padding-block-end'},
{'name': 'padding-block-start'},
{'name': 'padding-bottom'},
{'longhands': ['padding-inline-start', 'padding-inline-end'], 'name': 'padding-inline'},
{'name': 'padding-inline-end'},
{'name': 'padding-inline-start'},
{'name': 'padding-left'},
{'name': 'padding-right'},
{'name': 'padding-top'},
{'name': 'page', 'keywords': ['auto']},
{'longhands': ['break-after'], 'name': 'page-break-after'},
{'longhands': ['break-before'], 'name': 'page-break-before'},
{'longhands': ['break-inside'], 'name': 'page-break-inside'},
{'name': 'page-orientation'},
{'name': 'paint-order', 'inherited': true, 'keywords': ['normal', 'fill', 'stroke', 'markers']},
{'name': 'perspective', 'keywords': ['none']},
{'name': 'perspective-origin'},
{'longhands': ['align-content', 'justify-content'], 'name': 'place-content'},
{'longhands': ['align-items', 'justify-items'], 'name': 'place-items'},
{'longhands': ['align-self', 'justify-self'], 'name': 'place-self'},
{
'name': 'pointer-events',
'inherited': true,
'keywords': [
'none', 'auto', 'stroke', 'fill', 'painted', 'visible', 'visiblestroke', 'visiblefill', 'visiblepainted',
'bounding-box', 'all'
]
},
{'name': 'position', 'keywords': ['static', 'relative', 'absolute', 'fixed', 'sticky']},
{'name': 'prefix'},
{'name': 'quotes', 'inherited': true, 'keywords': ['auto', 'none']},
{'name': 'r'},
{'name': 'range'},
{'name': 'resize', 'keywords': ['none', 'both', 'horizontal', 'vertical', 'block', 'inline']},
{'name': 'right', 'keywords': ['auto']},
{'name': 'rotate'},
{'name': 'row-gap', 'keywords': ['normal']},
{'inherited': true, 'name': 'ruby-position'},
{'name': 'rx', 'keywords': ['auto']},
{'name': 'ry', 'keywords': ['auto']},
{'name': 'scale'},
{'name': 'scroll-behavior', 'keywords': ['auto', 'smooth']},
{'name': 'scroll-customization'},
{
'longhands': ['scroll-margin-top', 'scroll-margin-right', 'scroll-margin-bottom', 'scroll-margin-left'],
'name': 'scroll-margin'
},
{'longhands': ['scroll-margin-block-start', 'scroll-margin-block-end'], 'name': 'scroll-margin-block'},
{'name': 'scroll-margin-block-end'},
{'name': 'scroll-margin-block-start'},
{'name': 'scroll-margin-bottom'},
{'longhands': ['scroll-margin-inline-start', 'scroll-margin-inline-end'], 'name': 'scroll-margin-inline'},
{'name': 'scroll-margin-inline-end'},
{'name': 'scroll-margin-inline-start'},
{'name': 'scroll-margin-left'},
{'name': 'scroll-margin-right'},
{'name': 'scroll-margin-top'},
{
'longhands': ['scroll-padding-top', 'scroll-padding-right', 'scroll-padding-bottom', 'scroll-padding-left'],
'name': 'scroll-padding'
},
{'longhands': ['scroll-padding-block-start', 'scroll-padding-block-end'], 'name': 'scroll-padding-block'},
{'name': 'scroll-padding-block-end', 'keywords': ['auto']},
{'name': 'scroll-padding-block-start', 'keywords': ['auto']},
{'name': 'scroll-padding-bottom', 'keywords': ['auto']},
{'longhands': ['scroll-padding-inline-start', 'scroll-padding-inline-end'], 'name': 'scroll-padding-inline'},
{'name': 'scroll-padding-inline-end', 'keywords': ['auto']},
{'name': 'scroll-padding-inline-start', 'keywords': ['auto']},
{'name': 'scroll-padding-left', 'keywords': ['auto']},
{'name': 'scroll-padding-right', 'keywords': ['auto']},
{'name': 'scroll-padding-top', 'keywords': ['auto']},
{'name': 'scroll-snap-align', 'keywords': ['none', 'start', 'end', 'center']},
{'name': 'scroll-snap-stop', 'keywords': ['normal', 'always']},
{'name': 'scroll-snap-type', 'keywords': ['none', 'x', 'y', 'block', 'inline', 'both', 'mandatory', 'proximity']},
{'name': 'scrollbar-gutter', 'inherited': false, 'keywords': ['auto', 'stable', 'both-edges']},
{'name': 'scrollbar-width', 'inherited': false, 'keywords': ['auto', 'thin', 'none']},
{'name': 'shape-image-threshold'},
{'name': 'shape-margin', 'keywords': ['none']},
{'name': 'shape-outside', 'keywords': ['none']},
{
'name': 'shape-rendering',
'inherited': true,
'keywords': ['auto', 'optimizespeed', 'crispedges', 'geometricprecision']
},
{'name': 'size'},
{'name': 'size-adjust'},
{'name': 'source'},
{
'name': 'speak',
'inherited': true,
'keywords': ['none', 'normal', 'spell-out', 'digits', 'literal-punctuation', 'no-punctuation']
},
{'name': 'speak-as'},
{'name': 'src'},
{'name': 'start'},
{'name': 'stop-color', 'keywords': ['currentcolor']},
{'name': 'stop-opacity'},
{'name': 'stroke', 'inherited': true},
{'name': 'stroke-dasharray', 'inherited': true, 'keywords': ['none']},
{'name': 'stroke-dashoffset', 'inherited': true},
{'name': 'stroke-linecap', 'inherited': true, 'keywords': ['butt', 'round', 'square']},
{'name': 'stroke-linejoin', 'inherited': true, 'keywords': ['miter', 'bevel', 'round']},
{'name': 'stroke-miterlimit', 'inherited': true},
{'name': 'stroke-opacity', 'inherited': true},
{'name': 'stroke-width', 'inherited': true},
{'name': 'suffix'},
{'name': 'symbols'},
{'name': 'syntax'},
{'name': 'system'},
{'name': 'tab-size', 'inherited': true},
{'name': 'table-layout', 'keywords': ['auto', 'fixed']},
{
'name': 'text-align',
'inherited': true,
'keywords':
['left', 'right', 'center', 'justify', '-webkit-left', '-webkit-right', '-webkit-center', 'start', 'end']
},
{
'name': 'text-align-last',
'inherited': true,
'keywords': ['auto', 'start', 'end', 'left', 'right', 'center', 'justify']
},
{'name': 'text-anchor', 'inherited': true, 'keywords': ['start', 'middle', 'end']},
{'name': 'text-combine-upright', 'inherited': true, 'keywords': ['none', 'all']},
{
'longhands':
['text-decoration-line', 'text-decoration-thickness', 'text-decoration-style', 'text-decoration-color'],
'name': 'text-decoration'
},
{'name': 'text-decoration-color', 'keywords': ['currentcolor']},
{
'name': 'text-decoration-line',
'keywords': ['none', 'underline', 'overline', 'line-through', 'blink', 'spelling-error', 'grammar-error']
},
{'name': 'text-decoration-skip-ink', 'inherited': true, 'keywords': ['none', 'auto']},
{'name': 'text-decoration-style', 'keywords': ['solid', 'double', 'dotted', 'dashed', 'wavy']},
{'name': 'text-decoration-thickness', 'inherited': true, 'keywords': ['auto', 'from-font']},
{'longhands': ['text-emphasis-style', 'text-emphasis-color'], 'name': 'text-emphasis', 'inherited': true},
{'name': 'text-emphasis-color', 'inherited': true, 'keywords': ['currentcolor']},
{'name': 'text-emphasis-position', 'inherited': true},
{'name': 'text-emphasis-style', 'inherited': true},
{'name': 'text-indent', 'inherited': true},
{'name': 'text-justify', 'inherited': true, 'keywords': ['auto', 'none', 'inter-word', 'distribute']},
{'name': 'text-orientation', 'inherited': true, 'keywords': ['sideways', 'mixed', 'upright']},
{'name': 'text-overflow', 'keywords': ['clip', 'ellipsis']},
{
'name': 'text-rendering',
'inherited': true,
'keywords': ['auto', 'optimizespeed', 'optimizelegibility', 'geometricprecision']
},
{'name': 'text-shadow', 'inherited': true, 'keywords': ['none']},
{'name': 'text-size-adjust', 'inherited': true, 'keywords': ['none', 'auto']},
{
'name': 'text-transform',
'inherited': true,
'keywords': ['capitalize', 'uppercase', 'lowercase', 'none', 'math-auto']
},
{'name': 'text-underline-offset', 'inherited': true, 'keywords': ['auto']},
{'name': 'text-underline-position', 'inherited': true, 'keywords': ['auto', 'from-font', 'under', 'left', 'right']},
{'name': 'top', 'keywords': ['auto']},
{
'name': 'touch-action',
'keywords':
['auto', 'none', 'pan-x', 'pan-left', 'pan-right', 'pan-y', 'pan-up', 'pan-down', 'pinch-zoom', 'manipulation']
},
{'name': 'transform', 'keywords': ['none']},
{'name': 'transform-box', 'keywords': ['fill-box', 'view-box']},
{'name': 'transform-origin'},
{'name': 'transform-style', 'keywords': ['flat', 'preserve-3d']},
{
'longhands': ['transition-property', 'transition-duration', 'transition-timing-function', 'transition-delay'],
'name': 'transition'
},
{'name': 'transition-delay'},
{'name': 'transition-duration'},
{'name': 'transition-property', 'keywords': ['none']},
{
'name': 'transition-timing-function',
'keywords': [
'linear', 'ease', 'ease-in', 'ease-out', 'ease-in-out', 'jump-both', 'jump-end', 'jump-none', 'jump-start',
'step-start', 'step-end'
]
},
{'name': 'translate'},
{
'name': 'unicode-bidi',
'keywords': ['normal', 'embed', 'bidi-override', 'isolate', 'plaintext', 'isolate-override']
},
{'name': 'unicode-range'},
{'name': 'user-select', 'inherited': true, 'keywords': ['auto', 'none', 'text', 'all']},
{'name': 'user-zoom'},
{'name': 'vector-effect', 'keywords': ['none', 'non-scaling-stroke']},
{'name': 'vertical-align', 'keywords': ['baseline', 'sub', 'super', 'text-top', 'text-bottom', 'middle']},
{'name': 'viewport-fit'},
{'name': 'visibility', 'inherited': true, 'keywords': ['visible', 'hidden', 'collapse']},
{
'name': 'white-space',
'inherited': true,
'keywords': ['normal', 'pre', 'pre-wrap', 'pre-line', 'nowrap', '-webkit-nowrap', 'break-spaces']
},
{'name': 'widows', 'inherited': true},
{'name': 'width', 'keywords': ['auto', 'fit-content', 'min-content', 'max-content']},
{'keywords': ['auto'], 'name': 'will-change'},
{'name': 'word-break', 'inherited': true, 'keywords': ['normal', 'break-all', 'keep-all', 'break-word']},
{'inherited': true, 'keywords': ['normal'], 'name': 'word-spacing'},
{'name': 'writing-mode', 'inherited': true, 'keywords': ['horizontal-tb', 'vertical-rl', 'vertical-lr']},
{'name': 'x'},
{'name': 'y'},
{'name': 'z-index', 'keywords': ['auto']},
{'name': 'zoom'}
];
export const generatedPropertyValues = {
'-webkit-box-align': {'values': ['stretch', 'start', 'center', 'end', 'baseline']},
'-webkit-box-decoration-break': {'values': ['slice', 'clone']},
'-webkit-box-direction': {'values': ['normal', 'reverse']},
'-webkit-box-orient': {'values': ['horizontal', 'vertical']},
'-webkit-box-pack': {'values': ['start', 'center', 'end', 'justify']},
'-webkit-line-break': {'values': ['auto', 'loose', 'normal', 'strict', 'after-white-space', 'anywhere']},
'-webkit-print-color-adjust': {'values': ['economy', 'exact']},
'-webkit-rtl-ordering': {'values': ['logical', 'visual']},
'-webkit-ruby-position': {'values': ['before', 'after']},
'-webkit-text-security': {'values': ['none', 'disc', 'circle', 'square']},
'-webkit-user-drag': {'values': ['auto', 'none', 'element']},
'-webkit-user-modify': {'values': ['read-only', 'read-write', 'read-write-plaintext-only']},
'accent-color': {'values': ['auto', 'currentcolor']},
'alignment-baseline': {
'values': [
'auto', 'baseline', 'alphabetic', 'ideographic', 'middle', 'central', 'mathematical', 'before-edge',
'text-before-edge', 'after-edge', 'text-after-edge', 'hanging'
]
},
'animation-direction': {'values': ['normal', 'reverse', 'alternate', 'alternate-reverse']},
'animation-fill-mode': {'values': ['none', 'forwards', 'backwards', 'both']},
'animation-iteration-count': {'values': ['infinite']},
'animation-name': {'values': ['none']},
'animation-play-state': {'values': ['running', 'paused']},
'animation-timeline': {'values': ['none', 'auto']},
'animation-timing-function': {
'values': [
'linear', 'ease', 'ease-in', 'ease-out', 'ease-in-out', 'jump-both', 'jump-end', 'jump-none', 'jump-start',
'step-start', 'step-end'
]
},
'app-region': {'values': ['none', 'drag', 'no-drag']},
'aspect-ratio': {'values': ['auto']},
'backdrop-filter': {'values': ['none']},
'backface-visibility': {'values': ['visible', 'hidden']},
'background-attachment': {'values': ['scroll', 'fixed', 'local']},
'background-blend-mode': {
'values': [
'normal', 'multiply', 'screen', 'overlay', 'darken', 'lighten', 'color-dodge', 'color-burn', 'hard-light',
'soft-light', 'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity'
]
},
'background-clip': {'values': ['border-box', 'padding-box', 'content-box']},
'background-color': {'values': ['currentcolor']},
'background-image': {'values': ['auto', 'none']},
'background-origin': {'values': ['border-box', 'padding-box', 'content-box']},
'background-size': {'values': ['auto', 'cover', 'contain']},
'baseline-shift': {'values': ['baseline', 'sub', 'super']},
'block-size': {'values': ['auto']},
'border-bottom-color': {'values': ['currentcolor']},
'border-bottom-style':
{'values': ['none', 'hidden', 'inset', 'groove', 'outset', 'ridge', 'dotted', 'dashed', 'solid', 'double']},
'border-bottom-width': {'values': ['thin', 'medium', 'thick']},
'border-collapse': {'values': ['separate', 'collapse']},
'border-image-repeat': {'values': ['stretch', 'repeat', 'round', 'space']},
'border-image-source': {'values': ['none']},
'border-image-width': {'values': ['auto']},
'border-left-color': {'values': ['currentcolor']},
'border-left-style':
{'values': ['none', 'hidden', 'inset', 'groove', 'outset', 'ridge', 'dotted', 'dashed', 'solid', 'double']},
'border-left-width': {'values': ['thin', 'medium', 'thick']},
'border-right-color': {'values': ['currentcolor']},
'border-right-style':
{'values': ['none', 'hidden', 'inset', 'groove', 'outset', 'ridge', 'dotted', 'dashed', 'solid', 'double']},
'border-right-width': {'values': ['thin', 'medium', 'thick']},
'border-style': {'values': ['none']},
'border-top-color': {'values': ['currentcolor']},
'border-top-style':
{'values': ['none', 'hidden', 'inset', 'groove', 'outset', 'ridge', 'dotted', 'dashed', 'solid', 'double']},
'border-top-width': {'values': ['thin', 'medium', 'thick']},
'bottom': {'values': ['auto']},
'box-shadow': {'values': ['none']},
'box-sizing': {'values': ['content-box', 'border-box']},
'break-after':
{'values': ['auto', 'avoid', 'avoid-column', 'avoid-page', 'column', 'left', 'page', 'recto', 'right', 'verso']},
'break-before':
{'values': ['auto', 'avoid', 'avoid-column', 'avoid-page', 'column', 'left', 'page', 'recto', 'right', 'verso']},
'break-inside': {'values': ['auto', 'avoid', 'avoid-column', 'avoid-page']},
'buffered-rendering': {'values': ['auto', 'dynamic', 'static']},
'caption-side': {'values': ['top', 'bottom']},
'caret-color': {'values': ['auto', 'currentcolor']},
'clear': {'values': ['none', 'left', 'right', 'both', 'inline-start', 'inline-end']},
'clip': {'values': ['auto']},
'clip-path': {'values': ['none']},
'clip-rule': {'values': ['nonzero', 'evenodd']},
'color': {'values': ['currentcolor']},
'color-interpolation': {'values': ['auto', 'srgb', 'linearrgb']},
'color-interpolation-filters': {'values': ['auto', 'srgb', 'linearrgb']},
'color-rendering': {'values': ['auto', 'optimizespeed', 'optimizequality']},
'column-count': {'values': ['auto']},
'column-fill': {'values': ['balance', 'auto']},
'column-gap': {'values': ['normal']},
'column-rule-color': {'values': ['currentcolor']},
'column-rule-style':
{'values': ['none', 'hidden', 'inset', 'groove', 'outset', 'ridge', 'dotted', 'dashed', 'solid', 'double']},
'column-rule-width': {'values': ['thin', 'medium', 'thick']},
'column-span': {'values': ['none', 'all']},
'column-width': {'values': ['auto']},
'contain': {'values': ['none', 'strict', 'content', 'size', 'layout', 'style', 'paint', 'inline-size', 'block-size']},
'contain-intrinsic-height': {'values': ['auto', 'none']},
'contain-intrinsic-width': {'values': ['auto', 'none']},
'container-name': {'values': ['none']},
'container-type': {'values': ['none', 'block-size', 'inline-size', 'size']},
'content-visibility': {'values': ['visible', 'auto', 'hidden', 'hidden-matchable']},
'counter-increment': {'values': ['none']},
'counter-reset': {'values': ['none']},
'counter-set': {'values': ['none']},
'cursor': {
'values': [
'auto', 'default', 'none', 'context-menu', 'help', 'pointer', 'progress', 'wait',
'cell', 'crosshair', 'text', 'vertical-text', 'alias', 'copy', 'move', 'no-drop',
'not-allowed', 'e-resize', 'n-resize', 'ne-resize', 'nw-resize', 's-resize', 'se-resize', 'sw-resize',
'w-resize', 'ew-resize', 'ns-resize', 'nesw-resize', 'nwse-resize', 'col-resize', 'row-resize', 'all-scroll',
'zoom-in', 'zoom-out', 'grab', 'grabbing'
]
},
'd': {'values': ['none']},
'direction': {'values': ['ltr', 'rtl']},
'display': {
'values': [
'inline',
'block',
'list-item',
'inline-block',
'table',
'inline-table',
'table-row-group',
'table-header-group',
'table-footer-group',
'table-row',
'table-column-group',
'table-column',
'table-cell',
'table-caption',
'-webkit-box',
'-webkit-inline-box',
'flex',
'inline-flex',
'grid',
'inline-grid',
'contents',
'flow-root',
'none'
]
},
'dominant-baseline': {
'values': [
'auto', 'alphabetic', 'ideographic', 'middle', 'central', 'mathematical', 'hanging', 'use-script', 'no-change',
'reset-size', 'text-after-edge', 'text-before-edge'
]
},
'empty-cells': {'values': ['show', 'hide']},
'fill-rule': {'values': ['nonzero', 'evenodd']},
'filter': {'values': ['none']},
'flex-basis': {'values': ['auto', 'fit-content', 'min-content', 'max-content', 'content']},
'flex-direction': {'values': ['row', 'row-reverse', 'column', 'column-reverse']},
'flex-wrap': {'values': ['nowrap', 'wrap', 'wrap-reverse']},
'float': {'values': ['none', 'left', 'right', 'inline-start', 'inline-end']},
'flood-color': {'values': ['currentcolor']},
'font-feature-settings': {'values': ['normal']},
'font-kerning': {'values': ['auto', 'normal', 'none']},
'font-optical-sizing': {'values': ['auto', 'none']},
'font-palette': {'values': ['normal', 'light', 'dark']},
'font-size': {
'values': [
'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', 'xxx-large', 'larger', 'smaller',
'-webkit-xxx-large'
]
},
'font-size-adjust': {'values': ['none']},
'font-stretch': {
'values': [
'normal', 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'semi-expanded', 'expanded',
'extra-expanded', 'ultra-expanded'
]
},
'font-style': {'values': ['normal', 'italic', 'oblique']},
'font-synthesis-small-caps': {'values': ['auto', 'none']},
'font-synthesis-style': {'values': ['auto', 'none']},
'font-synthesis-weight': {'values': ['auto', 'none']},
'font-variant-caps': {
'values': ['normal', 'small-caps', 'all-small-caps', 'petite-caps', 'all-petite-caps', 'unicase', 'titling-caps']
},
'font-variant-east-asian': {
'values': [
'normal', 'jis78', 'jis83', 'jis90', 'jis04', 'simplified', 'traditional', 'full-width', 'proportional-width',
'ruby'
]
},
'font-variant-ligatures': {
'values': [
'normal', 'none', 'common-ligatures', 'no-common-ligatures', 'discretionary-ligatures',
'no-discretionary-ligatures', 'historical-ligatures', 'no-historical-ligatures', 'contextual', 'no-contextual'
]
},
'font-variant-numeric': {
'values': [
'normal', 'lining-nums', 'oldstyle-nums', 'proportional-nums', 'tabular-nums', 'diagonal-fractions',
'stacked-fractions', 'ordinal', 'slashed-zero'
]
},
'font-variation-settings': {'values': ['normal']},
'font-weight': {'values': ['normal', 'bold', 'bolder', 'lighter']},
'forced-color-adjust': {'values': ['auto', 'none', 'preserve-parent-color']},
'grid-auto-columns': {'values': ['auto', 'min-content', 'max-content']},
'grid-auto-flow': {'values': ['row', 'column']},
'grid-auto-rows': {'values': ['auto', 'min-content', 'max-content']},
'grid-column-end': {'values': ['auto']},
'grid-column-start': {'values': ['auto']},
'grid-row-end': {'values': ['auto']},
'grid-row-start': {'values': ['auto']},
'grid-template-areas': {'values': ['none']},
'grid-template-columns': {'values': ['none']},
'grid-template-rows': {'values': ['none']},
'height': {'values': ['auto', 'fit-content', 'min-content', 'max-content']},
'hyphens': {'values': ['none', 'manual', 'auto']},
'image-rendering': {'values': ['auto', 'optimizespeed', 'optimizequality', '-webkit-optimize-contrast', 'pixelated']},
'inline-size': {'values': ['auto']},
'isolation': {'values': ['auto', 'isolate']},
'left': {'values': ['auto']},
'letter-spacing': {'values': ['normal']},
'lighting-color': {'values': ['currentcolor']},
'line-break': {'values': ['auto', 'loose', 'normal', 'strict', 'anywhere']},
'line-height': {'values': ['normal']},
'list-style-image': {'values': ['none']},
'list-style-position': {'values': ['outside', 'inside']},
'list-style-type':
{'values': ['disc', 'circle', 'square', 'disclosure-open', 'disclosure-closed', 'decimal', 'none']},
'margin-block-end': {'values': ['auto']},
'margin-block-start': {'values': ['auto']},
'margin-bottom': {'values': ['auto']},
'margin-inline-end': {'values': ['auto']},
'margin-inline-start': {'values': ['auto']},
'margin-left': {'values': ['auto']},
'margin-right': {'values': ['auto']},
'margin-top': {'values': ['auto']},
'marker-end': {'values': ['none']},
'marker-mid': {'values': ['none']},
'marker-start': {'values': ['none']},
'mask-type': {'values': ['luminance', 'alpha']},
'math-shift': {'values': ['normal', 'compact']},
'math-style': {'values': ['normal', 'compact']},
'max-block-size': {'values': ['none']},
'max-height': {'values': ['none']},
'max-inline-size': {'values': ['none']},
'max-width': {'values': ['none']},
'mix-blend-mode': {
'values': [
'normal', 'multiply', 'screen', 'overlay', 'darken', 'lighten', 'color-dodge', 'color-burn', 'hard-light',
'soft-light', 'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity', 'plus-lighter'
]
},
'object-fit': {'values': ['fill', 'contain', 'cover', 'none', 'scale-down']},
'offset-anchor': {'values': ['auto']},
'offset-path': {'values': ['none']},
'offset-position': {'values': ['auto']},
'offset-rotate': {'values': ['auto', 'reverse']},
'origin-trial-test-property': {'values': ['normal', 'none']},
'outline-color': {'values': ['currentcolor']},
'outline-style':
{'values': ['none', 'hidden', 'inset', 'groove', 'outset', 'ridge', 'dotted', 'dashed', 'solid', 'double']},
'outline-width': {'values': ['thin', 'medium', 'thick']},
'overflow-anchor': {'values': ['visible', 'none', 'auto']},
'overflow-wrap': {'values': ['normal', 'break-word', 'anywhere']},
'overflow-x': {'values': ['visible', 'hidden', 'scroll', 'auto', 'overlay', 'clip']},
'overflow-y': {'values': ['visible', 'hidden', 'scroll', 'auto', 'overlay', 'clip']},
'overscroll-behavior-x': {'values': ['auto', 'contain', 'none']},
'overscroll-behavior-y': {'values': ['auto', 'contain', 'none']},
'page': {'values': ['auto']},
'paint-order': {'values': ['normal', 'fill', 'stroke', 'markers']},
'perspective': {'values': ['none']},
'pointer-events': {
'values': [
'none', 'auto', 'stroke', 'fill', 'painted', 'visible', 'visiblestroke', 'visiblefill', 'visiblepainted',
'bounding-box', 'all'
]
},
'position': {'values': ['static', 'relative', 'absolute', 'fixed', 'sticky']},
'quotes': {'values': ['auto', 'none']},
'resize': {'values': ['none', 'both', 'horizontal', 'vertical', 'block', 'inline']},
'right': {'values': ['auto']},
'row-gap': {'values': ['normal']},
'rx': {'values': ['auto']},
'ry': {'values': ['auto']},
'scroll-behavior': {'values': ['auto', 'smooth']},
'scroll-padding-block-end': {'values': ['auto']},
'scroll-padding-block-start': {'values': ['auto']},
'scroll-padding-bottom': {'values': ['auto']},
'scroll-padding-inline-end': {'values': ['auto']},
'scroll-padding-inline-start': {'values': ['auto']},
'scroll-padding-left': {'values': ['auto']},
'scroll-padding-right': {'values': ['auto']},
'scroll-padding-top': {'values': ['auto']},
'scroll-snap-align': {'values': ['none', 'start', 'end', 'center']},
'scroll-snap-stop': {'values': ['normal', 'always']},
'scroll-snap-type': {'values': ['none', 'x', 'y', 'block', 'inline', 'both', 'mandatory', 'proximity']},
'scrollbar-gutter': {'values': ['auto', 'stable', 'both-edges']},
'scrollbar-width': {'values': ['auto', 'thin', 'none']},
'shape-margin': {'values': ['none']},
'shape-outside': {'values': ['none']},
'shape-rendering': {'values': ['auto', 'optimizespeed', 'crispedges', 'geometricprecision']},
'speak': {'values': ['none', 'normal', 'spell-out', 'digits', 'literal-punctuation', 'no-punctuation']},
'stop-color': {'values': ['currentcolor']},
'stroke-dasharray': {'values': ['none']},
'stroke-linecap': {'values': ['butt', 'round', 'square']},
'stroke-linejoin': {'values': ['miter', 'bevel', 'round']},
'table-layout': {'values': ['auto', 'fixed']},
'text-align': {
'values': ['left', 'right', 'center', 'justify', '-webkit-left', '-webkit-right', '-webkit-center', 'start', 'end']
},
'text-align-last': {'values': ['auto', 'start', 'end', 'left', 'right', 'center', 'justify']},
'text-anchor': {'values': ['start', 'middle', 'end']},
'text-combine-upright': {'values': ['none', 'all']},
'text-decoration-color': {'values': ['currentcolor']},
'text-decoration-line':
{'values': ['none', 'underline', 'overline', 'line-through', 'blink', 'spelling-error', 'grammar-error']},
'text-decoration-skip-ink': {'values': ['none', 'auto']},
'text-decoration-style': {'values': ['solid', 'double', 'dotted', 'dashed', 'wavy']},
'text-decoration-thickness': {'values': ['auto', 'from-font']},
'text-emphasis-color': {'values': ['currentcolor']},
'text-justify': {'values': ['auto', 'none', 'inter-word', 'distribute']},
'text-orientation': {'values': ['sideways', 'mixed', 'upright']},
'text-overflow': {'values': ['clip', 'ellipsis']},
'text-rendering': {'values': ['auto', 'optimizespeed', 'optimizelegibility', 'geometricprecision']},
'text-shadow': {'values': ['none']},
'text-size-adjust': {'values': ['none', 'auto']},
'text-transform': {'values': ['capitalize', 'uppercase', 'lowercase', 'none', 'math-auto']},
'text-underline-offset': {'values': ['auto']},
'text-underline-position': {'values': ['auto', 'from-font', 'under', 'left', 'right']},
'top': {'values': ['auto']},
'touch-action': {
'values':
['auto', 'none', 'pan-x', 'pan-left', 'pan-right', 'pan-y', 'pan-up', 'pan-down', 'pinch-zoom', 'manipulation']
},
'transform': {'values': ['none']},
'transform-box': {'values': ['fill-box', 'view-box']},
'transform-style': {'values': ['flat', 'preserve-3d']},
'transition-property': {'values': ['none']},
'transition-timing-function': {
'values': [
'linear', 'ease', 'ease-in', 'ease-out', 'ease-in-out', 'jump-both', 'jump-end', 'jump-none', 'jump-start',
'step-start', 'step-end'
]
},
'unicode-bidi': {'values': ['normal', 'embed', 'bidi-override', 'isolate', 'plaintext', 'isolate-override']},
'user-select': {'values': ['auto', 'none', 'text', 'all']},
'vector-effect': {'values': ['none', 'non-scaling-stroke']},
'vertical-align': {'values': ['baseline', 'sub', 'super', 'text-top', 'text-bottom', 'middle']},
'visibility': {'values': ['visible', 'hidden', 'collapse']},
'white-space': {'values': ['normal', 'pre', 'pre-wrap', 'pre-line', 'nowrap', '-webkit-nowrap', 'break-spaces']},
'width': {'values': ['auto', 'fit-content', 'min-content', 'max-content']},
'will-change': {'values': ['auto']},
'word-break': {'values': ['normal', 'break-all', 'keep-all', 'break-word']},
'word-spacing': {'values': ['normal']},
'writing-mode': {'values': ['horizontal-tb', 'vertical-rl', 'vertical-lr']},
'z-index': {'values': ['auto']}
};
export const generatedAliasesFor = new Map([
['-epub-caption-side', 'caption-side'],
['-epub-text-combine', '-webkit-text-combine'],
['-epub-text-emphasis', 'text-emphasis'],
['-epub-text-emphasis-color', 'text-emphasis-color'],
['-epub-text-emphasis-style', 'text-emphasis-style'],
['-epub-text-orientation', '-webkit-text-orientation'],
['-epub-text-transform', 'text-transform'],
['-epub-word-break', 'word-break'],
['-epub-writing-mode', '-webkit-writing-mode'],
['-webkit-align-content', 'align-content'],
['-webkit-align-items', 'align-items'],
['-webkit-align-self', 'align-self'],
['-webkit-animation', 'animation'],
['-webkit-animation-delay', 'animation-delay'],
['-webkit-animation-direction', 'animation-direction'],
['-webkit-animation-duration', 'animation-duration'],
['-webkit-animation-fill-mode', 'animation-fill-mode'],
['-webkit-animation-iteration-count', 'animation-iteration-count'],
['-webkit-animation-name', 'animation-name'],
['-webkit-animation-play-state', 'animation-play-state'],
['-webkit-animation-timing-function', 'animation-timing-function'],
['-webkit-app-region', 'app-region'],
['-webkit-appearance', 'appearance'],
['-webkit-backface-visibility', 'backface-visibility'],
['-webkit-background-clip', 'background-clip'],
['-webkit-background-origin', 'background-origin'],
['-webkit-background-size', 'background-size'],
['-webkit-border-after', 'border-block-end'],
['-webkit-border-after-color', 'border-block-end-color'],
['-webkit-border-after-style', 'border-block-end-style'],
['-webkit-border-after-width', 'border-block-end-width'],
['-webkit-border-before', 'border-block-start'],
['-webkit-border-before-color', 'border-block-start-color'],
['-webkit-border-before-style', 'border-block-start-style'],
['-webkit-border-before-width', 'border-block-start-width'],
['-webkit-border-bottom-left-radius', 'border-bottom-left-radius'],
['-webkit-border-bottom-right-radius', 'border-bottom-right-radius'],
['-webkit-border-end', 'border-inline-end'],
['-webkit-border-end-color', 'border-inline-end-color'],
['-webkit-border-end-style', 'border-inline-end-style'],
['-webkit-border-end-width', 'border-inline-end-width'],
['-webkit-border-radius', 'border-radius'],
['-webkit-border-start', 'border-inline-start'],
['-webkit-border-start-color', 'border-inline-start-color'],
['-webkit-border-start-style', 'border-inline-start-style'],
['-webkit-border-start-width', 'border-inline-start-width'],
['-webkit-border-top-left-radius', 'border-top-left-radius'],
['-webkit-border-top-right-radius', 'border-top-right-radius'],
['-webkit-box-shadow', 'box-shadow'],
['-webkit-box-sizing', 'box-sizing'],
['-webkit-clip-path', 'clip-path'],
['-webkit-column-count', 'column-count'],
['-webkit-column-gap', 'column-gap'],
['-webkit-column-rule', 'column-rule'],
['-webkit-column-rule-color', 'column-rule-color'],
['-webkit-column-rule-style', 'column-rule-style'],
['-webkit-column-rule-width', 'column-rule-width'],
['-webkit-column-span', 'column-span'],
['-webkit-column-width', 'column-width'],
['-webkit-columns', 'columns'],
['-webkit-filter', 'filter'],
['-webkit-flex', 'flex'],
['-webkit-flex-basis', 'flex-basis'],
['-webkit-flex-direction', 'flex-direction'],
['-webkit-flex-flow', 'flex-flow'],
['-webkit-flex-grow', 'flex-grow'],
['-webkit-flex-shrink', 'flex-shrink'],
['-webkit-flex-wrap', 'flex-wrap'],
['-webkit-font-feature-settings', 'font-feature-settings'],
['-webkit-justify-content', 'justify-content'],
['-webkit-logical-height', 'block-size'],
['-webkit-logical-width', 'inline-size'],
['-webkit-margin-after', 'margin-block-end'],
['-webkit-margin-before', 'margin-block-start'],
['-webkit-margin-end', 'margin-inline-end'],
['-webkit-margin-start', 'margin-inline-start'],
['-webkit-max-logical-height', 'max-block-size'],
['-webkit-max-logical-width', 'max-inline-size'],
['-webkit-min-logical-height', 'min-block-size'],
['-webkit-min-logical-width', 'min-inline-size'],
['-webkit-opacity', 'opacity'],
['-webkit-order', 'order'],
['-webkit-padding-after', 'padding-block-end'],
['-webkit-padding-before', 'padding-block-start'],
['-webkit-padding-end', 'padding-inline-end'],
['-webkit-padding-start', 'padding-inline-start'],
['-webkit-perspective', 'perspective'],
['-webkit-perspective-origin', 'perspective-origin'],
['-webkit-shape-image-threshold', 'shape-image-threshold'],
['-webkit-shape-margin', 'shape-margin'],
['-webkit-shape-outside', 'shape-outside'],
['-webkit-text-emphasis', 'text-emphasis'],
['-webkit-text-emphasis-color', 'text-emphasis-color'],
['-webkit-text-emphasis-position', 'text-emphasis-position'],
['-webkit-text-emphasis-style', 'text-emphasis-style'],
['-webkit-text-size-adjust', 'text-size-adjust'],
['-webkit-transform', 'transform'],
['-webkit-transform-origin', 'transform-origin'],
['-webkit-transform-style', 'transform-style'],
['-webkit-transition', 'transition'],
['-webkit-transition-delay', 'transition-delay'],
['-webkit-transition-duration', 'transition-duration'],
['-webkit-transition-property', 'transition-property'],
['-webkit-transition-timing-function', 'transition-timing-function'],
['-webkit-user-select', 'user-select'],
['word-wrap', 'overflow-wrap']
]);
| ChromeDevTools/devtools-frontend | front_end/generated/SupportedCSSProperties.js | JavaScript | bsd-3-clause | 63,358 |
/*!
* Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file.
*/
import runAbstractStorageAdapterSpec from '@webex/storage-adapter-spec';
import {skipInNode} from '@webex/test-helper-mocha';
import StorageAdapterLocalForage from '@webex/storage-adapter-local-forage';
skipInNode(describe)('StorageAdapterLocalFtorage', () => {
runAbstractStorageAdapterSpec(new StorageAdapterLocalForage('test'));
});
| aimeex3/spark-js-sdk | packages/node_modules/@webex/storage-adapter-local-forage/test/unit/spec/storage-adapter-local-forage.js | JavaScript | mit | 413 |
var expect = require('expect.js');
var stub = require('sinon').stub;
var PopupHandler = require('../../src/helper/popup-handler');
var MockAuth0Plugin = require('../mock/mock-auth0-plugin');
var WebAuth = require('../../src/web-auth');
var version = require('../../src/version');
describe('auth0.WebAuth extensibility', function () {
context('validations', function () {
it('should validate the plugin version (must throw)', function() {
expect(function() {
var webAuth = new WebAuth({
domain: 'test.auth0.com',
clientID: '...',
responseType: 'token id_token',
plugins: [
new MockAuth0Plugin({ version: 'v1.0.0' })
]
});
}).to.throwException(function (e) {
expect(e.message).to.be('Plugin MockPlugin version (v1.0.0) is not compatible with the SDK version (' + version.raw + ')');
});
})
it('should validate the plugin version', function() {
var plugin = new MockAuth0Plugin();
var webAuth = new WebAuth({
domain: 'test.auth0.com',
clientID: '...',
responseType: 'token id_token',
plugins: [
plugin
]
});
expect(plugin.webAuth).to.be(webAuth);
})
});
context('buildPopupHandler', function () {
before(function(){
this.webAuth = new WebAuth({
domain: 'test.auth0.com',
clientID: '...',
responseType: 'token id_token',
plugins: [
new MockAuth0Plugin({extensibilityPoints: 'popup.getPopupHandler', handler: {
getPopupHandler: function() {
return 'CustomPopupHandler';
}
}
})
]
});
})
it('should get the popup handler from the plugin', function() {
var popupHandler = this.webAuth.popup.buildPopupHandler();
expect(popupHandler).to.eql('CustomPopupHandler');
});
});
context('overrdide popup.authorize params', function () {
before(function(){
this.webAuth = new WebAuth({
domain: 'test.auth0.com',
clientID: '...',
responseType: 'token id_token',
plugins: [
new MockAuth0Plugin({extensibilityPoints: 'popup.authorize', handler: {
processParams: function(params) {
params.redirectUri = 'http://custom-url.com';
params.responseType = 'code';
return params;
}
}
})
],
_sendTelemetry: false
});
})
after(function () {
PopupHandler.prototype.load.restore();
});
it('should change the content of the params', function(done) {
stub(PopupHandler.prototype, 'load', function(url, relayUrl, options, cb) {
expect(url).to.be('https://test.auth0.com/authorize?client_id=...&response_type=code&owp=true&redirect_uri=http%3A%2F%2Fcustom-url.com');
expect(relayUrl).to.be('https://test.auth0.com/relay.html');
expect(options).to.eql({});
cb(null, {
email_verified: false,
email: 'me@example.com'
});
});
this.webAuth.popup.authorize({owp: true}, function (err, data) {
expect(err).to.be(null);
expect(data).to.eql({
emailVerified: false,
email: 'me@example.com'
});
done();
});
});
});
}); | saphocom/auth0.js | test/web-auth/extensibility.test.js | JavaScript | mit | 3,378 |
define({
"_widgetLabel": "Kesadaran Situasi",
"locate_incident": "Cari Lokasi Insiden",
"reverse_geocoded_address": "Alamat Terdekat",
"reverse_geocoded_error": "Tidak tersedia",
"actionLabel": "Atur Lokasi",
"drawPoint": "Gambar titik",
"drawLine": "Gambar garis",
"drawPolygon": "Gambar poligon",
"saveIncident": "Simpan",
"clearIncident": "Mulai Ulang",
"noFeaturesFound": "Fitur tidak ditemukan.",
"downloadCSV": "Unduh",
"sum": "Jumlah",
"min": "Minimal",
"max": "Maksimal",
"avg": "Rata-rata",
"count": "COUNT",
"area": "AREA",
"length": "PANJANG",
"update_btn": "Selesai",
"delete_btn": "Hapus",
"get_directions": "Dapatkan Arah",
"incident": "Insiden",
"incidents": "Insiden",
"buffer": "Buffer",
"buffers": "Buffer",
"_featureAction_ActionLabel": "Atur Lokasi",
"_featureAction_AddRemoveActionLabel": "Tambah/Buang Lokasi",
"snapshot": "Folder SnapShot dibuat menurut id Aplikasi:",
"user_credentials": "Pengguna tidak memiliki hak istimewa yang valid.",
"notPolySnapShot": "Harap tentukan jarak buffer sebelum membuat snapshot.",
"notPolyReport": "Tidak ada hasil yang valid untuk ditambahkan ke laporan.",
"notValidDownload": "Tidak ada hasil valid untuk diunduh.",
"of_append": "dari",
"layer_append": "layer",
"downloadAll": "Unduh semua",
"createSnapshot": "Buat snapshot.",
"createReport": "Buat laporan",
"calculated_results": "Informasi Ringkas",
"closest": "Fitur Terdekat",
"proximity": "Kedekatan",
"summary": "Ringkasan",
"groupedSummary": "Jumlah yang Dikelompokkan",
"_count": "Jumlah",
"approximate": "mendekati",
"snapshot_name": "Atur Properti Snapshot",
"report_name": "Atur Properti Laporan",
"invalid_snapshot_name": "Nama snapshot tidak valid.",
"invalid_report_name": "Judul laporan tidak valid.",
"orientation": "Orientasi",
"pageSize": "Ukuran Halaman",
"comments": "Komentar",
"choose_group": "Grup",
"forecast": "Ramalan",
"select_group": "Pilih Grup",
"select_group_instruction": "Snapshot akan dibuat dan dibagikan dengan grup yang dipilih",
"information_append": " Informasi",
"distance": "JARAK",
"buffer_invalid": "Masukkan angka valid antara ${min} dan ${max}",
"layerNotAvalible": "Layer Tidak Ditemukan",
"missingLayer": "Nama: ${name}",
"missingLayerHint": "Satu layer atau lebih yang direferensikan dalam konfigurasi saat ini tidak tersedia.",
"zoomToFeature": "Fitur zoom hingga"
}); | tmcgee/cmv-wab-widgets | wab/2.15/widgets/SituationAwareness/nls/id/strings.js | JavaScript | mit | 2,455 |