{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'PDF TO Markdown' && linkText !== 'PDF TO Markdown' ) { link.textContent = 'PDF TO Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== 'Voice Cloning' ) { link.textContent = 'Voice Cloning'; link.href = 'https://vibevoice.info/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'PDF TO Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n\n\nA: You're experiencing this bug: http://www.brunildo.org/test/IEWlispace.php\nAs you can see, different combinations cause the problem, so there are various way to fix it.\nHere's your original code: http://jsbin.com/itaxek\nOne possible fix is to move width: 200px; from ul li ul li to ul ul: http://jsbin.com/itaxek/2\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635223\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967515,"cells":{"text":{"kind":"string","value":"Q: Bitmap Cache (SoftReference, Hard) on Lazy List does not seem to work properly - Android I have read several topics on lazy list loading in stackoverflow and I am trying to understand how to work on the different cache levels in android.\nAs mentioned here:\nLazy load of images in ListView\nI used the \nMultithreading For Performance, a tutorial by Gilles Debunne.\nexample. I modified it in order to just work with the correct way and also work with 1.6. Here is the code:\n/*\n * Copyright (C) 2010 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npublic class ImageDownloader \n{\n\nprivate static final String TAG = \"ImageDownloader\";\n\nprivate static final int HARD_CACHE_CAPACITY = 40;\nprivate static final int DELAY_BEFORE_PURGE = 10 * 1000; // in milliseconds\n\nprivate final static ConcurrentHashMap> sSoftBitmapCache = new ConcurrentHashMap>(HARD_CACHE_CAPACITY / 2);\n\n/* Download the specified image from the Internet and binds it to the provided ImageView. The\n * binding is immediate if the image is found in the cache and will be done asynchronously\n * otherwise. A null bitmap will be associated to the ImageView if an error occurs.\n *\n * @param url The URL of the image to download.\n * @param imageView The ImageView to bind the downloaded image to.\n */\n\npublic void download(String url, ImageView imageView) {\n\n Log.d(TAG, \"download(String url, ImageView imageView)\");\n\n resetPurgeTimer();\n\n Bitmap bitmap = getBitmapFromCache(url);\n\n if (bitmap == null) {\n\n Log.d(TAG, \"(bitmap == null)\");\n\n forceDownload(url, imageView);\n\n } else {\n\n Log.d(TAG, \"(bitmap != null) \");\n\n cancelPotentialDownload(url, imageView);\n imageView.setImageBitmap(bitmap);\n }\n}\n\n/*\n * Same as download but the image is always downloaded and the cache is not used.\n * Kept private at the moment as its interest is not clear.\n private void forceDownload(String url, ImageView view) {\n forceDownload(url, view, null);\n }\n */\n\n/**\n * Same as download but the image is always downloaded and the cache is not used.\n * Kept private at the moment as its interest is not clear.\n */\nprivate void forceDownload(String url, ImageView imageView) {\n\n Log.d(TAG, \"forceDownload(String url, ImageView imageView)\");\n\n\n // State sanity: url is guaranteed to never be null in DownloadedDrawable and cache keys.\n if (url == null) {\n\n Log.d(TAG, \"(url == null)\");\n\n imageView.setImageDrawable(null);\n return;\n }\n Bitmap bitmap = null;\n BitmapDownloaderTask task = null;\n\n if (cancelPotentialDownload(url, imageView)) {\n\n Log.d(TAG, \"(cancelPotentialDownload(url, imageView))\");\n\n\n task = new BitmapDownloaderTask(imageView);\n DownloadedDrawable downloadedDrawable = new DownloadedDrawable(task);\n imageView.setImageDrawable(downloadedDrawable);\n imageView.setMinimumHeight(156);\n task.execute(url);\n\n }\n}\n\n/**\n * Returns true if the current download has been canceled or if there was no download in\n * progress on this image view.\n * Returns false if the download in progress deals with the same url. The download is not\n * stopped in that case.\n */\nprivate static boolean cancelPotentialDownload(String url, ImageView imageView) {\n\n Log.d(TAG, \"---cancelPotentialDownload(String url, ImageView imageView)----)\");\n\n\n BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView);\n\n if (bitmapDownloaderTask != null) {\n\n Log.d(TAG, \"(bitmapDownloaderTask != null)\");\n\n\n String bitmapUrl = bitmapDownloaderTask.url;\n\n if ((bitmapUrl == null) || (!bitmapUrl.equals(url))) {\n\n Log.d(TAG, \"(((bitmapUrl == null) || (!bitmapUrl.equals(url)))\");\n\n\n bitmapDownloaderTask.cancel(true);\n } else {\n\n Log.d(TAG, \"The same URL is already being downloaded.\");\n\n // The same URL is already being downloaded.\n return false;\n }\n }\n return true;\n}\n\n/**\n * @param imageView Any imageView\n * @return Retrieve the currently active download task (if any) associated with this imageView.\n * null if there is no such task.\n */\nprivate static BitmapDownloaderTask getBitmapDownloaderTask(ImageView imageView) {\n\n Log.d(TAG, \"getBitmapDownloaderTask(ImageView imageView)\");\n\n\n if (imageView != null) {\n\n Log.d(TAG, \"(imageView != null) )\");\n\n\n Drawable drawable = imageView.getDrawable();\n\n if (drawable instanceof DownloadedDrawable) {\n\n Log.d(TAG, \"(drawable instanceof DownloadedDrawable) \");\n\n\n DownloadedDrawable downloadedDrawable = (DownloadedDrawable)drawable;\n return downloadedDrawable.getBitmapDownloaderTask();\n }\n }\n return null;\n}\n\nBitmap downloadBitmap(String stringUrl) {\n\n Log.d(TAG, \"(downloadBitmap(String stringUrl)\");\n\n\n URL url = null;\n HttpURLConnection connection = null;\n InputStream inputStream = null;\n\n try {\n url = new URL(stringUrl);\n connection = (HttpURLConnection) url.openConnection();\n connection.setUseCaches(true);\n inputStream = connection.getInputStream();\n\n return BitmapFactory.decodeStream(new FlushedInputStream(inputStream));\n /* \n BitmapFactory.Options bfOptions=new BitmapFactory.Options();\n\n bfOptions.inDither=false; //Disable Dithering mode\n bfOptions.inPurgeable=true; //Tell to gc that whether it needs free memory, the Bitmap can be cleared\n bfOptions.inInputShareable=true; //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future\n bfOptions.inTempStorage=new byte[32 * 1024]; \n\n\n Bitmap b=BitmapFactory.decodeStream(new FlushedInputStream(inputStream), null,bfOptions );\n\n return b;\n */ \n\n } catch (IOException e) {\n //getRequest.abort();\n Log.w(TAG, \"I/O error while retrieving bitmap from \" + url, e);\n } catch (IllegalStateException e) {\n // getRequest.abort();\n Log.w(TAG, \"Incorrect URL: \" + url);\n } catch (Exception e) {\n //getRequest.abort();\n Log.w(TAG, \"Error while retrieving bitmap from \" + url, e);\n } finally {\n if (connection != null) {\n connection.disconnect();\n }\n }\n\n\n return null;\n}\n\n/*\n * An InputStream that skips the exact number of bytes provided, unless it reaches EOF.\n */\nstatic class FlushedInputStream extends FilterInputStream {\n\n\n\n public FlushedInputStream(InputStream inputStream) {\n super(inputStream);\n }\n\n @Override\n public long skip(long n) throws IOException {\n long totalBytesSkipped = 0L;\n while (totalBytesSkipped < n) {\n long bytesSkipped = in.skip(n - totalBytesSkipped);\n if (bytesSkipped == 0L) {\n int b = read();\n if (b < 0) {\n break; // we reached EOF\n } else {\n bytesSkipped = 1; // we read one byte\n }\n }\n totalBytesSkipped += bytesSkipped;\n }\n return totalBytesSkipped;\n }\n}\n\n/**\n * The actual AsyncTask that will asynchronously download the image.\n */\nclass BitmapDownloaderTask extends AsyncTask {\n\n private String url;\n\n private final WeakReference imageViewReference;\n\n public BitmapDownloaderTask(ImageView imageView) {\n\n Log.w(TAG, \"BitmapDownloaderTask(ImageView imageView)\");\n\n imageViewReference = new WeakReference(imageView);\n }\n\n /**\n * Actual download method.\n */\n @Override\n protected Bitmap doInBackground(String... params) {\n\n Log.w(TAG, \"doInBackground\");\n\n\n url = params[0];\n return downloadBitmap(url);\n }\n\n /**\n * Once the image is downloaded, associates it to the imageView\n */\n @Override\n protected void onPostExecute(Bitmap bitmap) {\n\n Log.w(TAG, \"onPostExecute\");\n\n\n if (isCancelled()) {\n bitmap = null;\n }\n\n addBitmapToCache(url, bitmap);\n\n if (imageViewReference != null) {\n\n Log.w(TAG, \"(imageViewReference != null)\");\n\n\n ImageView imageView = imageViewReference.get();\n\n BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView);\n\n // Change bitmap only if this process is still associated with it\n // Or if we don't use any bitmap to task association (NO_DOWNLOADED_DRAWABLE mode)\n\n if ((this == bitmapDownloaderTask)) {\n\n Log.w(TAG, \" if ((this == bitmapDownloaderTask)\");\n\n\n imageView.setImageBitmap(bitmap);\n }\n }\n }\n}\n\n\n/**\n * A fake Drawable that will be attached to the imageView while the download is in progress.\n *\n *

Contains a reference to the actual download task, so that a download task can be stopped\n * if a new binding is required, and makes sure that only the last started download process can\n * bind its result, independently of the download finish order.

\n */\nstatic class DownloadedDrawable extends ColorDrawable {\n\n private final WeakReference bitmapDownloaderTaskReference;\n\n public DownloadedDrawable(BitmapDownloaderTask bitmapDownloaderTask) {\n super(Color.BLACK);\n\n Log.w(TAG, \"DownloadedDrawable(BitmapDownloaderTask bitmapDownloaderTask) \");\n\n\n bitmapDownloaderTaskReference = new WeakReference(bitmapDownloaderTask);\n }\n\n public BitmapDownloaderTask getBitmapDownloaderTask() {\n\n Log.w(TAG, \"BitmapDownloaderTask getBitmapDownloaderTask() \");\n\n\n return bitmapDownloaderTaskReference.get();\n }\n}\n\n/*\npublic void setMode(Mode mode) {\n this.mode = mode;\n clearCache();\n}\n*/\n\n/*\n * Cache-related fields and methods.\n * \n * We use a hard and a soft cache. A soft reference cache is too aggressively cleared by the\n * Garbage Collector.\n */\n\n// Hard cache, with a fixed maximum capacity and a life duration\nprivate final HashMap sHardBitmapCache = new LinkedHashMap(HARD_CACHE_CAPACITY / 2, 0.75f, true)\n\n // private final HashMap sHardBitmapCache = new LinkedHashMap() \n{\n // private static final long serialVersionUID = -695136752926135717L;\n\n @Override\n protected boolean removeEldestEntry(LinkedHashMap.Entry eldest) {\n\n Log.w(TAG, \"removeEldestEntry(LinkedHashMap.Entry eldest) \");\n\n Log.w(TAG, \"size() : \" + size());\n Log.w(TAG, \"HARD_CACHE_CAPACITY : \" + HARD_CACHE_CAPACITY);\n\n if (size() > HARD_CACHE_CAPACITY) {\n\n Log.w(TAG, \"(size() > HARD_CACHE_CAPACITY) \");\n Log.e(TAG, \"sSoftBitmapCache --> sSoftBitmapCache.put \");\n\n // Entries push-out of hard reference cache are transferred to soft reference cache\n sSoftBitmapCache.put(eldest.getKey(), new SoftReference(eldest.getValue()));\n\n return true;\n\n } else\n return false;\n }\n};\n\n//HARD_CACHE_CAPACITY / 2\n// Soft cache for bitmaps kicked out of hard cache\n // private final static ConcurrentHashMap> sSoftBitmapCache = new ConcurrentHashMap>();\n\nprivate final Handler purgeHandler = new Handler();\n\nprivate final Runnable purger = new Runnable() {\n public void run() {\n Log.e(TAG, \"purger run\");\n\n\n // clearCache();\n }\n};\n\n/**\n * Adds this bitmap to the cache.\n * @param bitmap The newly downloaded bitmap.\n */\nprivate void addBitmapToCache(String url, Bitmap bitmap) {\n\n Log.w(TAG, \"--------addBitmapToCache-----------\");\n\n\n if (bitmap != null) {\n\n Log.w(TAG, \"(bitmap != null) \");\n\n\n synchronized (sHardBitmapCache) {\n\n //final Bitmap tryData = sHardBitmapCache.get(url);\n\n // if (tryData != null) {\n // sHardBitmapCache.remove(url);\n // }\n\n Log.w(TAG, \" sHardBitmapCache.put(url, bitmap);\");\n\n sHardBitmapCache.put(url, bitmap);\n }\n }\n}\n\n/**\n * @param url The URL of the image that will be retrieved from the cache.\n * @return The cached bitmap or null if it was not found.\n */\nprivate Bitmap getBitmapFromCache(String url) {\n\n Log.e(TAG, \" --------getBitmapFromCache(String url)----------------\");\n\n\n // First try the hard reference cache\n synchronized (sHardBitmapCache) {\n\n final Bitmap bitmap = sHardBitmapCache.get(url);\n\n if (bitmap != null) {\n\n Log.e(TAG, \" getBitmapFromCache ---> Bitmap found in Hard cache!!!!!\");\n\n // Bitmap found in hard cache\n // Move element to first position, so that it is removed last\n\n sHardBitmapCache.remove(url);\n sHardBitmapCache.put(url, bitmap);\n\n return bitmap;\n\n }else{\n\n Log.e(TAG, \" getBitmapFromCache ---> Bitmap not found in Hard cache\");\n\n\n }\n }\n\n // Then try the soft reference cache\n SoftReference bitmapReference = sSoftBitmapCache.get(url);\n\n if (bitmapReference != null) {\n\n Log.e(TAG, \" getBitmapFromCache ---> bitmapReference found in SoftReference cache!\");\n\n\n final Bitmap bitmap = bitmapReference.get();\n\n if (bitmap != null) {\n\n Log.e(TAG, \"Bitmap found in SoftReference cache!!!!!!!\");\n\n\n // Bitmap found in soft cache\n return bitmap;\n\n\n } else {\n Log.e(TAG, \"oooooooooooooooooooo --> Soft reference has been Garbage Collected\");\n\n // Soft reference has been Garbage Collected\n sSoftBitmapCache.remove(url);\n }\n }\n\n return null;\n}\n\n/**\n * Clears the image cache used internally to improve performance. Note that for memory\n * efficiency reasons, the cache will automatically be cleared after a certain inactivity delay.\n */\npublic void clearCache() {\n\n Log.e(TAG, \"----------------clearCache() ------------------\");\n\n synchronized (sHardBitmapCache) {\n //sHardBitmapCache.clear();\n }\n //sSoftBitmapCache.clear();\n\n sHardBitmapCache.clear();\n sSoftBitmapCache.clear();\n}\n\n/**\n * Allow a new delay before the automatic cache clear is done.\n */\nprivate void resetPurgeTimer() {\n purgeHandler.removeCallbacks(purger);\n purgeHandler.postDelayed(purger, DELAY_BEFORE_PURGE);\n}\n\n}\nI completely understand the logic behind this example however I am confused why this does not work properly.\nWe have two levels of cache :The Hard cache and the SoftReference cache. We save the bitmaps in the hard cache and then when is filled we save in the SoftReference and reorder hard cache..\nThen I close the app, close the internet and restart it.In the constructor we call resetPurgeTimer() which clears the cache and therefore nothing is in the cache. To avoid this I commented that line in order not to clear the cache.. I restart my app and I can see 6-7 images which are present in SoftReference cache (according to LogCat)..\nI know that SoftReference cache maybe get empty when GC is called but it is almost empty even before closing the app or disabling wifi...There is a well known bug with SoftReferences which are garbage collected even without memory getting low..\nIs something wrong with this widely used example?\nThanks in advance,\nAndreas\n\nA: Yes, in Android 3.0 and above you can't use Weak or Soft References for Bitmaps. The JVM will aggressively collect them. Instead you should use an LRUCache (in the support library) to cache them. I'd also recommend setting the size of the max cache to some fraction of the size of the max heap (like 1/6 for example).\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635224\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"4\"\n}"}}},{"rowIdx":1967516,"cells":{"text":{"kind":"string","value":"Q: NSMergeConflict with multiple threads A 1 <----> * B\n\nI'm using core data in an iOS application. A and B are entities that have a 1-to-many relationship between A and B. I have a background thread that updates and creates B. A is updated on the main thread, except when I add B to A on the background thread, because of the inverse relationship A gets updated. I have separate MOCs for the main and background thread. \nI've added a mergeChangesFromContextDidSaveNotification: on the main thread, but I get a NSMergeConflict on the background thread for A. Looking at the userInfo of the NSMergeConflict doesn't help, because all the attributes are the same, it's the to many relationships that I imagine are conflicting, and those arent returned by nsmergeconflict. \nI've tried adding a mergeChangesFromContextDidSaveNotification: to the background thread, but it now deadlocks when both threads try to save. \nI've looked over the answer for this NSMergeConflict question. I've tried adding the \nmergeChangesFromContextDidSaveNotification: notification, but I'm still seeing the NSMergeConflict. I don't think that any of the NSMergePolicy options are applicable, because I want to keep all of the persistent store's changes except for the relationship. I'm also not clear on how I can \"manually resolve any conflicts\".\nHow would I be able to resolve or avoid these conflicts?\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635233\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967517,"cells":{"text":{"kind":"string","value":"Q: Delphi logging with multiple sinks and delayed classification? Imagine i want to parse a binary blob of data. If all comes okay, then all the logs are INFO, and user by default does not even see them. If there is an error, then user is presented with error and can view the log to see exact reason (i don't like programs that just say \"file is invaid. for some reason. you do not want to know it\" )\nProbably most log libraries are aimed at quickly loading, classifying and keeping many many log lines per second. which by itself is questionable, as there is no comfort lazy evaluation and closures in Delphi. Envy Scala :-) \nHowever that need every line be pre-сlassified.\nImagine this hypothetical flow:\n\n\n*\n\n*\n*\n\n*Got object FOO [ok]\n\n*\n\n*1.1. found property BAR [ok]\n\n*\n\n*1.1.1. parsed data for BAR [ok]\n\n\n*1.2 found property BAZ [ok]\n\n*\n\n*1.2.1 successfully parsed data for BAR [ok]\n\n*1.2.2 matching data: checked dependancy between BAR and BAZ [fail]\n...\n\n\n\n\n\nSo, what can be desired features?\n1) Nested logging (indenting, subordination) is desired then.\nSomething like highlighted in TraceTool - see TraceNode.Send Method at http://www.codeproject.com/KB/trace/tracetool.aspx#premain0\n2) The 1, 1.1, 1.1.1, 1.2, 1.2.1 lines are sent as they happen in a info sink (TMemo, OutputDebugString, EventLog and so one), so user can see and report at least which steps are complete before error.\n3) 1, 1.2, 1.2.2 are retroactively marked as error (or warning, or whatever) inheriting from most specific line. Obviously, warning superseeds info, error superseeds warning and info, etc/\n4) 1 + 1.2 + 1.2.2 can be easily combined like with LogMessage('1.2.2').FullText to be shown to user or converted to Exception, to carry the full story to human.\n4.1) Optionally, with relevant setup, it would not only be converted to Exception, but the latter even would be auto-raised. This probably would require some kind of context with supplied exception class or supplied exception constructing callback.\n5) Multisink: info can be just appended into collapsible panel with TMemo on main form or currently active form. The error state could open such panel additionally or prompt user to do it. At the same time some file or network server could for example receive warning and error grade messages and not receive info grade ones.\n6) extra associated data might be nice too. Say, if to render it with TreeView rather than TMemo, then it could have \"1.1.1. parsed data for BAR [ok]\" item, with mouse tooltip like \"Foo's dimensions are told to be 2x4x3.2 metres\"\n\n\n*\n\n*Being free library is nice, especially free with sources. Sometimes track and fix the bug relying solely on DCUs is much harder.\n\n*Non-requiring extra executable. it could offer extra more advanced viewer, but should not be required for just any functionality.\n\n*Not being stalled/abandoned.\n\n*ability to work and show at least something before GUI is initialized would be nice too. Class constructors are cool, yet are executed as part of unit visualization, when VCL is not booted yet. If any assertion/exception is thrown from there, user would only see Runtime error 217, with all the detail lost. At least OutputDebugStreen can be used, if nothing more...\n\n\nStack tracing is not required, if needed i can do it and add with Jedi CodeLib. But it is rarely needed.\nExternal configuration is not required. It might be good for big application to reconfigure on the fly, but to me simplicity is much more important and configuration in code, by calling constructors or such, is what really matters. Extra XML file, like for Log4J, would only make things more fragile and complex.\nI glanced few mentioned here libraries.\n\n\n*\n\n*TraceTool has a great presentation, link is above. Yet it has no info grade, only 3 predefined grades (Debug/Error/Warning) and nothing more, but maybe Debug would suit for Info replacement... Seems like black box, only saving data into its own file, and using external tool to view it, not giving stream of events back to me. But their messages nesting and call chaining seems cool. Cools is also attaching objects/collection to messages.\n\n*Log4D and Log4Delphi seems to be in a stasis, with last releases of 2007 and 2009, last targeted version Delphi 7. Lack documentation (probably okay for log4j guy, but not for me :- ) Log4Delphi even had test folder - but those test do not compile in Delphi XE2-Upd1. Pity: In another thread here Log4delphi been hailed for how simple is to create custom log appender (sink)...\n\n*\n\n*BTW, the very fact that the only LOG4J was forked into two independent Delphi ports leaves the question of which is better and that both lack something, if they had to remain in split.\n\n\n*mORMot part is hardly separated from the rest library. Demo application required UAC escalation for use its embedded SQLite3 engine and is frozen (no window opened, yet the process never exits normally) if refused Admin grants. Another demo just started infinite stream of AV exceptions, trying to unwind the stack. So is probably not ready yet for last Delphi. Though its list of message grades is excessive, maybe even a bit too many.\n\n\nThank you.\n\nA: mORMot is stable, even with latest XE2 version of Delphi.\nWhat you tried starting were the regression tests. Among its 6,000,000 tests, it includes the HTTP/1.1 Client-Server part of the ORM. Without the Admin rights, the http.sys Server is not able to register the URI, so you got errors. Which makes perfectly sense. It's a Vista/Seven restriction, not a mORMot restriction.\nThe logging part can be used completely separated from the ORM part. Logging is implemented in SynCommons.pas (and SynLZ.pas for the fast compression algorithm used for archival and .map embedding). I use the TSynLog class without any problem to log existing applications (even Delphi 5 and Delphi 6 applications), existing for years. The SQLite3 / ORM classes are implemented in other units. \nIt supports the nesting of events, with auto-leave feature, just as you expect. That is you can write:\nprocedure TMyClass.MyMethod(const Params: integer);\nbegin\n TSynLog.Enter;\n // .... my method code\nend;\n\nAnd adding this TSynLog.Enter will be logged with indentation corresponding to the recursive level. IMHO this may meet your requirements. It will declare an ISynLog interface on the stack, which will be freed by Delphi at the \"end;\" code line, so it will implement an Auto-Leave feature. And the exact unit name, method name and source code line number will be written into the log (as MyUnit.TMyClass.MyMethod (123)), if you generated a .map file at compilation (which may be compressed and appended to the .exe so that your customers logs will contain the source line numbers). You have methods at the ISynLog interface level to add some custom logging, including parameters and custom state (you can log objects properties as JSON if you need to, or write your custom logging data).\nThe exact timing of each methods are tracked, so you are able to profile your application from the data supplied by your customer.\nIf you think the logs are too much verbose, you have several levels of logging, to be customized on the client side. See the blog articles and the corresponding part of the framework documentation (in the SynCommons part). You've for instance \"Fail\" events and some custom kind of events. And it is totally VCL-independent, so you can use it without GUI or before any GUI is started.\nYou have at hand a log viewer, which allow client-side profiling and nested Enter/Leave view (if you click on the \"Leave\" line, you'll go back to the corresponding \"Enter\", e.g.):\n\nIf this log viewer is not enough, you have its source code to make it fulfill your requirements, and all the needed classes to parse and process the .log file on your own, if you wish. Logs are textual by default, but can be compressed into binary on request, to save disk space (the log viewer is able to read those compressed binary files). Stack tracing and exception interception are both implemented, and can be activated on request.\nYou could easily add a numeration like \"1.2.1\" to the logs, if you wish to. You've got the whole source code of the logging unit. Feel free to ask any question in our forum.\n\nA: Log4D supports nested diagnostic contexts in the TLogNDC class, they can be used to group together all steps which are related to one compound action (instead of a 'session' based grouping of log events). Multi-Sinks are called Appenders in log4d and log4delphi so you could write a TLogMemoAppender with around twentyfive lines of code, and use it at the same time as a ODSAppender, a RollingFileAppender, or a SocketAppender, configurable at run time (no external config file required).\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635235\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"3\"\n}"}}},{"rowIdx":1967518,"cells":{"text":{"kind":"string","value":"Q: numpy: syntax/idiom to cast (n,) array to a (n, 1) array? I'd like to cast a numpy ndarray object of shape (n,) into one having shape (n, 1). The best I've come up with is to roll my own _to_col function:\ndef _to_col(a):\n return a.reshape((a.size, 1))\n\nBut it is hard for me to believe that such a ubiquitous operation is not already built into numpy's syntax. I figure that I just have not been able to hit upon the right Google search to find it.\n\nA: np.expand_dims is my favorite when I want to add arbitrary axis.\nNone or np.newaxis is good for code that doesn't need to have flexible axis. (aix's answer)\n>>> np.expand_dims(np.arange(5), 0).shape\n(1, 5)\n>>> np.expand_dims(np.arange(5), 1).shape\n(5, 1)\n\nexample usage: demean an array by any given axis\n>>> x = np.random.randn(4,5)\n>>> x - x.mean(1)\nTraceback (most recent call last):\n File \"\", line 1, in \nValueError: shape mismatch: objects cannot be broadcast to a single shape\n\n\n>>> ax = 1\n>>> x - np.expand_dims(x.mean(ax), ax)\narray([[-0.04152658, 0.4229244 , -0.91990969, 0.91270622, -0.37419434],\n [ 0.60757566, 1.09020783, -0.87167478, -0.22299015, -0.60311856],\n [ 0.60015774, -0.12358954, 0.33523495, -1.1414706 , 0.32966745],\n [-1.91919832, 0.28125008, -0.30916116, 1.85416974, 0.09293965]])\n>>> ax = 0\n>>> x - np.expand_dims(x.mean(ax), ax)\narray([[ 0.15469413, 0.01319904, -0.47055919, 0.57007525, -0.22754506],\n [ 0.70385617, 0.58054228, -0.52226447, -0.66556131, -0.55640947],\n [ 1.05009459, -0.27959876, 1.03830159, -1.23038543, 0.73003287],\n [-1.90864489, -0.31414256, -0.04547794, 1.32587149, 0.05392166]])\n\n\nA: I'd use the following:\na[:,np.newaxis]\n\nAn alternative (but perhaps slightly less clear) way to write the same thing is:\na[:,None]\n\nAll of the above (including your version) are constant-time operations.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635237\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"6\"\n}"}}},{"rowIdx":1967519,"cells":{"text":{"kind":"string","value":"Q: Passing params through nested user controls in Silverlight 4 I have a three level of nested user controls in my Silverlght 4 application.\nthe most low level control fires an event with some parameter, then second user control takes the parameter and also fires an event sending parameter to up. Third user controls makes same thing passing parameter to the MainPage. Anyway a have got my parameter but the way I did it very boring and confusing. Is there any acceptable and easy understanding way to do same thing shorter.\nThanks a lot!\n\nA: That is the correct way, mainly because any level is replaceable and so should function the same way.\nBoring and simple looking are actually good things for code... makes it easier for others to follow.\nIf you want excitement... I would suggest a career change :)\n\nA: It all depends on what the event is and what the parameter you are bubbling up contains. If this is purely user-interaction and the visual parent needs to react to your event, then, as HiTech Magic mentions, this is the best way to do it.\nNow, if what you are trying to do is actually related with the business logic of the application, then maybe your user control is not best place to handle this event and you may benefit from binding a view model to your user controls and using some kind of event aggregator to broadcast your events.\nIt may be good for you to add more context to the event your are firing and the parameter which you are bubbling up to the container for you to get additional information which applies to your context.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635245\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967520,"cells":{"text":{"kind":"string","value":"Q: MongoDB C# Driver FindAndModify I'm trying to run a FindAndModify operation in MongoDB, but I'm getting an unusual exception\nvar query = Query.EQ(\"_id\", wiki.ID);\nvar sortBy = SortBy.Descending(\"Version\");\nvar update = Update.Set(\"Content\", wiki.Content)\n .Set(\"CreatedBy\", wiki.CreatedBy)\n .Set(\"CreatedDate\", wiki.CreatedDate)\n .Set(\"Name\", wiki.Name)\n .Set(\"PreviousVersion\", wiki.PreviousVersion.ToBsonDocument())\n .Set(\"Title\", wiki.Title)\n .Set(\"Version\", wiki.Version);\nvar result = collection.FindAndModify(query, sortBy, update, true);\n\nThe exception I get is \nWriteStartArray can only be called when State is Value, not when State is Initial\nDescription: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.\n\nException Details: System.InvalidOperationException: WriteStartArray can only be called when State is Value, not when State is Initial\n\nSource Error:\n\nLine 45: var query = Query.EQ(\"_id\", wiki.ID);\nLine 46: var sortBy = SortBy.Descending(\"Version\");\nLine 47: var update = Update.Set(\"Content\", wiki.Content)\nLine 48: .Set(\"CreatedBy\", wiki.CreatedBy)\nLine 49: .Set(\"CreatedDate\", wiki.CreatedDate)\n\nThoughts? I've implemented this per the API on mongodb's site.\nEDIT--\nFixed per @jeffsaracco\nvar update = Update.Set(\"Content\", wiki.Content)\n.Set(\"CreatedBy\", wiki.CreatedBy)\n.Set(\"CreatedDate\", wiki.CreatedDate)\n.Set(\"Name\", wiki.Name)\n.PushAllWrapped(\"PreviousVersion\", wiki.PreviousVersion)\n.Set(\"Title\", wiki.Title)\n.Set(\"Version\", wiki.Version);\n\n\nA: Your solution with PushAllWrapped may or may not be want you want. It is different from Set because it appends the new values to the current array value. If you wanted to replace the existing array value with a new array value you could use this version of Set:\nvar update = Update.Set(\"Content\", wiki.Content)\n // other lines\n .Set(\"WikiHistory\", new BsonArray(BsonDocumentWrapper.CreateMultiple(wiki.PreviousVersion);\n\nwhich says: set the value of the WikiHistory element to a new BsonArray constructed by serializing the wrapped values of the custom type of PreviousVersion.\n\nA: Are one of your columns an array type? If so, you might want to call \nUpdate.Push\n\nOR\nUpdate.PushAll\n\nfor that column, and if PreviousVersion is already a BsonDocument you probably don't need to convert again\n\nA: Are you sure of your SortBy.Descending ?\nThe api does not state that you could use somehting else than string[] as parameter (http://api.mongodb.org/csharp/current/html/96408b4e-c537-0772-5556-6f43805dd4d4.htm)\n\nA: In the end, since I'm just tracking the history of the object, I ended up using .AddToSetWrapped(\"PreviousVersion\", CurrentVersion) which just appends the item to the set in the object.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635254\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"2\"\n}"}}},{"rowIdx":1967521,"cells":{"text":{"kind":"string","value":"Q: Having problems binding data using % wildcards Using sqlite and building queries, they all work fine until I try to bind certain data into a query such as -\nNSString *query = @\"SELECT id, title FROM fields WHERE (staff LIKE '%?%');\nsqlite3_prepare_v2(lessonPlansDatabase, [query UTF8String], -1, &stmt, nil);\n\nNSString *theValue = @\"Fred\";\nsqlite3_bind_text(stmt, 1, [theValue UTF8String], -1, NULL);\n\nThe problem appears to be with using the '%'. I've tried putting it into the string which I'm binding, but that doesn't work either. If I just make the query in full, like -\nNSString *query = @\"SELECT id, title FROM fields WHERE (staff LIKE '%Fred%');\n\nand don't bind anything, it works fine. But I don't want to do this in case there are characters in the string which upset the query, I'd prefer to let sqlite do the binding. The binding works fine where there are no '%' characters.\nAny help much appreciated!\n\nA: You want\nNSString *query = @\"SELECT id, title FROM fields WHERE (staff LIKE ?)\";\nsqlite3_prepare_v2(lessonPlansDatabase, [query UTF8String], -1, &stmt, nil);\n\nNSString *theValue = @\"%Fred%\";\nsqlite3_bind_text(stmt, 1, [theValue UTF8String], -1, NULL);\n\n\nA: Escape the (%)s with (%) and try to bind text.\n(staff LIKE '%%?%%')\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635259\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967522,"cells":{"text":{"kind":"string","value":"Q: Is MouseEvent a class or an instance of a class or both? I'm having trouble getting the hang of as3 syntax (php is the only other coding language I know)\nmybutton.addEventListener(MouseEvent.CLICK, myListenerFunction);\n\nfunction myListenerFunction(e:MouseEvent):void\n{\n // function body\n}\n\nIn this code it seems like MouseEvent is an instance of the class MouseEvent.\nMouseEvent.CLICK\n\nHowever in this code it seems like e is an instance of class MouseEvent\ne:MouseEvent\n\n\nA: MouseEvent.CLICK is a class's public constant which can be accessed everywhere with no need to create an instance. It's like public static variable in php class. \ne:MouseEvent is an instance of MouseEvent class. \nCheck out MouseEvent class documentation http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/MouseEvent.html\n\nA: MouseEvent.CLICK\n\nThis is reference to a static constant of the MouseEvent class. So to answer your question, MouseEvent here is a reference to a Class. The CLICK Constant might be defined within the MouseEvent Class something like this:\npackage flash.events {\n public class MouseEvent extends Event {\n ...\n public static const CLICK:String = \"click\";\n ...\n }\n}\n\nSo writing:\ntrace(MouseEvent.CLICK);\n\nWould output the String:\nclick\n\n\nA: MouseEvent.CLICK is a static member of MouseEvent. It contains a string, which is the event name. You could also use addEventListener(\"click\", myListenerFunction), though that is less safe.\nI guess they just needed somewhere to put that constant.\nThe MouseEvent-class instance contains information on what happened to trigger the event etc.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635261\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"3\"\n}"}}},{"rowIdx":1967523,"cells":{"text":{"kind":"string","value":"Q: Piping into objects/properties/methods in PowerShell In PowerShell, you can pipe into Cmdlets and into scripted functions. But is it possible to pipe into objects, properties, or member functions?\nFor example, if I have a database connection object $dbCon, I want to be able to so something like this:\n$dbCon.GetSomeRecords() | Consonant\n\ncheak [] = \"\"\ncheak (char:chars) =\nif elem (toUpper char) isVowel == false\nthen cheak chars\nelse cheak = Cons (char:chars) \"Not Consonant\" \n-- here I want to use \"break\", but I don't know how to use it in Haskell... \n\ncheak = Cons (char:chars) \"Is Consonant\" \n\nIt doesn't work... How to change the code? Pls help! Thank you!\nUpdate:\n module Consonant where\n\n import Char\n\n type Word = String\n type ConOrNot = String\n data Consonant = Cons Word ConOrNot\n deriving (Show,Eq)\n\n\n isConsonant = \"BCDFGHJKLMNPQRSTVWXYZ\"\n\n cheak :: String -> Consonant\n\n cheak [] = Cons \"\" \"\"\n\n\n cheak (char:chars) \n |elem (toUpper char) isCosonant = cheak chars --if all the letters are cosonant, I want it return (Cons (char:chars) \"is Consonant\").. still working on it\n |otherwise = Cons (char:chars) \"Not Consonant\"\n\nIt works now if the string got both vowels and consonant or only vowels, how to improve the code so it also works with only consonants?\n\nA: This is homework, isn't it?\nIssues with your code include:\n\n\n*\n\n*This line makes no sense:\ncheak [] = \"\"\n\nbecause cheak is supposed to return a Consonant, but here you return a String.\n\n*This line also makes no sense:\ncheak = Cons (seq:seqs) \"Is Consonant\"\n\nbeacause cheak is supposed to take a String parameter and return a Consonant, but here you just return a Consonant without taking any parameter.\n\n*This line makes even less sense:\nelse cheak = Cons (seq:seqs) \"Not Consonant\"\n\nHaskell is not Pascal or Visual Basic. You return a value from a function by letting the RHS of the equation evaluate to that value.\n\n*Indentation matters.\n\n*There is a function called break in Haskell, but it is unrelated to the break keyword you may be familiar with from Java or C. The Java/C concept of breaking out of a loop doesn't exist in Haskell.\n\n*You probably want to use a helper function.\n\n*\"Cheak\" isn't a word.\n\n*if-then-else is not a statement. The then-branch and the else-branch are not statements either. They're all expressions. It's like ?: from Java, C and some other languages.\n\nA: I'm not entirely sure what you are asking for. Is the Word in the returned Cons supposed to be the Word passed to cheak or the remainder of the Word starting from the first vowel?\nDoes this do what you want?\nmodule Consonant\n where\n\nimport Data.Char\n\ntype Word = String\ntype ConOrNot = String\ndata Consonant = Cons Word ConOrNot\n deriving (Show,Eq)\n\ncheak :: Word -> Consonant\ncheak \"\" = Cons \"\" \"\"\ncheak s = Cons s $ if any isVowel s then \"Not Consonant\" else \"is Consonant\"\n where isVowel c = (toUpper c) `elem` \"AEIOU\"\n\n\nA: There are many ways to do what you want to do in Haskell. The obvious first choices are Maybe and Either. But in general, checkout the 8 ways to report errors in Haskell .\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635263\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967525,"cells":{"text":{"kind":"string","value":"Q: SQL Server - XML Validation: Invalid simple type value I'm trying to validate an XML input against an XML Schema in SQL Server 2005 and I get an error when validating the e-mail:\n\nMsg 6926, Level 16, State 1, Line 4\nXML Validation: Invalid simple type value: 'john_doe@yahoo.com'. Location: /:xxx[1]/:yyy[1]/*:Email[1]\n\nThe email field is defined in the schema as:\n \n \n \n \n \n\nEvery email address that matches the regexp is considered valid except for something with underscores in it (johnDoe@yahoo.com is OK, john.doe@yahoo.com is OK, but john_doe@yahoo.com is not).\nIf I remove the underscore the XML is validated.\nI've tested my regexp (which is the one you can find on MSDN for validating emails) with various tools and they all say it's valid. But not SQL Server.\nWhy does it not validate underscores? Is there something special I must do in SQL Server?\n\nA: Found a link about the issue with a workaround. http://www.agilior.pt/blogs/rodrigo.guerreiro/archive/2008/11/14/5965.aspx\nApparently \\w should include the underscore and does so except when it comes to handling XSD schemas. So this is not a specific SQL Server problem. I have the exact same behavior when validating an XML using XMLSpy.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635264\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"5\"\n}"}}},{"rowIdx":1967526,"cells":{"text":{"kind":"string","value":"Q: Can I load flex components asynchronously? I have a flex application that shows information gathered from different external services by using rest api. Some of them are resource intensive, take longer to response. Is there any way I can load the different components asyncronously?\n\nA: ActionScript (Flex) executes asynchronously by default. So, if you make concurrent calls to a service, ensure that your code handles the results appropriately (via Event handlers). By default, making a request to a web service operation that is already executing does not cancel the existing request.\nSo, simply invoke your services, and register (result/failure) event handlers on them to capture their responses, and load the components accordingly.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635266\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967527,"cells":{"text":{"kind":"string","value":"Q: how to access private key from eToken with jsp It's my first time to here, so please forgive me at first time if I make mistake. I am new to RSA(Cryptography), My requirement is, accessing private key from eToken for decryption and store decrypted data in a file.\nI want to ask here that where to find private key & how to access it via jsp page?\nI am using Spring 3 and RSA.\nPlease share resource if any available.\nThanks\n\nA: Is the \"eToken\" the product described here? If so, it's basically a smartcard, which means you can't extract the private key. The way you'd use it is to send the encrypted data to the token and have it decrypt for you.\nYou said you're using JSP. Are you trying to utilize an eToken plugged into your server, or into the client's PC? A JSP page on your server can't talk to devices plugged into the client's PC; you'd need an application running on the client (maybe a browser plugin) to do it on your behalf.\nIf it were possible for a website to extract the private key from a user's eToken, the eToken would be worthless as a security product.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635267\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967528,"cells":{"text":{"kind":"string","value":"Q: Magento vs. I have seen in at least one layout xml file the use of the xml node in place of the typical node. I have scoured the interwebs as well as any Magento Layout books and documents I have but I can't find an explanation about this. I initially thought there was a difference in the order in which it applies the updates, but that doesn't seem to be the case after further testing. Can someone explain what (if any) differences there are between the two?\nThanks!\nExample\nTypical layout update XML file structure:\n\n\n \n \n ...\n \n \n\n\nA different version that still seems to work:\n\n\n \n \n ...\n \n \n\n\nIs there any functional difference between these 2?\n\nA: The tag is supposed to be . However, in current versions of Magento (and likely future versions), the name of this tag doesn't matter. Those files are all combined into a single XML tree. The code Magento uses to load those files into a single tree looks like this\n$fileStr = file_get_contents($filename);\n$fileStr = str_replace($this->_subst['from'], $this->_subst['to'], $fileStr);\n$fileXml = simplexml_load_string($fileStr, $elementClass);\nif (!$fileXml instanceof SimpleXMLElement) {\n continue;\n}\n$layoutStr .= $fileXml->innerXml();\n\nThe last line ($fileXml->innerXml();) is the one we're interested in, . The innerXml method works just like the browser DOM method of the same name. All the child nodes will be extracted into a string, but the root node will be ignored. You could name it , , . It currently doesn't matter. \nThat said, you should name it to avoid confusing people. \n\nA: Module layout update XML files contain the root node . Any top-level node contained by this root node is a layout update handle. Layout update handles are used to contain sets of layout update XML directives. The version number for the root node is not ever evaluated (to my knowledge).\nLayout update handles are essentially arbitrary, and may be any XML-safe string. Depending on how or if the controller action handling the request is using layout updates, certain layout update handles are called into scope.\nFor more information on the related methods see the following:\nMage_Core_Controller_Varien_Action's loadLayout() and renderLayout() methods, Mage_Core_Model_Layout, and Mage_Core_Model_Layout_Update.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635273\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967529,"cells":{"text":{"kind":"string","value":"Q: How to detect if a click() is a mouse click or triggered by some code? How to detect if a click() is a mouse click or triggered by some code?\n\nA: Wait for some time and use event.isTrusted - its supported by IE9, Opera 12, and Firefox Nightly. Webkit will support it too, most probably.\nCurrently, there is no guaranteed way to know.\n\nA: Use the which property of the event object. It should be undefined for code-triggered events:\n$(\"#someElem\").click(function(e) {\n if(e.which) {\n //Actually clicked\n }\n else {\n //Triggered by code\n }\n});\n\nHere's a working example of the above.\nUpdate based on comments\nPressing the Enter key when an input element has focus can trigger the click event. If you want to distinguish between code-triggered clicks and all other clicks (mouse or keyboard triggered) then the above method should work fine.\n\nA: You should check e.originalEvent:\n$(\"#someElem\").click(function(e) {\n if(e.originalEvent === undefined) {\n //triggered \n }\n else {\n //clicked by user\n }\n});\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635274\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"20\"\n}"}}},{"rowIdx":1967530,"cells":{"text":{"kind":"string","value":"Q: Should or can an iphone app have a like button I have just implemented FB login and status updates in my app following the sample app in the IOS SDK.\nI know it is common practice to have a like button for a page but is it also true for an app?\nI mean is it possible to have a like button in my app that when tapped makes an entry on my FB page stating I like the app?\nI can't seem to track the like feature down in the docs :-(\nThanks\n\nA: basically you can add UIWebView and put your html tags inside it \ncheck this and this sample they may help you\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635275\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967531,"cells":{"text":{"kind":"string","value":"Q: How to properly scroll an overflowing div based on mouse position within its container I am working on a small jQuery plugin that autoscrolls through a set of overflowing elements within a container div based on the mouse position within that container div. \nSee the Demo Here\nThe idea is for this plugin to be an improvement of something I wrote a while ago. See the autoscrolling navigation in the lower left here The old problem with this was that it jumps around when you mouseenter from anywhere but the bottom(javascript perspective) of the container div.\nNow everything is working fine with my plugin but when you mouseenter from the top it screws up from time to time(move your mouse in and out fast and it will happen for sure), I think this is because I am getting different values from my mouseenter event and my mousemove event which are both used to calculate how to scroll the inner elements. Here is the function, the rest of the source is pretty small and decently commented.\nprojList.mousemove(function(e){\n\n //keep it from freaking out when we mouseenter from Top of div\n if(enterMouseY > divHeight){\n enterMouseY = divHeight;\n }\n\n mouseY = e.pageY-projList.offset().top;\n\n //ok that didnt work... try to keep it from freaking out when we mouseenter from Top of div\n if (mouseY > divHeight){\n mouseY = divHeight;\n }\n\n //distnace from top of container div to where our mouse Entered\n var distToTop = divHeight - enterMouseY;\n\n //here is the calculation, I parameterize the mouseY pos as a value between 0-1\n //0 being where we entered and 1 being the top or bottom of the div\n //then multiply that by how much we have to scroll to get to the end of the list\n\n //are we moving up or down\n if(mouseY>enterMouseY){\n //if up calculate based on Top\n var dist =totalScrollDistance * ((mouseY-enterMouseY-projList.offset().top)/(distToTop));\n }else if(mouseYtotalScrollDistance){\n pos = totalScrollDistance;\n\n }\n\n $('#div1').text(\"mouseY: \"+ mouseY +\" enterMouseY: \"+ enterMouseY +\" distance:\"+ dist.toFixed(1) + \" pos:\"+ pos.toFixed(1)); \n\n\n });\n\n\nA: I solved this problem, there was an error in my calculations, but works how I described above.\nYou can see it in action here\nhttp://web.archive.org/web/20130529212243/http://www.robincwillis.com/AutoScroll/\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635276\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967532,"cells":{"text":{"kind":"string","value":"Q: Get count of selected column out of DataGridView What do I have:\n\n\n*\n\n*Filled datagridview\n\n*Selected cells of this grid\n\n\nWhat do I want:\n\n\n*\n\n*Amount of unique columns of the selected cells\n\n*Names of these columns\n\n\nWhat I found: \nint selectedColumnsCount = dataGridView3.SelectedColumns.Count;\n\nSomehow this piece of code isn't working in my case. \nMy question: How can I get the columns name and the amount of columns selected out of a DataGridView?\nThis is what I created now:\nint selectedCellCount = dataGridView3.GetCellCount(DataGridViewElementStates.Selected);\nint selectedcolumncount = dataGridView3.SelectedColumns.Count;\nArrayList arr = new ArrayList();\nint j = 0;\n\nif (selectedCellCount > 0)\n{\n for (int i = 0; i < selectedCellCount; i++)\n {\n int Xcor2 = int.Parse(dataGridView3.SelectedCells[i].ColumnIndex.ToString());\n test = test + dataGridView3.Columns[Xcor2].Name;\n arr.Add(dataGridView3.Columns[Xcor2].Name);\n }\n}\n\nArrayList arr2 = new ArrayList();\nforeach (string str in arr)\n{\n if (!arr2.Contains(str))\n {\n arr2.Add(str);\n j++;\n }\n}\n\nThis is what I made myself, not that nice but its working to get the count of columns if anyone has a better way of realizing this, feel free to add\n\nA: You can register for the SelectionChanged event and process the SelectedCells. For example\npublic Form1()\n{\n InitializeComponent();\n dataGridView1.SelectionChanged += new EventHandler(dataGridView1_SelectionChanged);\n}\n\nHashSet column_indicies = new HashSet();\nHashSet column_names = new HashSet();\nint number_of_columns = 0;\n\nvoid dataGridView1_SelectionChanged(object sender, EventArgs e)\n{\n column_indicies.Clear();\n column_names.Clear();\n foreach (DataGridViewCell cell in dataGridView1.SelectedCells)\n {\n // Set of column indicies\n column_indicies.Add(cell.ColumnIndex);\n // Set of column names\n column_names.Add(dataGridView1.Columns[cell.ColumnIndex].Name);\n }\n // Number of columns the selection ranges over\n number_of_columns = column_indicies.Count;\n}\n\n\nA: You cannot select columns. Only one columns can be selected at a time!\nColumns are the same as Rows.\nOr did you mean to get those columns, which cells are slected?\n\nA: Ok, this is one of the way of getting column names (you can even use HeaderText property instead of Name):\n List listOfColumns = new List();\n foreach (DataGridViewCell cell in dataGridView1.SelectedCells)\n {\n DataGridViewColumn col = dataGridView1.Columns[cell.ColumnIndex] as DataGridViewColumn;\n if (!listOfColumns.Contains(col))\n listOfColumns.Add(col);\n }\n StringBuilder sb =new StringBuilder();\n foreach (DataGridViewColumn col in listOfColumns)\n sb.AppendLine(col.Name);\n MessageBox.Show(\"Column names of selected cells are:\\n\" + sb.ToString());\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635282\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967533,"cells":{"text":{"kind":"string","value":"Q: Calling C function from lua Can someone tell me is it possible to somehow call c function or simply wrap it into a lua function WITHOUT building a new module.\n\nA: If it works for you, try the FFI library. See also luaffi.\n\nA: Lua can't call arbitrary C functions - they have to be bound to something in the Lua namespace first. (This is intentional to prevent breaking out of sandboxes in embedded applications.)\n\nA: Or the Alien library.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635287\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"2\"\n}"}}},{"rowIdx":1967534,"cells":{"text":{"kind":"string","value":"Q: How to write an 8 bit grey scale tiff with Java? I am trying to write a grey scale image to an TIFF file using Sanselan. Obviously would like the save the data to be 8 bit grey scale file but somehow I always end up with a 24 bit colour file.\nI have searched for file formats in general and ExifTagConstants.EXIF_TAG_PIXEL_FORMAT in particular but was unable to find anything helpful.\nI also considered colour profiles but there seem to be none for grey scale images. But then they all have wacky names — I might just have overlooked the right one.\nOr do I have to use a different library?\nHere the code I use (without business logic and experimental stuff:\n Test_Only_Sanselan:\n try\n {\n final Map parameter = new HashMap <>();\n parameter.put(org.apache.sanselan.SanselanConstants.PARAM_KEY_COMPRESSION,\n org.apache.sanselan.formats.tiff.constants.TiffConstants.TIFF_COMPRESSION_UNCOMPRESSED);\n\n final java.io.OutputStream output = new java.io.FileOutputStream(\"Test-1.tiff\");\n org.apache.sanselan.Sanselan.writeImage(image, output,\n org.apache.sanselan.ImageFormat.IMAGE_FORMAT_TIFF, parameter);\n output.close();\n }\n catch (final IOException exception)\n {\n LdfImage.log.info(\"! Could not create tiff image.\", exception);\n }\n catch (final org.apache.sanselan.ImageWriteException exception)\n {\n LdfImage.log.info(\"! Could not create tiff image.\", exception);\n }\n\nI wonder if I need to add a special parameter. But I have not found a useful parameter yet.\nThe following is a test of the Java 7 image writer which creates a correct grey scale image. But as PNG and not TIFF:\n Test_Only_Java_7:\n try\n {\n final java.util.Iterator imageWriters = javax.imageio.ImageIO.getImageWritersByMIMEType (\"image/png\");\n final javax.imageio.ImageWriter imageWriter = (javax.imageio.ImageWriter) imageWriters.next();\n final java.io.File file = new java.io.File(\"Test-2.png\");\n final javax.imageio.stream.ImageOutputStream output = javax.imageio.ImageIO.createImageOutputStream(file);\n\n imageWriter.setOutput(output);\n imageWriter.write(image);\n }\n catch (final IOException exception)\n {\n LdfImage.log.info(\"! Could not create tiff image.\", exception);\n }\n\nIs there a TIFF pug-in for imageio?\n\nA: I'm not familiar with Sanselan but I see there is a ImageInfo.COLOR_TYPE_GRAYSCALE constant, I'm guessing it could be used in the params parameter map given to writeImage.\nI didn't find the javadoc for Sanselan, their link is broken, would you have one more up-to-date?\nIf you want to use JAI you can get your inspiration here:\nvoid get8bitImage(byte[] data, int width, int height) {\n BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);\n byte[] rasterData = ((DataBufferByte)image.getRaster().getDataBuffer()).getData();\n System.arraycopy(pixels, 0, rasterData, 0, pixels.length); // A LOT faster than 'setData()'\n}\n\nvoid main(String[] argv) {\n TIFFEncodeParam ep = new TIFFEncodeParam();\n FileOutputStream out = new FileOutputStream(\"c:\\\\test.tiff\");\n BufferedImage img = get8bitImage(myData);\n ImageEncoder encoder = ImageCodec.createImageEncoder(\"tiff\", out, ep);\n encoder.encode(img);\n}\n\nBe sure that the BufferedImage has BufferedImage.TYPE_BYTE_GRAY as imageType.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635289\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967535,"cells":{"text":{"kind":"string","value":"Q: How can I let a user navigate and play a playlist using the HTML5 tag? I want to link a playlist with the