Best JavaScript code snippet using cypress
detect-server-settings.js
Source:detect-server-settings.js
...15const formatValue = (str) => chalk.green(`'${str}'`)16const readHttpsSettings = async (options) => {17 if (!isPlainObject(options)) {18 throw new TypeError(19 `https options should be an object with ${formatProperty('keyFile')} and ${formatProperty(20 'certFile',21 )} string properties`,22 )23 }24 const { keyFile, certFile } = options25 if (typeof keyFile !== 'string') {26 throw new TypeError(`Private key file configuration should be a string`)27 }28 if (typeof certFile !== 'string') {29 throw new TypeError(`Certificate file configuration should be a string`)30 }31 const [{ content: key, error: keyError }, { content: cert, error: certError }] = await Promise.all([32 readFileAsyncCatchError(keyFile),33 readFileAsyncCatchError(certFile),34 ])35 if (keyError) {36 throw new Error(`Error reading private key file: ${keyError.message}`)37 }38 if (certError) {39 throw new Error(`Error reading certificate file: ${certError.message}`)40 }41 return { key, cert }42}43const validateStringProperty = ({ devConfig, property }) => {44 if (devConfig[property] && typeof devConfig[property] !== 'string') {45 const formattedProperty = formatProperty(property)46 throw new TypeError(47 `Invalid ${formattedProperty} option provided in config. The value of ${formattedProperty} option must be a string`,48 )49 }50}51const validateNumberProperty = ({ devConfig, property }) => {52 if (devConfig[property] && typeof devConfig[property] !== 'number') {53 const formattedProperty = formatProperty(property)54 throw new TypeError(55 `Invalid ${formattedProperty} option provided in config. The value of ${formattedProperty} option must be an integer`,56 )57 }58}59const validateFrameworkConfig = ({ devConfig }) => {60 validateStringProperty({ devConfig, property: 'command' })61 validateNumberProperty({ devConfig, property: 'port' })62 validateNumberProperty({ devConfig, property: 'targetPort' })63 if (devConfig.targetPort && devConfig.targetPort === devConfig.port) {64 throw new Error(65 `${formatProperty('port')} and ${formatProperty(66 'targetPort',67 )} options cannot have same values. Please consult the documentation for more details: https://cli.netlify.com/netlify-dev#netlifytoml-dev-block`,68 )69 }70}71const validateConfiguredPort = ({ devConfig, detectedPort }) => {72 if (devConfig.port && devConfig.port === detectedPort) {73 const formattedPort = formatProperty('port')74 throw new Error(75 `The ${formattedPort} option you specified conflicts with the port of your application. Please use a different value for ${formattedPort}`,76 )77 }78}79const DEFAULT_PORT = 888880const DEFAULT_STATIC_PORT = 399981const getDefaultDist = () => {82 log(`${NETLIFYDEVWARN} Unable to determine public folder to serve files from. Using current working directory`)83 log(`${NETLIFYDEVWARN} Setup a netlify.toml file with a [dev] section to specify your dev server settings.`)84 log(`${NETLIFYDEVWARN} See docs at: https://cli.netlify.com/netlify-dev#project-detection`)85 return process.cwd()86}87const handleStaticServer = async ({ flags, devConfig, projectDir }) => {88 validateNumberProperty({ devConfig, property: 'staticServerPort' })89 if (flags.dir) {90 log(`${NETLIFYDEVWARN} Using simple static server because ${formatProperty('--dir')} flag was specified`)91 } else if (devConfig.framework === '#static') {92 log(93 `${NETLIFYDEVWARN} Using simple static server because ${formatProperty(94 '[dev.framework]',95 )} was set to ${formatValue('#static')}`,96 )97 }98 if (devConfig.command) {99 log(100 `${NETLIFYDEVWARN} Ignoring command setting since using a simple static server. Configure ${formatProperty(101 'command',102 )} ${chalk.bold('and')} ${formatProperty('targetPort')} for a custom setup`,103 )104 }105 if (devConfig.targetPort) {106 log(107 `${NETLIFYDEVWARN} Ignoring ${formatProperty(108 'targetPort',109 )} setting since using a simple static server.${EOL}${NETLIFYDEVWARN} Use --staticServerPort or [dev.staticServerPort] to configure the static server port`,110 )111 }112 const dist = flags.dir || devConfig.publish || getDefaultDist()113 log(`${NETLIFYDEVWARN} Running static server from "${path.relative(path.dirname(projectDir), dist)}"`)114 const frameworkPort = await acquirePort({115 configuredPort: devConfig.staticServerPort,116 defaultPort: DEFAULT_STATIC_PORT,117 errorMessage: 'Could not acquire configured static server port',118 })119 return {120 useStaticServer: true,121 frameworkPort,122 dist,123 }124}125const getSettingsFromFramework = (framework) => {126 const {127 build: { directory: dist },128 dev: {129 commands: [command],130 port: frameworkPort,131 pollingStrategies,132 },133 name: frameworkName,134 staticAssetsDirectory: staticDir,135 env,136 } = framework137 return {138 command,139 frameworkPort,140 dist: staticDir || dist,141 framework: frameworkName,142 env,143 pollingStrategies: pollingStrategies.map(({ name }) => name),144 }145}146const hasDevCommand = (framework) => Array.isArray(framework.dev.commands) && framework.dev.commands.length !== 0147const detectFrameworkSettings = async ({ projectDir }) => {148 const frameworks = (await listFrameworks({ projectDir })).filter((framework) => hasDevCommand(framework))149 if (frameworks.length === 1) {150 return getSettingsFromFramework(frameworks[0])151 }152 if (frameworks.length > 1) {153 // performance optimization, load inquirer on demand154 // eslint-disable-next-line node/global-require155 const inquirer = require('inquirer')156 // eslint-disable-next-line node/global-require157 const inquirerAutocompletePrompt = require('inquirer-autocomplete-prompt')158 /** multiple matching detectors, make the user choose */159 inquirer.registerPrompt('autocomplete', inquirerAutocompletePrompt)160 const scriptInquirerOptions = formatSettingsArrForInquirer(frameworks)161 const { chosenFramework } = await inquirer.prompt({162 name: 'chosenFramework',163 message: `Multiple possible start commands found`,164 type: 'autocomplete',165 source(_, input) {166 if (!input || input === '') {167 return scriptInquirerOptions168 }169 // only show filtered results170 return filterSettings(scriptInquirerOptions, input)171 },172 })173 log(174 `Add ${formatProperty(175 `framework = "${chosenFramework.id}"`,176 )} to the [dev] section of your netlify.toml to avoid this selection prompt next time`,177 )178 return getSettingsFromFramework(chosenFramework)179 }180}181const hasCommandAndTargetPort = ({ devConfig }) => devConfig.command && devConfig.targetPort182const handleCustomFramework = ({ devConfig }) => {183 if (!hasCommandAndTargetPort({ devConfig })) {184 throw new Error(185 `${formatProperty('command')} and ${formatProperty('targetPort')} properties are required when ${formatProperty(186 'framework',187 )} is set to ${formatValue('#custom')}`,188 )189 }190 return {191 command: devConfig.command,192 frameworkPort: devConfig.targetPort,193 dist: devConfig.publish || getDefaultDist(),194 framework: '#custom',195 pollingStrategies: devConfig.pollingStrategies || [],196 }197}198const handleForcedFramework = async ({ devConfig, projectDir }) => {199 // this throws if `devConfig.framework` is not a supported framework200 const { command, frameworkPort, dist, framework, env, pollingStrategies } = getSettingsFromFramework(201 await getFramework(devConfig.framework, { projectDir }),202 )203 return {204 command: devConfig.command || command,205 frameworkPort: devConfig.targetPort || frameworkPort,206 dist: devConfig.publish || dist,207 framework,208 env,209 pollingStrategies,210 }211}212const detectServerSettings = async (devConfig, flags, projectDir) => {213 validateStringProperty({ devConfig, property: 'framework' })214 let settings = {}215 if (flags.dir || devConfig.framework === '#static') {216 // serving files statically without a framework server217 settings = await handleStaticServer({ flags, devConfig, projectDir })218 } else if (devConfig.framework === '#auto') {219 // this is the default CLI behavior220 // we don't need to run the detection if both command and targetPort are configured221 const runDetection = !hasCommandAndTargetPort({ devConfig })222 const frameworkSettings = runDetection ? await detectFrameworkSettings({ projectDir }) : undefined223 if (frameworkSettings === undefined && runDetection) {224 log(`${NETLIFYDEVWARN} No app server detected. Using simple static server`)225 settings = await handleStaticServer({ flags, devConfig, projectDir })226 } else {227 validateFrameworkConfig({ devConfig })228 const { command, frameworkPort, dist, framework, env, pollingStrategies = [] } = frameworkSettings || {}229 settings = {230 command: devConfig.command || command,231 frameworkPort: devConfig.targetPort || frameworkPort,232 dist: devConfig.publish || dist || getDefaultDist(),233 framework,234 env,235 pollingStrategies,236 }237 }238 } else if (devConfig.framework === '#custom') {239 validateFrameworkConfig({ devConfig })240 // when the users wants to configure `command` and `targetPort`241 settings = handleCustomFramework({ devConfig })242 } else if (devConfig.framework) {243 validateFrameworkConfig({ devConfig })244 // this is when the user explicitly configures a framework, e.g. `framework = "gatsby"`245 settings = await handleForcedFramework({ devConfig, projectDir })246 }247 validateConfiguredPort({ devConfig, detectedPort: settings.frameworkPort })248 const acquiredPort = await acquirePort({249 configuredPort: devConfig.port,250 defaultPort: DEFAULT_PORT,251 errorMessage: `Could not acquire required ${formatProperty('port')}`,252 })253 const functionsDir = devConfig.functions || settings.functions254 const internalFunctionsDir = await getInternalFunctionsDir({ base: projectDir })255 const shouldStartFunctionsServer = Boolean(functionsDir || internalFunctionsDir)256 return {257 ...settings,258 port: acquiredPort,259 jwtSecret: devConfig.jwtSecret || 'secret',260 jwtRolePath: devConfig.jwtRolePath || 'app_metadata.authorization.roles',261 functions: functionsDir,262 ...(shouldStartFunctionsServer && { functionsPort: await getPort({ port: devConfig.functionsPort || 0 }) }),263 ...(devConfig.https && { https: await readHttpsSettings(devConfig.https) }),264 }265}...
parsers.js
Source:parsers.js
1;(function() {2 "use strict";3 var xml2js = require("xml2js");4 var parser = new xml2js.Parser();5 var cap = require("../lib/capitalize.js");6 var clean = require("../lib/cleanobj.js");7 var serviceArrays = require("../config/serverConfig").map.serviceArrays;8 function toTitleCase(str) {9 return str.replace(/\w\S*/g, function(txt) {return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});10 }11 function streetworksApiParser (xml) {12 var json = {};13 parser.parseString(xml, function(err, result) {14 if (result.hasOwnProperty("Locations") && typeof result !== "undefined" && result.hasOwnProperty("Locations") && result.Locations.hasOwnProperty("StreetWorks")) {15 json.location = {};16 json.location.Area = result.Locations.$.postcode;17 json.location.Latitude = result.Locations.$.Lat;18 json.location.Longitude = result.Locations.$.Lng;19 json.properties = [];20 result.Locations.StreetWorks.map(function(p) {21 var formattedProperty = {};22 formattedProperty.Longitude = p.$.Lng;23 formattedProperty.Latitude = p.$.Lat;24 formattedProperty.LAref = p.$.LAref;25 formattedProperty.externalref = p.$.externalref;26 formattedProperty.display = {};27 formattedProperty.display.Organisation = p.$.Organisation;28 formattedProperty.display.Name = p.$.Street + " - " + p.$.externalref.split("-")[p.$.externalref.split("-").length - 1];29 formattedProperty.display.StartDate = p.$.StartDate;30 formattedProperty.display.EndDate = p.$.EndDate;31 formattedProperty.display.Telephone = p.$.Telephone;32 formattedProperty.display.Street = p.$.Street;33 formattedProperty.display.Description = p.$.Description;34 formattedProperty.display = clean(formattedProperty.display);35 formattedProperty = clean(formattedProperty);36 json.properties.push(formattedProperty);37 });38 } else {39 return {40 error: "Service Not Found",41 message: "Sorry, we could not find the right information on that service or location"42 };43 }44 });45 return json;46 }47 function localInformationApiParser (xml) {48 var json = {};49 parser.parseString(xml, function(err, result) {50 json.location = {};51 if(typeof result !== "undefined" && result.hasOwnProperty("Locations") && result.Locations.hasOwnProperty("AddressSearchResults")) {52 json.location.Area = result.Locations.AddressSearchResults[0].$.sPostcode;53 json.location.Latitude = result.Locations.AddressSearchResults[0].$.Latitude;54 json.location.Longitude = result.Locations.AddressSearchResults[0].$.Longitude;55 json.location.BuildingName = result.Locations.AddressSearchResults[0].$.sBuildingName;56 json.location.Street = result.Locations.AddressSearchResults[0].$.sStreet;57 } else {58 return {59 error: "Service Not Found",60 message: "Sorry, we could not find the right information on that location"61 };62 }63 json.information = {};64 if(result.Locations.hasOwnProperty("LocalInformation") && result.Locations.LocalInformation[0].hasOwnProperty("Table")) {65 result.Locations.LocalInformation[0].Table.map(function(p) {66 json.information[p.$.TableDesc] = {};67 json.information[p.$.TableDesc].Value = p.Object[0].$.ObjectDesc;68 json.information[p.$.TableDesc].Url = p.Object[0].$.ObjectLink;69 });70 } else {71 return {72 error: "Service Not Found",73 message: "Sorry, we could not find the right information on that location"74 };75 }76 });77 return json;78 }79 function recyclingApiParser (xml) {80 var json = {};81 parser.parseString(xml, function(err, result) {82 json.location = {};83 json.location.Area = result.Locations.$.Area;84 json.properties = [];85 if (result.hasOwnProperty("Locations") &&86 (result.Locations.hasOwnProperty("RecycleCentre") ||87 result.Locations.hasOwnProperty("RecyclePoint"))) {88 var properties = [];89 if (result.Locations.hasOwnProperty("RecycleCentre")) {90 properties.push("RecycleCentre");91 }92 if (result.Locations.hasOwnProperty("RecyclePoint")) {93 properties.push("RecyclePoint");94 }95 properties.map(function(property) {96 result.Locations[property].map(function(p) {97 var formatProperty = {};98 formatProperty.Latitude = p.$.Lat;99 formatProperty.Longitude = p.$.Lng;100 formatProperty.display = {};101 formatProperty.display.Name = p.$.Name;102 formatProperty.display.OpeningHours = p.$.OpeningHours;103 formatProperty.display.Telephone = p.$.Telephone;104 formatProperty.display.URL = p.$.URL;105 formatProperty.display = clean(formatProperty.display);106 formatProperty = clean(formatProperty);107 json.properties.push(formatProperty);108 });109 });110 } else {111 return {112 error: "Service Not Found",113 message: "Sorry, we could not find the right information on that location"114 };115 }116 });117 return json;118 }119 function parkingApiParser (xml) {120 var json = {};121 parser.parseString(xml, function(err, result) {122 json.location = {};123 if(typeof result !== undefined && result.hasOwnProperty("Locations") && result.Locations.hasOwnProperty("ParkingBay")) {124 json.location.Latitude = result.Locations.$.Lat;125 json.location.Longitude = result.Locations.$.Lng;126 json.location.Area = result.Locations.$.postcode;127 json.properties = [];128 result.Locations.ParkingBay.map(function(p) {129 var formatProperty = {};130 formatProperty.Latitude = p.$.Lat;131 formatProperty.Longitude = p.$.Lng;132 formatProperty.Street = p.$.Street;133 formatProperty.display = {};134 formatProperty.display.Name = toTitleCase(p.$.Street + " " + p.$.Type);135 formatProperty.display.Size = p.$.Size;136 formatProperty.display.OpeningHours = p.$.Time;137 formatProperty.display.Tariff = p.$.Tariff;138 formatProperty.display.Duration = p.$.Duration;139 formatProperty.display.Type = p.$.Type;140 formatProperty.display = clean(formatProperty.display);141 formatProperty = clean(formatProperty);142 json.properties.push(formatProperty);143 });144 }145 });146 return json;147 }148 function nearestApiParser (xml) {149 var json = {};150 json.properties = [];151 parser.parseString(xml, function (err, result) {152 if(typeof result !== "undefined" && result.hasOwnProperty("Locations") && result.Locations.hasOwnProperty("Properties") && result.Locations.Properties[0].hasOwnProperty("Property")) {153 if(result.Locations.hasOwnProperty("AddressSearchResults")) {154 json.location = result.Locations.AddressSearchResults[0]["$"];155 } else {156 json.location = {};157 json.location.Latitude = result.Locations.$.lat;158 json.location.Longitude = result.Locations.$.lng;159 }160 result.Locations.Properties[0].Property.map(function(p) {161 var formatProperty = clean(p["$"]);162 formatProperty.display = clean(p.PoI[0]["$"]);163 json.properties.push(formatProperty);164 });165 }166 });167 return json;168 }169 function whichParser (xml, service) {170 service = cap(service);171 if (serviceArrays.recycling.indexOf(service) > -1) {172 return recyclingApiParser(xml);173 } else if (serviceArrays.parking.indexOf(service) > -1) {174 return parkingApiParser(xml);175 } else {176 return nearestApiParser(xml);177 }178 }179 module.exports = {180 nearestApiParser: nearestApiParser,181 parkingApiParser: parkingApiParser,182 recyclingApiParser: recyclingApiParser,183 localInformationApiParser: localInformationApiParser,184 streetworksApiParser: streetworksApiParser,185 whichParser: whichParser186 };...
config.js
Source:config.js
1function setUpConfig() {2 if (isConfigOutOfDate()) {3 resetConfig()4 }5 // saveConfigValue(HOST_IDENTIFIER, 'http://192.168.230.51:43108');6 // saveConfigValue(OXAION_HOST_IDENTIFIER, 'OXAION');7 // saveConfigValue(APPLICATION_IDENTIFIER, 'iqu ilm');8 // saveConfigValue(MODULE_IDENTIFIER, 'ILM');9 // saveConfigValue(PROJECTS_IDENTIFIER, 'iqu60,ilm60_bas,ilm60_op412');10 // saveConfigValue(USER_IDENTIFIER, 'DUNKEL');11 // saveConfigValue(PASSWORD_IDENTIFIER, 'oxaion');12 // saveConfigValue(FORMATSIZE_IDENTIFIER, 'APP');13}14function resetConfig() {15 window.localStorage.setItem('config', JSON.stringify(DEFAULT_CONFIG));16}17function isConfigOutOfDate() {18 try {19 const configWithoutValues = cloneAndRemoveValueField(getConfig());20 const defaultConfigWithoutValues = cloneAndRemoveValueField(DEFAULT_CONFIG);21 return JSON.stringify(configWithoutValues) !== JSON.stringify(defaultConfigWithoutValues);22 } catch (err) {23 return true;24 }25}26function cloneAndRemoveValueField(configJSON) {27 const jsonClone = JSON.clone(configJSON);28 jsonClone.options.map((option) => delete option.value);29 return jsonClone;30}31function getConfig() {32 return JSON.parse(window.localStorage.getItem('config'));33}34function saveConfig() {35 Array.from($('.configValue')).map((input) => saveConfigValue($(input).attr('id'), $(input).val()))36 resetView();37 initApp();38}39function saveConfigValue(identifier, value) {40 const config = getConfig();41 const query = `.options{.identifier=='${identifier}'}`;42 JSPath.apply(query, config)[0].value = value;43 configStr = JSON.stringify(config);44 window.localStorage.setItem('config', configStr);45}46function getConfigValue(identifier) {47 config = JSON.parse(window.localStorage.getItem('config'));48 const query = `.options{.identifier=='${identifier}'}`;49 return JSPath.apply(query, config)[0].value;50}51//prefix to prohib collision with views52function deleteStyles() {53 for (let i = 0; i < STYLE_IDENTIFIER_ARRAY.length; i++) {54 var styleValue = getConfigValue(STYLE_IDENTIFIER_ARRAY[i]);55 if (styleValue) {56 MAINVIEW.removeClass (function (index, className) {57 return (className.match (/(^|\s)style_\S+/g) || []).join(' ');58 });59 }60 }61}62function loadStyles() {63 for (let i = 0; i < STYLE_IDENTIFIER_ARRAY.length; i++) {64 var styleValue = getConfigValue(STYLE_IDENTIFIER_ARRAY[i]);65 if (styleValue) {66 MAINVIEW.addClass(STYLE_PREFIX + styleValue);67 }68 }69}70function scanButtonNeeded() {71 switch (getConfigValue(SCANNER_IDENTIFIER)) {72 case 'on':73 return true;74 case 'off':75 return false;76 default:77 return true;78 }79}80function isLoginTypeInput() {81 switch (getConfigValue(LOGINTYPE_IDENTIFIER)) {82 case 'input':83 return true;84 case 'scan':85 return false;86 default:87 return true;88 }89}90function getTimeout() {91 var timeoutValue = getConfigValue(TIMEOUT_IDENTIFIER);92 var parsedValue = parseInt(timeoutValue);93 if (isNaN(parsedValue)) {94 return 3000095 } else {96 return parsedValue * 1000;97 }98}99function getLoginXML() {100 //layout info of login template101 const inputLoginXML = '<?xml version= "1.0" encoding= "UTF-8" ?><mobis><header><error value="false" /><message value="" /><terminal /><info><project value="" /><procedure value="LOGIN" /><format value="" /><checknum value="" /><firma value="" /></info></header><session value="1491985469021000" /><template name="LOGIN"><callback><source /><action /></callback><events text="Ok" value="ENTER" /><formatproperty key="BUTTONLIST_BACKCOLOR" value="WhiteSmoke" /><formatproperty key="DISPLAYBACKCOLOR" value="White" /><formatproperty key="DISPLAYHEIGHT" value="150" /><formatproperty key="EDITBACKCOLOR" value="LightSteelBlue" /><formatproperty key="KEYBOARD" value="TRUE" /><formatproperty key="LINECOLOR" value="DarkRed" /><formatproperty key="LINEWIDTH" value="1" /><formatproperty key="LOGIN_PASSWORD" value="e15" /><formatproperty key="LOGIN_USER" value="e7" /><formatproperty key="TITLE" value="Anmeldung" /><formatproperty key="TITLEBACKCOLOR" value="DarkRed" /><formatproperty key="TITLEFORECOLOR" value="White" /><formatproperty key="XPDISPLAYHEIGHT" value="390" /><elements><element content="Benutzer:" events="" image="" name="e6" position="5,200" size="21,94" style="LABEL_EDITZONE" text="" type="Label"><formatelementproperty key="STYLE" value="Arial,9.75,LightSteelBlue,MidnightBlue,True,False,False,LEFT" /></element><element content="" events="" image="" name="e7" position="104,200" size="21,127" style="INPUT_ABC" text="" type="TextBox"><formatelementproperty key="TABTOENTER" value="FALSE" /><formatelementproperty key="ENTERTOTAB" value="TRUE" /><formatelementproperty key="STYLE" value="Arial,9.75,White,Black,False,False,False,LEFT" /></element><element content="Geben Sie Ihren Benutzernamen und das Kennwort ein:" events="" image="" name="e12" position="5,160" size="38,226" style="ORDER" text="" type="Label"><formatelementproperty key="STYLE" value="Arial,9.75,LightSteelBlue,DarkRed,True,False,True,LEFT" /></element><element content="Kennwort:" events="" image="" name="e14" position="5,224" size="21,91" style="LABEL_EDITZONE" text="" type="Label"><formatelementproperty key="STYLE" value="Arial,9.75,LightSteelBlue,MidnightBlue,True,False,False,LEFT" /></element><element content="" events="" image="" name="e15" position="104,224" size="21,127" style="INPUT_ABC" text="" type="TextBox"><formatelementproperty key="TABTOENTER" value="FALSE" /><formatelementproperty key="STYLE" value="Arial,9.75,White,Black,False,False,False,LEFT" /><formatelementproperty key="PASSWORD_CHARACTER" value="*" /></element></elements></template></mobis>';102 const scanLoginXML = '<?xml version="1.0" encoding="UTF-8" ?><mobis><header><error value="false"></error><message value=""></message><terminal></terminal><info><project value=""></project><procedure value="LOGIN"></procedure><format value=""></format><checknum value=""></checknum><firma value=""></firma></info></header><session value="1538474553440000"></session><template name="LOGIN"><callback><source></source><action></action></callback><events text="Ok" value="ENTER"></events><formatproperty key="BUTTONLIST_BACKCOLOR" value="WhiteSmoke"></formatproperty><formatproperty key="DISPLAYBACKCOLOR" value="White"></formatproperty><formatproperty key="DISPLAYHEIGHT" value="150"></formatproperty><formatproperty key="DISPLAYHEIGHT_PDA_BIG" value="300"></formatproperty><formatproperty key="EDITBACKCOLOR" value="LightSteelBlue"></formatproperty><formatproperty key="KEYBOARD" value="TRUE"></formatproperty><formatproperty key="LINECOLOR" value="DarkRed"></formatproperty><formatproperty key="LINEWIDTH" value="1"></formatproperty><formatproperty key="LOGIN_USER" value="e7"></formatproperty><formatproperty key="TITLE" value="Anmeldung"></formatproperty><formatproperty key="TITLEBACKCOLOR" value="DarkRed"></formatproperty><formatproperty key="TITLEFORECOLOR" value="White"></formatproperty><formatproperty key="XPDISPLAYHEIGHT" value="390"></formatproperty><elements><element content="Anmeldedaten:" events="" image="" name="e6" position="5,220" size="21,220" style="LABEL_EDITZONE" text="" type="Label"><formatelementproperty key="STYLE" value="Arial,9.75,LightSteelBlue,MidnightBlue,True,False,False,LEFT"></formatelementproperty></element><element content="950_LOELL" events="" image="" name="e7" position="5,250" size="21,210" style="INPUT_ABC" text="" type="TextBox"><formatelementproperty key="TABTOENTER" value="FALSE"></formatelementproperty><formatelementproperty key="STYLE" value="Arial,9.75,White,Black,False,False,False,LEFT"></formatelementproperty><formatelementproperty key="PASSWORD_CHARACTER" value="*"></formatelementproperty></element><element content="Geben Sie Ihren Benutzernamen und das Kennwort getrennt durch das von Ihnen konfigurierte Zeichen ein!" events="" image="" name="e12" position="5,160" size="57,226" style="ORDER" text="" type="Label"><formatelementproperty key="STYLE" value="Arial,9.75,LightSteelBlue,DarkRed,True,False,True,LEFT"></formatelementproperty></element></elements></template></mobis>';103 104 if (isLoginTypeInput()) {105 return inputLoginXML;106 } else {107 return scanLoginXML;108 }...
ExportUtils.js
Source:ExportUtils.js
...22// =================================== Format ========================23function formatTypeNode(type, name) {24 return prefixStr + "<Node Type=\"" + type + "\" Name=\"" + name + "\" >" + "\n"25}26function formatProperty(name, value) {27 return prefixStr + spaceStr + "<Property Name=\"" + name + "\" Value=\"" + value + "\" \/>" + "\n"28}29function formatNodeEnd() {30 return prefixStr + "</Node>" + "\n"31}32function formatAnchorPoint(layer) {33 var anchorX = 0.534 var anchorY = 0.535 return formatProperty("AnchorPoint", "{" + anchorX + "," + anchorY + "}")36}37function formatPosition(layer) {38 // bounds [0,1,2,3] åå«æ¯ 0:å·¦ä¾§å·¦è¾¹è· ï¼1:é¡¶ä¾§é¡¶è¾¹è· ï¼2:å³ä¾§å·¦è¾¹è· ï¼3:åºä¾§é¡¶è¾¹è·39 var bounds = layer.bounds40 var posX = (bounds[0] + bounds[2]) / 241 var posY = HEIGHT - ((bounds[1] + bounds[3]) / 2)42 return formatProperty("Position", "{" + getNumInUnitValue(posX) + "," + getNumInUnitValue(posY) + "}")43}44function formatLocalPosition(layer) {45 var bounds = layer.bounds46 var posX = (bounds[0] + bounds[2]) / 247 var posY = HEIGHT - ((bounds[1] + bounds[3]) / 2)48 if (layer.parent.typename == "LayerSet") {49 var bounds = layer.parent.bounds50 var parPosX = (bounds[0] + bounds[2]) / 251 var parPosY = HEIGHT - ((bounds[1] + bounds[3]) / 2)52 posX -= parPosX53 posY -= parPosY54 }55 return formatProperty("LocalPosition", "{" + posX + "," + posY + "}")56}57function formatContentSize(layer) {58 var bounds = layer.bounds59 var width = makeNumPOT(bounds[2] - bounds[0])60 var height = makeNumPOT(bounds[3] - bounds[1])61 return formatProperty("ContentSize", "{" + getNumInUnitValue(width) + "," + getNumInUnitValue(height) + "}")62}63function formatImage(layer) {64 var name = layer.name65 var findIndex = layer.name.search(KEY_SIGN)66 if (findIndex != -1) {67 name = layer.name.substr(0, findIndex)68 }69 var list = name.split(":")70 return formatProperty("Image", formatUIPath(list[0], list[1]))71}72function formatImageType(layer) {73 if (searchName(layer, KEY_RAW_IMAGE)) {74 return ""75 }76 if (searchName(layer, KEY_9_SLICE)) {77 return formatProperty("ImageType", "Sliced")78 } else {79 return formatProperty("ImageType", "Simple")80 }81}82function formatOpacity(layer) {83 var opacity = layer.opacity84 if (opacity < 100) {85 var opa = Math.ceil(255 / 100 * opacity)86 return formatProperty("Opacity", opa.toString())87 }88 return ""89}90function formatUIPath(atlasName, spriteName) {91 // return "Assets/Res/UI/NewUI/texture/ui_menu/" + atlasName + "/" + spriteName92 return atlasName + "/" + spriteName93}94function formatFontSize(layer) {95 if (layer.textItem) {96 return formatProperty("FontSize", Math.ceil(layer.textItem.size.value))97 }98 return ""99}100function formatTextColor(layer) {101 if (layer.textItem) {102 return formatProperty("TextColor", "FF" + layer.textItem.color.rgb.hexValue)103 }104 return ""105}106function formatTextContent(layer) {107 if (layer.textItem) {108 return formatProperty("TextContent", layer.textItem.contents)109 }110 return ""111}112// ===========================================================113//移å°settingUtlis114// function createExportOptions() {115// var exportOptions = new ExportOptionsSaveForWeb116// exportOptions.format = SaveDocumentType.PNG117// exportOptions.transparency = true118// exportOptions.quality = 100119// exportOptions.PNG8 = false120// return exportOptions121// }122createExportOptions = settingUtils.createExportOptions...
style-formatter.js
Source:style-formatter.js
...43 'width: 100%;height: 100%;transition: transform .1s ease-in-out;position: absolute;bottom: 0;left: 0; top: 0;right: 0;margin: auto;';44 const { font = {}, background = {}, border = {} } = style;45 const primaryColor = theme.getDataColorSpecials().primary;46 // enable47 styles += disabled ? formatProperty('opacity', 0.4) : formatProperty('cursor', 'pointer');48 // font49 styles += formatProperty('color', getColor(font, '#ffffff', theme));50 const fontStyle = font.style || DEFAULTS.FONT_STYLE;51 fontStyle.bold && (styles += formatProperty('font-weight', 'bold'));52 fontStyle.italic && (styles += formatProperty('font-style', 'italic'));53 // background54 const backgroundColor = getColor(background, primaryColor, theme);55 styles += formatProperty('background-color', backgroundColor);56 if (background.useImage && background.url.qStaticContentUrl) {57 let bgUrl = background.url.qStaticContentUrl.qUrl;58 if (bgUrl) {59 bgUrl = urlUtils.getImageUrl(bgUrl);60 styles += formatProperty('background-image', `url('${bgUrl}')`);61 styles += formatProperty('background-size', backgroundSize[background.size || DEFAULTS.BACKGROUND_SIZE]);62 styles += formatProperty(63 'background-position',64 backgroundPosition[background.position || DEFAULTS.BACKGROUND_POSITION]65 );66 styles += formatProperty('background-repeat', 'no-repeat');67 }68 }69 // border70 if (border.useBorder) {71 const lengthShortSide = Math.min(element.offsetWidth, element.offsetHeight);72 const borderColor = getColor(border, colorUtils.getFadedColor(backgroundColor), theme);73 const borderSize = ((border.width || DEFAULTS.BORDER_WIDTH) * lengthShortSide) / 2;74 styles += formatProperty('border', `${borderSize}px solid ${borderColor}`);75 styles += formatProperty(76 'border-radius',77 `${((border.radius || DEFAULTS.BORDER_RADIUS) * lengthShortSide) / 2}px`78 );79 } else {80 styles += 'border: none;';81 }82 return styles;83 },84 createLabelAndIcon({ button, theme, style = {}, isSense }) {85 const { icon = {}, font = {}, label = DEFAULTS.LABEL } = style;86 // text element wrapping label and icon87 const text = document.createElement('text');88 text.style.whiteSpace = 'nowrap';89 text.style.fontFamily = theme.getStyle('', '', 'fontFamily');...
AdhocCtrl.js
Source:AdhocCtrl.js
1// "class" for customizing select2 (with possibility to create selection items on the fly2// Appropriated from http://jsfiddle.net/7AvKZ/59/3// Only minor changes made to this class - largely the original4function Select2Tagging(items,formatProperty, multienabled) {5 if(!formatProperty) {6 formatProperty="text";7 }8 if (typeof multienabled === "undefined") {9 multienabled = true;10 }11 var f={};12 f.formatProperty=formatProperty;13 f.data=items;14 var itemMap={};15 $.each(items,function(index,value){16 itemMap[value.id]=value;17 });18 f.initSelection = function(element, callback) {19 var data = [];20 var eleVal=element.val();21 var ids = eleVal.split(",");22 $(ids).each(function() {23 var id=this;24 $(f.data).each(function() {25 if (id.localeCompare(""+this.id)==0) data.push(this);26 });27 });28 callback(data);29 };30 f.createSearchChoice = function(term, data) {31 if ($(data).filter(function() {32 return this[f.formatProperty].localeCompare(term) === 0;33 //return this.text.localeCompare(term) === 0;34 }35 ).length === 0) {36 var result= {37 id: term,38 //text: term39 };40 result[f.formatProperty]=term;41 return result;42 }43 };44 formatResult=function(item) {45 if(item[f.formatProperty]) {46 return item[f.formatProperty];47 } else {48 return item;49 }50 };51 formatSelection=function(item) {52 if(item[f.formatProperty]) {53 return item[f.formatProperty];54 } else {55 return item;56 }57 };58 f.formatResult= formatResult;59 f.formatSelection= formatSelection;60 f.multiple = multienabled;61 return f;62}63function AdhocCtrl($scope, $http, Analyzer, Tokenizer, Filter, Data){64 $scope.analyzer = Analyzer;65 $scope.tokenizer = Tokenizer;66 $scope.filter = Filter;67 $scope.data = Data;68 $scope.tokenizerSelection = [];69 $scope.filterSelection = [];70 //Select2 requires objects in format of {id:0, name: 'val'}71 //Convert our tokenizer array into a local object72 var availTokenizers = [];73 for (i in $scope.tokenizer.tokenizers) {74 availTokenizers.push( {id: i, name: $scope.tokenizer.tokenizers[i]});75 }76 $scope.tokenizerAllOptions = new Select2Tagging(availTokenizers, 'name', false);77 //Select2 requires objects in format of {id:0, name: 'val'}78 //Convert our filter array into a local object79 var availFilters = [];80 for (i in $scope.filter.filters) {81 availFilters.push( {id: i, name: $scope.filter.filters[i]});82 }83 $scope.filterAllOptions = new Select2Tagging(availFilters, 'name');84 $scope.$watch('tokenizerSelection', function(selection) {85 $scope.analyzeAdhoc($scope.tokenizerSelection, $scope.filterSelection);86 });87 $scope.$watch('filterSelection', function(selection) {88 $scope.analyzeAdhoc($scope.tokenizerSelection, $scope.filterSelection);89 });90 //If the text changes, query ES to get the tokens91 $scope.$watch('analyzer.query', function(value){92 $scope.analyzeAdhoc($scope.tokenizerSelection, $scope.filterSelection);93 });94 $scope.analyzeAdhoc = function(tokenizer, filters) {95 //tokenizer must be supplied, filters is optional96 if (typeof tokenizer === "undefined" || tokenizer.length == 0)97 return;98 var filterList = [];99 for (i in filters) {100 filterList.push(filters[i].name);101 }102 filterList = filterList.join(",");103 var path = $scope.data.host + "/_analyze?tokenizer=" + tokenizer.name + "&filters=" + filterList;104 $http.post(path, $scope.analyzer.query)105 .success(function(response){106 var tokens = [];107 for(i in response.tokens){108 tokens.push(response.tokens[i]);109 }110 $scope.analyzer.atext['adhoc'] = tokens;111 })112 .error(function(data, status, headers, config){113 //console.log(data);114 });115 }...
test_formatter.js
Source:test_formatter.js
...25describe('interpreter.formatProperty', () => {26 describe('on generated date types, works from a Time instance', () => {27 it('From \'2018-08-07T16:06:06+0200\'', () => {28 const date = new Time('2018-08-07T16:06:06+0200');29 expect(interpreter.formatProperty('month_of_year', date)).to.be.equal('Aug');30 expect(interpreter.formatProperty('day_of_month', date)).to.be.equal('07');31 expect(interpreter.formatProperty('day_of_week', date)).to.be.equal('Tue');32 expect(interpreter.formatProperty('time_of_day', date)).to.be.equal('16:06:06');33 });34 it('From \'2018-08-06T08:32:58.000Z\'', () => {35 const date = new Time('2018-08-06T08:32:58.000Z');36 expect(interpreter.formatProperty('month_of_year', date)).to.be.equal('Aug');37 expect(interpreter.formatProperty('day_of_month', date)).to.be.equal('06');38 expect(interpreter.formatProperty('day_of_week', date)).to.be.equal('Mon');39 expect(interpreter.formatProperty('time_of_day', date)).to.be.equal('08:32:58');40 });41 it('From \'2017-10-03T09:13-0800\'', () => {42 const date = new Time('2017-10-03T09:13-0800');43 expect(interpreter.formatProperty('month_of_year', date)).to.be.equal('Oct');44 expect(interpreter.formatProperty('day_of_month', date)).to.be.equal('03');45 expect(interpreter.formatProperty('day_of_week', date)).to.be.equal('Tue');46 expect(interpreter.formatProperty('time_of_day', date)).to.be.equal('09:13');47 });48 it('From \'2017-12-03T02:03+0500\' on tz \'-02:00\'', () => {49 const date = new Time('2017-12-03T02:03+0500', '-02:00');50 expect(interpreter.formatProperty('month_of_year', date)).to.be.equal('Dec');51 expect(interpreter.formatProperty('day_of_month', date)).to.be.equal('02');52 expect(interpreter.formatProperty('day_of_week', date)).to.be.equal('Sat');53 expect(interpreter.formatProperty('time_of_day', date)).to.be.equal('19:03');54 });55 it('From \'2017-07-01T04:20:00.000Z\' on tz \'+02:00\'', () => {56 const date = new Time('2017-07-01T04:20:00.000Z', '+02:00');57 expect(interpreter.formatProperty('month_of_year', date)).to.be.equal('Jul');58 expect(interpreter.formatProperty('day_of_month', date)).to.be.equal('01');59 expect(interpreter.formatProperty('day_of_week', date)).to.be.equal('Sat');60 expect(interpreter.formatProperty('time_of_day', date)).to.be.equal('06:20');61 });62 it('From \'2007-12-01T17:23:00.000Z\' on tz \'+01:00\'', () => {63 const date = new Time('2007-12-01T17:23:00.000Z', '+01:00');64 expect(interpreter.formatProperty('month_of_year', date)).to.be.equal('Dec');65 expect(interpreter.formatProperty('day_of_month', date)).to.be.equal('01');66 expect(interpreter.formatProperty('day_of_week', date)).to.be.equal('Sat');67 expect(interpreter.formatProperty('time_of_day', date)).to.be.equal('18:23');68 });69 });70 describe('on boolean values', () => {71 it('From \'false\'', () => {72 expect(interpreter.formatProperty('boolean', false)).to.be.equal('false');73 });74 it('From \'true\'', () => {75 expect(interpreter.formatProperty('boolean', true)).to.be.equal('true');76 });77 });...
properties.js
Source:properties.js
...9export function formatDecisionRule(decisionRule) {10 deprecation('Properties.formatDecisionRule', 'interpreter.formatDecisionRules');11 return formatDecisionRules([decisionRule]);12}13export function formatProperty(property) {14 deprecation('Properties.formatProperty', 'interpreter.formatProperty');15 return _formatProperty(property);16}...
Using AI Code Generation
1Cypress.Commands.add("formatProperty", (text) => {2 return text.replace(/\s+/g, '-').toLowerCase();3});4Cypress.Commands.add("formatProperty", (text) => {5 return text.replace(/\s+/g, '-').toLowerCase();6});7Cypress.Commands.add("formatProperty", (text) => {8 return text.replace(/\s+/g, '-').toLowerCase();9});10Cypress.Commands.add("formatProperty", (text) => {11 return text.replace(/\s+/g, '-').toLowerCase();12});13Cypress.Commands.add("formatProperty", (text) => {14 return text.replace(/\s+/g, '-').toLowerCase();15});16Cypress.Commands.add("formatProperty", (text) => {17 return text.replace(/\s+/g, '-').toLowerCase();18});19Cypress.Commands.add("formatProperty", (text) => {20 return text.replace(/\s+/g, '-').toLowerCase();21});22Cypress.Commands.add("formatProperty", (text) => {23 return text.replace(/\s+/g, '-').toLowerCase();24});25Cypress.Commands.add("formatProperty", (text) => {26 return text.replace(/\s+/g, '-').toLowerCase();27});28Cypress.Commands.add("formatProperty", (text) => {29 return text.replace(/\s+/g, '-').toLowerCase();30});31Cypress.Commands.add("formatProperty", (text) => {32 return text.replace(/\s+/g, '-').toLowerCase();33});34Cypress.Commands.add("formatProperty", (text) => {35 return text.replace(/\s+/g, '-').toLowerCase();
Using AI Code Generation
1cy.get('input').first().type('test');2cy.get('input').last().type('test');3cy.get('input').first().should('have.value', 'test');4cy.get('input').last().should('have.value', 'test');5cy.get('input').first().clear();6cy.get('input').last().clear();7cy.get('input').first().should('have.value', '');8cy.get('input').last().should('have.value', '');9cy.get('input').first().type('test');10cy.get('input').last().type('test');11cy.get('input').first().should('have.value', 'test');12cy.get('input').last().should('have.value', 'test');13cy.get('input').first().clear();14cy.get('input').last().clear();15cy.get('input').first().should('have.value', '');16cy.get('input').last().should('have.value', '');17cy.get('input').first().type('test');18cy.get('input').last().type('test');19cy.get('input').first().should('have.value', 'test');20cy.get('input').last().should('have.value', 'test');21cy.get('input').first().clear();22cy.get('input').last().clear();23cy.get('input').first().should('have.value', '');24cy.get('input').last().should('have.value', '');25cy.get('input').first().type('test');26cy.get('input').last().type('test');27cy.get('input').first().should('have.value', 'test');28cy.get('input').last().should('have.value', 'test');29cy.get('input').first().clear();30cy.get('input').last().clear();31cy.get('input').first().should('have.value', '');32cy.get('input').last().should('have.value', '');33cy.get('input').first().type('test');34cy.get('input').last().type('test');35cy.get('input').first().should('have.value', 'test');36cy.get('input').last().should('have.value', 'test');37cy.get('input').first().clear();38cy.get('input').last().clear();39cy.get('input').first().should('have.value', '');40cy.get('input').last().should('have.value', '');41cy.get('input').first().type('test');42cy.get('input').last().type
Using AI Code Generation
1describe('Test', () => {2 it('should pass', () => {3 cy.get('.home-list > :nth-child(1) > .home-list-item').formatProperty('innerText');4 });5});6Cypress.Commands.add('formatProperty', (property) => {7 cy.get('body').then((body) => {8 const propertyValue = body[0][property];9 console.log(propertyValue);10 });11});12import './commands';13{14}
Using AI Code Generation
1Cypress.Commands.add("formatProperty", (property) => {2 return cy.wrap(property).then((property) => {3 const formattedProperty = {4 price: property.price.toString(),5 bedrooms: property.bedrooms.toString(),6 bathrooms: property.bathrooms.toString(),7 carSpaces: property.carSpaces.toString(),8 };9 return formattedProperty;10 });11});
Using AI Code Generation
1Cypress.Commands.add("formatProperty", (property) => {2 .get(`[data-test="${property}"]`)3 .invoke("text")4 .then((text) => {5 return text.trim();6 });7});8Cypress.Commands.add("formatProperty", (property) => {9 .get(`[data-test="${property}"]`)10 .invoke("text")11 .then((text) => {12 return text.trim();13 });14});15Cypress.Commands.add("formatProperty", (property) => {16 .get(`[data-test="${property}"]`)17 .invoke("text")18 .then((text) => {19 return text.trim();20 });21});22Cypress.Commands.add("formatProperty", (property) => {23 .get(`[data-test="${property}"]`)24 .invoke("text")25 .then((text) => {26 return text.trim();27 });28});29Cypress.Commands.add("formatProperty", (property) => {30 .get(`[data-test="${property}"]`)31 .invoke("text")32 .then((text) => {33 return text.trim();34 });35});36Cypress.Commands.add("formatProperty", (property) => {37 .get(`[data-test="${property}"]`)38 .invoke("text")39 .then((text) => {40 return text.trim();41 });42});43Cypress.Commands.add("formatProperty", (property) => {44 .get(`[data-test="${property}"]`)45 .invoke("text")46 .then((text) => {47 return text.trim();48 });49});50Cypress.Commands.add("formatProperty", (property) => {51 .get(`[data-test="${property}"]`)52 .invoke("text")53 .then((text) => {54 return text.trim();55 });56});57Cypress.Commands.add("formatProperty", (property) => {58 .get(`[data-test="${property}"]`)59 .invoke("text")60 .then((text) => {
Using AI Code Generation
1const formatProperty = require('cypress-fixture-format-property')2describe('test', () => {3 it('test', () => {4 cy.fixture('test.json')5 .then(fixture => {6 const formattedFixture = formatProperty(fixture, 'date', 'yyyy-MM-dd')7 expect(formattedFixture).to.deep.equal({8 })9 })10 })11})12import { formatProperty } from 'cypress-fixture-format-property'13Cypress.Commands.add('formatProperty', (fixture, property, format) => {14 return formatProperty(fixture, property, format)15})16describe('test', () => {17 it('test', () => {18 cy.fixture('test.json')19 .then(fixture => {20 cy.formatProperty(fixture, 'date', 'yyyy-MM-dd')21 .then(formattedFixture => {22 expect(formattedFixture).to.deep.equal({23 })24 })25 })26 })27})
Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.
You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!