{ // 获取包含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 !== 'GitHub加速' && linkText !== 'GitHub加速' ) { link.textContent = 'GitHub加速'; link.href = 'https://githubproxy.cc'; 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 !== 'Vibevoice' ) { link.textContent = 'Vibevoice'; link.href = 'https://vibevoice.info/'; replacedLinks.add(link); } // 替换Pricing链接 - 仅替换一次 else if ( (linkHref.includes('/pricing') || linkHref === '/pricing' || linkText === 'Pricing' || linkText.match(/^s*Pricings*$/i)) && linkText !== 'SoraWatermarkRemover' ) { link.textContent = 'SoraWatermarkRemover'; link.href = 'https://sora2watermarkremover.net/'; replacedLinks.add(link); } // 替换Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) && linkText !== 'VoxCPM' ) { link.textContent = 'VoxCPM'; link.href = 'https://voxcpm.net'; 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, 'GitHub加速'); } 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 pw.flush();\n rs.getResponse().setStatus(HttpServletResponse.SC_OK);\n }\n protected boolean doDebugCmd(String cmd, StringTokenizer tz, PrintWriter pw) {\n return false;\n }\n public void doGetSystemProps(ReqState rs)\n throws Exception {\n rs.getResponse().setHeader(\"XDODS-Server\", getServerVersion());\n rs.getResponse().setContentType(\"text/html\");\n rs.getResponse().setHeader(\"Content-Description\", \"dods-status\");\n PrintWriter pw = new PrintWriter(new OutputStreamWriter(rs.getResponse().getOutputStream(), Util.UTF8));\n pw.println(\"\");\n pw.println(\"System Properties\");\n pw.println(\"
\");\n pw.println(\"

System Properties

\");\n pw.println(\"

Date: \" + new Date() + \"

\");\n Properties sysp = System.getProperties();\n Enumeration e = sysp.propertyNames();\n pw.println(\"
    \");\n while (e.hasMoreElements()) {\n String name = (String) e.nextElement();\n String value = System.getProperty(name);\n pw.println(\"
  • \" + name + \": \" + value + \"
  • \");\n }\n pw.println(\"
\");\n pw.println(\"

Runtime Info:

\");\n Runtime rt = Runtime.getRuntime();\n pw.println(\"JVM Max Memory: \" + (rt.maxMemory() / 1024) / 1000. + \" MB (JVM Maximum Allowable Heap)
\");\n pw.println(\"JVM Total Memory: \" + (rt.totalMemory() / 1024) / 1000. + \" MB (JVM Heap size)
\");\n pw.println(\"JVM Free Memory: \" + (rt.freeMemory() / 1024) / 1000. + \" MB (Unused part of heap)
\");\n pw.println(\"JVM Used Memory: \" + ((rt.totalMemory() - rt.freeMemory()) / 1024) / 1000. + \" MB (Currently active memory)
\");\n pw.println(\"
\");\n pw.println(\"\");\n pw.println(\"\");\n pw.flush();\n rs.getResponse().setStatus(HttpServletResponse.SC_OK);\n }\n public void doGetStatus(ReqState rs)\n throws Exception {\n rs.getResponse().setHeader(\"XDODS-Server\", getServerVersion());\n rs.getResponse().setContentType(\"text/html\");\n rs.getResponse().setHeader(\"Content-Description\", \"dods-status\");\n PrintWriter pw = new PrintWriter(new OutputStreamWriter(rs.getResponse().getOutputStream(), Util.UTF8));\n pw.println(\"Server Status\");\n pw.println(\"
    \");\n printStatus(pw);\n pw.println(\"
\");\n pw.flush();\n rs.getResponse().setStatus(HttpServletResponse.SC_OK);\n }\n // to be overridden by servers that implement status report\n protected void printStatus(PrintWriter os) throws IOException {\n os.println(\"

Server version = \" + getServerVersion() + \"

\");\n os.println(\"

Number of Requests Received = \" + HitCounter + \"

\");\n if (track) {\n int n = prArr.size();\n int pending = 0;\n StringBuilder preqs = new StringBuilder();\n for (int i = 0; i < n; i++) {\n ReqState rs = (ReqState) prArr.get(i);\n RequestDebug reqD = (RequestDebug) rs.getUserObject();\n if (!reqD.done) {\n preqs.append(\"
\n          preqs.append(\"Request[\");\n          preqs.append(reqD.reqno);\n          preqs.append(\"](\");\n          preqs.append(reqD.threadDesc);\n          preqs.append(\") is pending.\\n\");\n          preqs.append(rs.toString());\n          preqs.append(\"
\");\n pending++;\n }\n }\n os.println(\"

\" + pending + \" Pending Request(s)

\");\n os.println(preqs.toString());\n }\n }\n public void probeRequest(PrintWriter ps, ReqState rs) {\n Enumeration e;\n int i;\n ps.println(\"\n ps.println(\"The HttpServletRequest object is actually a: \" + rs.getRequest().getClass().getName());\n ps.println(\"\");\n ps.println(\"HttpServletRequest Interface:\");\n ps.println(\" getAuthType: \" + rs.getRequest().getAuthType());\n ps.println(\" getMethod: \" + rs.getRequest().getMethod());\n ps.println(\" getPathInfo: \" + rs.getRequest().getPathInfo());\n ps.println(\" getPathTranslated: \" + rs.getRequest().getPathTranslated());\n ps.println(\" getRequestURL: \" + rs.getRequest().getRequestURL());\n ps.println(\" getQueryString: \" + rs.getRequest().getQueryString());\n ps.println(\" getRemoteUser: \" + rs.getRequest().getRemoteUser());\n ps.println(\" getRequestedSessionId: \" + rs.getRequest().getRequestedSessionId());\n ps.println(\" getRequestURI: \" + rs.getRequest().getRequestURI());\n ps.println(\" getServletPath: \" + rs.getRequest().getServletPath());\n ps.println(\" isRequestedSessionIdFromCookie: \" + rs.getRequest().isRequestedSessionIdFromCookie());\n ps.println(\" isRequestedSessionIdValid: \" + rs.getRequest().isRequestedSessionIdValid());\n ps.println(\" isRequestedSessionIdFromURL: \" + rs.getRequest().isRequestedSessionIdFromURL());\n ps.println(\"\");\n i = 0;\n e = rs.getRequest().getHeaderNames();\n ps.println(\" Header Names:\");\n while (e.hasMoreElements()) {\n i++;\n String s = (String) e.nextElement();\n ps.print(\" Header[\" + i + \"]: \" + s);\n ps.println(\": \" + rs.getRequest().getHeader(s));\n }\n ps.println(\"\");\n ps.println(\"ServletRequest Interface:\");\n ps.println(\" getCharacterEncoding: \" + rs.getRequest().getCharacterEncoding());\n ps.println(\" getContentType: \" + rs.getRequest().getContentType());\n ps.println(\" getContentLength: \" + rs.getRequest().getContentLength());\n ps.println(\" getProtocol: \" + rs.getRequest().getProtocol());\n ps.println(\" getScheme: \" + rs.getRequest().getScheme());\n ps.println(\" getServerName: \" + rs.getRequest().getServerName());\n ps.println(\" getServerPort: \" + rs.getRequest().getServerPort());\n ps.println(\" getRemoteAddr: \" + rs.getRequest().getRemoteAddr());\n ps.println(\" getRemoteHost: \" + rs.getRequest().getRemoteHost());\n //ps.println(\" getRealPath: \"+rs.getRequest().getRealPath());\n ps.println(\".............................\");\n ps.println(\"\");\n i = 0;\n e = rs.getRequest().getAttributeNames();\n ps.println(\" Attribute Names:\");\n while (e.hasMoreElements()) {\n i++;\n String s = (String) e.nextElement();\n ps.print(\" Attribute[\" + i + \"]: \" + s);\n ps.println(\" Type: \" + rs.getRequest().getAttribute(s));\n }\n ps.println(\".............................\");\n ps.println(\"\");\n i = 0;\n e = rs.getRequest().getParameterNames();\n ps.println(\" Parameter Names:\");\n while (e.hasMoreElements()) {\n i++;\n String s = (String) e.nextElement();\n ps.print(\" Parameter[\" + i + \"]: \" + s);\n ps.println(\" Value: \" + rs.getRequest().getParameter(s));\n }\n ps.println(\"- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\");\n ps.println(\" . . . . . . . . . Servlet Infomation API . . . . . . . . . . . . . .\");\n ps.println(\"\");\n ps.println(\"Servlet Context:\");\n ps.println(\"\");\n /* i = 0;\n e = servletContext.getAttributeNames();\n ps.println(\" Attribute Names:\");\n while (e.hasMoreElements()) {\n i++;\n String s = (String) e.nextElement();\n ps.print(\" Attribute[\" + i + \"]: \" + s);\n ps.println(\" Type: \" + servletContext.getAttribute(s));\n }\n ps.println(\" ServletContext.getRealPath(\\\".\\\"): \" + servletContext.getRealPath(\".\"));\n ps.println(\" ServletContext.getMajorVersion(): \" + servletContext.getMajorVersion());\n// ps.println(\"ServletContext.getMimeType(): \" + sc.getMimeType());\n ps.println(\" ServletContext.getMinorVersion(): \" + servletContext.getMinorVersion());\n// ps.println(\"ServletContext.getRealPath(): \" + sc.getRealPath()); */\n ps.println(\".............................\");\n ps.println(\"Servlet Config:\");\n ps.println(\"\");\n ServletConfig scnfg = getServletConfig();\n i = 0;\n e = scnfg.getInitParameterNames();\n ps.println(\" InitParameters:\");\n while (e.hasMoreElements()) {\n String p = (String) e.nextElement();\n ps.print(\" InitParameter[\" + i + \"]: \" + p);\n ps.println(\" Value: \" + scnfg.getInitParameter(p));\n i++;\n }\n ps.println(\"\");\n ps.println(\"\n ps.println(\"\");\n }\n public String getServerName() {\n // Ascertain the name of this server.\n String servletName = this.getClass().getName();\n return (servletName);\n }\n public void doGet(HttpServletRequest request,\n HttpServletResponse response) {\n // setHeader(\"Last-Modified\", (new Date()).toString() );\n boolean isDebug = false;\n ReqState rs = null;\n RequestDebug reqD = null;\n try {\n rs = getRequestState(request, response);\n if (rs != null) {\n if (Debug.isSet(\"probeRequest\")) {\n probeRequest(new PrintWriter(new OutputStreamWriter(System.out, Util.UTF8), true), rs);\n }\n String ds = rs.getDataSet();\n String suff = rs.getRequestSuffix();\n isDebug = ((ds != null) && ds.equals(\"debug\") && (suff != null) && suff.equals(\"\"));\n }\n synchronized (syncLock) {\n if (!isDebug) {\n long reqno = HitCounter++;\n if (track) {\n reqD = new RequestDebug(reqno, Thread.currentThread().toString());\n rs.setUserObject(reqD);\n if (prArr == null) prArr = new ArrayList(10000);\n prArr.add((int) reqno, rs);\n }\n if (Debug.isSet(\"showRequest\")) {\n log.debug(\"\n log.debug(\"Server: \" + getServerName() + \" Request #\" + reqno);\n log.debug(\"Client: \" + rs.getRequest().getRemoteHost());\n log.debug(rs.toString());\n log.debug(\"Request dataset: '\" + rs.getDataSet() + \"' suffix: '\" + rs.getRequestSuffix() +\n \"' CE: '\" + rs.getConstraintExpression() + \"'\");\n }\n }\n } // synch\n if (rs != null) {\n String dataSet = rs.getDataSet();\n String requestSuffix = rs.getRequestSuffix();\n if (dataSet == null) {\n doGetDIR(rs);\n } else if (dataSet.equals(\"/\")) {\n doGetDIR(rs);\n } else if (dataSet.equals(\"\")) {\n doGetDIR(rs);\n } else if (dataSet.equalsIgnoreCase(\"/version\") || dataSet.equalsIgnoreCase(\"/version/\")) {\n doGetVER(rs);\n } else if (dataSet.equalsIgnoreCase(\"/help\") || dataSet.equalsIgnoreCase(\"/help/\")) {\n doGetHELP(rs);\n } else if (dataSet.equalsIgnoreCase(\"/\" + requestSuffix)) {\n doGetHELP(rs);\n } else if (requestSuffix.equalsIgnoreCase(\"dds\")) {\n doGetDDS(rs);\n } else if (requestSuffix.equalsIgnoreCase(\"das\")) {\n doGetDAS(rs);\n } else if (requestSuffix.equalsIgnoreCase(\"ddx\")) {\n doGetDDX(rs);\n } else if (requestSuffix.equalsIgnoreCase(\"blob\")) {\n doGetBLOB(rs);\n } else if (requestSuffix.equalsIgnoreCase(\"dods\")) {\n doGetDAP2Data(rs);\n } else if (requestSuffix.equalsIgnoreCase(\"asc\") ||\n requestSuffix.equalsIgnoreCase(\"ascii\")) {\n doGetASC(rs);\n } else if (requestSuffix.equalsIgnoreCase(\"info\")) {\n doGetINFO(rs);\n } else if (requestSuffix.equalsIgnoreCase(\"html\") || requestSuffix.equalsIgnoreCase(\"htm\")) {\n doGetHTML(rs);\n } else if (requestSuffix.equalsIgnoreCase(\"ver\") || requestSuffix.equalsIgnoreCase(\"version\")) {\n doGetVER(rs);\n } else if (requestSuffix.equalsIgnoreCase(\"help\")) {\n doGetHELP(rs);\n /* JC added\n } else if (dataSet.equalsIgnoreCase(\"catalog\") && requestSuffix.equalsIgnoreCase(\"xml\")) {\n doGetCatalog(rs);\n } else if (dataSet.equalsIgnoreCase(\"status\")) {\n doGetStatus(rs);\n } else if (dataSet.equalsIgnoreCase(\"systemproperties\")) {\n doGetSystemProps(rs);\n } else if (isDebug) {\n doDebug(rs); */\n } else if (requestSuffix.equals(\"\")) {\n badURL(rs);\n } else {\n badURL(rs);\n }\n } else {\n badURL(rs);\n }\n if (reqD != null) reqD.done = true;\n } catch (Throwable e) {\n anyExceptionHandler(e, rs);\n }\n }\n /**\n * @param request\n * @return the request state\n */\n protected ReqState getRequestState(HttpServletRequest request, HttpServletResponse response) {\n ReqState rs = null;\n // The url and query strings will come to us in encoded form\n // (see HTTPmethod.newMethod())\n String baseurl = request.getRequestURL().toString();\n baseurl = EscapeStrings.unescapeURL(baseurl);\n String query = request.getQueryString();\n query = EscapeStrings.unescapeURLQuery(query);\n try {\n rs = new ReqState(request, response, rootpath, getServerName(), baseurl, query);\n } catch (Exception bue) {\n rs = null;\n }\n return rs;\n }\n private void printHelpPage(PrintWriter pw) {\n pw.println(\"

OPeNDAP Server Help

\");\n pw.println(\"To access most of the features of this OPeNDAP server, append\");\n pw.println(\"one of the following a eight suffixes to a URL: .das, .dds, .dods, .ddx, .blob, .info,\");\n pw.println(\".ver or .help. Using these suffixes, you can ask this server for:\");\n pw.println(\"
\");\n pw.println(\"
das
Dataset Attribute Structure (DAS)
\");\n pw.println(\"
dds
Dataset Descriptor Structure (DDS)
\");\n pw.println(\"
dods
DataDDS object (A constrained DDS populated with data)
\");\n pw.println(\"
ddx
XML version of the DDS/DAS
\");\n pw.println(\"
blob
Serialized binary data content for requested data set, \" +\n \"with the constraint expression applied.
\");\n pw.println(\"
info
info object (attributes, types and other information)
\");\n pw.println(\"
html
html form for this dataset
\");\n pw.println(\"
ver
return the version number of the server
\");\n pw.println(\"
help
help information (this text)
\");\n pw.println(\"
\");\n pw.println(\"For example, to request the DAS object from the FNOC1 dataset at URI/GSO (a\");\n pw.println(\"test dataset) you would appand `.das' to the URL:\");\n pw.println(\"http://opendap.gso.url.edu/cgi-bin/nph-nc/data/fnoc1.nc.das.\");\n pw.println(\"

Note: Many OPeNDAP clients supply these extensions for you so you don't\");\n pw.println(\"need to append them (for example when using interfaces supplied by us or\");\n pw.println(\"software re-linked with a OPeNDAP client-library). Generally, you only need to\");\n pw.println(\"add these if you are typing a URL directly into a WWW browser.\");\n pw.println(\"

Note: If you would like version information for this server but\");\n pw.println(\"don't know a specific data file or data set name, use `/version' for the\");\n pw.println(\"filename. For example: http://opendap.gso.url.edu/cgi-bin/nph-nc/version will\");\n pw.println(\"return the version number for the netCDF server used in the first example. \");\n pw.println(\"

Suggestion: If you're typing this URL into a WWW browser and\");\n pw.println(\"would like information about the dataset, use the `.info' extension.\");\n pw.println(\"

If you'd like to see a data values, use the `.html' extension and submit a\");\n pw.println(\"query using the customized form.\");\n }\n private void printBadURLPage(PrintWriter pw) {\n pw.println(\"

Error in URL

\");\n pw.println(\"The URL extension did not match any that are known by this\");\n pw.println(\"server. Below is a list of the five extensions that are be recognized by\");\n pw.println(\"all OPeNDAP servers. If you think that the server is broken (that the URL you\");\n pw.println(\"submitted should have worked), then please contact the\");\n pw.println(\"OPeNDAP user support coordinator at: \");\n pw.println(\"support@unidata.ucar.edu

\");\n }"}}},{"rowIdx":346226,"cells":{"answer":{"kind":"string","value":"package step.functions;\nimport java.util.Map;\nimport javax.json.JsonObject;\nimport com.fasterxml.jackson.annotation.JsonTypeInfo;\nimport com.fasterxml.jackson.annotation.JsonTypeInfo.Id;\nimport step.core.accessors.AbstractOrganizableObject;\nimport step.core.dynamicbeans.DynamicValue;\n/**\n * This class encapsulates all the configuration parameters of functions (aka Keywords)\n * which can also be defined on the configuration dialog of Keywords in the UI\n *\n */\n@JsonTypeInfo(use=Id.CLASS,property=\"type\")\npublic class Function extends AbstractOrganizableObject {\n protected DynamicValue callTimeout = new DynamicValue<>(180000);\n protected JsonObject schema;\n protected boolean executeLocally;\n protected Map tokenSelectionCriteria;\n protected boolean managed;\n protected boolean useCustomTemplate=false;\n protected String htmlTemplate;\n public Map getTokenSelectionCriteria() {\n return tokenSelectionCriteria;\n }\n /**\n * Defines additional selection criteria of agent token on which the function should be executed\n *\n * @param tokenSelectionCriteria a map containing the additional selection criteria as key-value pairs\n */\n public void setTokenSelectionCriteria(Map tokenSelectionCriteria) {\n this.tokenSelectionCriteria = tokenSelectionCriteria;\n }\n /**\n * @return if the function has to be executed on a local token\n */\n public boolean isExecuteLocally() {\n return executeLocally;\n }\n /**\n * Defines if the function has to be executed on a local token\n *\n * @param executeLocally\n */\n public void setExecuteLocally(boolean executeLocally) {\n this.executeLocally = executeLocally;\n }\n public DynamicValue getCallTimeout() {\n return callTimeout;\n }\n /**\n * @param callTimeout the call timeout of the function in ms\n */\n public void setCallTimeout(DynamicValue callTimeout) {\n this.callTimeout = callTimeout;\n }\n public JsonObject getSchema() {\n return schema;\n }\n public void setSchema(JsonObject schema) {\n this.schema = schema;\n }\n public boolean requiresLocalExecution() {\n return executeLocally;\n }\n public boolean isManaged() {\n return managed;\n }\n public void setManaged(boolean managed) {\n this.managed = managed;\n }\n public boolean isUseCustomTemplate() {\n return useCustomTemplate;\n }\n public void setUseCustomTemplate(boolean customTemplate) {\n this.useCustomTemplate = customTemplate;\n }\n public String getHtmlTemplate() {\n return htmlTemplate;\n }\n public void setHtmlTemplate(String customTemplateContent) {\n this.htmlTemplate = customTemplateContent;\n if (htmlTemplate != null && !htmlTemplate.isEmpty()) {\n this.setUseCustomTemplate(true);\n }\n }\n}"}}},{"rowIdx":346227,"cells":{"answer":{"kind":"string","value":"package cn.cerc.mis.core;\nimport java.io.IOException;\nimport javax.servlet.ServletContext;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletRequest;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\nimport org.springframework.web.context.support.WebApplicationContextUtils;\nimport cn.cerc.core.ClassConfig;\nimport cn.cerc.core.ClassResource;\nimport cn.cerc.core.ISession;\nimport cn.cerc.core.LanguageResource;\nimport cn.cerc.db.core.IAppConfig;\nimport cn.cerc.db.core.IHandle;\nimport cn.cerc.db.core.ISessionOwner;\nimport cn.cerc.db.core.ITokenManage;\nimport cn.cerc.db.core.ServerConfig;\nimport cn.cerc.db.core.SupportHandle;\nimport cn.cerc.mis.SummerMIS;\nimport cn.cerc.mis.config.ApplicationConfig;\nimport cn.cerc.mis.language.Language;\nimport lombok.extern.slf4j.Slf4j;\n@Slf4j\npublic class Application {\n private static final ClassResource res = new ClassResource(Application.class, SummerMIS.ID);\n private static final ClassConfig config = new ClassConfig(Application.class, SummerMIS.ID);\n // tomcat JSESSION.ID\n public static final String sessionId = \"sessionId\";\n // token id\n // FIXME RequestDataTokensql LoginID_\n public static final String TOKEN = \"ID\";\n // user id\n public static final String userId = \"UserID\";\n public static final String userCode = \"UserCode\";\n public static final String userName = \"UserName\";\n public static final String roleCode = \"RoleCode\";\n public static final String bookNo = \"BookNo\";\n public static final String deviceLanguage = \"language\";\n public static final String ProxyUsers = \"ProxyUsers\";\n public static final String clientIP = \"clientIP\";\n public static final String loginTime = \"loginTime\";\n public static final String webclient = \"webclient\";\n // FIXME: 2019/12/7\n public static final String App_Language = getAppLanguage(); // cn/en\n public static final String PATH_FORMS = \"application.pathForms\";\n public static final String PATH_SERVICES = \"application.pathServices\";\n public static final String FORM_WELCOME = \"application.formWelcome\";\n public static final String FORM_DEFAULT = \"application.formDefault\";\n public static final String FORM_LOGOUT = \"application.formLogout\";\n public static final String FORM_VERIFY_DEVICE = \"application.formVerifyDevice\";\n public static final String JSPFILE_LOGIN = \"application.jspLoginFile\";\n public static final String FORM_ID = \"formId\";\n private static ApplicationContext context;\n private static String staticPath;\n static {\n staticPath = config.getString(\"app.static.path\", \"\");\n }\n public static void init(String packageId) {\n if (context != null)\n return;\n String xmlFile = String.format(\"%s-spring.xml\", packageId);\n if (packageId == null)\n xmlFile = \"application.xml\";\n ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(xmlFile);\n context = ctx;\n }\n public static ApplicationContext getContext() {\n return context;\n }\n private static String getAppLanguage() {\n return LanguageResource.appLanguage;\n }\n public static void setContext(ApplicationContext applicationContext) {\n if (context != applicationContext) {\n if (context == null) {\n } else {\n log.warn(\"applicationContext overload!\");\n }\n context = applicationContext;\n }\n }\n public static ApplicationContext get(ServletContext servletContext) {\n setContext(WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext));\n return context;\n }\n public static ApplicationContext get(ServletRequest request) {\n setContext(WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()));\n return context;\n }\n @Deprecated\n public static T getBean(String beanId, Class requiredType) {\n return context.getBean(beanId, requiredType);\n }\n public static T getBean(Class requiredType, String... beans) {\n for (String key : beans) {\n if (!context.containsBean(key)) {\n continue;\n }\n return context.getBean(key, requiredType);\n }\n return null;\n }\n /**\n * ISessionOwner session\n *\n * ITokenManage tokenManage, tokenManageDefault\n *\n * @param \n * @param requiredType\n * @param session\n * @return\n */\n public static T getBeanDefault(Class requiredType, ISession session) {\n String[] items = requiredType.getName().split(\"\\\\.\");\n String itemId = items[items.length - 1];\n String classId = itemId;\n if (itemId.substring(0, 2).toUpperCase().equals(itemId.substring(0, 2))) {\n classId = itemId.substring(1);\n }\n String beanId = classId.substring(0, 1).toLowerCase() + classId.substring(1);\n T result = getBean(requiredType, beanId, beanId + \"Default\");\n // session\n if ((session != null) && (result instanceof ISessionOwner)) {\n ((ISessionOwner) result).setSession(session);\n }\n return result;\n }\n public static T getBean(Class requiredType) {\n String[] items = requiredType.getName().split(\"\\\\.\");\n String itemId = items[items.length - 1];\n String beanId;\n if (itemId.substring(0, 2).toUpperCase().equals(itemId.substring(0, 2))) {\n beanId = itemId;\n } else {\n beanId = itemId.substring(0, 1).toLowerCase() + itemId.substring(1);\n }\n return context.getBean(beanId, requiredType);\n }\n @Deprecated\n public static IHandle getHandle() {\n return new Handle(createSession());\n }\n public static ISession createSession() {\n return getBeanDefault(ISession.class, null);\n }\n /**\n * ClassResourceAppConfigDefault\n *\n * @return\n */\n @Deprecated\n public static IAppConfig getAppConfig() {\n return getBeanDefault(IAppConfig.class, null);\n }\n @Deprecated // getBean\n public static T get(IHandle handle, Class requiredType) {\n return getBean(handle, requiredType);\n }\n public static T getBean(IHandle handle, Class requiredType) {\n T bean = getBean(requiredType);\n if (bean != null && handle != null) {\n if (bean instanceof IHandle) {\n ((IHandle) bean).setSession(handle.getSession());\n }\n }\n return bean;\n }\n public static IService getService(IHandle handle, String serviceCode) {\n IService bean = context.getBean(serviceCode, IService.class);\n if (bean != null && handle != null) {\n bean.setHandle(handle);\n }\n return bean;\n }\n public static IPassport getPassport(ISession session) {\n return getBeanDefault(IPassport.class, session);\n }\n public static IPassport getPassport(ISessionOwner owner) {\n return getBeanDefault(IPassport.class, owner.getSession());\n }\n public static ISystemTable getSystemTable() {\n return getBeanDefault(ISystemTable.class, null);\n }\n public static IForm getForm(HttpServletRequest req, HttpServletResponse resp, String formId) {\n if (formId == null || \"\".equals(formId) || \"service\".equals(formId)) {\n return null;\n }\n setContext(WebApplicationContextUtils.getRequiredWebApplicationContext(req.getServletContext()));\n if (!context.containsBean(formId)) {\n throw new RuntimeException(String.format(\"form %s not find!\", formId));\n }\n IForm form = context.getBean(formId, IForm.class);\n if (form != null) {\n form.setRequest(req);\n form.setResponse(resp);\n }\n return form;\n }\n public static String getLanguage() {\n String lang = ServerConfig.getInstance().getProperty(deviceLanguage);\n if (lang == null || \"\".equals(lang) || App_Language.equals(lang)) {\n return App_Language;\n } else if (Language.en_US.equals(lang)) {\n return lang;\n } else {\n throw new RuntimeException(\"not support language: \" + lang);\n }\n }\n public static String getFormView(HttpServletRequest req, HttpServletResponse resp, String formId, String funcCode, String... pathVariables) {\n req.setAttribute(\"logon\", false);\n IFormFilter formFilter = Application.getBean(IFormFilter.class, \"AppFormFilter\");\n if (formFilter != null) {\n try {\n if (formFilter.doFilter(resp, formId, funcCode)) {\n return null;\n }\n } catch (IOException e) {\n log.error(e.getMessage());\n e.printStackTrace();\n }\n }\n ISession session = null;\n try {\n IForm form = Application.getForm(req, resp, formId);\n if (form == null) {\n outputErrorPage(req, resp, new RuntimeException(\"error servlet:\" + req.getServletPath()));\n return null;\n }\n AppClient client = new AppClient();\n client.setRequest(req);\n req.setAttribute(\"_showMenu_\", !AppClient.ee.equals(client.getDevice()));\n form.setClient(client);\n session = Application.createSession();\n session.setProperty(Application.sessionId, req.getSession().getId());\n session.setProperty(Application.deviceLanguage, client.getLanguage());\n IHandle handle = new Handle(session);\n req.setAttribute(\"myappHandle\", handle);\n form.setId(formId);\n form.setHandle(handle);\n form.setPathVariables(pathVariables);\n // Form\n if (form.allowGuestUser()) {\n return form.getView(funcCode);\n }\n if (session.logon()) {\n if (!Application.getPassport(session).pass(form)) {\n resp.setContentType(\"text/html;charset=UTF-8\");\n JsonPage output = new JsonPage(form);\n output.setResultMessage(false, res.getString(1, \"\"));\n output.execute();\n return null;\n }\n } else {\n IAppLogin appLogin = Application.getBeanDefault(IAppLogin.class, session);\n if (!appLogin.pass(form)) {\n return appLogin.getJspFile();\n }\n }\n if (form.isSecurityDevice()) {\n return form.getView(funcCode);\n }\n ISecurityDeviceCheck deviceCheck = Application.getBeanDefault(ISecurityDeviceCheck.class, session);\n switch (deviceCheck.pass(form)) {\n case PASS:\n return form.getView(funcCode);\n case CHECK:\n return \"redirect:\" + config.getString(Application.FORM_VERIFY_DEVICE, \"VerifyDevice\");\n default:\n resp.setContentType(\"text/html;charset=UTF-8\");\n JsonPage output = new JsonPage(form);\n output.setResultMessage(false, res.getString(2, \"\"));\n output.execute();\n return null;\n }\n } catch (Exception e) {\n outputErrorPage(req, resp, e);\n return null;\n } finally {\n if (session != null) {\n session.close();\n }\n }\n }\n public static void outputView(HttpServletRequest request, HttpServletResponse response, String url) throws IOException, ServletException {\n if (url == null)\n return;\n if (url.startsWith(\"redirect:\")) {\n String redirect = url.substring(9);\n redirect = response.encodeRedirectURL(redirect);\n response.sendRedirect(redirect);\n return;\n }\n // jsp\n String jspFile = String.format(\"/WEB-INF/%s/%s\", config.getString(Application.PATH_FORMS, \"forms\"), url);\n request.getServletContext().getRequestDispatcher(jspFile).forward(request, response);\n }\n public static void outputErrorPage(HttpServletRequest request, HttpServletResponse response, Throwable e) {\n Throwable err = e.getCause();\n if (err == null) {\n err = e;\n }\n IAppErrorPage errorPage = Application.getBeanDefault(IAppErrorPage.class, null);\n if (errorPage != null) {\n String result = errorPage.getErrorPage(request, response, err);\n if (result != null) {\n String url = String.format(\"/WEB-INF/%s/%s\", config.getString(Application.PATH_FORMS, \"forms\"), result);\n try {\n request.getServletContext().getRequestDispatcher(url).forward(request, response);\n } catch (ServletException | IOException e1) {\n log.error(e1.getMessage());\n e1.printStackTrace();\n }\n }\n } else {\n log.warn(\"not define bean: errorPage\");\n log.error(err.getMessage());\n err.printStackTrace();\n }\n }\n /**\n * token\n *\n * @param handle\n * @return\n */\n public static String getToken(IHandle handle) {\n return (String) handle.getProperty(Application.TOKEN);\n }\n public static String getStaticPath() {\n return staticPath;\n }\n public static ITokenManage getTokenManage(ISession session) {\n return getBeanDefault(ITokenManage.class, session);\n }\n public static String getHomePage() {\n return config.getString(Application.FORM_DEFAULT, \"default\");\n }\n}"}}},{"rowIdx":346228,"cells":{"answer":{"kind":"string","value":"package oap.dictionary;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.function.Predicate;\nimport static java.util.stream.Collectors.toList;\npublic interface Dictionary {\n int getOrDefault( String id, int defaultValue );\n Integer get( String id );\n String getOrDefault( int externlId, String defaultValue );\n boolean containsValueWithId( String id );\n List ids();\n int[] externalIds();\n Map getProperties();\n Optional getValueOpt( String name );\n Dictionary getValue( String name );\n Dictionary getValue( int externalId );\n List getValues();\n default List getValues( Predicate p ) {\n return getValues().stream().filter( p ).collect( toList() );\n }\n String getId();\n Optional getProperty( String name );\n default T getPropertyOrThrow( String name ) {\n return this.getProperty( name )\n .orElseThrow( () -> new IllegalArgumentException( getId() + \": not found\" ) );\n }\n boolean isEnabled();\n int getExternalId();\n boolean containsProperty( String name );\n @SuppressWarnings( \"unchecked\" )\n default List getTags() {\n return ( List ) getProperty( \"tags\" ).orElse( Collections.emptyList() );\n }\n}"}}},{"rowIdx":346229,"cells":{"answer":{"kind":"string","value":"package graph;\nimport generaltools.ArrayTools;\nimport graphtools.EdmondsKarpMaxFlowMinCut;\nimport hashtools.TwoKeyHash;\nimport java.util.Arrays;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.SortedSet;\nimport java.util.TreeSet;\nimport java.util.Vector;\nimport mathtools.MapleTools;\nimport mathtools.Subsets;\nimport org.jgrapht.WeightedGraph;\nimport org.jgrapht.alg.EdmondsKarpMaximumFlow;\nimport org.jgrapht.alg.MinSourceSinkCut;\nimport org.jgrapht.alg.StoerWagnerMinimumCut;\nimport org.jgrapht.graph.DefaultWeightedEdge;\nimport org.jgrapht.graph.DirectedWeightedMultigraph;\nimport filetools.WriteFile;\nimport returntools.Tuple2;\nimport syst.Instance;\nimport syst.Systm;\nimport syst.Variable;\npublic class BinaryGraph {\n private Systm sys;\n private DirectedWeightedMultigraph graph;\n private final Variable source = new Variable(\"S\");\n private final Variable sink = new Variable(\"T\");\n private final String[] biLabels;\n private boolean isAE; //is from an alpha expansion\n /* * * * * * * * * *\n * CONSTRUCTORS *\n * * * * * * * * * */\n /**\n * @param s A binary Systm\n */\n public BinaryGraph(Systm s, boolean ae){\n // Instantiate the Systm and make the hats\n sys = s;\n sys.makeHats();\n if (ae){\n biLabels = Systm.binaryLabels;\n if (!sys.getIsBinary()){\n System.out.println(\"Must have a binary Systm to make a BinaryGraph!\");\n System.exit(0);\n }else{\n // Make the flow network from the normal form energy\n createNonSubmodularFlowNetworkAE();\n //printGraphCompact();\n }\n }else{\n biLabels = null;\n if (!sys.getIsBinary()){\n System.out.println(\"Must have a binary Systm to make a BinaryGraph!\");\n System.exit(0);\n }else{\n // Make the flow network from the normal form energy\n createNonSubmodularFlowNetworkNonAE();\n printGraphCompact();\n }\n }\n }\n public BinaryGraph(Systm s, boolean ae, WriteFile wr){\n // Instantiate the Systm and make the hats\n sys = s;\n sys.makeHats();\n if (ae){\n biLabels = Systm.binaryLabels;\n if (!sys.getIsBinary()){\n System.out.println(\"Must have a binary Systm to make a BinaryGraph!\");\n System.exit(0);\n }else{\n // Make the flow network from the normal form energy\n createNonSubmodularFlowNetworkAE();\n //printGraphCompact();\n }\n }else{\n biLabels = null;\n if (!sys.getIsBinary()){\n System.out.println(\"Must have a binary Systm to make a BinaryGraph!\");\n System.exit(0);\n }else{\n // Make the flow network from the normal form energy\n createNonSubmodularFlowNetworkNonAE();\n printGraphCompact(wr);\n }\n }\n }\n /* * * * * * *\n * THE CUT *\n * * * * * * */\n /**\n * Does the graph cut on the flow network to find the minimum\n * energy configuration. If some Variables are not assigned we\n * do the brute force minimization on just those unassigned\n * Variables.\n * @return The array of {0,1} indicating the output of\n * the cut. There may be some -1 in the array if the cut\n * algorithm failed to label everything and what it didn't\n * label was too large for brute force (currently >25 elements)\n */\n public HashMap doCut(){\n System.out.println(\"Doing the cut!\");\n EdmondsKarpMaxFlowMinCut F =\n new EdmondsKarpMaxFlowMinCut(graph);\n Vector vars = sys.getVars();\n Double constantNF = sys.getConstantNF();\n F.calculateMinimumCut(source, sink);\n F.calculateMinimumCutValue();\n System.out.println();\n Map minCut = F.getMinimumCut();\n Double minCutValue = F.getMinimumCutValue();\n Vector S = new Vector();\n Vector T = new Vector();\n Vector U = new Vector();\n Iterator it = vars.iterator();\n int[] varSeq = new int[sys.getVars().size()]; int ind = 0;\n HashMap varHM = new HashMap();\n while (it.hasNext()){\n Variable gr = it.next();\n if (minCut.get(gr) == 0 && minCut.get(gr.getHat()) == 1){\n S.add(gr);\n varSeq[ind] = 0;\n varHM.put(gr, 0);\n }else if (minCut.get(gr) == 1 && minCut.get(gr.getHat())==0){\n T.add(gr);\n varSeq[ind] = 1;\n varHM.put(gr, 1);\n }else{\n U.add(gr);\n varSeq[ind] = -1;\n varHM.put(gr, -1);\n }\n ind++;\n }\n //System.out.println(\"flow: \"+F.getMaximumFlow().toString());\n System.out.println(\"flow value: \"+F.getMaximumFlowValue().toString());\n System.out.println(\"cut: \"+minCut.toString());\n System.out.println(\"cut value: \"+minCutValue);\n //System.out.println(\"cut constant: \"+constantNF);\n System.out.println(\"cut + constant: \" + (minCutValue+constantNF));\n System.out.println();\n printST(S,T);\n System.out.println(\"UNKNOWN groups: \"+Arrays.deepToString(U.toArray()));\n System.out.println(\"\n Tuple2 better = bruteLeftOver(varSeq);\n if (better != null){\n Double minValue = better.getFirst();\n int[] varSeq2 = better.getSecond();\n HashMap varHM2 = new HashMap();\n Vector S2 = new Vector();\n Vector T2 = new Vector();\n Vector U2 = new Vector();\n //TODO: Here I'm just picking the first of the minimizers\n // since they are all the same minimum value. Should probably\n // pick more carefully\n //for (int i=0; i doCutNonAE(){\n System.out.println(\"Doing the cut!\");\n EdmondsKarpMaxFlowMinCut F =\n new EdmondsKarpMaxFlowMinCut(graph);\n Vector vars = sys.getVars();\n Double constantNF = sys.getConstantNF();\n F.calculateMinimumCut(source, sink);\n F.calculateMinimumCutValue();\n System.out.println();\n Map minCut = F.getMinimumCut();\n Double minCutValue = F.getMinimumCutValue();\n Vector S = new Vector();\n Vector T = new Vector();\n Vector U = new Vector();\n Iterator it = vars.iterator();\n int[] varSeq = new int[sys.getVars().size()]; int ind = 0;\n HashMap varHM = new HashMap();\n while (it.hasNext()){\n Variable gr = it.next();\n if (minCut.get(gr) == 0 && minCut.get(gr.getHat()) == 1){\n S.add(gr);\n varSeq[ind] = 0;\n varHM.put(gr, gr.getInstances().get(0));\n }else if (minCut.get(gr) == 1 && minCut.get(gr.getHat())==0){\n T.add(gr);\n varSeq[ind] = 1;\n varHM.put(gr, gr.getInstances().get(1));\n }else{\n U.add(gr);\n varSeq[ind] = -1;\n varHM.put(gr, null);\n }\n ind++;\n }\n System.out.println(\"flow: \"+F.getMaximumFlow().toString());\n System.out.println(\"flow value: \"+F.getMaximumFlowValue().toString());\n System.out.println(\"cut: \"+minCut.toString());\n System.out.println(\"cut value: \"+minCutValue);\n //System.out.println(\"cut constant: \"+constantNF);\n System.out.println(\"cut + constant: \" + (minCutValue+constantNF));\n System.out.println();\n printST(S,T);\n System.out.println(\"UNKNOWN groups: \"+Arrays.deepToString(U.toArray()));\n System.out.println(\"\n Tuple2 better = bruteLeftOver(varSeq);\n if (better != null){\n Double minValue = better.getFirst();\n int[] varSeq2 = better.getSecond();\n HashMap varHM2 = new HashMap();\n Vector S2 = new Vector();\n Vector T2 = new Vector();\n Vector U2 = new Vector();\n //TODO: Here I'm just picking the first of the minimizers\n // since they are all the same minimum value. Should probably\n // pick more carefully\n //for (int i=0; i doCutNonAE(WriteFile wr){\n System.out.println(\"Doing the cut!\");\n EdmondsKarpMaxFlowMinCut F =\n new EdmondsKarpMaxFlowMinCut(graph);\n Vector vars = sys.getVars();\n Double constantNF = sys.getConstantNF();\n F.calculateMinimumCut(source, sink);\n F.calculateMinimumCutValue();\n System.out.println();\n Map minCut = F.getMinimumCut();\n Double minCutValue = F.getMinimumCutValue();\n Vector S = new Vector();\n Vector T = new Vector();\n Vector U = new Vector();\n Iterator it = vars.iterator();\n int[] varSeq = new int[sys.getVars().size()]; int ind = 0;\n HashMap varHM = new HashMap();\n while (it.hasNext()){\n Variable gr = it.next();\n if (minCut.get(gr) == 0 && minCut.get(gr.getHat()) == 1){\n S.add(gr);\n varSeq[ind] = 0;\n varHM.put(gr, gr.getInstances().get(0));\n }else if (minCut.get(gr) == 1 && minCut.get(gr.getHat())==0){\n T.add(gr);\n varSeq[ind] = 1;\n varHM.put(gr, gr.getInstances().get(1));\n }else{\n U.add(gr);\n varSeq[ind] = -1;\n varHM.put(gr, null);\n }\n ind++;\n }\n wr.writeln(\"RESULTS\");\n wr.writeln(\"flow: \"+F.getMaximumFlow().toString());\n wr.writeln(\"flow value: \"+F.getMaximumFlowValue().toString());\n wr.writeln(\"cut: \"+minCut.toString());\n wr.writeln(\"cut value: \"+minCutValue);\n //System.out.println(\"cut constant: \"+constantNF);\n wr.writeln(\"cut + constant: \" + (minCutValue+constantNF));\n wr.writeln();\n printST(S,T,wr);\n wr.writeln(\"UNKNOWN groups: \"+Arrays.deepToString(U.toArray()));\n wr.writeln(\"\n Tuple2 better = bruteLeftOver(varSeq, wr);\n if (better != null){\n Double minValue = better.getFirst();\n int[] varSeq2 = better.getSecond();\n HashMap varHM2 = new HashMap();\n Vector S2 = new Vector();\n Vector T2 = new Vector();\n Vector U2 = new Vector();\n //TODO: Here I'm just picking the first of the minimizers\n // since they are all the same minimum value. Should probably\n // pick more carefully\n //for (int i=0; i doCutNonAE(WriteFile main, WriteFile sec){\n System.out.println(\"Doing the cut!\");\n MinSourceSinkCut MSSC =\n new MinSourceSinkCut(graph);\n EdmondsKarpMaximumFlow F =\n new EdmondsKarpMaximumFlow(graph);\n Vector vars = sys.getVars();\n Double constantNF = sys.getConstantNF();\n// F.calculateMinimumCut(source, sink);\n// F.calculateMinimumCutValue();\n F.calculateMaximumFlow(source, sink);\n MSSC.computeMinCut(source, sink);\n System.out.println();\n// Map minCut = F.getMinimumCut();\n Set SRC = MSSC.getSourcePartition();\n Set SNK = MSSC.getSinkPartition();\n// Double minCutValue = F.getMinimumCutValue();\n Double minCutValue = MSSC.getCutWeight();\n if (minCutValue - F.getMaximumFlowValue() > 0.00001){\n throw new IllegalArgumentException(\n \"maxflow != mincut\");\n }\n Vector S = new Vector();\n Vector T = new Vector();\n Vector U = new Vector();\n Iterator it = vars.iterator();\n int[] varSeq = new int[sys.getVars().size()]; int ind = 0;\n HashMap varHM = new HashMap();\n while (it.hasNext()){\n Variable gr = it.next();\n// if (minCut.get(gr) == 0 && minCut.get(gr.getHat()) == 1){\n if (SRC.contains(gr) && SNK.contains(gr.getHat())){\n S.add(gr);\n varSeq[ind] = 0;\n varHM.put(gr, gr.getInstances().get(0));\n// }else if (minCut.get(gr) == 1 && minCut.get(gr.getHat())==0){\n }else if (SNK.contains(gr) && SRC.contains(gr.getHat())){\n T.add(gr);\n varSeq[ind] = 1;\n varHM.put(gr, gr.getInstances().get(1));\n }else{\n U.add(gr);\n varSeq[ind] = -1;\n varHM.put(gr, null);\n }\n ind++;\n }\n main.writeln(\"RESULTS\");\n// main.writeln(\"flow: \"+F.getMaximumFlow().toString());\n main.writeln(\"flow: \"+F.getMaximumFlow().toString());\n main.writeln(\"flow value: \"+F.getMaximumFlowValue().toString());\n// main.writeln(\"cut: \"+minCut.toString());\n main.writeln(\"cut:\");\n main.writeln(\" SRC = \"+SRC.toString());\n main.writeln(\" SNK = \"+SNK.toString());\n main.writeln(\"cut value: \"+minCutValue);\n //System.out.println(\"cut constant: \"+constantNF);\n main.writeln(\"cut + constant: \" + (minCutValue+constantNF));\n main.writeln();\n printST(S,T,main);\n main.writeln(\"UNKNOWN groups: \"+Arrays.deepToString(U.toArray()));\n main.writeln(\"\n Tuple2 better = bruteLeftOver(varSeq, main, sec);\n if (better != null){\n Double minValue = better.getFirst();\n int[] varSeq2 = better.getSecond();\n HashMap varHM2 = new HashMap();\n Vector S2 = new Vector();\n Vector T2 = new Vector();\n Vector U2 = new Vector();\n //TODO: Here I'm just picking the first of the minimizers\n // since they are all the same minimum value. Should probably\n // pick more carefully\n //for (int i=0; i bruteLeftOver(int[] varSeq) {\n int[] unassigned = MapleTools.select(-1, varSeq);\n int n = unassigned.length;\n System.out.println(\"There are \"+n+\" unassigned residues.\");\n if (n==0){\n //System.out.println(\"There are no unassigned residues.\");\n // long endBrute = System.currentTimeMillis();\n // System.out.println(\"Took \"+(endBrute - startBrute)+\" ms to do the brute force minimization on the unassigned residues.\");\n // //time.write(\"brute \"+(endBrute-startBrute)+\" \");\n // time.write(\"NO \");\n return null;\n }\n if (n>25){\n System.out.println(\"Can't do brute that high! There are \"+n+\" unassigned residues.\");\n // long endBrute = System.currentTimeMillis();\n // System.out.println(\"Took \"+(endBrute - startBrute)+\" ms to do the brute force minimization on the unassigned residues.\");\n // //time.write(\"brute \"+(endBrute-startBrute)+\" \");\n // time.write(\"XX \");\n // wr.write(n+\" \");\n return null;\n }\n Subsets S = new Subsets(n);\n double currentMin = Double.POSITIVE_INFINITY;\n int[] currentMinimizer = new int[n];\n while (S.hasNext()){\n int[] subset = S.next();\n int[] fullSub = varSeq.clone();\n for (int j=0; j Ret = new Tuple2(currentMin, currentMinimizer);\n return Ret;\n }\n private Tuple2 bruteLeftOver(int[] varSeq, WriteFile wr) {\n int[] unassigned = MapleTools.select(-1, varSeq);\n int n = unassigned.length;\n wr.writeln(\"There are \"+n+\" unassigned residues.\");\n if (n==0){\n //System.out.println(\"There are no unassigned residues.\");\n // long endBrute = System.currentTimeMillis();\n // System.out.println(\"Took \"+(endBrute - startBrute)+\" ms to do the brute force minimization on the unassigned residues.\");\n // //time.write(\"brute \"+(endBrute-startBrute)+\" \");\n // time.write(\"NO \");\n return null;\n }\n if (n>25){\n wr.writeln(\"Can't do brute that high! There are \"+n+\" unassigned residues.\");\n // long endBrute = System.currentTimeMillis();\n // System.out.println(\"Took \"+(endBrute - startBrute)+\" ms to do the brute force minimization on the unassigned residues.\");\n // //time.write(\"brute \"+(endBrute-startBrute)+\" \");\n // time.write(\"XX \");\n // wr.write(n+\" \");\n return null;\n }\n Subsets S = new Subsets(n);\n double currentMin = Double.POSITIVE_INFINITY;\n int[] currentMinimizer = new int[n];\n while (S.hasNext()){\n int[] subset = S.next();\n int[] fullSub = varSeq.clone();\n for (int j=0; j Ret = new Tuple2(currentMin, currentMinimizer);\n return Ret;\n }\n private Tuple2 bruteLeftOver(int[] varSeq, WriteFile wr, WriteFile sec) {\n int[] unassigned = MapleTools.select(-1, varSeq);\n int n = unassigned.length;\n wr.writeln(\"There are \"+n+\" unassigned residues.\");\n sec.writeln(sys.getVars().size()+\" \"+n);\n if (n==0){\n //System.out.println(\"There are no unassigned residues.\");\n // long endBrute = System.currentTimeMillis();\n // System.out.println(\"Took \"+(endBrute - startBrute)+\" ms to do the brute force minimization on the unassigned residues.\");\n // //time.write(\"brute \"+(endBrute-startBrute)+\" \");\n // time.write(\"NO \");\n return null;\n }\n if (n>25){\n wr.writeln(\"Can't do brute that high! There are \"+n+\" unassigned residues.\");\n // long endBrute = System.currentTimeMillis();\n // System.out.println(\"Took \"+(endBrute - startBrute)+\" ms to do the brute force minimization on the unassigned residues.\");\n // //time.write(\"brute \"+(endBrute-startBrute)+\" \");\n // time.write(\"XX \");\n // wr.write(n+\" \");\n return null;\n }\n Subsets S = new Subsets(n);\n double currentMin = Double.POSITIVE_INFINITY;\n int[] currentMinimizer = new int[n];\n while (S.hasNext()){\n int[] subset = S.next();\n int[] fullSub = varSeq.clone();\n for (int j=0; j Ret = new Tuple2(currentMin, currentMinimizer);\n return Ret;\n }\n /* * * * * * * *\n * MAKE GRAPH *\n * * * * * * * */\n /**\n * Creates the flow network for the general binary Systm\n * of this BinaryGraph object.\n */\n private void createNonSubmodularFlowNetworkNonAE(){\n System.out.println(\"Making the binary energy flow network for the binary Systm.\");\n // Get the variables and normal form binary energy\n Vector vars = sys.getVars();\n TwoKeyHash matrixNF = sys.getBinaryNF();\n // This will be the flow network\n DirectedWeightedMultigraph g =\n new DirectedWeightedMultigraph(DefaultWeightedEdge.class);\n int n = vars.size();\n g.addVertex(source);\n g.addVertex(sink);\n // Weight the edges as indicated in the Minimizing Non-Submodular Energy paper.\n for(int i = 0; i<=n-1; i++){\n Variable vi = vars.get(i); //System.out.println(vi);\n Variable viHat = vi.getHat(); //System.out.println(viHat);\n Vector viInsts = vi.getInstances();\n Instance vi0 = viInsts.get(0);\n Instance vi1 = viInsts.get(1);\n g.addVertex(vi);\n g.addVertex(viHat);\n Double E0 = vi0.getEnergyNF();\n Double E1 = vi1.getEnergyNF();\n g.addEdge(vi,sink);\n g.setEdgeWeight(g.getEdge(vi, sink),0.5*E0);\n g.addEdge(source,viHat);\n g.setEdgeWeight(g.getEdge(source,viHat), 0.5*E0);\n g.addEdge(source,vi);\n g.setEdgeWeight(g.getEdge(source,vi),0.5*E1);\n g.addEdge(viHat, sink);\n g.setEdgeWeight(g.getEdge(viHat,sink),0.5*E1);\n }\n for(int p=0; p<=n-1; p++){\n for(int q=p+1; q<=n-1 && p!=q; q++){\n Variable vp = vars.get(p);\n Vector vpInsts = vp.getInstances();\n Instance vp0 = vpInsts.get(0); Instance vp1 = vpInsts.get(1);\n Variable vpHat = vp.getHat();\n Variable vq = vars.get(q);\n Vector vqInsts = vq.getInstances();\n Instance vq0 = vqInsts.get(0); Instance vq1 = vqInsts.get(1);\n Variable vqHat = vq.getHat();\n //System.out.println(vp.toString()+\" [\"+vp0.toString()+\", \"+vp1.toString()+\"] \"+vq.toString()+\" [\"+vq0.toString()+\", \"+vq1.toString()+\"]\");\n Double E01 = matrixNF.get(vp0, vq1);\n Double E10 = matrixNF.get(vp1, vq0);\n Double E00 = matrixNF.get(vp0, vq0);\n Double E11 = matrixNF.get(vp1, vq1);\n g.addEdge(vp,vq);\n g.addEdge(vqHat,vpHat);\n g.setEdgeWeight(g.getEdge(vp,vq), 0.5*E01);\n g.setEdgeWeight(g.getEdge(vqHat,vpHat), 0.5*E01);\n g.addEdge(vq,vp);\n g.addEdge(vpHat,vqHat);\n g.setEdgeWeight(g.getEdge(vq,vp),0.5*E10);\n g.setEdgeWeight(g.getEdge(vpHat,vqHat), 0.5*E10);\n g.addEdge(vp,vqHat);\n g.addEdge(vq,vpHat);\n g.setEdgeWeight(g.getEdge(vp,vqHat),0.5*E00);\n g.setEdgeWeight(g.getEdge(vq,vpHat), 0.5*E00);\n g.addEdge(vqHat,vp);\n g.addEdge(vpHat,vq);\n g.setEdgeWeight(g.getEdge(vqHat,vp),0.5*E11);\n g.setEdgeWeight(g.getEdge(vpHat,vq),0.5*E11);\n }\n }\n graph = addWeights(g);\n }\n /**\n * Creates the flow network for the binary Systm (created for\n * the alpha-expansion) of this BinaryGraph object.\n */\n private void createNonSubmodularFlowNetworkAE() {\n System.out.println(\"Making the binary energy flow network for the alpha-expansion.\");\n // Get the variables and normal form binary energy\n Vector vars = sys.getVars();\n TwoKeyHash matrixNF = sys.getBinaryNF();\n // This will be the flow network\n DirectedWeightedMultigraph g =\n new DirectedWeightedMultigraph(DefaultWeightedEdge.class);\n int n = vars.size();\n g.addVertex(source);\n g.addVertex(sink);\n // Weight the edges as indicated in the Minimizing Non-Submodular Energy paper.\n for(int i = 0; i<=n-1; i++){\n Variable vi = vars.get(i); //System.out.println(vi);\n Variable viHat = vi.getHat(); //System.out.println(viHat);\n Instance vi0 = vi.getInstance(biLabels[0]);\n Instance vi1 = vi.getInstance(biLabels[1]);\n g.addVertex(vi);\n g.addVertex(viHat);\n Double E0 = vi0.getEnergyNF();\n Double E1 = vi1.getEnergyNF();\n g.addEdge(vi,sink);\n g.setEdgeWeight(g.getEdge(vi, sink),0.5*E0);\n g.addEdge(source,viHat);\n g.setEdgeWeight(g.getEdge(source,viHat), 0.5*E0);\n g.addEdge(source,vi);\n g.setEdgeWeight(g.getEdge(source,vi),0.5*E1);\n g.addEdge(viHat, sink);\n g.setEdgeWeight(g.getEdge(viHat,sink),0.5*E1);\n }\n for(int p=0; p<=n-1; p++){\n for(int q=p+1; q<=n-1 && p!=q; q++){\n Variable vp = vars.get(p);\n Instance vp0 = vp.getInstance(biLabels[0]); Instance vp1 = vp.getInstance(biLabels[1]);\n Variable vpHat = vp.getHat();\n Variable vq = vars.get(q);\n Instance vq0 = vq.getInstance(biLabels[0]); Instance vq1 = vq.getInstance(biLabels[1]);\n Variable vqHat = vq.getHat();\n Double E01 = matrixNF.get(vp0, vq1);\n Double E10 = matrixNF.get(vp1, vq0);\n Double E00 = matrixNF.get(vp0, vq0);\n Double E11 = matrixNF.get(vp1, vq1);\n g.addEdge(vp,vq);\n g.addEdge(vqHat,vpHat);\n g.setEdgeWeight(g.getEdge(vp,vq), 0.5*E01);\n g.setEdgeWeight(g.getEdge(vqHat,vpHat), 0.5*E01);\n g.addEdge(vq,vp);\n g.addEdge(vpHat,vqHat);\n g.setEdgeWeight(g.getEdge(vq,vp),0.5*E10);\n g.setEdgeWeight(g.getEdge(vpHat,vqHat), 0.5*E10);\n g.addEdge(vp,vqHat);\n g.addEdge(vq,vpHat);\n g.setEdgeWeight(g.getEdge(vp,vqHat),0.5*E00);\n g.setEdgeWeight(g.getEdge(vq,vpHat), 0.5*E00);\n g.addEdge(vqHat,vp);\n g.addEdge(vpHat,vq);\n g.setEdgeWeight(g.getEdge(vqHat,vp),0.5*E11);\n g.setEdgeWeight(g.getEdge(vpHat,vq),0.5*E11);\n }\n }\n graph = addWeights(g);\n }\n /**\n * @param g A flow network with possible multi-edges\n * @return The same flow network with all multi-edges\n * collapsed into a single edge having weight equal\n * to the sum of the original weights.\n */\n private DirectedWeightedMultigraph addWeights(\n DirectedWeightedMultigraph g) {\n DirectedWeightedMultigraph g1 =\n new DirectedWeightedMultigraph(DefaultWeightedEdge.class);\n Set vertices = g.vertexSet();\n for(Variable v: vertices){\n for(Variable w: vertices){\n g1.addVertex(v);\n g1.addVertex(w);\n Set edges = g.getAllEdges(v, w);\n Double newWt = new Double(0);\n for(DefaultWeightedEdge e: edges){\n newWt += g.getEdgeWeight(e);\n }\n if(newWt != 0){\n g1.addEdge(v,w);\n g1.setEdgeWeight(g1.getEdge(v,w), newWt);\n }\n }\n }\n return g1;\n }\n /* * * * * * * *\n * PRINTING *\n * * * * * * * */\n /**\n * Prints out the number of vertices as well as the edges with weights\n * Number of vertices first followed by each edge and weight\n * on subsequent lines (one line per edge)\n */\n public void printGraph() {\n Set vertices = graph.vertexSet();\n System.out.println(\"There are \"+vertices.size() +\" vertices.\");\n System.out.println(\"The edges with weights are:\");\n for(Variable v: vertices){\n for(Variable w: vertices){\n Set edges = graph.getAllEdges(v, w);\n for(DefaultWeightedEdge e: edges){\n double wt = graph.getEdgeWeight(e);\n System.out.println(v.toString()+\", \"+ w.toString() +\", \"+ wt);\n }\n }\n }\n }\n /**\n * Prints out the vertex set and edge set with weights on one line.\n * [vertex set], {(v1,v2)=wt...}\n * where (v1,v2) is an edge with weight wt\n */\n public void printGraphCompact(){\n Set vertices = graph.vertexSet();\n String toPrint = \" \";\n toPrint = toPrint.concat(vertices.toString()+\", {\");\n for(Variable v: vertices){\n for(Variable w: vertices){\n Set edges = graph.getAllEdges(v, w);\n for(DefaultWeightedEdge e: edges){\n double wt = graph.getEdgeWeight(e);\n toPrint = toPrint.concat(\"(\"+v.toString()+\", \"+ w.toString() +\")= \"+ wt+\", \");\n }\n }\n }\n toPrint = toPrint.substring(0,toPrint.length()-2);\n toPrint = toPrint.concat(\"}\");\n System.out.println(toPrint);\n }\n public void printGraphCompact(WriteFile wr){\n Set vertices = graph.vertexSet();\n // sort the vertices alphabetically\n Comparator comparator = new Comparator() {\n public int compare(Variable o1, Variable o2) {\n return o1.getName().toString().compareTo(o2.getName().toString());\n }\n };\n SortedSet sorted_keys = new TreeSet(comparator);\n sorted_keys.addAll(vertices);\n // run through the vertices to print\n String toPrintVerts = \"Vertices:\\n\";\n String toPrintEdges = \"Edges:\\n\";\n for(Variable vtx1: sorted_keys){\n String vname = vtx1.toString();\n String vnameTranslate = \"\";\n if (vname.equals(\"S\"))\n vnameTranslate = \"S\";\n else if (vname.equals(\"T\"))\n vnameTranslate = \"T\";\n else if (vname.substring(vname.length()-2).equals(\"_H\")){\n vnameTranslate = vname.substring(0, vname.length()-2)+\"_PROTONATED\";\n }else{\n vnameTranslate = vname+\"_DEPROTONATED\";\n }\n toPrintVerts += (vnameTranslate+\"\\n\");\n for (Variable vtx2 : sorted_keys){\n if (vtx1.equals(vtx2))\n continue;\n String wname = vtx2.toString();\n String wnameTranslate = \"\";\n if (wname.equals(\"S\"))\n wnameTranslate = \"S\";\n else if (wname.equals(\"T\"))\n wnameTranslate = \"T\";\n else if (wname.substring(wname.length()-2).equals(\"_H\")){\n wnameTranslate = wname.substring(0, wname.length()-2)+\"_DEPROTONATED\";\n }else{\n wnameTranslate = wname+\"_PROTONATED\";\n }\n Set edges = graph.getAllEdges(vtx1, vtx2);\n for(DefaultWeightedEdge e: edges){\n double wt = graph.getEdgeWeight(e);\n toPrintEdges += (\"(\"+vnameTranslate+\", \"+ wnameTranslate +\")= \"+ Math.round(wt*10000.0)/10000.0+\"\\n\");\n }\n }\n }\n// String toPrint = \" \";\n// toPrint = toPrint.concat(vertices.toString()+\", {\");\n// for(Variable v: vertices){\n// for(Variable w: vertices){\n// Set edges = graph.getAllEdges(v, w);\n// for(DefaultWeightedEdge e: edges){\n// double wt = graph.getEdgeWeight(e);\n// toPrint = toPrint.concat(\"(\"+v.toString()+\", \"+ w.toString() +\")= \"+ wt+\", \");\n// toPrint = toPrint.substring(0,toPrint.length()-2);\n// toPrint = toPrint.concat(\"}\");\n wr.writeln(\"Flow network:\");\n wr.writeln(toPrintVerts);\n wr.writeln(toPrintEdges);\n }\n /**\n * Prints out the configuration given by the S and T sets\n * @param S Vector of Variables assigned to \"0\"\n * @param T Vector of Variables assigned to \"1\"\n */\n private void printST(Vector S, Vector T) {\n System.out.print(\"0 instances: \");\n for (int i=0; i S, Vector T, WriteFile wr) {\n wr.write(\"0 instances: \");\n for (int i=0; i findCustomAuthScripts(String pattern, int sizeLimit) {\n String[] targetArray = new String[] { pattern };\n Filter descriptionFilter = Filter.createSubstringFilter(OxConstants.DESCRIPTION, null, targetArray, null);\n Filter scriptTypeFilter = Filter.createEqualityFilter(OxConstants.SCRIPT_TYPE,\n CustomScriptType.PERSON_AUTHENTICATION);\n Filter displayNameFilter = Filter.createSubstringFilter(OxConstants.DISPLAY_NAME, null, targetArray, null);\n Filter searchFilter = Filter.createORFilter(descriptionFilter, displayNameFilter);\n return persistenceEntryManager.findEntries(getDnForCustomScript(null), CustomScript.class,\n Filter.createANDFilter(searchFilter, scriptTypeFilter), sizeLimit);\n }\n public List findCustomAuthScripts(int sizeLimit) {\n Filter searchFilter = Filter.createEqualityFilter(OxConstants.SCRIPT_TYPE,\n CustomScriptType.PERSON_AUTHENTICATION.getValue());\n return persistenceEntryManager.findEntries(getDnForCustomScript(null), CustomScript.class, searchFilter,\n sizeLimit);\n }\n public List findOtherCustomScripts(String pattern, int sizeLimit) {\n String[] targetArray = new String[] { pattern };\n Filter descriptionFilter = Filter.createSubstringFilter(OxConstants.DESCRIPTION, null, targetArray, null);\n Filter scriptTypeFilter = Filter.createNOTFilter(\n Filter.createEqualityFilter(OxConstants.SCRIPT_TYPE, CustomScriptType.PERSON_AUTHENTICATION));\n Filter displayNameFilter = Filter.createSubstringFilter(OxConstants.DISPLAY_NAME, null, targetArray, null);\n Filter searchFilter = Filter.createORFilter(descriptionFilter, displayNameFilter);\n return persistenceEntryManager.findEntries(getDnForCustomScript(null), CustomScript.class,\n Filter.createANDFilter(searchFilter, scriptTypeFilter), sizeLimit);\n }\n public List findScriptByType(CustomScriptType type, int sizeLimit) {\n Filter searchFilter = Filter.createEqualityFilter(OxConstants.SCRIPT_TYPE, type);\n return persistenceEntryManager.findEntries(getDnForCustomScript(null), CustomScript.class, searchFilter,\n sizeLimit);\n }\n public List findScriptByType(CustomScriptType type) {\n Filter searchFilter = Filter.createEqualityFilter(OxConstants.SCRIPT_TYPE, type);\n return persistenceEntryManager.findEntries(getDnForCustomScript(null), CustomScript.class, searchFilter, null);\n }\n public List findScriptByPatternAndType(String pattern, CustomScriptType type, int sizeLimit) {\n String[] targetArray = new String[] { pattern };\n Filter descriptionFilter = Filter.createSubstringFilter(OxConstants.DESCRIPTION, null, targetArray, null);\n Filter displayNameFilter = Filter.createSubstringFilter(OxConstants.DISPLAY_NAME, null, targetArray, null);\n Filter searchFilter = Filter.createORFilter(descriptionFilter, displayNameFilter);\n Filter typeFilter = Filter.createEqualityFilter(OxConstants.SCRIPT_TYPE, type);\n return persistenceEntryManager.findEntries(getDnForCustomScript(null), CustomScript.class,\n Filter.createANDFilter(searchFilter, typeFilter), sizeLimit);\n }\n public List findScriptByPatternAndType(String pattern, CustomScriptType type) {\n String[] targetArray = new String[] { pattern };\n Filter descriptionFilter = Filter.createSubstringFilter(OxConstants.DESCRIPTION, null, targetArray, null);\n Filter displayNameFilter = Filter.createSubstringFilter(OxConstants.DISPLAY_NAME, null, targetArray, null);\n Filter searchFilter = Filter.createORFilter(descriptionFilter, displayNameFilter);\n Filter typeFilter = Filter.createEqualityFilter(OxConstants.SCRIPT_TYPE, type);\n return persistenceEntryManager.findEntries(getDnForCustomScript(null), CustomScript.class,\n Filter.createANDFilter(searchFilter, typeFilter), null);\n }\n public List findOtherCustomScripts(int sizeLimit) {\n Filter searchFilter = Filter.createNOTFilter(\n Filter.createEqualityFilter(OxConstants.SCRIPT_TYPE, CustomScriptType.PERSON_AUTHENTICATION));\n return persistenceEntryManager.findEntries(getDnForCustomScript(null), CustomScript.class, searchFilter,\n sizeLimit);\n }\n public String getDnForCustomScript(String inum) {\n String orgDn = organizationService.getDnForOrganization(null);\n if (StringHelper.isEmpty(inum)) {\n return String.format(\"ou=scripts,%s\", orgDn);\n }\n return String.format(\"inum=%s,ou=scripts,%s\", inum, orgDn);\n }\n public String baseDn() {\n return String.format(\"ou=scripts,%s\", organizationService.getDnForOrganization(null));\n }\n}"}}},{"rowIdx":346231,"cells":{"answer":{"kind":"string","value":"package org.jfree.data.time.junit;\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.ObjectInput;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutput;\nimport java.io.ObjectOutputStream;\nimport junit.framework.Test;\nimport junit.framework.TestCase;\nimport junit.framework.TestSuite;\nimport org.jfree.data.general.SeriesChangeEvent;\nimport org.jfree.data.general.SeriesChangeListener;\nimport org.jfree.data.general.SeriesException;\nimport org.jfree.data.time.Day;\nimport org.jfree.data.time.FixedMillisecond;\nimport org.jfree.data.time.Month;\nimport org.jfree.data.time.MonthConstants;\nimport org.jfree.data.time.RegularTimePeriod;\nimport org.jfree.data.time.TimeSeries;\nimport org.jfree.data.time.TimeSeriesDataItem;\nimport org.jfree.data.time.Year;\n/**\n * A collection of test cases for the {@link TimeSeries} class.\n */\npublic class TimeSeriesTests extends TestCase implements SeriesChangeListener {\n /** A time series. */\n private TimeSeries seriesA;\n /** A time series. */\n private TimeSeries seriesB;\n /** A time series. */\n private TimeSeries seriesC;\n /** A flag that indicates whether or not a change event was fired. */\n private boolean gotSeriesChangeEvent = false;\n /**\n * Returns the tests as a test suite.\n *\n * @return The test suite.\n */\n public static Test suite() {\n return new TestSuite(TimeSeriesTests.class);\n }\n /**\n * Constructs a new set of tests.\n *\n * @param name the name of the tests.\n */\n public TimeSeriesTests(String name) {\n super(name);\n }\n /**\n * Common test setup.\n */\n protected void setUp() {\n this.seriesA = new TimeSeries(\"Series A\");\n try {\n this.seriesA.add(new Year(2000), new Integer(102000));\n this.seriesA.add(new Year(2001), new Integer(102001));\n this.seriesA.add(new Year(2002), new Integer(102002));\n this.seriesA.add(new Year(2003), new Integer(102003));\n this.seriesA.add(new Year(2004), new Integer(102004));\n this.seriesA.add(new Year(2005), new Integer(102005));\n }\n catch (SeriesException e) {\n System.err.println(\"Problem creating series.\");\n }\n this.seriesB = new TimeSeries(\"Series B\");\n try {\n this.seriesB.add(new Year(2006), new Integer(202006));\n this.seriesB.add(new Year(2007), new Integer(202007));\n this.seriesB.add(new Year(2008), new Integer(202008));\n }\n catch (SeriesException e) {\n System.err.println(\"Problem creating series.\");\n }\n this.seriesC = new TimeSeries(\"Series C\");\n try {\n this.seriesC.add(new Year(1999), new Integer(301999));\n this.seriesC.add(new Year(2000), new Integer(302000));\n this.seriesC.add(new Year(2002), new Integer(302002));\n }\n catch (SeriesException e) {\n System.err.println(\"Problem creating series.\");\n }\n }\n /**\n * Sets the flag to indicate that a {@link SeriesChangeEvent} has been\n * received.\n *\n * @param event the event.\n */\n public void seriesChanged(SeriesChangeEvent event) {\n this.gotSeriesChangeEvent = true;\n }\n /**\n * Check that cloning works.\n */\n public void testClone() {\n TimeSeries series = new TimeSeries(\"Test Series\");\n RegularTimePeriod jan1st2002 = new Day(1, MonthConstants.JANUARY, 2002);\n try {\n series.add(jan1st2002, new Integer(42));\n }\n catch (SeriesException e) {\n System.err.println(\"Problem adding to series.\");\n }\n TimeSeries clone = null;\n try {\n clone = (TimeSeries) series.clone();\n clone.setKey(\"Clone Series\");\n try {\n clone.update(jan1st2002, new Integer(10));\n }\n catch (SeriesException e) {\n e.printStackTrace();\n }\n }\n catch (CloneNotSupportedException e) {\n assertTrue(false);\n }\n int seriesValue = series.getValue(jan1st2002).intValue();\n int cloneValue = Integer.MAX_VALUE;\n if (clone != null) {\n cloneValue = clone.getValue(jan1st2002).intValue();\n }\n assertEquals(42, seriesValue);\n assertEquals(10, cloneValue);\n assertEquals(\"Test Series\", series.getKey());\n if (clone != null) {\n assertEquals(\"Clone Series\", clone.getKey());\n }\n else {\n assertTrue(false);\n }\n }\n /**\n * Another test of the clone() method.\n */\n public void testClone2() {\n TimeSeries s1 = new TimeSeries(\"S1\");\n s1.add(new Year(2007), 100.0);\n s1.add(new Year(2008), null);\n s1.add(new Year(2009), 200.0);\n TimeSeries s2 = null;\n try {\n s2 = (TimeSeries) s1.clone();\n }\n catch (CloneNotSupportedException e) {\n e.printStackTrace();\n }\n assertTrue(s1.equals(s2));\n // check independence\n s2.addOrUpdate(new Year(2009), 300.0);\n assertFalse(s1.equals(s2));\n s1.addOrUpdate(new Year(2009), 300.0);\n assertTrue(s1.equals(s2));\n }\n /**\n * Add a value to series A for 1999. It should be added at index 0.\n */\n public void testAddValue() {\n try {\n this.seriesA.add(new Year(1999), new Integer(1));\n }\n catch (SeriesException e) {\n System.err.println(\"Problem adding to series.\");\n }\n int value = this.seriesA.getValue(0).intValue();\n assertEquals(1, value);\n }\n /**\n * Tests the retrieval of values.\n */\n public void testGetValue() {\n Number value1 = this.seriesA.getValue(new Year(1999));\n assertNull(value1);\n int value2 = this.seriesA.getValue(new Year(2000)).intValue();\n assertEquals(102000, value2);\n }\n /**\n * Tests the deletion of values.\n */\n public void testDelete() {\n this.seriesA.delete(0, 0);\n assertEquals(5, this.seriesA.getItemCount());\n Number value = this.seriesA.getValue(new Year(2000));\n assertNull(value);\n }\n /**\n * Basic tests for the delete() method.\n */\n public void testDelete2() {\n TimeSeries s1 = new TimeSeries(\"Series\");\n s1.add(new Year(2000), 13.75);\n s1.add(new Year(2001), 11.90);\n s1.add(new Year(2002), null);\n s1.addChangeListener(this);\n this.gotSeriesChangeEvent = false;\n s1.delete(new Year(2001));\n assertTrue(this.gotSeriesChangeEvent);\n assertEquals(2, s1.getItemCount());\n assertEquals(null, s1.getValue(new Year(2001)));\n // try deleting a time period that doesn't exist...\n this.gotSeriesChangeEvent = false;\n s1.delete(new Year(2006));\n assertFalse(this.gotSeriesChangeEvent);\n // try deleting null\n try {\n s1.delete(null);\n fail(\"Expected IllegalArgumentException.\");\n }\n catch (IllegalArgumentException e) {\n // expected\n }\n }\n /**\n * Some checks for the delete(int, int) method.\n */\n public void testDelete3() {\n TimeSeries s1 = new TimeSeries(\"S1\");\n s1.add(new Year(2011), 1.1);\n s1.add(new Year(2012), 2.2);\n s1.add(new Year(2013), 3.3);\n s1.add(new Year(2014), 4.4);\n s1.add(new Year(2015), 5.5);\n s1.add(new Year(2016), 6.6);\n s1.delete(2, 5);\n assertEquals(2, s1.getItemCount());\n assertEquals(new Year(2011), s1.getTimePeriod(0));\n assertEquals(new Year(2012), s1.getTimePeriod(1));\n assertEquals(1.1, s1.getMinY(), EPSILON);\n assertEquals(2.2, s1.getMaxY(), EPSILON);\n }\n /**\n * Check that the item bounds are determined correctly when there is a\n * maximum item count and a new value is added.\n */\n public void testDelete_RegularTimePeriod() {\n TimeSeries s1 = new TimeSeries(\"S1\");\n s1.add(new Year(2010), 1.1);\n s1.add(new Year(2011), 2.2);\n s1.add(new Year(2012), 3.3);\n s1.add(new Year(2013), 4.4);\n s1.delete(new Year(2010));\n s1.delete(new Year(2013));\n assertEquals(2.2, s1.getMinY(), EPSILON);\n assertEquals(3.3, s1.getMaxY(), EPSILON);\n }\n /**\n * Serialize an instance, restore it, and check for equality.\n */\n public void testSerialization() {\n TimeSeries s1 = new TimeSeries(\"A test\");\n s1.add(new Year(2000), 13.75);\n s1.add(new Year(2001), 11.90);\n s1.add(new Year(2002), null);\n s1.add(new Year(2005), 19.32);\n s1.add(new Year(2007), 16.89);\n TimeSeries s2 = null;\n try {\n ByteArrayOutputStream buffer = new ByteArrayOutputStream();\n ObjectOutput out = new ObjectOutputStream(buffer);\n out.writeObject(s1);\n out.close();\n ObjectInput in = new ObjectInputStream(\n new ByteArrayInputStream(buffer.toByteArray())\n );\n s2 = (TimeSeries) in.readObject();\n in.close();\n }\n catch (Exception e) {\n System.out.println(e.toString());\n }\n assertTrue(s1.equals(s2));\n }\n /**\n * Tests the equals method.\n */\n public void testEquals() {\n TimeSeries s1 = new TimeSeries(\"Time Series 1\");\n TimeSeries s2 = new TimeSeries(\"Time Series 2\");\n boolean b1 = s1.equals(s2);\n assertFalse(\"b1\", b1);\n s2.setKey(\"Time Series 1\");\n boolean b2 = s1.equals(s2);\n assertTrue(\"b2\", b2);\n RegularTimePeriod p1 = new Day();\n RegularTimePeriod p2 = p1.next();\n s1.add(p1, 100.0);\n s1.add(p2, 200.0);\n boolean b3 = s1.equals(s2);\n assertFalse(\"b3\", b3);\n s2.add(p1, 100.0);\n s2.add(p2, 200.0);\n boolean b4 = s1.equals(s2);\n assertTrue(\"b4\", b4);\n s1.setMaximumItemCount(100);\n boolean b5 = s1.equals(s2);\n assertFalse(\"b5\", b5);\n s2.setMaximumItemCount(100);\n boolean b6 = s1.equals(s2);\n assertTrue(\"b6\", b6);\n s1.setMaximumItemAge(100);\n boolean b7 = s1.equals(s2);\n assertFalse(\"b7\", b7);\n s2.setMaximumItemAge(100);\n boolean b8 = s1.equals(s2);\n assertTrue(\"b8\", b8);\n }\n /**\n * Tests a specific bug report where null arguments in the constructor\n * cause the equals() method to fail. Fixed for 0.9.21.\n */\n public void testEquals2() {\n TimeSeries s1 = new TimeSeries(\"Series\", null, null);\n TimeSeries s2 = new TimeSeries(\"Series\", null, null);\n assertTrue(s1.equals(s2));\n }\n /**\n * Some tests to ensure that the createCopy(RegularTimePeriod,\n * RegularTimePeriod) method is functioning correctly.\n */\n public void testCreateCopy1() {\n TimeSeries series = new TimeSeries(\"Series\");\n series.add(new Month(MonthConstants.JANUARY, 2003), 45.0);\n series.add(new Month(MonthConstants.FEBRUARY, 2003), 55.0);\n series.add(new Month(MonthConstants.JUNE, 2003), 35.0);\n series.add(new Month(MonthConstants.NOVEMBER, 2003), 85.0);\n series.add(new Month(MonthConstants.DECEMBER, 2003), 75.0);\n try {\n // copy a range before the start of the series data...\n TimeSeries result1 = series.createCopy(\n new Month(MonthConstants.NOVEMBER, 2002),\n new Month(MonthConstants.DECEMBER, 2002));\n assertEquals(0, result1.getItemCount());\n // copy a range that includes only the first item in the series...\n TimeSeries result2 = series.createCopy(\n new Month(MonthConstants.NOVEMBER, 2002),\n new Month(MonthConstants.JANUARY, 2003));\n assertEquals(1, result2.getItemCount());\n // copy a range that begins before and ends in the middle of the\n // series...\n TimeSeries result3 = series.createCopy(\n new Month(MonthConstants.NOVEMBER, 2002),\n new Month(MonthConstants.APRIL, 2003));\n assertEquals(2, result3.getItemCount());\n TimeSeries result4 = series.createCopy(\n new Month(MonthConstants.NOVEMBER, 2002),\n new Month(MonthConstants.DECEMBER, 2003));\n assertEquals(5, result4.getItemCount());\n TimeSeries result5 = series.createCopy(\n new Month(MonthConstants.NOVEMBER, 2002),\n new Month(MonthConstants.MARCH, 2004));\n assertEquals(5, result5.getItemCount());\n TimeSeries result6 = series.createCopy(\n new Month(MonthConstants.JANUARY, 2003),\n new Month(MonthConstants.JANUARY, 2003));\n assertEquals(1, result6.getItemCount());\n TimeSeries result7 = series.createCopy(\n new Month(MonthConstants.JANUARY, 2003),\n new Month(MonthConstants.APRIL, 2003));\n assertEquals(2, result7.getItemCount());\n TimeSeries result8 = series.createCopy(\n new Month(MonthConstants.JANUARY, 2003),\n new Month(MonthConstants.DECEMBER, 2003));\n assertEquals(5, result8.getItemCount());\n TimeSeries result9 = series.createCopy(\n new Month(MonthConstants.JANUARY, 2003),\n new Month(MonthConstants.MARCH, 2004));\n assertEquals(5, result9.getItemCount());\n TimeSeries result10 = series.createCopy(\n new Month(MonthConstants.MAY, 2003),\n new Month(MonthConstants.DECEMBER, 2003));\n assertEquals(3, result10.getItemCount());\n TimeSeries result11 = series.createCopy(\n new Month(MonthConstants.MAY, 2003),\n new Month(MonthConstants.MARCH, 2004));\n assertEquals(3, result11.getItemCount());\n TimeSeries result12 = series.createCopy(\n new Month(MonthConstants.DECEMBER, 2003),\n new Month(MonthConstants.DECEMBER, 2003));\n assertEquals(1, result12.getItemCount());\n TimeSeries result13 = series.createCopy(\n new Month(MonthConstants.DECEMBER, 2003),\n new Month(MonthConstants.MARCH, 2004));\n assertEquals(1, result13.getItemCount());\n TimeSeries result14 = series.createCopy(\n new Month(MonthConstants.JANUARY, 2004),\n new Month(MonthConstants.MARCH, 2004));\n assertEquals(0, result14.getItemCount());\n }\n catch (CloneNotSupportedException e) {\n assertTrue(false);\n }\n }\n /**\n * Some tests to ensure that the createCopy(int, int) method is\n * functioning correctly.\n */\n public void testCreateCopy2() {\n TimeSeries series = new TimeSeries(\"Series\");\n series.add(new Month(MonthConstants.JANUARY, 2003), 45.0);\n series.add(new Month(MonthConstants.FEBRUARY, 2003), 55.0);\n series.add(new Month(MonthConstants.JUNE, 2003), 35.0);\n series.add(new Month(MonthConstants.NOVEMBER, 2003), 85.0);\n series.add(new Month(MonthConstants.DECEMBER, 2003), 75.0);\n try {\n // copy just the first item...\n TimeSeries result1 = series.createCopy(0, 0);\n assertEquals(new Month(1, 2003), result1.getTimePeriod(0));\n // copy the first two items...\n result1 = series.createCopy(0, 1);\n assertEquals(new Month(2, 2003), result1.getTimePeriod(1));\n // copy the middle three items...\n result1 = series.createCopy(1, 3);\n assertEquals(new Month(2, 2003), result1.getTimePeriod(0));\n assertEquals(new Month(11, 2003), result1.getTimePeriod(2));\n // copy the last two items...\n result1 = series.createCopy(3, 4);\n assertEquals(new Month(11, 2003), result1.getTimePeriod(0));\n assertEquals(new Month(12, 2003), result1.getTimePeriod(1));\n // copy the last item...\n result1 = series.createCopy(4, 4);\n assertEquals(new Month(12, 2003), result1.getTimePeriod(0));\n }\n catch (CloneNotSupportedException e) {\n assertTrue(false);\n }\n // check negative first argument\n boolean pass = false;\n try {\n /* TimeSeries result = */ series.createCopy(-1, 1);\n }\n catch (IllegalArgumentException e) {\n pass = true;\n }\n catch (CloneNotSupportedException e) {\n pass = false;\n }\n assertTrue(pass);\n // check second argument less than first argument\n pass = false;\n try {\n /* TimeSeries result = */ series.createCopy(1, 0);\n }\n catch (IllegalArgumentException e) {\n pass = true;\n }\n catch (CloneNotSupportedException e) {\n pass = false;\n }\n assertTrue(pass);\n TimeSeries series2 = new TimeSeries(\"Series 2\");\n try {\n TimeSeries series3 = series2.createCopy(99, 999);\n assertEquals(0, series3.getItemCount());\n }\n catch (CloneNotSupportedException e) {\n assertTrue(false);\n }\n }\n /**\n * Test the setMaximumItemCount() method to ensure that it removes items\n * from the series if necessary.\n */\n public void testSetMaximumItemCount() {\n TimeSeries s1 = new TimeSeries(\"S1\");\n s1.add(new Year(2000), 13.75);\n s1.add(new Year(2001), 11.90);\n s1.add(new Year(2002), null);\n s1.add(new Year(2005), 19.32);\n s1.add(new Year(2007), 16.89);\n assertTrue(s1.getItemCount() == 5);\n s1.setMaximumItemCount(3);\n assertTrue(s1.getItemCount() == 3);\n TimeSeriesDataItem item = s1.getDataItem(0);\n assertTrue(item.getPeriod().equals(new Year(2002)));\n assertEquals(16.89, s1.getMinY(), EPSILON);\n assertEquals(19.32, s1.getMaxY(), EPSILON);\n }\n /**\n * Some checks for the addOrUpdate() method.\n */\n public void testAddOrUpdate() {\n TimeSeries s1 = new TimeSeries(\"S1\");\n s1.setMaximumItemCount(2);\n s1.addOrUpdate(new Year(2000), 100.0);\n assertEquals(1, s1.getItemCount());\n s1.addOrUpdate(new Year(2001), 101.0);\n assertEquals(2, s1.getItemCount());\n s1.addOrUpdate(new Year(2001), 102.0);\n assertEquals(2, s1.getItemCount());\n s1.addOrUpdate(new Year(2002), 103.0);\n assertEquals(2, s1.getItemCount());\n }\n /**\n * Test the add branch of the addOrUpdate() method.\n */\n public void testAddOrUpdate2() {\n TimeSeries s1 = new TimeSeries(\"S1\");\n s1.setMaximumItemCount(2);\n s1.addOrUpdate(new Year(2010), 1.1);\n s1.addOrUpdate(new Year(2011), 2.2);\n s1.addOrUpdate(new Year(2012), 3.3);\n assertEquals(2, s1.getItemCount());\n assertEquals(2.2, s1.getMinY(), EPSILON);\n assertEquals(3.3, s1.getMaxY(), EPSILON);\n }\n /**\n * Test that the addOrUpdate() method won't allow multiple time period\n * classes.\n */\n public void testAddOrUpdate3() {\n TimeSeries s1 = new TimeSeries(\"S1\");\n s1.addOrUpdate(new Year(2010), 1.1);\n assertEquals(Year.class, s1.getTimePeriodClass());\n boolean pass = false;\n try {\n s1.addOrUpdate(new Month(1, 2009), 0.0);\n }\n catch (SeriesException e) {\n pass = true;\n }\n assertTrue(pass);\n }\n /**\n * Some more checks for the addOrUpdate() method.\n */\n public void testAddOrUpdate4() {\n TimeSeries ts = new TimeSeries(\"S\");\n TimeSeriesDataItem overwritten = ts.addOrUpdate(new Year(2009), 20.09);\n assertNull(overwritten);\n overwritten = ts.addOrUpdate(new Year(2009), 1.0);\n assertEquals(new Double(20.09), overwritten.getValue());\n assertEquals(new Double(1.0), ts.getValue(new Year(2009)));\n // changing the overwritten record shouldn't affect the series\n overwritten.setValue(null);\n assertEquals(new Double(1.0), ts.getValue(new Year(2009)));\n TimeSeriesDataItem item = new TimeSeriesDataItem(new Year(2010), 20.10);\n overwritten = ts.addOrUpdate(item);\n assertNull(overwritten);\n assertEquals(new Double(20.10), ts.getValue(new Year(2010)));\n // changing the item that was added should not change the series\n item.setValue(null);\n assertEquals(new Double(20.10), ts.getValue(new Year(2010)));\n }\n /**\n * A test for the bug report 1075255.\n */\n public void testBug1075255() {\n TimeSeries ts = new TimeSeries(\"dummy\");\n ts.add(new FixedMillisecond(0L), 0.0);\n TimeSeries ts2 = new TimeSeries(\"dummy2\");\n ts2.add(new FixedMillisecond(0L), 1.0);\n try {\n ts.addAndOrUpdate(ts2);\n }\n catch (Exception e) {\n e.printStackTrace();\n assertTrue(false);\n }\n assertEquals(1, ts.getItemCount());\n }\n /**\n * A test for bug 1832432.\n */\n public void testBug1832432() {\n TimeSeries s1 = new TimeSeries(\"Series\");\n TimeSeries s2 = null;\n try {\n s2 = (TimeSeries) s1.clone();\n }\n catch (CloneNotSupportedException e) {\n e.printStackTrace();\n }\n assertTrue(s1 != s2);\n assertTrue(s1.getClass() == s2.getClass());\n assertTrue(s1.equals(s2));\n // test independence\n s1.add(new Day(1, 1, 2007), 100.0);\n assertFalse(s1.equals(s2));\n }\n /**\n * Some checks for the getIndex() method.\n */\n public void testGetIndex() {\n TimeSeries series = new TimeSeries(\"Series\");\n assertEquals(-1, series.getIndex(new Month(1, 2003)));\n series.add(new Month(1, 2003), 45.0);\n assertEquals(0, series.getIndex(new Month(1, 2003)));\n assertEquals(-1, series.getIndex(new Month(12, 2002)));\n assertEquals(-2, series.getIndex(new Month(2, 2003)));\n series.add(new Month(3, 2003), 55.0);\n assertEquals(-1, series.getIndex(new Month(12, 2002)));\n assertEquals(0, series.getIndex(new Month(1, 2003)));\n assertEquals(-2, series.getIndex(new Month(2, 2003)));\n assertEquals(1, series.getIndex(new Month(3, 2003)));\n assertEquals(-3, series.getIndex(new Month(4, 2003)));\n }\n /**\n * Some checks for the getDataItem(int) method.\n */\n public void testGetDataItem1() {\n TimeSeries series = new TimeSeries(\"S\");\n // can't get anything yet...just an exception\n boolean pass = false;\n try {\n /*TimeSeriesDataItem item =*/ series.getDataItem(0);\n }\n catch (IndexOutOfBoundsException e) {\n pass = true;\n }\n assertTrue(pass);\n series.add(new Year(2006), 100.0);\n TimeSeriesDataItem item = series.getDataItem(0);\n assertEquals(new Year(2006), item.getPeriod());\n pass = false;\n try {\n /*item = */series.getDataItem(-1);\n }\n catch (IndexOutOfBoundsException e) {\n pass = true;\n }\n assertTrue(pass);\n pass = false;\n try {\n /*item = */series.getDataItem(1);\n }\n catch (IndexOutOfBoundsException e) {\n pass = true;\n }\n assertTrue(pass);\n }\n /**\n * Some checks for the getDataItem(RegularTimePeriod) method.\n */\n public void testGetDataItem2() {\n TimeSeries series = new TimeSeries(\"S\");\n assertNull(series.getDataItem(new Year(2006)));\n // try a null argument\n boolean pass = false;\n try {\n /* TimeSeriesDataItem item = */ series.getDataItem(null);\n }\n catch (IllegalArgumentException e) {\n pass = true;\n }\n assertTrue(pass);\n }\n /**\n * Some checks for the removeAgedItems() method.\n */\n public void testRemoveAgedItems() {\n TimeSeries series = new TimeSeries(\"Test Series\");\n series.addChangeListener(this);\n assertEquals(Long.MAX_VALUE, series.getMaximumItemAge());\n assertEquals(Integer.MAX_VALUE, series.getMaximumItemCount());\n this.gotSeriesChangeEvent = false;\n // test empty series\n series.removeAgedItems(true);\n assertEquals(0, series.getItemCount());\n assertFalse(this.gotSeriesChangeEvent);\n // test series with one item\n series.add(new Year(1999), 1.0);\n series.setMaximumItemAge(0);\n this.gotSeriesChangeEvent = false;\n series.removeAgedItems(true);\n assertEquals(1, series.getItemCount());\n assertFalse(this.gotSeriesChangeEvent);\n // test series with two items\n series.setMaximumItemAge(10);\n series.add(new Year(2001), 2.0);\n this.gotSeriesChangeEvent = false;\n series.setMaximumItemAge(2);\n assertEquals(2, series.getItemCount());\n assertEquals(0, series.getIndex(new Year(1999)));\n assertFalse(this.gotSeriesChangeEvent);\n series.setMaximumItemAge(1);\n assertEquals(1, series.getItemCount());\n assertEquals(0, series.getIndex(new Year(2001)));\n assertTrue(this.gotSeriesChangeEvent);\n }\n /**\n * Some checks for the removeAgedItems(long, boolean) method.\n */\n public void testRemoveAgedItems2() {\n long y2006 = 1157087372534L; // milliseconds somewhere in 2006\n TimeSeries series = new TimeSeries(\"Test Series\");\n series.addChangeListener(this);\n assertEquals(Long.MAX_VALUE, series.getMaximumItemAge());\n assertEquals(Integer.MAX_VALUE, series.getMaximumItemCount());\n this.gotSeriesChangeEvent = false;\n // test empty series\n series.removeAgedItems(y2006, true);\n assertEquals(0, series.getItemCount());\n assertFalse(this.gotSeriesChangeEvent);\n // test a series with 1 item\n series.add(new Year(2004), 1.0);\n series.setMaximumItemAge(1);\n this.gotSeriesChangeEvent = false;\n series.removeAgedItems(new Year(2005).getMiddleMillisecond(), true);\n assertEquals(1, series.getItemCount());\n assertFalse(this.gotSeriesChangeEvent);\n series.removeAgedItems(y2006, true);\n assertEquals(0, series.getItemCount());\n assertTrue(this.gotSeriesChangeEvent);\n // test a series with two items\n series.setMaximumItemAge(2);\n series.add(new Year(2003), 1.0);\n series.add(new Year(2005), 2.0);\n assertEquals(2, series.getItemCount());\n this.gotSeriesChangeEvent = false;\n assertEquals(2, series.getItemCount());\n series.removeAgedItems(new Year(2005).getMiddleMillisecond(), true);\n assertEquals(2, series.getItemCount());\n assertFalse(this.gotSeriesChangeEvent);\n series.removeAgedItems(y2006, true);\n assertEquals(1, series.getItemCount());\n assertTrue(this.gotSeriesChangeEvent);\n }\n /**\n * Calling removeAgedItems() on an empty series should not throw any\n * exception.\n */\n public void testRemoveAgedItems3() {\n TimeSeries s = new TimeSeries(\"Test\");\n boolean pass = true;\n try {\n s.removeAgedItems(0L, true);\n }\n catch (Exception e) {\n pass = false;\n }\n assertTrue(pass);\n }\n /**\n * Check that the item bounds are determined correctly when there is a\n * maximum item count.\n */\n public void testRemoveAgedItems4() {\n TimeSeries s1 = new TimeSeries(\"S1\");\n s1.setMaximumItemAge(2);\n s1.add(new Year(2010), 1.1);\n s1.add(new Year(2011), 2.2);\n s1.add(new Year(2012), 3.3);\n s1.add(new Year(2013), 2.5);\n assertEquals(3, s1.getItemCount());\n assertEquals(2.2, s1.getMinY(), EPSILON);\n assertEquals(3.3, s1.getMaxY(), EPSILON);\n }\n /**\n * Check that the item bounds are determined correctly after a call to\n * removeAgedItems().\n */\n public void testRemoveAgedItems5() {\n TimeSeries s1 = new TimeSeries(\"S1\");\n s1.setMaximumItemAge(4);\n s1.add(new Year(2010), 1.1);\n s1.add(new Year(2011), 2.2);\n s1.add(new Year(2012), 3.3);\n s1.add(new Year(2013), 2.5);\n s1.removeAgedItems(new Year(2015).getMiddleMillisecond(), true);\n assertEquals(3, s1.getItemCount());\n assertEquals(2.2, s1.getMinY(), EPSILON);\n assertEquals(3.3, s1.getMaxY(), EPSILON);\n }\n /**\n * Some simple checks for the hashCode() method.\n */\n public void testHashCode() {\n TimeSeries s1 = new TimeSeries(\"Test\");\n TimeSeries s2 = new TimeSeries(\"Test\");\n assertEquals(s1, s2);\n assertEquals(s1.hashCode(), s2.hashCode());\n s1.add(new Day(1, 1, 2007), 500.0);\n s2.add(new Day(1, 1, 2007), 500.0);\n assertEquals(s1, s2);\n assertEquals(s1.hashCode(), s2.hashCode());\n s1.add(new Day(2, 1, 2007), null);\n s2.add(new Day(2, 1, 2007), null);\n assertEquals(s1, s2);\n assertEquals(s1.hashCode(), s2.hashCode());\n s1.add(new Day(5, 1, 2007), 111.0);\n s2.add(new Day(5, 1, 2007), 111.0);\n assertEquals(s1, s2);\n assertEquals(s1.hashCode(), s2.hashCode());\n s1.add(new Day(9, 1, 2007), 1.0);\n s2.add(new Day(9, 1, 2007), 1.0);\n assertEquals(s1, s2);\n assertEquals(s1.hashCode(), s2.hashCode());\n }\n /**\n * Test for bug report 1864222.\n */\n public void testBug1864222() {\n TimeSeries s = new TimeSeries(\"S\");\n s.add(new Day(19, 8, 2005), 1);\n s.add(new Day(31, 1, 2006), 1);\n boolean pass = true;\n try {\n s.createCopy(new Day(1, 12, 2005), new Day(18, 1, 2006));\n }\n catch (CloneNotSupportedException e) {\n pass = false;\n }\n assertTrue(pass);\n }\n private static final double EPSILON = 0.0000000001;\n /**\n * Some checks for the getMinY() method.\n */\n public void testGetMinY() {\n TimeSeries s1 = new TimeSeries(\"S1\");\n assertTrue(Double.isNaN(s1.getMinY()));\n s1.add(new Year(2008), 1.1);\n assertEquals(1.1, s1.getMinY(), EPSILON);\n s1.add(new Year(2009), 2.2);\n assertEquals(1.1, s1.getMinY(), EPSILON);\n s1.add(new Year(2000), 99.9);\n assertEquals(1.1, s1.getMinY(), EPSILON);\n s1.add(new Year(2002), -1.1);\n assertEquals(-1.1, s1.getMinY(), EPSILON);\n s1.add(new Year(2003), null);\n assertEquals(-1.1, s1.getMinY(), EPSILON);\n s1.addOrUpdate(new Year(2002), null);\n assertEquals(1.1, s1.getMinY(), EPSILON);\n }\n /**\n * Some checks for the getMaxY() method.\n */\n public void testGetMaxY() {\n TimeSeries s1 = new TimeSeries(\"S1\");\n assertTrue(Double.isNaN(s1.getMaxY()));\n s1.add(new Year(2008), 1.1);\n assertEquals(1.1, s1.getMaxY(), EPSILON);\n s1.add(new Year(2009), 2.2);\n assertEquals(2.2, s1.getMaxY(), EPSILON);\n s1.add(new Year(2000), 99.9);\n assertEquals(99.9, s1.getMaxY(), EPSILON);\n s1.add(new Year(2002), -1.1);\n assertEquals(99.9, s1.getMaxY(), EPSILON);\n s1.add(new Year(2003), null);\n assertEquals(99.9, s1.getMaxY(), EPSILON);\n s1.addOrUpdate(new Year(2000), null);\n assertEquals(2.2, s1.getMaxY(), EPSILON);\n }\n /**\n * A test for the clear method.\n */\n public void testClear() {\n TimeSeries s1 = new TimeSeries(\"S1\");\n s1.add(new Year(2009), 1.1);\n s1.add(new Year(2010), 2.2);\n assertEquals(2, s1.getItemCount());\n s1.clear();\n assertEquals(0, s1.getItemCount());\n assertTrue(Double.isNaN(s1.getMinY()));\n assertTrue(Double.isNaN(s1.getMaxY()));\n }\n /**\n * Check that the item bounds are determined correctly when there is a\n * maximum item count and a new value is added.\n */\n public void testAdd() {\n TimeSeries s1 = new TimeSeries(\"S1\");\n s1.setMaximumItemCount(2);\n s1.add(new Year(2010), 1.1);\n s1.add(new Year(2011), 2.2);\n s1.add(new Year(2012), 3.3);\n assertEquals(2, s1.getItemCount());\n assertEquals(2.2, s1.getMinY(), EPSILON);\n assertEquals(3.3, s1.getMaxY(), EPSILON);\n }\n /**\n * Some checks for the update(RegularTimePeriod...method).\n */\n public void testUpdate_RegularTimePeriod() {\n TimeSeries s1 = new TimeSeries(\"S1\");\n s1.add(new Year(2010), 1.1);\n s1.add(new Year(2011), 2.2);\n s1.add(new Year(2012), 3.3);\n s1.update(new Year(2012), 4.4);\n assertEquals(4.4, s1.getMaxY(), EPSILON);\n s1.update(new Year(2010), 0.5);\n assertEquals(0.5, s1.getMinY(), EPSILON);\n s1.update(new Year(2012), null);\n assertEquals(2.2, s1.getMaxY(), EPSILON);\n s1.update(new Year(2010), null);\n assertEquals(2.2, s1.getMinY(), EPSILON);\n }\n /**\n * Create a TimeSeriesDataItem, add it to a TimeSeries. Now, modifying\n * the original TimeSeriesDataItem should NOT affect the TimeSeries.\n */\n public void testAdd_TimeSeriesDataItem() {\n TimeSeriesDataItem item = new TimeSeriesDataItem(new Year(2009), 1.0);\n TimeSeries series = new TimeSeries(\"S1\");\n series.add(item);\n assertTrue(item.equals(series.getDataItem(0)));\n item.setValue(new Double(99.9));\n assertFalse(item.equals(series.getDataItem(0)));\n }\n}"}}},{"rowIdx":346232,"cells":{"answer":{"kind":"string","value":"package com.ea.orbit.web.diagnostics;\nimport com.ea.orbit.container.Container;\nimport javax.inject.Inject;\nimport javax.ws.rs.GET;\nimport javax.ws.rs.Path;\nimport javax.ws.rs.Produces;\nimport javax.ws.rs.core.MediaType;\nimport java.util.Date;\n@Path(\"/orbit/diagnostics\")\npublic class DiagnosticsHandler\n{\n @Inject\n Container orbitContainer;\n public static class HealthcheckResult\n {\n private Boolean alive = true;\n private Date serverTime = new Date();\n public Boolean getAlive()\n {\n return alive;\n }\n public void setAlive(Boolean alive)\n {\n this.alive = alive;\n }\n public Date getServerTime()\n {\n return serverTime;\n }\n public void setServerTime(Date serverTime)\n {\n this.serverTime = serverTime;\n }\n }\n @GET\n @Path(\"/healthcheck\")\n @Produces(MediaType.APPLICATION_JSON)\n public HealthcheckResult getHealthCheck()\n {\n final HealthcheckResult healthcheckResult = new HealthcheckResult();\n healthcheckResult.setAlive(orbitContainer.getContainerState() == Container.ContainerState.STARTED);\n return healthcheckResult;\n }\n}"}}},{"rowIdx":346233,"cells":{"answer":{"kind":"string","value":"package com.netcracker.controllers;\nimport com.netcracker.dto.AttachmentDtoInfo;\nimport com.netcracker.entities.Attachment;\nimport com.netcracker.entities.User;\nimport com.netcracker.services.Converter;\nimport com.netcracker.services.impl.AttachmentServiceImpl;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.core.context.SecurityContextHolder;\nimport org.springframework.web.bind.annotation.*;\nimport org.springframework.web.context.ContextLoader;\nimport org.springframework.web.multipart.MultipartFile;\nimport javax.servlet.http.HttpServletRequest;\nimport java.io.BufferedOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.util.List;\nimport java.util.stream.Collectors;\n/**\n * The controller, whose methods provide ways of interacting with\n * an authorized user comments. It is worth noting that in\n * this controller is not the method getComment (), as the comments\n * received getFullLabelInfo perform () method of the class\n * {@link com.netcracker.controllers.LabelController}.\n *\n * This controller is responsible for:\n * UC17 - Adding attachments; +\n * UC18 - Deleting attachments; +\n *\n * @author Oveian Egor\n * @author Kozhuchar Alexander\n */\n@RestController\n@RequestMapping(\"/labels/{labelId}/attachments\")\npublic class AttachmentController {\n @Autowired\n private AttachmentServiceImpl attachmentService;\n @Autowired\n private Converter converter;\n /**\n * Method of attachments extraction, depending on which label id came from client.\n *\n * Described in:\n * FR14 - The system should provide the ability to view attachments;\n * FR15 - The system should provide display of attachments in accordance\n * with the order they are added to the label\n *\n * @param labelId\n * @return list of {@link AttachmentDtoInfo} - objects, that contain information about existing attachments.\n */\n @GetMapping\n public List getAttachmentsByLabel(@PathVariable(name = \"labelId\") Long labelId) {\n return attachmentService.getAttachmentsByLabel(labelId)\n .stream().map(a -> converter.convertAttachmentToDtoInfo(a))\n .collect(Collectors.toList());\n }\n /**\n * Method of adding attachment to current label\n *\n * Described in:\n * FR57 - The system should provide the authorized user the ability to attach files to their label.\n * FR59 - The system should provide adding file attachments from the user file system.\n *\n * @param attach - object that contains bytes of attachment.\n * @return {@link AttachmentDtoInfo} - object, that contains information about created attachment.\n */\n @PostMapping(\"/add\")\n public AttachmentDtoInfo addAttachment(@PathVariable(name = \"labelId\") Long labelId, @RequestParam(\"attach\")MultipartFile attach) throws IOException {\n User user = (User) SecurityContextHolder.getContext().getAuthentication()\n .getPrincipal();\n String uploadRootPath = \"/var/www/resources/upload/\"+labelId;\n File uploadRootDir = new File(uploadRootPath);\n if (!uploadRootDir.exists()) {\n uploadRootDir.mkdirs();\n }\n File serverFile = new File(uploadRootDir.getAbsolutePath() + File.separator + attach.getOriginalFilename());\n attach.transferTo(serverFile);\n Attachment dbRecord = attachmentService.addAttachment(labelId,user.getUserId(),attach.getOriginalFilename());\n return converter.convertAttachmentToDtoInfo(dbRecord);\n }\n /**\n * Method of attachment extraction by its id\n *\n * Described in:\n * nowhere\n *\n * @param labelId\n * @param attachmentId\n * @return {@link AttachmentDtoInfo} - object, that contains information about existing attachment.\n */\n @GetMapping(\"/{attachmentId}\")\n public AttachmentDtoInfo getAttachment(@PathVariable(name = \"labelId\") Long labelId,\n @PathVariable(name = \"attachmentId\") Long attachmentId) {\n return null;\n }\n /**\n * Method of deleting attachment from specified label.\n *\n * Described in:\n * FR61 - The system should provide the authorized user to remove attached file from their label.\n *\n * @param attachmentId\n * @return status of deleting attachment from database\n */\n @DeleteMapping(\"/{attachmentId}\")\n public Integer deleteAttachment(@PathVariable(name = \"labelId\") Long labelId,\n @PathVariable(name = \"attachmentId\") Long attachmentId) {\n return 0;\n }\n}"}}},{"rowIdx":346234,"cells":{"answer":{"kind":"string","value":"package org.wikipedia.analytics;\nimport android.net.Uri;\nimport android.util.Log;\nimport com.github.kevinsawicki.http.HttpRequest;\nimport org.json.JSONException;\nimport org.json.JSONObject;\nimport org.wikipedia.WikipediaApp;\nimport org.wikipedia.concurrency.SaneAsyncTask;\n/**\n * Base class for all various types of events that are logged to EventLogging.\n *\n * Each Schema has its own class, and has its own constructor that makes it easy\n * to call from everywhere without having to duplicate param info at all places.\n * Updating schemas / revisions is also easier this way.\n */\npublic class EventLoggingEvent {\n private static final String EVENTLOG_URL = \"https://bits.wikimedia.org/event.gif\";\n /* Use for testing: */\n private final JSONObject data;\n private final String userAgent;\n /**\n * Create an EventLoggingEvent that logs to a given revision of a given schema with\n * the gven data payload.\n *\n * @param schema Schema name (as specified on meta.wikimedia.org)\n * @param revID Revision of the schema to log to\n * @param wiki DBName (enwiki, dewiki, etc) of the wiki in which we are operating\n * @param userAgent User-Agent string to use for this request\n * @param eventData Data for the actual event payload. Considered to be\n *\n */\n public EventLoggingEvent(String schema, int revID, String wiki, String userAgent, JSONObject eventData) {\n data = new JSONObject();\n try {\n data.put(\"schema\", schema);\n data.put(\"revision\", revID);\n data.put(\"wiki\", wiki);\n data.put(\"event\", eventData);\n } catch (JSONException e) {\n throw new RuntimeException(e);\n }\n this.userAgent = userAgent;\n }\n /**\n * Log the current event.\n *\n * Returns immediately after queueing the network request in the background.\n */\n public void log() {\n new LogEventTask(data).execute();\n }\n private class LogEventTask extends SaneAsyncTask {\n private final JSONObject data;\n public LogEventTask(JSONObject data) {\n super(SINGLE_THREAD);\n this.data = data;\n }\n @Override\n public Integer performTask() throws Throwable {\n String elUrl = WikipediaApp.getInstance().getSslFailCount() < 2 ? EVENTLOG_URL : EVENTLOG_URL.replace(\"https\", \"http\");\n String dataURL = Uri.parse(elUrl)\n .buildUpon().query(data.toString())\n .build().toString();\n return HttpRequest.get(dataURL).header(\"User-Agent\", userAgent).code();\n }\n @Override\n public void onCatch(Throwable caught) {\n // Do nothing bad. EL data is ok to lose.\n Log.d(Funnel.ANALYTICS_TAG, \"Lost EL data: \" + data.toString());\n }\n }\n}"}}},{"rowIdx":346235,"cells":{"answer":{"kind":"string","value":"package com.intellij.updater;\nimport com.intellij.openapi.application.ex.PathManagerEx;\nimport com.intellij.testFramework.rules.TempDirectory;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport java.io.File;\npublic abstract class UpdaterTestCase {\n protected static class TestUpdaterUI extends ConsoleUpdaterUI {\n public boolean cancelled = false;\n @Override public void setDescription(String oldBuildDesc, String newBuildDesc) { }\n @Override public void startProcess(String title) { }\n @Override public void checkCancelled() throws OperationCancelledException { if (cancelled) throw new OperationCancelledException(); }\n @Override public void showError(String message) { }\n }\n @Rule public TempDirectory tempDir = new TempDirectory();\n protected File dataDir;\n protected TestUpdaterUI TEST_UI;\n protected CheckSums CHECKSUMS;\n @Before\n public void setUp() throws Exception {\n dataDir = PathManagerEx.findFileUnderCommunityHome(\"updater/testData\");\n Runner.checkCaseSensitivity(dataDir.getPath());\n Runner.initTestLogger();\n TEST_UI = new TestUpdaterUI();\n CHECKSUMS = new CheckSums(\n new File(dataDir, \"Readme.txt\").length() == 7132,\n File.separatorChar == '\\\\');\n }\n @After\n public void tearDown() throws Exception {\n Utils.cleanup();\n }\n public File getTempFile(String fileName) {\n return new File(tempDir.getRoot(), fileName);\n }\n @SuppressWarnings(\"FieldMayBeStatic\")\n protected static class CheckSums {\n public final long README_TXT;\n public final long IDEA_BAT;\n public final long ANNOTATIONS_JAR = 2119442657L;\n public final long ANNOTATIONS_JAR_BIN = 2525796836L;\n public final long ANNOTATIONS_CHANGED_JAR = 4088078858L;\n public final long ANNOTATIONS_CHANGED_JAR_BIN = 2587736223L;\n public final long BOOT_JAR = 3018038682L;\n public final long BOOT_WITH_DIRECTORY_BECOMES_FILE_JAR = 1972168924;\n public final long BOOT2_JAR = 2406818996L;\n public final long BOOT2_CHANGED_WITH_UNCHANGED_CONTENT_JAR = 2406818996L;\n public final long BOOTSTRAP_JAR = 2082851308L;\n public final long BOOTSTRAP_JAR_BIN = 2745721972L;\n public final long BOOTSTRAP_DELETED_JAR = 544883981L;\n public final long LINK_TO_README_TXT = 2305843011042707672L;\n public final long LINK_TO_DOT_README_TXT;\n public CheckSums(boolean crLfs, boolean backwardSlashes) {\n README_TXT = crLfs ? 1272723667L : 7256327L;\n IDEA_BAT = crLfs ? 3088608749L : 1493936069L;\n LINK_TO_DOT_README_TXT = backwardSlashes ? 2305843011210142148L : 2305843009503057206L;\n }\n }\n}"}}},{"rowIdx":346236,"cells":{"answer":{"kind":"string","value":"package org.jfree.chart;\nimport java.awt.AWTEvent;\nimport java.awt.AlphaComposite;\nimport java.awt.Color;\nimport java.awt.Composite;\nimport java.awt.Cursor;\nimport java.awt.Dimension;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.GraphicsConfiguration;\nimport java.awt.Image;\nimport java.awt.Insets;\nimport java.awt.Paint;\nimport java.awt.Point;\nimport java.awt.Rectangle;\nimport java.awt.Toolkit;\nimport java.awt.Transparency;\nimport java.awt.datatransfer.Clipboard;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.InputEvent;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.MouseListener;\nimport java.awt.event.MouseMotionListener;\nimport java.awt.geom.AffineTransform;\nimport java.awt.geom.Line2D;\nimport java.awt.geom.Point2D;\nimport java.awt.geom.Rectangle2D;\nimport java.awt.print.PageFormat;\nimport java.awt.print.Printable;\nimport java.awt.print.PrinterException;\nimport java.awt.print.PrinterJob;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.Serializable;\nimport java.util.EventListener;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.ResourceBundle;\nimport javax.swing.JFileChooser;\nimport javax.swing.JMenu;\nimport javax.swing.JMenuItem;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.JPopupMenu;\nimport javax.swing.SwingUtilities;\nimport javax.swing.ToolTipManager;\nimport javax.swing.event.EventListenerList;\nimport org.jfree.chart.editor.ChartEditor;\nimport org.jfree.chart.editor.ChartEditorManager;\nimport org.jfree.chart.entity.ChartEntity;\nimport org.jfree.chart.entity.EntityCollection;\nimport org.jfree.chart.event.ChartChangeEvent;\nimport org.jfree.chart.event.ChartChangeListener;\nimport org.jfree.chart.event.ChartProgressEvent;\nimport org.jfree.chart.event.ChartProgressListener;\nimport org.jfree.chart.panel.Overlay;\nimport org.jfree.chart.event.OverlayChangeEvent;\nimport org.jfree.chart.event.OverlayChangeListener;\nimport org.jfree.chart.plot.Pannable;\nimport org.jfree.chart.plot.Plot;\nimport org.jfree.chart.plot.PlotOrientation;\nimport org.jfree.chart.plot.PlotRenderingInfo;\nimport org.jfree.chart.plot.Zoomable;\nimport org.jfree.chart.util.ResourceBundleWrapper;\nimport org.jfree.io.SerialUtilities;\nimport org.jfree.ui.ExtensionFileFilter;\n/**\n * A Swing GUI component for displaying a {@link JFreeChart} object.\n *

\n * The panel registers with the chart to receive notification of changes to any\n * component of the chart. The chart is redrawn automatically whenever this\n * notification is received.\n */\npublic class ChartPanel extends JPanel implements ChartChangeListener,\n ChartProgressListener, ActionListener, MouseListener,\n MouseMotionListener, OverlayChangeListener, Printable, Serializable {\n /** For serialization. */\n private static final long serialVersionUID = 6046366297214274674L;\n /**\n * Default setting for buffer usage. The default has been changed to\n * true from version 1.0.13 onwards, because of a severe\n * performance problem with drawing the zoom rectangle using XOR (which\n * now happens only when the buffer is NOT used).\n */\n public static final boolean DEFAULT_BUFFER_USED = true;\n /** The default panel width. */\n public static final int DEFAULT_WIDTH = 680;\n /** The default panel height. */\n public static final int DEFAULT_HEIGHT = 420;\n /** The default limit below which chart scaling kicks in. */\n public static final int DEFAULT_MINIMUM_DRAW_WIDTH = 300;\n /** The default limit below which chart scaling kicks in. */\n public static final int DEFAULT_MINIMUM_DRAW_HEIGHT = 200;\n /** The default limit above which chart scaling kicks in. */\n public static final int DEFAULT_MAXIMUM_DRAW_WIDTH = 1024;\n /** The default limit above which chart scaling kicks in. */\n public static final int DEFAULT_MAXIMUM_DRAW_HEIGHT = 768;\n /** The minimum size required to perform a zoom on a rectangle */\n public static final int DEFAULT_ZOOM_TRIGGER_DISTANCE = 10;\n /** Properties action command. */\n public static final String PROPERTIES_COMMAND = \"PROPERTIES\";\n /**\n * Copy action command.\n *\n * @since 1.0.13\n */\n public static final String COPY_COMMAND = \"COPY\";\n /** Save action command. */\n public static final String SAVE_COMMAND = \"SAVE\";\n /** Print action command. */\n public static final String PRINT_COMMAND = \"PRINT\";\n /** Zoom in (both axes) action command. */\n public static final String ZOOM_IN_BOTH_COMMAND = \"ZOOM_IN_BOTH\";\n /** Zoom in (domain axis only) action command. */\n public static final String ZOOM_IN_DOMAIN_COMMAND = \"ZOOM_IN_DOMAIN\";\n /** Zoom in (range axis only) action command. */\n public static final String ZOOM_IN_RANGE_COMMAND = \"ZOOM_IN_RANGE\";\n /** Zoom out (both axes) action command. */\n public static final String ZOOM_OUT_BOTH_COMMAND = \"ZOOM_OUT_BOTH\";\n /** Zoom out (domain axis only) action command. */\n public static final String ZOOM_OUT_DOMAIN_COMMAND = \"ZOOM_DOMAIN_BOTH\";\n /** Zoom out (range axis only) action command. */\n public static final String ZOOM_OUT_RANGE_COMMAND = \"ZOOM_RANGE_BOTH\";\n /** Zoom reset (both axes) action command. */\n public static final String ZOOM_RESET_BOTH_COMMAND = \"ZOOM_RESET_BOTH\";\n /** Zoom reset (domain axis only) action command. */\n public static final String ZOOM_RESET_DOMAIN_COMMAND = \"ZOOM_RESET_DOMAIN\";\n /** Zoom reset (range axis only) action command. */\n public static final String ZOOM_RESET_RANGE_COMMAND = \"ZOOM_RESET_RANGE\";\n /** The chart that is displayed in the panel. */\n private JFreeChart chart;\n /** Storage for registered (chart) mouse listeners. */\n private transient EventListenerList chartMouseListeners;\n /** A flag that controls whether or not the off-screen buffer is used. */\n private boolean useBuffer;\n /** A flag that indicates that the buffer should be refreshed. */\n private boolean refreshBuffer;\n /** A buffer for the rendered chart. */\n private transient Image chartBuffer;\n /** The height of the chart buffer. */\n private int chartBufferHeight;\n /** The width of the chart buffer. */\n private int chartBufferWidth;\n /**\n * The minimum width for drawing a chart (uses scaling for smaller widths).\n */\n private int minimumDrawWidth;\n /**\n * The minimum height for drawing a chart (uses scaling for smaller\n * heights).\n */\n private int minimumDrawHeight;\n /**\n * The maximum width for drawing a chart (uses scaling for bigger\n * widths).\n */\n private int maximumDrawWidth;\n /**\n * The maximum height for drawing a chart (uses scaling for bigger\n * heights).\n */\n private int maximumDrawHeight;\n /** The popup menu for the frame. */\n private JPopupMenu popup;\n /** The drawing info collected the last time the chart was drawn. */\n private ChartRenderingInfo info;\n /** The chart anchor point. */\n private Point2D anchor;\n /** The scale factor used to draw the chart. */\n private double scaleX;\n /** The scale factor used to draw the chart. */\n private double scaleY;\n /** The plot orientation. */\n private PlotOrientation orientation = PlotOrientation.VERTICAL;\n /** A flag that controls whether or not domain zooming is enabled. */\n private boolean domainZoomable = false;\n /** A flag that controls whether or not range zooming is enabled. */\n private boolean rangeZoomable = false;\n /**\n * The zoom rectangle starting point (selected by the user with a mouse\n * click). This is a point on the screen, not the chart (which may have\n * been scaled up or down to fit the panel).\n */\n private Point2D zoomPoint = null;\n /** The zoom rectangle (selected by the user with the mouse). */\n private transient Rectangle2D zoomRectangle = null;\n /** Controls if the zoom rectangle is drawn as an outline or filled. */\n private boolean fillZoomRectangle = true;\n /** The minimum distance required to drag the mouse to trigger a zoom. */\n private int zoomTriggerDistance;\n /** A flag that controls whether or not horizontal tracing is enabled. */\n private boolean horizontalAxisTrace = false;\n /** A flag that controls whether or not vertical tracing is enabled. */\n private boolean verticalAxisTrace = false;\n /** A vertical trace line. */\n private transient Line2D verticalTraceLine;\n /** A horizontal trace line. */\n private transient Line2D horizontalTraceLine;\n /** Menu item for zooming in on a chart (both axes). */\n private JMenuItem zoomInBothMenuItem;\n /** Menu item for zooming in on a chart (domain axis). */\n private JMenuItem zoomInDomainMenuItem;\n /** Menu item for zooming in on a chart (range axis). */\n private JMenuItem zoomInRangeMenuItem;\n /** Menu item for zooming out on a chart. */\n private JMenuItem zoomOutBothMenuItem;\n /** Menu item for zooming out on a chart (domain axis). */\n private JMenuItem zoomOutDomainMenuItem;\n /** Menu item for zooming out on a chart (range axis). */\n private JMenuItem zoomOutRangeMenuItem;\n /** Menu item for resetting the zoom (both axes). */\n private JMenuItem zoomResetBothMenuItem;\n /** Menu item for resetting the zoom (domain axis only). */\n private JMenuItem zoomResetDomainMenuItem;\n /** Menu item for resetting the zoom (range axis only). */\n private JMenuItem zoomResetRangeMenuItem;\n /**\n * The default directory for saving charts to file.\n *\n * @since 1.0.7\n */\n private File defaultDirectoryForSaveAs;\n /** A flag that controls whether or not file extensions are enforced. */\n private boolean enforceFileExtensions;\n /** A flag that indicates if original tooltip delays are changed. */\n private boolean ownToolTipDelaysActive;\n /** Original initial tooltip delay of ToolTipManager.sharedInstance(). */\n private int originalToolTipInitialDelay;\n /** Original reshow tooltip delay of ToolTipManager.sharedInstance(). */\n private int originalToolTipReshowDelay;\n /** Original dismiss tooltip delay of ToolTipManager.sharedInstance(). */\n private int originalToolTipDismissDelay;\n /** Own initial tooltip delay to be used in this chart panel. */\n private int ownToolTipInitialDelay;\n /** Own reshow tooltip delay to be used in this chart panel. */\n private int ownToolTipReshowDelay;\n /** Own dismiss tooltip delay to be used in this chart panel. */\n private int ownToolTipDismissDelay;\n /** The factor used to zoom in on an axis range. */\n private double zoomInFactor = 0.5;\n /** The factor used to zoom out on an axis range. */\n private double zoomOutFactor = 2.0;\n /**\n * A flag that controls whether zoom operations are centred on the\n * current anchor point, or the centre point of the relevant axis.\n *\n * @since 1.0.7\n */\n private boolean zoomAroundAnchor;\n /**\n * The paint used to draw the zoom rectangle outline.\n *\n * @since 1.0.13\n */\n private transient Paint zoomOutlinePaint;\n /**\n * The zoom fill paint (should use transparency).\n *\n * @since 1.0.13\n */\n private transient Paint zoomFillPaint;\n /** The resourceBundle for the localization. */\n protected static ResourceBundle localizationResources\n = ResourceBundleWrapper.getBundle(\n \"org.jfree.chart.LocalizationBundle\");\n /**\n * Temporary storage for the width and height of the chart\n * drawing area during panning.\n */\n private double panW, panH;\n /** The last mouse position during panning. */\n private Point panLast;\n /**\n * The mask for mouse events to trigger panning.\n *\n * @since 1.0.13\n */\n private int panMask = InputEvent.CTRL_MASK;\n /**\n * A list of overlays for the panel.\n *\n * @since 1.0.13\n */\n private List overlays;\n /**\n * Constructs a panel that displays the specified chart.\n *\n * @param chart the chart.\n */\n public ChartPanel(JFreeChart chart) {\n this(\n chart,\n DEFAULT_WIDTH,\n DEFAULT_HEIGHT,\n DEFAULT_MINIMUM_DRAW_WIDTH,\n DEFAULT_MINIMUM_DRAW_HEIGHT,\n DEFAULT_MAXIMUM_DRAW_WIDTH,\n DEFAULT_MAXIMUM_DRAW_HEIGHT,\n DEFAULT_BUFFER_USED,\n true, // properties\n true, // save\n true, // print\n true, // zoom\n true // tooltips\n );\n }\n /**\n * Constructs a panel containing a chart. The useBuffer flag\n * controls whether or not an offscreen BufferedImage is\n * maintained for the chart. If the buffer is used, more memory is\n * consumed, but panel repaints will be a lot quicker in cases where the\n * chart itself hasn't changed (for example, when another frame is moved\n * to reveal the panel). WARNING: If you set the useBuffer\n * flag to false, note that the mouse zooming rectangle will (in that case)\n * be drawn using XOR, and there is a SEVERE performance problem with that\n * on JRE6 on Windows.\n *\n * @param chart the chart.\n * @param useBuffer a flag controlling whether or not an off-screen buffer\n * is used (read the warning above before setting this\n * to false).\n */\n public ChartPanel(JFreeChart chart, boolean useBuffer) {\n this(chart, DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_MINIMUM_DRAW_WIDTH,\n DEFAULT_MINIMUM_DRAW_HEIGHT, DEFAULT_MAXIMUM_DRAW_WIDTH,\n DEFAULT_MAXIMUM_DRAW_HEIGHT, useBuffer,\n true, // properties\n true, // save\n true, // print\n true, // zoom\n true // tooltips\n );\n }\n /**\n * Constructs a JFreeChart panel.\n *\n * @param chart the chart.\n * @param properties a flag indicating whether or not the chart property\n * editor should be available via the popup menu.\n * @param save a flag indicating whether or not save options should be\n * available via the popup menu.\n * @param print a flag indicating whether or not the print option\n * should be available via the popup menu.\n * @param zoom a flag indicating whether or not zoom options should\n * be added to the popup menu.\n * @param tooltips a flag indicating whether or not tooltips should be\n * enabled for the chart.\n */\n public ChartPanel(JFreeChart chart,\n boolean properties,\n boolean save,\n boolean print,\n boolean zoom,\n boolean tooltips) {\n this(chart,\n DEFAULT_WIDTH,\n DEFAULT_HEIGHT,\n DEFAULT_MINIMUM_DRAW_WIDTH,\n DEFAULT_MINIMUM_DRAW_HEIGHT,\n DEFAULT_MAXIMUM_DRAW_WIDTH,\n DEFAULT_MAXIMUM_DRAW_HEIGHT,\n DEFAULT_BUFFER_USED,\n properties,\n save,\n print,\n zoom,\n tooltips\n );\n }\n /**\n * Constructs a JFreeChart panel.\n *\n * @param chart the chart.\n * @param width the preferred width of the panel.\n * @param height the preferred height of the panel.\n * @param minimumDrawWidth the minimum drawing width.\n * @param minimumDrawHeight the minimum drawing height.\n * @param maximumDrawWidth the maximum drawing width.\n * @param maximumDrawHeight the maximum drawing height.\n * @param useBuffer a flag that indicates whether to use the off-screen\n * buffer to improve performance (at the expense of\n * memory).\n * @param properties a flag indicating whether or not the chart property\n * editor should be available via the popup menu.\n * @param save a flag indicating whether or not save options should be\n * available via the popup menu.\n * @param print a flag indicating whether or not the print option\n * should be available via the popup menu.\n * @param zoom a flag indicating whether or not zoom options should be\n * added to the popup menu.\n * @param tooltips a flag indicating whether or not tooltips should be\n * enabled for the chart.\n */\n public ChartPanel(JFreeChart chart, int width, int height,\n int minimumDrawWidth, int minimumDrawHeight, int maximumDrawWidth,\n int maximumDrawHeight, boolean useBuffer, boolean properties,\n boolean save, boolean print, boolean zoom, boolean tooltips) {\n this(chart, width, height, minimumDrawWidth, minimumDrawHeight,\n maximumDrawWidth, maximumDrawHeight, useBuffer, properties,\n true, save, print, zoom, tooltips);\n }\n /**\n * Constructs a JFreeChart panel.\n *\n * @param chart the chart.\n * @param width the preferred width of the panel.\n * @param height the preferred height of the panel.\n * @param minimumDrawWidth the minimum drawing width.\n * @param minimumDrawHeight the minimum drawing height.\n * @param maximumDrawWidth the maximum drawing width.\n * @param maximumDrawHeight the maximum drawing height.\n * @param useBuffer a flag that indicates whether to use the off-screen\n * buffer to improve performance (at the expense of\n * memory).\n * @param properties a flag indicating whether or not the chart property\n * editor should be available via the popup menu.\n * @param copy a flag indicating whether or not a copy option should be\n * available via the popup menu.\n * @param save a flag indicating whether or not save options should be\n * available via the popup menu.\n * @param print a flag indicating whether or not the print option\n * should be available via the popup menu.\n * @param zoom a flag indicating whether or not zoom options should be\n * added to the popup menu.\n * @param tooltips a flag indicating whether or not tooltips should be\n * enabled for the chart.\n *\n * @since 1.0.13\n */\n public ChartPanel(JFreeChart chart, int width, int height,\n int minimumDrawWidth, int minimumDrawHeight, int maximumDrawWidth,\n int maximumDrawHeight, boolean useBuffer, boolean properties,\n boolean copy, boolean save, boolean print, boolean zoom,\n boolean tooltips) {\n setChart(chart);\n this.chartMouseListeners = new EventListenerList();\n this.info = new ChartRenderingInfo();\n setPreferredSize(new Dimension(width, height));\n this.useBuffer = useBuffer;\n this.refreshBuffer = false;\n this.minimumDrawWidth = minimumDrawWidth;\n this.minimumDrawHeight = minimumDrawHeight;\n this.maximumDrawWidth = maximumDrawWidth;\n this.maximumDrawHeight = maximumDrawHeight;\n this.zoomTriggerDistance = DEFAULT_ZOOM_TRIGGER_DISTANCE;\n // set up popup menu...\n this.popup = null;\n if (properties || copy || save || print || zoom) {\n this.popup = createPopupMenu(properties, copy, save, print, zoom);\n }\n enableEvents(AWTEvent.MOUSE_EVENT_MASK);\n enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK);\n setDisplayToolTips(tooltips);\n addMouseListener(this);\n addMouseMotionListener(this);\n this.defaultDirectoryForSaveAs = null;\n this.enforceFileExtensions = true;\n // initialize ChartPanel-specific tool tip delays with\n // values the from ToolTipManager.sharedInstance()\n ToolTipManager ttm = ToolTipManager.sharedInstance();\n this.ownToolTipInitialDelay = ttm.getInitialDelay();\n this.ownToolTipDismissDelay = ttm.getDismissDelay();\n this.ownToolTipReshowDelay = ttm.getReshowDelay();\n this.zoomAroundAnchor = false;\n this.zoomOutlinePaint = Color.blue;\n this.zoomFillPaint = new Color(0, 0, 255, 63);\n this.panMask = InputEvent.CTRL_MASK;\n // for MacOSX we can't use the CTRL key for mouse drags, see:\n String osName = System.getProperty(\"os.name\").toLowerCase();\n if (osName.startsWith(\"mac os x\")) {\n this.panMask = InputEvent.ALT_MASK;\n }\n this.overlays = new java.util.ArrayList();\n }\n /**\n * Returns the chart contained in the panel.\n *\n * @return The chart (possibly null).\n */\n public JFreeChart getChart() {\n return this.chart;\n }\n /**\n * Sets the chart that is displayed in the panel.\n *\n * @param chart the chart (null permitted).\n */\n public void setChart(JFreeChart chart) {\n // stop listening for changes to the existing chart\n if (this.chart != null) {\n this.chart.removeChangeListener(this);\n this.chart.removeProgressListener(this);\n }\n // add the new chart\n this.chart = chart;\n if (chart != null) {\n this.chart.addChangeListener(this);\n this.chart.addProgressListener(this);\n Plot plot = chart.getPlot();\n this.domainZoomable = false;\n this.rangeZoomable = false;\n if (plot instanceof Zoomable) {\n Zoomable z = (Zoomable) plot;\n this.domainZoomable = z.isDomainZoomable();\n this.rangeZoomable = z.isRangeZoomable();\n this.orientation = z.getOrientation();\n }\n }\n else {\n this.domainZoomable = false;\n this.rangeZoomable = false;\n }\n if (this.useBuffer) {\n this.refreshBuffer = true;\n }\n repaint();\n }\n /**\n * Returns the minimum drawing width for charts.\n *

\n * If the width available on the panel is less than this, then the chart is\n * drawn at the minimum width then scaled down to fit.\n *\n * @return The minimum drawing width.\n */\n public int getMinimumDrawWidth() {\n return this.minimumDrawWidth;\n }\n /**\n * Sets the minimum drawing width for the chart on this panel.\n *

\n * At the time the chart is drawn on the panel, if the available width is\n * less than this amount, the chart will be drawn using the minimum width\n * then scaled down to fit the available space.\n *\n * @param width The width.\n */\n public void setMinimumDrawWidth(int width) {\n this.minimumDrawWidth = width;\n }\n /**\n * Returns the maximum drawing width for charts.\n *

\n * If the width available on the panel is greater than this, then the chart\n * is drawn at the maximum width then scaled up to fit.\n *\n * @return The maximum drawing width.\n */\n public int getMaximumDrawWidth() {\n return this.maximumDrawWidth;\n }\n /**\n * Sets the maximum drawing width for the chart on this panel.\n *

\n * At the time the chart is drawn on the panel, if the available width is\n * greater than this amount, the chart will be drawn using the maximum\n * width then scaled up to fit the available space.\n *\n * @param width The width.\n */\n public void setMaximumDrawWidth(int width) {\n this.maximumDrawWidth = width;\n }\n /**\n * Returns the minimum drawing height for charts.\n *

\n * If the height available on the panel is less than this, then the chart\n * is drawn at the minimum height then scaled down to fit.\n *\n * @return The minimum drawing height.\n */\n public int getMinimumDrawHeight() {\n return this.minimumDrawHeight;\n }\n /**\n * Sets the minimum drawing height for the chart on this panel.\n *

\n * At the time the chart is drawn on the panel, if the available height is\n * less than this amount, the chart will be drawn using the minimum height\n * then scaled down to fit the available space.\n *\n * @param height The height.\n */\n public void setMinimumDrawHeight(int height) {\n this.minimumDrawHeight = height;\n }\n /**\n * Returns the maximum drawing height for charts.\n *

\n * If the height available on the panel is greater than this, then the\n * chart is drawn at the maximum height then scaled up to fit.\n *\n * @return The maximum drawing height.\n */\n public int getMaximumDrawHeight() {\n return this.maximumDrawHeight;\n }\n /**\n * Sets the maximum drawing height for the chart on this panel.\n *

\n * At the time the chart is drawn on the panel, if the available height is\n * greater than this amount, the chart will be drawn using the maximum\n * height then scaled up to fit the available space.\n *\n * @param height The height.\n */\n public void setMaximumDrawHeight(int height) {\n this.maximumDrawHeight = height;\n }\n /**\n * Returns the X scale factor for the chart. This will be 1.0 if no\n * scaling has been used.\n *\n * @return The scale factor.\n */\n public double getScaleX() {\n return this.scaleX;\n }\n /**\n * Returns the Y scale factory for the chart. This will be 1.0 if no\n * scaling has been used.\n *\n * @return The scale factor.\n */\n public double getScaleY() {\n return this.scaleY;\n }\n /**\n * Returns the anchor point.\n *\n * @return The anchor point (possibly null).\n */\n public Point2D getAnchor() {\n return this.anchor;\n }\n /**\n * Sets the anchor point. This method is provided for the use of\n * subclasses, not end users.\n *\n * @param anchor the anchor point (null permitted).\n */\n protected void setAnchor(Point2D anchor) {\n this.anchor = anchor;\n }\n /**\n * Returns the popup menu.\n *\n * @return The popup menu.\n */\n public JPopupMenu getPopupMenu() {\n return this.popup;\n }\n /**\n * Sets the popup menu for the panel.\n *\n * @param popup the popup menu (null permitted).\n */\n public void setPopupMenu(JPopupMenu popup) {\n this.popup = popup;\n }\n /**\n * Returns the chart rendering info from the most recent chart redraw.\n *\n * @return The chart rendering info.\n */\n public ChartRenderingInfo getChartRenderingInfo() {\n return this.info;\n }\n /**\n * A convenience method that switches on mouse-based zooming.\n *\n * @param flag true enables zooming and rectangle fill on\n * zoom.\n */\n public void setMouseZoomable(boolean flag) {\n setMouseZoomable(flag, true);\n }\n /**\n * A convenience method that switches on mouse-based zooming.\n *\n * @param flag true if zooming enabled\n * @param fillRectangle true if zoom rectangle is filled,\n * false if rectangle is shown as outline only.\n */\n public void setMouseZoomable(boolean flag, boolean fillRectangle) {\n setDomainZoomable(flag);\n setRangeZoomable(flag);\n setFillZoomRectangle(fillRectangle);\n }\n /**\n * Returns the flag that determines whether or not zooming is enabled for\n * the domain axis.\n *\n * @return A boolean.\n */\n public boolean isDomainZoomable() {\n return this.domainZoomable;\n }\n /**\n * Sets the flag that controls whether or not zooming is enable for the\n * domain axis. A check is made to ensure that the current plot supports\n * zooming for the domain values.\n *\n * @param flag true enables zooming if possible.\n */\n public void setDomainZoomable(boolean flag) {\n if (flag) {\n Plot plot = this.chart.getPlot();\n if (plot instanceof Zoomable) {\n Zoomable z = (Zoomable) plot;\n this.domainZoomable = flag && (z.isDomainZoomable());\n }\n }\n else {\n this.domainZoomable = false;\n }\n }\n /**\n * Returns the flag that determines whether or not zooming is enabled for\n * the range axis.\n *\n * @return A boolean.\n */\n public boolean isRangeZoomable() {\n return this.rangeZoomable;\n }\n /**\n * A flag that controls mouse-based zooming on the vertical axis.\n *\n * @param flag true enables zooming.\n */\n public void setRangeZoomable(boolean flag) {\n if (flag) {\n Plot plot = this.chart.getPlot();\n if (plot instanceof Zoomable) {\n Zoomable z = (Zoomable) plot;\n this.rangeZoomable = flag && (z.isRangeZoomable());\n }\n }\n else {\n this.rangeZoomable = false;\n }\n }\n /**\n * Returns the flag that controls whether or not the zoom rectangle is\n * filled when drawn.\n *\n * @return A boolean.\n */\n public boolean getFillZoomRectangle() {\n return this.fillZoomRectangle;\n }\n /**\n * A flag that controls how the zoom rectangle is drawn.\n *\n * @param flag true instructs to fill the rectangle on\n * zoom, otherwise it will be outlined.\n */\n public void setFillZoomRectangle(boolean flag) {\n this.fillZoomRectangle = flag;\n }\n /**\n * Returns the zoom trigger distance. This controls how far the mouse must\n * move before a zoom action is triggered.\n *\n * @return The distance (in Java2D units).\n */\n public int getZoomTriggerDistance() {\n return this.zoomTriggerDistance;\n }\n /**\n * Sets the zoom trigger distance. This controls how far the mouse must\n * move before a zoom action is triggered.\n *\n * @param distance the distance (in Java2D units).\n */\n public void setZoomTriggerDistance(int distance) {\n this.zoomTriggerDistance = distance;\n }\n /**\n * Returns the flag that controls whether or not a horizontal axis trace\n * line is drawn over the plot area at the current mouse location.\n *\n * @return A boolean.\n */\n public boolean getHorizontalAxisTrace() {\n return this.horizontalAxisTrace;\n }\n /**\n * A flag that controls trace lines on the horizontal axis.\n *\n * @param flag true enables trace lines for the mouse\n * pointer on the horizontal axis.\n */\n public void setHorizontalAxisTrace(boolean flag) {\n this.horizontalAxisTrace = flag;\n }\n /**\n * Returns the horizontal trace line.\n *\n * @return The horizontal trace line (possibly null).\n */\n protected Line2D getHorizontalTraceLine() {\n return this.horizontalTraceLine;\n }\n /**\n * Sets the horizontal trace line.\n *\n * @param line the line (null permitted).\n */\n protected void setHorizontalTraceLine(Line2D line) {\n this.horizontalTraceLine = line;\n }\n /**\n * Returns the flag that controls whether or not a vertical axis trace\n * line is drawn over the plot area at the current mouse location.\n *\n * @return A boolean.\n */\n public boolean getVerticalAxisTrace() {\n return this.verticalAxisTrace;\n }\n /**\n * A flag that controls trace lines on the vertical axis.\n *\n * @param flag true enables trace lines for the mouse\n * pointer on the vertical axis.\n */\n public void setVerticalAxisTrace(boolean flag) {\n this.verticalAxisTrace = flag;\n }\n /**\n * Returns the vertical trace line.\n *\n * @return The vertical trace line (possibly null).\n */\n protected Line2D getVerticalTraceLine() {\n return this.verticalTraceLine;\n }\n /**\n * Sets the vertical trace line.\n *\n * @param line the line (null permitted).\n */\n protected void setVerticalTraceLine(Line2D line) {\n this.verticalTraceLine = line;\n }\n /**\n * Returns the default directory for the \"save as\" option.\n *\n * @return The default directory (possibly null).\n *\n * @since 1.0.7\n */\n public File getDefaultDirectoryForSaveAs() {\n return this.defaultDirectoryForSaveAs;\n }\n /**\n * Sets the default directory for the \"save as\" option. If you set this\n * to null, the user's default directory will be used.\n *\n * @param directory the directory (null permitted).\n *\n * @since 1.0.7\n */\n public void setDefaultDirectoryForSaveAs(File directory) {\n if (directory != null) {\n if (!directory.isDirectory()) {\n throw new IllegalArgumentException(\n \"The 'directory' argument is not a directory.\");\n }\n }\n this.defaultDirectoryForSaveAs = directory;\n }\n /**\n * Returns true if file extensions should be enforced, and\n * false otherwise.\n *\n * @return The flag.\n *\n * @see #setEnforceFileExtensions(boolean)\n */\n public boolean isEnforceFileExtensions() {\n return this.enforceFileExtensions;\n }\n /**\n * Sets a flag that controls whether or not file extensions are enforced.\n *\n * @param enforce the new flag value.\n *\n * @see #isEnforceFileExtensions()\n */\n public void setEnforceFileExtensions(boolean enforce) {\n this.enforceFileExtensions = enforce;\n }\n /**\n * Returns the flag that controls whether or not zoom operations are\n * centered around the current anchor point.\n *\n * @return A boolean.\n *\n * @since 1.0.7\n *\n * @see #setZoomAroundAnchor(boolean)\n */\n public boolean getZoomAroundAnchor() {\n return this.zoomAroundAnchor;\n }\n /**\n * Sets the flag that controls whether or not zoom operations are\n * centered around the current anchor point.\n *\n * @param zoomAroundAnchor the new flag value.\n *\n * @since 1.0.7\n *\n * @see #getZoomAroundAnchor()\n */\n public void setZoomAroundAnchor(boolean zoomAroundAnchor) {\n this.zoomAroundAnchor = zoomAroundAnchor;\n }\n /**\n * Returns the zoom rectangle fill paint.\n *\n * @return The zoom rectangle fill paint (never null).\n *\n * @see #setZoomFillPaint(java.awt.Paint)\n * @see #setFillZoomRectangle(boolean)\n *\n * @since 1.0.13\n */\n public Paint getZoomFillPaint() {\n return this.zoomFillPaint;\n }\n /**\n * Sets the zoom rectangle fill paint.\n *\n * @param paint the paint (null not permitted).\n *\n * @see #getZoomFillPaint()\n * @see #getFillZoomRectangle()\n *\n * @since 1.0.13\n */\n public void setZoomFillPaint(Paint paint) {\n if (paint == null) {\n throw new IllegalArgumentException(\"Null 'paint' argument.\");\n }\n this.zoomFillPaint = paint;\n }\n /**\n * Returns the zoom rectangle outline paint.\n *\n * @return The zoom rectangle outline paint (never null).\n *\n * @see #setZoomOutlinePaint(java.awt.Paint)\n * @see #setFillZoomRectangle(boolean)\n *\n * @since 1.0.13\n */\n public Paint getZoomOutlinePaint() {\n return this.zoomOutlinePaint;\n }\n /**\n * Sets the zoom rectangle outline paint.\n *\n * @param paint the paint (null not permitted).\n *\n * @see #getZoomOutlinePaint()\n * @see #getFillZoomRectangle()\n *\n * @since 1.0.13\n */\n public void setZoomOutlinePaint(Paint paint) {\n this.zoomOutlinePaint = paint;\n }\n /**\n * The mouse wheel handler.\n */\n private MouseWheelHandler mouseWheelHandler;\n /**\n * Returns true if the mouse wheel handler is enabled, and\n * false otherwise.\n *\n * @return A boolean.\n *\n * @since 1.0.13\n */\n public boolean isMouseWheelEnabled() {\n return this.mouseWheelHandler != null;\n }\n /**\n * Enables or disables mouse wheel support for the panel.\n *\n * @param flag a boolean.\n *\n * @since 1.0.13\n */\n public void setMouseWheelEnabled(boolean flag) {\n if (flag && this.mouseWheelHandler == null) {\n this.mouseWheelHandler = new MouseWheelHandler(this);\n }\n else if (!flag && this.mouseWheelHandler != null) {\n this.removeMouseWheelListener(this.mouseWheelHandler);\n this.mouseWheelHandler = null;\n }\n }\n /**\n * Add an overlay to the panel.\n *\n * @param overlay the overlay (null not permitted).\n *\n * @since 1.0.13\n */\n public void addOverlay(Overlay overlay) {\n if (overlay == null) {\n throw new IllegalArgumentException(\"Null 'overlay' argument.\");\n }\n this.overlays.add(overlay);\n overlay.addChangeListener(this);\n repaint();\n }\n /**\n * Removes an overlay from the panel.\n *\n * @param overlay the overlay to remove (null not permitted).\n *\n * @since 1.0.13\n */\n public void removeOverlay(Overlay overlay) {\n if (overlay == null) {\n throw new IllegalArgumentException(\"Null 'overlay' argument.\");\n }\n boolean removed = this.overlays.remove(overlay);\n if (removed) {\n overlay.removeChangeListener(this);\n repaint();\n }\n }\n /**\n * Handles a change to an overlay by repainting the panel.\n *\n * @param event the event.\n *\n * @since 1.0.13\n */\n public void overlayChanged(OverlayChangeEvent event) {\n repaint();\n }\n /**\n * Switches the display of tooltips for the panel on or off. Note that\n * tooltips can only be displayed if the chart has been configured to\n * generate tooltip items.\n *\n * @param flag true to enable tooltips, false to\n * disable tooltips.\n */\n public void setDisplayToolTips(boolean flag) {\n if (flag) {\n ToolTipManager.sharedInstance().registerComponent(this);\n }\n else {\n ToolTipManager.sharedInstance().unregisterComponent(this);\n }\n }\n /**\n * Returns a string for the tooltip.\n *\n * @param e the mouse event.\n *\n * @return A tool tip or null if no tooltip is available.\n */\n public String getToolTipText(MouseEvent e) {\n String result = null;\n if (this.info != null) {\n EntityCollection entities = this.info.getEntityCollection();\n if (entities != null) {\n Insets insets = getInsets();\n ChartEntity entity = entities.getEntity(\n (int) ((e.getX() - insets.left) / this.scaleX),\n (int) ((e.getY() - insets.top) / this.scaleY));\n if (entity != null) {\n result = entity.getToolTipText();\n }\n }\n }\n return result;\n }\n /**\n * Translates a Java2D point on the chart to a screen location.\n *\n * @param java2DPoint the Java2D point.\n *\n * @return The screen location.\n */\n public Point translateJava2DToScreen(Point2D java2DPoint) {\n Insets insets = getInsets();\n int x = (int) (java2DPoint.getX() * this.scaleX + insets.left);\n int y = (int) (java2DPoint.getY() * this.scaleY + insets.top);\n return new Point(x, y);\n }\n /**\n * Translates a panel (component) location to a Java2D point.\n *\n * @param screenPoint the screen location (null not\n * permitted).\n *\n * @return The Java2D coordinates.\n */\n public Point2D translateScreenToJava2D(Point screenPoint) {\n Insets insets = getInsets();\n double x = (screenPoint.getX() - insets.left) / this.scaleX;\n double y = (screenPoint.getY() - insets.top) / this.scaleY;\n return new Point2D.Double(x, y);\n }\n /**\n * Applies any scaling that is in effect for the chart drawing to the\n * given rectangle.\n *\n * @param rect the rectangle (null not permitted).\n *\n * @return A new scaled rectangle.\n */\n public Rectangle2D scale(Rectangle2D rect) {\n Insets insets = getInsets();\n double x = rect.getX() * getScaleX() + insets.left;\n double y = rect.getY() * getScaleY() + insets.top;\n double w = rect.getWidth() * getScaleX();\n double h = rect.getHeight() * getScaleY();\n return new Rectangle2D.Double(x, y, w, h);\n }\n /**\n * Returns the chart entity at a given point.\n *

\n * This method will return null if there is (a) no entity at the given\n * point, or (b) no entity collection has been generated.\n *\n * @param viewX the x-coordinate.\n * @param viewY the y-coordinate.\n *\n * @return The chart entity (possibly null).\n */\n public ChartEntity getEntityForPoint(int viewX, int viewY) {\n ChartEntity result = null;\n if (this.info != null) {\n Insets insets = getInsets();\n double x = (viewX - insets.left) / this.scaleX;\n double y = (viewY - insets.top) / this.scaleY;\n EntityCollection entities = this.info.getEntityCollection();\n result = entities != null ? entities.getEntity(x, y) : null;\n }\n return result;\n }\n /**\n * Returns the flag that controls whether or not the offscreen buffer\n * needs to be refreshed.\n *\n * @return A boolean.\n */\n public boolean getRefreshBuffer() {\n return this.refreshBuffer;\n }\n /**\n * Sets the refresh buffer flag. This flag is used to avoid unnecessary\n * redrawing of the chart when the offscreen image buffer is used.\n *\n * @param flag true indicates that the buffer should be\n * refreshed.\n */\n public void setRefreshBuffer(boolean flag) {\n this.refreshBuffer = flag;\n }\n /**\n * Paints the component by drawing the chart to fill the entire component,\n * but allowing for the insets (which will be non-zero if a border has been\n * set for this component). To increase performance (at the expense of\n * memory), an off-screen buffer image can be used.\n *\n * @param g the graphics device for drawing on.\n */\n public void paintComponent(Graphics g) {\n super.paintComponent(g);\n if (this.chart == null) {\n return;\n }\n Graphics2D g2 = (Graphics2D) g.create();\n // first determine the size of the chart rendering area...\n Dimension size = getSize();\n Insets insets = getInsets();\n Rectangle2D available = new Rectangle2D.Double(insets.left, insets.top,\n size.getWidth() - insets.left - insets.right,\n size.getHeight() - insets.top - insets.bottom);\n // work out if scaling is required...\n boolean scale = false;\n double drawWidth = available.getWidth();\n double drawHeight = available.getHeight();\n this.scaleX = 1.0;\n this.scaleY = 1.0;\n if (drawWidth < this.minimumDrawWidth) {\n this.scaleX = drawWidth / this.minimumDrawWidth;\n drawWidth = this.minimumDrawWidth;\n scale = true;\n }\n else if (drawWidth > this.maximumDrawWidth) {\n this.scaleX = drawWidth / this.maximumDrawWidth;\n drawWidth = this.maximumDrawWidth;\n scale = true;\n }\n if (drawHeight < this.minimumDrawHeight) {\n this.scaleY = drawHeight / this.minimumDrawHeight;\n drawHeight = this.minimumDrawHeight;\n scale = true;\n }\n else if (drawHeight > this.maximumDrawHeight) {\n this.scaleY = drawHeight / this.maximumDrawHeight;\n drawHeight = this.maximumDrawHeight;\n scale = true;\n }\n Rectangle2D chartArea = new Rectangle2D.Double(0.0, 0.0, drawWidth,\n drawHeight);\n // are we using the chart buffer?\n if (this.useBuffer) {\n // do we need to resize the buffer?\n if ((this.chartBuffer == null)\n || (this.chartBufferWidth != available.getWidth())\n || (this.chartBufferHeight != available.getHeight())) {\n this.chartBufferWidth = (int) available.getWidth();\n this.chartBufferHeight = (int) available.getHeight();\n GraphicsConfiguration gc = g2.getDeviceConfiguration();\n this.chartBuffer = gc.createCompatibleImage(\n this.chartBufferWidth, this.chartBufferHeight,\n Transparency.TRANSLUCENT);\n this.refreshBuffer = true;\n }\n // do we need to redraw the buffer?\n if (this.refreshBuffer) {\n this.refreshBuffer = false; // clear the flag\n Rectangle2D bufferArea = new Rectangle2D.Double(\n 0, 0, this.chartBufferWidth, this.chartBufferHeight);\n // make the background of the buffer clear and transparent\n Graphics2D bufferG2 = (Graphics2D)\n this.chartBuffer.getGraphics();\n Composite savedComposite = bufferG2.getComposite();\n bufferG2.setComposite(AlphaComposite.getInstance(\n AlphaComposite.CLEAR, 0.0f));\n Rectangle r = new Rectangle(0, 0, this.chartBufferWidth,\n this.chartBufferHeight);\n bufferG2.fill(r);\n bufferG2.setComposite(savedComposite);\n if (scale) {\n AffineTransform saved = bufferG2.getTransform();\n AffineTransform st = AffineTransform.getScaleInstance(\n this.scaleX, this.scaleY);\n bufferG2.transform(st);\n this.chart.draw(bufferG2, chartArea, this.anchor,\n this.info);\n bufferG2.setTransform(saved);\n }\n else {\n this.chart.draw(bufferG2, bufferArea, this.anchor,\n this.info);\n }\n }\n // zap the buffer onto the panel...\n g2.drawImage(this.chartBuffer, insets.left, insets.top, this);\n }\n // or redrawing the chart every time...\n else {\n AffineTransform saved = g2.getTransform();\n g2.translate(insets.left, insets.top);\n if (scale) {\n AffineTransform st = AffineTransform.getScaleInstance(\n this.scaleX, this.scaleY);\n g2.transform(st);\n }\n this.chart.draw(g2, chartArea, this.anchor, this.info);\n g2.setTransform(saved);\n }\n Iterator iterator = this.overlays.iterator();\n while (iterator.hasNext()) {\n Overlay overlay = (Overlay) iterator.next();\n overlay.paintOverlay(g2, this);\n }\n // redraw the zoom rectangle (if present) - if useBuffer is false,\n // we use XOR so we can XOR the rectangle away again without redrawing\n // the chart\n drawZoomRectangle(g2, !this.useBuffer);\n g2.dispose();\n this.anchor = null;\n this.verticalTraceLine = null;\n this.horizontalTraceLine = null;\n }\n /**\n * Receives notification of changes to the chart, and redraws the chart.\n *\n * @param event details of the chart change event.\n */\n public void chartChanged(ChartChangeEvent event) {\n this.refreshBuffer = true;\n Plot plot = this.chart.getPlot();\n if (plot instanceof Zoomable) {\n Zoomable z = (Zoomable) plot;\n this.orientation = z.getOrientation();\n }\n repaint();\n }\n /**\n * Receives notification of a chart progress event.\n *\n * @param event the event.\n */\n public void chartProgress(ChartProgressEvent event) {\n // does nothing - override if necessary\n }\n /**\n * Handles action events generated by the popup menu.\n *\n * @param event the event.\n */\n public void actionPerformed(ActionEvent event) {\n String command = event.getActionCommand();\n // many of the zoom methods need a screen location - all we have is\n // the zoomPoint, but it might be null. Here we grab the x and y\n // coordinates, or use defaults...\n double screenX = -1.0;\n double screenY = -1.0;\n if (this.zoomPoint != null) {\n screenX = this.zoomPoint.getX();\n screenY = this.zoomPoint.getY();\n }\n if (command.equals(PROPERTIES_COMMAND)) {\n doEditChartProperties();\n }\n else if (command.equals(COPY_COMMAND)) {\n doCopy();\n }\n else if (command.equals(SAVE_COMMAND)) {\n try {\n doSaveAs();\n }\n catch (IOException e) {\n e.printStackTrace();\n }\n }\n else if (command.equals(PRINT_COMMAND)) {\n createChartPrintJob();\n }\n else if (command.equals(ZOOM_IN_BOTH_COMMAND)) {\n zoomInBoth(screenX, screenY);\n }\n else if (command.equals(ZOOM_IN_DOMAIN_COMMAND)) {\n zoomInDomain(screenX, screenY);\n }\n else if (command.equals(ZOOM_IN_RANGE_COMMAND)) {\n zoomInRange(screenX, screenY);\n }\n else if (command.equals(ZOOM_OUT_BOTH_COMMAND)) {\n zoomOutBoth(screenX, screenY);\n }\n else if (command.equals(ZOOM_OUT_DOMAIN_COMMAND)) {\n zoomOutDomain(screenX, screenY);\n }\n else if (command.equals(ZOOM_OUT_RANGE_COMMAND)) {\n zoomOutRange(screenX, screenY);\n }\n else if (command.equals(ZOOM_RESET_BOTH_COMMAND)) {\n restoreAutoBounds();\n }\n else if (command.equals(ZOOM_RESET_DOMAIN_COMMAND)) {\n restoreAutoDomainBounds();\n }\n else if (command.equals(ZOOM_RESET_RANGE_COMMAND)) {\n restoreAutoRangeBounds();\n }\n }\n /**\n * Handles a 'mouse entered' event. This method changes the tooltip delays\n * of ToolTipManager.sharedInstance() to the possibly different values set\n * for this chart panel.\n *\n * @param e the mouse event.\n */\n public void mouseEntered(MouseEvent e) {\n if (!this.ownToolTipDelaysActive) {\n ToolTipManager ttm = ToolTipManager.sharedInstance();\n this.originalToolTipInitialDelay = ttm.getInitialDelay();\n ttm.setInitialDelay(this.ownToolTipInitialDelay);\n this.originalToolTipReshowDelay = ttm.getReshowDelay();\n ttm.setReshowDelay(this.ownToolTipReshowDelay);\n this.originalToolTipDismissDelay = ttm.getDismissDelay();\n ttm.setDismissDelay(this.ownToolTipDismissDelay);\n this.ownToolTipDelaysActive = true;\n }\n }\n /**\n * Handles a 'mouse exited' event. This method resets the tooltip delays of\n * ToolTipManager.sharedInstance() to their\n * original values in effect before mouseEntered()\n *\n * @param e the mouse event.\n */\n public void mouseExited(MouseEvent e) {\n if (this.ownToolTipDelaysActive) {\n // restore original tooltip dealys\n ToolTipManager ttm = ToolTipManager.sharedInstance();\n ttm.setInitialDelay(this.originalToolTipInitialDelay);\n ttm.setReshowDelay(this.originalToolTipReshowDelay);\n ttm.setDismissDelay(this.originalToolTipDismissDelay);\n this.ownToolTipDelaysActive = false;\n }\n }\n /**\n * Handles a 'mouse pressed' event.\n *

\n * This event is the popup trigger on Unix/Linux. For Windows, the popup\n * trigger is the 'mouse released' event.\n *\n * @param e The mouse event.\n */\n public void mousePressed(MouseEvent e) {\n if (this.chart == null) {\n return;\n }\n Plot plot = this.chart.getPlot();\n int mods = e.getModifiers();\n if ((mods & this.panMask) == this.panMask) {\n // can we pan this plot?\n if (plot instanceof Pannable) {\n Pannable pannable = (Pannable) plot;\n if (pannable.isDomainPannable() || pannable.isRangePannable()) {\n Rectangle2D screenDataArea = getScreenDataArea(e.getX(),\n e.getY());\n if (screenDataArea != null && screenDataArea.contains(\n e.getPoint())) {\n this.panW = screenDataArea.getWidth();\n this.panH = screenDataArea.getHeight();\n this.panLast = e.getPoint();\n setCursor(Cursor.getPredefinedCursor(\n Cursor.MOVE_CURSOR));\n }\n }\n // the actual panning occurs later in the mouseDragged()\n // method\n }\n }\n else if (this.zoomRectangle == null) {\n Rectangle2D screenDataArea = getScreenDataArea(e.getX(), e.getY());\n if (screenDataArea != null) {\n this.zoomPoint = getPointInRectangle(e.getX(), e.getY(),\n screenDataArea);\n }\n else {\n this.zoomPoint = null;\n }\n if (e.isPopupTrigger()) {\n if (this.popup != null) {\n displayPopupMenu(e.getX(), e.getY());\n }\n }\n }\n }\n /**\n * Returns a point based on (x, y) but constrained to be within the bounds\n * of the given rectangle. This method could be moved to JCommon.\n *\n * @param x the x-coordinate.\n * @param y the y-coordinate.\n * @param area the rectangle (null not permitted).\n *\n * @return A point within the rectangle.\n */\n private Point2D getPointInRectangle(int x, int y, Rectangle2D area) {\n double xx = Math.max(area.getMinX(), Math.min(x, area.getMaxX()));\n double yy = Math.max(area.getMinY(), Math.min(y, area.getMaxY()));\n return new Point2D.Double(xx, yy);\n }\n /**\n * Handles a 'mouse dragged' event.\n *\n * @param e the mouse event.\n */\n public void mouseDragged(MouseEvent e) {\n // if the popup menu has already been triggered, then ignore dragging...\n if (this.popup != null && this.popup.isShowing()) {\n return;\n }\n // handle panning if we have a start point\n if (this.panLast != null) {\n double dx = e.getX() - this.panLast.getX();\n double dy = e.getY() - this.panLast.getY();\n if (dx == 0.0 && dy == 0.0) {\n return;\n }\n double wPercent = -dx / this.panW;\n double hPercent = dy / this.panH;\n boolean old = this.chart.getPlot().isNotify();\n this.chart.getPlot().setNotify(false);\n Pannable p = (Pannable) this.chart.getPlot();\n if (p.getOrientation() == PlotOrientation.VERTICAL) {\n p.panDomainAxes(wPercent, this.info.getPlotInfo(),\n this.panLast);\n p.panRangeAxes(hPercent, this.info.getPlotInfo(),\n this.panLast);\n }\n else {\n p.panDomainAxes(hPercent, this.info.getPlotInfo(),\n this.panLast);\n p.panRangeAxes(wPercent, this.info.getPlotInfo(),\n this.panLast);\n }\n this.panLast = e.getPoint();\n this.chart.getPlot().setNotify(old);\n return;\n }\n // if no initial zoom point was set, ignore dragging...\n if (this.zoomPoint == null) {\n return;\n }\n Graphics2D g2 = (Graphics2D) getGraphics();\n // erase the previous zoom rectangle (if any). We only need to do\n // this is we are using XOR mode, which we do when we're not using\n // the buffer (if there is a buffer, then at the end of this method we\n // just trigger a repaint)\n if (!this.useBuffer) {\n drawZoomRectangle(g2, true);\n }\n boolean hZoom = false;\n boolean vZoom = false;\n if (this.orientation == PlotOrientation.HORIZONTAL) {\n hZoom = this.rangeZoomable;\n vZoom = this.domainZoomable;\n }\n else {\n hZoom = this.domainZoomable;\n vZoom = this.rangeZoomable;\n }\n Rectangle2D scaledDataArea = getScreenDataArea(\n (int) this.zoomPoint.getX(), (int) this.zoomPoint.getY());\n if (hZoom && vZoom) {\n // selected rectangle shouldn't extend outside the data area...\n double xmax = Math.min(e.getX(), scaledDataArea.getMaxX());\n double ymax = Math.min(e.getY(), scaledDataArea.getMaxY());\n this.zoomRectangle = new Rectangle2D.Double(\n this.zoomPoint.getX(), this.zoomPoint.getY(),\n xmax - this.zoomPoint.getX(), ymax - this.zoomPoint.getY());\n }\n else if (hZoom) {\n double xmax = Math.min(e.getX(), scaledDataArea.getMaxX());\n this.zoomRectangle = new Rectangle2D.Double(\n this.zoomPoint.getX(), scaledDataArea.getMinY(),\n xmax - this.zoomPoint.getX(), scaledDataArea.getHeight());\n }\n else if (vZoom) {\n double ymax = Math.min(e.getY(), scaledDataArea.getMaxY());\n this.zoomRectangle = new Rectangle2D.Double(\n scaledDataArea.getMinX(), this.zoomPoint.getY(),\n scaledDataArea.getWidth(), ymax - this.zoomPoint.getY());\n }\n // Draw the new zoom rectangle...\n if (this.useBuffer) {\n repaint();\n }\n else {\n // with no buffer, we use XOR to draw the rectangle \"over\" the\n // chart...\n drawZoomRectangle(g2, true);\n }\n g2.dispose();\n }\n /**\n * Handles a 'mouse released' event. On Windows, we need to check if this\n * is a popup trigger, but only if we haven't already been tracking a zoom\n * rectangle.\n *\n * @param e information about the event.\n */\n public void mouseReleased(MouseEvent e) {\n // if we've been panning, we need to reset now that the mouse is\n // released...\n if (this.panLast != null) {\n this.panLast = null;\n setCursor(Cursor.getDefaultCursor());\n }\n else if (this.zoomRectangle != null) {\n boolean hZoom = false;\n boolean vZoom = false;\n if (this.orientation == PlotOrientation.HORIZONTAL) {\n hZoom = this.rangeZoomable;\n vZoom = this.domainZoomable;\n }\n else {\n hZoom = this.domainZoomable;\n vZoom = this.rangeZoomable;\n }\n boolean zoomTrigger1 = hZoom && Math.abs(e.getX()\n - this.zoomPoint.getX()) >= this.zoomTriggerDistance;\n boolean zoomTrigger2 = vZoom && Math.abs(e.getY()\n - this.zoomPoint.getY()) >= this.zoomTriggerDistance;\n if (zoomTrigger1 || zoomTrigger2) {\n if ((hZoom && (e.getX() < this.zoomPoint.getX()))\n || (vZoom && (e.getY() < this.zoomPoint.getY()))) {\n restoreAutoBounds();\n }\n else {\n double x, y, w, h;\n Rectangle2D screenDataArea = getScreenDataArea(\n (int) this.zoomPoint.getX(),\n (int) this.zoomPoint.getY());\n double maxX = screenDataArea.getMaxX();\n double maxY = screenDataArea.getMaxY();\n // for mouseReleased event, (horizontalZoom || verticalZoom)\n // will be true, so we can just test for either being false;\n // otherwise both are true\n if (!vZoom) {\n x = this.zoomPoint.getX();\n y = screenDataArea.getMinY();\n w = Math.min(this.zoomRectangle.getWidth(),\n maxX - this.zoomPoint.getX());\n h = screenDataArea.getHeight();\n }\n else if (!hZoom) {\n x = screenDataArea.getMinX();\n y = this.zoomPoint.getY();\n w = screenDataArea.getWidth();\n h = Math.min(this.zoomRectangle.getHeight(),\n maxY - this.zoomPoint.getY());\n }\n else {\n x = this.zoomPoint.getX();\n y = this.zoomPoint.getY();\n w = Math.min(this.zoomRectangle.getWidth(),\n maxX - this.zoomPoint.getX());\n h = Math.min(this.zoomRectangle.getHeight(),\n maxY - this.zoomPoint.getY());\n }\n Rectangle2D zoomArea = new Rectangle2D.Double(x, y, w, h);\n zoom(zoomArea);\n }\n this.zoomPoint = null;\n this.zoomRectangle = null;\n }\n else {\n // erase the zoom rectangle\n Graphics2D g2 = (Graphics2D) getGraphics();\n if (this.useBuffer) {\n repaint();\n }\n else {\n drawZoomRectangle(g2, true);\n }\n g2.dispose();\n this.zoomPoint = null;\n this.zoomRectangle = null;\n }\n }\n else if (e.isPopupTrigger()) {\n if (this.popup != null) {\n displayPopupMenu(e.getX(), e.getY());\n }\n }\n }\n /**\n * Receives notification of mouse clicks on the panel. These are\n * translated and passed on to any registered {@link ChartMouseListener}s.\n *\n * @param event Information about the mouse event.\n */\n public void mouseClicked(MouseEvent event) {\n Insets insets = getInsets();\n int x = (int) ((event.getX() - insets.left) / this.scaleX);\n int y = (int) ((event.getY() - insets.top) / this.scaleY);\n this.anchor = new Point2D.Double(x, y);\n if (this.chart == null) {\n return;\n }\n this.chart.setNotify(true); // force a redraw\n // new entity code...\n Object[] listeners = this.chartMouseListeners.getListeners(\n ChartMouseListener.class);\n if (listeners.length == 0) {\n return;\n }\n ChartEntity entity = null;\n if (this.info != null) {\n EntityCollection entities = this.info.getEntityCollection();\n if (entities != null) {\n entity = entities.getEntity(x, y);\n }\n }\n ChartMouseEvent chartEvent = new ChartMouseEvent(getChart(), event,\n entity);\n for (int i = listeners.length - 1; i >= 0; i -= 1) {\n ((ChartMouseListener) listeners[i]).chartMouseClicked(chartEvent);\n }\n }\n /**\n * Implementation of the MouseMotionListener's method.\n *\n * @param e the event.\n */\n public void mouseMoved(MouseEvent e) {\n Graphics2D g2 = (Graphics2D) getGraphics();\n if (this.horizontalAxisTrace) {\n drawHorizontalAxisTrace(g2, e.getX());\n }\n if (this.verticalAxisTrace) {\n drawVerticalAxisTrace(g2, e.getY());\n }\n g2.dispose();\n Object[] listeners = this.chartMouseListeners.getListeners(\n ChartMouseListener.class);\n if (listeners.length == 0) {\n return;\n }\n Insets insets = getInsets();\n int x = (int) ((e.getX() - insets.left) / this.scaleX);\n int y = (int) ((e.getY() - insets.top) / this.scaleY);\n ChartEntity entity = null;\n if (this.info != null) {\n EntityCollection entities = this.info.getEntityCollection();\n if (entities != null) {\n entity = entities.getEntity(x, y);\n }\n }\n // we can only generate events if the panel's chart is not null\n // (see bug report 1556951)\n if (this.chart != null) {\n ChartMouseEvent event = new ChartMouseEvent(getChart(), e, entity);\n for (int i = listeners.length - 1; i >= 0; i -= 1) {\n ((ChartMouseListener) listeners[i]).chartMouseMoved(event);\n }\n }\n }\n /**\n * Zooms in on an anchor point (specified in screen coordinate space).\n *\n * @param x the x value (in screen coordinates).\n * @param y the y value (in screen coordinates).\n */\n public void zoomInBoth(double x, double y) {\n Plot plot = this.chart.getPlot();\n if (plot == null) {\n return;\n }\n // here we tweak the notify flag on the plot so that only\n // one notification happens even though we update multiple\n // axes...\n boolean savedNotify = plot.isNotify();\n plot.setNotify(false);\n zoomInDomain(x, y);\n zoomInRange(x, y);\n plot.setNotify(savedNotify);\n }\n /**\n * Decreases the length of the domain axis, centered about the given\n * coordinate on the screen. The length of the domain axis is reduced\n * by the value of {@link #getZoomInFactor()}.\n *\n * @param x the x coordinate (in screen coordinates).\n * @param y the y-coordinate (in screen coordinates).\n */\n public void zoomInDomain(double x, double y) {\n Plot plot = this.chart.getPlot();\n if (plot instanceof Zoomable) {\n // here we tweak the notify flag on the plot so that only\n // one notification happens even though we update multiple\n // axes...\n boolean savedNotify = plot.isNotify();\n plot.setNotify(false);\n Zoomable z = (Zoomable) plot;\n z.zoomDomainAxes(this.zoomInFactor, this.info.getPlotInfo(),\n translateScreenToJava2D(new Point((int) x, (int) y)),\n this.zoomAroundAnchor);\n plot.setNotify(savedNotify);\n }\n }\n /**\n * Decreases the length of the range axis, centered about the given\n * coordinate on the screen. The length of the range axis is reduced by\n * the value of {@link #getZoomInFactor()}.\n *\n * @param x the x-coordinate (in screen coordinates).\n * @param y the y coordinate (in screen coordinates).\n */\n public void zoomInRange(double x, double y) {\n Plot plot = this.chart.getPlot();\n if (plot instanceof Zoomable) {\n // here we tweak the notify flag on the plot so that only\n // one notification happens even though we update multiple\n // axes...\n boolean savedNotify = plot.isNotify();\n plot.setNotify(false);\n Zoomable z = (Zoomable) plot;\n z.zoomRangeAxes(this.zoomInFactor, this.info.getPlotInfo(),\n translateScreenToJava2D(new Point((int) x, (int) y)),\n this.zoomAroundAnchor);\n plot.setNotify(savedNotify);\n }\n }\n /**\n * Zooms out on an anchor point (specified in screen coordinate space).\n *\n * @param x the x value (in screen coordinates).\n * @param y the y value (in screen coordinates).\n */\n public void zoomOutBoth(double x, double y) {\n Plot plot = this.chart.getPlot();\n if (plot == null) {\n return;\n }\n // here we tweak the notify flag on the plot so that only\n // one notification happens even though we update multiple\n // axes...\n boolean savedNotify = plot.isNotify();\n plot.setNotify(false);\n zoomOutDomain(x, y);\n zoomOutRange(x, y);\n plot.setNotify(savedNotify);\n }\n /**\n * Increases the length of the domain axis, centered about the given\n * coordinate on the screen. The length of the domain axis is increased\n * by the value of {@link #getZoomOutFactor()}.\n *\n * @param x the x coordinate (in screen coordinates).\n * @param y the y-coordinate (in screen coordinates).\n */\n public void zoomOutDomain(double x, double y) {\n Plot plot = this.chart.getPlot();\n if (plot instanceof Zoomable) {\n // here we tweak the notify flag on the plot so that only\n // one notification happens even though we update multiple\n // axes...\n boolean savedNotify = plot.isNotify();\n plot.setNotify(false);\n Zoomable z = (Zoomable) plot;\n z.zoomDomainAxes(this.zoomOutFactor, this.info.getPlotInfo(),\n translateScreenToJava2D(new Point((int) x, (int) y)),\n this.zoomAroundAnchor);\n plot.setNotify(savedNotify);\n }\n }\n /**\n * Increases the length the range axis, centered about the given\n * coordinate on the screen. The length of the range axis is increased\n * by the value of {@link #getZoomOutFactor()}.\n *\n * @param x the x coordinate (in screen coordinates).\n * @param y the y-coordinate (in screen coordinates).\n */\n public void zoomOutRange(double x, double y) {\n Plot plot = this.chart.getPlot();\n if (plot instanceof Zoomable) {\n // here we tweak the notify flag on the plot so that only\n // one notification happens even though we update multiple\n // axes...\n boolean savedNotify = plot.isNotify();\n plot.setNotify(false);\n Zoomable z = (Zoomable) plot;\n z.zoomRangeAxes(this.zoomOutFactor, this.info.getPlotInfo(),\n translateScreenToJava2D(new Point((int) x, (int) y)),\n this.zoomAroundAnchor);\n plot.setNotify(savedNotify);\n }\n }\n /**\n * Zooms in on a selected region.\n *\n * @param selection the selected region.\n */\n public void zoom(Rectangle2D selection) {\n // get the origin of the zoom selection in the Java2D space used for\n // drawing the chart (that is, before any scaling to fit the panel)\n Point2D selectOrigin = translateScreenToJava2D(new Point(\n (int) Math.ceil(selection.getX()),\n (int) Math.ceil(selection.getY())));\n PlotRenderingInfo plotInfo = this.info.getPlotInfo();\n Rectangle2D scaledDataArea = getScreenDataArea(\n (int) selection.getCenterX(), (int) selection.getCenterY());\n if ((selection.getHeight() > 0) && (selection.getWidth() > 0)) {\n double hLower = (selection.getMinX() - scaledDataArea.getMinX())\n / scaledDataArea.getWidth();\n double hUpper = (selection.getMaxX() - scaledDataArea.getMinX())\n / scaledDataArea.getWidth();\n double vLower = (scaledDataArea.getMaxY() - selection.getMaxY())\n / scaledDataArea.getHeight();\n double vUpper = (scaledDataArea.getMaxY() - selection.getMinY())\n / scaledDataArea.getHeight();\n Plot p = this.chart.getPlot();\n if (p instanceof Zoomable) {\n // here we tweak the notify flag on the plot so that only\n // one notification happens even though we update multiple\n // axes...\n boolean savedNotify = p.isNotify();\n p.setNotify(false);\n Zoomable z = (Zoomable) p;\n if (z.getOrientation() == PlotOrientation.HORIZONTAL) {\n z.zoomDomainAxes(vLower, vUpper, plotInfo, selectOrigin);\n z.zoomRangeAxes(hLower, hUpper, plotInfo, selectOrigin);\n }\n else {\n z.zoomDomainAxes(hLower, hUpper, plotInfo, selectOrigin);\n z.zoomRangeAxes(vLower, vUpper, plotInfo, selectOrigin);\n }\n p.setNotify(savedNotify);\n }\n }\n }\n /**\n * Restores the auto-range calculation on both axes.\n */\n public void restoreAutoBounds() {\n Plot plot = this.chart.getPlot();\n if (plot == null) {\n return;\n }\n // here we tweak the notify flag on the plot so that only\n // one notification happens even though we update multiple\n // axes...\n boolean savedNotify = plot.isNotify();\n plot.setNotify(false);\n restoreAutoDomainBounds();\n restoreAutoRangeBounds();\n plot.setNotify(savedNotify);\n }\n /**\n * Restores the auto-range calculation on the domain axis.\n */\n public void restoreAutoDomainBounds() {\n Plot plot = this.chart.getPlot();\n if (plot instanceof Zoomable) {\n Zoomable z = (Zoomable) plot;\n // here we tweak the notify flag on the plot so that only\n // one notification happens even though we update multiple\n // axes...\n boolean savedNotify = plot.isNotify();\n plot.setNotify(false);\n // we need to guard against this.zoomPoint being null\n Point2D zp = (this.zoomPoint != null\n ? this.zoomPoint : new Point());\n z.zoomDomainAxes(0.0, this.info.getPlotInfo(), zp);\n plot.setNotify(savedNotify);\n }\n }\n /**\n * Restores the auto-range calculation on the range axis.\n */\n public void restoreAutoRangeBounds() {\n Plot plot = this.chart.getPlot();\n if (plot instanceof Zoomable) {\n Zoomable z = (Zoomable) plot;\n // here we tweak the notify flag on the plot so that only\n // one notification happens even though we update multiple\n // axes...\n boolean savedNotify = plot.isNotify();\n plot.setNotify(false);\n // we need to guard against this.zoomPoint being null\n Point2D zp = (this.zoomPoint != null\n ? this.zoomPoint : new Point());\n z.zoomRangeAxes(0.0, this.info.getPlotInfo(), zp);\n plot.setNotify(savedNotify);\n }\n }\n /**\n * Returns the data area for the chart (the area inside the axes) with the\n * current scaling applied (that is, the area as it appears on screen).\n *\n * @return The scaled data area.\n */\n public Rectangle2D getScreenDataArea() {\n Rectangle2D dataArea = this.info.getPlotInfo().getDataArea();\n Insets insets = getInsets();\n double x = dataArea.getX() * this.scaleX + insets.left;\n double y = dataArea.getY() * this.scaleY + insets.top;\n double w = dataArea.getWidth() * this.scaleX;\n double h = dataArea.getHeight() * this.scaleY;\n return new Rectangle2D.Double(x, y, w, h);\n }\n /**\n * Returns the data area (the area inside the axes) for the plot or subplot,\n * with the current scaling applied.\n *\n * @param x the x-coordinate (for subplot selection).\n * @param y the y-coordinate (for subplot selection).\n *\n * @return The scaled data area.\n */\n public Rectangle2D getScreenDataArea(int x, int y) {\n PlotRenderingInfo plotInfo = this.info.getPlotInfo();\n Rectangle2D result;\n if (plotInfo.getSubplotCount() == 0) {\n result = getScreenDataArea();\n }\n else {\n // get the origin of the zoom selection in the Java2D space used for\n // drawing the chart (that is, before any scaling to fit the panel)\n Point2D selectOrigin = translateScreenToJava2D(new Point(x, y));\n int subplotIndex = plotInfo.getSubplotIndex(selectOrigin);\n if (subplotIndex == -1) {\n return null;\n }\n result = scale(plotInfo.getSubplotInfo(subplotIndex).getDataArea());\n }\n return result;\n }\n /**\n * Returns the initial tooltip delay value used inside this chart panel.\n *\n * @return An integer representing the initial delay value, in milliseconds.\n *\n * @see javax.swing.ToolTipManager#getInitialDelay()\n */\n public int getInitialDelay() {\n return this.ownToolTipInitialDelay;\n }\n /**\n * Returns the reshow tooltip delay value used inside this chart panel.\n *\n * @return An integer representing the reshow delay value, in milliseconds.\n *\n * @see javax.swing.ToolTipManager#getReshowDelay()\n */\n public int getReshowDelay() {\n return this.ownToolTipReshowDelay;\n }\n /**\n * Returns the dismissal tooltip delay value used inside this chart panel.\n *\n * @return An integer representing the dismissal delay value, in\n * milliseconds.\n *\n * @see javax.swing.ToolTipManager#getDismissDelay()\n */\n public int getDismissDelay() {\n return this.ownToolTipDismissDelay;\n }\n /**\n * Specifies the initial delay value for this chart panel.\n *\n * @param delay the number of milliseconds to delay (after the cursor has\n * paused) before displaying.\n *\n * @see javax.swing.ToolTipManager#setInitialDelay(int)\n */\n public void setInitialDelay(int delay) {\n this.ownToolTipInitialDelay = delay;\n }\n /**\n * Specifies the amount of time before the user has to wait initialDelay\n * milliseconds before a tooltip will be shown.\n *\n * @param delay time in milliseconds\n *\n * @see javax.swing.ToolTipManager#setReshowDelay(int)\n */\n public void setReshowDelay(int delay) {\n this.ownToolTipReshowDelay = delay;\n }\n /**\n * Specifies the dismissal delay value for this chart panel.\n *\n * @param delay the number of milliseconds to delay before taking away the\n * tooltip\n *\n * @see javax.swing.ToolTipManager#setDismissDelay(int)\n */\n public void setDismissDelay(int delay) {\n this.ownToolTipDismissDelay = delay;\n }\n /**\n * Returns the zoom in factor.\n *\n * @return The zoom in factor.\n *\n * @see #setZoomInFactor(double)\n */\n public double getZoomInFactor() {\n return this.zoomInFactor;\n }\n /**\n * Sets the zoom in factor.\n *\n * @param factor the factor.\n *\n * @see #getZoomInFactor()\n */\n public void setZoomInFactor(double factor) {\n this.zoomInFactor = factor;\n }\n /**\n * Returns the zoom out factor.\n *\n * @return The zoom out factor.\n *\n * @see #setZoomOutFactor(double)\n */\n public double getZoomOutFactor() {\n return this.zoomOutFactor;\n }\n /**\n * Sets the zoom out factor.\n *\n * @param factor the factor.\n *\n * @see #getZoomOutFactor()\n */\n public void setZoomOutFactor(double factor) {\n this.zoomOutFactor = factor;\n }\n /**\n * Draws zoom rectangle (if present).\n * The drawing is performed in XOR mode, therefore\n * when this method is called twice in a row,\n * the second call will completely restore the state\n * of the canvas.\n *\n * @param g2 the graphics device.\n * @param xor use XOR for drawing?\n */\n private void drawZoomRectangle(Graphics2D g2, boolean xor) {\n if (this.zoomRectangle != null) {\n if (xor) {\n // Set XOR mode to draw the zoom rectangle\n g2.setXORMode(Color.gray);\n }\n if (this.fillZoomRectangle) {\n g2.setPaint(this.zoomFillPaint);\n g2.fill(this.zoomRectangle);\n }\n else {\n g2.setPaint(this.zoomOutlinePaint);\n g2.draw(this.zoomRectangle);\n }\n if (xor) {\n // Reset to the default 'overwrite' mode\n g2.setPaintMode();\n }\n }\n }\n /**\n * Draws a vertical line used to trace the mouse position to the horizontal\n * axis.\n *\n * @param g2 the graphics device.\n * @param x the x-coordinate of the trace line.\n */\n private void drawHorizontalAxisTrace(Graphics2D g2, int x) {\n Rectangle2D dataArea = getScreenDataArea();\n g2.setXORMode(Color.orange);\n if (((int) dataArea.getMinX() < x) && (x < (int) dataArea.getMaxX())) {\n if (this.verticalTraceLine != null) {\n g2.draw(this.verticalTraceLine);\n this.verticalTraceLine.setLine(x, (int) dataArea.getMinY(), x,\n (int) dataArea.getMaxY());\n }\n else {\n this.verticalTraceLine = new Line2D.Float(x,\n (int) dataArea.getMinY(), x, (int) dataArea.getMaxY());\n }\n g2.draw(this.verticalTraceLine);\n }\n // Reset to the default 'overwrite' mode\n g2.setPaintMode();\n }\n /**\n * Draws a horizontal line used to trace the mouse position to the vertical\n * axis.\n *\n * @param g2 the graphics device.\n * @param y the y-coordinate of the trace line.\n */\n private void drawVerticalAxisTrace(Graphics2D g2, int y) {\n Rectangle2D dataArea = getScreenDataArea();\n g2.setXORMode(Color.orange);\n if (((int) dataArea.getMinY() < y) && (y < (int) dataArea.getMaxY())) {\n if (this.horizontalTraceLine != null) {\n g2.draw(this.horizontalTraceLine);\n this.horizontalTraceLine.setLine((int) dataArea.getMinX(), y,\n (int) dataArea.getMaxX(), y);\n }\n else {\n this.horizontalTraceLine = new Line2D.Float(\n (int) dataArea.getMinX(), y, (int) dataArea.getMaxX(),\n y);\n }\n g2.draw(this.horizontalTraceLine);\n }\n // Reset to the default 'overwrite' mode\n g2.setPaintMode();\n }\n /**\n * Displays a dialog that allows the user to edit the properties for the\n * current chart.\n *\n * @since 1.0.3\n */\n public void doEditChartProperties() {\n ChartEditor editor = ChartEditorManager.getChartEditor(this.chart);\n int result = JOptionPane.showConfirmDialog(this, editor,\n localizationResources.getString(\"Chart_Properties\"),\n JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);\n if (result == JOptionPane.OK_OPTION) {\n editor.updateChart(this.chart);\n }\n }\n /**\n * Copies the current chart to the system clipboard.\n *\n * @since 1.0.13\n */\n public void doCopy() {\n Clipboard systemClipboard\n = Toolkit.getDefaultToolkit().getSystemClipboard();\n Insets insets = getInsets();\n int w = getWidth() - insets.left - insets.right;\n int h = getHeight() - insets.top - insets.bottom;\n ChartTransferable selection = new ChartTransferable(this.chart, w, h,\n getMinimumDrawWidth(), getMinimumDrawHeight(),\n getMaximumDrawWidth(), getMaximumDrawHeight(), true);\n systemClipboard.setContents(selection, null);\n }\n /**\n * Opens a file chooser and gives the user an opportunity to save the chart\n * in PNG format.\n *\n * @throws IOException if there is an I/O error.\n */\n public void doSaveAs() throws IOException {\n JFileChooser fileChooser = new JFileChooser();\n fileChooser.setCurrentDirectory(this.defaultDirectoryForSaveAs);\n ExtensionFileFilter filter = new ExtensionFileFilter(\n localizationResources.getString(\"PNG_Image_Files\"), \".png\");\n fileChooser.addChoosableFileFilter(filter);\n int option = fileChooser.showSaveDialog(this);\n if (option == JFileChooser.APPROVE_OPTION) {\n String filename = fileChooser.getSelectedFile().getPath();\n if (isEnforceFileExtensions()) {\n if (!filename.endsWith(\".png\")) {\n filename = filename + \".png\";\n }\n }\n ChartUtilities.saveChartAsPNG(new File(filename), this.chart,\n getWidth(), getHeight());\n }\n }\n /**\n * Creates a print job for the chart.\n */\n public void createChartPrintJob() {\n PrinterJob job = PrinterJob.getPrinterJob();\n PageFormat pf = job.defaultPage();\n PageFormat pf2 = job.pageDialog(pf);\n if (pf2 != pf) {\n job.setPrintable(this, pf2);\n if (job.printDialog()) {\n try {\n job.print();\n }\n catch (PrinterException e) {\n JOptionPane.showMessageDialog(this, e);\n }\n }\n }\n }\n /**\n * Prints the chart on a single page.\n *\n * @param g the graphics context.\n * @param pf the page format to use.\n * @param pageIndex the index of the page. If not 0, nothing\n * gets print.\n *\n * @return The result of printing.\n */\n public int print(Graphics g, PageFormat pf, int pageIndex) {\n if (pageIndex != 0) {\n return NO_SUCH_PAGE;\n }\n Graphics2D g2 = (Graphics2D) g;\n double x = pf.getImageableX();\n double y = pf.getImageableY();\n double w = pf.getImageableWidth();\n double h = pf.getImageableHeight();\n this.chart.draw(g2, new Rectangle2D.Double(x, y, w, h), this.anchor,\n null);\n return PAGE_EXISTS;\n }\n /**\n * Adds a listener to the list of objects listening for chart mouse events.\n *\n * @param listener the listener (null not permitted).\n */\n public void addChartMouseListener(ChartMouseListener listener) {\n if (listener == null) {\n throw new IllegalArgumentException(\"Null 'listener' argument.\");\n }\n this.chartMouseListeners.add(ChartMouseListener.class, listener);\n }\n /**\n * Removes a listener from the list of objects listening for chart mouse\n * events.\n *\n * @param listener the listener.\n */\n public void removeChartMouseListener(ChartMouseListener listener) {\n this.chartMouseListeners.remove(ChartMouseListener.class, listener);\n }\n /**\n * Returns an array of the listeners of the given type registered with the\n * panel.\n *\n * @param listenerType the listener type.\n *\n * @return An array of listeners.\n */\n public EventListener[] getListeners(Class listenerType) {\n if (listenerType == ChartMouseListener.class) {\n // fetch listeners from local storage\n return this.chartMouseListeners.getListeners(listenerType);\n }\n else {\n return super.getListeners(listenerType);\n }\n }\n /**\n * Creates a popup menu for the panel.\n *\n * @param properties include a menu item for the chart property editor.\n * @param save include a menu item for saving the chart.\n * @param print include a menu item for printing the chart.\n * @param zoom include menu items for zooming.\n *\n * @return The popup menu.\n */\n protected JPopupMenu createPopupMenu(boolean properties, boolean save,\n boolean print, boolean zoom) {\n return createPopupMenu(properties, false, save, print, zoom);\n }\n /**\n * Creates a popup menu for the panel.\n *\n * @param properties include a menu item for the chart property editor.\n * @param copy include a menu item for copying to the clipboard.\n * @param save include a menu item for saving the chart.\n * @param print include a menu item for printing the chart.\n * @param zoom include menu items for zooming.\n *\n * @return The popup menu.\n *\n * @since 1.0.13\n */\n protected JPopupMenu createPopupMenu(boolean properties,\n boolean copy, boolean save, boolean print, boolean zoom) {\n JPopupMenu result = new JPopupMenu(localizationResources.getString(\"Chart\") + \":\");\n boolean separator = false;\n if (properties) {\n JMenuItem propertiesItem = new JMenuItem(\n localizationResources.getString(\"Properties...\"));\n propertiesItem.setActionCommand(PROPERTIES_COMMAND);\n propertiesItem.addActionListener(this);\n result.add(propertiesItem);\n separator = true;\n }\n if (copy) {\n if (separator) {\n result.addSeparator();\n separator = false;\n }\n JMenuItem copyItem = new JMenuItem(\n localizationResources.getString(\"Copy\"));\n copyItem.setActionCommand(COPY_COMMAND);\n copyItem.addActionListener(this);\n result.add(copyItem);\n separator = !save;\n }\n if (save) {\n if (separator) {\n result.addSeparator();\n separator = false;\n }\n JMenuItem saveItem = new JMenuItem(\n localizationResources.getString(\"Save_as...\"));\n saveItem.setActionCommand(SAVE_COMMAND);\n saveItem.addActionListener(this);\n result.add(saveItem);\n separator = true;\n }\n if (print) {\n if (separator) {\n result.addSeparator();\n separator = false;\n }\n JMenuItem printItem = new JMenuItem(\n localizationResources.getString(\"Print...\"));\n printItem.setActionCommand(PRINT_COMMAND);\n printItem.addActionListener(this);\n result.add(printItem);\n separator = true;\n }\n if (zoom) {\n if (separator) {\n result.addSeparator();\n separator = false;\n }\n JMenu zoomInMenu = new JMenu(\n localizationResources.getString(\"Zoom_In\"));\n this.zoomInBothMenuItem = new JMenuItem(\n localizationResources.getString(\"All_Axes\"));\n this.zoomInBothMenuItem.setActionCommand(ZOOM_IN_BOTH_COMMAND);\n this.zoomInBothMenuItem.addActionListener(this);\n zoomInMenu.add(this.zoomInBothMenuItem);\n zoomInMenu.addSeparator();\n this.zoomInDomainMenuItem = new JMenuItem(\n localizationResources.getString(\"Domain_Axis\"));\n this.zoomInDomainMenuItem.setActionCommand(ZOOM_IN_DOMAIN_COMMAND);\n this.zoomInDomainMenuItem.addActionListener(this);\n zoomInMenu.add(this.zoomInDomainMenuItem);\n this.zoomInRangeMenuItem = new JMenuItem(\n localizationResources.getString(\"Range_Axis\"));\n this.zoomInRangeMenuItem.setActionCommand(ZOOM_IN_RANGE_COMMAND);\n this.zoomInRangeMenuItem.addActionListener(this);\n zoomInMenu.add(this.zoomInRangeMenuItem);\n result.add(zoomInMenu);\n JMenu zoomOutMenu = new JMenu(\n localizationResources.getString(\"Zoom_Out\"));\n this.zoomOutBothMenuItem = new JMenuItem(\n localizationResources.getString(\"All_Axes\"));\n this.zoomOutBothMenuItem.setActionCommand(ZOOM_OUT_BOTH_COMMAND);\n this.zoomOutBothMenuItem.addActionListener(this);\n zoomOutMenu.add(this.zoomOutBothMenuItem);\n zoomOutMenu.addSeparator();\n this.zoomOutDomainMenuItem = new JMenuItem(\n localizationResources.getString(\"Domain_Axis\"));\n this.zoomOutDomainMenuItem.setActionCommand(\n ZOOM_OUT_DOMAIN_COMMAND);\n this.zoomOutDomainMenuItem.addActionListener(this);\n zoomOutMenu.add(this.zoomOutDomainMenuItem);\n this.zoomOutRangeMenuItem = new JMenuItem(\n localizationResources.getString(\"Range_Axis\"));\n this.zoomOutRangeMenuItem.setActionCommand(ZOOM_OUT_RANGE_COMMAND);\n this.zoomOutRangeMenuItem.addActionListener(this);\n zoomOutMenu.add(this.zoomOutRangeMenuItem);\n result.add(zoomOutMenu);\n JMenu autoRangeMenu = new JMenu(\n localizationResources.getString(\"Auto_Range\"));\n this.zoomResetBothMenuItem = new JMenuItem(\n localizationResources.getString(\"All_Axes\"));\n this.zoomResetBothMenuItem.setActionCommand(\n ZOOM_RESET_BOTH_COMMAND);\n this.zoomResetBothMenuItem.addActionListener(this);\n autoRangeMenu.add(this.zoomResetBothMenuItem);\n autoRangeMenu.addSeparator();\n this.zoomResetDomainMenuItem = new JMenuItem(\n localizationResources.getString(\"Domain_Axis\"));\n this.zoomResetDomainMenuItem.setActionCommand(\n ZOOM_RESET_DOMAIN_COMMAND);\n this.zoomResetDomainMenuItem.addActionListener(this);\n autoRangeMenu.add(this.zoomResetDomainMenuItem);\n this.zoomResetRangeMenuItem = new JMenuItem(\n localizationResources.getString(\"Range_Axis\"));\n this.zoomResetRangeMenuItem.setActionCommand(\n ZOOM_RESET_RANGE_COMMAND);\n this.zoomResetRangeMenuItem.addActionListener(this);\n autoRangeMenu.add(this.zoomResetRangeMenuItem);\n result.addSeparator();\n result.add(autoRangeMenu);\n }\n return result;\n }\n /**\n * The idea is to modify the zooming options depending on the type of chart\n * being displayed by the panel.\n *\n * @param x horizontal position of the popup.\n * @param y vertical position of the popup.\n */\n protected void displayPopupMenu(int x, int y) {\n if (this.popup == null) {\n return;\n }\n // go through each zoom menu item and decide whether or not to\n // enable it...\n boolean isDomainZoomable = false;\n boolean isRangeZoomable = false;\n Plot plot = (this.chart != null ? this.chart.getPlot() : null);\n if (plot instanceof Zoomable) {\n Zoomable z = (Zoomable) plot;\n isDomainZoomable = z.isDomainZoomable();\n isRangeZoomable = z.isRangeZoomable();\n }\n if (this.zoomInDomainMenuItem != null) {\n this.zoomInDomainMenuItem.setEnabled(isDomainZoomable);\n }\n if (this.zoomOutDomainMenuItem != null) {\n this.zoomOutDomainMenuItem.setEnabled(isDomainZoomable);\n }\n if (this.zoomResetDomainMenuItem != null) {\n this.zoomResetDomainMenuItem.setEnabled(isDomainZoomable);\n }\n if (this.zoomInRangeMenuItem != null) {\n this.zoomInRangeMenuItem.setEnabled(isRangeZoomable);\n }\n if (this.zoomOutRangeMenuItem != null) {\n this.zoomOutRangeMenuItem.setEnabled(isRangeZoomable);\n }\n if (this.zoomResetRangeMenuItem != null) {\n this.zoomResetRangeMenuItem.setEnabled(isRangeZoomable);\n }\n if (this.zoomInBothMenuItem != null) {\n this.zoomInBothMenuItem.setEnabled(isDomainZoomable\n && isRangeZoomable);\n }\n if (this.zoomOutBothMenuItem != null) {\n this.zoomOutBothMenuItem.setEnabled(isDomainZoomable\n && isRangeZoomable);\n }\n if (this.zoomResetBothMenuItem != null) {\n this.zoomResetBothMenuItem.setEnabled(isDomainZoomable\n && isRangeZoomable);\n }\n this.popup.show(this, x, y);\n }\n /**\n * Updates the UI for a LookAndFeel change.\n */\n public void updateUI() {\n // here we need to update the UI for the popup menu, if the panel\n // has one...\n if (this.popup != null) {\n SwingUtilities.updateComponentTreeUI(this.popup);\n }\n super.updateUI();\n }\n /**\n * Provides serialization support.\n *\n * @param stream the output stream.\n *\n * @throws IOException if there is an I/O error.\n */\n private void writeObject(ObjectOutputStream stream) throws IOException {\n stream.defaultWriteObject();\n SerialUtilities.writePaint(this.zoomFillPaint, stream);\n SerialUtilities.writePaint(this.zoomOutlinePaint, stream);\n }\n /**\n * Provides serialization support.\n *\n * @param stream the input stream.\n *\n * @throws IOException if there is an I/O error.\n * @throws ClassNotFoundException if there is a classpath problem.\n */\n private void readObject(ObjectInputStream stream)\n throws IOException, ClassNotFoundException {\n stream.defaultReadObject();\n this.zoomFillPaint = SerialUtilities.readPaint(stream);\n this.zoomOutlinePaint = SerialUtilities.readPaint(stream);\n // we create a new but empty chartMouseListeners list\n this.chartMouseListeners = new EventListenerList();\n // register as a listener with sub-components...\n if (this.chart != null) {\n this.chart.addChangeListener(this);\n }\n }\n}"}}},{"rowIdx":346237,"cells":{"answer":{"kind":"string","value":"package VASSAL.counters;\nimport VASSAL.build.GameModule;\nimport VASSAL.build.module.Chatter;\nimport VASSAL.build.module.Map;\nimport VASSAL.build.module.documentation.HelpFile;\nimport VASSAL.build.module.properties.PropertySource;\nimport VASSAL.command.ChangeTracker;\nimport VASSAL.command.Command;\nimport VASSAL.configure.BooleanConfigurer;\nimport VASSAL.configure.NamedKeyStrokeArrayConfigurer;\nimport VASSAL.configure.PlayerIdFormattedExpressionConfigurer;\nimport VASSAL.configure.StringArrayConfigurer;\nimport VASSAL.configure.StringConfigurer;\nimport VASSAL.i18n.PieceI18nData;\nimport VASSAL.i18n.Resources;\nimport VASSAL.i18n.TranslatablePiece;\nimport VASSAL.script.expression.AuditTrail;\nimport VASSAL.search.HTMLImageFinder;\nimport VASSAL.tools.FormattedString;\nimport VASSAL.tools.NamedKeyStroke;\nimport VASSAL.tools.ProblemDialog;\nimport VASSAL.tools.SequenceEncoder;\nimport java.awt.Component;\nimport java.awt.Graphics;\nimport java.awt.Rectangle;\nimport java.awt.Shape;\nimport java.awt.event.InputEvent;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Objects;\nimport javax.swing.JLabel;\nimport javax.swing.KeyStroke;\nimport org.apache.commons.lang3.ArrayUtils;\n/**\n * d/b/a \"Report Action\"\n *\n * A GamePiece with this trait will echo the piece's current name when any of a given key commands are pressed\n * (and after they take effect)\n */\npublic class ReportState extends Decorator implements TranslatablePiece {\n public static final String ID = \"report;\"; // NON-NLS\n protected NamedKeyStroke[] keys;\n protected FormattedString format = new FormattedString();\n protected String reportFormat;\n protected String[] cycleReportFormat;\n protected NamedKeyStroke[] cycleDownKeys;\n protected int cycleIndex = -1;\n protected String description;\n protected boolean noSuppress;\n public ReportState() {\n this(ID, null);\n }\n public ReportState(String type, GamePiece inner) {\n mySetType(type);\n setInner(inner);\n }\n @Override\n public Rectangle boundingBox() {\n return piece.boundingBox();\n }\n @Override\n public void draw(Graphics g, int x, int y, Component obs, double zoom) {\n piece.draw(g, x, y, obs, zoom);\n }\n @Override\n public String getName() {\n return piece.getName();\n }\n @Override\n protected KeyCommand[] myGetKeyCommands() {\n return KeyCommand.NONE;\n }\n @Override\n public String myGetState() {\n return Integer.toString(cycleIndex);\n }\n @Override\n public String myGetType() {\n final SequenceEncoder se = new SequenceEncoder(';');\n se.append(NamedKeyStrokeArrayConfigurer.encode(keys))\n .append(reportFormat)\n .append(NamedKeyStrokeArrayConfigurer.encode(cycleDownKeys))\n .append(StringArrayConfigurer.arrayToString(cycleReportFormat))\n .append(description)\n .append(noSuppress);\n return ID + se.getValue();\n }\n // We perform the inner commands first so that their effects will be reported\n @Override\n public Command keyEvent(KeyStroke stroke) {\n final Command c = piece.keyEvent(stroke);\n return c == null ? myKeyEvent(stroke) : c.append(myKeyEvent(stroke));\n }\n @Override\n public Command myKeyEvent(KeyStroke stroke) {\n final GamePiece outer = getOutermost(this);\n // Retrieve the name, location and visibility of the unit prior to the\n // trait being executed if it is outside this one.\n format.setProperty(MAP_NAME, getMap() == null ? null : getMap().getConfigureName());\n format.setProperty(LOCATION_NAME, getMap() == null ? null : getMap().locationName(getPosition()));\n format.setProperty(OLD_MAP_NAME, (String) getProperty(BasicPiece.OLD_MAP));\n format.setProperty(OLD_LOCATION_NAME, (String) getProperty(BasicPiece.OLD_LOCATION_NAME));\n Command c = null;\n final java.util.Map oldPiece;\n final Object o = getProperty(Properties.SNAPSHOT);\n // If the SNAPSHOT is returned as a PropertyExporter instead of a Map, then it been set from custom code\n // that is still calling using PieceCloner.clonePiece. Extract the Property Map from the supplied GamePiece and annoy the user.\n if (o instanceof PropertyExporter) {\n oldPiece = ((PropertyExporter) o).getProperties();\n ProblemDialog.showOutdatedUsage(Resources.getString(\"Editor.ReportState.custom_trait_warning\"));\n }\n else {\n // If this cast fails, then custom code developer has done something terribly wrong, so just let it crash and burn\n oldPiece = (java.util.Map) o;\n }\n final boolean wasVisible = oldPiece != null && !Boolean.TRUE.equals(oldPiece.get(Properties.INVISIBLE_TO_OTHERS));\n final boolean isVisible = !Boolean.TRUE.equals(outer.getProperty(Properties.INVISIBLE_TO_OTHERS));\n PieceAccess.GlobalAccess.hideAll();\n final String oldUnitName = oldPiece == null ? null : (String) oldPiece.get(PropertyExporter.LOCALIZED_NAME);\n format.setProperty(OLD_UNIT_NAME, oldUnitName);\n final String newUnitName = outer.getLocalizedName();\n format.setProperty(NEW_UNIT_NAME, newUnitName);\n PieceAccess.GlobalAccess.revertAll();\n // Only make a report if:\n // 1. It's not part of a global command with Single Reporting on\n // 2. The piece is visible to all players either before or after the trait\n // command was executed.\n if (isVisible || wasVisible) {\n final NamedKeyStroke[] allKeys = ArrayUtils.addAll(keys, cycleDownKeys);\n for (int i = 0; i < allKeys.length; ++i) {\n if (stroke != null && stroke.equals(allKeys[i].getKeyStroke())) {\n // Find the Command Name\n String commandName = \"\";\n final KeyCommand[] k = ((Decorator) outer).getKeyCommands();\n for (final KeyCommand keyCommand : k) {\n final KeyStroke commandKey = keyCommand.getKeyStroke();\n if (stroke.equals(commandKey)) {\n commandName = keyCommand.getName();\n }\n }\n final ChangeTracker tracker = new ChangeTracker(this);\n format.setProperty(COMMAND_NAME, commandName);\n String theFormat = reportFormat;\n if (cycleIndex >= 0 && cycleReportFormat.length > 0) {\n if (i < keys.length) {\n theFormat = cycleReportFormat[cycleIndex];\n cycleIndex = (cycleIndex + 1) % cycleReportFormat.length;\n }\n else {\n cycleIndex = (cycleIndex + cycleReportFormat.length - 1) % cycleReportFormat.length;\n theFormat = cycleReportFormat[(cycleIndex + cycleReportFormat.length - 1) % cycleReportFormat.length];\n }\n }\n format.setFormat(getTranslation(theFormat));\n final OldAndNewPieceProperties properties = new OldAndNewPieceProperties(oldPiece, outer);\n // Create explicit Audit Trail as format is evaluated twice\n final AuditTrail audit = AuditTrail.create(this, format.getFormat(), Resources.getString(\"Editor.ReportState.report_format_3\"));\n String reportText = format.getLocalizedText(properties, this, audit);\n if (getMap() != null) {\n format.setFormat(getMap().getChangeFormat(noSuppress));\n }\n else if (!Map.isChangeReportingEnabled() && !noSuppress) {\n format.setFormat(\"\");\n }\n else {\n format.setFormat(\"$\" + Map.MESSAGE + \"$\");\n }\n format.setProperty(Map.MESSAGE, reportText);\n reportText = format.getLocalizedText(properties, this, audit);\n if (reportText.length() > 0) {\n final Command display = new Chatter.DisplayText(GameModule.getGameModule().getChatter(), \"* \" + reportText);\n display.execute();\n c = display;\n }\n c = tracker.getChangeCommand().append(c);\n break;\n }\n }\n }\n return c;\n }\n protected String getPieceName() {\n final String name;\n PieceAccess.GlobalAccess.hideAll();\n name = getOutermost(this).getName();\n PieceAccess.GlobalAccess.revertAll();\n return name;\n }\n @Override\n public void mySetState(String newState) {\n if (newState.length() > 0) {\n try {\n cycleIndex = Integer.parseInt(newState);\n }\n catch (NumberFormatException e) {\n cycleIndex = -1;\n reportDataError(this, Resources.getString(\"Error.non_number_error\"), \"Trying to init Message Index to \" + newState); // NON-NLS\n }\n }\n else {\n cycleIndex = -1;\n }\n }\n @Override\n public Shape getShape() {\n return piece.getShape();\n }\n @Override\n public String getDescription() {\n String s = buildDescription(\"Editor.ReportState.trait_description\", description);\n for (final NamedKeyStroke n : keys) {\n s += getCommandDesc(\"\", n);\n }\n return s;\n }\n @Override\n public String getBaseDescription() {\n return Resources.getString(\"Editor.ReportState.trait_description\");\n }\n @Override\n public HelpFile getHelpFile() {\n return HelpFile.getReferenceManualPage(\"ReportChanges.html\"); // NON-NLS\n }\n @Override\n public void mySetType(String type) {\n final SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(type, ';');\n st.nextToken();\n final String encodedKeys = st.nextToken(\"\");\n if (encodedKeys.indexOf(',') > 0) {\n keys = NamedKeyStrokeArrayConfigurer.decode(encodedKeys);\n }\n else {\n keys = new NamedKeyStroke[encodedKeys.length()];\n for (int i = 0; i < keys.length; i++) {\n keys[i] = NamedKeyStroke.of(encodedKeys.charAt(i), InputEvent.CTRL_DOWN_MASK);\n }\n }\n reportFormat = st.nextToken(\"$\" + LOCATION_NAME + \"$: $\" + NEW_UNIT_NAME + \"$ *\");\n final String encodedCycleDownKeys = st.nextToken(\"\");\n if (encodedCycleDownKeys.indexOf(',') > 0) {\n cycleDownKeys = NamedKeyStrokeArrayConfigurer.decode(encodedCycleDownKeys);\n }\n else {\n cycleDownKeys = new NamedKeyStroke[encodedCycleDownKeys.length()];\n for (int i = 0; i < cycleDownKeys.length; i++) {\n cycleDownKeys[i] = NamedKeyStroke.of(encodedCycleDownKeys.charAt(i), InputEvent.CTRL_DOWN_MASK);\n }\n }\n cycleReportFormat = StringArrayConfigurer.stringToArray(st.nextToken(\"\"));\n description = st.nextToken(\"\");\n noSuppress = st.nextBoolean(false);\n }\n @Override\n public PieceEditor getEditor() {\n return new Ed(this);\n }\n @Override\n public PieceI18nData getI18nData() {\n final int c = cycleReportFormat == null ? 0 : cycleReportFormat.length;\n final String[] formats = new String[c + 1];\n final String[] descriptions = new String[c + 1];\n formats[0] = reportFormat;\n descriptions[0] = getCommandDescription(description, Resources.getString(\"Editor.ReportState.report_format\"));\n int j = 1;\n for (int i = 0; i < c; i++) {\n formats[j] = cycleReportFormat[i];\n descriptions[j] = getCommandDescription(description, Resources.getString(\"Editor.ReportState.report_format_2\"));\n j++;\n }\n return getI18nData(formats, descriptions);\n }\n @Override\n public boolean testEquals(Object o) {\n if (! (o instanceof ReportState)) return false;\n final ReportState c = (ReportState) o;\n if (!Arrays.equals(keys, c.keys)) return false;\n if (! Objects.equals(reportFormat, c.reportFormat)) return false;\n if (!Arrays.equals(cycleDownKeys, c.cycleDownKeys)) return false;\n if (!Arrays.equals(cycleReportFormat, c.cycleReportFormat)) return false;\n if (!Objects.equals(noSuppress, c.noSuppress)) return false;\n return Objects.equals(description, c.description);\n }\n public static final String OLD_UNIT_NAME = \"oldPieceName\"; // NON-NLS\n public static final String NEW_UNIT_NAME = \"newPieceName\"; // NON-NLS\n public static final String MAP_NAME = \"mapName\"; // NON-NLS\n public static final String OLD_MAP_NAME = \"oldMapName\"; // NON-NLS\n public static final String LOCATION_NAME = \"location\"; // NON-NLS\n public static final String OLD_LOCATION_NAME = \"oldLocation\"; // NON-NLS\n public static final String COMMAND_NAME = \"menuCommand\"; // NON-NLS\n public static class Ed implements PieceEditor {\n private final NamedKeyStrokeArrayConfigurer keys;\n private final StringConfigurer format;\n private final JLabel formatLabel;\n private final BooleanConfigurer cycle;\n private final JLabel cycleLabel;\n private final StringArrayConfigurer cycleFormat;\n private final JLabel cycleDownLabel;\n private final NamedKeyStrokeArrayConfigurer cycleDownKeys;\n protected StringConfigurer descInput;\n private final TraitConfigPanel box;\n private final BooleanConfigurer noSuppressConfig;\n public Ed(ReportState piece) {\n box = new TraitConfigPanel();\n descInput = new StringConfigurer(piece.description);\n descInput.setHintKey(\"Editor.description_hint\");\n box.add(\"Editor.description_label\", descInput);\n keys = new NamedKeyStrokeArrayConfigurer(piece.keys);\n box.add(\"Editor.ReportState.report_on_these_keystrokes\", keys);\n cycle = new BooleanConfigurer(piece.cycleReportFormat.length > 0);\n cycle.addPropertyChangeListener(e -> adjustVisibilty());\n box.add(\"Editor.ReportState.cycle_through_different_messages\", cycle);\n formatLabel = new JLabel(Resources.getString(\"Editor.ReportState.report_format_3\"));\n format = new PlayerIdFormattedExpressionConfigurer(\n new String[]{\n COMMAND_NAME,\n OLD_UNIT_NAME,\n NEW_UNIT_NAME,\n MAP_NAME,\n OLD_MAP_NAME,\n LOCATION_NAME,\n OLD_LOCATION_NAME},\n piece.reportFormat);\n box.add(formatLabel, format);\n cycleLabel = new JLabel(Resources.getString(\"Editor.ReportState.message_formats\"));\n cycleFormat = new StringArrayConfigurer(piece.cycleReportFormat);\n box.add(cycleLabel, cycleFormat);\n cycleDownLabel = new JLabel(Resources.getString(\"Editor.ReportState.report_previous\"));\n cycleDownKeys = new NamedKeyStrokeArrayConfigurer(piece.cycleDownKeys);\n box.add(cycleDownLabel, cycleDownKeys);\n noSuppressConfig = new BooleanConfigurer(piece.noSuppress);\n box.add(\"Editor.ReportState.no_suppress\", noSuppressConfig);\n adjustVisibilty();\n }\n private void adjustVisibilty() {\n format.getControls().setVisible(!cycle.getValueBoolean());\n formatLabel.setVisible(!cycle.getValueBoolean());\n cycleFormat.getControls().setVisible(cycle.getValueBoolean());\n cycleLabel.setVisible(cycle.getValueBoolean());\n cycleDownKeys.getControls().setVisible(cycle.getValueBoolean());\n cycleDownLabel.setVisible(cycle.getValueBoolean());\n repack(box);\n }\n @Override\n public Component getControls() {\n return box;\n }\n @Override\n public String getState() {\n return cycle.getValueBoolean() ? \"0\" : \"-1\";\n }\n @Override\n public String getType() {\n final SequenceEncoder se = new SequenceEncoder(';');\n se.append(keys.getValueString())\n .append(format.getValueString())\n .append(cycleDownKeys.getValueString())\n .append(cycle.getValueBoolean() ? cycleFormat.getValueString() : \"\")\n .append(descInput.getValueString())\n .append(noSuppressConfig.getValueString());\n return ID + se.getValue();\n }\n }\n /**\n * Looks in both the new and old piece for property values.\n * Any properties with names of the format \"oldXyz\" are changed\n * to \"xyz\" and applied to the old piece.\n * @author rkinney\n *\n */\n public static class OldAndNewPieceProperties implements PropertySource {\n private final java.util.Map oldPiece;\n private final GamePiece newPiece;\n public OldAndNewPieceProperties(java.util.Map oldPiece, GamePiece newPiece) {\n super();\n this.oldPiece = oldPiece;\n this.newPiece = newPiece;\n }\n public GamePiece getNewPiece() {\n return newPiece;\n }\n @Override\n public Object getProperty(Object key) {\n Object value = null;\n if (key != null) {\n String name = key.toString();\n if (name.startsWith(\"old\") && name.length() >= 4) { // NON-NLS\n name = name.substring(3);\n value = oldPiece.get(name);\n }\n else {\n value = newPiece.getProperty(key);\n }\n }\n return value;\n }\n @Override\n public Object getLocalizedProperty(Object key) {\n return getProperty(key);\n }\n }\n /**\n * @return a list of any Named KeyStrokes referenced in the Decorator, if any (for search)\n */\n @Override\n public List getNamedKeyStrokeList() {\n return Arrays.asList(keys);\n }\n /**\n * @return a list of any Message Format strings referenced in the Decorator, if any (for search)\n */\n @Override\n public List getFormattedStringList() {\n final List l = new ArrayList<>();\n if (cycleIndex >= 0 && cycleReportFormat.length > 0) {\n Collections.addAll(l, cycleReportFormat);\n }\n else {\n l.add(reportFormat);\n }\n return l;\n }\n /**\n * In case reports use HTML and refer to any image files\n * @param s Collection to add image names to\n */\n @Override\n public void addLocalImageNames(Collection s) {\n HTMLImageFinder h;\n if (cycleIndex >= 0 && cycleReportFormat.length > 0) {\n for (final String r : cycleReportFormat) {\n h = new HTMLImageFinder(r);\n h.addImageNames(s);\n }\n }\n else {\n h = new HTMLImageFinder(reportFormat);\n h.addImageNames(s);\n }\n }\n}"}}},{"rowIdx":346238,"cells":{"answer":{"kind":"string","value":"package com.psddev.dari.util;\nimport java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.image.BufferedImage;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport javax.servlet.http.HttpServletRequest;\nimport org.imgscalr.Scalr;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\npublic class LocalImageEditor extends AbstractImageEditor {\n private static final String DEFAULT_IMAGE_FORMAT = \"png\";\n private static final String DEFAULT_IMAGE_CONTENT_TYPE = \"image/\" + DEFAULT_IMAGE_FORMAT;\n private static final String DEFAULT_SECRET = \"secret!\";\n private static final String ORIGINAL_WIDTH_METADATA_PATH = \"image/originalWidth\";\n private static final String ORIGINAL_HEIGHT_METADATA_PATH = \"image/originalHeight\";\n /** Setting key for quality to use for the output images. */\n private static final String QUALITY_SETTING = \"quality\";\n protected static final String TIFF_READER_CLASS = \"com.sun.media.imageioimpl.plugins.tiff.TIFFImageReaderSpi\";\n protected static final String THUMBNAIL_COMMAND = \"thumbnail\";\n private static final Logger LOGGER = LoggerFactory.getLogger(LocalImageEditor.class);\n private Scalr.Method quality = Scalr.Method.AUTOMATIC;\n private String baseUrl;\n private String basePath;\n private String sharedSecret;\n public Scalr.Method getQuality() {\n return quality;\n }\n public void setQuality(Scalr.Method quality) {\n this.quality = quality;\n }\n public String getBaseUrl() {\n return baseUrl;\n }\n public String getBasePath() {\n if (StringUtils.isBlank(basePath) && !(StringUtils.isBlank(baseUrl))) {\n basePath = baseUrl.substring(baseUrl.indexOf(\"\n basePath = basePath.substring(basePath.indexOf(\"/\") + 1);\n if (!basePath.endsWith(\"/\")) {\n basePath += \"/\";\n }\n }\n return basePath;\n }\n public void setBaseUrl(String baseUrl) {\n this.baseUrl = baseUrl;\n }\n public String getSharedSecret() {\n return sharedSecret;\n }\n public void setSharedSecret(String sharedSecret) {\n this.sharedSecret = sharedSecret;\n }\n @Override\n public StorageItem edit(StorageItem storageItem, String command, Map options, Object... arguments) {\n if (StringUtils.isBlank(this.getBasePath()) && PageContextFilter.Static.getRequest() != null) {\n setBaseUrlFromRequest(PageContextFilter.Static.getRequest());\n setSharedSecret(DEFAULT_SECRET);\n }\n if (ImageEditor.CROP_COMMAND.equals(command) &&\n options != null &&\n options.containsKey(ImageEditor.CROP_OPTION) &&\n options.get(ImageEditor.CROP_OPTION).equals(ImageEditor.CROP_OPTION_NONE)) {\n return storageItem;\n }\n String imageUrl = storageItem.getPublicUrl();\n List commands = new ArrayList();\n if (imageUrl.startsWith(this.getBaseUrl()) && imageUrl.contains(\"?url=\")) {\n String[] imageComponents = imageUrl.split(\"\\\\?url=\");\n imageUrl = imageComponents[1];\n String path = imageComponents[0].substring(this.getBaseUrl().length() + 1);\n for (String parameter : path.split(\"/\")) {\n commands.add(parameter);\n }\n if (!StringUtils.isBlank(this.getSharedSecret())) {\n commands = commands.subList(2, commands.size());\n }\n }\n Object cropOption = options != null ? options.get(ImageEditor.CROP_OPTION) : null;\n Dimension originalDimension = null;\n Dimension outputDimension = null;\n Map oldMetadata = storageItem.getMetadata();\n if (oldMetadata != null) {\n Integer originalWidth = null;\n Integer originalHeight = null;\n // grab the original width and height of the image\n originalWidth = ObjectUtils.to(Integer.class,\n CollectionUtils.getByPath(oldMetadata, ORIGINAL_WIDTH_METADATA_PATH));\n if (originalWidth == null) {\n originalWidth = ObjectUtils.to(Integer.class, oldMetadata.get(\"width\"));\n }\n originalHeight = ObjectUtils.to(Integer.class,\n CollectionUtils.getByPath(oldMetadata, ORIGINAL_HEIGHT_METADATA_PATH));\n if (originalHeight == null) {\n originalHeight = ObjectUtils.to(Integer.class, oldMetadata.get(\"height\"));\n }\n originalDimension = new Dimension(originalWidth, originalHeight);\n }\n if (ImageEditor.CROP_COMMAND.equals(command) &&\n ObjectUtils.to(Integer.class, arguments[0]) == null &&\n ObjectUtils.to(Integer.class, arguments[1]) == null) {\n commands.add(THUMBNAIL_COMMAND);\n command = RESIZE_COMMAND;\n arguments[0] = arguments[2];\n arguments[1] = arguments[3];\n } else {\n commands.add(command);\n }\n if (ImageEditor.CROP_COMMAND.equals(command)) {\n Integer width = ObjectUtils.to(Integer.class, arguments[2]);\n Integer height = ObjectUtils.to(Integer.class, arguments[3]);\n commands.add(arguments[0] + \"x\" + arguments[1] + \"x\" + width + \"x\" + height);\n if (originalDimension != null) {\n outputDimension = new Dimension(Math.min(originalDimension.width, width),\n Math.min(originalDimension.height, height));\n }\n } else if (ImageEditor.RESIZE_COMMAND.equals(command)) {\n Integer width = ObjectUtils.to(Integer.class, arguments[0]);\n Integer height = ObjectUtils.to(Integer.class, arguments[1]);\n StringBuilder resizeBuilder = new StringBuilder();\n if (width != null) {\n resizeBuilder.append(width);\n }\n resizeBuilder.append(\"x\");\n if (height != null) {\n resizeBuilder.append(height);\n }\n Object resizeOption = options != null ? options.get(ImageEditor.RESIZE_OPTION) : null;\n if (resizeOption != null &&\n (cropOption == null || !cropOption.equals(ImageEditor.CROP_OPTION_AUTOMATIC))) {\n if (resizeOption.equals(ImageEditor.RESIZE_OPTION_IGNORE_ASPECT_RATIO)) {\n resizeBuilder.append(\"!\");\n } else if (resizeOption.equals(ImageEditor.RESIZE_OPTION_ONLY_SHRINK_LARGER)) {\n resizeBuilder.append(\">\");\n if (originalDimension != null && width != null && height != null) {\n outputDimension = new Dimension(Math.min(originalDimension.width, width),\n Math.min(originalDimension.height, height));\n }\n } else if (resizeOption.equals(ImageEditor.RESIZE_OPTION_ONLY_ENLARGE_SMALLER)) {\n resizeBuilder.append(\"<\");\n if (originalDimension != null && width != null && height != null) {\n outputDimension = new Dimension(Math.max(originalDimension.width, width),\n Math.max(originalDimension.height, height));\n }\n } else if (resizeOption.equals(ImageEditor.RESIZE_OPTION_FILL_AREA)) {\n resizeBuilder.append(\"^\");\n }\n }\n if (originalDimension != null && width != null && height != null && (resizeOption == null ||\n resizeOption.equals(ImageEditor.RESIZE_OPTION_IGNORE_ASPECT_RATIO) ||\n resizeOption.equals(ImageEditor.RESIZE_OPTION_FILL_AREA))) {\n outputDimension = new Dimension(Math.min(originalDimension.width, width),\n Math.min(originalDimension.height, height));\n }\n commands.add(resizeBuilder.toString());\n }\n StringBuilder storageItemUrlBuilder = new StringBuilder();\n storageItemUrlBuilder.append(this.getBaseUrl());\n if (!StringUtils.isBlank(this.getSharedSecret())) {\n StringBuilder commandsBuilder = new StringBuilder();\n for (String parameter : commands) {\n commandsBuilder.append(StringUtils.encodeUri(parameter))\n .append('/');\n }\n Long expireTs = (long) Integer.MAX_VALUE;\n String signature = expireTs + this.getSharedSecret() + StringUtils.decodeUri(\"/\" + commandsBuilder.toString()) + imageUrl;\n String md5Hex = StringUtils.hex(StringUtils.md5(signature));\n String requestSig = md5Hex.substring(0, 7);\n storageItemUrlBuilder.append(requestSig)\n .append(\"/\")\n .append(expireTs.toString())\n .append(\"/\");\n }\n for (String parameter : commands) {\n storageItemUrlBuilder.append(parameter)\n .append(\"/\");\n }\n storageItemUrlBuilder.append(\"?url=\")\n .append(imageUrl);\n UrlStorageItem newStorageItem = StorageItem.Static.createUrl(storageItemUrlBuilder.toString());\n String format = DEFAULT_IMAGE_FORMAT;\n String contentType = DEFAULT_IMAGE_CONTENT_TYPE;\n if (storageItem.getContentType() != null && storageItem.getContentType().contains(\"/\")) {\n contentType = storageItem.getContentType();\n format = storageItem.getContentType().split(\"/\")[1];\n }\n newStorageItem.setContentType(contentType);\n Map metadata = storageItem.getMetadata();\n if (metadata == null) {\n metadata = new HashMap();\n }\n // store the new width and height in the metadata map\n if (outputDimension != null && outputDimension.width != null) {\n metadata.put(\"width\", outputDimension.width);\n }\n if (outputDimension != null && outputDimension.height != null) {\n metadata.put(\"height\", outputDimension.height);\n }\n // store the original width and height in the map for use with future image edits.\n if (originalDimension != null && originalDimension.width != null) {\n CollectionUtils.putByPath(metadata, ORIGINAL_WIDTH_METADATA_PATH, originalDimension.width);\n }\n if (originalDimension != null && originalDimension.height != null) {\n CollectionUtils.putByPath(metadata, ORIGINAL_HEIGHT_METADATA_PATH, originalDimension.height);\n }\n newStorageItem.setMetadata(metadata);\n return newStorageItem;\n }\n @Override\n public void initialize(String settingsKey, Map settings) {\n Object qualitySetting = settings.get(QUALITY_SETTING);\n if (qualitySetting == null) {\n qualitySetting = Settings.get(QUALITY_SETTING);\n }\n if (qualitySetting != null) {\n if (qualitySetting instanceof Integer) {\n Integer qualityInteger = ObjectUtils.to(Integer.class, qualitySetting);\n quality = findQualityByInteger(qualityInteger);\n } else if (qualitySetting instanceof String) {\n quality = Scalr.Method.valueOf(ObjectUtils.to(String.class, qualitySetting));\n }\n }\n if (!ObjectUtils.isBlank(settings.get(\"servletPath\"))) {\n LocalImageServlet.setServletPath(ObjectUtils.to(String.class, settings.get(\"servletPath\")));\n }\n if (!ObjectUtils.isBlank(settings.get(\"baseUrl\"))) {\n setBaseUrl(ObjectUtils.to(String.class, settings.get(\"baseUrl\")));\n }\n if (!ObjectUtils.isBlank(settings.get(\"sharedSecret\"))) {\n setSharedSecret(ObjectUtils.to(String.class, settings.get(\"sharedSecret\")));\n } else {\n setSharedSecret(DEFAULT_SECRET);\n }\n }\n protected void setBaseUrlFromRequest(HttpServletRequest request) {\n StringBuilder baseUrlBuilder = new StringBuilder();\n baseUrlBuilder.append(\"http\");\n if (request.isSecure()) {\n baseUrlBuilder.append(\"s\");\n }\n baseUrlBuilder.append(\":\n .append(request.getServerName());\n if (request.getServerPort() != 80 && request.getServerPort() != 443) {\n baseUrlBuilder.append(\":\")\n .append(request.getServerPort());\n }\n baseUrlBuilder.append(LocalImageServlet.getServletPath());\n setBaseUrl(baseUrlBuilder.toString());\n }\n protected static Scalr.Method findQualityByInteger(Integer quality) {\n if (quality >= 80) {\n return Scalr.Method.ULTRA_QUALITY;\n } else if (quality >= 60) {\n return Scalr.Method.QUALITY;\n } else if (quality >= 40) {\n return Scalr.Method.AUTOMATIC;\n } else if (quality >= 20) {\n return Scalr.Method.BALANCED;\n } else {\n return Scalr.Method.SPEED;\n }\n }\n /** Helper class so that width and height can be returned in a single object */\n protected static class Dimension {\n public final Integer width;\n public final Integer height;\n public Dimension(Integer width, Integer height) {\n this.width = width;\n this.height = height;\n }\n }\n public BufferedImage reSize(BufferedImage bufferedImage, Integer width, Integer height, String option, Scalr.Method quality) {\n if (quality == null) {\n quality = this.quality;\n }\n if (width != null || height != null) {\n if (!StringUtils.isBlank(option) &&\n option.equals(ImageEditor.RESIZE_OPTION_ONLY_SHRINK_LARGER)) {\n if ((height == null && width >= bufferedImage.getWidth()) ||\n (width == null && height >= bufferedImage.getHeight()) ||\n (width != null && height != null && width >= bufferedImage.getWidth() && height >= bufferedImage.getHeight())) {\n return bufferedImage;\n }\n } else if (!StringUtils.isBlank(option) &&\n option.equals(ImageEditor.RESIZE_OPTION_ONLY_ENLARGE_SMALLER)) {\n if ((height == null && width <= bufferedImage.getWidth()) ||\n (width == null && height <= bufferedImage.getHeight()) ||\n (width != null && height != null && (width <= bufferedImage.getWidth() || height <= bufferedImage.getHeight()))) {\n return bufferedImage;\n }\n }\n if (StringUtils.isBlank(option) ||\n option.equals(ImageEditor.RESIZE_OPTION_ONLY_SHRINK_LARGER) ||\n option.equals(ImageEditor.RESIZE_OPTION_ONLY_ENLARGE_SMALLER)) {\n if (height == null) {\n return Scalr.resize(bufferedImage, quality, Scalr.Mode.FIT_TO_WIDTH, width);\n } else if (width == null) {\n return Scalr.resize(bufferedImage, quality, Scalr.Mode.FIT_TO_HEIGHT, height);\n } else {\n return Scalr.resize(bufferedImage, quality, width, height);\n }\n } else if (height != null && width != null) {\n if (option.equals(ImageEditor.RESIZE_OPTION_IGNORE_ASPECT_RATIO)) {\n return Scalr.resize(bufferedImage, quality, Scalr.Mode.FIT_EXACT, width, height);\n } else if (option.equals(ImageEditor.RESIZE_OPTION_FILL_AREA)) {\n Dimension dimension = getFillAreaDimension(bufferedImage.getWidth(), bufferedImage.getHeight(), width, height);\n return Scalr.resize(bufferedImage, quality, Scalr.Mode.FIT_EXACT, dimension.width, dimension.height);\n }\n }\n }\n return null;\n }\n public static BufferedImage crop(BufferedImage bufferedImage, Integer x, Integer y, Integer width, Integer height) {\n if (width != null || height != null) {\n if (height == null) {\n height = (int) ((double) bufferedImage.getHeight() / (double) bufferedImage.getWidth() * (double) width);\n } else if (width == null) {\n width = (int) ((double) bufferedImage.getWidth() / (double) bufferedImage.getHeight() * (double) height);\n }\n if (x == null) {\n x = bufferedImage.getWidth() / 2;\n }\n if (y == null) {\n y = bufferedImage.getHeight() / 2;\n }\n if (x + width > bufferedImage.getWidth()) {\n width = bufferedImage.getWidth() - x;\n }\n if (y + height > bufferedImage.getHeight()) {\n height = bufferedImage.getHeight() - y;\n }\n return Scalr.crop(bufferedImage, x, y, width, height);\n }\n return null;\n }\n public static BufferedImage grayscale(BufferedImage sourceImage) {\n BufferedImage resultImage = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), BufferedImage.TYPE_BYTE_GRAY);\n Graphics g = resultImage.getGraphics();\n g.drawImage(sourceImage, 0, 0, null);\n g.dispose();\n return resultImage;\n }\n public static BufferedImage brightness(BufferedImage sourceImage, int brightness, int contrast) {\n BufferedImage resultImage = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), sourceImage.getType());\n int multiply = 100;\n int add;\n if (contrast == 0) {\n add = Math.round(brightness / 100.0f * 255);\n } else {\n if (contrast > 0) {\n contrast = contrast * 4;\n }\n contrast = 100 - (contrast * -1);\n multiply = contrast;\n brightness = Math.round(brightness / 100.0f * 255);\n add = ((Double) (((brightness - 128) * (multiply / 100.0d) + 128))).intValue();\n }\n for (int x = 0; x < sourceImage.getWidth(); x++) {\n for (int y = 0; y < sourceImage.getHeight(); y++) {\n int rgb = sourceImage.getRGB(x, y);\n int alpha = (rgb >> 24) & 0xFF;\n int red = (rgb >> 16) & 0xFF;\n int green = (rgb >> 8) & 0xFF;\n int blue = rgb & 0xFF;\n red = adjustColor(red, multiply, add);\n green = adjustColor(green, multiply, add);\n blue = adjustColor(blue, multiply, add);\n int newRgb = (alpha << 24) | (red << 16) | (green << 8) | blue;\n resultImage.setRGB(x, y, newRgb);\n }\n }\n return resultImage;\n }\n public static BufferedImage flipHorizontal(BufferedImage sourceImage) {\n return Scalr.rotate(sourceImage, Scalr.Rotation.FLIP_HORZ);\n }\n public static BufferedImage flipVertical(BufferedImage sourceImage) {\n return Scalr.rotate(sourceImage, Scalr.Rotation.FLIP_VERT);\n }\n public static BufferedImage invert(BufferedImage sourceImage) {\n BufferedImage resultImage = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), sourceImage.getType());\n for (int x = 0; x < sourceImage.getWidth(); x++) {\n for (int y = 0; y < sourceImage.getHeight(); y++) {\n int rgb = sourceImage.getRGB(x, y);\n int alpha = (rgb >> 24) & 0xFF;\n int red = 255 - (rgb >> 16) & 0xFF;\n int green = 255 - (rgb >> 8) & 0xFF;\n int blue = 255 - rgb & 0xFF;\n int newRgb = (alpha << 24) | (red << 16) | (green << 8) | blue;\n resultImage.setRGB(x, y, newRgb);\n }\n }\n return resultImage;\n }\n public static BufferedImage rotate(BufferedImage sourceImage, int degrees) {\n Scalr.Rotation rotation;\n if (degrees == 90) {\n rotation = Scalr.Rotation.CW_90;\n } else if (degrees == 180) {\n rotation = Scalr.Rotation.CW_180;\n } else if (degrees == 270 || degrees == -90) {\n rotation = Scalr.Rotation.CW_270;\n } else {\n double radians = Math.toRadians(degrees);\n int w = (new Double(Math.abs(sourceImage.getWidth() * Math.cos(radians)) + Math.abs(sourceImage.getHeight() * Math.sin(radians)))).intValue();\n int h = (new Double(Math.abs(sourceImage.getWidth() * Math.sin(radians)) + Math.abs(sourceImage.getHeight() * Math.cos(radians)))).intValue();\n BufferedImage resultImage = new BufferedImage(w, h, sourceImage.getType());\n Graphics2D graphics = resultImage.createGraphics();\n graphics.setColor(Color.WHITE);\n graphics.fillRect(0, 0, w, h);\n int x = -1 * (sourceImage.getWidth() - w) / 2;\n int y = -1 * (sourceImage.getHeight() - h) / 2;\n graphics.rotate(Math.toRadians(degrees), (w / 2), (h / 2));\n graphics.drawImage(sourceImage, null, x, y);\n return resultImage;\n }\n return Scalr.rotate(sourceImage, rotation);\n }\n public static BufferedImage sepia(BufferedImage sourceImage) {\n BufferedImage resultImage = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), sourceImage.getType());\n for (int x = 0; x < sourceImage.getWidth(); x++) {\n for (int y = 0; y < sourceImage.getHeight(); y++) {\n int rgb = sourceImage.getRGB(x, y);\n int alpha = (rgb >> 24) & 0xFF;\n int red = (rgb >> 16) & 0xFF;\n int green = (rgb >> 8) & 0xFF;\n int blue = rgb & 0xFF;\n int newRed = (new Double((red * .393) + (green * .769) + (blue * .189))).intValue();\n int newGreen = (new Double((red * .349) + (green * .686) + (blue * .168))).intValue();\n int newBlue = (new Double((red * .272) + (green * .534) + (blue * .131))).intValue();\n newRed = colorMinMax(newRed);\n newGreen = colorMinMax(newGreen);\n newBlue = colorMinMax(newBlue);\n int newRgb = (alpha << 24) | (newRed << 16) | (newGreen << 8) | newBlue;\n resultImage.setRGB(x, y, newRgb);\n }\n }\n return resultImage;\n }\n private static int adjustColor(int color, int multiply, int add) {\n color = Math.round(color * (multiply / 100.0f)) + add;\n return colorMinMax(color);\n }\n private static int colorMinMax(int color) {\n if (color < 0) {\n return 0;\n } else if (color > 255) {\n return 255;\n }\n return color;\n }\n private static Dimension getFillAreaDimension(Integer originalWidth, Integer originalHeight, Integer requestedWidth, Integer requestedHeight) {\n Integer actualWidth = null;\n Integer actualHeight = null;\n if (originalWidth != null && originalHeight != null &&\n (requestedWidth != null || requestedHeight != null)) {\n float originalRatio = (float) originalWidth / (float) originalHeight;\n if (requestedWidth != null && requestedHeight != null) {\n Integer potentialWidth = Math.round((float) requestedHeight * originalRatio);\n Integer potentialHeight = Math.round((float) requestedWidth / originalRatio);\n if (potentialWidth > requestedWidth) {\n actualWidth = potentialWidth;\n actualHeight = requestedHeight;\n } else { // potentialHeight > requestedHeight\n actualWidth = requestedWidth;\n actualHeight = potentialHeight;\n }\n } else if (originalWidth > originalHeight) {\n actualHeight = requestedHeight != null ? requestedHeight : requestedWidth;\n actualWidth = Math.round((float) actualHeight * originalRatio);\n } else { // originalWidth <= originalHeight\n actualWidth = requestedWidth != null ? requestedWidth : requestedHeight;\n actualHeight = Math.round((float) actualWidth / originalRatio);\n }\n }\n return new Dimension(actualWidth, actualHeight);\n }\n}"}}},{"rowIdx":346239,"cells":{"answer":{"kind":"string","value":"package appathon.com.billythesilly;\nimport android.app.Activity;\nimport android.graphics.Color;\nimport android.graphics.LightingColorFilter;\nimport android.os.Bundle;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.Button;\nimport android.content.Intent;\n// import android.widget.TextView;\n// Commented Page Number feature\npublic class ScenariosScreen extends Activity {\n String [] arrayButtons = new String[18];\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_scenarios_screen);\n }\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n // Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.menu_scenarios_screen, menu);\n return true;\n }\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n // Handle action bar item clicks here. The action bar will\n // automatically handle clicks on the Home/Up button, so long\n // as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n //noinspection SimplifiableIfStatement\n if (id == R.id.action_settings) {\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n public void goButton1(View view){\n Intent intent = new Intent(this,BaseGameActivity.class);\n startActivity(intent);\n }\n public void goButton2(View view){\n Intent intent = new Intent(this,StartScreen.class);\n startActivity(intent);\n }\n public void goButton3(View view){\n Intent intent = new Intent(this,StartScreen.class);\n startActivity(intent);\n }\n public void goNextPage(View view){\n generateButtonStrings();\n Button current1 = (Button) findViewById(R.id.button1);\n Button current2 = (Button) findViewById(R.id.button2);\n Button current3 = (Button) findViewById(R.id.button3);\n int position = findPosition(current1.getText().toString());\n current1.setText(arrayButtons[(position+3)%18]);\n current2.setText(arrayButtons[(position+4)%18]);\n current3.setText(arrayButtons[(position+5)%18]);\n //Line that changes color of text: current1.setTextColor(Color.BLUE);\n //setPage(position);\n }\n public void goPreviousPage(View view) {\n generateButtonStrings();\n Button current1 = (Button) findViewById(R.id.button1);\n Button current2 = (Button) findViewById(R.id.button2);\n Button current3 = (Button) findViewById(R.id.button3);\n int position = findPosition(current1.getText().toString());\n current1.setText(arrayButtons[(position+15)%18]);\n current2.setText(arrayButtons[(position+16)%18]);\n current3.setText(arrayButtons[(position+17)%18]);\n //setPage(position);\n }\n /*public void setPage(int n){\n TextView page = (TextView) findViewById(R.id.textPage);\n String s = \"Page \"+ Integer.toString((n/3)+1);\n CharSequence num = s;\n page.setText(num);\n }*/\n public void generateButtonStrings(){\n for(int i=0; i<18; i++){\n arrayButtons[i] = (\"Testing Changes \" + i);\n }\n }\n public int findPosition(String n){\n int position=0;\n for(int i=0; i<18; i++){\n if(arrayButtons[i].equals(n))\n position = i;\n }\n return position;\n }\n}"}}},{"rowIdx":346240,"cells":{"answer":{"kind":"string","value":"package com.networknt.utility;\nimport org.junit.Assert;\nimport org.junit.Test;\npublic class HashUtilTest {\n @Test\n public void testMd5Hex() {\n String md5 = HashUtil.md5Hex(\"stevehu@gmail.com\");\n Assert.assertEquals(md5, \"417bed6d9644f12d8bc709059c225c27\");\n }\n @Test\n public void testPasswordHash() throws Exception {\n String password = \"123456\";\n String hashedPass = HashUtil.generateStorngPasswordHash(password);\n System.out.println(\"hashedPass = \" + hashedPass);\n Assert.assertTrue(HashUtil.validatePassword(password, hashedPass));\n }\n @Test\n public void testClientSecretHash() throws Exception {\n String secret = \"f6h1FTI8Q3-7UScPZDzfXA\";\n String hashedPass = HashUtil.generateStorngPasswordHash(secret);\n System.out.println(\"hashedSecret = \" + hashedPass);\n Assert.assertTrue(HashUtil.validatePassword(secret, hashedPass));\n }\n}"}}},{"rowIdx":346241,"cells":{"answer":{"kind":"string","value":"package com.chickenkiller.upods2.utils;\nimport android.util.Log;\nimport org.json.JSONArray;\nimport org.json.JSONException;\npublic class GlobalUtils {\n private static final String[] bestStreamPatterns = {\".+\\\\.mp3\", \".+[^.]{4}$\"};\n public static String getBestStreamUrl(JSONArray allUrls) {\n String url = \"\";\n try {\n url = allUrls.getString(0);\n for (String pattern : bestStreamPatterns) {\n for (int i = 0; i < allUrls.length(); i++) {\n if (allUrls.getString(i).matches(pattern)) {\n Log.i(\"MATCHES\", allUrls.getString(i) + \"pattern \" + pattern);\n url = allUrls.getString(i);\n return url;\n }\n Log.i(\"NOT\", allUrls.getString(i) + \"pattern\" + pattern);\n }\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n return url;\n }\n}"}}},{"rowIdx":346242,"cells":{"answer":{"kind":"string","value":"package com.darkkeeper.minecraft.mods;\nimport android.app.ActionBar;\nimport android.app.Activity;\nimport android.app.AlertDialog;\nimport android.content.ActivityNotFoundException;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.content.pm.PackageManager;\nimport android.content.pm.ResolveInfo;\nimport android.net.ConnectivityManager;\nimport android.net.NetworkInfo;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.Parcelable;\nimport android.provider.Settings;\nimport android.support.v4.app.ActivityCompat;\nimport android.support.v4.content.ContextCompat;\nimport android.support.v4.widget.NestedScrollView;\nimport android.support.v7.app.AppCompatActivity;\nimport android.util.Log;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.LinearLayout;\nimport android.widget.ProgressBar;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport com.appodeal.ads.Appodeal;\n/*import com.google.android.gms.analytics.GoogleAnalytics;\nimport com.google.android.gms.analytics.HitBuilders;\nimport com.google.android.gms.analytics.Tracker;*/\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\n//import com.google.firebase.analytics.FirebaseAnalytics;\nimport com.appodeal.ads.BannerCallbacks;\nimport com.appodeal.ads.BannerView;\nimport com.appodeal.ads.InterstitialCallbacks;\nimport com.backendless.Backendless;\nimport com.google.android.gms.analytics.GoogleAnalytics;\nimport com.google.android.gms.analytics.HitBuilders;\nimport com.google.android.gms.analytics.Tracker;\npublic class BaseActivity extends AppCompatActivity {\n /* private Tracker globalTracker;*/\n public final static String BACKENDLESS_ID = \"CB0EF57E-5CF2-1505-FF6A-C070AF81DA00\";\n public final static String BACKENDLESS_SECRET_KEY = \"091E1EA1-2543-89FC-FF96-A3EFF6815500\";\n public final static String APP_VERSION = \"v1\";\n public final static String DEFAULT_LANGUAGE = \"en\";\n public static String CURRENT_LANGUAGE = \"en\";\n private Tracker globalTracker;\n public final static String INTENT_UPDATE = \"UPDATE_APP\";\n protected boolean canShowCommercial = false;\n private boolean isBannerShowing = false;\n // private static FirebaseAnalytics mFirebaseAnalytics;\n private static int backPressedCount = 1;\n private Toast toast = null;\n private static boolean isActivityVisible;\n @Override\n protected void onResume() {\n super.onResume();\n isActivityVisible = true;\n isBannerShowing = false;\n try {\n BannerView bannerView1 = (BannerView) findViewById( R.id.appodealBannerView );\n bannerView1.setVisibility(View.GONE);\n } catch (Exception e){\n }\n try {\n BannerView bannerView2 = (BannerView) findViewById( R.id.appodealBannerView2 );\n bannerView2.setVisibility(View.GONE);\n } catch (Exception e){\n }\n showBanner(this);\n }\n @Override\n protected void onPause() {\n super.onPause();\n isActivityVisible = false;\n }\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n // Handle action bar item clicks here. The action bar will\n // automatically handle clicks on the Home/Up button, so long\n // as you specify a parent activity in AndroidManifest.xml.\n switch ( item.getItemId() ){\n case android.R.id.home:\n logFirebaseEvent(\"back\");\n onBackPressed();\n return true;\n case R.id.action_share:\n logFirebaseEvent( \"share\" );\n canShowCommercial = true;\n showInterestial( this );\n share( this );\n return true;\n case R.id.action_rate:\n logFirebaseEvent( \"rate\" );\n canShowCommercial = true;\n showInterestial( this );\n rate( this );\n return true;\n case R.id.action_help:\n logFirebaseEvent( \"help\" );\n/* canShowCommercial = true;\n showInterestial( this );*/\n help( this );\n return true;\n default:\n return super.onOptionsItemSelected(item);\n }\n }\n @Override\n public void onBackPressed(){\n canShowCommercial = true;\n showInterestial( this );\n super.onBackPressed();\n/* backPressedCount++;\n if ( (3 + backPressedCount)%3 == 0 ){\n canShowCommercial = true;\n showInterestial( this );\n }\n super.onBackPressed();*/\n }\n protected boolean isOnline() {\n ConnectivityManager cm =\n (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo netInfo = cm.getActiveNetworkInfo();\n return netInfo != null && netInfo.isConnectedOrConnecting();\n }\n protected void getSystemLanguage (){\n CURRENT_LANGUAGE = Locale.getDefault().getLanguage();\n }\n protected void initDatabase () {\n Backendless.initApp(this, BACKENDLESS_ID, BACKENDLESS_SECRET_KEY, APP_VERSION);\n }\n protected void initAds () {\n String appKey = getResources().getString(R.string.appodeal_id);\n Appodeal.confirm(Appodeal.SKIPPABLE_VIDEO);\n Appodeal.disableNetwork(this, \"cheetah\");\n // Appodeal.disableNetwork(this, \"yandex\");\n Appodeal.disableNetwork(this, \"unity_ads\");\n Appodeal.initialize(this, appKey, Appodeal.BANNER_BOTTOM | Appodeal.INTERSTITIAL | Appodeal.SKIPPABLE_VIDEO);\n }\n protected void initGoogleAnalytics ( Context context ) {\n // mFirebaseAnalytics = FirebaseAnalytics.getInstance( context );\n GoogleAnalytics analytics = GoogleAnalytics.getInstance(context);\n globalTracker = analytics.newTracker( R.xml.global_tracker );\n globalTracker.setScreenName(getPackageName());\n globalTracker.send(new HitBuilders.ScreenViewBuilder().build());\n }\n private void logFirebaseEvent ( String event ){\n/* Bundle bundle = new Bundle();\n bundle.putString(FirebaseAnalytics.Param.ITEM_ID, event);\n // bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, event);\n mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);*/\n }\n protected void showInterestial ( Context context ) {\n // Log.d(\"MY_LOGS2\", \"CAN_SHOW = \" + canShowCommercial );\n if (canShowCommercial) {\n Appodeal.show((Activity) context, Appodeal.INTERSTITIAL);\n }\n }\n protected void showBanner ( Context context ) {\n // Log.d(\"MY_LOGS2\", \"CAN_SHOW = \" + canShowCommercial );\n // isBannerShowing = false;\n Appodeal.show((Activity) context, Appodeal.BANNER_BOTTOM);\n }\n protected void setAppodealCallbacks ( final Context context ) {\n Appodeal.setInterstitialCallbacks(new InterstitialCallbacks() {\n private Toast mToast;\n @Override\n public void onInterstitialLoaded(boolean isPrecache) {\n canShowCommercial = false;\n // Log.d(\"LOG_D\", \"CanShowCommercial = \" + canShowCommercial);\n }\n @Override\n public void onInterstitialFailedToLoad() {\n canShowCommercial = false;\n // Log.d(\"LOG_D\", \"CanShowCommercial = \" + canShowCommercial);\n }\n @Override\n public void onInterstitialShown() {\n canShowCommercial = false;\n // Log.d(\"LOG_D\", \"CanShowCommercial = \" + canShowCommercial);\n }\n @Override\n public void onInterstitialClicked() {\n canShowCommercial = false;\n // Log.d(\"LOG_D\", \"CanShowCommercial = \" + canShowCommercial);\n }\n @Override\n public void onInterstitialClosed() {\n canShowCommercial = false;\n // Log.d(\"LOG_D\", \"CanShowCommercial = \" + canShowCommercial);\n }\n });\n Appodeal.setBannerCallbacks(new BannerCallbacks() {\n private Toast mToast;\n @Override\n public void onBannerLoaded(int height, boolean isPrecache) {\n // showToast(String.format(\"onBannerLoaded, %ddp\" + isBannerShowing, height));\n/* if ( !isBannerShowing && Appodeal.isLoaded(Appodeal.BANNER_BOTTOM)){\n Appodeal.show((Activity) context, Appodeal.BANNER_BOTTOM);\n isBannerShowing = true;\n }*/\n }\n @Override\n public void onBannerFailedToLoad() {\n // showToast(\"onBannerFailedToLoad\");\n }\n @Override\n public void onBannerShown() {\n/* try {\n BannerView bannerView1 = (BannerView) findViewById( R.id.appodealBannerView );\n bannerView1.setVisibility(View.VISIBLE);\n } catch (Exception e){\n }\n try {\n BannerView bannerView2 = (BannerView) findViewById( R.id.appodealBannerView2 );\n bannerView2.setVisibility(View.VISIBLE);\n NestedScrollView nestedScrollView = (NestedScrollView) findViewById(R.id.nestedScrollView2);\n Log.d(\"MY_LOGS\", \"heights = \" + nestedScrollView.getLayoutParams().height);\n nestedScrollView.getLayoutParams().height += 50;\n Log.d(\"MY_LOGS\", \"heights = \" + nestedScrollView.getLayoutParams().height);\n nestedScrollView.invalidate();\n } catch (Exception e){\n Log.d(\"MY_LOGS\", \"ERROR = \" + e.toString());\n e.printStackTrace();\n }*/\n // showToast(\"onBannerShown\");\n }\n @Override\n public void onBannerClicked() {\n // showToast(\"onBannerClicked\");\n }\n void showToast(final String text) {\n if (mToast == null) {\n mToast = Toast.makeText(context, text, Toast.LENGTH_SHORT);\n }\n mToast.setText(text);\n mToast.setDuration(Toast.LENGTH_SHORT);\n mToast.show();\n }\n });\n }\n/* protected void showAdsOnStart ( Context context ) {\n Appodeal.show((Activity) context, Appodeal.INTERSTITIAL);\n Appodeal.show((Activity) context, Appodeal.BANNER_BOTTOM);\n }*/\n protected void showPermissionDialog ( final Context context ) {\n AlertDialog.Builder permissions = new AlertDialog.Builder( context );\n permissions.setMessage(R.string.showPermissionMessage)\n .setTitle(R.string.notificationMessage)\n .setCancelable(false)\n .setPositiveButton(R.string.answerOk,\n new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int id) {\n ActivityCompat.requestPermissions((MainActivity) context, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);\n return;\n }\n }\n );\n AlertDialog alert = permissions.create();\n alert.show();\n }\n protected void showOffer ( final Context mContext, String spinnerChoice ){\n if ( spinnerChoice != null ) {\n AlertDialog.Builder rate = new AlertDialog.Builder(mContext);\n String helpMessage = getString(R.string.offerMessage1) + mContext.getResources().getString(R.string.app_name) + \"!\" + \"\\n\" + \"\\n\" +\n getString(R.string.offerMessage2) + \"\\n\" + \"\\n\" +\n getString(R.string.offerMessage3);\n rate.setMessage(helpMessage)\n .setTitle(R.string.offerTitle)\n .setCancelable(false)\n .setNegativeButton(R.string.answerCancel,\n new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int id) {\n return;\n }\n }\n )\n .setPositiveButton(getString(R.string.answerOk),\n new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int id) {\n Intent i = new Intent(Intent.ACTION_VIEW);\n i.setData(Uri.parse(\"https://play.google.com/store/apps/details?id=net.zhuoweizhang.mcpelauncher\"));\n mContext.startActivity(i);\n }\n }\n );\n AlertDialog alert = rate.create();\n alert.show();\n } else {\n Toast toast = Toast.makeText( mContext, R.string.noVersionSelectedMessage, Toast.LENGTH_LONG );\n toast.show();\n }\n }\n protected void showInetRequirementMessage ( final Context context ) {\n if (isActivityVisible) {\n try {\n toast.getView().isShown();\n toast.setText(R.string.networkReq);\n } catch (Exception e) {\n toast = Toast.makeText(context, R.string.networkReq, Toast.LENGTH_SHORT);\n }\n toast.show();\n }\n/* if ( toast==null || toast.getView().getWindowVisibility() != View.GONE ) {\n toast = Toast.makeText(context, \"Network is Unnavailable\", Toast.LENGTH_SHORT);\n toast.show();\n Log.d(\"LOGS\", \"\" + toast + \" VISIBILITY = \" + toast.getView().getWindowVisibility() + \" isShown = \" + toast.getView().isShown() + \" getWindowToken = \" + toast.getView().getWindowToken());\n }*/\n }\n protected void showExitDialog ( Context context ) {\n Appodeal.show((Activity) context, Appodeal.SKIPPABLE_VIDEO | Appodeal.INTERSTITIAL);\n AlertDialog.Builder exit = new AlertDialog.Builder( context );\n exit.setMessage(R.string.exitText)\n .setTitle(R.string.exitQuestion)\n .setCancelable(false)\n .setPositiveButton(R.string.answerYes,\n new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int id) {\n System.exit(0);\n }\n }\n )\n .setNegativeButton(R.string.answerNo,\n new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int id) {\n return;\n }\n }\n );\n AlertDialog alert = exit.create();\n alert.show();\n }\n protected void showUpdateDialog ( final Context context ) {\n AlertDialog.Builder alert = new AlertDialog.Builder( context );\n alert.setMessage(R.string.updateMessage)\n .setTitle(R.string.updateTitle)\n .setCancelable(false)\n .setPositiveButton(R.string.answerInstallNow,\n new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int id) {\n finish();\n Intent i = new Intent( Intent.ACTION_VIEW );\n i.setData(Uri.parse(\"https://play.google.com/store/apps/details?id=\" + context.getPackageName()));\n context.startActivity(i);\n }\n }\n )\n .setNegativeButton(R.string.answerLater,\n new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int id) {\n finish();\n return;\n }\n }\n );\n AlertDialog alertDialog = alert.create();\n alertDialog.show();\n }\n protected void rate ( Context context ) {\n Intent i = new Intent( Intent.ACTION_VIEW );\n i.setData(Uri.parse(\"https://play.google.com/store/apps/details?id=\" + context.getPackageName()));\n context.startActivity(i);\n }\n protected void share ( Context context ) {\n PackageManager pm = context.getPackageManager();\n Intent sendIntent = new Intent(Intent.ACTION_SEND);\n sendIntent.setType(\"text/plain\");\n List targetedShareIntents = new ArrayList();\n List resInfo = pm.queryIntentActivities(sendIntent, 0);\n if (!resInfo.isEmpty()) {\n for (ResolveInfo info : resInfo) {\n Intent targetedShare = new Intent(android.content.Intent.ACTION_SEND);\n targetedShare.setType(\"text/plain\");\n if (info.activityInfo.packageName.toLowerCase().contains(\"facebook\") || info.activityInfo.name.toLowerCase().contains(\"facebook\") || info.activityInfo.packageName.toLowerCase().contains(\"twitter\") || info.activityInfo.name.toLowerCase().contains(\"twitter\") || info.activityInfo.packageName.toLowerCase().contains(\"vk\") || info.activityInfo.name.toLowerCase().contains(\"vk\")) {\n targetedShare.putExtra(Intent.EXTRA_TEXT, context.getString( context.getApplicationInfo().labelRes) + getString(R.string.shareMessage) + \"https://play.google.com/store/apps/details?id=\" + context.getPackageName());\n targetedShare.setPackage(info.activityInfo.packageName);\n targetedShareIntents.add(targetedShare);\n }\n }\n Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), getString(R.string.sharePickApp));\n chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[]{}));\n context.startActivity(chooserIntent);\n }\n }\n protected void help ( final Context context ) {\n Intent i = new Intent( context, HelpActivity.class );\n context.startActivity(i);\n }\n protected void sendEmail( Context context ){\n Intent myIntent1 = new Intent(android.content.Intent.ACTION_SEND);\n myIntent1.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{\"apiatosin@gmail.com\"});\n final String my1 = Settings.Secure.getString( context.getContentResolver(), Settings.Secure.ANDROID_ID);\n final String my2 = android.os.Build.DEVICE;\n final String my3 = android.os.Build.MANUFACTURER;\n final String my4 = android.os.Build.MODEL;\n final String my5 = android.os.Build.VERSION.RELEASE;\n final int my6 = android.os.Build.VERSION.SDK_INT;\n final String my7 = android.os.Build.BRAND;\n final String my8 = android.os.Build.VERSION.INCREMENTAL;\n final String my9 = android.os.Build.PRODUCT;\n myIntent1.putExtra(android.content.Intent.EXTRA_SUBJECT, \"Support Request: \" + my1 + \" Application: \" + context.getPackageName() + \" Device: \" + my2 + \" Manufacturer: \" + my3 + \" Model: \" + my4 + \" Version: \" + my5 + \" SDK: \" + my6 + \" Brand: \" + my7 + \" Incremental: \" + my8 + \" Product: \" + my9);\n myIntent1.setType(\"text/plain\");\n//IN CASE EMAIL APP FAILS, THEN DEFINE THE OPTION TO LAUNCH SUPPORT WEBSITE\n String url2 = \"\";\n Intent myIntent2 = new Intent(Intent.ACTION_VIEW);\n myIntent2.setData(Uri.parse(url2));\n//IF USER CLICKS THE OK BUTTON, THEN DO THIS\n try {\n// TRY TO LAUNCH TO EMAIL APP\n context.startActivity(Intent.createChooser(myIntent1, \"Send email to Developer\"));\n// startActivity(myIntent1);\n } catch (ActivityNotFoundException ex) {\n// ELSE LAUNCH TO WEB BROWSER\n // activity.startActivity(myIntent2);\n }\n }\n protected boolean isPermissionGranted (){\n return ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED ;\n }\n}"}}},{"rowIdx":346243,"cells":{"answer":{"kind":"string","value":"package com.jasonette.seed.Action;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport android.net.Uri;\nimport android.os.AsyncTask;\nimport android.util.Log;\nimport com.github.scribejava.core.builder.ServiceBuilder;\nimport com.github.scribejava.core.builder.api.DefaultApi10a;\nimport com.github.scribejava.core.builder.api.DefaultApi20;\nimport com.github.scribejava.core.model.OAuth1AccessToken;\nimport com.github.scribejava.core.model.OAuth1RequestToken;\nimport com.github.scribejava.core.model.OAuth2AccessToken;\nimport com.github.scribejava.core.model.OAuthRequest;\nimport com.github.scribejava.core.model.Verb;\nimport com.github.scribejava.core.oauth.OAuth10aService;\nimport com.github.scribejava.core.oauth.OAuth20Service;\nimport com.jasonette.seed.Helper.JasonHelper;\nimport org.json.JSONException;\nimport org.json.JSONObject;\npublic class JasonOauthAction {\n public void auth(final JSONObject action, final JSONObject data, final JSONObject event, final Context context) {\n try {\n final JSONObject options = action.getJSONObject(\"options\");\n if(options.getString(\"version\").equals(\"1\")) {\n //OAuth 1\n JSONObject request_options = options.getJSONObject(\"request\");\n JSONObject authorize_options = options.getJSONObject(\"authorize\");\n String client_id = request_options.getString(\"client_id\");\n String client_secret = request_options.getString(\"client_secret\");\n if(!request_options.has(\"scheme\") || request_options.getString(\"scheme\").length() == 0\n || !request_options.has(\"host\") || request_options.getString(\"host\").length() == 0\n || !request_options.has(\"path\") || request_options.getString(\"path\").length() == 0\n || !authorize_options.has(\"scheme\") || authorize_options.getString(\"scheme\").length() == 0\n || !authorize_options.has(\"host\") || authorize_options.getString(\"host\").length() == 0\n || !authorize_options.has(\"path\") || authorize_options.getString(\"path\").length() == 0\n ) {\n JasonHelper.next(\"error\", action, data, event, context);\n } else {\n JSONObject request_options_data = request_options.getJSONObject(\"data\");\n Uri.Builder uriBuilder = new Uri.Builder();\n uriBuilder.scheme(request_options.getString(\"scheme\"))\n .encodedAuthority(request_options.getString(\"host\"))\n .encodedPath(request_options.getString(\"path\"));\n final String requestUri = uriBuilder.build().toString();\n final Uri.Builder authorizeUriBuilder = new Uri.Builder();\n authorizeUriBuilder.scheme(authorize_options.getString(\"scheme\"))\n .encodedAuthority(authorize_options.getString(\"host\"))\n .encodedPath(authorize_options.getString(\"path\"));\n String callback_uri = request_options_data.getString(\"oauth_callback\");\n DefaultApi10a oauthApi = new DefaultApi10a() {\n @Override\n public String getRequestTokenEndpoint() {\n return requestUri;\n }\n @Override\n public String getAccessTokenEndpoint() {\n return null;\n }\n @Override\n public String getAuthorizationUrl(OAuth1RequestToken requestToken) {\n return authorizeUriBuilder\n .appendQueryParameter(\"oauth_token\", requestToken.getToken())\n .build().toString();\n }\n };\n final OAuth10aService oauthService = new ServiceBuilder()\n .apiKey(client_id)\n .apiSecret(client_secret)\n .callback(callback_uri)\n .build(oauthApi);\n new AsyncTask() {\n @Override\n protected Void doInBackground(String... params) {\n try {\n String client_id = params[0];\n OAuth1RequestToken request_token = oauthService.getRequestToken();\n SharedPreferences preferences = context.getSharedPreferences(\"oauth\", Context.MODE_PRIVATE);\n preferences.edit().putString(client_id + \"_request_token_secret\", request_token.getTokenSecret()).apply();\n String auth_url = oauthService.getAuthorizationUrl(request_token);\n Intent intent = new Intent(Intent.ACTION_VIEW);\n intent.setData(Uri.parse(auth_url));\n context.startActivity(intent);\n } catch(Exception e) {\n handleError(e, action, event, context);\n }\n return null;\n }\n }.execute(client_id);\n }\n } else {\n //OAuth 2\n JSONObject authorize_options = options.getJSONObject(\"authorize\");\n JSONObject authorize_options_data = new JSONObject();\n if(authorize_options.has(\"data\")) {\n authorize_options_data = authorize_options.getJSONObject(\"data\");\n }\n if(authorize_options_data.has(\"grant_type\") && authorize_options_data.getString(\"grant_type\").equals(\"password\")) {\n String client_id = authorize_options.getString(\"client_id\");\n String client_secret = \"\";\n if(authorize_options.has(\"client_secret\")) {\n client_secret = authorize_options.getString(\"client_secret\");\n }\n if(!authorize_options.has(\"scheme\") || authorize_options.getString(\"scheme\").length() == 0\n || !authorize_options.has(\"host\") || authorize_options.getString(\"host\").length() == 0\n || !authorize_options.has(\"path\") || authorize_options.getString(\"path\").length() == 0\n || !authorize_options_data.has(\"username\") || authorize_options_data.getString(\"username\").length() == 0\n || !authorize_options_data.has(\"password\") || authorize_options_data.getString(\"password\").length() == 0\n ) {\n JasonHelper.next(\"error\", action, data, event, context);\n } else {\n String username = authorize_options_data.getString(\"username\");\n String password = authorize_options_data.getString(\"password\");\n Uri.Builder builder = new Uri.Builder();\n builder.scheme(authorize_options.getString(\"scheme\"))\n .encodedAuthority(authorize_options.getString(\"host\"))\n .encodedPath(authorize_options.getString(\"path\"));\n final Uri uri = builder.build();\n DefaultApi20 oauthApi = new DefaultApi20() {\n @Override\n public String getAccessTokenEndpoint() {\n return uri.toString();\n }\n @Override\n protected String getAuthorizationBaseUrl() {\n return null;\n }\n };\n ServiceBuilder serviceBuilder = new ServiceBuilder();\n serviceBuilder.apiKey(client_id);\n if(client_secret.length() > 0) {\n serviceBuilder.apiSecret(client_secret);\n }\n if(authorize_options_data.has(\"scope\") && authorize_options_data.getString(\"scope\").length() > 0) {\n serviceBuilder.scope(authorize_options_data.getString(\"scope\"));\n }\n final OAuth20Service oauthService = serviceBuilder.build(oauthApi);\n new AsyncTask() {\n @Override\n protected Void doInBackground(String... params) {\n try {\n String username = params[0];\n String password = params[1];\n String client_id = params[2];\n String access_token = oauthService.getAccessTokenPasswordGrant(username, password).getAccessToken();\n SharedPreferences preferences = context.getSharedPreferences(\"oauth\", Context.MODE_PRIVATE);\n preferences.edit().putString(client_id, access_token).apply();\n JSONObject result = new JSONObject();\n try {\n result.put(\"token\", access_token);\n JasonHelper.next(\"success\", action, result, event, context);\n } catch(JSONException e) {\n handleError(e, action, event, context);\n }\n } catch(Exception e) {\n handleError(e, action, event, context);\n }\n return null;\n }\n }.execute(username, password, client_id);\n }\n } else {\n if(authorize_options.has(\"data\")) {\n authorize_options_data = authorize_options.getJSONObject(\"data\");\n } else {\n JSONObject error = new JSONObject();\n error.put(\"data\", \"Authorize data missing\");\n JasonHelper.next(\"error\", action, error, event, context);\n }\n //Assuming code auth\n if(authorize_options == null || authorize_options.length() == 0) {\n JasonHelper.next(\"error\", action, data, event, context);\n } else {\n String client_id = authorize_options.getString(\"client_id\");\n String client_secret = \"\";\n String redirect_uri = \"\";\n String scope = \"\";\n //Secret can be missing in implicit authentication\n if(authorize_options.has(\"client_secret\")) {\n client_secret = authorize_options.getString(\"client_secret\");\n }\n if(authorize_options_data.has(\"redirect_uri\")) {\n redirect_uri = authorize_options_data.getString(\"redirect_uri\");\n }\n if(!authorize_options.has(\"scheme\") || authorize_options.getString(\"scheme\").length() == 0\n || !authorize_options.has(\"host\") || authorize_options.getString(\"host\").length() == 0\n || !authorize_options.has(\"path\") || authorize_options.getString(\"path\").length() == 0\n ) {\n JasonHelper.next(\"error\", action, data, event, context);\n } else {\n Uri.Builder builder = new Uri.Builder();\n builder.scheme(authorize_options.getString(\"scheme\"))\n .encodedAuthority(authorize_options.getString(\"host\"))\n .encodedPath(authorize_options.getString(\"path\"));\n final Uri uri = builder.build();\n DefaultApi20 oauthApi = new DefaultApi20() {\n @Override\n public String getAccessTokenEndpoint() {\n return null;\n }\n @Override\n protected String getAuthorizationBaseUrl() {\n return uri.toString();\n }\n };\n ServiceBuilder serviceBuilder = new ServiceBuilder();\n serviceBuilder.apiKey(client_id);\n if(client_secret.length() > 0) {\n serviceBuilder.apiSecret(client_secret);\n }\n if(authorize_options_data.has(\"scope\") && authorize_options_data.getString(\"scope\").length() > 0) {\n serviceBuilder.scope(authorize_options_data.getString(\"scope\"));\n }\n serviceBuilder.callback(redirect_uri);\n OAuth20Service oauthService = serviceBuilder.build(oauthApi);\n Intent intent = new Intent(Intent.ACTION_VIEW);\n intent.setData(Uri.parse(oauthService.getAuthorizationUrl()));\n context.startActivity(intent);\n }\n }\n }\n }\n } catch(JSONException e) {\n handleError(e, action, event, context);\n }\n }\n public void access_token(final JSONObject action, final JSONObject data, final JSONObject event, final Context context) {\n try {\n final JSONObject options = action.getJSONObject(\"options\");\n String client_id = options.getJSONObject(\"access\").getString(\"client_id\");\n SharedPreferences sharedPreferences = context.getSharedPreferences(\"oauth\", Context.MODE_PRIVATE);\n String access_token = sharedPreferences.getString(client_id, null);\n if(access_token != null) {\n JSONObject result = new JSONObject();\n result.put(\"token\", access_token);\n JasonHelper.next(\"success\", action, result, event, context);\n } else {\n JSONObject error = new JSONObject();\n error.put(\"data\", \"access token not found\");\n JasonHelper.next(\"error\", action, error, event, context);\n }\n } catch(JSONException e) {\n try {\n JSONObject error = new JSONObject();\n error.put(\"data\", e.toString());\n JasonHelper.next(\"error\", action, error, event, context);\n } catch(JSONException error) {\n Log.d(\"Error\", error.toString());\n }\n }\n }\n public void oauth_callback(final JSONObject action, final JSONObject data, final JSONObject event, final Context context) {\n try {\n final JSONObject options = action.getJSONObject(\"options\");\n if (options.has(\"version\") && options.getString(\"version\").equals(\"1\")) {\n //OAuth 1\n if(action.has(\"uri\")) {\n Uri uri = Uri.parse(action.getString(\"uri\"));\n String oauth_token = uri.getQueryParameter(\"oauth_token\");\n String oauth_verifier = uri.getQueryParameter(\"oauth_verifier\");\n JSONObject access_options = options.getJSONObject(\"access\");\n if(\n oauth_token.length() > 0 && oauth_verifier.length() > 0\n && access_options.has(\"scheme\") && access_options.getString(\"scheme\").length() > 0\n && access_options.has(\"host\") && access_options.getString(\"host\").length() > 0\n && access_options.has(\"path\") && access_options.getString(\"path\").length() > 0\n && access_options.has(\"path\") && access_options.getString(\"path\").length() > 0\n && access_options.has(\"client_id\") && access_options.getString(\"client_id\").length() > 0\n && access_options.has(\"client_secret\") && access_options.getString(\"client_secret\").length() > 0\n ) {\n String client_id = access_options.getString(\"client_id\");\n String client_secret = access_options.getString(\"client_secret\");\n Uri.Builder uriBuilder = new Uri.Builder();\n uriBuilder.scheme(access_options.getString(\"scheme\"))\n .encodedAuthority(access_options.getString(\"host\"))\n .encodedPath(access_options.getString(\"path\"));\n final String accessUri = uriBuilder.build().toString();\n DefaultApi10a oauthApi = new DefaultApi10a() {\n @Override\n public String getAuthorizationUrl(OAuth1RequestToken requestToken) { return null; }\n @Override\n public String getRequestTokenEndpoint() { return null; }\n @Override\n public String getAccessTokenEndpoint() {\n return accessUri.toString();\n }\n };\n final OAuth10aService oauthService = new ServiceBuilder()\n .apiKey(client_id)\n .apiSecret(client_secret)\n .build(oauthApi);\n new AsyncTask() {\n @Override\n protected Void doInBackground(String... params) {\n try {\n SharedPreferences preferences = context.getSharedPreferences(\"oauth\", Context.MODE_PRIVATE);\n String string_oauth_token = params[0];\n String oauth_verifier = params[1];\n String client_id = params[2];\n String oauth_token_secret = preferences.getString(client_id + \"_request_token_secret\", null);\n OAuth1RequestToken oauthToken = new OAuth1RequestToken(string_oauth_token, oauth_token_secret);\n OAuth1AccessToken access_token = oauthService.getAccessToken(oauthToken, oauth_verifier);\n preferences.edit().putString(client_id, access_token.getToken()).apply();\n preferences.edit().putString(client_id + \"_access_token_secret\", access_token.getTokenSecret()).apply();\n JSONObject result = new JSONObject();\n result.put(\"token\", access_token.getToken());\n JasonHelper.next(\"success\", action, result, event, context);\n } catch(Exception e) {\n handleError(e, action, event, context);\n }\n return null;\n }\n }.execute(oauth_token, oauth_verifier, client_id);\n } else {\n JasonHelper.next(\"error\", action, data, event, context);\n }\n } else {\n JasonHelper.next(\"error\", action, data, event, context);\n }\n } else {\n // OAuth 2\n Uri uri = Uri.parse(action.getString(\"uri\"));\n String access_token = uri.getQueryParameter(\"access_token\"); // get access token from url here\n JSONObject authorize_options = options.getJSONObject(\"authorize\");\n if (access_token != null && access_token.length() > 0) {\n String client_id = authorize_options.getString(\"client_id\");\n SharedPreferences preferences = context.getSharedPreferences(\"oauth\", Context.MODE_PRIVATE);\n preferences.edit().putString(client_id, access_token).apply();\n JSONObject result = new JSONObject();\n result.put(\"token\", access_token);\n JasonHelper.next(\"success\", action, result, event, context);\n } else {\n JSONObject access_options = options.getJSONObject(\"access\");\n final String client_id = access_options.getString(\"client_id\");\n String client_secret = access_options.getString(\"client_secret\");\n String redirect_uri = \"\";\n if(access_options.has(\"redirect_uri\")) {\n redirect_uri = access_options.getString(\"redirect_uri\");\n }\n final String code = uri.getQueryParameter(\"code\");\n if (access_options.length() == 0\n || !access_options.has(\"scheme\") || access_options.getString(\"scheme\").length() == 0\n || !access_options.has(\"host\") || access_options.getString(\"host\").length() == 0\n || !access_options.has(\"path\") || access_options.getString(\"path\").length() == 0\n ) {\n JasonHelper.next(\"error\", action, data, event, context);\n } else {\n final Uri.Builder builder = new Uri.Builder();\n builder.scheme(access_options.getString(\"scheme\"))\n .authority(access_options.getString(\"host\"))\n .appendEncodedPath(access_options.getString(\"path\"));\n if(redirect_uri != \"\") {\n builder.appendQueryParameter(\"redirect_uri\", redirect_uri);\n }\n DefaultApi20 oauthApi = new DefaultApi20() {\n @Override\n public String getAccessTokenEndpoint() {\n return builder.build().toString();\n }\n @Override\n protected String getAuthorizationBaseUrl() {\n return null;\n }\n };\n ServiceBuilder serviceBuilder = new ServiceBuilder();\n serviceBuilder.apiKey(client_id);\n serviceBuilder.apiSecret(client_secret);\n if(redirect_uri != \"\") {\n serviceBuilder.callback(redirect_uri);\n }\n final OAuth20Service oauthService = serviceBuilder.build(oauthApi);\n new AsyncTask() {\n @Override\n protected Void doInBackground(Void... params) {\n try {\n String access_token = oauthService.getAccessToken(code).getAccessToken();\n SharedPreferences preferences = context.getSharedPreferences(\"oauth\", Context.MODE_PRIVATE);\n preferences.edit().putString(client_id, access_token).apply();\n JSONObject result = new JSONObject();\n try {\n result.put(\"token\", access_token);\n } catch(JSONException e) {\n handleError(e, action, event, context);\n }\n JasonHelper.next(\"success\", action, result, event, context);\n } catch(Exception e) {\n handleError(e, action, event, context);\n }\n return null;\n }\n }.execute();\n }\n }\n }\n }\n catch(JSONException e) {\n try {\n JSONObject error = new JSONObject();\n error.put(\"data\", e.toString());\n JasonHelper.next(\"error\", action, error, event, context);\n } catch(JSONException error) {\n Log.d(\"Error\", error.toString());\n }\n }\n }\n public void reset(final JSONObject action, final JSONObject data, final JSONObject event, final Context context) {\n try {\n final JSONObject options = action.getJSONObject(\"options\");\n String client_id = options.getString(\"client_id\");\n if(options.has(\"version\") && options.getString(\"version\").equals(\"1\")) {\n //TODO\n } else {\n SharedPreferences preferences = context.getSharedPreferences(\"oauth\", Context.MODE_PRIVATE);\n preferences.edit().remove(client_id).apply();\n JasonHelper.next(\"success\", action, data, event, context);\n }\n } catch(JSONException e) {\n handleError(e, action, event, context);\n }\n }\n public void request(final JSONObject action, final JSONObject data, final JSONObject event, final Context context) {\n try {\n JSONObject options = action.getJSONObject(\"options\");\n String client_id = options.getString(\"client_id\");\n String client_secret = \"\";\n if(options.has(\"client_secret\") && options.getString(\"client_secret\").length() > 0) {\n client_secret = options.getString(\"client_secret\");\n }\n SharedPreferences sharedPreferences = context.getSharedPreferences(\"oauth\", Context.MODE_PRIVATE);\n String access_token = sharedPreferences.getString(client_id, null);\n String path = options.getString(\"path\");\n String scheme = options.getString(\"scheme\");\n String host = options.getString(\"host\");\n String method;\n if(options.has(\"method\")) {\n method = options.getString(\"method\");\n } else {\n method = \"GET\";\n }\n if(access_token != null && access_token.length() > 0) {\n if(options.has(\"version\") && options.getString(\"version\").equals(\"1\")) {\n DefaultApi10a oauthApi = new DefaultApi10a() {\n @Override\n public String getRequestTokenEndpoint() { return null; }\n @Override\n public String getAccessTokenEndpoint() { return null; }\n @Override\n public String getAuthorizationUrl(OAuth1RequestToken requestToken) { return null; }\n };\n ServiceBuilder serviceBuilder = new ServiceBuilder();\n serviceBuilder.apiKey(client_id);\n if(client_secret.length() > 0) {\n serviceBuilder.apiSecret(client_secret);\n }\n final OAuth10aService oauthService = serviceBuilder.build(oauthApi);\n Uri.Builder uriBuilder = new Uri.Builder();\n uriBuilder.scheme(scheme);\n uriBuilder.encodedAuthority(host);\n uriBuilder.path(path);\n Uri uri = uriBuilder.build();\n String url = uri.toString();\n final OAuthRequest request = new OAuthRequest(Verb.valueOf(method), url);\n String access_token_secret = sharedPreferences.getString(client_id + \"_access_token_secret\", null);\n oauthService.signRequest(new OAuth1AccessToken(access_token, access_token_secret), request);\n new AsyncTask() {\n @Override\n protected Void doInBackground(Void... voids) {\n try {\n com.github.scribejava.core.model.Response response = oauthService.execute(request);\n JasonHelper.next(\"success\", action, response.getBody(), event, context);\n } catch(Exception e) {\n handleError(e, action, event, context);\n }\n return null;\n }\n }.execute();\n } else {\n DefaultApi20 oauthApi = new DefaultApi20() {\n @Override\n public String getAccessTokenEndpoint() {\n return null;\n }\n @Override\n protected String getAuthorizationBaseUrl() {\n return null;\n }\n };\n ServiceBuilder serviceBuilder = new ServiceBuilder();\n serviceBuilder.apiKey(client_id);\n if(client_secret.length() > 0) {\n serviceBuilder.apiSecret(client_secret);\n }\n final OAuth20Service oauthService = serviceBuilder.build(oauthApi);\n Uri.Builder uriBuilder = new Uri.Builder();\n uriBuilder.scheme(scheme);\n uriBuilder.encodedAuthority(host);\n uriBuilder.encodedPath(path);\n Uri uri = uriBuilder.build();\n String url = uri.toString();\n final OAuthRequest request = new OAuthRequest(Verb.valueOf(method), url);\n oauthService.signRequest(new OAuth2AccessToken(access_token), request);\n new AsyncTask() {\n @Override\n protected Void doInBackground(Void... voids) {\n try {\n com.github.scribejava.core.model.Response response = oauthService.execute(request);\n JasonHelper.next(\"success\", action, response.getBody(), event, context);\n } catch(Exception e) {\n handleError(e, action, event, context);\n }\n return null;\n }\n }.execute();\n }\n } else {\n JasonHelper.next(\"error\", action, data, event, context);\n }\n //change exception\n } catch(JSONException e) {\n handleError(e, action, event, context);\n }\n }\n private void handleError(Exception e, JSONObject action, JSONObject event, Context context) {\n try {\n JSONObject error = new JSONObject();\n error.put(\"data\", e.toString());\n JasonHelper.next(\"error\", action, error, event, context);\n } catch(JSONException error) {\n Log.d(\"Error\", error.toString());\n }\n }\n}"}}},{"rowIdx":346244,"cells":{"answer":{"kind":"string","value":"package com.t28.rxweather.fragment;\nimport android.app.Activity;\nimport android.app.Fragment;\nimport android.os.Bundle;\nimport android.support.annotation.Nullable;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport com.t28.rxweather.R;\nimport com.t28.rxweather.data.model.Coordinate;\nimport com.t28.rxweather.data.model.MainAttribute;\nimport com.t28.rxweather.data.model.Weather;\nimport com.t28.rxweather.data.service.WeatherService;\nimport com.t28.rxweather.rx.CoordinateEventBus;\nimport com.t28.rxweather.volley.RequestQueueRetriever;\nimport butterknife.ButterKnife;\nimport butterknife.InjectView;\nimport rx.Observable;\nimport rx.Observer;\nimport rx.android.observables.AndroidObservable;\nimport rx.android.schedulers.AndroidSchedulers;\nimport rx.functions.Func1;\nimport rx.schedulers.Schedulers;\npublic class WeatherFragment extends Fragment {\n @InjectView(R.id.weather_temperature)\n TextView mTemperatureView;\n @InjectView(R.id.weather_min_temperature)\n TextView mMinTemperatureView;\n @InjectView(R.id.weather_max_temperature)\n TextView mMaxTemperatureView;\n private WeatherService mWeatherService;\n public WeatherFragment() {\n setRetainInstance(true);\n }\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n mWeatherService = new WeatherService(\"\", RequestQueueRetriever.retrieve());\n AndroidObservable.bindFragment(this, createWeatherObservable())\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe(new Observer() {\n @Override\n public void onCompleted() {\n }\n @Override\n public void onError(Throwable cause) {\n onFailure(cause);\n }\n @Override\n public void onNext(Weather result) {\n onSuccess(result);\n }\n });\n }\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater,\n ViewGroup container, Bundle savedInstanceState) {\n final View view = inflater.inflate(R.layout.fragment_weather, container, false);\n ButterKnife.inject(this, view);\n return view;\n }\n @Override\n public void onDestroyView() {\n ButterKnife.reset(this);\n super.onDestroyView();\n }\n private void onSuccess(Weather result) {\n if (isDetached()) {\n return;\n }\n final Activity activity = getActivity();\n Toast.makeText(activity, result.toString(), Toast.LENGTH_SHORT).show();\n final MainAttribute attribute = result.getAttribute();\n mTemperatureView.setText(String.valueOf(attribute.getTemperature()));\n mMinTemperatureView.setText(String.valueOf(attribute.getMinTemperature()));\n mMaxTemperatureView.setText(String.valueOf(attribute.getMaxTemperature()));\n }\n private void onFailure(Throwable cause) {\n if (isDetached()) {\n return;\n }\n final Activity activity = getActivity();\n Toast.makeText(activity, cause.toString(), Toast.LENGTH_SHORT).show();\n }\n private Observable createWeatherObservable() {\n return CoordinateEventBus.Retriever.retrieve()\n .getEventStream()\n .flatMap(new Func1>() {\n @Override\n public Observable call(Coordinate coordinate) {\n return mWeatherService.findWeather(coordinate);\n }\n });\n }\n}"}}},{"rowIdx":346245,"cells":{"answer":{"kind":"string","value":"package com.walkap.x_android.fragment;\nimport android.content.Context;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.support.design.widget.TabLayout;\nimport android.support.v4.app.Fragment;\nimport android.support.v4.view.ViewPager;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport com.walkap.x_android.R;\nimport com.walkap.x_android.adapter.SectionsPagerAdapter;\nimport java.util.Calendar;\n/**\n * A simple {@link Fragment} subclass.\n * Activities that contain this fragment must implement the\n * {@link HomeFragment.OnFragmentInteractionListener} interface\n * to handle interaction events.\n * Use the {@link HomeFragment#newInstance} factory method to\n * create an instance of this fragment.\n */\npublic class HomeFragment extends BaseFragment{\n private OnFragmentInteractionListener mListener;\n private final String TAG = \"HomeFragment\";\n private SectionsPagerAdapter mSectionsPagerAdapter;\n private ViewPager mViewPager;\n private Calendar calendar = Calendar.getInstance();\n private int day = calendar.get(Calendar.DAY_OF_WEEK) - 2;\n public HomeFragment() {\n // Required empty public constructor\n }\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n }\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n // Inflate the layout for this fragment\n View rootView = inflater.inflate(R.layout.fragment_home, container, false);\n TabLayout tabLayout = (TabLayout) rootView.findViewById(R.id.tabs);\n mViewPager = (ViewPager) rootView.findViewById(R.id.view_pager);\n mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager());\n mViewPager.setAdapter(mSectionsPagerAdapter);\n mViewPager.setOffscreenPageLimit(6);\n tabLayout.setupWithViewPager(mViewPager);\n mViewPager.setCurrentItem(day);\n return rootView;\n }\n @Override\n public void onStart(){\n super.onStart();\n }\n // TODO: Rename method, update argument and hook method into UI event\n public void onButtonPressed(Uri uri) {\n if (mListener != null) {\n mListener.onFragmentInteraction(uri);\n }\n }\n @Override\n public void onAttach(Context context) {\n super.onAttach(context);\n if (context instanceof OnFragmentInteractionListener) {\n mListener = (OnFragmentInteractionListener) context;\n } else {\n throw new RuntimeException(context.toString()\n + \" must implement OnFragmentInteractionListener\");\n }\n }\n @Override\n public void onDetach() {\n super.onDetach();\n mListener = null;\n }\n public interface OnFragmentInteractionListener {\n // TODO: Update argument type and name\n void onFragmentInteraction(Uri uri);\n }\n}"}}},{"rowIdx":346246,"cells":{"answer":{"kind":"string","value":"package com.zulip.android.activities;\nimport java.sql.SQLException;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.concurrent.Callable;\nimport java.util.ArrayList;\nimport android.animation.Animator;\nimport android.annotation.SuppressLint;\nimport android.annotation.TargetApi;\nimport android.app.AlertDialog;\nimport android.app.SearchManager;\nimport android.content.BroadcastReceiver;\nimport android.content.ComponentName;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.content.SharedPreferences;\nimport android.content.res.Configuration;\nimport android.database.Cursor;\nimport android.database.MatrixCursor;\nimport android.database.MergeCursor;\nimport android.graphics.Bitmap;\nimport android.graphics.PorterDuff;\nimport android.graphics.drawable.Drawable;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.CountDownTimer;\nimport android.os.Handler;\nimport android.support.design.widget.AppBarLayout;\nimport android.support.design.widget.FloatingActionButton;\nimport android.support.v4.app.ActionBarDrawerToggle;\nimport android.support.v4.app.FragmentManager;\nimport android.support.v4.app.FragmentTransaction;\nimport android.support.v4.content.ContextCompat;\nimport android.support.v4.view.GravityCompat;\nimport android.support.v4.view.MenuItemCompat;\nimport android.support.v4.view.animation.FastOutSlowInInterpolator;\nimport android.support.v4.widget.DrawerLayout;\nimport android.support.v4.widget.SimpleCursorAdapter;\nimport android.support.v7.app.AppCompatActivity;\nimport android.support.v7.app.AppCompatDelegate;\nimport android.support.v7.widget.Toolbar;\nimport android.text.TextUtils;\nimport android.util.Log;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.view.ViewPropertyAnimator;\nimport android.view.animation.Interpolator;\nimport android.view.inputmethod.InputMethodManager;\nimport android.widget.AdapterView;\nimport android.widget.AdapterView.OnItemClickListener;\nimport android.widget.AutoCompleteTextView;\nimport android.widget.EditText;\nimport android.widget.ExpandableListView;\nimport android.widget.FilterQueryProvider;\nimport android.widget.ImageView;\nimport android.widget.LinearLayout;\nimport android.widget.ListView;\nimport android.widget.SimpleCursorTreeAdapter;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport com.j256.ormlite.android.AndroidDatabaseResults;\nimport com.zulip.android.BuildConfig;\nimport com.zulip.android.database.DatabaseHelper;\nimport com.zulip.android.models.Emoji;\nimport com.zulip.android.filters.NarrowFilterToday;\nimport com.zulip.android.models.Message;\nimport com.zulip.android.models.MessageType;\nimport com.zulip.android.filters.NarrowFilter;\nimport com.zulip.android.filters.NarrowFilterAllPMs;\nimport com.zulip.android.filters.NarrowFilterPM;\nimport com.zulip.android.filters.NarrowFilterSearch;\nimport com.zulip.android.filters.NarrowFilterStream;\nimport com.zulip.android.filters.NarrowListener;\nimport com.zulip.android.gcm.Notifications;\nimport com.zulip.android.models.Person;\nimport com.zulip.android.models.Presence;\nimport com.zulip.android.models.PresenceType;\nimport com.zulip.android.R;\nimport com.zulip.android.models.Stream;\nimport com.zulip.android.networking.AsyncSend;\nimport com.zulip.android.util.AnimationHelper;\nimport com.zulip.android.util.SwipeRemoveLinearLayout;\nimport com.zulip.android.util.ZLog;\nimport com.zulip.android.ZulipApp;\nimport com.zulip.android.gcm.GcmBroadcastReceiver;\nimport com.zulip.android.networking.AsyncGetEvents;\nimport com.zulip.android.networking.AsyncStatusUpdate;\nimport com.zulip.android.networking.ZulipAsyncPushTask;\nimport org.json.JSONObject;\n/**\n * The main Activity responsible for holding the {@link MessageListFragment} which has the list to the\n * messages\n * */\npublic class ZulipActivity extends AppCompatActivity implements\n MessageListFragment.Listener, NarrowListener, SwipeRemoveLinearLayout.leftToRightSwipeListener {\n private static final String NARROW = \"narrow\";\n private static final String PARAMS = \"params\";\n //At these many letters the emoji/person hint will not show now on\n private static final int MAX_THRESOLD_EMOJI_HINT = 5;\n //At these many letters the emoji/person hint starts to show up\n private static final int MIN_THRESOLD_EMOJI_HINT = 1;\n private ZulipApp app;\n private List mutedTopics;\n private boolean suspended = false;\n private boolean logged_in = false;\n private ZulipActivity that = this; // self-ref\n private SharedPreferences settings;\n String client_id;\n private DrawerLayout drawerLayout;\n private ActionBarDrawerToggle drawerToggle;\n private ExpandableListView streamsDrawer;\n private static final Interpolator FAST_OUT_SLOW_IN_INTERPOLATOR = new FastOutSlowInInterpolator();\n private SwipeRemoveLinearLayout chatBox;\n private FloatingActionButton fab;\n private CountDownTimer fabHidder;\n private boolean isTextFieldFocused = false;\n private static final int HIDE_FAB_AFTER_SEC = 5;\n private HashMap gravatars = new HashMap<>();\n private AsyncGetEvents event_poll;\n private Handler statusUpdateHandler;\n private Toolbar toolbar;\n public MessageListFragment currentList;\n private MessageListFragment narrowedList;\n private MessageListFragment homeList;\n private AutoCompleteTextView streamActv;\n private AutoCompleteTextView topicActv;\n private AutoCompleteTextView messageEt;\n private TextView textView;\n private ImageView sendBtn;\n private ImageView togglePrivateStreamBtn;\n private Notifications notifications;\n private SimpleCursorAdapter streamActvAdapter;\n private SimpleCursorAdapter subjectActvAdapter;\n private SimpleCursorAdapter emailActvAdapter;\n private BroadcastReceiver onGcmMessage = new BroadcastReceiver() {\n public void onReceive(Context contenxt, Intent intent) {\n // Block the event before it propagates to show a notification.\n // TODO: could be smarter and only block the event if the message is\n // in the narrow.\n Log.i(\"GCM\", \"Dropping a push because the activity is active\");\n abortBroadcast();\n }\n };\n @Override\n public void removeChatBox(boolean animToRight) {\n AnimationHelper.hideViewX(chatBox, animToRight);\n }\n // Intent Extra constants\n public enum Flag {\n RESET_DATABASE,\n }\n public HashMap getGravatars() {\n return gravatars;\n }\n private SimpleCursorAdapter.ViewBinder peopleBinder = new SimpleCursorAdapter.ViewBinder() {\n @Override\n public boolean setViewValue(View view, Cursor cursor, int i) {\n switch (view.getId()) {\n case R.id.name:\n TextView name = (TextView) view;\n name.setText(cursor.getString(i));\n return true;\n case R.id.stream_dot:\n String email = cursor.getString(i);\n if (app == null || email == null) {\n view.setVisibility(View.INVISIBLE);\n } else {\n Presence presence = app.presences.get(email);\n if (presence == null) {\n view.setVisibility(View.INVISIBLE);\n } else {\n PresenceType status = presence.getStatus();\n long age = presence.getAge();\n if (age > 2 * 60) {\n view.setVisibility(View.VISIBLE);\n view.setBackgroundResource(R.drawable.presence_inactive);\n } else if (PresenceType.ACTIVE == status) {\n view.setVisibility(View.VISIBLE);\n view.setBackgroundResource(R.drawable.presence_active);\n } else if (PresenceType.IDLE == status) {\n view.setVisibility(View.VISIBLE);\n view.setBackgroundResource(R.drawable.presence_away);\n } else {\n view.setVisibility(View.INVISIBLE);\n }\n }\n }\n return true;\n default:\n break;\n }\n return false;\n }\n };\n private RefreshableCursorAdapter peopleAdapter;\n @Override\n public void addToList(Message message) {\n mutedTopics.add(message);\n }\n @Override\n public void muteTopic(Message message) {\n app.muteTopic(message);\n for (int i = homeList.adapter.getItemCount() - 1; i >= 0; i\n Object object = homeList.adapter.getItem(i);\n if (object instanceof Message) {\n Message msg = (Message) object;\n if (msg.getStream() != null\n && msg.getStream().getId() == message.getStream().getId()\n && msg.getSubject().equals(message.getSubject())) {\n mutedTopics.add(msg);\n homeList.adapter.remove(msg);\n }\n }\n }\n homeList.adapter.notifyDataSetChanged();\n }\n @Override\n public void recyclerViewScrolled() {\n if (chatBox.getVisibility() == View.VISIBLE && !isTextFieldFocused) {\n displayChatBox(false);\n displayFAB(true);\n }\n }\n public RefreshableCursorAdapter getPeopleAdapter() {\n return peopleAdapter;\n }\n /**\n * Called when the activity is first created.\n */\n @SuppressLint(\"NewApi\")\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n app = (ZulipApp) getApplicationContext();\n settings = app.getSettings();\n processParams();\n if (!app.isLoggedIn()) {\n openLogin();\n return;\n }\n this.logged_in = true;\n notifications = new Notifications(this);\n notifications.register();\n setContentView(R.layout.main);\n toolbar = (Toolbar) findViewById(R.id.toolbar);\n setSupportActionBar(toolbar);\n getSupportActionBar().setDisplayHomeAsUpEnabled(true);\n getSupportActionBar().setHomeButtonEnabled(true);\n getSupportActionBar().setTitle(R.string.app_name);\n getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu_24dp);\n streamActv = (AutoCompleteTextView) findViewById(R.id.stream_actv);\n topicActv = (AutoCompleteTextView) findViewById(R.id.topic_actv);\n messageEt = (AutoCompleteTextView) findViewById(R.id.message_et);\n textView = (TextView) findViewById(R.id.textView);\n sendBtn = (ImageView) findViewById(R.id.send_btn);\n togglePrivateStreamBtn = (ImageView) findViewById(R.id.togglePrivateStream_btn);\n mutedTopics = new ArrayList<>();\n drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);\n drawerToggle = new ActionBarDrawerToggle(this, drawerLayout,\n R.drawable.ic_drawer, R.string.streams_open,\n R.string.streams_close) {\n /** Called when a drawer has settled in a completely closed state. */\n public void onDrawerClosed(View view) {\n // pass\n }\n /** Called when a drawer has settled in a completely open state. */\n public void onDrawerOpened(View drawerView) {\n // pass\n }\n };\n // Set the drawer toggle as the DrawerListener\n drawerLayout.setDrawerListener(drawerToggle);\n ListView peopleDrawer = (ListView) findViewById(R.id.people_drawer);\n // row number which is used to differentiate the 'All private messages'\n // row from the people\n final int allPeopleId = -1;\n Callable peopleGenerator = new Callable() {\n @Override\n public Cursor call() throws Exception {\n // TODO Auto-generated method stub\n List people = app.getDao(Person.class).queryBuilder()\n .where().eq(Person.ISBOT_FIELD, false).and()\n .eq(Person.ISACTIVE_FIELD, true).query();\n Person.sortByPresence(app, people);\n String[] columnsWithPresence = new String[]{\"_id\",\n Person.EMAIL_FIELD, Person.NAME_FIELD};\n MatrixCursor sortedPeopleCursor = new MatrixCursor(\n columnsWithPresence);\n for (Person person : people) {\n Object[] row = new Object[]{person.getId(), person.getEmail(),\n person.getName()};\n sortedPeopleCursor.addRow(row);\n }\n // add private messages row\n MatrixCursor allPrivateMessages = new MatrixCursor(\n sortedPeopleCursor.getColumnNames());\n Object[] row = new Object[]{allPeopleId, \"\",\n \"All private messages\"};\n allPrivateMessages.addRow(row);\n return new MergeCursor(new Cursor[]{\n allPrivateMessages, sortedPeopleCursor});\n }\n };\n try {\n this.peopleAdapter = new RefreshableCursorAdapter(\n this.getApplicationContext(), R.layout.stream_tile,\n peopleGenerator.call(), peopleGenerator, new String[]{\n Person.NAME_FIELD, Person.EMAIL_FIELD}, new int[]{\n R.id.name, R.id.stream_dot}, 0);\n peopleAdapter.setViewBinder(peopleBinder);\n peopleDrawer.setAdapter(peopleAdapter);\n } catch (SQLException e) {\n throw new RuntimeException(e);\n } catch (Exception e) {\n ZLog.logException(e);\n }\n peopleDrawer.setOnItemClickListener(new OnItemClickListener() {\n @Override\n public void onItemClick(AdapterView parent, View view,\n int position, long id) {\n if (id == allPeopleId) {\n doNarrow(new NarrowFilterAllPMs(app.getYou()));\n } else {\n narrow_pm_with(Person.getById(app, (int) id));\n }\n }\n });\n // send status update and check again every couple minutes\n statusUpdateHandler = new Handler();\n Runnable statusUpdateRunnable = new Runnable() {\n @Override\n public void run() {\n AsyncStatusUpdate task = new AsyncStatusUpdate(\n ZulipActivity.this);\n task.setCallback(new ZulipAsyncPushTask.AsyncTaskCompleteListener() {\n @Override\n public void onTaskComplete(String result, JSONObject object) {\n peopleAdapter.refresh();\n }\n @Override\n public void onTaskFailure(String result) {\n }\n });\n task.execute();\n statusUpdateHandler.postDelayed(this, 2 * 60 * 1000);\n }\n };\n statusUpdateHandler.post(statusUpdateRunnable);\n homeList = MessageListFragment.newInstance(null);\n pushListFragment(homeList, null);\n togglePrivateStreamBtn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n switchView();\n }\n });\n sendBtn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n sendMessage();\n }\n });\n composeStatus = (LinearLayout) findViewById(R.id.composeStatus);\n setUpAdapter();\n streamActv.setAdapter(streamActvAdapter);\n topicActv.setAdapter(subjectActvAdapter);\n checkAndSetupStreamsDrawer();\n setupFab();\n View.OnFocusChangeListener focusChangeListener = new View.OnFocusChangeListener() {\n @Override\n public void onFocusChange(View view, boolean focus) {\n isTextFieldFocused = focus;\n }\n };\n messageEt.setOnFocusChangeListener(focusChangeListener);\n topicActv.setOnFocusChangeListener(focusChangeListener);\n streamActv.setOnFocusChangeListener(focusChangeListener);\n SimpleCursorAdapter combinedAdapter = new SimpleCursorAdapter(\n that, R.layout.emoji_tile, null,\n new String[]{Emoji.NAME_FIELD, Emoji.NAME_FIELD},\n new int[]{R.id.emojiImageView, R.id.nameTV}, 0);\n combinedAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {\n @Override\n public boolean setViewValue(View view, Cursor cursor, int columnIndex) {\n //TODO - columnIndex is 6 for Person table and columnIndex is 1 for Emoji table, Confirm this will be perfect to distinguish between these two tables! It seems alphabetical ordering of columns!\n boolean personTable = !(columnIndex == 1);\n String name = cursor.getString(cursor.getColumnIndex(Emoji.NAME_FIELD));\n switch (view.getId()) {\n case R.id.emojiImageView:\n if (personTable) {\n view.setVisibility(View.GONE);\n } else {\n try {\n Drawable drawable = Drawable.createFromStream(getApplicationContext().getAssets().open(\"emoji/\" + name),\n \"emoji/\" + name);\n ((ImageView) view).setImageDrawable(drawable);\n } catch (Exception e) {\n ZLog.logException(e);\n }\n }\n return true;\n case R.id.nameTV:\n ((TextView) view).setText(name);\n return true;\n }\n if (BuildConfig.DEBUG)\n ZLog.logException(new RuntimeException(getResources().getResourceName(view.getId()) + \" - this view not binded!\"));\n return false;\n }\n });\n combinedAdapter.setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() {\n @Override\n public CharSequence convertToString(Cursor cursor) {\n if (cursor == null) return messageEt.getText();\n int index = cursor.getColumnIndex(Emoji.NAME_FIELD);\n String name = cursor.getString(index);\n String currText = messageEt.getText().toString();\n int last = (cursor.getColumnIndex(Emoji.NAME_FIELD) == 6) ? currText.lastIndexOf(\"@\") : currText.lastIndexOf(\":\");\n return TextUtils.substring(currText, 0, last) + ((cursor.getColumnIndex(Emoji.NAME_FIELD) == 6) ? \"@**\" + name + \"**\" : \":\" + name.replace(\".png\", \"\") + \":\");\n }\n });\n combinedAdapter.setFilterQueryProvider(new FilterQueryProvider() {\n @Override\n public Cursor runQuery(CharSequence charSequence) {\n if (charSequence == null) return null;\n int length = charSequence.length();\n int personLength = charSequence.toString().lastIndexOf(\"@\");\n int smileyLength = charSequence.toString().lastIndexOf(\":\");\n if (length - 1 > Math.max(personLength, smileyLength) + MAX_THRESOLD_EMOJI_HINT\n || length - Math.max(personLength, smileyLength) - 1 < MIN_THRESOLD_EMOJI_HINT\n || (personLength + smileyLength == -2))\n return null;\n try {\n if (personLength > smileyLength) {\n return makePeopleNameCursor(charSequence.subSequence(personLength + 1, length));\n } else {\n return makeEmojiCursor(charSequence.subSequence(smileyLength + 1, length));\n }\n } catch (SQLException e) {\n Log.e(\"SQLException\", \"SQL not correct\", e);\n return null;\n }\n }\n });\n messageEt.setAdapter(combinedAdapter);\n }\n /**\n * Returns a cursor for the combinedAdapter used to suggest Emoji when ':' is typed in the {@link #messageEt}\n * @param emoji A string to search in the existing database\n */\n private Cursor makeEmojiCursor(CharSequence emoji)\n throws SQLException {\n if (emoji == null) {\n emoji = \"\";\n }\n return ((AndroidDatabaseResults) app\n .getDao(Emoji.class)\n .queryRaw(\"SELECT rowid _id,name FROM emoji WHERE name LIKE '%\" + emoji + \"%'\")\n .closeableIterator().getRawResults()).getRawCursor();\n }\n private Cursor makePeopleNameCursor(CharSequence name) throws SQLException {\n if (name == null) {\n name = \"\";\n }\n return ((AndroidDatabaseResults) app\n .getDao(Person.class)\n .queryRaw(\n \"SELECT rowid _id, * FROM people WHERE \"\n + Person.ISBOT_FIELD + \" = 0 AND \"\n + Person.ISACTIVE_FIELD + \" = 1 AND \"\n + Person.NAME_FIELD\n + \" LIKE ? ESCAPE '\\\\' ORDER BY \"\n + Person.NAME_FIELD + \" COLLATE NOCASE\",\n DatabaseHelper.likeEscape(name.toString()) + \"%\")\n .closeableIterator().getRawResults()).getRawCursor();\n }\n private void setupFab() {\n fab = (FloatingActionButton) findViewById(R.id.fab);\n chatBox = (SwipeRemoveLinearLayout) findViewById(R.id.messageBoxContainer);\n chatBox.registerToSwipeEvents(this);\n fabHidder = new CountDownTimer(HIDE_FAB_AFTER_SEC * 1000, HIDE_FAB_AFTER_SEC * 1000) {\n public void onTick(long millisUntilFinished) {\n }\n public void onFinish() {\n if (!isTextFieldFocused) {\n displayFAB(true);\n displayChatBox(false);\n } else {\n start();\n }\n }\n };\n fab.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n currentList.stopRecyclerViewScroll();\n displayChatBox(true);\n displayFAB(false);\n fabHidder.start();\n }\n });\n }\n private void displayChatBox(boolean show) {\n if (show) {\n showView(chatBox);\n } else {\n hideView(chatBox);\n }\n }\n private void displayFAB(boolean show) {\n if (show) {\n showView(fab);\n } else {\n hideView(fab);\n }\n }\n public void hideView(final View view) {\n ViewPropertyAnimator animator = view.animate()\n .translationY((view instanceof AppBarLayout) ? -1 * view.getHeight() : view.getHeight())\n .setInterpolator(FAST_OUT_SLOW_IN_INTERPOLATOR)\n .setDuration(200);\n animator.setListener(new Animator.AnimatorListener() {\n @Override\n public void onAnimationStart(Animator animator) {\n }\n @Override\n public void onAnimationEnd(Animator animator) {\n view.setVisibility(View.GONE);\n }\n @Override\n public void onAnimationCancel(Animator animator) {\n }\n @Override\n public void onAnimationRepeat(Animator animator) {\n }\n });\n animator.start();\n }\n public void showView(final View view) {\n ViewPropertyAnimator animator = view.animate()\n .translationY(0)\n .setInterpolator(FAST_OUT_SLOW_IN_INTERPOLATOR)\n .setDuration(200);\n animator.setListener(new Animator.AnimatorListener() {\n @Override\n public void onAnimationStart(Animator animator) {\n view.setVisibility(View.VISIBLE);\n }\n @Override\n public void onAnimationEnd(Animator animator) {\n }\n @Override\n public void onAnimationCancel(Animator animator) {\n }\n @Override\n public void onAnimationRepeat(Animator animator) {\n }\n });\n animator.start();\n }\n Callable streamsGenerator = new Callable() {\n @Override\n public Cursor call() throws Exception {\n int pointer = app.getPointer();\n return ((AndroidDatabaseResults) app.getDao(Stream.class).queryRaw(\"SELECT s.id as _id, s.name, s.color,\" +\n \" count(case when m.id > \" + pointer + \" then 1 end) as \" + ExpandableStreamDrawerAdapter.UNREAD_TABLE_NAME\n + \" FROM streams as s LEFT JOIN messages as m ON s.id=m.stream group by s.name order by s.name COLLATE NOCASE\").closeableIterator().getRawResults()).getRawCursor();\n }\n };\n /**\n * Setup the streams Drawer which has a {@link ExpandableListView} categorizes the stream and subject\n */\n private void setupListViewAdapter() {\n ExpandableStreamDrawerAdapter streamsDrawerAdapter = null;\n String[] groupFrom = {Stream.NAME_FIELD, Stream.COLOR_FIELD, ExpandableStreamDrawerAdapter.UNREAD_TABLE_NAME};\n int[] groupTo = {R.id.name, R.id.stream_dot, R.id.unread_group};\n // Comparison of data elements and View\n String[] childFrom = {Message.SUBJECT_FIELD, ExpandableStreamDrawerAdapter.UNREAD_TABLE_NAME};\n int[] childTo = {R.id.name_child, R.id.unread_child};\n final ExpandableListView streamsDrawer = (ExpandableListView) findViewById(R.id.streams_drawer);\n streamsDrawer.setGroupIndicator(null);\n try {\n streamsDrawerAdapter = new ExpandableStreamDrawerAdapter(this, streamsGenerator.call(),\n R.layout.stream_tile_new, groupFrom,\n groupTo, R.layout.stream_tile_child, childFrom,\n childTo);\n } catch (Exception e) {\n ZLog.logException(e);\n }\n streamsDrawer.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {\n @Override\n public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {\n switch (v.getId()) {\n case R.id.name_child:\n String streamName = ((Cursor) streamsDrawer.getExpandableListAdapter().getGroup(groupPosition)).getString(1);\n String subjectName = ((TextView) v).getText().toString();\n onNarrow(new NarrowFilterStream(streamName, subjectName));\n onNarrowFillSendBoxStream(streamName, subjectName, false);\n break;\n default:\n return false;\n }\n return false;\n }\n });\n streamsDrawer.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {\n int previousClick = -1;\n @Override\n public boolean onGroupClick(ExpandableListView expandableListView, View view, int position, long l) {\n String streamName = ((TextView) view.findViewById(R.id.name)).getText().toString();\n doNarrow(new NarrowFilterStream(streamName, null));\n drawerLayout.openDrawer(GravityCompat.START);\n if (previousClick != -1 && expandableListView.getCount() > previousClick) {\n expandableListView.collapseGroup(previousClick);\n }\n expandableListView.expandGroup(position);\n previousClick = position;\n return true;\n }\n });\n streamsDrawerAdapter.setViewBinder(new SimpleCursorTreeAdapter.ViewBinder() {\n @Override\n public boolean setViewValue(View view, Cursor cursor, int columnIndex) {\n switch (view.getId()) {\n case R.id.name:\n TextView name = (TextView) view;\n final String streamName = cursor.getString(columnIndex);\n name.setText(streamName);\n //Change color in the drawer if this stream is inHomeView only.\n if (!Stream.getByName(app, streamName).getInHomeView()) {\n name.setTextColor(ContextCompat.getColor(ZulipActivity.this, R.color.colorTextTertiary));\n } else {\n name.setTextColor(ContextCompat.getColor(ZulipActivity.this, R.color.colorTextPrimary));\n }\n view.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n onNarrow(new NarrowFilterStream(streamName, null));\n onNarrowFillSendBoxStream(streamName, \"\", false);\n }\n });\n return true;\n case R.id.stream_dot:\n // Set the color of the (currently white) dot\n view.setVisibility(View.VISIBLE);\n view.getBackground().setColorFilter(cursor.getInt(columnIndex),\n PorterDuff.Mode.MULTIPLY);\n return true;\n case R.id.unread_group:\n TextView unreadGroupTextView = (TextView) view;\n final String unreadGroupCount = cursor.getString(columnIndex);\n if (unreadGroupCount.equals(\"0\")) {\n unreadGroupTextView.setVisibility(View.GONE);\n } else {\n unreadGroupTextView.setText(unreadGroupCount);\n unreadGroupTextView.setVisibility(View.VISIBLE);\n }\n return true;\n case R.id.unread_child:\n TextView unreadChildTextView = (TextView) view;\n final String unreadChildNumber = cursor.getString(columnIndex);\n if (unreadChildNumber.equals(\"0\")) {\n unreadChildTextView.setVisibility(View.GONE);\n } else {\n unreadChildTextView.setText(unreadChildNumber);\n unreadChildTextView.setVisibility(View.VISIBLE);\n }\n return true;\n case R.id.name_child:\n TextView name_child = (TextView) view;\n name_child.setText(cursor.getString(columnIndex));\n if (app.isTopicMute(cursor.getInt(1), cursor.getString(columnIndex))) {\n name_child.setTextColor(ContextCompat.getColor(ZulipActivity.this, R.color.colorTextSecondary));\n }\n return true;\n }\n return false;\n }\n });\n streamsDrawer.setAdapter(streamsDrawerAdapter);\n }\n /**\n * Initiates the streams Drawer if the streams in the drawer is 0.\n */\n public void checkAndSetupStreamsDrawer() {\n try {\n if (streamsDrawer.getAdapter().getCount() != 0) {\n return;\n }\n setupListViewAdapter();\n } catch (NullPointerException npe) {\n setupListViewAdapter();\n }\n }\n private void sendMessage() {\n if (isCurrentModeStream()) {\n if (TextUtils.isEmpty(streamActv.getText().toString())) {\n streamActv.setError(getString(R.string.stream_error));\n streamActv.requestFocus();\n return;\n } else {\n try {\n Cursor streamCursor = makeStreamCursor(streamActv.getText().toString());\n if (streamCursor.getCount() == 0) {\n streamActv.setError(getString(R.string.stream_not_exists));\n streamActv.requestFocus();\n return;\n }\n } catch (SQLException e) {\n Log.e(\"SQLException\", \"SQL not correct\", e);\n }\n }\n if (TextUtils.isEmpty(topicActv.getText().toString())) {\n topicActv.setError(getString(R.string.subject_error));\n topicActv.requestFocus();\n return;\n }\n } else {\n if (TextUtils.isEmpty(topicActv.getText().toString())) {\n topicActv.setError(getString(R.string.person_error));\n topicActv.requestFocus();\n return;\n }\n }\n if (TextUtils.isEmpty(messageEt.getText().toString())) {\n messageEt.setError(getString(R.string.no_message_error));\n messageEt.requestFocus();\n return;\n }\n sendingMessage(true);\n MessageType messageType = isCurrentModeStream() ? MessageType.STREAM_MESSAGE : MessageType.PRIVATE_MESSAGE;\n Message msg = new Message(app);\n msg.setSender(app.getYou());\n if (messageType == MessageType.STREAM_MESSAGE) {\n msg.setType(messageType);\n msg.setStream(new Stream(streamActv.getText().toString()));\n msg.setSubject(topicActv.getText().toString());\n } else if (messageType == MessageType.PRIVATE_MESSAGE) {\n msg.setType(messageType);\n msg.setRecipient(topicActv.getText().toString().split(\",\"));\n }\n msg.setContent(messageEt.getText().toString());\n AsyncSend sender = new AsyncSend(that, msg);\n sender.setCallback(new ZulipAsyncPushTask.AsyncTaskCompleteListener() {\n public void onTaskComplete(String result, JSONObject jsonObject) {\n Toast.makeText(ZulipActivity.this, R.string.message_sent, Toast.LENGTH_SHORT).show();\n messageEt.setText(\"\");\n sendingMessage(false);\n }\n public void onTaskFailure(String result) {\n Log.d(\"onTaskFailure\", \"Result: \" + result);\n Toast.makeText(ZulipActivity.this, R.string.message_error, Toast.LENGTH_SHORT).show();\n sendingMessage(false);\n }\n });\n sender.execute();\n }\n /**\n * Disable chatBox and show a loading footer while sending the message.\n */\n private void sendingMessage(boolean isSending) {\n streamActv.setEnabled(!isSending);\n textView.setEnabled(!isSending);\n messageEt.setEnabled(!isSending);\n topicActv.setEnabled(!isSending);\n sendBtn.setEnabled(!isSending);\n togglePrivateStreamBtn.setEnabled(!isSending);\n if (isSending)\n composeStatus.setVisibility(View.VISIBLE);\n else\n composeStatus.setVisibility(View.GONE);\n }\n private LinearLayout composeStatus;\n /**\n * Setup adapter's for the {@link AutoCompleteTextView}\n *\n * These adapters are being intialized -\n *\n * {@link #streamActvAdapter} Adapter for suggesting all the stream names in this AutoCompleteTextView\n * {@link #emailActvAdapter} Adapter for suggesting all the person email's in this AutoCompleteTextView\n * {@link #subjectActvAdapter} Adapter for suggesting all the topic for the stream specified in the {@link #streamActv} in this AutoCompleteTextView\n */\n private void setUpAdapter() {\n streamActvAdapter = new SimpleCursorAdapter(\n that, R.layout.stream_tile, null,\n new String[]{Stream.NAME_FIELD},\n new int[]{R.id.name}, 0);\n streamActvAdapter.setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() {\n @Override\n public CharSequence convertToString(Cursor cursor) {\n int index = cursor.getColumnIndex(Stream.NAME_FIELD);\n return cursor.getString(index);\n }\n });\n streamActvAdapter.setFilterQueryProvider(new FilterQueryProvider() {\n @Override\n public Cursor runQuery(CharSequence charSequence) {\n try {\n return makeStreamCursor(charSequence);\n } catch (SQLException e) {\n Log.e(\"SQLException\", \"SQL not correct\", e);\n return null;\n }\n }\n });\n subjectActvAdapter = new SimpleCursorAdapter(\n that, R.layout.stream_tile, null,\n new String[]{Message.SUBJECT_FIELD},\n new int[]{R.id.name}, 0);\n subjectActvAdapter.setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() {\n @Override\n public CharSequence convertToString(Cursor cursor) {\n int index = cursor.getColumnIndex(Message.SUBJECT_FIELD);\n return cursor.getString(index);\n }\n });\n subjectActvAdapter.setFilterQueryProvider(new FilterQueryProvider() {\n @Override\n public Cursor runQuery(CharSequence charSequence) {\n try {\n return makeSubjectCursor(streamActv.getText().toString(), charSequence);\n } catch (SQLException e) {\n Log.e(\"SQLException\", \"SQL not correct\", e);\n return null;\n }\n }\n });\n emailActvAdapter = new SimpleCursorAdapter(\n that, R.layout.stream_tile, null,\n new String[]{Person.EMAIL_FIELD},\n new int[]{R.id.name}, 0);\n emailActvAdapter\n .setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() {\n @Override\n public CharSequence convertToString(Cursor cursor) {\n String text = topicActv.getText().toString();\n String prefix;\n int lastIndex = text.lastIndexOf(',');\n if (lastIndex != -1) {\n prefix = text.substring(0, lastIndex + 1);\n } else {\n prefix = \"\";\n }\n int index = cursor.getColumnIndex(Person.EMAIL_FIELD);\n return prefix + cursor.getString(index);\n }\n });\n emailActvAdapter.setFilterQueryProvider(new FilterQueryProvider() {\n @Override\n public Cursor runQuery(CharSequence charSequence) {\n try {\n return makePeopleCursor(charSequence);\n } catch (SQLException e) {\n Log.e(\"SQLException\", \"SQL not correct\", e);\n return null;\n }\n }\n });\n sendingMessage(false);\n }\n /**\n * Creates a cursor to get the streams saved in the database\n * @param streamName Filter out streams name containing this string\n */\n private Cursor makeStreamCursor(CharSequence streamName)\n throws SQLException {\n if (streamName == null) {\n streamName = \"\";\n }\n return ((AndroidDatabaseResults) app\n .getDao(Stream.class)\n .queryRaw(\n \"SELECT rowid _id, * FROM streams WHERE \"\n + Stream.SUBSCRIBED_FIELD + \" = 1 AND \"\n + Stream.NAME_FIELD\n + \" LIKE ? ESCAPE '\\\\' ORDER BY \"\n + Stream.NAME_FIELD + \" COLLATE NOCASE\",\n DatabaseHelper.likeEscape(streamName.toString()) + \"%\")\n .closeableIterator().getRawResults()).getRawCursor();\n }\n /**\n * Creates a cursor to get the topics in the stream in\n * @param stream\n * @param subject Filter out subject containing this string\n */\n private Cursor makeSubjectCursor(CharSequence stream, CharSequence subject)\n throws SQLException {\n if (subject == null) {\n subject = \"\";\n }\n if (stream == null) {\n stream = \"\";\n }\n AndroidDatabaseResults results = (AndroidDatabaseResults) app\n .getDao(Message.class)\n .queryRaw(\n \"SELECT DISTINCT \"\n + Message.SUBJECT_FIELD\n + \", 1 AS _id FROM messages JOIN streams ON streams.\"\n + Stream.ID_FIELD + \" = messages.\"\n + Message.STREAM_FIELD + \" WHERE \"\n + Message.SUBJECT_FIELD\n + \" LIKE ? ESCAPE '\\\\' AND \"\n + Stream.NAME_FIELD + \" = ? ORDER BY \"\n + Message.SUBJECT_FIELD + \" COLLATE NOCASE\",\n DatabaseHelper.likeEscape(subject.toString()) + \"%\",\n stream.toString()).closeableIterator().getRawResults();\n return results.getRawCursor();\n }\n /**\n * Creates a cursor to get the E-Mails stored in the database\n * @param email Filter out emails containing this string\n */\n private Cursor makePeopleCursor(CharSequence email) throws SQLException {\n if (email == null) {\n email = \"\";\n }\n String[] pieces = TextUtils.split(email.toString(), \",\");\n String piece;\n if (pieces.length == 0) {\n piece = \"\";\n } else {\n piece = pieces[pieces.length - 1].trim();\n }\n return ((AndroidDatabaseResults) app\n .getDao(Person.class)\n .queryRaw(\n \"SELECT rowid _id, * FROM people WHERE \"\n + Person.ISBOT_FIELD + \" = 0 AND \"\n + Person.ISACTIVE_FIELD + \" = 1 AND \"\n + Person.EMAIL_FIELD\n + \" LIKE ? ESCAPE '\\\\' ORDER BY \"\n + Person.NAME_FIELD + \" COLLATE NOCASE\",\n DatabaseHelper.likeEscape(piece) + \"%\")\n .closeableIterator().getRawResults()).getRawCursor();\n }\n private void switchToStream() {\n removeEditTextErrors();\n if (!isCurrentModeStream()) {\n switchView();\n }\n }\n private void switchToPrivate() {\n removeEditTextErrors();\n if (isCurrentModeStream()) {\n switchView();\n }\n }\n private boolean isCurrentModeStream() {\n //The TextView is VISIBLE which means currently send to stream is on.\n return textView.getVisibility() == View.VISIBLE;\n }\n private void removeEditTextErrors() {\n streamActv.setError(null);\n topicActv.setError(null);\n messageEt.setError(null);\n }\n /**\n * Switch from Private to Stream or vice versa in chatBox\n */\n private void switchView() {\n if (isCurrentModeStream()) { //Person\n togglePrivateStreamBtn.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_action_bullhorn));\n tempStreamSave = topicActv.getText().toString();\n topicActv.setText(null);\n topicActv.setHint(R.string.hint_person);\n topicActv.setAdapter(emailActvAdapter);\n streamActv.setVisibility(View.GONE);\n textView.setVisibility(View.GONE);\n } else { //Stream\n topicActv.setText(tempStreamSave);\n togglePrivateStreamBtn.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_action_person));\n streamActv.setEnabled(true);\n topicActv.setHint(R.string.hint_subject);\n streamActv.setHint(R.string.hint_stream);\n streamActv.setVisibility(View.VISIBLE);\n textView.setVisibility(View.VISIBLE);\n topicActv.setVisibility(View.VISIBLE);\n streamActv.setAdapter(streamActvAdapter);\n topicActv.setAdapter(subjectActvAdapter);\n }\n }\n private String tempStreamSave = null;\n @Override\n public void clearChatBox() {\n if (messageEt != null) {\n if (TextUtils.isEmpty(messageEt.getText())) {\n topicActv.setText(\"\");\n streamActv.setText(\"\");\n }\n }\n }\n public void onBackPressed() {\n if (narrowedList != null) {\n narrowedList = null;\n getSupportFragmentManager().popBackStack(NARROW,\n FragmentManager.POP_BACK_STACK_INCLUSIVE);\n } else {\n super.onBackPressed();\n }\n }\n private void pushListFragment(MessageListFragment list, String back) {\n currentList = list;\n FragmentTransaction transaction = getSupportFragmentManager()\n .beginTransaction();\n transaction.replace(R.id.list_fragment_container, list);\n if (back != null) {\n transaction.addToBackStack(back);\n }\n transaction.commit();\n getSupportFragmentManager().executePendingTransactions();\n }\n private void processParams() {\n Bundle params = getIntent().getExtras();\n if (params == null)\n return;\n for (String unprocessedParam : params.keySet()) {\n Flag param;\n if (unprocessedParam.contains(getBaseContext().getPackageName())) {\n try {\n param = Flag.valueOf(unprocessedParam\n .substring(getBaseContext().getPackageName()\n .length() + 1));\n } catch (IllegalArgumentException e) {\n Log.e(PARAMS, \"Invalid app-specific intent specified.\", e);\n continue;\n }\n } else {\n continue;\n }\n switch (param) {\n case RESET_DATABASE:\n Log.i(PARAMS, \"Resetting the database...\");\n app.resetDatabase();\n Log.i(PARAMS, \"Database deleted successfully.\");\n this.finish();\n break;\n default:\n break;\n }\n }\n }\n protected void narrow(final Stream stream) {\n doNarrow(new NarrowFilterStream(stream, null));\n }\n private void narrow_pm_with(final Person person) {\n doNarrow(new NarrowFilterPM(Arrays.asList(app.getYou(), person)));\n }\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n public void onListResume(MessageListFragment list) {\n currentList = list;\n NarrowFilter filter = list.filter;\n if (filter == null) {\n setupTitleBar(getString(R.string.app_name), null);\n this.drawerToggle.setDrawerIndicatorEnabled(true);\n } else {\n setupTitleBar(filter.getTitle(), filter.getSubtitle());\n this.drawerToggle.setDrawerIndicatorEnabled(false);\n }\n this.drawerLayout.closeDrawers();\n }\n private void setupTitleBar(String title, String subtitle) {\n if (android.os.Build.VERSION.SDK_INT >= 11 && getSupportActionBar() != null) {\n if (title != null) getSupportActionBar().setTitle(title);\n getSupportActionBar().setSubtitle(subtitle);\n }\n }\n /**\n * This method creates a new Instance of the MessageListFragment and displays it with the filter.\n */\n public void doNarrow(NarrowFilter filter) {\n narrowedList = MessageListFragment.newInstance(filter);\n // Push to the back stack if we are not already narrowed\n pushListFragment(narrowedList, NARROW);\n narrowedList.onReadyToDisplay(true);\n }\n @Override\n public void onNarrowFillSendBoxPrivate(Person peopleList[], boolean openSoftKeyboard) {\n displayChatBox(true);\n displayFAB(false);\n switchToPrivate();\n ArrayList names = new ArrayList();\n for (Person person : peopleList) {\n if (person.getId() != app.getYou().getId()) {\n names.add(person.getEmail());\n }\n }\n topicActv.setText(TextUtils.join(\", \", names));\n messageEt.requestFocus();\n if (openSoftKeyboard) {\n ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);\n }\n }\n /**\n * Fills the chatBox according to the {@link MessageType}\n * @param openSoftKeyboard If true open's up the SoftKeyboard else not.\n */\n @Override\n public void onNarrowFillSendBox(Message message, boolean openSoftKeyboard) {\n displayChatBox(true);\n displayFAB(false);\n if (message.getType() == MessageType.PRIVATE_MESSAGE) {\n switchToPrivate();\n topicActv.setText(message.getReplyTo(app));\n messageEt.requestFocus();\n } else {\n switchToStream();\n streamActv.setText(message.getStream().getName());\n topicActv.setText(message.getSubject());\n if (\"\".equals(message.getSubject())) {\n topicActv.requestFocus();\n } else messageEt.requestFocus();\n }\n if (openSoftKeyboard) {\n ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);\n }\n }\n /**\n * Fills the chatBox with the stream name and the topic\n * @param stream Stream name to be filled\n * @param subject Subject to be filled\n * @param openSoftKeyboard If true open's the softKeyboard else not\n */\n public void onNarrowFillSendBoxStream(String stream, String subject, boolean openSoftKeyboard) {\n displayChatBox(true);\n displayFAB(false);\n switchToStream();\n streamActv.setText(stream);\n topicActv.setText(subject);\n if (\"\".equals(subject)) {\n topicActv.requestFocus();\n } else messageEt.requestFocus();\n if (openSoftKeyboard) {\n ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);\n }\n }\n public void onNarrow(NarrowFilter narrowFilter) {\n // TODO: check if already narrowed to this particular stream/subject\n doNarrow(narrowFilter);\n }\n @Override\n protected void onPostCreate(Bundle savedInstanceState) {\n super.onPostCreate(savedInstanceState);\n // Sync the toggle state after onRestoreInstanceState has occurred.\n drawerToggle.syncState();\n }\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n // Inflate the menu; this adds items to the action bar if it is present.\n Log.d(\"ASD\", \"onCreateOptionsMenu: \");\n if (this.logged_in) {\n getMenuInflater().inflate(R.menu.options, menu);\n prepareSearchView(menu);\n return true;\n }\n return false;\n }\n private boolean prepareSearchView(Menu menu) {\n if (this.logged_in && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {\n // Get the SearchView and set the searchable configuration\n final SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);\n // Assumes current activity is the searchable activity\n final MenuItem mSearchMenuItem = menu.findItem(R.id.search);\n final android.support.v7.widget.SearchView searchView = (android.support.v7.widget.SearchView) MenuItemCompat.getActionView(mSearchMenuItem);\n searchView.setSearchableInfo(searchManager.getSearchableInfo(new ComponentName(getApplicationContext(), ZulipActivity.class)));\n searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));\n ((EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text)).setHintTextColor(ContextCompat.getColor(this, R.color.colorTextPrimary));\n searchView.setOnQueryTextListener(new android.support.v7.widget.SearchView.OnQueryTextListener() {\n @Override\n public boolean onQueryTextSubmit(String s) {\n doNarrow(new NarrowFilterSearch(s));\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {\n mSearchMenuItem.collapseActionView();\n }\n return true;\n }\n @Override\n public boolean onQueryTextChange(String s) {\n return false;\n }\n });\n }\n return true;\n }\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n // Pass the event to ActionBarDrawerToggle, if it returns\n // true, then it has handled the app icon touch event\n if (drawerToggle.onOptionsItemSelected(item)) {\n // Close the right drawer if we opened the left one\n drawerLayout.closeDrawer(GravityCompat.END);\n return true;\n }\n // Handle item selection\n switch (item.getItemId()) {\n case android.R.id.home:\n getSupportFragmentManager().popBackStack(NARROW,\n FragmentManager.POP_BACK_STACK_INCLUSIVE);\n break;\n case R.id.search:\n // show a pop up dialog only if gingerbread or under\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {\n AlertDialog.Builder builder = new AlertDialog.Builder(this);\n builder.setTitle(\"Search Zulip\");\n final EditText editText = new EditText(this);\n builder.setView(editText);\n builder.setPositiveButton(\"Ok\",\n new DialogInterface.OnClickListener() {\n @Override\n public void onClick(\n DialogInterface dialogInterface, int i) {\n String query = editText.getText().toString();\n doNarrow(new NarrowFilterSearch(query));\n }\n });\n builder.show();\n }\n break;\n case R.id.daynight:\n switch (AppCompatDelegate.getDefaultNightMode()) {\n case -1:\n case AppCompatDelegate.MODE_NIGHT_NO:\n setNightMode(AppCompatDelegate.MODE_NIGHT_YES);\n break;\n case AppCompatDelegate.MODE_NIGHT_YES:\n setNightMode(AppCompatDelegate.MODE_NIGHT_NO);\n break;\n default:\n setNightMode(AppCompatDelegate.MODE_NIGHT_NO);\n break;\n }\n break;\n case R.id.refresh:\n Log.w(\"menu\", \"Refreshed manually by user. We shouldn't need this.\");\n onRefresh();\n break;\n case R.id.today:\n doNarrow(new NarrowFilterToday());\n break;\n case R.id.logout:\n logout();\n break;\n case R.id.legal:\n openLegal();\n break;\n default:\n return super.onOptionsItemSelected(item);\n }\n return true;\n }\n /**\n * Switches the current Day/Night mode to Night/Day mode\n * @param nightMode which Mode {@link android.support.v7.app.AppCompatDelegate.NightMode}\n */\n private void setNightMode(@AppCompatDelegate.NightMode int nightMode) {\n AppCompatDelegate.setDefaultNightMode(nightMode);\n if (Build.VERSION.SDK_INT >= 11) {\n recreate();\n }\n }\n /**\n * Log the user out of the app, clearing our cache of their credentials.\n */\n private void logout() {\n this.logged_in = false;\n notifications.logOut(new Runnable() {\n public void run() {\n app.logOut();\n openLogin();\n }\n });\n }\n /**\n * Switch to the login view.\n */\n private void openLogin() {\n Intent i = new Intent(this, LoginActivity.class);\n startActivity(i);\n finish();\n }\n private void openLegal() {\n Intent i = new Intent(this, LegalActivity.class);\n startActivityForResult(i, 0);\n }\n public void onConfigurationChanged(Configuration newConfig) {\n super.onConfigurationChanged(newConfig);\n // our display has changed, lets recalculate the spacer\n // this.size_bottom_spacer();\n drawerToggle.onConfigurationChanged(newConfig);\n }\n protected void onPause() {\n super.onPause();\n Log.i(\"status\", \"suspend\");\n this.suspended = true;\n unregisterReceiver(onGcmMessage);\n if (event_poll != null) {\n event_poll.abort();\n event_poll = null;\n }\n if (statusUpdateHandler != null) {\n statusUpdateHandler.removeMessages(0);\n }\n }\n protected void onResume() {\n super.onResume();\n Log.i(\"status\", \"resume\");\n this.suspended = false;\n // Set up the BroadcastReceiver to trap GCM messages so notifications\n // don't show while in the app\n IntentFilter filter = new IntentFilter(GcmBroadcastReceiver.getGCMReceiverAction(getApplicationContext()));\n filter.setPriority(2);\n registerReceiver(onGcmMessage, filter);\n homeList.onActivityResume();\n if (narrowedList != null) {\n narrowedList.onActivityResume();\n }\n startRequests();\n }\n @Override\n protected void onDestroy() {\n super.onDestroy();\n if (statusUpdateHandler != null) {\n statusUpdateHandler.removeMessages(0);\n }\n }\n /**\n * Refresh the current user profile, removes all the tables from the database and reloads them from the server, reset the queue.\n */\n private void onRefresh() {\n super.onResume();\n if (event_poll != null) {\n event_poll.abort();\n event_poll = null;\n }\n app.clearConnectionState();\n app.resetDatabase();\n app.setEmail(app.getYou().getEmail());\n startRequests();\n }\n private void startRequests() {\n Log.i(\"zulip\", \"Starting requests\");\n if (event_poll != null) {\n event_poll.abort();\n event_poll = null;\n }\n event_poll = new AsyncGetEvents(this);\n event_poll.start();\n }\n public void onReadyToDisplay(boolean registered) {\n homeList.onReadyToDisplay(registered);\n if (narrowedList != null) {\n narrowedList.onReadyToDisplay(registered);\n }\n }\n public void onNewMessages(Message[] messages) {\n homeList.onNewMessages(messages);\n if (narrowedList != null) {\n narrowedList.onNewMessages(messages);\n }\n }\n}"}}},{"rowIdx":346247,"cells":{"answer":{"kind":"string","value":"package com.xlythe.textmanager.text;\nimport android.annotation.SuppressLint;\nimport android.content.ContentResolver;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.net.Uri;\nimport android.provider.BaseColumns;\nimport android.provider.Telephony;\nimport android.text.TextUtils;\nimport android.util.Log;\nimport com.xlythe.textmanager.Message;\nimport com.xlythe.textmanager.MessageCallback;\nimport com.xlythe.textmanager.MessageThread;\nimport java.io.Serializable;\nimport java.text.SimpleDateFormat;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\n/**\n * An SMS conversation\n */\npublic class Thread implements MessageThread, Serializable {\n long mThreadId;\n int mCount;\n int mUnreadCount;\n Text mText;\n protected Thread(Context context, Cursor cursor) {\n mThreadId = cursor.getLong(cursor.getColumnIndexOrThrow(Telephony.Sms.Conversations.THREAD_ID));\n mCount = 0;//cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Sms.Conversations.MESSAGE_COUNT));\n mUnreadCount = 0;\n buildLastMessage(context, mThreadId);\n }\n public void buildLastMessage(Context context, long threadId) {\n ContentResolver contentResolver = context.getContentResolver();\n final String[] projection = TextManager.PROJECTION;\n final Uri uri = Uri.parse(Mock.Telephony.MmsSms.CONTENT_CONVERSATIONS_URI +\"/\"+ threadId);\n final String order = \"normalized_date ASC\";\n Cursor c = contentResolver.query(uri, projection, null, null, order);\n if (c!=null && c.moveToFirst()) {\n mText = new Text(context, c);\n c.close();\n }\n }\n @Override\n public String getId(){\n return Long.toString(mThreadId);\n }\n @Override\n public int getCount() {\n return 0;\n }\n @Override\n public int getUnreadCount() {\n return 0;\n }\n @Override\n public Text getLatestMessage() {\n return mText;\n }\n}"}}},{"rowIdx":346248,"cells":{"answer":{"kind":"string","value":"package de.eightbitboy.hijacr.data.comic;\n//TODO use getters and stuff\n/**\n * Contains data for a comic whose page URLs can be counted easily.\n */\npublic class ComicData {\n /**\n * The comic's title.\n */\n private String title;\n /**\n * The comic's website URL.\n */\n private String url;\n /**\n * The URL to the first page of the comic.\n */\n private String firstUrl;\n private String baseUrl;\n /**\n * The number of the first comic. It is only used when baseUrl is given.\n */\n private int firstNumber;\n /**\n * The jsoup query for getting the comic img element.\n */\n private String imageQuery;\n /**\n * The jsoup query for getting the anchor with the href to the previous page.\n */\n private String previousQuery;\n /**\n * The jsoup query for getting the anchor with the href to the next page.\n */\n private String nextQuery;\n private boolean simple = false;\n /**\n * Define \"simple\" a comic which uses an URL which ends with a\n * number that can be counted and incremented for accessing comic pages.\n *\n * @param title\n * @param url\n * @param baseUrl\n * @param firstNumber\n * @param imageQuery\n */\n public ComicData(String title, String url, String baseUrl, int firstNumber, String\n imageQuery) {\n this.title = title;\n this.url = url;\n this.baseUrl = baseUrl;\n this.firstNumber = firstNumber;\n this.imageQuery = imageQuery;\n this.simple = true;\n }\n /**\n * Define a comic. The URLs for accessing comic pages must be parsed from a page.\n *\n * @param title\n * @param url\n * @param firstUrl\n * @param imageQuery\n * @param previousQuery\n * @param nextQuery\n */\n public ComicData(String title, String url, String firstUrl, String imageQuery, String\n previousQuery, String nextQuery) {\n this.title = title;\n this.url = url;\n this.firstUrl = firstUrl;\n this.imageQuery = imageQuery;\n this.previousQuery = previousQuery;\n this.nextQuery = nextQuery;\n this.simple = false;\n }\n public String getTitle() {\n return title;\n }\n public String getUrl() {\n return url;\n }\n public String getFirstUrl() {\n return firstUrl;\n }\n public String getBaseUrl() {\n return baseUrl;\n }\n public int getFirstNumber() {\n return firstNumber;\n }\n public String getImageQuery() {\n return imageQuery;\n }\n public String getPreviousQuery() {\n return previousQuery;\n }\n public String getNextQuery() {\n return nextQuery;\n }\n public boolean isSimple() {\n return simple;\n }\n //TODO improve cleanup\n public String getCleanUrl() {\n String cleanUrl;\n cleanUrl = url.replaceAll(\"/\", \"\");\n cleanUrl = cleanUrl.replaceAll(\"http\", \"\");\n cleanUrl = cleanUrl.replaceAll(\":\", \"\");\n cleanUrl = cleanUrl.replaceAll(\"www.\", \"\");\n return cleanUrl;\n }\n @Override\n public boolean equals(Object o) {\n return o instanceof ComicData && title.equals(((ComicData) o).getTitle());\n }\n}"}}},{"rowIdx":346249,"cells":{"answer":{"kind":"string","value":"package jp.gr.java_conf.nippy.kikisen;\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport android.content.pm.ActivityInfo;\nimport android.os.Bundle;\nimport android.os.CountDownTimer;\nimport android.preference.PreferenceManager;\nimport android.util.Log;\nimport android.view.KeyEvent;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.view.WindowManager;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\nimport jp.gr.java_conf.nippy.kikisen.dialog.DirectionDialogFragment;\nimport jp.gr.java_conf.nippy.kikisen.dialog.DistanceDialogFragment;\nimport jp.gr.java_conf.nippy.kikisen.dialog.NumberDialogFragment;\nimport jp.gr.java_conf.nippy.kikisen.dialog.YesDialogFragment;\npublic class MainActivity extends Activity {\n private static final String TAG = MainActivity.class.getName();\n TextView tvIP;\n EditText etSendString;\n Button btSend;\n Button btNo;\n Button btYes;\n Button btEnemy;\n Button btDirection;\n Button btDistance;\n Button btNumber;\n Button btTimerStart;\n Button btTimerEnd;\n TextView tvTimer;\n BouyomiChan4J bouyomi;\n SharedPreferences pref;\n final long circle_update[] = {2 * 60, 12 * 60, 17 * 60 + 40, 21 * 60 + 40, 24 * 60 + 40, 27 * 60 + 20, 29 * 60 + 20, 31 * 60 + 20};\n final long circle_shrink_start[] = {0, 7 * 60, 15 * 60 + 20, 20 * 60 + 10, 23 * 60 + 40, 26 * 60 + 40, 28 * 60 + 50, 30 * 60 + 50};\n final long total_time = circle_update[circle_update.length - 1];\n final long err_time = 10;//(sec)\n /**\n * Called when the activity is first created.\n */\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);\n setContentView(R.layout.activity_main);\n // Keep screen on\n getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);\n tvIP = (TextView) findViewById(R.id.tvIP);\n etSendString = (EditText) findViewById(R.id.etSendString);\n btSend = (Button) findViewById(R.id.btSend);\n btNo = (Button) findViewById(R.id.btNo);\n btYes = (Button) findViewById(R.id.btYes);\n btEnemy = (Button) findViewById(R.id.btEnemy);\n btDirection = (Button) findViewById(R.id.btDirection);\n btDistance = (Button) findViewById(R.id.btDistance);\n btNumber = (Button) findViewById(R.id.btNumber);\n btTimerStart = (Button) findViewById(R.id.btTimerStart);\n btTimerEnd = (Button) findViewById(R.id.btTimerEnd);\n tvTimer = (TextView) findViewById(R.id.tvTimer);\n //preference\n pref = PreferenceManager.getDefaultSharedPreferences(this);\n tvTimer.setText(\"press start\");\n Log.v(TAG, \"total time \" + total_time);\n // CountDownTimer(long millisInFuture, long countDownInterval)\n // 3= 3x60x1000 = 180000 msec\n final CountDown countDown = new CountDown(total_time * 1000, 100);\n //SEND button\n btSend.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n talk(etSendString.getText().toString());\n etSendString.getEditableText().clear();\n }\n });\n //enter pressed\n etSendString.setOnKeyListener(new View.OnKeyListener() {\n @Override\n public boolean onKey(View v, int keyCode, KeyEvent event) {\n if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && !(etSendString.getText().toString().equals(\"\"))) {\n talk(etSendString.getText().toString());\n etSendString.getEditableText().clear();\n return true;\n }\n return false;\n }\n });\n //No button\n btNo.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n talk(\"\");\n }\n });\n //Yes button\n btYes.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n talk(\"\");\n }\n });\n //Yes button Long click\n btYes.setOnLongClickListener(new View.OnLongClickListener() {\n @Override\n public boolean onLongClick(View v) {\n YesDialogFragment yesDialogFragment = new YesDialogFragment();\n yesDialogFragment.show(getFragmentManager(), \"yes\");\n return true;\n }\n });\n //Enemy button\n btEnemy.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n talk(\"\");\n }\n });\n //Direction button\n btDirection.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n //talk(\"\");\n //TODO enter direction\n DirectionDialogFragment directionDialogFragment = new DirectionDialogFragment();\n directionDialogFragment.show(getFragmentManager(), \"yes\");\n }\n });\n //Distance button\n btDistance.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n //talk(\"\");\n //TODO enter distance\n DistanceDialogFragment distanceDialogFragment = new DistanceDialogFragment();\n distanceDialogFragment.show(getFragmentManager(), \"yes\");\n }\n });\n //Number button\n btNumber.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n //talk(\"\");\n //TODO enter number\n NumberDialogFragment numberDialogFragment = new NumberDialogFragment();\n numberDialogFragment.show(getFragmentManager(), \"yes\");\n }\n });\n // SKIP button\n Button btSkip = (Button) findViewById(R.id.btSkip);\n btSkip.setOnClickListener(new View.OnClickListener() {\n public void onClick(View v) {\n new Thread(new Runnable() {\n public void run() {\n bouyomi.clear();\n bouyomi.skip();\n }\n }).start();\n }\n });\n btTimerStart.setOnClickListener(new View.OnClickListener() {\n public void onClick(View v) {\n countDown.start();\n talk_auto(\"\");\n }\n });\n btTimerEnd.setOnClickListener(new View.OnClickListener() {\n public void onClick(View v) {\n countDown.cancel();\n tvTimer.setText(\"press start\");\n }\n });\n }\n //send string to bouyomi-chan\n private void talk(final String str) {\n if (!(str.equals(\"\"))) {\n new Thread(new Runnable() {\n public void run() {\n bouyomi.talk(Integer.parseInt(pref.getString(\"list_preference_volume\", \"50\")),\n Integer.parseInt(pref.getString(\"list_preference_speed\", \"100\")),\n Integer.parseInt(pref.getString(\"list_preference_interval\", \"100\")),\n Integer.parseInt(pref.getString(\"list_preference_type\", \"0\")),\n pref.getString(\"edit_text_preference_command\", \" \") + str);\n }\n }).start();\n }\n }\n //talk for timer\n private void talk_auto(final String str) {\n if (!(str.equals(\"\"))) {\n new Thread(new Runnable() {\n public void run() {\n bouyomi.talk(Integer.parseInt(pref.getString(\"list_preference_volume\", \"50\")),\n Integer.parseInt(pref.getString(\"list_preference_speed\", \"100\")),\n Integer.parseInt(pref.getString(\"list_preference_interval\", \"100\")),\n Integer.parseInt(pref.getString(\"list_preference_type_auto\", \"0\")),\n pref.getString(\"edit_text_preference_command_auto\", \"\") + str);\n }\n }).start();\n }\n }\n class CountDown extends CountDownTimer {\n public CountDown(long millisInFuture, long countDownInterval) {\n super(millisInFuture, countDownInterval);\n }\n @Override\n public void onFinish() {\n tvTimer.setText(\"0:00.000\");\n }\n long old_time = 0;\n @Override\n public void onTick(long millisUntilFinished) {\n final long time_now = total_time * 1000 - millisUntilFinished - err_time * 1000;\n if (pref.getBoolean(\"switch_preference_auto_start\", false)) {\n for (int i = 0; i < circle_shrink_start.length; i++) {\n if (old_time < circle_shrink_start[i] * 1000 && circle_shrink_start[i] * 1000 < time_now) {\n if (i != 0) talk_auto(\"\" + (i) + \" \");\n }\n }\n }\n if (pref.getBoolean(\"switch_preference_auto_5sec\", false)) {\n for (int i = 0; i < circle_shrink_start.length; i++) {\n if (old_time < (circle_shrink_start[i] - 5) * 1000 && (circle_shrink_start[i] - 5) * 1000 < time_now) {\n if (i != 0) talk_auto(\"5\");\n }\n }\n }\n if (pref.getBoolean(\"switch_preference_auto_30sec\", false)) {\n for (int i = 0; i < circle_shrink_start.length; i++) {\n if (old_time < (circle_shrink_start[i] - 30) * 1000 && (circle_shrink_start[i] - 30) * 1000 < time_now) {\n if (i != 0) talk_auto(\"30\");\n }\n }\n }\n if (pref.getBoolean(\"switch_preference_auto_60sec\", false)) {\n for (int i = 0; i < circle_shrink_start.length; i++) {\n if (old_time < (circle_shrink_start[i] - 60) * 1000 && (circle_shrink_start[i] - 60) * 1000 < time_now) {\n if (i != 0) talk_auto(\"\" + (i) + \" 1\");\n }\n }\n }\n if (pref.getBoolean(\"switch_preference_auto_120sec\", false)) {\n for (int i = 0; i < circle_shrink_start.length; i++) {\n if (old_time < (circle_shrink_start[i] - 120) * 1000 && (circle_shrink_start[i] - 120) * 1000 < time_now) {\n if (i != 0) talk_auto(\"\" + (i) + \" 2\");\n }\n }\n }\n if (pref.getBoolean(\"switch_preference_auto_circle_update\", false)) {\n for (int i = 0; i < circle_update.length; i++) {\n if (old_time < circle_update[i] * 1000 && circle_update[i] * 1000 < time_now) {\n if (i == 0) talk_auto(\"\");\n if (i != 0) talk_auto(\"\");\n }\n }\n }\n old_time = time_now;\n long mm = millisUntilFinished / 1000 / 60;\n long ss = millisUntilFinished / 1000 % 60;\n long ms = millisUntilFinished - ss * 1000 - mm * 1000 * 60;\n //tvTimer.setText(String.format(\"%1$02d:%2$02d.%3$03d\", mm, ss, ms));\n tvTimer.setText(String.format(\" \" + (int) (time_now / 1000) + \"sec\"));\n }\n }\n //menu\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case R.id.optionsMenu_01:\n Intent intent1 = new android.content.Intent(this, MainPreferenceActivity.class);\n startActivity(intent1);\n return true;\n case R.id.optionsMenu_02:\n Intent intent2 = new android.content.Intent(this, HowToUseActivity.class);\n startActivity(intent2);\n return true;\n case R.id.optionsMenu_03:\n Intent intent3 = new android.content.Intent(this, AboutThisAppActivity.class);\n startActivity(intent3);\n return true;\n default:\n return super.onOptionsItemSelected(item);\n }\n }\n @Override\n public void onStart() {\n Log.v(TAG, \"onStart\");\n super.onStart();\n }\n @Override\n public void onStop() {\n Log.v(TAG, \"onStop\");\n super.onStop();\n bouyomi = null;\n }\n @Override\n public void onResume() {\n Log.v(TAG, \"onResume\");\n super.onResume();\n new Thread(new Runnable() {\n public void run() {\n bouyomi = new BouyomiChan4J(pref.getString(\"edit_text_preference_ip\", \"127.0.0.1\"), Integer.parseInt(pref.getString(\"edit_text_preference_port\", \"50001\")));\n }\n }).start();\n /*tvIP.setText(\" \\nip:\" + pref.getString(\"edit_text_preference_ip\", \"127.0.0.1\") + \"\\nport:\" + pref.getString(\"edit_text_preference_port\", \"50001\")\n + \"\\nvolume:\" + pref.getString(\"list_preference_volume\", \"50\") + \"\\nspeed:\" + pref.getString(\"list_preference_speed\", \"100\")\n + \"\\ninterval:\" + pref.getString(\"list_preference_interval\", \"100\") + \"\\nvoice type:\" + pref.getString(\"list_preference_type:\", \"0\"));*/\n tvIP.setText(\"ip:\" + pref.getString(\"edit_text_preference_ip\", \"127.0.0.1\") + \" port:\" + pref.getString(\"edit_text_preference_port\", \"50001\"));\n }\n @Override\n public void onPause() {\n Log.v(TAG, \"onPause\");\n super.onPause();\n }\n}"}}},{"rowIdx":346250,"cells":{"answer":{"kind":"string","value":"package com.worizon.junit.jsonrequest;\nimport static org.junit.Assert.*;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.Map;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport com.google.gson.Gson;\nimport com.worizon.jsonrpc.IDGenerator;\nimport com.worizon.jsonrpc.JsonRpcRequest;\nimport com.worizon.jsonrpc.gson.NonExpose;\npublic class JsonRpcRequestTest {\n @Test\n public void testId(){\n IDGenerator.getInstance().reset();\n for( long i=1; i < 10000; i++){\n JsonRpcRequest req = new JsonRpcRequest(\"test\");\n assertTrue( req.getId().longValue() == i );\n }\n }\n @Test\n public void testConstructor1() {\n Map params = new LinkedHashMap();\n JsonRpcRequest request = new JsonRpcRequest(\"test\", params);\n assertNotNull( request.getId() );\n assertEquals( request.getVersion(), \"2.0\");\n assertEquals( request.getMethod(), \"test\");\n }\n @Test\n public void testConstructor2() {\n JsonRpcRequest request = new JsonRpcRequest(\"test\");\n assertNotNull( request.getId() );\n assertEquals( request.getVersion(), \"2.0\");\n assertEquals( request.getMethod(), \"test\");\n assertTrue(request.toString().startsWith(\"{\\\"method\\\":\\\"test\\\",\\\"jsonrpc\\\":\\\"2.0\\\",\"));\n }\n @Test\n public void testConstructor3() {\n JsonRpcRequest request1 = new JsonRpcRequest(\"test\");\n JsonRpcRequest request2 = new JsonRpcRequest( request1 );\n assertTrue( request1.equals(request2) );\n }\n @Test\n public void testEquals(){\n JsonRpcRequest req1 = new JsonRpcRequest(\"test\");\n JsonRpcRequest req2 = new JsonRpcRequest(\"test\");\n assertFalse( req1.equals(req2) );\n }\n @Test\n public void testParamsOrderToString(){\n Map params = new LinkedHashMap();\n params.put(\"y\", new int[]{3,4,5});\n params.put(\"x\", 1);\n params.put(\"z\", true);\n JsonRpcRequest request = new JsonRpcRequest(\"test\", params);\n request.setId(1000L);\n assertEquals(request.toString(), \"{\\\"method\\\":\\\"test\\\",\\\"params\\\":{\\\"y\\\":[3,4,5],\\\"x\\\":1,\\\"z\\\":true},\\\"jsonrpc\\\":\\\"2.0\\\",\\\"id\\\":1000}\");\n }\n class A{\n int x;\n String y;\n public A( int x, String y){\n this.x = x;\n this.y = y;\n }\n }\n @Test\n public void testObjectToString(){\n Map params = new LinkedHashMap();\n params.put(\"a\", new A(5,\"test\"));\n JsonRpcRequest request = new JsonRpcRequest(\"test\",params);\n request.setId(1000L);\n assertEquals(\"{\\\"method\\\":\\\"test\\\",\\\"params\\\":{\\\"a\\\":{\\\"x\\\":5,\\\"y\\\":\\\"test\\\"}},\\\"jsonrpc\\\":\\\"2.0\\\",\\\"id\\\":1000}\", request.toString());\n }\n class B{\n int x;\n @NonExpose String y;\n public B( int x, String y){\n this.x = x;\n this.y = y;\n }\n @Override\n public boolean equals( Object obj ){\n return ((B)obj).x == x && ((B)obj).y.equals(y);\n }\n }\n @Test\n public void testObjectNonExposeFieldToString(){\n Map params = new LinkedHashMap();\n params.put(\"b\", new B(5,\"test\"));\n JsonRpcRequest request = new JsonRpcRequest(\"test\", params);\n request.setId(1000L);\n assertEquals(\"{\\\"method\\\":\\\"test\\\",\\\"params\\\":{\\\"b\\\":{\\\"x\\\":5}},\\\"jsonrpc\\\":\\\"2.0\\\",\\\"id\\\":1000}\", request.toString());\n }\n @Test\n public void testParseNumbers(){\n JsonRpcRequest req = JsonRpcRequest.parse(\"{\\\"method\\\":\\\"test_numbers\\\",\\\"params\\\":{\\\"x\\\":5,\\\"y\\\":10.0},\\\"jsonrpc\\\":\\\"2.0\\\",\\\"id\\\":1000}\");\n Map params = new LinkedHashMap();\n params.put(\"x\", 5.0);\n params.put(\"y\", 10.0);\n JsonRpcRequest expected = new JsonRpcRequest(\"test_numbers\", params);\n expected.setId(1000L);\n assertEquals(expected, req);\n }\n @Test\n public void testParseStrings(){\n JsonRpcRequest req = JsonRpcRequest.parse(\"{\\\"method\\\":\\\"test_strings\\\",\\\"params\\\":{\\\"x\\\":\\\"foo\\\",\\\"y\\\":\\\"bar\\\"},\\\"jsonrpc\\\":\\\"2.0\\\",\\\"id\\\":1000}\");\n Map params = new LinkedHashMap();\n params.put(\"x\", \"foo\");\n params.put(\"y\", \"bar\");\n JsonRpcRequest expected = new JsonRpcRequest(\"test_strings\", params);\n expected.setId(1000L);\n assertEquals(expected, req);\n }\n @Test\n public void testParseArray(){\n JsonRpcRequest req = JsonRpcRequest.parse(\"{\\\"method\\\":\\\"test_array\\\",\\\"params\\\":{\\\"x\\\":[1,2,3]},\\\"jsonrpc\\\":\\\"2.0\\\",\\\"id\\\":1000}\");\n Map params = new LinkedHashMap();\n ArrayList values = new ArrayList();\n values.add(1.0d);\n values.add(2.0d);\n values.add(3.0d);\n params.put(\"x\", values);\n JsonRpcRequest expected = new JsonRpcRequest(\"test_array\", params);\n expected.setId(1000L);\n assertEquals(expected, req);\n }\n}"}}},{"rowIdx":346251,"cells":{"answer":{"kind":"string","value":"package mn.devfest.speakers;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.Nullable;\nimport android.support.v4.app.Fragment;\nimport android.transition.Transition;\nimport android.util.Log;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport com.google.firebase.database.DataSnapshot;\nimport com.google.firebase.database.DatabaseError;\nimport com.google.firebase.database.DatabaseReference;\nimport com.google.firebase.database.FirebaseDatabase;\nimport com.google.firebase.database.ValueEventListener;\nimport butterknife.Bind;\nimport butterknife.ButterKnife;\nimport mn.devfest.R;\nimport mn.devfest.api.model.Speaker;\nimport mn.devfest.view.SpeakerView;\nimport timber.log.Timber;\nimport static mn.devfest.sessions.SessionsFragment.DEVFEST_2017_KEY;\nimport static mn.devfest.sessions.SessionsFragment.SPEAKERS_CHILD_KEY;\n/**\n * Fragment that displays details for a particular session\n *\n * @author bherbst\n */\npublic class SpeakerDetailsFragment extends Fragment {\n private static final String ARG_SPEAKER_ID = \"speakerId\";\n @Bind(R.id.speaker)\n SpeakerView mSpeakerView;\n private Speaker mSpeaker;\n private DatabaseReference mFirebaseDatabaseReference;\n public static SpeakerDetailsFragment newInstance(String speakerId) {\n Bundle args = new Bundle();\n args.putString(ARG_SPEAKER_ID, speakerId);\n SpeakerDetailsFragment frag = new SpeakerDetailsFragment();\n frag.setArguments(args);\n return frag;\n }\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n return inflater.inflate(R.layout.fragment_speaker_details, container, false);\n }\n @Override\n public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n ButterKnife.bind(this, view);\n Bundle args = getArguments();\n if (args != null && args.containsKey(ARG_SPEAKER_ID)) {\n String speakerId = args.getString(ARG_SPEAKER_ID);\n mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();\n mFirebaseDatabaseReference.child(DEVFEST_2017_KEY).child(SPEAKERS_CHILD_KEY)\n .child(speakerId).addValueEventListener(new ValueEventListener() {\n @Override\n public void onDataChange(DataSnapshot dataSnapshot) {\n Timber.d(dataSnapshot.toString());\n mSpeaker = dataSnapshot.getValue(Speaker.class);\n transitionSpeaker();\n }\n @Override\n public void onCancelled(DatabaseError databaseError) {\n // Failed to read value\n Log.w(this.getClass().getSimpleName(), \"Failed to read speaker value.\", databaseError.toException());\n }\n });\n } else {\n throw new IllegalStateException(\"SpeakerDetailsFragment requires a speaker ID passed via newInstance()\");\n }\n }\n private void transitionSpeaker() {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && addTransitionListener()) {\n // If we are transitioning in, use the already loaded thumbnail\n mSpeakerView.setSpeaker(mSpeaker, true);\n } else {\n // Otherwise do the normal Picasso loading of the full size image\n mSpeakerView.setSpeaker(mSpeaker, false);\n }\n getActivity().setTitle(getResources().getString(R.string.speaker_title));\n // Now the content exists, so we can start the transition\n getActivity().supportStartPostponedEnterTransition();\n }\n private boolean addTransitionListener() {\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {\n // Can't transition below lollipop\n return false;\n }\n final Transition transition = getActivity().getWindow().getSharedElementEnterTransition();\n if (transition != null) {\n // There is an entering shared element transition so add a listener to it\n transition.addListener(new Transition.TransitionListener() {\n @Override\n public void onTransitionEnd(Transition transition) {\n // As the transition has ended, we can now load the full-size image\n mSpeakerView.loadFullSizeImage(false);\n // Make sure we remove ourselves as a listener\n transition.removeListener(this);\n }\n @Override\n public void onTransitionStart(Transition transition) {\n // No-op\n }\n @Override\n public void onTransitionCancel(Transition transition) {\n // Make sure we remove ourselves as a listener\n transition.removeListener(this);\n }\n @Override\n public void onTransitionPause(Transition transition) {\n // No-op\n }\n @Override\n public void onTransitionResume(Transition transition) {\n // No-op\n }\n });\n return true;\n }\n // If we reach here then we have not added a listener\n return false;\n }\n}"}}},{"rowIdx":346252,"cells":{"answer":{"kind":"string","value":"package com.lmy.lycommon.http;\nimport android.os.AsyncTask;\nimport android.support.annotation.NonNull;\nimport com.lmy.lycommon.utils.Log;\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.OutputStream;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\nimport java.util.Map;\nimport java.util.UUID;\npublic class HttpUtil implements IHttpUtil {\n public final static int EXECUTE_TYPE_GET = 0x00;\n public final static int EXECUTE_TYPE_POST = 0x01;\n public final static int TIME_OUT_DEFAULT = 10000;\n public final static String CHARSET_DEFAULT = \"utf-8\";\n public final static String BOUNDARY = UUID.randomUUID().toString();\n public final static String PREFIX = \"--\", LINE_END = \"\\r\\n\";\n public final static String CONTENT_TYPE = \"multipart/form-data\";\n private int timeOut;\n private String charset;\n public static HttpUtil create() {\n return new HttpUtil();\n }\n public static HttpUtil create(int timeOut, String charset) {\n return new HttpUtil(timeOut, charset);\n }\n private HttpUtil() {\n this(TIME_OUT_DEFAULT, CHARSET_DEFAULT);\n }\n private HttpUtil(int timeOut, String charset) {\n this.timeOut = timeOut;\n this.charset = charset;\n }\n @Override\n public void execute(@NonNull HttpTask task) {\n new AsyncHttpTask(task).execute();\n }\n private class AsyncHttpTask extends AsyncTask {\n private HttpTask task;\n public AsyncHttpTask(HttpTask task) {\n this.task = task;\n }\n public void progress(int progress) {\n publishProgress(progress);\n }\n @Override\n protected String[] doInBackground(HttpTask... params) {\n checkType(task.getType());\n try {\n switch (task.getType()) {\n case EXECUTE_TYPE_GET:\n return doGet(this, task);\n case EXECUTE_TYPE_POST:\n return doPost(this, task);\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n return null;\n }\n @Override\n protected void onPostExecute(String[] result) {\n if (result == null) task.getHttpExecuteLinstener().onError(-1, \"unknown error!\");\n else if (result.length >= 2)\n task.getHttpExecuteLinstener().onError(Integer.parseInt(result[0]), result[1]);\n else task.getHttpExecuteLinstener().onSuccess(result[0]);\n }\n @Override\n protected void onProgressUpdate(Integer... values) {\n task.getHttpExecuteLinstener().onProgress(values[0]);\n }\n }\n private void checkType(int type) {\n if (type > EXECUTE_TYPE_POST || type < EXECUTE_TYPE_GET)\n throw new RuntimeException(\"This type(\" + type + \") of request is not supported!\");\n }\n private String[] doGet(AsyncHttpTask asyncTask, HttpTask task) throws IOException {\n asyncTask.progress(0);\n HttpURLConnection connection = initConnection(task.getURL(), EXECUTE_TYPE_POST);\n setCookies(connection);\n /**\n * 200=\n */\n int code = connection.getResponseCode();\n String[] result = new String[]{\"\"};\n if (code == 200) {\n BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));\n String lines;\n while ((lines = reader.readLine()) != null) {\n result[0] += lines;\n }\n } else {\n result = new String[]{\"\", \"\"};\n result[0] = String.valueOf(code);\n result[1] = \"Error!\";\n }\n connection.disconnect();\n asyncTask.progress(100);\n return result;\n }\n private String[] doPost(AsyncHttpTask asyncTask, HttpTask task) throws IOException {\n asyncTask.progress(0);\n HttpURLConnection connection = initConnection(task.getURL(), EXECUTE_TYPE_POST);\n setCookies(connection);\n OutputStream os = connection.getOutputStream();\n StringBuffer sb = parseParams(task.getParams());\n byte[] paramsByteArray = sb.toString().getBytes();\n byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)\n .getBytes();\n os.write(paramsByteArray);\n os.write(end_data);\n os.write(LINE_END.getBytes());\n os.flush();\n os.close();\n /**\n * 200=\n */\n int code = connection.getResponseCode();\n String[] result = new String[]{\"\"};\n if (code == 200) {\n BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));\n String lines = \"\";\n while ((lines = reader.readLine()) != null) {\n result[0] += lines;\n }\n } else {\n result = new String[]{\"\", \"\"};\n result[0] = String.valueOf(code);\n result[1] = \"Error!\";\n }\n connection.disconnect();\n asyncTask.progress(100);\n return result;\n }\n private StringBuffer parseParams(Map map) {\n StringBuffer sb = new StringBuffer();\n for (Map.Entry entry : map.entrySet()) {\n sb.append(PREFIX);\n sb.append(BOUNDARY);\n sb.append(LINE_END);\n sb.append(\"Content-Disposition: form-data; name=\\\"\"\n + entry.getKey() + \"\\\"\" + LINE_END);\n sb.append(\"Content-Type: text/plain; charset=\" + charset + LINE_END);\n sb.append(\"Content-Transfer-Encoding: 8bit\" + LINE_END);\n sb.append(LINE_END);\n sb.append(entry.getValue());\n sb.append(LINE_END);\n }\n return sb;\n }\n private void setCookies(HttpURLConnection connection) {\n }\n @Override\n public void setTimeOut(int timeOut) {\n this.timeOut = timeOut;\n }\n @Override\n public int setTimeOut() {\n return timeOut;\n }\n @Override\n public void setCharset(String charset) {\n this.charset = charset;\n }\n @Override\n public String getCharset() {\n return charset;\n }\n private HttpURLConnection initConnection(String url, int type) throws IOException {\n URL u = new URL(url);\n HttpURLConnection conn = (HttpURLConnection) u.openConnection();\n conn.setReadTimeout(timeOut);\n conn.setConnectTimeout(timeOut);\n conn.setDoInput(true);\n conn.setDoOutput(true);\n conn.setUseCaches(false);\n if (type == EXECUTE_TYPE_GET)\n conn.setRequestMethod(\"GET\");\n else if (type == EXECUTE_TYPE_POST)\n conn.setRequestMethod(\"POST\");\n conn.setRequestProperty(\"Charset\", charset);\n conn.setRequestProperty(\"connection\", \"keep-alive\");\n conn.setRequestProperty(\"Content-Type\", CONTENT_TYPE + \";boundary=\" + BOUNDARY);\n return conn;\n }\n}"}}},{"rowIdx":346253,"cells":{"answer":{"kind":"string","value":"package org.openlmis.core.exceptions;\nimport com.crashlytics.android.Crashlytics;\npublic class LMISException extends Exception {\n public LMISException(String msg) {\n super(msg);\n }\n public LMISException(Exception e) {\n super(e);\n }\n public void reportToFabric() {\n //this will save exception messages locally\n //it only uploads to fabric server when network is available\n //so this actually behaves analogously with our sync logic\n Crashlytics.logException(this);\n }\n}"}}},{"rowIdx":346254,"cells":{"answer":{"kind":"string","value":"package com.malhartech.lib.math;\nimport com.malhartech.annotation.InputPortFieldAnnotation;\nimport com.malhartech.annotation.OutputPortFieldAnnotation;\nimport com.malhartech.api.BaseOperator;\nimport com.malhartech.api.Context.OperatorContext;\nimport com.malhartech.api.DefaultInputPort;\nimport com.malhartech.api.DefaultOutputPort;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport javax.script.*;\n/**\n *\n * @author David Yan \n */\npublic class Script extends BaseOperator\n{\n protected transient ScriptEngineManager sem = new ScriptEngineManager();\n protected transient ScriptEngine engine = sem.getEngineByName(\"JavaScript\");\n protected String script;\n protected boolean keepContext = true;\n protected boolean isPassThru = true;\n protected transient SimpleScriptContext scriptContext = new SimpleScriptContext();\n protected SimpleBindings scriptBindings = new SimpleBindings();\n protected ArrayList prerunScripts = new ArrayList();\n protected Object evalResult;\n @InputPortFieldAnnotation(name = \"inBindings\", optional = true)\n public final transient DefaultInputPort> inBindings = new DefaultInputPort>(this)\n {\n @Override\n public void process(Map tuple)\n {\n for (Map.Entry entry: tuple.entrySet()) {\n engine.put(entry.getKey(), entry.getValue());\n }\n Object res;\n try {\n evalResult = engine.eval(script, scriptContext);\n if (isPassThru) {\n result.emit(evalResult);\n }\n }\n catch (ScriptException ex) {\n Logger.getLogger(Script.class.getName()).log(Level.SEVERE, null, ex);\n }\n if (isPassThru) {\n outBindings.emit(new HashMap(engine.getBindings(ScriptContext.ENGINE_SCOPE)));\n }\n }\n };\n @OutputPortFieldAnnotation(name = \"outBindings\", optional = true)\n public final transient DefaultOutputPort> outBindings = new DefaultOutputPort>(this);\n @OutputPortFieldAnnotation(name = \"result\", optional = true)\n public final transient DefaultOutputPort result = new DefaultOutputPort(this);\n public void setEngineByName(String name)\n {\n engine = sem.getEngineByName(name);\n }\n public void setKeepContext(boolean keepContext)\n {\n this.keepContext = keepContext;\n }\n public void setScript(String script)\n {\n this.script = script;\n }\n public void addPrerunScript(String script) throws ScriptException\n {\n prerunScripts.add(script);\n }\n public void setPassThru(boolean isPassThru)\n {\n this.isPassThru = isPassThru;\n }\n @Override\n public void endWindow()\n {\n if (!isPassThru) {\n result.emit(evalResult);\n outBindings.emit(new HashMap(this.scriptContext.getBindings(ScriptContext.ENGINE_SCOPE)));\n }\n if (!keepContext) {\n this.scriptContext = new SimpleScriptContext();\n engine.setContext(this.scriptContext);\n }\n }\n @Override\n public void setup(OperatorContext context)\n {\n this.scriptContext.setBindings(scriptBindings, ScriptContext.ENGINE_SCOPE);\n engine.setContext(this.scriptContext);\n try {\n for (String s: prerunScripts) {\n engine.eval(s, this.scriptContext);\n }\n }\n catch (ScriptException ex) {\n Logger.getLogger(Script.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n public void put(String key, Object val)\n {\n scriptBindings.put(key, val);\n }\n}"}}},{"rowIdx":346255,"cells":{"answer":{"kind":"string","value":"package org.y20k.transistor.helpers;\nimport android.app.Activity;\nimport android.graphics.Bitmap;\nimport android.net.Uri;\nimport android.os.AsyncTask;\nimport android.os.Bundle;\nimport android.widget.Toast;\nimport org.y20k.transistor.MainActivity;\nimport org.y20k.transistor.R;\nimport org.y20k.transistor.core.Station;\nimport java.io.File;\nimport java.net.MalformedURLException;\nimport java.net.URL;\n/**\n * StationFetcher class\n */\npublic final class StationFetcher extends AsyncTask implements TransistorKeys {\n /* Define log tag */\n private static final String LOG_TAG = StationFetcher.class.getSimpleName();\n /* Main class variables */\n private final Activity mActivity;\n private final File mFolder;\n private final Uri mStationUri;\n private final String mStationName;\n private final String mStationUriScheme;\n private URL mStationURL;\n private final boolean mFolderExists;\n /* Constructor */\n public StationFetcher(Activity activity, File folder, Uri stationUri, String stationName) {\n mActivity = activity;\n mFolder = folder;\n mStationUri = stationUri;\n mStationName =stationName; // optional station name // todo set station name, if given in postexecute\n mFolderExists = mFolder.exists();\n mStationUriScheme = stationUri.getScheme();\n if (stationUri != null && mStationUriScheme != null && mStationUriScheme.startsWith(\"http\")) {\n Toast.makeText(mActivity, mActivity.getString(R.string.toastmessage_add_download_started), Toast.LENGTH_LONG).show();\n } else if (stationUri != null && mStationUriScheme != null && mStationUriScheme.startsWith(\"file\")) {\n Toast.makeText(mActivity, mActivity.getString(R.string.toastmessage_add_open_file_started), Toast.LENGTH_LONG).show();\n }\n }\n /* Background thread: download station */\n @Override\n public Bundle doInBackground(Void... params) {\n Bundle stationDownloadBundle = new Bundle();\n Station station = null;\n Bitmap stationImage = null;\n if (mFolderExists && mStationUriScheme != null && mStationUriScheme.startsWith(\"http\") && urlCleanup()) {\n // download new station,\n station = new Station(mFolder, mStationURL);\n // check if multiple streams\n if (station.getStationFetchResults().getInt(RESULT_FETCH_STATUS) == CONTAINS_ONE_STREAM) {\n // check if name parameter was given\n if (mStationName != null) {\n station.setStationName(mStationName);\n }\n // download new station image\n stationImage = station.fetchImageFile(mStationURL);\n // pack bundle\n stationDownloadBundle.putParcelable(KEY_DOWNLOAD_STATION, station);\n stationDownloadBundle.putParcelable(KEY_DOWNLOAD_STATION_IMAGE, stationImage);\n }\n return stationDownloadBundle;\n } else if (mFolderExists && mStationUriScheme != null && mStationUriScheme.startsWith(\"file\")) {\n // read file and return new station\n station = new Station(mFolder, mStationUri);\n // check if multiple streams\n if (station.getStationFetchResults().getInt(RESULT_FETCH_STATUS) == CONTAINS_ONE_STREAM) {\n // pack bundle\n stationDownloadBundle.putParcelable(KEY_DOWNLOAD_STATION, station);\n }\n return stationDownloadBundle;\n } else {\n return stationDownloadBundle;\n }\n }\n /* Main thread: set station and activate listener */\n @Override\n protected void onPostExecute(Bundle stationDownloadBundle) {\n // get station from download bundle\n Station station = null;\n if (stationDownloadBundle.containsKey(KEY_DOWNLOAD_STATION)) {\n station = stationDownloadBundle.getParcelable(KEY_DOWNLOAD_STATION);\n }\n // get fetch results from station\n Bundle fetchResults = null;\n if (station != null) {\n fetchResults = station.getStationFetchResults();\n }\n // CASE 1: station was successfully fetched\n if (station != null && fetchResults != null && fetchResults.getInt(RESULT_FETCH_STATUS) == CONTAINS_ONE_STREAM && mFolderExists) {\n // hand over result to MainActivity\n ((MainActivity)mActivity).handleStationAdd(stationDownloadBundle);\n LogHelper.v(LOG_TAG, \"Station was successfully fetched: \" + station.getStreamUri().toString());\n }\n // CASE 2: multiple streams found\n if (station != null && fetchResults != null && fetchResults.getInt(RESULT_FETCH_STATUS) == CONTAINS_MULTIPLE_STREAMS && mFolderExists) {\n // let user choose\n DialogAddChooseStream.show(mActivity, fetchResults.getStringArrayList(RESULT_LIST_OF_URIS), fetchResults.getStringArrayList(RESULT_LIST_OF_NAMES));\n }\n // CASE 3: an error occurred\n if (station == null || (fetchResults != null && fetchResults.getInt(RESULT_FETCH_STATUS) == CONTAINS_NO_STREAM) || !mFolderExists) {\n String errorTitle;\n String errorMessage;\n String errorDetails;\n if (mStationUriScheme != null && mStationUriScheme.startsWith(\"http\")) {\n // construct error message for \"http\"\n errorTitle = mActivity.getResources().getString(R.string.dialog_error_title_fetch_download);\n errorMessage = mActivity.getResources().getString(R.string.dialog_error_message_fetch_download);\n errorDetails = buildDownloadErrorDetails(fetchResults);\n } else if (mStationUriScheme != null && mStationUriScheme.startsWith(\"file\")) {\n // construct error message for \"file\"\n errorTitle = mActivity.getResources().getString(R.string.dialog_error_title_fetch_read);\n errorMessage = mActivity.getResources().getString(R.string.dialog_error_message_fetch_read);\n errorDetails = buildReadErrorDetails(fetchResults);\n } else if (!mFolderExists) {\n // construct error message for write error\n errorTitle = mActivity.getResources().getString(R.string.dialog_error_title_fetch_write);\n errorMessage = mActivity.getResources().getString(R.string.dialog_error_message_fetch_write);\n errorDetails = mActivity.getResources().getString(R.string.dialog_error_details_write);\n } else {\n // default values\n errorTitle = mActivity.getResources().getString(R.string.dialog_error_title_default);\n errorMessage = mActivity.getResources().getString(R.string.dialog_error_message_default);\n errorDetails = mActivity.getResources().getString(R.string.dialog_error_details_default);\n }\n // show error dialog\n DialogError.show(mActivity, errorTitle, errorMessage, errorDetails);\n }\n }\n /* checks and cleans url string and sets mStationURL */\n private boolean urlCleanup() {\n // remove whitespaces and create url\n try {\n mStationURL = new URL(mStationUri.toString().trim());\n return true;\n } catch (MalformedURLException e) {\n e.printStackTrace();\n return false;\n }\n }\n /* Builds more detailed download error string */\n private String buildDownloadErrorDetails(Bundle fetchResults) {\n String fileContent = fetchResults.getString(RESULT_FILE_CONTENT);\n String playListType;\n String streamType;\n if (fetchResults.containsKey(RESULT_PLAYLIST_TYPE) && fetchResults.getParcelable(RESULT_PLAYLIST_TYPE) != null) {\n playListType = fetchResults.getParcelable(RESULT_PLAYLIST_TYPE).toString();\n } else {\n playListType = \"unknown\";\n }\n if (fetchResults.containsKey(RESULT_STREAM_TYPE) && fetchResults.getParcelable(RESULT_STREAM_TYPE) != null) {\n streamType = fetchResults.getParcelable(RESULT_STREAM_TYPE).toString();\n } else {\n streamType = \"unknown\";\n }\n // construct details string\n StringBuilder sb = new StringBuilder(\"\");\n sb.append(mActivity.getResources().getString(R.string.dialog_error_message_fetch_general_external_storage));\n sb.append(\"\\n\");\n sb.append(mFolder);\n sb.append(\"\\n\\n\");\n if (mStationUri.getScheme().startsWith(\"file\")) {\n sb.append(mActivity.getResources().getString(R.string.dialog_error_message_fetch_read_file_location));\n } else {\n sb.append(mActivity.getResources().getString(R.string.dialog_error_message_fetch_download_station_url));\n }\n sb.append(\"\\n\");\n sb.append(mStationUri);\n if ((mStationUri.getLastPathSegment() != null && !mStationUri.getLastPathSegment().contains(\"m3u\")) ||\n (mStationUri.getLastPathSegment() != null && !mStationUri.getLastPathSegment().contains(\"pls\")) ) {\n sb.append(\"\\n\\n\");\n sb.append(mActivity.getResources().getString(R.string.dialog_error_message_fetch_general_hint_m3u));\n }\n if (playListType != null) {\n sb.append(\"\\n\\n\");\n sb.append(mActivity.getResources().getString(R.string.dialog_error_message_fetch_general_playlist_type));\n sb.append(\"\\n\");\n sb.append(playListType);\n }\n if (streamType != null) {\n sb.append(\"\\n\\n\");\n sb.append(mActivity.getResources().getString(R.string.dialog_error_message_fetch_general_stream_type));\n sb.append(\"\\n\");\n sb.append(streamType);\n }\n if (fileContent != null) {\n sb.append(\"\\n\\n\");\n sb.append(mActivity.getResources().getString(R.string.dialog_error_message_fetch_general_file_content));\n sb.append(\"\\n\");\n sb.append(fileContent);\n }\n return sb.toString();\n }\n /* Builds more detailed read error string */\n private String buildReadErrorDetails(Bundle fetchResults) {\n // construct details string\n StringBuilder sb = new StringBuilder(\"\");\n sb.append(mActivity.getResources().getString(R.string.dialog_error_message_fetch_general_external_storage));\n sb.append(\"\\n\");\n sb.append(mFolder);\n sb.append(\"\\n\\n\");\n sb.append(mActivity.getResources().getString(R.string.dialog_error_message_fetch_read));\n sb.append(\"\\n\");\n sb.append(mStationUri);\n if (!mStationUri.getLastPathSegment().contains(\"m3u\") || !mStationUri.getLastPathSegment().contains(\"pls\") ) {\n sb.append(\"\\n\\n\");\n sb.append(mActivity.getResources().getString(R.string.dialog_error_message_fetch_general_hint_m3u));\n }\n if (fetchResults != null && fetchResults.getBoolean(RESULT_FETCH_STATUS)) {\n String fileContent = fetchResults.getString(RESULT_FILE_CONTENT);\n if (fileContent != null) {\n sb.append(\"\\n\\n\");\n sb.append(mActivity.getResources().getString(R.string.dialog_error_message_fetch_general_file_content));\n sb.append(\"\\n\");\n sb.append(fileContent);\n } else {\n LogHelper.v(LOG_TAG, \"no content in local file\");\n }\n }\n return sb.toString();\n }\n}"}}},{"rowIdx":346256,"cells":{"answer":{"kind":"string","value":"package sg.rc4.collegelaundry;\nimport android.app.Activity;\nimport android.app.AlarmManager;\nimport android.app.NotificationManager;\nimport android.app.PendingIntent;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport android.support.v4.app.Fragment;\nimport android.os.Bundle;\nimport android.support.v4.app.NotificationCompat;\nimport android.support.v4.app.TaskStackBuilder;\nimport android.text.format.DateUtils;\nimport android.util.Log;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\nimport org.joda.time.DateTime;\nimport org.joda.time.Period;\nimport java.util.Timer;\nimport java.util.TimerTask;\nimport butterknife.Bind;\nimport butterknife.ButterKnife;\nimport butterknife.OnClick;\nimport sg.rc4.collegelaundry.utility.Vibrator;\n/**\n * A placeholder fragment containing a simple view.\n */\npublic class MainActivityFragment extends Fragment {\n private final int DEFAULT_NOTIFICATION_ID = 4021495;\n @Bind(R.id.timerDisplay)\n TextView timerDisplay;\n Timer displayUpdateTimer;\n DateTime dtLaundryDone;\n boolean hasDoneAlerted = false;\n SharedPreferences pref;\n private int timerSeconds = 2100;\n private int notificationId = DEFAULT_NOTIFICATION_ID;\n public MainActivityFragment() {\n }\n @Override\n public void setArguments(Bundle arguments){\n if (arguments != null) {\n if (arguments.containsKey(\"timer\")) {\n timerSeconds = arguments.getInt(\"timer\");\n }\n if (arguments.containsKey(\"notificationId\")) {\n notificationId = arguments.getInt(\"notificationId\");\n }\n }\n }\n public void alert(){\n Vibrator v = new Vibrator(getContext());\n v.vibrate(2000);\n NotificationCompat.Builder mBuilder =\n new NotificationCompat.Builder(getActivity())\n .setSmallIcon(R.drawable.ic_stat_college_laundry_notification_icon)\n .setContentTitle(\"Your laundry is done!\")\n .setContentText(\"College Laundry\");\n // Creates an explicit intent for an Activity in your app\n Intent resultIntent = new Intent(getActivity(), MainActivity.class);\n // The stack builder object will contain an artificial back stack for the\n // started Activity.\n // This ensures that navigating backward from the Activity leads out of\n // your application to the Home screen.\n TaskStackBuilder stackBuilder = TaskStackBuilder.create(getActivity());\n // Adds the back stack for the Intent (but not the Intent itself)\n stackBuilder.addParentStack(MainActivity.class);\n // Adds the Intent that starts the Activity to the top of the stack\n stackBuilder.addNextIntent(resultIntent);\n PendingIntent resultPendingIntent =\n stackBuilder.getPendingIntent(\n 0,\n PendingIntent.FLAG_UPDATE_CURRENT\n );\n mBuilder.setContentIntent(resultPendingIntent);\n NotificationManager mNotificationManager =\n (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);\n// mId allows you to update the notification later on.\n mNotificationManager.notify(notificationId, mBuilder.build());\n }\n protected Context getContext() {\n return getActivity().getApplicationContext();\n }\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n View view = inflater.inflate(R.layout.fragment_main, container, false);\n ButterKnife.bind(this, view);\n return view;\n }\n @Override\n public void onResume() {\n Log.i(\"DEBUG\", \"MainActivityFragment::onResume\");\n super.onResume();\n pref = getActivity().getSharedPreferences(getString(R.string.app_name), 0);\n String laundryDoneString = pref.getString(getString(R.string.dtLaundryDoneKey) + notificationId, null);\n Log.i(\"DEBUG\", \"MainActivityFragment::onResume - \" + laundryDoneString + \" NOTIF: \" + notificationId);\n if (laundryDoneString != null) {\n dtLaundryDone = new DateTime(laundryDoneString);\n pref.edit().remove(getString(R.string.dtLaundryDoneKey) + notificationId).commit();\n }\n }\n @Override\n public void onPause() {\n super.onPause();\n Log.i(\"DEBUG\", \"MainActivityFragment::onPause\" + \" NOTIF: \" + notificationId);\n SharedPreferences.Editor editor = pref.edit();\n if (dtLaundryDone != null) {\n editor.putString(getString(R.string.dtLaundryDoneKey) + notificationId, dtLaundryDone.toString());\n }\n editor.apply();\n }\n public void onStart() {\n super.onStart();\n displayUpdateTimer = new Timer();\n displayUpdateTimer.schedule(new TimerTask() {\n @Override\n public void run() {\n Activity activity = getActivity();\n if (activity == null) {\n return;\n }\n activity.runOnUiThread(new Runnable() {\n @Override\n public void run() {\n if (dtLaundryDone == null) {\n timerDisplay.setText(R.string.timerDisplay);\n } else {\n Period diff = new Period(new DateTime(), dtLaundryDone);\n int totalSeconds = diff.toStandardSeconds().getSeconds();\n if (totalSeconds < 0) {\n if (!hasDoneAlerted) {\n alert();\n hasDoneAlerted = true;\n }\n // the laundry has been done!!!\n if (totalSeconds > -20) {\n timerDisplay.setText(\"Laundry is done!\");\n } else {\n // the laundry has been done!!!\n timerDisplay.setText(\"Done for \" + DateUtils.formatElapsedTime(-1 * totalSeconds));\n }\n } else {\n timerDisplay.setText(DateUtils.formatElapsedTime(totalSeconds));\n }\n }\n }\n });\n }\n }, 200, 200);\n }\n @OnClick(R.id.timerDisplay)\n void timerDisplayTap(View v) {\n AlarmManager alarm = (AlarmManager)getContext().getSystemService(getContext().ALARM_SERVICE);\n Intent intent = new Intent(getContext(), OnAlarmReceive.class);\n PendingIntent pendingIntent = PendingIntent.getBroadcast(\n getContext(), 0, intent,\n PendingIntent.FLAG_UPDATE_CURRENT);\n if (dtLaundryDone == null) {\n hasDoneAlerted = false;\n dtLaundryDone = (new DateTime()).plusSeconds(timerSeconds);\n alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+ timerSeconds * 1000, pendingIntent);\n } else {\n // remove the notification\n NotificationManager mNotificationManager =\n (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);\n mNotificationManager.cancel(notificationId);\n dtLaundryDone = null;\n // cancel the alarm\n alarm.cancel(pendingIntent);\n }\n }\n}"}}},{"rowIdx":346257,"cells":{"answer":{"kind":"string","value":"package cn.sevensencond.petmonitor;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.ImageView;\nimport android.widget.LinearLayout;\nimport android.widget.ListView;\nimport android.widget.SimpleAdapter;\nimport android.widget.TextView;\npublic class DevicePageActivity extends Activity {\n private TextView mSpotName = null;\n private TextView mSpotNumber = null;\n private TextView mLastLocationTime = null;\n private TextView mLastLocationStatus = null;\n private TextView mLastLocationAddress = null;\n private TextView mSpotPhoneNumber = null;\n private TextView mSpotpageDownarrow = null;\n private TextView mSpotpageUparrow = null;\n private ListView mOperationList = null;\n private LinearLayout mLocationInfo = null;\n private LinearLayout mWaitingLinear = null;\n private ImageView mHeadImage = null;\n private ImageView mSettingImage = null;\n private ImageView mBatteryImage = null;\n private Button mButtonShare = null;\n private List> getData()\n {\n ArrayList localArrayList = new ArrayList();\n HashMap localHashMap1 = new HashMap();\n localHashMap1.put(\"operationImg\", Integer.valueOf(R.drawable.listitem_trackobject));\n localHashMap1.put(\"operationTitle\", getString(R.string.location_label));\n localHashMap1.put(\"operationDesc\", getString(R.string.locationdesc_label));\n localHashMap1.put(\"operationTips\", \"\");\n localArrayList.add(localHashMap1);\n HashMap localHashMap2 = new HashMap();\n localHashMap2.put(\"operationImg\", Integer.valueOf(R.drawable.listitem_history));\n localHashMap2.put(\"operationTitle\", getString(R.string.history));\n localHashMap2.put(\"operationDesc\", getString(R.string.history_desc));\n localHashMap2.put(\"operationTips\", \"\");\n localArrayList.add(localHashMap2);\n HashMap localHashMap3 = new HashMap();\n localHashMap3.put(\"operationImg\", Integer.valueOf(R.drawable.listitem_fence));\n localHashMap3.put(\"operationTitle\", getString(R.string.fence));\n localHashMap3.put(\"operationDesc\", getString(R.string.fence_desc));\n localHashMap3.put(\"operationTips\", getString(R.string.fencein));\n localArrayList.add(localHashMap3);\n HashMap localHashMap9 = new HashMap();\n localHashMap9.put(\"operationImg\", Integer.valueOf(R.drawable.listitem_tracking));\n localHashMap9.put(\"operationTitle\", getString(R.string.following));\n localHashMap9.put(\"operationDesc\", getString(R.string.follow_desc));\n localHashMap9.put(\"operationTips\", \"\");\n localArrayList.add(localHashMap9);\n HashMap localHashMap7 = new HashMap();\n localHashMap7.put(\"operationImg\", Integer.valueOf(R.drawable.listitem_trackormode));\n localHashMap7.put(\"operationTitle\", getString(R.string.trackormode));\n localHashMap7.put(\"operationDesc\", getString(R.string.trackormode_desc));\n localHashMap7.put(\"operationTips\", \"\");\n localArrayList.add(localHashMap7);\n HashMap localHashMap8 = new HashMap();\n localHashMap8.put(\"operationImg\", Integer.valueOf(R.drawable.listitem_sos));\n localHashMap8.put(\"operationTitle\", getString(R.string.trackorsos));\n localHashMap8.put(\"operationDesc\", getString(R.string.sossetting));\n localHashMap8.put(\"operationTips\", \"\");\n localArrayList.add(localHashMap8);\n HashMap localHashMap4 = new HashMap();\n localHashMap4.put(\"operationImg\", Integer.valueOf(R.drawable.listitem_gps));\n localHashMap4.put(\"operationTitle\", getString(R.string.gps_status));\n localHashMap4.put(\"operationDesc\", getString(R.string.gps_status_desc));\n localHashMap4.put(\"operationTips\", getString(R.string.gps_enable));\n localArrayList.add(localHashMap4);\n// HashMap localHashMap5 = new HashMap();\n// localHashMap5.put(\"operationImg\", Integer.valueOf(R.drawable.listitem_deletetrackor));\n// localHashMap5.put(\"operationTitle\", getString(R.string.cancel_share));\n// localHashMap5.put(\"operationDesc\", getString(R.string.cancel_share_desc));\n// localHashMap5.put(\"operationTips\", \"\");\n// localArrayList.add(localHashMap5);\n HashMap localHashMap6 = new HashMap();\n localHashMap6.put(\"operationImg\", Integer.valueOf(R.drawable.listitem_deletetrackor));\n localHashMap6.put(\"operationTitle\", getString(R.string.delete_label));\n localHashMap6.put(\"operationDesc\", getString(R.string.deletedesc_label));\n localHashMap6.put(\"operationTips\", \"\");\n localArrayList.add(localHashMap6);\n return localArrayList;\n }\n View.OnClickListener clickListener = new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n // TODO Auto-generated method stub\n if (v.getId() == R.id.spotpage_text_name)\n {\n Log.d(\"Device\", \"start device setting\");\n Intent localIntent3 = new Intent(DevicePageActivity.this, DeviceSettingActivity.class);\n// localIntent3.putExtra(\"com.bigbangtech.whereru.clip\", true);\n// localIntent3.putExtra(\"com.bigbangtech.whereru.trackerserial\", SpotPage.this.curTracker.serialNumber);\n startActivity(localIntent3);\n }\n }\n };\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n Log.d(\"DevicePage\", \"onCreate\");\n super.onCreate(savedInstanceState);\n setContentView(R.layout.devicepage);\n this.mSpotName = ((TextView)findViewById(R.id.spotpage_text_name));\n this.mSpotName.setOnClickListener(this.clickListener);\n this.mSpotNumber = ((TextView)findViewById(R.id.spotpage_text_number));\n this.mLastLocationTime = ((TextView)findViewById(R.id.last_location_time));\n this.mLastLocationStatus = ((TextView)findViewById(R.id.last_location_status));\n this.mLastLocationAddress = ((TextView)findViewById(R.id.last_location_address));\n this.mSpotPhoneNumber = ((TextView)findViewById(R.id.spotpage_phone_number));\n this.mSpotpageDownarrow = ((TextView)findViewById(R.id.spotpage_downarrow));\n this.mSpotpageUparrow = ((TextView)findViewById(R.id.spotpage_uparrow));\n this.mOperationList = ((ListView)findViewById(R.id.spotpage_listview_operation));\n this.mLocationInfo = ((LinearLayout)findViewById(R.id.devicepage_linear_locationInfo));\n this.mWaitingLinear = ((LinearLayout)findViewById(R.id.devicepage_linear_getLocation));\n this.mHeadImage = ((ImageView)findViewById(R.id.spotpage_image_head));\n this.mSettingImage = ((ImageView)findViewById(R.id.spotpage_personal_setting));\n// this.mHeadImage.setOnClickListener(this.clickListener);\n// this.mSettingImage.setOnClickListener(this.clickListener);\n this.mBatteryImage = ((ImageView)findViewById(R.id.spotpage_image_battery));\n this.mButtonShare = ((Button)findViewById(R.id.spotpage_share));\n// this.mButtonShare.setOnClickListener(this.clickListener);\n Bundle localBundle = getIntent().getBundleExtra(\"cn.sevensencond.petmonitor.devicePage\");\n String deviceName = localBundle.getString(\"cn.sevensencond.petmonitor.devicename\");\n mSpotName.setText(deviceName);\n mLocationInfo.setVisibility(View.VISIBLE);\n mWaitingLinear.setVisibility(View.GONE);\n // stub text first\n// mSpotName.setText(\"075\");\n mSpotPhoneNumber.setText(\"18800000000\");\n mSpotNumber.setText(\"18600000000\");\n mLastLocationTime.setText(\"2012-12-21 00:00:00\");\n mLastLocationStatus.setText(\"\");\n mLastLocationAddress.setText(\"\");\n List localList = getData();\n int i = R.layout.operationlistitem;\n String[] arrayOfString = { \"operationImg\", \"operationTitle\", \"operationDesc\", \"operationTips\" };\n int[] arrayOfInt = new int[4];\n arrayOfInt[0] = R.id.operationlisteitem_img_icon;\n arrayOfInt[1] = R.id.operationlisteitem_text_title;\n arrayOfInt[2] = R.id.operationlisteitem_text_info;\n arrayOfInt[3] = R.id.operationlisteitem_text_tip;\n SimpleAdapter localSimpleAdapter = new SimpleAdapter(this, localList, i, arrayOfString, arrayOfInt);\n this.mOperationList.setAdapter(localSimpleAdapter);\n }\n}"}}},{"rowIdx":346258,"cells":{"answer":{"kind":"string","value":"package uk.ac.soton.ecs.comp3005.l3;\nimport java.awt.Component;\nimport java.awt.Dimension;\nimport java.awt.Font;\nimport java.awt.GridBagConstraints;\nimport java.awt.GridBagLayout;\nimport java.awt.image.BufferedImage;\nimport java.io.IOException;\nimport java.util.Random;\nimport javax.swing.JCheckBox;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.JSeparator;\nimport javax.swing.JSlider;\nimport javax.swing.JTextField;\nimport javax.swing.event.ChangeEvent;\nimport javax.swing.event.ChangeListener;\nimport org.openimaj.content.slideshow.Slide;\nimport org.openimaj.content.slideshow.SlideshowApplication;\nimport org.openimaj.image.DisplayUtilities;\nimport org.openimaj.image.DisplayUtilities.ImageComponent;\nimport org.openimaj.image.ImageUtilities;\nimport org.openimaj.image.MBFImage;\nimport org.openimaj.image.colour.ColourSpace;\nimport org.openimaj.image.colour.RGBColour;\nimport org.openimaj.image.renderer.RenderHints;\nimport org.openimaj.math.geometry.point.Point2dImpl;\nimport org.openimaj.math.geometry.shape.Ellipse;\nimport org.openimaj.math.geometry.shape.EllipseUtilities;\nimport org.openimaj.math.geometry.transforms.TransformUtilities;\nimport org.openimaj.math.statistics.distribution.CachingMultivariateGaussian;\nimport uk.ac.soton.ecs.comp3005.utils.Utils;\nimport uk.ac.soton.ecs.comp3005.utils.annotations.Demonstration;\nimport Jama.Matrix;\n/**\n * Demonstration of 2D covariance\n *\n * @author Jonathon Hare (jsh2@ecs.soton.ac.uk)\n */\n@Demonstration(title = \"2D Covariance Matrix Demo\")\npublic class CovarianceDemo implements Slide {\n protected static final Font FONT = Font.decode(\"Monaco-48\");\n protected Matrix covariance;\n protected BufferedImage bimg;\n protected MBFImage image;\n protected ImageComponent imageComp;\n protected JSlider xxSlider;\n protected JSlider yySlider;\n protected JSlider xySlider;\n protected JTextField xxField;\n protected JTextField xyField;\n protected JTextField yxField;\n protected JTextField yyField;\n protected boolean drawData = true;\n protected boolean drawEllipse = false;\n @Override\n public Component getComponent(int width, int height) throws IOException {\n covariance = Matrix.identity(2, 2);\n final JPanel base = new JPanel();\n base.setOpaque(false);\n base.setPreferredSize(new Dimension(width, height));\n base.setLayout(new GridBagLayout());\n image = new MBFImage(400, 400, ColourSpace.RGB);\n imageComp = new DisplayUtilities.ImageComponent(true, false);\n imageComp.setShowPixelColours(false);\n imageComp.setShowXYPosition(false);\n imageComp.setAllowZoom(false);\n imageComp.setAllowPanning(false);\n base.add(imageComp);\n final JPanel sep = new JPanel();\n sep.setOpaque(false);\n sep.setPreferredSize(new Dimension(80, 450));\n base.add(sep);\n xxSlider = new JSlider();\n yySlider = new JSlider();\n xySlider = new JSlider();\n xySlider.setMinimum(-100);\n xySlider.setMaximum(100);\n xxSlider.setValue(100);\n xySlider.setValue(0);\n yySlider.setValue(100);\n xxSlider.addChangeListener(new ChangeListener() {\n @Override\n public void stateChanged(ChangeEvent e) {\n setXX();\n }\n });\n yySlider.addChangeListener(new ChangeListener() {\n @Override\n public void stateChanged(ChangeEvent e) {\n setYY();\n }\n });\n xySlider.addChangeListener(new ChangeListener() {\n @Override\n public void stateChanged(ChangeEvent e) {\n setXY();\n }\n });\n final GridBagConstraints c = new GridBagConstraints();\n final JPanel matrix = new JPanel(new GridBagLayout());\n c.gridwidth = 1;\n c.gridheight = 1;\n c.gridy = 0;\n c.gridx = 0;\n matrix.add(xxField = new JTextField(5), c);\n xxField.setFont(FONT);\n xxField.setEditable(false);\n c.gridx = 1;\n matrix.add(xyField = new JTextField(5), c);\n xyField.setFont(FONT);\n xyField.setEditable(false);\n c.gridy = 1;\n c.gridx = 0;\n matrix.add(yxField = new JTextField(5), c);\n yxField.setFont(FONT);\n yxField.setEditable(false);\n c.gridx = 1;\n matrix.add(yyField = new JTextField(5), c);\n yyField.setFont(FONT);\n yyField.setEditable(false);\n final JPanel controls = new JPanel(new GridBagLayout());\n controls.setOpaque(false);\n c.gridwidth = 2;\n c.gridheight = 1;\n c.gridy = 0;\n c.gridx = 0;\n controls.add(matrix, c);\n c.gridwidth = 2;\n c.gridy = 2;\n c.gridx = 0;\n controls.add(new JSeparator(), c);\n c.gridy = 3;\n c.gridx = 0;\n controls.add(new JSeparator(), c);\n c.gridwidth = 1;\n c.gridy = 4;\n c.gridx = 0;\n final JLabel xxLabel = new JLabel(\"XX:\");\n xxLabel.setFont(FONT);\n controls.add(xxLabel, c);\n c.gridx = 1;\n controls.add(xxSlider, c);\n c.gridy = 5;\n c.gridx = 0;\n final JLabel yyLabel = new JLabel(\"YY:\");\n yyLabel.setFont(FONT);\n controls.add(yyLabel, c);\n c.gridx = 1;\n controls.add(yySlider, c);\n c.gridy = 6;\n c.gridx = 0;\n final JLabel xyLabel = new JLabel(\"XY:\");\n xyLabel.setFont(FONT);\n xyLabel.setHorizontalAlignment(JLabel.RIGHT);\n controls.add(xyLabel, c);\n c.gridx = 1;\n controls.add(xySlider, c);\n c.gridwidth = 2;\n c.gridy = 7;\n c.gridx = 0;\n controls.add(new JSeparator(), c);\n c.gridy = 5;\n c.gridx = 0;\n controls.add(new JSeparator(), c);\n c.gridwidth = 1;\n c.gridy = 8;\n c.gridx = 0;\n controls.add(new JLabel(\"Show data points:\"), c);\n c.gridx = 1;\n final JCheckBox checkBox = new JCheckBox();\n checkBox.setSelected(drawData);\n checkBox.addChangeListener(new ChangeListener() {\n @Override\n public void stateChanged(ChangeEvent e) {\n drawData = ((JCheckBox) e.getSource()).isSelected();\n updateImage();\n }\n });\n controls.add(checkBox, c);\n c.gridwidth = 1;\n c.gridy = 9;\n c.gridx = 0;\n controls.add(new JLabel(\"Show ellipse:\"), c);\n c.gridx = 1;\n final JCheckBox checkBox2 = new JCheckBox();\n checkBox2.setSelected(drawEllipse);\n checkBox2.addChangeListener(new ChangeListener() {\n @Override\n public void stateChanged(ChangeEvent e) {\n drawEllipse = ((JCheckBox) e.getSource()).isSelected();\n updateImage();\n }\n });\n controls.add(checkBox2, c);\n base.add(controls);\n updateImage();\n return base;\n }\n protected void updateImage() {\n xxField.setText(String.format(\"%2.2f\", covariance.get(0, 0)));\n xyField.setText(String.format(\"%2.2f\", covariance.get(0, 1)));\n yxField.setText(String.format(\"%2.2f\", covariance.get(1, 0)));\n yyField.setText(String.format(\"%2.2f\", covariance.get(1, 1)));\n image.fill(RGBColour.WHITE);\n image.drawLine(image.getWidth() / 2, 0, image.getWidth() / 2, image.getHeight(), 3, RGBColour.BLACK);\n image.drawLine(0, image.getHeight() / 2, image.getWidth(), image.getHeight() / 2, 3, RGBColour.BLACK);\n Ellipse e = EllipseUtilities.ellipseFromCovariance(image.getWidth() / 2, image.getHeight() / 2, covariance,\n 100);\n e = e.transformAffine(TransformUtilities.scaleMatrixAboutPoint(1, -1, image.getWidth() / 2, image.getHeight() / 2));\n if (!Double.isNaN(e.getMajor()) && !Double.isNaN(e.getMinor()) && covariance.rank() == 2) {\n final Matrix mean = new Matrix(new double[][] { { image.getWidth() / 2, image.getHeight() / 2 } });\n final CachingMultivariateGaussian gauss = new CachingMultivariateGaussian(mean, covariance);\n if (drawData) {\n final Random rng = new Random();\n for (int i = 0; i < 1000; i++) {\n final double[] sample = gauss.sample(rng);\n Point2dImpl pt = new Point2dImpl((float) sample[0], (float) sample[1]);\n pt = pt.transform(TransformUtilities.scaleMatrixAboutPoint(40, -40, image.getWidth() / 2,\n image.getHeight() / 2));\n image.drawPoint(pt, RGBColour.BLUE, 3);\n }\n }\n if (drawEllipse)\n image.createRenderer(RenderHints.ANTI_ALIASED).drawShape(e, 3, RGBColour.RED);\n }\n this.imageComp.setImage(bimg = ImageUtilities.createBufferedImageForDisplay(image, bimg));\n }\n protected void setYY() {\n covariance.set(1, 1, yySlider.getValue() / 100d);\n updateImage();\n }\n protected void setXY() {\n covariance.set(1, 0, xySlider.getValue() / 100d);\n covariance.set(0, 1, xySlider.getValue() / 100d);\n updateImage();\n }\n protected void setXX() {\n covariance.set(0, 0, xxSlider.getValue() / 100d);\n updateImage();\n }\n @Override\n public void close() {\n // do nothing\n }\n public static void main(String[] args) throws IOException {\n new SlideshowApplication(new CovarianceDemo(), 1024, 768, Utils.BACKGROUND_IMAGE);\n }\n}"}}},{"rowIdx":346259,"cells":{"answer":{"kind":"string","value":"package af.algorithms;\nimport af.model.Pathway;\nimport af.model.WayPoint;\nimport java.util.Properties;\npublic class ShortRouteCalculator implements RouteCalculator {\n Properties props;\n @Override\n public Pathway calcRoute(Pathway pw) {\n pw.addWaypoint(new WayPoint(\"one\", 0, 0));\n pw.addWaypoint(new WayPoint(\"two\", 0, 0));\n return pw;\n }\n @Override\n public void setCalcOptions(Properties props) {\n this.props = props;\n }\n}"}}},{"rowIdx":346260,"cells":{"answer":{"kind":"string","value":"package org.commcare.activities;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.Button;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport org.commcare.CommCareApplication;\nimport org.commcare.dalvik.R;\nimport org.commcare.tasks.ConnectionDiagnosticTask;\nimport org.commcare.tasks.DataSubmissionListener;\nimport org.commcare.tasks.LogSubmissionTask;\nimport org.commcare.utils.CommCareUtil;\nimport org.commcare.utils.MarkupUtil;\nimport org.commcare.views.ManagedUi;\nimport org.commcare.views.UiElement;\nimport org.commcare.views.dialogs.CustomProgressDialog;\nimport org.javarosa.core.services.Logger;\nimport org.javarosa.core.services.locale.Localization;\n/**\n * Activity that will diagnose various connection problems that a user may be facing.\n *\n * @author srengesh\n */\n@ManagedUi(R.layout.connection_diagnostic)\npublic class ConnectionDiagnosticActivity extends CommCareActivity {\n private static final String TAG = ConnectionDiagnosticActivity.class.getSimpleName();\n public static final String logUnsetPostURLMessage = \"CCHQ ping test: post URL not set.\";\n @UiElement(value = R.id.run_connection_test, locale = \"connection.test.run\")\n Button btnRunTest;\n @UiElement(value = R.id.output_message, locale = \"connection.test.messages\")\n TextView txtInteractiveMessages;\n @UiElement(value = R.id.settings_button, locale = \"connection.test.access.settings\")\n Button settingsButton;\n @UiElement(value = R.id.report_button, locale = \"connection.test.report.button.message\")\n Button reportButton;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n btnRunTest.setOnClickListener(v -> {\n ConnectionDiagnosticTask mConnectionDiagnosticTask =\n new ConnectionDiagnosticTask(getApplicationContext()) {\n @Override\n // receiver, result.\n // is the return from DoTaskBackground, of type ArrayList\n protected void deliverResult(ConnectionDiagnosticActivity receiver, Test failedTest) {\n //user-caused connection issues\n if (failedTest == Test.isOnline ||\n failedTest == Test.googlePing) {\n //get the appropriate display message based on what the problem is\n String displayMessage = failedTest == Test.isOnline ?\n Localization.get(\"connection.task.internet.fail\")\n : Localization.get(\"connection.task.remote.ping.fail\");\n receiver.txtInteractiveMessages.setText(displayMessage);\n receiver.txtInteractiveMessages.setVisibility(View.VISIBLE);\n receiver.settingsButton.setVisibility(View.VISIBLE);\n } else if (failedTest == Test.commCarePing) {\n //unable to ping commcare -- report this to cchq\n receiver.txtInteractiveMessages.setText(\n Localization.get(\"connection.task.commcare.html.fail\"));\n receiver.txtInteractiveMessages.setVisibility(View.VISIBLE);\n receiver.reportButton.setVisibility(View.VISIBLE);\n } else if (failedTest == null) {\n receiver.txtInteractiveMessages.setText(Localization.get(\"connection.task.success\"));\n receiver.txtInteractiveMessages.setVisibility(View.VISIBLE);\n receiver.settingsButton.setVisibility(View.INVISIBLE);\n receiver.reportButton.setVisibility(View.INVISIBLE);\n }\n }\n @Override\n protected void deliverUpdate(ConnectionDiagnosticActivity receiver, String... update) {\n receiver.txtInteractiveMessages.setText((Localization.get(\"connection.test.update.message\")));\n }\n @Override\n protected void deliverError(ConnectionDiagnosticActivity receiver, Exception e) {\n receiver.txtInteractiveMessages.setText(Localization.get(\"connection.test.error.message\"));\n receiver.transplantStyle(txtInteractiveMessages, R.layout.template_text_notification_problem);\n }\n };\n mConnectionDiagnosticTask.connect(ConnectionDiagnosticActivity.this);\n mConnectionDiagnosticTask.executeParallel();\n });\n //Set a button that allows you to change your airplane mode settings\n this.settingsButton.setOnClickListener(v -> startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS)));\n this.reportButton.setOnClickListener(v -> {\n String url = LogSubmissionTask.getSubmissionUrl(CommCareApplication.instance().getCurrentApp().getAppPreferences());\n if (url != null) {\n CommCareUtil.executeLogSubmission(url, false);\n ConnectionDiagnosticActivity.this.finish();\n Toast.makeText(\n CommCareApplication.instance(),\n Localization.get(\"connection.task.report.commcare.popup\"),\n Toast.LENGTH_LONG).show();\n } else {\n Logger.log(ConnectionDiagnosticTask.CONNECTION_DIAGNOSTIC_REPORT, logUnsetPostURLMessage);\n ConnectionDiagnosticActivity.this.txtInteractiveMessages.setText(MarkupUtil.localizeStyleSpannable(ConnectionDiagnosticActivity.this, \"connection.task.unset.posturl\"));\n ConnectionDiagnosticActivity.this.txtInteractiveMessages.setVisibility(View.VISIBLE);\n }\n });\n }\n /**\n * Implementation of generateProgressDialog() for DialogController -- other methods\n * handled entirely in CommCareActivity\n */\n @Override\n public CustomProgressDialog generateProgressDialog(int taskId) {\n if (taskId == ConnectionDiagnosticTask.CONNECTION_ID) {\n String title = Localization.get(\"connection.test.run.title\");\n String message = Localization.get(\"connection.test.now.running\");\n CustomProgressDialog dialog = CustomProgressDialog.newInstance(title, message, taskId);\n dialog.setCancelable();\n return dialog;\n } else {\n Log.w(TAG, \"taskId passed to generateProgressDialog does not match \"\n + \"any valid possibilities in ConnectionDiagnosticActivity\");\n return null;\n }\n }\n}"}}},{"rowIdx":346261,"cells":{"answer":{"kind":"string","value":"package org.commcare.dalvik.activities;\nimport android.app.ActionBar;\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.database.Cursor;\nimport android.net.Uri;\nimport android.os.AsyncTask;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.PowerManager;\nimport android.support.v4.app.Fragment;\nimport android.support.v4.app.FragmentManager;\nimport android.support.v4.app.FragmentTransaction;\nimport android.util.Log;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.widget.Toast;\nimport org.commcare.android.database.global.models.ApplicationRecord;\nimport org.commcare.android.fragments.SetupEnterURLFragment;\nimport org.commcare.android.fragments.SetupInstallFragment;\nimport org.commcare.android.fragments.SetupKeepInstallFragment;\nimport org.commcare.android.framework.CommCareActivity;\nimport org.commcare.android.framework.ManagedUi;\nimport org.commcare.android.logic.BarcodeScanListenerDefaultImpl;\nimport org.commcare.android.logic.GlobalConstants;\nimport org.commcare.android.models.notifications.NotificationMessage;\nimport org.commcare.android.models.notifications.NotificationMessageFactory;\nimport org.commcare.android.resource.AppInstallStatus;\nimport org.commcare.android.tasks.ResourceEngineListener;\nimport org.commcare.android.tasks.ResourceEngineTask;\nimport org.commcare.android.tasks.RetrieveParseVerifyMessageListener;\nimport org.commcare.android.tasks.RetrieveParseVerifyMessageTask;\nimport org.commcare.dalvik.BuildConfig;\nimport org.commcare.dalvik.R;\nimport org.commcare.dalvik.application.CommCareApp;\nimport org.commcare.dalvik.application.CommCareApplication;\nimport org.commcare.dalvik.dialogs.CustomProgressDialog;\nimport org.commcare.resources.model.UnresolvedResourceException;\nimport org.javarosa.core.reference.InvalidReferenceException;\nimport org.javarosa.core.reference.ReferenceManager;\nimport org.javarosa.core.services.locale.Localization;\nimport org.javarosa.core.util.PropertyUtils;\nimport org.joda.time.DateTime;\nimport java.io.IOException;\nimport java.security.SignatureException;\nimport java.util.List;\n/**\n * Responsible for identifying the state of the application (uninstalled,\n * installed) and performing any necessary setup to get to a place where\n * CommCare can load normally.\n *\n * If the startup activity identifies that the app is installed properly it\n * should not ever require interaction or be visible to the user.\n *\n * @author ctsims\n */\n@ManagedUi(R.layout.first_start_screen_modern)\npublic class CommCareSetupActivity extends CommCareActivity\n implements ResourceEngineListener, SetupEnterURLFragment.URLInstaller,\n SetupKeepInstallFragment.StartStopInstallCommands, RetrieveParseVerifyMessageListener {\n private static final String TAG = CommCareSetupActivity.class.getSimpleName();\n public static final String KEY_PROFILE_REF = \"app_profile_ref\";\n private static final String KEY_UI_STATE = \"current_install_ui_state\";\n private static final String KEY_OFFLINE = \"offline_install\";\n private static final String KEY_FROM_EXTERNAL = \"from_external\";\n private static final String KEY_FROM_MANAGER = \"from_manager\";\n /**\n * Should the user be logged out when this activity is done?\n */\n public static final String KEY_REQUIRE_REFRESH = \"require_referesh\";\n public static final String KEY_INSTALL_FAILED = \"install_failed\";\n /**\n * Activity is being launched by auto update, instead of being triggered\n * manually.\n */\n public static final String KEY_LAST_INSTALL = \"last_install_time\";\n /**\n * How many sms messages to scan over looking for commcare install link\n */\n private static final int SMS_CHECK_COUNT = 100;\n /**\n * UI configuration states.\n */\n public enum UiState {\n IN_URL_ENTRY,\n CHOOSE_INSTALL_ENTRY_METHOD,\n READY_TO_INSTALL,\n ERROR\n }\n private UiState uiState = UiState.CHOOSE_INSTALL_ENTRY_METHOD;\n private static final int MODE_ARCHIVE = Menu.FIRST;\n private static final int MODE_SMS = Menu.FIRST + 2;\n public static final int BARCODE_CAPTURE = 1;\n private static final int ARCHIVE_INSTALL = 3;\n private static final int DIALOG_INSTALL_PROGRESS = 4;\n private boolean startAllowed = true;\n private String incomingRef;\n private CommCareApp ccApp;\n /**\n * Indicates that this activity was launched from the AppManagerActivity\n */\n private boolean fromManager;\n /**\n * Indicates that this activity was launched from an outside application (such as a bit.ly\n * url entered in a browser)\n */\n private boolean fromExternal;\n /**\n * Indicates that the current install attempt will be made from a .ccz file, so we do\n * not need to check for internet connectivity\n */\n private boolean offlineInstall;\n //region UIState fragments\n private final FragmentManager fm = getSupportFragmentManager();\n private final SetupKeepInstallFragment startInstall = new SetupKeepInstallFragment();\n private final SetupInstallFragment installFragment = new SetupInstallFragment();\n //endregion\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n CommCareSetupActivity oldActivity = (CommCareSetupActivity)this.getDestroyedActivityState();\n this.fromManager = this.getIntent().\n getBooleanExtra(AppManagerActivity.KEY_LAUNCH_FROM_MANAGER, false);\n //Retrieve instance state\n if (savedInstanceState == null) {\n Log.v(\"UiState\", \"SavedInstanceState is null, not getting anything from it =/\");\n if (Intent.ACTION_VIEW.equals(this.getIntent().getAction())) {\n //We got called from an outside application, it's gonna be a wild ride!\n fromExternal = true;\n incomingRef = this.getIntent().getData().toString();\n if (incomingRef.contains(\".ccz\")) {\n // make sure this is in the file system\n boolean isFile = incomingRef.contains(\"file:\n if (isFile) {\n // remove file:// prepend\n incomingRef = incomingRef.substring(incomingRef.indexOf(\"\n Intent i = new Intent(this, InstallArchiveActivity.class);\n i.putExtra(InstallArchiveActivity.ARCHIVE_REFERENCE, incomingRef);\n startActivityForResult(i, ARCHIVE_INSTALL);\n } else {\n fail(NotificationMessageFactory.message(NotificationMessageFactory.StockMessages.Bad_Archive_File), true);\n }\n } else {\n this.uiState = UiState.READY_TO_INSTALL;\n //Now just start up normally.\n }\n } else {\n incomingRef = this.getIntent().getStringExtra(KEY_PROFILE_REF);\n }\n } else {\n String uiStateEncoded = savedInstanceState.getString(KEY_UI_STATE);\n this.uiState = uiStateEncoded == null ? UiState.CHOOSE_INSTALL_ENTRY_METHOD : UiState.valueOf(UiState.class, uiStateEncoded);\n Log.v(\"UiState\", \"uiStateEncoded is: \" + uiStateEncoded +\n \", so my uiState is: \" + uiState);\n incomingRef = savedInstanceState.getString(\"profileref\");\n fromExternal = savedInstanceState.getBoolean(KEY_FROM_EXTERNAL);\n fromManager = savedInstanceState.getBoolean(KEY_FROM_MANAGER);\n offlineInstall = savedInstanceState.getBoolean(KEY_OFFLINE);\n // Uggggh, this might not be 100% legit depending on timing, what\n // if we've already reconnected and shut down the dialog?\n startAllowed = savedInstanceState.getBoolean(\"startAllowed\");\n }\n // reclaim ccApp for resuming installation\n if (oldActivity != null) {\n this.ccApp = oldActivity.ccApp;\n }\n Log.v(\"UiState\", \"Current vars: \" +\n \"UIState is: \" + this.uiState + \" \" +\n \"incomingRef is: \" + incomingRef + \" \" +\n \"startAllowed is: \" + startAllowed + \" \"\n );\n uiStateScreenTransition();\n performSMSInstall(false);\n }\n @Override\n public void onAttachFragment(Fragment fragment) {\n super.onAttachFragment(fragment);\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {\n ActionBar actionBar = getActionBar();\n if (actionBar != null) {\n // removes the back button from the action bar\n actionBar.setDisplayHomeAsUpEnabled(false);\n }\n }\n }\n @Override\n protected void onResume() {\n super.onResume();\n // If clicking the regular app icon brought us to CommCareSetupActivity\n // (because that's where we were last time the app was up), but there are now\n // 1 or more available apps, we want to redirect to CCHomeActivity\n if (!fromManager && !fromExternal &&\n CommCareApplication._().usableAppsPresent()) {\n Intent i = new Intent(this, CommCareHomeActivity.class);\n startActivity(i);\n }\n }\n @Override\n public void onURLChosen(String url) {\n if (BuildConfig.DEBUG) {\n Log.d(TAG, \"SetupEnterURLFragment returned: \" + url);\n }\n incomingRef = url;\n this.uiState = UiState.READY_TO_INSTALL;\n uiStateScreenTransition();\n }\n private void uiStateScreenTransition() {\n Fragment fragment;\n FragmentTransaction ft = fm.beginTransaction();\n switch (uiState) {\n case READY_TO_INSTALL:\n if (incomingRef == null || incomingRef.length() == 0) {\n Log.e(TAG, \"During install: IncomingRef is empty!\");\n Toast.makeText(getApplicationContext(), \"Invalid URL: '\" +\n incomingRef + \"'\", Toast.LENGTH_SHORT).show();\n return;\n }\n // the buttonCommands were already set when the fragment was\n // attached, no need to set them here\n fragment = startInstall;\n break;\n case IN_URL_ENTRY:\n fragment = restoreInstallSetupFragment();\n this.offlineInstall = false;\n break;\n case CHOOSE_INSTALL_ENTRY_METHOD:\n fragment = installFragment;\n this.offlineInstall = false;\n break;\n default:\n return;\n }\n ft.replace(R.id.setup_fragment_container, fragment);\n ft.commit();\n }\n private Fragment restoreInstallSetupFragment() {\n Fragment fragment = null;\n List fgmts = fm.getFragments();\n int lastIndex = fgmts != null ? fgmts.size() - 1 : -1;\n if (lastIndex > -1) {\n fragment = fgmts.get(lastIndex);\n if (BuildConfig.DEBUG) {\n Log.v(TAG, \"Last fragment: \" + fragment);\n }\n }\n if (!(fragment instanceof SetupEnterURLFragment)) {\n // last fragment wasn't url entry, so default to the installation method chooser\n fragment = installFragment;\n }\n return fragment;\n }\n @Override\n protected void onStart() {\n super.onStart();\n uiStateScreenTransition();\n }\n @Override\n protected int getWakeLockLevel() {\n return PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE;\n }\n @Override\n protected void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n outState.putString(KEY_UI_STATE, uiState.toString());\n outState.putString(\"profileref\", incomingRef);\n outState.putBoolean(\"startAllowed\", startAllowed);\n outState.putBoolean(KEY_OFFLINE, offlineInstall);\n outState.putBoolean(KEY_FROM_EXTERNAL, fromExternal);\n outState.putBoolean(KEY_FROM_MANAGER, fromManager);\n Log.v(\"UiState\", \"Saving instance state: \" + outState);\n }\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n String result = null;\n switch (requestCode) {\n case BARCODE_CAPTURE:\n if (resultCode == Activity.RESULT_OK) {\n result = data.getStringExtra(BarcodeScanListenerDefaultImpl.SCAN_RESULT);\n String dbg = \"Got url from barcode scanner: \" + result;\n Log.i(TAG, dbg);\n }\n break;\n case ARCHIVE_INSTALL:\n if (resultCode == Activity.RESULT_OK) {\n offlineInstall = true;\n result = data.getStringExtra(InstallArchiveActivity.ARCHIVE_REFERENCE);\n }\n break;\n }\n if (result == null) return;\n incomingRef = result;\n this.uiState = UiState.READY_TO_INSTALL;\n try {\n // check if the reference can be derived without erroring out\n ReferenceManager._().DeriveReference(incomingRef);\n } catch (InvalidReferenceException ire) {\n // Couldn't process reference, return to basic ui state to ask user\n // for new install reference\n incomingRef = null;\n Toast.makeText(getApplicationContext(),\n Localization.get(\"install.bad.ref\"),\n Toast.LENGTH_LONG).show();\n this.uiState = UiState.CHOOSE_INSTALL_ENTRY_METHOD;\n }\n uiStateScreenTransition();\n }\n private String getRef() {\n return incomingRef;\n }\n private CommCareApp getCommCareApp() {\n ApplicationRecord newRecord =\n new ApplicationRecord(PropertyUtils.genUUID().replace(\"-\", \"\"),\n ApplicationRecord.STATUS_UNINITIALIZED);\n return new CommCareApp(newRecord);\n }\n @Override\n public void startBlockingForTask(int id) {\n super.startBlockingForTask(id);\n this.startAllowed = false;\n }\n @Override\n public void stopBlockingForTask(int id) {\n super.stopBlockingForTask(id);\n this.startAllowed = true;\n }\n private void startResourceInstall() {\n if (startAllowed) {\n CommCareApp app = getCommCareApp();\n ccApp = app;\n CustomProgressDialog lastDialog = getCurrentDialog();\n // used to tell the ResourceEngineTask whether or not it should\n // sleep before it starts, set based on whether we are currently\n // in keep trying mode.\n boolean shouldSleep = (lastDialog != null) && lastDialog.isChecked();\n ResourceEngineTask task =\n new ResourceEngineTask(app,\n DIALOG_INSTALL_PROGRESS, shouldSleep) {\n @Override\n protected void deliverResult(CommCareSetupActivity receiver,\n AppInstallStatus result) {\n switch (result) {\n case Installed:\n receiver.reportSuccess(true);\n break;\n case UpToDate:\n receiver.reportSuccess(false);\n break;\n case MissingResourcesWithMessage:\n // fall through to more general case:\n case MissingResources:\n receiver.failMissingResource(this.missingResourceException, result);\n break;\n case IncompatibleReqs:\n receiver.failBadReqs(badReqCode, vRequired, vAvailable, majorIsProblem);\n break;\n case NoLocalStorage:\n receiver.failWithNotification(AppInstallStatus.NoLocalStorage);\n break;\n case BadCertificate:\n receiver.failWithNotification(AppInstallStatus.BadCertificate);\n break;\n case DuplicateApp:\n receiver.failWithNotification(AppInstallStatus.DuplicateApp);\n break;\n default:\n receiver.failUnknown(AppInstallStatus.UnknownFailure);\n break;\n }\n }\n @Override\n protected void deliverUpdate(CommCareSetupActivity receiver,\n int[]... update) {\n receiver.updateResourceProgress(update[0][0], update[0][1], update[0][2]);\n }\n @Override\n protected void deliverError(CommCareSetupActivity receiver,\n Exception e) {\n receiver.failUnknown(AppInstallStatus.UnknownFailure);\n }\n };\n task.connect(this);\n task.execute(getRef());\n } else {\n Log.i(TAG, \"During install: blocked a resource install press since a task was already running\");\n }\n }\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n super.onCreateOptionsMenu(menu);\n menu.add(0, MODE_ARCHIVE, 0, Localization.get(\"menu.archive\")).setIcon(android.R.drawable.ic_menu_upload);\n menu.add(0, MODE_SMS, 1, Localization.get(\"menu.sms\")).setIcon(android.R.drawable.stat_notify_chat);\n return true;\n }\n @Override\n public boolean onPrepareOptionsMenu(Menu menu) {\n super.onPrepareOptionsMenu(menu);\n return true;\n }\n /**\n * Scan SMS messages for texts with profile references.\n * @param installTriggeredManually if scan was triggered manually, then\n * install automatically if reference is found\n */\n private void performSMSInstall(boolean installTriggeredManually){\n this.scanSMSLinks(installTriggeredManually);\n }\n /**\n * Scan the most recent incoming text messages for a message with a\n * verified link to a commcare app and install it. Message scanning stops\n * after the number of scanned messages reaches 'SMS_CHECK_COUNT'.\n *\n * @param installTriggeredManually don't install the found app link\n */\n private void scanSMSLinks(final boolean installTriggeredManually){\n final Uri SMS_INBOX = Uri.parse(\"content://sms/inbox\");\n DateTime oneDayAgo = (new DateTime()).minusDays(1);\n Cursor cursor = getContentResolver().query(SMS_INBOX,\n null, \"date >? \",\n new String[] {\"\" + oneDayAgo.getMillis() },\n \"date DESC\");\n if (cursor == null) {\n return;\n }\n int messageIterationCount = 0;\n try {\n boolean attemptedInstall = false;\n while (cursor.moveToNext() && messageIterationCount <= SMS_CHECK_COUNT) { // must check the result to prevent exception\n messageIterationCount++;\n String textMessageBody = cursor.getString(cursor.getColumnIndex(\"body\"));\n if (textMessageBody.contains(GlobalConstants.SMS_INSTALL_KEY_STRING)) {\n attemptedInstall = true;\n RetrieveParseVerifyMessageTask mTask =\n new RetrieveParseVerifyMessageTask(this, installTriggeredManually) {\n @Override\n protected void deliverResult(CommCareSetupActivity receiver, String result) {\n if (installTriggeredManually) {\n if (result != null) {\n receiver.incomingRef = result;\n receiver.uiState = UiState.READY_TO_INSTALL;\n receiver.uiStateScreenTransition();\n receiver.startResourceInstall();\n } else {\n // only notify if this was manually triggered, since most people won't use this\n Toast.makeText(receiver, Localization.get(\"menu.sms.not.found\"), Toast.LENGTH_LONG).show();\n }\n } else {\n if (result != null) {\n receiver.incomingRef = result;\n receiver.uiState = UiState.READY_TO_INSTALL;\n receiver.uiStateScreenTransition();\n Toast.makeText(receiver, Localization.get(\"menu.sms.ready\"), Toast.LENGTH_LONG).show();\n }\n }\n }\n @Override\n protected void deliverUpdate(CommCareSetupActivity receiver, Void... update) {\n //do nothing for now\n }\n @Override\n protected void deliverError(CommCareSetupActivity receiver, Exception e) {\n if (e instanceof SignatureException) {\n e.printStackTrace();\n Toast.makeText(receiver, Localization.get(\"menu.sms.not.verified\"), Toast.LENGTH_LONG).show();\n } else if (e instanceof IOException) {\n e.printStackTrace();\n Toast.makeText(receiver, Localization.get(\"menu.sms.not.retrieved\"), Toast.LENGTH_LONG).show();\n } else {\n e.printStackTrace();\n Toast.makeText(receiver, Localization.get(\"notification.install.unknown.title\"), Toast.LENGTH_LONG).show();\n }\n }\n };\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {\n mTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, textMessageBody);\n } else {\n mTask.execute(textMessageBody);\n }\n break;\n }\n }\n // attemptedInstall will only be true if we found no texts with the SMS_INSTALL_KEY_STRING tag\n // if we found one, notification will be handle by the task receiver\n if(!attemptedInstall && installTriggeredManually) {\n Toast.makeText(this, Localization.get(\"menu.sms.not.found\"), Toast.LENGTH_LONG).show();\n }\n }\n finally {\n cursor.close();\n }\n }\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n if (item.getItemId() == MODE_ARCHIVE) {\n Intent i = new Intent(getApplicationContext(), InstallArchiveActivity.class);\n startActivityForResult(i, ARCHIVE_INSTALL);\n }\n if (item.getItemId() == MODE_SMS) {\n performSMSInstall(true);\n }\n return true;\n }\n /**\n * Return to or launch home activity.\n *\n * @param requireRefresh should the user be logged out upon returning to\n * home activity?\n * @param failed did installation occur successfully?\n */\n private void done(boolean requireRefresh, boolean failed) {\n if (Intent.ACTION_VIEW.equals(CommCareSetupActivity.this.getIntent().getAction())) {\n //Call out to CommCare Home\n Intent i = new Intent(getApplicationContext(), CommCareHomeActivity.class);\n i.putExtra(KEY_REQUIRE_REFRESH, requireRefresh);\n startActivity(i);\n } else {\n //Good to go\n Intent i = new Intent(getIntent());\n i.putExtra(KEY_REQUIRE_REFRESH, requireRefresh);\n i.putExtra(KEY_INSTALL_FAILED, failed);\n setResult(RESULT_OK, i);\n }\n finish();\n }\n /**\n * Raise failure message and return to the home activity with cancel code\n */\n private void fail(NotificationMessage message, boolean alwaysNotify) {\n Toast.makeText(this, message.getTitle(), Toast.LENGTH_LONG).show();\n if (alwaysNotify) {\n CommCareApplication._().reportNotificationMessage(message);\n }\n // Last install attempt failed, so restore to starting uistate to try again\n uiState = UiState.CHOOSE_INSTALL_ENTRY_METHOD;\n uiStateScreenTransition();\n }\n // All final paths from the Update are handled here (Important! Some\n // interaction modes should always auto-exit this activity) Everything here\n // should call one of: fail() or done()\n /* All methods for implementation of ResourceEngineListener */\n @Override\n public void reportSuccess(boolean appChanged) {\n //If things worked, go ahead and clear out any warnings to the contrary\n CommCareApplication._().clearNotifications(\"install_update\");\n if (!appChanged) {\n Toast.makeText(this, Localization.get(\"updates.success\"), Toast.LENGTH_LONG).show();\n }\n done(appChanged, false);\n }\n @Override\n public void failMissingResource(UnresolvedResourceException ure, AppInstallStatus statusMissing) {\n fail(NotificationMessageFactory.message(statusMissing, new String[]{null, ure.getResource().getDescriptor(), ure.getMessage()}), ure.isMessageUseful());\n }\n @Override\n public void failBadReqs(int code, String vRequired, String vAvailable, boolean majorIsProblem) {\n String versionMismatch = Localization.get(\"install.version.mismatch\", new String[]{vRequired, vAvailable});\n String error;\n if (majorIsProblem) {\n error = Localization.get(\"install.major.mismatch\");\n } else {\n error = Localization.get(\"install.minor.mismatch\");\n }\n fail(NotificationMessageFactory.message(AppInstallStatus.IncompatibleReqs, new String[]{null, versionMismatch, error}), true);\n }\n @Override\n public void failUnknown(AppInstallStatus unknown) {\n fail(NotificationMessageFactory.message(unknown), false);\n }\n @Override\n public void updateResourceProgress(int done, int total, int phase) {\n updateProgress(Localization.get(\"profile.found\", new String[]{\"\" + done, \"\" + total}), DIALOG_INSTALL_PROGRESS);\n updateProgressBar(done, total, DIALOG_INSTALL_PROGRESS);\n }\n @Override\n public void failWithNotification(AppInstallStatus statusfailstate) {\n fail(NotificationMessageFactory.message(statusfailstate), true);\n }\n @Override\n public CustomProgressDialog generateProgressDialog(int taskId) {\n if (taskId != DIALOG_INSTALL_PROGRESS) {\n Log.w(TAG, \"taskId passed to generateProgressDialog does not match \"\n + \"any valid possibilities in CommCareSetupActivity\");\n return null;\n }\n String title = Localization.get(\"updates.resources.initialization\");\n String message = Localization.get(\"updates.resources.profile\");\n CustomProgressDialog dialog = CustomProgressDialog.newInstance(title, message, taskId);\n dialog.setCancelable(false);\n String checkboxText = Localization.get(\"install.keep.trying\");\n CustomProgressDialog lastDialog = getCurrentDialog();\n boolean isChecked = (lastDialog != null) && lastDialog.isChecked();\n dialog.addCheckbox(checkboxText, isChecked);\n dialog.addProgressBar();\n return dialog;\n }\n //region StartStopInstallCommands implementation\n @Override\n public void onStartInstallClicked() {\n if (!offlineInstall && isNetworkNotConnected()) {\n failWithNotification(AppInstallStatus.NoConnection);\n } else {\n startResourceInstall();\n }\n }\n @Override\n public void onStopInstallClicked() {\n incomingRef = null;\n uiState = UiState.CHOOSE_INSTALL_ENTRY_METHOD;\n uiStateScreenTransition();\n }\n public void setUiState(UiState newState) {\n uiState = newState;\n }\n @Override\n public void downloadLinkReceived(String url) {\n if (url != null) {\n incomingRef = url;\n uiState = UiState.READY_TO_INSTALL;\n uiStateScreenTransition();\n Toast.makeText(this, Localization.get(\"menu.sms.ready\"), Toast.LENGTH_LONG).show();\n }\n }\n @Override\n public void downloadLinkReceivedAutoInstall(String url) {\n if(url != null){\n incomingRef = url;\n uiState = UiState.READY_TO_INSTALL;\n uiStateScreenTransition();\n startResourceInstall();\n } else{\n // only notify if this was manually triggered, since most people won't use this\n Toast.makeText(this, Localization.get(\"menu.sms.not.found\"), Toast.LENGTH_LONG).show();\n }\n }\n @Override\n public void exceptionReceived(Exception e) {\n if(e instanceof SignatureException){\n e.printStackTrace();\n Toast.makeText(this, Localization.get(\"menu.sms.not.verified\"), Toast.LENGTH_LONG).show();\n } else if(e instanceof IOException){\n e.printStackTrace();\n Toast.makeText(this, Localization.get(\"menu.sms.not.retrieved\"), Toast.LENGTH_LONG).show();\n } else{\n e.printStackTrace();\n Toast.makeText(this, Localization.get(\"notification.install.unknown.title\"), Toast.LENGTH_LONG).show();\n }\n }\n}"}}},{"rowIdx":346262,"cells":{"answer":{"kind":"string","value":"package com.peterjosling.scroball;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.JUnit4;\nimport static com.google.common.truth.Truth.assertThat;\n@RunWith(JUnit4.class)\npublic class PlaybackItemTest {\n Track track = ImmutableTrack.builder()\n .track(\"Track\")\n .artist(\"Artist\")\n .build();\n @Test\n public void updateAmountPlayed_hasNoEffectWhenNotPlaying() {\n long timestamp = System.currentTimeMillis() - 10 * 1000;\n PlaybackItem playbackItem1 = new PlaybackItem(track, timestamp);\n PlaybackItem playbackItem2 = new PlaybackItem(track, timestamp);\n assertThat(playbackItem1.getAmountPlayed()).isEqualTo(0);\n assertThat(playbackItem2.getAmountPlayed()).isEqualTo(0);\n playbackItem1.updateAmountPlayed();\n playbackItem2.updateAmountPlayed();\n assertThat(playbackItem1.getAmountPlayed()).isEqualTo(0);\n assertThat(playbackItem2.getAmountPlayed()).isEqualTo(0);\n }\n @Test\n public void updateAmountPlayed_updatesWhenPlaying() {\n long delay = 10 * 1000;\n long alreadyPlayed = 2000;\n long startTime = System.currentTimeMillis() - delay;\n PlaybackItem playbackItem1 = new PlaybackItem(track, startTime);\n playbackItem1.startPlaying();\n PlaybackItem playbackItem2 = new PlaybackItem(track, startTime, alreadyPlayed);\n assertThat(playbackItem1.getAmountPlayed()).isEqualTo(0);\n assertThat(playbackItem2.getAmountPlayed()).isEqualTo(alreadyPlayed);\n playbackItem1.stopPlaying();\n playbackItem2.updateAmountPlayed();\n// assertThat(playbackItem1.getAmountPlayed() / 1000).isEqualTo(delay / 1000);\n// assertThat(playbackItem2.getAmountPlayed() / 1000).isEqualTo((delay + alreadyPlayed) / 1000);\n // TODO use fake clock to fix this test.\n }\n @Test\n public void updateAmountPlayed_updatesStartTimeToAvoidCountingTwice() {\n // TODO\n }\n}"}}},{"rowIdx":346263,"cells":{"answer":{"kind":"string","value":"package musikerverwaltung;\nimport java.awt.*;\nimport javax.swing.*;\nimport javax.swing.SwingUtilities;\nimport java.awt.Font;\npublic class MusicLounge02 extends JFrame {\n // VersionsNr. festlegen\n private static final long serialVersionUID = 02L;\n // Felder:\n // Schriften:\n private Font fheader;\n // Farben\n private Color bgheader, bginfo, bgmain, bgnew, bgfooter;\n // Contentpane\n private Container copa;\n // JPanel\n private JPanel jpall, jpheader, jpmain, jpinfo, jpnew, jpfooter;\n // JLabels\n private JLabel jlheader, jlsearch;\n // JTextField\n private JTextField jtfsearch;\n // Konstruktor\n private MusicLounge02() {\n // Titel (Aufruf mit super aus der Basisklasse)\n super(\"MusicLounge\");\n // Sauberes Schlieen ermoeglichen\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n // Schriften erzeugen\n fheader = new Font(Font.DIALOG, Font.BOLD + Font.ITALIC, 25);\n // Farben erzeugen\n bgheader = new Color(176, 176, 176);\n bginfo = new Color(122, 139, 139);\n bgmain = new Color(217, 217, 217);\n bgnew = new Color(122, 139, 139);\n bgfooter = new Color(176, 176, 176);\n // Gibt ContentPane Objekt zurueck\n copa = getContentPane();\n // JPanel erzeugen mit BorderLayout\n jpall = new JPanel(new BorderLayout());\n jpheader = new JPanel();\n jpmain = new JPanel();\n jpinfo = new JPanel();\n jpnew = new JPanel();\n jpfooter = new JPanel();\n // Farben hinzufuegen\n jpheader.setBackground(bgheader);\n jpinfo.setBackground(bginfo);\n jpmain.setBackground(bgmain);\n jpnew.setBackground(bgnew);\n jpfooter.setBackground(bgfooter);\n // JPanels der >jpall< hinzufuegen\n jpall.add(jpheader, BorderLayout.NORTH);\n jpall.add(jpmain, BorderLayout.CENTER);\n jpall.add(jpinfo, BorderLayout.EAST);\n jpall.add(jpnew, BorderLayout.WEST);\n jpall.add(jpfooter, BorderLayout.SOUTH);\n // JLabel erzeugen\n jlheader = new JLabel(\"MusicLounge\");\n jlsearch = new JLabel(\"Suche\");\n // Schriftart hinzufuegen\n jlheader.setFont(fheader);\n // JLabel der >jpheader< hinzufuegen\n jpheader.add(jlheader);\n jpheader.add(jlsearch);\n // JPanel der ContentPane hinzufuegen\n copa.add(jpall);\n // Automatische Groesse setzen\n pack();\n // Frame sichtbar machen\n setVisible(true);\n }\n public static void main(String[] args) {\n // TODO Auto-generated method stub\n // Konfliktfreies spaeteres paralleles Betreiben des Dialoges\n // sicherstellen\n SwingUtilities.invokeLater(new Runnable() {\n public void run() {\n new MusicLounge02();\n }\n });\n }\n}"}}},{"rowIdx":346264,"cells":{"answer":{"kind":"string","value":"package necromunda;\nimport java.nio.FloatBuffer;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Observable;\nimport java.util.Observer;\nimport java.util.Set;\nimport necromunda.Fighter.State;\nimport necromunda.MaterialFactory.MaterialIdentifier;\nimport necromunda.Necromunda.Phase;\nimport necromunda.Necromunda.SelectionMode;\nimport weapons.Ammunition;\nimport weapons.RangeCombatWeapon;\nimport weapons.Weapon;\nimport weapons.WebPistol;\nimport weapons.RangeCombatWeapon.WeaponType;\nimport com.jme3.app.SimpleApplication;\nimport com.jme3.app.state.ScreenshotAppState;\nimport com.jme3.asset.TextureKey;\nimport com.jme3.asset.plugins.ClasspathLocator;\nimport com.jme3.bounding.BoundingBox;\nimport com.jme3.bounding.BoundingSphere;\nimport com.jme3.bounding.BoundingVolume;\nimport com.jme3.bullet.BulletAppState;\nimport com.jme3.bullet.PhysicsSpace;\nimport com.jme3.bullet.PhysicsTickListener;\nimport com.jme3.bullet.collision.PhysicsCollisionEvent;\nimport com.jme3.bullet.collision.PhysicsCollisionListener;\nimport com.jme3.bullet.collision.shapes.BoxCollisionShape;\nimport com.jme3.bullet.collision.shapes.CollisionShape;\nimport com.jme3.bullet.collision.shapes.CylinderCollisionShape;\nimport com.jme3.bullet.control.GhostControl;\nimport com.jme3.bullet.control.RigidBodyControl;\nimport com.jme3.bullet.util.CollisionShapeFactory;\nimport com.jme3.collision.Collidable;\nimport com.jme3.collision.CollisionResult;\nimport com.jme3.collision.CollisionResults;\nimport com.jme3.font.BitmapText;\nimport com.jme3.input.KeyInput;\nimport com.jme3.input.MouseInput;\nimport com.jme3.input.controls.ActionListener;\nimport com.jme3.input.controls.AnalogListener;\nimport com.jme3.input.controls.KeyTrigger;\nimport com.jme3.input.controls.MouseAxisTrigger;\nimport com.jme3.input.controls.MouseButtonTrigger;\nimport com.jme3.light.AmbientLight;\nimport com.jme3.light.DirectionalLight;\nimport com.jme3.material.Material;\nimport com.jme3.material.RenderState.BlendMode;\nimport com.jme3.material.plugins.NeoTextureMaterialKey;\nimport com.jme3.math.ColorRGBA;\nimport com.jme3.math.FastMath;\nimport com.jme3.math.Quaternion;\nimport com.jme3.math.Ray;\nimport com.jme3.math.Rectangle;\nimport com.jme3.math.Vector3f;\nimport com.jme3.post.FilterPostProcessor;\nimport com.jme3.post.filters.BloomFilter;\nimport com.jme3.renderer.queue.RenderQueue.Bucket;\nimport com.jme3.renderer.queue.RenderQueue.ShadowMode;\nimport com.jme3.scene.Geometry;\nimport com.jme3.scene.Node;\nimport com.jme3.scene.Spatial;\nimport com.jme3.scene.VertexBuffer;\nimport com.jme3.scene.control.BillboardControl;\nimport com.jme3.scene.shape.Box;\nimport com.jme3.scene.shape.Cylinder;\nimport com.jme3.scene.shape.Quad;\nimport com.jme3.scene.shape.Sphere;\nimport com.jme3.system.AppSettings;\nimport com.jme3.texture.Image;\nimport com.jme3.texture.Texture;\nimport com.jme3.util.SkyFactory;\npublic class Necromunda3dProvider extends SimpleApplication implements Observer {\n public static final float MAX_COLLISION_NORMAL_ANGLE = 0.05f;\n public static final float MAX_SLOPE = 0.05f;\n public static final float NOT_TOUCH_DISTANCE = 0.01f;\n public static final float MAX_LADDER_DISTANCE = 0.5f;\n public static final boolean ENABLE_PHYSICS_DEBUG = false;\n public static final Vector3f GROUND_BUFFER = new Vector3f(0, NOT_TOUCH_DISTANCE, 0);\n private Necromunda game;\n private boolean invertMouse;\n private FighterNode selectedFighterNode;\n private List validTargetFighterNodes;\n private List fighterNodes;\n private Node buildingsNode;\n private Node selectedBuildingNode;\n private RigidBodyControl buildingsControl;\n private Line currentPath;\n private ClimbPath currentClimbPath;\n private Node currentPathBoxNode;\n private Line currentLineOfSight;\n private Node currentLineOfSightBoxNode;\n private TemplateNode currentTemplateNode;\n private List templateNodes;\n private List templateRemovers;\n private boolean physicsTickLock1;\n private boolean physicsTickLock2;\n private List targetedFighterNodes;\n private List validSustainedFireTargetFighterNodes;\n private boolean rightButtonDown;\n private LinkedList buildingNodes;\n private Ladder currentLadder;\n private List currentLadders;\n private BitmapText statusMessage;\n private MaterialFactory materialFactory;\n private String terrainType;\n public Necromunda3dProvider(Necromunda game) {\n this.game = game;\n fighterNodes = new ArrayList();\n buildingsNode = new Node(\"buildingsNode\");\n buildingNodes = new LinkedList();\n templateNodes = new ArrayList();\n templateRemovers = new ArrayList();\n targetedFighterNodes = new ArrayList();\n validSustainedFireTargetFighterNodes = new ArrayList();\n validTargetFighterNodes = new ArrayList();\n AppSettings settings = new AppSettings(false);\n settings.setTitle(\"Necromunda\");\n settings.setSettingsDialogImage(\"/Textures/Splashscreen01.png\");\n setSettings(settings);\n }\n @Override\n public void simpleInitApp() {\n BulletAppState bulletAppState = new BulletAppState();\n stateManager.attach(bulletAppState);\n ScreenshotAppState screenshotAppState = new ScreenshotAppState();\n stateManager.attach(screenshotAppState);\n assetManager.registerLocator(\"\", ClasspathLocator.class.getName());\n assetManager.registerLoader(\"com.jme3.material.plugins.NeoTextureMaterialLoader\", \"tgr\");\n materialFactory = new MaterialFactory(assetManager, this);\n Node tableNode = createTableNode();\n rootNode.attachChild(tableNode);\n createBuildings();\n PhysicsSpace physicsSpace = getPhysicsSpace();\n physicsSpace.addCollisionListener(new PhysicsCollisionListenerImpl());\n physicsSpace.addTickListener(new PhysicsTickListenerImpl());\n Node objectsNode = new Node(\"objectsNode\");\n rootNode.attachChild(objectsNode);\n rootNode.attachChild(buildingsNode);\n cam.setLocation(new Vector3f(0, 20, 50));\n getFlyByCamera().setMoveSpeed(20f);\n guiNode.detachAllChildren();\n if (invertMouse) {\n invertMouse();\n }\n DirectionalLight sun = new DirectionalLight();\n sun.setDirection(new Vector3f(-0.5f, -1.5f, -1).normalize());\n sun.setColor(ColorRGBA.White);\n rootNode.addLight(sun);\n AmbientLight ambientLight = new AmbientLight();\n ambientLight.setColor(new ColorRGBA(0.2f, 0.2f, 0.2f, 1.0f));\n rootNode.addLight(ambientLight);\n initCrossHairs();\n initStatusMessage();\n TextureKey key0 = new TextureKey(\"Textures/sky_top_bottom.PNG\", true);\n key0.setGenerateMips(true);\n key0.setAsCube(true);\n Texture tex0 = assetManager.loadTexture(key0);\n TextureKey key1 = new TextureKey(\"Textures/sky_left.PNG\", true);\n key1.setGenerateMips(true);\n key1.setAsCube(true);\n Texture tex1 = assetManager.loadTexture(key1);\n TextureKey key2 = new TextureKey(\"Textures/sky_right.PNG\", true);\n key2.setGenerateMips(true);\n key2.setAsCube(true);\n Texture tex2 = assetManager.loadTexture(key2);\n TextureKey key3 = new TextureKey(\"Textures/sky_front.PNG\", true);\n key3.setGenerateMips(true);\n key3.setAsCube(true);\n Texture tex3 = assetManager.loadTexture(key3);\n TextureKey key4 = new TextureKey(\"Textures/sky_back.PNG\", true);\n key4.setGenerateMips(true);\n key4.setAsCube(true);\n Texture tex4 = assetManager.loadTexture(key4);\n Geometry sky = (Geometry) SkyFactory.createSky(assetManager, tex1, tex2, tex3, tex4, tex0, tex0);\n // Fix bug which sometimes culls the skybox\n sky.setLocalScale(100);\n rootNode.attachChild(sky);\n MouseListener mouseListener = new MouseListener();\n inputManager.addMapping(\"leftClick\", new MouseButtonTrigger(MouseInput.BUTTON_LEFT));\n inputManager.addMapping(\"rightClick\", new MouseButtonTrigger(MouseInput.BUTTON_RIGHT));\n inputManager.addListener(mouseListener, \"leftClick\");\n inputManager.addListener(mouseListener, \"rightClick\");\n inputManager.addMapping(\"Move_Left\", new MouseAxisTrigger(MouseInput.AXIS_X, true));\n inputManager.addMapping(\"Move_Right\", new MouseAxisTrigger(MouseInput.AXIS_X, false));\n inputManager.addMapping(\"Move_Up\", new MouseAxisTrigger(MouseInput.AXIS_Y, true));\n inputManager.addMapping(\"Move_Down\", new MouseAxisTrigger(MouseInput.AXIS_Y, false));\n inputManager.addListener(mouseListener, \"Move_Left\", \"Move_Right\", \"Move_Up\", \"Move_Down\");\n KeyboardListener keyboardListener = new KeyboardListener();\n inputManager.addMapping(\"Break\", new KeyTrigger(KeyInput.KEY_B));\n inputManager.addListener(keyboardListener, \"Break\");\n inputManager.addMapping(\"Move\", new KeyTrigger(KeyInput.KEY_M));\n inputManager.addListener(keyboardListener, \"Move\");\n inputManager.addMapping(\"Run\", new KeyTrigger(KeyInput.KEY_R));\n inputManager.addListener(keyboardListener, \"Run\");\n inputManager.addMapping(\"Climb\", new KeyTrigger(KeyInput.KEY_C));\n inputManager.addListener(keyboardListener, \"Climb\");\n inputManager.addMapping(\"Cycle\", new KeyTrigger(KeyInput.KEY_Y));\n inputManager.addListener(keyboardListener, \"Cycle\");\n inputManager.addMapping(\"Yes\", new KeyTrigger(KeyInput.KEY_Y));\n inputManager.addListener(keyboardListener, \"Yes\");\n inputManager.addMapping(\"Mode\", new KeyTrigger(KeyInput.KEY_O));\n inputManager.addListener(keyboardListener, \"Mode\");\n inputManager.addMapping(\"Shoot\", new KeyTrigger(KeyInput.KEY_H));\n inputManager.addListener(keyboardListener, \"Shoot\");\n inputManager.addMapping(\"NextPhase\", new KeyTrigger(KeyInput.KEY_N));\n inputManager.addListener(keyboardListener, \"NextPhase\");\n inputManager.addMapping(\"No\", new KeyTrigger(KeyInput.KEY_N));\n inputManager.addListener(keyboardListener, \"No\");\n inputManager.addMapping(\"EndTurn\", new KeyTrigger(KeyInput.KEY_E));\n inputManager.addListener(keyboardListener, \"EndTurn\");\n inputManager.addMapping(\"SkipBuilding\", new KeyTrigger(KeyInput.KEY_K));\n inputManager.addListener(keyboardListener, \"SkipBuilding\");\n if (ENABLE_PHYSICS_DEBUG) {\n physicsSpace.enableDebug(assetManager);\n //createLadderLines();\n }\n }\n private Node createTableNode() {\n Box box = new Box(new Vector3f(24, -0.5f, 24), 24, 0.5f, 24);\n Geometry tableGeometry = new Geometry(\"tableGeometry\", box);\n tableGeometry.setMaterial(materialFactory.createMaterial(MaterialIdentifier.TABLE));\n Node tableNode = new Node(\"tableNode\");\n tableNode.attachChild(tableGeometry);\n return tableNode;\n }\n private void createBuildings() {\n for (Building building : game.getBuildings()) {\n BuildingNode buildingNode = new BuildingNode(\"buildingNode\");\n for (String identifier : building.getIdentifiers()) {\n Material buildingMaterial = materialFactory.createBuildingMaterial(identifier);\n Spatial model = assetManager.loadModel(\"Building\" + identifier + \".mesh.xml\");\n model.setMaterial(buildingMaterial);\n buildingNode.attachChild(model);\n //Create ladders\n Material selectedMaterial = materialFactory.createMaterial(MaterialIdentifier.SELECTED);\n List ladders = Ladder.createLaddersFrom(\"/Building\" + identifier + \".ladder\", selectedMaterial);\n for (Ladder ladder : ladders) {\n buildingNode.setLadders(ladders);\n buildingNode.attachChild(ladder.getLineNode());\n }\n }\n buildingNodes.add(buildingNode);\n }\n }\n private void createLadderLines() {\n for (Ladder ladder : getLaddersFrom(buildingsNode)) {\n com.jme3.scene.shape.Line lineShape = new com.jme3.scene.shape.Line(Vector3f.ZERO, Vector3f.UNIT_Y);\n Geometry lineGeometry = new Geometry(\"line\", lineShape);\n lineGeometry.setMaterial(materialFactory.createMaterial(MaterialFactory.MaterialIdentifier.SELECTED));\n ladder.getLineNode().attachChild(lineGeometry);\n }\n }\n private List getLaddersFrom(Node buildingsNode) {\n List ladders = new ArrayList();\n List buildingNodes = buildingsNode.getChildren();\n for (Spatial buildingNode : buildingNodes) {\n ladders.addAll(((BuildingNode)buildingNode).getLadders());\n }\n return ladders;\n }\n private void invertMouse() {\n inputManager.deleteMapping(\"FLYCAM_Up\");\n inputManager.deleteMapping(\"FLYCAM_Down\");\n inputManager.addMapping(\"FLYCAM_Up\", new MouseAxisTrigger(MouseInput.AXIS_Y, true), new KeyTrigger(KeyInput.KEY_DOWN));\n inputManager.addMapping(\"FLYCAM_Down\", new MouseAxisTrigger(MouseInput.AXIS_Y, false), new KeyTrigger(KeyInput.KEY_UP));\n inputManager.addListener(getFlyByCamera(), \"FLYCAM_Up\", \"FLYCAM_Down\");\n }\n @Override\n public void update(Observable o, Object arg) {\n updateModels();\n statusMessage.setText(getStatusTextFrom(game));\n }\n private void updateModels() {\n Iterator it = fighterNodes.iterator();\n selectedFighterNode = null;\n while (it.hasNext()) {\n FighterNode fighterNode = it.next();\n Fighter fighter = fighterNode.getFighter();\n if (fighter.isOutOfAction()) {\n it.remove();\n getObjectsNode().detachChild(fighterNode);\n GhostControl control = fighterNode.getGhostControl();\n getPhysicsSpace().remove(control);\n }\n if (fighter == game.getSelectedFighter()) {\n selectedFighterNode = fighterNode;\n setBaseSelected(fighterNode);\n }\n else if (targetedFighterNodes.contains(fighterNode)) {\n setBaseTargeted(fighterNode);\n }\n else {\n setBaseNormal(fighterNode);\n }\n Node figureNode = (Node) fighterNode.getChild(\"figureNode\");\n figureNode.detachChildNamed(\"symbol\");\n if (fighter.isPinned()) {\n fighterNode.attachSymbol(materialFactory.createMaterial(MaterialIdentifier.SYMBOL_PINNED));\n }\n else if (fighter.isDown()) {\n fighterNode.attachSymbol(materialFactory.createMaterial(MaterialIdentifier.SYMBOL_DOWN));\n }\n else if (fighter.isSedated()) {\n fighterNode.attachSymbol(materialFactory.createMaterial(MaterialIdentifier.SYMBOL_SEDATED));\n }\n else if (fighter.isComatose()) {\n fighterNode.attachSymbol(materialFactory.createMaterial(MaterialIdentifier.SYMBOL_COMATOSE));\n }\n List laddersInReach = getLaddersInReach(fighterNode.getLocalTranslation(), fighter.getBaseRadius());\n if (!laddersInReach.isEmpty()) {\n fighterNode.attachSymbol(materialFactory.createMaterial(MaterialIdentifier.SYMBOL_LADDER));\n }\n }\n if (currentTemplateNode != null) {\n colouriseBasesUnderTemplate(currentTemplateNode);\n }\n for (TemplateNode templateNode : templateNodes) {\n colouriseBasesUnderTemplate(templateNode);\n }\n }\n private Node getObjectsNode() {\n return (Node) rootNode.getChild(\"objectsNode\");\n }\n private Node getBuildingsNode() {\n return (Node) rootNode.getChild(\"buildingsNode\");\n }\n private Node getTableNode() {\n return (Node) rootNode.getChild(\"tableNode\");\n }\n public void setInvertMouse(boolean invertMouse) {\n this.invertMouse = invertMouse;\n }\n private void colouriseBasesUnderTemplate(TemplateNode templateNode) {\n List fighterNodesUnderTemplate = getFighterNodesUnderTemplate(templateNode, fighterNodes);\n for (FighterNode fighterNodeUnderTemplate : fighterNodesUnderTemplate) {\n setBaseTargeted(fighterNodeUnderTemplate);\n }\n }\n private void executeKeyboardAction(String name) {\n Necromunda.setStatusMessage(\"\");\n Fighter selectedFighter = game.getSelectedFighter();\n if (name.equals(\"NextPhase\")) {\n tearDownCurrentPath();\n game.setSelectionMode(SelectionMode.SELECT);\n game.nextPhase();\n }\n else if (name.equals(\"EndTurn\")) {\n tearDownCurrentPath();\n game.setSelectionMode(SelectionMode.SELECT);\n game.endTurn();\n turnStarted();\n }\n else if (name.equals(\"SkipBuilding\") && game.getSelectionMode().equals(SelectionMode.DEPLOY_BUILDING)) {\n skipBuilding();\n }\n else if (selectedFighter == null) {\n Necromunda.setStatusMessage(\"You must select a fighter first.\");\n }\n else {\n if (game.getSelectionMode().equals(SelectionMode.SELECT) && game.getCurrentGang().getGangMembers().contains(selectedFighterNode.getFighter())) {\n if (name.equals(\"Break\") && game.getPhase().equals(Phase.MOVEMENT)) {\n if (selectedFighter.isPinned()) {\n Necromunda.setStatusMessage(\"This ganger can not break the web.\");\n }\n else {\n if (selectedFighter.isWebbed()) {\n int webRoll = Utils.rollD6();\n if ((webRoll + selectedFighter.getStrength()) >= 9) {\n selectedFighter.setWebbed(false);\n Necromunda.appendToStatusMessage(\"This ganger has broken the web.\");\n }\n else {\n WebPistol.dealWebDamageTo(selectedFighter);\n }\n }\n else {\n Necromunda.setStatusMessage(\"This ganger is not webbed.\");\n }\n }\n }\n else if (name.equals(\"Move\") && game.getPhase().equals(Phase.MOVEMENT)) {\n if (selectedFighter.canMove() && !selectedFighter.hasRun()) {\n if (!selectedFighter.hasMoved()) {\n selectedFighter.setIsGoingToRun(false);\n }\n game.setSelectionMode(SelectionMode.MOVE);\n setUpMovement();\n }\n else {\n Necromunda.setStatusMessage(\"This ganger cannot move.\");\n }\n }\n else if (name.equals(\"Run\") && game.getPhase().equals(Phase.MOVEMENT)) {\n if (selectedFighter.canRun() && !selectedFighter.hasMoved()) {\n if (!selectedFighter.hasRun()) {\n selectedFighter.setIsGoingToRun(true);\n }\n game.setSelectionMode(SelectionMode.MOVE);\n setUpMovement();\n }\n else {\n Necromunda.setStatusMessage(\"This ganger cannot run.\");\n }\n }\n else if (name.equals(\"Shoot\") && game.getPhase().equals(Phase.SHOOTING)) {\n if (selectedFighter.canShoot()) {\n if (!selectedFighter.getWeapons().isEmpty()) {\n RangeCombatWeapon weapon = selectedFighter.getSelectedRangeCombatWeapon();\n if (weapon == null) {\n weapon = (RangeCombatWeapon) selectedFighter.getWeapons().get(0);\n selectedFighter.setSelectedRangeCombatWeapon(weapon);\n }\n if (weapon.isBroken()) {\n Necromunda.setStatusMessage(\"The selected weapon is broken.\");\n }\n else if (!weapon.isEnabled()) {\n Necromunda.setStatusMessage(\"The selected weapon is disabled.\");\n }\n else if (weapon.isMoveOrFire() && selectedFighter.hasMoved()) {\n Necromunda.setStatusMessage(\"The selected weapon cannot be fired after moving.\");\n }\n else {\n weapon.resetNumberOfShots();\n game.setSelectionMode(SelectionMode.TARGET);\n updateValidTargetFighterNodes();\n setUpTargeting();\n }\n }\n else {\n Necromunda.setStatusMessage(\"This ganger has no weapons.\");\n }\n }\n else {\n Necromunda.setStatusMessage(\"This ganger cannot shoot.\");\n }\n }\n else if (name.equals(\"Cycle\")) {\n List weapons = selectedFighter.getWeapons();\n if (!weapons.isEmpty()) {\n RangeCombatWeapon weapon = selectedFighter.getSelectedRangeCombatWeapon();\n if (weapon == null) {\n weapon = (RangeCombatWeapon) selectedFighter.getWeapons().get(0);\n }\n else {\n int index = weapons.indexOf(weapon);\n if (index < weapons.size() - 1) {\n weapon = (RangeCombatWeapon) weapons.get(index + 1);\n }\n else {\n weapon = (RangeCombatWeapon) selectedFighter.getWeapons().get(0);\n }\n }\n selectedFighter.setSelectedRangeCombatWeapon(weapon);\n }\n else {\n Necromunda.setStatusMessage(\"This ganger has no weapons.\");\n }\n }\n else if (name.equals(\"Mode\")) {\n RangeCombatWeapon weapon = selectedFighter.getSelectedRangeCombatWeapon();\n if (weapon != null) {\n List ammunitions = weapon.getAmmunitions();\n int index = ammunitions.indexOf(weapon.getCurrentAmmunition());\n if (index == -1) {\n weapon.setCurrentAmmunition(ammunitions.get(0));\n }\n else {\n if (index < ammunitions.size() - 1) {\n weapon.setCurrentAmmunition(ammunitions.get(index + 1));\n }\n else {\n weapon.setCurrentAmmunition(ammunitions.get(0));\n }\n }\n }\n else {\n Necromunda.setStatusMessage(\"No weapon selected.\");\n }\n }\n }\n else if (name.equals(\"Climb\")) {\n if (game.getSelectionMode().equals(SelectionMode.MOVE)) {\n currentLadders = getLaddersInReach(currentPath.getOrigin(), selectedFighter.getBaseRadius());\n if (currentLadders.isEmpty()) {\n Necromunda.setStatusMessage(\"There is no ladder in reach.\");\n }\n else {\n currentLadder = currentLadders.get(0);\n game.setSelectionMode(SelectionMode.CLIMB);\n climbLadder(currentLadder);\n }\n }\n else if (game.getSelectionMode().equals(SelectionMode.CLIMB)) {\n int ladderIndex = currentLadders.indexOf(currentLadder);\n if (ladderIndex < currentLadders.size() - 1) {\n ladderIndex += 1;\n }\n else {\n ladderIndex = 0;\n }\n currentLadder = currentLadders.get(ladderIndex);\n climbLadder(currentLadder);\n }\n }\n }\n }\n private void climbLadder(Ladder ladder) {\n Vector3f currentPathOrigin;\n if (currentPath != null) {\n currentPathOrigin = currentPath.getOrigin();\n tearDownCurrentPath();\n }\n else {\n currentPathOrigin = currentClimbPath.getStart().clone();\n }\n currentClimbPath = new ClimbPath(currentPathOrigin.clone());\n Vector3f nearestLadderCollisionPoint = getLadderCollisionPoint(ladder);\n currentClimbPath.addToLength(nearestLadderCollisionPoint.distance(currentPathOrigin));\n selectedFighterNode.setLocalTranslation(getLadderCollisionPoint(ladder.getPeer()));\n currentClimbPath.addToLength(nearestLadderCollisionPoint.distance(selectedFighterNode.getLocalTranslation()));\n }\n private void executeMouseAction(String name, boolean isPressed) {\n if (name.equals(\"leftClick\")) {\n onLeftClick(isPressed);\n }\n else if (name.equals(\"rightClick\")) {\n onRightClick(isPressed);\n }\n }\n private void onLeftClick(boolean isPressed) {\n if (isPressed) {\n Necromunda.setStatusMessage(\"\");\n if (game.getSelectionMode().equals(SelectionMode.SELECT)) {\n select();\n }\n else if (game.getSelectionMode().equals(SelectionMode.MOVE)) {\n move();\n }\n else if (game.getSelectionMode().equals(SelectionMode.CLIMB)) {\n climb();\n }\n else if (game.getSelectionMode().equals(SelectionMode.TARGET)) {\n target();\n }\n else if (game.getSelectionMode().equals(SelectionMode.DEPLOY_BUILDING)) {\n deployBuilding();\n }\n else if (game.getSelectionMode().equals(SelectionMode.DEPLOY_MODEL)) {\n deployModel();\n }\n }\n }\n private void deployBuilding() {\n Vector3f nearestIntersection = getTableCollisionPoint();\n if (nearestIntersection == null) {\n return;\n }\n selectedBuildingNode = selectedBuildingNode.clone(false);\n selectedBuildingNode.setLocalTranslation(nearestIntersection);\n buildingsNode.attachChild(selectedBuildingNode);\n }\n private void skipBuilding() {\n buildingsNode.detachChild(selectedBuildingNode);\n selectedBuildingNode = buildingNodes.poll();\n Vector3f nearestIntersection = getTableCollisionPoint();\n if (nearestIntersection == null) {\n return;\n }\n if (selectedBuildingNode == null) {\n CollisionShape sceneShape = CollisionShapeFactory.createMeshShape(buildingsNode);\n buildingsControl = new RigidBodyControl(sceneShape, 0);\n buildingsControl.setKinematic(false);\n buildingsNode.addControl(buildingsControl);\n getPhysicsSpace().add(buildingsNode);\n game.setSelectionMode(SelectionMode.DEPLOY_MODEL);\n updateModelPosition();\n }\n else {\n selectedBuildingNode.setLocalTranslation(nearestIntersection);\n buildingsNode.attachChild(selectedBuildingNode);\n }\n }\n private void updateModelPosition() {\n Vector3f nearestIntersection = getSceneryCollisionPoint();\n if (nearestIntersection == null) {\n return;\n }\n if (selectedFighterNode == null) {\n selectedFighterNode = new FighterNode(\"fighterNode\", game.getSelectedFighter(), materialFactory);\n getPhysicsSpace().add(selectedFighterNode.getGhostControl());\n getObjectsNode().attachChild(selectedFighterNode);\n fighterNodes.add(selectedFighterNode);\n game.updateStatus();\n }\n selectedFighterNode.setLocalTranslation(nearestIntersection);\n lockPhysics();\n }\n private void deployModel() {\n Vector3f contactPoint = getSceneryCollisionPoint();\n List fighterNodesWithinDistance = getFighterNodesWithinDistance(selectedFighterNode, NOT_TOUCH_DISTANCE);\n if ((contactPoint != null) && (selectedFighterNode != null) && hasValidPosition(selectedFighterNode) && fighterNodesWithinDistance.isEmpty()) {\n game.fighterDeployed();\n }\n /*List pointCloud = selectedFighterNode.getCollisionShapePointCloud();\n Material material = materialFactory.createMaterial(MaterialIdentifier.SELECTED);\n for (Vector3f vector : pointCloud) {\n Quad quad = new Quad(0.01f, 0.01f);\n Geometry geometry = new Geometry(\"cloudpoint\", quad);\n geometry.setMaterial(material);\n geometry.setLocalTranslation(vector);\n rootNode.attachChild(geometry);\n }*/\n }\n private void select() {\n if (selectedFighterNode != null) {\n deselectFighter();\n }\n FighterNode fighterNodeUnderCursor = getFighterNodeUnderCursor();\n if (fighterNodeUnderCursor != null) {\n selectFighter(fighterNodeUnderCursor);\n }\n }\n private void move() {\n if (hasValidPosition(selectedFighterNode) && currentPath.isValid()\n && (getFighterNodesWithinDistance(selectedFighterNode, NOT_TOUCH_DISTANCE).isEmpty())) {\n List fighterNodesWithinDistance = getFighterNodesWithinDistance(selectedFighterNode, Necromunda.RUN_SPOT_DISTANCE);\n List hostileFighterNodesWithinDistance = getHostileFighterNodesFrom(fighterNodesWithinDistance);\n List hostileFighterNodesWithinDistanceAndWithLineOfSight = getFighterNodesWithLineOfSightFrom(selectedFighterNode,\n hostileFighterNodesWithinDistance);\n if (selectedFighterNode.getFighter().isGoingToRun() && (!hostileFighterNodesWithinDistanceAndWithLineOfSight.isEmpty())) {\n Necromunda.setStatusMessage(\"You cannot run so close to an enemy fighter.\");\n }\n else {\n commitMovement();\n }\n }\n }\n private void climb() {\n if (hasValidPosition(selectedFighterNode) && (getFighterNodesWithinDistance(selectedFighterNode, NOT_TOUCH_DISTANCE).isEmpty())) {\n if (currentClimbPath.getLength() <= game.getSelectedFighter().getRemainingMovementDistance()) {\n commitClimb();\n }\n else {\n Necromunda.setStatusMessage(\"This ganger cannot climb that far.\");\n }\n }\n }\n private void target() {\n Fighter selectedFighter = game.getSelectedFighter();\n RangeCombatWeapon weapon = selectedFighter.getSelectedRangeCombatWeapon();\n if (!weapon.isTargeted()) {\n weapon.trigger();\n fireTemplate(currentTemplateNode);\n removeTargetingFacilities();\n game.setSelectionMode(SelectionMode.SELECT);\n }\n else {\n FighterNode fighterNodeUnderCursor = getFighterNodeUnderCursor();\n if (fighterNodeUnderCursor == null) {\n return;\n }\n if (!getHostileFighterNodesFrom(fighterNodes).contains(fighterNodeUnderCursor)) {\n Necromunda.setStatusMessage(\"This fighter is not hostile.\");\n return;\n }\n List collidables = getBoundingVolumes();\n if (currentTemplateNode != null) {\n collidables.removeAll(currentTemplateNode.getBoundingSpheres());\n }\n collidables.add(getBuildingsNode());\n /*List otherFighterNodes = new ArrayList(fighterNodes);\n otherFighterNodes.remove(selectedFighterNode);\n otherFighterNodes.remove(fighterNodeUnderCursor);\n collidables.addAll(otherFighterNodes);*/\n VisibilityInfo visibilityInfo = getVisibilityInfo(selectedFighterNode, fighterNodeUnderCursor, collidables);\n if (/*!currentLineOfSight.isValid() ||*/ (visibilityInfo.getNumberOfVisiblePoints() == 0) || isPhysicsLocked()) {\n Necromunda.setStatusMessage(\"Object out of sight.\");\n return;\n }\n if (validSustainedFireTargetFighterNodes.isEmpty() && (!validTargetFighterNodes.contains(fighterNodeUnderCursor))) {\n Necromunda.setStatusMessage(\"This fighter is not the nearest target.\");\n return;\n }\n boolean targetAdded = addTarget(fighterNodeUnderCursor);\n if (targetAdded) {\n weapon.targetAdded();\n }\n if (weapon.getNumberOfShots() > 0) {\n return;\n }\n float visiblePercentage = visibilityInfo.getVisiblePercentage();\n Necromunda.appendToStatusMessage(\"Visible percentage: \" + (visiblePercentage * 100));\n int hitModifier = 0;\n if ((visiblePercentage < 1.0) && (visiblePercentage >= 0.5)) {\n hitModifier = -1;\n }\n else if (visiblePercentage < 0.5) {\n hitModifier = -2;\n }\n fireTargetedWeapon(weapon, hitModifier);\n removeTargetingFacilities();\n targetedFighterNodes.clear();\n validSustainedFireTargetFighterNodes.clear();\n }\n game.setSelectionMode(SelectionMode.SELECT);\n }\n private void onRightClick(boolean isPressed) {\n if (isPressed) {\n rightButtonDown = true;\n if (game.getSelectionMode().equals(SelectionMode.MOVE)) {\n tearDownCurrentPath();\n game.setSelectionMode(SelectionMode.SELECT);\n deselectFighter();\n }\n else if (game.getSelectionMode().equals(SelectionMode.CLIMB)) {\n abortClimbing();\n game.setSelectionMode(SelectionMode.SELECT);\n deselectFighter();\n }\n else if (game.getSelectionMode().equals(SelectionMode.TARGET)) {\n removeTargetingFacilities();\n game.setSelectionMode(SelectionMode.SELECT);\n deselectFighter();\n }\n }\n else {\n rightButtonDown = false;\n }\n }\n private FighterNode getFighterNodeUnderCursor() {\n List collidables = new ArrayList();\n collidables.add(getObjectsNode());\n CollisionResult closestCollision = Utils.getNearestCollisionFrom(cam.getLocation(), cam.getDirection(), collidables);\n FighterNode fighterNodeUnderCursor = null;\n if (closestCollision != null) {\n Geometry geometry = closestCollision.getGeometry();\n fighterNodeUnderCursor = (FighterNode) getParent(geometry, \"fighterNode\");\n }\n return fighterNodeUnderCursor;\n }\n private void updateValidTargetFighterNodes() {\n validTargetFighterNodes.clear();\n List visibleHostileFighterNodes = getFighterNodesWithLineOfSightFrom(selectedFighterNode, getHostileFighterNodesFrom(fighterNodes));\n boolean normalFighterNodeFound = false;\n while ((!normalFighterNodeFound) && (!visibleHostileFighterNodes.isEmpty())) {\n FighterNode fighterNode = getNearestFighterNodeFrom(selectedFighterNode, visibleHostileFighterNodes);\n Fighter fighter = fighterNode.getFighter();\n if (fighter.isNormal() || fighter.isPinned()) {\n normalFighterNodeFound = true;\n }\n validTargetFighterNodes.add(fighterNode);\n visibleHostileFighterNodes.remove(fighterNode);\n }\n }\n private boolean addTarget(FighterNode fighterNode) {\n if (validSustainedFireTargetFighterNodes.isEmpty()) {\n addFirstTarget(fighterNode);\n return true;\n }\n else {\n return addSubsequentTarget(fighterNode);\n }\n }\n private void addFirstTarget(FighterNode fighterNode) {\n targetedFighterNodes.add(fighterNode);\n List sustainedFireNeighbours = getFighterNodesWithinDistance(getFighterNodeUnderCursor(), Necromunda.SUSTAINED_FIRE_RADIUS);\n validSustainedFireTargetFighterNodes.add(fighterNode);\n validSustainedFireTargetFighterNodes.addAll(sustainedFireNeighbours);\n }\n private boolean addSubsequentTarget(FighterNode fighterNode) {\n if (validSustainedFireTargetFighterNodes.contains(fighterNode)) {\n targetedFighterNodes.add(fighterNode);\n return true;\n }\n else {\n Necromunda.setStatusMessage(\"This target is too far away from the first.\");\n return false;\n }\n }\n private void tearDownCurrentPath() {\n if (currentPath != null) {\n selectedFighterNode.setLocalTranslation(currentPath.getOrigin());\n }\n if (currentClimbPath != null) {\n selectedFighterNode.setLocalTranslation(currentClimbPath.getStart());\n }\n rootNode.detachChildNamed(\"currentPathBoxNode\");\n if (currentPathBoxNode != null) {\n GhostControl physicsGhostObject = currentPathBoxNode.getControl(GhostControl.class);\n getPhysicsSpace().remove(physicsGhostObject);\n }\n currentPath = null;\n currentPathBoxNode = null;\n }\n private void abortClimbing() {\n if (currentClimbPath != null) {\n selectedFighterNode.setLocalTranslation(currentClimbPath.getStart());\n }\n currentClimbPath = null;\n }\n private void removeTargetingFacilities() {\n rootNode.detachChildNamed(\"currentLineOfSightBoxNode\");\n rootNode.detachChildNamed(\"currentLineOfSightLine\");\n if (currentLineOfSightBoxNode != null) {\n GhostControl physicsGhostObject = currentLineOfSightBoxNode.getControl(GhostControl.class);\n getPhysicsSpace().remove(physicsGhostObject);\n }\n currentLineOfSight = null;\n currentLineOfSightBoxNode = null;\n removeCurrentWeaponTemplate();\n }\n private void removeCurrentWeaponTemplate() {\n rootNode.detachChildNamed(\"currentTemplateNode\");\n currentTemplateNode = null;\n }\n private void commitMovement() {\n Fighter selectedObject = game.getSelectedFighter();\n Vector3f movementVector = currentPath.getVector();\n float distance = movementVector.length();\n float remainingMovementDistance = selectedObject.getRemainingMovementDistance() - distance;\n selectedObject.setRemainingMovementDistance(remainingMovementDistance);\n currentPath.getOrigin().set(selectedFighterNode.getLocalTranslation());\n for (Fighter object : selectedObject.getGang().getGangMembers()) {\n if (object != selectedObject) {\n if (object.hasMoved() || object.hasRun()) {\n object.setRemainingMovementDistance(0);\n }\n }\n }\n if (selectedObject.isGoingToRun()) {\n selectedObject.setHasRun(true);\n }\n else {\n selectedObject.setHasMoved(true);\n }\n if (selectedObject.isSpotted() && selectedObject.hasRun()) {\n selectedObject.setRemainingMovementDistance(0);\n game.setSelectionMode(SelectionMode.SELECT);\n }\n if (selectedObject.getRemainingMovementDistance() < 0.01f) {\n selectedObject.setRemainingMovementDistance(0);\n tearDownCurrentPath();\n game.setSelectionMode(SelectionMode.SELECT);\n }\n }\n private void commitClimb() {\n Fighter selectedObject = game.getSelectedFighter();\n float distance = currentClimbPath.getLength();\n System.out.println(\"Climb Path Length: \" + distance);\n float remainingMovementDistance = selectedObject.getRemainingMovementDistance() - distance;\n selectedObject.setRemainingMovementDistance(remainingMovementDistance);\n currentClimbPath.getStart().set(selectedFighterNode.getLocalTranslation());\n for (Fighter object : selectedObject.getGang().getGangMembers()) {\n if (object != selectedObject) {\n if (object.hasMoved() || object.hasRun()) {\n object.setRemainingMovementDistance(0);\n }\n }\n }\n if (selectedObject.isGoingToRun()) {\n selectedObject.setHasRun(true);\n }\n else {\n selectedObject.setHasMoved(true);\n }\n if (selectedObject.getRemainingMovementDistance() < 0.01f) {\n selectedObject.setRemainingMovementDistance(0);\n }\n abortClimbing();\n deselectFighter();\n game.setSelectionMode(SelectionMode.SELECT);\n }\n private Geometry getPathBoxGeometryFor(FighterNode fighterNode) {\n Vector3f halfExtents = getHalfExtentsOf(fighterNode);\n float pathLength = 0;\n if (currentPath != null) {\n pathLength = currentPath.length();\n }\n Box box = new Box(halfExtents.getX(), halfExtents.getY(), pathLength / 2);\n Geometry boxGeometry = new Geometry(\"currentPathBoxGeometry\", box);\n boxGeometry.setMaterial(materialFactory.createMaterial(MaterialIdentifier.PATH));\n boxGeometry.setQueueBucket(Bucket.Transparent);\n return boxGeometry;\n }\n private CollisionShape getPathBoxCollisionShapeOf(FighterNode fighterNode, Line path) {\n Vector3f halfExtents = getHalfExtentsOf(fighterNode);\n float pathLength = 0;\n if (path != null) {\n pathLength = path.length();\n }\n Vector3f vector = new Vector3f(halfExtents.getX(), halfExtents.getY(), pathLength / 2);\n BoxCollisionShape collisionShape = new BoxCollisionShape(vector);\n return collisionShape;\n }\n private Vector3f getHalfExtentsOf(FighterNode fighterNode) {\n GhostControl control = fighterNode.getGhostControl();\n CylinderCollisionShape shape = (CylinderCollisionShape) control.getCollisionShape();\n Vector3f halfExtents = shape.getHalfExtents();\n return halfExtents;\n }\n private void selectFighter(FighterNode fighterNode) {\n Fighter fighter = fighterNode.getFighter();\n /*\n * if (fighter.getGang() == game.getCurrentGang()) {\n * game.setSelectedFighter(fighter); }\n */\n game.setSelectedFighter(fighter);\n }\n private void deselectFighter() {\n game.setSelectedFighter(null);\n }\n private void setBaseSelected(Node model) {\n Spatial base = model.getChild(\"base\");\n base.setMaterial(materialFactory.createMaterial(MaterialIdentifier.SELECTED));\n }\n private void setBaseTargeted(Node model) {\n Spatial base = model.getChild(\"base\");\n base.setMaterial(materialFactory.createMaterial(MaterialIdentifier.TARGETED));\n }\n private void setBaseNormal(Node model) {\n Spatial base = model.getChild(\"base\");\n base.setMaterial(materialFactory.createMaterial(MaterialIdentifier.NORMAL));\n }\n private boolean hasValidPosition(FighterNode fighterNode) {\n if (!fighterNode.isPositionValid() || isPhysicsLocked()) {\n System.out.println(\"Position invalid...\");\n return false;\n }\n else {\n return true;\n }\n }\n private Node getParent(Spatial spatial, String name) {\n Node parent = spatial.getParent();\n if (parent == null) {\n return null;\n }\n else if (parent.getName().equals(name)) {\n return parent;\n }\n else {\n return getParent(parent, name);\n }\n }\n private void initCrossHairs() {\n guiFont = assetManager.loadFont(\"Interface/Fonts/Default.fnt\");\n BitmapText crosshair = new BitmapText(guiFont, false);\n crosshair.setSize(guiFont.getCharSet().getRenderedSize() * 2);\n // crosshairs\n crosshair.setText(\"+\");\n // center\n crosshair.setLocalTranslation(settings.getWidth() / 2 - guiFont.getCharSet().getRenderedSize() / 3 * 2, settings.getHeight() / 2\n + crosshair.getLineHeight() / 2, 0);\n guiNode.attachChild(crosshair);\n }\n private void initStatusMessage() {\n guiFont = assetManager.loadFont(\"Interface/Fonts/Default.fnt\");\n statusMessage = new BitmapText(guiFont, false);\n statusMessage.setSize(guiFont.getCharSet().getRenderedSize());\n statusMessage.setLocalTranslation(10, 120, 0);\n guiNode.attachChild(statusMessage);\n }\n private VisibilityInfo getVisibilityInfo(FighterNode source, FighterNode target, List collidables) {\n Vector3f sourceUpTranslation = new Vector3f(0, source.getFighter().getBaseRadius() * 1.5f, 0);\n Vector3f sourceLocation = source.getLocalTranslation().add(sourceUpTranslation);\n List pointCloud = target.getCollisionShapePointCloud();\n int numberOfVisiblePoints = 0;\n for (Vector3f vector : pointCloud) {\n Vector3f direction = vector.subtract(sourceLocation);\n CollisionResult closestCollision = Utils.getNearestCollisionFrom(sourceLocation, direction, collidables);\n if (closestCollision != null) {\n float distanceToTarget = direction.length();\n float distanceToCollisionPoint = closestCollision.getContactPoint().subtract(sourceLocation).length();\n if (distanceToCollisionPoint >= distanceToTarget) {\n numberOfVisiblePoints++;\n }\n }\n else {\n numberOfVisiblePoints++;\n }\n }\n VisibilityInfo visibilityInfo = new VisibilityInfo(numberOfVisiblePoints, pointCloud.size());\n return visibilityInfo;\n }\n private List getBoundingVolumes() {\n List boundingVolumes = new ArrayList();\n for (TemplateNode templateNode : templateNodes) {\n boundingVolumes.addAll(templateNode.getBoundingSpheres());\n }\n return boundingVolumes;\n }\n private Vector3f getTableCollisionPoint() {\n List collidables = new ArrayList();\n collidables.add(getTableNode());\n CollisionResult closestCollision = Utils.getNearestCollisionFrom(cam.getLocation(), cam.getDirection(), collidables);\n if (closestCollision != null) {\n return closestCollision.getContactPoint().add(GROUND_BUFFER);\n }\n else {\n return null;\n }\n }\n private Vector3f getSceneryCollisionPoint() {\n List collidables = new ArrayList();\n collidables.add(getTableNode());\n collidables.add(getBuildingsNode());\n CollisionResult closestCollision = Utils.getNearestCollisionFrom(cam.getLocation(), cam.getDirection(), collidables);\n if ((closestCollision != null) && closestCollision.getContactNormal().angleBetween(Vector3f.UNIT_Y) <= MAX_COLLISION_NORMAL_ANGLE) {\n return closestCollision.getContactPoint().add(GROUND_BUFFER);\n }\n else {\n return null;\n }\n }\n private Vector3f getLadderCollisionPoint(Ladder ladder) {\n CollisionResults results = new CollisionResults();\n Ray ray = new Ray(ladder.getWorldEnd(), Vector3f.UNIT_Y.mult(-1));\n getTableNode().collideWith(ray, results);\n getBuildingsNode().collideWith(ray, results);\n CollisionResult closestCollision = results.getClosestCollision();\n if (closestCollision != null && closestCollision.getContactNormal().angleBetween(Vector3f.UNIT_Y) <= MAX_COLLISION_NORMAL_ANGLE) {\n return closestCollision.getContactPoint().add(GROUND_BUFFER);\n }\n else {\n return null;\n }\n }\n private class PhysicsCollisionListenerImpl implements PhysicsCollisionListener {\n @Override\n public void collision(PhysicsCollisionEvent event) {\n Spatial a = event.getNodeA();\n Spatial b = event.getNodeB();\n Spatial selectedCollisionShapeNode = null;\n if (selectedFighterNode != null) {\n selectedCollisionShapeNode = selectedFighterNode.getChild(\"collisionShapeNode\");\n }\n Spatial targetedCollisionShapeNode = null;\n FighterNode fighterNodeUnderCursor = getFighterNodeUnderCursor();\n if (fighterNodeUnderCursor != null) {\n targetedCollisionShapeNode = fighterNodeUnderCursor.getChild(\"collisionShapeNode\");\n }\n if ((a == selectedCollisionShapeNode) && (b.getName().equals(\"buildingsNode\")) || (b == selectedCollisionShapeNode)\n && (a.getName().equals(\"buildingsNode\"))) {\n selectedFighterNode.setPositionValid(false);\n }\n else if ((a == selectedCollisionShapeNode) && (b.getName().equals(\"collisionShapeNode\")) || (b == selectedCollisionShapeNode)\n && (a.getName().equals(\"collisionShapeNode\"))) {\n selectedFighterNode.setPositionValid(false);\n }\n else if ((b.getName().equals(\"currentLineOfSightBoxNode\")\n && ((a.getName().equals(\"collisionShapeNode\") && (a != selectedCollisionShapeNode) && (a != targetedCollisionShapeNode))) || (a.getName()\n .equals(\"currentLineOfSightBoxNode\"))\n && ((b.getName().equals(\"collisionShapeNode\") && (b != selectedCollisionShapeNode) && (b != targetedCollisionShapeNode))))) {\n if (currentLineOfSight != null) {\n currentLineOfSight.setValid(false);\n }\n }\n else if ((a.getName().equals(\"currentLineOfSightBoxNode\")) && (b.getName().equals(\"buildingsNode\"))\n || (b.getName().equals(\"currentLineOfSightBoxNode\")) && (a.getName().equals(\"buildingsNode\"))) {\n if (currentLineOfSight != null) {\n currentLineOfSight.setValid(false);\n }\n }\n else if ((a.getName().equals(\"currentPathBoxNode\")) && ((b.getName().equals(\"collisionShapeNode\")) && (b != selectedCollisionShapeNode))\n || (b.getName().equals(\"currentPathBoxNode\")) && ((a.getName().equals(\"collisionShapeNode\")) && (a != selectedCollisionShapeNode))) {\n if (currentPath != null) {\n currentPath.setValid(false);\n }\n }\n else if ((a.getName().equals(\"currentPathBoxNode\")) && (b.getName().equals(\"buildingsNode\")) || (b.getName().equals(\"currentPathBoxNode\"))\n && (a.getName().equals(\"buildingsNode\"))) {\n if (currentPath != null) {\n currentPath.setValid(false);\n }\n }\n }\n }\n private class PhysicsTickListenerImpl implements PhysicsTickListener {\n @Override\n public void prePhysicsTick(PhysicsSpace space, float f) {\n }\n @Override\n public void physicsTick(PhysicsSpace space, float f) {\n if (!physicsTickLock1) {\n physicsTickLock1 = true;\n }\n else {\n physicsTickLock2 = true;\n }\n }\n }\n private class MouseListener implements ActionListener, AnalogListener {\n public void onAction(String name, boolean isPressed, float tpf) {\n executeMouseAction(name, isPressed);\n game.updateStatus();\n }\n public void onAnalog(String name, float value, float tpf) {\n if (game.getSelectionMode().equals(SelectionMode.MOVE)) {\n setUpMovement();\n }\n else if (game.getSelectionMode().equals(SelectionMode.TARGET)) {\n setUpTargeting();\n }\n else if (game.getSelectionMode().equals(SelectionMode.DEPLOY_MODEL)) {\n updateModelPosition();\n }\n else if (game.getSelectionMode().equals(SelectionMode.DEPLOY_BUILDING)) {\n if (rightButtonDown) {\n if ((selectedBuildingNode != null) && isMouseMovement(name)) {\n float direction = 1;\n if (name.equals(\"Move_Left\")) {\n direction = -1;\n }\n selectedBuildingNode.rotate(0, value * 3 * direction, 0);\n }\n }\n else {\n Vector3f nearestIntersection = getTableCollisionPoint();\n if (nearestIntersection == null) {\n return;\n }\n if (selectedBuildingNode == null) {\n selectedBuildingNode = buildingNodes.poll();\n buildingsNode.attachChild(selectedBuildingNode);\n }\n selectedBuildingNode.setLocalTranslation(nearestIntersection);\n }\n }\n updateModels();\n }\n }\n private boolean isMouseMovement(String name) {\n if (name.equals(\"Move_Left\") || name.equals(\"Move_Right\") || name.equals(\"Move_Up\") || name.equals(\"Move_Down\")) {\n return true;\n }\n else {\n return false;\n }\n }\n private class KeyboardListener implements ActionListener {\n @Override\n public void onAction(String name, boolean isPressed, float tpf) {\n if (isPressed) {\n executeKeyboardAction(name);\n game.updateStatus();\n }\n }\n }\n private class TemplateRemover {\n private TemplateNode temporaryWeaponTemplate;\n private int timer;\n public TemplateRemover(TemplateNode temporaryWeaponTemplate) {\n this.temporaryWeaponTemplate = temporaryWeaponTemplate;\n this.timer = 2000;\n }\n public void remove() {\n rootNode.detachChild(temporaryWeaponTemplate);\n templateNodes.remove(temporaryWeaponTemplate);\n updateModels();\n }\n public int getTimer() {\n return timer;\n }\n public void setTimer(int timer) {\n this.timer = timer;\n }\n }\n private List getLaddersInReach(Vector3f origin, float baseRadius) {\n List laddersInReach = new ArrayList();\n for (Ladder ladder : (List)getLaddersFrom(buildingsNode)) {\n float distance = ladder.getWorldStart().distance(origin);\n if ((distance - baseRadius) <= MAX_LADDER_DISTANCE) {\n laddersInReach.add(ladder);\n }\n }\n return laddersInReach;\n }\n private void unpinFighters() {\n for (FighterNode fighterNode : fighterNodes) {\n Fighter fighter = fighterNode.getFighter();\n if (game.getCurrentGang().getGangMembers().contains(fighter) && fighter.isPinned()) {\n List surroundingFighterNodes = getFighterNodesWithinDistance(fighterNode, Necromunda.UNPIN_BY_INITIATIVE_DISTANCE);\n List reliableMates = new ArrayList();\n for (FighterNode surroundingFighterNode : surroundingFighterNodes) {\n Fighter surroundingFighter = surroundingFighterNode.getFighter();\n if (fighter.getGang().getGangMembers().contains(surroundingFighter) && surroundingFighter.isReliableMate()) {\n reliableMates.add(surroundingFighter);\n }\n }\n if (!reliableMates.isEmpty() || fighter instanceof Leader) {\n fighter.unpinByInitiative();\n }\n else {\n Necromunda.appendToStatusMessage(String.format(\"%s has no reliable mates around.\", fighter));\n }\n }\n }\n }\n private void turnStarted() {\n unpinFighters();\n removeTemplates();\n moveTemplates();\n applyTemplateEffects();\n removeTemplateTrails();\n }\n private void removeTemplates() {\n Iterator it = templateNodes.iterator();\n while (it.hasNext()) {\n TemplateNode templateNode = it.next();\n if (templateNode.isTemplateToBeRemoved()) {\n it.remove();\n rootNode.detachChild(templateNode);\n }\n }\n }\n private void moveTemplates() {\n for (TemplateNode templateNode : templateNodes) {\n if (templateNode.isTemplateMoving()) {\n float distance = templateNode.getDriftDistance();\n float angle = templateNode.getDriftAngle();\n Vector3f start = templateNode.getLocalTranslation().clone();\n List collidables = new ArrayList();\n collidables.add(getBuildingsNode());\n templateNode.moveAndCollide(distance, angle, collidables);\n templateNode.attachTrail(start);\n }\n }\n }\n private void applyTemplateEffects() {\n for (TemplateNode templateNode : templateNodes) {\n List affectedFighterNodes = getFighterNodesUnderTemplate(templateNode, fighterNodes);\n templateNode.dealDamageTo(affectedFighterNodes);\n }\n }\n private void removeTemplateTrails() {\n for (TemplateNode templateNode : templateNodes) {\n templateNode.removeTrail();\n }\n }\n private void setUpMovement() {\n updateCurrentPath();\n if (currentPath != null) {\n updateCurrentPathBox();\n }\n }\n private void updateCurrentPath() {\n Vector3f nearestIntersection = getSceneryCollisionPoint();\n Vector3f objectPosition = null;\n if (currentPath == null) {\n objectPosition = selectedFighterNode.getLocalTranslation();\n }\n else {\n objectPosition = currentPath.getOrigin();\n }\n if (nearestIntersection == null) {\n return;\n }\n float slope = FastMath.abs(nearestIntersection.getY() - objectPosition.getY());\n if (slope > MAX_SLOPE) {\n return;\n }\n if (currentPath == null) {\n currentPath = new Line(objectPosition.clone(), nearestIntersection);\n }\n Vector3f movementVector = nearestIntersection.subtract(currentPath.getOrigin());\n float distance = movementVector.length();\n float remainingMovementDistance = game.getSelectedFighter().getRemainingMovementDistance();\n if (distance > remainingMovementDistance) {\n movementVector.normalizeLocal().multLocal(remainingMovementDistance);\n }\n currentPath.getDirection().set(currentPath.getOrigin().add(movementVector));\n }\n private void updateCurrentPathBox() {\n CollisionShape boxCollisionShape = getPathBoxCollisionShapeOf(selectedFighterNode, currentPath);\n GhostControl physicsGhostObject;\n if (currentPathBoxNode == null) {\n physicsGhostObject = new GhostControl(boxCollisionShape);\n currentPathBoxNode = new Node(\"currentPathBoxNode\");\n currentPathBoxNode.addControl(physicsGhostObject);\n getPhysicsSpace().add(physicsGhostObject);\n }\n else {\n currentPathBoxNode.detachChildNamed(\"currentPathBoxGeometry\");\n physicsGhostObject = currentPathBoxNode.getControl(GhostControl.class);\n physicsGhostObject.setCollisionShape(boxCollisionShape);\n }\n currentPath.setValid(true);\n currentPathBoxNode.attachChild(getPathBoxGeometryFor(selectedFighterNode));\n rootNode.attachChild(currentPathBoxNode);\n Vector3f halfExtents = getHalfExtentsOf(selectedFighterNode);\n Vector3f upTranslation = new Vector3f(0, halfExtents.getY(), 0);\n Vector3f vector = currentPath.getOrigin().add(currentPath.getVector().mult(0.5f)).addLocal(upTranslation);\n currentPathBoxNode.setLocalTranslation(vector);\n currentPathBoxNode.lookAt(currentPath.getDirection().add(upTranslation), Vector3f.UNIT_Y);\n selectedFighterNode.setLocalTranslation(currentPath.getDirection());\n lockPhysics();\n }\n private void setUpTargeting() {\n Fighter selectedFighter = game.getSelectedFighter();\n RangeCombatWeapon weapon = selectedFighter.getSelectedRangeCombatWeapon();\n Ammunition currentAmmunition = weapon.getCurrentAmmunition();\n if (currentAmmunition.isTemplated()) {\n Line line = null;\n if (weapon.isTargeted()) {\n if (getFighterNodeUnderCursor() == null) {\n removeTargetingFacilities();\n return;\n }\n updateCurrentLineOfSight();\n updateCurrentLineOfSightLine();\n updateCurrentLineOfSightBox();\n line = currentLineOfSight;\n }\n else {\n Vector3f upTranslation = new Vector3f(0, selectedFighter.getBaseRadius() * 1.5f, 0);\n line = new Line(selectedFighterNode.getLocalTranslation().add(upTranslation), getSceneryCollisionPoint().add(upTranslation));\n }\n if (currentTemplateNode == null) {\n currentTemplateNode = TemplateNode.createTemplateNode(assetManager, currentAmmunition);\n }\n Vector3f lineOfSightVector = line.getDirection().subtract(line.getOrigin());\n lineOfSightVector = lineOfSightVector.normalize();\n if (weapon.isTemplateAttached()) {\n currentTemplateNode.rotateUpTo(lineOfSightVector);\n currentTemplateNode.setLocalTranslation(line.getOrigin());\n }\n else {\n currentTemplateNode.setLocalTranslation(line.getDirection());\n }\n rootNode.detachChildNamed(\"currentTemplateNode\");\n rootNode.attachChild(currentTemplateNode);\n }\n else {\n if (getFighterNodeUnderCursor() != null) {\n updateCurrentLineOfSight();\n updateCurrentLineOfSightLine();\n updateCurrentLineOfSightBox();\n }\n else {\n removeTargetingFacilities();\n }\n }\n }\n private void updateCurrentLineOfSight() {\n Vector3f sourceCenter = selectedFighterNode.getChild(\"collisionShapeNode\").getWorldTranslation().clone().add(0, selectedFighterNode.getCenterToHeadOffset(), 0);\n Vector3f targetCenter = getFighterNodeUnderCursor().getChild(\"collisionShapeNode\").getWorldTranslation().clone();\n if (currentLineOfSight == null) {\n currentLineOfSight = new Line(sourceCenter, targetCenter);\n }\n else {\n currentLineOfSight.getOrigin().set(sourceCenter);\n currentLineOfSight.getDirection().set(targetCenter);\n }\n }\n private void updateCurrentLineOfSightLine() {\n Geometry lineGeometry = (Geometry) rootNode.getChild(\"currentLineOfSightLine\");\n Vector3f start = currentLineOfSight.getOrigin();\n Vector3f end = currentLineOfSight.getDirection();\n if (lineGeometry == null) {\n com.jme3.scene.shape.Line line = new com.jme3.scene.shape.Line(start, end);\n lineGeometry = new Geometry(\"currentLineOfSightLine\", line);\n lineGeometry.setMaterial(materialFactory.createMaterial(MaterialIdentifier.SELECTED));\n rootNode.attachChild(lineGeometry);\n }\n else {\n com.jme3.scene.shape.Line line = (com.jme3.scene.shape.Line) lineGeometry.getMesh();\n line.updatePoints(start, end);\n }\n }\n private void updateCurrentLineOfSightBox() {\n float lineOfSightLength = getLineLength(currentLineOfSight);\n Vector3f halfExtents = new Vector3f(0.1f, 0.1f, lineOfSightLength * 0.5f);\n CollisionShape boxCollisionShape = new BoxCollisionShape(halfExtents);\n GhostControl physicsGhostObject;\n if (currentLineOfSightBoxNode == null) {\n physicsGhostObject = new GhostControl(boxCollisionShape);\n currentLineOfSightBoxNode = new Node(\"currentLineOfSightBoxNode\");\n currentLineOfSightBoxNode.addControl(physicsGhostObject);\n getPhysicsSpace().add(physicsGhostObject);\n rootNode.attachChild(currentLineOfSightBoxNode);\n }\n else {\n physicsGhostObject = currentLineOfSightBoxNode.getControl(GhostControl.class);\n physicsGhostObject.setCollisionShape(boxCollisionShape);\n }\n currentLineOfSight.setValid(true);\n Vector3f vector = currentLineOfSight.getOrigin().add(currentLineOfSight.getVector().mult(0.5f));\n currentLineOfSightBoxNode.setLocalTranslation(vector);\n lockPhysics();\n currentLineOfSightBoxNode.lookAt(currentLineOfSight.getDirection(), Vector3f.UNIT_Y);\n }\n private float getLineLength(Line line) {\n return line.getOrigin().distance(line.getDirection());\n }\n private PhysicsSpace getPhysicsSpace() {\n return stateManager.getState(BulletAppState.class).getPhysicsSpace();\n }\n private void lockPhysics() {\n physicsTickLock1 = false;\n physicsTickLock2 = false;\n }\n private boolean isPhysicsLocked() {\n return !physicsTickLock1 || !physicsTickLock2;\n }\n private List getHostileFighterNodesFrom(List fighterNodes) {\n List hostileFighterNodes = new ArrayList();\n for (FighterNode fighterNode : fighterNodes) {\n Fighter fighter = fighterNode.getFighter();\n if (game.getHostileGangers().contains(fighter)) {\n hostileFighterNodes.add(fighterNode);\n }\n }\n return hostileFighterNodes;\n }\n private List getFighterNodesWithLineOfSightFrom(FighterNode source, List fighterNodes) {\n List fighterNodesWithLineOfSight = new ArrayList();\n List collidables = getBoundingVolumes();\n collidables.add(getBuildingsNode());\n for (FighterNode fighterNode : fighterNodes) {\n if (getVisibilityInfo(source, fighterNode, collidables).getNumberOfVisiblePoints() > 0) {\n fighterNodesWithLineOfSight.add(fighterNode);\n }\n }\n return fighterNodesWithLineOfSight;\n }\n private FighterNode getNearestFighterNodeFrom(FighterNode source, List fighterNodes) {\n float nearestDistance = Float.MAX_VALUE;\n FighterNode nearestFighterNode = null;\n for (FighterNode fighterNode : fighterNodes) {\n float distance = source.getLocalTranslation().distance(fighterNode.getLocalTranslation());\n if (distance < nearestDistance) {\n nearestDistance = distance;\n nearestFighterNode = fighterNode;\n }\n }\n return nearestFighterNode;\n }\n private List getFighterNodesWithinDistance(FighterNode fighterNode, float maxDistance) {\n List otherFighterNodes = new ArrayList();\n Fighter fighter = fighterNode.getFighter();\n for (FighterNode otherFighterNode : fighterNodes) {\n if (otherFighterNode == fighterNode) {\n continue;\n }\n Fighter otherFighter = otherFighterNode.getFighter();\n float distance = fighterNode.getLocalTranslation().distance(otherFighterNode.getLocalTranslation());\n distance -= fighter.getBaseRadius() + otherFighter.getBaseRadius();\n if (distance < maxDistance) {\n otherFighterNodes.add(otherFighterNode);\n }\n }\n return otherFighterNodes;\n }\n private List getFighterNodesUnderTemplate(TemplateNode templateNode, List fighterNodes) {\n List fighterNodesUnderTemplate = new ArrayList();\n for (FighterNode fighterNode : fighterNodes) {\n CylinderCollisionShape shape = (CylinderCollisionShape) fighterNode.getGhostControl().getCollisionShape();\n Vector3f halfExtents = shape.getHalfExtents();\n Vector3f localTranslation = fighterNode.getLocalTranslation().clone();\n Fighter fighter = fighterNode.getFighter();\n localTranslation.y += fighter.getBaseRadius() * 1.5f;\n BoundingBox boundingBox = new BoundingBox(localTranslation, halfExtents.x, halfExtents.y, halfExtents.z);\n for (BoundingSphere sphere : templateNode.getBoundingSpheres()) {\n if (boundingBox.intersectsSphere(sphere)) {\n fighterNodesUnderTemplate.add(fighterNode);\n break;\n }\n }\n }\n return fighterNodesUnderTemplate;\n }\n private void fireTargetedWeapon(RangeCombatWeapon weapon, int hitModifier) {\n weapon.trigger();\n Iterator targetedFighterNodesIterator = targetedFighterNodes.iterator();\n while (targetedFighterNodesIterator.hasNext()) {\n FighterNode fighterNode = targetedFighterNodesIterator.next();\n float distance = fighterNode.getLocalTranslation().distance(selectedFighterNode.getLocalTranslation());\n if (distance > weapon.getMaximumRange()) {\n Necromunda.appendToStatusMessage(\"Object out of range.\");\n targetedFighterNodesIterator.remove();\n continue;\n }\n Fighter selectedFighter = game.getSelectedFighter();\n int targetHitRoll = 7 - selectedFighter.getBallisticSkill() - weapon.getRangeModifier(distance) - hitModifier;\n if (targetHitRoll >= 10) {\n Necromunda.appendToStatusMessage(String.format(\"You need a %s to hit - impossible!\", targetHitRoll));\n targetedFighterNodesIterator.remove();\n continue;\n }\n Necromunda.appendToStatusMessage(String.format(\"Target hit roll is %s.\", targetHitRoll));\n int hitRoll = Utils.rollD6();\n if ((targetHitRoll > 6) && (hitRoll == 6)) {\n targetHitRoll -= 3;\n hitRoll = Utils.rollD6();\n }\n if ((hitRoll < targetHitRoll) || (hitRoll <= 1)) {\n Necromunda.appendToStatusMessage(String.format(\"Rolled a %s and missed...\", hitRoll));\n shotHasMissed(weapon.isScattering());\n targetedFighterNodesIterator.remove();\n continue;\n }\n Necromunda.appendToStatusMessage(String.format(\"Rolled a %s and hit!\", hitRoll));\n fireAtTarget(hitRoll);\n targetedFighterNodesIterator.remove();\n }\n }\n private void fireAtTarget(int hitRoll) {\n Fighter selectedFighter = game.getSelectedFighter();\n RangeCombatWeapon weapon = selectedFighter.getSelectedRangeCombatWeapon();\n weapon.hitRoll(hitRoll);\n if (currentTemplateNode != null) {\n fireTemplate(currentTemplateNode);\n queueTemplateNodeForRemoval(currentTemplateNode);\n }\n else {\n applyShotToTargets(weapon);\n }\n }\n private void shotHasMissed(boolean isScattering) {\n if (currentTemplateNode != null) {\n boolean hasEffect = true;\n if (isScattering) {\n List collidables = new ArrayList();\n collidables.add(getBuildingsNode());\n hasEffect = currentTemplateNode.scatter(getLineLength(currentLineOfSight), collidables);\n }\n if (hasEffect) {\n fireTemplate(currentTemplateNode);\n }\n queueTemplateNodeForRemoval(currentTemplateNode);\n }\n }\n private void queueTemplateNodeForRemoval(TemplateNode templateNode) {\n templateNodes.add(templateNode);\n if (!currentTemplateNode.isTemplatePersistent()) {\n templateNode.setName(\"temporaryTemplateNode\");\n TemplateRemover templateRemover = new TemplateRemover(templateNode);\n templateRemovers.add(templateRemover);\n }\n else {\n templateNode.setName(\"persistentTemplateNode\");\n }\n }\n private void applyShotToTargets(RangeCombatWeapon weapon) {\n List affectedFighterNodes = new ArrayList();\n FighterNode affectedFighterNode = targetedFighterNodes.get(0);\n affectedFighterNodes.add(affectedFighterNode);\n if (weapon.getAdditionalTargetRange() > 0) {\n List fighterNodesWithinRange = getFighterNodesWithinDistance(affectedFighterNode, weapon.getAdditionalTargetRange());\n List visibleFighterNodes = getFighterNodesWithLineOfSightFrom(selectedFighterNode, fighterNodesWithinRange);\n affectedFighterNodes.addAll(visibleFighterNodes);\n }\n pinFighters(affectedFighterNodes);\n for (FighterNode fighterNode : affectedFighterNodes) {\n Fighter fighter = fighterNode.getFighter();\n weapon.dealDamageTo(fighter);\n }\n }\n private void fireTemplate(TemplateNode templateNode) {\n List affectedFighterNodes = getFighterNodesUnderTemplate(templateNode, fighterNodes);\n pinFighters(affectedFighterNodes);\n templateNode.dealDamageTo(affectedFighterNodes);\n }\n private void pinFighters(List fighterNodes) {\n for (FighterNode fighterNode : fighterNodes) {\n Fighter fighter = fighterNode.getFighter();\n if (fighter.isNormal()) {\n fighter.setState(State.PINNED);\n }\n }\n }\n private String getStatusTextFrom(Necromunda game) {\n StringBuilder statusText = new StringBuilder();\n String string = String.format(\"Turn %s, %s\\n\", game.getTurn(), game.getCurrentGang().toString());\n statusText.append(string);\n if (game.getSelectedFighter() != null) {\n Fighter ganger = (Fighter) game.getSelectedFighter();\n statusText.append(String.format(\"%s, %s, %sFlesh Wounds: %s\\n\", ganger.getName(), ganger.getState(), (ganger.isWebbed() ? \"Webbed, \" : \"\"), ganger\n .getFleshWounds()));\n RangeCombatWeapon weapon = ganger.getSelectedRangeCombatWeapon();\n if (weapon != null) {\n String broken = weapon.isBroken() ? \" (Broken), \" : \", \";\n String mode = (weapon.getAmmunitions().size() > 1) ? String.format(\" Ammunition: %s, \", weapon.getCurrentAmmunition().getName()) : \"\";\n statusText.append(String.format(\"%s%s%s%s\\n\", weapon, broken, mode, weapon.getProfileString()));\n }\n else {\n statusText.append(\"No weapon selected\\n\");\n }\n }\n else {\n statusText.append(\"\\n\\n\");\n }\n if (Necromunda.getStatusMessage() != null) {\n statusText.append(String.format(\"%s\\n\", Necromunda.getStatusMessage()));\n }\n else {\n statusText.append(\"\\n\");\n }\n if (game.getPhase() != null) {\n statusText.append(game.getPhase().toString());\n }\n else {\n statusText.append(\" \");\n }\n return statusText.toString();\n }\n @Override\n public void simpleUpdate(float tpf) {\n int millis = (int) (tpf * 1000);\n Iterator it = templateRemovers.iterator();\n while (it.hasNext()) {\n TemplateRemover templateRemover = it.next();\n templateRemover.setTimer(templateRemover.getTimer() - millis);\n if (templateRemover.getTimer() < 0) {\n templateRemover.remove();\n it.remove();\n }\n }\n }\n public String getTerrainType() {\n return terrainType;\n }\n public void setTerrainType(String terrainType) {\n this.terrainType = terrainType;\n }\n}"}}},{"rowIdx":346265,"cells":{"answer":{"kind":"string","value":"package com.wegas.core.ejb;\nimport com.wegas.core.event.internal.EngineInvocationEvent;\nimport com.wegas.core.exception.WegasException;\nimport com.wegas.core.persistence.AbstractEntity;\nimport com.wegas.core.persistence.game.GameModelContent;\nimport com.wegas.core.persistence.game.Player;\nimport com.wegas.core.persistence.game.Script;\nimport com.wegas.core.persistence.variable.VariableDescriptor;\nimport com.wegas.core.persistence.variable.VariableInstance;\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.Serializable;\nimport java.nio.file.Files;\nimport java.util.*;\nimport java.util.Map.Entry;\nimport javax.ejb.EJB;\nimport javax.ejb.LocalBean;\nimport javax.ejb.Stateless;\nimport javax.enterprise.event.Event;\nimport javax.enterprise.event.ObserverException;\nimport javax.enterprise.event.Observes;\nimport javax.inject.Inject;\nimport javax.persistence.EntityManager;\nimport javax.persistence.PersistenceContext;\nimport javax.script.ScriptEngine;\nimport javax.script.ScriptEngineManager;\nimport javax.script.ScriptException;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n/**\n *\n * @author Francois-Xavier Aeberhard \n */\n@Stateless\n@LocalBean\npublic class ScriptFacade implements Serializable {\n private static final Logger logger = LoggerFactory.getLogger(ScriptFacade.class);\n @PersistenceContext(unitName = \"wegasPU\")\n private EntityManager em;\n @EJB\n private PlayerFacade playerEntityFacade;\n @EJB\n private VariableDescriptorFacade variableDescriptorFacade;\n @Inject\n private ScriptEventFacade event;\n @Inject\n private RequestManager requestManager;\n @Inject\n Event engineInvocationEvent;\n /**\n *\n * Fires an engineInvocationEvent, which should be intercepted to customize\n * engine scope.\n *\n * @param script\n * @param arguments\n * @return\n * @throws WegasException\n */\n public Object eval(Script script, Map arguments) throws WegasException {\n if (script == null) {\n return null;\n }\n ScriptEngine engine = requestManager.getCurrentEngine();\n if (engine == null) {\n ScriptEngineManager mgr = new ScriptEngineManager(); // Instantiate the corresponding script engine\n try {\n engine = mgr.getEngineByName(script.getLanguage());\n // Invocable invocableEngine = (Invocable) engine;\n } catch (NullPointerException ex) {\n logger.error(\"Could not find language\", ex.getMessage(), ex.getStackTrace());\n throw new WegasException(\"Could not instantiate script engine for script\" + script);\n }\n try {\n engineInvocationEvent.fire(\n new EngineInvocationEvent(requestManager.getPlayer(), engine));// Fires the engine invocation event, to allow extensions\n } catch (ObserverException ex) {\n throw (WegasException) ex.getCause();\n }\n requestManager.setCurrentEngine(engine);\n }\n for (Entry arg : arguments.entrySet()) { // Inject the arguments\n engine.put(arg.getKey(), arg.getValue());\n }\n try {\n engine.put(ScriptEngine.FILENAME, script.getContent()); //@TODO: JAVA 8 filename in scope\n return engine.eval(script.getContent());\n } catch (ScriptException ex) {\n// requestManager.addException(\n// new com.wegas.core.exception.ScriptException(script.getContent(), ex.getLineNumber(), ex.getMessage()));\n// throw new ScriptException(ex.getMessage(), script.getContent(), ex.getLineNumber());\n throw new com.wegas.core.exception.ScriptException(script.getContent(), ex.getLineNumber(), ex.getMessage());\n }\n }\n /**\n * Default customization of our engine: inject the script library, the root\n * variable instances and some libraries.\n *\n * @param evt\n */\n public void onEngineInstantiation(@Observes EngineInvocationEvent evt) {\n evt.getEngine().put(\"self\", evt.getPlayer()); // Inject current player\n evt.getEngine().put(\"gameModel\", evt.getPlayer().getGameModel()); // Inject current gameModel\n evt.getEngine().put(\"Variable\", variableDescriptorFacade); // Inject the variabledescriptor facade\n evt.getEngine().put(\"VariableDescriptorFacade\", variableDescriptorFacade);// @backwardcompatibility\n evt.getEngine().put(\"RequestManager\", requestManager); // Inject the request manager\n evt.getEngine().put(\"Event\", event); // Inject the Event manager\n event.detachAll();\n this.injectStaticScript(evt);\n for (Entry arg\n : evt.getPlayer().getGameModel().getScriptLibrary().entrySet()) { // Inject the script library\n evt.getEngine().put(ScriptEngine.FILENAME, \"Server script \" + arg.getKey()); //@TODO: JAVA 8 filename in scope\n try {\n evt.getEngine().eval(arg.getValue().getContent());\n } catch (ScriptException ex) {\n throw new com.wegas.core.exception.ScriptException(\"Server script \" + arg.getKey(), ex.getLineNumber(), ex.getMessage());\n }\n }\n for (VariableDescriptor vd\n : evt.getPlayer().getGameModel().getChildVariableDescriptors()) { // Inject the variable instances in the script\n VariableInstance vi = vd.getInstance(evt.getPlayer());\n try {\n evt.getEngine().put(vd.getName(), vi);\n } catch (IllegalArgumentException ex) {\n //logger.error(\"Missing name for Variable label [\" + vd.getLabel() + \"]\");\n }\n }\n }\n /**\n * Inject script files specified in GameModel's property scriptFiles into\n * engine\n *\n * @param evt EngineInvocationEvent\n * @throws ScriptException\n */\n private void injectStaticScript(EngineInvocationEvent evt) {\n String currentPath = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();\n Integer index = currentPath.indexOf(\"WEB-INF\");\n if (index < 1) { // @ TODO find an other way to get web app root currently war packaging required.\n return;\n }\n String root = currentPath.substring(0, index);\n String[] files = new String[0];\n if (evt.getPlayer().getGameModel().getProperties().getScriptUri() != null) { //@TODO : precompile? cache ?\n files = evt.getPlayer().getGameModel().getProperties().getScriptUri().split(\";\");\n }\n for (String f : getJavaScriptsRecursively(root, files)) {\n evt.getEngine().put(ScriptEngine.FILENAME, \"Script file \" + f); //@TODO: JAVA 8 filename in scope\n try {\n evt.getEngine().eval(new java.io.FileReader(f));\n logger.info(\"File \" + f + \" successfully injected\");\n } catch (FileNotFoundException ex) {\n logger.warn(\"File \" + f + \" was not found\");\n } catch (ScriptException ex) {\n throw new com.wegas.core.exception.ScriptException(f, ex.getLineNumber(), ex.getMessage());\n }\n }\n }\n /**\n * extract all javascript files from the files list. If one of the files is\n * a directory, recurse through it and fetch *.js.\n *\n * Note: When iterating, if a script and its minified version stands in the directory,\n * the minified is ignored (debugging purpose)\n *\n * @param root\n * @param files\n * @return\n */\n private Collection getJavaScriptsRecursively(String root, String[] files) {\n List queue = new LinkedList<>();\n List result = new LinkedList<>();\n for (String file : files) {\n File f = new File(root + \"/\" + file);\n // Put directories in the recurse queue and files in result list\n // this test may look redundant with the one done bellow... but...\n // actually, it ensures a -min.js script given by the user is never ignored\n if (f.isDirectory()) {\n queue.add(f);\n } else {\n result.add(f.getPath());\n }\n }\n while (queue.size() > 0) {\n File current = queue.remove(0);\n System.out.flush();\n if (!Files.isSymbolicLink(current.toPath()) && current.canRead()) {\n if (current.isDirectory()) {\n File[] listFiles = current.listFiles();\n if (listFiles == null) {\n break;\n } else {\n queue.addAll(Arrays.asList(listFiles));\n }\n } else {\n if (current.isFile()\n && current.getName().endsWith(\".js\") // Is a javascript\n && !isMinifedDuplicata(current)) { // avoid minified version when original exists\n result.add(current.getPath());\n }\n }\n }\n }\n return result;\n }\n /**\n * check if the given file is a minified version of an existing one\n *\n * @param file\n * @return\n */\n private boolean isMinifedDuplicata(File file) {\n if (file.getName().endsWith(\"-min.js\")) {\n String siblingPath = file.getPath().replaceAll(\"-min.js$\", \".js\");\n File f = new File(siblingPath);\n return f.exists();\n }\n return false;\n }\n /**\n *\n * @param scripts\n * @param arguments\n * @return\n * @throws WegasException\n */\n public Object eval(List