function createObjectAndSetValuesWithMap(object, map, enumProperties) { var enumProps = _.reduce(_.toPairs(enumProperties), function(ob, x) { var propName = x[0], fields = x[1] return utils.merge(ob, utils.keyValue(propName, toArray(fields))) function toArray(fields) { return _.reduce(fields, function(acc, field) { if (object[field]) return acc.concat(field) else return acc }, []) } }, {}) var props = _.reduce(_.toPairs(utils.flattenObject(object)), function(ob, pair) { var key = pair[0], val = pair[1], prop = {} utils.setValueForPath(key.split('.'), prop, val) return utils.merge(ob, prop) }, {}) return utils.merge(enumProps, omitEnumProps(props)) function omitEnumProps(props) { var enumPropNames = _(enumProperties).toPairs().map(function (x) { return x[1] }).flatten().value() return _.omit(props, enumPropNames) } }
async function updateSafariUserSettings (sim, settingSet) { // add extra stuff to UserSettings.plist and EffectiveUserSettings.plist let newUserSettings = {}; if (_.has(settingSet, 'WebKitJavaScriptEnabled')) { newUserSettings.safariAllowJavaScript = settingSet.WebKitJavaScriptEnabled; } if (_.has(settingSet, 'WebKitJavaScriptCanOpenWindowsAutomatically')) { newUserSettings.safariAllowPopups = settingSet.WebKitJavaScriptCanOpenWindowsAutomatically; } if (_.has(settingSet, 'WarnAboutFraudulentWebsites')) { newUserSettings.safariForceFraudWarning = !settingSet.WarnAboutFraudulentWebsites; } if (_.size(newUserSettings) > 0) { log.debug('Updating Safari user settings'); let curUserSettings = await readSettings(sim, 'userSettings'); for (let [file, userSettingSet] of _.toPairs(curUserSettings)) { // the user settings plist has two buckets, one for // boolean settings (`restrictedBool`) and one for // other value settings (`restrictedValue`). In each, the value // is in a `value` sub-field. if (!_.has(userSettingSet, 'restrictedBool')) { userSettingSet.restrictedBool = {}; } for (let [key, value] of _.toPairs(newUserSettings)) { userSettingSet.restrictedBool[key] = {value}; } // actually do the update await update(file, userSettingSet); } } }
renderAddressOption = (type) => { let provinceArr = [] let cityArr = [] let districtArr = [] const {province, city, district} = this.state switch (type) { case ADDRESS_TYPE.PROVINCE: for (let [k, v] of _.toPairs(province)) { provinceArr.push(<option value={k} key={k}>{v}</option>) } return provinceArr break case ADDRESS_TYPE.CITY: for (let [k, v] of _.toPairs(city)) { cityArr.push((<option value={k} key={k}>{v}</option>)) } return cityArr break case ADDRESS_TYPE.DISTRICT: for (let [k, v] of _.toPairs(district)) { districtArr.push(<option value={k} key={k}>{v}</option>) } return districtArr break default: return null break } }
function makeDeclarationSet(groupKey, isAlias) { const modifiers = config.theme.modifiers[groupKey]; if (isAlias) { lodash.toPairs(config.theme.alias[groupKey]).forEach(([jsAlias, jsKey]) => { if (modifiers) { modifiers.order.forEach(modifierValue => { const variableName = makeName( `${groupKey}-${jsAlias}-${modifierValue}` ); const baseName = makeName(`${groupKey}-${jsKey}-${modifierValue}`); if (!declarations[baseName]) { throw new Error(`Base variable ${baseName} not assigned.`); } declarations[variableName] = `var(${baseName})`; }); } else { const variableName = makeName(`${groupKey}-${jsAlias}`); const baseName = makeName(`${groupKey}-${jsKey}`); if (!declarations[baseName]) { throw new Error(`Base variable ${baseName} not assigned.`); } declarations[variableName] = `var(${baseName})`; } }); } else { lodash.toPairs(config.theme.base[groupKey]).forEach(([jsKey, value]) => { if (modifiers) { const modifierObject = typeof value === "object" ? value : { [modifiers.default]: value }; modifiers.order.forEach(modifierValue => { const variableName = makeName( `${groupKey}-${jsKey}-${modifierValue}` ); const cssValue = modifierObject[modifierValue]; if (typeof cssValue !== "undefined") { declarations[variableName] = cssValue; } else { const fallback = modifiers.values[modifierValue]; if (fallback === null) { throw new Error( `Cannot resolve modifiers for "${groupKey}", "${jsKey}"` ); } const baseName = makeName(`${groupKey}-${jsKey}-${fallback}`); declarations[variableName] = `var(${baseName})`; } }); } else { if (typeof value === "object") { throw new Error(`Invalid modifier object in group ${groupKey}`); } declarations[makeName(`${groupKey}-${jsKey}`)] = value; } }); } }
return function (app) { for (let [path, methods] of _.toPairs(METHOD_MAP)) { for (let [method, spec] of _.toPairs(methods)) { let isSessCmd = isSessionCommand(spec.command); // set up the express route handler buildHandler(app, method, path, spec, driver, isSessCmd); } } };
it('check accesibility reduce motion settings', async function () { let sim = await getSimulator(udid); await sim.setReduceMotion(true); let fileSettings = await readSettings(sim, 'accessibilitySettings'); for (let [, settings] of _.toPairs(fileSettings)) { settings.ReduceMotionEnabled.should.eql(1); } await sim.setReduceMotion(false); fileSettings = await readSettings(sim, 'accessibilitySettings'); for (let [, settings] of _.toPairs(fileSettings)) { settings.ReduceMotionEnabled.should.eql(0); } });
module.exports = function(options) { var helpers = { assetPath: loadTemplateHelper(require('../template-helpers/assetPath'),options), assetS3Url: loadTemplateHelper(require('../template-helpers/assetS3Url'),options), concat: require('../../handlebars-helpers/concat'), helper: loadTemplateHelper(require('../template-helpers/helper'),options), layout: loadTemplateHelper(require('../template-helpers/layout'),options), partial: loadTemplateHelper(require('../template-helpers/partial'),options), ref: require('../template-helpers/ref'), requireAssets: loadTemplateHelper(require('../template-helpers/requireAssets'),options), scopeId: require('../template-helpers/scopeId'), set: loadTemplateHelper(require('../template-helpers/set'),options), templateS3Url: loadTemplateHelper(require('../template-helpers/templateS3Url'),options) }; _.each(_.values(sections), function(v) { helpers[v.NAME] = loadTemplateHelper(v,options); }); var engine = options.handlebars; _.each(_.toPairs(helpers), function(kv) { if (!engine.helpers[kv[0]]) { engine.registerHelper(kv[0],kv[1]); } }); return helpers; };
// convert our object to an array of key/value pairs and run the tests on it function evalObject(obj, tests) { var pairs = _.toPairs(obj); // evaluate all the `'BOUND'` tests first var boundResults; try { boundResults = testType('BOUND', tests, pairs); } catch(e) { console.log(e); return false; } // evaulate all the `'FREE'` tests var freeResults; try { freeResults = testType('FREE', tests, boundResults); } catch(e) { console.log(e); return false; } // if the tests didn't fail, and we don't have any unclaimed // key/value pairs, then all the tests succeeded! return freeResults.length === 0; }
beforeEach(function () { sandbox = sinon.createSandbox(); mocks[SANDBOX] = sandbox; for (let [key, value] of _.toPairs(libs)) { mocks[key] = sandbox.mock(value); } });
beforeEach(() => { sandbox = sinon.sandbox.create(); mocks[SANDBOX] = sandbox; for (let [key, value] of _.toPairs(libs)) { mocks[key] = sandbox.mock(value); } });
prompt.get(['githubApiAccessToken'], (error, result) => { if (error) { return console.error(error); } const inputPairs = _.toPairs(result); console.log('\n---------------------------------------------------------------------------\n'); console.log('Command-line input received:\n'); inputPairs.forEach(function(pair) { console.log(pair[0] + " = " + pair[1] ); }); const output = inputPairs.map(function(pair){ return "export const " + pair[0] + ": string = '" + pair[1] + "';"; }).join('\n'); console.log('\n---------------------------------------------------------------------------\n'); console.log('Output of setup script:\n'); console.log(output); console.log('\n---------------------------------------------------------------------------\n'); console.log('Writing output to ' + targetFile + "\n"); fs.writeFileSync(targetFile, output); });
async function buildCode (opts) { // only build the code if it hasn't been done before if (opts.code) return opts.code; let env = getEnv(opts); log.debug(`Dynamic env: ${JSON.stringify(env)}`); let bootstrapJs = BOOTSTRAP_JS_PATH; // if special imports were sent in, make use of them let imports = (opts.imports && opts.imports.pre) ? opts.imports.pre : []; let bootstrapCode = await buildScript(bootstrapJs, imports); // generate the dynamic part of the bootstrap code // with the environment set up properly let lines = []; lines.push('// This file is automatically generated. Do not manually modify!'); lines.push(''); lines.push(bootstrapCode); lines.push(''); lines.push('bootstrap({'); // add each defined variable to the environment for (let [key, value] of _.toPairs(env)) { if (!_.isUndefined(value)) { let quote = _.isString(value) ? '\"' : ''; lines.push(` "${key}": ${quote}${value}${quote},`); } } // get rid of the last comma that was added lines[lines.length - 1] = lines[lines.length - 1].replace(/,$/, ''); lines.push('});'); return lines.join('\r\n'); }
function _guessType(values) { // Get matching types const matches = []; for (const value of values) { for (const type of _TYPE_ORDER) { const cast = types[`cast${lodash.upperFirst(type)}`]; const result = cast("default", value); if (result !== ERROR) { matches.push(type); break; } } } // Get winner type let winner = "any"; let count = 0; for (const [itemType, itemCount] of lodash.toPairs(lodash.countBy(matches))) { if (itemCount > count) { winner = itemType; count = itemCount; } } return winner; }
Handlebars.registerHelper('client_url', function (clientUrl) { if (!clientUrl) { return; } const createUrlString = function createUrlString (clientUrl, name = getBaseHostname(clientUrl)) { return `[${name}](${clientUrl})`; }; if (!_.isArray(clientUrl)) { return createUrlString(clientUrl); } let urlStrings = []; for (const item of clientUrl) { for (let [key, value] of _.toPairs(item)) { key = key.toLowerCase(); const urlStr = CLIENT_URL_TYPES[key] === 'hostname' ? createUrlString(value) : createUrlString(value, CLIENT_URL_TYPES[key]); urlStrings.push(urlStr); } } return urlStrings.join(' '); });
var filteredModules = _.flatMap(modules, function(mod) { var eligible = _.flatMap(_.toPairs(mod.interface.types), function( pair ) { var name = pair[0]; var annotation = pair[1].annotation; if ( annotation.moduleName && annotation.moduleName.package === 'elm-explorations/test' && annotation.moduleName.module === 'Test' && annotation.name === 'Test' ) { return name; } else { return []; } }); // Must have at least 1 value of type Test. Otherwise ignore this module. if (eligible.length > 0) { return [{ name: mod.moduleName, tests: eligible }]; } else { return []; } });
module.exports = ( condition, msg ) => { if( condition instanceof Function ) { return condition( msg ) } else if( Array.isArray( condition ) ) { return condition.every( key => key in msg ) } return _.toPairs( condition ).every( pair => { const key = pair[0] const cond = pair[1] const val = msg[ key ] if( typeof cond === 'string' ) { return matchers.string( cond, val ) } else if( typeof cond === 'number' ) { return matchers.number( cond, val ) } else if( cond instanceof Function ) { return cond( val ) } else if( cond instanceof RegExp ) { return matchers.regexp( cond, val ) } else { return matchers.object( cond, val ) } }) }
createMetricLabel(md, target, groupByTags, options) { if (target.alias) { var scopedVars = _.clone(options.scopedVars || {}); _.each(md.tags, function(value, key) { scopedVars['tag_' + key] = {value: value}; }); return this.templateSrv.replace(target.alias, scopedVars); } var label = md.metric; var tagData = []; if (!_.isEmpty(md.tags)) { _.each(_.toPairs(md.tags), function(tag) { if (_.has(groupByTags, tag[0])) { tagData.push(tag[0] + "=" + tag[1]); } }); } if (!_.isEmpty(tagData)) { label += "{" + tagData.join(", ") + "}"; } return label; }
const getValidation = validation => map( toPairs(validation), ([type, options]) => ( Object.hasOwnProperty.call(validations, type) ? validations[type](options) : () => (`Validation "${type}" not found`) ), );
async getSessions () { const sessions = await sessionsListGuard.acquire(AppiumDriver.name, () => this.sessions); return _.toPairs(sessions) .map(([id, driver]) => { return {id, capabilities: driver.caps}; }); }
return function headerCookiesManager(request, response, next) { var headers = request.headers; var isEqTo = function(base) { return function(compare) { return base.toLowerCase() === compare.toLowerCase(); }; }; var isSetHeader = isEqTo(SET_HEADER); var isClearHeader = isEqTo(CLEAR_HEADER); _.forEach(_.toPairs(headers), function(header) { var key = _.first(header); var tail = _.join(_.flatten(_.tail(header)), ',').split(','); if (isSetHeader(key)) { _.each(tail, function(cookieVal) { var splitCookie = cookieVal.split('='); response.cookie(_.first(splitCookie), _.join(_.tail(splitCookie), '=')); }); } if (isClearHeader(key)) { _.each(tail, function(name) { response.clearCookie(name); }); } }); next(); };
it('should merge extraneous MJSONWP caps into W3C', function () { let jsonwpCaps = { ...BASE_CAPS, automationName: 'Fake', }; const {desiredCaps, processedJsonwpCapabilities, processedW3CCapabilities, protocol} = parseCapsForInnerDriver(jsonwpCaps, { alwaysMatch: {platformName: 'Fake', propertyName: 'PROP_NAME'}, }); // We expect a combo of jsonwp caps and w3c provided caps with `appium:` prefix for non-standard caps const expectedCaps = {}; for (let [key, value] of _.toPairs(jsonwpCaps)) { if (key !== 'platformName') { expectedCaps[`appium:${key}`] = value; } else { expectedCaps[key] = value; } } expectedCaps['appium:propertyName'] = 'PROP_NAME'; processedW3CCapabilities.alwaysMatch.should.eql(expectedCaps); desiredCaps.should.eql({ ...jsonwpCaps, propertyName: 'PROP_NAME', }); processedJsonwpCapabilities.should.eql(jsonwpCaps); protocol.should.equal('W3C'); });
return async (dispatch, getState) => { // Set the selected element in the source tree dispatch({type: SELECT_ELEMENT, path}); const state = getState().inspector; const {attributes: selectedElementAttributes, xpath: selectedElementXPath} = state.selectedElement; const {sourceXML} = state; // Expand all of this element's ancestors so that it's visible in the source tree let {expandedPaths} = getState().inspector; let pathArr = path.split('.').slice(0, path.length - 1); while (pathArr.length > 1) { pathArr.splice(pathArr.length - 1); let path = pathArr.join('.'); if (expandedPaths.indexOf(path) < 0) { expandedPaths.push(path); } } dispatch({type: SET_EXPANDED_PATHS, paths: expandedPaths}); // Find the optimal selection strategy. If none found, fall back to XPath. const strategyMap = _.toPairs(getLocators(selectedElementAttributes, sourceXML)); strategyMap.push(['xpath', selectedElementXPath]); // Debounce find element so that if another element is selected shortly after, cancel the previous search await findElement(strategyMap, dispatch, getState, path); };
.then(data => { // redo serialization to destroy non-serializable stuff like functions. const raw = JSON.stringify(localeval(`${data}; SHIPDATA`)) const kcReplayData = JSON.parse(raw) const resultObj = _.fromPairs( _.flatMap( _.toPairs(kcReplayData), ([mstIdStr, shipRaw]) => { const mstId = Number(mstIdStr) if (! _.isInteger(mstId) || mstId <= 1500) return [] return [ [ // key mstIdStr, // value _.fromPairs( 'HP FP AR TP EV AA ASW SPD LOS RNG LUK SLOTS EQUIPS' .split(' ').map(propName => [propName, shipRaw[propName]])), ], ] })) writeJsonSync('assets/abyssal.json', resultObj) })
/* * Restart the session with the original caps, * preserving the timeout config. */ async reset () { log.debug('Resetting app mid-session'); log.debug('Running generic full reset'); // preserving state let currentConfig = {}; for (let property of ['implicitWaitMs', 'newCommandTimeoutMs', 'sessionId', 'resetOnUnexpectedShutdown']) { currentConfig[property] = this[property]; } // We also need to preserve the unexpected shutdown, and make sure it is not cancelled during reset. this.resetOnUnexpectedShutdown = () => {}; try { await this.deleteSession(this.sessionId); log.debug('Restarting app'); await this.createSession(this.caps); } finally { // always restore state. for (let [key, value] of _.toPairs(currentConfig)) { this[key] = value; } } this.clearNewCommandTimeout(); }
return (dispatch, getState) => { const state = getState().session; const {rawDesiredCaps, caps: capsArray} = state; try { const newCaps = JSON.parse(rawDesiredCaps); // Transform the current caps array to an object let caps = {}; for (let {type, name, value} of capsArray) { caps[name] = {type, value}; } // Translate the caps JSON to array format let newCapsArray = toPairs(newCaps).map(([name, value]) => ({ type: (() => { let type = typeof value; // If we already have this cap and it's file type, keep the type the same if (caps[name] && caps[name].type === 'file' && type === 'string') { return 'file'; } else if (type === 'string') { return 'text'; } else { return type; } })(), name, value, })); dispatch({type: SAVE_RAW_DESIRED_CAPS, caps: newCapsArray}); } catch (e) { dispatch({type: SHOW_DESIRED_CAPS_JSON_ERROR, message: e.message}); } };
validateDesiredCaps (caps) { if (!this.shouldValidateCaps) { return true; } // we validate on only caps that are not null or undefined so that if // someone sends in e.g. null they don't get a 'was not a string' // error; just count as though it weren't sent in at all let validationErrors = validator.validate(_.pickBy(caps, util.hasValue), this._constraints, {fullMessages: false}); if (validationErrors) { let message = `The desiredCapabilities object was not valid for the ` + `following reason(s):`; for (let [attribute, reasons] of _.toPairs(validationErrors)) { for (let reason of reasons) { message += ` ${attribute} ${reason},`; } } message = `${message.slice(0, -1)}.`; log.errorAndThrow(new errors.SessionNotCreatedError(message)); } this.logExtraCaps(caps); return true; }
async getSessions () { let sessions = []; for (let [id, driver] of _.toPairs(this.sessions)) { sessions.push({id: id, capabilities: driver.caps}); } return sessions; }
export function generatePage(document, config, helpers, renderers) { if (!document.sourcePath) { throw new Error(`Source path not specified. Add "sourcePath" front matter field.`); } if (!document.layout) { throw new Error(`Layout not specified for ${document.sourcePath}. Add "layout" front matter field.`); } let pagePath = removeExtension(document.sourcePath); let pageContext = makeContext(document, config, helpers); if (document.layout === 'RSS') { return { pagePath: `${pagePath}.xml`, content: renderRss(pageContext), }; } let [templateExtension, render] = _.toPairs(renderers).shift(); let templateFile = `${document.layout}.${templateExtension}`; let content = render(templateFile, pageContext); let pageExtension = getExtension(document.layout) || 'html'; return { pagePath: `${pagePath}.${pageExtension}`, content, }; }
function recurse ($, el, fn) { const attrs = !isEmpty(el.attribs) ? ' ' + toPairs(el.attribs).map(([k, v]) => `${k}='${v}'`).join(' ') : '' return `<${el.name}${attrs}>${fn($(el))}</${el.name}>` }
const matches = (conditions, event) => { if (!_.isPlainObject(conditions)) { conditions = { text: conditions } } const pairs = _.toPairs(conditions) return _.every(pairs, ([key, comparrer]) => { const eventValue = _.get(event, key, null) if (_.isFunction(comparrer)) { return comparrer(eventValue, event) === true } else if (_.isRegExp(comparrer)) { const matches = comparrer.test(eventValue) if (matches && _.isString(eventValue)) { if (_.isNil(event.captured)) { event.captured = [] } const a = _.tail(comparrer.exec(eventValue)) a.forEach(m => event.captured.push(m)) } return matches } else { return _.isEqual(comparrer, eventValue) } }) }