{ // 获取包含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 !== 'VoxCPM' ) { link.textContent = 'VoxCPM'; link.href = 'https://voxcpm.net/'; replacedLinks.add(link); } // 替换Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) && linkText !== 'IndexTTS2' ) { link.textContent = 'IndexTTS2'; link.href = 'https://vibevoice.info/indextts2'; 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"}}},{"rowIdx":916,"cells":{"language":{"kind":"string","value":"Java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2913,"string":"2,913"},"score":{"kind":"number","value":3.09375,"string":"3.09375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package hangman;\n\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Scanner;\nimport java.util.Set;\nimport java.util.TreeSet;\n\npublic class EvilHangmanGame implements IEvilHangmanGame {\n\tprivate KeyPartPair kpp;\n\tpublic Partition mypart;\n\tprivate int gcount;\n\tprivate ArrayList guessedletters = new ArrayList<>();\n\tpublic Key gamekey;\n\tpublic boolean winstatus = false;\n\n\tpublic EvilHangmanGame() {\n\t\t// TODO Auto-generated constructor stub\n\n\t}\n\n\t@Override\n\tpublic void startGame(File dictionary, int wordLength) {\n\t\t// TODO Auto-generated method stub\n\t\t// check wordlength ********************* >= 2\n\t\tsetGcount(0);\n\t\ttry {\n\t\t\tScanner sc = new Scanner(dictionary);\n\t\t\tmypart = new Partition();\n\t\t\twhile (sc.hasNext()) {\n\t\t\t\tmypart.add(sc.next());\n\t\t\t}\n\t\t\tsc.close();\n\n\t\t\tmypart.setWordLength(wordLength);\n\t\t\tgamekey = new Key(wordLength);\n\n\t\t} catch (FileNotFoundException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t@Override\n\tpublic Set makeGuess(char guess) throws GuessAlreadyMadeException {\n\t\t// TODO Auto-generated method stub\n\t\tthis.checkGuessMade(guess);\n\t\tkpp = new KeyPartPair(mypart, guess);\n\t\tSet output = new TreeSet<>();\n\t\toutput = kpp.getBestSet();\n\t\taddGuessedLetter(guess);\n\t\tmypart.words = output;\n\t\t//System.out.print(output);\n\t\treturn output;\n\t}\n\n\tpublic int getGcount() {\n\t\treturn gcount;\n\t}\n\n\tpublic void setGcount(int gcount) {\n\t\tthis.gcount = gcount;\n\t}\n\n\tpublic void addGuessedLetter(char in) {\n\t\tString temp = Character.toString(in);\n\t\tguessedletters.add(temp);\n\t}\n\n\tpublic void addGuessedLetter(String in) {\n\t\tguessedletters.add(in);\n\t}\n\n\tpublic String printGuessedLetters() {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tCollections.sort(guessedletters);\n\t\tfor (String s : guessedletters) {\n\t\t\tsb.append(s + \" \");\n\t\t}\n\t\treturn sb.toString();\n\t}\n\n\tpublic void checkGuessMade(char in) throws GuessAlreadyMadeException {\n\t\tfor (int x = 0; x < guessedletters.size(); x += 1) {\n\t\t\tif (guessedletters.get(x).charAt(0) == in) {\n\t\t\t\tthrow new GuessAlreadyMadeException();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic boolean gameRunning(EvilHangmanGame game) {\n\t\tif (game.getGcount() == 0) {\n\t\t\treturn false;\n\t\t}\n\t\tif (game.gamekey.checkIfWordFull()) {\n\t\t\twinstatus = true;\n\t\t\treturn false;\n\t\t}\n\t\tif (game.winstatus) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tpublic boolean checkGuessValid(String in) {\n\t\tif (in.length() != 1) {\n\t\t\treturn false;\n\t\t}\n\t\tchar dachar = in.charAt(0);\n\t\tif (!Character.isLetter(dachar)) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tpublic int haveTheyWon(char letter) {\n\t\tKey partitionkey = mypart.getPartsKey(letter);\n\t\tif (partitionkey == null) {\n\t\t\twinstatus = true;\n\t\t\treturn 0;\n\t\t} else if (partitionkey.getCount() > 0) {\n\t\t\tgamekey.addletters(partitionkey);\n\t\t\treturn partitionkey.getCount();\n\t\t} else {\n\t\t\tgcount -= 1;\n\t\t\treturn -1;\n\t\t}\n\t}\n}\n"}}},{"rowIdx":917,"cells":{"language":{"kind":"string","value":"Python"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2347,"string":"2,347"},"score":{"kind":"number","value":2.625,"string":"2.625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"import importFile\nimport kmeans\nimport bisecting_kmeans\nimport fuzzyCmeans\nimport utils\nfrom sklearn import metrics\nimport sys\n\n\ndef main(algorithm, data, cl_labels, min_k, max_k, max_iterations, epsilon):\n results, silhouette, chs, ssws, ssbs, ars, hom, comp = [], [], [], [], [], [], [], []\n membership, centroids, labels = [], [], []\n\n for c in range(min_k, max_k + 1):\n if algorithm == 'kmeans':\n labels, centroids = kmeans.kmeans(data, c)\n elif algorithm == 'bisecting_kmeans':\n labels, centroids = bisecting_kmeans.bisecting_kmeans(data, c)\n elif algorithm == 'fuzzy_cmeans':\n membership, centroids = fuzzyCmeans.execute(data, max_iterations, c, epsilon)\n labels = fuzzyCmeans.get_labels(len(data), membership)\n\n silhouette.append((c, metrics.silhouette_score(data, labels, metric='euclidean')))\n chs.append((c, metrics.calinski_harabaz_score(data, labels)))\n ssws.append((c, utils.get_ssw(data, centroids, labels)))\n ssbs.append((c, utils.get_ssb(centroids)))\n ars.append((c, metrics.adjusted_rand_score(cl_labels, labels)))\n hom.append((c, metrics.homogeneity_score(cl_labels, labels)))\n comp.append((c, metrics.completeness_score(cl_labels, labels)))\n\n results.append((\"Silhouette\", \"\", zip(*silhouette)[0], \"\", zip(*silhouette)[1], 333, \"blue\"))\n results.append((\"Calinski-Harabaz Index\", \"\", zip(*chs)[0], \"\", zip(*chs)[1], 334, \"blue\"))\n results.append((\"Intra cluster Variance\", \"\", zip(*ssws)[0], \"\", zip(*ssws)[1], 331, \"blue\"))\n results.append((\"Inter cluster Variance\", \"\", zip(*ssbs)[0], \"\", zip(*ssbs)[1], 332, \"blue\"))\n results.append((\"Adjusted Rand Index\", \"\", zip(*ars)[0], \"\", zip(*ars)[1], 335, \"orange\"))\n results.append((\"Homogeneity\", \"\", zip(*hom)[0], \"\", zip(*hom)[1], 336, \"orange\"))\n results.append((\"Completeness\", \"\", zip(*comp)[0], \"\", zip(*comp)[1], 337, \"orange\"))\n\n print(labels)\n utils.plot_results(results, algorithm)\n\n\narguments = sys.argv\nfile_name = arguments[1]\nclass_name = arguments[2]\nalgo = arguments[3]\nminimum_k = int(arguments[4])\nmaximum_k = int(arguments[5])\nmax_iter = int(arguments[6])\nepsilon_ = float(arguments[7])\n\nda, classif = importFile.read_file(file_name, class_name)\nmain(algo, da, classif, minimum_k, maximum_k, max_iter, epsilon_)\n"}}},{"rowIdx":918,"cells":{"language":{"kind":"string","value":"Java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":427,"string":"427"},"score":{"kind":"number","value":2.703125,"string":"2.703125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package com.saptar.dijkstra.driver;\r\n\r\nimport com.saptar.warshallflyod.engine.WarshallFlyod;\r\n\r\npublic class WarshallFlyodDriver {\r\n\tfinal static int INF = 99999, V = 4;\r\n\r\n\tpublic static void main(String[] args) {\r\n\t\tint graph[][] = { { 0, 5, INF, 10 }, { INF, 0, 3, INF },\r\n\t\t\t\t{ INF, INF, 0, 1 }, { INF, INF, INF, 0 } };\r\n\t\tWarshallFlyod a = new WarshallFlyod();\r\n\r\n\t\t// Print the solution\r\n\t\ta.flyodWarshal(graph);\r\n\t}\r\n}\r\n"}}},{"rowIdx":919,"cells":{"language":{"kind":"string","value":"Markdown"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":381,"string":"381"},"score":{"kind":"number","value":2.578125,"string":"2.578125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"# myASR\nFinal project for EE516 PMP at UW. Matlab implementation of a simple speaker independent, isolated word, whole-word model, single Gaussian per state, diagonal covariance Gaussian, automatic speech recognition (ASR) system, using the ten-word vocabulary W = {“zero”, “one”, “two”, “three”, ... \"nine\"}.\n\nSee FinalProjectWriteUp.pdf for further information. \n"}}},{"rowIdx":920,"cells":{"language":{"kind":"string","value":"C#"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":498,"string":"498"},"score":{"kind":"number","value":3.078125,"string":"3.078125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace ConsoleApp.Decorator\n{\n class ConcreteDecoratorB:Decorator\n {\n public override double Operation(double Prices)\n {\n Prices = Prices * 0.5;\n AddedBehavior();\n Console.WriteLine(\"打5折后值为:\" + Prices);\n return base.Operation(Prices);\n }\n private void AddedBehavior() {\n //本类独有的方法,区别于\n }\n }\n}\n"}}},{"rowIdx":921,"cells":{"language":{"kind":"string","value":"Python"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":16765,"string":"16,765"},"score":{"kind":"number","value":3.265625,"string":"3.265625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"import numpy as np\nimport cPickle as pickle\n\ndef _list2UT(l, N):\n \"\"\"Return a list of the rows of an NxN upper triangular\"\"\"\n mat = []\n start = 0\n for i in range(N):\n mat.append(l[start:start+N-i])\n start += N-i\n return mat\n\ndef _UT2list(m):\n \"\"\"Return the elements of an NxN upper triangular in row major order\"\"\"\n return np.array([item for thing in m for item in thing])\n \ndef _unsort(l, ind):\n \"\"\"Scramble and return a list l by indexes ind\"\"\"\n l0 = np.zeros(len(l))\n for i, x in zip(ind, l):\n l0[i]=x\n return l0\n\ndef _symmetrize(A):\n \"\"\"Form a symmetric matrix out of a list of upper triangle elements\n \n Example:\n >>> A = [[0, 1, 2], [3, 4], [5]]\n >>> symmetrize(A)\n array([[ 0., 1., 2.],\n [ 1., 3., 4.],\n [ 2., 4., 5.]])\n \"\"\"\n N = len(A)\n As = np.zeros((N, N))\n for i, t in enumerate(A):\n As[i, i:]=t\n return As + As.T - np.diag(As.diagonal())\n \ndef _tile_arrays(A):\n \"\"\"Take a symmetric array, A, size N x N, where N is even and return\n an array [ N x N ; N - 1 ]\n [ N - 1 ; A[1, 1] ]\n such that the lower to exploit symmetries.\n \n Example (N=2): \n >>> A = array([[0, 1, 2],\n >>> ... [1, 3, 4],\n >>> ... [2, 4, 6]])\n >>> tile_arrays(tmp)\n array([[ 0., 1., 2., 1.],\n [ 1., 3., 4., 3.],\n [ 2., 4., 6., 4.],\n [ 1., 3., 4., 3.]])\n \"\"\" \n \n N = 2*(np.shape(A)[0]-1) \n A_ref = np.zeros((N,N))\n A_ref[:N/2+1,:N/2+1]=A\n A_ref[N/2:,:N/2+1] = A_ref[N/2:0:-1,:N/2+1]\n A_ref[:,N/2:] = A_ref[:,N/2:0:-1]\n return A_ref\n \ndef _list_to_fft_mat(lis, index, N):\n lis = _unsort(lis, index)\n mat = _list2UT(lis, N/2+1)\n mat = _symmetrize(mat) # Make use of symmetries to\n mat = _tile_arrays(mat) # to construct the whole array.\n return mat\n \ndef form_wl(N):\n #fwl = 10*N\n fwl = 6000.\n wl = np.array([[fwl/np.sqrt(i**2+j**2) if (i!=0 or j!=0) else 16000 \n for i in range(j, N)] \n for j in range(N)])\n return _symmetrize(wl)\n \ndef yield_wl(i, j, fwl=6000):\n if i == j == 0:\n return 16000\n else:\n return fwl/np.sqrt(i**2+j**2)\n \ndef prop(u, d, k):\n \"\"\"Return the propagator for a layer of depth d and viscosity u with a \n harmonic load of order k\n \n As defined in Cathles 1975, p41, III-12.\n \"\"\"\n y = k*d\n s = np.sinh(y)\n c = np.cosh(y)\n cp = c + y*s\n cm = c - y*s\n sp = s + y*c\n sm = s - y*c\n s = y*s\n c = y*c\n \n return np.array([[cp, c, sp/u, s/u], \n [-c, cm, -s/u, sm/u], \n [sp*u, s*u, cp, c], \n [-s*u, sm*u, -c, cm]])\n \ndef exp_decay_const(earth, i, j):\n \"\"\"Return the 2D exponential decay constant for order harmonic unit loads. \n \n Parameters\n ----------\n earth - the earth object containing the parameters...\n i, j (int) - the x, y order numbers of the harmonic load\n \n Returns\n -------\n tau - the exponential decay constant for harmonic load i,j, in yrs\n \n The resulting decay, dec(i, j) = 1-np.exp(elapsed_time * 1000./tauc(i, j)),\n along with lithospheric filter can be returned using earth.get_resp.\n \"\"\"\n wl = yield_wl(i, j, fwl=600*10) # wavelength\n ak = 2*np.pi/wl # wavenumber\n \n # ----- Interior to Surface integration ----- #\n # uses propagator method from Cathles 1975\n \n # initialize two interior boundary vectors\n # assuming solution stays finite in the substratum (Cathles 1975, p41)\n cc = np.array([[1., 0., 1., 0.], \n [0., 1., 0., 1.]])\n \n # Determine the necessary start depth (start lower for longer wavelengths)\n # to solve a roundoff problem with the matrix method.\n #TODO look into stability problem here\n if wl < 40:\n lstart = 9\n elif wl < 200:\n lstart = 6\n elif wl < 500:\n lstart = 4\n else:\n lstart = 0\n \n # integrate from starting depth to surface, layer by layer\n for dd, uu, in zip(earth.d[lstart:], earth.u[lstart:]):\n p = prop(uu, dd, ak)\n for k, c in enumerate(cc):\n cc[k,:] = p.dot(c)\n \n # initialize the inegration constants\n x = np.zeros(2)\n # solve for them, assuming 1 dyne normal load at surface\n x[0] = cc[1,2]/(cc[0,2]*cc[1,3]-cc[0,3]*cc[1,2])\n x[1] = -cc[0,2]/(cc[0,2]*cc[1,3]-cc[0,3]*cc[1,2])\n \n # multiply into the solution\n for k in range(2):\n cc[k,:]=x[k]*cc[k,:]\n # form the final solution\n cc = np.sum(cc, axis=0)\n \n # As cc[1] gives the surface velocity, the exponential time constant is \n # its reciprocal (see Cathles 1975, p43)\n # 1955600 = 2/rho (~3.313) /g (~9.8) * (1/pi*1e8) unit conversion to years\n tau = 1955600.*ak/cc[1]\n \n return tau\n\nclass FlatEarthBase(object):\n \"\"\"A Base class for 2D, flat earth models. Provides methods for saving,\n adding descriptions, and returning response.\n\n User must define a method for generating taus, \n \"\"\"\n def __init__(self):\n self.taus = None\n self.ak = None\n self.alpha = None\n self.index = None\n self.N = None\n\n def __call__(self, t_dur):\n return self.get_resp(t_dur)\n \n def save(self, filename):\n pickle.dump(self, open(filename, 'wb'))\n\n def get_resp(self, t_dur):\n \"\"\"Calculate and return earth response to a unit load in an fft_mat.\n \n Parameters\n ----------\n t_dur (float) - the duration, in cal ka BP, of applied load\n \"\"\" \n # Convert tau list to fft matrix\n taus = _list_to_fft_mat(self.taus, self.index, self.N)\n \n resp = (1-np.exp(t_dur/taus))/self.alpha\n return resp\n\n def set_N(self, N):\n self.N = N\n\nclass EarthNLayer(FlatEarthBase):\n \"\"\"Return the isostatic response of a 2D earth with n viscosity layers.\n \n The response is calculated from a viscous profile overlain by an elastic\n lithosphere in the fourier domain.\n \"\"\"\n \n def __init__(self, u=None, d=None, fr23=10., g=9.8, rho=3.313):\n if u is None:\n self.u = np.array([1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,0.018])\n else:\n self.u = u\n if d is None:\n self.d = np.array([400.,300.,300.,300.,300.,300.,\n 300.,200.,215.,175.,75. ])\n else:\n self.d = d\n \n self.NLayers = len(self.u)\n self.fr23=fr23\n self.g=g\n self.rho=rho\n \n def reset_params_list(self, params, arglist):\n \"\"\"Set the full mantle rheology and calculate the decay constants.\n\n self.N must have been set already.\n \"\"\"\n us = ds = fr23 = N = None\n i=0\n if 'us' in arglist:\n us = params[i:i+self.NLayers]\n i += self.NLayers\n if 'ds' in arglist:\n ds = params[i:i+self.NLayers]\n i += self.NLayers\n if 'fr23' in arglist:\n fr23 = params[i]\n i += 1\n if 'N' in arglist:\n N = params[i]\n\n self.reset_params(us, ds, fr23, N)\n \n def reset_params(self, us=None, ds=None, fr23=None, N=None): \n if us is not None: self.u = us\n if ds is not None: self.d = ds\n self.fr23 = fr23 or self.fr23\n N = N or self.N\n self.calc_taus(N)\n\n def set_taus(self, taus):\n self.taus=taus\n \n def calc_taus(self, N=None):\n \"\"\"Generate and store a list of exponential decay constants.\n \n The procedure sets class data: \n N (the maximum order number calculated)\n taus (decay constants by increasing wavenumber)\n ak (wavenumbers in increasing order)\n index (the sorting key to reorder taus to increasing wavenumber)\n alpha (the lithospheric filter values in FFTmat format)\n\n Parameters\n ----------\n N (int) - the maximum order number. Resulting earth parameters ak,\n taus, and alpha will be size NxN when in FFTmat format.\n\n For description of formats, see help(_list_to_fft_mat)\n \"\"\"\n self.N = N or self.N\n taus = [[exp_decay_const(self, i, j) for i in xrange(j, N/2+1)] \n for j in xrange(N/2+1)]\n #TODO Generalize to arbitrary wavelengths using GridObject?\n wl = np.array([[6000/np.sqrt(i**2+j**2) if (i!=0 or j!=0) else 16000 \n for i in range(j, N/2+1)] \n for j in range(N/2+1)])\n wl = _UT2list(wl)\n self.ak = 2*np.pi/np.array(wl)\n \n # Sort by increasing order number\n self.index = range(len(self.ak))\n self.index.sort(key=self.ak.__getitem__)\n self.ak = self.ak[self.index]\n self.taus = _UT2list(taus)[self.index]*1e-3 # and convert to kyrs\n \n # the Lithosphere filter, sorted by wave number\n # factor of 1e8 is for unit conversion\n self.alpha = 1.+((self.ak)**4)*self.fr23/self.g/self.rho*1e8\n\n # Augment the decay times by the Lithosphere filter\n self.taus = self.taus/self.alpha \n \n # Turn the Lithosphere filter and taus into a matrix that matches the \n # frequencey matrix from an NxN fft.\n self.alpha = _list_to_fft_mat(self.alpha, self.index, self.N)\n \n \nclass EarthTwoLayer(FlatEarthBase):\n \"\"\"Return the isostatic response of a flat earth with two layers.\n \n The response is calculated analytically in the fourier domain from a\n uniform mantle of viscosity u overlain by an elastic lithosphere with\n flexural rigidty fr23.\n \"\"\"\n \n def __init__(self, u, fr23, g=9.8, rho=3.313):\n self.u = u\n self.fr23 = fr23\n self.g = g\n self.rho = rho\n\n def reset_params_list(self, params, arglist):\n params = dict(zip(arglist, xs))\n self.reset_params(params)\n\n def reset_params(self, u=None, fr23=None, N=None):\n self.u = u or self.u\n self.fr23 = fr23 or self.fr23\n N = N or self.N\n self.calc_taus(N)\n\n def calc_taus(self, N=None):\n \"\"\"Generate and store a list of exponential decay constants.\n \n The procedure sets class data: \n N (the maximum order number calculated)\n taus (decay constants in flattend upper diagonal list)\n ak (wavenumbers in increasing order)\n index (the sorting key to reorder taus to increasing wavenumber)\n alpha (the lithospheric filter values in FFTmat format)\n\n Parameters\n ----------\n N (int) - the maximum order number. Resulting earth parameters ak,\n taus, and alpha will be size NxN when in FFTmat format.\n\n For description of formats, see help(_list_to_fft_mat)\n \"\"\"\n N = N or self.N\n \n #TODO Generalize to arbitrary wavelengths \n wl = np.array([[6000/np.sqrt(i**2+j**2) if (i!=0 or j!=0) else 16000 \n for i in range(j, N/2+1)] \n for j in range(N/2+1)])\n wl = _UT2list(wl)\n self.ak = 2*np.pi/np.array(wl)\n\n # Sort by increasing order number\n self.index = range(len(self.ak))\n self.index.sort(key=self.ak.__getitem__)\n self.ak = self.ak[self.index]\n\n self.taus = -2*self.u*self.ak/self.g/self.rho\n # Unit conversion so result is in kyrs:\n # u in Pa s=kg/m s, ak in 1/km, g in m/s2, rho in g/cc\n # and np.pi*1e7 s/yr\n self.taus = self.taus*(1./np.pi)*1e5\n\n \n # the Lithosphere filter, sorted by wave number\n # factor of 1e8 is for unit conversion\n self.alpha = 1.+((self.ak)**4)*self.fr23/self.g/self.rho*1e8\n \n # Augment the decay times by the Lithosphere filter\n self.taus = self.taus/self.alpha \n \n # Turn the Lithosphere filter and taus into a matrix that matches the \n # frequencey matrix from an NxN fft.\n self.alpha = _list_to_fft_mat(self.alpha, self.index, self.N)\n\nclass EarthThreeLayer(FlatEarthBase):\n \"\"\"Return the isostatic response of a flat earth with three layers.\n \n The response is calculated analytically in the fourier domain from a\n two layer mantle whose lower layer, of viscosity u1, is overlain layer\n of viscosity u2 and width h, which in turn is overlain by an elastic\n lithosphere with flexural rigidty fr23.\n \"\"\"\n \n def __init__(self, u1, u2, fr23, h, g=9.8, rho=3.313):\n self.g = g\n self.rho = rho\n self.u1 = u1\n self.u2 = u2\n self.fr23 = fr23\n self.h = h\n\n def reset_params_list(self, params, arglist):\n params = dict(zip(arglist, xs))\n self.reset_params(params)\n\n def reset_params(self, u1=None, u2=None, fr23=None, h=None, N=None):\n self.u1 = u1 or self.u1\n self.u2 = u2 or self.u2\n self.fr23 = fr23 or self.fr23\n self.h = h or self.h\n N = N or self.N\n self.calc_taus(N)\n\n def get_params(self):\n return [self.u1, self.u2, self.fr23, self.h]\n\n def calc_taus(self, N):\n \"\"\"Generate and store a list of exponential decay constants.\n \n The procedure sets class data: \n N (the maximum order number calculated)\n taus (decay constants in flattend upper diagonal list)\n ak (wavenumbers in increasing order)\n index (the sorting key to reorder taus to increasing wavenumber)\n alpha (the lithospheric filter values in FFTmat format)\n\n Parameters\n ----------\n N (int) - the maximum order number. Resulting earth parameters ak,\n taus, and alpha will be size NxN when in FFTmat format.\n\n For description of formats, see help(_list_to_fft_mat)\n \"\"\"\n self.N = N\n \n #TODO Generalize to arbitrary wavelengths \n wl = np.array([[6000/np.sqrt(i**2+j**2) if (i!=0 or j!=0) else 16000 \n for i in range(j, N/2+1)] \n for j in range(N/2+1)])\n wl = _UT2list(wl)\n self.ak = 2*np.pi/np.array(wl)\n\n # Sort by increasing order number\n self.index = range(len(self.ak))\n self.index.sort(key=self.ak.__getitem__)\n self.ak = self.ak[self.index]\n \n # Cathles (1975) III-21\n c = np.cosh(self.ak*self.h)\n s = np.sinh(self.ak*self.h)\n u = self.u2/self.u1\n ui = 1./u\n r = 2*c*s*u + (1-u**2)*(self.ak*self.h)**2 + ((u*s)**2+c**2)\n r = r/((u+ui)*s*c + self.ak*self.h*(u-ui) + (s**2+c**2))\n\n r = 2*c*s*u + (1-u**2)*(self.ak*self.h)**2 + ((u*s)**2+c**2)\n r = r/((u+ui)*s*c + self.ak*self.h*(u-ui) + (s**2+c**2))\n\n self.taus = -2*self.u1*self.ak/self.g/self.rho*r\n # Unit conversion so result is in kyrs:\n # u in Pa s=kg/m s, ak in 1/km, g in m/s2, rho in g/cc\n # and np.pi*1e7 s/yr\n self.taus = self.taus*(1./np.pi)*1e5\n \n # the Lithosphere filter, sorted by wave number\n # factor of 1e8 is for unit conversion\n self.alpha = 1.+((self.ak)**4)*self.fr23/self.g/self.rho*1e8\n \n # Augment the decay times by the Lithosphere filter\n self.taus = self.taus/self.alpha \n \n # Turn the Lithosphere filter and taus into a matrix that matches the \n # frequencey matrix from an NxN fft.\n self.alpha = _list_to_fft_mat(self.alpha, self.index, self.N)\n \n\ndef check_k(earth):\n \"\"\"Check whether different 2D k matrices are identical, useful for\n debugging.\n \"\"\"\n N = earth.N\n\n wl = form_wl(N/2+1)\n wl = _tile_arrays(wl)\n ak_wl = 2*np.pi/wl\n\n ki = np.reshape(np.tile(\n np.fft.fftfreq(N, 6000/(2*np.pi)/N), N), (N, N))\n ak_fft = np.sqrt(ki**2 + ki.T**2) \n ak_fft[0,0] = 2*np.pi/16000\n\n ak_ea = _list_to_fft_mat(earth.ak, earth.index, N)\n\n print \"ak_wl and ak_fft are close: \"+str(np.allclose(ak_wl, ak_fft))\n print \"ak_wl and ak_ea are close: \"+str(np.allclose(ak_wl, ak_ea))\n print \"ak_fft and ak_ea are close: \"+str(np.allclose(ak_fft, ak_ea))\n\n \ndef load(filename):\n return pickle.load(open(filename, 'r'))\n"}}},{"rowIdx":922,"cells":{"language":{"kind":"string","value":"C++"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":7279,"string":"7,279"},"score":{"kind":"number","value":3.046875,"string":"3.046875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#include \n#include \n#include \nusing namespace std;\n\nclass fraction{\npublic:\n long long int x;\n long long int y=1;\n fraction(int a,int b){\n x=a;\n y=b;\n }\n fraction(int c){\n x=c;\n y=1;\n }\n fraction operator + (fraction f){\n long long int tempX=x*f.y+f.x*y;\n long long int tempY=f.y*y;\n return fraction(tempX,tempY);\n };\n fraction operator - (fraction f){\n long long int tempX=x*f.y-f.x*y;\n long long int tempY=f.y*y;\n return fraction(tempX,tempY);\n };\n fraction operator / (fraction f){\n return fraction(x*f.y,y*f.x);\n };\n fraction operator * (fraction f){\n if(f.x==0){\n return fraction(0);\n }\n return fraction(x*f.x,y*f.y);\n };\n bool operator > (fraction f){\n return (double)x/y>(double)f.x/f.y;\n };\n bool operator < (fraction f){\n return (double)x/y<(double)f.x/f.y;\n };\n bool operator == (double a){\n return (double)x/y==a;\n };\n bool operator != (double a){\n return !((double)x/y==a);\n };\n\n};\nvoid sortRows(vector>& matrix,vector>& imatrix,vector& b, int select){\n for(int i=select+1;i=select;j--){\n if(matrix[j+1][select]>matrix[j][select]){\n auto temp = matrix[j];\n matrix[j]=matrix[j+1];\n matrix[j+1]=temp;\n auto itemp = imatrix[j];\n imatrix[j]=imatrix[j+1];\n imatrix[j+1]=itemp;\n auto btemp = b[j];\n b[j]=b[j+1];\n b[j+1]=btemp;\n }\n }\n }\n}\nvoid rowOperations(vector>& matrix,vector>& imatrix,vector& b,int startRow){\n for(int i=startRow+1;i> identityy(vector> matrix,vector> imatrix){\n for(int i=0;i> identity(int n){\n vector> iMatrix;\n for(int i=0;i temp;\n for(int j=0;j>& matrix,vector>& imatrix,vector& b,ifstream& infile){\n int size;\n infile>>size;\n for(int i=0;i v;\n for(int j=0;j>temp;\n while((int)temp!=temp){\n temp*=10;\n bottom*=10;\n }\n v.push_back(fraction(temp,bottom));\n }\n double temp;\n double bottom=1;\n infile>>temp;\n while((int)temp!=temp){\n temp*=10;\n bottom*=10;\n }\n b.push_back(fraction(temp,bottom));\n matrix.push_back(v);\n }\n imatrix=identity(size);\n\n}\nvoid printMatrix(vector> matrix,ofstream& outfile){\n for(int i=0;i solve(vector> matrix,vector b,int arbitrary){\n vector reverseSolution;\n for(int i=0;i=0;i--){\n fraction sum(0);\n int count=0;\n if(reverseSolution.size()!=0)\n for(int j=matrix.size()-1;j>i;j--){\n sum=sum+(reverseSolution[count]*matrix[i][j]);\n count++;\n }\n b[i]=b[i]-sum;\n reverseSolution.push_back(b[i]/matrix[i][i]);\n }\n return reverseSolution;\n}\nvoid findRank(ifstream& infile,ofstream& outfile){\n vector> matrix;\n vector> iMatrix;\n vector b;\n assign(matrix,iMatrix,b,infile);\n for(int i=0;i sol;\n sol=solve(matrix,b,arbitrary);\n int count=1;\n outfile<<\"Arbitrary variables:\";\n for(int i=sol.size()-1;i>=0;i--){\n fraction h=sol[i];\n if(h.x==0){\n outfile<<\"x\"<=0;i--){\n fraction h=sol[i];\n outfile<<\"x\"< sol;\n sol=solve(matrix,b,0);\n for(int i=sol.size()-1;i>=0;i--){\n fraction h=sol[i];\n outfile<\n\nnamespace stlplus\n{\n\n // wild = the wildcard expression\n // match = the string to test against that expression\n // e.g. wildcard(\"[a-f]*\", \"fred\") returns true\n bool wildcard(const std::string& wild, const std::string& match);\n\n}\n\n#endif\n"}}},{"rowIdx":924,"cells":{"language":{"kind":"string","value":"Java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":585,"string":"585"},"score":{"kind":"number","value":2.21875,"string":"2.21875"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package org.intellij.trinkets.problemsView.problems;\r\n\r\nimport org.intellij.trinkets.problemsView.ui.TreeNodeElement;\r\nimport org.jetbrains.annotations.NotNull;\r\n\r\n/**\r\n * Problem.\r\n *\r\n * @author Alexey Efimov\r\n */\r\npublic interface Problem extends TreeNodeElement {\r\n Problem[] EMPTY_PROBLEM_ARRAY = new Problem[]{};\r\n\r\n /**\r\n * Get problem type.\r\n *\r\n * @return Problem type.\r\n */\r\n @NotNull\r\n ProblemType getType();\r\n\r\n /**\r\n * Return fixes for this problem.\r\n *\r\n * @return Fixes array.\r\n */\r\n @NotNull\r\n ProblemFix[] getFixes();\r\n}\r\n"}}},{"rowIdx":925,"cells":{"language":{"kind":"string","value":"JavaScript"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":540,"string":"540"},"score":{"kind":"number","value":2.59375,"string":"2.59375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"'use strict';\n\n// Remove focus away from the hero as the user scrolls by making it darker\nvar $mainHeader = $('main header');\n$mainHeader.css({\n background: 'rgba(0, 0, 0, .5)'\n});\n\nvar scrollFade = function scrollFade() {\n var winheight = $(window).height();\n var scrollTop = $(window).scrollTop();\n var trackLength = winheight - scrollTop;\n var opacity = (1 - trackLength / winheight) / 2;\n\n $mainHeader.css({\n background: 'rgba(0, 0, 0, ' + (.5 + opacity) + ')'\n });\n};\n\n$(window).on('scroll', function () {\n scrollFade();\n});"}}},{"rowIdx":926,"cells":{"language":{"kind":"string","value":"Java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2619,"string":"2,619"},"score":{"kind":"number","value":2.484375,"string":"2.484375"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package org.teiid.core.types.basic;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\n\nimport org.teiid.core.CorePlugin;\nimport org.teiid.core.types.Transform;\nimport org.teiid.core.types.TransformationException;\n\npublic abstract class NumberToNumberTransform extends Transform {\n\n private Class sourceType;\n private Comparable min;\n private Comparable max;\n\n public NumberToNumberTransform(Number min, Number max, Class sourceType) {\n this.sourceType = sourceType;\n if (sourceType == Short.class) {\n this.min = min.shortValue();\n this.max = max.shortValue();\n } else if (sourceType == Integer.class) {\n this.min = min.intValue();\n this.max = max.intValue();\n } else if (sourceType == Long.class) {\n this.min = min.longValue();\n this.max = max.longValue();\n } else if (sourceType == Float.class) {\n this.min = min.floatValue();\n this.max = max.floatValue();\n } else if (sourceType == Double.class) {\n this.min = min.doubleValue();\n this.max = max.doubleValue();\n } else if (sourceType == BigInteger.class) {\n if (min instanceof Double || min instanceof Float) {\n this.min = BigDecimal.valueOf(min.doubleValue()).toBigInteger();\n this.max = BigDecimal.valueOf(max.doubleValue()).toBigInteger();\n } else {\n this.min = BigInteger.valueOf(min.longValue());\n this.max = BigInteger.valueOf(max.longValue());\n }\n } else if (sourceType == BigDecimal.class) {\n if (min instanceof Double || min instanceof Float) {\n this.min = BigDecimal.valueOf(min.doubleValue());\n this.max = BigDecimal.valueOf(max.doubleValue());\n } else {\n this.min = BigDecimal.valueOf(min.longValue());\n this.max = BigDecimal.valueOf(max.longValue());\n }\n } else if (sourceType == Byte.class) {\n } else {\n throw new AssertionError();\n }\n }\n\n @Override\n public Class getSourceType() {\n return sourceType;\n }\n\n protected void checkValueRange(Object value)\n throws TransformationException {\n if (((Comparable)value).compareTo(min) < 0 || ((Comparable)value).compareTo(max) > 0) {\n throw new TransformationException(CorePlugin.Event.TEIID10058, CorePlugin.Util.gs(CorePlugin.Event.TEIID10058, value, getSourceType().getSimpleName(), getTargetType().getSimpleName()));\n }\n }\n\n}\n"}}},{"rowIdx":927,"cells":{"language":{"kind":"string","value":"Python"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":674,"string":"674"},"score":{"kind":"number","value":3.109375,"string":"3.109375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"from typing import List\nintervals=[[1,4], [4,5], [0,1]]\nclass Solution:\n def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n if len(intervals)==0:\n return intervals\n addList=[]\n hold=''\n intervals=sorted(intervals, key=lambda x : x[0])\n for i, v in enumerate(intervals):\n if (i==0):\n hold=v\n else:\n if(hold[1]>=v[0]):\n hold=[hold[0], v[1]]\n elif (hold[1]\n \n name\n \n \n Yao Shengli\n \n\n\n### 区块元素\n***\n**段落和换行**\n\n一个 Markdown 段落是由一个或多个连续的文本行组成,它的前后要有一个以上的空行(空行的定义是显示上看起来像是空的,便会被视为空行。比方说,若某一行只包含空格和制表符,则该行也会被视为空行)。普通段落不该用空格或制表符来缩进。\n\n**标题**\n\n类 Atx 形式则是在行首插入 1 到 6 个 # ,对应到标题 1 到 6 阶,例如:\n\n # 这是 H1\n ## 这是 H2\n ###### 这是 H6\n\n**区块引用**\n\nMarkdown 标记区块引用是使用类似 email 中用 > 的引用方式。如果你还熟悉在 email 信件中的引言部分,你就知道怎么在 Markdown 文件中建立一个区块引用,那会看起来像是你自己先断好行,然后在每行的最前面加上 > :、\n\n >这就是区块引用\n >这也是\n\nMarkdown 也允许你偷懒只在整个段落的第一行最前面加上 > :\n\n >这样写也行\n 也行\n >还真有意思\n 啊\n\n引用的区块内也可以使用其他的 Markdown 语法,包括标题、列表、代码区块等:\n\n > ## 这是一个标题。\n > \n > 1. 这是第一行列表项。\n > 2. 这是第二行列表项。\n > \n > 给出一些例子代码:\n > \n > return shell_exec(\"echo $input | $markdown_script\");\n\n**列表**\n\nMarkdown 支持有序列表和无序列表。\n\n * red\n * green\n * blue\n\n有序列表则使用数字接着一个英文句点\n\n 1. red\n 2. green\n 3. blue\n\n**代码区块**\n\n要在 Markdown 中建立代码区块很简单,只要简单地缩进 4 个空格或是 1 个制表符就可以,例如,下面的输入:\n\n 这是一个普通的锻炼\n 这是一个代码区块\n\n**分隔线**\n\n你可以在一行中用三个以上的星号、减号、底线来建立一个分隔线,行内不能有其他东西。你也可以在星号或是减号中间插入空格。下面每种写法都可以建立分隔线:\n\n * * *\n ***\n *****\n - - -\n ------------------\n\n### 区段元素\n***\n\n**链接**\n\n [链接名字](链接地址)\n\n**强调**\n\n **强调**\n\n**代码**\n\n如果要标记一小段行内代码,你可以用反引号把它包起),例如:\n\n `printf()`\n\n`printf()`测试\n\n如果要在代码区段内插入反引号,你可以用多个反引号来开启和结束代码区段:\n\n ``function a(){\n console.log(\"hellow\")\n }``\n \n```javascript\nfunction a(){\n console.log(\"hellow\")\n }\n```\n\n**图片**\n\n ![Alt text](/path/to/img.jpg)\n\n![](/img/avatar-hux-ny.jpg)"}}},{"rowIdx":929,"cells":{"language":{"kind":"string","value":"JavaScript"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1152,"string":"1,152"},"score":{"kind":"number","value":2.765625,"string":"2.765625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"'use strict'\n\nconst constants = require('./constants')\n\nconst min = 0\n\nconst isNil =\n (val) => typeof val === 'undefined' || val === null\n\nconst isValidInRange =\n (num, max) => !isNaN(num) && num >= min && num <= max\n\nconst isValid = (val, max) => {\n if (!isValidInRange(val, max)) {\n throw new Error(`'${val}' must be a number between ${min} and ${max}`)\n }\n\n return true\n}\n\nconst getTimestampNoMs = (date) =>\n parseInt(date / constants.second, constants.radix10) % constants.uIntMax\n\nconst getNumFromPosInHexString = (hexString, start, length) =>\n parseInt(hexString.substr(start, length), constants.radix16)\n\nconst getMaskedHexString = (length, num) => {\n const hexString = num.toString(constants.radix16)\n\n if (hexString.length === length) {\n return hexString\n }\n\n if (hexString.length !== length) {\n return constants.hexStringIntMask.substring(hexString.length, length) + hexString\n }\n}\n\nconst getIsoFormattedTimestampNoMs = (num) =>\n new Date(num * constants.second).toISOString()\n\nmodule.exports = {\n isNil,\n isValid,\n getTimestampNoMs,\n getNumFromPosInHexString,\n getMaskedHexString,\n getIsoFormattedTimestampNoMs\n}\n"}}},{"rowIdx":930,"cells":{"language":{"kind":"string","value":"PHP"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":729,"string":"729"},"score":{"kind":"number","value":2.609375,"string":"2.609375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT","LicenseRef-scancode-unknown-license-reference"],"string":"[\n \"MIT\",\n \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"');\r\n\r\n$workspacesJson = $mavenlinkApi->getWorkspaces();\r\n$workspacesDecodedJson = json_decode($workspacesJson, true);\r\necho '

Your workspaces:

';\r\necho '
    ';\r\n$totalBudget = 0;\r\n\r\nforeach ($workspacesDecodedJson[results] as $dataItem) {\r\n $workspace = $workspacesDecodedJson[$dataItem[key]][$dataItem[id]];\r\n echo '
  • ' . $workspace[title] . '
    Budget: ' . $workspace[price] . '

  • ';\r\n $totalBudget = $totalBudget + $workspace[price_in_cents];\r\n}\r\necho '
';\r\nsetlocale(LC_MONETARY, 'en_US');\r\necho '

Total Project Budgets: ' . money_format('%i', $totalBudget/100) . '

';\r\n?>\r\n"}}},{"rowIdx":931,"cells":{"language":{"kind":"string","value":"Markdown"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1572,"string":"1,572"},"score":{"kind":"number","value":3.015625,"string":"3.015625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"# Visual_tracking-based-on-CNN-and-RNN\n### Motivation:\nThe key challenge in building a neural net is requirement of humongous training data. The next hindrance to deploy the model in embedded AI device is number of computaions,\nthus demanding a lighter model. We hypothesized that training Re3 visual tracker with less number of videos should also provide an appreciable level of tracking. Our \nhypothesis is backed up by the core idea of Re3, structured to learn tracking through feature level differences between consecutive frames of training videos.\n\n### Model:\nThe training dataset for our project is 15 videos from imagenet video dataset. The model is implemented in Pytorch framework against the author\\`s implementation in tensorflow.\nSince Pytorch is easy for debugging and maintenance, this framework was chosen. \n\n### Prerequisites:\n1. python3.6\n2. PyTorch\n3. OpenCV 3.4.2 or greater\n4. Numpy 1.16 or greater\n\n### Result:\nModel\\`s behaviour of tracking animals can be seen below. \n![](dog.gif)\nHowever, the model could not track a hand thus failing to generalize. Our training videos consist of animals like horse, panda,\netc.., as object of interest. It could be the reason behind model\\`s behaviour on animal videos. Also, the CNN model was frozen during training.\n\n### Future Scope:\n1) Unfreeze the CNN model and see its impact on generalization.\n2) Analyze the behaviour of the model with lighter CNN nets like resnet.\n\n### Authors:\n* **Goushika Janani** -[GoushikaJanani](https://github.com/GoushikaJanani)\n* **Bharath C Renjith** -[cr-bharath](https://github.com/cr-bharath)\n"}}},{"rowIdx":932,"cells":{"language":{"kind":"string","value":"C++"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":550,"string":"550"},"score":{"kind":"number","value":2.953125,"string":"2.953125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#include \n#include \nusing namespace std;\nstatic int a[101][101] = {0};\nint uniquePaths(int m, int n) {\n //m为列,n为行\n if(m<=0 || n<=0) return 0;\n else if(m==1||n==1) return 1;\n else if(m==2 && n==2) return 2;\n else if((m==3 && n==2) || (m==2 && n==3)) return 3;\n if(a[m][n]>0) return a[m][n];\n a[m-1][n] = uniquePaths(m-1,n);\n a[m][n-1] = uniquePaths(m,n-1);\n a[m][n] = a[m-1][n]+a[m][n-1];\n return a[m][n];\n}\n\nint main(){\n cout< userLoginEngine = new LoginEngine<>();\n LoginEngine adminLoginEngine = new LoginEngine<>();\n\n UserCreationPanel userCreationPanel = new UserCreationPanel(userLoginEngine);\n AdminCreationPanel adminCreationPanel = new AdminCreationPanel(adminLoginEngine);\n\n LoginPanel userLoginPanel = new LoginPanel(userLoginEngine);\n LoginPanel adminLoginPanel = new LoginPanel(adminLoginEngine);\n\n loadTestAccounts(userCreationPanel);\n loadTestAccounts(adminCreationPanel);\n userLoginEngine.showAccounts();\n adminLoginEngine.showAccounts();\n\n// Admin admin = adminLoginPanel.login();\n// System.out.println(admin);\n\n AuctionEngine.loadTestCategories();\n CategoriesBrowser.viewCategories(CategoriesBrowser.byName());\n\n }\n\n public static void loadTestAccounts(AccountCreationPanel creationPanel) {\n creationPanel.createAccount(\"qwe@o2.pl\", \"Zaq12wsx\");\n creationPanel.createAccount(\"qwe@o2.pl\", \"Zaq12wsx\");\n creationPanel.createAccount(\"asd@o2.pl\", \"Zaq12wsx\");\n creationPanel.createAccount(\"zxc@o2.pl\", \"Zaq12wsx\");\n creationPanel.createAccount(\"wer@o2.pl\", \"Zaq12wsx\");\n\n }\n}\n"}}},{"rowIdx":934,"cells":{"language":{"kind":"string","value":"Java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":8642,"string":"8,642"},"score":{"kind":"number","value":2.328125,"string":"2.328125"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"/*\r\n * To change this license header, choose License Headers in Project Properties.\r\n * To change this template file, choose Tools | Templates\r\n * and open the template in the editor.\r\n */\r\npackage dipit_game;\r\n\r\nimport dipit_game.GameWindowJFrame;\r\nimport java.io.File;\r\nimport java.io.FileNotFoundException;\r\nimport java.io.FileReader;\r\nimport java.io.IOException;\r\nimport java.io.Reader;\r\nimport ExpandedGame.ExpandedGame_OnKeyPressedImpl;\r\nimport java.lang.reflect.InvocationTargetException;\r\nimport java.lang.reflect.Method;\r\nimport java.net.URL;\r\nimport java.util.ArrayList;\r\nimport java.util.Iterator;\r\nimport java.util.List;\r\nimport java.util.logging.Level;\r\nimport java.util.logging.Logger;\r\nimport org.xeustechnologies.jcl.JarClassLoader;\r\nimport org.xeustechnologies.jcl.JclObjectFactory;\r\nimport org.xeustechnologies.jcl.proxy.CglibProxyProvider;\r\nimport org.xeustechnologies.jcl.proxy.ProxyProviderFactory;\r\n\r\n/**\r\n *\r\n * @author Arch\r\n */\r\npublic class DIPIT_GAME_Main {\r\n\r\n public static final String DIPITPATH = \"C:/Users/Arch/Documents/NetBeansProjects/DIPIT_GAME/build/classes\";\r\n public static World_DIPIT TheWorld;\r\n public static PlayerBase ThePlayer;\r\n public static GameWindowJFrame GameWindow;\r\n static int sizex = 4;\r\n static int sizey = 4;\r\n public static List ConsoleOuts = new ArrayList<>();\r\n\r\n private static final List postWorldGen_listeners = new ArrayList<>();\r\n private static List OnKeyPressed_Listeners = new ArrayList<>();\r\n\r\n public static void add_postWorldGen_Listener(dipit_game.events.PostWorldGenInterface toAdd) {\r\n postWorldGen_listeners.add(toAdd);\r\n }\r\n\r\n public static void add_OnKeyPressed_Listener(dipit_game.events.OnKeyPressedInterface toAdd) {\r\n OnKeyPressed_Listeners.add(toAdd);\r\n }\r\n\r\n public static void OnKeyPressed(java.awt.event.KeyEvent evt) {\r\n OnKeyPressed_Listeners.stream().forEach((hl) -> {\r\n //System.out.println((\"hl(null) : \" + (hl == null)));\r\n hl.OnKeyPressed(evt);\r\n });\r\n }\r\n\r\n public static void main(String[] args) {\r\n URL main = dipit_game.DIPIT_GAME_Main.class.getResource(\"dipit_game.DIPIT_GAME_Main.class\");\r\n if (!\"file\".equalsIgnoreCase(main.getProtocol())) {\r\n throw new IllegalStateException(\"Main class is not stored in a file.\");\r\n }\r\n File path = new File(main.getPath());\r\n System.out.println(\"Classpath? : \" + (path.toString()));\r\n \r\n //\r\n LoadMods();\r\n TheWorld = new World_DIPIT(sizex, sizey);\r\n TheWorld.AddSolidTag(\"W\");\r\n // TODO code application logic here\r\n for (int y = 0; y < sizey; y++) {\r\n for (int x = 0; x < sizex; x++) {\r\n TileBase aNewTile = new TileBase(x, y);\r\n aNewTile.SetRenderCharacter(\"+\");\r\n TheWorld.AddTile(aNewTile);\r\n }\r\n }\r\n postWorldGen_listeners.stream().forEach((hl) -> {\r\n //System.out.println((\"hl(null) : \" + (hl == null)));\r\n hl.ModifyWorldGen(TheWorld);\r\n });\r\n ThePlayer = new PlayerBase(0, 0, TheWorld);\r\n GameWindow = new dipit_game.GameWindowJFrame(TheWorld, ThePlayer);\r\n GameWindow.setVisible(true);\r\n Iterator ConsoleIterator;\r\n ConsoleIterator = ConsoleOuts.iterator();\r\n String output = \"\";\r\n while (ConsoleIterator.hasNext()) {\r\n output = output + \"\\n\" + ConsoleIterator.next();\r\n }\r\n GameWindow.ConsoleOut.setText(output);\r\n Debug_PrintWorldAsString();\r\n }\r\n\r\n public static void Debug_PrintWorldAsString() {\r\n String print_line = \"\";\r\n for (int y = 0; y < sizey; y++) {\r\n print_line += \"\\n\";\r\n for (int x = 0; x < sizey; x++) {\r\n if (ThePlayer.GetPositionX() == x && ThePlayer.GetPositionY() == y) {\r\n print_line += \"[\" + ThePlayer.GetRenderCharacter() + \"]\";\r\n } else {\r\n print_line += \"[\" + TheWorld.GetTile(TheWorld.GetTileAtPosition(x, y)).GetRenderCharacter() + \"]\";\r\n }\r\n }\r\n }\r\n System.out.println(print_line);\r\n }\r\n\r\n private static void LoadMods() {\r\n String referencedModlistString = \"C:\\\\Users\\\\Arch\\\\Documents\\\\NetBeansProjects\\\\referenced\" + \"/modlist.txt\";\r\n String BaseModString = \"C:\\\\Users\\\\Arch\\\\Documents\\\\NetBeansProjects\\\\referenced\";\r\n\r\n ConsoleOuts.add(referencedModlistString);\r\n List ModsToLoad = new ArrayList<>();\r\n try {\r\n FileReader MyReader = new FileReader(referencedModlistString);\r\n ModsToLoad.addAll(GetModsToLoad(MyReader));\r\n } catch (FileNotFoundException ex) {\r\n Logger.getLogger(DIPIT_GAME_Main.class.getName()).log(Level.SEVERE, null, ex);\r\n ConsoleOuts.add(ex.getMessage());\r\n } catch (IOException ex) {\r\n Logger.getLogger(DIPIT_GAME_Main.class.getName()).log(Level.SEVERE, null, ex);\r\n }\r\n //ConsoleOuts.addAll(MyDebugOut);\r\n JarClassLoader jcl = new JarClassLoader();\r\n jcl.add(\"ExpandedGame/\");\r\n ProxyProviderFactory.setDefaultProxyProvider(new CglibProxyProvider());\r\n\r\n //Create a factory of castable objects/proxies\r\n JclObjectFactory factory = JclObjectFactory.getInstance(true);\r\n\r\n //Create and cast object of loaded class\r\n dipit_game.DipitModBase mi = (dipit_game.DipitModBase) factory.create(jcl, \"ExpandedGame.ExpandedMain\");\r\n //Object obj = factory.create(jcl, \"ExpandedGame.ExpandedMain\");\r\n for (String str : ModsToLoad) {\r\n jcl.add(BaseModString + \"\\\\\" + str);\r\n ConsoleOuts.add(BaseModString + \"\\\\\" + str);\r\n //factory.create(jcl, BaseModString + \"\\\\ModLibrary.jar\");\r\n ConsoleOuts.add(\">Attempting to ClassLoad [\" + str + \"] \\n Suceeded = \" + (LoadMod(BaseModString + \"\\\\\" + str)));\r\n }\r\n\r\n }\r\n\r\n private static List GetModsToLoad(FileReader MyReader) throws IOException {\r\n String ModPathBuild = \"\";\r\n List ModsList = new ArrayList<>();\r\n char[] readout = new char[1024];\r\n MyReader.read(readout);\r\n\r\n for (char c : readout) {\r\n //System.out.println(\"> \" + java.lang.Character.toString(c));\r\n // System.out.println(\"=* \" + (c == '*') );\r\n if (c == ';') {\r\n ConsoleOuts.add(\"Adding Build >\" + ModPathBuild.trim());\r\n ModsList.add(ModPathBuild.trim());\r\n ModPathBuild = \"\";\r\n } else {\r\n ModPathBuild = ModPathBuild + java.lang.Character.toString(c);\r\n }\r\n }\r\n\r\n return ModsList;\r\n }\r\n\r\n /**\r\n * Loads the Mod at Binary String point [BinaryModName]. Throws exceptions,\r\n * and continues to run the application if the mod is unable to be loaded\r\n * for whatever reason.\r\n *\r\n * @param BinaryModName the Binary String name of the, [ex. MyMod.ModClass]\r\n * .\r\n * @return [boolean] true if the mod was loaded successfully, false if it\r\n * failed for whatever reason.\r\n */\r\n private static boolean LoadMod(String BinaryModName) {\r\n Class ModClass = null;\r\n Method method = null;\r\n try {\r\n Class ModClass_ = ClassLoader.getSystemClassLoader().loadClass(BinaryModName);\r\n ModClass = ModClass_;\r\n } catch (ClassNotFoundException ex) {\r\n Logger.getLogger(DIPIT_GAME_Main.class.getName()).log(Level.SEVERE, \"Inable to find Mod @\" + BinaryModName, ex);\r\n }\r\n if (ModClass != null) {\r\n //Get InitMod Method\r\n try {\r\n Method method_ = ModClass.getMethod(\"InitMod\");\r\n method = method_;\r\n } catch (NoSuchMethodException ex) {\r\n Logger.getLogger(DIPIT_GAME_Main.class.getName()).log(Level.CONFIG, \"Mod @\" + BinaryModName + \" has not specified a [InitMod] Method!\", ex);\r\n } catch (SecurityException ex) {\r\n Logger.getLogger(DIPIT_GAME_Main.class.getName()).log(Level.CONFIG, null, ex);\r\n }\r\n //Get Init Mod\r\n try {\r\n method.invoke(null, null);\r\n } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {\r\n Logger.getLogger(DIPIT_GAME_Main.class.getName()).log(Level.SEVERE, null, ex);\r\n }\r\n }\r\n return (ModClass != null);\r\n }\r\n}\r\n"}}},{"rowIdx":935,"cells":{"language":{"kind":"string","value":"Python"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":518,"string":"518"},"score":{"kind":"number","value":4.5,"string":"4.5"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"'''Crie um programa onde o usuário possa digitar sete valores numéricos e cadastre-os em uma\nlista única que mantenha separados os valores pares e ímpares. No final, mostre os valores\npares e ímpares em ordem crescente'''\n\nvalores = [[], []]\nn = 0\nfor i in range(1, 8):\n n = int(input(f'Digite o valor {i}: '))\n if n % 2 == 0:\n valores[0].append(n)\n else:\n valores[1].append(n)\nvalores[0].sort()\nvalores[1].sort()\nprint(f'Valores pares {valores[0]}')\nprint(f'Valores impares {valores[1]}')\n"}}},{"rowIdx":936,"cells":{"language":{"kind":"string","value":"Java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":5135,"string":"5,135"},"score":{"kind":"number","value":2.21875,"string":"2.21875"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package milu.gui.ctrl.schema;\r\n\r\nimport java.util.ResourceBundle;\r\nimport java.sql.SQLException;\r\n\r\nimport javafx.scene.control.SplitPane;\r\nimport javafx.scene.control.Tab;\r\nimport javafx.scene.control.TabPane;\r\nimport javafx.scene.control.Label;\r\nimport javafx.scene.layout.BorderPane;\r\nimport javafx.scene.layout.AnchorPane;\r\nimport javafx.scene.Node;\r\nimport javafx.application.Platform;\r\nimport javafx.event.Event;\r\nimport javafx.geometry.Orientation;\r\n\r\nimport milu.db.MyDBAbstract;\r\n\r\nimport milu.gui.view.DBView;\r\nimport milu.main.MainController;\r\nimport milu.tool.MyGUITool;\r\nimport milu.gui.ctrl.common.inf.ChangeLangInterface;\r\nimport milu.gui.ctrl.common.inf.FocusInterface;\r\nimport milu.gui.ctrl.schema.handle.SelectedItemHandlerAbstract;\r\nimport milu.gui.ctrl.schema.handle.SelectedItemHandlerFactory;\r\n\r\npublic class DBSchemaTab extends Tab\r\n\timplements \r\n\t\tFocusInterface,\r\n\t\tGetDataInterface,\r\n\t\tChangeLangInterface\r\n{\r\n\tprivate DBView dbView = null;\r\n\t\r\n\t// upper pane on SplitPane\r\n\tprivate AnchorPane upperPane = new AnchorPane();\r\n\t\r\n\tprivate SchemaTreeView schemaTreeView = null;\r\n\tprivate TabPane tabPane = null;\r\n\t\r\n\tpublic DBSchemaTab( DBView dbView )\r\n\t{\r\n\t\tsuper();\r\n\t\t\r\n\t\tthis.dbView = dbView;\r\n\t\t\r\n\t\tthis.schemaTreeView = new SchemaTreeView( this.dbView, this );\r\n\t\tthis.tabPane = new TabPane();\r\n\t\t// no tab text & dragging doesn't work well.\r\n\t\t// -----------------------------------------------------\r\n\t\t// Enable tag dragging\r\n\t\t//DraggingTabPaneSupport dragSupport = new DraggingTabPaneSupport();\r\n\t\t//dragSupport.addSupport( this.tabPane );\r\n\t\t\r\n\t\tthis.upperPane.getChildren().add( this.schemaTreeView );\r\n\t\tthis.schemaTreeView.init();\r\n\t\tAnchorPane.setTopAnchor( this.schemaTreeView, 0.0 );\r\n\t\tAnchorPane.setBottomAnchor( this.schemaTreeView, 0.0 );\r\n\t\tAnchorPane.setLeftAnchor( this.schemaTreeView, 0.0 );\r\n\t\tAnchorPane.setRightAnchor( this.schemaTreeView, 0.0 );\r\n\t\t\r\n\t\tSplitPane splitPane = new SplitPane();\r\n\t\tsplitPane.setOrientation(Orientation.VERTICAL);\r\n\t\tsplitPane.getItems().addAll( this.upperPane, this.tabPane );\r\n\t\tsplitPane.setDividerPositions( 0.5f, 0.5f );\r\n\t\t\r\n\t\tBorderPane brdPane = new BorderPane();\r\n\t\tbrdPane.setCenter( splitPane );\r\n\t\t\r\n\t\tthis.setContent( brdPane );\r\n\r\n\t\t// set icon on Tab\r\n\t\tthis.setGraphic( MyGUITool.createImageView( 16, 16, this.dbView.getMainController().getImage(\"file:resources/images/schema.png\") ) );\r\n\t\t\r\n\t\tthis.setAction();\r\n\t\t\r\n\t\tthis.changeLang();\r\n\t\t\r\n\t\tthis.getDataNoRefresh( null );\r\n\t}\r\n\t\r\n\tprivate void setAction()\r\n\t{\r\n\t\tthis.selectedProperty().addListener\r\n\t\t(\r\n\t\t\t(obs,oldval,newVal)->\r\n\t\t\t{\r\n\t\t\t\tif ( newVal == false )\r\n\t\t\t\t{\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tthis.setFocus();\r\n\t\t\t}\r\n\t\t);\r\n\t}\r\n\t\r\n\t/**\r\n\t * set Focus on TreeView\r\n\t */\r\n\t@Override\r\n\tpublic void setFocus()\r\n\t{\r\n\t\t// https://sites.google.com/site/63rabbits3/javafx2/jfx2coding/dialogbox\r\n\t\t// https://stackoverflow.com/questions/20049452/javafx-focusing-textfield-programmatically\r\n\t\t// call after \"new Scene\"\r\n\t\tPlatform.runLater( ()->{ this.schemaTreeView.requestFocus(); System.out.println( \"schemaTreeView focused.\"); } );\r\n\t}\r\n\t\r\n\t// GetDataInterface\r\n\t@Override\r\n\tpublic void getDataNoRefresh( Event event )\r\n\t{\r\n\t\tthis.getSchemaData( event, SelectedItemHandlerAbstract.REFRESH_TYPE.NO_REFRESH );\r\n\t}\r\n\t\r\n\t// GetDataInterface\r\n\t@Override\r\n\tpublic void getDataWithRefresh( Event event )\r\n\t{\r\n\t\tthis.getSchemaData( event, SelectedItemHandlerAbstract.REFRESH_TYPE.WITH_REFRESH );\r\n\t}\r\n\t\r\n\tprivate void getSchemaData( Event event, SelectedItemHandlerAbstract.REFRESH_TYPE refreshType )\r\n\t{\r\n\t\tMyDBAbstract myDBAbs = this.dbView.getMyDBAbstract();\r\n\t\ttry\r\n\t\t{\r\n\t\t\tSelectedItemHandlerAbstract handleAbs = \r\n\t\t\t\tSelectedItemHandlerFactory.getInstance\r\n\t\t\t\t( \r\n\t\t\t\t\tthis.schemaTreeView, \r\n\t\t\t\t\tthis.tabPane, \r\n\t\t\t\t\tthis.dbView,\r\n\t\t\t\t\tmyDBAbs, \r\n\t\t\t\t\trefreshType \r\n\t\t\t\t);\r\n\t\t\tif ( handleAbs != null )\r\n\t\t\t{\r\n\t\t\t\thandleAbs.exec();\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch ( UnsupportedOperationException uoEx )\r\n\t\t{\r\n \t\tMyGUITool.showException( this.dbView.getMainController(), \"conf.lang.gui.common.MyAlert\", \"TITLE_UNSUPPORT_ERROR\", uoEx );\r\n\t\t}\r\n\t\tcatch ( SQLException sqlEx )\r\n\t\t{\r\n\t\t\tMyGUITool.showException( this.dbView.getMainController(), \"conf.lang.gui.common.MyAlert\", \"TITLE_EXEC_QUERY_ERROR\", sqlEx );\r\n\t\t}\r\n\t\tcatch ( Exception ex )\r\n\t\t{\r\n \t\tMyGUITool.showException( this.dbView.getMainController(), \"conf.lang.gui.common.MyAlert\", \"TITLE_MISC_ERROR\", ex );\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**************************************************\r\n\t * Override from ChangeLangInterface\r\n\t ************************************************** \r\n\t */\r\n\t@Override\t\r\n\tpublic void changeLang()\r\n\t{\r\n\t\tMainController mainCtrl = this.dbView.getMainController();\r\n\t\tResourceBundle langRB = mainCtrl.getLangResource(\"conf.lang.gui.ctrl.schema.DBSchemaTab\");\r\n\t\t\r\n\t\t// Tab Title\r\n\t\tNode tabGraphic = this.getGraphic();\r\n\t\tif ( tabGraphic instanceof Label )\r\n\t\t{\r\n\t\t\t((Label)tabGraphic).setText( langRB.getString(\"TITLE_TAB\") );\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tthis.setText( langRB.getString(\"TITLE_TAB\") );\r\n\t\t}\r\n\t\t\r\n\t\tthis.schemaTreeView.changeLang();\r\n\t\tthis.schemaTreeView.refresh();\r\n\t}\r\n}\r\n"}}},{"rowIdx":937,"cells":{"language":{"kind":"string","value":"TypeScript"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3299,"string":"3,299"},"score":{"kind":"number","value":2.953125,"string":"2.953125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["LicenseRef-scancode-unknown-license-reference","MIT"],"string":"[\n \"LicenseRef-scancode-unknown-license-reference\",\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"import * as cormo from 'cormo';\n\nexport function Model(options: { connection?: cormo.Connection; name?: string; description?: string } = {}) {\n const c = cormo.Model({ connection: options.connection, name: options.name, description: options.description });\n return (ctor: typeof cormo.BaseModel) => {\n c(ctor);\n };\n}\n\ninterface ColumnBasicOptions {\n required?: boolean;\n graphql_required?: boolean;\n unique?: boolean;\n name?: string;\n description?: string;\n default_value?: string | number | (() => string | number);\n}\n\nexport function Column(\n options:\n | ({ enum: any } & ColumnBasicOptions)\n | ({ type: cormo.types.ColumnType | cormo.types.ColumnType[] } & ColumnBasicOptions),\n): PropertyDecorator;\nexport function Column(\n options: {\n enum?: any;\n type?: cormo.types.ColumnType | cormo.types.ColumnType[];\n } & ColumnBasicOptions,\n): PropertyDecorator {\n let cormo_type: cormo.types.ColumnType | cormo.types.ColumnType[];\n if (options.enum) {\n cormo_type = cormo.types.Integer;\n } else {\n cormo_type = options.type!;\n }\n const c = cormo.Column({\n default_value: options.default_value,\n name: options.name,\n required: options.required,\n type: cormo_type,\n description: options.description,\n unique: options.unique,\n });\n return (target: object, propertyKey: string | symbol) => {\n c(target, propertyKey);\n };\n}\n\ninterface ObjectColumnOptions {\n type: any;\n required?: boolean;\n description?: string;\n}\n\nexport function ObjectColumn(options: ObjectColumnOptions): PropertyDecorator {\n const c = cormo.ObjectColumn(options.type);\n return (target: object, propertyKey: string | symbol) => {\n c(target, propertyKey);\n };\n}\n\ninterface HasManyBasicOptions {\n type?: string;\n foreign_key?: string;\n integrity?: 'ignore' | 'nullify' | 'restrict' | 'delete';\n description?: string;\n}\n\nexport function HasMany(options: HasManyBasicOptions) {\n const c_options = {\n foreign_key: options.foreign_key,\n integrity: options.integrity,\n type: options.type,\n };\n const c = cormo.HasMany(c_options);\n return (target: cormo.BaseModel, propertyKey: string) => {\n c(target, propertyKey);\n };\n}\n\ninterface HasOneBasicOptions {\n type?: string;\n foreign_key?: string;\n integrity?: 'ignore' | 'nullify' | 'restrict' | 'delete';\n description?: string;\n}\n\nexport function HasOne(options: HasOneBasicOptions) {\n const c_options = {\n foreign_key: options.foreign_key,\n integrity: options.integrity,\n type: options.type,\n };\n const c = cormo.HasOne(c_options);\n return (target: cormo.BaseModel, propertyKey: string) => {\n c(target, propertyKey);\n };\n}\n\ninterface BelongsToBasicOptions {\n type?: string;\n required?: boolean;\n foreign_key?: string;\n description?: string;\n}\n\nexport function BelongsTo(options: BelongsToBasicOptions) {\n const c_options = {\n foreign_key: options.foreign_key,\n required: options.required,\n type: options.type,\n };\n const c = cormo.BelongsTo(c_options);\n return (target: cormo.BaseModel, propertyKey: string) => {\n c(target, propertyKey);\n };\n}\n\nexport function Index(columns: { [column: string]: 1 | -1 }, options?: { name?: string; unique?: boolean }) {\n const c = cormo.Index(columns, options);\n return (ctor: typeof cormo.BaseModel) => {\n c(ctor);\n };\n}\n"}}},{"rowIdx":938,"cells":{"language":{"kind":"string","value":"Shell"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1078,"string":"1,078"},"score":{"kind":"number","value":3.1875,"string":"3.1875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#!/bin/bash\n\nopen ~/Databases/Hackage.sparsebundle\nsleep 5\n\nif ! quickping hackage.haskell.org; then\n exit 1\nfi\n\nsimple-mirror --from=\"http://hackage.haskell.org\" --to=\"/Volumes/Hackage\"\n\nindex=/Volumes/Hackage/00-index.tar.gz\nif [[ -f $index ]]; then\n echo Installing package database from local mirror...\n size=$(gzip -q -l $index | awk '{print $2}')\nelse\n size=0\nfi\n\necho Downloading package database from hackage.haskell.org...\nmkdir -p ~/.cabal/packages/hackage.haskell.org\ncurl -s -o - http://hackage.haskell.org/packages/index.tar.gz \\\n | gzip -dc | pv \\\n > ~/.cabal/packages/hackage.haskell.org/00-index.tar\n\nif [[ -f $index ]]; then\n echo Installing package database from local mirror...\n mkdir -p ~/.cabal/packages/mirror\n gzip -dc $index | pv -s $size \\\n > ~/.cabal/packages/mirror/00-index.tar\nfi\n\n# sleep 5\n#\n# cd /Volumes/Hackage\n#\n# export PATH=$PATH:/usr/local/tools/hackage-server/cabal-dev/bin\n#\n# hackage-server run --port=9010 &\n#\n# sleep 300\n# hackage-mirror -v --continuous mirror.cfg\n"}}},{"rowIdx":939,"cells":{"language":{"kind":"string","value":"PHP"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":786,"string":"786"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"andWhere($alias . '.name' . ' = ' . ':name' )->setParameter('name' , $value['value']->getName());\n\t\treturn true;\n\t}\n\t\n\tpublic function filterByUserId($queryBuilder, $alias, $field, $value){\n\t\tif(!$value['value']){\n\t\t\treturn;\n\t\t}\n\t\t$queryBuilder->andWhere($alias . '.user_id' . ' = ' . ':user_id' )->setParameter('user_id' , $value['value']->getId());\n\t\treturn true;\n\t}\n\t\n}\n"}}},{"rowIdx":940,"cells":{"language":{"kind":"string","value":"Python"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1445,"string":"1,445"},"score":{"kind":"number","value":3.203125,"string":"3.203125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nGiven a directory path, search all files in the path for a given text string\nwithin the 'word/document.xml' section of a MSWord .dotm file.\n\"\"\"\n__author__ = \"mprodhan/yabamov/madarp\"\n\nimport os\nimport argparse\nfrom zipfile import ZipFile\n\ndef create_parser():\n parser = argparse.ArgumentParser(description=\"search for a particular substring within dotm files\")\n parser.add_argument(\"--dir\", default=\".\", help=\"specify the directory to search into \")\n parser.add_argument('text', help=\"specify the text that is being searched for \")\n return parser\n\ndef scan_directory(dir_name, search_text):\n for root, _, files in os.walk(dir_name):\n for file in files:\n if file.endswith(\".dotm\"):\n dot_m = ZipFile(os.path.join(root, file))\n content = dot_m.read('word/document.xml').decode('utf-8')\n if search_file(content, search_text):\n print('Match found in file./dotm_file/' + file)\n print(search_text)\n\n\n\n\ndef search_file(text, search_text):\n for line in text.split('\\n'):\n index = line.find(search_text)\n if index >= 0:\n print(line[index-40:index+40])\n return True\n return False\n\n\ndef main():\n parser = create_parser()\n args = parser.parse_args()\n print(args)\n scan_directory(args.dir, args.text)\n\n\n\nif __name__ == '__main__':\n main()\n"}}},{"rowIdx":941,"cells":{"language":{"kind":"string","value":"Markdown"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2317,"string":"2,317"},"score":{"kind":"number","value":2.828125,"string":"2.828125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"# [Gulp-imagemin](https://www.npmjs.com/package/gulp-imagemin) + [Imagemin-pngquant](https://www.npmjs.com/package/imagemin-pngquant) plugins\n\n## Описание\n\nПлагины для оптимизации изображений\n\n## Install\n\n`npm install --save-dev gulp-imagemin`\n\n`npm install --save-dev imagemin-pngquant`\n\n## Example\n\n***gulp-imagemin***\n```js\nconst gulp = require('gulp');\nconst imagemin = require('gulp-imagemin');\n \ngulp.task('default', () =>\n gulp.src('src/images/*')\n .pipe(imagemin())\n .pipe(gulp.dest('dist/images'))\n);\n```\n\n***imgmin-pngquant***\n```js\nconst imagemin = require('imagemin');\nconst imageminPngquant = require('imagemin-pngquant');\n \nimagemin(['images/*.png'], 'build/images', {use: [imageminPngquant()]}).then(() => {\n console.log('Images optimized');\n});\n```\n\n---\n## Общий пример использования + plugin gulp-cache\n\nБез использования gulp-cache \n```js\nvar imagemin = require('gulp-imagemin'), // Подключаем библиотеку для работы с изображениями\n pngquant = require('imagemin-pngquant'); // Подключаем библиотеку для работы с png\n\ngulp.task('img', function() {\n return gulp.src('app/img/**/*') // Берем все изображения из app\n .pipe(imagemin({ // Сжимаем их с наилучшими настройками\n interlaced: true,\n progressive: true,\n svgoPlugins: [{removeViewBox: false}],\n use: [pngquant()]\n }))\n .pipe(gulp.dest('dist/img')); // Выгружаем на продакшен\n});\n```\n\nВместе с gulp-cache :\n```js\nvar cache = require('gulp-cache'); // Подключаем библиотеку кеширования\n\ngulp.task('img', function() {\n return gulp.src('app/img/**/*') // Берем все изображения из app\n .pipe(cache(imagemin({ // Сжимаем их с наилучшими настройками с учетом кеширования\n interlaced: true,\n progressive: true,\n svgoPlugins: [{removeViewBox: false}],\n use: [pngquant()]\n })))\n .pipe(gulp.dest('dist/img')); // Выгружаем на продакшен\n});\n```"}}},{"rowIdx":942,"cells":{"language":{"kind":"string","value":"Python"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4600,"string":"4,600"},"score":{"kind":"number","value":2.796875,"string":"2.796875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["BSD-3-Clause"],"string":"[\n \"BSD-3-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"\"\"\"Auxiliary functions.\"\"\"\n\ntry:\n import cPickle as pickle\nexcept ImportError:\n import pickle\nimport re\nimport os\n\nfrom SPARQLWrapper import SPARQLWrapper, JSON\n\n\nYAGO_ENPOINT_URL = \"https://linkeddata1.calcul.u-psud.fr/sparql\"\nRESOURCE_PREFIX = 'http://yago-knowledge.org/resource/'\n\n\ndef safe_mkdir(dir_name):\n \"\"\"Checks if a directory exists, and if it doesn't, creates one.\"\"\"\n try:\n os.stat(dir_name)\n except OSError:\n os.mkdir(dir_name)\n\n\ndef pickle_to_file(object_, filename):\n \"\"\"Abstraction to pickle object with the same protocol always.\"\"\"\n with open(filename, 'wb') as file_:\n pickle.dump(object_, file_, pickle.HIGHEST_PROTOCOL)\n\n\ndef pickle_from_file(filename):\n \"\"\"Abstraction to read pickle file with the same protocol always.\"\"\"\n with open(filename, 'rb') as file_:\n return pickle.load(file_)\n\n\ndef get_input_files(input_dirpath, pattern):\n \"\"\"Returns the names of the files in input_dirpath that matches pattern.\"\"\"\n all_files = os.listdir(input_dirpath)\n for filename in all_files:\n if re.match(pattern, filename) and os.path.isfile(os.path.join(\n input_dirpath, filename)):\n yield os.path.join(input_dirpath, filename)\n\n\n# TODO(mili): Is is better a pandas DataFrame\ndef query_sparql(query, endpoint):\n \"\"\"Run a query again an SPARQL endpoint.\n\n Returns:\n A double list with only the values of each requested variable in\n the query. The first row in the result contains the name of the\n variables.\n \"\"\"\n sparql = SPARQLWrapper(endpoint)\n sparql.setReturnFormat(JSON)\n\n sparql.setQuery(query)\n response = sparql.query().convert()\n bindings = response['results']['bindings']\n variables = response['head']['vars']\n result = [variables]\n for binding in bindings:\n row = []\n for variable in variables:\n row.append(binding[variable]['value'])\n result.append(row)\n return result\n\n\ndef download_category(category_name, limit):\n \"\"\"Downloads a single category and stores result in directory_name.\"\"\"\n query = \"\"\"SELECT DISTINCT ?entity ?wikiPage WHERE {\n ?entity rdf:type .\n ?entity ?wikiPage\n } LIMIT %s\"\"\" % (category_name, limit)\n return query_sparql(query, YAGO_ENPOINT_URL)\n\n\ndef get_categories_from_file(category_filename):\n \"\"\"Read categories and ofsets\"\"\"\n with open(category_filename, 'r') as input_file:\n lines = input_file.read().split('\\n')\n return lines\n\n\ndef query_subclasses(category_name, populated=True):\n query = \"\"\"SELECT DISTINCT ?subCategory WHERE {\n ?subCategory rdfs:subClassOf <%s%s> .\n \"\"\" % (RESOURCE_PREFIX, category_name)\n if populated:\n query += \"\"\"\n ?entity rdf:type ?subCategory .\n }\"\"\"\n else:\n query += '}'\n return query_sparql(query, YAGO_ENPOINT_URL)[1:]\n\n\ndef add_subcategories(category_name, graph, ancestors=[]):\n \"\"\"Updates the children categories and level of category name.\n \"\"\"\n def add_ancestor(category_name):\n graph.add_edge(ancestors[-1], category_name, path_len=len(ancestors))\n response = query_subclasses(category_name)\n\n for result in response:\n child_category = result[0].replace(RESOURCE_PREFIX, '')\n if 'wikicat' in child_category:\n continue\n add_subcategories(child_category, graph,\n ancestors=ancestors + [category_name])\n\n if category_name not in graph:\n if len(ancestors):\n add_ancestor(category_name)\n else:\n graph.add_node(category_name)\n return\n\n # We have seen the node before\n if len(graph.predecessors(category_name)) == 0: # There is no ancestor yet.\n if len(ancestors): # it's not the first recursive call\n add_ancestor(category_name)\n else: # There is a previous ancestor\n added = False\n for prev_ancestor in graph.predecessors(category_name):\n if prev_ancestor in ancestors:\n added = True\n if len(ancestors) > graph.get_edge_data(\n prev_ancestor, category_name)['path_len']:\n # The current ancestor has a longer path\n graph.remove_edge(prev_ancestor, category_name)\n add_ancestor(category_name)\n # The new ancestor doesn't overlap with any previous ancestor's path.\n if not added and len(ancestors):\n add_ancestor(category_name)\n"}}},{"rowIdx":943,"cells":{"language":{"kind":"string","value":"C++"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2699,"string":"2,699"},"score":{"kind":"number","value":2.65625,"string":"2.65625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"/*\nID: j316chuck\nPROG: milk3\nLANG: C++\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nconst double Pi=acos(-1.0);\ntypedef long long LL;\n\n#define Set(a, s) memset(a, s, sizeof (a))\n#define Rd(r) freopen(r, \"r\", stdin)\n#define Wt(w) freopen(w, \"w\", stdout)\n\nusing namespace std;\n\nint A, B, C;\nint amountA,amountB, amountC;\nbool possible[21];\nint counter =0;\n\nclass three\n{\n public:\n int first,second, third;\n};\n\nthree paths[10000];\n\nbool checkcycle()\n{\n for(int i =0; i < counter; i++)\n {\n if(paths[i].first==amountA&&paths[i].second==amountB&&paths[i].third==amountC)\n return false;\n }\n return true;\n}\nvoid Recursion()\n{\n if(amountA==0)\n possible[amountC]==true;\n return;\n paths[counter].first=amountA;\n paths[counter].second=amountB;\n paths[counter].third=amountC;\n\n if(checkcycle()==false)\n return;\n if(B=amountA+amountB){\n amountB=amountA+amountB;\n amountA=0;\n Recursion();\n }if(C=amountC+amountA){\n amountC=amountC+amountA;\n amountA=0;\n Recursion();\n }if(A=amountA+amountB){\n amountA=amountA+amountB;\n amountB=0;\n Recursion();\n }if(C=amountB+amountC){\n amountC=amountB+amountC;\n amountB=0;\n Recursion();\n }if(A=amountA+amountC){\n amountA=amountA+amountC;\n amountC=0;\n Recursion();\n }if(B=amountB+amountC){\n amountB=amountB+amountC;\n amountC=0;\n Recursion();\n }\n counter++;\n}\n\nint main()\n{\n Rd(\"milk3.in\");\n //Wt(\"milk3.out\");\n\n cin>>A>>B>>C;\n amountA=0;\n amountB=0;\n amountC=C;\n Recursion();\n for(int i = 0; i < C; i++)\n {\n if(possible[i]==true)\n {\n cout< selectAllBooks(){\n return BookConvertDTO.convertToDTOs(bookService.selectAllBooks());\n }\n\n @GetMapping(\"/books/{id}\")\n public Book selectBookById(@PathVariable long id){\n return bookService.selectBookById(id);\n }\n @PostMapping(\"/books/add\")\n public Book addBook(@RequestBody Book book){\n return bookService.addBook(book);\n }\n\n @DeleteMapping(\"/books/delete/{id}\")\n public void deleteBook(@PathVariable long id){\n bookService.deleteBook(id);\n }\n\n}\n"}}},{"rowIdx":945,"cells":{"language":{"kind":"string","value":"C++"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1879,"string":"1,879"},"score":{"kind":"number","value":2.625,"string":"2.625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#include \"stdafx.h\"\n#include \"CopyFileToDir.h\"\n#include \n#include \n#include \n#include \n\n\n//??????????????(unicode -- > ascll)\n#define WCHAR_TO_CHAR(lpW_Char,lpChar) WideCharToMultiByte(CP_ACP,NULL,lpW_Char,-1,lpChar,_countof(lpChar),NULL,FALSE);\n\n//??????????????(unicode -- > ascll)\n#define CHAR_TO_WCHAR(lpChar,lpW_Char) MultiByteToWideChar(CP_ACP,NULL,lpChar,-1,lpW_Char,_countof(lpW_Char));\n\nusing namespace std;\n\nCopyFileToDir::CopyFileToDir()\n{\n}\n\nbool CopyFileToDir::ReadTXTFile_GetPath(char * PathText,char *Path)\n{\n\n\t//?????\n\tifstream in(PathText);\n\tstring filename;\n\tstring line;\n\n\t//???????????\n\tint num = 0;\n\n\tif (in) // ?и???? \n\t{\n\t\twhile (getline(in, line)) // line?в???????е???з? \n\t\t{\n\t\t\t//???????????vector??\n\t\t\tvecTatgetPath.push_back(line);\n\t\t\tnum++;\n\n\t\t}\n\t}\n\telse // ??и???? \n\t{\n\t\tcout << \"no such file\" << endl;\n\t}\n\tcout << \"???????????\" << num << endl;\n\n\n\tWCHAR W_Dir[MAX_PATH];\n\tWCHAR W_FilePath[MAX_PATH];\n\tWCHAR W_FileName[MAX_PATH];\n\n\n\n\tfor (size_t i = 0; i < vecTatgetPath.size(); i++)\n\t{\n\n\t\tCHAR_TO_WCHAR(Path, W_Dir);\n\t\tCHAR_TO_WCHAR(vecTatgetPath[i].c_str(), W_FilePath);\n\t\t//??????\n\t\tsize_t found = vecTatgetPath[i].find_last_of(\"/\\\\\");\n\t\tCHAR_TO_WCHAR(vecTatgetPath[i].substr(found).c_str(), W_FileName);\n\t\tlstrcat(W_Dir,W_FileName);\n\n\t\tif (!CopyFile(W_FilePath, W_Dir, TRUE))\n\t\t{\n\t\t\t//LastError == 0x50??????????\n\t\t\tif (GetLastError() == 0x50)\n\t\t\t{\n\t\t\t\tprintf(\"???%ls??????????????y/n??\", W_Dir);\n\t\t\t\tif ('y' == getchar())\n\t\t\t\t{\n\t\t\t\t\t//??????????????????????\n\t\t\t\t\tif (!CopyFile(W_FilePath, W_Dir, FALSE))\n\t\t\t\t\t{\n\t\t\t\t\t\tprintf(\"???????????%d\\n\", GetLastError());\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tprintf(\"????????\\n\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprintf(\"%ls ????????\\n\", W_FileName);\n\t\t}\n\n\t}\n\n\n\t\n\n\n\treturn false;\n\n\n}\n\n\nCopyFileToDir::~CopyFileToDir()\n{\n}\n"}}},{"rowIdx":946,"cells":{"language":{"kind":"string","value":"PHP"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1923,"string":"1,923"},"score":{"kind":"number","value":2.671875,"string":"2.671875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"success==false){\n //$everything_OK = false;\n $e_bot = \"Potwierdź, że nie jesteś botem!\"; \n }\n\n if (($everything_OK == true) && $user->save()) {\n\n $user_temporary = $user->authenticate($user->email, $user->password);\n $user->addDefaultCategoriesToDB($user_temporary->id);\n \n $this->redirect('/signup/success');\n\n } else {\n Flash::addMessage('Rejestracja nie powiodła się.', Flash::WARNING);\n\n View::renderTemplate('Signup/new.html', [\n 'user' => $user,\n 'e_rules' => $e_rules,\n 'e_bot' => $e_bot,\n 'rules' => $rules\n ]);\n }\n }\n\n /**\n * Show the signup success page\n *\n * @return void\n */\n\n public function successAction()\n {\n View::renderTemplate('Signup/success.html');\n }\n}\n"}}},{"rowIdx":947,"cells":{"language":{"kind":"string","value":"JavaScript"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":856,"string":"856"},"score":{"kind":"number","value":2.9375,"string":"2.9375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"function piller(){\n this.pos = {}\n this.height = floor(random(100, 250))\n this.width = 60\n this.pos.x = 600\n this.pos.y = 400-this.height\n this.bottom = this.pos.y\n this.space = 150\n this.top = this.pos.y - this.space\n this.speed = 6\n this.pillerbottomImage = pillerbottomImage\n this.pillertopImage = pillertopImage\n\n this.update = function(){\n this.pos.x -= this.speed\n }\n\n this.draw = function(){\n for(i = this.pos.y; i < this.pos.y + this.height;i+=3){\n image(pillerbottomImage,this.pos.x, i, this.width);\n }\n image(pillertopImage,this.pos.x, this.pos.y, this.width);\n \n\n for(i = 0; i+20 < this.top;i+=20){\n image(pillerbottomImage,this.pos.x, i, this.width);\n }\n image(pillertopImage,this.pos.x,this.top - 20, this.width);\n }\n}\n"}}},{"rowIdx":948,"cells":{"language":{"kind":"string","value":"SQL"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":341,"string":"341"},"score":{"kind":"number","value":2.578125,"string":"2.578125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"CREATE TABLE IF NOT EXISTS Items (id INTEGER PRIMARY KEY AUTOINCREMENT, name CHAR);\n\nCREATE TABLE IF NOT EXISTS Purchase (id INTEGER PRIMARY KEY AUTOINCREMENT, date CHAR, invoice CHAR, item CHAR, quantity INTEGER);\n\nCREATE TABLE IF NOT EXISTS Sale (id INTEGER PRIMARY KEY AUTOINCREMENT, date CHAR, invoice CHAR, item CHAR, quantity INTEGER);"}}},{"rowIdx":949,"cells":{"language":{"kind":"string","value":"Ruby"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":189,"string":"189"},"score":{"kind":"number","value":3.625,"string":"3.625"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\r\ndef d n\r\n sum = 0\r\n (1..n/2+1).each {|x|\r\n sum += x if n%x == 0 \r\n }\r\n sum\r\nend\r\nputs d 284\r\ns = 0\r\n(1..10000).each {|x|\r\n y = d(x)\r\n s += x if x!=y && d(d(x))==x \r\n}\r\nputs s\r\n"}}},{"rowIdx":950,"cells":{"language":{"kind":"string","value":"Markdown"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4082,"string":"4,082"},"score":{"kind":"number","value":3.828125,"string":"3.828125"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"```python\n# random variables (no need to import random library)\n\n# Solutions with variables converted to string\n# Make sure you name the solution with part id at the end. e.g. 'solution1' will be solution for part 1.\nsolution1 = \"4^2\"\nsolution2 = \"C(52-5,2) - C(52-5-4,2)\"\nsolution3 = \"C(52-5,2)\"\nsolution4 = \"(C(52-5,2) - C(52-5-4,2) + 4^2) / C(52-5,2)\"\n\n\n# Group all solutions into a list\nsolutions = [solution1, solution2, solution3, solution4]\n\n\n```\n\n\n\nIn Texas Hold'Em, a standard 52-card deck is used. Each player is dealt two cards from the deck face down so that only the player that got the two cards can see them. After checking his two cards, a player places a bet. The dealer then puts 5 cards from the deck face up on the table, this is called the \"board\" or the \"communal cards\" because all players can see and use them. The board is layed down in 3 steps: first, the dealer puts 3 cards down (that is called \"the flop\") followed by two single cards, the first is called \"the turn\" and the second is called \"the river\". After the flop, the turn and the river each player can update their bet. The winner of the game is the person that can form the strongest 5-card hand from the 2 cards in their hand and any 3 of the 5 cards in the board. In previous homework you calculated the probability of getting each 5-card hand.\n\nHere we are interested in something a bit more complex: what is the probability of a particular hand given the cards that are currently available to the player.\n\nThe outcome space in this kind of problem is the set of 7 cards the user has at his disposal after all 5 board cards have been dealt. The size of this space is \\\\\\(|\\\\Omega| = C(52,7)\\\\\\)\n\nSuppose that \\\\\\(A, B\\\\\\) are events, i.e. subsets of \\\\\\(\\\\Omega\\\\\\). We will want to calculate conditional probabilities of the type \\\\\\(P(A|B)\\\\\\). Given that the probability of each set of seven cards is equal to \\\\\\(1/C(52,7)\\\\\\) we get that the conditional probability can be expressed as:\n\n\\\\\\[P(A|B) = \\\\frac{P(A \\\\cap B)}{P(B)} =\n\\\\frac{\\\\frac{|A \\\\cap B|}{|\\\\Omega|}}{\\\\frac{|B|}{|\\\\Omega|}}\n = \\\\frac{|A \\\\cap B|}{|B|} \\\\\\]\n\nTherefore the calculation of conditional probability (for finite sample spaces with uniform distribution) boils down to calculating the ratio between the sizes of two sets.\n\n* Suppose you have been dealt \"4\\\\\\(\\\\heartsuit\\\\\\), 5\\\\\\(\\\\heartsuit\\\\\\)\".\n\n* What is the conditional probability that you will get a straight given that you have been dealt these two cards, and that the flop is \"2\\\\\\(\\\\clubsuit\\\\\\), 6\\\\\\(\\\\spadesuit\\\\\\), K\\\\\\(\\\\diamondsuit\\\\\\)\"?\n - Define \\\\\\(B\\\\\\) as the set {7-card hands that contain these 5 cards already revealed}.\n - Define \\\\\\(A\\\\\\) as the set {7-card hands that contain a straight}.\n The question is asking for \\\\\\(P(A|B)\\\\\\). According to the formula above we need to find \\\\\\(|A\\\\cap B|\\\\\\) and \\\\\\(|B|\\\\\\).\n - In this case \\\\\\(A \\\\cap B\\\\\\) is the set {7-card hands that contain the 5 revealed cards AND contain a straight}. To get a straight, the remaining two cards (turn and river) must either be {7,8} or contain 3. We hence define two subsets within \\\\\\(A \\\\cap B\\\\\\):\n - \\\\\\(S_1\\\\\\): {7-card hands that are in \\\\\\(A \\\\cap B\\\\\\) AND the remaining two cards are 7 and 8, regardless of order}.\n\n \\\\\\(|S_1|=\\\\\\)\n\n [_]\n\n - \\\\\\(S_2\\\\\\): {7-card hands that are in \\\\\\(A \\\\cap B\\\\\\) AND its turn and river contain 3}.\n\n \\\\\\(|S_2| = \\\\\\)\n\n [_]\n\n Because there is no overlap in these two subsets \\\\\\(S_1 \\\\cap S_2 = \\\\emptyset\\\\\\) and these two subsets cover all possible valid hands \\\\\\(A \\\\cap B = S_1 \\\\cup S_2 \\\\\\), by definition \\\\\\(S_1\\\\\\) and \\\\\\(S_2\\\\\\) form a _partition_ of \\\\\\(A \\\\cap B\\\\\\), and we have \\\\\\(|A \\\\cap B| = |S_1| + |S_2|\\\\\\).\n\n - Computing \\\\\\(|B|\\\\\\) should be easy. 5 cards in the hand are already fixed, so we can choose any card as our turn and river from the rest 47 cards.\n\n \\\\\\(|B| = \\\\\\)\n\n [_]\n\n - The conditional probability\n\n \\\\\\(P(A|B) = \\\\frac{P(A \\\\cap B)}{P(B)} = \\\\frac{|A\\\\cap B|}{|B|} = \\\\frac{|S_1|+|S_2|}{|B|}\\\\\\) is\n\n [_]\n\n---\n"}}},{"rowIdx":951,"cells":{"language":{"kind":"string","value":"C++"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1099,"string":"1,099"},"score":{"kind":"number","value":2.84375,"string":"2.84375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"/* \n * File: Alumno.h\n * Author: alulab14\n *\n * Created on 6 de noviembre de 2015, 08:03 AM\n */\n\n/*\n * Nombre: Diego Alonso Guardia Ayala\n * Codigo: 20125849\n */\n\n#ifndef ALUMNO_H\n#define\tALUMNO_H\n\n#include \n#include \n\nclass Alumno {\npublic:\n Alumno();\n void SetCreditos(double creditos);\n double GetCreditos() const;\n void SetPromedio(double promedio);\n double GetPromedio() const;\n void SetSemFin(int semFin);\n int GetSemFin() const;\n void SetAnFin(int anFin);\n int GetAnFin() const;\n void SetSemIn(int semIn);\n int GetSemIn() const;\n void SetAnIn(int anIn);\n int GetAnIn() const;\n void SetNombre(char *);\n void GetNombre(char *) const;\n void SetCodigo(int codigo);\n int GetCodigo() const;\n void SetEspecialidad(char *);\n void GetEspecialidad(char *) const;\nprivate:\n int codigo;\n char nombre[50];\n char especialidad[50];\n int anIn; //Año de inicio\n int semIn; //Semestre que inicio\n int anFin; //Año de egresó\n int semFin; //Semestre que egresó\n double promedio;\n double creditos;\n};\n\n#endif\t/* ALUMNO_H */\n\n"}}},{"rowIdx":952,"cells":{"language":{"kind":"string","value":"Java"},"src_encoding":{"kind":"string","value":"UHC"},"length_bytes":{"kind":"number","value":1125,"string":"1,125"},"score":{"kind":"number","value":3.28125,"string":"3.28125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"import java.util.Scanner;\n\npublic class BFmatch {\n\n\tpublic static void main(String[] args) {\n\t\tScanner sc = new Scanner(System.in);\n\t\t\n\t\tSystem.out.print(\"ؽƮ : \");\n\t\tString s1 = sc.next();\n\t\t\n\t\tSystem.out.print(\" : \");\n\t\tString s2 = sc.next();\n\t\t\n\t\tint idx = bfMatch(s1,s2);\n\t\t\n\t\tif(idx==-1)\n\t\t\tSystem.out.println(\"ؽƮ ϴ.\");\n\t\telse {\n\t\t\tint len=0;\n\t\t\tfor(int i=0; igetFlectiveClass();\n}\n$word = '';\nif(!empty($_POST['word'])) {\n $word=$_POST['word'];\n}\necho '\n\n\n \n\n Генерация словоформ\n\n \n\n \n\n\n\n
\n Введите слово в именительном падеже (пример: адам)
\n \n
\n';\nif(!empty($resultArray)) {\n echo '\n \n \n \n ';\n foreach($resultArray as $res) {\n echo '\n \n \n \n ';\n }\n echo '
Конфигурация слово образованияФорма слова
'.$res['type'].''.$res['word'].'
';\n}\necho '\n\n\n';"}}},{"rowIdx":954,"cells":{"language":{"kind":"string","value":"Java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1051,"string":"1,051"},"score":{"kind":"number","value":3.71875,"string":"3.71875"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package com.test17;\n\nimport java.util.Comparator;\nimport java.util.Scanner;\nimport java.util.TreeSet;\n\nimport com.student.Student;\n\npublic class Demo_StudentMassage {\n\t/*\n\t * 键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按学生总分进行排名\n\t * 1.创建键盘录入对象\n\t * 2.依次录入5名学生信息学生信息,存储在TreeSet集合中\n\t */\n\tpublic static void main(String[] args) {\n\t\tScanner sc=new Scanner(System.in);\n\t\tTreeSet ts=new TreeSet(new Comparator() {\n\t\t\t@Override\n\t\t\tpublic int compare(Student o1, Student o2) {\n\t\t\t\t//按总分从高到低进行比较\n\t\t\t\tint num=o2.getSum()-o1.getSum();\n\t\t\t\treturn num==0 ? 1 : num;\n\t\t\t}\n\t\t});\n\t\twhile(ts.size()<5) {\n\t\t\tString str=sc.nextLine();\n\t\t\tString[] sarr=str.split(\",\"); //使用“,”分割\n\t\t\tint chgrate=Integer.parseInt(sarr[1]);\n\t\t\tint magrate=Integer.parseInt(sarr[2]);\n\t\t\tint engrate=Integer.parseInt(sarr[3]);\n\t\t\tts.add(new Student(sarr[0],chgrate,magrate,engrate));\n\t\t}\n\t\t\tSystem.out.println(ts);\n\t}\n}\n"}}},{"rowIdx":955,"cells":{"language":{"kind":"string","value":"C"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":452,"string":"452"},"score":{"kind":"number","value":3.9375,"string":"3.9375"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"//Program to check whether all digits in a number in ascending order or not\r\n#include\r\n#include\r\nint main()\r\n{\r\n\tint j,n,d,h,flag=1;\r\n\tprintf(\"Enter a number:\");\r\n\tscanf(\"%d\",&n);\r\n\td=floor(log10(n));\r\n\twhile(d>0)\r\n\t{\r\n\t\tj=n/(int)(pow(10,d));\r\n\t\tn=n%(int)(pow(10,d));\r\n\t\th=n/(int)(pow(10,d-1));\r\n\t\tif(j>h)\r\n\t\t{\r\n\t\t\tflag=0;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\td--;\r\n\t}\r\n\tif(flag)\r\n\tprintf(\"Ascending\");\r\n\telse\r\n\tprintf(\"not ascending\");\r\n\treturn 0;\r\n}\r\n"}}},{"rowIdx":956,"cells":{"language":{"kind":"string","value":"TypeScript"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1364,"string":"1,364"},"score":{"kind":"number","value":2.5625,"string":"2.5625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"import { Injectable } from '@angular/core';\n\n@Injectable()\nexport class FavoritoService {\n name = \"_f\";\n\n private favoritos = [];\n\n constructor() { }\n\n listar(){\n if(!this.favoritos || this.favoritos.length == 0){\n let lista = localStorage.getItem(this.name);\n this.favoritos = lista?JSON.parse(lista):[];\n } \n return this.favoritos;\n }\n\n removeFavorito(book){\n if(this.isFavorito(book.id)){\n if(this.favoritos){\n var index = this.favoritos.findIndex(element => element.id == book.id ); \n if(index > -1){\n this.favoritos.splice(index, 1);\n } \n let listaJSON = this.favoritos? JSON.stringify(this.favoritos): null;\n localStorage[this.name] = listaJSON;\n }\n \n }\n }\n\n setFavorito(book){\n if(!this.isFavorito(book.id)){\n this.favoritos.push(book);\n localStorage[this.name] = JSON.stringify(this.favoritos);\n }\n }\n\n isFavorito(id :String){\n let books = this.getFavorito(id);\n\n return books != null && books.length > 0 ? true : false; \n }\n\n getFavorito(id :String){\n return this.listar().filter(element => {\n return element.id == id;\n });\n }\n}"}}},{"rowIdx":957,"cells":{"language":{"kind":"string","value":"C++"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":931,"string":"931"},"score":{"kind":"number","value":2.921875,"string":"2.921875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#include \n#include \n#include \n#include \n\nusing namespace std;\n\nbool compare(const int &a, const int &b)\n{\n\treturn a > b;\n}\n\nint main()\n{\n\tint T, m, n, i, j, k, cnt, index;\n\tstring temp, str;\n\tvector strarr;\n\tvector answerarr;\n\tcin >> T;\n\tfor (i = 1; i <= T; i++) {\n\t\tcin >> m >> n;\n\t\tcin >> str;\n\t\tcnt = m / 4;\n\t\tfor(j = 0; j < cnt; j++) {\n\t\t\tstr = str.substr(m - 1, 1) + str.substr(0, m - 1);\n\t\t\tfor (k = 0; k < 4; k++) \n\t\t\t\tstrarr.push_back(str.substr(k * cnt, cnt));\t\t\n\t\t}\n\t\tfor (j = 0; j < strarr.size(); j++)\n\t\t\tanswerarr.push_back(strtol(strarr[j].c_str(), NULL, 16));\n\t\tsort(answerarr.begin(), answerarr.end(), compare);\n\t\tanswerarr.erase(unique(answerarr.begin(), answerarr.end()), answerarr.end());\n\t\tcout << \"#\" << i << \" \" << answerarr[n - 1] << endl;\n\t\tstrarr.erase(strarr.begin(), strarr.end());\n\t\tanswerarr.erase(answerarr.begin(), answerarr.end());\n\t}\n\n\treturn 0;\n}\n"}}},{"rowIdx":958,"cells":{"language":{"kind":"string","value":"Java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":695,"string":"695"},"score":{"kind":"number","value":2.5625,"string":"2.5625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package schedule;\n\n\nimport javax.servlet.ServletContextListener;\nimport javax.servlet.ServletContextEvent;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.ScheduledExecutorService;\nimport java.util.concurrent.TimeUnit;\n\npublic class MyListener implements ServletContextListener {\n\t\n\tprivate ScheduledExecutorService scheduler;\n\t\n\t@Override\n\tpublic void contextInitialized(ServletContextEvent event) {\n\t\tscheduler = Executors.newSingleThreadScheduledExecutor();\n\t\tscheduler.scheduleAtFixedRate(new MyTask(), 0, 120, TimeUnit.SECONDS);\n\t}\n\t\n\t@Override\n\tpublic void contextDestroyed(ServletContextEvent event) {\n\t\tSystem.out.println(\"shut down\");\n\t\tscheduler.shutdownNow();\n\t}\n}\n"}}},{"rowIdx":959,"cells":{"language":{"kind":"string","value":"PHP"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1884,"string":"1,884"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"\n * @copyright Copyright (c) 2013 http://qingmvc.com\n * @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0\n */\nclass Con01Test extends Base{\n /**\n * \n */\n public function test(){\n \t$res=Container::set('aaa',AAA::class);\n \t$res=Container::set('bbb',BBB::class);\n \t$res=Container::set('closure',function(){\n \t\treturn new BBB();\n \t});\n \t$res=Container::set('ccc',['class'=>CCC::class,'aaa'=>'aaa','bbb'=>'bbb']);\n \t//\n \t$aaa=Container::get('aaa');\n \t$this->assertTrue(is_object($aaa) && $aaa instanceof AAA);\n \t$bbb=Container::get('bbb');\n \t$this->assertTrue(is_object($bbb) && $bbb instanceof BBB);\n \t$func=Container::get('closure');\n \t$this->assertTrue(is_object($func) && $func instanceof BBB);\n \t//实例ccc依赖aaa&bbb\n \t$ccc=Container::get('ccc');\n \t$this->assertTrue(is_object($ccc) && $ccc instanceof CCC);\n \t$this->assertTrue($ccc->aaa===$aaa && $ccc->bbb===$bbb);\n \t//\n \t//$con=Coms::get('container');\n \t//dump(Container::getInstance());\n }\n /**\n * 实例分类\n * \n * @see app/config/main.php\n */\n public function testCat(){\n \t$di=Container::get('M:Sites');\n \t$this->assertTrue(is_object($di) && $di instanceof \\main\\model\\Sites);\n \t$di=Container::get('M:sites');\n \t$this->assertTrue(is_object($di) && $di instanceof \\main\\model\\Sites);\n \t//\n \t$di=Container::get('C:Index');\n \t$this->assertTrue(is_object($di) && $di instanceof \\main\\controller\\Index);\n \t$di=Container::get('C:index');\n \t$this->assertTrue(is_object($di) && $di instanceof \\main\\controller\\Index);\n \t\n }\n}\n?>"}}},{"rowIdx":960,"cells":{"language":{"kind":"string","value":"C++"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":388,"string":"388"},"score":{"kind":"number","value":2.5625,"string":"2.5625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#pragma once\n\n#include \"AbstractMonster.hpp\"\n\nnamespace patterns {\nnamespace abstract_factory {\n\nclass EasyMonster: public AbstractMonster\n{\npublic:\n virtual EasyMonster* clone() override {\n return new EasyMonster();\n }\n virtual std::string text() const override {\n return \"Easy monster\";\n }\n\n virtual ~EasyMonster() { }\n};\n\n} //abstract factory\n} //patterns\n"}}},{"rowIdx":961,"cells":{"language":{"kind":"string","value":"C++"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3610,"string":"3,610"},"score":{"kind":"number","value":3.21875,"string":"3.21875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#include \"LCDHelper.h\"\n#include \n#include \n\nLCDHelper::LCDHelper(Adafruit_RGBLCDShield &lcd) {\n this->lcd = &lcd;\n this->color = VIOLET;\n this->clearDisplay = true;\n this->displayUntil = 0;\n this->nextScrollTime = 0;\n this->scrollIndex = 0;\n}\n\nvoid LCDHelper::printNext(\n const char *row1,\n const char *row2,\n const int color,\n const unsigned long displayUntil) {\n\n this->displayUntil = displayUntil;\n this->color = color;\n\n // Just return if the text hasn't changed\n if (strcmp(this->row1, row1) == 0 && strcmp(this->row2, row2) == 0) {\n return;\n }\n\n strcpy(this->row1, row1);\n strcpy(this->row2, row2);\n this->clearDisplay = true;\n}\n\nvoid LCDHelper::printNextP(\n const char *row1P,\n const char *row2P,\n const int color,\n const unsigned long displayUntil) {\n char row1[strlen_P(row1P) + 1];\n char row2[strlen_P(row2P) + 1];\n strcpy_P(this->row1, row1P);\n strcpy_P(this->row2, row2P);\n printNext(this->row1, this->row2, color, 0);\n}\n\nvoid LCDHelper::maybePrintNext(\n const char *row1,\n const char *row2,\n const int color) {\n\n if (millis() < displayUntil) {\n return;\n }\n\n printNext(row1, row2, color, 0);\n}\n\nvoid LCDHelper::maybePrintNextP(\n const char *row1P,\n const char *row2P,\n const int color) {\n char row1[strlen_P(row1P) + 1];\n char row2[strlen_P(row2P) + 1];\n strcpy_P(row1, row1P);\n strcpy_P(row2, row2P);\n maybePrintNext(row1, row2, color);\n}\n\nvoid LCDHelper::maybeScrollRow(\n char result[LCD_ROW_STR_LENGTH],\n const char *row) {\n const unsigned int rowLen = strlen(row);\n\n // No scroll necessary, copy and return\n if (rowLen < LCD_ROW_LENGTH) {\n copy16(result, row);\n return;\n }\n\n if (millis() >= this->nextScrollTime) {\n this->nextScrollTime = millis() + LCD_SCROLL_DELAY_MS;\n this->scrollIndex++;\n\n // We've scrolled beyond all of the row's content plus the padding, so\n // reset the pointer to 0.\n if (this->scrollIndex >= rowLen + LCD_SCROLL_PADDING) {\n this->scrollIndex = 0;\n }\n }\n\n for (int i = 0; i < LCD_ROW_LENGTH; i++) {\n unsigned int rowIndex = this->scrollIndex + i;\n unsigned char c;\n if (rowIndex >= rowLen) {\n // This is the padding between the last char of the content and the\n // start of the beginning of the content entering from the right of\n // the screen.\n if (rowIndex < rowLen + LCD_SCROLL_PADDING) {\n c = ' ';\n } else {\n // This is the beginning of the content entering from the right\n // of the screen.\n c = row[rowIndex - rowLen - LCD_SCROLL_PADDING];\n }\n } else {\n c = row[rowIndex];\n }\n\n result[i] = c;\n }\n\n result[LCD_ROW_LENGTH] = '\\0';\n}\n\nvoid LCDHelper::copy16(\n char dest[LCD_ROW_STR_LENGTH],\n const char *src) {\n strncpy(dest, src, LCD_ROW_LENGTH);\n dest[min(LCD_ROW_LENGTH, strlen(src))] = '\\0';\n}\n\nvoid LCDHelper::print() {\n if (this->clearDisplay) {\n lcd->clear();\n // Restart scrolling\n this->scrollIndex = -1;\n clearDisplay = false;\n }\n\n char row[LCD_ROW_STR_LENGTH];\n maybeScrollRow(row, this->row1);\n lcd->setCursor(0, 0);\n lcd->print(row);\n\n maybeScrollRow(row, this->row2);\n lcd->setCursor(0, 1);\n lcd->print(row);\n\n lcd->setBacklight(this->color);\n}\n\nvoid LCDHelper::screenOff() {\n this->lcd->clear();\n this->lcd->setBacklight(BLACK);\n this->lcd->noDisplay();\n}\n\nvoid LCDHelper::screenOn() {\n this->lcd->display();\n}"}}},{"rowIdx":962,"cells":{"language":{"kind":"string","value":"C"},"src_encoding":{"kind":"string","value":"ISO-8859-1"},"length_bytes":{"kind":"number","value":755,"string":"755"},"score":{"kind":"number","value":3.5,"string":"3.5"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#include\n#include\n#include\n#include\n\n/*\n10 - So conhecidas as notas de um determinado aluno em uma determinada disciplina\ndurante um semestre letivo: p1, p2, t1 e t2 com pesos respectivamente 3, 5, 1, e 1. So\nconhecidos tambm o total de aulas desta disciplina e a quantidade de aulas que o aluno\nassistiu. Elaborar um programa para calcular e exibir a mdia do aluno e a sua frequncia.\n*/\n\nmain(){\n\tsetlocale(LC_ALL, \"Portuguese\");\n\tfloat p1=3,p2=5,t1=1,t2=1,media;\n\tint faulas,aulas=100;\n\t\n\tprintf(\"Informe o nmeros de aulas que voc frequentou: \");\n\tscanf(\"%d\", &faulas);\n\tmedia=(p1+p2+t1+t2)/4;\n\tsystem(\"cls\");\n\tprintf(\"A frequencia do aluno de %d/100, e a mdia das notas %.2f\",faulas,media);\n}\n"}}},{"rowIdx":963,"cells":{"language":{"kind":"string","value":"Java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1193,"string":"1,193"},"score":{"kind":"number","value":2.734375,"string":"2.734375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)\nimport java.util.ArrayList;\n/**\n * Write a description of class Obstacles here.\n * \n * @author (your name) \n * @version (a version number or a date)\n */\npublic class Obstacles extends Actor implements ISubject\n{\n private ObstacleType obstacle = null;\n\n IObserver gameLogic = null;\n GameLogic gl = GameLogic.getGameLogicInstance();\n \n public void attach(IObserver ob){\n \n }\n public void detach(IObserver ob){\n gameLogic = null;\n }\n public void notifyObserver(){\n notifyGameLogic();\n }\n public Obstacles(ObstacleType obstacle) {\n this.obstacle = obstacle;\n }\n \n public ObstacleType getObstacle() {\n return obstacle;\n }\n\n public void setObstacle(ObstacleType obstacle) {\n this.obstacle = obstacle;\n }\n \n public void notifyGameLogic(){\n \n if(this.getY() == 360 ){\n System.out.println(\"IF--- Notify Obstacle class\");\n gl.update(this,\"obstacle\");\n }\n }\n \n\n \n public void act() {\n } \n \n public void moveRight(){}\n \n public void moveLeft(){} \n}\n"}}},{"rowIdx":964,"cells":{"language":{"kind":"string","value":"Java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":250,"string":"250"},"score":{"kind":"number","value":2.046875,"string":"2.046875"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package slug.soc.game.gameObjects.tiles.faction;\r\n\r\nimport java.awt.Color;\r\n\r\nimport slug.soc.game.gameObjects.tiles.GameTile;\r\n\r\npublic class TileVillage extends GameTile {\r\n\r\n\tpublic TileVillage(Color color) {\r\n\t\tsuper(\"village\", color);\r\n\t}\r\n\r\n}\r\n"}}},{"rowIdx":965,"cells":{"language":{"kind":"string","value":"Java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2393,"string":"2,393"},"score":{"kind":"number","value":3.875,"string":"3.875"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package elementary_Data_Structures_Trees.BinaryTrees;\n\nimport java.util.LinkedList;\nimport java.util.Queue;\nimport java.util.Stack;\n\npublic class BinaryTree {\n\n\tpublic static int startIndex = 0;\n\n\tpublic Node crateBinaryTree(int[] values, Node root, int nullNum) {\n\t\tint value = values[startIndex++];\n\t\t// nullNum means no child\n\t\tif (value == nullNum) {\n\t\t\troot = null;\n\t\t} else {\n\t\t\troot = new Node(value, null, null);\n\t\t\troot.setLeftChild(crateBinaryTree(values, root.getLeftChild(),\n\t\t\t\t\tnullNum));\n\t\t\troot.setRightChild(crateBinaryTree(values, root.getRightChild(),\n\t\t\t\t\tnullNum));\n\t\t}\n\t\treturn root;\n\t}\n\n\tpublic void preOrderTraverse(Node root) {\n\t\tif (!(root == null)) {\n\t\t\tSystem.out.print(\" \" + root.getValue() + \" \");\n\t\t\tpreOrderTraverse(root.getLeftChild());\n\t\t\tpreOrderTraverse(root.getRightChild());\n\t\t}\n\t}\n\n\tpublic void inOrderTraverse(Node root) {\n\t\tif (!(root == null)) {\n\t\t\tinOrderTraverse(root.getLeftChild());\n\t\t\tSystem.out.print(\" \" + root.getValue() + \" \");\n\t\t\tinOrderTraverse(root.getRightChild());\n\t\t}\n\t}\n\n\tpublic void postOrderTraverse(Node root) {\n\t\tif (!(root == null)) {\n\t\t\tpostOrderTraverse(root.getLeftChild());\n\t\t\tpostOrderTraverse(root.getRightChild());\n\t\t\tSystem.out.print(\" \" + root.getValue() + \" \");\n\t\t}\n\t}\n\n\tpublic void breadthFirstSearch(Node root) {\n\t\tif (!(root == null)) {\n\t\t\tQueue bts_Queue = new LinkedList();\n\t\t\tbts_Queue.add(root);\n\t\t\twhile (!bts_Queue.isEmpty()) {\n\t\t\t\tNode currentNode = bts_Queue.poll();\n\t\t\t\tSystem.out.print(\" \" + currentNode.getValue() + \" \");\n\t\t\t\tif (currentNode.getLeftChild() != null) {\n\t\t\t\t\tbts_Queue.offer(currentNode.getLeftChild());\n\t\t\t\t}\n\t\t\t\tif (currentNode.getRightChild() != null) {\n\t\t\t\t\tbts_Queue.offer(currentNode.getRightChild());\n\t\t\t\t}\n\t\t\t}\n\t\t} else\n\t\t\tSystem.out.print(\"Empty Tree\");\n\t}\n\n\tpublic void depthFirstSearch(Node root) {\n\t\tif (!(root == null)) {\n\t\t\tStack bts_Queue = new Stack();\n\t\t\tbts_Queue.add(root);\n\t\t\twhile (!bts_Queue.isEmpty()) {\n\t\t\t\tNode currentNode = bts_Queue.pop();\n\t\t\t\tSystem.out.print(\" \" + currentNode.getValue() + \" \");\n\t\t\t\tif (currentNode.getRightChild() != null) {\n\t\t\t\t\tbts_Queue.push(currentNode.getRightChild());\n\t\t\t\t}\n\t\t\t\t// left child will be read first\n\t\t\t\tif (currentNode.getLeftChild() != null) {\n\t\t\t\t\tbts_Queue.push(currentNode.getLeftChild());\n\t\t\t\t}\n\t\t\t}\n\t\t} else\n\t\t\tSystem.out.print(\"Empty Tree\");\n\t}\n\n\tpublic void refresh() {\n\t\tstartIndex = 0;\n\t}\n\n}\n"}}},{"rowIdx":966,"cells":{"language":{"kind":"string","value":"Java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":33168,"string":"33,168"},"score":{"kind":"number","value":1.515625,"string":"1.515625"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package com.grgbanking.ct;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.text.SimpleDateFormat;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Timer;\nimport java.util.TimerTask;\n\nimport org.apache.http.NameValuePair;\nimport org.apache.http.message.BasicNameValuePair;\nimport org.json.JSONException;\nimport org.json.JSONObject;\n\nimport android.annotation.SuppressLint;\nimport android.app.Activity;\nimport android.app.AlertDialog;\nimport android.app.AlertDialog.Builder;\nimport android.app.Dialog;\nimport android.app.ProgressDialog;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport android.database.Cursor;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.os.Environment;\nimport android.os.Handler;\nimport android.os.Message;\nimport android.provider.DocumentsContract;\nimport android.provider.MediaStore;\nimport android.util.Log;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.view.Window;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.ImageView;\nimport android.widget.ListView;\nimport android.widget.SimpleAdapter;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.baidu.location.BDLocation;\nimport com.baidu.location.BDLocationListener;\nimport com.baidu.location.LocationClient;\nimport com.baidu.location.LocationClientOption;\nimport com.baidu.location.LocationClientOption.LocationMode;\nimport com.grgbanking.ct.cach.DataCach;\nimport com.grgbanking.ct.database.Person;\nimport com.grgbanking.ct.database.PersonTableHelper;\nimport com.grgbanking.ct.entity.PdaCashboxInfo;\nimport com.grgbanking.ct.entity.PdaGuardManInfo;\nimport com.grgbanking.ct.entity.PdaLoginMessage;\nimport com.grgbanking.ct.entity.PdaNetInfo;\nimport com.grgbanking.ct.entity.PdaNetPersonInfo;\nimport com.grgbanking.ct.http.FileLoadUtils;\nimport com.grgbanking.ct.http.HttpPostUtils;\nimport com.grgbanking.ct.http.ResultInfo;\nimport com.grgbanking.ct.http.UICallBackDao;\nimport com.grgbanking.ct.page.CaptureActivity;\nimport com.grgbanking.ct.rfid.UfhData;\nimport com.grgbanking.ct.rfid.UfhData.UhfGetData;\n\n@SuppressLint(\"NewApi\")\npublic class DetailActivity extends Activity {\n\n\tprivate Context context;\n\tprivate EditText remarkEditView;\n\tTextView positionTextView = null;\n\tTextView branchNameTextView = null;\n\tButton commitYesButton = null;\n\tButton commitNoButton = null;\n\n\tTextView detailTitleTextView = null;\n\tButton connDeviceButton = null;\n\tButton startDeviceButton = null;\n\tTextView person1TextView = null;\n\tTextView person2TextView = null;\n\tListView deviceListView;\n\tSimpleAdapter listItemAdapter;\n\tArrayList> listItem;\n\n\tprivate int tty_speed = 57600;\n\tprivate byte addr = (byte) 0xff;\n\n\tprivate Timer timer;\n\tprivate boolean Scanflag=false;\n\tprivate static final int SCAN_INTERVAL = 10;\n\tprivate boolean isCanceled = true;\n\tprivate Handler mHandler;\n\tprivate static final int MSG_UPDATE_LISTVIEW = 0;\n\tprivate Map data;\n\tstatic HashMap boxesMap1 = null;//保存正确款箱map\n\tstatic HashMap boxesMap2 = null;//保存错误款箱map\n\tstatic PdaNetPersonInfo netPersonInfo = null;//保存网点人员\n\tstatic PdaGuardManInfo guardManInfo = null;//保存押运人员\n\n\tprivate String branchCode = null;\n\tprivate String branchId = null;\n\tprivate String imageUrl = null;// 上传成功后的图片URL\n\n\tprivate String address;\n\tprivate double latitude;\n\tprivate double longitude;\n\n\tprivate boolean uploadFlag = false;\n\tprivate ProgressDialog pd = null;\n\tprivate Person person = null;\n\n\tprivate void showWaitDialog(String msg) {\n\t\tif (pd == null) {\n\t\t\tpd = new ProgressDialog(this);\n\t\t}\n\t\tpd.setCancelable(false);\n\t\tpd.setMessage(msg);\n\t\tpd.show();\n\t}\n\n\tprivate void hideWaitDialog() {\n\t\tif (pd != null) {\n\t\t\tpd.cancel();\n\t\t}\n\t}\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\trequestWindowFeature(Window.FEATURE_NO_TITLE);\n\t\tsetContentView(R.layout.detail);\n\t\tcontext = getApplicationContext();\n\t\tremarkEditView = (EditText) findViewById(R.id.detail_remark);\n\t\tcommitNoButton = (Button) findViewById(R.id.detail_btn_commit_n);\n\t\tbranchNameTextView = (TextView) findViewById(R.id.detail_branch_name);\n\t\tdetailTitleTextView = (TextView) findViewById(R.id.detail_title_view);\n\t\tconnDeviceButton = (Button) findViewById(R.id.button1);\n\t\tstartDeviceButton = (Button) findViewById(R.id.Button01);\n\t\tperson1TextView = (TextView) findViewById(R.id.textView2);\n\t\tperson2TextView = (TextView) findViewById(R.id.textView_person2);\n\t\tdeviceListView = (ListView) findViewById(R.id.ListView_boxs);\n\n\t\t// 生成动态数组,加入数据\n\t\tlistItem = new ArrayList>();\n\t\t// 生成适配器的Item和动态数组对应的元素\n\t\tlistItemAdapter = new SimpleAdapter(this,listItem,R.layout.boxes_list_item , new String[] { \"list_img\", \"list_title\"} , new int[] { R.id.list_boxes_img, R.id.list_boxes_title});\n\t\t// 添加并且显示\n\t\tdeviceListView.setAdapter(listItemAdapter);\n\n\t\tshowWaitDialog(\"正在加载中,请稍后...\");\n\n\t\tloadDevices();\n\n\t\t//启动RFID扫描功能刷新扫描款箱数据\n\t\tflashInfo();\n\n\t\thideWaitDialog();\n\t\t// 点击返回按钮操作内容\n\t\tfindViewById(R.id.detail_btn_back).setOnClickListener(click);\n\n\t\tcommitNoButton.setOnClickListener(click);\n\t\tconnDeviceButton.setOnClickListener(click);\n\t\tstartDeviceButton.setOnClickListener(click);\n\n\t\t// 点击添加照片按钮操作内容\n//\t\tfindViewById(R.id.add_photo).setOnClickListener(click);\n\t}\n\n\tprivate void flashInfo () {\n\t\tmHandler = new Handler(){\n\n\t\t\t@Override\n\t\t\tpublic void handleMessage(Message msg) {\n\t\t\t\t// TODO Auto-generated method stub\n\t\t\t\tif(isCanceled) return;\n\t\t\t\tswitch (msg.what) {\n\t\t\t\t\tcase MSG_UPDATE_LISTVIEW:\n//\t\t\t\t\tif(mode.equals(MainActivity.TABLE_6B)){\n//\t\t\t\t\t\tdata = UfhData.scanResult6b;\n//\t\t\t\t\t}else {\n//\t\t\t\t\t\tdata = UfhData.scanResult6c;\n//\t\t\t\t\t}\n\t\t\t\t\t\tdata = UfhData.scanResult6c;\n//\t\t\t\t\tif(listItemAdapter == null){\n//\t\t\t\t\t\tmyAdapter = new MyAdapter(ScanMode.this, new ArrayList(data.keySet()));\n//\t\t\t\t\t\tlistView.setAdapter(myAdapter);\n//\t\t\t\t\t}else{\n//\t\t\t\t\t\tmyAdapter.mList = new ArrayList(data.keySet());\n//\t\t\t\t\t}\n\t\t\t\t\t\tString person1 = person1TextView.getText().toString();\n\t\t\t\t\t\tString person2 = person2TextView.getText().toString();\n\n\t\t\t\t\t\tIterator it = data.keySet().iterator();\n\t\t\t\t\t\twhile (it.hasNext()) {\n\t\t\t\t\t\t\tString key = (String)it.next();\n\n\t\t\t\t\t\t\t//判断是否是押运人员\n\t\t\t\t\t\t\tif (key.indexOf(Constants.PRE_RFID_GUARD) != -1) {\n\n\t\t\t\t\t\t\t\tif (person1.trim().equals(\"\")) {\n\t\t\t\t\t\t\t\t\tPdaLoginMessage plm = DataCach.getPdaLoginMessage();\n\t\t\t\t\t\t\t\t\tif (plm != null) {\n\t\t\t\t\t\t\t\t\t\tList guardManInfoList = plm.getGuardManInfoList();\n\t\t\t\t\t\t\t\t\t\tif (guardManInfoList != null && guardManInfoList.size() > 0) {\n\t\t\t\t\t\t\t\t\t\t\tfor (PdaGuardManInfo info : guardManInfoList) {\n\t\t\t\t\t\t\t\t\t\t\t\tif (info.getGuardManRFID().equals(key)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tperson1TextView.setText(info.getGuardManName());\n\t\t\t\t\t\t\t\t\t\t\t\t\tguardManInfo = info;\n\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t//判断是否是网点人员\n\t\t\t\t\t\t\telse if (key.indexOf(Constants.PRE_RFID_BANKEMPLOYEE) != -1) {\n\n\t\t\t\t\t\t\t\tif (person2.trim().equals(\"\")) {\n\t\t\t\t\t\t\t\t\tIntent intent = getIntent();\n\t\t\t\t\t\t\t\t\tBundle bundle = intent.getBundleExtra(\"bundle\");\n\t\t\t\t\t\t\t\t\tint count = bundle.getInt(\"count\");\n\t\t\t\t\t\t\t\t\tHashMap map = DataCach.taskMap.get(count+ \"\");\n\t\t\t\t\t\t\t\t\tPdaNetInfo pni = (PdaNetInfo) map.get(\"data\");\n\n\t\t\t\t\t\t\t\t\tif (pni != null) {\n\t\t\t\t\t\t\t\t\t\tList netPersonInfoList = pni.getNetPersonInfoList();\n\t\t\t\t\t\t\t\t\t\tif (netPersonInfoList != null && netPersonInfoList.size() > 0) {\n\t\t\t\t\t\t\t\t\t\t\tfor (PdaNetPersonInfo info : netPersonInfoList) {\n\t\t\t\t\t\t\t\t\t\t\t\tif (info.getNetPersonRFID().equals(key)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tperson2TextView.setText(info.getNetPersonName());\n\t\t\t\t\t\t\t\t\t\t\t\t\tnetPersonInfo = info;\n\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n//\t\t\t\t\t\t\t\t\t\tif (person2TextView.getText().toString().equals(\"\")) {\n//\t\t\t\t\t\t\t\t\t\t\tToast.makeText(context, \"该网点人员不是本网点人员\", 5000).show();\n//\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t//判断是否是正确款箱RFID\n\t\t\t\t\t\t\telse if (boxesMap1.get(key) != null) {\n\t\t\t\t\t\t\t\tHashMap map = DataCach.boxesMap.get(key);\n\t\t\t\t\t\t\t\tmap.put(\"list_img\", R.drawable.boxes_list_status_1);// 图像资源的ID\n\n\t\t\t\t\t\t\t\tHashMap map1 = (HashMap) boxesMap1.get(key);\n\t\t\t\t\t\t\t\t//记录该款箱是否已扫描 0:未扫描;1:已扫描\n\t\t\t\t\t\t\t\tmap1.put(\"status\", \"1\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t//判断是否是错误款箱RFID\n\t\t\t\t\t\t\telse if (boxesMap2.get(key) == null) {\n\n\t\t\t\t\t\t\t\tPdaLoginMessage pdaLoginMessage = DataCach.getPdaLoginMessage();\n\t\t\t\t\t\t\t\tMap allPdaBoxsMap = pdaLoginMessage.getAllPdaBoxsMap();\n\t\t\t\t\t\t\t\tif (allPdaBoxsMap.get(key) != null) {\n\t\t\t\t\t\t\t\t\tHashMap map1 = new HashMap();\n\t\t\t\t\t\t\t\t\tmap1.put(\"list_img\", R.drawable.boxes_list_status_3);// 图像资源的ID\n\t\t\t\t\t\t\t\t\tmap1.put(\"list_title\",allPdaBoxsMap.get(key));\n\n\t\t\t\t\t\t\t\t\tDataCach.boxesMap.put(key, map1);\n\t\t\t\t\t\t\t\t\tboxesMap2.put(key, map1);\n\t\t\t\t\t\t\t\t\tlistItem.add(map1);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t//判断是否正确扫描到全部款箱和交接人员,如果是自动停止扫描\n\n\t\t\t\t\t\t\tif (boxesMap1 != null && boxesMap1.size() > 0) {\n\t\t\t\t\t\t\t\tboolean right = true;\n\t\t\t\t\t\t\t\tIterator it2 = boxesMap1.keySet().iterator();\n\t\t\t\t\t\t\t\twhile (it2.hasNext()) {\n\t\t\t\t\t\t\t\t\tString key2 = (String) it2.next();\n\t\t\t\t\t\t\t\t\tHashMap map1 = (HashMap) boxesMap1.get(key2);\n\t\t\t\t\t\t\t\t\tif (map1.get(\"status\").equals(\"0\")) {\n\t\t\t\t\t\t\t\t\t\tright = false;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (boxesMap2 != null && boxesMap2.size() > 0) {\n\t\t\t\t\t\t\t\t\tright = false;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t//判断人员是否扫描\n\t\t\t\t\t\t\t\tif (guardManInfo == null) {\n\t\t\t\t\t\t\t\t\tright = false;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (netPersonInfo == null) {\n\t\t\t\t\t\t\t\t\tright = false;\n\t\t\t\t\t\t\t\t}\n\n\n\t\t\t\t\t\t\t\tif (right) {\n\t\t\t\t\t\t\t\t\tString context = startDeviceButton.getText().toString();\n\t\t\t\t\t\t\t\t\tif (context.equals(\"Stop\")) {\n\t\t\t\t\t\t\t\t\t\tstartDevices ();\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n//\t\t\t\t\ttxNum.setText(String.valueOf(myAdapter.getCount()));\n\t\t\t\t\t\tlistItemAdapter.notifyDataSetChanged();\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tsuper.handleMessage(msg);\n\t\t\t}\n\n\t\t};\n\t}\n\n\tprivate void connDevices () {\n\t\tint result=UhfGetData.OpenUhf(tty_speed, addr, 4, 1, null);\n\t\tif(result==0){\n\t\t\tUhfGetData.GetUhfInfo();\n\t\t\tToast.makeText(context, \"连接设备成功\", Toast.LENGTH_LONG).show();\n\t\t\t//\t\tmHandler.removeMessages(MSG_SHOW_PROPERTIES);\n\t\t\t//\t\tmHandler.sendEmptyMessage(MSG_SHOW_PROPERTIES);\n\t\t} else {\n\t\t\tToast.makeText(context, \"连接设备失败,请关闭程序重新登录\", Toast.LENGTH_LONG).show();\n\t\t}\n\t}\n\n\tprivate void startDevices () {\n\t\tif(!UfhData.isDeviceOpen()){\n\t\t\tToast.makeText(this, R.string.detail_title, Toast.LENGTH_LONG).show();\n\t\t\treturn;\n\t\t}\n\t\tif(timer == null){\n//\t\t\tcdtion.setEnabled(false);\n\t\t\t///////////声音开关初始化\n\t\t\tUfhData.Set_sound(true);\n\t\t\tUfhData.SoundFlag=false;\n\t\t\t//////////\n//\t\t\tif (myAdapter != null) {\n//\t\t\t\tif(mode.equals(MainActivity.TABLE_6B)){\n//\t\t\t\t\tUfhData.scanResult6b.clear();\n//\t\t\t\t}else if(mode.equals(MainActivity.TABLE_6C)){\n//\t\t\t\t\tUfhData.scanResult6c.clear();\n//\t\t\t\t}\n//\t\t\t\tmyAdapter.mList.clear();\n//\t\t\t\tmyAdapter.notifyDataSetChanged();\n//\t\t\t\tmHandler.removeMessages(MSG_UPDATE_LISTVIEW);\n//\t\t\t\tmHandler.sendEmptyMessage(MSG_UPDATE_LISTVIEW);\n//\t\t\t}\n\n\t\t\tisCanceled = false;\n\t\t\ttimer = new Timer();\n\t\t\t//\n\t\t\ttimer.schedule(new TimerTask() {\n\t\t\t\t@Override\n\t\t\t\tpublic void run() {\n\t\t\t\t\tif(Scanflag)return;\n\t\t\t\t\tScanflag=true;\n//\t\t\t\t\tif(mode.equals(MainActivity.TABLE_6B)){\n//\t\t\t\t\t\tLog.i(\"zhouxin\", \"------onclick-------6b\");\n//\t\t\t\t\t\tUfhData.read6b();\n//\t\t\t\t\t}else if(mode.equals(MainActivity.TABLE_6C)){\n//\t\t\t\t\t\tUfhData.read6c();\n//\t\t\t\t\t}\n\t\t\t\t\tLog.i(\"zhouxin\", \"------onclick-------6c\");\n\t\t\t\t\tUfhData.read6c();\n\t\t\t\t\tmHandler.removeMessages(MSG_UPDATE_LISTVIEW);\n\t\t\t\t\tmHandler.sendEmptyMessage(MSG_UPDATE_LISTVIEW);\n\t\t\t\t\tScanflag=false;\n\t\t\t\t}\n\t\t\t}, 0, SCAN_INTERVAL);\n\t\t\tstartDeviceButton.setText(\"Stop\");\n\t\t}else{\n\t\t\tcancelScan();\n\t\t\tUfhData.Set_sound(false);\n\t\t}\n\n\t}\n\n\tprivate void cancelScan(){\n\t\tisCanceled = true;\n//\t\tcdtion.setEnabled(true);\n\t\tmHandler.removeMessages(MSG_UPDATE_LISTVIEW);\n\t\tif(timer != null){\n\t\t\ttimer.cancel();\n\t\t\ttimer = null;\n\t\t\tstartDeviceButton.setText(\"Scan\");\n//\t\t\tif(mode.equals(MainActivity.TABLE_6B)){\n//\t\t\t\tUfhData.scanResult6b.clear();\n//\t\t\t}else if(mode.equals(MainActivity.TABLE_6C)){\n//\t\t\t\tUfhData.scanResult6c.clear();\n//\t\t\t}\n\t\t\tUfhData.scanResult6c.clear();\n//\t\t\tif (listItemAdapter != null) {\n//\t\t\t\tlistItem.clear();\n//\t\t\t\tlistItemAdapter.notifyDataSetChanged();\n//\t\t\t}\n//\t\t\ttxNum.setText(\"0\");\n\t\t}\n\t}\n\n\tprivate void loadDevices () {\n\t\t//加载数据要先把数据缓存清空\n\t\tperson1TextView.setText(\"\");\n\t\tperson2TextView.setText(\"\");\n\t\tDataCach.boxesMap = null;\n\t\tDataCach.boxesMap = new LinkedHashMap>();\n\t\tboxesMap1 = null;\n\t\tboxesMap1 = new HashMap();\n\t\tboxesMap2 = null;\n\t\tboxesMap2 = new HashMap();\n\t\tnetPersonInfo = null;\n\t\tguardManInfo = null;\n\t\tlistItem.removeAll(listItem);\n\n\n\t\tIntent intent = getIntent();\n\t\tBundle bundle = intent.getBundleExtra(\"bundle\");\n\t\tint count = bundle.getInt(\"count\");\n\t\tif (DataCach.taskMap.get(count+ \"\") != null) {\n\t\t\tHashMap map = DataCach.taskMap.get(count+ \"\");\n\t\t\tPdaNetInfo pni = (PdaNetInfo) map.get(\"data\");\n\t\t\tdetailTitleTextView.setText(pni.getBankName());\n\n\t\t\tList cashBoxInfoList = pni.getCashBoxInfoList();\n\n\t\t\tif (cashBoxInfoList != null && cashBoxInfoList.size() > 0) {\n\n\t\t\t\tfor (PdaCashboxInfo pci: cashBoxInfoList) {\n\n\t\t\t\t\tHashMap map1 = new HashMap();\n\t\t\t\t\tmap1.put(\"list_img\", R.drawable.boxes_list_status_2);// 图像资源的ID\n\t\t\t\t\tmap1.put(\"list_title\", pci.getBoxSn());\n //记录该款箱是否已扫描 0:未扫描;1:已扫描\n\t\t\t\t\tmap1.put(\"status\", \"0\");\n DataCach.boxesMap.put(pci.getRfidNum(), map1);\n\t\t\t\t\tboxesMap1.put(pci.getRfidNum(), map1);\n\t\t\t\t\tlistItem.add(map1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlistItemAdapter.notifyDataSetChanged();\n\t}\n\n\t@Override\n\tprotected void onStart() {\n\t\t// TODO Auto-generated method stub\n\t\tsuper.onStart();\n\t}\n\n\tOnClickListener click = new OnClickListener() {\n\t\t@Override\n\t\tpublic void onClick(View arg0) {\n\t\t\tString context = startDeviceButton.getText().toString();\n\t\t\t// TODO Auto-generated method stub\n\t\t\tswitch (arg0.getId()) {\n\t\t\t\tcase R.id.detail_btn_back:\n\t\t\t\t\tif (context.equals(\"Stop\")) {\n\t\t\t\t\t\tToast.makeText(DetailActivity.this, \"请先停止扫描\", 3000).show();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbackListPage();\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n//\t\t\tcase R.id.detail_btn_commit_y:\n//\t\t\t\tdoCommit(\"Y\");\n//\t\t\t\tbreak;\n\t\t\t\tcase R.id.detail_btn_commit_n:\n//\t\t\t\tif (uploadFlag) {\n//\t\t\t\t\tdoCommit(\"N\");\n//\t\t\t\t} else {\n//\t\t\t\t\tToast.makeText(DetailActivity.this, \"图片正在上传中,请稍等。\", 5000)\n//\t\t\t\t\t\t\t.show();\n//\t\t\t\t}\n\t\t\t\t\tif (context.equals(\"Stop\")) {\n\t\t\t\t\t\tToast.makeText(DetailActivity.this, \"请先停止扫描\", 3000).show();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdialog();\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n//\t\t\tcase R.id.add_photo:\n//\t\t\t\tdoAddPhoto();\n//\t\t\t\tbreak;\n\n\t\t\t\tcase R.id.button1:\n\t\t\t\t\t//连接设备\n\t\t\t\t\tconnDevices();\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase R.id.Button01:\n\t\t\t\t\t//启动设备\n\t\t\t\t\tif (!context.equals(\"Stop\")) {\n\t\t\t\t\t\tloadDevices();\n\t\t\t\t\t}\n\n\t\t\t\t\tstartDevices();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t};\n\n\tprotected void dialog() {\n//\t 通过AlertDialog.Builder这个类来实例化我们的一个AlertDialog的对象\n\t\tAlertDialog.Builder builder = new AlertDialog.Builder(DetailActivity.this);\n// // 设置Title的图标\n// builder.setIcon(R.drawable.ic_launcher);\n\t\t// 设置Title的内容\n\t\tbuilder.setTitle(\"提示\");\n\t\t// 设置Content来显示一个信息\n\t\tbuilder.setMessage(\"确定交接?\");\n\t\t// 设置一个PositiveButton\n\t\tbuilder.setPositiveButton(\"取消\", new DialogInterface.OnClickListener()\n\t\t{\n\t\t\t@Override\n\t\t\tpublic void onClick(DialogInterface dialog, int which)\n\t\t\t{\n\t\t\t}\n\t\t});\n\t\t// 设置一个NegativeButton\n\t\tbuilder.setNegativeButton(\"确认\", new DialogInterface.OnClickListener()\n\t\t{\n\t\t\t@Override\n\t\t\tpublic void onClick(DialogInterface dialog, int which)\n\t\t\t{\n\t\t\t\tshowWaitDialog(\"正在提交数据...\");\n\t\t\t\tResultInfo ri = this.getNetIncommitData();\n\t\t\t\tif (ri.getCode().endsWith(ResultInfo.CODE_ERROR)) {\n\t\t\t\t\thideWaitDialog();\n\t\t\t\t\tToast.makeText(context, ri.getMessage(), 5000).show();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tList params = new ArrayList();\n\t\t\t\tparams.add(new BasicNameValuePair(\"param\", ri.getText()));\n\t\t\t\tnew HttpPostUtils(Constants.URL_NET_IN_COMMIT, params,new UICallBackDao() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void callBack(ResultInfo resultInfo) {\n\t\t\t\t\t\tif (resultInfo.getCode().equals(ResultInfo.CODE_ERROR)) {\n\t\t\t\t\t\t\thideWaitDialog();\n\t\t\t\t\t\t\tToast.makeText(context, resultInfo.getMessage(), 5000).show();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\thideWaitDialog();\n\t\t\t\t\t\t\tToast.makeText(context, resultInfo.getMessage(), 5000).show();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}).execute();\n\t\t\t\thideWaitDialog();\n\n\t\t\t\t// 得到跳转到该Activity的Intent对象\n\t\t\t\tIntent intent = getIntent();\n\t\t\t\tBundle bundle = intent.getBundleExtra(\"bundle\");\n\t\t\t\tint count = bundle.getInt(\"count\");\n\t\t\t\tif (DataCach.taskMap.get(count+ \"\") != null) {\n\t\t\t\t\tHashMap map = DataCach.taskMap.get(count+ \"\");\n\t\t\t\t\tmap.put(\"list_img\", R.drawable.task_1);// 图像资源的ID\n\t\t\t\t\tmap.put(\"list_worktime\",\"已完成\");\n\t\t\t\t}\n\t\t\t\tbackListPage();\n\t\t\t}\n\n\t\t\tprivate ResultInfo getNetIncommitData() {\n\t\t\t\tResultInfo ri = new ResultInfo();\n\t\t\t\tMap dataMap = new HashMap();\n\t\t\t\tif (guardManInfo == null) {\n\t\t\t\t\tri.setCode(ResultInfo.CODE_ERROR);\n\t\t\t\t\tri.setMessage(\"请扫描押运人员\");\n\t\t\t\t\treturn ri;\n\t\t\t\t}\n\t\t\t\tif (netPersonInfo == null) {\n\t\t\t\t\tri.setCode(ResultInfo.CODE_ERROR);\n\t\t\t\t\tri.setMessage(\"请扫描网点人员\");\n\t\t\t\t\treturn ri;\n\t\t\t\t}\n\t\t\t\tif ((boxesMap1 == null || boxesMap1.size() == 0) && (boxesMap2 == null || boxesMap2.size() == 0)) {\n\t\t\t\t\tri.setCode(ResultInfo.CODE_ERROR);\n\t\t\t\t\tri.setMessage(\"请扫描款箱\");\n\t\t\t\t\treturn ri;\n\t\t\t\t}\n\n\t\t\t\t//开始组装数据\n\t\t\t\tPdaLoginMessage pdaLoginMessage = DataCach.getPdaLoginMessage();\n\t\t\t\tSimpleDateFormat format = new SimpleDateFormat(\"yyyy/MM/dd HH:mm:ss\");\n\t\t\t\tdataMap.put(\"lineId\", pdaLoginMessage.getLineId());\n\t\t\t\tdataMap.put(\"scanningDate\", format.format(new Date()));\n\t\t\t\tdataMap.put(\"netPersonName\", netPersonInfo.getNetPersonName());\n\t\t\t\tdataMap.put(\"netPersonId\", netPersonInfo.getNetPersonId());\n\t\t\t\tdataMap.put(\"guardPersonName\", guardManInfo.getGuardManName());\n\t\t\t\tdataMap.put(\"guradPersonId\", guardManInfo.getGuardManId());\n\t\t\t\tdataMap.put(\"note\", remarkEditView.getText().toString());\n\n\n\t\t\t\tIntent intent = getIntent();\n\t\t\t\tBundle bundle = intent.getBundleExtra(\"bundle\");\n\t\t\t\tint count = bundle.getInt(\"count\");\n\n\t\t\t\tdataMap.put(\"scanningType\", DataCach.netType);\n\n\t\t\t\tHashMap map = DataCach.taskMap.get(count+ \"\");\n\t\t\t\tPdaNetInfo pni = (PdaNetInfo) map.get(\"data\");\n\t\t\t\tdataMap.put(\"netId\", pni.getBankId());\n\n\t\t\t\tString rightRfidNums = \"\";\n\t\t\t\tString missRfidNums = \"\";\n\t\t\t\tString errorRfidNums = \"\";\n\t\t\t\tif (boxesMap1 != null && boxesMap1.size() > 0) {\n\t\t\t\t\tIterator it = boxesMap1.keySet().iterator();\n\t\t\t\t\twhile (it.hasNext()) {\n\t\t\t\t\t\tString key = (String) it.next();\n\t\t\t\t\t\tHashMap map1 = (HashMap) boxesMap1.get(key);\n\t\t\t\t\t\tif (map1.get(\"status\").equals(\"1\")) {\n\t\t\t\t\t\t\trightRfidNums += \";\" + key;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tmissRfidNums += \";\" + key;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (rightRfidNums.length() > 0) {\n\t\t\t\t\t\trightRfidNums = rightRfidNums.substring(1);\n\t\t\t\t\t}\n\t\t\t\t\tif (missRfidNums.length() > 0) {\n\t\t\t\t\t\tmissRfidNums = missRfidNums.substring(1);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (boxesMap2 != null && boxesMap2.size() > 0) {\n\t\t\t\t\tIterator it = boxesMap2.keySet().iterator();\n\t\t\t\t\twhile (it.hasNext()) {\n\t\t\t\t\t\tString key = (String) it.next();\n\t\t\t\t\t\terrorRfidNums += \";\" + key;\n\t\t\t\t\t}\n\t\t\t\t\tif (errorRfidNums.length() > 0) {\n\t\t\t\t\t\terrorRfidNums = errorRfidNums.substring(1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tdataMap.put(\"rightRfidNums\", rightRfidNums);\n\t\t\t\tdataMap.put(\"missRfidNums\", missRfidNums);\n\t\t\t\tdataMap.put(\"errorRfidNums\", errorRfidNums);\n\n\t\t\t\tif (rightRfidNums.length() > 0 && missRfidNums.length() == 0 && errorRfidNums.length() == 0) {\n\t\t\t\t\tdataMap.put(\"scanStatus\", Constants.NET_COMMIT_STATUS_RIGHT);\n\t\t\t\t} else {\n\t\t\t\t\tdataMap.put(\"scanStatus\", Constants.NET_COMMIT_STATUS_ERROR);\n\t\t\t\t}\n\n\t\t\t\tJSONObject jsonObject = new JSONObject(dataMap);\n\t\t\t\tString data = jsonObject.toString();\n\t\t\t\tri.setCode(ResultInfo.CODE_SUCCESS);\n\t\t\t\tri.setText(data);\n\t\t\t\treturn ri;\n\t\t\t}\n\n\n\t\t});\n// // 设置一个NeutralButton\n// builder.setNeutralButton(\"忽略\", new DialogInterface.OnClickListener()\n// {\n// @Override\n// public void onClick(DialogInterface dialog, int which)\n// {\n// Toast.makeText(DetailActivity.this, \"neutral: \" + which, Toast.LENGTH_SHORT).show();\n// }\n// });\n\t\t// 显示出该对话框\n\t\tbuilder.show();\n\t}\n\n\tvoid backListPage() {\n\t\tstartActivity(new Intent(getApplicationContext(), MainActivity.class));\n\t\tfinish();\n\t}\n\n\tvoid doCommit(String flag) {\n\n\t\tif(address==null||\"\".equals(address)){\n\t\t\tToast.makeText(DetailActivity.this, \"错误提示:无法获取您当前的地理位置,请返回重新扫描二维码。\", 5000)\n\t\t\t\t\t.show();\n\t\t\treturn;\n\t\t}\n\n\t\tshowWaitDialog(\"正在处理中...\");\n\t\tString remark = remarkEditView.getText().toString();\n\t\tString status = flag;\n\t\tList params = new ArrayList();\n\t\tparams.add(new BasicNameValuePair(\"userid\", person.getUser_id()));\n\t\tparams.add(new BasicNameValuePair(\"name\", person.getUser_name()));\n\n\t\tparams.add(new BasicNameValuePair(\"branchId\", branchId));\n\t\tparams.add(new BasicNameValuePair(\"remark\", remark));\n\t\tparams.add(new BasicNameValuePair(\"status\", status));\n\t\tparams.add(new BasicNameValuePair(\"imageUrl\", imageUrl));\n\t\tparams.add(new BasicNameValuePair(\"longitude\", longitude + \"\"));\n\t\tparams.add(new BasicNameValuePair(\"latitude\", latitude + \"\"));\n\t\tparams.add(new BasicNameValuePair(\"address\", address));\n\t\tnew HttpPostUtils(Constants.URL_SAVE_TASK, params, new UICallBackDao() {\n\t\t\t@Override\n\t\t\tpublic void callBack(ResultInfo resultInfo) {\n\t\t\t\thideWaitDialog();\n\n\t\t\t\tif(\"1\".equals(resultInfo.getCode())){\n\t\t\t\t\tnew AlertDialog.Builder(DetailActivity.this)\n\t\t\t\t\t\t\t.setTitle(\"消息\")\n\t\t\t\t\t\t\t.setMessage(\"提交成功!\")\n\t\t\t\t\t\t\t.setPositiveButton(\"确定\",\n\t\t\t\t\t\t\t\t\tnew DialogInterface.OnClickListener() {// 设置确定按钮\n\t\t\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\t\t\t// 处理确定按钮点击事件\n\t\t\t\t\t\t\t\t\t\tpublic void onClick(DialogInterface dialog,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tint which) {\n\t\t\t\t\t\t\t\t\t\t\tbackListPage();\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}).show();\n\t\t\t\t}else{\n\t\t\t\t\tToast.makeText(DetailActivity.this, resultInfo.getMessage(), 5*1000).show();\n\n\t\t\t\t}\n\n\n\t\t\t}\n\t\t}).execute();\n\t}\n\n\tvoid doAddPhoto() {\n\t\tfinal CharSequence[] items = { \"相册\", \"拍照\" };\n\t\tAlertDialog dlg = new AlertDialog.Builder(DetailActivity.this)\n\t\t\t\t.setTitle(\"选择照片\")\n\t\t\t\t.setItems(items, new DialogInterface.OnClickListener() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void onClick(DialogInterface dialog, int which) {\n\t\t\t\t\t\t// TODO Auto-generated method stub\n\t\t\t\t\t\t// 这里item是根据选择的方式, 在items数组里面定义了两种方式,拍照的下标为1所以就调用拍照方法\n\t\t\t\t\t\tif (which == 1) {\n\t\t\t\t\t\t\ttakePhoto();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpickPhoto();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}).create();\n\t\tdlg.show();\n\t}\n\n\tprivate static final int IMAGE_REQUEST_CODE = 0; // 选择本地图片\n\tprivate static final int CAMERA_REQUEST_CODE = 1; // 拍照\n\tprivate static final String IMAGE_FILE_NAME = \"faceImage.jpg\";\n\n\t/**\n\t * 拍照\n\t */\n\tprivate void takePhoto() {\n\t\tIntent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);\n\t\t// 判断存储卡是否可以用,可用进行存�?\n\t\tString state = Environment.getExternalStorageState();\n\t\tif (state.equals(Environment.MEDIA_MOUNTED)) {\n\t\t\tintentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri\n\t\t\t\t\t.fromFile(new File(Environment\n\t\t\t\t\t\t\t.getExternalStorageDirectory(), IMAGE_FILE_NAME)));\n\t\t}\n\t\tstartActivityForResult(intentFromCapture, CAMERA_REQUEST_CODE);\n\t}\n\n\t/**\n\t * 选择本地图片\n\t */\n\tprivate void pickPhoto() {\n\t\tIntent intentFromGallery = new Intent();\n\t\tintentFromGallery.setType(\"image/*\"); // 设置文件类型\n\t\tintentFromGallery.setAction(Intent.ACTION_GET_CONTENT);\n\t\tstartActivityForResult(intentFromGallery, IMAGE_REQUEST_CODE);\n\t}\n\n\tpublic String uri2filePath(Uri uri) {\n\t\tString path = \"\";\n\t\tif (DocumentsContract.isDocumentUri(this, uri)) {\n\t\t\tString wholeID = DocumentsContract.getDocumentId(uri);\n\t\t\tString id = wholeID.split(\":\")[1];\n\t\t\tString[] column = { MediaStore.Images.Media.DATA };\n\t\t\tString sel = MediaStore.Images.Media._ID + \"=?\";\n\t\t\tCursor cursor = this.getContentResolver().query(\n\t\t\t\t\tMediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel,\n\t\t\t\t\tnew String[] { id }, null);\n\t\t\tint columnIndex = cursor.getColumnIndex(column[0]);\n\t\t\tif (cursor.moveToFirst()) {\n\t\t\t\tpath = cursor.getString(columnIndex);\n\t\t\t}\n\t\t\tcursor.close();\n\t\t} else {\n\t\t\tString[] projection = { MediaStore.Images.Media.DATA };\n\t\t\tCursor cursor = this.getContentResolver().query(uri,\n\t\t\t\t\tprojection, null, null, null);\n\t\t\tint column_index = cursor\n\t\t\t\t\t.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);\n\t\t\tcursor.moveToFirst();\n\t\t\tpath = cursor.getString(column_index);\n\t\t}\n\t\treturn path;\n\n\t}\n\n\t@Override\n\tprotected void onActivityResult(int requestCode, int resultCode, Intent data) {\n\t\tif (resultCode == Activity.RESULT_OK) {\n\t\t\tswitch (requestCode) {\n\t\t\t\tcase CAMERA_REQUEST_CODE:\n\t\t\t\t\tString state = Environment.getExternalStorageState();\n\t\t\t\t\tif (state.equals(Environment.MEDIA_MOUNTED)) {\n\t\t\t\t\t\tBitmap bitmap = compressImage(getSmallBitmap(Environment\n\t\t\t\t\t\t\t\t.getExternalStorageDirectory()\n\t\t\t\t\t\t\t\t+ \"/\"\n\t\t\t\t\t\t\t\t+ IMAGE_FILE_NAME));\n\n//\t\t\t\t\taddPhotoImageView.setImageBitmap(bitmap);\n//\t\t\t\t\tuploadStatusTextView.setText(\"图片上传中...\");\n\n\t\t\t\t\t\tnew FileLoadUtils(Constants.URL_FILE_UPLOAD, new File(\n\t\t\t\t\t\t\t\tEnvironment.getExternalStorageDirectory()\n\t\t\t\t\t\t\t\t\t\t+ \"/faceImage1.jpg\"), new UICallBackDao() {\n\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\tpublic void callBack(ResultInfo resultInfo) {\n\t\t\t\t\t\t\t\tif (resultInfo != null\n\t\t\t\t\t\t\t\t\t\t&& \"200\".equals(resultInfo.getCode())) {\n\t\t\t\t\t\t\t\t\tToast.makeText(DetailActivity.this, \"上传成功\",\n\t\t\t\t\t\t\t\t\t\t\t5000).show();\n//\t\t\t\t\t\t\t\tuploadStatusTextView.setText(\"上传成功。\");\n//\t\t\t\t\t\t\t\timageUrl = resultInfo.getMessage();\n\t\t\t\t\t\t\t\t\tuploadFlag = true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}).execute();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tToast.makeText(this, getString(R.string.sdcard_unfound),\n\t\t\t\t\t\t\t\tToast.LENGTH_SHORT).show();\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase IMAGE_REQUEST_CODE:\n\t\t\t\t\ttry {\n\t\t\t\t\t\tString path = uri2filePath(data.getData());\n\t\t\t\t\t\tBitmap bitmap = compressImage(getSmallBitmap(path));\n//\t\t\t\t\taddPhotoImageView.setImageBitmap(bitmap);\n//\t\t\t\t\tuploadStatusTextView.setText(\"图片上传中...\");\n\t\t\t\t\t\tnew FileLoadUtils(Constants.URL_FILE_UPLOAD,\n\t\t\t\t\t\t\t\tnew File(path), new UICallBackDao() {\n\n\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\tpublic void callBack(ResultInfo resultInfo) {\n\t\t\t\t\t\t\t\tif (resultInfo != null\n\t\t\t\t\t\t\t\t\t\t&& \"200\".equals(resultInfo\n\t\t\t\t\t\t\t\t\t\t.getCode())) {\n\t\t\t\t\t\t\t\t\tToast.makeText(DetailActivity.this,\n\t\t\t\t\t\t\t\t\t\t\t\"上传成功\", 5000).show();\n//\t\t\t\t\t\t\t\t\t\tuploadStatusTextView.setText(\"上传成功。\");\n\t\t\t\t\t\t\t\t\timageUrl = resultInfo.getMessage();\n\t\t\t\t\t\t\t\t\tuploadFlag = true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}).execute();\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * 图片压缩方法实现\n\t *\n\t * @param srcPath\n\t * @return\n\t */\n\tprivate Bitmap getimage(String srcPath) {\n\t\tBitmapFactory.Options newOpts = new BitmapFactory.Options();\n\t\t// 开始读入图片,此时把options.inJustDecodeBounds 设回true了\n\t\tnewOpts.inJustDecodeBounds = true;\n\t\tBitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);\n\n\t\tnewOpts.inJustDecodeBounds = false;\n\t\tint w = newOpts.outWidth;\n\t\tint h = newOpts.outHeight;\n\t\tint hh = 800;// 这里设置高度为800f\n\t\tint ww = 480;// 这里设置宽度为480f\n\t\t// 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可\n\t\tint be = 1;// be=1表示不缩放\n\t\tif (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放\n\t\t\tbe = newOpts.outWidth / ww;\n\t\t} else if (w < h && h > hh) {// 如果高度高的话根据高度固定大小缩放\n\t\t\tbe = newOpts.outHeight / hh;\n\t\t}\n\t\tif (be <= 0)\n\t\t\tbe = 1;\n\t\tnewOpts.inSampleSize = be;// 设置缩放比例\n\t\t// 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了\n\t\tbitmap = BitmapFactory.decodeFile(srcPath, newOpts);\n\t\treturn compressImage(bitmap);// 压缩好比例大小后再进行质量压缩\n\t}\n\n\t/**\n\t * 质量压缩\n\t *\n\t * @param image\n\t * @return\n\t */\n\tprivate Bitmap compressImage(Bitmap image) {\n\n\t\tByteArrayOutputStream baos = new ByteArrayOutputStream();\n\t\timage.compress(Bitmap.CompressFormat.JPEG, 50, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中\n\t\tint options = 100;\n\t\twhile (baos.toByteArray().length * 3 / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩\n\t\t\tbaos.reset();// 重置baos即清空baos\n\t\t\toptions -= 10;// 每次都减少10\n\t\t\timage.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中\n\t\t}\n\t\tByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中\n\t\tBitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片\n\t\ttry {\n\t\t\tFileOutputStream out = new FileOutputStream(\n\t\t\t\t\tEnvironment.getExternalStorageDirectory()\n\t\t\t\t\t\t\t+ \"/faceImage1.jpg\");\n\t\t\tbitmap.compress(Bitmap.CompressFormat.PNG, 40, out);\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn bitmap;\n\t}\n\n\tpublic void initLocation(final Context context,\n\t\t\t\t\t\t\t final DetailActivity detailActivity) {\n\t\tLocationClient locationClient = new LocationClient(context);\n\t\t// 设置定位条件\n\t\tLocationClientOption option = new LocationClientOption();\n\t\toption.setOpenGps(true); // 是否打开GPS\n\t\toption.setIsNeedAddress(true);\n\t\toption.setLocationMode(LocationMode.Hight_Accuracy);\n\t\toption.setScanSpan(0);// 设置定时定位的时间间隔。单位毫秒\n\t\toption.setAddrType(\"all\");\n\t\toption.setCoorType(\"bd09ll\");\n\t\tlocationClient.setLocOption(option);\n\t\t// 注册位置监听器\n\t\tlocationClient.registerLocationListener(new BDLocationListener() {\n\t\t\t@Override\n\t\t\tpublic void onReceiveLocation(BDLocation location) {\n//\t\t\t\tgpsPositionTextView = (TextView) detailActivity\n//\t\t\t\t\t\t.findViewById(R.id.gps_position);\n//\t\t\t\tgpsPositionTextView.setText(\"我的位置:\" + location.getAddrStr());\n\t\t\t\taddress = location.getAddrStr();\n\t\t\t\tlatitude = location.getLatitude();\n\t\t\t\tlongitude = location.getLongitude();\n\t\t\t}\n\t\t});\n\t\tlocationClient.start();\n\t}\n\n\t/**\n\t * 计算图片的缩放值\n\t *\n\t * @param options\n\t * @param reqWidth\n\t * @param reqHeight\n\t * @return\n\t */\n\tpublic static int calculateInSampleSize(BitmapFactory.Options options,\n\t\t\t\t\t\t\t\t\t\t\tint reqWidth, int reqHeight) {\n\t\t// Raw height and width of image\n\t\tfinal int height = options.outHeight;\n\t\tfinal int width = options.outWidth;\n\t\tint inSampleSize = 1;\n\n\t\tif (height > reqHeight || width > reqWidth) {\n\n\t\t\t// Calculate ratios of height and width to requested height and\n\t\t\t// width\n\t\t\tfinal int heightRatio = Math.round((float) height\n\t\t\t\t\t/ (float) reqHeight);\n\t\t\tfinal int widthRatio = Math.round((float) width / (float) reqWidth);\n\n\t\t\t// Choose the smallest ratio as inSampleSize value, this will\n\t\t\t// guarantee\n\t\t\t// a final image with both dimensions larger than or equal to the\n\t\t\t// requested height and width.\n\t\t\tinSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;\n\t\t}\n\n\t\treturn inSampleSize;\n\t}\n\n\t/**\n\t * 根据路径获得突破并压缩返回bitmap用于显示\n\t *\n\t * @return\n\t */\n\tpublic static Bitmap getSmallBitmap(String filePath) {\n\t\tfinal BitmapFactory.Options options = new BitmapFactory.Options();\n\t\toptions.inJustDecodeBounds = true;\n\t\tBitmapFactory.decodeFile(filePath, options);\n\n\t\t// Calculate inSampleSize\n\t\toptions.inSampleSize = calculateInSampleSize(options, 480, 800);\n\n\t\t// Decode bitmap with inSampleSize set\n\t\toptions.inJustDecodeBounds = false;\n\n\t\treturn BitmapFactory.decodeFile(filePath, options);\n\t}\n}\n"}}},{"rowIdx":967,"cells":{"language":{"kind":"string","value":"C#"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":6703,"string":"6,703"},"score":{"kind":"number","value":2.703125,"string":"2.703125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"using System.Text;\nusing FileServer.Core;\nusing Xunit;\n\nnamespace FileServer.Test\n{\n [Collection(\"Using IO\")]\n public class ProgramTest\n {\n [Theory]\n [InlineData(-1)]\n [InlineData(0)]\n [InlineData(1000)]\n [InlineData(1999)]\n [InlineData(65001)]\n [InlineData(9999999)]\n public void Out_Of_Range_Ports(int invaildPorts)\n {\n var correctOutput = new StringBuilder();\n correctOutput.Append(\"Invaild Port Detected.\");\n correctOutput.Append(\"Vaild Ports 2000 - 65000\");\n\n string[] argsHelloWorld = { \"-p\", invaildPorts.ToString() };\n var mockPrinterOne = new MockPrinter();\n var serverMadeHelloWorld = Program.MakeServer(argsHelloWorld, mockPrinterOne);\n Assert.Null(serverMadeHelloWorld);\n mockPrinterOne.VerifyPrint(correctOutput.ToString());\n\n string[] args = { \"-p\", invaildPorts.ToString(), \"-d\", \"C:\\\\\" };\n var mockPrinterTwo = new MockPrinter();\n var serverMade = Program.MakeServer(args, mockPrinterTwo);\n Assert.Null(serverMade);\n mockPrinterTwo.VerifyPrint(correctOutput.ToString());\n\n var mockPrinterThree = new MockPrinter();\n string[] argsSwaped = { \"-d\", \"C:\\\\\", \"-p\", invaildPorts.ToString() };\n var serverMadeSwaped = Program.MakeServer(argsSwaped, mockPrinterThree);\n Assert.Null(serverMadeSwaped);\n mockPrinterThree.VerifyPrint(correctOutput.ToString());\n }\n\n [Fact]\n public void Make_Dirctory_Server_Correct()\n {\n var mockPrinter = new MockPrinter();\n string[] args = { \"-p\", \"32000\", \"-d\", \"C:\\\\\" };\n var serverMade = Program.MakeServer(args, mockPrinter);\n Assert.NotNull(serverMade);\n }\n\n [Fact]\n public void Make_Dirctory_Server_Twice_Same_Port()\n {\n var mockPrinter = new MockPrinter();\n var correctOutput = new StringBuilder();\n\n string[] args = { \"-p\", \"8765\", \"-d\", \"C:\\\\\" };\n var serverMade = Program.MakeServer(args, mockPrinter);\n Assert.NotNull(serverMade);\n\n var serverMadeInvaild = Program.MakeServer(args, mockPrinter);\n Assert.Null(serverMadeInvaild);\n mockPrinter.VerifyPrint(\"Another Server is running on that port\");\n }\n\n [Fact]\n public void Make_Dirctory_Server_Correct_Arg_Backwords()\n {\n var mockPrinter = new MockPrinter();\n string[] args = { \"-d\", \"C:\\\\\", \"-p\", \"2020\" };\n var serverMade = Program.MakeServer(args, mockPrinter);\n Assert.NotNull(serverMade);\n }\n\n [Fact]\n public void Make_Dirctory_Server_Inncorect_Correct_Not_Dir()\n {\n var mockPrinter = new MockPrinter();\n var correctOutput = new StringBuilder();\n\n string[] args = { \"-d\", \"Hello\", \"-p\", \"3258\" };\n var serverMade = Program.MakeServer(args, mockPrinter);\n Assert.Null(serverMade);\n\n mockPrinter.VerifyPrint(\"Not a vaild directory\");\n }\n\n [Fact]\n public void Make_Dirctory_Server_Inncorect_Correct_Not_Port()\n {\n var mockPrinter = new MockPrinter();\n var correctOutput = new StringBuilder();\n correctOutput.Append(\"Invaild Port Detected.\");\n correctOutput.Append(\"Vaild Ports 2000 - 65000\");\n\n string[] args = { \"-d\", \"C:\\\\\", \"-p\", \"hello\" };\n var serverMade = Program.MakeServer(args, mockPrinter);\n Assert.Null(serverMade);\n mockPrinter.VerifyPrint(correctOutput.ToString());\n }\n\n\n [Fact]\n public void Make_Dirctory_Server_Inncorect_Correct()\n {\n var mockPrinter = new MockPrinter();\n var correctOutput = new StringBuilder();\n\n string[] args = { \"-p\", \"32000\", \"-d\", \"-d\" };\n var serverMade = Program.MakeServer(args, mockPrinter);\n Assert.Null(serverMade);\n\n mockPrinter.VerifyPrint(\"Not a vaild directory\");\n }\n\n\n [Fact]\n public void Make_Hello_World_Server_Correct()\n {\n var mockPrinter = new MockPrinter();\n string[] args = { \"-p\", \"9560\" };\n var serverMade = Program.MakeServer(args, mockPrinter);\n Assert.NotNull(serverMade);\n }\n\n [Fact]\n public void Make_Hello_World_Incorrect_Correct()\n {\n var mockPrinter = new MockPrinter();\n string[] args = { \"2750\", \"-p\" };\n var serverMade = Program.MakeServer(args, mockPrinter);\n Assert.Null(serverMade);\n }\n\n [Fact]\n public void Make_Hello_World_Incorrect_Correct_No_Port()\n {\n var mockPrinter = new MockPrinter();\n string[] args = { \"-p\", \"-p\" };\n var serverMade = Program.MakeServer(args, mockPrinter);\n Assert.Null(serverMade);\n }\n\n [Fact]\n public void Make_Server_Inncorect_NoArgs()\n {\n var mockPrinter = new MockPrinter();\n var correctOutput = new StringBuilder();\n correctOutput.Append(\"Invaild Number of Arguments.\\n\");\n correctOutput.Append(\"Can only be -p PORT\\n\");\n correctOutput.Append(\"or -p PORT -d DIRECTORY\\n\");\n correctOutput.Append(\"Examples:\\n\");\n correctOutput.Append(\"Server.exe -p 8080 -d C:/\\n\");\n correctOutput.Append(\"Server.exe -d C:/HelloWorld -p 5555\\n\");\n correctOutput.Append(\"Server.exe -p 9999\");\n\n var args = new[] { \"-s\" };\n var serverMade = Program.MakeServer(args, mockPrinter);\n Assert.Null(serverMade);\n mockPrinter.VerifyPrint(correctOutput.ToString());\n }\n\n [Fact]\n public void Main_Starting_Program()\n {\n string[] args = { };\n Assert.Equal(0, Program.Main(args));\n }\n\n [Fact]\n public void Test_Running_Of_Server()\n {\n var mockServer = new MockMainServer()\n .StubAcceptingNewConn();\n Program.RunServer(mockServer);\n mockServer.VerifyRun();\n mockServer.VerifyAcceptingNewConn();\n }\n\n [Fact]\n public void Make_Log_File()\n {\n var mockPrinter = new MockPrinter();\n\n string[] args = { \"-p\", \"10560\", \"-l\", \"c:/TestLog\" };\n var serverMade = Program.MakeServer(args, mockPrinter);\n Assert.Equal(\"c:/TestLog\", mockPrinter.Log);\n Assert.NotNull(serverMade);\n }\n }\n}"}}},{"rowIdx":968,"cells":{"language":{"kind":"string","value":"JavaScript"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1165,"string":"1,165"},"score":{"kind":"number","value":2.96875,"string":"2.96875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"// a tree is a list of nodes\nfunction find_bookmark_by_title(tree, title) {\n if (!tree)\n return null;\n \n for (var i=0; i0;}\n\t\n\t$(\".add\").click(function (event) {\n\t\tevent.preventDefault();\t\t\t\t\t\n\t\tvar inputitem = $('#newitem').val();\t\t\n\t\tif (inputitem == '')\n\t\t{\t\t\t\n\t\t\tvar empty_item = confirm(\"Item is empty, do you want to add an empty item?\");\n\t\t\tif (empty_item)\n\t\t\t{\n\t\t\t\t$(\"ul\").append(\"
  • Item
  • \");\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\t\t\t\n\t\t\t$(\"ul\").append(\"
  • \"+inputitem+\"
  • \");\n\t\t\t$('#newitem').val(\"\");\n\t\t}\n\t\t\n\t\t$(\".checkout\").show();\n\t});\n\n\t$('#shopping-items').on('click', '.remove', function(){ \n\t\t$(this).closest(\"li\").remove();\n\t});\t\n\n\t$('#shopping-items').on('click', '.checkout', function(){ \n\t\tevent.preventDefault();\t\n\t\t$(\"button\").prop('disabled',true);\n\t\t$(\"li\").css(\"text-decoration\",\"line-through\");\n\t\t$(\".singlecheck\").prop('checked', true);\n\t\t$(\"li\").find(\"img\").remove();\t\n\t\t$(\"#shopping-items li\").append(\"checked out\");\t\t\n\t\t$(this).text('All Checked Out');\n\t});\t\t \n\t\n\t$('#shopping-items').on('change','.singlecheck', function() {\t\t\n\t\tif ($(this).is(':checked'))\n\t\t{\t\t\t\n\t\t\t$(this).closest(\"li\").find(\"img\").remove();\t\n\t\t\t$(this).closest(\"li\").append(\"checked out\");\t\n\t\t\t$(\".checkout\").text('Checkout');\n\t\t\t$(\"button\").prop('disabled',false);\n\t\t\t$(this).closest('li').find(\"button\").prop('disabled',true);\n\t\t\t$(this).closest('li').css(\"text-decoration\",\"line-through\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tconsole.log(\"not checked\");\n\t\t\t$(this).closest(\"li\").find(\"img\").remove();\t\t\t\n\t\t\t$(\".checkout\").text('Checkout');\t\t\n\t\t\t$(\".checkout\").prop('disabled',false);\n\t\t\t$(\".add\").prop('disabled',false);\n\t\t\t$(this).closest(\"li\").find(\"button\").prop('disabled',false);\n\t\t\t$(this).closest('li').css(\"text-decoration\",\"none\");\n\t\t}\t\n\t});\t\n\t\n\t\n});"}}},{"rowIdx":970,"cells":{"language":{"kind":"string","value":"Python"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":135,"string":"135"},"score":{"kind":"number","value":2.609375,"string":"2.609375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"import datetime\nd={'Cumpleaños':20,'Ricardo':2002,'Fecha':datetime.date.today()}\nd.setdefault('Año minimo',datetime.MINYEAR)\nprint(d)"}}},{"rowIdx":971,"cells":{"language":{"kind":"string","value":"C++"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":479,"string":"479"},"score":{"kind":"number","value":2.765625,"string":"2.765625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#include \"DataStore.h\"\n#include \n\n\n/*\ntemplate < class T >\nDataStore::DataStore(uint16_t start, uint8_t maxdata ) :\n\tstartAddres(start), \n\tmaxData(maxdata)\n{\n\tlastData = 0;\n}\n*/\ntemplate < class T >\nvoid DataStore::pushBack(T data) {\n\tuint8_t length = sizeof(T);\n\tuint8_t * p = (uint8_t *) data;\n\n\tfor (uint8_t i = 0; i < length; i++) {\n\t\tEEPROM.write(startAddres + lastData, *p);\n\t\tp++;\n\t}\n}\n\n/*\ntemplate < class T >\nDataStore::~DataStore()\n{\n}\n*/\n"}}},{"rowIdx":972,"cells":{"language":{"kind":"string","value":"Java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3372,"string":"3,372"},"score":{"kind":"number","value":3.328125,"string":"3.328125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package net.Programmers;\n\nimport java.util.Comparator;\nimport java.util.PriorityQueue;\n\npublic class Sonf {\n //곡별로 음계 전체 만들기\n static String[][] pattern = new String[][]{{\"C#\",\"c\"},{\"D#\",\"d\"},{\"F#\",\"f\"},{\"G#\",\"g\"},{\"A#\",\"a\"}};\n public String solution(String m, String[] musicinfos) {\n String answer = \"(None)\";\n PriorityQueue queue = new PriorityQueue<>(new Comparator() {\n @Override\n public int compare(Song o1, Song o2) {\n if(o1.time==o2.time)return o1.start-o2.start;\n else return o2.time-o1.time;\n }\n });\n for(String s: musicinfos){\n String str[] = s.split(\",\");\n int time = getTime(str[0],str[1]);\n queue.offer(new Song(Integer.parseInt(str[0].replaceAll(\":\",\"\")),time,str[2],getFull(time,str[3])));\n }\n System.out.println(queue);\n while(!queue.isEmpty()){\n Song current = queue.poll();\n if(check(m,current))return current.name;\n }\n return answer;\n }\n //전체음계 구하기\n static String getFull(int time,String scale){\n StringBuilder total=new StringBuilder();\n scale = removeSharp(scale);\n System.out.println(time+scale);\n for(int i=0;i> {}\"\\\n .format(type(value), datatype, value, e)\n print(msg)\n raise\n"}}},{"rowIdx":974,"cells":{"language":{"kind":"string","value":"Python"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":854,"string":"854"},"score":{"kind":"number","value":2.5625,"string":"2.5625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"# data from:\n# LIGO open science center\n# www.gw-openscience.org/GW150914data/LOSC_Event_tutorial_GW150914.html\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.mlab import psd\nfrom matplotlib import rc\n\ndata = [np.loadtxt('H-H1_LOSC_4_V2-1126259446-32.txt'),\n np.loadtxt('L-L1_LOSC_4_V2-1126259446-32.txt') + 1.e-18]\nlabel = ['Hanford', 'Livingston']\ncolor = ['b', 'g']\n\nfs = 4096\nN = len(data[0])\n\nplt.figure(figsize=(6.4, 6))\nrc('text', usetex=True)\n\nfor (i,h) in enumerate(data):\n (S,f) = psd(h, Fs=fs, NFFT=N//8)\n plt.subplot(2,1,i+1)\n plt.axis([20, 2000, 5e-23, 5e-18])\n plt.loglog(f, np.sqrt(fs*S/2), color[i], label=label[i], lw=1)\n plt.legend()\n plt.ylabel(r'$\\sqrt{f_{\\rm c}\\, S(f)}$', fontsize=14)\n\nplt.xlabel('frequency / Hz', fontsize=14)\nplt.tight_layout()\nplt.savefig('fig2.eps')\nplt.show()\n"}}},{"rowIdx":975,"cells":{"language":{"kind":"string","value":"Markdown"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":9289,"string":"9,289"},"score":{"kind":"number","value":2.984375,"string":"2.984375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"# Introduction\nCe document a pour but de vous expliquer en 5 minutes de lecture (et 5 autres de \"digestion\" ;) ) tout ce que vous devez savoir sur le XML et le XPATH utilisé par le Référentiel législatif de l'AN et les données en \"OpenData\" qui en sont issues.\n\nVous en saurez assez pour comprendre tout le XML et effectuer les requêtes XPATH vous permettant d'exploiter les données de l'OpenData.\n\nXML et XPath sont des technologies riches et si vous voulez devenir un maitre Jedi dans ces matières vous devrez vous tourner vers d'autres sources d'information en ligne.\nCela ne devrait pas être nécessaire pour exploiter l'OpenData de l'Assemnblée nationale cependant.\n\n# XML\n\nLe XML se présente comme un format textuel dont voici un exemple.\nCe fichier XML serra la base de tous nos exemples subséquents.\n\n```XML\n\n \n \n PO711218\n MISINFO\n Formation des enseignants\n \n 2015-12-16\n \n 2016-10-05\n \n 14\n \n \n \n \n \n \n PO714518\n ASSEMBLEE\n Assemble nationale\n \n 2016-12-16\n \n 2018-10-05\n \n 14\n \n \n \n \n \n \n \n \n PA3445\n \n \n jean\n valjean\n \n \n \n \n PM3455\n Assemblee\n PA3445\n \n \n \n \n\n```\n\n## L'essentiel\n\n### Arbre\nun document XML est un arbre (il y a une \"racine\", unique, des \"branches\" et des \"feuilles\") de \"noeuds\". ces noeuds peuvent être de deux grands types : Les `Eléménts` et les `Attributs` (il y a d'autres tpes possibles mais vous ne les rencontrerez pas explicitement dans nos documents.)\n\n## Balise\n\n* Une balise est une chaine de charactère quelconque ('acteur', 'organe', 'ratatouille', 'poix123')\n* Une balise peut être ouvrante comprise entre les symboles < et > ( etc ...) ou fermante, comprise entre les caractères < et /> (, ).\n* Une balise peut enfin être \"vide\" ouvrante et fermante, comme ceci \n* Toute balise ouvrante doit être assoiciée à une balise fermante (ou être une balise vide, ouvrante et fermante à la fois)\n* Enfin, Les balises peuvent et doivent être imbriquée mais jamais se \"chevaucher\".\n\nExemple :\n\n ```xml\n \n \n \n \n ```\n\nMais jamais :\n\n ```xml\n \n \n \n \n \n \n```\n\n\n### élément\nUn élément est la réunion d'une balise ouvrante et fermante et de tout ce qui se trouve entre.\nPar exemple :\n```xml\n\n \n \n\n```\nL'élément `secretariat` contient deux autres éléments `secretaire`\n\n### Attribut\n\n## Concepts \"avancés\"\n\nCes concepts sont inutiles pour comprenndre les données de l'Open Data mais vous en aurez besoin pour des usages avancés des données avec des outils sophisitiqués.\n\n### Namespace\n\n### schémas\n\n# XPath\n\n## L'essentiel\nXPath est un langage de requếtage sur des documents au format XML.\nC'est à dire qu'une expression XPath appliqué à un document XML retourne entre zéro et `n` noeuds (éléments ou attributs).\n\nUne expression XPath simplement décrit le \"chemin\" pour accéder aux noeuds qu'elle souhaite récupérer, comme ceci :\n\n```/export/organes/organe```\nou\n```./organe```\n\nLe résultat de l'expression XPath est l'ensemble des noeuds qui satisfont à l'expression.\nLa façon la plus simple d'apréhender une expression XPath est de la considérer comme un 'chemin' sélectionnant les noeuds correspondant au parcours de ce chemin depuils le point d'évaluation.\n\nL'expression `/export/organes` limite ces noeuds aux fils de l'élément `Organes` eux même fils de la racine du document `export`.\nElle exprime ceci \"retournez moi les noeuds appelés `organe`, fils d'un élément `organes` lui même fils de l'élément racine (`export`).\nLes seuls noeud correspondants sont les deux éléments `organe` fils de `organes`, ce sont eux qui serront retournés, intégralement (avec leurs fils et tout leur contenu).\n\nL'expression `./organe` retourne les noeuds `organe` fils `/` du noeud courant `.`.\nEn traduction pas à pas \"du noeud ou vous êtes retournez moi les éléments fils de nom `organe`)\n\nSon résultat dépend donc de l'endroit du fichier XML où elle est évaluée.\n* Evaluée à la racine (``) cette expression ne retourne **rien** : Il n'y a pas d'élément `organe` fils de la racine (``).\n* Evaluée sur l'élément `organes` elle retourne le même résultat que l'expression précédente :les deux éléments `organe` du document exemple qui sont bien fils directs de l'élément `organes`.\n\nMais peut-être voulez vous seulement le *premier* élément organe ?\n```/export/organes/organe[1]```\nou le second\n```/export/organes/organe[2]```\n\nVous pourriez aussi vouloir récupérer **tous** les éléments `organe`, peut importe où ils sont placés dans l'arborescence :\n```//organe```\n le symbole `//` veut dire 'n'importe où en dessous', fils direct, petit fils, petit petit fils, etc ...\n\n## Un peu plus et ce sera assez ...\n\n### Selecteur\nDans l'exemple ```/export/organes/organe[1]``` l'expression entre crochets ```[]``` est un selecteur.\n\nUn sélecteur réduit le nombre de noeuds capturés par l'expression en posant une contrainte, un critère, un test sur les noeuds à cet endroit de l'expression.\nUn simple nombre `n` indique de sélectionner le noeud de rang `n`, mais il est possible de construire des expressions plus puissantes.\n\n```/export/organes/organe[uid=\"PO714518\"]```\nSélectionne uniquement l'organe fils direct de ```/export/organes/``` possédant un fils `uid` de valeur \"PO714518\" si il existe.\nDans notre exemple il en existe un, le second.\n\n```/export/organes/organe[.//dateDebut>\"2016-01-01\"]```\nSélectionne les organes fils de ```/export/organes/``` ayant un sous élément `dateDebut` postérieur au 1er janvier 2016.\nVous l'aurez remarqué l'expression de sélection est \"enracinée\" par défaut i.e. évaluée au point courant de l'expression, dans notre cas ```/export/organes/```, et nous pouvons utiliser la notation `//` pour sélectionner n'importe quel élément descendant `dateDebut` à partir ce ce point.\nEn l'occurence l'élément date début est en fait situé en `./viMoDe/dateDebut` et nous aurious pu écrire l'expression comme ceci :\n```/export/organes/organe[./viMoDe/dateDebut > \"2016-01-01\"]```\n\nL'expression 'sélecteur' peut être n'importe quelle expression XPath valide qui traduit une condition booléenne.\n\n## Any\nLe symbole `*` représente n'importe quel élément.\n Ainsi l'expression :\n ```//*[uid=\"PO714518\"]```\n représente n'importe quel élément possédant un fils direct `uid` de valeur `PO714518`\n =>un organe dans notre exemple :\n ```xml\n \n PO714518\n ASSEMBLEE\n ...\n```\n\n ```/*[uid=\"PO714518\"]```\nreprésente n'importe quel élément racine possédant un fils direct `uid` de valeur `PO714518`\n=> aucun dans notre exemple\n\n\n ```//*[uid=\"PO714518\"]```\n représente n'importe quel élément racine possédant un descendant `uid` de valeur `PO714518`\n => le document racine 'export' en entier dans notre exemple\n\n\n\n### Filtrer sur un attribut, xsi:nil ...\n\nEnfin, pour tester la valeur d'un attribut il faut utiliser l'opérateur `@`\n\n```//organe[@xsi:type=\"OrganeParlementaire_Type\"]```\nsélectionne tous les organes ayant un attribut xsi:type de valeur \"OrganeParlementaire_Type\"\n=> dans notre cas les deux éléments organes répondent à ce critère.\n\n```//*[@xsi:nil=\"true\"]``` ...\nretournera les 4 éléments `` **et** deux élémens `` dans notre exemple... vous devriez comprendre pourquoi à présent ;)\n\nL'expression :\n```//secretaire[@xsi:nil=\"true\"]```\nne retournerait, elle, que les 4 éléments ``\n\n\n\n# Et en Python ? lxml et co ..."}}},{"rowIdx":976,"cells":{"language":{"kind":"string","value":"Python"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1073,"string":"1,073"},"score":{"kind":"number","value":3.765625,"string":"3.765625"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"def maxi(*l):\n\tif len(l) == 0:\n\t\treturn 0\n\n\tm = l[0]\n\n\tfor ix in range(1, len(l)):\n\t\tif l[ix] > m:\n\t\t\tm = l[ix]\n\n\treturn m\n\ndef mini(*l):\n\tif len(l) == 0:\n\t\treturn 0\n\n\tm = l[0]\n\n\tfor ix in range(1, len(l)):\n\t\tif l[ix] < m:\n\t\t\tm = l[ix]\n\n\treturn m\n\n\ndef media(*l):\n\tif len(l) == 0:\n\t\treturn 0\n\n\tsuma = 0\n\tfor valor in l:\n\t\tsuma += valor\n\n\treturn suma / len(l)\n\nfunciones = {\n\t\"max\": maxi,\n\t\"min\": mini,\n\t\"med\": media\n}\n\ndef returnF(nombre):\n\tnombre = nombre.lower()\n\tif nombre in funciones.keys():\n\t\treturn funciones[nombre]\n\n\treturn None\n\n# A continuación la función returnF devolverá el nombre de otra función.\nprint(returnF(\"max\"))\n\n# Si quiero que la función \"max\" se ejecute a través de la función \"returnF\" escribiré lo siguiente:\nprint(returnF(\"max\")(1, 3, -1, 15, 9))\n\n# Si quiero que la función \"min\" se ejecute a través de la función \"returnF\" escribiré lo siguiente:\nprint(returnF(\"min\")(1, 3, -1, 15, 9))\n\n# Si quiero que la función \"med\" se ejecute a través de la función \"returnF\" escribiré lo siguiente:\nprint(returnF(\"med\")(1, 3, -1, 15, 9))\n"}}},{"rowIdx":977,"cells":{"language":{"kind":"string","value":"C"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1209,"string":"1,209"},"score":{"kind":"number","value":2.875,"string":"2.875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#define _GNU_SOURCE\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"jjp_lib.h\"\n\nint flag_18;\n\nvoid fSIGSTP(int signum) {\n if(flag_18==0) {\n flag_18=1;\n sigset_t mask;\n sigfillset(&mask);\n sigdelset(&mask, SIGTSTP);\n printf(\"\\n\\nWaiting for:\\n\\tCtrl+Z - resume\\n\\tCtrl+C - exit\\n\");\n sigsuspend(&mask);\n \n }\n else { \n flag_18=0;\n printf(\"\\n\\n\");\n }\n}\n\nvoid fSIGINT() {\n printf(\"\\n\\nProgram received signal SIGINT(2). Exiting...\\n\\n\");\n exit(0);\n}\n\nint main(int argc, char** argv) {\n flag_18=0;\n struct sigaction sigint_action;\n sigint_action.sa_handler = fSIGINT;\n sigemptyset(&sigint_action.sa_mask);\n sigint_action.sa_flags = 0;\n\n signal(SIGTSTP, fSIGSTP);\n sigaction(SIGINT, &sigint_action, NULL);\n\n time_t timer;\n char buffer[26];\n struct tm* tm_info;\n printf(\"\\nPID:\\t%d\\n\", getpid());\n while(1) {\n sleep(1);\n time(&timer);\n tm_info = localtime(&timer);\n\n strftime(buffer, 26, \"%Y-%m-%d %H:%M:%S\", tm_info);\n puts(buffer);\n }\n\n return 0;\n}"}}},{"rowIdx":978,"cells":{"language":{"kind":"string","value":"Java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":342,"string":"342"},"score":{"kind":"number","value":2.421875,"string":"2.421875"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package base.components;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\n\nimport base.model.Engine;\n\n@Component(\"car\")\npublic class Car {\n\tEngine engine;\n\t\n\t@Autowired\n\tpublic void setEngine(Engine engine){\n\t\tthis.engine = engine;\n\t\tSystem.out.println(\"car engine set\");\n\n\t}\n}\n"}}},{"rowIdx":979,"cells":{"language":{"kind":"string","value":"Java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1798,"string":"1,798"},"score":{"kind":"number","value":3.765625,"string":"3.765625"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package lecture11;\n\npublic class ArrayDeque implements Deque {\n\n\tprivate Object[] data;\n\tprivate int first, size;\n\t\n\tpublic ArrayDeque(int capacity) {\n\t\tthis.data = new Object[capacity];\n\t\tthis.first = 0;\n\t\tthis.size = 0;\n\t}\n\t\n\t@Override\n\tpublic void addFirst(E e) {\n\t\tif (this.size == this.data.length)\n\t\t\tthis.resize(this.data.length * 2);\n\t\tthis.first = (this.first + this.data.length - 1) % this.data.length;\n\t\tthis.data[this.first] = e;\n\t\tthis.size++;\n\t}\n\n\t@Override\n\tpublic void addLast(E e) {\n\t\tif (this.size == this.data.length) \n\t\t\tthis.resize(this.data.length * 2);\n\t\tint nextAvailable = (this.first + this.size) % this.data.length;\n\t\tthis.data[nextAvailable] = e;\n\t\tthis.size++;\n\t}\n\n\t@Override\n\tpublic E removeFirst() {\n\t\tif (this.isEmpty()) \n\t\t\tthrow new IllegalStateException(\"Deque is empty\");\n\t\tE val = (E) this.data[this.first];\n\t\tthis.data[this.first] = null;\n\t\tthis.first = (this.first + 1) % this.data.length;\n\t\tthis.size--;\n\t\treturn val;\n\t}\n\n\t@Override\n\tpublic E removeLast() {\n\t\tif (this.isEmpty())\n\t\t\tthrow new IllegalStateException(\"Deque is empty\");\n\t\tint last = (this.first + this.size - 1) % this.data.length;\n\t\tE val = (E) this.data[last];\n\t\tthis.data[last] = null;\n\t\tthis.size--;\n\t\treturn val;\n\t}\n\n\t@Override\n\tpublic E first() {\n\t\treturn (E) this.data[this.first];\n\t}\n\n\t@Override\n\tpublic E last() {\n\t\tint last = (this.first + this.size - 1) % this.data.length;\n\t\treturn (E) this.data[last];\n\t}\n\n\t@Override\n\tpublic int size() {\n\t\treturn this.size;\n\t}\n\n\t@Override\n\tpublic boolean isEmpty() {\n\t\treturn this.size == 0;\n\t}\n\t\n\tprivate void resize(int newSize) {\n\t\tObject[] larger = new Object[newSize];\n\t\tfor (int i = 0; i < this.size; i++) {\n\t\t\tint j = (this.first + i) % this.data.length;\n\t\t\tlarger[i] = this.data[j];\n\t\t}\n\t\tthis.data = larger;\n\t\tthis.first = 0;\n\t}\n\n}\n"}}},{"rowIdx":980,"cells":{"language":{"kind":"string","value":"C#"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3875,"string":"3,875"},"score":{"kind":"number","value":2.65625,"string":"2.65625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"using System;\nusing Skybrud.Social.Sonos.Endpoints;\nusing Skybrud.Social.Sonos.OAuth;\n\nnamespace Skybrud.Social.Sonos {\n\n /// \n /// Class working as an entry point to the Sonos API.\n /// \n public class SonosService {\n\n #region Properties\n\n /// \n /// Gets a reference to the internal OAuth client.\n /// \n public SonosOAuthClient Client { get; }\n \n /// \n /// Gets a reference to the groups endpoint.\n /// \n public SonosGroupsEndpoint Groups { get; }\n\n /// \n /// Gets a reference to the households endpoint.\n /// \n public SonosHouseholdsEndpoint Households { get; }\n\n /// \n /// Gets a reference to the players endpoint.\n /// \n public SonosPlayersEndpoint Players { get; }\n\n #endregion\n\n #region Constructors\n\n private SonosService(SonosOAuthClient client) {\n Client = client;\n Groups = new SonosGroupsEndpoint(this);\n Households = new SonosHouseholdsEndpoint(this);\n Players = new SonosPlayersEndpoint(this);\n }\n\n #endregion\n\n #region Static methods\n\n /// \n /// Initialize a new service instance from the specified OAuth .\n /// \n /// The OAuth client.\n /// The created instance of .\n public static SonosService CreateFromOAuthClient(SonosOAuthClient client) {\n if (client == null) throw new ArgumentNullException(nameof(client));\n return new SonosService(client);\n }\n\n /// \n /// Initializes a new service instance from the specifie OAuth 2 .\n /// \n /// The access token.\n /// The created instance of .\n public static SonosService CreateFromAccessToken(string accessToken) {\n if (String.IsNullOrWhiteSpace(accessToken)) throw new ArgumentNullException(nameof(accessToken));\n return new SonosService(new SonosOAuthClient(accessToken));\n }\n\n ///// \n ///// Initializes a new instance based on the specified .\n ///// \n ///// The client ID.\n ///// The client secret.\n ///// The refresh token of the user.\n ///// The created instance of .\n //public static SonosService CreateFromRefreshToken(string clientId, string clientSecret, string refreshToken) {\n\n // if (String.IsNullOrWhiteSpace(clientId)) throw new ArgumentNullException(nameof(clientId));\n // if (String.IsNullOrWhiteSpace(clientSecret)) throw new ArgumentNullException(nameof(clientSecret));\n // if (String.IsNullOrWhiteSpace(refreshToken)) throw new ArgumentNullException(nameof(refreshToken));\n\n // // Initialize a new OAuth client\n // SonosOAuthClient client = new SonosOAuthClient(clientId, clientSecret);\n\n // // Get an access token from the refresh token.\n // SonosTokenResponse response = client.GetAccessTokenFromRefreshToken(refreshToken);\n\n // // Update the OAuth client with the access token\n // client.AccessToken = response.Body.AccessToken;\n\n // // Initialize a new service instance\n // return new SonosService(client);\n\n //}\n\n #endregion\n\n }\n\n}"}}},{"rowIdx":981,"cells":{"language":{"kind":"string","value":"Python"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":341,"string":"341"},"score":{"kind":"number","value":2.71875,"string":"2.71875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"class Solution:\n def isHappy(self, n: int) -> bool:\n\n ht = dict()\n while n:\n if 1 in ht:\n return True\n if n in ht:\n return False\n ht[n] = 0\n tmp = 0\n while n:\n tmp += (n%10) ** 2\n n //= 10\n n = tmp\n"}}},{"rowIdx":982,"cells":{"language":{"kind":"string","value":"Java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2456,"string":"2,456"},"score":{"kind":"number","value":1.8203125,"string":"1.820313"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":["LicenseRef-scancode-warranty-disclaimer","Apache-2.0","LicenseRef-scancode-unknown-license-reference"],"string":"[\n \"LicenseRef-scancode-warranty-disclaimer\",\n \"Apache-2.0\",\n \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"/*\n * Copyright © 2012-2014 Cask Data, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\n\npackage co.cask.tephra.persist;\n\nimport co.cask.tephra.TxConstants;\nimport co.cask.tephra.metrics.TxMetricsCollector;\nimport co.cask.tephra.snapshot.SnapshotCodecProvider;\nimport org.apache.hadoop.conf.Configuration;\nimport org.apache.hadoop.hdfs.MiniDFSCluster;\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.ClassRule;\nimport org.junit.rules.TemporaryFolder;\n\nimport java.io.IOException;\n\n\n/**\n * Tests persistence of transaction snapshots and write-ahead logs to HDFS storage, using the\n * {@link HDFSTransactionStateStorage} and {@link HDFSTransactionLog} implementations.\n */\npublic class HDFSTransactionStateStorageTest extends AbstractTransactionStateStorageTest {\n\n @ClassRule\n public static TemporaryFolder tmpFolder = new TemporaryFolder();\n\n private static MiniDFSCluster dfsCluster;\n private static Configuration conf;\n\n @BeforeClass\n public static void setupBeforeClass() throws Exception {\n Configuration hConf = new Configuration();\n hConf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, tmpFolder.newFolder().getAbsolutePath());\n\n dfsCluster = new MiniDFSCluster.Builder(hConf).numDataNodes(1).build();\n conf = new Configuration(dfsCluster.getFileSystem().getConf());\n }\n\n @AfterClass\n public static void tearDownAfterClass() throws Exception {\n dfsCluster.shutdown();\n }\n\n @Override\n protected Configuration getConfiguration(String testName) throws IOException {\n // tests should use the current user for HDFS\n conf.unset(TxConstants.Manager.CFG_TX_HDFS_USER);\n conf.set(TxConstants.Manager.CFG_TX_SNAPSHOT_DIR, tmpFolder.newFolder().getAbsolutePath());\n return conf;\n }\n\n @Override\n protected AbstractTransactionStateStorage getStorage(Configuration conf) {\n return new HDFSTransactionStateStorage(conf, new SnapshotCodecProvider(conf), new TxMetricsCollector());\n }\n}\n"}}},{"rowIdx":983,"cells":{"language":{"kind":"string","value":"C"},"src_encoding":{"kind":"string","value":"ISO-8859-1"},"length_bytes":{"kind":"number","value":1805,"string":"1,805"},"score":{"kind":"number","value":2.765625,"string":"2.765625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"/* \n * Projeto: Teclado e Display 1\n * Arquivo: App.c\n * Autor: JABNeto\n * Data: 10/02/2016\n */\n\n#include \n#include \n#include \n#include \"Base_1.h\"\n#include \"Oscilador.h\"\n\n\n//Prottipos das funes -----------------------------\nvoid Timer0_Inicializacao (void);\nvoid Timer0_Recarga (void);\n\n\n//Alocao de memria para o mdulo-------------------\nUlong Contador;\n\nstruct\n{\n Uchar Temporizador100ms;\n\n union\n {\n Uchar Valor;\n \n struct\n {\n Uchar Contador:1; \n \n };\n }EventosDe100ms;\n}TMR0_Eventos;\n\n\n//Funes do mdulo ----------------------------------\nint main(int argc, char** argv)\n{\n Oscilador_Inicializacao();\n Display_InicializaVarredura();\n Timer0_Inicializacao();\n \n Contador = 0;\n Varredura.Opcoes.OmiteZeros = _SIM;\n Varredura.Opcoes.ExibePonto5 = _SIM;\n Display_ExibeNumero(Contador);\n \n INTCONbits.GIEH = 1;\n \n while(1)\n {\n if(TMR0_Eventos.EventosDe100ms.Contador == 1)\n {\n TMR0_Eventos.EventosDe100ms.Contador = 0;\n \n if (++Contador == 10000) Contador = 0;\n Display_ExibeNumero(Contador);\n }\n }\n \n return (EXIT_SUCCESS);\n}\n\n\n/* Interrupt_High\n * Atendimento das interrupes de alta prioridade\n */\nvoid interrupt high_priority Interrupt_High(void)\n{\n \n if ((INTCONbits.TMR0IE == 1) &&\n (INTCONbits.TMR0IF == 1))\n {\n Timer0_Recarga();\n \n if(--TMR0_Eventos.Temporizador100ms == 0)\n {\n TMR0_Eventos.Temporizador100ms = 100;\n TMR0_Eventos.EventosDe100ms.Valor = 0xFF;\n }\n \n //Funes do usurio -------------------------\n Display_ExecutaVarredura();\n }\n}\n\n"}}},{"rowIdx":984,"cells":{"language":{"kind":"string","value":"Python"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":570,"string":"570"},"score":{"kind":"number","value":3.234375,"string":"3.234375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"# -*- coding: utf-8 -*-\r\n\r\n\r\nimport time\r\nimport math\r\nimport numpy as np\r\n\r\nx = [i for i in xrange(1000 * 1000)]\r\nstart = time.clock()\r\nfor i, t in enumerate(x):\r\n x[i] = math.sin(t)\r\nprint \"math.sin:\", time.clock() - start\r\n\r\nx = [i for i in xrange(1000 * 1000)]\r\nx = np.array(x)\r\nstart = time.clock()\r\nnp.sin(x, x)\r\nprint \"numpy.sin:\", time.clock() - start\r\n\r\nx = np.arange(1, 4)\r\ny = np.arange(2, 5)\r\n\r\nprint np.add(x, y)\r\nprint np.subtract(y, x)\r\nprint np.multiply(x, y)\r\nprint np.divide(y, x)\r\nprint np.true_divide(y, x)\r\nprint np.floor_divide(y, x)\r\n\r\n\r\n\r\n\r\n\r\n"}}},{"rowIdx":985,"cells":{"language":{"kind":"string","value":"Python"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":804,"string":"804"},"score":{"kind":"number","value":2.59375,"string":"2.59375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"# connect\n# close\n\n# dinh nghia class db\n# co self , nam, usr., host, db_password, 4 thong so \n\n# \"\"\"\"db_host = localhost\n# db_user = root\n# db_name = cdcol\n# db_password = root\n# \"\"\"\nimport MySQLdb\nimport ConfigLoader\n\nclass Database(object):\n\t\"\"\"docstring for Database\"\"\"\n\tdef __init__(self, host, user, db, password):\n\t\tself.host = raw_input(\"Nhap Ten host :\")\n\t\tself.user = raw_input(\"Nhap Ten User :\")\n\t\tself.db = raw_input(\"Nhap Ten Database :\")\n\t\tself.password = raw_input(\"Nhap Password :\")\n\tdef connect():\n\t\tcon = MySQLdb.connect(self.host,self.user,self.db,self.password)\n\t\tcur = con.cursor() # dung con tro de lam viec vs DB\n\t\tcur.execute(\"SELECT VERSION()\")\n\t\trow = cursor.fetchall()\n\t\tprint \"server version\",row[0]\n\t\tcursor.close()\n\t\tcon.close()\n\n\nif __name__ == '__main__':\n\tmain()\n\n"}}},{"rowIdx":986,"cells":{"language":{"kind":"string","value":"Java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2027,"string":"2,027"},"score":{"kind":"number","value":2.875,"string":"2.875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package com.finago.interview.fileProcessor;\r\n\r\nimport java.io.IOException;\r\nimport java.nio.file.Files;\r\nimport java.nio.file.Paths;\r\nimport java.nio.file.StandardCopyOption;\r\n\r\nimport javax.xml.parsers.ParserConfigurationException;\r\n\r\nimport com.finago.interview.task.Constants;\r\n\r\n/**\r\n * \r\n * @author Ajay Naik File Processor Usage : This class will validate the xml\r\n * with xsd , read xml if the validation is successful move all xml to\r\n * archive location and delete all pdf\r\n */\r\npublic class FileProcessor {\r\n\t/**\r\n\t * This class will validate the xml with xsd read xml if the validation is\r\n\t * successful. if validation is successfull perform the logic as given if\r\n\t * validation is not successful move the files to error location\r\n\t * \r\n\t * \r\n\t * @throws ParserConfigurationException\r\n\t */\r\n\r\n\t/**\r\n\t * \r\n\t * Main method method to process the xml\r\n\t * \r\n\t * @param xmlString\r\n\t * @throws ParserConfigurationException\r\n\t */\r\n\tpublic static void process(String xmlString) throws ParserConfigurationException {\r\n\t\tif (FileUtility.fileExists(xmlString)) {\r\n\t\t\tif (new XMLValidator().validate(xmlString, Constants.XSDFILEPATH)) {\r\n\t\t\t\tSystem.out.println(\"validation is successful and Processing File start \" + xmlString);\r\n\t\t\t\tXMLReader.readANDProcessXML(xmlString);\r\n\r\n\t\t\t\tSystem.out.println(\"validation is successful and Processing File end \" + xmlString);\r\n\t\t\t} else {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tif (FileUtility.fileExists(xmlString)) {\r\n\t\t\t\t\t\tSystem.out.println(\r\n\t\t\t\t\t\t\t\txmlString + \" validation is un-successful and moving the file to error location \");\r\n\t\t\t\t\t\tFiles.move(Paths.get(xmlString),\r\n\t\t\t\t\t\t\t\tPaths.get(Constants.XMLERRORFOLDER + Paths.get(xmlString).getFileName().toString()),\r\n\t\t\t\t\t\t\t\tStandardCopyOption.REPLACE_EXISTING);\r\n\t\t\t\t\t}\r\n\t\t\t\t} catch (IOException e) {\r\n\t\t\t\t\t// TODO Auto-generated catch block\r\n\t\t\t\t\tSystem.out.println(\"Processing fail for xml \"+ xmlString);\r\n\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}else {\r\n\t\t\tSystem.out.println(xmlString + \" File doesn't exists\");\r\n\t\t}\r\n\r\n\t}\r\n\r\n}\r\n"}}},{"rowIdx":987,"cells":{"language":{"kind":"string","value":"Python"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":385,"string":"385"},"score":{"kind":"number","value":3.9375,"string":"3.9375"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#Multi line printing versions\n#You can print with defining it into variable then print variable\nmessage = \"\"\"This message will\nspan several\nlines.\"\"\"\nprint(message)\n#Or you can write you multi line printing into directly print function\nprint(\"\"\"This message will span\nseveral lines\nof the text.\"\"\")\n\n\n# Different String versions\nprint('This is a string.')\nprint(\"\"\"And so is this.\"\"\")\n"}}},{"rowIdx":988,"cells":{"language":{"kind":"string","value":"Java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":6933,"string":"6,933"},"score":{"kind":"number","value":2.234375,"string":"2.234375"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package com.ravisravan.capstone.UI;\n\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.support.v4.app.Fragment;\nimport android.support.v4.app.LoaderManager;\nimport android.support.v4.content.CursorLoader;\nimport android.support.v4.content.Loader;\nimport android.support.v7.widget.GridLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.view.ViewTreeObserver;\n\nimport com.ravisravan.capstone.R;\nimport com.ravisravan.capstone.UI.adapters.RemindersAdapter;\nimport com.ravisravan.capstone.data.ReminderContract;\n\n/**\n * A simple {@link Fragment} subclass.\n * Activities that contain this fragment must implement the\n * {@link AllEventsFragment.Callback} interface\n * to handle interaction events.\n */\npublic class AllEventsFragment extends Fragment implements LoaderManager.LoaderCallbacks {\n\n private final int REMINDERS_LOADER = 200;\n private RecyclerView recyclerview_reminders;\n private RemindersAdapter mRemindersAdapter;\n private Callback mListener;\n\n public AllEventsFragment() {\n // Required empty public constructor\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n }\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_all_events, container, false);\n recyclerview_reminders = (RecyclerView) rootview.findViewById(R.id.recyclerview_reminders);\n\n //TODO: configure the spancount in integers and use\n recyclerview_reminders.setLayoutManager(new GridLayoutManager(getActivity(), 1));\n View emptyView = rootview.findViewById(R.id.recyclerview_reminders_empty);\n mRemindersAdapter = new RemindersAdapter(getActivity(), emptyView,\n new RemindersAdapter.ReminderAdapterOnClickHandler() {\n @Override\n public void onClick(Long id, RemindersAdapter.ReminderViewHolder vh) {\n ((Callback) getActivity())\n .onItemSelected(ReminderContract.Reminders.buildReminderUri(id), vh);\n }\n });\n recyclerview_reminders.setAdapter(mRemindersAdapter);\n // use this setting to improve performance if you know that changes\n // in content do not change the layout size of the RecyclerView\n recyclerview_reminders.setHasFixedSize(true);\n return rootview;\n }\n\n @Override\n public void onActivityCreated(Bundle savedInstanceState) {\n // we hold for transition here just in case the activity\n // needs to be recreated. In a standard return transition,\n // this doesn't actually make a difference.\n //TODO: transitions\n// if (mHoldForTransition) {\n// getActivity().supportPostponeEnterTransition();\n// }\n getLoaderManager().initLoader(REMINDERS_LOADER, null, this);\n super.onActivityCreated(savedInstanceState);\n }\n\n @Override\n public void onAttach(Context context) {\n super.onAttach(context);\n if (context instanceof Callback) {\n mListener = (Callback) context;\n } else {\n throw new RuntimeException(context.toString()\n + \" must implement OnFragmentInteractionListener\");\n }\n }\n\n @Override\n public void onDetach() {\n super.onDetach();\n mListener = null;\n }\n\n @Override\n public Loader onCreateLoader(int id, Bundle args) {\n //1 is active 0 is inactive\n return new CursorLoader(getActivity(), ReminderContract.Reminders.CONTENT_URI, null,\n ReminderContract.Reminders.COLUMN_STATE + \" = ?\", new String[]{\"1\"},\n ReminderContract.Reminders.COLUMN_CREATED_DATE);\n }\n\n @Override\n public void onLoadFinished(Loader loader, Cursor data) {\n mRemindersAdapter.swapCursor(data);\n recyclerview_reminders.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {\n @Override\n public boolean onPreDraw() {\n // Since we know we're going to get items, we keep the listener around until\n // we see Children.\n recyclerview_reminders.getViewTreeObserver().removeOnPreDrawListener(this);\n if (recyclerview_reminders.getChildCount() > 0) {\n int position = 0;\n// if (position == RecyclerView.NO_POSITION &&\n// -1 != mInitialSelectedMessage) {\n// Cursor data = mMessagesAdapter.getCursor();\n// int count = data.getCount();\n// int messageColumn = data.getColumnIndex(ReminderContract.MessageLkpTable._ID);\n// for (int i = 0; i < count; i++) {\n// data.moveToPosition(i);\n// if (data.getLong(messageColumn) == mInitialSelectedMessage) {\n// position = i;\n// break;\n// }\n// }\n// }\n //if (position == RecyclerView.NO_POSITION) position = 0;\n // If we don't need to restart the loader, and there's a desired position to restore\n // to, do so now.\n recyclerview_reminders.smoothScrollToPosition(position);\n RecyclerView.ViewHolder vh = recyclerview_reminders.findViewHolderForAdapterPosition(position);\n// if (null != vh) {\n// mRemindersAdapter.selectView(vh);\n// }\n return true;\n } else {\n\n }\n return false;\n }\n });\n }\n\n @Override\n public void onLoaderReset(Loader loader) {\n mRemindersAdapter.swapCursor(null);\n }\n\n /**\n * This interface must be implemented by activities that contain this\n * fragment to allow an interaction in this fragment to be communicated\n * to the activity and potentially other fragments contained in that\n * activity.\n *

    \n * See the Android Training lesson Communicating with Other Fragments for more information.\n */\n public interface Callback {\n /**\n * ViewReminder for when an item has been selected.\n */\n public void onItemSelected(Uri uri, RemindersAdapter.ReminderViewHolder vh);\n }\n}\n"}}},{"rowIdx":989,"cells":{"language":{"kind":"string","value":"Markdown"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":5800,"string":"5,800"},"score":{"kind":"number","value":2.578125,"string":"2.578125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"# circos-utilities\n\nUtility scripts for working with Circos.\n\n# The scripts\n\n* UCSC_chrom_sizes_2_circos_karyotype.py\n> UCSC chrom.sizes files --> karyotype.tab file for use in Circos\n\nTakes a URL for a UCSC `chrom.sizes` file and makes a `karyotype.tab` file from it for use with Circos.\n\nVerified compatible with both Python 2.7 and Python 3.6.\n\nWritten to run from command line or pasted/loaded/imported inside a Jupyter notebook cell. \nThe main ways to run the script are demonstrated in the notebook [`demo UCSC_chrom_sizes_2_circos_karyotype script.ipynb`](https://github.com/fomightez/sequencework/blob/master/circos-utilities/demo%20UCSC_chrom_sizes_2_circos_karyotype%20script.ipynb) that is included in this repository. (That notebook can be viewed in a nicer rendering [here](https://nbviewer.jupyter.org/github/fomightez/sequencework/blob/master/circos-utilities/demo%20UCSC_chrom_sizes_2_circos_karyotype%20script.ipynb).)\n\nTo determine the URL to feed the script, google `YOUR_ORGANISM genome UCSC chrom.sizes`, where you replace `YOUR_ORGANISM` with your organism name and then adapt the path you see in the best match to be something similar to \n`http://hgdownload.cse.ucsc.edu/goldenPath/sacCer3/bigZips/sacCer3.chrom.sizes` -or-\n`http://hgdownload.cse.ucsc.edu/goldenPath/canFam2/bigZips/canFam2.chrom.sizes`. \nYou can get an idea of what is available by exploring the top section [here](http://hgdownload.cse.ucsc.edu/downloads.html); clicking on the arrows creates drop-down lists reveal many genomes for each category.\n\nImportantly, this script is intended for organisms without cytogenetic bands, such as dog, cow, yeast, etc.. \n(For organisms with cytogenetic band data: Acquiring the cytogenetic bands information is described [here](http://circos.ca/tutorials/lessons/ideograms/karyotypes/), about halfway down \nthe page where it says, \"obtain the karyotype structure from...\". \nUnfortunately, it seems the output to which one is directed to by those instructions is not\ndirectly useful in Circos(?). Fortunately, though as described [here](http://circos.ca/documentation/tutorials/quick_start/hello_world/), \"Circos ships with several predefined karyotype files for common sequence \nassemblies: human, mouse, rat, and drosophila. These files are located in \ndata/karyotype within the Circos distribution.\" And also included there is a script for converting the cytogenetic band data to karyotype, see [here](http://circos.ca/documentation/tutorials/quick_start/hello_world/) and [here](https://groups.google.com/d/msg/circos-data-visualization/B55NlByQ6jY/nKWGSPsXCwAJ).)\n\nExample call to run script from command line:\n```\npython UCSC_chrom_sizes_2_circos_karyotype.py http://hgdownload.cse.ucsc.edu/goldenPath/sacCer3/bigZips/sacCer3.chrom.sizes\n```\n(Alternatively, upload the script to a Jupyter environment and use `%run UCSC_chrom_sizes_2_circos_karyotype.py http://hgdownload.cse.ucsc.edu/goldenPath/sacCer3/bigZips/sacCer3.chrom.sizes` in a Python-backed notebook to run the example.)\n\nExample input from http://hgdownload.cse.ucsc.edu/goldenPath/sacCer3/bigZips/sacCer3.chrom.sizes :\n```\nchrIV 1531933\nchrXV 1091291\nchrVII 1090940\nchrXII 1078177\nchrXVI 948066\nchrXIII 924431\nchrII 813184\nchrXIV 784333\nchrX 745751\nchrXI 666816\nchrV 576874\nchrVIII 562643\nchrIX 439888\nchrIII 316620\nchrVI 270161\nchrI 230218\nchrM 85779\n```\n\nExample output sent to file (tab-separated):\n```\nchr - Sc-chrIV chrIV 0 1531933 black\nchr - Sc-chrXV chrXV 0 1091291 black\nchr - Sc-chrVII chrVII 0 1090940 black\nchr - Sc-chrXII chrXII 0 1078177 black\nchr - Sc-chrXVI chrXVI 0 948066 black\nchr - Sc-chrXIII chrXIII 0 924431 black\nchr - Sc-chrII chrII 0 813184 black\nchr - Sc-chrXIV chrXIV 0 784333 black\nchr - Sc-chrX chrX 0 745751 black\nchr - Sc-chrXI chrXI 0 666816 black\nchr - Sc-chrV chrV 0 576874 black\nchr - Sc-chrVIII chrVIII 0 562643 black\nchr - Sc-chrIX chrIX 0 439888 black\nchr - Sc-chrIII chrIII 0 316620 black\nchr - Sc-chrVI chrVI 0 270161 black\nchr - Sc-chrI chrI 0 230218 black\nchr - Sc-chrM chrM 0 85779 black\n```\n\n\n#### For running in a Jupyter notebook:\n\nTo use this script after pasting or loading into a cell in a Jupyter notebook, in the next cell define the URL and then call the main function similar to below:\n```\nurl = \"http://hgdownload.cse.ucsc.edu/goldenPath/sacCer3/bigZips/sacCer3.chrom.sizes\"\nspecies_code = \"Ys\"\nUCSC_chrom_sizes_2_circos_karyotype(url, species_code)\n```\n-or-\n\n```\nUCSC_chrom_sizes_2_circos_karyotype(url)\n```\nWithout supplying a second argument, a species code will be extracted automatically and used.\n\nNote that `url` is actually not needed if you are using the yeast one because that specific one is hardcoded in script as default.\nIn fact, because I hardcoded in defaults, just `main()` will indeed work for yeast after script pasted in or loaded into a cell.\nSee [here](https://nbviewer.jupyter.org/github/fomightez/sequencework/blob/master/circos-utilities/demo%20UCSC_chrom_sizes_2_circos_karyotype%20script.ipynb) for a notebook demonstrating use within a Jupyter notebook.\n\n\nRelated\n-------\n\n- [circos-binder](https://github.com/fomightez/circos-binder) - for running Circos in your browser without need for downloads, installations, or maintenance.\n\n- [gos: (epi)genomic visualization in python](https://gosling-lang.github.io/gos/) looks to circos-like images, see that page in the link for representative examples in the image at the top. [The Example Gallery](https://gosling-lang.github.io/gos/gallery/index.html) has a link to a Circos-style example under the 'Others' heading; it includes code [here](https://gosling-lang.github.io/gos/gallery/circos.html).\n"}}},{"rowIdx":990,"cells":{"language":{"kind":"string","value":"Java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":11306,"string":"11,306"},"score":{"kind":"number","value":3.046875,"string":"3.046875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"import javax.swing.*;\r\nimport java.awt.*;\r\nimport java.awt.event.*;\r\n\r\n/**\r\n * in this class we design the interface of our calculator.\r\n *\r\n * @author Mahdi Hejarti 9723100\r\n * @since 2020.04.23\r\n */\r\n\r\npublic class View {\r\n\r\n private JFrame calFrame;\r\n private JPanel standardMode;\r\n private JPanel scientificMode;\r\n private JButton[] buttons1;\r\n private JButton[] buttons2;\r\n private JTextArea display1;\r\n private JTextArea display2;\r\n\r\n private Controller controller;\r\n\r\n /**\r\n * constructor of View class\r\n */\r\n public View() {\r\n\r\n Handler handler = new Handler();\r\n controller = new Controller();\r\n\r\n // create main frame\r\n calFrame = new JFrame();\r\n designCalculatorFrame();\r\n\r\n // add a tab to frame to change mode\r\n JTabbedPane modeTabbedPane = new JTabbedPane();\r\n calFrame.setContentPane(modeTabbedPane);\r\n\r\n // add a panel to tabbedPane for standard mode\r\n standardMode = new JPanel();\r\n standardMode.setLayout(new BorderLayout(5, 5));\r\n modeTabbedPane.add(\"Standard View\", standardMode);\r\n\r\n // add a panel to tabbedPane for scientific mode\r\n scientificMode = new JPanel();\r\n scientificMode.setLayout(new BorderLayout(5, 5));\r\n modeTabbedPane.add(\"Scientific View\", scientificMode);\r\n\r\n // create keys and add them to panels\r\n buttons1 = new JButton[20];\r\n AddStandardKey(buttons1);\r\n buttons2 = new JButton[30];\r\n AddScientificKey(buttons2);\r\n // add action listener to buttons\r\n for (JButton button : buttons2) {\r\n button.addActionListener(handler);\r\n button.addKeyListener(new KeyLis());\r\n }\r\n\r\n // add display part to panels\r\n addFirstDisplay();\r\n addSecondDisplay();\r\n\r\n // create menu bar\r\n JMenuBar menuBar = new JMenuBar();\r\n // create file menu\r\n JMenu mainMenu = new JMenu(\"Menu\");\r\n mainMenu.setMnemonic('N');\r\n\r\n // create exit item\r\n JMenuItem exitItem = new JMenuItem(\"Exit\");\r\n exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.ALT_MASK));\r\n exitItem.addActionListener(new ActionListener() {\r\n public void actionPerformed(ActionEvent ev) {\r\n System.exit(0);\r\n }\r\n });\r\n\r\n // create copy item\r\n JMenuItem copyItem = new JMenuItem(\"Copy\");\r\n copyItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK));\r\n copyItem.addActionListener(new ActionListener() {\r\n public void actionPerformed(ActionEvent ev) {\r\n controller.setCopiedText(display2, display1);\r\n }\r\n });\r\n\r\n // create about item\r\n JMenuItem aboutItem = new JMenuItem(\"About\");\r\n aboutItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK));\r\n aboutItem.addActionListener(new ActionListener() {\r\n public void actionPerformed(ActionEvent ev) {\r\n JOptionPane.showMessageDialog(null,\r\n \"Mahdi Hejrati \\n9723100 \\n\",\r\n \"About\",\r\n JOptionPane.INFORMATION_MESSAGE);\r\n }\r\n });\r\n\r\n // add menu\r\n mainMenu.add(exitItem);\r\n mainMenu.add(copyItem);\r\n mainMenu.add(aboutItem);\r\n menuBar.add(mainMenu);\r\n calFrame.setJMenuBar(menuBar);\r\n\r\n calFrame.addKeyListener(new KeyLis());\r\n calFrame.requestFocusInWindow();\r\n calFrame.setFocusable(true);\r\n }\r\n\r\n /**\r\n * design the main frame\r\n */\r\n public void designCalculatorFrame() {\r\n calFrame.setTitle(\"My Calculator\");\r\n calFrame.setSize(430, 550);\r\n calFrame.setLocation(600, 230);\r\n calFrame.setMinimumSize(new Dimension(380, 350));\r\n calFrame.setResizable(true);\r\n calFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\r\n }\r\n\r\n /**\r\n * create keys and add them to the center part of standardMode panel\r\n */\r\n public void AddStandardKey(JButton[] buttons) {\r\n JPanel standardKeyboardPanel = new JPanel();\r\n standardKeyboardPanel.setLayout(new GridLayout(5, 4));\r\n standardMode.add(standardKeyboardPanel, BorderLayout.CENTER);\r\n\r\n String[] buttonText = {\"%\", \"CE\", \"C\", \"/\", \"7\", \"8\", \"9\", \"*\", \"4\", \"5\", \"6\", \"-\", \"1\", \"2\", \"3\", \"+\", \"( )\", \"0\", \".\", \"=\"};\r\n\r\n // add properties to buttons\r\n for (int i = 0; i < 20; i++) {\r\n buttons[i] = new JButton();\r\n buttons[i].setText(buttonText[i]);\r\n buttons[i].setBackground(new Color(50, 50, 50));\r\n buttons[i].setForeground(Color.white);\r\n buttons[i].setOpaque(true);\r\n buttons[i].setToolTipText(buttonText[i]);\r\n buttons[i].setFont(buttons[i].getFont().deriveFont(16f));\r\n standardKeyboardPanel.add(buttons[i]);\r\n }\r\n }\r\n\r\n /**\r\n * create keys and add them to the center part of scientificMode panel\r\n */\r\n public void AddScientificKey(JButton[] buttons) {\r\n JPanel scientificKeyboardPanel = new JPanel();\r\n scientificKeyboardPanel.setLayout(new GridLayout(5, 6));\r\n scientificMode.add(scientificKeyboardPanel, BorderLayout.CENTER);\r\n\r\n String[] buttonText = {\"PI\", \"%\", \"CE\", \"C\", \"/\", \"sin\", \"e\", \"7\", \"8\", \"9\", \"*\", \"tan\", \"^\", \"4\", \"5\", \"6\", \"-\", \"log\", \"!\", \"1\", \"2\", \"3\", \"+\", \"exp\", \"(\", \")\", \"0\", \".\", \"=\", \"shift\"};\r\n\r\n // add properties to buttons\r\n for (int i = 0; i < 30; i++) {\r\n buttons[i] = new JButton();\r\n buttons[i].setText(buttonText[i]);\r\n buttons[i].setBackground(new Color(50, 50, 50));\r\n buttons[i].setForeground(Color.white);\r\n buttons[i].setOpaque(true);\r\n buttons[i].setToolTipText(buttonText[i]);\r\n buttons[i].setFont(buttons[i].getFont().deriveFont(16f));\r\n scientificKeyboardPanel.add(buttons[i]);\r\n }\r\n }\r\n\r\n /**\r\n * creat display part and add it to north part of standardMode panel\r\n */\r\n public void addFirstDisplay() {\r\n display1 = new JTextArea();\r\n\r\n makeDisplay(display1);\r\n\r\n JScrollPane scrollPane = new JScrollPane(display1);\r\n scrollPane.setPreferredSize(new Dimension(100, 90));\r\n\r\n standardMode.add(scrollPane, BorderLayout.NORTH);\r\n }\r\n\r\n /**\r\n * creat display part and add it to north part of scientificMode panel\r\n */\r\n public void addSecondDisplay() {\r\n display2 = new JTextArea();\r\n\r\n makeDisplay(display2);\r\n\r\n JScrollPane scrollPane = new JScrollPane(display2);\r\n scrollPane.setPreferredSize(new Dimension(100, 90));\r\n\r\n scientificMode.add(scrollPane, BorderLayout.NORTH);\r\n }\r\n\r\n /**\r\n * add properties to display\r\n * @param display\r\n */\r\n void makeDisplay(JTextArea display) {\r\n display.setEditable(false);\r\n display.setForeground(Color.white);\r\n display.setBackground(new Color(100, 100, 100));\r\n display.setFont(display.getFont().deriveFont(19f));\r\n display.setToolTipText(\"text area to show operations\");\r\n }\r\n\r\n /**\r\n * set the frame visible to show\r\n */\r\n public void setVisible() {\r\n calFrame.setVisible(true);\r\n }\r\n\r\n /**\r\n * inner class of button handler\r\n */\r\n private class Handler implements ActionListener {\r\n\r\n @Override\r\n public void actionPerformed(ActionEvent e) {\r\n\r\n for (int i = 0; i < 29; i++)\r\n if (e.getSource().equals(buttons2[i])) {\r\n controller.clickButton(buttons2[i], i, display2);\r\n }\r\n\r\n if (e.getSource().equals(buttons2[29])) {\r\n controller.shift(buttons2);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * inner class of key handler\r\n */\r\n private class KeyLis extends KeyAdapter {\r\n @Override\r\n public void keyPressed(KeyEvent e) {\r\n switch (e.getKeyCode()) {\r\n case KeyEvent.VK_7:\r\n case KeyEvent.VK_NUMPAD7:\r\n controller.clickButton(buttons2[7], 7, display2);\r\n break;\r\n case KeyEvent.VK_8:\r\n case KeyEvent.VK_NUMPAD8:\r\n controller.clickButton(buttons2[8], 8, display2);\r\n break;\r\n case KeyEvent.VK_9:\r\n case KeyEvent.VK_NUMPAD9:\r\n controller.clickButton(buttons2[9], 9, display2);\r\n break;\r\n case KeyEvent.VK_4:\r\n case KeyEvent.VK_NUMPAD4:\r\n controller.clickButton(buttons2[13], 13, display2);\r\n break;\r\n case KeyEvent.VK_5:\r\n case KeyEvent.VK_NUMPAD5:\r\n controller.clickButton(buttons2[14], 14, display2);\r\n break;\r\n case KeyEvent.VK_6:\r\n case KeyEvent.VK_NUMPAD6:\r\n controller.clickButton(buttons2[15], 15, display2);\r\n break;\r\n case KeyEvent.VK_1:\r\n case KeyEvent.VK_NUMPAD1:\r\n controller.clickButton(buttons2[19], 19, display2);\r\n break;\r\n case KeyEvent.VK_2:\r\n case KeyEvent.VK_NUMPAD2:\r\n controller.clickButton(buttons2[20], 20, display2);\r\n break;\r\n case KeyEvent.VK_3:\r\n case KeyEvent.VK_NUMPAD3:\r\n controller.clickButton(buttons2[21], 21, display2);\r\n break;\r\n case KeyEvent.VK_0:\r\n case KeyEvent.VK_NUMPAD0:\r\n controller.clickButton(buttons2[26], 26, display2);\r\n break;\r\n case KeyEvent.VK_R:\r\n controller.clickButton(buttons2[1], 1, display2);\r\n break;\r\n case KeyEvent.VK_D:\r\n controller.clickButton(buttons2[4], 4, display2);\r\n break;\r\n case KeyEvent.VK_M:\r\n controller.clickButton(buttons2[10], 10, display2);\r\n break;\r\n case KeyEvent.VK_S:\r\n controller.clickButton(buttons2[16], 16, display2);\r\n break;\r\n case KeyEvent.VK_P:\r\n controller.clickButton(buttons2[22], 22, display2);\r\n break;\r\n case KeyEvent.VK_ENTER:\r\n controller.clickButton(buttons2[28], 28, display2);\r\n break;\r\n case KeyEvent.VK_BACK_SPACE:\r\n controller.clickButton(buttons2[3], 3, display2);\r\n break;\r\n case KeyEvent.VK_I:\r\n controller.clickButton(buttons2[5], 5, display2);\r\n break;\r\n case KeyEvent.VK_T:\r\n controller.clickButton(buttons2[11], 11, display2);\r\n break;\r\n case KeyEvent.VK_H:\r\n controller.shift(buttons2);\r\n break;\r\n }\r\n }\r\n }\r\n}"}}},{"rowIdx":991,"cells":{"language":{"kind":"string","value":"C++"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2179,"string":"2,179"},"score":{"kind":"number","value":3.015625,"string":"3.015625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#include \r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace std;\r\n\r\ntemplate \r\nvoid prove(T a);\r\n\r\nvoid fill_array(int** ary, const int N, const int M);\r\n\r\nvoid solution(int** ary, const int N, const int M);\r\n\r\nint main()\r\n{\r\n\tsetlocale(LC_CTYPE, \"rus\");\r\n\tsrand(time(NULL));\r\n\tint n, m, sum = 0;\r\n\tcout << \"Введите n: \";\tcin >> n;\tprove(n);\r\n\tcout << \"Введите m: \";\tcin >> m;\tprove(m);\r\n\r\n\tint** matrix = new int* [n];\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tmatrix[i] = new int[m];\r\n\r\n\tfill_array(matrix, n, m);\r\n\t\r\n\tsolution(matrix, n, m);\r\n\r\n\tcout << endl;\r\n\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tdelete[] matrix[i];\r\n\tdelete[] matrix;\r\n\r\n\tsystem(\"pause\");\r\n\treturn 0;\r\n}\r\n\r\ntemplate \r\nvoid prove(T a)\r\n{\r\n\twhile (cin.fail())\r\n\t{\r\n\t\tcin.clear();\r\n\t\tcin.ignore(INT16_MAX, '\\t');\r\n\t\tcout << \"Error\\nВведите другое значение\";\r\n\t\tcin >> a;\r\n\t}\r\n}\r\n\r\nvoid fill_array(int** ary, const int N, const int M)\r\n{\r\n\tfor (int i = 0; i < N; i++)\r\n\t{\r\n\t\tfor (int j = 0; j < M; j++)\r\n\t\t{\r\n\t\t\tcout << \"array[\" << i + 1 << \"][\" << j + 1 << \"] = \";\r\n\t\t\tcin >> ary[i][j];\r\n\t\t}\r\n\t\tcout << endl;\r\n\t}\r\n\tfor (int i = 0; i < N; i++)\r\n\t{\r\n\t\tfor (int j = 0; j < M; j++)\r\n\t\t{\r\n\t\t\tprintf(\"%5i\", ary[i][j]);\r\n\t\t}\r\n\t\tcout << endl;\r\n\t}\r\n}\r\n\r\nvoid solution(int** ary, const int N, const int M)\r\n{\r\n\tbool col = true, row = true, p = true;\r\n\r\n\tfor (int i = 0; i < N; i++)\r\n\t{\r\n\t\t\r\n\t\tfor (int j = 0; j < M; j++)\r\n\t\t{\r\n\t\t\tcol = true, row = true;\r\n\t\t\tfor (int i1 = 0; i1 < N; i1++)\r\n\t\t\t\tif (ary[i][j] < ary[i1][j])\r\n\t\t\t\t\tcol = false;\r\n\t\t\tfor (int j1 = 0; j1 < M; j1++)\r\n\t\t\t\tif (ary[i][j] > ary[i][j1])\r\n\t\t\t\t\trow = false;\r\n\r\n\t\t\tif (row && col)\r\n\t\t\t{\r\n\t\t\t\tcout << '[' << i + 1 << \"][\" << j + 1 << ']' << '\\t';\r\n\t\t\t\tp = false;\r\n\t\t\t}\r\n\r\n\t\t\tcol = true, row = true;\r\n\t\t\tfor (int i1 = 0; i1 < N; i1++)\r\n\t\t\t\tif (ary[i][j] > ary[i1][j])\r\n\t\t\t\t\tcol = false;\r\n\t\t\tfor (int j1 = 0; j1 < M; j1++)\r\n\t\t\t\tif (ary[i][j] < ary[i][j1])\r\n\t\t\t\t\trow = false;\r\n\r\n\t\t\tif (row && col)\r\n\t\t\t{\r\n\t\t\t\tcout << '[' << i + 1 << \"][\" << j + 1 << ']' << '\\t' << endl;\r\n\t\t\t\tp = false;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (p)\r\n\t\tcout << \"\\nТаких элемениов нет\\n\";\r\n}"}}},{"rowIdx":992,"cells":{"language":{"kind":"string","value":"JavaScript"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1574,"string":"1,574"},"score":{"kind":"number","value":3.578125,"string":"3.578125"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"// PLEASE DON'T change function name\nmodule.exports = function makeExchange(currency) {\n // Your code goes here!\n // Return an object containing the minimum number of coins needed to make change\n\n currency = +currency;\n let remainderH = 0, remainderQ = 0, remainderD = 0, remainderN = 0, remainderP = 0;\n let answer = {};\n\n if (currency > 10000){\n answer = {error: \"You are rich, my friend! We don't have so much coins for exchange\"};\n } else if(currency <= 0){\n answer = {};\n } else{\n\n answer['H'] = Math.floor(currency / 50);\n\n if (answer['H'] > 0){\n remainderH = currency - (answer['H'] * 50);\n } else{\n remainderH = currency;\n delete answer['H'];\n }\n\n answer['Q'] = Math.floor(remainderH / 25);\n\n if (answer['Q'] > 0){\n remainderQ = remainderH - (answer['Q'] * 25);\n } else{\n remainderQ = remainderH;\n delete answer['Q'];\n }\n \n answer['D'] = Math.floor(remainderQ / 10);\n\n if (answer['D'] > 0){\n remainderD = remainderQ - (answer['D'] * 10);\n } else{\n remainderD = remainderQ;\n delete answer['D'];\n }\n\n answer['N'] = Math.floor(remainderD / 5);\n\n if (answer['N'] > 0){\n remainderN = remainderD - (answer['N'] * 5);\n } else{\n remainderN = remainderD;\n delete answer['N'];\n } \n\n if (remainderN > 0){\n answer['P'] = remainderN;\n }\n\n }\n return answer;\n}\n"}}},{"rowIdx":993,"cells":{"language":{"kind":"string","value":"Java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":210,"string":"210"},"score":{"kind":"number","value":1.8828125,"string":"1.882813"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\npackage base;\n\nimport org.openqa.selenium.WebElement;\n\npublic class PageElement {\n\n private WebElement webElement;\n private String elementType;\n private String elementName;\n int elementTimeout;\n\n\n}"}}},{"rowIdx":994,"cells":{"language":{"kind":"string","value":"Markdown"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":424,"string":"424"},"score":{"kind":"number","value":2.703125,"string":"2.703125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"Thank You for looking at my resume! If Markdown isn't your thing you can find links to other formats of the resume below:\n\n- [PDF](https://github.com/justgage/resume/raw/master/resume-in-many-formats/GageKPetersonsResume.pdf)\n- [Website (HTML)](http://justgage.github.io/resume/) \n- [Markdown](https://github.com/justgage/resume/blob/master/resume-in-many-formats/GageKPetersonsResume.md) (without comments at the top)\n\n***\n"}}},{"rowIdx":995,"cells":{"language":{"kind":"string","value":"Python"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1563,"string":"1,563"},"score":{"kind":"number","value":3.3125,"string":"3.3125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"from itertools import cycle\r\nfrom player import Player\r\nfrom poker import Poker\r\n\r\n\"\"\"\r\ndef bet_loop(poker):\r\n stay = poker.players\r\n fold = set()\r\n pool = cycle(stay) \r\n for p in pool:\r\n\"\"\"\r\n\r\nif __name__ == \"__main__\":\r\n p1 = Player('P1', 1000)\r\n p2 = Player('P2', 1000)\r\n p3 = Player('P3', 1000)\r\n \r\n poker = Poker()\r\n\r\n while True:\r\n poker.start_game()\r\n poker.register_player(p1)\r\n poker.register_player(p2)\r\n poker.register_player(p3)\r\n poker.deliver()\r\n print(p1)\r\n print(p2)\r\n print(p3)\r\n #bet_loop(poker)\r\n for i, p in enumerate(poker.players):\r\n if i == 0:\r\n poker.get_money(p.bet(50))\r\n elif i == 1:\r\n poker.get_money(p.bet(100))\r\n\r\n \r\n #print([str(p) for p in poker.players])\r\n poker.fold_player(p2) \r\n poker.reveal_card()\r\n poker.reveal_card()\r\n poker.reveal_card()\r\n poker.reveal_card()\r\n poker.reveal_card()\r\n \r\n print('Table: {} / {}'.format([str(c) for c in poker.table_cards], poker.table_money))\r\n\r\n win, score = poker.winner()\r\n\r\n print('Winner: ' + win.name + ' with ' + score)\r\n print([str(p) for p in poker.players]) \r\n control = input('Press any key to continue or q to quit:')\r\n if control.lower() == 'q':\r\n break\r\n #poker.unregister_player(p1)\r\n #poker.unregister_player(p2)\r\n #poker.unregister_player(p3)\r\n\r\n #print(poker.players)"}}},{"rowIdx":996,"cells":{"language":{"kind":"string","value":"Rust"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":7755,"string":"7,755"},"score":{"kind":"number","value":3.71875,"string":"3.71875"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":["BSD-2-Clause"],"string":"[\n \"BSD-2-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"pub mod huffman {\n\tuse std::boxed::Box;\n\tuse std::cmp::Ordering;\n\tuse std::collections::*;\n\n\t///\tNode is a binary tree data structure.\n\t///\tIt will be used by huffman compression algorithm\n\t#[derive(Clone, PartialEq, Eq, Ord, std::fmt::Debug)]\n\tstruct Node {\n\t\tletter: char,\n\t\tfreq: i32,\n\t\tleft: Option>,\n\t\tright: Option>,\n\t}\n\timpl PartialOrd for Node {\n\t\tfn partial_cmp(self: &Node, other: &Node) -> Option {\n\t\t\tlet cmp = self.freq.cmp(&other.freq);\n\t\t\tSome(cmp.reverse()) // For min heap\n\t\t}\n\t}\n\timpl Node {\n\t\t/// A convinence function to create a leaf node, i.e a node with no children\n\t\tfn new(letter: char, freq: i32) -> Node {\n\t\t\tNode {\n\t\t\t\tletter,\n\t\t\t\tfreq,\n\t\t\t\tleft: None,\n\t\t\t\tright: None,\n\t\t\t}\n\t\t}\n\t}\n\n\t///\n\t/// Count the frequency of chars, return a vector of node.\n\t///\n\t/// Each node contains the character and corresponding frequency\n\t/// > Note: Algotithm is based on sorting\n\t///\n\tfn freq_count(text: std::str::Chars) -> Vec {\n\t\tlet mut freq_vec = Vec::new();\n\t\tlet mut chars: Vec = text.collect();\n\t\tchars.sort();\n\t\tlet mut freq = 0;\n\t\tlet mut prev: char = *chars.first().expect(\"Input cannot be empty\");\n\t\tfor c in chars {\n\t\t\tif c == prev {\n\t\t\t\tfreq += 1;\n\t\t\t} else {\n\t\t\t\tfreq_vec.push(Node::new(prev, freq));\n\t\t\t\tfreq = 1;\n\t\t\t\tprev = c;\n\t\t\t}\n\t\t}\n\t\tfreq_vec.push(Node::new(prev, freq));\n\t\treturn freq_vec;\n\t}\n\n\t/// Create huffman encoding using huffman algorithm\n\t/// ## Input:\n\t/// Frequency vector: A vector of Nodes containing character frequency\n\t/// (Use the freq_count function)\n\t/// ## Output:\n\t/// Root node of Huffman Tree of type Option>\n\t/// # Algorithm\n\t/// - While priority_queue contains atleast 2 nodes:\n\t/// \t- Choose two minimum elements and combine them\n\t/// \t- Insert combined value back to tree\n\t/// - Return tree\n\t///\n\tfn construct_huffman_tree(freq: Vec) -> Node {\n\t\tlet mut pq = BinaryHeap::new();\n\t\tfor node in freq {\n\t\t\tpq.push(node);\n\t\t}\n\t\twhile pq.len() > 1 {\n\t\t\tlet (a, b) = (pq.pop().unwrap(), pq.pop().unwrap());\n\t\t\tlet new_node = Node {\n\t\t\t\tletter: '\\0',\n\t\t\t\tfreq: a.freq + b.freq,\n\t\t\t\tleft: Option::from(Box::from(a)),\n\t\t\t\tright: Option::from(Box::from(b)),\n\t\t\t};\n\t\t\tpq.push(new_node);\n\t\t}\n\t\tpq.pop().unwrap()\n\t}\n\t/// Convert huffman tree to a hashmap with key as char and value as encoding\n\t/// E.g key = 'a', value = '1000'\n\tfn to_hashmap(node: &Node) -> HashMap {\n\t\tlet mut hm = HashMap::new();\n\t\t// Huffman tree is complete binary tree, a node will have either 0 or 2 children, 1 is not possible\n\t\tif node.left.is_none() {\n\t\t\thm.insert(node.letter, \"0\".to_string());\n\t\t\treturn hm;\n\t\t}\n\t\tfn encode(hm: &mut HashMap, node: &Node, encoding: String) {\n\t\t\tif node.left.is_none() {\n\t\t\t\thm.insert(node.letter, encoding);\n\t\t\t} else {\n\t\t\t\tlet left_path = String::from(&encoding) + \"0\";\n\t\t\t\tlet right_path = String::from(&encoding) + \"1\";\n\t\t\t\tif let Some(left) = &node.left {\n\t\t\t\t\tencode(hm, &left, left_path);\n\t\t\t\t}\n\t\t\t\tif let Some(right) = &node.right {\n\t\t\t\t\tencode(hm, &right, right_path);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tencode(&mut hm, &node, \"\".to_string());\n\t\treturn hm;\n\t}\n\t/// Convert huffman node to string of chars using post-order traversal\n\tfn to_string(huffman_node: &Node) -> String {\n\t\tlet mut output = String::new();\n\t\tfn post_order(node: &Node, output_str: &mut String) {\n\t\t\tif let Some(left) = &node.left {\n\t\t\t\tpost_order(left.as_ref(), output_str);\n\t\t\t}\n\t\t\tif let Some(right) = &node.right {\n\t\t\t\tpost_order(right.as_ref(), output_str);\n\t\t\t}\n\t\t\toutput_str.push(node.letter);\n\t\t}\n\n\t\tpost_order(huffman_node, &mut output);\n\t\treturn output;\n\t}\n\t/// Convert huffman tree to vector of bytes\n\t///\n\t/// First element is length of tree\n\t///\n\t/// There are only 100 or so printable characters \n\t/// based on python's string.printable\n\t/// So worst case tree size is 2N-1 = 199\n\t/// So a unsigned char will suffice for length of tree\n\t///\n\t/// Following elements are charectars in post-order traversal of tree\n\tfn embed_tree(huffman_node: &Node) -> Vec {\n\t\tlet mut compressed_data = to_string(huffman_node).into_bytes();\n\t\tcompressed_data.insert(0, compressed_data.len() as u8); // Append length\n\t\treturn compressed_data;\n\t}\n\n\t/// Simply maps input characters to their corresponding encoding and return as byte array\n\t///\n\t/// The first element is padding, (Number of zeroes appended for last encoding), as encoding might not fit into 8 bits\n\tfn compress_data(text: &String, huffman_node: &Node) -> Vec {\n\t\tlet mut byte_stream: Vec = Vec::new();\n\t\tlet (mut byte, mut count) = (0, 0);\n\n\t\tlet huffman_map = to_hashmap(huffman_node);\n\t\tfor c in text.chars() {\n\t\t\tlet encoding = huffman_map.get(&c).unwrap();\n\t\t\tfor e in encoding.bytes() {\n\t\t\t\tlet bit: bool = (e - '0' as u8) != 0;\n\t\t\t\tbyte = byte << 1 | (bit as u8);\n\t\t\t\tcount = (count + 1) % 8;\n\t\t\t\tif count == 0 {\n\t\t\t\t\tbyte_stream.push(byte);\n\t\t\t\t\tbyte = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif count != 0 {\n\t\t\tlet padding: u8 = 8 - count;\n\t\t\tbyte <<= padding;\n\t\t\tbyte_stream.push(byte);\n\t\t\tbyte_stream.insert(0, padding);\n\t\t} else {\n\t\t\tbyte_stream.insert(0, 0);\n\t\t}\n\t\treturn byte_stream;\n\t}\n\t/// Compression using huffman's algorithm\n\t/// # Data Format\n\t/// First byte (n): Length of post-order traversal of huffman tree\n\t///\n\t/// Following n bytes contain post-order traversal\n\t///\n\t/// Padding byte (p): Padding for final byte\n\t///\n\t/// All remaining bytes are data\n\tpub fn compress(text: &String) -> Vec {\n\t\tlet frequency = freq_count(text.chars());\n\t\tlet huffman_tree = construct_huffman_tree(frequency);\n\t\tlet mut compressed_data = Vec::from(embed_tree(&huffman_tree));\n\t\tcompressed_data.extend(compress_data(text, &huffman_tree));\n\t\treturn compressed_data;\n\t}\n\tfn construct_tree_from_postorder(postorder: &[u8]) -> Node {\n\t\t// parent left right\n\t\t// Assuming input does not contain null\n\t\tlet mut stack = Vec::new();\n\t\tfor c in postorder {\n\t\t\tif *c == 0 as u8 {\n\t\t\t\tlet (left, right) = (\n\t\t\t\t\tstack.pop().expect(\"Input contains Null byte\"),\n\t\t\t\t\tstack.pop().expect(\"Input contains Null byte\"),\n\t\t\t\t);\n\t\t\t\tstack.push(Node {\n\t\t\t\t\tletter: '\\0',\n\t\t\t\t\tfreq: 0,\n\t\t\t\t\tleft: Option::from(Box::from(right)),\n\t\t\t\t\tright: Option::from(Box::from(left)),\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tstack.push(Node {\n\t\t\t\t\tletter: *c as char,\n\t\t\t\t\tfreq: 0,\n\t\t\t\t\tleft: None,\n\t\t\t\t\tright: None,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn stack.pop().unwrap();\n\t}\n\n\tfn decompress_data(data: &[u8], tree: &Node) -> String {\n\t\tlet padding = *data.first().expect(\"Data empty\");\n\t\tlet data = &data[1..]; // Remove first element which stores number of padded bits\n\t\tlet mut bit_stream = Vec::new();\n\t\tlet mut tmp = tree;\n\t\tlet mut output = String::new();\n\t\tfor character in data.iter() {\n\t\t\tlet mut character = *character;\n\t\t\tfor _ in 0..8 {\n\t\t\t\tlet bit: bool = (character >> 7 & 1) != 0;\n\t\t\t\tcharacter <<= 1;\n\t\t\t\tbit_stream.push(bit);\n\t\t\t}\n\t\t}\n\t\tbit_stream.resize(bit_stream.len() - padding as usize, false); // Remove padding bits\n\t\tif tree.left.is_none() {\n\t\t\t// Huffman tree is complete binary tree, a node will have either 0 or 2 children, 1 is not possible\n\t\t\tfor _ in 0..bit_stream.len() {\n\t\t\t\toutput.push(tree.letter);\n\t\t\t}\n\t\t\treturn output;\n\t\t}\n\t\tfor &bit in &bit_stream {\n\t\t\tif tmp.left.is_none() {\n\t\t\t\toutput.push(tmp.letter);\n\t\t\t\ttmp = tree;\n\t\t\t}\n\t\t\tlet right: &Node = tmp.right.as_ref().unwrap().as_ref();\n\t\t\tlet left: &Node = tmp.left.as_ref().unwrap().as_ref();\n\t\t\ttmp = if bit { right } else { left };\n\t\t}\n\t\tif tmp != tree {\n\t\t\toutput.push(tmp.letter);\n\t\t}\n\t\treturn output;\n\t}\n\tpub fn decompress(data: &Vec) -> String {\n\t\tlet post_order_length = *data.first().expect(\"Data cannot be empty\") as usize;\n\t\tlet post_order = &data[1..=post_order_length];\n\t\tlet huffman_tree = construct_tree_from_postorder(post_order);\n\t\tlet data = &data[post_order_length + 1..];\n\t\tdecompress_data(data, &huffman_tree)\n\t}\n}\n"}}},{"rowIdx":997,"cells":{"language":{"kind":"string","value":"C++"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3069,"string":"3,069"},"score":{"kind":"number","value":2.71875,"string":"2.71875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#include \"receiver.h\"\r\n#include \r\n\r\nReceiver::Receiver(QWidget *parent) : QWidget(parent)\r\n{\r\n}\r\nvoid Receiver::receiveValueHW1(int i)\r\n{\r\n if(scoreHW1 != i){\r\n scoreHW1 = i;\r\n double t = this->recalculate();\r\n emit signalValue(t);\r\n //emit two signals? or maybe emit calculated value?\r\n }\r\n}\r\nvoid Receiver::receiveValueHW2(int i){\r\n if(scoreHW2 != i){\r\n scoreHW2 = i;\r\n double t = this->recalculate();\r\n emit signalValue(t);\r\n //emit two signals? or maybe emit calculated value?\r\n }\r\n}\r\nvoid Receiver::receiveValueHW3(int i){\r\n if(scoreHW3 != i){\r\n scoreHW3 = i;\r\n double t = this->recalculate();\r\n emit signalValue(t);\r\n //emit two signals? or maybe emit calculated value?\r\n }\r\n}\r\nvoid Receiver::receiveValueHW4(int i){\r\n if(scoreHW4 != i){\r\n scoreHW4 = i;\r\n double t = this->recalculate();\r\n emit signalValue(t);\r\n //emit two signals? or maybe emit calculated value?\r\n }\r\n}\r\nvoid Receiver::receiveValueHW5(int i){\r\n if(scoreHW5 != i){\r\n scoreHW5 = i;\r\n double t = this->recalculate();\r\n emit signalValue(t);\r\n //emit two signals? or maybe emit calculated value?\r\n }\r\n}\r\nvoid Receiver::receiveValueHW6(int i){\r\n if(scoreHW6 != i){\r\n scoreHW6 = i;\r\n double t = this->recalculate();\r\n emit signalValue(t);\r\n //emit two signals? or maybe emit calculated value?\r\n }\r\n}\r\nvoid Receiver::receiveValueHW7(int i){\r\n if(scoreHW7 != i){\r\n scoreHW7 = i;\r\n double t = this->recalculate();\r\n emit signalValue(t);\r\n //emit two signals? or maybe emit calculated value?\r\n }\r\n}\r\nvoid Receiver::receiveValueHW8(int i){\r\n if(scoreHW8 != i){\r\n scoreHW8 = i;\r\n double t = this->recalculate();\r\n emit signalValue(t);\r\n //emit two signals? or maybe emit calculated value?\r\n }\r\n}\r\nvoid Receiver::receiveValueMID1(int i){\r\n if(scoreMID1 != i){\r\n scoreMID1 = i;\r\n double t = this->recalculate();\r\n emit signalValue(t);\r\n //emit two signals? or maybe emit calculated value?\r\n }\r\n}\r\nvoid Receiver::receiveValueMID2(int i){\r\n if(scoreMID2 != i){\r\n scoreMID2 = i;\r\n double t = this->recalculate();\r\n emit signalValue(t);\r\n //emit two signals? or maybe emit calculated value?\r\n }\r\n}\r\nvoid Receiver::receiveValueFIN(int i){\r\n if(scoreFIN != i){\r\n scoreFIN = i;\r\n double t = this->recalculate();\r\n emit signalValue(t);\r\n\r\n }\r\n}\r\ndouble Receiver::recalculate()\r\n{\r\n double temp1 = ((scoreHW1 + scoreHW2 + scoreHW3 + scoreHW4 + scoreHW5 + scoreHW6 + scoreHW7 + scoreHW8) / 800. * 25.) + (scoreMID1) / 100. * 20. + (scoreMID2) / 100. * 20. + (scoreFIN) / 100. * 35.;\r\n double temp2 = (scoreHW1 + scoreHW2 + scoreHW3 + scoreHW4 + scoreHW5 + scoreHW6 + scoreHW7 + scoreHW8) / 800. * 25. + fmax(scoreMID1,scoreMID2) / 100. * 30. + (scoreFIN) / 100. * 44.;\r\n score = fmax(temp1,temp2);\r\n return score;\r\n}\r\n"}}},{"rowIdx":998,"cells":{"language":{"kind":"string","value":"JavaScript"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":442,"string":"442"},"score":{"kind":"number","value":3.1875,"string":"3.1875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"export const format = (seconds) => {\n\tif (isNaN(seconds)) return '...';\n\n\tconst minutes = Math.floor(seconds / 60);\n\tseconds = Math.floor(seconds % 60);\n\tif (seconds < 10) seconds = '0' + seconds;\n\n\treturn `${minutes}:${seconds}`;\n}\n\nexport const timeToMiliSeconds = (time) => {\n\tif (time === null || time === undefined) return '...';\n\n\tconst [min, sec] = time.split(':');\n\tconst milliseconds = (+min * 60) + +sec + 1; \n\treturn milliseconds\n}"}}},{"rowIdx":999,"cells":{"language":{"kind":"string","value":"Python"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1057,"string":"1,057"},"score":{"kind":"number","value":3.15625,"string":"3.15625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 5 10:08:31 2018\n\n@author: Tim\n\"\"\"\n\n#1. Board, Marble, 1D, Pitch/Roll\nfrom sense_hat import SenseHat\nsense = SenseHat()\n\nb = (0,0,0)\nw = (255,255,255)\n\nboard = [[b,b,b,b,b,b,b,b],\n [b,b,b,b,b,b,b,b],\n [b,b,b,b,b,b,b,b],\n [b,b,b,b,b,b,b,b],\n [b,b,b,b,b,b,b,b],\n [b,b,b,b,b,b,b,b],\n [b,b,b,b,b,b,b,b],\n [b,b,b,b,b,b,b,b]]\n\ny = 2\nx = 2\nboard[y][x] = w\n\nboard_1D = sum(board,[])\nsense.set_pixels(board_1D)\n\ndef move_marble(pitch, roll, x, y):\n new_x = x\n new_y = y\n if 1 < pitch <179 and x !=0:\n new_x -= 1\n elif 179 < pitch < 359 and x!= 7:\n new_x += 1\n \n if 1 < roll <179 and x !=7:\n new_x += 1\n elif 179 < roll < 359 and x!= 0:\n new_x -= 1 \n \n return new_x, new_y\n\nwhile True:\n pitch = sense.get_orientation()['pitch']\n roll = sense.get_orientation()['roll']\n \n board[y][x] = b\n x,y = move_marble(pitch,roll,x,y)\n board[y][x] = w\n sense.set_pixels(sum(board,[]))\n sleep(0.05)\n"}}}],"truncated":false,"partial":true},"paginationData":{"pageIndex":9,"numItemsPerPage":100,"numTotalItems":1735108,"offset":900,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1ODk1NzcyOSwic3ViIjoiL2RhdGFzZXRzL1RlY2h4R2VudXMvc3RhY2stZWR1IiwiZXhwIjoxNzU4OTYxMzI5LCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.TVCK09NbJlG0GjJpo80FWvapCBXdbWltR7y2DRygJEhTsUmft7y58O32DCn5fxxK-s4sisV2HasF6m3SoBMJDw","displayUrls":true},"discussionsStats":{"closed":0,"open":1,"total":1},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">

    language
    stringclasses
    15 values
    src_encoding
    stringclasses
    34 values
    length_bytes
    int64
    6
    7.85M
    score
    float64
    1.5
    5.69
    int_score
    int64
    2
    5
    detected_licenses
    listlengths
    0
    160
    license_type
    stringclasses
    2 values
    text
    stringlengths
    9
    7.85M
    Python
    UTF-8
    405
    3.796875
    4
    []
    no_license
    print("hello world") message = "hello world" print(message) name = "add lovelace" print(name.title()) print(name.upper()) print(name.lower()) first_name = "ada" last_name = "lovelace" full_name = first_name + " " + last_name print(full_name) print("\tPython") print("\nPython") favorite_language = "Python " print(favorite_language) favorite_language.rstrip() print(favorite_language.rstrip()) print(3**3)
    Java
    UTF-8
    2,484
    2.65625
    3
    [ "MIT" ]
    permissive
    package org.dmc.services; import java.io.IOException; import java.util.logging.FileHandler; import java.util.logging.ConsoleHandler; import java.util.logging.Level; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import org.json.JSONObject; public class ServiceLogger { private static FileHandler logFileHandler; private static SimpleFormatter logFileFormatter; private static Logger logger; private static Logger rootLogger; private final String LOGFILE = Config.LOG_FILE; private static ServiceLogger serviceLoggerInstance = null; protected ServiceLogger() { try { this.setup(); } catch (IOException e) { System.out.println(e.getMessage()); } } public static void log (String logTag, String message) { if (serviceLoggerInstance == null) { serviceLoggerInstance = new ServiceLogger(); } logger.info(logTag + ": " + message); } /** * Exception Logging * @param logTag * @param e */ public static void logException (String logTag, DMCServiceException e) { String logMessage = null; if (serviceLoggerInstance == null) { serviceLoggerInstance = new ServiceLogger(); } JSONObject logJson = new JSONObject(); logJson.put("Class", logTag); logJson.put("Error", e.getError()); logJson.put("HttpStatus Code", e.getHttpStatusCode()); logJson.put("Message", e.getMessage()); logMessage += "\n---------------------------------------------------------------------------------------------------------------\n"; logMessage +="DMC EXCEPTION: "; logMessage +=logJson.toString(); logMessage += "\n---------------------------------------------------------------------------------------------------------------\n"; logger.info(logMessage); } private void setup() throws IOException { logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); //Log to the file by default logger.setLevel(Level.INFO); logFileHandler = new FileHandler(LOGFILE); logger.addHandler(logFileHandler); //disable console logging by default logger.setUseParentHandlers(false); //Use the Simple file formatter logFileFormatter = new SimpleFormatter(); logFileHandler.setFormatter(logFileFormatter); //Log to console if enabled in config if (Config.CONSOLE_LOGGING) { ConsoleHandler consoleHandler = new ConsoleHandler(); consoleHandler.setLevel(Level.ALL); logger.addHandler(consoleHandler); } } }
    Python
    UTF-8
    861
    3.5625
    4
    []
    no_license
    #!/usr/bin/env python3 # -*- coding:utf-8 -*- ### # File: c:\Users\olivi.000\Dropbox\Public\My Library\IT\SW Programming\sego\Intro to Python\ch04\snippets_py\Exercise 4.9.py # Project: c:\Users\olivi.000\Dropbox\Public\My Library\IT\SW Programming\sego\Intro to Python\ch04\snippets_py # Created Date: Tuesday, April 21st 2020, 11:13:14 pm # Author: Olivia Serna # Description: # ----- # Last Modified: Thu Apr 23 2020 # Modified By: Olivia Serna # ----- # Copyright (c) 2020 OLI CO. LTD. # # Know thy self, know thy enemy. A thousand battles, a thousand victories # ----- # HISTORY: # Date By Comments # ---------- --- ---------------------------------------------------------- ### def C2F (c_degrees): return (c_degrees * (9/5)) + 32 print ("Farenheit Celcius") print ("------------------") for i in range (101): print (f'{i:>9.1f} {C2F(i):>7.1f}')
    Java
    UTF-8
    3,913
    3.265625
    3
    []
    no_license
    package com.atcafuc.java; import org.junit.Test; import java.io.*; /** * 处理流之一:缓冲流的使用 * * 1.缓冲流 * BufferedInputStream * BufferedOutputStream * BufferedReader * BufferedWriter * * 2.作用:提供流的读取、写入的速度 * 提高读写速度的原因:内部提供了一个缓冲区 * * @author jh * @create 2021-08-26 14:21 */ public class BufferedTest { /* 实现为文本文件的复制 */ @Test public void test() { FileInputStream fis = null; FileOutputStream fos = null; BufferedInputStream bis = null; BufferedOutputStream bos = null; try { //1.造文件 File srcFile = new File("8-26.jpg"); File destFile = new File("8-26.2.jpg"); //2.造流 //2.1 造字节流 fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); //2.2 造缓冲流 bis = new BufferedInputStream(fis); bos = new BufferedOutputStream(fos); //3.复制的细节:读取、写入 byte[] buffer = new byte[10]; int len; while((len = bis.read(buffer)) != -1){ bos.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { //4.资源关闭 //要求:先关闭外层的流,再关闭内层的流 try { if(bos != null) bos.close(); } catch (IOException e) { e.printStackTrace(); } try { if(bis != null) bis.close(); } catch (IOException e) { e.printStackTrace(); } //说明:关闭外层流的同时,内层的流也会自动进行关闭。 // fis.close(); // fos.close(); } } //文件复制的方法 public void copy(String srcPath,String destPath){ FileInputStream fis = null; FileOutputStream fos = null; BufferedInputStream bis = null; BufferedOutputStream bos = null; try { //1.造文件 File srcFile = new File(srcPath); File destFile = new File(destPath); //2.造流 //2.1 造字节流 fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); //2.2 造缓冲流 bis = new BufferedInputStream(fis); bos = new BufferedOutputStream(fos); //3.复制的细节:读取、写入 byte[] buffer = new byte[1024]; int len; while((len = bis.read(buffer)) != -1){ bos.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { //4.资源关闭 //要求:先关闭外层的流,再关闭内层的流 try { if(bos != null) bos.close(); } catch (IOException e) { e.printStackTrace(); } try { if(bis != null) bis.close(); } catch (IOException e) { e.printStackTrace(); } //说明:关闭外层流的同时,内层的流也会自动进行关闭。 // fis.close(); // fos.close(); } } @Test public void testCopy(){ long start = System.currentTimeMillis(); copy("22.avi","22-1.avi"); long end = System.currentTimeMillis(); System.out.println("复制时间为" + (end - start)); //time 147 } @Test public void test1(){ byte b = 124; byte b1 = (byte) (b ^5); } }
    Java
    UTF-8
    2,494
    4.125
    4
    []
    no_license
    package Q2; class MyThread1 extends Thread{ MyThread1(String name){ super(name); } public void run() { System.out.println("Hello this is thread: "+ this.getName()); System.out.println("Thread "+this.getName()+ " will now sleep:"); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } class MyThread2 extends Thread{ MyThread2(String name){ super(name); } @Override public void run() { System.out.println("Hello this is thread: "+ this.getName()); System.out.println("Thread "+this.getName()+ " will now sleep:"); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } } class MyThread3 extends Thread{ MyThread3(String name){ super(name); } @Override public void run() { System.out.println("Hello this is thread: "+ this.getName()); System.out.println("Thread "+this.getName()+ " will now sleep:"); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Calling yield on "+ this.getName()+" this will now stop:"); Thread.yield(); } } public class q2 { public static void main(String[] args) { MyThread1 t1 = new MyThread1("sania"); MyThread2 t2 = new MyThread2("maria"); MyThread3 t3 = new MyThread3("serena"); t1.setPriority(Thread.MIN_PRIORITY); t2.setPriority(Thread.NORM_PRIORITY); t3.setPriority(Thread.MAX_PRIORITY); System.out.println("Now the thread t1 will run:"); t1.run(); System.out.println("Now threads t1, t2, t3 will start:"); t1.start(); t2.start(); t3.start(); System.out.println("The priority of thread t1 is :"+ t1.getPriority()); System.out.println("The priority of thread t2 is :"+ t2.getPriority()); System.out.println("The priority of thread t3 is :"+ t3.getPriority()); System.out.println("Thread t3 now will be suspended."); t3.suspend(); System.out.println("Thread t3 now will be resumed."); t3.resume(); try { System.out.println("Calling join method on thread t1. "); t1.join(); } catch (InterruptedException e) { e.printStackTrace(); } } }
    Java
    UTF-8
    1,292
    2.453125
    2
    [ "MIT" ]
    permissive
    package de.aaaaaaah.velcom.backend.access.entities; import java.time.Instant; import java.util.Collection; public class Commit { private final RepoId repoId; private final CommitHash hash; private final Collection<CommitHash> parentHashes; private final String author; private final Instant authorDate; private final String committer; private final Instant committerDate; private final String message; public Commit(RepoId repoId, CommitHash hash, Collection<CommitHash> parentHashes, String author, Instant authorDate, String committer, Instant committerDate, String message) { this.repoId = repoId; this.hash = hash; this.parentHashes = parentHashes; this.author = author; this.authorDate = authorDate; this.committer = committer; this.committerDate = committerDate; this.message = message; } public RepoId getRepoId() { return repoId; } public CommitHash getHash() { return hash; } public Collection<CommitHash> getParentHashes() { return parentHashes; } public String getAuthor() { return author; } public Instant getAuthorDate() { return authorDate; } public String getCommitter() { return committer; } public Instant getCommitterDate() { return committerDate; } public String getMessage() { return message; } }
    Python
    UTF-8
    556
    2.984375
    3
    []
    no_license
    #!usr/bin/env python import requests target_url = ""//your target url data_dict = {"username": "123", "password": "", "Login": "submit"} with open("<file_for_passwords>", "r") as wordlist_file://put the password list inside the " < > " for line in wordlist_file: word = line.strip() data_dict["password"] = word response = requests.post(target_url, data=data_dict) if "Login failed" not in response.content: print("[+] Got the password --> " + word) exit() print("[+] Reached end of line.")
    Java
    UTF-8
    3,854
    1.671875
    2
    []
    no_license
    /** * generated by Xtext 2.13.0 */ package uofa.lbirdsey.castle.casl.impl; import java.util.Collection; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; import uofa.lbirdsey.castle.casl.CaslPackage; import uofa.lbirdsey.castle.casl.Interaction; import uofa.lbirdsey.castle.casl.Interactions; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Interactions</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link uofa.lbirdsey.castle.casl.impl.InteractionsImpl#getInteractions <em>Interactions</em>}</li> * </ul> * * @generated */ public class InteractionsImpl extends MinimalEObjectImpl.Container implements Interactions { /** * The cached value of the '{@link #getInteractions() <em>Interactions</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getInteractions() * @generated * @ordered */ protected EList<Interaction> interactions; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected InteractionsImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return CaslPackage.eINSTANCE.getInteractions(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Interaction> getInteractions() { if (interactions == null) { interactions = new EObjectContainmentEList<Interaction>(Interaction.class, this, CaslPackage.INTERACTIONS__INTERACTIONS); } return interactions; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case CaslPackage.INTERACTIONS__INTERACTIONS: return ((InternalEList<?>)getInteractions()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case CaslPackage.INTERACTIONS__INTERACTIONS: return getInteractions(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case CaslPackage.INTERACTIONS__INTERACTIONS: getInteractions().clear(); getInteractions().addAll((Collection<? extends Interaction>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case CaslPackage.INTERACTIONS__INTERACTIONS: getInteractions().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case CaslPackage.INTERACTIONS__INTERACTIONS: return interactions != null && !interactions.isEmpty(); } return super.eIsSet(featureID); } } //InteractionsImpl
    Markdown
    UTF-8
    1,404
    2.6875
    3
    []
    no_license
    最近做的h5项目中有一个微信登录功能,将自己遇到的一些坑记录一下 前提: 1. 一个公众号 2. appid 首先就是在自己的vue项目中引入微信的接口 `<script src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>` 接着我们就可以在自己的login.vue中调用微信函数`WxLogin` 在login.vue中的mounted ```javascript var obj = new WxLogin({ id:"div", //div的id appid: "公众号里的appid", scope: "snsapi_login", redirect_uri: "http%3a%2f%2f96ac7d.natappfree.cc%2f%23%2fjump",//urlencode编码 }); ``` 解释一下redirect_url: 1. 如果是在开发环境,也就是用8080端口,网站还没有域名时,但是需要外网穿透,这时候你需要下一个natapp,可以帮你改自己的域名。(natapp不要下在c盘,我的下在c盘打不开,换到d盘就打开了,natapp的配置官网讲的很清楚) 2. 要用**urlencode编码**把redirect_url转化一下,这个百度转码工具就可以了 3. **域名有了要修改微信开放平台里的授权回调域**,这样才不会报参数错误 现在你就可以扫码登录了,空白页作为跳转中转站jump.vue,也就是上面的重定向地址,在这个地址里可以就收到code。code作为参数向后端发一次axios请求,得到用户信息
    Markdown
    UTF-8
    4,144
    3.484375
    3
    [ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
    permissive
    +++ date = "2016-07-12T20:20:27+01:00" description = "Tutorial on using find, a UNIX and Linux command for walking a file hierarchy. Examples of finding a file by name, finding and deleting a file, finding a directory and searching by modification time and permissions." image = "images/covers/find.png" caption = "The UNIX and Linux find command" slug = "unix-find" tags = ["UNIX"] title = "Linux and Unix find command tutorial with examples" +++ ## What is the find command in UNIX? The `find` command in UNIX is a command line utility for walking a file hierarchy. It can be used to find files and directories and perform subsequent operations on them. It supports searching by file, folder, name, creation date, modification date, owner and permissions. By using the `- exec` other UNIX commands can be executed on files or folders found. ## How to find a single file by name To find a single file by name pass the `-name` option to `find` along with the name of the file you are looking for. Suppose the following directory structure exists shown here as the output of the `tree` command. ```sh foo ├── bar ├── baz │   └── foo.txt └── bop ``` The file `foo.txt` can be located with the `find` by using the `-name` option. ```sh find ./foo -name foo.txt ./foo/baz/foo.txt ``` ## How to find and delete a file To find and delete a file pass the `-delete` option to `find`. This will delete the file with no undo so be careful. ```sh find ./foo -name foo.txt -delete ``` To be prompted to confirm deletion combine `-exec` with `rm -i`. ```sh find ./foo -name foo.txt -exec rm -i {} \; ``` Comparing the efficiency of these methods when operating on 10000 files we can see that using `-delete` is far more efficient. ```sh touch {0..10000}.txt time find ./ -type f -name "*.txt" -exec rm {} \; find ./ -type f -name "*.txt" -exec rm {} \; 3.95s user 1.44s system 99% cpu 5.402 total touch {0..10000}.txt time find ./ -type f -name '*.txt' -delete find ./ -type f -name '*.txt' -delete 0.03s user 0.06s system 98% cpu 0.090 total ``` ## How to find a directory To find a directory specify the option `-type d` with `find`. ```sh find ./foo -type d -name bar ./foo/bar ``` ## How to find files by modification time To find files by modification time use the `-mtime` option followed by the number of days to look for. The number can be a positive or negative value. A negative value equates to less then so `-1` will find files modified within the last day. Similarly `+1` will find files modified more than one day ago. ```sh find ./foo -mtime -1 find ./foo -mtime +1 ``` ## How to find files by permission To find files by permission use the `-perm` option and pass the value you want to search for. The following example will find files that everyone can read, write and execute. ```sh find ./foo -perm 777 ``` ## How to find and operate on files To find and operate on file us the `-exec` option. This allows a command to be executed on files that are found. ```sh find ./foo -type f -name bar -exec chmod 777 {} \; ``` ## How to find and replace in a range of files To find and replace across a range of files the `find` command may be combined with another utility like `sed` to operate on the files by using the `-exec` option. In the following example any occurrence of find is replaced with replace. ```sh find ./ -type f -exec sed -i 's/find/replace/g' {} \; ``` ## How to search for text within multiple files Another use of combining `find` with `exec` is to search for text within multiple files. ```sh find ./ -type f -name "*.md" -exec grep 'foo' {} \; ``` ## Further reading - [find man page][1] - [A collection of Unix/Linux find command examples][2] - [Find Command in Unix and Linux Examples][3] - [Some examples of using UNIX find command][4] [1]: http://linux.die.net/man/1/find [2]: http://alvinalexander.com/unix/edu/examples/find.shtml [3]: http://www.folkstalk.com/2011/12/101-examples-of-using-find-command-in.html [4]: http://www.ling.ohio-state.edu/~kyoon/tts/unix-help/unix-find-command-examples.htm [5]: /images/articles/find.png
    Rust
    UTF-8
    3,219
    2.65625
    3
    [ "Apache-2.0" ]
    permissive
    //! amqpr-api is AMQP client api library. //! You can talk with AMQP server via channel controller provided by this crate. //! There is two kind of channel controllers; GlobalChannelController and LocalChannelController. //! extern crate bytes; #[macro_use] extern crate error_chain; #[macro_use] extern crate futures; #[macro_use] extern crate log; extern crate tokio_core; extern crate tokio_io; extern crate amqpr_codec; macro_rules! try_stream_ready { ($polled: expr) => { match $polled { Ok(::futures::Async::Ready(Some(frame))) => frame, Ok(::futures::Async::Ready(None)) => return Err(::errors::Error::from(::errors::ErrorKind::UnexpectedConnectionClose).into()), Ok(::futures::Async::NotReady) => return Ok(::futures::Async::NotReady), Err(e) => return Err(e.into()), } } } pub mod channel; pub mod exchange; pub mod queue; pub mod basic; pub mod subscribe_stream; pub mod publish_sink; pub mod handshake; pub mod errors; pub(crate) mod common; pub use handshake::start_handshake; pub use channel::open_channel; pub use exchange::declare_exchange; pub use queue::{bind_queue, declare_queue}; pub use basic::{get_delivered, start_consume}; pub use basic::publish::publish; pub use subscribe_stream::subscribe_stream; pub use publish_sink::publish_sink; use futures::{Async, AsyncSink, Poll, Sink, StartSend, Stream}; use errors::Error; use amqpr_codec::Frame; type RawSocket = tokio_io::codec::Framed<tokio_core::net::TcpStream, amqpr_codec::Codec>; pub struct AmqpSocket(RawSocket); impl Stream for AmqpSocket { type Item = Frame; type Error = Error; fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { self.0.poll().map_err(|io_err| Error::from(io_err)) } } impl Sink for AmqpSocket { type SinkItem = Frame; type SinkError = Error; fn start_send(&mut self, item: Frame) -> StartSend<Frame, Error> { self.0 .start_send(item) .map_err(|io_err| Error::from(io_err)) } fn poll_complete(&mut self) -> Poll<(), Error> { self.0.poll_complete().map_err(|io_err| Error::from(io_err)) } fn close(&mut self) -> Poll<(), Error> { self.0.close().map_err(|io_err| Error::from(io_err)) } } /// This struct is useful when the case such as some functions require `S: Stream + Sink` but your socket is /// separeted into `Stream` and `Sink`. pub struct InOut<In: Stream, Out: Sink>(pub In, pub Out); impl<In: Stream, Out: Sink> Stream for InOut<In, Out> { type Item = In::Item; type Error = In::Error; fn poll(&mut self) -> Result<Async<Option<In::Item>>, In::Error> { self.0.poll() } } impl<In: Stream, Out: Sink> Sink for InOut<In, Out> { type SinkItem = Out::SinkItem; type SinkError = Out::SinkError; fn start_send( &mut self, item: Out::SinkItem, ) -> Result<AsyncSink<Out::SinkItem>, Out::SinkError> { self.1.start_send(item) } fn poll_complete(&mut self) -> Result<Async<()>, Out::SinkError> { self.1.poll_complete() } fn close(&mut self) -> Result<Async<()>, Out::SinkError> { self.1.close() } }
    Java
    UTF-8
    8,088
    1.96875
    2
    []
    no_license
    package com.dartrix.proyectoagenda; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.PersistableBundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import org.w3c.dom.Text; public class MostrarAsignacionActivity extends Activity { final Context cnt = this; String s; Activity currentActivity = this; DBproyectoAgenda sql = new DBproyectoAgenda(this, "Agendarium", null, 1); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.verasig_layout); Intent i = getIntent(); Bundle b = i.getExtras(); if (b!=null){ s = (String) b.get("id"); } final DBproyectoAgenda sql = new DBproyectoAgenda(this, "Agendarium", null, 1); llenarDatos(sql.traerAsignacion(s)); Button button = (Button) findViewById(R.id.calificar); // add button listener button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // custom dialog final Dialog dialog = new Dialog(cnt); dialog.setContentView(R.layout.custom_calificar_dialog); Button calificar = (Button) dialog.findViewById(R.id.calificar); Button cancelar = (Button) dialog.findViewById(R.id.cancelar); // if button is clicked, close the custom dialog calificar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView cal = (TextView)dialog.findViewById(R.id.calificacion); sql.editarAsignacionCalificacion(s, cal.getText().toString()); sql.actualizarAcumuladoMateria(Integer.toString(sql.traerAsignacion(s).getMateriaFK())); llenarDatos(sql.traerAsignacion(s)); dialog.dismiss(); Toast.makeText(getApplicationContext(),"Asignacion calificada",Toast.LENGTH_SHORT).show(); } }); cancelar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); Toast.makeText(getApplicationContext(),"Cancelado",Toast.LENGTH_SHORT).show(); } }); dialog.show(); } }); } @Override protected void onResume() { super.onResume(); setContentView(R.layout.verasig_layout); Intent i = getIntent(); Bundle b = i.getExtras(); if (b!=null){ s = (String) b.get("id"); } final DBproyectoAgenda sql = new DBproyectoAgenda(this, "Agendarium", null, 1); llenarDatos(sql.traerAsignacion(s)); Button button = (Button) findViewById(R.id.calificar); // add button listener button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // custom dialog final Dialog dialog = new Dialog(cnt); dialog.setContentView(R.layout.custom_calificar_dialog); Button calificar = (Button) dialog.findViewById(R.id.calificar); Button cancelar = (Button) dialog.findViewById(R.id.cancelar); // if button is clicked, close the custom dialog calificar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView cal = (TextView)dialog.findViewById(R.id.calificacion); sql.editarAsignacionCalificacion(s, cal.getText().toString()); llenarDatos(sql.traerAsignacion(s)); sql.actualizarAcumuladoMateria(Integer.toString(sql.traerAsignacion(s).getMateriaFK())); dialog.dismiss(); Toast.makeText(getApplicationContext(),"Asignacion calificada",Toast.LENGTH_SHORT).show(); } }); cancelar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); Toast.makeText(getApplicationContext(),"Cancelado",Toast.LENGTH_SHORT).show(); } }); dialog.show(); } }); } public void llenarDatos(Asignacion as){ TextView titulo = (TextView)findViewById(R.id.titulo); TextView fechahora = (TextView)findViewById(R.id.fechahora); TextView materia = (TextView)findViewById(R.id.materia); TextView tipo = (TextView)findViewById(R.id.tipo); TextView calificacion = (TextView)findViewById(R.id.calificacion); TextView desc = (TextView)findViewById(R.id.descripcion); Log.d("dat",as.getNombre()); titulo.setText(as.getNombre()); fechahora.setText(as.getFechalimite() + " " + as.getHoralimite()); DBproyectoAgenda sql = new DBproyectoAgenda(this, "Agendarium", null, 1); Materia m = sql.traerMateria(Integer.toString(as.getMateriaFK())); materia.setText(m.getNombreMateria()); tipo.setText(as.getTipo()); if (as.getCalificacion().equals("0")){ calificacion.setText("Sin calificar"); }else{ calificacion.setText(as.getCalificacion()); } Button circulo = (Button)findViewById(R.id.circulo); switch (as.getTipo()){ case "Tarea": circulo.setBackgroundTintList(getResources().getColorStateList(R.color.colorTarea)); break; case "Exposicion": circulo.setBackgroundTintList(getResources().getColorStateList(R.color.colorExposicion)); break; case "Proyecto": circulo.setBackgroundTintList(getResources().getColorStateList(R.color.colorProyecto)); break; case "Examen": circulo.setBackgroundTintList(getResources().getColorStateList(R.color.colorExamen)); break; } desc.setText(as.getDescripcion()); } public void eliminarAsign(View v){ AlertDialog.Builder builder1 = new AlertDialog.Builder(this); builder1.setTitle("Agendarium"); builder1.setMessage("Desea borrar esta materia? (Se borraran todas las asignaciones)"); builder1.setCancelable(true); builder1.setPositiveButton( "Si", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { sql.eliminarAsignacion(s); currentActivity.finish(); Toast.makeText(currentActivity,"Asignacion borrada.",Toast.LENGTH_LONG).show(); dialog.cancel(); } }); builder1.setNegativeButton( "No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert11 = builder1.create(); alert11.show(); } public void abrir (View v){ Intent i = new Intent(this, EditarAsignaturaActivity.class); i.putExtra("id",s); startActivity(i); } }
    JavaScript
    UTF-8
    142
    2.9375
    3
    [ "MIT" ]
    permissive
    async function(iter) { var result = 0; for (var value of iter) { result += await value; if (result > 10) break; } return result; }
    C++
    UTF-8
    6,717
    2.796875
    3
    []
    no_license
    int Int = 11; int S1 = 2; int S2 = 3; int S3 = 4; byte com = 0; int CG = 1; void setup() { Serial.begin(9600); pinMode(Int, OUTPUT); // lights up when command from group 1 is recognized pinMode(S1, OUTPUT); // lights up when subgroup x command 1 is recognized pinMode(S2, OUTPUT); // lights up when subgroup x command 2 is recognized pinMode(S3, OUTPUT); // lights up when subgroup x command 3 is recognized delay(2000); Serial.write(0xAA); // wait for input Serial.write(0x37); // enter compact mode delay(1000); Serial.write(0xAA); // wait for input Serial.write(0x21); // import group 1 Serial.println(); Serial.write(0x11); // //REMOVE LATERERERERERERRERER <------------------------------ Serial.println(" = Voice 1"); Serial.write(0x12); // //REMOVE LATERERERERERERRERER <------------------------------ Serial.println(" = Voice 2"); Serial.write(0x13); // //REMOVE LATERERERERERERRERER <------------------------------ Serial.println(" = Voice 3"); } void loop() { while(Serial.available()) { com = Serial.read(); switch(com) { case 0x11: // current group: command 1 if (CG == 1) // if current group is 1 (initializer group) { digitalWrite(Int, HIGH); // turn on the Int LED Serial.println("Switched to SG1"); //REMOVE LATERERERERERERRERER <------------------------------ Serial.write(0x22); // switch voice checks to group 2 CG = 2; // switch actions to group 2 (command subgroup for initializer 1) } else { if (CG == 2) // if current group is 2 (command subgroup for initializer 1) { digitalWrite(S1, HIGH); // turn on the S1 LED delay(100); digitalWrite(Int, LOW); // turn off the Int LED delay(1000); digitalWrite(S1, LOW); // turn off the S1 LED Serial.println("SG1 Command 1; switched to G1"); //REMOVE LATERERERERERERRERER <------------------------------ Serial.write(0x21); // switch voice checks to group 1 CG = 1; // switch back to initializer group } if (CG == 3) // if current group is 3 (command subgroup for initializer 2) { digitalWrite(Int, LOW); // turn off the Int LED Serial.println("SG2 Command 1; switched to G1"); //REMOVE LATERERERERERERRERER <------------------------------ Serial.write(0x21); // switch voice checks to group 1 CG = 1; // switch back to initializer group } if (CG == 4) // if current group is 4 (command subgroup for initializer 3) { digitalWrite(Int, LOW); // turn off the Int LED Serial.write(0x21); // switch voice checks to group 1 CG = 1; // switch back to initializer group } } break; //----------------------------------------------- case 0x12: if (CG == 1) // if current group is 1 (initializer group) { digitalWrite(Int, HIGH); // turn on the Int LED Serial.println("Switched to SG2"); //REMOVE LATERERERERERERRERER <------------------------------ Serial.write(0x23); // switch voice checks to group 3 CG = 3; // switch actions to group 3 (command subgroup for initializer 2) } else { if (CG == 2) // if current group is 2 (command subgroup for initializer 1) { digitalWrite(S2, HIGH); // turn on the S2 LED delay(100); digitalWrite(Int, LOW); // turn off the Int LED delay(1000); digitalWrite(S2, LOW); // turn off the S1 LED Serial.println("SG1 Command 2; switched to G1"); //REMOVE LATERERERERERERRERER <------------------------------ Serial.write(0x21); // switch voice checks to group 1 CG = 1; // switch back to initializer group } if (CG == 3) // if current group is 3 (command subgroup for initializer 2) { digitalWrite(Int, LOW); // turn off the Int LED Serial.println("SG2 Command 2; switched to G1"); //REMOVE LATERERERERERERRERER <------------------------------ Serial.write(0x21); // switch voice checks to group 1 CG = 1; // switch back to initializer group } if (CG == 4) // if current group is 4 (command subgroup for initializer 3) { digitalWrite(Int, LOW); // turn off the Int LED Serial.write(0x21); // switch voice checks to group 1 CG = 1; // switch back to initializer group } } break; //----------------------------------------------- case 0x13: if (CG == 1) // if current group is 1 (initializer group) { digitalWrite(Int, HIGH); // turn on the Int LED Serial.write(0x24); // switch voice checks to group 4 CG = 4; // switch actions to group 4 (command subgroup for initializer 4) } else { if (CG == 2) // if current group is 2 (command subgroup for initializer 1) { digitalWrite(S3, HIGH); // turn on the S3 LED delay(100); digitalWrite(Int, LOW); // turn off the Int LED delay(1000); digitalWrite(S3, LOW); // turn off the S3 LED Serial.println("SG1 Command 3; switched to G1"); //REMOVE LATERERERERERERRERER <------------------------------ Serial.write(0x21); // switch voice checks to group 1 CG = 1; // switch back to initializer group } if (CG == 3) // if current group is 3 (command subgroup for initializer 2) { digitalWrite(Int, LOW); // turn off the Int LED Serial.println("SG2 Command 3; switched to G1"); //REMOVE LATERERERERERERRERER <------------------------------ Serial.write(0x21); // switch voice checks to group 1 CG = 1; // switch back to initializer group } if (CG == 4) // if current group is 4 (command subgroup for initializer 3) { digitalWrite(Int, LOW); // turn off the Int LED Serial.write(0x21); // switch voice checks to group 1 CG = 1; // switch back to initializer group } } break; //----------------------------------------------- case 0x14: break; //----------------------------------------------- case 0x15: break; //----------------------------------------------- } } }
    C#
    UTF-8
    1,582
    2.609375
    3
    []
    no_license
    using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; using System.Xml.Serialization; using testFileUpload.Core.Types; namespace testFileUpload.Core.Models { [Serializable] [XmlRoot("Transaction")] public class XmlTransaction { [XmlAttribute] [MaxLength(50)] public string Id { get; set; } //Date Format yyyy-MM-ddThh:mm:ss e.g. 2019-0123T13:45:10 public DateTime TransactionDate { get; set; } public PaymentDetails PaymentDetails { get; set; } public XmlStatus Status { get; set; } } public class PaymentDetails { public decimal Amount { get; set; } public string CurrencyCode { get; set; } } [XmlRoot("Transactions")] public class TransactionFile : List<XmlTransaction> { } public static class TransactionHelper { public static string ToXml<T>(this T transaction) { var ns = new XmlSerializerNamespaces(); ns.Add("", ""); using var stringWriter = new StringWriter(); var serializer = new XmlSerializer(typeof(T)); serializer.Serialize(stringWriter, transaction, ns); return stringWriter.ToString(); } public static T FromXml<T>(this string xmlText) { using (var stringReader = new StringReader(xmlText)) { var serializer = new XmlSerializer(typeof(T)); return (T) serializer.Deserialize(stringReader); } } } }
    PHP
    UTF-8
    1,119
    2.953125
    3
    []
    no_license
    <?php require_once 'connectDB.php'; //$conn = connectDB(); $sql = "select cateId, cateName, modifyDate from category"; $result = mysqli_query($conn, $sql); ?> <!DOCTYPE html> <html> <head> </head> <body> <h2>CATEGORY FORM </h2> <p>This is function of adminstrator to insert, edit, delete one category.</p> <p><a href="Adding_Category.php"> New Category</a></p> <table style="width:100%" border = "1"> <tr> <th>Catgory Id</th> <th>Category Name</th> <th>Modify Date</th> <th></th> <th></th> </tr> <?php if (mysqli_num_rows($result) > 0) { // output data of each row while($row = mysqli_fetch_assoc($result)) { ?> <tr> <td><?php echo $row['cateId']?> </td> <td><?php echo $row['cateName']?></td> <td><?php echo $row['modifyDate']?></td> <td><a href="delete_category.php?id=<?php echo $row['cateId']?>">Delete</a></td> <td><a href="Adding_Category.php?id=<?php echo $row['cateId']?>">Edit</a></td> </tr> <?php } } else { echo "0 results"; } mysqli_close($conn); ?> </table> </body> </html>
    Java
    UTF-8
    2,913
    3.09375
    3
    []
    no_license
    package hangman; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class EvilHangmanGame implements IEvilHangmanGame { private KeyPartPair kpp; public Partition mypart; private int gcount; private ArrayList<String> guessedletters = new ArrayList<>(); public Key gamekey; public boolean winstatus = false; public EvilHangmanGame() { // TODO Auto-generated constructor stub } @Override public void startGame(File dictionary, int wordLength) { // TODO Auto-generated method stub // check wordlength ********************* >= 2 setGcount(0); try { Scanner sc = new Scanner(dictionary); mypart = new Partition(); while (sc.hasNext()) { mypart.add(sc.next()); } sc.close(); mypart.setWordLength(wordLength); gamekey = new Key(wordLength); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public Set<String> makeGuess(char guess) throws GuessAlreadyMadeException { // TODO Auto-generated method stub this.checkGuessMade(guess); kpp = new KeyPartPair(mypart, guess); Set<String> output = new TreeSet<>(); output = kpp.getBestSet(); addGuessedLetter(guess); mypart.words = output; //System.out.print(output); return output; } public int getGcount() { return gcount; } public void setGcount(int gcount) { this.gcount = gcount; } public void addGuessedLetter(char in) { String temp = Character.toString(in); guessedletters.add(temp); } public void addGuessedLetter(String in) { guessedletters.add(in); } public String printGuessedLetters() { StringBuilder sb = new StringBuilder(); Collections.sort(guessedletters); for (String s : guessedletters) { sb.append(s + " "); } return sb.toString(); } public void checkGuessMade(char in) throws GuessAlreadyMadeException { for (int x = 0; x < guessedletters.size(); x += 1) { if (guessedletters.get(x).charAt(0) == in) { throw new GuessAlreadyMadeException(); } } } public boolean gameRunning(EvilHangmanGame game) { if (game.getGcount() == 0) { return false; } if (game.gamekey.checkIfWordFull()) { winstatus = true; return false; } if (game.winstatus) { return false; } return true; } public boolean checkGuessValid(String in) { if (in.length() != 1) { return false; } char dachar = in.charAt(0); if (!Character.isLetter(dachar)) { return false; } return true; } public int haveTheyWon(char letter) { Key partitionkey = mypart.getPartsKey(letter); if (partitionkey == null) { winstatus = true; return 0; } else if (partitionkey.getCount() > 0) { gamekey.addletters(partitionkey); return partitionkey.getCount(); } else { gcount -= 1; return -1; } } }
    Python
    UTF-8
    2,347
    2.625
    3
    [ "MIT" ]
    permissive
    import importFile import kmeans import bisecting_kmeans import fuzzyCmeans import utils from sklearn import metrics import sys def main(algorithm, data, cl_labels, min_k, max_k, max_iterations, epsilon): results, silhouette, chs, ssws, ssbs, ars, hom, comp = [], [], [], [], [], [], [], [] membership, centroids, labels = [], [], [] for c in range(min_k, max_k + 1): if algorithm == 'kmeans': labels, centroids = kmeans.kmeans(data, c) elif algorithm == 'bisecting_kmeans': labels, centroids = bisecting_kmeans.bisecting_kmeans(data, c) elif algorithm == 'fuzzy_cmeans': membership, centroids = fuzzyCmeans.execute(data, max_iterations, c, epsilon) labels = fuzzyCmeans.get_labels(len(data), membership) silhouette.append((c, metrics.silhouette_score(data, labels, metric='euclidean'))) chs.append((c, metrics.calinski_harabaz_score(data, labels))) ssws.append((c, utils.get_ssw(data, centroids, labels))) ssbs.append((c, utils.get_ssb(centroids))) ars.append((c, metrics.adjusted_rand_score(cl_labels, labels))) hom.append((c, metrics.homogeneity_score(cl_labels, labels))) comp.append((c, metrics.completeness_score(cl_labels, labels))) results.append(("Silhouette", "", zip(*silhouette)[0], "", zip(*silhouette)[1], 333, "blue")) results.append(("Calinski-Harabaz Index", "", zip(*chs)[0], "", zip(*chs)[1], 334, "blue")) results.append(("Intra cluster Variance", "", zip(*ssws)[0], "", zip(*ssws)[1], 331, "blue")) results.append(("Inter cluster Variance", "", zip(*ssbs)[0], "", zip(*ssbs)[1], 332, "blue")) results.append(("Adjusted Rand Index", "", zip(*ars)[0], "", zip(*ars)[1], 335, "orange")) results.append(("Homogeneity", "", zip(*hom)[0], "", zip(*hom)[1], 336, "orange")) results.append(("Completeness", "", zip(*comp)[0], "", zip(*comp)[1], 337, "orange")) print(labels) utils.plot_results(results, algorithm) arguments = sys.argv file_name = arguments[1] class_name = arguments[2] algo = arguments[3] minimum_k = int(arguments[4]) maximum_k = int(arguments[5]) max_iter = int(arguments[6]) epsilon_ = float(arguments[7]) da, classif = importFile.read_file(file_name, class_name) main(algo, da, classif, minimum_k, maximum_k, max_iter, epsilon_)
    Java
    UTF-8
    427
    2.703125
    3
    []
    no_license
    package com.saptar.dijkstra.driver; import com.saptar.warshallflyod.engine.WarshallFlyod; public class WarshallFlyodDriver { final static int INF = 99999, V = 4; public static void main(String[] args) { int graph[][] = { { 0, 5, INF, 10 }, { INF, 0, 3, INF }, { INF, INF, 0, 1 }, { INF, INF, INF, 0 } }; WarshallFlyod a = new WarshallFlyod(); // Print the solution a.flyodWarshal(graph); } }
    Markdown
    UTF-8
    381
    2.578125
    3
    []
    no_license
    # myASR Final project for EE516 PMP at UW. Matlab implementation of a simple speaker independent, isolated word, whole-word model, single Gaussian per state, diagonal covariance Gaussian, automatic speech recognition (ASR) system, using the ten-word vocabulary W = {“zero”, “one”, “two”, “three”, ... "nine"}. See FinalProjectWriteUp.pdf for further information.
    C#
    UTF-8
    498
    3.078125
    3
    []
    no_license
    using System; using System.Collections.Generic; using System.Text; namespace ConsoleApp.Decorator { class ConcreteDecoratorB:Decorator { public override double Operation(double Prices) { Prices = Prices * 0.5; AddedBehavior(); Console.WriteLine("打5折后值为:" + Prices); return base.Operation(Prices); } private void AddedBehavior() { //本类独有的方法,区别于 } } }
    Python
    UTF-8
    16,765
    3.265625
    3
    []
    no_license
    import numpy as np import cPickle as pickle def _list2UT(l, N): """Return a list of the rows of an NxN upper triangular""" mat = [] start = 0 for i in range(N): mat.append(l[start:start+N-i]) start += N-i return mat def _UT2list(m): """Return the elements of an NxN upper triangular in row major order""" return np.array([item for thing in m for item in thing]) def _unsort(l, ind): """Scramble and return a list l by indexes ind""" l0 = np.zeros(len(l)) for i, x in zip(ind, l): l0[i]=x return l0 def _symmetrize(A): """Form a symmetric matrix out of a list of upper triangle elements Example: >>> A = [[0, 1, 2], [3, 4], [5]] >>> symmetrize(A) array([[ 0., 1., 2.], [ 1., 3., 4.], [ 2., 4., 5.]]) """ N = len(A) As = np.zeros((N, N)) for i, t in enumerate(A): As[i, i:]=t return As + As.T - np.diag(As.diagonal()) def _tile_arrays(A): """Take a symmetric array, A, size N x N, where N is even and return an array [ N x N ; N - 1 ] [ N - 1 ; A[1, 1] ] such that the lower to exploit symmetries. Example (N=2): >>> A = array([[0, 1, 2], >>> ... [1, 3, 4], >>> ... [2, 4, 6]]) >>> tile_arrays(tmp) array([[ 0., 1., 2., 1.], [ 1., 3., 4., 3.], [ 2., 4., 6., 4.], [ 1., 3., 4., 3.]]) """ N = 2*(np.shape(A)[0]-1) A_ref = np.zeros((N,N)) A_ref[:N/2+1,:N/2+1]=A A_ref[N/2:,:N/2+1] = A_ref[N/2:0:-1,:N/2+1] A_ref[:,N/2:] = A_ref[:,N/2:0:-1] return A_ref def _list_to_fft_mat(lis, index, N): lis = _unsort(lis, index) mat = _list2UT(lis, N/2+1) mat = _symmetrize(mat) # Make use of symmetries to mat = _tile_arrays(mat) # to construct the whole array. return mat def form_wl(N): #fwl = 10*N fwl = 6000. wl = np.array([[fwl/np.sqrt(i**2+j**2) if (i!=0 or j!=0) else 16000 for i in range(j, N)] for j in range(N)]) return _symmetrize(wl) def yield_wl(i, j, fwl=6000): if i == j == 0: return 16000 else: return fwl/np.sqrt(i**2+j**2) def prop(u, d, k): """Return the propagator for a layer of depth d and viscosity u with a harmonic load of order k As defined in Cathles 1975, p41, III-12. """ y = k*d s = np.sinh(y) c = np.cosh(y) cp = c + y*s cm = c - y*s sp = s + y*c sm = s - y*c s = y*s c = y*c return np.array([[cp, c, sp/u, s/u], [-c, cm, -s/u, sm/u], [sp*u, s*u, cp, c], [-s*u, sm*u, -c, cm]]) def exp_decay_const(earth, i, j): """Return the 2D exponential decay constant for order harmonic unit loads. Parameters ---------- earth - the earth object containing the parameters... i, j (int) - the x, y order numbers of the harmonic load Returns ------- tau - the exponential decay constant for harmonic load i,j, in yrs The resulting decay, dec(i, j) = 1-np.exp(elapsed_time * 1000./tauc(i, j)), along with lithospheric filter can be returned using earth.get_resp. """ wl = yield_wl(i, j, fwl=600*10) # wavelength ak = 2*np.pi/wl # wavenumber # ----- Interior to Surface integration ----- # # uses propagator method from Cathles 1975 # initialize two interior boundary vectors # assuming solution stays finite in the substratum (Cathles 1975, p41) cc = np.array([[1., 0., 1., 0.], [0., 1., 0., 1.]]) # Determine the necessary start depth (start lower for longer wavelengths) # to solve a roundoff problem with the matrix method. #TODO look into stability problem here if wl < 40: lstart = 9 elif wl < 200: lstart = 6 elif wl < 500: lstart = 4 else: lstart = 0 # integrate from starting depth to surface, layer by layer for dd, uu, in zip(earth.d[lstart:], earth.u[lstart:]): p = prop(uu, dd, ak) for k, c in enumerate(cc): cc[k,:] = p.dot(c) # initialize the inegration constants x = np.zeros(2) # solve for them, assuming 1 dyne normal load at surface x[0] = cc[1,2]/(cc[0,2]*cc[1,3]-cc[0,3]*cc[1,2]) x[1] = -cc[0,2]/(cc[0,2]*cc[1,3]-cc[0,3]*cc[1,2]) # multiply into the solution for k in range(2): cc[k,:]=x[k]*cc[k,:] # form the final solution cc = np.sum(cc, axis=0) # As cc[1] gives the surface velocity, the exponential time constant is # its reciprocal (see Cathles 1975, p43) # 1955600 = 2/rho (~3.313) /g (~9.8) * (1/pi*1e8) unit conversion to years tau = 1955600.*ak/cc[1] return tau class FlatEarthBase(object): """A Base class for 2D, flat earth models. Provides methods for saving, adding descriptions, and returning response. User must define a method for generating taus, """ def __init__(self): self.taus = None self.ak = None self.alpha = None self.index = None self.N = None def __call__(self, t_dur): return self.get_resp(t_dur) def save(self, filename): pickle.dump(self, open(filename, 'wb')) def get_resp(self, t_dur): """Calculate and return earth response to a unit load in an fft_mat. Parameters ---------- t_dur (float) - the duration, in cal ka BP, of applied load """ # Convert tau list to fft matrix taus = _list_to_fft_mat(self.taus, self.index, self.N) resp = (1-np.exp(t_dur/taus))/self.alpha return resp def set_N(self, N): self.N = N class EarthNLayer(FlatEarthBase): """Return the isostatic response of a 2D earth with n viscosity layers. The response is calculated from a viscous profile overlain by an elastic lithosphere in the fourier domain. """ def __init__(self, u=None, d=None, fr23=10., g=9.8, rho=3.313): if u is None: self.u = np.array([1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,0.018]) else: self.u = u if d is None: self.d = np.array([400.,300.,300.,300.,300.,300., 300.,200.,215.,175.,75. ]) else: self.d = d self.NLayers = len(self.u) self.fr23=fr23 self.g=g self.rho=rho def reset_params_list(self, params, arglist): """Set the full mantle rheology and calculate the decay constants. self.N must have been set already. """ us = ds = fr23 = N = None i=0 if 'us' in arglist: us = params[i:i+self.NLayers] i += self.NLayers if 'ds' in arglist: ds = params[i:i+self.NLayers] i += self.NLayers if 'fr23' in arglist: fr23 = params[i] i += 1 if 'N' in arglist: N = params[i] self.reset_params(us, ds, fr23, N) def reset_params(self, us=None, ds=None, fr23=None, N=None): if us is not None: self.u = us if ds is not None: self.d = ds self.fr23 = fr23 or self.fr23 N = N or self.N self.calc_taus(N) def set_taus(self, taus): self.taus=taus def calc_taus(self, N=None): """Generate and store a list of exponential decay constants. The procedure sets class data: N (the maximum order number calculated) taus (decay constants by increasing wavenumber) ak (wavenumbers in increasing order) index (the sorting key to reorder taus to increasing wavenumber) alpha (the lithospheric filter values in FFTmat format) Parameters ---------- N (int) - the maximum order number. Resulting earth parameters ak, taus, and alpha will be size NxN when in FFTmat format. For description of formats, see help(_list_to_fft_mat) """ self.N = N or self.N taus = [[exp_decay_const(self, i, j) for i in xrange(j, N/2+1)] for j in xrange(N/2+1)] #TODO Generalize to arbitrary wavelengths using GridObject? wl = np.array([[6000/np.sqrt(i**2+j**2) if (i!=0 or j!=0) else 16000 for i in range(j, N/2+1)] for j in range(N/2+1)]) wl = _UT2list(wl) self.ak = 2*np.pi/np.array(wl) # Sort by increasing order number self.index = range(len(self.ak)) self.index.sort(key=self.ak.__getitem__) self.ak = self.ak[self.index] self.taus = _UT2list(taus)[self.index]*1e-3 # and convert to kyrs # the Lithosphere filter, sorted by wave number # factor of 1e8 is for unit conversion self.alpha = 1.+((self.ak)**4)*self.fr23/self.g/self.rho*1e8 # Augment the decay times by the Lithosphere filter self.taus = self.taus/self.alpha # Turn the Lithosphere filter and taus into a matrix that matches the # frequencey matrix from an NxN fft. self.alpha = _list_to_fft_mat(self.alpha, self.index, self.N) class EarthTwoLayer(FlatEarthBase): """Return the isostatic response of a flat earth with two layers. The response is calculated analytically in the fourier domain from a uniform mantle of viscosity u overlain by an elastic lithosphere with flexural rigidty fr23. """ def __init__(self, u, fr23, g=9.8, rho=3.313): self.u = u self.fr23 = fr23 self.g = g self.rho = rho def reset_params_list(self, params, arglist): params = dict(zip(arglist, xs)) self.reset_params(params) def reset_params(self, u=None, fr23=None, N=None): self.u = u or self.u self.fr23 = fr23 or self.fr23 N = N or self.N self.calc_taus(N) def calc_taus(self, N=None): """Generate and store a list of exponential decay constants. The procedure sets class data: N (the maximum order number calculated) taus (decay constants in flattend upper diagonal list) ak (wavenumbers in increasing order) index (the sorting key to reorder taus to increasing wavenumber) alpha (the lithospheric filter values in FFTmat format) Parameters ---------- N (int) - the maximum order number. Resulting earth parameters ak, taus, and alpha will be size NxN when in FFTmat format. For description of formats, see help(_list_to_fft_mat) """ N = N or self.N #TODO Generalize to arbitrary wavelengths wl = np.array([[6000/np.sqrt(i**2+j**2) if (i!=0 or j!=0) else 16000 for i in range(j, N/2+1)] for j in range(N/2+1)]) wl = _UT2list(wl) self.ak = 2*np.pi/np.array(wl) # Sort by increasing order number self.index = range(len(self.ak)) self.index.sort(key=self.ak.__getitem__) self.ak = self.ak[self.index] self.taus = -2*self.u*self.ak/self.g/self.rho # Unit conversion so result is in kyrs: # u in Pa s=kg/m s, ak in 1/km, g in m/s2, rho in g/cc # and np.pi*1e7 s/yr self.taus = self.taus*(1./np.pi)*1e5 # the Lithosphere filter, sorted by wave number # factor of 1e8 is for unit conversion self.alpha = 1.+((self.ak)**4)*self.fr23/self.g/self.rho*1e8 # Augment the decay times by the Lithosphere filter self.taus = self.taus/self.alpha # Turn the Lithosphere filter and taus into a matrix that matches the # frequencey matrix from an NxN fft. self.alpha = _list_to_fft_mat(self.alpha, self.index, self.N) class EarthThreeLayer(FlatEarthBase): """Return the isostatic response of a flat earth with three layers. The response is calculated analytically in the fourier domain from a two layer mantle whose lower layer, of viscosity u1, is overlain layer of viscosity u2 and width h, which in turn is overlain by an elastic lithosphere with flexural rigidty fr23. """ def __init__(self, u1, u2, fr23, h, g=9.8, rho=3.313): self.g = g self.rho = rho self.u1 = u1 self.u2 = u2 self.fr23 = fr23 self.h = h def reset_params_list(self, params, arglist): params = dict(zip(arglist, xs)) self.reset_params(params) def reset_params(self, u1=None, u2=None, fr23=None, h=None, N=None): self.u1 = u1 or self.u1 self.u2 = u2 or self.u2 self.fr23 = fr23 or self.fr23 self.h = h or self.h N = N or self.N self.calc_taus(N) def get_params(self): return [self.u1, self.u2, self.fr23, self.h] def calc_taus(self, N): """Generate and store a list of exponential decay constants. The procedure sets class data: N (the maximum order number calculated) taus (decay constants in flattend upper diagonal list) ak (wavenumbers in increasing order) index (the sorting key to reorder taus to increasing wavenumber) alpha (the lithospheric filter values in FFTmat format) Parameters ---------- N (int) - the maximum order number. Resulting earth parameters ak, taus, and alpha will be size NxN when in FFTmat format. For description of formats, see help(_list_to_fft_mat) """ self.N = N #TODO Generalize to arbitrary wavelengths wl = np.array([[6000/np.sqrt(i**2+j**2) if (i!=0 or j!=0) else 16000 for i in range(j, N/2+1)] for j in range(N/2+1)]) wl = _UT2list(wl) self.ak = 2*np.pi/np.array(wl) # Sort by increasing order number self.index = range(len(self.ak)) self.index.sort(key=self.ak.__getitem__) self.ak = self.ak[self.index] # Cathles (1975) III-21 c = np.cosh(self.ak*self.h) s = np.sinh(self.ak*self.h) u = self.u2/self.u1 ui = 1./u r = 2*c*s*u + (1-u**2)*(self.ak*self.h)**2 + ((u*s)**2+c**2) r = r/((u+ui)*s*c + self.ak*self.h*(u-ui) + (s**2+c**2)) r = 2*c*s*u + (1-u**2)*(self.ak*self.h)**2 + ((u*s)**2+c**2) r = r/((u+ui)*s*c + self.ak*self.h*(u-ui) + (s**2+c**2)) self.taus = -2*self.u1*self.ak/self.g/self.rho*r # Unit conversion so result is in kyrs: # u in Pa s=kg/m s, ak in 1/km, g in m/s2, rho in g/cc # and np.pi*1e7 s/yr self.taus = self.taus*(1./np.pi)*1e5 # the Lithosphere filter, sorted by wave number # factor of 1e8 is for unit conversion self.alpha = 1.+((self.ak)**4)*self.fr23/self.g/self.rho*1e8 # Augment the decay times by the Lithosphere filter self.taus = self.taus/self.alpha # Turn the Lithosphere filter and taus into a matrix that matches the # frequencey matrix from an NxN fft. self.alpha = _list_to_fft_mat(self.alpha, self.index, self.N) def check_k(earth): """Check whether different 2D k matrices are identical, useful for debugging. """ N = earth.N wl = form_wl(N/2+1) wl = _tile_arrays(wl) ak_wl = 2*np.pi/wl ki = np.reshape(np.tile( np.fft.fftfreq(N, 6000/(2*np.pi)/N), N), (N, N)) ak_fft = np.sqrt(ki**2 + ki.T**2) ak_fft[0,0] = 2*np.pi/16000 ak_ea = _list_to_fft_mat(earth.ak, earth.index, N) print "ak_wl and ak_fft are close: "+str(np.allclose(ak_wl, ak_fft)) print "ak_wl and ak_ea are close: "+str(np.allclose(ak_wl, ak_ea)) print "ak_fft and ak_ea are close: "+str(np.allclose(ak_fft, ak_ea)) def load(filename): return pickle.load(open(filename, 'r'))
    C++
    UTF-8
    7,279
    3.046875
    3
    []
    no_license
    #include <iostream> #include <vector> #include <fstream> using namespace std; class fraction{ public: long long int x; long long int y=1; fraction(int a,int b){ x=a; y=b; } fraction(int c){ x=c; y=1; } fraction operator + (fraction f){ long long int tempX=x*f.y+f.x*y; long long int tempY=f.y*y; return fraction(tempX,tempY); }; fraction operator - (fraction f){ long long int tempX=x*f.y-f.x*y; long long int tempY=f.y*y; return fraction(tempX,tempY); }; fraction operator / (fraction f){ return fraction(x*f.y,y*f.x); }; fraction operator * (fraction f){ if(f.x==0){ return fraction(0); } return fraction(x*f.x,y*f.y); }; bool operator > (fraction f){ return (double)x/y>(double)f.x/f.y; }; bool operator < (fraction f){ return (double)x/y<(double)f.x/f.y; }; bool operator == (double a){ return (double)x/y==a; }; bool operator != (double a){ return !((double)x/y==a); }; }; void sortRows(vector<vector<fraction>>& matrix,vector<vector<fraction>>& imatrix,vector<fraction>& b, int select){ for(int i=select+1;i<matrix.size();i++){ for(int j=i-1;j>=select;j--){ if(matrix[j+1][select]>matrix[j][select]){ auto temp = matrix[j]; matrix[j]=matrix[j+1]; matrix[j+1]=temp; auto itemp = imatrix[j]; imatrix[j]=imatrix[j+1]; imatrix[j+1]=itemp; auto btemp = b[j]; b[j]=b[j+1]; b[j+1]=btemp; } } } } void rowOperations(vector<vector<fraction>>& matrix,vector<vector<fraction>>& imatrix,vector<fraction>& b,int startRow){ for(int i=startRow+1;i<matrix.size();i++){ fraction multi = matrix[i][startRow]/matrix[startRow][startRow]; for(int j=0;j<matrix[i].size();j++){ matrix[i][j]=matrix[i][j]-(matrix[startRow][j]*multi); imatrix[i][j]=imatrix[i][j]-(imatrix[startRow][j]*multi); } b[i]=b[i]-(b[startRow]*multi); } } vector<vector<fraction>> identityy(vector<vector<fraction>> matrix,vector<vector<fraction>> imatrix){ for(int i=0;i<matrix.size();i++){ for(int j=0;j<matrix.size();j++){ if(i==j){ fraction pivot=matrix[i][i]; matrix[i][j]=matrix[i][j]/pivot; imatrix[i][j]=imatrix[i][j]/pivot; } } } fraction pivot = matrix[0][1]; for(int i=0;i<3;i++){ matrix[0][i]=matrix[0][i]-(matrix[1][i]*pivot); imatrix[0][i]=imatrix[0][i]-(imatrix[1][i]*pivot); } imatrix[0][2]=imatrix[0][2]-(imatrix[2][2]*matrix[0][2]); imatrix[1][2]=imatrix[1][2]-(imatrix[2][2]*matrix[1][2]); return imatrix; } vector<vector<fraction>> identity(int n){ vector<vector<fraction>> iMatrix; for(int i=0;i<n;i++){ vector<fraction> temp; for(int j=0;j<n;j++){ if(i==j) temp.push_back(fraction(1)); else temp.push_back(fraction(0)); } iMatrix.push_back(temp); } return iMatrix; } void assign(vector<vector<fraction>>& matrix,vector<vector<fraction>>& imatrix,vector<fraction>& b,ifstream& infile){ int size; infile>>size; for(int i=0;i<size;i++){ vector<fraction> v; for(int j=0;j<size;j++){ double temp; double bottom=1; infile>>temp; while((int)temp!=temp){ temp*=10; bottom*=10; } v.push_back(fraction(temp,bottom)); } double temp; double bottom=1; infile>>temp; while((int)temp!=temp){ temp*=10; bottom*=10; } b.push_back(fraction(temp,bottom)); matrix.push_back(v); } imatrix=identity(size); } void printMatrix(vector<vector<fraction>> matrix,ofstream& outfile){ for(int i=0;i<matrix.size();i++){ for(fraction j:matrix[i]){ outfile<<j.x/(double)j.y<<" "; } outfile<<endl; } } vector<fraction> solve(vector<vector<fraction>> matrix,vector<fraction> b,int arbitrary){ vector<fraction> reverseSolution; for(int i=0;i<arbitrary;i++){ reverseSolution.push_back(fraction(0)); } for(int i=matrix.size()-arbitrary-1;i>=0;i--){ fraction sum(0); int count=0; if(reverseSolution.size()!=0) for(int j=matrix.size()-1;j>i;j--){ sum=sum+(reverseSolution[count]*matrix[i][j]); count++; } b[i]=b[i]-sum; reverseSolution.push_back(b[i]/matrix[i][i]); } return reverseSolution; } void findRank(ifstream& infile,ofstream& outfile){ vector<vector<fraction>> matrix; vector<vector<fraction>> iMatrix; vector<fraction> b; assign(matrix,iMatrix,b,infile); for(int i=0;i<matrix.size();i++){ sortRows(matrix,iMatrix,b,i); if(matrix[i][i]==0){ continue; } rowOperations(matrix,iMatrix,b,i); } int rank=matrix.size(); for(int i=0;i<matrix.size();i++){ if(matrix[i][i]==0) rank--; } // if 0 arbitrary if 1 no solution if 2 unique solution int selection; if(rank<matrix.size()){ bool solvable=true; int lastColumn=matrix.size()-1; while(matrix[lastColumn][matrix.size()-1]==0){ if(b[lastColumn]!=0){ solvable= false; break; } lastColumn--; } if(solvable){ selection=0; } else{ selection=1; } } else{ selection=2; } if(selection==0){ int arbitrary=matrix.size()-rank; vector<fraction> sol; sol=solve(matrix,b,arbitrary); int count=1; outfile<<"Arbitrary variables:"; for(int i=sol.size()-1;i>=0;i--){ fraction h=sol[i]; if(h.x==0){ outfile<<"x"<<sol.size()-i<<" "; } } outfile<<endl; outfile<<"Arbitrary Solution:"<<endl; for(int i=sol.size()-1;i>=0;i--){ fraction h=sol[i]; outfile<<"x"<<count<<"="<<h.x/(double)h.y<<" "; count++; } } else if(selection==1){ outfile<<"Inconsistent"<<" "<<"problem"; } else{ outfile<<"Unique Solution:"; vector<fraction> sol; sol=solve(matrix,b,0); for(int i=sol.size()-1;i>=0;i--){ fraction h=sol[i]; outfile<<h.x/(double)h.y<<" "; } outfile<<endl<<"Inverted A:"; iMatrix=identityy(matrix,iMatrix); printMatrix(matrix,outfile); } } int main() { ifstream infile1("../input1.txt"); ofstream outfile1("../output1.txt"); ifstream infile2("../input2.txt"); ofstream outfile2("../output2.txt"); ifstream infile3("../input3.txt"); ofstream outfile3("../output3.txt"); findRank(infile1,outfile1); findRank(infile2,outfile2); findRank(infile3,outfile3); return 0; }
    C++
    UTF-8
    1,412
    2.703125
    3
    [ "BSD-3-Clause" ]
    permissive
    #ifndef STLPLUS_WILDCARD #define STLPLUS_WILDCARD //////////////////////////////////////////////////////////////////////////////// // Author: Andy Rushton // Copyright: (c) Southampton University 1999-2004 // (c) Andy Rushton 2004 onwards // License: BSD License, see ../docs/license.html // This is a portable interface to wildcard matching. // The problem: // * matches any number of characters - this is achieved by matching 1 and seeing if the remainder matches // if not, try 2 characters and see if the remainder matches etc. // this must be recursive, not iterative, so that multiple *s can appear in the same wildcard expression // ? matches exactly one character so doesn't need the what-if approach // \ escapes special characters such as *, ? and [ // [] matches exactly one character in the set - the difficulty is the set can contain ranges, e.g [a-zA-Z0-9] // a set cannot be empty and the ] character can be included by making it the first character //////////////////////////////////////////////////////////////////////////////// #include "./portability_fixes.hpp" #include <string> namespace stlplus { // wild = the wildcard expression // match = the string to test against that expression // e.g. wildcard("[a-f]*", "fred") returns true bool wildcard(const std::string& wild, const std::string& match); } #endif
    Java
    UTF-8
    585
    2.21875
    2
    []
    no_license
    package org.intellij.trinkets.problemsView.problems; import org.intellij.trinkets.problemsView.ui.TreeNodeElement; import org.jetbrains.annotations.NotNull; /** * Problem. * * @author Alexey Efimov */ public interface Problem extends TreeNodeElement { Problem[] EMPTY_PROBLEM_ARRAY = new Problem[]{}; /** * Get problem type. * * @return Problem type. */ @NotNull ProblemType getType(); /** * Return fixes for this problem. * * @return Fixes array. */ @NotNull ProblemFix[] getFixes(); }
    JavaScript
    UTF-8
    540
    2.59375
    3
    []
    no_license
    'use strict'; // Remove focus away from the hero as the user scrolls by making it darker var $mainHeader = $('main header'); $mainHeader.css({ background: 'rgba(0, 0, 0, .5)' }); var scrollFade = function scrollFade() { var winheight = $(window).height(); var scrollTop = $(window).scrollTop(); var trackLength = winheight - scrollTop; var opacity = (1 - trackLength / winheight) / 2; $mainHeader.css({ background: 'rgba(0, 0, 0, ' + (.5 + opacity) + ')' }); }; $(window).on('scroll', function () { scrollFade(); });
    Java
    UTF-8
    2,619
    2.484375
    2
    [ "Apache-2.0" ]
    permissive
    package org.teiid.core.types.basic; import java.math.BigDecimal; import java.math.BigInteger; import org.teiid.core.CorePlugin; import org.teiid.core.types.Transform; import org.teiid.core.types.TransformationException; public abstract class NumberToNumberTransform extends Transform { private Class<?> sourceType; private Comparable<?> min; private Comparable<?> max; public NumberToNumberTransform(Number min, Number max, Class<?> sourceType) { this.sourceType = sourceType; if (sourceType == Short.class) { this.min = min.shortValue(); this.max = max.shortValue(); } else if (sourceType == Integer.class) { this.min = min.intValue(); this.max = max.intValue(); } else if (sourceType == Long.class) { this.min = min.longValue(); this.max = max.longValue(); } else if (sourceType == Float.class) { this.min = min.floatValue(); this.max = max.floatValue(); } else if (sourceType == Double.class) { this.min = min.doubleValue(); this.max = max.doubleValue(); } else if (sourceType == BigInteger.class) { if (min instanceof Double || min instanceof Float) { this.min = BigDecimal.valueOf(min.doubleValue()).toBigInteger(); this.max = BigDecimal.valueOf(max.doubleValue()).toBigInteger(); } else { this.min = BigInteger.valueOf(min.longValue()); this.max = BigInteger.valueOf(max.longValue()); } } else if (sourceType == BigDecimal.class) { if (min instanceof Double || min instanceof Float) { this.min = BigDecimal.valueOf(min.doubleValue()); this.max = BigDecimal.valueOf(max.doubleValue()); } else { this.min = BigDecimal.valueOf(min.longValue()); this.max = BigDecimal.valueOf(max.longValue()); } } else if (sourceType == Byte.class) { } else { throw new AssertionError(); } } @Override public Class<?> getSourceType() { return sourceType; } protected void checkValueRange(Object value) throws TransformationException { if (((Comparable)value).compareTo(min) < 0 || ((Comparable)value).compareTo(max) > 0) { throw new TransformationException(CorePlugin.Event.TEIID10058, CorePlugin.Util.gs(CorePlugin.Event.TEIID10058, value, getSourceType().getSimpleName(), getTargetType().getSimpleName())); } } }
    Python
    UTF-8
    674
    3.109375
    3
    []
    no_license
    from typing import List intervals=[[1,4], [4,5], [0,1]] class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: if len(intervals)==0: return intervals addList=[] hold='' intervals=sorted(intervals, key=lambda x : x[0]) for i, v in enumerate(intervals): if (i==0): hold=v else: if(hold[1]>=v[0]): hold=[hold[0], v[1]] elif (hold[1]<v[0]): addList.append(hold) hold=v addList.append(hold) return addList o=Solution() y=o.merge(intervals) print(y)
    Markdown
    UTF-8
    3,804
    3.25
    3
    [ "MIT", "Apache-2.0" ]
    permissive
    --- layout: post title: "markdown语法初体验" subtitle: "学习使我快乐" date: 2018-08-01 12:00:00 author: "Yao Shengli" header-img: "img/post-bg-nextgen-web-pwa.jpg" header-mask: 0.3 catalog: true tags: - 知识学杂 --- ## markdown 语法 ### 概述 *** **宗旨** Markdown 的目标是实现「易读易写」. 可读性,无论如何,都是最重要的。一份使用 Markdown 格式撰写的文件应该可以直接以纯文本发布,并且看起来不会像是由许多标签或是格式指令所构成。Markdown 语法受到一些既有 text-to-HTML 格式的影响,包括 [Setext](http://docutils.sourceforge.net/mirror/setext.html)、[atx](http://www.aaronsw.com/2002/atx/)、[Textile](http://textism.com/tools/textile/)、[reStructuredText](http://docutils.sourceforge.net/rst.html)、[Grutatext](http://www.triptico.com/software/grutatxt.html) 和 [EtText](http://ettext.taint.org/doc/),而最大灵感来源其实是纯文本电子邮件的格式。 **兼容HTML** 例子如下,在Markdown文件里加上一段HTML表格: <table> <tr> <td>name</td> </tr> <tr> <td>Yao Shengli</td> </tr> </table> ### 区块元素 *** **段落和换行** 一个 Markdown 段落是由一个或多个连续的文本行组成,它的前后要有一个以上的空行(空行的定义是显示上看起来像是空的,便会被视为空行。比方说,若某一行只包含空格和制表符,则该行也会被视为空行)。普通段落不该用空格或制表符来缩进。 **标题** 类 Atx 形式则是在行首插入 1 到 6 个 # ,对应到标题 1 到 6 阶,例如: # 这是 H1 ## 这是 H2 ###### 这是 H6 **区块引用** Markdown 标记区块引用是使用类似 email 中用 > 的引用方式。如果你还熟悉在 email 信件中的引言部分,你就知道怎么在 Markdown 文件中建立一个区块引用,那会看起来像是你自己先断好行,然后在每行的最前面加上 > :、 >这就是区块引用 >这也是 Markdown 也允许你偷懒只在整个段落的第一行最前面加上 > : >这样写也行 也行 >还真有意思 啊 引用的区块内也可以使用其他的 Markdown 语法,包括标题、列表、代码区块等: > ## 这是一个标题。 > > 1. 这是第一行列表项。 > 2. 这是第二行列表项。 > > 给出一些例子代码: > > return shell_exec("echo $input | $markdown_script"); **列表** Markdown 支持有序列表和无序列表。 * red * green * blue 有序列表则使用数字接着一个英文句点 1. red 2. green 3. blue **代码区块** 要在 Markdown 中建立代码区块很简单,只要简单地缩进 4 个空格或是 1 个制表符就可以,例如,下面的输入: 这是一个普通的锻炼 这是一个代码区块 **分隔线** 你可以在一行中用三个以上的星号、减号、底线来建立一个分隔线,行内不能有其他东西。你也可以在星号或是减号中间插入空格。下面每种写法都可以建立分隔线: * * * *** ***** - - - ------------------ ### 区段元素 *** **链接** [链接名字](链接地址) **强调** **强调** **代码** 如果要标记一小段行内代码,你可以用反引号把它包起),例如: `printf()` `printf()`测试 如果要在代码区段内插入反引号,你可以用多个反引号来开启和结束代码区段: ``function a(){ console.log("hellow") }`` ```javascript function a(){ console.log("hellow") } ``` **图片** ![Alt text](/path/to/img.jpg) ![](/img/avatar-hux-ny.jpg)
    JavaScript
    UTF-8
    1,152
    2.765625
    3
    [ "MIT" ]
    permissive
    'use strict' const constants = require('./constants') const min = 0 const isNil = (val) => typeof val === 'undefined' || val === null const isValidInRange = (num, max) => !isNaN(num) && num >= min && num <= max const isValid = (val, max) => { if (!isValidInRange(val, max)) { throw new Error(`'${val}' must be a number between ${min} and ${max}`) } return true } const getTimestampNoMs = (date) => parseInt(date / constants.second, constants.radix10) % constants.uIntMax const getNumFromPosInHexString = (hexString, start, length) => parseInt(hexString.substr(start, length), constants.radix16) const getMaskedHexString = (length, num) => { const hexString = num.toString(constants.radix16) if (hexString.length === length) { return hexString } if (hexString.length !== length) { return constants.hexStringIntMask.substring(hexString.length, length) + hexString } } const getIsoFormattedTimestampNoMs = (num) => new Date(num * constants.second).toISOString() module.exports = { isNil, isValid, getTimestampNoMs, getNumFromPosInHexString, getMaskedHexString, getIsoFormattedTimestampNoMs }
    PHP
    UTF-8
    729
    2.609375
    3
    [ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
    permissive
    <?php require '../lib/mavenlink_api.php'; $mavenlinkApi = new MavenlinkApi('<oauthTokenHere>'); $workspacesJson = $mavenlinkApi->getWorkspaces(); $workspacesDecodedJson = json_decode($workspacesJson, true); echo '<h1> Your workspaces: </h1>'; echo '<ul>'; $totalBudget = 0; foreach ($workspacesDecodedJson[results] as $dataItem) { $workspace = $workspacesDecodedJson[$dataItem[key]][$dataItem[id]]; echo '<li>' . $workspace[title] . '<br /> Budget: ' . $workspace[price] . '<br /><br /></li>'; $totalBudget = $totalBudget + $workspace[price_in_cents]; } echo '</ul>'; setlocale(LC_MONETARY, 'en_US'); echo '<br /><br /><h3> Total Project Budgets: ' . money_format('%i', $totalBudget/100) . '</h3>'; ?>
    Markdown
    UTF-8
    1,572
    3.015625
    3
    []
    no_license
    # Visual_tracking-based-on-CNN-and-RNN ### Motivation: The key challenge in building a neural net is requirement of humongous training data. The next hindrance to deploy the model in embedded AI device is number of computaions, thus demanding a lighter model. We hypothesized that training Re3 visual tracker with less number of videos should also provide an appreciable level of tracking. Our hypothesis is backed up by the core idea of Re3, structured to learn tracking through feature level differences between consecutive frames of training videos. ### Model: The training dataset for our project is 15 videos from imagenet video dataset. The model is implemented in Pytorch framework against the author\`s implementation in tensorflow. Since Pytorch is easy for debugging and maintenance, this framework was chosen. ### Prerequisites: 1. python3.6 2. PyTorch 3. OpenCV 3.4.2 or greater 4. Numpy 1.16 or greater ### Result: Model\`s behaviour of tracking animals can be seen below. ![](dog.gif) However, the model could not track a hand thus failing to generalize. Our training videos consist of animals like horse, panda, etc.., as object of interest. It could be the reason behind model\`s behaviour on animal videos. Also, the CNN model was frozen during training. ### Future Scope: 1) Unfreeze the CNN model and see its impact on generalization. 2) Analyze the behaviour of the model with lighter CNN nets like resnet. ### Authors: * **Goushika Janani** -[GoushikaJanani](https://github.com/GoushikaJanani) * **Bharath C Renjith** -[cr-bharath](https://github.com/cr-bharath)
    C++
    UTF-8
    550
    2.953125
    3
    []
    no_license
    #include <iostream> #include <vector> using namespace std; static int a[101][101] = {0}; int uniquePaths(int m, int n) { //m为列,n为行 if(m<=0 || n<=0) return 0; else if(m==1||n==1) return 1; else if(m==2 && n==2) return 2; else if((m==3 && n==2) || (m==2 && n==3)) return 3; if(a[m][n]>0) return a[m][n]; a[m-1][n] = uniquePaths(m-1,n); a[m][n-1] = uniquePaths(m,n-1); a[m][n] = a[m-1][n]+a[m][n-1]; return a[m][n]; } int main(){ cout<<uniquePaths(3,2)<<endl; system("pause"); return 0; }
    Java
    UTF-8
    1,486
    2.265625
    2
    []
    no_license
    import java.text.SimpleDateFormat; import java.time.LocalDateTime; public class Main { public static void main(String[] args) { SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); System.out.println(LocalDateTime.now()); LoginEngine<User> userLoginEngine = new LoginEngine<>(); LoginEngine<Admin> adminLoginEngine = new LoginEngine<>(); UserCreationPanel userCreationPanel = new UserCreationPanel(userLoginEngine); AdminCreationPanel adminCreationPanel = new AdminCreationPanel(adminLoginEngine); LoginPanel userLoginPanel = new LoginPanel(userLoginEngine); LoginPanel adminLoginPanel = new LoginPanel(adminLoginEngine); loadTestAccounts(userCreationPanel); loadTestAccounts(adminCreationPanel); userLoginEngine.showAccounts(); adminLoginEngine.showAccounts(); // Admin admin = adminLoginPanel.login(); // System.out.println(admin); AuctionEngine.loadTestCategories(); CategoriesBrowser.viewCategories(CategoriesBrowser.byName()); } public static void loadTestAccounts(AccountCreationPanel creationPanel) { creationPanel.createAccount("[email protected]", "Zaq12wsx"); creationPanel.createAccount("[email protected]", "Zaq12wsx"); creationPanel.createAccount("[email protected]", "Zaq12wsx"); creationPanel.createAccount("[email protected]", "Zaq12wsx"); creationPanel.createAccount("[email protected]", "Zaq12wsx"); } }
    Java
    UTF-8
    8,642
    2.328125
    2
    []
    no_license
    /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package dipit_game; import dipit_game.GameWindowJFrame; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import ExpandedGame.ExpandedGame_OnKeyPressedImpl; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.xeustechnologies.jcl.JarClassLoader; import org.xeustechnologies.jcl.JclObjectFactory; import org.xeustechnologies.jcl.proxy.CglibProxyProvider; import org.xeustechnologies.jcl.proxy.ProxyProviderFactory; /** * * @author Arch */ public class DIPIT_GAME_Main { public static final String DIPITPATH = "C:/Users/Arch/Documents/NetBeansProjects/DIPIT_GAME/build/classes"; public static World_DIPIT TheWorld; public static PlayerBase ThePlayer; public static GameWindowJFrame GameWindow; static int sizex = 4; static int sizey = 4; public static List<String> ConsoleOuts = new ArrayList<>(); private static final List<dipit_game.events.PostWorldGenInterface> postWorldGen_listeners = new ArrayList<>(); private static List<dipit_game.events.OnKeyPressedInterface> OnKeyPressed_Listeners = new ArrayList<>(); public static void add_postWorldGen_Listener(dipit_game.events.PostWorldGenInterface toAdd) { postWorldGen_listeners.add(toAdd); } public static void add_OnKeyPressed_Listener(dipit_game.events.OnKeyPressedInterface toAdd) { OnKeyPressed_Listeners.add(toAdd); } public static void OnKeyPressed(java.awt.event.KeyEvent evt) { OnKeyPressed_Listeners.stream().forEach((hl) -> { //System.out.println(("hl(null) : " + (hl == null))); hl.OnKeyPressed(evt); }); } public static void main(String[] args) { URL main = dipit_game.DIPIT_GAME_Main.class.getResource("dipit_game.DIPIT_GAME_Main.class"); if (!"file".equalsIgnoreCase(main.getProtocol())) { throw new IllegalStateException("Main class is not stored in a file."); } File path = new File(main.getPath()); System.out.println("Classpath? : " + (path.toString())); // LoadMods(); TheWorld = new World_DIPIT(sizex, sizey); TheWorld.AddSolidTag("W"); // TODO code application logic here for (int y = 0; y < sizey; y++) { for (int x = 0; x < sizex; x++) { TileBase aNewTile = new TileBase(x, y); aNewTile.SetRenderCharacter("+"); TheWorld.AddTile(aNewTile); } } postWorldGen_listeners.stream().forEach((hl) -> { //System.out.println(("hl(null) : " + (hl == null))); hl.ModifyWorldGen(TheWorld); }); ThePlayer = new PlayerBase(0, 0, TheWorld); GameWindow = new dipit_game.GameWindowJFrame(TheWorld, ThePlayer); GameWindow.setVisible(true); Iterator<String> ConsoleIterator; ConsoleIterator = ConsoleOuts.iterator(); String output = ""; while (ConsoleIterator.hasNext()) { output = output + "\n" + ConsoleIterator.next(); } GameWindow.ConsoleOut.setText(output); Debug_PrintWorldAsString(); } public static void Debug_PrintWorldAsString() { String print_line = ""; for (int y = 0; y < sizey; y++) { print_line += "\n"; for (int x = 0; x < sizey; x++) { if (ThePlayer.GetPositionX() == x && ThePlayer.GetPositionY() == y) { print_line += "[" + ThePlayer.GetRenderCharacter() + "]"; } else { print_line += "[" + TheWorld.GetTile(TheWorld.GetTileAtPosition(x, y)).GetRenderCharacter() + "]"; } } } System.out.println(print_line); } private static void LoadMods() { String referencedModlistString = "C:\\Users\\Arch\\Documents\\NetBeansProjects\\referenced" + "/modlist.txt"; String BaseModString = "C:\\Users\\Arch\\Documents\\NetBeansProjects\\referenced"; ConsoleOuts.add(referencedModlistString); List<String> ModsToLoad = new ArrayList<>(); try { FileReader MyReader = new FileReader(referencedModlistString); ModsToLoad.addAll(GetModsToLoad(MyReader)); } catch (FileNotFoundException ex) { Logger.getLogger(DIPIT_GAME_Main.class.getName()).log(Level.SEVERE, null, ex); ConsoleOuts.add(ex.getMessage()); } catch (IOException ex) { Logger.getLogger(DIPIT_GAME_Main.class.getName()).log(Level.SEVERE, null, ex); } //ConsoleOuts.addAll(MyDebugOut); JarClassLoader jcl = new JarClassLoader(); jcl.add("ExpandedGame/"); ProxyProviderFactory.setDefaultProxyProvider(new CglibProxyProvider()); //Create a factory of castable objects/proxies JclObjectFactory factory = JclObjectFactory.getInstance(true); //Create and cast object of loaded class dipit_game.DipitModBase mi = (dipit_game.DipitModBase) factory.create(jcl, "ExpandedGame.ExpandedMain"); //Object obj = factory.create(jcl, "ExpandedGame.ExpandedMain"); for (String str : ModsToLoad) { jcl.add(BaseModString + "\\" + str); ConsoleOuts.add(BaseModString + "\\" + str); //factory.create(jcl, BaseModString + "\\ModLibrary.jar"); ConsoleOuts.add(">Attempting to ClassLoad [" + str + "] \n Suceeded = " + (LoadMod(BaseModString + "\\" + str))); } } private static List<String> GetModsToLoad(FileReader MyReader) throws IOException { String ModPathBuild = ""; List<String> ModsList = new ArrayList<>(); char[] readout = new char[1024]; MyReader.read(readout); for (char c : readout) { //System.out.println("> " + java.lang.Character.toString(c)); // System.out.println("=* " + (c == '*') ); if (c == ';') { ConsoleOuts.add("Adding Build >" + ModPathBuild.trim()); ModsList.add(ModPathBuild.trim()); ModPathBuild = ""; } else { ModPathBuild = ModPathBuild + java.lang.Character.toString(c); } } return ModsList; } /** * Loads the Mod at Binary String point [BinaryModName]. Throws exceptions, * and continues to run the application if the mod is unable to be loaded * for whatever reason. * * @param BinaryModName the Binary String name of the, [ex. MyMod.ModClass] * . * @return [boolean] true if the mod was loaded successfully, false if it * failed for whatever reason. */ private static boolean LoadMod(String BinaryModName) { Class<?> ModClass = null; Method method = null; try { Class<?> ModClass_ = ClassLoader.getSystemClassLoader().loadClass(BinaryModName); ModClass = ModClass_; } catch (ClassNotFoundException ex) { Logger.getLogger(DIPIT_GAME_Main.class.getName()).log(Level.SEVERE, "Inable to find Mod @" + BinaryModName, ex); } if (ModClass != null) { //Get InitMod Method try { Method method_ = ModClass.getMethod("InitMod"); method = method_; } catch (NoSuchMethodException ex) { Logger.getLogger(DIPIT_GAME_Main.class.getName()).log(Level.CONFIG, "Mod @" + BinaryModName + " has not specified a [InitMod] Method!", ex); } catch (SecurityException ex) { Logger.getLogger(DIPIT_GAME_Main.class.getName()).log(Level.CONFIG, null, ex); } //Get Init Mod try { method.invoke(null, null); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { Logger.getLogger(DIPIT_GAME_Main.class.getName()).log(Level.SEVERE, null, ex); } } return (ModClass != null); } }
    Python
    UTF-8
    518
    4.5
    4
    [ "MIT" ]
    permissive
    '''Crie um programa onde o usuário possa digitar sete valores numéricos e cadastre-os em uma lista única que mantenha separados os valores pares e ímpares. No final, mostre os valores pares e ímpares em ordem crescente''' valores = [[], []] n = 0 for i in range(1, 8): n = int(input(f'Digite o valor {i}: ')) if n % 2 == 0: valores[0].append(n) else: valores[1].append(n) valores[0].sort() valores[1].sort() print(f'Valores pares {valores[0]}') print(f'Valores impares {valores[1]}')
    Java
    UTF-8
    5,135
    2.21875
    2
    []
    no_license
    package milu.gui.ctrl.schema; import java.util.ResourceBundle; import java.sql.SQLException; import javafx.scene.control.SplitPane; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.scene.layout.AnchorPane; import javafx.scene.Node; import javafx.application.Platform; import javafx.event.Event; import javafx.geometry.Orientation; import milu.db.MyDBAbstract; import milu.gui.view.DBView; import milu.main.MainController; import milu.tool.MyGUITool; import milu.gui.ctrl.common.inf.ChangeLangInterface; import milu.gui.ctrl.common.inf.FocusInterface; import milu.gui.ctrl.schema.handle.SelectedItemHandlerAbstract; import milu.gui.ctrl.schema.handle.SelectedItemHandlerFactory; public class DBSchemaTab extends Tab implements FocusInterface, GetDataInterface, ChangeLangInterface { private DBView dbView = null; // upper pane on SplitPane private AnchorPane upperPane = new AnchorPane(); private SchemaTreeView schemaTreeView = null; private TabPane tabPane = null; public DBSchemaTab( DBView dbView ) { super(); this.dbView = dbView; this.schemaTreeView = new SchemaTreeView( this.dbView, this ); this.tabPane = new TabPane(); // no tab text & dragging doesn't work well. // ----------------------------------------------------- // Enable tag dragging //DraggingTabPaneSupport dragSupport = new DraggingTabPaneSupport(); //dragSupport.addSupport( this.tabPane ); this.upperPane.getChildren().add( this.schemaTreeView ); this.schemaTreeView.init(); AnchorPane.setTopAnchor( this.schemaTreeView, 0.0 ); AnchorPane.setBottomAnchor( this.schemaTreeView, 0.0 ); AnchorPane.setLeftAnchor( this.schemaTreeView, 0.0 ); AnchorPane.setRightAnchor( this.schemaTreeView, 0.0 ); SplitPane splitPane = new SplitPane(); splitPane.setOrientation(Orientation.VERTICAL); splitPane.getItems().addAll( this.upperPane, this.tabPane ); splitPane.setDividerPositions( 0.5f, 0.5f ); BorderPane brdPane = new BorderPane(); brdPane.setCenter( splitPane ); this.setContent( brdPane ); // set icon on Tab this.setGraphic( MyGUITool.createImageView( 16, 16, this.dbView.getMainController().getImage("file:resources/images/schema.png") ) ); this.setAction(); this.changeLang(); this.getDataNoRefresh( null ); } private void setAction() { this.selectedProperty().addListener ( (obs,oldval,newVal)-> { if ( newVal == false ) { return; } this.setFocus(); } ); } /** * set Focus on TreeView */ @Override public void setFocus() { // https://sites.google.com/site/63rabbits3/javafx2/jfx2coding/dialogbox // https://stackoverflow.com/questions/20049452/javafx-focusing-textfield-programmatically // call after "new Scene" Platform.runLater( ()->{ this.schemaTreeView.requestFocus(); System.out.println( "schemaTreeView focused."); } ); } // GetDataInterface @Override public void getDataNoRefresh( Event event ) { this.getSchemaData( event, SelectedItemHandlerAbstract.REFRESH_TYPE.NO_REFRESH ); } // GetDataInterface @Override public void getDataWithRefresh( Event event ) { this.getSchemaData( event, SelectedItemHandlerAbstract.REFRESH_TYPE.WITH_REFRESH ); } private void getSchemaData( Event event, SelectedItemHandlerAbstract.REFRESH_TYPE refreshType ) { MyDBAbstract myDBAbs = this.dbView.getMyDBAbstract(); try { SelectedItemHandlerAbstract handleAbs = SelectedItemHandlerFactory.getInstance ( this.schemaTreeView, this.tabPane, this.dbView, myDBAbs, refreshType ); if ( handleAbs != null ) { handleAbs.exec(); } } catch ( UnsupportedOperationException uoEx ) { MyGUITool.showException( this.dbView.getMainController(), "conf.lang.gui.common.MyAlert", "TITLE_UNSUPPORT_ERROR", uoEx ); } catch ( SQLException sqlEx ) { MyGUITool.showException( this.dbView.getMainController(), "conf.lang.gui.common.MyAlert", "TITLE_EXEC_QUERY_ERROR", sqlEx ); } catch ( Exception ex ) { MyGUITool.showException( this.dbView.getMainController(), "conf.lang.gui.common.MyAlert", "TITLE_MISC_ERROR", ex ); } } /************************************************** * Override from ChangeLangInterface ************************************************** */ @Override public void changeLang() { MainController mainCtrl = this.dbView.getMainController(); ResourceBundle langRB = mainCtrl.getLangResource("conf.lang.gui.ctrl.schema.DBSchemaTab"); // Tab Title Node tabGraphic = this.getGraphic(); if ( tabGraphic instanceof Label ) { ((Label)tabGraphic).setText( langRB.getString("TITLE_TAB") ); } else { this.setText( langRB.getString("TITLE_TAB") ); } this.schemaTreeView.changeLang(); this.schemaTreeView.refresh(); } }
    TypeScript
    UTF-8
    3,299
    2.953125
    3
    [ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
    permissive
    import * as cormo from 'cormo'; export function Model(options: { connection?: cormo.Connection; name?: string; description?: string } = {}) { const c = cormo.Model({ connection: options.connection, name: options.name, description: options.description }); return (ctor: typeof cormo.BaseModel) => { c(ctor); }; } interface ColumnBasicOptions { required?: boolean; graphql_required?: boolean; unique?: boolean; name?: string; description?: string; default_value?: string | number | (() => string | number); } export function Column( options: | ({ enum: any } & ColumnBasicOptions) | ({ type: cormo.types.ColumnType | cormo.types.ColumnType[] } & ColumnBasicOptions), ): PropertyDecorator; export function Column( options: { enum?: any; type?: cormo.types.ColumnType | cormo.types.ColumnType[]; } & ColumnBasicOptions, ): PropertyDecorator { let cormo_type: cormo.types.ColumnType | cormo.types.ColumnType[]; if (options.enum) { cormo_type = cormo.types.Integer; } else { cormo_type = options.type!; } const c = cormo.Column({ default_value: options.default_value, name: options.name, required: options.required, type: cormo_type, description: options.description, unique: options.unique, }); return (target: object, propertyKey: string | symbol) => { c(target, propertyKey); }; } interface ObjectColumnOptions { type: any; required?: boolean; description?: string; } export function ObjectColumn(options: ObjectColumnOptions): PropertyDecorator { const c = cormo.ObjectColumn(options.type); return (target: object, propertyKey: string | symbol) => { c(target, propertyKey); }; } interface HasManyBasicOptions { type?: string; foreign_key?: string; integrity?: 'ignore' | 'nullify' | 'restrict' | 'delete'; description?: string; } export function HasMany(options: HasManyBasicOptions) { const c_options = { foreign_key: options.foreign_key, integrity: options.integrity, type: options.type, }; const c = cormo.HasMany(c_options); return (target: cormo.BaseModel, propertyKey: string) => { c(target, propertyKey); }; } interface HasOneBasicOptions { type?: string; foreign_key?: string; integrity?: 'ignore' | 'nullify' | 'restrict' | 'delete'; description?: string; } export function HasOne(options: HasOneBasicOptions) { const c_options = { foreign_key: options.foreign_key, integrity: options.integrity, type: options.type, }; const c = cormo.HasOne(c_options); return (target: cormo.BaseModel, propertyKey: string) => { c(target, propertyKey); }; } interface BelongsToBasicOptions { type?: string; required?: boolean; foreign_key?: string; description?: string; } export function BelongsTo(options: BelongsToBasicOptions) { const c_options = { foreign_key: options.foreign_key, required: options.required, type: options.type, }; const c = cormo.BelongsTo(c_options); return (target: cormo.BaseModel, propertyKey: string) => { c(target, propertyKey); }; } export function Index(columns: { [column: string]: 1 | -1 }, options?: { name?: string; unique?: boolean }) { const c = cormo.Index(columns, options); return (ctor: typeof cormo.BaseModel) => { c(ctor); }; }
    Shell
    UTF-8
    1,078
    3.1875
    3
    []
    no_license
    #!/bin/bash open ~/Databases/Hackage.sparsebundle sleep 5 if ! quickping hackage.haskell.org; then exit 1 fi simple-mirror --from="http://hackage.haskell.org" --to="/Volumes/Hackage" index=/Volumes/Hackage/00-index.tar.gz if [[ -f $index ]]; then echo Installing package database from local mirror... size=$(gzip -q -l $index | awk '{print $2}') else size=0 fi echo Downloading package database from hackage.haskell.org... mkdir -p ~/.cabal/packages/hackage.haskell.org curl -s -o - http://hackage.haskell.org/packages/index.tar.gz \ | gzip -dc | pv \ > ~/.cabal/packages/hackage.haskell.org/00-index.tar if [[ -f $index ]]; then echo Installing package database from local mirror... mkdir -p ~/.cabal/packages/mirror gzip -dc $index | pv -s $size \ > ~/.cabal/packages/mirror/00-index.tar fi # sleep 5 # # cd /Volumes/Hackage # # export PATH=$PATH:/usr/local/tools/hackage-server/cabal-dev/bin # # hackage-server run --port=9010 & # # sleep 300 # hackage-mirror -v --continuous mirror.cfg
    PHP
    UTF-8
    786
    2.53125
    3
    []
    no_license
    <?php /* Service class */ namespace AppBundle\Util; use Doctrine\ORM\Mapping as ORM; class Utility{ const DATE_FORMAT_DATE = 'yyyy-MM-dd'; const DATE_FORMAT_DATETIME = 'yyyy-MM-dd HH:mm:ss'; const FIELD_STYLE_SMALL = 'width:250px'; const FIELD_STYLE_MEDIUM = 'width:500px'; public function filterByName($queryBuilder, $alias, $field, $value){ if(!$value['value']){ return; } $queryBuilder->andWhere($alias . '.name' . ' = ' . ':name' )->setParameter('name' , $value['value']->getName()); return true; } public function filterByUserId($queryBuilder, $alias, $field, $value){ if(!$value['value']){ return; } $queryBuilder->andWhere($alias . '.user_id' . ' = ' . ':user_id' )->setParameter('user_id' , $value['value']->getId()); return true; } }
    Python
    UTF-8
    1,445
    3.203125
    3
    []
    no_license
    #!/usr/bin/env python # -*- coding: utf-8 -*- """ Given a directory path, search all files in the path for a given text string within the 'word/document.xml' section of a MSWord .dotm file. """ __author__ = "mprodhan/yabamov/madarp" import os import argparse from zipfile import ZipFile def create_parser(): parser = argparse.ArgumentParser(description="search for a particular substring within dotm files") parser.add_argument("--dir", default=".", help="specify the directory to search into ") parser.add_argument('text', help="specify the text that is being searched for ") return parser def scan_directory(dir_name, search_text): for root, _, files in os.walk(dir_name): for file in files: if file.endswith(".dotm"): dot_m = ZipFile(os.path.join(root, file)) content = dot_m.read('word/document.xml').decode('utf-8') if search_file(content, search_text): print('Match found in file./dotm_file/' + file) print(search_text) def search_file(text, search_text): for line in text.split('\n'): index = line.find(search_text) if index >= 0: print(line[index-40:index+40]) return True return False def main(): parser = create_parser() args = parser.parse_args() print(args) scan_directory(args.dir, args.text) if __name__ == '__main__': main()
    Markdown
    UTF-8
    2,317
    2.828125
    3
    []
    no_license
    # [Gulp-imagemin](https://www.npmjs.com/package/gulp-imagemin) + [Imagemin-pngquant](https://www.npmjs.com/package/imagemin-pngquant) plugins ## Описание Плагины для оптимизации изображений ## Install `npm install --save-dev gulp-imagemin` `npm install --save-dev imagemin-pngquant` ## Example ***gulp-imagemin*** ```js const gulp = require('gulp'); const imagemin = require('gulp-imagemin'); gulp.task('default', () => gulp.src('src/images/*') .pipe(imagemin()) .pipe(gulp.dest('dist/images')) ); ``` ***imgmin-pngquant*** ```js const imagemin = require('imagemin'); const imageminPngquant = require('imagemin-pngquant'); imagemin(['images/*.png'], 'build/images', {use: [imageminPngquant()]}).then(() => { console.log('Images optimized'); }); ``` --- ## Общий пример использования + plugin gulp-cache Без использования gulp-cache ```js var imagemin = require('gulp-imagemin'), // Подключаем библиотеку для работы с изображениями pngquant = require('imagemin-pngquant'); // Подключаем библиотеку для работы с png gulp.task('img', function() { return gulp.src('app/img/**/*') // Берем все изображения из app .pipe(imagemin({ // Сжимаем их с наилучшими настройками interlaced: true, progressive: true, svgoPlugins: [{removeViewBox: false}], use: [pngquant()] })) .pipe(gulp.dest('dist/img')); // Выгружаем на продакшен }); ``` Вместе с gulp-cache : ```js var cache = require('gulp-cache'); // Подключаем библиотеку кеширования gulp.task('img', function() { return gulp.src('app/img/**/*') // Берем все изображения из app .pipe(cache(imagemin({ // Сжимаем их с наилучшими настройками с учетом кеширования interlaced: true, progressive: true, svgoPlugins: [{removeViewBox: false}], use: [pngquant()] }))) .pipe(gulp.dest('dist/img')); // Выгружаем на продакшен }); ```
    Python
    UTF-8
    4,600
    2.796875
    3
    [ "BSD-3-Clause" ]
    permissive
    """Auxiliary functions.""" try: import cPickle as pickle except ImportError: import pickle import re import os from SPARQLWrapper import SPARQLWrapper, JSON YAGO_ENPOINT_URL = "https://linkeddata1.calcul.u-psud.fr/sparql" RESOURCE_PREFIX = 'http://yago-knowledge.org/resource/' def safe_mkdir(dir_name): """Checks if a directory exists, and if it doesn't, creates one.""" try: os.stat(dir_name) except OSError: os.mkdir(dir_name) def pickle_to_file(object_, filename): """Abstraction to pickle object with the same protocol always.""" with open(filename, 'wb') as file_: pickle.dump(object_, file_, pickle.HIGHEST_PROTOCOL) def pickle_from_file(filename): """Abstraction to read pickle file with the same protocol always.""" with open(filename, 'rb') as file_: return pickle.load(file_) def get_input_files(input_dirpath, pattern): """Returns the names of the files in input_dirpath that matches pattern.""" all_files = os.listdir(input_dirpath) for filename in all_files: if re.match(pattern, filename) and os.path.isfile(os.path.join( input_dirpath, filename)): yield os.path.join(input_dirpath, filename) # TODO(mili): Is is better a pandas DataFrame def query_sparql(query, endpoint): """Run a query again an SPARQL endpoint. Returns: A double list with only the values of each requested variable in the query. The first row in the result contains the name of the variables. """ sparql = SPARQLWrapper(endpoint) sparql.setReturnFormat(JSON) sparql.setQuery(query) response = sparql.query().convert() bindings = response['results']['bindings'] variables = response['head']['vars'] result = [variables] for binding in bindings: row = [] for variable in variables: row.append(binding[variable]['value']) result.append(row) return result def download_category(category_name, limit): """Downloads a single category and stores result in directory_name.""" query = """SELECT DISTINCT ?entity ?wikiPage WHERE { ?entity rdf:type <http://yago-knowledge.org/resource/%s> . ?entity <http://yago-knowledge.org/resource/hasWikipediaUrl> ?wikiPage } LIMIT %s""" % (category_name, limit) return query_sparql(query, YAGO_ENPOINT_URL) def get_categories_from_file(category_filename): """Read categories and ofsets""" with open(category_filename, 'r') as input_file: lines = input_file.read().split('\n') return lines def query_subclasses(category_name, populated=True): query = """SELECT DISTINCT ?subCategory WHERE { ?subCategory rdfs:subClassOf <%s%s> . """ % (RESOURCE_PREFIX, category_name) if populated: query += """ ?entity rdf:type ?subCategory . }""" else: query += '}' return query_sparql(query, YAGO_ENPOINT_URL)[1:] def add_subcategories(category_name, graph, ancestors=[]): """Updates the children categories and level of category name. """ def add_ancestor(category_name): graph.add_edge(ancestors[-1], category_name, path_len=len(ancestors)) response = query_subclasses(category_name) for result in response: child_category = result[0].replace(RESOURCE_PREFIX, '') if 'wikicat' in child_category: continue add_subcategories(child_category, graph, ancestors=ancestors + [category_name]) if category_name not in graph: if len(ancestors): add_ancestor(category_name) else: graph.add_node(category_name) return # We have seen the node before if len(graph.predecessors(category_name)) == 0: # There is no ancestor yet. if len(ancestors): # it's not the first recursive call add_ancestor(category_name) else: # There is a previous ancestor added = False for prev_ancestor in graph.predecessors(category_name): if prev_ancestor in ancestors: added = True if len(ancestors) > graph.get_edge_data( prev_ancestor, category_name)['path_len']: # The current ancestor has a longer path graph.remove_edge(prev_ancestor, category_name) add_ancestor(category_name) # The new ancestor doesn't overlap with any previous ancestor's path. if not added and len(ancestors): add_ancestor(category_name)
    C++
    UTF-8
    2,699
    2.65625
    3
    []
    no_license
    /* ID: j316chuck PROG: milk3 LANG: C++ */ #include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <string> #include <cctype> #include <stack> #include <queue> #include <list> #include <vector> #include <map> #include <sstream> #include <cmath> #include <bitset> #include <utility> #include <set> #include <numeric> #include <ctime> #include <climits> #include <cstdlib> const double Pi=acos(-1.0); typedef long long LL; #define Set(a, s) memset(a, s, sizeof (a)) #define Rd(r) freopen(r, "r", stdin) #define Wt(w) freopen(w, "w", stdout) using namespace std; int A, B, C; int amountA,amountB, amountC; bool possible[21]; int counter =0; class three { public: int first,second, third; }; three paths[10000]; bool checkcycle() { for(int i =0; i < counter; i++) { if(paths[i].first==amountA&&paths[i].second==amountB&&paths[i].third==amountC) return false; } return true; } void Recursion() { if(amountA==0) possible[amountC]==true; return; paths[counter].first=amountA; paths[counter].second=amountB; paths[counter].third=amountC; if(checkcycle()==false) return; if(B<amountA+amountB){ amountB=B; amountA=amountA+amountB-B; Recursion(); }if(B>=amountA+amountB){ amountB=amountA+amountB; amountA=0; Recursion(); }if(C<amountC+amountA){ amountC=C; amountA=amountA+amountC-C; Recursion(); }if(C>=amountC+amountA){ amountC=amountC+amountA; amountA=0; Recursion(); }if(A<amountB+amountA){ amountA=A; amountB=amountB+amountA-A; Recursion(); }if(A>=amountA+amountB){ amountA=amountA+amountB; amountB=0; Recursion(); }if(C<amountB+amountC){ amountC=C; amountB=amountB+amountC-C; Recursion(); }if(C>=amountB+amountC){ amountC=amountB+amountC; amountB=0; Recursion(); }if(A<amountA+amountC){ amountA=A; amountC=amountC+amountA-A; Recursion(); }if(A>=amountA+amountC){ amountA=amountA+amountC; amountC=0; Recursion(); }if(B<amountB+amountC){ amountC=C; amountB=amountB+amountC-C; Recursion(); }if(B>=amountB+amountC){ amountB=amountB+amountC; amountC=0; Recursion(); } counter++; } int main() { Rd("milk3.in"); //Wt("milk3.out"); cin>>A>>B>>C; amountA=0; amountB=0; amountC=C; Recursion(); for(int i = 0; i < C; i++) { if(possible[i]==true) { cout<<i<<endl; } } }
    Java
    UTF-8
    1,183
    2.28125
    2
    []
    no_license
    package pl.skycash.zadanie_rekrutacyjne.crud_example.controller; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; import pl.skycash.zadanie_rekrutacyjne.crud_example.controller.dto.BookConvertDTO; import pl.skycash.zadanie_rekrutacyjne.crud_example.controller.dto.BookDTO; import pl.skycash.zadanie_rekrutacyjne.crud_example.model.Book; import pl.skycash.zadanie_rekrutacyjne.crud_example.service.BookServiceImpl; import java.util.List; import java.util.Optional; @RestController @RequiredArgsConstructor public class BookController { private final BookServiceImpl bookService; @GetMapping("/books") public List<BookDTO> selectAllBooks(){ return BookConvertDTO.convertToDTOs(bookService.selectAllBooks()); } @GetMapping("/books/{id}") public Book selectBookById(@PathVariable long id){ return bookService.selectBookById(id); } @PostMapping("/books/add") public Book addBook(@RequestBody Book book){ return bookService.addBook(book); } @DeleteMapping("/books/delete/{id}") public void deleteBook(@PathVariable long id){ bookService.deleteBook(id); } }
    C++
    UTF-8
    1,879
    2.625
    3
    []
    no_license
    #include "stdafx.h" #include "CopyFileToDir.h" #include <fstream> #include <string> #include <iostream> #include <windows.h> //??????????????(unicode -- > ascll) #define WCHAR_TO_CHAR(lpW_Char,lpChar) WideCharToMultiByte(CP_ACP,NULL,lpW_Char,-1,lpChar,_countof(lpChar),NULL,FALSE); //??????????????(unicode -- > ascll) #define CHAR_TO_WCHAR(lpChar,lpW_Char) MultiByteToWideChar(CP_ACP,NULL,lpChar,-1,lpW_Char,_countof(lpW_Char)); using namespace std; CopyFileToDir::CopyFileToDir() { } bool CopyFileToDir::ReadTXTFile_GetPath(char * PathText,char *Path) { //????? ifstream in(PathText); string filename; string line; //??????????? int num = 0; if (in) // ?и???? { while (getline(in, line)) // line?в???????е???з? { //???????????vector?? vecTatgetPath.push_back(line); num++; } } else // ??и???? { cout << "no such file" << endl; } cout << "???????????" << num << endl; WCHAR W_Dir[MAX_PATH]; WCHAR W_FilePath[MAX_PATH]; WCHAR W_FileName[MAX_PATH]; for (size_t i = 0; i < vecTatgetPath.size(); i++) { CHAR_TO_WCHAR(Path, W_Dir); CHAR_TO_WCHAR(vecTatgetPath[i].c_str(), W_FilePath); //?????? size_t found = vecTatgetPath[i].find_last_of("/\\"); CHAR_TO_WCHAR(vecTatgetPath[i].substr(found).c_str(), W_FileName); lstrcat(W_Dir,W_FileName); if (!CopyFile(W_FilePath, W_Dir, TRUE)) { //LastError == 0x50?????????? if (GetLastError() == 0x50) { printf("???%ls??????????????y/n??", W_Dir); if ('y' == getchar()) { //?????????????????????? if (!CopyFile(W_FilePath, W_Dir, FALSE)) { printf("???????????%d\n", GetLastError()); } else { printf("????????\n"); } } else { return 0; } } } else { printf("%ls ????????\n", W_FileName); } } return false; } CopyFileToDir::~CopyFileToDir() { }
    PHP
    UTF-8
    1,923
    2.671875
    3
    []
    no_license
    <?php namespace App\Controllers; use \Core\View; use \App\Models\User; use \App\Flash; /** * Signup controller * * PHP version 7.2 */ class Signup extends \Core\Controller { /** * Show the signup page * * @return void */ public function newAction() { View::renderTemplate('Signup/new.html'); } /** * Sign up a new user * * @return void */ public function createAction() { $user = new User($_POST); $everything_OK = true; $e_rules = ""; $e_bot = ""; $rules = isset($_POST['rules']); if (!$rules){ $e_rules = "Potwierdź akceptację regulaminu!"; $everything_OK = false; } //checking reCAPTCHA $secret = '6LfD_7wZAAAAAPmDQvgE9QJjiwT__HkfmsE88in1'; $check = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']); $answer = json_decode($check); if($answer->success==false){ //$everything_OK = false; $e_bot = "Potwierdź, że nie jesteś botem!"; } if (($everything_OK == true) && $user->save()) { $user_temporary = $user->authenticate($user->email, $user->password); $user->addDefaultCategoriesToDB($user_temporary->id); $this->redirect('/signup/success'); } else { Flash::addMessage('Rejestracja nie powiodła się.', Flash::WARNING); View::renderTemplate('Signup/new.html', [ 'user' => $user, 'e_rules' => $e_rules, 'e_bot' => $e_bot, 'rules' => $rules ]); } } /** * Show the signup success page * * @return void */ public function successAction() { View::renderTemplate('Signup/success.html'); } }
    JavaScript
    UTF-8
    856
    2.9375
    3
    []
    no_license
    function piller(){ this.pos = {} this.height = floor(random(100, 250)) this.width = 60 this.pos.x = 600 this.pos.y = 400-this.height this.bottom = this.pos.y this.space = 150 this.top = this.pos.y - this.space this.speed = 6 this.pillerbottomImage = pillerbottomImage this.pillertopImage = pillertopImage this.update = function(){ this.pos.x -= this.speed } this.draw = function(){ for(i = this.pos.y; i < this.pos.y + this.height;i+=3){ image(pillerbottomImage,this.pos.x, i, this.width); } image(pillertopImage,this.pos.x, this.pos.y, this.width); for(i = 0; i+20 < this.top;i+=20){ image(pillerbottomImage,this.pos.x, i, this.width); } image(pillertopImage,this.pos.x,this.top - 20, this.width); } }
    SQL
    UTF-8
    341
    2.578125
    3
    []
    no_license
    CREATE TABLE IF NOT EXISTS Items (id INTEGER PRIMARY KEY AUTOINCREMENT, name CHAR); CREATE TABLE IF NOT EXISTS Purchase (id INTEGER PRIMARY KEY AUTOINCREMENT, date CHAR, invoice CHAR, item CHAR, quantity INTEGER); CREATE TABLE IF NOT EXISTS Sale (id INTEGER PRIMARY KEY AUTOINCREMENT, date CHAR, invoice CHAR, item CHAR, quantity INTEGER);
    Ruby
    UTF-8
    189
    3.625
    4
    []
    no_license
    def d n sum = 0 (1..n/2+1).each {|x| sum += x if n%x == 0 } sum end puts d 284 s = 0 (1..10000).each {|x| y = d(x) s += x if x!=y && d(d(x))==x } puts s
    Markdown
    UTF-8
    4,082
    3.828125
    4
    []
    no_license
    ```python # random variables (no need to import random library) # Solutions with variables converted to string # Make sure you name the solution with part id at the end. e.g. 'solution1' will be solution for part 1. solution1 = "4^2" solution2 = "C(52-5,2) - C(52-5-4,2)" solution3 = "C(52-5,2)" solution4 = "(C(52-5,2) - C(52-5-4,2) + 4^2) / C(52-5,2)" # Group all solutions into a list solutions = [solution1, solution2, solution3, solution4] ``` In Texas Hold'Em, a standard 52-card deck is used. Each player is dealt two cards from the deck face down so that only the player that got the two cards can see them. After checking his two cards, a player places a bet. The dealer then puts 5 cards from the deck face up on the table, this is called the "board" or the "communal cards" because all players can see and use them. The board is layed down in 3 steps: first, the dealer puts 3 cards down (that is called "the flop") followed by two single cards, the first is called "the turn" and the second is called "the river". After the flop, the turn and the river each player can update their bet. The winner of the game is the person that can form the strongest 5-card hand from the 2 cards in their hand and any 3 of the 5 cards in the board. In previous homework you calculated the probability of getting each 5-card hand. Here we are interested in something a bit more complex: what is the probability of a particular hand given the cards that are currently available to the player. The outcome space in this kind of problem is the set of 7 cards the user has at his disposal after all 5 board cards have been dealt. The size of this space is \\\(|\\Omega| = C(52,7)\\\) Suppose that \\\(A, B\\\) are events, i.e. subsets of \\\(\\Omega\\\). We will want to calculate conditional probabilities of the type \\\(P(A|B)\\\). Given that the probability of each set of seven cards is equal to \\\(1/C(52,7)\\\) we get that the conditional probability can be expressed as: \\\[P(A|B) = \\frac{P(A \\cap B)}{P(B)} = \\frac{\\frac{|A \\cap B|}{|\\Omega|}}{\\frac{|B|}{|\\Omega|}} = \\frac{|A \\cap B|}{|B|} \\\] Therefore the calculation of conditional probability (for finite sample spaces with uniform distribution) boils down to calculating the ratio between the sizes of two sets. * Suppose you have been dealt "4\\\(\\heartsuit\\\), 5\\\(\\heartsuit\\\)". * What is the conditional probability that you will get a straight given that you have been dealt these two cards, and that the flop is "2\\\(\\clubsuit\\\), 6\\\(\\spadesuit\\\), K\\\(\\diamondsuit\\\)"? - Define \\\(B\\\) as the set {7-card hands that contain these 5 cards already revealed}. - Define \\\(A\\\) as the set {7-card hands that contain a straight}. The question is asking for \\\(P(A|B)\\\). According to the formula above we need to find \\\(|A\\cap B|\\\) and \\\(|B|\\\). - In this case \\\(A \\cap B\\\) is the set {7-card hands that contain the 5 revealed cards AND contain a straight}. To get a straight, the remaining two cards (turn and river) must either be {7,8} or contain 3. We hence define two subsets within \\\(A \\cap B\\\): - \\\(S_1\\\): {7-card hands that are in \\\(A \\cap B\\\) AND the remaining two cards are 7 and 8, regardless of order}. \\\(|S_1|=\\\) [_] - \\\(S_2\\\): {7-card hands that are in \\\(A \\cap B\\\) AND its turn and river contain 3}. \\\(|S_2| = \\\) [_] Because there is no overlap in these two subsets \\\(S_1 \\cap S_2 = \\emptyset\\\) and these two subsets cover all possible valid hands \\\(A \\cap B = S_1 \\cup S_2 \\\), by definition \\\(S_1\\\) and \\\(S_2\\\) form a _partition_ of \\\(A \\cap B\\\), and we have \\\(|A \\cap B| = |S_1| + |S_2|\\\). - Computing \\\(|B|\\\) should be easy. 5 cards in the hand are already fixed, so we can choose any card as our turn and river from the rest 47 cards. \\\(|B| = \\\) [_] - The conditional probability \\\(P(A|B) = \\frac{P(A \\cap B)}{P(B)} = \\frac{|A\\cap B|}{|B|} = \\frac{|S_1|+|S_2|}{|B|}\\\) is [_] ---
    C++
    UTF-8
    1,099
    2.84375
    3
    []
    no_license
    /* * File: Alumno.h * Author: alulab14 * * Created on 6 de noviembre de 2015, 08:03 AM */ /* * Nombre: Diego Alonso Guardia Ayala * Codigo: 20125849 */ #ifndef ALUMNO_H #define ALUMNO_H #include <cstdlib> #include <cstring> class Alumno { public: Alumno(); void SetCreditos(double creditos); double GetCreditos() const; void SetPromedio(double promedio); double GetPromedio() const; void SetSemFin(int semFin); int GetSemFin() const; void SetAnFin(int anFin); int GetAnFin() const; void SetSemIn(int semIn); int GetSemIn() const; void SetAnIn(int anIn); int GetAnIn() const; void SetNombre(char *); void GetNombre(char *) const; void SetCodigo(int codigo); int GetCodigo() const; void SetEspecialidad(char *); void GetEspecialidad(char *) const; private: int codigo; char nombre[50]; char especialidad[50]; int anIn; //Año de inicio int semIn; //Semestre que inicio int anFin; //Año de egresó int semFin; //Semestre que egresó double promedio; double creditos; }; #endif /* ALUMNO_H */
    Java
    UHC
    1,125
    3.28125
    3
    []
    no_license
    import java.util.Scanner; public class BFmatch { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("ؽƮ : "); String s1 = sc.next(); System.out.print(" : "); String s2 = sc.next(); int idx = bfMatch(s1,s2); if(idx==-1) System.out.println("ؽƮ ϴ."); else { int len=0; for(int i=0; i<idx; i++) len+=s1.substring(i, i+1).getBytes().length; //substring(ġ1,ġ2) : ش ڿ ġ1~ġ2 ؽ ߶ ֱ len+=s2.length(); System.out.println((idx+1)+"° ں ġ"); System.out.println("ؽƮ : "+s1); System.out.printf(String.format(" : %%%ds\n", len), s2); } } static int bfMatch(String txt, String pat) { int pt = 0;//txtĿ int pp = 0;//paternĿ while(pt != txt.length() && pp != pat.length()) { if(txt.charAt(pt)==pat.charAt(pp)) { pt++; pp++; }else { pt = pt-pp+1; pp = 0; } } if(pp==pat.length())//˻ return pt-pp; return -1; } }
    PHP
    UTF-8
    1,233
    2.890625
    3
    []
    no_license
    <?php /** * Created by PhpStorm. * User: salerat * Date: 4/9/14 * Time: 3:20 PM */ namespace kaz; require 'Kaz.php'; if(!empty($_POST)) { $kaz = new Kaz($_POST['word']); $resultArray = $kaz->getFlectiveClass(); } $word = ''; if(!empty($_POST['word'])) { $word=$_POST['word']; } echo '<!doctype html> <html lang="ru"> <head> <meta charset="utf-8"> <title>Генерация словоформ</title> <link rel="stylesheet" href="css/styles.css"> <!--[if lt IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <form method="POST"> Введите слово в именительном падеже (пример: адам) <input type="text" name="word" value="'.$word.'"><br> <input type="submit" value="Сгенерировать"> </form> '; if(!empty($resultArray)) { echo '<table border="1"> <tr> <td><b>Конфигурация слово образования</b></td> <td><b>Форма слова</b></td> </tr>'; foreach($resultArray as $res) { echo ' <tr> <td>'.$res['type'].'</td> <td>'.$res['word'].'</td> </tr>'; } echo '</table>'; } echo ' </body> </html> ';
    Java
    UTF-8
    1,051
    3.71875
    4
    []
    no_license
    package com.test17; import java.util.Comparator; import java.util.Scanner; import java.util.TreeSet; import com.student.Student; public class Demo_StudentMassage { /* * 键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按学生总分进行排名 * 1.创建键盘录入对象 * 2.依次录入5名学生信息学生信息,存储在TreeSet集合中 */ public static void main(String[] args) { Scanner sc=new Scanner(System.in); TreeSet<Student> ts=new TreeSet<Student>(new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { //按总分从高到低进行比较 int num=o2.getSum()-o1.getSum(); return num==0 ? 1 : num; } }); while(ts.size()<5) { String str=sc.nextLine(); String[] sarr=str.split(","); //使用“,”分割 int chgrate=Integer.parseInt(sarr[1]); int magrate=Integer.parseInt(sarr[2]); int engrate=Integer.parseInt(sarr[3]); ts.add(new Student(sarr[0],chgrate,magrate,engrate)); } System.out.println(ts); } }
    C
    UTF-8
    452
    3.9375
    4
    []
    no_license
    //Program to check whether all digits in a number in ascending order or not #include<stdio.h> #include<math.h> int main() { int j,n,d,h,flag=1; printf("Enter a number:"); scanf("%d",&n); d=floor(log10(n)); while(d>0) { j=n/(int)(pow(10,d)); n=n%(int)(pow(10,d)); h=n/(int)(pow(10,d-1)); if(j>h) { flag=0; break; } d--; } if(flag) printf("Ascending"); else printf("not ascending"); return 0; }
    TypeScript
    UTF-8
    1,364
    2.5625
    3
    []
    no_license
    import { Injectable } from '@angular/core'; @Injectable() export class FavoritoService { name = "_f"; private favoritos = []; constructor() { } listar(){ if(!this.favoritos || this.favoritos.length == 0){ let lista = localStorage.getItem(this.name); this.favoritos = lista?JSON.parse(lista):[]; } return this.favoritos; } removeFavorito(book){ if(this.isFavorito(book.id)){ if(this.favoritos){ var index = this.favoritos.findIndex(element => element.id == book.id ); if(index > -1){ this.favoritos.splice(index, 1); } let listaJSON = this.favoritos? JSON.stringify(this.favoritos): null; localStorage[this.name] = listaJSON; } } } setFavorito(book){ if(!this.isFavorito(book.id)){ this.favoritos.push(book); localStorage[this.name] = JSON.stringify(this.favoritos); } } isFavorito(id :String){ let books = this.getFavorito(id); return books != null && books.length > 0 ? true : false; } getFavorito(id :String){ return this.listar().filter(element => { return element.id == id; }); } }
    C++
    UTF-8
    931
    2.921875
    3
    []
    no_license
    #include <iostream> #include <algorithm> #include <vector> #include <string> using namespace std; bool compare(const int &a, const int &b) { return a > b; } int main() { int T, m, n, i, j, k, cnt, index; string temp, str; vector<string> strarr; vector<int> answerarr; cin >> T; for (i = 1; i <= T; i++) { cin >> m >> n; cin >> str; cnt = m / 4; for(j = 0; j < cnt; j++) { str = str.substr(m - 1, 1) + str.substr(0, m - 1); for (k = 0; k < 4; k++) strarr.push_back(str.substr(k * cnt, cnt)); } for (j = 0; j < strarr.size(); j++) answerarr.push_back(strtol(strarr[j].c_str(), NULL, 16)); sort(answerarr.begin(), answerarr.end(), compare); answerarr.erase(unique(answerarr.begin(), answerarr.end()), answerarr.end()); cout << "#" << i << " " << answerarr[n - 1] << endl; strarr.erase(strarr.begin(), strarr.end()); answerarr.erase(answerarr.begin(), answerarr.end()); } return 0; }
    Java
    UTF-8
    695
    2.5625
    3
    []
    no_license
    package schedule; import javax.servlet.ServletContextListener; import javax.servlet.ServletContextEvent; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class MyListener implements ServletContextListener { private ScheduledExecutorService scheduler; @Override public void contextInitialized(ServletContextEvent event) { scheduler = Executors.newSingleThreadScheduledExecutor(); scheduler.scheduleAtFixedRate(new MyTask(), 0, 120, TimeUnit.SECONDS); } @Override public void contextDestroyed(ServletContextEvent event) { System.out.println("shut down"); scheduler.shutdownNow(); } }
    PHP
    UTF-8
    1,884
    2.53125
    3
    [ "Apache-2.0" ]
    permissive
    <?php namespace qtests\container; use qing\facades\Container; class AAA{ public $name='aaa'; } class BBB{ public $name='bbb'; } class CCC{ public $name='ccc'; public $aaa; public $bbb; } /** * * @see app/config/main.php * @author xiaowang <[email protected]> * @copyright Copyright (c) 2013 http://qingmvc.com * @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 */ class Con01Test extends Base{ /** * */ public function test(){ $res=Container::set('aaa',AAA::class); $res=Container::set('bbb',BBB::class); $res=Container::set('closure',function(){ return new BBB(); }); $res=Container::set('ccc',['class'=>CCC::class,'aaa'=>'aaa','bbb'=>'bbb']); // $aaa=Container::get('aaa'); $this->assertTrue(is_object($aaa) && $aaa instanceof AAA); $bbb=Container::get('bbb'); $this->assertTrue(is_object($bbb) && $bbb instanceof BBB); $func=Container::get('closure'); $this->assertTrue(is_object($func) && $func instanceof BBB); //实例ccc依赖aaa&bbb $ccc=Container::get('ccc'); $this->assertTrue(is_object($ccc) && $ccc instanceof CCC); $this->assertTrue($ccc->aaa===$aaa && $ccc->bbb===$bbb); // //$con=Coms::get('container'); //dump(Container::getInstance()); } /** * 实例分类 * * @see app/config/main.php */ public function testCat(){ $di=Container::get('M:Sites'); $this->assertTrue(is_object($di) && $di instanceof \main\model\Sites); $di=Container::get('M:sites'); $this->assertTrue(is_object($di) && $di instanceof \main\model\Sites); // $di=Container::get('C:Index'); $this->assertTrue(is_object($di) && $di instanceof \main\controller\Index); $di=Container::get('C:index'); $this->assertTrue(is_object($di) && $di instanceof \main\controller\Index); } } ?>
    C++
    UTF-8
    388
    2.5625
    3
    []
    no_license
    #pragma once #include "AbstractMonster.hpp" namespace patterns { namespace abstract_factory { class EasyMonster: public AbstractMonster { public: virtual EasyMonster* clone() override { return new EasyMonster(); } virtual std::string text() const override { return "Easy monster"; } virtual ~EasyMonster() { } }; } //abstract factory } //patterns
    C++
    UTF-8
    3,610
    3.21875
    3
    []
    no_license
    #include "LCDHelper.h" #include <Arduino.h> #include <Adafruit_RGBLCDShield.h> LCDHelper::LCDHelper(Adafruit_RGBLCDShield &lcd) { this->lcd = &lcd; this->color = VIOLET; this->clearDisplay = true; this->displayUntil = 0; this->nextScrollTime = 0; this->scrollIndex = 0; } void LCDHelper::printNext( const char *row1, const char *row2, const int color, const unsigned long displayUntil) { this->displayUntil = displayUntil; this->color = color; // Just return if the text hasn't changed if (strcmp(this->row1, row1) == 0 && strcmp(this->row2, row2) == 0) { return; } strcpy(this->row1, row1); strcpy(this->row2, row2); this->clearDisplay = true; } void LCDHelper::printNextP( const char *row1P, const char *row2P, const int color, const unsigned long displayUntil) { char row1[strlen_P(row1P) + 1]; char row2[strlen_P(row2P) + 1]; strcpy_P(this->row1, row1P); strcpy_P(this->row2, row2P); printNext(this->row1, this->row2, color, 0); } void LCDHelper::maybePrintNext( const char *row1, const char *row2, const int color) { if (millis() < displayUntil) { return; } printNext(row1, row2, color, 0); } void LCDHelper::maybePrintNextP( const char *row1P, const char *row2P, const int color) { char row1[strlen_P(row1P) + 1]; char row2[strlen_P(row2P) + 1]; strcpy_P(row1, row1P); strcpy_P(row2, row2P); maybePrintNext(row1, row2, color); } void LCDHelper::maybeScrollRow( char result[LCD_ROW_STR_LENGTH], const char *row) { const unsigned int rowLen = strlen(row); // No scroll necessary, copy and return if (rowLen < LCD_ROW_LENGTH) { copy16(result, row); return; } if (millis() >= this->nextScrollTime) { this->nextScrollTime = millis() + LCD_SCROLL_DELAY_MS; this->scrollIndex++; // We've scrolled beyond all of the row's content plus the padding, so // reset the pointer to 0. if (this->scrollIndex >= rowLen + LCD_SCROLL_PADDING) { this->scrollIndex = 0; } } for (int i = 0; i < LCD_ROW_LENGTH; i++) { unsigned int rowIndex = this->scrollIndex + i; unsigned char c; if (rowIndex >= rowLen) { // This is the padding between the last char of the content and the // start of the beginning of the content entering from the right of // the screen. if (rowIndex < rowLen + LCD_SCROLL_PADDING) { c = ' '; } else { // This is the beginning of the content entering from the right // of the screen. c = row[rowIndex - rowLen - LCD_SCROLL_PADDING]; } } else { c = row[rowIndex]; } result[i] = c; } result[LCD_ROW_LENGTH] = '\0'; } void LCDHelper::copy16( char dest[LCD_ROW_STR_LENGTH], const char *src) { strncpy(dest, src, LCD_ROW_LENGTH); dest[min(LCD_ROW_LENGTH, strlen(src))] = '\0'; } void LCDHelper::print() { if (this->clearDisplay) { lcd->clear(); // Restart scrolling this->scrollIndex = -1; clearDisplay = false; } char row[LCD_ROW_STR_LENGTH]; maybeScrollRow(row, this->row1); lcd->setCursor(0, 0); lcd->print(row); maybeScrollRow(row, this->row2); lcd->setCursor(0, 1); lcd->print(row); lcd->setBacklight(this->color); } void LCDHelper::screenOff() { this->lcd->clear(); this->lcd->setBacklight(BLACK); this->lcd->noDisplay(); } void LCDHelper::screenOn() { this->lcd->display(); }
    C
    ISO-8859-1
    755
    3.5
    4
    []
    no_license
    #include<stdio.h> #include<stdlib.h> #include<math.h> #include<locale.h> /* 10 - So conhecidas as notas de um determinado aluno em uma determinada disciplina durante um semestre letivo: p1, p2, t1 e t2 com pesos respectivamente 3, 5, 1, e 1. So conhecidos tambm o total de aulas desta disciplina e a quantidade de aulas que o aluno assistiu. Elaborar um programa para calcular e exibir a mdia do aluno e a sua frequncia. */ main(){ setlocale(LC_ALL, "Portuguese"); float p1=3,p2=5,t1=1,t2=1,media; int faulas,aulas=100; printf("Informe o nmeros de aulas que voc frequentou: "); scanf("%d", &faulas); media=(p1+p2+t1+t2)/4; system("cls"); printf("A frequencia do aluno de %d/100, e a mdia das notas %.2f",faulas,media); }
    Java
    UTF-8
    1,193
    2.734375
    3
    []
    no_license
    import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.util.ArrayList; /** * Write a description of class Obstacles here. * * @author (your name) * @version (a version number or a date) */ public class Obstacles extends Actor implements ISubject { private ObstacleType obstacle = null; IObserver gameLogic = null; GameLogic gl = GameLogic.getGameLogicInstance(); public void attach(IObserver ob){ } public void detach(IObserver ob){ gameLogic = null; } public void notifyObserver(){ notifyGameLogic(); } public Obstacles(ObstacleType obstacle) { this.obstacle = obstacle; } public ObstacleType getObstacle() { return obstacle; } public void setObstacle(ObstacleType obstacle) { this.obstacle = obstacle; } public void notifyGameLogic(){ if(this.getY() == 360 ){ System.out.println("IF--- Notify Obstacle class"); gl.update(this,"obstacle"); } } public void act() { } public void moveRight(){} public void moveLeft(){} }
    Java
    UTF-8
    250
    2.046875
    2
    []
    no_license
    package slug.soc.game.gameObjects.tiles.faction; import java.awt.Color; import slug.soc.game.gameObjects.tiles.GameTile; public class TileVillage extends GameTile { public TileVillage(Color color) { super("village", color); } }
    Java
    UTF-8
    2,393
    3.875
    4
    []
    no_license
    package elementary_Data_Structures_Trees.BinaryTrees; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; public class BinaryTree { public static int startIndex = 0; public Node crateBinaryTree(int[] values, Node root, int nullNum) { int value = values[startIndex++]; // nullNum means no child if (value == nullNum) { root = null; } else { root = new Node(value, null, null); root.setLeftChild(crateBinaryTree(values, root.getLeftChild(), nullNum)); root.setRightChild(crateBinaryTree(values, root.getRightChild(), nullNum)); } return root; } public void preOrderTraverse(Node root) { if (!(root == null)) { System.out.print(" " + root.getValue() + " "); preOrderTraverse(root.getLeftChild()); preOrderTraverse(root.getRightChild()); } } public void inOrderTraverse(Node root) { if (!(root == null)) { inOrderTraverse(root.getLeftChild()); System.out.print(" " + root.getValue() + " "); inOrderTraverse(root.getRightChild()); } } public void postOrderTraverse(Node root) { if (!(root == null)) { postOrderTraverse(root.getLeftChild()); postOrderTraverse(root.getRightChild()); System.out.print(" " + root.getValue() + " "); } } public void breadthFirstSearch(Node root) { if (!(root == null)) { Queue<Node> bts_Queue = new LinkedList<Node>(); bts_Queue.add(root); while (!bts_Queue.isEmpty()) { Node currentNode = bts_Queue.poll(); System.out.print(" " + currentNode.getValue() + " "); if (currentNode.getLeftChild() != null) { bts_Queue.offer(currentNode.getLeftChild()); } if (currentNode.getRightChild() != null) { bts_Queue.offer(currentNode.getRightChild()); } } } else System.out.print("Empty Tree"); } public void depthFirstSearch(Node root) { if (!(root == null)) { Stack<Node> bts_Queue = new Stack<Node>(); bts_Queue.add(root); while (!bts_Queue.isEmpty()) { Node currentNode = bts_Queue.pop(); System.out.print(" " + currentNode.getValue() + " "); if (currentNode.getRightChild() != null) { bts_Queue.push(currentNode.getRightChild()); } // left child will be read first if (currentNode.getLeftChild() != null) { bts_Queue.push(currentNode.getLeftChild()); } } } else System.out.print("Empty Tree"); } public void refresh() { startIndex = 0; } }
    Java
    UTF-8
    33,168
    1.515625
    2
    []
    no_license
    package com.grgbanking.ct; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import com.baidu.location.LocationClientOption.LocationMode; import com.grgbanking.ct.cach.DataCach; import com.grgbanking.ct.database.Person; import com.grgbanking.ct.database.PersonTableHelper; import com.grgbanking.ct.entity.PdaCashboxInfo; import com.grgbanking.ct.entity.PdaGuardManInfo; import com.grgbanking.ct.entity.PdaLoginMessage; import com.grgbanking.ct.entity.PdaNetInfo; import com.grgbanking.ct.entity.PdaNetPersonInfo; import com.grgbanking.ct.http.FileLoadUtils; import com.grgbanking.ct.http.HttpPostUtils; import com.grgbanking.ct.http.ResultInfo; import com.grgbanking.ct.http.UICallBackDao; import com.grgbanking.ct.page.CaptureActivity; import com.grgbanking.ct.rfid.UfhData; import com.grgbanking.ct.rfid.UfhData.UhfGetData; @SuppressLint("NewApi") public class DetailActivity extends Activity { private Context context; private EditText remarkEditView; TextView positionTextView = null; TextView branchNameTextView = null; Button commitYesButton = null; Button commitNoButton = null; TextView detailTitleTextView = null; Button connDeviceButton = null; Button startDeviceButton = null; TextView person1TextView = null; TextView person2TextView = null; ListView deviceListView; SimpleAdapter listItemAdapter; ArrayList<HashMap<String, Object>> listItem; private int tty_speed = 57600; private byte addr = (byte) 0xff; private Timer timer; private boolean Scanflag=false; private static final int SCAN_INTERVAL = 10; private boolean isCanceled = true; private Handler mHandler; private static final int MSG_UPDATE_LISTVIEW = 0; private Map<String,Integer> data; static HashMap<String, Object> boxesMap1 = null;//保存正确款箱map static HashMap<String, Object> boxesMap2 = null;//保存错误款箱map static PdaNetPersonInfo netPersonInfo = null;//保存网点人员 static PdaGuardManInfo guardManInfo = null;//保存押运人员 private String branchCode = null; private String branchId = null; private String imageUrl = null;// 上传成功后的图片URL private String address; private double latitude; private double longitude; private boolean uploadFlag = false; private ProgressDialog pd = null; private Person person = null; private void showWaitDialog(String msg) { if (pd == null) { pd = new ProgressDialog(this); } pd.setCancelable(false); pd.setMessage(msg); pd.show(); } private void hideWaitDialog() { if (pd != null) { pd.cancel(); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.detail); context = getApplicationContext(); remarkEditView = (EditText) findViewById(R.id.detail_remark); commitNoButton = (Button) findViewById(R.id.detail_btn_commit_n); branchNameTextView = (TextView) findViewById(R.id.detail_branch_name); detailTitleTextView = (TextView) findViewById(R.id.detail_title_view); connDeviceButton = (Button) findViewById(R.id.button1); startDeviceButton = (Button) findViewById(R.id.Button01); person1TextView = (TextView) findViewById(R.id.textView2); person2TextView = (TextView) findViewById(R.id.textView_person2); deviceListView = (ListView) findViewById(R.id.ListView_boxs); // 生成动态数组,加入数据 listItem = new ArrayList<HashMap<String, Object>>(); // 生成适配器的Item和动态数组对应的元素 listItemAdapter = new SimpleAdapter(this,listItem,R.layout.boxes_list_item , new String[] { "list_img", "list_title"} , new int[] { R.id.list_boxes_img, R.id.list_boxes_title}); // 添加并且显示 deviceListView.setAdapter(listItemAdapter); showWaitDialog("正在加载中,请稍后..."); loadDevices(); //启动RFID扫描功能刷新扫描款箱数据 flashInfo(); hideWaitDialog(); // 点击返回按钮操作内容 findViewById(R.id.detail_btn_back).setOnClickListener(click); commitNoButton.setOnClickListener(click); connDeviceButton.setOnClickListener(click); startDeviceButton.setOnClickListener(click); // 点击添加照片按钮操作内容 // findViewById(R.id.add_photo).setOnClickListener(click); } private void flashInfo () { mHandler = new Handler(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub if(isCanceled) return; switch (msg.what) { case MSG_UPDATE_LISTVIEW: // if(mode.equals(MainActivity.TABLE_6B)){ // data = UfhData.scanResult6b; // }else { // data = UfhData.scanResult6c; // } data = UfhData.scanResult6c; // if(listItemAdapter == null){ // myAdapter = new MyAdapter(ScanMode.this, new ArrayList(data.keySet())); // listView.setAdapter(myAdapter); // }else{ // myAdapter.mList = new ArrayList(data.keySet()); // } String person1 = person1TextView.getText().toString(); String person2 = person2TextView.getText().toString(); Iterator it = data.keySet().iterator(); while (it.hasNext()) { String key = (String)it.next(); //判断是否是押运人员 if (key.indexOf(Constants.PRE_RFID_GUARD) != -1) { if (person1.trim().equals("")) { PdaLoginMessage plm = DataCach.getPdaLoginMessage(); if (plm != null) { List<PdaGuardManInfo> guardManInfoList = plm.getGuardManInfoList(); if (guardManInfoList != null && guardManInfoList.size() > 0) { for (PdaGuardManInfo info : guardManInfoList) { if (info.getGuardManRFID().equals(key)) { person1TextView.setText(info.getGuardManName()); guardManInfo = info; break; } } } } } } //判断是否是网点人员 else if (key.indexOf(Constants.PRE_RFID_BANKEMPLOYEE) != -1) { if (person2.trim().equals("")) { Intent intent = getIntent(); Bundle bundle = intent.getBundleExtra("bundle"); int count = bundle.getInt("count"); HashMap<String, Object> map = DataCach.taskMap.get(count+ ""); PdaNetInfo pni = (PdaNetInfo) map.get("data"); if (pni != null) { List<PdaNetPersonInfo> netPersonInfoList = pni.getNetPersonInfoList(); if (netPersonInfoList != null && netPersonInfoList.size() > 0) { for (PdaNetPersonInfo info : netPersonInfoList) { if (info.getNetPersonRFID().equals(key)) { person2TextView.setText(info.getNetPersonName()); netPersonInfo = info; break; } } // if (person2TextView.getText().toString().equals("")) { // Toast.makeText(context, "该网点人员不是本网点人员", 5000).show(); // } } } } } //判断是否是正确款箱RFID else if (boxesMap1.get(key) != null) { HashMap<String, Object> map = DataCach.boxesMap.get(key); map.put("list_img", R.drawable.boxes_list_status_1);// 图像资源的ID HashMap<String, Object> map1 = (HashMap<String, Object>) boxesMap1.get(key); //记录该款箱是否已扫描 0:未扫描;1:已扫描 map1.put("status", "1"); } //判断是否是错误款箱RFID else if (boxesMap2.get(key) == null) { PdaLoginMessage pdaLoginMessage = DataCach.getPdaLoginMessage(); Map<String, String> allPdaBoxsMap = pdaLoginMessage.getAllPdaBoxsMap(); if (allPdaBoxsMap.get(key) != null) { HashMap<String, Object> map1 = new HashMap<String, Object>(); map1.put("list_img", R.drawable.boxes_list_status_3);// 图像资源的ID map1.put("list_title",allPdaBoxsMap.get(key)); DataCach.boxesMap.put(key, map1); boxesMap2.put(key, map1); listItem.add(map1); } } //判断是否正确扫描到全部款箱和交接人员,如果是自动停止扫描 if (boxesMap1 != null && boxesMap1.size() > 0) { boolean right = true; Iterator it2 = boxesMap1.keySet().iterator(); while (it2.hasNext()) { String key2 = (String) it2.next(); HashMap<String, Object> map1 = (HashMap<String, Object>) boxesMap1.get(key2); if (map1.get("status").equals("0")) { right = false; break; } } if (boxesMap2 != null && boxesMap2.size() > 0) { right = false; } //判断人员是否扫描 if (guardManInfo == null) { right = false; } if (netPersonInfo == null) { right = false; } if (right) { String context = startDeviceButton.getText().toString(); if (context.equals("Stop")) { startDevices (); break; } } } } // txNum.setText(String.valueOf(myAdapter.getCount())); listItemAdapter.notifyDataSetChanged(); break; default: break; } super.handleMessage(msg); } }; } private void connDevices () { int result=UhfGetData.OpenUhf(tty_speed, addr, 4, 1, null); if(result==0){ UhfGetData.GetUhfInfo(); Toast.makeText(context, "连接设备成功", Toast.LENGTH_LONG).show(); // mHandler.removeMessages(MSG_SHOW_PROPERTIES); // mHandler.sendEmptyMessage(MSG_SHOW_PROPERTIES); } else { Toast.makeText(context, "连接设备失败,请关闭程序重新登录", Toast.LENGTH_LONG).show(); } } private void startDevices () { if(!UfhData.isDeviceOpen()){ Toast.makeText(this, R.string.detail_title, Toast.LENGTH_LONG).show(); return; } if(timer == null){ // cdtion.setEnabled(false); ///////////声音开关初始化 UfhData.Set_sound(true); UfhData.SoundFlag=false; ////////// // if (myAdapter != null) { // if(mode.equals(MainActivity.TABLE_6B)){ // UfhData.scanResult6b.clear(); // }else if(mode.equals(MainActivity.TABLE_6C)){ // UfhData.scanResult6c.clear(); // } // myAdapter.mList.clear(); // myAdapter.notifyDataSetChanged(); // mHandler.removeMessages(MSG_UPDATE_LISTVIEW); // mHandler.sendEmptyMessage(MSG_UPDATE_LISTVIEW); // } isCanceled = false; timer = new Timer(); // timer.schedule(new TimerTask() { @Override public void run() { if(Scanflag)return; Scanflag=true; // if(mode.equals(MainActivity.TABLE_6B)){ // Log.i("zhouxin", "------onclick-------6b"); // UfhData.read6b(); // }else if(mode.equals(MainActivity.TABLE_6C)){ // UfhData.read6c(); // } Log.i("zhouxin", "------onclick-------6c"); UfhData.read6c(); mHandler.removeMessages(MSG_UPDATE_LISTVIEW); mHandler.sendEmptyMessage(MSG_UPDATE_LISTVIEW); Scanflag=false; } }, 0, SCAN_INTERVAL); startDeviceButton.setText("Stop"); }else{ cancelScan(); UfhData.Set_sound(false); } } private void cancelScan(){ isCanceled = true; // cdtion.setEnabled(true); mHandler.removeMessages(MSG_UPDATE_LISTVIEW); if(timer != null){ timer.cancel(); timer = null; startDeviceButton.setText("Scan"); // if(mode.equals(MainActivity.TABLE_6B)){ // UfhData.scanResult6b.clear(); // }else if(mode.equals(MainActivity.TABLE_6C)){ // UfhData.scanResult6c.clear(); // } UfhData.scanResult6c.clear(); // if (listItemAdapter != null) { // listItem.clear(); // listItemAdapter.notifyDataSetChanged(); // } // txNum.setText("0"); } } private void loadDevices () { //加载数据要先把数据缓存清空 person1TextView.setText(""); person2TextView.setText(""); DataCach.boxesMap = null; DataCach.boxesMap = new LinkedHashMap<String, HashMap<String, Object>>(); boxesMap1 = null; boxesMap1 = new HashMap<String, Object>(); boxesMap2 = null; boxesMap2 = new HashMap<String, Object>(); netPersonInfo = null; guardManInfo = null; listItem.removeAll(listItem); Intent intent = getIntent(); Bundle bundle = intent.getBundleExtra("bundle"); int count = bundle.getInt("count"); if (DataCach.taskMap.get(count+ "") != null) { HashMap<String, Object> map = DataCach.taskMap.get(count+ ""); PdaNetInfo pni = (PdaNetInfo) map.get("data"); detailTitleTextView.setText(pni.getBankName()); List<PdaCashboxInfo> cashBoxInfoList = pni.getCashBoxInfoList(); if (cashBoxInfoList != null && cashBoxInfoList.size() > 0) { for (PdaCashboxInfo pci: cashBoxInfoList) { HashMap<String, Object> map1 = new HashMap<String, Object>(); map1.put("list_img", R.drawable.boxes_list_status_2);// 图像资源的ID map1.put("list_title", pci.getBoxSn()); //记录该款箱是否已扫描 0:未扫描;1:已扫描 map1.put("status", "0"); DataCach.boxesMap.put(pci.getRfidNum(), map1); boxesMap1.put(pci.getRfidNum(), map1); listItem.add(map1); } } } listItemAdapter.notifyDataSetChanged(); } @Override protected void onStart() { // TODO Auto-generated method stub super.onStart(); } OnClickListener click = new OnClickListener() { @Override public void onClick(View arg0) { String context = startDeviceButton.getText().toString(); // TODO Auto-generated method stub switch (arg0.getId()) { case R.id.detail_btn_back: if (context.equals("Stop")) { Toast.makeText(DetailActivity.this, "请先停止扫描", 3000).show(); } else { backListPage(); } break; // case R.id.detail_btn_commit_y: // doCommit("Y"); // break; case R.id.detail_btn_commit_n: // if (uploadFlag) { // doCommit("N"); // } else { // Toast.makeText(DetailActivity.this, "图片正在上传中,请稍等。", 5000) // .show(); // } if (context.equals("Stop")) { Toast.makeText(DetailActivity.this, "请先停止扫描", 3000).show(); } else { dialog(); } break; // case R.id.add_photo: // doAddPhoto(); // break; case R.id.button1: //连接设备 connDevices(); break; case R.id.Button01: //启动设备 if (!context.equals("Stop")) { loadDevices(); } startDevices(); break; default: break; } } }; protected void dialog() { // 通过AlertDialog.Builder这个类来实例化我们的一个AlertDialog的对象 AlertDialog.Builder builder = new AlertDialog.Builder(DetailActivity.this); // // 设置Title的图标 // builder.setIcon(R.drawable.ic_launcher); // 设置Title的内容 builder.setTitle("提示"); // 设置Content来显示一个信息 builder.setMessage("确定交接?"); // 设置一个PositiveButton builder.setPositiveButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); // 设置一个NegativeButton builder.setNegativeButton("确认", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { showWaitDialog("正在提交数据..."); ResultInfo ri = this.getNetIncommitData(); if (ri.getCode().endsWith(ResultInfo.CODE_ERROR)) { hideWaitDialog(); Toast.makeText(context, ri.getMessage(), 5000).show(); return; } List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("param", ri.getText())); new HttpPostUtils(Constants.URL_NET_IN_COMMIT, params,new UICallBackDao() { @Override public void callBack(ResultInfo resultInfo) { if (resultInfo.getCode().equals(ResultInfo.CODE_ERROR)) { hideWaitDialog(); Toast.makeText(context, resultInfo.getMessage(), 5000).show(); } else { hideWaitDialog(); Toast.makeText(context, resultInfo.getMessage(), 5000).show(); } } }).execute(); hideWaitDialog(); // 得到跳转到该Activity的Intent对象 Intent intent = getIntent(); Bundle bundle = intent.getBundleExtra("bundle"); int count = bundle.getInt("count"); if (DataCach.taskMap.get(count+ "") != null) { HashMap<String, Object> map = DataCach.taskMap.get(count+ ""); map.put("list_img", R.drawable.task_1);// 图像资源的ID map.put("list_worktime","已完成"); } backListPage(); } private ResultInfo getNetIncommitData() { ResultInfo ri = new ResultInfo(); Map<String, String> dataMap = new HashMap<String, String>(); if (guardManInfo == null) { ri.setCode(ResultInfo.CODE_ERROR); ri.setMessage("请扫描押运人员"); return ri; } if (netPersonInfo == null) { ri.setCode(ResultInfo.CODE_ERROR); ri.setMessage("请扫描网点人员"); return ri; } if ((boxesMap1 == null || boxesMap1.size() == 0) && (boxesMap2 == null || boxesMap2.size() == 0)) { ri.setCode(ResultInfo.CODE_ERROR); ri.setMessage("请扫描款箱"); return ri; } //开始组装数据 PdaLoginMessage pdaLoginMessage = DataCach.getPdaLoginMessage(); SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); dataMap.put("lineId", pdaLoginMessage.getLineId()); dataMap.put("scanningDate", format.format(new Date())); dataMap.put("netPersonName", netPersonInfo.getNetPersonName()); dataMap.put("netPersonId", netPersonInfo.getNetPersonId()); dataMap.put("guardPersonName", guardManInfo.getGuardManName()); dataMap.put("guradPersonId", guardManInfo.getGuardManId()); dataMap.put("note", remarkEditView.getText().toString()); Intent intent = getIntent(); Bundle bundle = intent.getBundleExtra("bundle"); int count = bundle.getInt("count"); dataMap.put("scanningType", DataCach.netType); HashMap<String, Object> map = DataCach.taskMap.get(count+ ""); PdaNetInfo pni = (PdaNetInfo) map.get("data"); dataMap.put("netId", pni.getBankId()); String rightRfidNums = ""; String missRfidNums = ""; String errorRfidNums = ""; if (boxesMap1 != null && boxesMap1.size() > 0) { Iterator it = boxesMap1.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); HashMap<String, Object> map1 = (HashMap<String, Object>) boxesMap1.get(key); if (map1.get("status").equals("1")) { rightRfidNums += ";" + key; } else { missRfidNums += ";" + key; } } if (rightRfidNums.length() > 0) { rightRfidNums = rightRfidNums.substring(1); } if (missRfidNums.length() > 0) { missRfidNums = missRfidNums.substring(1); } } if (boxesMap2 != null && boxesMap2.size() > 0) { Iterator it = boxesMap2.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); errorRfidNums += ";" + key; } if (errorRfidNums.length() > 0) { errorRfidNums = errorRfidNums.substring(1); } } dataMap.put("rightRfidNums", rightRfidNums); dataMap.put("missRfidNums", missRfidNums); dataMap.put("errorRfidNums", errorRfidNums); if (rightRfidNums.length() > 0 && missRfidNums.length() == 0 && errorRfidNums.length() == 0) { dataMap.put("scanStatus", Constants.NET_COMMIT_STATUS_RIGHT); } else { dataMap.put("scanStatus", Constants.NET_COMMIT_STATUS_ERROR); } JSONObject jsonObject = new JSONObject(dataMap); String data = jsonObject.toString(); ri.setCode(ResultInfo.CODE_SUCCESS); ri.setText(data); return ri; } }); // // 设置一个NeutralButton // builder.setNeutralButton("忽略", new DialogInterface.OnClickListener() // { // @Override // public void onClick(DialogInterface dialog, int which) // { // Toast.makeText(DetailActivity.this, "neutral: " + which, Toast.LENGTH_SHORT).show(); // } // }); // 显示出该对话框 builder.show(); } void backListPage() { startActivity(new Intent(getApplicationContext(), MainActivity.class)); finish(); } void doCommit(String flag) { if(address==null||"".equals(address)){ Toast.makeText(DetailActivity.this, "错误提示:无法获取您当前的地理位置,请返回重新扫描二维码。", 5000) .show(); return; } showWaitDialog("正在处理中..."); String remark = remarkEditView.getText().toString(); String status = flag; List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("userid", person.getUser_id())); params.add(new BasicNameValuePair("name", person.getUser_name())); params.add(new BasicNameValuePair("branchId", branchId)); params.add(new BasicNameValuePair("remark", remark)); params.add(new BasicNameValuePair("status", status)); params.add(new BasicNameValuePair("imageUrl", imageUrl)); params.add(new BasicNameValuePair("longitude", longitude + "")); params.add(new BasicNameValuePair("latitude", latitude + "")); params.add(new BasicNameValuePair("address", address)); new HttpPostUtils(Constants.URL_SAVE_TASK, params, new UICallBackDao() { @Override public void callBack(ResultInfo resultInfo) { hideWaitDialog(); if("1".equals(resultInfo.getCode())){ new AlertDialog.Builder(DetailActivity.this) .setTitle("消息") .setMessage("提交成功!") .setPositiveButton("确定", new DialogInterface.OnClickListener() {// 设置确定按钮 @Override // 处理确定按钮点击事件 public void onClick(DialogInterface dialog, int which) { backListPage(); } }).show(); }else{ Toast.makeText(DetailActivity.this, resultInfo.getMessage(), 5*1000).show(); } } }).execute(); } void doAddPhoto() { final CharSequence[] items = { "相册", "拍照" }; AlertDialog dlg = new AlertDialog.Builder(DetailActivity.this) .setTitle("选择照片") .setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub // 这里item是根据选择的方式, 在items数组里面定义了两种方式,拍照的下标为1所以就调用拍照方法 if (which == 1) { takePhoto(); } else { pickPhoto(); } } }).create(); dlg.show(); } private static final int IMAGE_REQUEST_CODE = 0; // 选择本地图片 private static final int CAMERA_REQUEST_CODE = 1; // 拍照 private static final String IMAGE_FILE_NAME = "faceImage.jpg"; /** * 拍照 */ private void takePhoto() { Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // 判断存储卡是否可以用,可用进行存�? String state = Environment.getExternalStorageState(); if (state.equals(Environment.MEDIA_MOUNTED)) { intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri .fromFile(new File(Environment .getExternalStorageDirectory(), IMAGE_FILE_NAME))); } startActivityForResult(intentFromCapture, CAMERA_REQUEST_CODE); } /** * 选择本地图片 */ private void pickPhoto() { Intent intentFromGallery = new Intent(); intentFromGallery.setType("image/*"); // 设置文件类型 intentFromGallery.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intentFromGallery, IMAGE_REQUEST_CODE); } public String uri2filePath(Uri uri) { String path = ""; if (DocumentsContract.isDocumentUri(this, uri)) { String wholeID = DocumentsContract.getDocumentId(uri); String id = wholeID.split(":")[1]; String[] column = { MediaStore.Images.Media.DATA }; String sel = MediaStore.Images.Media._ID + "=?"; Cursor cursor = this.getContentResolver().query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel, new String[] { id }, null); int columnIndex = cursor.getColumnIndex(column[0]); if (cursor.moveToFirst()) { path = cursor.getString(columnIndex); } cursor.close(); } else { String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = this.getContentResolver().query(uri, projection, null, null, null); int column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); path = cursor.getString(column_index); } return path; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { switch (requestCode) { case CAMERA_REQUEST_CODE: String state = Environment.getExternalStorageState(); if (state.equals(Environment.MEDIA_MOUNTED)) { Bitmap bitmap = compressImage(getSmallBitmap(Environment .getExternalStorageDirectory() + "/" + IMAGE_FILE_NAME)); // addPhotoImageView.setImageBitmap(bitmap); // uploadStatusTextView.setText("图片上传中..."); new FileLoadUtils(Constants.URL_FILE_UPLOAD, new File( Environment.getExternalStorageDirectory() + "/faceImage1.jpg"), new UICallBackDao() { @Override public void callBack(ResultInfo resultInfo) { if (resultInfo != null && "200".equals(resultInfo.getCode())) { Toast.makeText(DetailActivity.this, "上传成功", 5000).show(); // uploadStatusTextView.setText("上传成功。"); // imageUrl = resultInfo.getMessage(); uploadFlag = true; } } }).execute(); } else { Toast.makeText(this, getString(R.string.sdcard_unfound), Toast.LENGTH_SHORT).show(); } break; case IMAGE_REQUEST_CODE: try { String path = uri2filePath(data.getData()); Bitmap bitmap = compressImage(getSmallBitmap(path)); // addPhotoImageView.setImageBitmap(bitmap); // uploadStatusTextView.setText("图片上传中..."); new FileLoadUtils(Constants.URL_FILE_UPLOAD, new File(path), new UICallBackDao() { @Override public void callBack(ResultInfo resultInfo) { if (resultInfo != null && "200".equals(resultInfo .getCode())) { Toast.makeText(DetailActivity.this, "上传成功", 5000).show(); // uploadStatusTextView.setText("上传成功。"); imageUrl = resultInfo.getMessage(); uploadFlag = true; } } }).execute(); } catch (Exception e) { e.printStackTrace(); } break; } } } /** * 图片压缩方法实现 * * @param srcPath * @return */ private Bitmap getimage(String srcPath) { BitmapFactory.Options newOpts = new BitmapFactory.Options(); // 开始读入图片,此时把options.inJustDecodeBounds 设回true了 newOpts.inJustDecodeBounds = true; Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts); newOpts.inJustDecodeBounds = false; int w = newOpts.outWidth; int h = newOpts.outHeight; int hh = 800;// 这里设置高度为800f int ww = 480;// 这里设置宽度为480f // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可 int be = 1;// be=1表示不缩放 if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放 be = newOpts.outWidth / ww; } else if (w < h && h > hh) {// 如果高度高的话根据高度固定大小缩放 be = newOpts.outHeight / hh; } if (be <= 0) be = 1; newOpts.inSampleSize = be;// 设置缩放比例 // 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了 bitmap = BitmapFactory.decodeFile(srcPath, newOpts); return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩 } /** * 质量压缩 * * @param image * @return */ private Bitmap compressImage(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 50, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 int options = 100; while (baos.toByteArray().length * 3 / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩 baos.reset();// 重置baos即清空baos options -= 10;// 每次都减少10 image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中 } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中 Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片 try { FileOutputStream out = new FileOutputStream( Environment.getExternalStorageDirectory() + "/faceImage1.jpg"); bitmap.compress(Bitmap.CompressFormat.PNG, 40, out); } catch (Exception e) { e.printStackTrace(); } return bitmap; } public void initLocation(final Context context, final DetailActivity detailActivity) { LocationClient locationClient = new LocationClient(context); // 设置定位条件 LocationClientOption option = new LocationClientOption(); option.setOpenGps(true); // 是否打开GPS option.setIsNeedAddress(true); option.setLocationMode(LocationMode.Hight_Accuracy); option.setScanSpan(0);// 设置定时定位的时间间隔。单位毫秒 option.setAddrType("all"); option.setCoorType("bd09ll"); locationClient.setLocOption(option); // 注册位置监听器 locationClient.registerLocationListener(new BDLocationListener() { @Override public void onReceiveLocation(BDLocation location) { // gpsPositionTextView = (TextView) detailActivity // .findViewById(R.id.gps_position); // gpsPositionTextView.setText("我的位置:" + location.getAddrStr()); address = location.getAddrStr(); latitude = location.getLatitude(); longitude = location.getLongitude(); } }); locationClient.start(); } /** * 计算图片的缩放值 * * @param options * @param reqWidth * @param reqHeight * @return */ public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { // Calculate ratios of height and width to requested height and // width final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); // Choose the smallest ratio as inSampleSize value, this will // guarantee // a final image with both dimensions larger than or equal to the // requested height and width. inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; } /** * 根据路径获得突破并压缩返回bitmap用于显示 * * @return */ public static Bitmap getSmallBitmap(String filePath) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, 480, 800); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(filePath, options); } }
    C#
    UTF-8
    6,703
    2.703125
    3
    []
    no_license
    using System.Text; using FileServer.Core; using Xunit; namespace FileServer.Test { [Collection("Using IO")] public class ProgramTest { [Theory] [InlineData(-1)] [InlineData(0)] [InlineData(1000)] [InlineData(1999)] [InlineData(65001)] [InlineData(9999999)] public void Out_Of_Range_Ports(int invaildPorts) { var correctOutput = new StringBuilder(); correctOutput.Append("Invaild Port Detected."); correctOutput.Append("Vaild Ports 2000 - 65000"); string[] argsHelloWorld = { "-p", invaildPorts.ToString() }; var mockPrinterOne = new MockPrinter(); var serverMadeHelloWorld = Program.MakeServer(argsHelloWorld, mockPrinterOne); Assert.Null(serverMadeHelloWorld); mockPrinterOne.VerifyPrint(correctOutput.ToString()); string[] args = { "-p", invaildPorts.ToString(), "-d", "C:\\" }; var mockPrinterTwo = new MockPrinter(); var serverMade = Program.MakeServer(args, mockPrinterTwo); Assert.Null(serverMade); mockPrinterTwo.VerifyPrint(correctOutput.ToString()); var mockPrinterThree = new MockPrinter(); string[] argsSwaped = { "-d", "C:\\", "-p", invaildPorts.ToString() }; var serverMadeSwaped = Program.MakeServer(argsSwaped, mockPrinterThree); Assert.Null(serverMadeSwaped); mockPrinterThree.VerifyPrint(correctOutput.ToString()); } [Fact] public void Make_Dirctory_Server_Correct() { var mockPrinter = new MockPrinter(); string[] args = { "-p", "32000", "-d", "C:\\" }; var serverMade = Program.MakeServer(args, mockPrinter); Assert.NotNull(serverMade); } [Fact] public void Make_Dirctory_Server_Twice_Same_Port() { var mockPrinter = new MockPrinter(); var correctOutput = new StringBuilder(); string[] args = { "-p", "8765", "-d", "C:\\" }; var serverMade = Program.MakeServer(args, mockPrinter); Assert.NotNull(serverMade); var serverMadeInvaild = Program.MakeServer(args, mockPrinter); Assert.Null(serverMadeInvaild); mockPrinter.VerifyPrint("Another Server is running on that port"); } [Fact] public void Make_Dirctory_Server_Correct_Arg_Backwords() { var mockPrinter = new MockPrinter(); string[] args = { "-d", "C:\\", "-p", "2020" }; var serverMade = Program.MakeServer(args, mockPrinter); Assert.NotNull(serverMade); } [Fact] public void Make_Dirctory_Server_Inncorect_Correct_Not_Dir() { var mockPrinter = new MockPrinter(); var correctOutput = new StringBuilder(); string[] args = { "-d", "Hello", "-p", "3258" }; var serverMade = Program.MakeServer(args, mockPrinter); Assert.Null(serverMade); mockPrinter.VerifyPrint("Not a vaild directory"); } [Fact] public void Make_Dirctory_Server_Inncorect_Correct_Not_Port() { var mockPrinter = new MockPrinter(); var correctOutput = new StringBuilder(); correctOutput.Append("Invaild Port Detected."); correctOutput.Append("Vaild Ports 2000 - 65000"); string[] args = { "-d", "C:\\", "-p", "hello" }; var serverMade = Program.MakeServer(args, mockPrinter); Assert.Null(serverMade); mockPrinter.VerifyPrint(correctOutput.ToString()); } [Fact] public void Make_Dirctory_Server_Inncorect_Correct() { var mockPrinter = new MockPrinter(); var correctOutput = new StringBuilder(); string[] args = { "-p", "32000", "-d", "-d" }; var serverMade = Program.MakeServer(args, mockPrinter); Assert.Null(serverMade); mockPrinter.VerifyPrint("Not a vaild directory"); } [Fact] public void Make_Hello_World_Server_Correct() { var mockPrinter = new MockPrinter(); string[] args = { "-p", "9560" }; var serverMade = Program.MakeServer(args, mockPrinter); Assert.NotNull(serverMade); } [Fact] public void Make_Hello_World_Incorrect_Correct() { var mockPrinter = new MockPrinter(); string[] args = { "2750", "-p" }; var serverMade = Program.MakeServer(args, mockPrinter); Assert.Null(serverMade); } [Fact] public void Make_Hello_World_Incorrect_Correct_No_Port() { var mockPrinter = new MockPrinter(); string[] args = { "-p", "-p" }; var serverMade = Program.MakeServer(args, mockPrinter); Assert.Null(serverMade); } [Fact] public void Make_Server_Inncorect_NoArgs() { var mockPrinter = new MockPrinter(); var correctOutput = new StringBuilder(); correctOutput.Append("Invaild Number of Arguments.\n"); correctOutput.Append("Can only be -p PORT\n"); correctOutput.Append("or -p PORT -d DIRECTORY\n"); correctOutput.Append("Examples:\n"); correctOutput.Append("Server.exe -p 8080 -d C:/\n"); correctOutput.Append("Server.exe -d C:/HelloWorld -p 5555\n"); correctOutput.Append("Server.exe -p 9999"); var args = new[] { "-s" }; var serverMade = Program.MakeServer(args, mockPrinter); Assert.Null(serverMade); mockPrinter.VerifyPrint(correctOutput.ToString()); } [Fact] public void Main_Starting_Program() { string[] args = { }; Assert.Equal(0, Program.Main(args)); } [Fact] public void Test_Running_Of_Server() { var mockServer = new MockMainServer() .StubAcceptingNewConn(); Program.RunServer(mockServer); mockServer.VerifyRun(); mockServer.VerifyAcceptingNewConn(); } [Fact] public void Make_Log_File() { var mockPrinter = new MockPrinter(); string[] args = { "-p", "10560", "-l", "c:/TestLog" }; var serverMade = Program.MakeServer(args, mockPrinter); Assert.Equal("c:/TestLog", mockPrinter.Log); Assert.NotNull(serverMade); } } }
    JavaScript
    UTF-8
    1,165
    2.96875
    3
    []
    no_license
    // a tree is a list of nodes function find_bookmark_by_title(tree, title) { if (!tree) return null; for (var i=0; i<tree.length; i++) { var node = tree[i]; if (node.title == title) return node; } // nothing at top-level, keep going for (var i=0; i<tree.length; i++) { var node = tree[i]; var subsearch = find_bookmark_by_title(node.children, title); if (subsearch) return subsearch; } return null; } var BOOKMARK_DIRECTORY = 'Firefox'; function update_bookmarks(bookmarks) { chrome.bookmarks.getTree(function(tree) { var bar = find_bookmark_by_title(tree, BOOKMARK_DIRECTORY); if (bar) { bar.children.forEach(function(bookmark) { chrome.bookmarks.removeTree(bookmark.id); }); } else { // create it var bookmarks_bar = find_bookmark_by_title(tree, 'Bookmarks Bar'); bar = chrome.bookmarks.create({ parentId: bookmarks_bar.id, title: BOOKMARK_DIRECTORY }); } // add the bookmarks bookmarks.forEach(function(one_bookmark) { one_bookmark.parentId = bar.id; chrome.bookmarks.create(one_bookmark); }); }); }
    JavaScript
    UTF-8
    1,997
    2.6875
    3
    []
    no_license
    $(document).ready(function() { jQuery.fn.exists = function(){return this.length>0;} $(".add").click(function (event) { event.preventDefault(); var inputitem = $('#newitem').val(); if (inputitem == '') { var empty_item = confirm("Item is empty, do you want to add an empty item?"); if (empty_item) { $("ul").append("<li><input type='checkbox' class='singlecheck'/>Item<br/><button class='remove'>Delete Item</button></li>"); } } else { $("ul").append("<li><input type='checkbox' class='singlecheck'/>"+inputitem+"<br/><button class='remove'>Delete Item</button></li>"); $('#newitem').val(""); } $(".checkout").show(); }); $('#shopping-items').on('click', '.remove', function(){ $(this).closest("li").remove(); }); $('#shopping-items').on('click', '.checkout', function(){ event.preventDefault(); $("button").prop('disabled',true); $("li").css("text-decoration","line-through"); $(".singlecheck").prop('checked', true); $("li").find("img").remove(); $("#shopping-items li").append("<img class='tickmark' src='images/check-mark.jpg' alt='checked out'/>"); $(this).text('All Checked Out'); }); $('#shopping-items').on('change','.singlecheck', function() { if ($(this).is(':checked')) { $(this).closest("li").find("img").remove(); $(this).closest("li").append("<img class='tickmark' src='images/check-mark.jpg' alt='checked out'/>"); $(".checkout").text('Checkout'); $("button").prop('disabled',false); $(this).closest('li').find("button").prop('disabled',true); $(this).closest('li').css("text-decoration","line-through"); } else { console.log("not checked"); $(this).closest("li").find("img").remove(); $(".checkout").text('Checkout'); $(".checkout").prop('disabled',false); $(".add").prop('disabled',false); $(this).closest("li").find("button").prop('disabled',false); $(this).closest('li').css("text-decoration","none"); } }); });
    Python
    UTF-8
    135
    2.609375
    3
    []
    no_license
    import datetime d={'Cumpleaños':20,'Ricardo':2002,'Fecha':datetime.date.today()} d.setdefault('Año minimo',datetime.MINYEAR) print(d)
    C++
    UTF-8
    479
    2.765625
    3
    []
    no_license
    #include "DataStore.h" #include <EEPROM\src\EEPROM.h> /* template < class T > DataStore<T>::DataStore(uint16_t start, uint8_t maxdata ) : startAddres(start), maxData(maxdata) { lastData = 0; } */ template < class T > void DataStore<T>::pushBack(T data) { uint8_t length = sizeof(T); uint8_t * p = (uint8_t *) data; for (uint8_t i = 0; i < length; i++) { EEPROM.write(startAddres + lastData, *p); p++; } } /* template < class T > DataStore<T>::~DataStore() { } */
    Java
    UTF-8
    3,372
    3.328125
    3
    []
    no_license
    package net.Programmers; import java.util.Comparator; import java.util.PriorityQueue; public class Sonf { //곡별로 음계 전체 만들기 static String[][] pattern = new String[][]{{"C#","c"},{"D#","d"},{"F#","f"},{"G#","g"},{"A#","a"}}; public String solution(String m, String[] musicinfos) { String answer = "(None)"; PriorityQueue<Song> queue = new PriorityQueue<>(new Comparator<Song>() { @Override public int compare(Song o1, Song o2) { if(o1.time==o2.time)return o1.start-o2.start; else return o2.time-o1.time; } }); for(String s: musicinfos){ String str[] = s.split(","); int time = getTime(str[0],str[1]); queue.offer(new Song(Integer.parseInt(str[0].replaceAll(":","")),time,str[2],getFull(time,str[3]))); } System.out.println(queue); while(!queue.isEmpty()){ Song current = queue.poll(); if(check(m,current))return current.name; } return answer; } //전체음계 구하기 static String getFull(int time,String scale){ StringBuilder total=new StringBuilder(); scale = removeSharp(scale); System.out.println(time+scale); for(int i=0;i<time;i++){ total.append(scale.charAt(i%scale.length())); } return total.toString(); } //시간변환 static int getTime(String start, String end){ String startA[] = start.split(":"); String endA[] = end.split(":"); int hour = 0; int minute= 0; int sh = Integer.parseInt(startA[0]); int eh = Integer.parseInt(endA[0]); int sm =Integer.parseInt(startA[1]); int em = Integer.parseInt(endA[1]); if(em<sm){//분이 넘어가는 경우 minute = 60-sm+em; eh--; }else minute =em-sm; if(eh<sh){//시가 넘어가는 경우, 00:00이상일 경우 hour = 23-sh; minute = sm==0?0:60-sm; }else hour = eh-sh; System.out.println(hour+":"+minute); return hour*60+minute; } static boolean check(String input, Song song){ input = removeSharp(input); for(int i=0;i+input.length()<=song.scale.length();i++){ if(song.scale.substring(i,i+input.length()).equals(input))return true; } return false; } static String removeSharp(String input){ for(int i=0;i<pattern.length;i++){ input = input.replaceAll(pattern[i][0],pattern[i][1]); } return input; } class Song{ int start; int time; String name; String scale; public Song(int start,int time, String name, String scale) { this.start = start; this.time = time; this.name = name; this.scale = scale; } @Override public String toString() { return "Song{" + "start=" + start + ", name='" + name + '\'' + ", scale='" + scale + '\'' + '}'; } } public static void main(String[] args) { System.out.println(new Sonf().solution("ABC", new String[]{"13:40,13:40,HELLO,C#DEFGAB", "20:00,14:01,WORLD,ABCDEF"})); } }
    Python
    UTF-8
    5,118
    2.859375
    3
    [ "Apache-2.0" ]
    permissive
    # Copyright (C) 2018 Alteryx, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os import string from IPython.display import display, Markdown def convertObjToStr(obj): try: obj_str = '{}'.format(obj) except: obj_str = '<{}>'.format(type(obj)) return obj_str # return a string containing a msg followed by a filepath def fileErrorMsg(msg, filepath=None): if filepath is None: raise ReferenceError("No filepath provided") return ''.join([msg, ' (', filepath, ')']) # check if file exists. if not, throw error def fileExists(filepath, throw_error=None, msg=None, debug=None): # default is to not throw an error if throw_error is None: throw_error = False if msg is None: msg = 'Input data file does not exist' # set default for debug if debug is None: debug = False elif not isinstance(debug, bool): raise TypeError('debug value must be True or False') # if file exists, return true if os.path.isfile(filepath): if debug: print(fileErrorMsg('File exists', filepath)) return True elif os.path.isdir(filepath): if debug: print(fileErrorMsg('Directory exists', filepath)) return True else: if throw_error: raise FileNotFoundError(fileErrorMsg(msg, filepath)) elif debug: print(fileErrorMsg(msg, filepath)) return False # check if a string is a valid sqlite table name def tableNameIsValid(table_name): if isString(table_name): # stripped = ''.join( char for char in table_name if (char.isalnum() or char=='_')) valid_chars = ''.join([string.ascii_letters, string.digits, '_']) stripped = ''.join(char for char in table_name if (char in valid_chars)) if stripped != table_name: valid = False reason = 'invalid characters (only alphanumeric and underscores)' elif not table_name[0].isalpha(): valid = False reason = 'first character must be a letter' else: valid = True reason = None return valid, reason else: raise TypeError('table name must be a string') # delete a file (if it exists) def deleteFile(filepath, debug=None): # set default for debug if debug is None: debug = False elif not isinstance(debug, bool): raise TypeError('debug value must be True or False') # if file exists, attempt to delete it if fileExists(filepath, throw_error=False): try: os.remove(filepath) if debug: print(fileErrorMsg("Success: file deleted", filepath)) except: print(fileErrorMsg("Error: Unable to delete file", filepath)) raise else: if debug: print(fileErrorMsg("Success: file does not exist", filepath)) def isString(var): return isinstance(var, str) def isDictMappingStrToStr(d): try: if not isinstance(d, dict): raise TypeError('Input must be a python dict') elif not all(isinstance(item, str) for item in d.keys()): raise TypeError('All keys must be strings') elif not all(isinstance(d[item], str) for item in d.keys()): raise TypeError('All mapped values must be strings') else: return True except: print('Input: {}'.format(convertObjToStr(d))) raise def prepareMultilineMarkdownForDisplay(markdown): # split each line of input markdown into items in a list md_lines = markdown.splitlines() # strip each line of whitespace md_lines_stripped = list(map(lambda x: x.strip(), md_lines)) # add trailing spaces and newline char between lines when joining back together markdown_prepared = ' \n'.join(md_lines_stripped) # return prepared markdown return markdown_prepared def displayMarkdown(markdown): # display the prepared markdown as formatted text display(Markdown(markdown)) def convertToType(value, datatype): try: # special case: string to bool if (datatype is bool) and isinstance(value,str): if value.strip()[0].upper() in ['T', 'Y']: return True elif value.strip()[0].upper() in ['F', 'N']: return False # general case return datatype(value) except Exception as e: msg = "Unable to convert {} value to data type {}: {}\n>> {}"\ .format(type(value), datatype, value, e) print(msg) raise
    Python
    UTF-8
    854
    2.5625
    3
    []
    no_license
    # data from: # LIGO open science center # www.gw-openscience.org/GW150914data/LOSC_Event_tutorial_GW150914.html import numpy as np import matplotlib.pyplot as plt from matplotlib.mlab import psd from matplotlib import rc data = [np.loadtxt('H-H1_LOSC_4_V2-1126259446-32.txt'), np.loadtxt('L-L1_LOSC_4_V2-1126259446-32.txt') + 1.e-18] label = ['Hanford', 'Livingston'] color = ['b', 'g'] fs = 4096 N = len(data[0]) plt.figure(figsize=(6.4, 6)) rc('text', usetex=True) for (i,h) in enumerate(data): (S,f) = psd(h, Fs=fs, NFFT=N//8) plt.subplot(2,1,i+1) plt.axis([20, 2000, 5e-23, 5e-18]) plt.loglog(f, np.sqrt(fs*S/2), color[i], label=label[i], lw=1) plt.legend() plt.ylabel(r'$\sqrt{f_{\rm c}\, S(f)}$', fontsize=14) plt.xlabel('frequency / Hz', fontsize=14) plt.tight_layout() plt.savefig('fig2.eps') plt.show()
    Markdown
    UTF-8
    9,289
    2.984375
    3
    []
    no_license
    # Introduction Ce document a pour but de vous expliquer en 5 minutes de lecture (et 5 autres de "digestion" ;) ) tout ce que vous devez savoir sur le XML et le XPATH utilisé par le Référentiel législatif de l'AN et les données en "OpenData" qui en sont issues. Vous en saurez assez pour comprendre tout le XML et effectuer les requêtes XPATH vous permettant d'exploiter les données de l'OpenData. XML et XPath sont des technologies riches et si vous voulez devenir un maitre Jedi dans ces matières vous devrez vous tourner vers d'autres sources d'information en ligne. Cela ne devrait pas être nécessaire pour exploiter l'OpenData de l'Assemnblée nationale cependant. # XML Le XML se présente comme un format textuel dont voici un exemple. Ce fichier XML serra la base de tous nos exemples subséquents. ```XML <export xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <organes> <organe xsi:type="OrganeParlementaire_Type"> <uid>PO711218</uid> <codeType>MISINFO</codeType> <libelle>Formation des enseignants</libelle> <viMoDe> <dateDebut>2015-12-16</dateDebut> <dateAgrement xsi:nil="true"/> <dateFin>2016-10-05</dateFin> </viMoDe> <legislature>14</legislature> <secretariat> <secretaire xsi:nil="true"/> <secretaire xsi:nil="true"/> </secretariat> </organe> <organe xsi:type="OrganeParlementaire_Type"> <uid>PO714518</uid> <codeType>ASSEMBLEE</codeType> <libelle>Assemble nationale</libelle> <viMoDe> <dateDebut>2016-12-16</dateDebut> <dateAgrement xsi:nil="true"/> <dateFin>2018-10-05</dateFin> </viMoDe> <legislature>14</legislature> <secretariat> <secretaire xsi:nil="true"/> <secretaire xsi:nil="true"/> </secretariat> </organe> </organes> <acteurs> <acteur> <uid>PA3445</uid> <etatCivil> <ident> <nom>jean</nom> <prenom>valjean</prenom> </ident> </etatCivil> <mandats> <mandat> <uid>PM3455</uid> <typeorgane>Assemblee</typeorgane> <acteurRef>PA3445</acteurRef> </mandat> </mandats> </acteur> </acteurs> </export> ``` ## L'essentiel ### Arbre un document XML est un arbre (il y a une "racine", unique, des "branches" et des "feuilles") de "noeuds". ces noeuds peuvent être de deux grands types : Les `Eléménts` et les `Attributs` (il y a d'autres tpes possibles mais vous ne les rencontrerez pas explicitement dans nos documents.) ## Balise * Une balise est une chaine de charactère quelconque ('acteur', 'organe', 'ratatouille', 'poix123') * Une balise peut être ouvrante comprise entre les symboles < et > (<acteur> <organe> etc ...) ou fermante, comprise entre les caractères < et /> (<acteur/>, <organe/>). * Une balise peut enfin être "vide" ouvrante et fermante, comme ceci <acteur/> * Toute balise ouvrante doit être assoiciée à une balise fermante (ou être une balise vide, ouvrante et fermante à la fois) * Enfin, Les balises peuvent et doivent être imbriquée mais jamais se "chevaucher". Exemple : ```xml <racine> <acteur><vide/></acteur> <mandats></mandats> </racine> ``` Mais jamais : ```xml <racine> <acteur> <mandats> </acteur> </mandats> </racine> ``` ### élément Un élément est la réunion d'une balise ouvrante et fermante et de tout ce qui se trouve entre. Par exemple : ```xml <secretariat> <secretaire xsi:nil="true"/> <secretaire xsi:nil="true"/> </secretariat> ``` L'élément `secretariat` contient deux autres éléments `secretaire` ### Attribut ## Concepts "avancés" Ces concepts sont inutiles pour comprenndre les données de l'Open Data mais vous en aurez besoin pour des usages avancés des données avec des outils sophisitiqués. ### Namespace ### schémas # XPath ## L'essentiel XPath est un langage de requếtage sur des documents au format XML. C'est à dire qu'une expression XPath appliqué à un document XML retourne entre zéro et `n` noeuds (éléments ou attributs). Une expression XPath simplement décrit le "chemin" pour accéder aux noeuds qu'elle souhaite récupérer, comme ceci : ```/export/organes/organe``` ou ```./organe``` Le résultat de l'expression XPath est l'ensemble des noeuds qui satisfont à l'expression. La façon la plus simple d'apréhender une expression XPath est de la considérer comme un 'chemin' sélectionnant les noeuds correspondant au parcours de ce chemin depuils le point d'évaluation. L'expression `/export/organes` limite ces noeuds aux fils de l'élément `Organes` eux même fils de la racine du document `export`. Elle exprime ceci "retournez moi les noeuds appelés `organe`, fils d'un élément `organes` lui même fils de l'élément racine (`export`). Les seuls noeud correspondants sont les deux éléments `organe` fils de `organes`, ce sont eux qui serront retournés, intégralement (avec leurs fils et tout leur contenu). L'expression `./organe` retourne les noeuds `organe` fils `/` du noeud courant `.`. En traduction pas à pas "du noeud ou vous êtes retournez moi les éléments fils de nom `organe`) Son résultat dépend donc de l'endroit du fichier XML où elle est évaluée. * Evaluée à la racine (`<export>`) cette expression ne retourne **rien** : Il n'y a pas d'élément `organe` fils de la racine (`<export>`). * Evaluée sur l'élément `organes` elle retourne le même résultat que l'expression précédente :les deux éléments `organe` du document exemple qui sont bien fils directs de l'élément `organes`. Mais peut-être voulez vous seulement le *premier* élément organe ? ```/export/organes/organe[1]``` ou le second ```/export/organes/organe[2]``` Vous pourriez aussi vouloir récupérer **tous** les éléments `organe`, peut importe où ils sont placés dans l'arborescence : ```//organe``` le symbole `//` veut dire 'n'importe où en dessous', fils direct, petit fils, petit petit fils, etc ... ## Un peu plus et ce sera assez ... ### Selecteur Dans l'exemple ```/export/organes/organe[1]``` l'expression entre crochets ```[]``` est un selecteur. Un sélecteur réduit le nombre de noeuds capturés par l'expression en posant une contrainte, un critère, un test sur les noeuds à cet endroit de l'expression. Un simple nombre `n` indique de sélectionner le noeud de rang `n`, mais il est possible de construire des expressions plus puissantes. ```/export/organes/organe[uid="PO714518"]``` Sélectionne uniquement l'organe fils direct de ```/export/organes/``` possédant un fils `uid` de valeur "PO714518" si il existe. Dans notre exemple il en existe un, le second. ```/export/organes/organe[.//dateDebut>"2016-01-01"]``` Sélectionne les organes fils de ```/export/organes/``` ayant un sous élément `dateDebut` postérieur au 1er janvier 2016. Vous l'aurez remarqué l'expression de sélection est "enracinée" par défaut i.e. évaluée au point courant de l'expression, dans notre cas ```/export/organes/```, et nous pouvons utiliser la notation `//` pour sélectionner n'importe quel élément descendant `dateDebut` à partir ce ce point. En l'occurence l'élément date début est en fait situé en `./viMoDe/dateDebut` et nous aurious pu écrire l'expression comme ceci : ```/export/organes/organe[./viMoDe/dateDebut > "2016-01-01"]``` L'expression 'sélecteur' peut être n'importe quelle expression XPath valide qui traduit une condition booléenne. ## Any Le symbole `*` représente n'importe quel élément. Ainsi l'expression : ```//*[uid="PO714518"]``` représente n'importe quel élément possédant un fils direct `uid` de valeur `PO714518` =>un organe dans notre exemple : ```xml <organe xsi:type="OrganeParlementaire_Type"> <uid>PO714518</uid> <codeType>ASSEMBLEE</codeType> ... ``` ```/*[uid="PO714518"]``` représente n'importe quel élément racine possédant un fils direct `uid` de valeur `PO714518` => aucun dans notre exemple ```//*[uid="PO714518"]``` représente n'importe quel élément racine possédant un descendant `uid` de valeur `PO714518` => le document racine 'export' en entier dans notre exemple ### Filtrer sur un attribut, xsi:nil ... Enfin, pour tester la valeur d'un attribut il faut utiliser l'opérateur `@` ```//organe[@xsi:type="OrganeParlementaire_Type"]``` sélectionne tous les organes ayant un attribut xsi:type de valeur "OrganeParlementaire_Type" => dans notre cas les deux éléments organes répondent à ce critère. ```//*[@xsi:nil="true"]``` ... retournera les 4 éléments `<secretaire>` **et** deux élémens `<dateAgrement>` dans notre exemple... vous devriez comprendre pourquoi à présent ;) L'expression : ```//secretaire[@xsi:nil="true"]``` ne retournerait, elle, que les 4 éléments `<secretaire>` # Et en Python ? lxml et co ...
    Python
    UTF-8
    1,073
    3.765625
    4
    []
    no_license
    def maxi(*l): if len(l) == 0: return 0 m = l[0] for ix in range(1, len(l)): if l[ix] > m: m = l[ix] return m def mini(*l): if len(l) == 0: return 0 m = l[0] for ix in range(1, len(l)): if l[ix] < m: m = l[ix] return m def media(*l): if len(l) == 0: return 0 suma = 0 for valor in l: suma += valor return suma / len(l) funciones = { "max": maxi, "min": mini, "med": media } def returnF(nombre): nombre = nombre.lower() if nombre in funciones.keys(): return funciones[nombre] return None # A continuación la función returnF devolverá el nombre de otra función. print(returnF("max")) # Si quiero que la función "max" se ejecute a través de la función "returnF" escribiré lo siguiente: print(returnF("max")(1, 3, -1, 15, 9)) # Si quiero que la función "min" se ejecute a través de la función "returnF" escribiré lo siguiente: print(returnF("min")(1, 3, -1, 15, 9)) # Si quiero que la función "med" se ejecute a través de la función "returnF" escribiré lo siguiente: print(returnF("med")(1, 3, -1, 15, 9))
    C
    UTF-8
    1,209
    2.875
    3
    []
    no_license
    #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <time.h> #include <signal.h> #include <sys/wait.h> #include <sys/types.h> #include <unistd.h> #include "jjp_lib.h" int flag_18; void fSIGSTP(int signum) { if(flag_18==0) { flag_18=1; sigset_t mask; sigfillset(&mask); sigdelset(&mask, SIGTSTP); printf("\n\nWaiting for:\n\tCtrl+Z - resume\n\tCtrl+C - exit\n"); sigsuspend(&mask); } else { flag_18=0; printf("\n\n"); } } void fSIGINT() { printf("\n\nProgram received signal SIGINT(2). Exiting...\n\n"); exit(0); } int main(int argc, char** argv) { flag_18=0; struct sigaction sigint_action; sigint_action.sa_handler = fSIGINT; sigemptyset(&sigint_action.sa_mask); sigint_action.sa_flags = 0; signal(SIGTSTP, fSIGSTP); sigaction(SIGINT, &sigint_action, NULL); time_t timer; char buffer[26]; struct tm* tm_info; printf("\nPID:\t%d\n", getpid()); while(1) { sleep(1); time(&timer); tm_info = localtime(&timer); strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", tm_info); puts(buffer); } return 0; }
    Java
    UTF-8
    342
    2.421875
    2
    [ "Apache-2.0" ]
    permissive
    package base.components; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import base.model.Engine; @Component("car") public class Car { Engine engine; @Autowired public void setEngine(Engine engine){ this.engine = engine; System.out.println("car engine set"); } }
    Java
    UTF-8
    1,798
    3.765625
    4
    []
    no_license
    package lecture11; public class ArrayDeque<E> implements Deque<E> { private Object[] data; private int first, size; public ArrayDeque(int capacity) { this.data = new Object[capacity]; this.first = 0; this.size = 0; } @Override public void addFirst(E e) { if (this.size == this.data.length) this.resize(this.data.length * 2); this.first = (this.first + this.data.length - 1) % this.data.length; this.data[this.first] = e; this.size++; } @Override public void addLast(E e) { if (this.size == this.data.length) this.resize(this.data.length * 2); int nextAvailable = (this.first + this.size) % this.data.length; this.data[nextAvailable] = e; this.size++; } @Override public E removeFirst() { if (this.isEmpty()) throw new IllegalStateException("Deque is empty"); E val = (E) this.data[this.first]; this.data[this.first] = null; this.first = (this.first + 1) % this.data.length; this.size--; return val; } @Override public E removeLast() { if (this.isEmpty()) throw new IllegalStateException("Deque is empty"); int last = (this.first + this.size - 1) % this.data.length; E val = (E) this.data[last]; this.data[last] = null; this.size--; return val; } @Override public E first() { return (E) this.data[this.first]; } @Override public E last() { int last = (this.first + this.size - 1) % this.data.length; return (E) this.data[last]; } @Override public int size() { return this.size; } @Override public boolean isEmpty() { return this.size == 0; } private void resize(int newSize) { Object[] larger = new Object[newSize]; for (int i = 0; i < this.size; i++) { int j = (this.first + i) % this.data.length; larger[i] = this.data[j]; } this.data = larger; this.first = 0; } }
    C#
    UTF-8
    3,875
    2.65625
    3
    [ "MIT" ]
    permissive
    using System; using Skybrud.Social.Sonos.Endpoints; using Skybrud.Social.Sonos.OAuth; namespace Skybrud.Social.Sonos { /// <summary> /// Class working as an entry point to the Sonos API. /// </summary> public class SonosService { #region Properties /// <summary> /// Gets a reference to the internal OAuth client. /// </summary> public SonosOAuthClient Client { get; } /// <summary> /// Gets a reference to the <strong>groups</strong> endpoint. /// </summary> public SonosGroupsEndpoint Groups { get; } /// <summary> /// Gets a reference to the <strong>households</strong> endpoint. /// </summary> public SonosHouseholdsEndpoint Households { get; } /// <summary> /// Gets a reference to the <strong>players</strong> endpoint. /// </summary> public SonosPlayersEndpoint Players { get; } #endregion #region Constructors private SonosService(SonosOAuthClient client) { Client = client; Groups = new SonosGroupsEndpoint(this); Households = new SonosHouseholdsEndpoint(this); Players = new SonosPlayersEndpoint(this); } #endregion #region Static methods /// <summary> /// Initialize a new service instance from the specified OAuth <paramref name="client"/>. /// </summary> /// <param name="client">The OAuth client.</param> /// <returns>The created instance of <see cref="SonosService" />.</returns> public static SonosService CreateFromOAuthClient(SonosOAuthClient client) { if (client == null) throw new ArgumentNullException(nameof(client)); return new SonosService(client); } /// <summary> /// Initializes a new service instance from the specifie OAuth 2 <paramref name="accessToken"/>. /// </summary> /// <param name="accessToken">The access token.</param> /// <returns>The created instance of <see cref="SonosService" />.</returns> public static SonosService CreateFromAccessToken(string accessToken) { if (String.IsNullOrWhiteSpace(accessToken)) throw new ArgumentNullException(nameof(accessToken)); return new SonosService(new SonosOAuthClient(accessToken)); } ///// <summary> ///// Initializes a new instance based on the specified <paramref name="refreshToken"/>. ///// </summary> ///// <param name="clientId">The client ID.</param> ///// <param name="clientSecret">The client secret.</param> ///// <param name="refreshToken">The refresh token of the user.</param> ///// <returns>The created instance of <see cref="Skybrud.Social.Sonos.SonosService" />.</returns> //public static SonosService CreateFromRefreshToken(string clientId, string clientSecret, string refreshToken) { // if (String.IsNullOrWhiteSpace(clientId)) throw new ArgumentNullException(nameof(clientId)); // if (String.IsNullOrWhiteSpace(clientSecret)) throw new ArgumentNullException(nameof(clientSecret)); // if (String.IsNullOrWhiteSpace(refreshToken)) throw new ArgumentNullException(nameof(refreshToken)); // // Initialize a new OAuth client // SonosOAuthClient client = new SonosOAuthClient(clientId, clientSecret); // // Get an access token from the refresh token. // SonosTokenResponse response = client.GetAccessTokenFromRefreshToken(refreshToken); // // Update the OAuth client with the access token // client.AccessToken = response.Body.AccessToken; // // Initialize a new service instance // return new SonosService(client); //} #endregion } }
    Python
    UTF-8
    341
    2.71875
    3
    []
    no_license
    class Solution: def isHappy(self, n: int) -> bool: ht = dict() while n: if 1 in ht: return True if n in ht: return False ht[n] = 0 tmp = 0 while n: tmp += (n%10) ** 2 n //= 10 n = tmp
    Java
    UTF-8
    2,456
    1.820313
    2
    [ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
    permissive
    /* * Copyright © 2012-2014 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package co.cask.tephra.persist; import co.cask.tephra.TxConstants; import co.cask.tephra.metrics.TxMetricsCollector; import co.cask.tephra.snapshot.SnapshotCodecProvider; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.rules.TemporaryFolder; import java.io.IOException; /** * Tests persistence of transaction snapshots and write-ahead logs to HDFS storage, using the * {@link HDFSTransactionStateStorage} and {@link HDFSTransactionLog} implementations. */ public class HDFSTransactionStateStorageTest extends AbstractTransactionStateStorageTest { @ClassRule public static TemporaryFolder tmpFolder = new TemporaryFolder(); private static MiniDFSCluster dfsCluster; private static Configuration conf; @BeforeClass public static void setupBeforeClass() throws Exception { Configuration hConf = new Configuration(); hConf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, tmpFolder.newFolder().getAbsolutePath()); dfsCluster = new MiniDFSCluster.Builder(hConf).numDataNodes(1).build(); conf = new Configuration(dfsCluster.getFileSystem().getConf()); } @AfterClass public static void tearDownAfterClass() throws Exception { dfsCluster.shutdown(); } @Override protected Configuration getConfiguration(String testName) throws IOException { // tests should use the current user for HDFS conf.unset(TxConstants.Manager.CFG_TX_HDFS_USER); conf.set(TxConstants.Manager.CFG_TX_SNAPSHOT_DIR, tmpFolder.newFolder().getAbsolutePath()); return conf; } @Override protected AbstractTransactionStateStorage getStorage(Configuration conf) { return new HDFSTransactionStateStorage(conf, new SnapshotCodecProvider(conf), new TxMetricsCollector()); } }
    C
    ISO-8859-1
    1,805
    2.765625
    3
    []
    no_license
    /* * Projeto: Teclado e Display 1 * Arquivo: App.c * Autor: JABNeto * Data: 10/02/2016 */ #include <stdio.h> #include <stdlib.h> #include <xc.h> #include "Base_1.h" #include "Oscilador.h" //Prottipos das funes ----------------------------- void Timer0_Inicializacao (void); void Timer0_Recarga (void); //Alocao de memria para o mdulo------------------- Ulong Contador; struct { Uchar Temporizador100ms; union { Uchar Valor; struct { Uchar Contador:1; }; }EventosDe100ms; }TMR0_Eventos; //Funes do mdulo ---------------------------------- int main(int argc, char** argv) { Oscilador_Inicializacao(); Display_InicializaVarredura(); Timer0_Inicializacao(); Contador = 0; Varredura.Opcoes.OmiteZeros = _SIM; Varredura.Opcoes.ExibePonto5 = _SIM; Display_ExibeNumero(Contador); INTCONbits.GIEH = 1; while(1) { if(TMR0_Eventos.EventosDe100ms.Contador == 1) { TMR0_Eventos.EventosDe100ms.Contador = 0; if (++Contador == 10000) Contador = 0; Display_ExibeNumero(Contador); } } return (EXIT_SUCCESS); } /* Interrupt_High * Atendimento das interrupes de alta prioridade */ void interrupt high_priority Interrupt_High(void) { if ((INTCONbits.TMR0IE == 1) && (INTCONbits.TMR0IF == 1)) { Timer0_Recarga(); if(--TMR0_Eventos.Temporizador100ms == 0) { TMR0_Eventos.Temporizador100ms = 100; TMR0_Eventos.EventosDe100ms.Valor = 0xFF; } //Funes do usurio ------------------------- Display_ExecutaVarredura(); } }
    Python
    UTF-8
    570
    3.234375
    3
    []
    no_license
    # -*- coding: utf-8 -*- import time import math import numpy as np x = [i for i in xrange(1000 * 1000)] start = time.clock() for i, t in enumerate(x): x[i] = math.sin(t) print "math.sin:", time.clock() - start x = [i for i in xrange(1000 * 1000)] x = np.array(x) start = time.clock() np.sin(x, x) print "numpy.sin:", time.clock() - start x = np.arange(1, 4) y = np.arange(2, 5) print np.add(x, y) print np.subtract(y, x) print np.multiply(x, y) print np.divide(y, x) print np.true_divide(y, x) print np.floor_divide(y, x)
    Python
    UTF-8
    804
    2.59375
    3
    []
    no_license
    # connect # close # dinh nghia class db # co self , nam, usr., host, db_password, 4 thong so # """"db_host = localhost # db_user = root # db_name = cdcol # db_password = root # """ import MySQLdb import ConfigLoader class Database(object): """docstring for Database""" def __init__(self, host, user, db, password): self.host = raw_input("Nhap Ten host :") self.user = raw_input("Nhap Ten User :") self.db = raw_input("Nhap Ten Database :") self.password = raw_input("Nhap Password :") def connect(): con = MySQLdb.connect(self.host,self.user,self.db,self.password) cur = con.cursor() # dung con tro de lam viec vs DB cur.execute("SELECT VERSION()") row = cursor.fetchall() print "server version",row[0] cursor.close() con.close() if __name__ == '__main__': main()
    Java
    UTF-8
    2,027
    2.875
    3
    []
    no_license
    package com.finago.interview.fileProcessor; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import javax.xml.parsers.ParserConfigurationException; import com.finago.interview.task.Constants; /** * * @author Ajay Naik File Processor Usage : This class will validate the xml * with xsd , read xml if the validation is successful move all xml to * archive location and delete all pdf */ public class FileProcessor { /** * This class will validate the xml with xsd read xml if the validation is * successful. if validation is successfull perform the logic as given if * validation is not successful move the files to error location * * * @throws ParserConfigurationException */ /** * * Main method method to process the xml * * @param xmlString * @throws ParserConfigurationException */ public static void process(String xmlString) throws ParserConfigurationException { if (FileUtility.fileExists(xmlString)) { if (new XMLValidator().validate(xmlString, Constants.XSDFILEPATH)) { System.out.println("validation is successful and Processing File start " + xmlString); XMLReader.readANDProcessXML(xmlString); System.out.println("validation is successful and Processing File end " + xmlString); } else { try { if (FileUtility.fileExists(xmlString)) { System.out.println( xmlString + " validation is un-successful and moving the file to error location "); Files.move(Paths.get(xmlString), Paths.get(Constants.XMLERRORFOLDER + Paths.get(xmlString).getFileName().toString()), StandardCopyOption.REPLACE_EXISTING); } } catch (IOException e) { // TODO Auto-generated catch block System.out.println("Processing fail for xml "+ xmlString); e.printStackTrace(); } } }else { System.out.println(xmlString + " File doesn't exists"); } } }
    Python
    UTF-8
    385
    3.9375
    4
    []
    no_license
    #Multi line printing versions #You can print with defining it into variable then print variable message = """This message will span several lines.""" print(message) #Or you can write you multi line printing into directly print function print("""This message will span several lines of the text.""") # Different String versions print('This is a string.') print("""And so is this.""")
    Java
    UTF-8
    6,933
    2.234375
    2
    []
    no_license
    package com.ravisravan.capstone.UI; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import com.ravisravan.capstone.R; import com.ravisravan.capstone.UI.adapters.RemindersAdapter; import com.ravisravan.capstone.data.ReminderContract; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link AllEventsFragment.Callback} interface * to handle interaction events. */ public class AllEventsFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { private final int REMINDERS_LOADER = 200; private RecyclerView recyclerview_reminders; private RemindersAdapter mRemindersAdapter; private Callback mListener; public AllEventsFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootview = inflater.inflate(R.layout.fragment_all_events, container, false); recyclerview_reminders = (RecyclerView) rootview.findViewById(R.id.recyclerview_reminders); //TODO: configure the spancount in integers and use recyclerview_reminders.setLayoutManager(new GridLayoutManager(getActivity(), 1)); View emptyView = rootview.findViewById(R.id.recyclerview_reminders_empty); mRemindersAdapter = new RemindersAdapter(getActivity(), emptyView, new RemindersAdapter.ReminderAdapterOnClickHandler() { @Override public void onClick(Long id, RemindersAdapter.ReminderViewHolder vh) { ((Callback) getActivity()) .onItemSelected(ReminderContract.Reminders.buildReminderUri(id), vh); } }); recyclerview_reminders.setAdapter(mRemindersAdapter); // use this setting to improve performance if you know that changes // in content do not change the layout size of the RecyclerView recyclerview_reminders.setHasFixedSize(true); return rootview; } @Override public void onActivityCreated(Bundle savedInstanceState) { // we hold for transition here just in case the activity // needs to be recreated. In a standard return transition, // this doesn't actually make a difference. //TODO: transitions // if (mHoldForTransition) { // getActivity().supportPostponeEnterTransition(); // } getLoaderManager().initLoader(REMINDERS_LOADER, null, this); super.onActivityCreated(savedInstanceState); } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof Callback) { mListener = (Callback) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { //1 is active 0 is inactive return new CursorLoader(getActivity(), ReminderContract.Reminders.CONTENT_URI, null, ReminderContract.Reminders.COLUMN_STATE + " = ?", new String[]{"1"}, ReminderContract.Reminders.COLUMN_CREATED_DATE); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { mRemindersAdapter.swapCursor(data); recyclerview_reminders.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { // Since we know we're going to get items, we keep the listener around until // we see Children. recyclerview_reminders.getViewTreeObserver().removeOnPreDrawListener(this); if (recyclerview_reminders.getChildCount() > 0) { int position = 0; // if (position == RecyclerView.NO_POSITION && // -1 != mInitialSelectedMessage) { // Cursor data = mMessagesAdapter.getCursor(); // int count = data.getCount(); // int messageColumn = data.getColumnIndex(ReminderContract.MessageLkpTable._ID); // for (int i = 0; i < count; i++) { // data.moveToPosition(i); // if (data.getLong(messageColumn) == mInitialSelectedMessage) { // position = i; // break; // } // } // } //if (position == RecyclerView.NO_POSITION) position = 0; // If we don't need to restart the loader, and there's a desired position to restore // to, do so now. recyclerview_reminders.smoothScrollToPosition(position); RecyclerView.ViewHolder vh = recyclerview_reminders.findViewHolderForAdapterPosition(position); // if (null != vh) { // mRemindersAdapter.selectView(vh); // } return true; } else { } return false; } }); } @Override public void onLoaderReset(Loader<Cursor> loader) { mRemindersAdapter.swapCursor(null); } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface Callback { /** * ViewReminder for when an item has been selected. */ public void onItemSelected(Uri uri, RemindersAdapter.ReminderViewHolder vh); } }
    Markdown
    UTF-8
    5,800
    2.578125
    3
    []
    no_license
    # circos-utilities Utility scripts for working with Circos. # The scripts * UCSC_chrom_sizes_2_circos_karyotype.py > UCSC chrom.sizes files --> karyotype.tab file for use in Circos Takes a URL for a UCSC `chrom.sizes` file and makes a `karyotype.tab` file from it for use with Circos. Verified compatible with both Python 2.7 and Python 3.6. Written to run from command line or pasted/loaded/imported inside a Jupyter notebook cell. The main ways to run the script are demonstrated in the notebook [`demo UCSC_chrom_sizes_2_circos_karyotype script.ipynb`](https://github.com/fomightez/sequencework/blob/master/circos-utilities/demo%20UCSC_chrom_sizes_2_circos_karyotype%20script.ipynb) that is included in this repository. (That notebook can be viewed in a nicer rendering [here](https://nbviewer.jupyter.org/github/fomightez/sequencework/blob/master/circos-utilities/demo%20UCSC_chrom_sizes_2_circos_karyotype%20script.ipynb).) To determine the URL to feed the script, google `YOUR_ORGANISM genome UCSC chrom.sizes`, where you replace `YOUR_ORGANISM` with your organism name and then adapt the path you see in the best match to be something similar to `http://hgdownload.cse.ucsc.edu/goldenPath/sacCer3/bigZips/sacCer3.chrom.sizes` -or- `http://hgdownload.cse.ucsc.edu/goldenPath/canFam2/bigZips/canFam2.chrom.sizes`. You can get an idea of what is available by exploring the top section [here](http://hgdownload.cse.ucsc.edu/downloads.html); clicking on the arrows creates drop-down lists reveal many genomes for each category. Importantly, this script is intended for organisms without cytogenetic bands, such as dog, cow, yeast, etc.. (For organisms with cytogenetic band data: Acquiring the cytogenetic bands information is described [here](http://circos.ca/tutorials/lessons/ideograms/karyotypes/), about halfway down the page where it says, "obtain the karyotype structure from...". Unfortunately, it seems the output to which one is directed to by those instructions is not directly useful in Circos(?). Fortunately, though as described [here](http://circos.ca/documentation/tutorials/quick_start/hello_world/), "Circos ships with several predefined karyotype files for common sequence assemblies: human, mouse, rat, and drosophila. These files are located in data/karyotype within the Circos distribution." And also included there is a script for converting the cytogenetic band data to karyotype, see [here](http://circos.ca/documentation/tutorials/quick_start/hello_world/) and [here](https://groups.google.com/d/msg/circos-data-visualization/B55NlByQ6jY/nKWGSPsXCwAJ).) Example call to run script from command line: ``` python UCSC_chrom_sizes_2_circos_karyotype.py http://hgdownload.cse.ucsc.edu/goldenPath/sacCer3/bigZips/sacCer3.chrom.sizes ``` (Alternatively, upload the script to a Jupyter environment and use `%run UCSC_chrom_sizes_2_circos_karyotype.py http://hgdownload.cse.ucsc.edu/goldenPath/sacCer3/bigZips/sacCer3.chrom.sizes` in a Python-backed notebook to run the example.) Example input from http://hgdownload.cse.ucsc.edu/goldenPath/sacCer3/bigZips/sacCer3.chrom.sizes : ``` chrIV 1531933 chrXV 1091291 chrVII 1090940 chrXII 1078177 chrXVI 948066 chrXIII 924431 chrII 813184 chrXIV 784333 chrX 745751 chrXI 666816 chrV 576874 chrVIII 562643 chrIX 439888 chrIII 316620 chrVI 270161 chrI 230218 chrM 85779 ``` Example output sent to file (tab-separated): ``` chr - Sc-chrIV chrIV 0 1531933 black chr - Sc-chrXV chrXV 0 1091291 black chr - Sc-chrVII chrVII 0 1090940 black chr - Sc-chrXII chrXII 0 1078177 black chr - Sc-chrXVI chrXVI 0 948066 black chr - Sc-chrXIII chrXIII 0 924431 black chr - Sc-chrII chrII 0 813184 black chr - Sc-chrXIV chrXIV 0 784333 black chr - Sc-chrX chrX 0 745751 black chr - Sc-chrXI chrXI 0 666816 black chr - Sc-chrV chrV 0 576874 black chr - Sc-chrVIII chrVIII 0 562643 black chr - Sc-chrIX chrIX 0 439888 black chr - Sc-chrIII chrIII 0 316620 black chr - Sc-chrVI chrVI 0 270161 black chr - Sc-chrI chrI 0 230218 black chr - Sc-chrM chrM 0 85779 black ``` #### For running in a Jupyter notebook: To use this script after pasting or loading into a cell in a Jupyter notebook, in the next cell define the URL and then call the main function similar to below: ``` url = "http://hgdownload.cse.ucsc.edu/goldenPath/sacCer3/bigZips/sacCer3.chrom.sizes" species_code = "Ys" UCSC_chrom_sizes_2_circos_karyotype(url, species_code) ``` -or- ``` UCSC_chrom_sizes_2_circos_karyotype(url) ``` Without supplying a second argument, a species code will be extracted automatically and used. Note that `url` is actually not needed if you are using the yeast one because that specific one is hardcoded in script as default. In fact, because I hardcoded in defaults, just `main()` will indeed work for yeast after script pasted in or loaded into a cell. See [here](https://nbviewer.jupyter.org/github/fomightez/sequencework/blob/master/circos-utilities/demo%20UCSC_chrom_sizes_2_circos_karyotype%20script.ipynb) for a notebook demonstrating use within a Jupyter notebook. Related ------- - [circos-binder](https://github.com/fomightez/circos-binder) - for running Circos in your browser without need for downloads, installations, or maintenance. - [gos: (epi)genomic visualization in python](https://gosling-lang.github.io/gos/) looks to circos-like images, see that page in the link for representative examples in the image at the top. [The Example Gallery](https://gosling-lang.github.io/gos/gallery/index.html) has a link to a Circos-style example under the 'Others' heading; it includes code [here](https://gosling-lang.github.io/gos/gallery/circos.html).
    Java
    UTF-8
    11,306
    3.046875
    3
    []
    no_license
    import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * in this class we design the interface of our calculator. * * @author Mahdi Hejarti 9723100 * @since 2020.04.23 */ public class View { private JFrame calFrame; private JPanel standardMode; private JPanel scientificMode; private JButton[] buttons1; private JButton[] buttons2; private JTextArea display1; private JTextArea display2; private Controller controller; /** * constructor of View class */ public View() { Handler handler = new Handler(); controller = new Controller(); // create main frame calFrame = new JFrame(); designCalculatorFrame(); // add a tab to frame to change mode JTabbedPane modeTabbedPane = new JTabbedPane(); calFrame.setContentPane(modeTabbedPane); // add a panel to tabbedPane for standard mode standardMode = new JPanel(); standardMode.setLayout(new BorderLayout(5, 5)); modeTabbedPane.add("Standard View", standardMode); // add a panel to tabbedPane for scientific mode scientificMode = new JPanel(); scientificMode.setLayout(new BorderLayout(5, 5)); modeTabbedPane.add("Scientific View", scientificMode); // create keys and add them to panels buttons1 = new JButton[20]; AddStandardKey(buttons1); buttons2 = new JButton[30]; AddScientificKey(buttons2); // add action listener to buttons for (JButton button : buttons2) { button.addActionListener(handler); button.addKeyListener(new KeyLis()); } // add display part to panels addFirstDisplay(); addSecondDisplay(); // create menu bar JMenuBar menuBar = new JMenuBar(); // create file menu JMenu mainMenu = new JMenu("Menu"); mainMenu.setMnemonic('N'); // create exit item JMenuItem exitItem = new JMenuItem("Exit"); exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.ALT_MASK)); exitItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { System.exit(0); } }); // create copy item JMenuItem copyItem = new JMenuItem("Copy"); copyItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK)); copyItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { controller.setCopiedText(display2, display1); } }); // create about item JMenuItem aboutItem = new JMenuItem("About"); aboutItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK)); aboutItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { JOptionPane.showMessageDialog(null, "Mahdi Hejrati \n9723100 \n", "About", JOptionPane.INFORMATION_MESSAGE); } }); // add menu mainMenu.add(exitItem); mainMenu.add(copyItem); mainMenu.add(aboutItem); menuBar.add(mainMenu); calFrame.setJMenuBar(menuBar); calFrame.addKeyListener(new KeyLis()); calFrame.requestFocusInWindow(); calFrame.setFocusable(true); } /** * design the main frame */ public void designCalculatorFrame() { calFrame.setTitle("My Calculator"); calFrame.setSize(430, 550); calFrame.setLocation(600, 230); calFrame.setMinimumSize(new Dimension(380, 350)); calFrame.setResizable(true); calFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } /** * create keys and add them to the center part of standardMode panel */ public void AddStandardKey(JButton[] buttons) { JPanel standardKeyboardPanel = new JPanel(); standardKeyboardPanel.setLayout(new GridLayout(5, 4)); standardMode.add(standardKeyboardPanel, BorderLayout.CENTER); String[] buttonText = {"%", "CE", "C", "/", "7", "8", "9", "*", "4", "5", "6", "-", "1", "2", "3", "+", "( )", "0", ".", "="}; // add properties to buttons for (int i = 0; i < 20; i++) { buttons[i] = new JButton(); buttons[i].setText(buttonText[i]); buttons[i].setBackground(new Color(50, 50, 50)); buttons[i].setForeground(Color.white); buttons[i].setOpaque(true); buttons[i].setToolTipText(buttonText[i]); buttons[i].setFont(buttons[i].getFont().deriveFont(16f)); standardKeyboardPanel.add(buttons[i]); } } /** * create keys and add them to the center part of scientificMode panel */ public void AddScientificKey(JButton[] buttons) { JPanel scientificKeyboardPanel = new JPanel(); scientificKeyboardPanel.setLayout(new GridLayout(5, 6)); scientificMode.add(scientificKeyboardPanel, BorderLayout.CENTER); String[] buttonText = {"PI", "%", "CE", "C", "/", "sin", "e", "7", "8", "9", "*", "tan", "^", "4", "5", "6", "-", "log", "!", "1", "2", "3", "+", "exp", "(", ")", "0", ".", "=", "shift"}; // add properties to buttons for (int i = 0; i < 30; i++) { buttons[i] = new JButton(); buttons[i].setText(buttonText[i]); buttons[i].setBackground(new Color(50, 50, 50)); buttons[i].setForeground(Color.white); buttons[i].setOpaque(true); buttons[i].setToolTipText(buttonText[i]); buttons[i].setFont(buttons[i].getFont().deriveFont(16f)); scientificKeyboardPanel.add(buttons[i]); } } /** * creat display part and add it to north part of standardMode panel */ public void addFirstDisplay() { display1 = new JTextArea(); makeDisplay(display1); JScrollPane scrollPane = new JScrollPane(display1); scrollPane.setPreferredSize(new Dimension(100, 90)); standardMode.add(scrollPane, BorderLayout.NORTH); } /** * creat display part and add it to north part of scientificMode panel */ public void addSecondDisplay() { display2 = new JTextArea(); makeDisplay(display2); JScrollPane scrollPane = new JScrollPane(display2); scrollPane.setPreferredSize(new Dimension(100, 90)); scientificMode.add(scrollPane, BorderLayout.NORTH); } /** * add properties to display * @param display */ void makeDisplay(JTextArea display) { display.setEditable(false); display.setForeground(Color.white); display.setBackground(new Color(100, 100, 100)); display.setFont(display.getFont().deriveFont(19f)); display.setToolTipText("text area to show operations"); } /** * set the frame visible to show */ public void setVisible() { calFrame.setVisible(true); } /** * inner class of button handler */ private class Handler implements ActionListener { @Override public void actionPerformed(ActionEvent e) { for (int i = 0; i < 29; i++) if (e.getSource().equals(buttons2[i])) { controller.clickButton(buttons2[i], i, display2); } if (e.getSource().equals(buttons2[29])) { controller.shift(buttons2); } } } /** * inner class of key handler */ private class KeyLis extends KeyAdapter { @Override public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_7: case KeyEvent.VK_NUMPAD7: controller.clickButton(buttons2[7], 7, display2); break; case KeyEvent.VK_8: case KeyEvent.VK_NUMPAD8: controller.clickButton(buttons2[8], 8, display2); break; case KeyEvent.VK_9: case KeyEvent.VK_NUMPAD9: controller.clickButton(buttons2[9], 9, display2); break; case KeyEvent.VK_4: case KeyEvent.VK_NUMPAD4: controller.clickButton(buttons2[13], 13, display2); break; case KeyEvent.VK_5: case KeyEvent.VK_NUMPAD5: controller.clickButton(buttons2[14], 14, display2); break; case KeyEvent.VK_6: case KeyEvent.VK_NUMPAD6: controller.clickButton(buttons2[15], 15, display2); break; case KeyEvent.VK_1: case KeyEvent.VK_NUMPAD1: controller.clickButton(buttons2[19], 19, display2); break; case KeyEvent.VK_2: case KeyEvent.VK_NUMPAD2: controller.clickButton(buttons2[20], 20, display2); break; case KeyEvent.VK_3: case KeyEvent.VK_NUMPAD3: controller.clickButton(buttons2[21], 21, display2); break; case KeyEvent.VK_0: case KeyEvent.VK_NUMPAD0: controller.clickButton(buttons2[26], 26, display2); break; case KeyEvent.VK_R: controller.clickButton(buttons2[1], 1, display2); break; case KeyEvent.VK_D: controller.clickButton(buttons2[4], 4, display2); break; case KeyEvent.VK_M: controller.clickButton(buttons2[10], 10, display2); break; case KeyEvent.VK_S: controller.clickButton(buttons2[16], 16, display2); break; case KeyEvent.VK_P: controller.clickButton(buttons2[22], 22, display2); break; case KeyEvent.VK_ENTER: controller.clickButton(buttons2[28], 28, display2); break; case KeyEvent.VK_BACK_SPACE: controller.clickButton(buttons2[3], 3, display2); break; case KeyEvent.VK_I: controller.clickButton(buttons2[5], 5, display2); break; case KeyEvent.VK_T: controller.clickButton(buttons2[11], 11, display2); break; case KeyEvent.VK_H: controller.shift(buttons2); break; } } } }
    C++
    UTF-8
    2,179
    3.015625
    3
    []
    no_license
    #include <iostream> #include <cstdlib> #include <ctime> #include <conio.h> using namespace std; template <typename T> void prove(T a); void fill_array(int** ary, const int N, const int M); void solution(int** ary, const int N, const int M); int main() { setlocale(LC_CTYPE, "rus"); srand(time(NULL)); int n, m, sum = 0; cout << "Введите n: "; cin >> n; prove(n); cout << "Введите m: "; cin >> m; prove(m); int** matrix = new int* [n]; for (int i = 0; i < n; i++) matrix[i] = new int[m]; fill_array(matrix, n, m); solution(matrix, n, m); cout << endl; for (int i = 0; i < n; i++) delete[] matrix[i]; delete[] matrix; system("pause"); return 0; } template <typename T> void prove(T a) { while (cin.fail()) { cin.clear(); cin.ignore(INT16_MAX, '\t'); cout << "Error\nВведите другое значение"; cin >> a; } } void fill_array(int** ary, const int N, const int M) { for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { cout << "array[" << i + 1 << "][" << j + 1 << "] = "; cin >> ary[i][j]; } cout << endl; } for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { printf("%5i", ary[i][j]); } cout << endl; } } void solution(int** ary, const int N, const int M) { bool col = true, row = true, p = true; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { col = true, row = true; for (int i1 = 0; i1 < N; i1++) if (ary[i][j] < ary[i1][j]) col = false; for (int j1 = 0; j1 < M; j1++) if (ary[i][j] > ary[i][j1]) row = false; if (row && col) { cout << '[' << i + 1 << "][" << j + 1 << ']' << '\t'; p = false; } col = true, row = true; for (int i1 = 0; i1 < N; i1++) if (ary[i][j] > ary[i1][j]) col = false; for (int j1 = 0; j1 < M; j1++) if (ary[i][j] < ary[i][j1]) row = false; if (row && col) { cout << '[' << i + 1 << "][" << j + 1 << ']' << '\t' << endl; p = false; } } } if (p) cout << "\nТаких элемениов нет\n"; }
    JavaScript
    UTF-8
    1,574
    3.578125
    4
    []
    no_license
    // PLEASE DON'T change function name module.exports = function makeExchange(currency) { // Your code goes here! // Return an object containing the minimum number of coins needed to make change currency = +currency; let remainderH = 0, remainderQ = 0, remainderD = 0, remainderN = 0, remainderP = 0; let answer = {}; if (currency > 10000){ answer = {error: "You are rich, my friend! We don't have so much coins for exchange"}; } else if(currency <= 0){ answer = {}; } else{ answer['H'] = Math.floor(currency / 50); if (answer['H'] > 0){ remainderH = currency - (answer['H'] * 50); } else{ remainderH = currency; delete answer['H']; } answer['Q'] = Math.floor(remainderH / 25); if (answer['Q'] > 0){ remainderQ = remainderH - (answer['Q'] * 25); } else{ remainderQ = remainderH; delete answer['Q']; } answer['D'] = Math.floor(remainderQ / 10); if (answer['D'] > 0){ remainderD = remainderQ - (answer['D'] * 10); } else{ remainderD = remainderQ; delete answer['D']; } answer['N'] = Math.floor(remainderD / 5); if (answer['N'] > 0){ remainderN = remainderD - (answer['N'] * 5); } else{ remainderN = remainderD; delete answer['N']; } if (remainderN > 0){ answer['P'] = remainderN; } } return answer; }
    Java
    UTF-8
    210
    1.882813
    2
    []
    no_license
    package base; import org.openqa.selenium.WebElement; public class PageElement { private WebElement webElement; private String elementType; private String elementName; int elementTimeout; }
    Markdown
    UTF-8
    424
    2.703125
    3
    []
    no_license
    Thank You for looking at my resume! If Markdown isn't your thing you can find links to other formats of the resume below: - [PDF](https://github.com/justgage/resume/raw/master/resume-in-many-formats/GageKPetersonsResume.pdf) - [Website (HTML)](http://justgage.github.io/resume/) - [Markdown](https://github.com/justgage/resume/blob/master/resume-in-many-formats/GageKPetersonsResume.md) (without comments at the top) ***
    Python
    UTF-8
    1,563
    3.3125
    3
    []
    no_license
    from itertools import cycle from player import Player from poker import Poker """ def bet_loop(poker): stay = poker.players fold = set() pool = cycle(stay) for p in pool: """ if __name__ == "__main__": p1 = Player('P1', 1000) p2 = Player('P2', 1000) p3 = Player('P3', 1000) poker = Poker() while True: poker.start_game() poker.register_player(p1) poker.register_player(p2) poker.register_player(p3) poker.deliver() print(p1) print(p2) print(p3) #bet_loop(poker) for i, p in enumerate(poker.players): if i == 0: poker.get_money(p.bet(50)) elif i == 1: poker.get_money(p.bet(100)) #print([str(p) for p in poker.players]) poker.fold_player(p2) poker.reveal_card() poker.reveal_card() poker.reveal_card() poker.reveal_card() poker.reveal_card() print('Table: {} / {}'.format([str(c) for c in poker.table_cards], poker.table_money)) win, score = poker.winner() print('Winner: ' + win.name + ' with ' + score) print([str(p) for p in poker.players]) control = input('Press any key to continue or q to quit:') if control.lower() == 'q': break #poker.unregister_player(p1) #poker.unregister_player(p2) #poker.unregister_player(p3) #print(poker.players)
    Rust
    UTF-8
    7,755
    3.71875
    4
    [ "BSD-2-Clause" ]
    permissive
    pub mod huffman { use std::boxed::Box; use std::cmp::Ordering; use std::collections::*; /// Node is a binary tree data structure. /// It will be used by huffman compression algorithm #[derive(Clone, PartialEq, Eq, Ord, std::fmt::Debug)] struct Node { letter: char, freq: i32, left: Option<Box<Node>>, right: Option<Box<Node>>, } impl PartialOrd for Node { fn partial_cmp(self: &Node, other: &Node) -> Option<Ordering> { let cmp = self.freq.cmp(&other.freq); Some(cmp.reverse()) // For min heap } } impl Node { /// A convinence function to create a leaf node, i.e a node with no children fn new(letter: char, freq: i32) -> Node { Node { letter, freq, left: None, right: None, } } } /// /// Count the frequency of chars, return a vector of node. /// /// Each node contains the character and corresponding frequency /// > Note: Algotithm is based on sorting /// fn freq_count(text: std::str::Chars) -> Vec<Node> { let mut freq_vec = Vec::new(); let mut chars: Vec<char> = text.collect(); chars.sort(); let mut freq = 0; let mut prev: char = *chars.first().expect("Input cannot be empty"); for c in chars { if c == prev { freq += 1; } else { freq_vec.push(Node::new(prev, freq)); freq = 1; prev = c; } } freq_vec.push(Node::new(prev, freq)); return freq_vec; } /// Create huffman encoding using huffman algorithm /// ## Input: /// Frequency vector: A vector of Nodes containing character frequency /// (Use the freq_count function) /// ## Output: /// Root node of Huffman Tree of type Option<Box<Node>> /// # Algorithm /// - While priority_queue contains atleast 2 nodes: /// - Choose two minimum elements and combine them /// - Insert combined value back to tree /// - Return tree /// fn construct_huffman_tree(freq: Vec<Node>) -> Node { let mut pq = BinaryHeap::new(); for node in freq { pq.push(node); } while pq.len() > 1 { let (a, b) = (pq.pop().unwrap(), pq.pop().unwrap()); let new_node = Node { letter: '\0', freq: a.freq + b.freq, left: Option::from(Box::from(a)), right: Option::from(Box::from(b)), }; pq.push(new_node); } pq.pop().unwrap() } /// Convert huffman tree to a hashmap with key as char and value as encoding /// E.g key = 'a', value = '1000' fn to_hashmap(node: &Node) -> HashMap<char, String> { let mut hm = HashMap::new(); // Huffman tree is complete binary tree, a node will have either 0 or 2 children, 1 is not possible if node.left.is_none() { hm.insert(node.letter, "0".to_string()); return hm; } fn encode(hm: &mut HashMap<char, String>, node: &Node, encoding: String) { if node.left.is_none() { hm.insert(node.letter, encoding); } else { let left_path = String::from(&encoding) + "0"; let right_path = String::from(&encoding) + "1"; if let Some(left) = &node.left { encode(hm, &left, left_path); } if let Some(right) = &node.right { encode(hm, &right, right_path); } } }; encode(&mut hm, &node, "".to_string()); return hm; } /// Convert huffman node to string of chars using post-order traversal fn to_string(huffman_node: &Node) -> String { let mut output = String::new(); fn post_order(node: &Node, output_str: &mut String) { if let Some(left) = &node.left { post_order(left.as_ref(), output_str); } if let Some(right) = &node.right { post_order(right.as_ref(), output_str); } output_str.push(node.letter); } post_order(huffman_node, &mut output); return output; } /// Convert huffman tree to vector of bytes /// /// First element is length of tree /// /// There are only 100 or so printable characters /// based on python's string.printable /// So worst case tree size is 2N-1 = 199 /// So a unsigned char will suffice for length of tree /// /// Following elements are charectars in post-order traversal of tree fn embed_tree(huffman_node: &Node) -> Vec<u8> { let mut compressed_data = to_string(huffman_node).into_bytes(); compressed_data.insert(0, compressed_data.len() as u8); // Append length return compressed_data; } /// Simply maps input characters to their corresponding encoding and return as byte array /// /// The first element is padding, (Number of zeroes appended for last encoding), as encoding might not fit into 8 bits fn compress_data(text: &String, huffman_node: &Node) -> Vec<u8> { let mut byte_stream: Vec<u8> = Vec::new(); let (mut byte, mut count) = (0, 0); let huffman_map = to_hashmap(huffman_node); for c in text.chars() { let encoding = huffman_map.get(&c).unwrap(); for e in encoding.bytes() { let bit: bool = (e - '0' as u8) != 0; byte = byte << 1 | (bit as u8); count = (count + 1) % 8; if count == 0 { byte_stream.push(byte); byte = 0; } } } if count != 0 { let padding: u8 = 8 - count; byte <<= padding; byte_stream.push(byte); byte_stream.insert(0, padding); } else { byte_stream.insert(0, 0); } return byte_stream; } /// Compression using huffman's algorithm /// # Data Format /// First byte (n): Length of post-order traversal of huffman tree /// /// Following n bytes contain post-order traversal /// /// Padding byte (p): Padding for final byte /// /// All remaining bytes are data pub fn compress(text: &String) -> Vec<u8> { let frequency = freq_count(text.chars()); let huffman_tree = construct_huffman_tree(frequency); let mut compressed_data = Vec::from(embed_tree(&huffman_tree)); compressed_data.extend(compress_data(text, &huffman_tree)); return compressed_data; } fn construct_tree_from_postorder(postorder: &[u8]) -> Node { // parent left right // Assuming input does not contain null let mut stack = Vec::new(); for c in postorder { if *c == 0 as u8 { let (left, right) = ( stack.pop().expect("Input contains Null byte"), stack.pop().expect("Input contains Null byte"), ); stack.push(Node { letter: '\0', freq: 0, left: Option::from(Box::from(right)), right: Option::from(Box::from(left)), }); } else { stack.push(Node { letter: *c as char, freq: 0, left: None, right: None, }); } } return stack.pop().unwrap(); } fn decompress_data(data: &[u8], tree: &Node) -> String { let padding = *data.first().expect("Data empty"); let data = &data[1..]; // Remove first element which stores number of padded bits let mut bit_stream = Vec::new(); let mut tmp = tree; let mut output = String::new(); for character in data.iter() { let mut character = *character; for _ in 0..8 { let bit: bool = (character >> 7 & 1) != 0; character <<= 1; bit_stream.push(bit); } } bit_stream.resize(bit_stream.len() - padding as usize, false); // Remove padding bits if tree.left.is_none() { // Huffman tree is complete binary tree, a node will have either 0 or 2 children, 1 is not possible for _ in 0..bit_stream.len() { output.push(tree.letter); } return output; } for &bit in &bit_stream { if tmp.left.is_none() { output.push(tmp.letter); tmp = tree; } let right: &Node = tmp.right.as_ref().unwrap().as_ref(); let left: &Node = tmp.left.as_ref().unwrap().as_ref(); tmp = if bit { right } else { left }; } if tmp != tree { output.push(tmp.letter); } return output; } pub fn decompress(data: &Vec<u8>) -> String { let post_order_length = *data.first().expect("Data cannot be empty") as usize; let post_order = &data[1..=post_order_length]; let huffman_tree = construct_tree_from_postorder(post_order); let data = &data[post_order_length + 1..]; decompress_data(data, &huffman_tree) } }
    C++
    UTF-8
    3,069
    2.71875
    3
    []
    no_license
    #include "receiver.h" #include <iostream> Receiver::Receiver(QWidget *parent) : QWidget(parent) { } void Receiver::receiveValueHW1(int i) { if(scoreHW1 != i){ scoreHW1 = i; double t = this->recalculate(); emit signalValue(t); //emit two signals? or maybe emit calculated value? } } void Receiver::receiveValueHW2(int i){ if(scoreHW2 != i){ scoreHW2 = i; double t = this->recalculate(); emit signalValue(t); //emit two signals? or maybe emit calculated value? } } void Receiver::receiveValueHW3(int i){ if(scoreHW3 != i){ scoreHW3 = i; double t = this->recalculate(); emit signalValue(t); //emit two signals? or maybe emit calculated value? } } void Receiver::receiveValueHW4(int i){ if(scoreHW4 != i){ scoreHW4 = i; double t = this->recalculate(); emit signalValue(t); //emit two signals? or maybe emit calculated value? } } void Receiver::receiveValueHW5(int i){ if(scoreHW5 != i){ scoreHW5 = i; double t = this->recalculate(); emit signalValue(t); //emit two signals? or maybe emit calculated value? } } void Receiver::receiveValueHW6(int i){ if(scoreHW6 != i){ scoreHW6 = i; double t = this->recalculate(); emit signalValue(t); //emit two signals? or maybe emit calculated value? } } void Receiver::receiveValueHW7(int i){ if(scoreHW7 != i){ scoreHW7 = i; double t = this->recalculate(); emit signalValue(t); //emit two signals? or maybe emit calculated value? } } void Receiver::receiveValueHW8(int i){ if(scoreHW8 != i){ scoreHW8 = i; double t = this->recalculate(); emit signalValue(t); //emit two signals? or maybe emit calculated value? } } void Receiver::receiveValueMID1(int i){ if(scoreMID1 != i){ scoreMID1 = i; double t = this->recalculate(); emit signalValue(t); //emit two signals? or maybe emit calculated value? } } void Receiver::receiveValueMID2(int i){ if(scoreMID2 != i){ scoreMID2 = i; double t = this->recalculate(); emit signalValue(t); //emit two signals? or maybe emit calculated value? } } void Receiver::receiveValueFIN(int i){ if(scoreFIN != i){ scoreFIN = i; double t = this->recalculate(); emit signalValue(t); } } double Receiver::recalculate() { double temp1 = ((scoreHW1 + scoreHW2 + scoreHW3 + scoreHW4 + scoreHW5 + scoreHW6 + scoreHW7 + scoreHW8) / 800. * 25.) + (scoreMID1) / 100. * 20. + (scoreMID2) / 100. * 20. + (scoreFIN) / 100. * 35.; double temp2 = (scoreHW1 + scoreHW2 + scoreHW3 + scoreHW4 + scoreHW5 + scoreHW6 + scoreHW7 + scoreHW8) / 800. * 25. + fmax(scoreMID1,scoreMID2) / 100. * 30. + (scoreFIN) / 100. * 44.; score = fmax(temp1,temp2); return score; }
    JavaScript
    UTF-8
    442
    3.1875
    3
    []
    no_license
    export const format = (seconds) => { if (isNaN(seconds)) return '...'; const minutes = Math.floor(seconds / 60); seconds = Math.floor(seconds % 60); if (seconds < 10) seconds = '0' + seconds; return `${minutes}:${seconds}`; } export const timeToMiliSeconds = (time) => { if (time === null || time === undefined) return '...'; const [min, sec] = time.split(':'); const milliseconds = (+min * 60) + +sec + 1; return milliseconds }
    Python
    UTF-8
    1,057
    3.15625
    3
    []
    no_license
    # -*- coding: utf-8 -*- """ Created on Mon Nov 5 10:08:31 2018 @author: Tim """ #1. Board, Marble, 1D, Pitch/Roll from sense_hat import SenseHat sense = SenseHat() b = (0,0,0) w = (255,255,255) board = [[b,b,b,b,b,b,b,b], [b,b,b,b,b,b,b,b], [b,b,b,b,b,b,b,b], [b,b,b,b,b,b,b,b], [b,b,b,b,b,b,b,b], [b,b,b,b,b,b,b,b], [b,b,b,b,b,b,b,b], [b,b,b,b,b,b,b,b]] y = 2 x = 2 board[y][x] = w board_1D = sum(board,[]) sense.set_pixels(board_1D) def move_marble(pitch, roll, x, y): new_x = x new_y = y if 1 < pitch <179 and x !=0: new_x -= 1 elif 179 < pitch < 359 and x!= 7: new_x += 1 if 1 < roll <179 and x !=7: new_x += 1 elif 179 < roll < 359 and x!= 0: new_x -= 1 return new_x, new_y while True: pitch = sense.get_orientation()['pitch'] roll = sense.get_orientation()['roll'] board[y][x] = b x,y = move_marble(pitch,roll,x,y) board[y][x] = w sense.set_pixels(sum(board,[])) sleep(0.05)