How to use cached method in Best

Best JavaScript code snippet using best

CachedSource.js

Source:CachedSource.js Github

copy

Full Screen

1/*2 MIT License http://www.opensource.org/licenses/mit-license.php3 Author Tobias Koppers @sokra4*/5"use strict";6const Source = require("./Source");7const streamChunksOfSourceMap = require("./helpers/streamChunksOfSourceMap");8const streamChunksOfRawSource = require("./helpers/streamChunksOfRawSource");9const streamAndGetSourceAndMap = require("./helpers/streamAndGetSourceAndMap");10const mapToBufferedMap = map => {11 if (typeof map !== "object" || !map) return map;12 const bufferedMap = Object.assign({}, map);13 if (map.mappings) {14 bufferedMap.mappings = Buffer.from(map.mappings, "utf-8");15 }16 if (map.sourcesContent) {17 bufferedMap.sourcesContent = map.sourcesContent.map(18 str => str && Buffer.from(str, "utf-8")19 );20 }21 return bufferedMap;22};23const bufferedMapToMap = bufferedMap => {24 if (typeof bufferedMap !== "object" || !bufferedMap) return bufferedMap;25 const map = Object.assign({}, bufferedMap);26 if (bufferedMap.mappings) {27 map.mappings = bufferedMap.mappings.toString("utf-8");28 }29 if (bufferedMap.sourcesContent) {30 map.sourcesContent = bufferedMap.sourcesContent.map(31 buffer => buffer && buffer.toString("utf-8")32 );33 }34 return map;35};36class CachedSource extends Source {37 constructor(source, cachedData) {38 super();39 this._source = source;40 this._cachedSourceType = cachedData ? cachedData.source : undefined;41 this._cachedSource = undefined;42 this._cachedBuffer = cachedData ? cachedData.buffer : undefined;43 this._cachedSize = cachedData ? cachedData.size : undefined;44 this._cachedMaps = cachedData ? cachedData.maps : new Map();45 this._cachedHashUpdate = cachedData ? cachedData.hash : undefined;46 }47 getCachedData() {48 const bufferedMaps = new Map();49 for (const pair of this._cachedMaps) {50 let cacheEntry = pair[1];51 if (cacheEntry.bufferedMap === undefined) {52 cacheEntry.bufferedMap = mapToBufferedMap(53 this._getMapFromCacheEntry(cacheEntry)54 );55 }56 bufferedMaps.set(pair[0], {57 map: undefined,58 bufferedMap: cacheEntry.bufferedMap59 });60 }61 // We don't want to cache strings62 // So if we have a caches sources63 // create a buffer from it and only store64 // if it was a Buffer or string65 if (this._cachedSource) {66 this.buffer();67 }68 return {69 buffer: this._cachedBuffer,70 source:71 this._cachedSourceType !== undefined72 ? this._cachedSourceType73 : typeof this._cachedSource === "string"74 ? true75 : Buffer.isBuffer(this._cachedSource)76 ? false77 : undefined,78 size: this._cachedSize,79 maps: bufferedMaps,80 hash: this._cachedHashUpdate81 };82 }83 originalLazy() {84 return this._source;85 }86 original() {87 if (typeof this._source === "function") this._source = this._source();88 return this._source;89 }90 source() {91 const source = this._getCachedSource();92 if (source !== undefined) return source;93 return (this._cachedSource = this.original().source());94 }95 _getMapFromCacheEntry(cacheEntry) {96 if (cacheEntry.map !== undefined) {97 return cacheEntry.map;98 } else if (cacheEntry.bufferedMap !== undefined) {99 return (cacheEntry.map = bufferedMapToMap(cacheEntry.bufferedMap));100 }101 }102 _getCachedSource() {103 if (this._cachedSource !== undefined) return this._cachedSource;104 if (this._cachedBuffer && this._cachedSourceType !== undefined) {105 return (this._cachedSource = this._cachedSourceType106 ? this._cachedBuffer.toString("utf-8")107 : this._cachedBuffer);108 }109 }110 buffer() {111 if (this._cachedBuffer !== undefined) return this._cachedBuffer;112 if (this._cachedSource !== undefined) {113 if (Buffer.isBuffer(this._cachedSource)) {114 return (this._cachedBuffer = this._cachedSource);115 }116 return (this._cachedBuffer = Buffer.from(this._cachedSource, "utf-8"));117 }118 if (typeof this.original().buffer === "function") {119 return (this._cachedBuffer = this.original().buffer());120 }121 const bufferOrString = this.source();122 if (Buffer.isBuffer(bufferOrString)) {123 return (this._cachedBuffer = bufferOrString);124 }125 return (this._cachedBuffer = Buffer.from(bufferOrString, "utf-8"));126 }127 size() {128 if (this._cachedSize !== undefined) return this._cachedSize;129 if (this._cachedBuffer !== undefined) {130 return (this._cachedSize = this._cachedBuffer.length);131 }132 const source = this._getCachedSource();133 if (source !== undefined) {134 return (this._cachedSize = Buffer.byteLength(source));135 }136 return (this._cachedSize = this.original().size());137 }138 sourceAndMap(options) {139 const key = options ? JSON.stringify(options) : "{}";140 const cacheEntry = this._cachedMaps.get(key);141 // Look for a cached map142 if (cacheEntry !== undefined) {143 // We have a cached map in some representation144 const map = this._getMapFromCacheEntry(cacheEntry);145 // Either get the cached source or compute it146 return { source: this.source(), map };147 }148 // Look for a cached source149 let source = this._getCachedSource();150 // Compute the map151 let map;152 if (source !== undefined) {153 map = this.original().map(options);154 } else {155 // Compute the source and map together.156 const sourceAndMap = this.original().sourceAndMap(options);157 source = sourceAndMap.source;158 map = sourceAndMap.map;159 this._cachedSource = source;160 }161 this._cachedMaps.set(key, {162 map,163 bufferedMap: undefined164 });165 return { source, map };166 }167 streamChunks(options, onChunk, onSource, onName) {168 const key = options ? JSON.stringify(options) : "{}";169 if (170 this._cachedMaps.has(key) &&171 (this._cachedBuffer !== undefined || this._cachedSource !== undefined)172 ) {173 const { source, map } = this.sourceAndMap(options);174 if (map) {175 return streamChunksOfSourceMap(176 source,177 map,178 onChunk,179 onSource,180 onName,181 !!(options && options.finalSource),182 true183 );184 } else {185 return streamChunksOfRawSource(186 source,187 onChunk,188 onSource,189 onName,190 !!(options && options.finalSource)191 );192 }193 }194 const { result, source, map } = streamAndGetSourceAndMap(195 this.original(),196 options,197 onChunk,198 onSource,199 onName200 );201 this._cachedSource = source;202 this._cachedMaps.set(key, {203 map,204 bufferedMap: undefined205 });206 return result;207 }208 map(options) {209 const key = options ? JSON.stringify(options) : "{}";210 const cacheEntry = this._cachedMaps.get(key);211 if (cacheEntry !== undefined) {212 return this._getMapFromCacheEntry(cacheEntry);213 }214 const map = this.original().map(options);215 this._cachedMaps.set(key, {216 map,217 bufferedMap: undefined218 });219 return map;220 }221 updateHash(hash) {222 if (this._cachedHashUpdate !== undefined) {223 for (const item of this._cachedHashUpdate) hash.update(item);224 return;225 }226 const update = [];227 let currentString = undefined;228 const tracker = {229 update: item => {230 if (typeof item === "string" && item.length < 10240) {231 if (currentString === undefined) {232 currentString = item;233 } else {234 currentString += item;235 if (currentString.length > 102400) {236 update.push(Buffer.from(currentString));237 currentString = undefined;238 }239 }240 } else {241 if (currentString !== undefined) {242 update.push(Buffer.from(currentString));243 currentString = undefined;244 }245 update.push(item);246 }247 }248 };249 this.original().updateHash(tracker);250 if (currentString !== undefined) {251 update.push(Buffer.from(currentString));252 }253 for (const item of update) hash.update(item);254 this._cachedHashUpdate = update;255 }256}...

Full Screen

Full Screen

AbstractComponent.js

Source:AbstractComponent.js Github

copy

Full Screen

1/**2 * @private3 * This is the abstract class for {@link Ext.Component}.4 *5 * This should never be overriden.6 */7Ext.define('Ext.AbstractComponent', {8 extend: 'Ext.Evented',9 onClassExtended: function(Class, members) {10 if (!members.hasOwnProperty('cachedConfig')) {11 return;12 }13 var prototype = Class.prototype,14 config = members.config,15 cachedConfig = members.cachedConfig,16 cachedConfigList = prototype.cachedConfigList,17 hasCachedConfig = prototype.hasCachedConfig,18 name, value;19 delete members.cachedConfig;20 prototype.cachedConfigList = cachedConfigList = (cachedConfigList) ? cachedConfigList.slice() : [];21 prototype.hasCachedConfig = hasCachedConfig = (hasCachedConfig) ? Ext.Object.chain(hasCachedConfig) : {};22 if (!config) {23 members.config = config = {};24 }25 for (name in cachedConfig) {26 if (cachedConfig.hasOwnProperty(name)) {27 value = cachedConfig[name];28 if (!hasCachedConfig[name]) {29 hasCachedConfig[name] = true;30 cachedConfigList.push(name);31 }32 config[name] = value;33 }34 }35 },36 getElementConfig: Ext.emptyFn,37 referenceAttributeName: 'reference',38 referenceSelector: '[reference]',39 /**40 * @private41 * Significantly improve instantiation time for Component with multiple references42 * Ext.Element instance of the reference domNode is only created the very first time43 * it's ever used44 */45 addReferenceNode: function(name, domNode) {46 Ext.Object.defineProperty(this, name, {47 get: function() {48 var reference;49 delete this[name];50 this[name] = reference = new Ext.Element(domNode);51 return reference;52 },53 configurable: true54 });55 },56 initElement: function() {57 var prototype = this.self.prototype,58 id = this.getId(),59 referenceList = [],60 cleanAttributes = true,61 referenceAttributeName = this.referenceAttributeName,62 needsOptimization = false,63 renderTemplate, renderElement, element,64 referenceNodes, i, ln, referenceNode, reference,65 configNameCache, defaultConfig, cachedConfigList, initConfigList, initConfigMap, configList,66 elements, name, nameMap, internalName;67 if (prototype.hasOwnProperty('renderTemplate')) {68 renderTemplate = this.renderTemplate.cloneNode(true);69 renderElement = renderTemplate.firstChild;70 }71 else {72 cleanAttributes = false;73 needsOptimization = true;74 renderTemplate = document.createDocumentFragment();75 renderElement = Ext.Element.create(this.getElementConfig(), true);76 renderTemplate.appendChild(renderElement);77 }78 referenceNodes = renderTemplate.querySelectorAll(this.referenceSelector);79 for (i = 0,ln = referenceNodes.length; i < ln; i++) {80 referenceNode = referenceNodes[i];81 reference = referenceNode.getAttribute(referenceAttributeName);82 if (cleanAttributes) {83 referenceNode.removeAttribute(referenceAttributeName);84 }85 if (reference == 'element') {86 referenceNode.id = id;87 this.element = element = new Ext.Element(referenceNode);88 }89 else {90 this.addReferenceNode(reference, referenceNode);91 }92 referenceList.push(reference);93 }94 this.referenceList = referenceList;95 if (!this.innerElement) {96 this.innerElement = element;97 }98 if (renderElement === element.dom) {99 this.renderElement = element;100 }101 else {102 this.addReferenceNode('renderElement', renderElement);103 }104 // This happens only *once* per class, during the very first instantiation105 // to optimize renderTemplate based on cachedConfig106 if (needsOptimization) {107 configNameCache = Ext.Class.configNameCache;108 defaultConfig = this.config;109 cachedConfigList = this.cachedConfigList;110 initConfigList = this.initConfigList;111 initConfigMap = this.initConfigMap;112 configList = [];113 for (i = 0,ln = cachedConfigList.length; i < ln; i++) {114 name = cachedConfigList[i];115 nameMap = configNameCache[name];116 if (initConfigMap[name]) {117 initConfigMap[name] = false;118 Ext.Array.remove(initConfigList, name);119 }120 if (defaultConfig[name] !== null) {121 configList.push(name);122 this[nameMap.get] = this[nameMap.initGet];123 }124 }125 for (i = 0,ln = configList.length; i < ln; i++) {126 name = configList[i];127 nameMap = configNameCache[name];128 internalName = nameMap.internal;129 this[internalName] = null;130 this[nameMap.set].call(this, defaultConfig[name]);131 delete this[nameMap.get];132 prototype[internalName] = this[internalName];133 }134 renderElement = this.renderElement.dom;135 prototype.renderTemplate = renderTemplate = document.createDocumentFragment();136 renderTemplate.appendChild(renderElement.cloneNode(true));137 elements = renderTemplate.querySelectorAll('[id]');138 for (i = 0,ln = elements.length; i < ln; i++) {139 element = elements[i];140 element.removeAttribute('id');141 }142 for (i = 0,ln = referenceList.length; i < ln; i++) {143 reference = referenceList[i];144 this[reference].dom.removeAttribute('reference');145 }146 }147 return this;148 }...

Full Screen

Full Screen

test_functional.py

Source:test_functional.py Github

copy

Full Screen

...52 raise RuntimeError("never called, slots not supported")53# noinspection PyStatementEffect54@unittest.skipIf(sys.version_info >= (3, 8), "Python 3.8+ uses standard library implementation.")55class TestCachedProperty(unittest.TestCase):56 def test_cached(self):57 item = CachedCostItem()58 self.assertEqual(item.cost, 2)59 self.assertEqual(item.cost, 2) # not 360 def test_cached_attribute_name_differs_from_func_name(self):61 item = OptionallyCachedCostItem()62 self.assertEqual(item.get_cost(), 2)63 self.assertEqual(item.cached_cost, 3)64 self.assertEqual(item.get_cost(), 4)65 self.assertEqual(item.cached_cost, 3)66 def test_threaded(self):67 go = threading.Event()68 item = CachedCostItemWait(go)69 num_threads = 370 orig_si = sys.getswitchinterval()...

Full Screen

Full Screen

test_inlinequeryresultcachedvideo.py

Source:test_inlinequeryresultcachedvideo.py Github

copy

Full Screen

1#!/usr/bin/env python2#3# A library that provides a Python interface to the Telegram Bot API4# Copyright (C) 2015-20205# Leandro Toledo de Souza <devs@python-telegram-bot.org>6#7# This program is free software: you can redistribute it and/or modify8# it under the terms of the GNU Lesser Public License as published by9# the Free Software Foundation, either version 3 of the License, or10# (at your option) any later version.11#12# This program is distributed in the hope that it will be useful,13# but WITHOUT ANY WARRANTY; without even the implied warranty of14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the15# GNU Lesser Public License for more details.16#17# You should have received a copy of the GNU Lesser Public License18# along with this program. If not, see [http://www.gnu.org/licenses/].19import pytest20from telegram import (InlineKeyboardMarkup, InlineKeyboardButton, InputTextMessageContent,21 InlineQueryResultCachedVideo, InlineQueryResultCachedVoice)22@pytest.fixture(scope='class')23def inline_query_result_cached_video():24 return InlineQueryResultCachedVideo(25 TestInlineQueryResultCachedVideo.id_,26 TestInlineQueryResultCachedVideo.video_file_id,27 TestInlineQueryResultCachedVideo.title,28 caption=TestInlineQueryResultCachedVideo.caption,29 parse_mode=TestInlineQueryResultCachedVideo.parse_mode,30 description=TestInlineQueryResultCachedVideo.description,31 input_message_content=TestInlineQueryResultCachedVideo.input_message_content,32 reply_markup=TestInlineQueryResultCachedVideo.reply_markup)33class TestInlineQueryResultCachedVideo:34 id_ = 'id'35 type_ = 'video'36 video_file_id = 'video file id'37 title = 'title'38 caption = 'caption'39 parse_mode = 'Markdown'40 description = 'description'41 input_message_content = InputTextMessageContent('input_message_content')42 reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('reply_markup')]])43 def test_expected_values(self, inline_query_result_cached_video):44 assert inline_query_result_cached_video.type == self.type_45 assert inline_query_result_cached_video.id == self.id_46 assert inline_query_result_cached_video.video_file_id == self.video_file_id47 assert inline_query_result_cached_video.title == self.title48 assert inline_query_result_cached_video.description == self.description49 assert inline_query_result_cached_video.caption == self.caption50 assert inline_query_result_cached_video.parse_mode == self.parse_mode51 assert (inline_query_result_cached_video.input_message_content.to_dict()52 == self.input_message_content.to_dict())53 assert (inline_query_result_cached_video.reply_markup.to_dict()54 == self.reply_markup.to_dict())55 def test_to_dict(self, inline_query_result_cached_video):56 inline_query_result_cached_video_dict = inline_query_result_cached_video.to_dict()57 assert isinstance(inline_query_result_cached_video_dict, dict)58 assert (inline_query_result_cached_video_dict['type']59 == inline_query_result_cached_video.type)60 assert inline_query_result_cached_video_dict['id'] == inline_query_result_cached_video.id61 assert (inline_query_result_cached_video_dict['video_file_id']62 == inline_query_result_cached_video.video_file_id)63 assert (inline_query_result_cached_video_dict['title']64 == inline_query_result_cached_video.title)65 assert (inline_query_result_cached_video_dict['description']66 == inline_query_result_cached_video.description)67 assert (inline_query_result_cached_video_dict['caption']68 == inline_query_result_cached_video.caption)69 assert (inline_query_result_cached_video_dict['parse_mode']70 == inline_query_result_cached_video.parse_mode)71 assert (inline_query_result_cached_video_dict['input_message_content']72 == inline_query_result_cached_video.input_message_content.to_dict())73 assert (inline_query_result_cached_video_dict['reply_markup']74 == inline_query_result_cached_video.reply_markup.to_dict())75 def test_equality(self):76 a = InlineQueryResultCachedVideo(self.id_, self.video_file_id, self.title)77 b = InlineQueryResultCachedVideo(self.id_, self.video_file_id, self.title)78 c = InlineQueryResultCachedVideo(self.id_, '', self.title)79 d = InlineQueryResultCachedVideo('', self.video_file_id, self.title)80 e = InlineQueryResultCachedVoice(self.id_, '', '')81 assert a == b82 assert hash(a) == hash(b)83 assert a is not b84 assert a == c85 assert hash(a) == hash(c)86 assert a != d87 assert hash(a) != hash(d)88 assert a != e...

Full Screen

Full Screen

tagsView.js

Source:tagsView.js Github

copy

Full Screen

1const state = {2 visitedViews: [],3 cachedViews: []4}5const mutations = {6 ADD_VISITED_VIEW: (state, view) => {7 if (state.visitedViews.some(v => v.path === view.path)) return8 state.visitedViews.push(9 Object.assign({}, view, {10 title: view.meta.title || 'no-name'11 })12 )13 },14 ADD_CACHED_VIEW: (state, view) => {15 if (state.cachedViews.includes(view.name)) return16 if (!view.meta.noCache) {17 state.cachedViews.push(view.name)18 }19 },20 DEL_VISITED_VIEW: (state, view) => {21 for (const [i, v] of state.visitedViews.entries()) {22 if (v.path === view.path) {23 state.visitedViews.splice(i, 1)24 break25 }26 }27 },28 DEL_CACHED_VIEW: (state, view) => {29 const index = state.cachedViews.indexOf(view.name)30 index > -1 && state.cachedViews.splice(index, 1)31 },32 DEL_OTHERS_VISITED_VIEWS: (state, view) => {33 state.visitedViews = state.visitedViews.filter(v => {34 return v.meta.affix || v.path === view.path35 })36 },37 DEL_OTHERS_CACHED_VIEWS: (state, view) => {38 const index = state.cachedViews.indexOf(view.name)39 if (index > -1) {40 state.cachedViews = state.cachedViews.slice(index, index + 1)41 } else {42 // if index = -1, there is no cached tags43 state.cachedViews = []44 }45 },46 DEL_ALL_VISITED_VIEWS: state => {47 // keep affix tags48 const affixTags = state.visitedViews.filter(tag => tag.meta.affix)49 state.visitedViews = affixTags50 },51 DEL_ALL_CACHED_VIEWS: state => {52 state.cachedViews = []53 },54 UPDATE_VISITED_VIEW: (state, view) => {55 for (let v of state.visitedViews) {56 if (v.path === view.path) {57 v = Object.assign(v, view)58 break59 }60 }61 }62}63const actions = {64 addView({ dispatch }, view) {65 dispatch('addVisitedView', view)66 dispatch('addCachedView', view)67 },68 addVisitedView({ commit }, view) {69 commit('ADD_VISITED_VIEW', view)70 },71 addCachedView({ commit }, view) {72 commit('ADD_CACHED_VIEW', view)73 },74 delView({ dispatch, state }, view) {75 return new Promise(resolve => {76 dispatch('delVisitedView', view)77 dispatch('delCachedView', view)78 resolve({79 visitedViews: [...state.visitedViews],80 cachedViews: [...state.cachedViews]81 })82 })83 },84 delVisitedView({ commit, state }, view) {85 return new Promise(resolve => {86 commit('DEL_VISITED_VIEW', view)87 resolve([...state.visitedViews])88 })89 },90 delCachedView({ commit, state }, view) {91 return new Promise(resolve => {92 commit('DEL_CACHED_VIEW', view)93 resolve([...state.cachedViews])94 })95 },96 delOthersViews({ dispatch, state }, view) {97 return new Promise(resolve => {98 dispatch('delOthersVisitedViews', view)99 dispatch('delOthersCachedViews', view)100 resolve({101 visitedViews: [...state.visitedViews],102 cachedViews: [...state.cachedViews]103 })104 })105 },106 delOthersVisitedViews({ commit, state }, view) {107 return new Promise(resolve => {108 commit('DEL_OTHERS_VISITED_VIEWS', view)109 resolve([...state.visitedViews])110 })111 },112 delOthersCachedViews({ commit, state }, view) {113 return new Promise(resolve => {114 commit('DEL_OTHERS_CACHED_VIEWS', view)115 resolve([...state.cachedViews])116 })117 },118 delAllViews({ dispatch, state }, view) {119 return new Promise(resolve => {120 dispatch('delAllVisitedViews', view)121 dispatch('delAllCachedViews', view)122 resolve({123 visitedViews: [...state.visitedViews],124 cachedViews: [...state.cachedViews]125 })126 })127 },128 delAllVisitedViews({ commit, state }) {129 return new Promise(resolve => {130 commit('DEL_ALL_VISITED_VIEWS')131 resolve([...state.visitedViews])132 })133 },134 delAllCachedViews({ commit, state }) {135 return new Promise(resolve => {136 commit('DEL_ALL_CACHED_VIEWS')137 resolve([...state.cachedViews])138 })139 },140 updateVisitedView({ commit }, view) {141 commit('UPDATE_VISITED_VIEW', view)142 }143}144export default {145 namespaced: true,146 state,147 mutations,148 actions...

Full Screen

Full Screen

CRDataCache.py

Source:CRDataCache.py Github

copy

Full Screen

1from direct.distributed.CachedDOData import CachedDOData2# This has to be imported for __builtin__.config3from direct.showbase import ShowBase4__all__ = ["CRDataCache"]5class CRDataCache:6 # Stores cached data for DistributedObjects between instantiations on the client7 def __init__(self):8 self._doId2name2data = {}9 # maximum # of objects we will cache data for10 self._size = config.GetInt('crdatacache-size', 10)11 assert self._size > 012 # used to preserve the cache size13 self._junkIndex = 014 def destroy(self):15 del self._doId2name2data16 def setCachedData(self, doId, name, data):17 # stores a set of named data for a DistributedObject18 assert isinstance(data, CachedDOData)19 if len(self._doId2name2data) >= self._size:20 # cache is full, throw out a random doId's data21 if self._junkIndex >= len(self._doId2name2data):22 self._junkIndex = 023 junkDoId = self._doId2name2data.keys()[self._junkIndex]24 self._junkIndex += 125 for name in self._doId2name2data[junkDoId]:26 self._doId2name2data[junkDoId][name].flush()27 del self._doId2name2data[junkDoId]28 self._doId2name2data.setdefault(doId, {})29 cachedData = self._doId2name2data[doId].get(name)30 if cachedData:31 cachedData.flush()32 cachedData.destroy()33 self._doId2name2data[doId][name] = data34 def hasCachedData(self, doId):35 return doId in self._doId2name2data36 def popCachedData(self, doId):37 # retrieves all cached data for a DistributedObject and removes it from the cache38 data = self._doId2name2data[doId]39 del self._doId2name2data[doId]40 return data41 def flush(self):42 # get rid of all cached data43 for doId in self._doId2name2data:44 for name in self._doId2name2data[doId]:45 self._doId2name2data[doId][name].flush()46 self._doId2name2data = {}47 if __debug__:48 def _startMemLeakCheck(self):49 self._len = len(self._doId2name2data)50 def _stopMemLeakCheck(self):51 del self._len52 def _checkMemLeaks(self):53 assert self._len == len(self._doId2name2data)54if __debug__:55 class TestCachedData(CachedDOData):56 def __init__(self):57 CachedDOData.__init__(self)58 self._destroyed = False59 self._flushed = False60 def destroy(self):61 CachedDOData.destroy(self)62 self._destroyed = True63 def flush(self):64 CachedDOData.flush(self)65 self._flushed = True66 dc = CRDataCache()67 dc._startMemLeakCheck()68 cd = CachedDOData()69 cd.foo = 3470 dc.setCachedData(1, 'testCachedData', cd)71 del cd72 cd = CachedDOData()73 cd.bar = 4574 dc.setCachedData(1, 'testCachedData2', cd)75 del cd76 assert dc.hasCachedData(1)77 assert dc.hasCachedData(1)78 assert not dc.hasCachedData(2)79 # data is dict of dataName->data80 data = dc.popCachedData(1)81 assert len(data) == 282 assert 'testCachedData' in data83 assert 'testCachedData2' in data84 assert data['testCachedData'].foo == 3485 assert data['testCachedData2'].bar == 4586 for cd in data.itervalues():87 cd.flush()88 del data89 dc._checkMemLeaks()90 cd = CachedDOData()91 cd.bar = 123492 dc.setCachedData(43, 'testCachedData2', cd)93 del cd94 assert dc.hasCachedData(43)95 dc.flush()96 dc._checkMemLeaks()97 dc._stopMemLeakCheck()98 dc.destroy()99 del dc...

Full Screen

Full Screen

utils.py

Source:utils.py Github

copy

Full Screen

1def in_cache(cache_store:dict, cached_arg_num=0, cached_arg_name=None):2 def get_decorator(cached_func):3 def calling_func(*args, **kwargs):4 if cached_arg_name is not None and cached_arg_name in kwargs:5 cached_var = kwargs[cached_arg_name]6 else:7 cached_var = args[cached_arg_num]8 if cached_var is not None and cached_var in cache_store:9 return cache_store[cached_var]10 func_data = cached_func(*args, **kwargs)11 if func_data is not None and cached_var is not None:12 cache_store[cached_var] = func_data13 return func_data14 return calling_func...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var bb = require('bestbuy')(process.env.BESTBUY_API_KEY);2bb.stores('(area(78701,25))', {show: 'storeId,name,city,distance,phone'}).then(function(data){3 console.log(data);4});5bb.products('(search=tv&categoryPath.id=abcat0101000)', {show: 'sku,name,salePrice,regularPrice,shortDescription,thumbnailImage'}).then(function(data){6 console.log(data);7});8bb.products('(search=tv&categoryPath.id=abcat0101000)', {show: 'sku,name,salePrice,regularPrice,shortDescription,thumbnailImage', sort: 'regularPrice.asc'}).then(function(data){9 console.log(data);10});11bb.products('(search=tv&categoryPath.id=abcat0101000)', {show: 'sku,name,salePrice,regularPrice,shortDescription,thumbnailImage', sort: 'regularPrice.asc', pageSize: 10, page: 1}).then(function(data){12 console.log(data);13});14bb.products('(search=tv&categoryPath.id=abcat0101000)', {show: 'sku,name,salePrice,regularPrice,

Full Screen

Using AI Code Generation

copy

Full Screen

1var bestbuy = require('bestbuy')(process.env.BEST_BUY_API_KEY);2var express = require('express');3var app = express();4var router = express.Router();5var request = require('request');6var fs = require('fs');7var path = require('path');8var bodyParser = require('body-parser');9var jsonParser = bodyParser.json();10var urlencodedParser = bodyParser.urlencoded({ extended: false });11var jsonfile = require('jsonfile');12var file = './data.json';13var data = require('./data.json');14var json = require('./data.json');15var url = require('url');16var http = require('http');17var https = require('https');18var querystring = require('querystring');19var request = require('request');20var server = app.listen(process.env.PORT || 3000, function () {21 var host = server.address().address;22 var port = server.address().port;23});24app.use('/', router);25app.use(express.static(__dirname + '/public'));26app.use(bodyParser.json());27app.use(bodyParser.urlencoded({ extended: true }));28app.set('view engine', 'ejs');29app.get('/', function(req, res) {30 res.render('pages/index');31});32app.get('/about', function(req, res) {33 res.render('pages/about');34});35app.get('/contact', function(req, res) {36 res.render('pages/contact');37});38app.get('/search', function(req, res) {39 res.render('pages/search');40});41app.get('/searchresults', function(req, res) {42 res.render('pages/searchresults');43});44app.get('/searchresults2', function(req, res) {45 res.render('pages/searchresults2');46});47app.get('/searchresults3', function(req, res) {48 res.render('pages/searchresults3');49});50app.get('/searchresults4', function(req, res) {51 res.render('pages/search

Full Screen

Using AI Code Generation

copy

Full Screen

1var bestbuy = require('bestbuy')('yourAPIkey');2var fs = require('fs');3var cache = require('memory-cache');4var cacheTime = 1000 * 60 * 60 * 24;5bestbuy.products('(search=galaxy&categoryPath.id=abcat0502000)', {show: 'sku,name,regularPrice,salePrice,thumbnailImage,shortDescription,longDescription', page: 1, pageSize: 5, sort: 'regularPrice.asc', format: 'json'}).then(function(data) {6 cache.put('bestBuyCache', data, cacheTime);7});8var bestBuyCache = cache.get('bestBuyCache');9fs.writeFile('bestBuyCache.json', JSON.stringify(bestBuyCache), function(err) {10 if (err) {11 console.log(err);12 }13});14fs.readFile('bestBuyCache.json', function(err, data) {15 if (err) {16 console.log(err);17 }18 console.log(data);19});20cache.del('bestBuyCache');

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Best automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful