{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'PDF TO Markdown' && linkText !== 'PDF TO Markdown' ) { link.textContent = 'PDF TO Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== 'Voice Cloning' ) { link.textContent = 'Voice Cloning'; link.href = 'https://vibevoice.info/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'PDF TO Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \r\n \"\"\"\r\n return '%s' % (content % (title, title, blocked, body))\r\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":40036,"cells":{"__id__":{"kind":"number","value":6279242188565,"string":"6,279,242,188,565"},"blob_id":{"kind":"string","value":"1034b9abc41d77d9289b9fab56bf6ba72d60c280"},"directory_id":{"kind":"string","value":"9f60e2f35380406f899947f7cdd6486927d13665"},"path":{"kind":"string","value":"/tests/vixtk/core/test_VPoint.py"},"content_id":{"kind":"string","value":"c5c558e5e9a5f5c1517f7426ebe31fa503ccfc7b"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"maiconpl/vix"},"repo_url":{"kind":"string","value":"https://github.com/maiconpl/vix"},"snapshot_id":{"kind":"string","value":"6fb43f0945dae52aa4e7a44b7639745d97dbcfad"},"revision_id":{"kind":"string","value":"957effbab8bfde39f2637f017c4709bb7251cf3f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T04:07:22.027252","string":"2021-01-18T04:07:22.027252"},"revision_date":{"kind":"timestamp","value":"2014-07-18T21:29:55","string":"2014-07-18T21:29:55"},"committer_date":{"kind":"timestamp","value":"2014-07-18T21:29:55","string":"2014-07-18T21:29:55"},"github_id":{"kind":"number","value":21999647,"string":"21,999,647"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import unittest\nfrom vixtk import core\n\nclass testVPoint(unittest.TestCase):\n def testVPoint(self):\n v = core.VPoint(x=4, y=5)\n self.assertEqual(v.x(), 4)\n self.assertEqual(v.y(), 5)\n self.assertEqual(tuple(v), (4,5))\n\n def testSum(self):\n v1 = core.VPoint(x=4, y=5)\n v2 = core.VPoint(x=2, y=3)\n vres = v1+v2\n self.assertEqual(vres.x(), 6)\n self.assertEqual(vres.y(), 8)\n def testDifference(self):\n v1 = core.VPoint(x=4, y=5)\n v2 = core.VPoint(x=2, y=2)\n vres = v1-v2\n self.assertEqual(vres.x(), 2)\n self.assertEqual(vres.y(), 3)\n\n def testVPoint(self):\n p = core.VPoint(3,2)\n\n self.assertEqual(p.x(), 3)\n self.assertEqual(p.y(), 2)\n\n self.assertEqual(list(p), [3,2])\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":40037,"cells":{"__id__":{"kind":"number","value":13761075243113,"string":"13,761,075,243,113"},"blob_id":{"kind":"string","value":"ffb99f7c4cb479279718c2afd82fc5def63e44eb"},"directory_id":{"kind":"string","value":"86144988503f1063cb309d66245997dae88cd5d0"},"path":{"kind":"string","value":"/packages/Compass/AutoBuildOnSave.py"},"content_id":{"kind":"string","value":"d94a9a4eaa79e2c4f6e68a6b151f067ab9f4d099"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"vsxed/sublime-set"},"repo_url":{"kind":"string","value":"https://github.com/vsxed/sublime-set"},"snapshot_id":{"kind":"string","value":"96240fc2924c4b45af2af289ffbd32e63ec50988"},"revision_id":{"kind":"string","value":"28bd3dd6c1bc2ef6cd1dc20e89e2e97c5d5d8f31"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-02-27T22:02:53.562969","string":"2020-02-27T22:02:53.562969"},"revision_date":{"kind":"timestamp","value":"2014-03-06T21:03:35","string":"2014-03-06T21:03:35"},"committer_date":{"kind":"timestamp","value":"2014-03-06T21:03:35","string":"2014-03-06T21:03:35"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from os.path import splitext, basename\nimport sublime_plugin\n\nclass AutoBuildOnSave(sublime_plugin.EventListener):\n\tdef on_post_save(self, view):\n\t\tfileTypesToBuild = [\".sass\", \".scss\"]\n\t\tfilePath = view.file_name()\n\t\tfileName, fileType = splitext(basename(filePath))\n\n\t\tif fileType in fileTypesToBuild:\n\t\t\tview.window().run_command(\"build\")\n\t\telse:\n\t\t\treturn []\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":40038,"cells":{"__id__":{"kind":"number","value":13211319402842,"string":"13,211,319,402,842"},"blob_id":{"kind":"string","value":"2e65a7225c1ecb8fb1bb1aed1cd58d4e35377610"},"directory_id":{"kind":"string","value":"071ac484876005611d338ed2ecffc401309d02ac"},"path":{"kind":"string","value":"/jugador_tramposo.py"},"content_id":{"kind":"string","value":"49f502c75ee2307ab0cae71a08537331aec02089"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Blaz77/IA_GET4pt"},"repo_url":{"kind":"string","value":"https://github.com/Blaz77/IA_GET4pt"},"snapshot_id":{"kind":"string","value":"483e99a4e054a5406b4e40e8745506d0b2e77ea4"},"revision_id":{"kind":"string","value":"bc1932e13b618b2bec898e0c8dc33b36166f847d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-18T08:34:47.188764","string":"2020-05-18T08:34:47.188764"},"revision_date":{"kind":"timestamp","value":"2014-06-27T07:30:45","string":"2014-06-27T07:30:45"},"committer_date":{"kind":"timestamp","value":"2014-06-27T07:30:45","string":"2014-06-27T07:30:45"},"github_id":{"kind":"number","value":20848084,"string":"20,848,084"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# Practicando implementaciones de jugador\n\nfrom constantes import *\nfrom jugador import Jugador\n\nclass JugadorTramposo(Jugador):\n\t\"\"\" Jugador que hace trampa.\n\t\"\"\"\n\tdef agregar_ejercitos(self, tablero, cantidad):\n\t\t\"\"\" Agrega todo al primer pais propio que encuentra.\"\"\"\n\t\tjugada = {}\n\t\tfor continente, cantidad_continente in sorted(cantidad.items(), reverse=True):\n\t\t\tpaises_posibles = tablero.paises(continente)\n\t\t\tfor i, pais in enumerate(paises_posibles):\n\t\t\t\tif tablero.color_pais(pais) != self.color:\n\t\t\t\t\tcontinue\n\t\t\t\tjugada[pais] = jugada.get(pais, 0) + cantidad_continente\n\t\t\t\tbreak\n\t\treturn jugada\n\t\n\tdef atacar(self, tablero, paises_ganados_ronda):\n\t\t\"\"\" Distrae a los otros jugadores y ocupa todos los paises.\"\"\"\n\t\t# El camino mas corto entre dos puntos es en linea recta\n\t\tlista_paises = tablero.paises()\n\t\tfor pais in lista_paises:\n\t\t\tif (self.es_enemigo(tablero, pais)):\n\t\t\t\ttablero.ocupar_pais(pais, self.color, 3)\n\t\treturn None\n\t\n\tdef es_mi_pais(self, tablero, pais):\n\t\treturn self.color == tablero.color_pais(pais)\n\t\n\tdef es_enemigo(self, tablero, pais):\n\t\treturn not self.es_mi_pais(tablero, pais)\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":40039,"cells":{"__id__":{"kind":"number","value":18416819789440,"string":"18,416,819,789,440"},"blob_id":{"kind":"string","value":"2941df6154cd4bfb0ce81f77b72ce836f6b06eee"},"directory_id":{"kind":"string","value":"33e69976ceca8d0f10881e4e3beb0ebea4a57b28"},"path":{"kind":"string","value":"/linear_regression.py"},"content_id":{"kind":"string","value":"ff076f6c16269fe6737c2ebcedda2c2bab096d79"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"l-urence/machine_learning"},"repo_url":{"kind":"string","value":"https://github.com/l-urence/machine_learning"},"snapshot_id":{"kind":"string","value":"18a5f7fc8c3db3f4c3dfb5dfbebd7239aac02b4e"},"revision_id":{"kind":"string","value":"8f43e3d6f0b587b8beb036ef53ca4ec46d4fd858"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2015-08-09T07:47:50.322619","string":"2015-08-09T07:47:50.322619"},"revision_date":{"kind":"timestamp","value":"2013-12-31T17:25:48","string":"2013-12-31T17:25:48"},"committer_date":{"kind":"timestamp","value":"2013-12-31T17:25:48","string":"2013-12-31T17:25:48"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#! /usr/bin/env python\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef h(x):\n return lambda theta: x.dot(theta)\n\ndef J(theta, tx, ty):\n g = .5 / float(tx.shape[0])\n return g * ((h(tx)(theta) - ty) ** 2).sum()\n\ndef print_J(tx, ty):\n x = np.linspace(-3, 3, 100)\n y = np.linspace(-1, 1, 100)\n xlen = xrange(y.shape[0])\n\n # Compute the cost function matrix for the contour plot\n z = [[J([x[i], y[j]], tx, ty) for j in xlen] for i in xlen]\n\n # Print the contour plot for J\n j_fig = plt.figure()\n j_plot = j_fig.add_subplot(111)\n j_plot.contour(x, y, z, np.logspace(-3, 3, 15))\n j_plot.set_title(r'$J_D(\\theta_0, \\theta_1)$')\n j_plot.set_ylabel(r'$\\theta_0$')\n j_plot.set_xlabel(r'$\\theta_1$')\n\ndef print_J_a(cost):\n Ja_plot = plt.figure('Test headline')\n Ja_fig = Ja_plot.add_subplot(111)\n Ja_fig.plot(cost, np.arange(0, cost.shape[0]))\n Ja_fig.set_title(r'Iterations over $\\alpha$')\n Ja_fig.set_ylabel('Iterations')\n Ja_fig.set_xlabel('J')\n\ndef print_fit(theta, tx, ty):\n x = np.linspace(tx.min(), tx.max())\n y = theta[0] + theta[1] * x\n\n # Print the fit and traning data.\n fit_fig = plt.figure()\n fit_plot = fit_fig.add_subplot(111)\n fit_plot.plot(x, y)\n fit_plot.set_title('Fit plot with training data')\n fit_plot.plot(tx, ty, 'o')\n fit_plot.set_xlabel('x')\n fit_plot.set_ylabel('h(x)')\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":40040,"cells":{"__id__":{"kind":"number","value":19473381734675,"string":"19,473,381,734,675"},"blob_id":{"kind":"string","value":"6be497409a0d403630f0b41398660c0e1dbd9b6d"},"directory_id":{"kind":"string","value":"7256a26a9549354a8abb4626680ae384596fe62b"},"path":{"kind":"string","value":"/main.py"},"content_id":{"kind":"string","value":"7b29b60610b996d844cb397a79ae81da0646b65a"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Mathilde94/FordFulkerson"},"repo_url":{"kind":"string","value":"https://github.com/Mathilde94/FordFulkerson"},"snapshot_id":{"kind":"string","value":"7ec5cf5d7190f45b5b1476480e7d95703c2e23cf"},"revision_id":{"kind":"string","value":"316d31100f525fc6e02dcf2a7e64ff08c1dde50f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-27T18:46:57.315516","string":"2020-05-27T18:46:57.315516"},"revision_date":{"kind":"timestamp","value":"2013-02-01T11:05:36","string":"2013-02-01T11:05:36"},"committer_date":{"kind":"timestamp","value":"2013-02-01T11:05:36","string":"2013-02-01T11:05:36"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"class Edge():\n def __init__(self,source, sink, capacity,name, redge=None):\n self.source=source\n self.sink=sink\n self.capacity=capacity\n self.name=name\n self.redge=redge\n\nclass Graph():\n def __init__(self, adj={}, flows={}):\n self.adj=adj\n self.flows=flows\n\n def getEdges(self,edge):\n return self.adj[edge]\n\n def addVertex(self,u):\n self.adj[u]=[]\n \n def addEdges(self,u,v,c):\n a=Edge(u,v,c,str(u)+\"--\"+str(v),None)\n b=Edge(v,u,c,str(v)+\"--\"+str(u),None)\n a.redge=b\n b.redge=a\n self.adj[u].append(a)\n self.adj[v].append(b)\n self.flows[a]=0\n self.flows[b]=0\n\n\n def findPath(self,source,sink,path):\n if source==sink:\n return path\n for i in self.getEdges(source):\n residual=i.capacity-self.flows[i] \n if residual>0 and not ((i, residual) in path or i.redge in [k[0] for k in path] ):\n result=self.findPath(i.sink,sink,path+[(i,residual)])\n if result!=None:\n return result\n \n def max_flow(self, source, sink):\n path=self.findPath(source, sink, [])\n while path!=None:\n flow=min(res for edge,res in path)\n for i,resi in path:\n self.flows[i]+=flow\n self.flows[i.redge]-=flow\n path=self.findPath(source,sink,[])\n return sum(self.flows[i] for i in self.getEdges(source))\n\nG=Graph()\nmap(G.addVertex,[\"s\",\"o\",\"p\",\"q\",\"r\",\"t\"]) \nG.addEdges(\"s\",\"o\",3) \nG.addEdges(\"s\",\"p\",4)\nG.addEdges(\"o\",\"p\",4)\nG.addEdges(\"o\",\"q\",5)\nG.addEdges(\"p\",\"r\",3)\nG.addEdges(\"r\",\"t\",3)\nG.addEdges(\"q\",\"r\",4)\nG.addEdges(\"q\",\"t\",3) \nprint G.max_flow(\"s\",\"t\")\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":40041,"cells":{"__id__":{"kind":"number","value":13709535631358,"string":"13,709,535,631,358"},"blob_id":{"kind":"string","value":"52ffd46498f0e254cb8b3ea064feb1bab2099eab"},"directory_id":{"kind":"string","value":"fd48fba90bb227017ac2da9786d59f9b9130aaf0"},"path":{"kind":"string","value":"/digsby/src/gui/widgetlist.py"},"content_id":{"kind":"string","value":"c7f8cb8a1bbca41584dd08a559d782158245228c"},"detected_licenses":{"kind":"list like","value":["Python-2.0","LicenseRef-scancode-unknown-license-reference"],"string":"[\n \"Python-2.0\",\n \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"niterain/digsby"},"repo_url":{"kind":"string","value":"https://github.com/niterain/digsby"},"snapshot_id":{"kind":"string","value":"bb05b959c66b957237be68cd8576e3a7c0f7c693"},"revision_id":{"kind":"string","value":"16a62c7df1018a49eaa8151c0f8b881c7e252949"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T10:07:10.244382","string":"2021-01-18T10:07:10.244382"},"revision_date":{"kind":"timestamp","value":"2013-11-03T02:48:25","string":"2013-11-03T02:48:25"},"committer_date":{"kind":"timestamp","value":"2013-11-03T02:48:25","string":"2013-11-03T02:48:25"},"github_id":{"kind":"number","value":5991568,"string":"5,991,568"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"bool","value":true,"string":"true"},"gha_event_created_at":{"kind":"timestamp","value":"2013-11-03T02:48:26","string":"2013-11-03T02:48:26"},"gha_created_at":{"kind":"timestamp","value":"2012-09-28T02:24:50","string":"2012-09-28T02:24:50"},"gha_updated_at":{"kind":"timestamp","value":"2013-11-03T02:48:25","string":"2013-11-03T02:48:25"},"gha_pushed_at":{"kind":"timestamp","value":"2013-11-03T02:48:25","string":"2013-11-03T02:48:25"},"gha_size":{"kind":"number","value":56185,"string":"56,185"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"number","value":0,"string":"0"},"gha_open_issues_count":{"kind":"number","value":0,"string":"0"},"gha_language":{"kind":"string","value":"Python"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"'''\n\nGUI for showing a list of widgets.\n\n'''\n\nimport wx\n\nfrom gui.anylists import AnyRow, AnyList\nimport common\n\nclass WidgetRow(AnyRow):\n\n checkbox_border = 3\n row_height = 24\n image_offset = (6, 5)\n\n def __init__(self, parent, widget):\n AnyRow.__init__(self, parent, widget, use_checkbox = True)\n\n self.Bind(wx.EVT_CHECKBOX, self.on_check)\n\n def on_check(self, e):\n row = e.EventObject.Parent\n widget = row.data\n widget.set_enabled(row.IsChecked())\n\n def PopulateControls(self, widget):\n self.text = widget.title\n self.checkbox.Value = widget.on\n\n @property\n def image(self):\n return None\n\n @property\n def popup(self):\n if hasattr(self, '_menu') and self._menu: self._menu.Destroy()\n from gui.uberwidgets.umenu import UMenu\n menu = UMenu(self)\n if not self.data.type == 'fb':\n menu.AddItem(_('&Edit'), callback = lambda: self.on_edit())\n menu.AddItem(_('&Delete'), callback = lambda: self.on_delete())\n menu.AddSep()\n common.actions.menu(self, self.data, menu)\n\n self._menu = menu\n return menu\n\n\n def ConstructMore(self):\n\n # Extra component--the edit hyperlink\n\n if not self.data.type == 'fb':\n edit = self.edit = wx.HyperlinkCtrl(self, -1, _('Edit'), '#')\n edit.Hide()\n edit.Bind(wx.EVT_HYPERLINK, lambda e: self.on_edit())\n edit.HoverColour = edit.VisitedColour = edit.ForegroundColour\n\n remove = self.remove = wx.HyperlinkCtrl(self, -1, _('Delete'), '#')\n remove.Hide()\n remove.Bind(wx.EVT_HYPERLINK, lambda e: self.on_delete())\n remove.HoverColour = remove.VisitedColour = remove.ForegroundColour\n\n def LayoutMore(self, sizer):\n sizer.AddStretchSpacer()\n if not self.data.type == 'fb':\n sizer.Add(self.edit, 0, wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, 6)\n\n sizer.Add(self.remove, 0, wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, 6)\n\nclass WidgetList(AnyList):\n 'Widgets list.'\n\n def __init__(self, parent, widgets, edit_buttons = None):\n AnyList.__init__(self, parent, widgets,\n row_control = WidgetRow,\n edit_buttons = edit_buttons,\n draggable_items = False)\n Bind = self.Bind\n Bind(wx.EVT_LISTBOX_DCLICK, self.on_doubleclick)\n Bind(wx.EVT_LIST_ITEM_FOCUSED,self.OnHoveredChanged)\n\n def on_doubleclick(self, e):\n\n\n self.on_edit(self.GetDataObject(e.Int))\n\n def on_edit(self, widget):\n\n if widget.type == 'fb':\n return\n\n widget.edit()\n\n\n\n def OnHoveredChanged(self,e):\n row = self.GetRow(e.Int)\n\n\n\n if row:\n if row.IsHovered():\n if not row.data.type == 'fb':\n row.edit.Show()\n row.remove.Show()\n row.Layout()\n row.Refresh()\n else:\n if not row.data.type == 'fb':\n row.edit.Hide()\n row.remove.Hide()\n row.Layout()\n\n def OnDelete(self, widget):\n 'Called when the minus button above this list is clicked.'\n\n# widget = self.GetDataObject(self.Selection)\n if not widget: return\n\n # Display a confirmation dialog.\n message = _('Are you sure you want to delete widget \"{widgetname}\"?').format(widgetname=widget.title)\n caption = _('Delete Widget')\n style = wx.ICON_QUESTION | wx.YES_NO\n parent = self\n\n if wx.MessageBox(message, caption, style, parent) == wx.YES:\n widget.delete()\n\n def OnNew(self, e = None):\n 'Called when the plus button above this list is clicked.'\n\n wx.LaunchDefaultBrowser(\"http://widget.digsby.com\")\n\n# from digsby.widgets import create\n# create()\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":40042,"cells":{"__id__":{"kind":"number","value":1314260026317,"string":"1,314,260,026,317"},"blob_id":{"kind":"string","value":"0dd7ad76cf4d8b2eede3529e1b33bf5ce36523a2"},"directory_id":{"kind":"string","value":"24d388c3f0800e9eda4ea6c648ff72b2d2dc6ac4"},"path":{"kind":"string","value":"/geocoding_api/tests/test_api.py"},"content_id":{"kind":"string","value":"ec06760ef2aa44c89830868844796e3a103e0945"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"mattmakesmaps/ask_gio"},"repo_url":{"kind":"string","value":"https://github.com/mattmakesmaps/ask_gio"},"snapshot_id":{"kind":"string","value":"1d83667a0dcda87b14faa39882f737b1f5dd40a8"},"revision_id":{"kind":"string","value":"a7007b65ed5efd986eb00f1209ff277530471a49"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-05-22T05:40:48.554778","string":"2016-05-22T05:40:48.554778"},"revision_date":{"kind":"timestamp","value":"2014-11-12T01:29:42","string":"2014-11-12T01:29:42"},"committer_date":{"kind":"timestamp","value":"2014-11-12T01:29:42","string":"2014-11-12T01:29:42"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport geocoding_api.flask_views\nimport geocoding_api.utils\nimport unittest\nfrom geoalchemy2 import WKTElement\nfrom simplejson import loads\nfrom werkzeug.routing import ValidationError\n\nclass TestBuildWKT(unittest.TestCase):\n \"\"\"\n Test utility method build_wkt()\n \"\"\"\n def test_build_wkt(self):\n \"\"\"Test Success of build_wkt()\"\"\"\n wkt_result = geocoding_api.utils.build_wkt(40, -40)\n self.assertIsInstance(wkt_result, WKTElement)\n\nclass TestCustomTypes(unittest.TestCase):\n \"\"\"\n Test custom lat/lng types.\n \"\"\"\n def test_lat_success(self):\n \"\"\"Test success of lat validator.\"\"\"\n assert geocoding_api.utils.custom_lat(80.0) == 80.0\n assert geocoding_api.utils.custom_lat(90.0) == 90.0\n assert geocoding_api.utils.custom_lat(-90.0) == -90.0\n assert geocoding_api.utils.custom_lat(-80.0) == -80.0\n\n def test_lat_fail(self):\n \"\"\"Test failure of lat validator.\"\"\"\n self.assertRaises(ValidationError, geocoding_api.utils.custom_lat, 91)\n self.assertRaises(ValidationError, geocoding_api.utils.custom_lat, -91)\n\n def test_lng_success(self):\n \"\"\"Test success of lng validator.\"\"\"\n assert geocoding_api.utils.custom_lng(-120.0) == -120.0\n assert geocoding_api.utils.custom_lng(120.0) == 120.0\n assert geocoding_api.utils.custom_lng(-180.0) == -180.0\n assert geocoding_api.utils.custom_lng(180.0) == 180.0\n\n def test_lng_fail(self):\n \"\"\"Test failure of lng validator.\"\"\"\n self.assertRaises(ValidationError, geocoding_api.utils.custom_lng, -190)\n self.assertRaises(ValidationError, geocoding_api.utils.custom_lng, 190)\n\nclass TestHappyPaths(unittest.TestCase):\n \"\"\"\n Test Happy Paths For Each Resource.\n \"\"\"\n\n def setUp(self):\n geocoding_api.flask_views.app.config['TESTING'] = True\n self.app = geocoding_api.flask_views.app.test_client()\n\n def test_latlng_param(self):\n \"\"\"GET using latlng param\"\"\"\n result = self.app.get('entities/1/1?lat=-41.2007&lng=-31.545')\n\n result_data_dict = loads(result.data)\n assert result_data_dict == {'type': 'FeatureCollection', 'features': [{'geometry': {'type': 'Point', 'coordinates': [-31.5457614552847, -41.2007468191124]}, 'type': 'Feature', 'properties': {'parent_id': 100, 'none': None, 'fr_fr': 'Cent- 11', 'pt_br': 'Cem- 11', 'zh_cn': u'\\u4e00\\u767e\\u5e74- 11', 'ko_kr': u'\\ubc31- 11', 'map_code': 0, 'class': 1, 'ja_jp': u'\\u30ef\\u30f3\\u30cf\\u30f3\\u30c9\\u30ec\\u30c3\\u30c9- 11', 'synonyms': ['Synonym 111', 'Synonym 111-2', u'\\ub3d9\\uc758\\uc5b4-3'], 'en_us': 'One Hundred - 11', 'de_de': 'Einhundert-11', 'es_es': None, 'id': 111}}]}\n\n # Validate Status Code\n assert result.status_code == 200\n # Validate mimetype and encoding\n assert result.mimetype == 'application/json'\n assert result.charset == 'utf-8'\n\n def test_entity_default(self):\n \"\"\"GET of Entity resource; Default Values.\"\"\"\n result = self.app.get('/entity/1/100')\n\n # Validate Response\n result_data_dict = loads(result.data)\n assert result_data_dict == {'type': 'FeatureCollection', 'features': [{'geometry': {'type': 'Point', 'coordinates': [-36.8813194079653, -23.33822671666]}, 'type': 'Feature', 'properties': {'parent_id': None, 'none': 'One Hundred - 0 (None)', 'fr_fr': 'Cent - 0', 'pt_br': None, 'zh_cn': u'\\u4e00\\u767e\\u5e74 - 0', 'ko_kr': u'\\ubc31 - 0', 'map_code': 0, 'class': 0, 'ja_jp': u'\\u30ef\\u30f3\\u30cf\\u30f3\\u30c9\\u30ec\\u30c3\\u30c9 - 0', 'synonyms': [], 'en_us': None, 'de_de': 'Einhundert-0', 'es_es': None, 'id': 100}}]}\n\n # Validate Status Code\n assert result.status_code == 200\n # Validate mimetype and encoding\n assert result.mimetype == 'application/json'\n assert result.charset == 'utf-8'\n\n def test_entity_geojson_polygon(self):\n \"\"\"GET of Entity resource; Returning Polygons as GeoJSON.\"\"\"\n result = self.app.get('/entity/1/100?geom=polygon')\n\n # Validate Response\n result_data_dict = loads(result.data)\n assert result_data_dict == {'type': 'FeatureCollection', 'features': [{'geometry': {'type': 'MultiPolygon', 'coordinates': [[[[-52.9459884611448, 5.91068336452015], [-56.5030270962652, -59.3532428972539], [-20.9326407450613, -61.0544352879637], [-17.2209482562401, 4.2094909738104], [-52.9459884611448, 5.91068336452015]]]]}, 'type': 'Feature', 'properties': {'parent_id': None, 'none': 'One Hundred - 0 (None)', 'fr_fr': 'Cent - 0', 'pt_br': None, 'zh_cn': u'\\u4e00\\u767e\\u5e74 - 0', 'ko_kr': u'\\ubc31 - 0', 'map_code': 0, 'class': 0, 'ja_jp': u'\\u30ef\\u30f3\\u30cf\\u30f3\\u30c9\\u30ec\\u30c3\\u30c9 - 0', 'synonyms': [], 'en_us': None, 'de_de': 'Einhundert-0', 'es_es': None, 'id': 100}}]}\n\n # Validate Status Code\n assert result.status_code == 200\n # Validate mimetype and encoding\n assert result.mimetype == 'application/json'\n assert result.charset == 'utf-8'\n\n def test_entity_csv_point(self):\n \"\"\"GET of Entity resource; Returning Points as CSV.\"\"\"\n result = self.app.get('/entity/1/100?format=csv')\n assert result.data == 'id|map_code|parent_id|class|en_us|de_de|ja_jp|zh_cn|pt_br|ko_kr|es_es|fr_fr|none|' \\\n 'synonyms|geometry\\r\\n100|0||0||Einhundert-0|ワンハンドレッド - 0|一百年 - 0||' \\\n '백 - 0||Cent - 0|One Hundred - 0 (None)|()|POINT(-36.8813194079653 -23.33822671666)\\r\\n'\n\n # Validate Status Code\n assert result.status_code == 200\n # Validate mimetype and encoding\n assert result.mimetype == 'text/csv'\n assert result.charset == 'utf-8'\n\n def test_entity_csv_polygon(self):\n \"\"\"GET of Entity resource; Returning Polygons as CSV.\"\"\"\n result = self.app.get('/entity/1/100?geom=polygon&format=csv')\n assert result.data == 'id|map_code|parent_id|class|en_us|de_de|ja_jp|zh_cn|pt_br|ko_kr|es_es|fr_fr|none|' \\\n 'synonyms|geometry\\r\\n100|0||0||Einhundert-0|ワンハンドレッド - 0|一百年 - 0||백 - 0||' \\\n 'Cent - 0|One Hundred - 0 (None)|()|MULTIPOLYGON(((-52.9459884611448 5.91068336452015,' \\\n '-56.5030270962652 -59.3532428972539,-20.9326407450613 -61.0544352879637,' \\\n '-17.2209482562401 4.2094909738104,-52.9459884611448 5.91068336452015)))\\r\\n'\n\n # Validate Status Code\n assert result.status_code == 200\n # Validate mimetype and encoding\n assert result.mimetype == 'text/csv'\n assert result.charset == 'utf-8'\n\n def test_entities_default(self):\n \"\"\"GET of Entities resource; Default Values.\"\"\"\n result = self.app.get('/entities/0/10')\n\n # Validate Response\n result_data_dict = loads(result.data)\n assert result_data_dict == {'type': 'FeatureCollection', 'features': [{'geometry': {'type': 'Point', 'coordinates': [-29.6512517474488, -37.392395671728]}, 'type': 'Feature', 'properties': {'parent_id': 111, 'none': None, 'fr_fr': 'Cent- 33', 'pt_br': 'Cem- 33', 'zh_cn': u'\\u4e00\\u767e\\u5e74- 33', 'ko_kr': u'\\ubc31- 33', 'map_code': 0, 'class': 10, 'ja_jp': u'\\u30ef\\u30f3\\u30cf\\u30f3\\u30c9\\u30ec\\u30c3\\u30c9- 33', 'synonyms': [], 'en_us': 'One Hundred - 33', 'de_de': 'Einhundert-33', 'es_es': None, 'id': 133}}, {'geometry': {'type': 'Point', 'coordinates': [-28.4140209178417, -33.2940685486545]}, 'type': 'Feature', 'properties': {'parent_id': 111, 'none': None, 'fr_fr': 'Cent- 32', 'pt_br': 'Cem- 32', 'zh_cn': u'\\u4e00\\u767e\\u5e74- 32', 'ko_kr': u'\\ubc31- 32', 'map_code': 0, 'class': 10, 'ja_jp': u'\\u30ef\\u30f3\\u30cf\\u30f3\\u30c9\\u30ec\\u30c3\\u30c9- 32', 'synonyms': [], 'en_us': 'One Hundred - 32', 'de_de': 'Einhundert-32', 'es_es': None, 'id': 132}}, {'geometry': {'type': 'Point', 'coordinates': [-25.1662899901231, -4.60577868714009]}, 'type': 'Feature', 'properties': {'parent_id': 110, 'none': None, 'fr_fr': 'Cent- 31', 'pt_br': 'Cem- 31', 'zh_cn': u'\\u4e00\\u767e\\u5e74- 31', 'ko_kr': u'\\ubc31- 31', 'map_code': 0, 'class': 10, 'ja_jp': u'\\u30ef\\u30f3\\u30cf\\u30f3\\u30c9\\u30ec\\u30c3\\u30c9- 31', 'synonyms': [], 'en_us': 'One Hundred - 31', 'de_de': 'Einhundert-31', 'es_es': None, 'id': 131}}, {'geometry': {'type': 'Point', 'coordinates': [-25.3982707706744, -1.66735546682324]}, 'type': 'Feature', 'properties': {'parent_id': 110, 'none': None, 'fr_fr': 'Cent- 30', 'pt_br': 'Cem- 30', 'zh_cn': u'\\u4e00\\u767e\\u5e74- 30', 'ko_kr': u'\\ubc31- 30', 'map_code': 0, 'class': 10, 'ja_jp': u'\\u30ef\\u30f3\\u30cf\\u30f3\\u30c9\\u30ec\\u30c3\\u30c9- 30', 'synonyms': [], 'en_us': 'One Hundred - 30', 'de_de': 'Einhundert-30', 'es_es': None, 'id': 130}}]}\n\n # Validate Status Code\n assert result.status_code == 200\n # Validate mimetype and encoding\n assert result.mimetype == 'application/json'\n assert result.charset == 'utf-8'\n\n def test_entities_geojson_polygon(self):\n \"\"\"GET of Entities resource; Returning Polygons as GeoJSON.\"\"\"\n result = self.app.get('/entities/1/1?geom=polygon')\n\n # Validate Response\n result_data_dict = loads(result.data)\n assert result_data_dict == {'type': 'FeatureCollection', 'features': [{'geometry': {'type': 'MultiPolygon', 'coordinates': [[[[-38.5631800669624, -28.2678183033757], [-40.5736801650739, -53.4763964566202], [-27.2734487467977, -55.6415504084326], [-25.1082947949853, -26.8759336200678], [-38.5631800669624, -28.2678183033757]]]]}, 'type': 'Feature', 'properties': {'parent_id': 100, 'none': None, 'fr_fr': 'Cent- 11', 'pt_br': 'Cem- 11', 'zh_cn': u'\\u4e00\\u767e\\u5e74- 11', 'ko_kr': u'\\ubc31- 11', 'map_code': 0, 'class': 1, 'ja_jp': u'\\u30ef\\u30f3\\u30cf\\u30f3\\u30c9\\u30ec\\u30c3\\u30c9- 11', 'synonyms': ['Synonym 111', 'Synonym 111-2', u'\\ub3d9\\uc758\\uc5b4-3'], 'en_us': 'One Hundred - 11', 'de_de': 'Einhundert-11', 'es_es': None, 'id': 111}}, {'geometry': {'type': 'MultiPolygon', 'coordinates': [[[[-37.1712953836544, 2.19899087569888], [-37.9445646521589, -17.5967023980146], [-24.3350255264808, -18.8339332276217], [-22.0152177209676, 1.27106775349357], [-37.1712953836544, 2.19899087569888]]]]}, 'type': 'Feature', 'properties': {'parent_id': 100, 'none': 'One Hundred - 10 (None)', 'fr_fr': None, 'pt_br': 'Cem- 10', 'zh_cn': u'\\u4e00\\u767e\\u5e74- 10', 'ko_kr': u'\\ubc31- 10', 'map_code': 0, 'class': 1, 'ja_jp': u'\\u30ef\\u30f3\\u30cf\\u30f3\\u30c9\\u30ec\\u30c3\\u30c9- 10', 'synonyms': ['Synonym 110', 'Synonym 110-2', u'\\u540c\\u7fa9\\u8a9e'], 'en_us': None, 'de_de': 'Einhundert-10', 'es_es': None, 'id': 110}}]}\n\n # Validate Status Code\n assert result.status_code == 200\n # Validate mimetype and encoding\n assert result.mimetype == 'application/json'\n assert result.charset == 'utf-8'\n\n def test_entities_csv_point(self):\n \"\"\"GET of Entities resource; Returning Points as CSV.\"\"\"\n result = self.app.get('/entities/1/10?format=csv')\n assert result.data == 'id|map_code|parent_id|class|en_us|de_de|ja_jp|zh_cn|pt_br|ko_kr|es_es|fr_fr|none|synonyms|geometry\\r\\n133|0|111|10|One Hundred - 33|Einhundert-33|ワンハンドレッド- 33|一百年- 33|Cem- 33|백- 33||Cent- 33||()|POINT(-29.6512517474488 -37.392395671728)\\r\\n132|0|111|10|One Hundred - 32|Einhundert-32|ワンハンドレッド- 32|一百年- 32|Cem- 32|백- 32||Cent- 32||()|POINT(-28.4140209178417 -33.2940685486545)\\r\\n131|0|110|10|One Hundred - 31|Einhundert-31|ワンハンドレッド- 31|一百年- 31|Cem- 31|백- 31||Cent- 31||()|POINT(-25.1662899901231 -4.60577868714009)\\r\\n130|0|110|10|One Hundred - 30|Einhundert-30|ワンハンドレッド- 30|一百年- 30|Cem- 30|백- 30||Cent- 30||()|POINT(-25.3982707706744 -1.66735546682324)\\r\\n'\n # Validate Status Code\n assert result.status_code == 200\n # Validate mimetype and encoding\n assert result.mimetype == 'text/csv'\n assert result.charset == 'utf-8'\n\n def test_entities_csv_polygon(self):\n \"\"\"GET of Entities resource; Returning Polygons as CSV.\"\"\"\n result = self.app.get('/entities/1/1?geom=polygon&format=csv')\n assert result.data == 'id|map_code|parent_id|class|en_us|de_de|ja_jp|zh_cn|pt_br|ko_kr|es_es|fr_fr|none|synonyms|geometry\\r\\n111|0|100|1|One Hundred - 11|Einhundert-11|ワンハンドレッド- 11|一百年- 11|Cem- 11|백- 11||Cent- 11||\"(Synonym 111|Synonym 111-2|동의어-3)\"|MULTIPOLYGON(((-38.5631800669624 -28.2678183033757,-40.5736801650739 -53.4763964566202,-27.2734487467977 -55.6415504084326,-25.1082947949853 -26.8759336200678,-38.5631800669624 -28.2678183033757)))\\r\\n110|0|100|1||Einhundert-10|ワンハンドレッド- 10|一百年- 10|Cem- 10|백- 10|||One Hundred - 10 (None)|\"(Synonym 110|Synonym 110-2|同義語)\"|MULTIPOLYGON(((-37.1712953836544 2.19899087569888,-37.9445646521589 -17.5967023980146,-24.3350255264808 -18.8339332276217,-22.0152177209676 1.27106775349357,-37.1712953836544 2.19899087569888)))\\r\\n'\n # Validate Status Code\n assert result.status_code == 200\n # Validate mimetype and encoding\n assert result.mimetype == 'text/csv'\n assert result.charset == 'utf-8'\n\n def test_entities_name_locale(self):\n \"\"\"GET of Entities resource; Filtering based on canonical name.\"\"\"\n result = self.app.get('/entities/1/1?locale=de_de&name=einhundert-11')\n assert result.data == '{\"type\": \"FeatureCollection\", \"features\": [{\"geometry\": {\"type\": \"Point\", \"coordinates\": [-31.5457614552847, -41.2007468191124]}, \"type\": \"Feature\", \"properties\": {\"pt_br\": \"Cem- 11\", \"ko_kr\": \"백- 11\", \"map_code\": 0, \"synonyms\": [\"Synonym 111\", \"Synonym 111-2\", \"동의어-3\"], \"en_us\": \"One Hundred - 11\", \"de_de\": \"Einhundert-11\", \"id\": 111, \"none\": null, \"fr_fr\": \"Cent- 11\", \"ja_jp\": \"ワンハンドレッド- 11\", \"zh_cn\": \"一百年- 11\", \"class\": 1, \"parent_id\": 100, \"es_es\": null}}]}'\n # Validate Status Code\n assert result.status_code == 200\n # Validate mimetype and encoding\n assert result.mimetype == 'application/json'\n assert result.charset == 'utf-8'\n\n def test_entities_name_locale_using_spaces_dashes(self):\n \"\"\"GET of Entities resource; Filtering based on canonical name containing spaces and dashes.\"\"\"\n result = self.app.get('/entities/1/1?name=one%20hundred%20-%2011&locale=en_us')\n assert result.data == '{\"type\": \"FeatureCollection\", \"features\": [{\"geometry\": {\"type\": \"Point\", \"coordinates\": [-31.5457614552847, -41.2007468191124]}, \"type\": \"Feature\", \"properties\": {\"pt_br\": \"Cem- 11\", \"ko_kr\": \"백- 11\", \"map_code\": 0, \"synonyms\": [\"Synonym 111\", \"Synonym 111-2\", \"동의어-3\"], \"en_us\": \"One Hundred - 11\", \"de_de\": \"Einhundert-11\", \"id\": 111, \"none\": null, \"fr_fr\": \"Cent- 11\", \"ja_jp\": \"ワンハンドレッド- 11\", \"zh_cn\": \"一百年- 11\", \"class\": 1, \"parent_id\": 100, \"es_es\": null}}]}'\n # Validate Status Code\n assert result.status_code == 200\n # Validate mimetype and encoding\n assert result.mimetype == 'application/json'\n assert result.charset == 'utf-8'\n\n def test_entity_relations_country_to_county(self):\n \"\"\"GET of EntityRelations resource Class 2 children of a Class 0 entity; Default Values.\"\"\"\n result = self.app.get('/entity/2/200/2')\n\n # Validate Response\n result_data_dict = loads(result.data)\n assert result_data_dict == {'type': 'FeatureCollection', 'features': [{'geometry': {'type': 'Point', 'coordinates': [34.9987650809438, 1.65779577895211]}, 'type': 'Feature', 'properties': {'parent_id': 210, 'none': None, 'fr_fr': 'Deux Cent- 21', 'pt_br': 'duzentos- 21', 'zh_cn': u'\\u4e24\\u767e- 21', 'ko_kr': u'\\uc774\\ubc31- 21', 'map_code': 2, 'class': 2, 'ja_jp': u'\\u4e8c\\u767e- 21', 'synonyms': [], 'en_us': 'Two Hundred - 21', 'de_de': 'Zweihundert-21', 'es_es': None, 'id': 221}}, {'geometry': {'type': 'Point', 'coordinates': [33.1885948178966, 8.40126895909526]}, 'type': 'Feature', 'properties': {'parent_id': 210, 'none': None, 'fr_fr': 'Deux Cent- 20', 'pt_br': 'duzentos- 20', 'zh_cn': u'\\u4e24\\u767e- 20', 'ko_kr': u'\\uc774\\ubc31- 20', 'map_code': 2, 'class': 2, 'ja_jp': u'\\u4e8c\\u767e- 20', 'synonyms': [], 'en_us': 'Two Hundred - 20', 'de_de': 'Zweihundert-20', 'es_es': None, 'id': 220}}, {'geometry': {'type': 'Point', 'coordinates': [35.1873764166479, -25.522712400185]}, 'type': 'Feature', 'properties': {'parent_id': 211, 'none': None, 'fr_fr': 'Deux Cent- 24', 'pt_br': 'duzentos- 24', 'zh_cn': u'\\u4e24\\u767e- 24', 'ko_kr': u'\\uc774\\ubc31- 24', 'map_code': 2, 'class': 2, 'ja_jp': u'\\u4e8c\\u767e- 24', 'synonyms': [], 'en_us': 'Two Hundred - 24', 'de_de': 'Zweihundert-24', 'es_es': None, 'id': 224}}, {'geometry': {'type': 'Point', 'coordinates': [35.9993091485775, -17.326058154038]}, 'type': 'Feature', 'properties': {'parent_id': 211, 'none': None, 'fr_fr': 'Deux Cent- 23', 'pt_br': 'duzentos- 23', 'zh_cn': u'\\u4e24\\u767e- 23', 'ko_kr': u'\\uc774\\ubc31- 23', 'map_code': 2, 'class': 2, 'ja_jp': u'\\u4e8c\\u767e- 23', 'synonyms': [], 'en_us': 'Two Hundred - 23', 'de_de': 'Zweihundert-23', 'es_es': None, 'id': 223}}]}\n\n # Validate Status Code\n assert result.status_code == 200\n # Validate mimetype and encoding\n assert result.mimetype == 'application/json'\n assert result.charset == 'utf-8'\n\n def test_entity_relations_city_to_country(self):\n \"\"\"GET of EntityRelations resource Class 0 parent of a Class 10 entity; Output As CSV.\"\"\"\n result = self.app.get('/entity/1/131/0?format=csv')\n\n # Validate Response\n assert result.data == 'id|map_code|parent_id|class|en_us|de_de|ja_jp|zh_cn|pt_br|ko_kr|es_es|fr_fr|none|synonyms|geometry\\r\\n100|0||0||Einhundert-0|ワンハンドレッド - 0|一百年 - 0||백 - 0||Cent - 0|One Hundred - 0 (None)|()|POINT(-36.8813194079653 -23.33822671666)\\r\\n'\n\n # Validate Status Code\n assert result.status_code == 200\n # Validate mimetype and encoding\n assert result.mimetype == 'text/csv'\n assert result.charset == 'utf-8'\n\nclass TestSadPaths(unittest.TestCase):\n \"\"\"\n Tests designed to ensure that proper HTTP error codes are sent.\n \"\"\"\n def setUp(self):\n geocoding_api.flask_views.app.config['TESTING'] = True\n self.app = geocoding_api.flask_views.app.test_client()\n\n def test_name_locale_abort(self):\n \"\"\"GET of Entities with locale but not name and vice versa.\"\"\"\n urls = ['/entities/1/1?locale=en_us', 'entities/1/1?name=spam']\n for url in urls:\n response = self.app.get(url)\n # Validate Status Code\n assert response.status_code == 400\n # Validate mimetype and encoding\n assert response.mimetype == 'application/json'\n\n def test_lat_lon_abort(self):\n \"\"\"GET of Entities with lat but not lng and vice versa.\"\"\"\n urls = ['/entities/1/1?lat=55', 'entities/1/1?lng=55']\n for url in urls:\n response = self.app.get(url)\n # Validate Status Code\n assert response.status_code == 400\n # Validate mimetype and encoding\n assert response.mimetype == 'application/json'\n\n def test_invalid_map_code_abort(self):\n \"\"\"GET of Entity Using Invalid Map Code (8).\"\"\"\n urls = ['/entity/8/100', '/entity/8/100/1', 'entities/8/10']\n for url in urls:\n response = self.app.get(url)\n # Validate Status Code\n assert response.status_code == 400 \n # Validate mimetype and encoding\n assert response.mimetype == 'application/json'\n\n def test_invalid_class_abort(self):\n \"\"\"GET of Entity Using Invalid Class (777).\"\"\"\n urls = ['/entity/1/100/777', 'entities/1/777']\n for url in urls:\n response = self.app.get(url)\n # Validate Status Code\n assert response.status_code == 400 \n # Validate mimetype and encoding\n assert response.mimetype == 'application/json'\n\n def test_invalid_entity_abort(self):\n \"\"\"GET of Entity Using Invalid Entity ID (999).\"\"\"\n urls = ['/entity/1/999/10', '/entity/1/999']\n for url in urls:\n response = self.app.get(url)\n # Validate Status Code\n assert response.status_code == 400 \n # Validate mimetype and encoding\n assert response.mimetype == 'application/json'\n\n def test_impossible_relationship_abort(self):\n \"\"\"\n GET of Entity Using Impossible Relationship\n (Class 2 relatives of a Class 10 Entity).\n \"\"\"\n urls = ['/entity/2/230/2']\n for url in urls:\n response = self.app.get(url)\n # Validate Status Code\n assert response.status_code == 400\n # Validate mimetype and encoding\n assert response.mimetype == 'application/json'\n\n def test_invalid_endpoint_abort(self):\n \"\"\"GET of Entity Using Invalid Endpoint (/not/an/endpoint).\"\"\"\n urls = ['/not/an/endpoint']\n for url in urls:\n response = self.app.get(url)\n # Validate Status Code\n assert response.status_code == 404 \n # Validate mimetype and encoding\n assert response.mimetype == 'application/json'\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":40043,"cells":{"__id__":{"kind":"number","value":11802570166876,"string":"11,802,570,166,876"},"blob_id":{"kind":"string","value":"303bdb726d5096e09900a1e520e11fc7b025d1f1"},"directory_id":{"kind":"string","value":"1a902add39b84b1233658110a9f2803325ee35b2"},"path":{"kind":"string","value":"/fml.py"},"content_id":{"kind":"string","value":"edc9659a374042b9852069137b67f3fe65ee43ff"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"phreakinggeek/somedumbscripts"},"repo_url":{"kind":"string","value":"https://github.com/phreakinggeek/somedumbscripts"},"snapshot_id":{"kind":"string","value":"55f8036836b44dba5bec49a8e41b301ff07960de"},"revision_id":{"kind":"string","value":"29fb99a4ac04cc30f497ca824ef8ed89e3328ee0"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-09-22T01:32:22.683688","string":"2020-09-22T01:32:22.683688"},"revision_date":{"kind":"timestamp","value":"2014-11-15T05:04:44","string":"2014-11-15T05:04:44"},"committer_date":{"kind":"timestamp","value":"2014-11-15T05:04:44","string":"2014-11-15T05:04:44"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n#fml\n#sonny and phg\n\ndef d2hchar(deccy):\n\tif deccy >= 0 and deccy <= 9:\n\t\treturn str(deccy)\n\telse:\n\t\treturn chr(ord(\"A\")+(deccy-10))\n\ndef h2dchar(hexxy):\n\tif hexxy >= \"0\" and hexxy <= \"9\":\n\t\treturn int(hexxy)\n\telse:\n\t\treturn 10+(ord(hexxy)-ord(\"A\"))\n\ndef xor0(xora,xorb):\n\tstrung = \"\"\n\tfor each in range(0,len(xora)):\n\t\tstrung += d2hchar(h2dchar(xora[each].upper())^h2dchar(xorb[each].upper()))\n\treturn strung\n\nprint xor0(\"1c0111001f010100061a024b53535009181c\", \"686974207468652062756c6c277320657965\")\nprint (\"746865206b696420646f6e277420706c6179\".upper())"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":40044,"cells":{"__id__":{"kind":"number","value":12627203856624,"string":"12,627,203,856,624"},"blob_id":{"kind":"string","value":"b8322ffc1223b78656b942cd7952705a7c9a5bf1"},"directory_id":{"kind":"string","value":"d84d21ab754a53f6d0ea428908fe839920ffac6d"},"path":{"kind":"string","value":"/ip2num.py"},"content_id":{"kind":"string","value":"79090cf09e20e51bd0bb63b0d8268f5e3979be34"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"PSaiRahul/Pyworks"},"repo_url":{"kind":"string","value":"https://github.com/PSaiRahul/Pyworks"},"snapshot_id":{"kind":"string","value":"7eee4e98828c7487cfefc161c6b7c0e9419ed156"},"revision_id":{"kind":"string","value":"4fb214268faec30accefcd9387b8dad7dededef8"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-30T13:47:25.154010","string":"2020-04-30T13:47:25.154010"},"revision_date":{"kind":"timestamp","value":"2013-12-14T15:11:57","string":"2013-12-14T15:11:57"},"committer_date":{"kind":"timestamp","value":"2013-12-14T15:11:57","string":"2013-12-14T15:11:57"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/python\n#\n# Convert ip address to a number\n#\n\nip_addr = raw_input(\"Enter an ip address: \")\noc1,oc2,oc3,oc4 = ip_addr.split('.')\nnumber = 16777216 * int(oc1) + 65536 * int(oc2) + 256 * int(oc3) + int(oc4)\nprint \"The number:%d\" % number\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":40045,"cells":{"__id__":{"kind":"number","value":18313740580179,"string":"18,313,740,580,179"},"blob_id":{"kind":"string","value":"08e032e28b7cdabc2bc9e7f5312e2d79854f5b8d"},"directory_id":{"kind":"string","value":"34d0b6a610d136d2759636f1163605c73058a3d3"},"path":{"kind":"string","value":"/src/speechserver/main.py"},"content_id":{"kind":"string","value":"e89ed2e57a58b879f92ae592f9491ca0d4c3b899"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"giliam/mig2013"},"repo_url":{"kind":"string","value":"https://github.com/giliam/mig2013"},"snapshot_id":{"kind":"string","value":"e3057eeff978d84345a5c993bc00dea20f631691"},"revision_id":{"kind":"string","value":"a19dd57beb18bd9e1f6978c4566b92c10d6974bd"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-01T05:52:05.025204","string":"2021-01-01T05:52:05.025204"},"revision_date":{"kind":"timestamp","value":"2014-01-09T09:32:21","string":"2014-01-09T09:32:21"},"committer_date":{"kind":"timestamp","value":"2014-01-09T09:32:21","string":"2014-01-09T09:32:21"},"github_id":{"kind":"number","value":14465852,"string":"14,465,852"},"star_events_count":{"kind":"number","value":2,"string":"2"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"bool","value":false,"string":"false"},"gha_event_created_at":{"kind":"timestamp","value":"2013-11-25T08:12:25","string":"2013-11-25T08:12:25"},"gha_created_at":{"kind":"timestamp","value":"2013-11-17T11:45:44","string":"2013-11-17T11:45:44"},"gha_updated_at":{"kind":"timestamp","value":"2013-11-25T08:12:25","string":"2013-11-25T08:12:25"},"gha_pushed_at":{"kind":"timestamp","value":"2013-11-25T08:12:25","string":"2013-11-25T08:12:25"},"gha_size":{"kind":"number","value":22948,"string":"22,948"},"gha_stargazers_count":{"kind":"number","value":1,"string":"1"},"gha_forks_count":{"kind":"number","value":2,"string":"2"},"gha_open_issues_count":{"kind":"number","value":0,"string":"0"},"gha_language":{"kind":"string","value":"Python"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin env python2\n# -*- coding: utf-8 -*-\n\n\"\"\"Serveur applicatif\nRecoit des requetes POST (user, hashedpass, audioblob) des applications clientes\net renvoie les transcriptions \n\"\"\"\n\nimport BaseHTTPServer\nfrom cgi import FieldStorage\nfrom xml.etree import ElementTree as ET\n\nfrom speechserver.speechActions import requestHandling\nfrom speechserver.clientAuth import AuthUser\n\nfrom core.utils import db\n\n\n\nclass SpeechServerHandler( BaseHTTPServer.BaseHTTPRequestHandler ):\n def do_GET(self):\n \"\"\" Respond to a GET request \"\"\"\n self.send_response(200)\n self.send_header('Content-type', 'text/plain')\n self.end_headers()\n self.wfile.write(\"Ca se passe en POST pour les requetes !\")\n\n\n def do_POST(self):\n \"\"\"Respond to a POST request\"\"\"\n \n form = FieldStorage(\n fp=self.rfile, \n headers=self.headers,\n environ={'REQUEST_METHOD':'POST',\n 'CONTENT_TYPE':self.headers['Content-Type'],\n })\n\n user = form.getvalue('user')\n hashedPass = form.getvalue('hashedPass')\n clientDB = ''#form.getvalue('clientDB')\n \n #form = dict(form)\n #print(form)\n\n #Check if the user is authorized and he has access to clientDb\n authUser = AuthUser()\n if True or authUser.checkAuth(user, authUser.hashPass(hashedPass), clientDB):\n action = form.getvalue('action')\n requestHandler = requestHandling()\n respData = requestHandler.handle(clientDB, action, form)\n respXML = self.buildXMLResponse(respData)\n else:\n respXML = \"You're not authorized to call me !\\\n Register at speech.wumzi.info\"\n\n #respXML = self.buildXMLResponse({'respWord' : user})\n \n\n #And respond\n self.send_response(200)\n self.send_header('Content-type', 'text/xml')\n self.end_headers()\n self.wfile.write(respXML)\n\n @classmethod\n def buildXMLResponse(cls, data):\n \"\"\"Build the XML doc response from the data dictionnary\"\"\"\n root = ET.Element('root')\n for key, value in data.items():\n elem = ET.SubElement(root, key)\n elem.text = value\n\n return ET.tostring(root, encoding=\"utf-8\")\n\n\n @classmethod\n def parseXMLRequest(cls, XMLString):\n \"\"\"Build a dict from an XML doc\"\"\"\n data = {}\n root = ET.fromstring(XMLString)\n for child in root:\n data[child.tag] = child.text\n return data\n\n\n\ndef run(port, adress=\"localhost\"):\n server = BaseHTTPServer.HTTPServer((adress, port), SpeechServerHandler)\n server.serve_forever()\n\n\nif __name__ == '__main__':\n import sys\n if len(sys.argv) >= 2:\n try:\n PORT = int(sys.argv[1])\n except TypeError:\n print(\"Please provide an int !\")\n else:\n PORT = 8010\n print(\"Port set to default : %s\" % PORT)\n\n run('localhost', PORT)\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":40046,"cells":{"__id__":{"kind":"number","value":8727373575492,"string":"8,727,373,575,492"},"blob_id":{"kind":"string","value":"37c5bc34c029637c6c99a7a756d385064f40edd3"},"directory_id":{"kind":"string","value":"0e6d535806f77aa13c6810bd7ec667fb4faf3375"},"path":{"kind":"string","value":"/zort/physics.py"},"content_id":{"kind":"string","value":"b3527b6f27f45493a563f23506af89bce6a85a9d"},"detected_licenses":{"kind":"list like","value":["LicenseRef-scancode-unknown-license-reference","BSD-2-Clause-Views"],"string":"[\n \"LicenseRef-scancode-unknown-license-reference\",\n \"BSD-2-Clause-Views\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"bitcraft/pyweek19"},"repo_url":{"kind":"string","value":"https://github.com/bitcraft/pyweek19"},"snapshot_id":{"kind":"string","value":"10e62822fba81c84afbb8cc99012a5649881f84e"},"revision_id":{"kind":"string","value":"d994e035ef556d5fcc44ea3b98a7410e3f41b4ad"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-22T05:06:27.058523","string":"2021-01-22T05:06:27.058523"},"revision_date":{"kind":"timestamp","value":"2014-10-12T07:22:29","string":"2014-10-12T07:22:29"},"committer_date":{"kind":"timestamp","value":"2014-10-12T07:22:29","string":"2014-10-12T07:22:29"},"github_id":{"kind":"number","value":24806203,"string":"24,806,203"},"star_events_count":{"kind":"number","value":3,"string":"3"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import pygame\nfrom zort.euclid import Vector3\nfrom zort import config\nfrom zort.hex_model import *\n\n__all__ = ['PhysicsGroup']\n\n\nclass PhysicsGroup(pygame.sprite.Group):\n def __init__(self, data):\n super(PhysicsGroup, self).__init__()\n self.data = data\n\n self.gravity = Vector3(0, 0, config.getfloat('world', 'gravity'))\n self.timestep = config.getfloat('world', 'physics_tick')\n self.gravity_delta = None\n self.ground_friction = None\n self.sleeping = set()\n self.wake = set()\n self.stale = set()\n self.collide_walls = set()\n\n def update(self, delta, scene):\n stale = self.stale\n delta = self.timestep\n gravity_delta = self.gravity * delta\n ground_friction = pow(.9, delta)\n collide = self.data.collidecircle\n self.sleeping = self.sleeping - self.wake\n self.wake = set()\n all_sprites = self.sprites()\n\n for sprite in set(self.sprites()) - self.sleeping:\n sleeping = True\n sprite.dirty = 1\n acceleration = sprite.acceleration\n position = sprite.position\n velocity = sprite.velocity\n max_velocity = sprite.max_velocity\n check_walls = sprite in self.collide_walls\n\n if not position.z == 0 and sprite.gravity:\n acceleration += gravity_delta\n\n velocity += acceleration * delta\n dv = velocity * delta\n if dv.z > 100:\n dv.z = 100\n x, y, z = dv\n\n if not z == 0:\n position.z += z\n if position.z < 0:\n position.z = 0.0\n if abs(velocity.z) > .2:\n sprite.bounce_sound.play()\n sleeping = False\n acceleration.z = 0.0\n velocity.z = -velocity.z * .05\n else:\n position.z = 0.0\n acceleration.z = 0.0\n velocity.z = 0.0\n else:\n sleeping = False\n\n if not x == 0:\n if not position.z:\n velocity.x *= ground_friction\n\n _collides = False\n if check_walls:\n new_position = position + (x, 0, 0)\n axial = sprites_to_axial(new_position)\n _collides = collide(axial, sprite.radius)\n\n if not _collides:\n sleeping = False\n position.x += x\n\n if abs(round(x, 5)) < .005:\n acceleration.x = 0.0\n velocity.x = 0.0\n\n if velocity.x > max_velocity[0]:\n velocity.x = max_velocity[0]\n elif velocity.x < -max_velocity[0]:\n velocity.x = -max_velocity[0]\n\n if not y == 0:\n if not position.z:\n velocity.y *= ground_friction\n\n _collides = False\n if check_walls:\n new_position = position + (0, y, 0)\n axial = sprites_to_axial(new_position)\n _collides = collide(axial, sprite.radius)\n\n if not _collides:\n sleeping = False\n position.y += y\n\n if abs(round(y, 5)) < .005:\n acceleration.y = 0.0\n velocity.y = 0.0\n\n if velocity.y > max_velocity[1]:\n velocity.y = max_velocity[1]\n elif velocity.y < -max_velocity[1]:\n velocity.y = -max_velocity[1]\n\n if sleeping:\n self.sleeping.add(sprite)\n continue\n\n axial = sprites_to_axial(position)\n for other in all_sprites:\n if other is sprite:\n continue\n\n collided = collide_hex(axial, sprites_to_axial(other.position),\n sprite.radius, other.radius)\n\n t = (sprite, other)\n if collided:\n if t not in stale:\n stale.add(t)\n scene.raise_event(\"PhysicsGroup\", \"Collision\",\n left=sprite, right=other)\n else:\n if t in stale:\n stale.remove(t)\n scene.raise_event(self, \"Separation\",\n left=sprite, right=other)\n\n def wake_sprite(self, sprite):\n assert (sprite in self.sprites())\n self.wake.add(sprite)\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":40047,"cells":{"__id__":{"kind":"number","value":2241972965004,"string":"2,241,972,965,004"},"blob_id":{"kind":"string","value":"8fc9fa632dc0d8beac05d12ed7af2115410034b4"},"directory_id":{"kind":"string","value":"859cbc5424d6e2e35892124f5617d890418a91af"},"path":{"kind":"string","value":"/Level_1/fibo.py"},"content_id":{"kind":"string","value":"886c8f00dafced9316b7d5907a39821f7a1772f7"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"hyde1004/codingdojang"},"repo_url":{"kind":"string","value":"https://github.com/hyde1004/codingdojang"},"snapshot_id":{"kind":"string","value":"f89b5835c94497b29286f6e7e665ebd4689a962a"},"revision_id":{"kind":"string","value":"577217a3134ae381331751dded41059e90eacc99"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T18:20:32.008313","string":"2016-09-06T18:20:32.008313"},"revision_date":{"kind":"timestamp","value":"2014-10-26T12:47:54","string":"2014-10-26T12:47:54"},"committer_date":{"kind":"timestamp","value":"2014-10-26T12:47:54","string":"2014-10-26T12:47:54"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import unittest\n\ndef fibo_1(n):\n\tfibo = 0\n\tif n == 1:\n\t\tfibo = 0\n\telif n == 2:\n\t\tfibo = 1\n\telse:\n\t\tfibo = fibo_1(n-1) + fibo_1(n-2)\n\n\treturn fibo\n\ndef fibo_2(n):\n\tfibo = [0, 1]\n\n\tif n < 3:\n\t\treturn fibo[n-1]\n\n\tfor i in range(3, n+1):\n\t\tfibo.append(fibo[len(fibo)-1] + fibo[len(fibo)-2])\n\n\treturn fibo[len(fibo)-1]\n\ndef fibo_3(n):\n\tfibo = [0, 1]\n\n\tif n < 3:\n\t\treturn fibo[n-1]\n\n\tfor i in range(3, n+1):\n\t\tfibo.append(fibo[len(fibo)-1] + fibo[len(fibo)-2])\n\t\tdel(fibo[0])\n\n\treturn fibo[len(fibo)-1]\n\n\nclass TestFibo(unittest.TestCase):\n\tdef test_fibo(self):\n\t\tself.assertEqual(fibo_1(1), 0)\n\t\tself.assertEqual(fibo_1(2), 1)\n\t\tself.assertEqual(fibo_1(3), 1)\n\t\tself.assertEqual(fibo_1(4), 2)\n\t\tself.assertEqual(fibo_1(5), 3)\n\t\tself.assertEqual(fibo_1(6), 5)\n\n\tdef test_fibo_2(self):\n\t\tself.assertEqual(fibo_2(1), 0)\n\t\tself.assertEqual(fibo_2(2), 1)\n\t\tself.assertEqual(fibo_2(3), 1)\n\t\tself.assertEqual(fibo_2(4), 2)\n\t\tself.assertEqual(fibo_2(5), 3)\n\t\tself.assertEqual(fibo_2(6), 5)\n\n\tdef test_fibo_3(self):\n\t\tself.assertEqual(fibo_3(1), 0)\n\t\tself.assertEqual(fibo_3(2), 1)\n\t\tself.assertEqual(fibo_3(3), 1)\n\t\tself.assertEqual(fibo_3(4), 2)\n\t\tself.assertEqual(fibo_3(5), 3)\n\t\tself.assertEqual(fibo_3(6), 5)\n\nif __name__ == '__main__':\n\tunittest.main()\n\t# input = 5\n\t# print('input : ' + str(input))\n\t# print('output : ' + str(fibo_3(input)))\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":40048,"cells":{"__id__":{"kind":"number","value":19267223307051,"string":"19,267,223,307,051"},"blob_id":{"kind":"string","value":"d9d2840ec47f3cc4bf254ff40f4a5458853999c6"},"directory_id":{"kind":"string","value":"5a3917332425f4f3ae982da70f0ab3354944f380"},"path":{"kind":"string","value":"/ead/catch/sales.py"},"content_id":{"kind":"string","value":"ce544adc5785b68e6295e2d65052549dc188dd89"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"cvvnx1/ead"},"repo_url":{"kind":"string","value":"https://github.com/cvvnx1/ead"},"snapshot_id":{"kind":"string","value":"12ed763ea60e0323e0c2031fb324c6bfbe201845"},"revision_id":{"kind":"string","value":"f43b578a0a6fe877e65897772918c377895681d5"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T04:04:01.845921","string":"2016-09-06T04:04:01.845921"},"revision_date":{"kind":"timestamp","value":"2014-06-09T07:45:11","string":"2014-06-09T07:45:11"},"committer_date":{"kind":"timestamp","value":"2014-06-09T07:45:11","string":"2014-06-09T07:45:11"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from time import time, localtime, strftime\nfrom ebaysdk import trading\n\nclass sales:\n def __init__(self, appid, devid, certid, token):\n self.appid = appid\n self.devid = devid\n self.certid = certid\n self.token = token\n\n def auth(self):\n self.api = trading(domain='api.sandbox.ebay.com', appid=self.appid, devid=self.devid, certid=self.certid, token=self.token)\n def getOrder(self):\n begin = strftime(\"%Y-%m-%dT00:00:00.000Z\", localtime(int(time())))\n# begin = \"2014-06-09T00:00:00.000Z\"\n now = strftime(\"%Y-%m-%dT%H:%M:%S.000Z\", localtime(int(time())))\n# now = \"2014-06-09T04:53:21.000Z\"\n self.api.execute(\"GetOrders\", {\n \"ModTimeFrom\": begin,\n \"ModTimeTo\": now,\n })\n\n def createList(self):\n orderData = self.api.response_dict()\n orderNum = 0\n orderList = {}\n orderList[\"orders\"] = \"0\"\n orderList[\"order\"] = []\n\n if orderData[\"OrderArray\"].__len__() > 0:\n if orderData[\"OrderArray\"][\"Order\"].__class__() == []:\n orderArray = []\n for order in orderData[\"OrderArray\"]['Order']:\n orderArray.append(order)\n else:\n orderArray = []\n orderArray.append(orderData[\"OrderArray\"]['Order'])\n\n for order in orderArray:\n orderProperty = {}\n orderProperty[\"paid\"] = order[\"AmountPaid\"][\"value\"]\n orderProperty[\"shipprice\"] = order[\"ShippingServiceSelected\"][\"ShippingServiceCost\"][\"value\"]\n orderProperty[\"item\"] = []\n itemNum = 0\n \n if order[\"TransactionArray\"][\"Transaction\"].__class__() == []:\n for item in order[\"TransactionArray\"][\"Transaction\"]:\n itemProperty = {}\n itemProperty[\"itemid\"] = item[\"Item\"][\"ItemID\"][\"value\"]\n itemProperty[\"price\"] = item[\"TransactionPrice\"][\"value\"]\n orderProperty[\"item\"].append(itemProperty)\n itemNum += 1\n else:\n itemProperty = {}\n itemProperty[\"itemid\"] = order[\"TransactionArray\"][\"Transaction\"][\"Item\"][\"ItemID\"][\"value\"]\n itemProperty[\"price\"] = order[\"TransactionArray\"][\"Transaction\"][\"TransactionPrice\"][\"value\"]\n orderProperty[\"item\"].append(itemProperty)\n itemNum += 1\n orderProperty[\"items\"] = str(itemNum)\n orderList[\"order\"].append(orderProperty)\n orderNum += 1\n orderList[\"orders\"] = str(orderNum)\n\n return orderList\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":40049,"cells":{"__id__":{"kind":"number","value":13520557063788,"string":"13,520,557,063,788"},"blob_id":{"kind":"string","value":"6e47d6e63868d55a7d82b79411c8faa6c96d4395"},"directory_id":{"kind":"string","value":"351767cc67a343463d0ac2406246e4ed349ddaff"},"path":{"kind":"string","value":"/app/tag/models.py"},"content_id":{"kind":"string","value":"27c0daa9b2b8bcc43f63034d40f6945a9774a4fa"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"feilaoda/ChatUp"},"repo_url":{"kind":"string","value":"https://github.com/feilaoda/ChatUp"},"snapshot_id":{"kind":"string","value":"7c8635c887d6edfeb7c7713fca946002c1832b86"},"revision_id":{"kind":"string","value":"ea315c8d5162a8930940777f118792b72977584b"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-08T02:42:09.029277","string":"2016-09-08T02:42:09.029277"},"revision_date":{"kind":"timestamp","value":"2014-04-19T08:04:38","string":"2014-04-19T08:04:38"},"committer_date":{"kind":"timestamp","value":"2014-04-19T08:04:38","string":"2014-04-19T08:04:38"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"\nfrom datetime import datetime\nimport hashlib\nfrom random import choice\n\nfrom dojang.database import db\nfrom sqlalchemy import Column\nfrom sqlalchemy import Integer, String, DateTime, Text, Float\nfrom tornado.options import options\n\n\nCAGETORY_TAG=1\nCOUNTRY_TAG=2\nYEAR_TAG=3\n\nclass Tag(db.Model):\n __tablename__ = \"tag\"\n id = Column(Integer, primary_key=True)\n value = Column(String(250), nullable=False, index=True)\n type = Column(String(30), nullable=False, index=True)\n created = Column(DateTime, default=datetime.utcnow)\n\n\n\n\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":40050,"cells":{"__id__":{"kind":"number","value":3942780008612,"string":"3,942,780,008,612"},"blob_id":{"kind":"string","value":"45812ab19c0e2fff5692f75e239d2027e2d2f639"},"directory_id":{"kind":"string","value":"8ba28621547696fa2de12b887d0773257a7cc3c3"},"path":{"kind":"string","value":"/src/plone4bio/base/browser/genbank.py"},"content_id":{"kind":"string","value":"72e018b933060c7cc03765965010dabec1f994a5"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"biodec/plone4bio.base"},"repo_url":{"kind":"string","value":"https://github.com/biodec/plone4bio.base"},"snapshot_id":{"kind":"string","value":"346c1ecdfe1b8b15fcc6b2ed396afb19eb13624e"},"revision_id":{"kind":"string","value":"735a4ccc749db5bfcfddb3a5728f7d4ed097deb7"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T04:22:12.081769","string":"2016-09-06T04:22:12.081769"},"revision_date":{"kind":"timestamp","value":"2012-07-21T16:54:24","string":"2012-07-21T16:54:24"},"committer_date":{"kind":"timestamp","value":"2012-07-21T16:54:24","string":"2012-07-21T16:54:24"},"github_id":{"kind":"number","value":3192187,"string":"3,192,187"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n#\n# File: genbank.py\n#\n# Copyright (c) 2010 by Mauro Amico (Biodec Srl)\n#\n# GNU General Public License (GPL)\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n# 02110-1301, USA.\n#\n# @version $Revision$:\n# @author $Author$:\n# @date $Date$:\n\nfrom Products.Five import BrowserView\nfrom StringIO import StringIO\nfrom Bio import SeqIO\n\n\nclass SeqRecord2Genbank(BrowserView):\n \"\"\" \"\"\"\n def __call__(self):\n io = StringIO()\n # FIXME:\n # self.context.Description()\n seqrecord = self.context.getSeqRecord()\n # the maximum length of locus name, for genbak format, is 16\n seqrecord.name = seqrecord.name[:16]\n # features\n for f in seqrecord.features:\n f.type = f.type.replace(\" \", \"_\")\n SeqIO.write([seqrecord, ], io, \"genbank\")\n return io.getvalue()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":40051,"cells":{"__id__":{"kind":"number","value":4131758578236,"string":"4,131,758,578,236"},"blob_id":{"kind":"string","value":"7160983a1e3d6355dfbc00efb0b6f34c9baabb4d"},"directory_id":{"kind":"string","value":"e92ac1b69016d59d2793ed14e50c5e5d50c95bae"},"path":{"kind":"string","value":"/src/main.py"},"content_id":{"kind":"string","value":"78d9801805a3e1d16e2ee097f74139df5c12156a"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"centip3de/BFInterp"},"repo_url":{"kind":"string","value":"https://github.com/centip3de/BFInterp"},"snapshot_id":{"kind":"string","value":"f049a21d898db526535df6b6394b8d425f97d95d"},"revision_id":{"kind":"string","value":"ab34c994eac651ac271f39d6ceb4b965269b3819"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-05-02T06:57:01.249629","string":"2021-05-02T06:57:01.249629"},"revision_date":{"kind":"timestamp","value":"2014-09-18T21:09:38","string":"2014-09-18T21:09:38"},"committer_date":{"kind":"timestamp","value":"2014-09-18T21:09:38","string":"2014-09-18T21:09:38"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import sys\n\nclass Interp():\n def __init__(self, tokens):\n self.ptr = 0\n self.pos = 0\n self.mem = [0]\n self.tokens = tokens\n self.brace_map = build_brace_map(tokens)\n\n def next(self):\n self.ptr += 1\n self.mem.append(0) \n\n def prev(self):\n self.ptr -= 1\n\n def add(self):\n self.mem[self.ptr] = (self.mem[self.ptr] + 1) % 256\n\n def sub(self):\n self.mem[self.ptr] = (self.mem[self.ptr] - 1) % 256\n\n def output(self):\n print(chr(self.mem[self.ptr]), end=\"\")\n\n def user_input(self):\n ui = input(\"\")\n self.mem[self.ptr] = ord(ui[0])\n\n def get_token(self):\n return self.tokens[self.pos]\n\n def atEnd(self):\n return len(self.tokens) == self.pos\n\n def test_while(self):\n return self.mem[self.ptr] != 0\n\n def end_brace(self):\n return self.brace_map[self.pos]\n\ndef build_brace_map(tokens):\n\n lbrace_stack = []\n brace_map = {}\n\n for i, token in enumerate(tokens):\n\n if token == '[':\n lbrace_stack.append(i)\n\n elif token == ']':\n lbrace = lbrace_stack.pop()\n brace_map[lbrace] = i\n\n return brace_map\n \n\ndef execute(interp):\n\n call_stack = []\n\n while(not interp.atEnd()):\n token = interp.get_token()\n\n if(token == '>'):\n interp.next()\n\n elif(token == '<'):\n interp.prev()\n\n elif(token == '.'):\n interp.output()\n\n elif(token == ','):\n interp.user_input()\n\n elif(token == '+'):\n interp.add()\n\n elif(token == '-'):\n interp.sub()\n\n elif(token == '['):\n if(interp.test_while()):\n call_stack.append(interp.pos)\n else:\n interp.pos = interp.end_brace()\n\n elif(token == ']'):\n interp.pos = call_stack.pop() - 1\n\n else:\n pass\n\n interp.pos += 1\n \ndef main():\n\n if len(sys.argv) == 2:\n fp = open(sys.argv[1], 'r')\n text = fp.read()\n bf = Interp(text)\n execute(bf)\n\n else:\n print(\"ERROR\")\n\nif __name__ == \"__main__\":\n main()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":40052,"cells":{"__id__":{"kind":"number","value":12386685720561,"string":"12,386,685,720,561"},"blob_id":{"kind":"string","value":"0d1b328a34ee8e18b999a906ad83e3ffd9f95f63"},"directory_id":{"kind":"string","value":"c6d0cba0959d04c0ff6da6490feee64095647587"},"path":{"kind":"string","value":"/collective/pwexpiry/browser/preferences/pwexpirycontrolpanel.py"},"content_id":{"kind":"string","value":"4b90ebd26ab0128727013c3da4f64c4152d101d7"},"detected_licenses":{"kind":"list like","value":["ZPL-2.1"],"string":"[\n \"ZPL-2.1\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"fourdigits/collective.pwexpiry"},"repo_url":{"kind":"string","value":"https://github.com/fourdigits/collective.pwexpiry"},"snapshot_id":{"kind":"string","value":"4fcc2c24c533e9db3235a59d51fc659a398155e5"},"revision_id":{"kind":"string","value":"8908cb50bc0f52195be32612d45f968f59542a3d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T18:04:59.251632","string":"2021-01-18T18:04:59.251632"},"revision_date":{"kind":"timestamp","value":"2014-02-24T16:03:41","string":"2014-02-24T16:03:41"},"committer_date":{"kind":"timestamp","value":"2014-02-24T16:03:41","string":"2014-02-24T16:03:41"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from itertools import chain\n\nfrom DateTime import DateTime\nfrom Acquisition import aq_inner\n\nfrom zope.component import getMultiAdapter\nfrom plone.app.controlpanel.usergroups import UsersOverviewControlPanel\nfrom plone.protect import CheckAuthenticator\nfrom Products.CMFCore.utils import getToolByName\nfrom Products.CMFPlone.utils import normalizeString\nfrom Products.CMFPlone import PloneMessageFactory as _\n\nclass PwExpiryControlPanel(UsersOverviewControlPanel):\n\n def __call__(self):\n\n form = self.request.form\n submitted = form.get('form.submitted', False)\n search = form.get('form.button.Search', None) is not None\n findAll = form.get('form.button.FindAll', None) is not None\n self.searchString = not findAll and form.get('searchstring', '') or ''\n self.searchResults = []\n self.newSearch = False\n\n if search or findAll:\n self.newSearch = True\n\n if submitted:\n if form.get('form.button.Modify', None) is not None:\n self.manageUser(form.get('users', None),)\n\n if not(self.many_users) or bool(self.searchString):\n self.searchResults = self.doSearch(self.searchString)\n return self.index()\n\n def doSearch(self, searchString):\n mtool = getToolByName(self, 'portal_membership')\n searchView = getMultiAdapter((aq_inner(self.context), self.request),\n name='pas_search')\n explicit_users = searchView.merge(chain(\n *[searchView.searchUsers(**{field: searchString}\n ) for field in ['login', 'fullname', 'email']]), 'userid')\n results = []\n for user_info in explicit_users:\n userId = user_info['id']\n user = mtool.getMemberById(userId)\n if user is None:\n continue\n user_info['password_date'] = \\\n user.getProperty('password_date', '2000/01/01')\n user_info['last_notification_date'] = \\\n user.getProperty('last_notification_date', '2000/01/01')\n user_info['fullname'] = user.getProperty('fullname', '')\n results.append(user_info)\n\n results.sort(key=lambda x: x is not None and x['fullname'] is not None and \\\n normalizeString(x['fullname']) or '')\n return results\n\n def manageUser(self, users=None):\n if users is None:\n users = []\n CheckAuthenticator(self.request)\n\n if users:\n context = aq_inner(self.context)\n mtool = getToolByName(context, 'portal_membership')\n utils = getToolByName(context, 'plone_utils')\n\n for user in users:\n member = mtool.getMemberById(user.id)\n\n password_date = member.getProperty('password_date', '2000/01/01')\n new_password_date = DateTime(user.get('password'))\n if password_date != new_password_date:\n member.setMemberProperties(\n {'password_date': new_password_date}\n )\n\n notification_date = member.getProperty(\n 'last_notification_date', '2000/01/01'\n )\n new_notification = DateTime(user.get('notification'))\n if notification_date != new_notification:\n member.setMemberProperties(\n {'last_notification_date': new_notification}\n )\n\n utils.addPortalMessage(_(u'Changes applied.'))\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":40053,"cells":{"__id__":{"kind":"number","value":5334349400016,"string":"5,334,349,400,016"},"blob_id":{"kind":"string","value":"c9692be1887097c1f40e4963a3edc1db83662163"},"directory_id":{"kind":"string","value":"e32121b1abf9ef34a527f09c40f9cfbc3d50fbc9"},"path":{"kind":"string","value":"/skeinforge_tools/craft_plugins/fill.py"},"content_id":{"kind":"string","value":"243698f73bfe63718085114be0b37986015b02a3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"bmander/skeinforge"},"repo_url":{"kind":"string","value":"https://github.com/bmander/skeinforge"},"snapshot_id":{"kind":"string","value":"32b72f1f9e9cf26ac7a2f96b1084ff8e83ae44c8"},"revision_id":{"kind":"string","value":"fd69d8e856780c826386dc973ceabcc03623f3e8"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-19T05:05:45.974884","string":"2021-01-19T05:05:45.974884"},"revision_date":{"kind":"timestamp","value":"2010-02-11T07:38:43","string":"2010-02-11T07:38:43"},"committer_date":{"kind":"timestamp","value":"2010-02-11T07:38:43","string":"2010-02-11T07:38:43"},"github_id":{"kind":"number","value":512758,"string":"512,758"},"star_events_count":{"kind":"number","value":34,"string":"34"},"fork_events_count":{"kind":"number","value":17,"string":"17"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#! /usr/bin/env python\n\"\"\"\nThis page is in the table of contents.\nFill is a script to fill the perimeters of a gcode file.\n\nThe fill manual page is at:\nhttp://www.bitsfrombytes.com/wiki/index.php?title=Skeinforge_Fill\n\nAllan Ecker aka The Masked Retriever has written the \"Skeinforge Quicktip: Fill\" at:\nhttp://blog.thingiverse.com/2009/07/21/mysteries-of-skeinforge-fill/\n\n==Operation==\nThe default 'Activate Fill' checkbox is off. When it is on, the functions described below will work, when it is off, the functions will not be called.\n\n==Settings==\n===Diaphragm===\nThe diaphragm is a solid group of layers, at regular intervals. It can be used with a sparse infill to give the object watertight, horizontal compartments and/or a higher shear strength.\n\n====Diaphragm Period====\nDefault is one hundred.\n\nDefines the number of layers between diaphrams.\n\n====Diaphragm Thickness====\nDefault is zero, because the diaphragm feature is rarely used.\n\nDefines the number of layers the diaphram is composed of.\n\n===Extra Shells===\nThe shells interior perimeter loops. Adding extra shells makes the object stronger & heavier.\n\n====Extra Shells on Alternating Solid Layers====\nDefault is two.\n\nDefines the number of extra shells, on the alternating solid layers.\n\n====Extra Shells on Base====\nDefault is one.\n\nDefines the number of extra shells on the bottom, base layer and every even solid layer after that. Setting this to a different value than the \"Extra Shells on Alternating Solid Layers\" means the infill pattern will alternate, creating a strong interleaved bond even if the perimeter loop shrinks.\n\n====Extra Shells on Sparse Layer====\nDefault is one.\n\nDefines the number of extra shells on the sparse layers. The solid layers are those at the top & bottom, and wherever the object has a plateau or overhang, the sparse layers are the layers in between.\n\n===Grid===\n====Grid Extra Overlap====\nDefault is 0.1.\n\nDefines the amount of extra overlap added when extruding the grid to compensate for the fact that when the first thread going through a grid point is extruded, since there is nothing there yet for it to connect to it will shrink extra.\n\n====Grid Junction Separation over Octogon Radius At End====\nDefault is zero.\n\nDefines the ratio of the amount the grid square is increased in each direction over the extrusion width at the end, the default is zero. With a value of one or so the grid pattern will have large squares to go with the octogons.\n\n====Grid Junction Separation over Octogon Radius At Middle====\nDefault is zero.\n\nDefines the increase at the middle. If this value is different than the value at the end, the grid would have an accordion pattern, which would give it a higher shear strength.\n\n====Grid Junction Separation Band Height====\nDefault is ten.\n\nDefines the height of the bands of the accordion pattern.\n\n===Infill===\n====Infill Pattern====\nDefault is 'Line', since it is quicker to generate and does not add extra movements for the extruder. The grid pattern has extra diagonal lines, so when choosing a grid option, set the infill solidity to 0.2 or less so that there is not too much plastic and the grid generation time, which increases with the third power of solidity, will be reasonable.\n\n=====Grid Hexagonal=====\nWhen selected, the infill will be a hexagonal grid. Because the grid is made with threads rather than with molding or milling, only a partial hexagon is possible, so the rectangular grid pattern is stronger.\n\n=====Grid Rectangular=====\nWhen selected, the infill will be a funky octogon square honeycomb like pattern which gives the object extra strength.\n\n=====Line=====\nWhen selected, the infill will be made up of lines.\n\n====Infill Begin Rotation====\nDefault is forty five degrees, giving a diagonal infill.\n\nDefines the amount the infill direction of the base and every second layer thereafter is rotated.\n\n====Infill Odd Layer Extra Rotation====\nDefault is ninety degrees, making the odd layer infill perpendicular to the base layer.\n\nDefines the extra amount the infill direction of the odd layers is rotated compared to the base layer.\n\n====Infill Begin Rotation Repeat====\nDefault is one, giving alternating cross hatching.\n\nDefines the number of layers that the infill begin rotation will repeat. With a value higher than one, the infill will go in one direction more often, giving the object more strength in one direction and less in the other, this is useful for beams and cantilevers.\n\n====Infill Perimeter Overlap====\nDefault is 0.15.\n\nDefines the amount the infill overlaps the perimeter over the average of the perimeter and infill width. The higher the value the more the infill will overlap the perimeter, and the thicker join between the infill and the perimeter. If the value is too high, the join will be so thick that the nozzle will run plow through the join below making a mess, also when it is above 0.7 fill may not be able to create infill correctly. If you want to stretch the infill a lot, set 'Path Stretch over Perimeter Width' in stretch to a high value.\n\n====Infill Solidity====\nDefault is 0.2.\n\nDefines the solidity of the infill, this is the most important setting in fill. A value of one means the infill lines will be right beside each other, resulting in a solid, strong, heavy shape which takes a long time to extrude. A low value means the infill will be sparse, the interior will be mosty empty space, the object will be weak, light and quick to build.\n\n====Interior Infill Density over Exterior Density====\nDefault is 0.9.\n\nDefines the ratio of the infill density of the interior over the infill density of the exterior surfaces. The exterior should have a high infill density, so that the surface will be strong and watertight. With the interior infill density a bit lower than the exterior, the plastic will not fill up higher than the extruder nozzle. If the interior density is too high that could happen, as Nophead described in the Hydraraptor \"Bearing Fruit\" post at:\nhttp://hydraraptor.blogspot.com/2008/08/bearing-fruit.html\n\n====Infill Width over Thickness====\nDefault is 1.5.\n\nDefines the ratio of the infill width over the layer thickness. The higher the value the wider apart the infill will be and therefore the sparser the infill will be.\n\n===Solid Surface Thickness===\nDefault is three.\n\nDefines the number of solid layers that are at the bottom, top, plateaus and overhang. With a value of zero, the entire object will be composed of a sparse infill, and water could flow right through it. With a value of one, water will leak slowly through the surface and with a value of three, the object could be watertight. The higher the solid surface thickness, the stronger and heavier the object will be.\n\n===Thread Sequence Choice===\nThe 'Thread Sequence Choice' is the sequence in which the threads will be extruded. There are three kinds of thread, the perimeter threads on the outside of the object, the loop threads aka inner shell threads, and the interior infill threads.\n\nThe default choice is 'Perimeter > Loops > Infill', which the default stretch parameters are based on. If you change from the default sequence choice setting of perimeter, then loops, then infill, the optimal stretch thread parameters would also be different. In general, if the infill is extruded first, the infill would have to be stretched more so that even after the filament shrinkage, it would still be long enough to connect to the loop or perimeter. The six sequence combinations follow below.\n\n====Infill > Loops > Perimeter====\n====Infill > Perimeter > Loops====\n====Loops > Infill > Perimeter====\n====Loops > Perimeter > Infill====\n====Perimeter > Infill > Loops====\n====Perimeter > Loops > Infill====\n\n==Examples==\nThe following examples fill the file Screw Holder Bottom.stl. The examples are run in a terminal in the folder which contains Screw Holder Bottom.stl and fill.py.\n\n\n> python fill.py\nThis brings up the fill dialog.\n\n\n> python fill.py Screw Holder Bottom.stl\nThe fill tool is parsing the file:\nScrew Holder Bottom.stl\n..\nThe fill tool has created the file:\n.. Screw Holder Bottom_fill.gcode\n\n\n> python\nPython 2.5.1 (r251:54863, Sep 22 2007, 01:43:31)\n[GCC 4.2.1 (SUSE Linux)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import fill\n>>> fill.main()\nThis brings up the fill dialog.\n\n\n>>> fill.writeOutput( 'Screw Holder Bottom.stl' )\nThe fill tool is parsing the file:\nScrew Holder Bottom.stl\n..\nThe fill tool has created the file:\n.. Screw Holder Bottom_fill.gcode\n\n\"\"\"\n\nfrom __future__ import absolute_import\ntry:\n\timport psyco\n\tpsyco.full()\nexcept:\n\tpass\n#Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module.\nimport __init__\n\nfrom skeinforge_tools import profile\nfrom skeinforge_tools.meta_plugins import polyfile\nfrom skeinforge_tools.skeinforge_utilities import consecution\nfrom skeinforge_tools.skeinforge_utilities import euclidean\nfrom skeinforge_tools.skeinforge_utilities import gcodec\nfrom skeinforge_tools.skeinforge_utilities import intercircle\nfrom skeinforge_tools.skeinforge_utilities import interpret\nfrom skeinforge_tools.skeinforge_utilities import settings\nfrom skeinforge_tools.skeinforge_utilities.vector3 import Vector3\nimport math\nimport sys\n\n\n__author__ = \"Enrique Perez (perez_enrique@yahoo.com)\"\n__date__ = \"$Date: 2008/28/04 $\"\n__license__ = \"GPL 3.0\"\n\n\n# make fillBoundaries, getLastExistingLoops, try setting def getExtraFillLoops( insideLoops, outsideLoop, radius ):\tgreaterThanRadius to 1.2 * radius\n# save just before printing\n# create skeinforge_profile, skeinforge_help, etc..\n#\n# documentation\n# chop add extra layers documentation\n# coil documentation\n# winding documentation\n# stretch cross documentation\n# clip 'Connect Loops' documentation\n# coil, cleave documentation\n# circular wave, py documentation\n# inset loop order documentation\n# raft base interface temperature documentation\n# update plugin documentation\n# behold negative positive axis, remove xyz axis documentation\n# widen documentation\n# skeinview numeric pointer documentation\n# raft infill overhang.. values should be halved, raft in general has been changed, stretch cross, clip connect announce\n# update wiki how to page\n# move alterations and profiles to top level\n# fill_only\n#\n#\n#\n#\n# make frame for plugin groups, add plugin help menu, add craft below menu\n# veer\n# add hook _extrusion\n # implement acceleration & collinear removal in viewers _extrusion\n# maybe measuring rod\n# add polish, has perimeter, has cut first layer (False)\n# probably not set addedLocation in distanceFeedRate after arc move\n# maybe horizontal bridging and/or check to see if the ends are standing on anything\n# maybe add cached zones on first carving\n# thin self? check when removing intersecting paths in inset\n# maybe later remove isPerimeterPathInSurroundLoops, once there are no weird fill bugs, also change getHorizontalSegmentListsFromLoopLists\n# save all analyze viewers of the same name except itself, update help menu self.wikiManualPrimary.setUpdateFunction\n# check alterations folder first, if there is something copy it to the home directory, if not check the home directory\n# raft to temperature, raft\n#\n#\n#\n# help primary menu item refresh\n# integral thin width _extrusion\n# xml & svg more forgiving, svg make defaults for layerThickness, maxZ, minZ, add layer z to svg_template, make the slider on the template track even when mouse is outside\n# layer color, for multilayer start http://reprap.org/pub/Main/MultipleMaterialsFiles/legend.xml _extrusion\n# option of surrounding lines in display\n# maybe add connecting line in display line\n# maybe check inset loops to see if they have are smaller, but this would be slow\n# maybe status bar\n# maybe measurement ruler mouse tool\n# search rss from blogs, add search links for common materials, combine created on or progress bar with searchable help\n#boundaries, center radius z bottom top, circular or rectangular, polygon, put cool minimum radius orbits within boundaries\n# move & rotate model\n# comb improve running jump\n# trial, meta in a grid settings\n#laminate tool head\n#maybe use 5x5 radius search in circle node\n#maybe add layer updates in behold, skeinview and maybe others\n#lathe winding, extrusion and cutting; synonym for rotation or turning, loop angle\n# maybe split into source code and documentation sections\n# transform plugins, start with sarrus http://www.thingiverse.com/thing:1425\n# maybe make setting backups\n# maybe settings in gcode or saved versions\n# move skeinforge_utilities to fabmetheus_utilities\n#\n#\n#\n# pick and place\n# simulate\n#document gear script\n#transform\n#extrude loops I guess make circles? and/or run along sparse infill\n#custom inclined plane, inclined plane from model, screw, fillet travel as well maybe\n# probably not stretch single isLoop\n#maybe much afterwards make congajure multistep view\n#maybe stripe although model colors alone can handle it\n#stretch fiber around shape, maybe modify winding for asymmetric shapes\n#multiple heads around edge\n#maybe add full underscored date name for version\n#maybe add rarely used tool option\n#angle shape for overhang extrusions\n# maybe double height shells option _extrusion\n#maybe m111? countdown\n#make stl instead of essentially gts the default format\n#common tool\n#first time tool tip\n#individual tool tip to place in text\n# maybe try to simplify raft layer start\n# maybe make temp directory\n# maybe carve aoi xml testing and check xml gcode\n# maybe cross hatch support polishing???\n# maybe print svg view from current layer or zero layer in single view\n# maybe check if tower is picking the nearest island\n# maybe combine skein classes in fillet\n# maybe isometric svg option\n\n#Manual\n#10,990\n#11,1776\n#12,3304\n#1,4960\n#2, 7077\n#85 jan7, 86jan11, 87 jan13, 88 jan15, 91 jan21, 92 jan23, 95 jan30\n#make one piece electromagnet spool\n#stepper rotor with ceramic disk magnet in middle, electromagnet with long thin spool line?\n#stepper motor\n#make plastic coated thread in vat with pulley\n#tensile stuart platform\n#kayak\n#gear vacuum pump\n#gear turbine\n#heat engine\n#solar power\n#sailboat\n#yacht\n#house\n#condo with reflected gardens in between buildings\n#medical equipment\n#cell counter, etc..\n#pipe clamp lathe\n# square tube driller & cutter\n\n# archihedron\n# look from top of intersection circle plane to look for next, add a node; tree out until all are stepped on then connect, when more than three intersections are close\n# when loading a file, we should have a preview of the part and orientation in space\n# second (and most important in my opinion) would be the ability to rotate the part on X/Y/Z axis to chose it's orientation\n# third, a routine to detect the largest face and orient the part accordingly. Mat http://reprap.kumy.net/\n# concept, three perpendicular slices to get display spheres\n# extend lines around short segment after cross hatched boolean\n# concept, teslocracy; donation, postponement, rotate ad network, probably not gutenpedia, cached search options\n# concept, join cross slices, go from vertex to two orthogonal edges, then from edges to each other, if not to a common point, then simplify polygons by removing points which do not change the area much\n# concept, each node is fourfold, use sorted intersectionindexes to find close, connect each double sided edge\n# concept, in file, store polygon mesh and centers\n# concept, display spheres or polygons would have original triangle for work plane\n# .. then again no point with slices\n# concept, filled slices, about 2 mm thick\n# concept, rgb color triangle switch to get inside color, color golden ratio on 5:11 slope with a modulo 3 face\n# concept, interlaced bricks at corners ( length proportional to corner angle )\n# concept, new links to archi, import links to archi and adds skeinforge tool menu item, back on skeinforge named execute tool is added\n# concept, trnsnt\n# concept, inscribed key silencer\n# concept, spreadsheet to python and/or javascript\n# concept, blog, frequent updates, mix associated news\n\ndef addAroundGridPoint( arounds, gridPoint, gridPointInsetX, gridPointInsetY, gridPoints, gridSearchRadius, isBothOrNone, isDoubleJunction, isJunctionWide, paths, pixelTable, width ):\n\t\"Add the path around the grid point.\"\n\tclosestPathIndex = None\n\taroundIntersectionPaths = []\n\tfor aroundIndex in xrange( len( arounds ) ):\n\t\tloop = arounds[ aroundIndex ]\n\t\tfor pointIndex in xrange( len( loop ) ):\n\t\t\tpointFirst = loop[ pointIndex ]\n\t\t\tpointSecond = loop[ ( pointIndex + 1 ) % len( loop ) ]\n\t\t\tyIntersection = getYIntersectionIfExists( pointFirst, pointSecond, gridPoint.real )\n\t\t\taddYIntersectionPathToList( aroundIndex, pointIndex, gridPoint.imag, yIntersection, aroundIntersectionPaths )\n\tif len( aroundIntersectionPaths ) < 2:\n\t\tprint( 'This should never happen, aroundIntersectionPaths is less than 2 in fill.' )\n\t\tprint( aroundIntersectionPaths )\n\t\tprint( gridPoint )\n\t\treturn\n\tyCloseToCenterArounds = getClosestOppositeIntersectionPaths( aroundIntersectionPaths )\n\tif len( yCloseToCenterArounds ) < 2:\n\t\tprint( 'This should never happen, yCloseToCenterArounds is less than 2 in fill.' )\n\t\tprint( gridPoint )\n\t\treturn\n\tsegmentFirstY = min( yCloseToCenterArounds[ 0 ].y, yCloseToCenterArounds[ 1 ].y )\n\tsegmentSecondY = max( yCloseToCenterArounds[ 0 ].y, yCloseToCenterArounds[ 1 ].y )\n\tyIntersectionPaths = []\n\tgridPixel = euclidean.getStepKeyFromPoint( gridPoint / width )\n\tsegmentFirstPixel = euclidean.getStepKeyFromPoint( complex( gridPoint.real, segmentFirstY ) / width )\n\tsegmentSecondPixel = euclidean.getStepKeyFromPoint( complex( gridPoint.real, segmentSecondY ) / width )\n\tpathIndexTable = {}\n\taddPathIndexFirstSegment( gridPixel, pathIndexTable, pixelTable, segmentFirstPixel )\n\taddPathIndexSecondSegment( gridPixel, pathIndexTable, pixelTable, segmentSecondPixel )\n\tfor pathIndex in pathIndexTable.keys():\n\t\tpath = paths[ pathIndex ]\n\t\tfor pointIndex in xrange( len( path ) - 1 ):\n\t\t\tpointFirst = path[ pointIndex ]\n\t\t\tpointSecond = path[ pointIndex + 1 ]\n\t\t\tyIntersection = getYIntersectionInsideYSegment( segmentFirstY, segmentSecondY, pointFirst, pointSecond, gridPoint.real )\n\t\t\taddYIntersectionPathToList( pathIndex, pointIndex, gridPoint.imag, yIntersection, yIntersectionPaths )\n\tif len( yIntersectionPaths ) < 1:\n\t\treturn\n\tyCloseToCenterPaths = []\n\tif isDoubleJunction:\n\t\tyCloseToCenterPaths = getClosestOppositeIntersectionPaths( yIntersectionPaths )\n\telse:\n\t\tyIntersectionPaths.sort( compareDistanceFromCenter )\n\t\tyCloseToCenterPaths = [ yIntersectionPaths[ 0 ] ]\n\tfor yCloseToCenterPath in yCloseToCenterPaths:\n\t\tsetIsOutside( yCloseToCenterPath, yIntersectionPaths )\n\tif len( yCloseToCenterPaths ) < 2:\n\t\tyCloseToCenterPaths[ 0 ].gridPoint = gridPoint\n\t\tinsertGridPointPair( gridPoint, gridPointInsetX, gridPoints, isJunctionWide, paths, pixelTable, yCloseToCenterPaths[ 0 ], width )\n\t\treturn\n\tplusMinusSign = getPlusMinusSign( yCloseToCenterPaths[ 1 ].y - yCloseToCenterPaths[ 0 ].y )\n\tyCloseToCenterPaths[ 0 ].gridPoint = complex( gridPoint.real, gridPoint.imag - plusMinusSign * gridPointInsetY )\n\tyCloseToCenterPaths[ 1 ].gridPoint = complex( gridPoint.real, gridPoint.imag + plusMinusSign * gridPointInsetY )\n\tyCloseToCenterPaths.sort( comparePointIndexDescending )\n\tinsertGridPointPairs( gridPoint, gridPointInsetX, gridPoints, yCloseToCenterPaths[ 0 ], yCloseToCenterPaths[ 1 ], isBothOrNone, isJunctionWide, paths, pixelTable, width )\n\ndef addPath( infillWidth, infillPaths, path, rotationPlaneAngle ):\n\t\"Add simplified path to fill.\"\n\tsimplifiedPath = euclidean.getSimplifiedPath( path, infillWidth )\n\tif len( simplifiedPath ) < 2:\n\t\treturn\n\tplaneRotated = euclidean.getPointsRoundZAxis( rotationPlaneAngle, simplifiedPath )\n\tinfillPaths.append( planeRotated )\n\ndef addPathIndexFirstSegment( gridPixel, pathIndexTable, pixelTable, segmentFirstPixel ):\n\t\"Add the path index of the closest segment found toward the second segment.\"\n\tfor yStep in xrange( gridPixel[ 1 ], segmentFirstPixel[ 1 ] - 1, - 1 ):\n\t\tif getKeyIsInPixelTableAddValue( ( gridPixel[ 0 ], yStep ), pathIndexTable, pixelTable ):\n\t\t\treturn\n\ndef addPathIndexSecondSegment( gridPixel, pathIndexTable, pixelTable, segmentSecondPixel ):\n\t\"Add the path index of the closest segment found toward the second segment.\"\n\tfor yStep in xrange( gridPixel[ 1 ], segmentSecondPixel[ 1 ] + 1 ):\n\t\tif getKeyIsInPixelTableAddValue( ( gridPixel[ 0 ], yStep ), pathIndexTable, pixelTable ):\n\t\t\treturn\n\ndef addPointOnPath( path, pathIndex, pixelTable, point, pointIndex, width ):\n\t\"Add a point to a path and the pixel table.\"\n\tpointIndexMinusOne = pointIndex - 1\n\tif pointIndex < len( path ) and pointIndexMinusOne >= 0:\n\t\tsegmentTable = {}\n\t\tbegin = path[ pointIndexMinusOne ]\n\t\tend = path[ pointIndex ]\n\t\teuclidean.addValueSegmentToPixelTable( begin, end, segmentTable, pathIndex, width )\n\t\teuclidean.removePixelTableFromPixelTable( segmentTable, pixelTable )\n\tif pointIndexMinusOne >= 0:\n\t\tbegin = path[ pointIndexMinusOne ]\n\t\teuclidean.addValueSegmentToPixelTable( begin, point, pixelTable, pathIndex, width )\n\tif pointIndex < len( path ):\n\t\tend = path[ pointIndex ]\n\t\teuclidean.addValueSegmentToPixelTable( point, end, pixelTable, pathIndex, width )\n\tpath.insert( pointIndex, point )\n\ndef addPointOnPathIfFree( path, pathIndex, pixelTable, point, pointIndex, width ):\n\t\"Add the closest point to a path, if the point added to a path is free.\"\n\tif isAddedPointOnPathFree( path, pixelTable, point, pointIndex, width ):\n\t\taddPointOnPath( path, pathIndex, pixelTable, point, pointIndex, width )\n\ndef addShortenedLineSegment( lineSegment, shortenDistance, shortenedSegments ):\n\t\"Add shortened line segment.\"\n\tpointBegin = lineSegment[ 0 ].point\n\tpointEnd = lineSegment[ 1 ].point\n\tsegment = pointEnd - pointBegin\n\tsegmentLength = abs( segment )\n\tif segmentLength < 2.1 * shortenDistance:\n\t\treturn\n\tsegmentShorten = segment * shortenDistance / segmentLength\n\tlineSegment[ 0 ].point = pointBegin + segmentShorten\n\tlineSegment[ 1 ].point = pointEnd - segmentShorten\n\tshortenedSegments.append( lineSegment )\n\ndef addSparseEndpoints( doubleExtrusionWidth, endpoints, fillLine, horizontalSegmentLists, infillSolidity, removedEndpoints, solidSurfaceThickness, surroundingXIntersections ):\n\t\"Add sparse endpoints.\"\n\thorizontalEndpoints = horizontalSegmentLists[ fillLine ]\n\tfor segment in horizontalEndpoints:\n\t\taddSparseEndpointsFromSegment( doubleExtrusionWidth, endpoints, fillLine, horizontalSegmentLists, infillSolidity, removedEndpoints, segment, solidSurfaceThickness, surroundingXIntersections )\n\ndef addSparseEndpointsFromSegment( doubleExtrusionWidth, endpoints, fillLine, horizontalSegmentLists, infillSolidity, removedEndpoints, segment, solidSurfaceThickness, surroundingXIntersections ):\n\t\"Add sparse endpoints from a segment.\"\n\tendpointFirstPoint = segment[ 0 ].point\n\tendpointSecondPoint = segment[ 1 ].point\n\tif fillLine < 1 or fillLine >= len( horizontalSegmentLists ) - 1 or surroundingXIntersections == None:\n\t\tendpoints += segment\n\t\treturn\n\tif infillSolidity > 0.0:\n\t\tif int( round( round( fillLine * infillSolidity ) / infillSolidity ) ) == fillLine:\n\t\t\tendpoints += segment\n\t\t\treturn\n\tif abs( endpointFirstPoint - endpointSecondPoint ) < doubleExtrusionWidth:\n\t\tendpoints += segment\n\t\treturn\n\tif not isSegmentAround( horizontalSegmentLists[ fillLine - 1 ], segment ):\n\t\tendpoints += segment\n\t\treturn\n\tif not isSegmentAround( horizontalSegmentLists[ fillLine + 1 ], segment ):\n\t\tendpoints += segment\n\t\treturn\n\tif solidSurfaceThickness == 0:\n\t\tremovedEndpoints += segment\n\t\treturn\n\tif isSegmentCompletelyInAnIntersection( segment, surroundingXIntersections ):\n\t\tremovedEndpoints += segment\n\t\treturn\n\tendpoints += segment\n\ndef addYIntersectionPathToList( pathIndex, pointIndex, y, yIntersection, yIntersectionPaths ):\n\t\"Add the y intersection path to the y intersection paths.\"\n\tif yIntersection == None:\n\t\treturn\n\tyIntersectionPath = YIntersectionPath( pathIndex, pointIndex, yIntersection )\n\tyIntersectionPath.yMinusCenter = yIntersection - y\n\tyIntersectionPaths.append( yIntersectionPath )\n\ndef compareDistanceFromCenter( self, other ):\n\t\"Get comparison in order to sort y intersections in ascending order of distance from the center.\"\n\tdistanceFromCenter = abs( self.yMinusCenter )\n\tdistanceFromCenterOther = abs( other.yMinusCenter )\n\tif distanceFromCenter > distanceFromCenterOther:\n\t\treturn 1\n\tif distanceFromCenter < distanceFromCenterOther:\n\t\treturn - 1\n\treturn 0\n\ndef comparePointIndexDescending( self, other ):\n\t\"Get comparison in order to sort y intersections in descending order of point index.\"\n\tif self.pointIndex > other.pointIndex:\n\t\treturn - 1\n\tif self.pointIndex < other.pointIndex:\n\t\treturn 1\n\treturn 0\n\ndef createExtraFillLoops( radius, surroundingLoop ):\n\t\"Create extra fill loops.\"\n\tfor innerSurrounding in surroundingLoop.innerSurroundings:\n\t\tcreateFillForSurroundings( radius, innerSurrounding.innerSurroundings )\n\toutsides = []\n\tinsides = euclidean.getInsidesAddToOutsides( surroundingLoop.getFillLoops(), outsides )\n\tallFillLoops = []\n\tfor outside in outsides:\n\t\ttransferredLoops = euclidean.getTransferredPaths( insides, outside )\n\t\tallFillLoops += getExtraFillLoops( transferredLoops, outside, radius )\n\tsurroundingLoop.lastFillLoops = allFillLoops\n\tsurroundingLoop.extraLoops += allFillLoops\n\tif len( allFillLoops ) > 0:\n\t\tsurroundingLoop.lastExistingFillLoops = allFillLoops\n\ndef createFillForSurroundings( radius, surroundingLoops ):\n\t\"Create extra fill loops for surrounding loops.\"\n\tfor surroundingLoop in surroundingLoops:\n\t\tcreateExtraFillLoops( radius, surroundingLoop )\n\ndef getAdditionalLength( path, point, pointIndex ):\n\t\"Get the additional length added by inserting a point into a path.\"\n\tif pointIndex == 0:\n\t\treturn abs( point - path[ 0 ] )\n\tif pointIndex == len( path ):\n\t\treturn abs( point - path[ - 1 ] )\n\treturn abs( point - path[ pointIndex - 1 ] ) + abs( point - path[ pointIndex ] ) - abs( path[ pointIndex ] - path[ pointIndex - 1 ] )\n\ndef getCraftedText( fileName, gcodeText = '', fillRepository = None ):\n\t\"Fill the inset file or gcode text.\"\n\treturn getCraftedTextFromText( gcodec.getTextIfEmpty( fileName, gcodeText ), fillRepository )\n\ndef getCraftedTextFromText( gcodeText, fillRepository = None ):\n\t\"Fill the inset gcode text.\"\n\tif gcodec.isProcedureDoneOrFileIsEmpty( gcodeText, 'fill' ):\n\t\treturn gcodeText\n\tif fillRepository == None:\n\t\tfillRepository = settings.getReadRepository( FillRepository() )\n\tif not fillRepository.activateFill.value:\n\t\treturn gcodeText\n\treturn FillSkein().getCraftedGcode( fillRepository, gcodeText )\n\ndef getClosestOppositeIntersectionPaths( yIntersectionPaths ):\n\t\"Get the close to center paths, starting with the first and an additional opposite if it exists.\"\n\tyIntersectionPaths.sort( compareDistanceFromCenter )\n\tbeforeFirst = yIntersectionPaths[ 0 ].yMinusCenter < 0.0\n\tyCloseToCenterPaths = [ yIntersectionPaths[ 0 ] ]\n\tfor yIntersectionPath in yIntersectionPaths[ 1 : ]:\n\t\tbeforeSecond = yIntersectionPath.yMinusCenter < 0.0\n\t\tif beforeFirst != beforeSecond:\n\t\t\tyCloseToCenterPaths.append( yIntersectionPath )\n\t\t\treturn yCloseToCenterPaths\n\treturn yCloseToCenterPaths\n\ndef getExtraFillLoops( insideLoops, outsideLoop, radius ):\n\t\"Get extra loops between inside and outside loops.\"\n\tgreaterThanRadius = 1.4 * radius # later 1.01 * radius\n\textraFillLoops = []\n\tpoints = intercircle.getPointsFromLoops( insideLoops + [ outsideLoop ], greaterThanRadius )\n\tcenters = intercircle.getCentersFromPoints( points, greaterThanRadius )\n\totherLoops = insideLoops + [ outsideLoop ]\n\tfor center in centers:\n\t\tinset = intercircle.getSimplifiedInsetFromClockwiseLoop( center, radius )\n\t\tif intercircle.isLargeSameDirection( inset, center, radius ):\n\t\t\tif isPathAlwaysInsideLoop( outsideLoop, inset ):\n\t\t\t\tif isPathAlwaysOutsideLoops( insideLoops, inset ):\n\t\t\t\t\tif not euclidean.isLoopIntersectingLoops( inset, otherLoops ):\n\t\t\t\t\t\tinset.reverse()\n\t\t\t\t\t\textraFillLoops.append( inset )\n\treturn extraFillLoops\n\ndef getKeyIsInPixelTableAddValue( key, pathIndexTable, pixelTable ):\n\t\"Determine if the key is in the pixel table, and if it is and if the value is not None add it to the path index table.\"\n\tif key in pixelTable:\n\t\tvalue = pixelTable[ key ]\n\t\tif value != None:\n\t\t\tpathIndexTable[ value ] = None\n\t\treturn True\n\treturn False\n\ndef getNonIntersectingGridPointLine( gridPointInsetX, isJunctionWide, paths, pixelTable, yIntersectionPath, width ):\n\t\"Get the points around the grid point that is junction wide that do not intersect.\"\n\tpointIndexPlusOne = yIntersectionPath.getPointIndexPlusOne()\n\tpath = yIntersectionPath.getPath( paths )\n\tbegin = path[ yIntersectionPath.pointIndex ]\n\tend = path[ pointIndexPlusOne ]\n\tplusMinusSign = getPlusMinusSign( end.real - begin.real )\n\tif isJunctionWide:\n\t\tgridPointXFirst = complex( yIntersectionPath.gridPoint.real - plusMinusSign * gridPointInsetX, yIntersectionPath.gridPoint.imag )\n\t\tgridPointXSecond = complex( yIntersectionPath.gridPoint.real + plusMinusSign * gridPointInsetX, yIntersectionPath.gridPoint.imag )\n\t\tif isAddedPointOnPathFree( path, pixelTable, gridPointXSecond, pointIndexPlusOne, width ):\n\t\t\tif isAddedPointOnPathFree( path, pixelTable, gridPointXFirst, pointIndexPlusOne, width ):\n\t\t\t\treturn [ gridPointXSecond, gridPointXFirst ]\n\t\t\tif isAddedPointOnPathFree( path, pixelTable, yIntersectionPath.gridPoint, pointIndexPlusOne, width ):\n\t\t\t\treturn [ gridPointXSecond, yIntersectionPath.gridPoint ]\n\t\t\treturn [ gridPointXSecond ]\n\tif isAddedPointOnPathFree( path, pixelTable, yIntersectionPath.gridPoint, pointIndexPlusOne, width ):\n\t\treturn [ yIntersectionPath.gridPoint ]\n\treturn []\n\ndef getPlusMinusSign( number ):\n\t\"Get one if the number is zero or positive else negative one.\"\n\tif number >= 0.0:\n\t\treturn 1.0\n\treturn - 1.0\n\ndef getNewRepository():\n\t\"Get the repository constructor.\"\n\treturn FillRepository()\n\ndef getWithLeastLength( path, point ):\n\t\"Insert a point into a path, at the index at which the path would be shortest.\"\n\tif len( path ) < 1:\n\t\treturn 0\n\tshortestPointIndex = None\n\tshortestAdditionalLength = 999999999999999999.0\n\tfor pointIndex in xrange( len( path ) + 1 ):\n\t\tadditionalLength = getAdditionalLength( path, point, pointIndex )\n\t\tif additionalLength < shortestAdditionalLength:\n\t\t\tshortestAdditionalLength = additionalLength\n\t\t\tshortestPointIndex = pointIndex\n\treturn shortestPointIndex\n\ndef getYIntersection( firstPoint, secondPoint, x ):\n\t\"Get where the line crosses x.\"\n\tsecondMinusFirst = secondPoint - firstPoint\n\txMinusFirst = x - firstPoint.real\n\treturn xMinusFirst / secondMinusFirst.real * secondMinusFirst.imag + firstPoint.imag\n\ndef getYIntersectionIfExists( complexFirst, complexSecond, x ):\n\t\"Get the y intersection if it exists.\"\n\tisXAboveFirst = x > complexFirst.real\n\tisXAboveSecond = x > complexSecond.real\n\tif isXAboveFirst == isXAboveSecond:\n\t\treturn None\n\treturn getYIntersection( complexFirst, complexSecond, x )\n\ndef getYIntersectionInsideYSegment( segmentFirstY, segmentSecondY, complexFirst, complexSecond, x ):\n\t\"Get the y intersection inside the y segment if it does, else none.\"\n\tisXAboveFirst = x > complexFirst.real\n\tisXAboveSecond = x > complexSecond.real\n\tif isXAboveFirst == isXAboveSecond:\n\t\treturn None\n\tyIntersection = getYIntersection( complexFirst, complexSecond, x )\n\tif yIntersection <= min( segmentFirstY, segmentSecondY ):\n\t\treturn None\n\tif yIntersection < max( segmentFirstY, segmentSecondY ):\n\t\treturn yIntersection\n\treturn None\n\ndef insertGridPointPair( gridPoint, gridPointInsetX, gridPoints, isJunctionWide, paths, pixelTable, yIntersectionPath, width ):\n\t\"Insert a pair of points around the grid point is is junction wide, otherwise inset one point.\"\n\tlinePath = getNonIntersectingGridPointLine( gridPointInsetX, isJunctionWide, paths, pixelTable, yIntersectionPath, width )\n\tinsertGridPointPairWithLinePath( gridPoint, gridPointInsetX, gridPoints, isJunctionWide, linePath, paths, pixelTable, yIntersectionPath, width )\n\ndef insertGridPointPairs( gridPoint, gridPointInsetX, gridPoints, intersectionPathFirst, intersectionPathSecond, isBothOrNone, isJunctionWide, paths, pixelTable, width ):\n\t\"Insert a pair of points around a pair of grid points.\"\n\tgridPointLineFirst = getNonIntersectingGridPointLine( gridPointInsetX, isJunctionWide, paths, pixelTable, intersectionPathFirst, width )\n\tif len( gridPointLineFirst ) < 1:\n\t\tif isBothOrNone:\n\t\t\treturn\n\t\tintersectionPathSecond.gridPoint = gridPoint\n\t\tinsertGridPointPair( gridPoint, gridPointInsetX, gridPoints, isJunctionWide, paths, pixelTable, intersectionPathSecond, width )\n\t\treturn\n\tgridPointLineSecond = getNonIntersectingGridPointLine( gridPointInsetX, isJunctionWide, paths, pixelTable, intersectionPathSecond, width )\n\tif len( gridPointLineSecond ) > 0:\n\t\tinsertGridPointPairWithLinePath( gridPoint, gridPointInsetX, gridPoints, isJunctionWide, gridPointLineFirst, paths, pixelTable, intersectionPathFirst, width )\n\t\tinsertGridPointPairWithLinePath( gridPoint, gridPointInsetX, gridPoints, isJunctionWide, gridPointLineSecond, paths, pixelTable, intersectionPathSecond, width )\n\t\treturn\n\tif isBothOrNone:\n\t\treturn\n\toriginalGridPointFirst = intersectionPathFirst.gridPoint\n\tintersectionPathFirst.gridPoint = gridPoint\n\tgridPointLineFirstCenter = getNonIntersectingGridPointLine( gridPointInsetX, isJunctionWide, paths, pixelTable, intersectionPathFirst, width )\n\tif len( gridPointLineFirstCenter ) > 0:\n\t\tinsertGridPointPairWithLinePath( gridPoint, gridPointInsetX, gridPoints, isJunctionWide, gridPointLineFirstCenter, paths, pixelTable, intersectionPathFirst, width )\n\t\treturn\n\tintersectionPathFirst.gridPoint = originalGridPointFirst\n\tinsertGridPointPairWithLinePath( gridPoint, gridPointInsetX, gridPoints, isJunctionWide, gridPointLineFirst, paths, pixelTable, intersectionPathFirst, width )\n\ndef insertGridPointPairWithLinePath( gridPoint, gridPointInsetX, gridPoints, isJunctionWide, linePath, paths, pixelTable, yIntersectionPath, width ):\n\t\"Insert a pair of points around the grid point is is junction wide, otherwise inset one point.\"\n\tif len( linePath ) < 1:\n\t\treturn\n\tif gridPoint in gridPoints:\n\t\tgridPoints.remove( gridPoint )\n\tintersectionBeginPoint = None\n\tmoreThanInset = 2.1 * gridPointInsetX\n\tpath = yIntersectionPath.getPath( paths )\n\tbegin = path[ yIntersectionPath.pointIndex ]\n\tend = path[ yIntersectionPath.getPointIndexPlusOne() ]\n\tif yIntersectionPath.isOutside:\n\t\tdistanceX = end.real - begin.real\n\t\tif abs( distanceX ) > 2.1 * moreThanInset:\n\t\t\tintersectionBeginXDistance = yIntersectionPath.gridPoint.real - begin.real\n\t\t\tendIntersectionXDistance = end.real - yIntersectionPath.gridPoint.real\n\t\t\tintersectionPoint = begin * endIntersectionXDistance / distanceX + end * intersectionBeginXDistance / distanceX\n\t\t\tdistanceYAbsoluteInset = max( abs( yIntersectionPath.gridPoint.imag - intersectionPoint.imag ), moreThanInset )\n\t\t\tintersectionEndSegment = end - intersectionPoint\n\t\t\tintersectionEndSegmentLength = abs( intersectionEndSegment )\n\t\t\tif intersectionEndSegmentLength > 1.1 * distanceYAbsoluteInset:\n\t\t\t\tintersectionEndPoint = intersectionPoint + intersectionEndSegment * distanceYAbsoluteInset / intersectionEndSegmentLength\n\t\t\t\tpath.insert( yIntersectionPath.getPointIndexPlusOne(), intersectionEndPoint )\n\t\t\tintersectionBeginSegment = begin - intersectionPoint\n\t\t\tintersectionBeginSegmentLength = abs( intersectionBeginSegment )\n\t\t\tif intersectionBeginSegmentLength > 1.1 * distanceYAbsoluteInset:\n\t\t\t\tintersectionBeginPoint = intersectionPoint + intersectionBeginSegment * distanceYAbsoluteInset / intersectionBeginSegmentLength\n\tfor point in linePath:\n\t\taddPointOnPath( path, yIntersectionPath.pathIndex, pixelTable, point, yIntersectionPath.getPointIndexPlusOne(), width )\n\tif intersectionBeginPoint != None:\n\t\taddPointOnPath( path, yIntersectionPath.pathIndex, pixelTable, intersectionBeginPoint, yIntersectionPath.getPointIndexPlusOne(), width )\n\ndef isAddedPointOnPathFree( path, pixelTable, point, pointIndex, width ):\n\t\"Determine if the point added to a path is intersecting the pixel table or the path.\"\n\tif pointIndex > 0 and pointIndex < len( path ):\n\t\tif isSharpCorner( ( path[ pointIndex - 1 ] ), point, ( path[ pointIndex ] ) ):\n\t\t\treturn False\n\tpointIndexMinusOne = pointIndex - 1\n\tif pointIndexMinusOne >= 0:\n\t\tmaskTable = {}\n\t\tbegin = path[ pointIndexMinusOne ]\n\t\tif pointIndex < len( path ):\n\t\t\tend = path[ pointIndex ]\n\t\t\teuclidean.addValueSegmentToPixelTable( begin, end, maskTable, None, width )\n\t\tsegmentTable = {}\n\t\teuclidean.addSegmentToPixelTable( point, begin, segmentTable, 0.0, 2.0, width )\n\t\tif euclidean.isPixelTableIntersecting( pixelTable, segmentTable, maskTable ):\n\t\t\treturn False\n\t\tif isAddedPointOnPathIntersectingPath( begin, path, point, pointIndexMinusOne ):\n\t\t\treturn False\n\tif pointIndex < len( path ):\n\t\tmaskTable = {}\n\t\tbegin = path[ pointIndex ]\n\t\tif pointIndexMinusOne >= 0:\n\t\t\tend = path[ pointIndexMinusOne ]\n\t\t\teuclidean.addValueSegmentToPixelTable( begin, end, maskTable, None, width )\n\t\tsegmentTable = {}\n\t\teuclidean.addSegmentToPixelTable( point, begin, segmentTable, 0.0, 2.0, width )\n\t\tif euclidean.isPixelTableIntersecting( pixelTable, segmentTable, maskTable ):\n\t\t\treturn False\n\t\tif isAddedPointOnPathIntersectingPath( begin, path, point, pointIndex ):\n\t\t\treturn False\n\treturn True\n\ndef isAddedPointOnPathIntersectingPath( begin, path, point, pointIndex ):\n\t\"Determine if the point added to a path is intersecting the path by checking line intersection.\"\n\tsegment = point - begin\n\tsegmentLength = abs( segment )\n\tif segmentLength <= 0.0:\n\t\treturn False\n\tnormalizedSegment = segment / segmentLength\n\tsegmentYMirror = complex( normalizedSegment.real, - normalizedSegment.imag )\n\tpointRotated = segmentYMirror * point\n\tbeginRotated = segmentYMirror * begin\n\tif euclidean.isXSegmentIntersectingPath( path[ max( 0, pointIndex - 20 ) : pointIndex ], pointRotated.real, beginRotated.real, segmentYMirror, pointRotated.imag ):\n\t\treturn True\n\treturn euclidean.isXSegmentIntersectingPath( path[ pointIndex + 1 : pointIndex + 21 ], pointRotated.real, beginRotated.real, segmentYMirror, pointRotated.imag )\n\ndef isIntersectingLoopsPaths( loops, paths, pointBegin, pointEnd ):\n\t\"Determine if the segment between the first and second point is intersecting the loop list.\"\n\tnormalizedSegment = pointEnd.dropAxis( 2 ) - pointBegin.dropAxis( 2 )\n\tnormalizedSegmentLength = abs( normalizedSegment )\n\tif normalizedSegmentLength == 0.0:\n\t\treturn False\n\tnormalizedSegment /= normalizedSegmentLength\n\tsegmentYMirror = complex( normalizedSegment.real, - normalizedSegment.imag )\n\tpointBeginRotated = euclidean.getRoundZAxisByPlaneAngle( segmentYMirror, pointBegin )\n\tpointEndRotated = euclidean.getRoundZAxisByPlaneAngle( segmentYMirror, pointEnd )\n\tif euclidean.isLoopListIntersectingInsideXSegment( loops, pointBeginRotated.real, pointEndRotated.real, segmentYMirror, pointBeginRotated.imag ):\n\t\treturn True\n\treturn euclidean.isXSegmentIntersectingPaths( paths, pointBeginRotated.real, pointEndRotated.real, segmentYMirror, pointBeginRotated.imag )\n\ndef isPathAlwaysInsideLoop( loop, path ):\n\t\"Determine if all points of a path are inside another loop.\"\n\tfor point in path:\n\t\tif euclidean.getNumberOfIntersectionsToLeft( loop, point ) % 2 == 0:\n\t\t\treturn False\n\treturn True\n\ndef isPathAlwaysOutsideLoops( loops, path ):\n\t\"Determine if all points in a path are outside another loop in a list.\"\n\tfor loop in loops:\n\t\tfor point in path:\n\t\t\tif euclidean.getNumberOfIntersectionsToLeft( loop, point ) % 2 == 1:\n\t\t\t\treturn False\n\treturn True\n\ndef isPerimeterPathInSurroundLoops( surroundingLoops ):\n\t\"Determine if there is a perimeter path in the surrounding loops.\"\n\tfor surroundingLoop in surroundingLoops:\n\t\tif len( surroundingLoop.perimeterPaths ) > 0:\n\t\t\treturn True\n\treturn False\n\ndef isPointAddedAroundClosest( aroundPixelTable, layerExtrusionWidth, paths, removedEndpointPoint, width ):\n\t\"Add the closest removed endpoint to the path, with minimal twisting.\"\n\tclosestDistanceSquared = 999999999999999999.0\n\tclosestPathIndex = None\n\tfor pathIndex in xrange( len( paths ) ):\n\t\tpath = paths[ pathIndex ]\n\t\tfor pointIndex in xrange( len( path ) ):\n\t\t\tpoint = path[ pointIndex ]\n\t\t\tdistanceSquared = abs( point - removedEndpointPoint )\n\t\t\tif distanceSquared < closestDistanceSquared:\n\t\t\t\tclosestDistanceSquared = distanceSquared\n\t\t\t\tclosestPathIndex = pathIndex\n\tif closestPathIndex == None:\n\t\treturn\n\tif closestDistanceSquared < 0.8 * layerExtrusionWidth * layerExtrusionWidth:\n\t\treturn\n\tclosestPath = paths[ closestPathIndex ]\n\tclosestPointIndex = getWithLeastLength( closestPath, removedEndpointPoint )\n\tif isAddedPointOnPathFree( closestPath, aroundPixelTable, removedEndpointPoint, closestPointIndex, width ):\n\t\taddPointOnPath( closestPath, closestPathIndex, aroundPixelTable, removedEndpointPoint, closestPointIndex, width )\n\t\treturn True\n\treturn isSidePointAdded( aroundPixelTable, closestPath, closestPathIndex, closestPointIndex, layerExtrusionWidth, removedEndpointPoint, width )\n\ndef isSegmentAround( aroundSegments, segment ):\n\t\"Determine if there is another segment around.\"\n\tfor aroundSegment in aroundSegments:\n\t\tendpoint = aroundSegment[ 0 ]\n\t\tif isSegmentInX( segment, endpoint.point.real, endpoint.otherEndpoint.point.real ):\n\t\t\treturn True\n\treturn False\n\ndef isSegmentCompletelyInAnIntersection( segment, xIntersections ):\n\t\"Add sparse endpoints from a segment.\"\n\tfor xIntersectionIndex in xrange( 0, len( xIntersections ), 2 ):\n\t\tsurroundingXFirst = xIntersections[ xIntersectionIndex ]\n\t\tsurroundingXSecond = xIntersections[ xIntersectionIndex + 1 ]\n\t\tif euclidean.isSegmentCompletelyInX( segment, surroundingXFirst, surroundingXSecond ):\n\t\t\treturn True\n\treturn False\n\ndef isSegmentInX( segment, xFirst, xSecond ):\n\t\"Determine if the segment overlaps within x.\"\n\tsegmentFirstX = segment[ 0 ].point.real\n\tsegmentSecondX = segment[ 1 ].point.real\n\tif min( segmentFirstX, segmentSecondX ) > max( xFirst, xSecond ):\n\t\treturn False\n\treturn max( segmentFirstX, segmentSecondX ) > min( xFirst, xSecond )\n\ndef isSharpCorner( beginComplex, centerComplex, endComplex ):\n\t\"Determine if the three complex points form a sharp corner.\"\n\tcenterBeginComplex = beginComplex - centerComplex\n\tcenterEndComplex = endComplex - centerComplex\n\tcenterBeginLength = abs( centerBeginComplex )\n\tcenterEndLength = abs( centerEndComplex )\n\tif centerBeginLength <= 0.0 or centerEndLength <= 0.0:\n\t\treturn False\n\tcenterBeginComplex /= centerBeginLength\n\tcenterEndComplex /= centerEndLength\n\treturn euclidean.getDotProduct( centerBeginComplex, centerEndComplex ) > 0.9\n\ndef isSidePointAdded( aroundPixelTable, closestPath, closestPathIndex, closestPointIndex, layerExtrusionWidth, removedEndpointPoint, width ):\n\t\"Add side point along with the closest removed endpoint to the path, with minimal twisting.\"\n\tif closestPointIndex <= 0 or closestPointIndex >= len( closestPath ):\n\t\treturn False\n\tpointBegin = closestPath[ closestPointIndex - 1 ]\n\tpointEnd = closestPath[ closestPointIndex ]\n\tremovedEndpointPoint = removedEndpointPoint\n\tclosest = pointBegin\n\tfarthest = pointEnd\n\tremovedMinusClosest = removedEndpointPoint - pointBegin\n\tremovedMinusClosestLength = abs( removedMinusClosest )\n\tif removedMinusClosestLength <= 0.0:\n\t\treturn False\n\tremovedMinusOther = removedEndpointPoint - pointEnd\n\tremovedMinusOtherLength = abs( removedMinusOther )\n\tif removedMinusOtherLength <= 0.0:\n\t\treturn False\n\tinsertPointAfter = None\n\tinsertPointBefore = None\n\tif removedMinusOtherLength < removedMinusClosestLength:\n\t\tclosest = pointEnd\n\t\tfarthest = pointBegin\n\t\tremovedMinusClosest = removedMinusOther\n\t\tremovedMinusClosestLength = removedMinusOtherLength\n\t\tinsertPointBefore = removedEndpointPoint\n\telse:\n\t\tinsertPointAfter = removedEndpointPoint\n\tremovedMinusClosestNormalized = removedMinusClosest / removedMinusClosestLength\n\tperpendicular = removedMinusClosestNormalized * complex( 0.0, layerExtrusionWidth )\n\tsidePoint = removedEndpointPoint + perpendicular\n\t#extra check in case the line to the side point somehow slips by the line to the perpendicular\n\tsidePointOther = removedEndpointPoint - perpendicular\n\tif abs( sidePoint - farthest ) > abs( sidePointOther - farthest ):\n\t\tperpendicular = - perpendicular\n\t\tsidePoint = sidePointOther\n\tmaskTable = {}\n\tclosestSegmentTable = {}\n\ttoPerpendicularTable = {}\n\teuclidean.addValueSegmentToPixelTable( pointBegin, pointEnd, maskTable, None, width )\n\teuclidean.addValueSegmentToPixelTable( closest, removedEndpointPoint, closestSegmentTable, None, width )\n\teuclidean.addValueSegmentToPixelTable( sidePoint, farthest, toPerpendicularTable, None, width )\n\tif euclidean.isPixelTableIntersecting( aroundPixelTable, toPerpendicularTable, maskTable ) or euclidean.isPixelTableIntersecting( closestSegmentTable, toPerpendicularTable, maskTable ):\n\t\tsidePoint = removedEndpointPoint - perpendicular\n\t\ttoPerpendicularTable = {}\n\t\teuclidean.addValueSegmentToPixelTable( sidePoint, farthest, toPerpendicularTable, None, width )\n\t\tif euclidean.isPixelTableIntersecting( aroundPixelTable, toPerpendicularTable, maskTable ) or euclidean.isPixelTableIntersecting( closestSegmentTable, toPerpendicularTable, maskTable ):\n\t\t\treturn False\n\tif insertPointBefore != None:\n\t\taddPointOnPathIfFree( closestPath, closestPathIndex, aroundPixelTable, insertPointBefore, closestPointIndex, width )\n\taddPointOnPathIfFree( closestPath, closestPathIndex, aroundPixelTable, sidePoint, closestPointIndex, width )\n\tif insertPointAfter != None:\n\t\taddPointOnPathIfFree( closestPath, closestPathIndex, aroundPixelTable, insertPointAfter, closestPointIndex, width )\n\treturn True\n\ndef removeEndpoints( aroundPixelTable, layerExtrusionWidth, paths, removedEndpoints, aroundWidth ):\n\t\"Remove endpoints which are added to the path.\"\n\tfor removedEndpointIndex in xrange( len( removedEndpoints ) - 1, - 1, - 1 ):\n\t\tremovedEndpoint = removedEndpoints[ removedEndpointIndex ]\n\t\tremovedEndpointPoint = removedEndpoint.point\n\t\tif isPointAddedAroundClosest( aroundPixelTable, layerExtrusionWidth, paths, removedEndpointPoint, aroundWidth ):\n\t\t\tremovedEndpoints.remove( removedEndpoint )\n\ndef setIsOutside( yCloseToCenterPath, yIntersectionPaths ):\n\t\"Determine if the yCloseToCenterPath is outside.\"\n\tbeforeClose = yCloseToCenterPath.yMinusCenter < 0.0\n\tfor yIntersectionPath in yIntersectionPaths:\n\t\tif yIntersectionPath != yCloseToCenterPath:\n\t\t\tbeforePath = yIntersectionPath.yMinusCenter < 0.0\n\t\t\tif beforeClose == beforePath:\n\t\t\t\tyCloseToCenterPath.isOutside = False\n\t\t\t\treturn\n\tyCloseToCenterPath.isOutside = True\n\ndef writeOutput( fileName = '' ):\n\t\"Fill an inset gcode file.\"\n\tfileName = interpret.getFirstTranslatorFileNameUnmodified( fileName )\n\tif fileName != '':\n\t\tconsecution.writeChainTextWithNounMessage( fileName, 'fill' )\n\n\nclass FillRepository:\n\t\"A class to handle the fill settings.\"\n\tdef __init__( self ):\n\t\t\"Set the default settings, execute title & settings fileName.\"\n\t\tprofile.addListsToCraftTypeRepository( 'skeinforge_tools.craft_plugins.fill.html', self )\n\t\tself.fileNameInput = settings.FileNameInput().getFromFileName( interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Fill', self, '' )\n\t\tself.openWikiManualHelpPage = settings.HelpPage().getOpenFromAbsolute( 'http://www.bitsfrombytes.com/wiki/index.php?title=Skeinforge_Fill' )\n\t\tself.activateFill = settings.BooleanSetting().getFromValue( 'Activate Fill:', self, True )\n\t\tsettings.LabelDisplay().getFromName( '- Diaphragm -', self )\n\t\tself.diaphragmPeriod = settings.IntSpin().getFromValue( 20, 'Diaphragm Period (layers):', self, 200, 100 )\n\t\tself.diaphragmThickness = settings.IntSpin().getFromValue( 0, 'Diaphragm Thickness (layers):', self, 5, 0 )\n\t\tsettings.LabelDisplay().getFromName( '- Extra Shells -', self )\n\t\tself.extraShellsAlternatingSolidLayer = settings.IntSpin().getFromValue( 0, 'Extra Shells on Alternating Solid Layer (layers):', self, 3, 2 )\n\t\tself.extraShellsBase = settings.IntSpin().getFromValue( 0, 'Extra Shells on Base (layers):', self, 3, 1 )\n\t\tself.extraShellsSparseLayer = settings.IntSpin().getFromValue( 0, 'Extra Shells on Sparse Layer (layers):', self, 3, 1 )\n\t\tsettings.LabelDisplay().getFromName( '- Grid -', self )\n\t\tself.gridExtraOverlap = settings.FloatSpin().getFromValue( 0.0, 'Grid Extra Overlap (ratio):', self, 0.5, 0.1 )\n\t\tself.gridJunctionSeparationBandHeight = settings.IntSpin().getFromValue( 0, 'Grid Junction Separation Band Height (layers):', self, 20, 10 )\n\t\tself.gridJunctionSeparationOverOctogonRadiusAtEnd = settings.FloatSpin().getFromValue( 0.0, 'Grid Junction Separation over Octogon Radius At End (ratio):', self, 0.8, 0.0 )\n\t\tself.gridJunctionSeparationOverOctogonRadiusAtMiddle = settings.FloatSpin().getFromValue( 0.0, 'Grid Junction Separation over Octogon Radius At Middle (ratio):', self, 0.8, 0.0 )\n\t\tsettings.LabelDisplay().getFromName( '- Infill -', self )\n\t\tself.infillBeginRotation = settings.FloatSpin().getFromValue( 0.0, 'Infill Begin Rotation (degrees):', self, 90.0, 45.0 )\n\t\tself.infillBeginRotationRepeat = settings.IntSpin().getFromValue( 0, 'Infill Begin Rotation Repeat (layers):', self, 3, 1 )\n\t\tself.infillInteriorDensityOverExteriorDensity = settings.FloatSpin().getFromValue( 0.8, 'Infill Interior Density over Exterior Density (ratio):', self, 1.0, 0.9 )\n\t\tself.infillOddLayerExtraRotation = settings.FloatSpin().getFromValue( 30.0, 'Infill Odd Layer Extra Rotation (degrees):', self, 90.0, 90.0 )\n\t\tself.infillPatternLabel = settings.LabelDisplay().getFromName( 'Infill Pattern:', self )\n\t\tinfillLatentStringVar = settings.LatentStringVar()\n\t\tself.infillPatternGridHexagonal = settings.Radio().getFromRadio( infillLatentStringVar, 'Grid Hexagonal', self, False )\n\t\tself.infillPatternGridRectangular = settings.Radio().getFromRadio( infillLatentStringVar, 'Grid Rectangular', self, False )\n\t\tself.infillPatternLine = settings.Radio().getFromRadio( infillLatentStringVar, 'Line', self, True )\n\t\tself.infillPerimeterOverlap = settings.FloatSpin().getFromValue( 0.0, 'Infill Perimeter Overlap (ratio):', self, 0.4, 0.15 )\n\t\tself.infillSolidity = settings.FloatSpin().getFromValue( 0.04, 'Infill Solidity (ratio):', self, 0.3, 0.2 )\n\t\tself.infillWidthOverThickness = settings.FloatSpin().getFromValue( 1.3, 'Infill Width over Thickness (ratio):', self, 1.7, 1.5 )\n\t\tself.solidSurfaceThickness = settings.IntSpin().getFromValue( 0, 'Solid Surface Thickness (layers):', self, 5, 3 )\n\t\tself.threadSequenceChoice = settings.MenuButtonDisplay().getFromName( 'Thread Sequence Choice:', self )\n\t\tself.threadSequenceInfillLoops = settings.MenuRadio().getFromMenuButtonDisplay( self.threadSequenceChoice, 'Infill > Loops > Perimeter', self, False )\n\t\tself.threadSequenceInfillPerimeter = settings.MenuRadio().getFromMenuButtonDisplay( self.threadSequenceChoice, 'Infill > Perimeter > Loops', self, False )\n\t\tself.threadSequenceLoopsInfill = settings.MenuRadio().getFromMenuButtonDisplay( self.threadSequenceChoice, 'Loops > Infill > Perimeter', self, False )\n\t\tself.threadSequenceLoopsPerimeter = settings.MenuRadio().getFromMenuButtonDisplay( self.threadSequenceChoice, 'Loops > Perimeter > Infill', self, True )\n\t\tself.threadSequencePerimeterInfill = settings.MenuRadio().getFromMenuButtonDisplay( self.threadSequenceChoice, 'Perimeter > Infill > Loops', self, False )\n\t\tself.threadSequencePerimeterLoops = settings.MenuRadio().getFromMenuButtonDisplay( self.threadSequenceChoice, 'Perimeter > Loops > Infill', self, False )\n\t\tself.executeTitle = 'Fill'\n\n\tdef execute( self ):\n\t\t\"Fill button has been clicked.\"\n\t\tfileNames = polyfile.getFileOrDirectoryTypesUnmodifiedGcode( self.fileNameInput.value, interpret.getImportPluginFileNames(), self.fileNameInput.wasCancelled )\n\t\tfor fileName in fileNames:\n\t\t\twriteOutput( fileName )\n\n\nclass FillSkein:\n\t\"A class to fill a skein of extrusions.\"\n\tdef __init__( self ):\n\t\tself.bridgeWidthMultiplier = 1.0\n\t\tself.distanceFeedRate = gcodec.DistanceFeedRate()\n\t\tself.extruderActive = False\n\t\tself.fillInset = 0.18\n\t\tself.isPerimeter = False\n\t\tself.lastExtraShells = - 1\n\t\tself.lineIndex = 0\n\t\tself.oldLocation = None\n\t\tself.oldOrderedLocation = Vector3()\n\t\tself.rotatedLayer = None\n\t\tself.rotatedLayers = []\n\t\tself.shutdownLineIndex = sys.maxint\n\t\tself.surroundingLoop = None\n\t\tself.thread = None\n\n\tdef addFill( self, layerIndex ):\n\t\t\"Add fill to the carve layer.\"\n\t\talreadyFilledArounds = []\n\t\taroundPixelTable = {}\n\t\tarounds = []\n\t\tbetweenWidth = self.betweenWidth\n\t\tself.layerExtrusionWidth = self.infillWidth\n\t\tlayerFillInset = self.fillInset\n\t\trotatedLayer = self.rotatedLayers[ layerIndex ]\n#\t\tif layerIndex > 2:\n#\t\t\treturn\n#\t\tprint( 'layer index: %s z: %s' % ( layerIndex, rotatedLayer.z ) )\n\t\tself.distanceFeedRate.addLine( '( %s )' % rotatedLayer.z )\n\t\tlayerRotationAroundZAngle = self.getLayerRoundZ( layerIndex )\n\t\treverseZRotationAngle = complex( layerRotationAroundZAngle.real, - layerRotationAroundZAngle.imag )\n\t\tsurroundingCarves = []\n\t\tlayerRemainder = layerIndex % int( round( self.fillRepository.diaphragmPeriod.value ) )\n\t\tif layerRemainder >= int( round( self.fillRepository.diaphragmThickness.value ) ) and rotatedLayer.rotation == None:\n\t\t\tfor surroundingIndex in xrange( 1, self.solidSurfaceThickness + 1 ):\n\t\t\t\tself.addRotatedCarve( layerIndex - surroundingIndex, reverseZRotationAngle, surroundingCarves )\n\t\t\t\tself.addRotatedCarve( layerIndex + surroundingIndex, reverseZRotationAngle, surroundingCarves )\n\t\textraShells = self.fillRepository.extraShellsSparseLayer.value\n\t\tif len( surroundingCarves ) < self.doubleSolidSurfaceThickness:\n\t\t\textraShells = self.fillRepository.extraShellsAlternatingSolidLayer.value\n\t\t\tif self.lastExtraShells != self.fillRepository.extraShellsBase.value:\n\t\t\t\textraShells = self.fillRepository.extraShellsBase.value\n\t\tif rotatedLayer.rotation != None:\n\t\t\textraShells = 0\n\t\t\tbetweenWidth *= self.bridgeWidthMultiplier\n\t\t\tself.layerExtrusionWidth = self.infillWidth * self.bridgeWidthMultiplier\n\t\t\tlayerFillInset = self.fillInset * self.bridgeWidthMultiplier\n\t\t\tself.distanceFeedRate.addLine( '( %s )' % rotatedLayer.rotation )\n\t\taroundInset = 0.25 * self.layerExtrusionWidth\n\t\taroundWidth = 0.25 * self.layerExtrusionWidth\n\t\tself.lastExtraShells = extraShells\n\t\tgridPointInsetX = 0.5 * layerFillInset\n\t\tdoubleExtrusionWidth = 2.0 * self.layerExtrusionWidth\n\t\tendpoints = []\n\t\tinfillPaths = []\n\t\tlayerInfillSolidity = self.infillSolidity\n\t\tself.isDoubleJunction = True\n\t\tself.isJunctionWide = True\n\t\tif self.fillRepository.infillPatternGridHexagonal.value:\n\t\t\tif abs( euclidean.getDotProduct( layerRotationAroundZAngle, euclidean.getUnitPolar( self.infillBeginRotation ) ) ) < math.sqrt( 0.5 ):\n\t\t\t\tlayerInfillSolidity *= 0.5\n\t\t\t\tself.isDoubleJunction = False\n\t\t\telse:\n\t\t\t\tself.isJunctionWide = False\n\t\trotatedExtruderLoops = []\n\t\tfor surroundingLoop in rotatedLayer.surroundingLoops:\n\t\t\tsurroundingLoop.fillBoundaries = intercircle.getInsetLoopsFromLoop( betweenWidth, surroundingLoop.boundary )\n\t\t\tsurroundingLoop.lastExistingFillLoops = surroundingLoop.fillBoundaries\n\t\tsurroundingLoops = euclidean.getOrderedSurroundingLoops( self.layerExtrusionWidth, rotatedLayer.surroundingLoops )\n\t\tif isPerimeterPathInSurroundLoops( surroundingLoops ):\n\t\t\textraShells = 0\n\t\tfor extraShellIndex in xrange( extraShells ):\n\t\t\tcreateFillForSurroundings( self.layerExtrusionWidth, surroundingLoops )\n\t\tfillLoops = euclidean.getLastExistingFillOfSurroundings( surroundingLoops )\n\t\tslightlyGreaterThanFill = 1.01 * layerFillInset\n\t\tfor loop in fillLoops:\n\t\t\talreadyFilledLoop = []\n\t\t\talreadyFilledArounds.append( alreadyFilledLoop )\n\t\t\tplaneRotatedPerimeter = euclidean.getPointsRoundZAxis( reverseZRotationAngle, loop )\n\t\t\trotatedExtruderLoops.append( planeRotatedPerimeter )\n\t\t\tcenters = intercircle.getCentersFromLoop( planeRotatedPerimeter, slightlyGreaterThanFill )\n\t\t\teuclidean.addLoopToPixelTable( planeRotatedPerimeter, aroundPixelTable, aroundWidth )\n\t\t\tfor center in centers:\n\t\t\t\talreadyFilledInset = intercircle.getSimplifiedInsetFromClockwiseLoop( center, layerFillInset )\n\t\t\t\tif intercircle.isLargeSameDirection( alreadyFilledInset, center, layerFillInset ):\n\t\t\t\t\talreadyFilledLoop.append( alreadyFilledInset )\n\t\t\t\t\taround = intercircle.getSimplifiedInsetFromClockwiseLoop( center, aroundInset )\n\t\t\t\t\tif euclidean.isPathInsideLoop( planeRotatedPerimeter, around ) == euclidean.isWiddershins( planeRotatedPerimeter ):\n\t\t\t\t\t\taround.reverse()\n\t\t\t\t\t\tarounds.append( around )\n\t\t\t\t\t\teuclidean.addLoopToPixelTable( around, aroundPixelTable, aroundWidth )\n\t\tif len( arounds ) < 1:\n\t\t\tself.addThreadsBridgeLayer( rotatedLayer, surroundingLoops )\n\t\t\treturn\n\t\tback = euclidean.getBackOfLoops( arounds )\n\t\tfront = euclidean.getFrontOfLoops( arounds )\n\t\tarea = self.getCarveArea( layerIndex )\n\t\tif area > 0.0 and len( surroundingCarves ) >= self.doubleSolidSurfaceThickness:\n\t\t\tareaChange = 0.0\n\t\t\tfor surroundingIndex in xrange( 1, self.solidSurfaceThickness + 1 ):\n\t\t\t\tareaChange = max( areaChange, self.getAreaChange( area, layerIndex - surroundingIndex ) )\n\t\t\t\tareaChange = max( areaChange, self.getAreaChange( area, layerIndex + surroundingIndex ) )\n\t\t\tif areaChange < 0.5 or self.solidSurfaceThickness == 0:\n\t\t\t\tif self.fillRepository.infillInteriorDensityOverExteriorDensity.value <= 0.0:\n\t\t\t\t\tself.addThreadsBridgeLayer( rotatedLayer, surroundingLoops )\n\t\t\t\tself.layerExtrusionWidth /= self.fillRepository.infillInteriorDensityOverExteriorDensity.value\n\t\tfront = math.ceil( front / self.layerExtrusionWidth ) * self.layerExtrusionWidth\n\t\tfillWidth = back - front\n\t\tnumberOfLines = int( math.ceil( fillWidth / self.layerExtrusionWidth ) )\n\t\tself.frontOverWidth = 0.0\n\t\tself.horizontalSegmentLists = euclidean.getHorizontalSegmentListsFromLoopLists( alreadyFilledArounds, front, numberOfLines, rotatedExtruderLoops, self.layerExtrusionWidth )\n\t\tself.surroundingXIntersectionLists = []\n\t\tself.yList = []\n\t\tremovedEndpoints = []\n\t\tif len( surroundingCarves ) >= self.doubleSolidSurfaceThickness:\n\t\t\txIntersectionIndexLists = []\n\t\t\tself.frontOverWidth = euclidean.getFrontOverWidthAddXListYList( front, surroundingCarves, numberOfLines, xIntersectionIndexLists, self.layerExtrusionWidth, self.yList )\n\t\t\tfor fillLine in xrange( len( self.horizontalSegmentLists ) ):\n\t\t\t\txIntersectionIndexList = xIntersectionIndexLists[ fillLine ]\n\t\t\t\tsurroundingXIntersections = euclidean.getIntersectionOfXIntersectionIndexes( self.doubleSolidSurfaceThickness, xIntersectionIndexList )\n\t\t\t\tself.surroundingXIntersectionLists.append( surroundingXIntersections )\n\t\t\t\taddSparseEndpoints( doubleExtrusionWidth, endpoints, fillLine, self.horizontalSegmentLists, layerInfillSolidity, removedEndpoints, self.solidSurfaceThickness, surroundingXIntersections )\n\t\telse:\n\t\t\tfor fillLine in xrange( len( self.horizontalSegmentLists ) ):\n\t\t\t\taddSparseEndpoints( doubleExtrusionWidth, endpoints, fillLine, self.horizontalSegmentLists, layerInfillSolidity, removedEndpoints, self.solidSurfaceThickness, None )\n\t\tif len( endpoints ) < 1:\n\t\t\tself.addThreadsBridgeLayer( rotatedLayer, surroundingLoops )\n\t\t\treturn\n\t\tpaths = euclidean.getPathsFromEndpoints( endpoints, self.layerExtrusionWidth, aroundPixelTable, aroundWidth )\n\t\tif self.isGridToBeExtruded():\n\t\t\tself.addGrid( arounds, fillLoops, gridPointInsetX, layerIndex, paths, aroundPixelTable, reverseZRotationAngle, surroundingCarves, aroundWidth )\n\t\toldRemovedEndpointLength = len( removedEndpoints ) + 1\n\t\twhile oldRemovedEndpointLength - len( removedEndpoints ) > 0:\n\t\t\toldRemovedEndpointLength = len( removedEndpoints )\n\t\t\tremoveEndpoints( aroundPixelTable, self.layerExtrusionWidth, paths, removedEndpoints, aroundWidth )\n\t\tpaths = euclidean.getConnectedPaths( paths, aroundPixelTable, aroundWidth )\n\t\tfor path in paths:\n\t\t\taddPath( self.layerExtrusionWidth, infillPaths, path, layerRotationAroundZAngle )\n\t\teuclidean.transferPathsToSurroundingLoops( infillPaths, surroundingLoops )\n\t\tself.addThreadsBridgeLayer( rotatedLayer, surroundingLoops )\n\n\tdef addGcodeFromThreadZ( self, thread, z ):\n\t\t\"Add a gcode thread to the output.\"\n\t\tself.distanceFeedRate.addGcodeFromThreadZ( thread, z )\n\n\tdef addGrid( self, arounds, fillLoops, gridPointInsetX, layerIndex, paths, pixelTable, reverseZRotationAngle, surroundingCarves, width ):\n\t\t\"Add the grid to the infill layer.\"\n\t\tif len( surroundingCarves ) < self.doubleSolidSurfaceThickness:\n\t\t\treturn\n\t\texplodedPaths = []\n\t\tpathGroups = []\n\t\tfor path in paths:\n\t\t\tpathIndexBegin = len( explodedPaths )\n\t\t\tfor pointIndex in xrange( len( path ) - 1 ):\n\t\t\t\tpathSegment = [ path[ pointIndex ], path[ pointIndex + 1 ] ]\n\t\t\t\texplodedPaths.append( pathSegment )\n\t\t\tpathGroups.append( ( pathIndexBegin, len( explodedPaths ) ) )\n\t\tfor pathIndex in xrange( len( explodedPaths ) ):\n\t\t\texplodedPath = explodedPaths[ pathIndex ]\n\t\t\teuclidean.addPathToPixelTable( explodedPath, pixelTable, pathIndex, width )\n\t\tgridPoints = self.getGridPoints( fillLoops, reverseZRotationAngle )\n\t\tgridPointInsetY = gridPointInsetX * ( 1.0 - self.fillRepository.gridExtraOverlap.value )\n\t\tif self.fillRepository.infillPatternGridRectangular.value:\n\t\t\tgridBandHeight = self.fillRepository.gridJunctionSeparationBandHeight.value\n\t\t\tgridLayerRemainder = ( layerIndex - self.solidSurfaceThickness ) % gridBandHeight\n\t\t\thalfBandHeight = 0.5 * float( gridBandHeight )\n\t\t\thalfBandHeightFloor = math.floor( halfBandHeight )\n\t\t\tfromMiddle = math.floor( abs( gridLayerRemainder - halfBandHeight ) )\n\t\t\tfromEnd = halfBandHeightFloor - fromMiddle\n\t\t\tgridJunctionSeparation = self.gridJunctionSeparationAtEnd * fromMiddle + self.gridJunctionSeparationAtMiddle * fromEnd\n\t\t\tgridJunctionSeparation /= halfBandHeightFloor\n\t\t\tgridPointInsetX += gridJunctionSeparation\n\t\t\tgridPointInsetY += gridJunctionSeparation\n\t\toldGridPointLength = len( gridPoints ) + 1\n\t\twhile oldGridPointLength - len( gridPoints ) > 0:\n\t\t\toldGridPointLength = len( gridPoints )\n\t\t\tself.addRemainingGridPoints( arounds, gridPointInsetX, gridPointInsetY, gridPoints, True, explodedPaths, pixelTable, width )\n\t\toldGridPointLength = len( gridPoints ) + 1\n\t\twhile oldGridPointLength - len( gridPoints ) > 0:\n\t\t\toldGridPointLength = len( gridPoints )\n\t\t\tself.addRemainingGridPoints( arounds, gridPointInsetX, gridPointInsetY, gridPoints, False, explodedPaths, pixelTable, width )\n\t\tfor pathGroupIndex in xrange( len( pathGroups ) ):\n\t\t\tpathGroup = pathGroups[ pathGroupIndex ]\n\t\t\tpaths[ pathGroupIndex ] = []\n\t\t\tfor explodedPathIndex in xrange( pathGroup[ 0 ], pathGroup[ 1 ] ):\n\t\t\t\texplodedPath = explodedPaths[ explodedPathIndex ]\n\t\t\t\tif len( paths[ pathGroupIndex ] ) == 0:\n\t\t\t\t\tpaths[ pathGroupIndex ] = explodedPath\n\t\t\t\telse:\n\t\t\t\t\tpaths[ pathGroupIndex ] += explodedPath[ 1 : ]\n\n\tdef addGridLinePoints( self, begin, end, gridPoints, gridRotationAngle, offset, y ):\n\t\t\"Add the segments of one line of a grid to the infill.\"\n\t\tif self.gridRadius == 0.0:\n\t\t\treturn\n\t\tgridWidth = self.gridWidthMultiplier * self.gridRadius\n\t\tgridXStep = int( math.floor( ( begin ) / gridWidth ) ) - 3\n\t\tgridXOffset = offset + gridWidth * float( gridXStep )\n\t\twhile gridXOffset < begin:\n\t\t\tgridXStep = self.getNextGripXStep( gridXStep )\n\t\t\tgridXOffset = offset + gridWidth * float( gridXStep )\n\t\twhile gridXOffset < end:\n\t\t\tgridPointComplex = complex( gridXOffset, y ) * gridRotationAngle\n\t\t\tif self.isPointInsideLineSegments( gridPointComplex ):\n\t\t\t\tgridPoints.append( gridPointComplex )\n\t\t\tgridXStep = self.getNextGripXStep( gridXStep )\n\t\t\tgridXOffset = offset + gridWidth * float( gridXStep )\n\n\tdef addRemainingGridPoints( self, arounds, gridPointInsetX, gridPointInsetY, gridPoints, isBothOrNone, paths, pixelTable, width ):\n\t\t\"Add the remaining grid points to the grid point list.\"\n\t\tfor gridPointIndex in xrange( len( gridPoints ) - 1, - 1, - 1 ):\n\t\t\tgridPoint = gridPoints[ gridPointIndex ]\n\t\t\taddAroundGridPoint( arounds, gridPoint, gridPointInsetX, gridPointInsetY, gridPoints, self.gridRadius, isBothOrNone, self.isDoubleJunction, self.isJunctionWide, paths, pixelTable, width )\n\n\tdef addRotatedCarve( self, layerIndex, reverseZRotationAngle, surroundingCarves ):\n\t\t\"Add a rotated carve to the surrounding carves.\"\n\t\tif layerIndex < 0 or layerIndex >= len( self.rotatedLayers ):\n\t\t\treturn\n\t\tsurroundingLoops = self.rotatedLayers[ layerIndex ].surroundingLoops\n\t\trotatedCarve = []\n\t\tfor surroundingLoop in surroundingLoops:\n\t\t\tplaneRotatedLoop = euclidean.getPointsRoundZAxis( reverseZRotationAngle, surroundingLoop.boundary )\n\t\t\trotatedCarve.append( planeRotatedLoop )\n\t\tsurroundingCarves.append( rotatedCarve )\n\n\tdef addThreadsBridgeLayer( self, rotatedLayer, surroundingLoops ):\n\t\t\"Add the threads, add the bridge end & the layer end tag.\"\n\t\teuclidean.addToThreadsRemoveFromSurroundings( self.oldOrderedLocation, surroundingLoops, self )\n\t\tif rotatedLayer.rotation != None:\n\t\t\tself.distanceFeedRate.addLine( '()' )\n\t\tself.distanceFeedRate.addLine( '()' )\n\n\tdef addToThread( self, location ):\n\t\t\"Add a location to thread.\"\n\t\tif self.oldLocation == None:\n\t\t\treturn\n\t\tif self.isPerimeter:\n\t\t\tself.surroundingLoop.addToLoop( location )\n\t\t\treturn\n\t\telif self.thread == None:\n\t\t\tself.thread = [ self.oldLocation.dropAxis( 2 ) ]\n\t\t\tself.surroundingLoop.perimeterPaths.append( self.thread )\n\t\tself.thread.append( location.dropAxis( 2 ) )\n\n\tdef getAreaChange( self, area, layerIndex ):\n\t\t\"Get the difference between the area of the carve at the layer index and the given area.\"\n\t\tlayerArea = self.getCarveArea( layerIndex )\n\t\treturn 1.0 - min( area, layerArea ) / max( area, layerArea )\n\n\tdef getCraftedGcode( self, fillRepository, gcodeText ):\n\t\t\"Parse gcode text and store the bevel gcode.\"\n\t\tself.fillRepository = fillRepository\n\t\tself.lines = gcodec.getTextLines( gcodeText )\n\t\tself.threadSequence = None\n\t\tif fillRepository.threadSequenceInfillLoops.value:\n\t\t\tself.threadSequence = [ 'infill', 'loops', 'perimeter' ]\n\t\tif fillRepository.threadSequenceInfillPerimeter.value:\n\t\t\tself.threadSequence = [ 'infill', 'perimeter', 'loops' ]\n\t\tif fillRepository.threadSequenceLoopsInfill.value:\n\t\t\tself.threadSequence = [ 'loops', 'infill', 'perimeter' ]\n\t\tif fillRepository.threadSequenceLoopsPerimeter.value:\n\t\t\tself.threadSequence = [ 'loops', 'perimeter', 'infill' ]\n\t\tif fillRepository.threadSequencePerimeterInfill.value:\n\t\t\tself.threadSequence = [ 'perimeter', 'infill', 'loops' ]\n\t\tif fillRepository.threadSequencePerimeterLoops.value:\n\t\t\tself.threadSequence = [ 'perimeter', 'loops', 'infill' ]\n\t\tif self.fillRepository.infillPerimeterOverlap.value > 0.7:\n\t\t\tprint( '' )\n\t\t\tprint( '!!! WARNING !!!' )\n\t\t\tprint( '\"Infill Perimeter Overlap\" is greater than 0.7, which may create problems with the infill, like threads going through empty space.' )\n\t\t\tprint( 'If you want to stretch the infill a lot, set \"Path Stretch over Perimeter Width\" in stretch to a high value instead of setting \"Infill Perimeter Overlap\" to a high value.' )\n\t\t\tprint( '' )\n\t\tself.parseInitialization()\n\t\tself.betweenWidth = self.perimeterWidth - 0.5 * self.infillWidth\n\t\tself.fillInset = self.infillWidth - self.infillWidth * self.fillRepository.infillPerimeterOverlap.value\n\t\tif self.fillRepository.infillInteriorDensityOverExteriorDensity.value > 0:\n\t\t\tself.interiorExtrusionWidth /= self.fillRepository.infillInteriorDensityOverExteriorDensity.value\n\t\tself.infillSolidity = fillRepository.infillSolidity.value\n\t\tif self.isGridToBeExtruded():\n\t\t\tself.setGridVariables( fillRepository )\n\t\tself.infillBeginRotation = math.radians( fillRepository.infillBeginRotation.value )\n\t\tself.infillOddLayerExtraRotation = math.radians( fillRepository.infillOddLayerExtraRotation.value )\n\t\tself.solidSurfaceThickness = int( round( self.fillRepository.solidSurfaceThickness.value ) )\n\t\tself.doubleSolidSurfaceThickness = self.solidSurfaceThickness + self.solidSurfaceThickness\n\t\tfor lineIndex in xrange( self.lineIndex, len( self.lines ) ):\n\t\t\tself.parseLine( lineIndex )\n\t\tfor layerIndex in xrange( len( self.rotatedLayers ) ):\n\t\t\tself.addFill( layerIndex )\n\t\tself.distanceFeedRate.addLines( self.lines[ self.shutdownLineIndex : ] )\n\t\treturn self.distanceFeedRate.output.getvalue()\n\n\tdef getGridPoints( self, fillLoops, reverseZRotationAngle ):\n\t\t\"Get the grid pointsl.\"\n\t\tif self.infillSolidity > 0.8:\n\t\t\treturn []\n\t\tgridPoints = []\n\t\trotationBaseAngle = euclidean.getUnitPolar( self.infillBeginRotation )\n\t\treverseRotationBaseAngle = complex( rotationBaseAngle.real, - rotationBaseAngle.imag )\n\t\tgridRotationAngle = reverseZRotationAngle * rotationBaseAngle\n\t\tgridAlreadyFilledArounds = []\n\t\tgridRotatedExtruderLoops = []\n\t\tback = - 999999999.0\n\t\tfront = - back\n\t\tgridInset = 1.2 * self.interiorExtrusionWidth\n\t\tslightlyGreaterThanFill = 1.01 * gridInset\n\t\tfor loop in fillLoops:\n\t\t\tgridAlreadyFilledLoop = []\n\t\t\tgridAlreadyFilledArounds.append( gridAlreadyFilledLoop )\n\t\t\tplaneRotatedPerimeter = euclidean.getPointsRoundZAxis( reverseRotationBaseAngle, loop )\n\t\t\tgridRotatedExtruderLoops.append( planeRotatedPerimeter )\n\t\t\tcenters = intercircle.getCentersFromLoop( planeRotatedPerimeter, slightlyGreaterThanFill )\n\t\t\tfor center in centers:\n\t\t\t\talreadyFilledInset = intercircle.getSimplifiedInsetFromClockwiseLoop( center, gridInset )\n\t\t\t\tif euclidean.isWiddershins( alreadyFilledInset ) == euclidean.isWiddershins( center ):\n\t\t\t\t\tgridAlreadyFilledLoop.append( alreadyFilledInset )\n\t\t\t\t\tif euclidean.isPathInsideLoop( planeRotatedPerimeter, alreadyFilledInset ) == euclidean.isWiddershins( planeRotatedPerimeter ):\n\t\t\t\t\t\tfor point in alreadyFilledInset:\n\t\t\t\t\t\t\tback = max( back, point.imag )\n\t\t\t\t\t\t\tfront = min( front, point.imag )\n\t\tfront = ( 0.01 + math.ceil( front / self.gridRadius ) ) * self.gridRadius\n\t\tfillWidth = back - front\n\t\tnumberOfLines = int( math.ceil( fillWidth / self.gridRadius ) )\n\t\tgridSegmentLists = euclidean.getHorizontalSegmentListsFromLoopLists( gridAlreadyFilledArounds, front, numberOfLines, gridRotatedExtruderLoops, self.gridRadius )\n\t\tshortenedSegmentLists = []\n\t\tfor fillLine in xrange( numberOfLines ):\n\t\t\tlineSegments = gridSegmentLists[ fillLine ]\n\t\t\tshortenedSegments = []\n\t\t\tfor lineSegment in lineSegments:\n\t\t\t\taddShortenedLineSegment( lineSegment, self.interiorExtrusionWidth, shortenedSegments )\n\t\t\tshortenedSegmentLists.append( shortenedSegments )\n\t\tfor shortenedSegmentList in shortenedSegmentLists:\n\t\t\tfor shortenedSegment in shortenedSegmentList:\n\t\t\t\tendpointFirst = shortenedSegment[ 0 ]\n\t\t\t\tendpointSecond = shortenedSegment[ 1 ]\n\t\t\t\tbegin = min( endpointFirst.point.real, endpointSecond.point.real )\n\t\t\t\tend = max( endpointFirst.point.real, endpointSecond.point.real )\n\t\t\t\ty = endpointFirst.point.imag\n\t\t\t\toffset = self.offsetMultiplier * self.gridRadius * ( round( y / self.gridRadius ) % 2 )\n\t\t\t\tself.addGridLinePoints( begin, end, gridPoints, gridRotationAngle, offset, y )\n\t\treturn gridPoints\n\n\tdef getLayerRoundZ( self, layerIndex ):\n\t\t\"Get the plane angle around z that the layer is rotated by.\"\n\t\trotation = self.rotatedLayers[ layerIndex ].rotation\n\t\tif rotation != None:\n\t\t\treturn rotation\n\t\tinfillBeginRotationRepeat = self.fillRepository.infillBeginRotationRepeat.value\n\t\tinfillOddLayerRotationMultiplier = float( layerIndex % ( infillBeginRotationRepeat + 1 ) == infillBeginRotationRepeat )\n\t\treturn euclidean.getUnitPolar( self.infillBeginRotation + infillOddLayerRotationMultiplier * self.infillOddLayerExtraRotation )\n\n\tdef getNextGripXStep( self, gridXStep ):\n\t\t\"Get the next grid x step, increment by an extra one every three if hexagonal grid is chosen.\"\n\t\tgridXStep += 1\n\t\tif self.fillRepository.infillPatternGridHexagonal.value:\n\t\t\tif gridXStep % 3 == 0:\n\t\t\t\tgridXStep += 1\n\t\treturn gridXStep\n\n\tdef getCarveArea( self, layerIndex ):\n\t\t\"Get the area of the carve.\"\n\t\tif layerIndex < 0 or layerIndex >= len( self.rotatedLayers ):\n\t\t\treturn 0.0\n\t\tsurroundingLoops = self.rotatedLayers[ layerIndex ].surroundingLoops\n\t\tarea = 0.0\n\t\tfor surroundingLoop in surroundingLoops:\n\t\t\tarea += euclidean.getPolygonArea( surroundingLoop.boundary )\n\t\treturn area\n\n\tdef isGridToBeExtruded( self ):\n\t\t\"Determine if the grid is to be extruded.\"\n\t\treturn ( not self.fillRepository.infillPatternLine.value ) and self.fillRepository.infillInteriorDensityOverExteriorDensity.value > 0\n\n\tdef isPointInsideLineSegments( self, gridPoint ):\n\t\t\"Is the point inside the line segments of the loops.\"\n\t\tif self.solidSurfaceThickness <= 0:\n\t\t\treturn True\n\t\tfillLine = int( round( gridPoint.imag / self.layerExtrusionWidth - self.frontOverWidth ) )\n\t\tif fillLine >= len( self.horizontalSegmentLists ) or fillLine < 0:\n\t\t\treturn False\n\t\tlineSegments = self.horizontalSegmentLists[ fillLine ]\n\t\tsurroundingXIntersections = self.surroundingXIntersectionLists[ fillLine ]\n\t\tfor lineSegment in lineSegments:\n\t\t\tif isSegmentCompletelyInAnIntersection( lineSegment, surroundingXIntersections ):\n\t\t\t\txFirst = lineSegment[ 0 ].point.real\n\t\t\t\txSecond = lineSegment[ 1 ].point.real\n\t\t\t\tif gridPoint.real > min( xFirst, xSecond ) and gridPoint.real < max( xFirst, xSecond ):\n\t\t\t\t\treturn True\n\t\treturn False\n\n\tdef linearMove( self, splitLine ):\n\t\t\"Add a linear move to the thread.\"\n\t\tlocation = gcodec.getLocationFromSplitLine( self.oldLocation, splitLine )\n\t\tif self.extruderActive:\n\t\t\tself.addToThread( location )\n\t\tself.oldLocation = location\n\n\tdef parseInitialization( self ):\n\t\t\"Parse gcode initialization and store the parameters.\"\n\t\tfor self.lineIndex in xrange( len( self.lines ) ):\n\t\t\tline = self.lines[ self.lineIndex ]\n\t\t\tsplitLine = gcodec.getSplitLineBeforeBracketSemicolon( line )\n\t\t\tfirstWord = gcodec.getFirstWord( splitLine )\n\t\t\tself.distanceFeedRate.parseSplitLine( firstWord, splitLine )\n\t\t\tif firstWord == '(':\n\t\t\t\tself.perimeterWidth = float( splitLine[ 1 ] )\n\t\t\t\tthreadSequenceString = ' '.join( self.threadSequence )\n\t\t\t\tself.distanceFeedRate.addTagBracketedLine( 'threadSequenceString', threadSequenceString )\n\t\t\telif firstWord == '()':\n\t\t\t\tself.distanceFeedRate.addLine( '( fill )' )\n\t\t\telif firstWord == '()':\n\t\t\t\tself.distanceFeedRate.addLine( line )\n\t\t\t\treturn\n\t\t\telif firstWord == '(':\n\t\t\t\tself.bridgeWidthMultiplier = float( splitLine[ 1 ] )\n\t\t\telif firstWord == '(':\n\t\t\t\tself.layerThickness = float( splitLine[ 1 ] )\n\t\t\t\tself.infillWidth = self.fillRepository.infillWidthOverThickness.value * self.layerThickness\n\t\t\t\tself.interiorExtrusionWidth = self.infillWidth\n\t\t\tself.distanceFeedRate.addLine( line )\n \n\tdef parseLine( self, lineIndex ):\n\t\t\"Parse a gcode line and add it to the fill skein.\"\n\t\tline = self.lines[ lineIndex ]\n\t\tsplitLine = gcodec.getSplitLineBeforeBracketSemicolon( line )\n\t\tif len( splitLine ) < 1:\n\t\t\treturn\n\t\tfirstWord = splitLine[ 0 ]\n\t\tif firstWord == 'G1':\n\t\t\tself.linearMove( splitLine )\n\t\telif firstWord == 'M101':\n\t\t\tself.extruderActive = True\n\t\telif firstWord == 'M103':\n\t\t\tself.extruderActive = False\n\t\t\tself.thread = None\n\t\t\tself.isPerimeter = False\n\t\telif firstWord == '()':\n\t\t\tself.surroundingLoop = euclidean.SurroundingLoop( self.threadSequence )\n\t\t\tself.rotatedLayer.surroundingLoops.append( self.surroundingLoop )\n\t\telif firstWord == '()':\n\t\t\tself.surroundingLoop = None\n\t\telif firstWord == '(':\n\t\t\tlocation = gcodec.getLocationFromSplitLine( None, splitLine )\n\t\t\tself.surroundingLoop.addToBoundary( location )\n\t\telif firstWord == '(':\n\t\t\tsecondWordWithoutBrackets = splitLine[ 1 ].replace( '(', '' ).replace( ')', '' )\n\t\t\tself.rotatedLayer.rotation = complex( secondWordWithoutBrackets )\n\t\telif firstWord == '()':\n\t\t\tself.shutdownLineIndex = lineIndex\n\t\telif firstWord == '(':\n\t\t\tself.rotatedLayer = RotatedLayer( float( splitLine[ 1 ] ) )\n\t\t\tself.rotatedLayers.append( self.rotatedLayer )\n\t\t\tself.thread = None\n\t\telif firstWord == '(':\n\t\t\tself.isPerimeter = True\n\n\tdef setGridVariables( self, fillRepository ):\n\t\t\"Set the grid variables.\"\n\t\tself.gridRadius = self.interiorExtrusionWidth / self.infillSolidity\n\t\tself.gridWidthMultiplier = 2.0\n\t\tself.offsetMultiplier = 1.0\n\t\tif self.fillRepository.infillPatternGridHexagonal.value:\n\t\t\tself.gridWidthMultiplier = 2.0 / math.sqrt( 3.0 )\n\t\t\tself.offsetMultiplier = 2.0 / math.sqrt( 3.0 ) * 1.5\n\t\tif self.fillRepository.infillPatternGridRectangular.value:\n\t\t\thalfGridRadiusMinusInteriorExtrusionWidth = 0.5 * ( self.gridRadius - self.interiorExtrusionWidth )\n\t\t\tself.gridJunctionSeparationAtEnd = halfGridRadiusMinusInteriorExtrusionWidth * fillRepository.gridJunctionSeparationOverOctogonRadiusAtEnd.value\n\t\t\tself.gridJunctionSeparationAtMiddle = halfGridRadiusMinusInteriorExtrusionWidth * fillRepository.gridJunctionSeparationOverOctogonRadiusAtMiddle.value\n\n\nclass RotatedLayer:\n\t\"A rotated layer.\"\n\tdef __init__( self, z ):\n\t\tself.rotation = None\n\t\tself.surroundingLoops = []\n\t\tself.z = z\n\n\tdef __repr__( self ):\n\t\t\"Get the string representation of this RotatedLayer.\"\n\t\treturn '%s, %s, %s' % ( self.z, self.rotation, self.surroundingLoops )\n\n\nclass YIntersectionPath:\n\t\"A class to hold the y intersection position, the loop which it intersected and the point index of the loop which it intersected.\"\n\tdef __init__( self, pathIndex, pointIndex, y ):\n\t\t\"Initialize from the path, point index, and y.\"\n\t\tself.pathIndex = pathIndex\n\t\tself.pointIndex = pointIndex\n\t\tself.y = y\n\n\tdef __repr__( self ):\n\t\t\"Get the string representation of this y intersection.\"\n\t\treturn '%s, %s, %s' % ( self.pathIndex, self.pointIndex, self.y )\n\n\tdef getPath( self, paths ):\n\t\t\"Get the path from the paths and path index.\"\n\t\treturn paths[ self.pathIndex ]\n\n\tdef getPointIndexPlusOne( self ):\n\t\t\"Get the point index plus one.\"\n\t\treturn self.pointIndex + 1\n\n\ndef main():\n\t\"Display the fill dialog.\"\n\tif len( sys.argv ) > 1:\n\t\twriteOutput( ' '.join( sys.argv[ 1 : ] ) )\n\telse:\n\t\tsettings.startMainLoopFromConstructor( getNewRepository() )\n\nif __name__ == \"__main__\":\n\tmain()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2010,"string":"2,010"}}},{"rowIdx":40054,"cells":{"__id__":{"kind":"number","value":8469675519809,"string":"8,469,675,519,809"},"blob_id":{"kind":"string","value":"17cb6dfac03d071dfc37beefa2aa007eb2ff2753"},"directory_id":{"kind":"string","value":"3f910860e2b8b90931c9a205eb94edc22aa97e00"},"path":{"kind":"string","value":"/collect/test_app.py"},"content_id":{"kind":"string","value":"9c71999784112cc90571b92eb14680d869608f21"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"psherman/collectapp"},"repo_url":{"kind":"string","value":"https://github.com/psherman/collectapp"},"snapshot_id":{"kind":"string","value":"7f1e1dd8d0e9f482ff4eb5abb48d1b3c511cb428"},"revision_id":{"kind":"string","value":"7af85c674dc5dbb96a5ff19adbac2c9f0eff83f5"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-08-03T23:31:22.941731","string":"2016-08-03T23:31:22.941731"},"revision_date":{"kind":"timestamp","value":"2014-09-15T18:38:01","string":"2014-09-15T18:38:01"},"committer_date":{"kind":"timestamp","value":"2014-09-15T18:38:01","string":"2014-09-15T18:38:01"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import os\nimport shutil\nimport app as collect\nimport unittest\nimport json\n\nclass CollectTestCase(unittest.TestCase):\n\n def setUp(self):\n collect.app.testing = True\n collect.groups = {\n \"test\":\"ing\"\n }\n self.directory = collect.directory\n self.app = collect.app.test_client()\n\n def tearDown(self):\n example_directory = '%s/rules/example_com' % self.directory\n if os.path.isdir(example_directory):\n shutil.rmtree(example_directory)\n\n def test_get_groups(self):\n groups = self.app.get('/groups')\n self.assertEqual(groups.headers.get('Content-Type'), 'application/json')\n self.assertEqual(json.loads(groups.data), collect.groups)\n\n def test_upload(self):\n headers = [('Content-Type', 'application/json')]\n example_rules = {\n \"host\": \"example.com\",\n \"name\": \"examples\",\n \"rules\": {\n \"links\": {\n \"name\": \"links\",\n \"capture\": \"attr-href\",\n \"selector\": \"a\"\n },\n \"images\": {\n \"name\": \"images\",\n \"capture\": \"attr-src\",\n \"selector\": \"#main img\"\n }\n }\n }\n rules = self.app.post('/upload', headers=headers, data=json.dumps(example_rules))\n self.assertEqual(rules.status_code, 200)\n data_file = os.path.join(self.directory, 'rules', 'example_com', 'rules.json')\n with open(data_file) as fp:\n saved_rules = json.load(fp)\n self.assertEqual(saved_rules['examples'], example_rules['rules'])\n\n def test_upload_multiple(self):\n headers = [('Content-Type', 'application/json')]\n link_rules = {\n \"host\": \"example.com\",\n \"name\": \"links\",\n \"rules\": {\n \"links\": {\n \"name\": \"links\",\n \"capture\": \"attr-href\",\n \"selector\": \"a\"\n }, \n \"next\": {\n \"name\": \"next\",\n \"capture\": \"attr-href\",\n \"selector\": \"a.next\"\n }\n }\n }\n image_rules = {\n \"host\": \"example.com\",\n \"name\": \"images\",\n \"rules\": {\n \"images\": {\n \"name\": \"images\",\n \"capture\": \"attr-src\",\n \"selector\": \"#main img\"\n }\n }\n }\n rules = self.app.post('/upload', headers=headers, data=json.dumps(link_rules))\n self.assertEqual(rules.status_code, 200)\n rules = self.app.post('/upload', headers=headers, data=json.dumps(image_rules))\n self.assertEqual(rules.status_code, 200)\n data_file = os.path.join(self.directory, 'rules', 'example_com', 'rules.json')\n with open(data_file) as fp:\n saved_rules = json.load(fp)\n self.assertEqual(saved_rules['links'], link_rules['rules'])\n self.assertEqual(saved_rules['images'], image_rules['rules'])\n \n\nif __name__ == \"__main__\":\n unittest.main()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":40055,"cells":{"__id__":{"kind":"number","value":11733850699400,"string":"11,733,850,699,400"},"blob_id":{"kind":"string","value":"8f1e230f3f7c623b02b52f273926050daa7ff2b5"},"directory_id":{"kind":"string","value":"ba9023bb5882d30a964cc9e4d5c4a1fcfe1adcba"},"path":{"kind":"string","value":"/medium/locks.py"},"content_id":{"kind":"string","value":"beec5f3b890b2997ba7e0addeacf7852131c22fb"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"corinnelhh/code_eval"},"repo_url":{"kind":"string","value":"https://github.com/corinnelhh/code_eval"},"snapshot_id":{"kind":"string","value":"a3921a6e334356049e67263d4507a6567111a933"},"revision_id":{"kind":"string","value":"969ae10aa21a8991bc6917de49e2bac57e985576"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-01T16:13:20.533997","string":"2021-01-01T16:13:20.533997"},"revision_date":{"kind":"timestamp","value":"2014-10-02T18:36:38","string":"2014-10-02T18:36:38"},"committer_date":{"kind":"timestamp","value":"2014-10-02T18:36:38","string":"2014-10-02T18:36:38"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# https://www.codeeval.com/open_challenges/153/\n\n# Locks\n# Challenge Description:\n\n# There are \"n\" unlocked rooms located in a row along a long corridor.\n\n# A security guard starts at the beginning of the corridor, passes by and\n# locks the lock of every second door(2, 4, 6 ...). If a lock was open,\n# it now becomes closed, if it was closed, it stays closed. He then\n# returns to the beginning of the corridor and switches the lock to the\n# opposite position on every third door(3, 6, 9 ...): if the door's lock\n# was open before, he close it and vice versa. This algorithm (first every\n# second door's lock is closed; then every third door's lock is switched\n# to the opposite position) repeats \"m\"-1 times.\n\n# On his last pass (the \"m\" one), only the last door's lock must be\n# switched without any additional actions.\n\n# Your job is to determine how many doors have been left unlocked.\n\n# Input sample:\n\n# 3 1\n# 100 100\n\n# Your program should accept as its first argument a path to a filename.\n\n# Each line of input contains 2 integer - n - number of locks and m - how\n# many times to repeat actions:\n\n# Output sample:\n\n# For each line of input print out how many door are left unlocked:\n\n# 2\n# 50\n\nimport sys\n\n\ndef get_unlocked_doors(locks, passes):\n locks_dict = {i: False for i in range(locks)}\n for i in range(passes - 1):\n for i in range(1, locks, 2):\n locks_dict[i] = True\n for i in range(2, locks, 3):\n locks_dict[i] = not locks_dict[i]\n locks_dict[locks - 1] = not locks_dict[locks - 1]\n print len([k for k, v in locks_dict.items() if not v])\n\n\nwith open(sys.argv[1], 'r') as f:\n for line in f.readlines():\n get_unlocked_doors(*(int(n) for n in line.strip().split()))\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":40056,"cells":{"__id__":{"kind":"number","value":3272765091846,"string":"3,272,765,091,846"},"blob_id":{"kind":"string","value":"5f9320c951da242a2dfc87164ce8bc2a35d41b33"},"directory_id":{"kind":"string","value":"ec1cb67fd60d9dda8c79ef0fc0fc1eb4f3363f00"},"path":{"kind":"string","value":"/recommendations.py"},"content_id":{"kind":"string","value":"44ca65bf94a0faefddab19707d7f7298b0587e27"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"schemacs/pci"},"repo_url":{"kind":"string","value":"https://github.com/schemacs/pci"},"snapshot_id":{"kind":"string","value":"4fc773ff53d2ab090a9c19e73478d1b3ba78c6e7"},"revision_id":{"kind":"string","value":"8712354bded28839f314747113a7e4365d9fe43b"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-08-04T12:11:11.706530","string":"2016-08-04T12:11:11.706530"},"revision_date":{"kind":"timestamp","value":"2012-10-07T04:41:36","string":"2012-10-07T04:41:36"},"committer_date":{"kind":"timestamp","value":"2012-10-07T04:41:36","string":"2012-10-07T04:41:36"},"github_id":{"kind":"number","value":6076007,"string":"6,076,007"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":2,"string":"2"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2012 by Lele Long \n# This file is free software, distributed under the GPL License.\n#\n# get recommendation in programming collective Intelligence\n#\n\nfrom math import sqrt\n\n# A dictionary of movie critics and their ratings of a small\n# set of movies\ncritics = {'Lisa Rose': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5,\n 'Just My Luck': 3.0, 'Superman Returns': 3.5, 'You, Me and Dupree': 2.5,\n 'The Night Listener': 3.0},\n 'Gene Seymour': {'Lady in the Water': 3.0, 'Snakes on a Plane': 3.5,\n 'Just My Luck': 1.5, 'Superman Returns': 5.0, 'The Night Listener': 3.0,\n 'You, Me and Dupree': 3.5},\n 'Michael Phillips': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.0,\n 'Superman Returns': 3.5, 'The Night Listener': 4.0},\n 'Claudia Puig': {'Snakes on a Plane': 3.5, 'Just My Luck': 3.0,\n 'The Night Listener': 4.5, 'Superman Returns': 4.0,\n 'You, Me and Dupree': 2.5},\n 'Mick LaSalle': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0,\n 'Just My Luck': 2.0, 'Superman Returns': 3.0, 'The Night Listener': 3.0,\n 'You, Me and Dupree': 2.0},\n 'Jack Matthews': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0,\n 'The Night Listener': 3.0, 'Superman Returns': 5.0, 'You, Me and Dupree': 3.5},\n 'Toby': {'Snakes on a Plane': 4.5, 'You, Me and Dupree': 1.0, 'Superman Returns': 4.0}}\n\n\ndef sim_distance(prefs, p1, p2):\n si = {}\n for item in prefs[p1]:\n if item in prefs[p2]:\n si[item] = 1\n if len(si) == 0:\n return 0\n\n sum_of_squares = sum([pow(prefs[p1][item] - prefs[p2][item], 2) for item in si.iterkeys()])\n return 1 / (1 + sqrt(sum_of_squares))\n\n\ndef sim_pearson(prefs, p1, p2):\n '''Pearson's Correlation Coefficient\n 1) 样本共变异数除以的标准差与的标准差之乘积。\n 2) 协方差和标准差的商\n sum(x*y) - sum(x) * sum(y)/n\n ----------------------------\n sqrt( (sum(x^2) - sum(x)^2/n) * (sum(y^2) - sum(y)^2/n) )\n '''\n si = {}\n for item in prefs[p1]:\n if item in prefs[p2]:\n si[item] = 1\n n = len(si)\n if n == 0:\n return 0\n\n sum1 = sum([prefs[p1][it] for it in si])\n sum2 = sum([prefs[p2][it] for it in si])\n\n sum1Sq = sum([pow(prefs[p1][it], 2) for it in si])\n sum2Sq = sum([pow(prefs[p2][it], 2) for it in si])\n\n pSum = sum([prefs[p1][it] * prefs[p2][it] for it in si])\n\n num = pSum - (sum1 * sum2 / n)\n den = sqrt((sum1Sq - pow(sum1, 2) / n) * (sum2Sq - pow(sum2, 2) / n))\n if den == 0:\n return 0\n r = num / den\n\n return r\n\n\ndef topMatches(prefs, person, n=5, similarity=sim_pearson):\n scores = [(similarity(prefs, person, other), other)\n for other in prefs if other != person]\n scores.sort()\n scores.reverse()\n return scores[0:n]\n\n\ndef getRecommendations(prefs, person, similarity=sim_pearson):\n totals = {}\n simSums = {}\n for other in prefs:\n if other == person:\n continue\n sim = similarity(prefs, person, other)\n if sim <= 0:\n continue\n for item in prefs[other]:\n if item not in prefs[person] or prefs[person][item] == 0:\n totals.setdefault(item, 0)\n totals[item] += prefs[other][item] * sim\n simSums.setdefault(item, 0)\n simSums[item] += sim\n rankings = [(total / simSums[item], item) for item, total in totals.items()]\n rankings.sort()\n rankings.reverse()\n return rankings\n\n\ndef transformPrefs(prefs):\n result = {}\n for person in prefs:\n for item in prefs[person]:\n result.setdefault(item, {})\n result[item][person] = prefs[person][item]\n return result\n\n\ndef calculateSimilarItems(prefs, n=10):\n result = {}\n itemPrefs = transformPrefs(prefs)\n\n c = 0\n for item in itemPrefs:\n c += 1\n if c % 100 == 0:\n print \"%d / %d\" % (c, len(itemPrefs))\n scores = topMatches(itemPrefs, item, n=n, similarity=sim_distance)\n result[item] = scores\n return result\n\n\ndef getRecommendedItems(prefs, itemMatch, user):\n userRatings = prefs[user]\n scores = {}\n totalSim = {}\n\n for (item, rating) in userRatings.items():\n for (similarity, item2) in itemMatch[item]:\n if item2 in userRatings:\n continue\n scores.setdefault(item2, 0)\n scores[item2] += similarity * rating\n\n totalSim.setdefault(item2, 0)\n totalSim[item2] += similarity\n rankings = [(score / totalSim[item], item) for item, score in scores.items()]\n rankings.sort()\n rankings.reverse()\n return rankings\n\n\ndef loadMovies():\n movies = {}\n for line in open('u.item'):\n (id, title) = line.split('|')[0:2]\n movies[id] = title\n\n prefs = {}\n for line in open('u.data'):\n (user, movieid, rating, ts) = line.split('\\t')\n prefs.setdefault(user, {})\n prefs[user][movies[movieid]] = float(rating)\n return prefs\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":40057,"cells":{"__id__":{"kind":"number","value":18683107764467,"string":"18,683,107,764,467"},"blob_id":{"kind":"string","value":"91ed280f80a251087d1b40e46ee3ed485ad47d87"},"directory_id":{"kind":"string","value":"f79e53aedab9c74ae9bdd9f0bc652d17b303de63"},"path":{"kind":"string","value":"/mantis-1.0-beta/src/test/performance/SConscript"},"content_id":{"kind":"string","value":"441312e6b5a38e22906166609e752bd8722a0f88"},"detected_licenses":{"kind":"list like","value":["BSD-3-Clause"],"string":"[\n \"BSD-3-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"ghostandthemachine/mantis-os"},"repo_url":{"kind":"string","value":"https://github.com/ghostandthemachine/mantis-os"},"snapshot_id":{"kind":"string","value":"063490389a3cf6b445e3b1df38e0196e9a4632ce"},"revision_id":{"kind":"string","value":"848d97ff3f55b76c073eb622ad48536ee1eb7883"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-01T19:25:33.031047","string":"2021-01-01T19:25:33.031047"},"revision_date":{"kind":"timestamp","value":"2011-05-31T23:54:24","string":"2011-05-31T23:54:24"},"committer_date":{"kind":"timestamp","value":"2011-05-31T23:54:24","string":"2011-05-31T23:54:24"},"github_id":{"kind":"number","value":1829303,"string":"1,829,303"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"\nimport glob\nimport os\nimport string\nfrom scripts.build_support import *\n\nImport ('*')\n\n\n# List of application files and sources defined here\n# Example definition:\n#\n# app_names_list = ['foo.elf', 'bar.elf']\n# foo_sources = ['foo.c']\n# bar_sources = ['bar1.c', 'bar2.c', 'bar3.c']\n# app_sources_list = [foo_sources, bar_sources]\n\napp_names_list = ['thread.elf','nothread.elf','dev.elf','nodev.elf','com.elf','nocom.elf','thread-spam.elf']\nthread_sources = ['kernel-thread.c']\nnothread_sources = ['kernel-nothread.c']\ndev_sources = ['dev.c']\nnodev_sources = ['nodev.c']\ncom_sources = ['com.c']\nnocom_sources = ['nocom.c']\nthread_spam_sources = ['thread-spam.c']\napp_sources_list = [thread_sources, nothread_sources, dev_sources, nodev_sources, com_sources, nocom_sources, thread_spam_sources]\n\n\n\n\n\n\n# app build methods\nloadstat = ARGUMENTS.get('load', '0')\nbuild_app_function(env, app_names_list, app_sources_list, loadstat)\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2011,"string":"2,011"}}},{"rowIdx":40058,"cells":{"__id__":{"kind":"number","value":10711648455121,"string":"10,711,648,455,121"},"blob_id":{"kind":"string","value":"239b5c25a1904785db4af300aec2b8d8500ee1c0"},"directory_id":{"kind":"string","value":"2ad9b0245ae49ee62bf9058cff3e4bd5cd8f5a8c"},"path":{"kind":"string","value":"/predicate.py"},"content_id":{"kind":"string","value":"e62fb8f57b1ec03422d72275c4c0b7eafa70baaa"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"hbradlow/pygeom"},"repo_url":{"kind":"string","value":"https://github.com/hbradlow/pygeom"},"snapshot_id":{"kind":"string","value":"7918904b837da45baac2b5289b976eca9424c7b6"},"revision_id":{"kind":"string","value":"8bc5a7e871b4acb23aa6c1eaf8bfefe85e6c7d3d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-22T09:47:56.097964","string":"2021-01-22T09:47:56.097964"},"revision_date":{"kind":"timestamp","value":"2013-02-02T11:53:02","string":"2013-02-02T11:53:02"},"committer_date":{"kind":"timestamp","value":"2013-02-02T11:53:02","string":"2013-02-02T11:53:02"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import numpy as np\n\ndef orient_2d(p,q,r):\n \"\"\"\n > 0 if CCW\n < 0 if CW\n = 0 if colinear\n \"\"\"\n return (q[0]-p[0])*(r[1]-p[1]) - (r[0]-p[0])*(q[1]-p[1])\n\ndef intersects(seg1,seg2):\n return \\\n orient_2d(seg2.start,seg2.end,seg1.start)* \\\n orient_2d(seg2.start,seg2.end,seg1.end)<=0 \\\n and \\\n orient_2d(seg1.start,seg1.end,seg2.start)* \\\n orient_2d(seg1.start,seg1.end,seg2.end)<=0\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":40059,"cells":{"__id__":{"kind":"number","value":13254269090865,"string":"13,254,269,090,865"},"blob_id":{"kind":"string","value":"a273fc2ec9cb27bfc66ebb1a89274bc03a258761"},"directory_id":{"kind":"string","value":"fb2054a38b93cb1a441c76eb5b06e166a3373a4b"},"path":{"kind":"string","value":"/xmlutil.py"},"content_id":{"kind":"string","value":"ec788e9f2b4e72d91557228f0257b406bbd17ca8"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"bchang/musicdb-python"},"repo_url":{"kind":"string","value":"https://github.com/bchang/musicdb-python"},"snapshot_id":{"kind":"string","value":"f954bad3e29edd6f3fa8e672e50f0dfea1118159"},"revision_id":{"kind":"string","value":"34416bb7d36b8c83ba7efb57db08a8a7393a19c8"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-19T18:56:14.435299","string":"2021-01-19T18:56:14.435299"},"revision_date":{"kind":"timestamp","value":"2013-01-19T22:14:33","string":"2013-01-19T22:14:33"},"committer_date":{"kind":"timestamp","value":"2013-01-19T22:14:33","string":"2013-01-19T22:14:33"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"'''\nCreated on Jan 10, 2013\n\n@author: bchang\n'''\nfrom xml.dom import Node\n\ndef getChildren(parent):\n for node in parent.childNodes:\n if node.nodeType == Node.ELEMENT_NODE:\n yield node\n\ndef getChildrenByTagName(parent, name):\n for node in getChildren(parent):\n if node.tagName == name:\n yield node\n\ndef firstChildElement(node):\n node = node.firstChild\n return __ensureElement__(node)\n\ndef nextSiblingElement(node):\n node = node.nextSibling\n return __ensureElement__(node)\n\ndef __ensureElement__(node):\n while node is not None and node.nodeType != Node.ELEMENT_NODE:\n node = node.nextSibling\n return node\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":40060,"cells":{"__id__":{"kind":"number","value":5360119230356,"string":"5,360,119,230,356"},"blob_id":{"kind":"string","value":"8f04940841b8f0b17aa1e609cde8bd8c16fbcd22"},"directory_id":{"kind":"string","value":"82397140d41bcaa04f8b6c413b5042223d0e4168"},"path":{"kind":"string","value":"/pipeline.py"},"content_id":{"kind":"string","value":"981b2cb81d5446a2c87c486ba4398cedf9c44938"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"pkarmstr/relation-extraction"},"repo_url":{"kind":"string","value":"https://github.com/pkarmstr/relation-extraction"},"snapshot_id":{"kind":"string","value":"c415e4d3e8ee3cf4bc12a3cce92ec4e3f32398fd"},"revision_id":{"kind":"string","value":"b387d667fce2eba70a60649f64ba78ac83e2bdda"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-16T15:00:03.651075","string":"2016-09-16T15:00:03.651075"},"revision_date":{"kind":"timestamp","value":"2014-04-04T05:40:52","string":"2014-04-04T05:40:52"},"committer_date":{"kind":"timestamp","value":"2014-04-04T05:40:52","string":"2014-04-04T05:40:52"},"github_id":{"kind":"number","value":18023190,"string":"18,023,190"},"star_events_count":{"kind":"number","value":6,"string":"6"},"fork_events_count":{"kind":"number","value":4,"string":"4"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"__author__ = 'keelan'\n\nimport sys\nimport os\nimport shlex\nimport linecache\nfrom operator import itemgetter\nfrom os.path import join\nfrom subprocess import Popen, PIPE\nfrom feature_generator import Featurizer\nfrom file_reader import feature_list_reader, get_original_data\nfrom feature_functions import *\n\nclass Pipeline:\n\n def __init__(self, basedir, svmdir, type=\"dev\"):\n self.basedir = basedir\n self.svmdir = svmdir\n self.type = type\n self.svm_args = \"-t 5\"\n self.training_data = get_original_data(\"resources/cleaned-train.gold\")\n self.test_data = get_original_data(\"resources/cleaned-{:s}.notag\".format(type))\n\n def set_up(self):\n basedir_contents = os.listdir(self.basedir)\n files = [f for f in basedir_contents if os.path.isfile(join(self.basedir, f))]\n directories = [f for f in basedir_contents if os.path.isdir(join(self.basedir, f))]\n\n if \"feature_list.txt\" not in files or\\\n \"tree_list.txt\" not in files:\n sys.exit(\"You need feature_list.txt and tree_list.txt in the base directory\")\n if \"gold_files\" not in directories:\n os.mkdir(join(self.basedir, \"gold_files\"))\n if \"models\" not in directories:\n os.mkdir(join(self.basedir, \"models\"))\n if \"tagged_files\" not in directories:\n os.mkdir(join(self.basedir, \"tagged_files\"))\n self.tree_funcs = feature_list_reader(\n join(self.basedir, \"tree_list.txt\"), globals()\n )\n self.feature_funcs = feature_list_reader(\n join(self.basedir, \"feature_list.txt\"), globals()\n )\n\n def build_features(self):\n f_training = Featurizer(self.training_data, self.tree_funcs, self.feature_funcs)\n f_training.build_features()\n f_training.build_relation_class_vectors()\n f_training.write_multiple_vectors(join(self.basedir, \"gold_files\"), \"train.gold\")\n\n f_test = Featurizer(self.test_data, self.tree_funcs, self.feature_funcs, no_tag=True)\n f_test.build_features()\n f_test.write_no_tag(self.basedir, \"{:s}.notag\".format(self.type))\n\n def run_svm_learn(self):\n processes = []\n svm_learn = join(self.svmdir, \"svm_learn\")\n for gold_file in os.listdir(join(self.basedir, \"gold_files\")):\n prefix = gold_file.split(\"-train.gold\")[0]\n train = join(self.basedir, \"gold_files\", gold_file)\n model = join(self.basedir, \"models\", \"{:s}.model\".format(prefix))\n args = shlex.split(\"{:s} {:s} {:s} {:s}\".format(svm_learn, self.svm_args, train, model))\n p = Popen(args, stdout=PIPE)\n processes.append(p)\n print \"Building the model for {:s}\".format(prefix)\n for p in processes:\n p.wait()\n\n def run_svm_classify(self):\n processes = []\n svm_classify = join(self.svmdir, \"svm_classify\")\n for model in os.listdir(join(self.basedir, \"models\")):\n prefix = model.split(\".model\")[0]\n model = join(self.basedir, \"models\", model)\n notag = join(self.basedir, \"{:s}.notag\".format(self.type))\n tagged = join(self.basedir, \"tagged_files\", \"{:s}.tagged\".format(prefix))\n args = shlex.split(\"{:s} {:s} {:s} {:s}\".format(svm_classify, notag, model, tagged))\n p = Popen(args, stdout=PIPE)\n processes.append(p)\n print \"Classifying with the {:s} model\".format(prefix)\n for p in processes:\n p.wait()\n\n def _prepare_line(self, line):\n return float(line.rstrip())\n\n def translate_svm_output(self):\n relation_class = [\"PHYS\", \"PER-SOC\", \"OTHER-AFF\", \"GPE-AFF\", \"DISC\", \"ART\", \"EMP-ORG\"]\n file_locations = [join(self.basedir, \"tagged_files\", \"{:s}.tagged\".format(f)) for f in relation_class]\n relation_ids = zip(relation_class, file_locations)\n max_type = []\n class_indices = []\n with open(join(self.basedir, \"tagged_files\", \"no_rel.tagged\"), \"r\") as f_in:\n for i,line in enumerate(f_in):\n val = self._prepare_line(line)\n if val <= 0.5:\n class_indices.append(i)\n max_type.append((\"no_rel\", -10000)) #giant magic number\n else:\n max_type.append((\"no_rel\", val))\n\n for rel_class,f in relation_ids:\n for index in class_indices:\n val = self._prepare_line(linecache.getline(f, index))\n if val > max_type[index][1]:\n max_type[index] = (rel_class, val)\n linecache.clearcache()\n return zip(*max_type)[0]\n\n def evaluate(self):\n output = join(self.basedir, \"final_output.tagged\")\n gold = \"resources/cleaned-{:s}.gold\"\n redirect = \"> {:s}/eval.txt\".format(self.basedir)\n args = shlex.split(\"{:s} {:s} {:s} {:s} {:s}\".format(\"python27\",\n \"evaluator_finegrained.py\",\n gold,\n output,\n redirect))\n p = Popen(args, stdout=PIPE)\n p.wait()\n\n def run(self):\n print \"setting up...\",\n self.set_up()\n print \"[DONE]\"\n print \"building features...\"\n self.build_features()\n print \"built all features\"\n print \"building the models...\"\n self.run_svm_learn()\n print \"built all of the models\"\n print \"classifying across all models...\"\n self.run_svm_classify()\n print \"finished classification...\"\n answers = self.translate_svm_output()\n with open(join(self.basedir, \"final_output.tagged\"), \"w\") as f_out:\n f_out.write(\"\\n\".join(answers))\n print \"wrote the output into final_output.tagged [DONE]\"\n self.evaluate()\n print \"wrote the evaluation into eval.txt\"\n\n\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"basedir\", help=\"the directory in which the experiment wil be\")\n parser.add_argument(\"svmdir\", help=\"the directory in which the svm binaries live\")\n parser.add_argument(\"type\", help=\"dev or test\")\n args = parser.parse_args()\n\n pl = Pipeline(args.basedir, args.svmdir, args.type)\n pl.run()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":40061,"cells":{"__id__":{"kind":"number","value":11854109756732,"string":"11,854,109,756,732"},"blob_id":{"kind":"string","value":"a21efdade06d211d6ac0fedfc622eaa4e0b35858"},"directory_id":{"kind":"string","value":"90984d0c6ab0ea66495cb62b7c6df8f24322135c"},"path":{"kind":"string","value":"/mlt/map/writers/kml.py"},"content_id":{"kind":"string","value":"04896775ef957bcfdf5f42e36245d38b9027573e"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"pombredanne/mlt"},"repo_url":{"kind":"string","value":"https://github.com/pombredanne/mlt"},"snapshot_id":{"kind":"string","value":"4e83e7a60243f5a62e60c897ec334f4912e584a7"},"revision_id":{"kind":"string","value":"dd4e0a1650883ca8e9cdd47b2755742ac4ae4dbd"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2018-05-30T19:42:54.809327","string":"2018-05-30T19:42:54.809327"},"revision_date":{"kind":"timestamp","value":"2011-12-12T21:27:20","string":"2011-12-12T21:27:20"},"committer_date":{"kind":"timestamp","value":"2011-12-12T21:27:20","string":"2011-12-12T21:27:20"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from django.template.loader import render_to_string\n\nfrom .base import AddressWriter\n\n\n\nclass KMLWriter(AddressWriter):\n mimetype = \"application/vnd.google-earth.kml+xml\"\n extension = \"kml\"\n\n\n def save(self, stream):\n def addresses(objects):\n for address in objects:\n address.serialized = self.serializer.one(address)\n yield address\n\n stream.write(\n render_to_string(\n \"kml/base.kml\", {\"addresses\": addresses(self.objects)}))\n\n return len(self.objects)\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2011,"string":"2,011"}}},{"rowIdx":40062,"cells":{"__id__":{"kind":"number","value":7258494781274,"string":"7,258,494,781,274"},"blob_id":{"kind":"string","value":"2f26b90c9c36c00ef22670f15080a8e34d972d0f"},"directory_id":{"kind":"string","value":"423c9b82ffc7cb417f55b160c929d1af999ce43d"},"path":{"kind":"string","value":"/models.py"},"content_id":{"kind":"string","value":"743e08677d054051d877200465021f7ae2a3800b"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"mlunacek/drip"},"repo_url":{"kind":"string","value":"https://github.com/mlunacek/drip"},"snapshot_id":{"kind":"string","value":"a56c150db892e9cfd666756bec3abacb94e03a29"},"revision_id":{"kind":"string","value":"59c66ab70dfdd5ead767a714b7ca5ef2964826ae"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T13:48:49.633601","string":"2021-01-18T13:48:49.633601"},"revision_date":{"kind":"timestamp","value":"2012-10-30T15:28:49","string":"2012-10-30T15:28:49"},"committer_date":{"kind":"timestamp","value":"2012-10-30T15:28:49","string":"2012-10-30T15:28:49"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from django.db import models\nfrom piston.handler import BaseHandler\nfrom piston.utils import rc\nfrom django.db import IntegrityError\n\nclass Job(models.Model):\n job_id = models.CharField(max_length=60, unique=True)\n user_name = models.CharField(max_length=60)\n job_name = models.CharField(max_length=60)\n start_time = models.DateTimeField(db_index=True)\n resources = models.CharField(max_length=120,null=True, blank=True)\n test_run = models.BooleanField()\n\nclass NodeTest(models.Model):\n job = models.ForeignKey(Job, related_name='job')\n node_name = models.CharField(max_length=8)\n start_time = models.DateTimeField(db_index=True)\n \n def __unicode__(self):\n return self.job.job_id + \" \" + self.node_name\n \n def test_string(self):\n qs = self.node_test.all().order_by('test_name')\n strlist = [ str(q.value) for q in qs ]\n return \", \".join(strlist)\n \n class Meta:\n unique_together = ('job', 'node_name')\n \nclass Test(models.Model):\n node_test = models.ForeignKey(NodeTest, related_name='node_test')\n test_name = models.CharField(max_length=60) \n value = models.FloatField(null=True, blank=True) \n threshold = models.FloatField(null=True, blank=True) \n passed = models.NullBooleanField()\n \n def __unicode__(self):\n return self.test_name\n \n class Meta:\n unique_together = ('node_test', 'test_name')\n\n \nclass NodeTestHandler(BaseHandler):\n \n allowed_methods = ('GET','PUT','POST',)\n fields = ('node_name','test_date', ('node_test', ('test_name', 'value',),),) \n model = NodeTest\n \n def read(self, name=None):\n return self.model.objects.all()\n \n def create(self, request):\n if request.content_type:\n data = request.data\n\n for i in data:\n \n test_node_i = NodeTest(node_name=i['node_name'],test_date=i['test_date'])\n try:\n test_node_i.save()\n except IntegrityError as e:\n return rc.DUPLICATE_ENTRY\n \n for x in i['node_test']:\n test_x = Test(test_name=x['test_name'], value=x['value'], node_test=test_node_i)\n try:\n test_x.save()\n except IntegrityError as e:\n return rc.DUPLICATE_ENTRY\n \n return rc.CREATED\n else:\n super(NodeTest, self).create(request)\n \n\n \n "},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":40063,"cells":{"__id__":{"kind":"number","value":19456201851446,"string":"19,456,201,851,446"},"blob_id":{"kind":"string","value":"439779afbf578e6a0fc018c32595eb87a090bc40"},"directory_id":{"kind":"string","value":"284073c44f93fb77260ac00de394d238884e2318"},"path":{"kind":"string","value":"/testing/Test.py"},"content_id":{"kind":"string","value":"637f5cb242bf652e46f27ce80d9c00469adffb85"},"detected_licenses":{"kind":"list like","value":["LGPL-2.0-or-later"],"string":"[\n \"LGPL-2.0-or-later\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"yolanother/Xournal"},"repo_url":{"kind":"string","value":"https://github.com/yolanother/Xournal"},"snapshot_id":{"kind":"string","value":"aba6829f59cf7455efc65e840ab343e128ad9141"},"revision_id":{"kind":"string","value":"55b71cbd382fa4ebb7b790aca85f9d0428efed09"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-04-12T05:16:26.100136","string":"2021-04-12T05:16:26.100136"},"revision_date":{"kind":"timestamp","value":"2012-01-27T18:51:03","string":"2012-01-27T18:51:03"},"committer_date":{"kind":"timestamp","value":"2012-01-27T18:51:03","string":"2012-01-27T18:51:03"},"github_id":{"kind":"number","value":3251333,"string":"3,251,333"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import xournal\nimport undo.UndoRedoTest\nfrom TestNotImplementedException import TestNotImplementedException\nimport os\nimport sys\nimport gtk\nimport traceback\n\nclass XournalTestRunner:\n\tdef __init__(self):\n\t\tself.failedTests = 0\n\t\tself.notImplementedTests = 0\n\t\tself.successfullyTests = 0\n\t\tself.xoj = xournal.Xournal()\n\t\tself.faileTest = []\n\n\tdef start(self):\n\t\tprint '=== Xournal Testsuit ===\\n'\n\t\t\n\t\ttestCanceled = False\n\n\t\tsubfolders = ['clipboard', 'document', 'tools', 'undo']\n\t\tfor folder in subfolders:\n\t\t\tif self.xournalRunTestInSubfolder(folder) == False:\n\t\t\t\tprint 'Cancel Testing\\n'\n\t\t\t\ttestCanceled = True\n\t\t\t\tbreak\n\n\t\tprint '\\n=== End Xournal Testsuit ===\\n'\n\n\t\tif testCanceled == True:\n\t\t\tmd = gtk.MessageDialog(None, 0, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, 'Test cancelled!')\n\t\t\tmd.run()\n\t\t\tmd.destroy()\n\t\telif self.failedTests == 0:\n\t\t\tmsg = 'All test passed'\n\n\t\t\tif self.notImplementedTests != 0:\n\t\t\t\tmsg += ' (%i not implemented)' % self.notImplementedTests\n\n\t\t\tmd = gtk.MessageDialog(None, 0, gtk.MESSAGE_INFO, gtk.BUTTONS_CLOSE, msg)\n\t\t\tmd.run()\n\t\t\tmd.destroy()\n\t\telse:\n\t\t\ttests = '';\n\t\t\tfor test in self.faileTest:\n\t\t\t\ttests += u'\\n- ' + test\n\n\t\t\tnotImplemented = ''\n\t\t\tif self.notImplementedTests != 0:\n\t\t\t\tnotImplemented = ' (%i not implemented)' % self.notImplementedTests\n\n\n\t\t\tmd = gtk.MessageDialog(None, 0, gtk.MESSAGE_WARNING, gtk.BUTTONS_CLOSE, '')\n\t\t\tmd.set_markup('%i Test failed%s:\\n%s' % (self.failedTests, notImplemented, tests))\n\t\t\tmd.run()\n\t\t\tmd.destroy()\n\n\n\n\n\tdef xournalRunTestInSubfolder(self, subfolder):\n\t\tpath = os.path.realpath(__file__)\n\t\tpath = os.path.dirname(path)\n\t\tfolder = os.path.join(path, subfolder)\n\n\t\tprint 'Running scripts in %s' % folder\n\n\t\tfor name in os.listdir(folder):\n\t\t\tdirfile = os.path.join(folder, name)\n\t\t\n\t\t\tif os.path.isdir(dirfile) and not name.startswith('.') and os.path.exists(os.path.join(dirfile, name + '.py')):\n\t\t\t\tprint 'Run test in %s' % dirfile\n\t#\t\t\tprint 'Debug: import %s from %s' % (name, subfolder + '.' + name + '.' + name)\n\n\t\t\t\ttry:\n\t\t\t\t\tsFrom = subfolder + '.' + name + '.' + name\n\t\t\t\t\tmoduleObject = __import__(sFrom, globals(), locals(), [name], -1)\n\t\t\t\t\tclassObject = getattr(moduleObject, name)\n\t\t\t\t\tobj = classObject(self.xoj)\n\t\t\t\t\tobj.test()\n\t\t\t\t\tself.successfullyTests += 1\n\t\t\t\texcept (AssertionError, IOError) as e:\n\t\t\t\t\tself.failedTests += 1\n\n\t\t\t\t\tself.faileTest.append(subfolder + '/' + name)\n\n\t\t\t\t\tprint >> sys.stderr, 'Test %s failed!' % name\n\t\t\t\t\tprint >> sys.stderr, type(e) # the exception instance\n\t\t\t\t\tprint >> sys.stderr, e.args # arguments stored in .args\n\t\t\t\t\tprint >> sys.stderr, e\n\t\t\t\t\ttraceback.print_exc()\n\t\t\t\texcept (TestNotImplementedException) as e:\n\t\t\t\t\tself.notImplementedTests += 1\n\n\t\t\t\texcept (KeyboardInterrupt):\n\t\t\t\t\treturn False\n\n\t\t\t\texcept (Exception) as e:\n\t\t\t\t\tself.failedTests += 1\n\n\t\t\t\t\tself.faileTest.append(subfolder + '/' + name)\n\n\t\t\t\t\tprint >> sys.stderr, 'Test %s Unexpected error %s:' % (name, type(e))\n\t\t\t\t\tprint >> sys.stderr, e.args # arguments stored in .args\n\t\t\t\t\tprint >> sys.stderr, e\n\t\t\t\t\ttraceback.print_exc()\n\n\t\tprint '\\n\\n\\n==================================================='\n\t\tprint 'Testresult: %i successfully, %i not implemented, %i failed!' % (self.successfullyTests, self.notImplementedTests, self.failedTests)\n\t\tprint '===================================================\\n\\n'\n\n\t\treturn True\n\n\ndef xournalTest(args = ''):\n\tprint 'Xournal testsuit started...'\n\n\ttester = XournalTestRunner()\n\ttester.start()\n\tdel tester\n\n\n\t\n\n#\tprint xoj.openFile('/home/andreas/tmp/Notiz-10-03-2011-16-57.xoj')\n\n\"\"\"\txoj.mousePressed(10, 10)\n\txoj.mouseMoved(20, 20)\n\txoj.mouseReleased()\n\n\tud = ColorUndoAction()\n\"\"\"\n\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":40064,"cells":{"__id__":{"kind":"number","value":10840497472051,"string":"10,840,497,472,051"},"blob_id":{"kind":"string","value":"0e4e9bdacfb1183e00a606a979dd0ba0c8ad6bf2"},"directory_id":{"kind":"string","value":"efde83f95faa464a7505d8e0d1ab8de500ebcd8d"},"path":{"kind":"string","value":"/Contents/Code/__init__.py"},"content_id":{"kind":"string","value":"ea4fd5372c8a6b80472880f6ba41a0c211645ca1"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"corrado1968/PlexMovie.bundle"},"repo_url":{"kind":"string","value":"https://github.com/corrado1968/PlexMovie.bundle"},"snapshot_id":{"kind":"string","value":"abb0c5fe125755d09429415d6fcf47a6a7cf5787"},"revision_id":{"kind":"string","value":"cc5d1c1881ea901c0cb0dc9e3491fc95ffa4ed7d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-23T21:12:39.557651","string":"2021-01-23T21:12:39.557651"},"revision_date":{"kind":"timestamp","value":"2010-12-09T19:54:50","string":"2010-12-09T19:54:50"},"committer_date":{"kind":"timestamp","value":"2010-12-09T19:54:50","string":"2010-12-09T19:54:50"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import datetime, re, time, unicodedata, hashlib\n\n# [might want to look into language/country stuff at some point] \n# param info here: http://code.google.com/apis/ajaxsearch/documentation/reference.html\n#\nGOOGLE_JSON_URL = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&userip=%s&rsz=large&q=%s'\nFREEBASE_URL = 'http://freebase.plexapp.com'\nPLEXMOVIE_URL = 'http://plexmovie.plexapp.com'\n\nSCORE_THRESHOLD_IGNORE = 55\nSCORE_THRESHOLD_IGNORE_PENALTY = 100 - SCORE_THRESHOLD_IGNORE\nSCORE_THRESHOLD_IGNORE_PCT = float(SCORE_THRESHOLD_IGNORE_PENALTY)/100\n\ndef Start():\n HTTP.CacheTime = CACHE_1HOUR * 4\n \nclass PlexMovieAgent(Agent.Movies):\n name = 'Freebase'\n languages = [Locale.Language.English, Locale.Language.Swedish, Locale.Language.French, \n Locale.Language.Spanish, Locale.Language.Dutch, Locale.Language.German, \n Locale.Language.Italian]\n\n def identifierize(self, string):\n string = re.sub( r\"\\s+\", \" \", string.strip())\n string = unicodedata.normalize('NFKD', unicode(string))\n string = re.sub(r\"['\\\"!?@#$&%^*\\(\\)_+\\.,;:/]\",\"\", string)\n string = re.sub(r\"[_ ]+\",\"_\", string)\n string = string.strip('_')\n return string.strip().lower()\n\n def guidize(self, string):\n hash = hashlib.sha1()\n hash.update(string.encode('utf-8'))\n return hash.hexdigest()\n\n def titleyear_guid(self, title, year):\n if title is None:\n title = ''\n\n if year == '' or year is None or not year:\n string = \"%s\" % self.identifierize(title)\n else:\n string = \"%s_%s\" % (self.identifierize(title).lower(), year)\n return self.guidize(\"%s\" % string)\n \n def getPublicIP(self):\n ip = HTTP.Request('http://plexapp.com/ip.php').content.strip()\n return ip\n \n def getGoogleResults(self, url):\n try:\n jsonObj = JSON.ObjectFromURL(url, sleep=0.5)\n if jsonObj['responseData'] != None:\n jsonObj = jsonObj['responseData']['results']\n if len(jsonObj) > 0:\n return jsonObj\n except:\n Log(\"Exception obtaining result from Google.\")\n \n return []\n \n def search(self, results, media, lang):\n \n # Keep track of best name.\n idMap = {}\n bestNameMap = {}\n bestNameDist = 1000\n \n # TODO: create a plex controlled cache for lookup\n # TODO: by imdbid -> (title,year)\n # See if we're being passed a raw ID.\n findByIdCalled = False\n if media.guid or re.match('t*[0-9]{7}', media.name):\n theGuid = media.guid or media.name \n if not theGuid.startswith('tt'):\n theGuid = 'tt' + theGuid\n \n # Add a result for the id found in the passed in guid hint.\n findByIdCalled = True\n (title, year) = self.findById(theGuid)\n if title is not None:\n results.Append(MetadataSearchResult(id=theGuid, name=title, year=year, lang=lang, score=100))\n bestNameMap[theGuid] = title\n \n if media.year:\n searchYear = ' (' + str(media.year) + ')'\n else:\n searchYear = ''\n\n # first look in the proxy/cache \n titleyear_guid = self.titleyear_guid(media.name,searchYear)\n\n bestCacheHitScore = 0\n cacheConsulted = False\n\n # plexhash search vector\n plexHashes = []\n score = 100\n for item in media.items:\n for part in item.parts:\n if part.plexHash: plexHashes.append(part.plexHash)\n for ph in plexHashes: \n try:\n url = '%s/movie/hash/%s/%s.xml' % (PLEXMOVIE_URL, ph[0:2], ph)\n Log(\"checking plexhash search vector: %s\" % url)\n res = XML.ElementFromURL(url)\n for match in res.xpath('//match'):\n id = \"tt%s\" % match.get('guid')\n imdbName = match.get('title')\n imdbYear = match.get('year')\n bestNameMap[id] = imdbName \n\n scorePenalty = 0\n if int(imdbYear) > datetime.datetime.now().year:\n Log(imdbName + ' penalizing for future release date')\n scorePenalty += SCORE_THRESHOLD_IGNORE_PENALTY \n \n # Check to see if the hinted year is different from imdb's year, if so penalize.\n elif media.year and imdbYear and int(media.year) != int(imdbYear):\n Log(imdbName + ' penalizing for hint year and imdb year being different')\n yearDiff = abs(int(media.year)-(int(imdbYear)))\n if yearDiff == 1:\n scorePenalty += 5\n elif yearDiff == 2:\n scorePenalty += 10\n else:\n scorePenalty += 15\n # Bonus (or negatively penalize) for year match.\n elif media.year and imdbYear and int(media.year) != int(imdbYear):\n scorePenalty += -5\n \n # Sanity check to make sure we have SOME common substring.\n longestCommonSubstring = len(Util.LongestCommonSubstring(media.name.lower(), imdbName.lower()))\n \n # If we don't have at least 10% in common, then penalize below the 80 point threshold\n if (float(longestCommonSubstring) / len(media.name)) < SCORE_THRESHOLD_IGNORE_PCT:\n scorePenalty += SCORE_THRESHOLD_IGNORE_PENALTY \n\n Log(\"score penalty (used to determine if google is needed) = %d\" % scorePenalty)\n\n if (score - scorePenalty) > bestCacheHitScore:\n bestCacheHitScore = score - scorePenalty\n \n cacheConsulted = True\n # score at minimum 85 (threshold) since we trust the cache to be at least moderately good\n results.Append(MetadataSearchResult(id = id, name = imdbName, year = imdbYear, lang = lang, score = max([ score-scorePenalty, SCORE_THRESHOLD_IGNORE])))\n score = score - 4\n except Exception, e:\n Log(\"freebase/proxy plexHash lookup failed: %s\" % repr(e))\n\n # title|year search vector\n url = '%s/movie/guid/%s/%s.xml' % (PLEXMOVIE_URL, titleyear_guid[0:2], titleyear_guid)\n Log(\"checking title|year search vector: %s\" % url)\n try:\n res = XML.ElementFromURL(url)\n for match in res.xpath('//match'):\n id = \"tt%s\" % match.get('guid')\n\n imdbName = match.get('title')\n bestNameMap[id] = imdbName \n\n imdbYear = match.get('year')\n\n scorePenalty = 0\n if int(imdbYear) > datetime.datetime.now().year:\n Log(imdbName + ' penalizing for future release date')\n scorePenalty += SCORE_THRESHOLD_IGNORE_PENALTY \n\n # Check to see if the hinted year is different from imdb's year, if so penalize.\n elif media.year and imdbYear and int(media.year) != int(imdbYear):\n Log(imdbName + ' penalizing for hint year and imdb year being different')\n yearDiff = abs(int(media.year)-(int(imdbYear)))\n if yearDiff == 1:\n scorePenalty += 5\n elif yearDiff == 2:\n scorePenalty += 10\n else:\n scorePenalty += 15\n # Bonus (or negatively penalize) for year match.\n elif media.year and imdbYear and int(media.year) != int(imdbYear):\n scorePenalty += -5\n\n # Sanity check to make sure we have SOME common substring.\n longestCommonSubstring = len(Util.LongestCommonSubstring(media.name.lower(), imdbName.lower()))\n\n # If we don't have at least 10% in common, then penalize below the 80 point threshold\n if (float(longestCommonSubstring) / len(media.name)) < SCORE_THRESHOLD_IGNORE_PCT:\n scorePenalty += SCORE_THRESHOLD_IGNORE_PENALTY \n\n Log(\"score penalty (used to determine if google is needed) = %d\" % scorePenalty)\n\n if (score - scorePenalty) > bestCacheHitScore:\n bestCacheHitScore = score - scorePenalty\n\n cacheConsulted = True\n # score at minimum 85 (threshold) since we trust the cache to be at least moderately good\n results.Append(MetadataSearchResult(id = id, name = imdbName, year = imdbYear, lang = lang, score = max([ score-scorePenalty, SCORE_THRESHOLD_IGNORE])))\n score = score - 4\n except Exception, e:\n Log(\"freebase/proxy guid lookup failed: %s\" % repr(e))\n\n\n doGoogleSearch = False\n if len(results) == 0 or bestCacheHitScore <= SCORE_THRESHOLD_IGNORE:\n doGoogleSearch = True\n\n Log(\"PLEXMOVIE INFO RETRIEVAL: FINDBYID: %s CACHE: %s SEARCH_ENGINE: %s\" % (findByIdCalled, cacheConsulted, doGoogleSearch))\n\n if doGoogleSearch:\n normalizedName = String.StripDiacritics(media.name)\n GOOGLE_JSON_QUOTES = GOOGLE_JSON_URL % (self.getPublicIP(), String.Quote('\"' + normalizedName + searchYear + '\"', usePlus=True)) + '+site:imdb.com'\n GOOGLE_JSON_NOQUOTES = GOOGLE_JSON_URL % (self.getPublicIP(), String.Quote(normalizedName + searchYear, usePlus=True)) + '+site:imdb.com'\n GOOGLE_JSON_NOSITE = GOOGLE_JSON_URL % (self.getPublicIP(), String.Quote(normalizedName + searchYear, usePlus=True)) + '+imdb.com'\n if lang == Locale.Language.Italian:\n GOOGLE_JSON_QUOTES_LANG = GOOGLE_JSON_URL % (self.getPublicIP(), String.Quote('\"' + normalizedName + searchYear + '\"', usePlus=True)) + '+site:imdb.it'\n GOOGLE_JSON_NOQUOTES_LANG = GOOGLE_JSON_URL % (self.getPublicIP(), String.Quote(normalizedName + searchYear, usePlus=True)) + '+site:imdb.it'\n GOOGLE_JSON_NOSITE_LANG = GOOGLE_JSON_URL % (self.getPublicIP(), String.Quote(normalizedName + searchYear, usePlus=True)) + '+imdb.it'\n \n subsequentSearchPenalty = 0\n \n for s in [GOOGLE_JSON_QUOTES_LANG, GOOGLE_JSON_NOQUOTES_LANG, GOOGLE_JSON_QUOTES, GOOGLE_JSON_NOQUOTES]:\n if s == GOOGLE_JSON_QUOTES and (media.name.count(' ') == 0 or media.name.count('&') > 0 or media.name.count(' and ') > 0):\n # no reason to run this test, plus it screwed up some searches\n continue \n \n subsequentSearchPenalty += 1\n \n # Check to see if we need to bother running the subsequent searches\n Log(\"We have %d results\" % len(results))\n if len(results) < 3:\n score = 99\n \n # Make sure we have results and normalize them.\n jsonObj = self.getGoogleResults(s)\n \n # Now walk through the results. \n for r in jsonObj:\n \n # Get data.\n url = r['unescapedUrl']\n title = r['titleNoFormatting']\n \n # Parse the name and year.\n imdbName, imdbYear = self.parseTitle(title)\n if not imdbName:\n # Doesn't match, let's skip it.\n Log(\"Skipping strange title: \" + title + \" with URL \" + url)\n continue\n else:\n Log(\"Using [%s] derived from [%s] (url=%s)\" % (imdbName, title, url))\n \n scorePenalty = 0\n url = r['unescapedUrl'].lower().replace('us.vdc','www').replace('title?','title/tt') #massage some of the weird url's google has\n if url[-1:] == '/':\n url = url[:-1]\n \n splitUrl = url.split('/')\n \n if len(splitUrl) == 6 and re.match('tt[0-9]+', splitUrl[-2]) is not None:\n \n # This is the case where it is not just a link to the main imdb title page, but to a subpage. \n # In some odd cases, google is a bit off so let's include these with lower scores \"just in case\".\n #\n scorePenalty = 10\n del splitUrl[-1]\n \n if len(splitUrl) > 5 and re.match('tt[0-9]+', splitUrl[-1]) is not None:\n while len(splitUrl) > 5:\n del splitUrl[-2]\n scorePenalty += 5\n \n if len(splitUrl) == 5 and re.match('tt[0-9]+', splitUrl[-1]) is not None:\n \n id = splitUrl[-1]\n if id.count('+') > 0:\n # Penalizing for abnormal tt link.\n scorePenalty += 10\n try:\n \n # Keep the closest name around.\n distance = Util.LevenshteinDistance(media.name, imdbName)\n if not bestNameMap.has_key(id) or distance < bestNameDist:\n bestNameMap[id] = imdbName\n bestNameDist = distance\n \n # Don't process for the same ID more than once.\n if idMap.has_key(id):\n continue\n \n # Check to see if the item's release year is in the future, if so penalize.\n if imdbYear > datetime.datetime.now().year:\n Log(imdbName + ' penalizing for future release date')\n scorePenalty += SCORE_THRESHOLD_IGNORE_PENALTY \n \n # Check to see if the hinted year is different from imdb's year, if so penalize.\n elif media.year and imdbYear and int(media.year) != int(imdbYear): \n Log(imdbName + ' penalizing for hint year and imdb year being different')\n yearDiff = abs(int(media.year)-(int(imdbYear)))\n if yearDiff == 1:\n scorePenalty += 5\n elif yearDiff == 2:\n scorePenalty += 10\n else:\n scorePenalty += 15\n \n # Bonus (or negatively penalize) for year match.\n elif media.year and imdbYear and int(media.year) != int(imdbYear): \n scorePenalty += -5\n \n # It's a video game, run away!\n if title.count('(VG)') > 0:\n break\n \n # It's a TV series, don't use it.\n if title.count('(TV series)') > 0:\n Log(imdbName + ' penalizing for TV series')\n scorePenalty += 6\n \n # Sanity check to make sure we have SOME common substring.\n longestCommonSubstring = len(Util.LongestCommonSubstring(media.name.lower(), imdbName.lower()))\n \n # If we don't have at least 10% in common, then penalize below the 80 point threshold\n if (float(longestCommonSubstring) / len(media.name)) < SCORE_THRESHOLD_IGNORE_PCT: \n scorePenalty += SCORE_THRESHOLD_IGNORE_PENALTY \n \n # Finally, add the result.\n idMap[id] = True\n Log(\"score = %d\" % (score - scorePenalty + subsequentSearchPenalty))\n results.Append(MetadataSearchResult(id = id, name = imdbName, year = imdbYear, lang = lang, score = score - (scorePenalty + subsequentSearchPenalty)))\n except:\n Log('Exception processing IMDB Result')\n pass\n \n # Each search entry is worth less, but we subtract even if we don't use the entry...might need some thought.\n score = score - 4 \n \n ## end giant google block\n \n results.Sort('score', descending=True)\n \n # Finally, de-dupe the results.\n toWhack = []\n resultMap = {}\n for result in results:\n if not resultMap.has_key(result.id):\n resultMap[result.id] = True\n else:\n toWhack.append(result)\n \n for dupe in toWhack:\n results.Remove(dupe)\n\n # Make sure we're using the closest names.\n for result in results:\n result.name = bestNameMap[result.id]\n \n def update(self, metadata, media, lang):\n\n # Set the title. FIXME, this won't work after a queued restart.\n if media:\n metadata.title = media.title\n\n # Hit our repository.\n guid = re.findall('tt([0-9]+)', metadata.guid)[0]\n url = '%s/movies/%s/%s.xml' % (FREEBASE_URL, guid[-2:], guid)\n\n try:\n movie = XML.ElementFromURL(url)\n\n # Runtime.\n if int(movie.get('runtime')) > 0:\n metadata.duration = int(movie.get('runtime')) * 60 * 1000\n\n # Genres.\n metadata.genres.clear()\n genreMap = {}\n \n for genre in movie.xpath('genre'):\n id = genre.get('id')\n genreLang = genre.get('lang')\n genreName = genre.get('genre')\n \n if not genreMap.has_key(id) and genreLang in ('en', lang):\n genreMap[id] = [genreLang, genreName]\n \n elif genreMap.has_key(id) and genreLang == lang:\n genreMap[id] = [genreLang, genreName]\n \n keys = genreMap.keys()\n keys.sort()\n for id in keys:\n metadata.genres.add(genreMap[id][1])\n\n # Directors.\n metadata.directors.clear()\n for director in movie.xpath('director'):\n metadata.directors.add(director.get('name'))\n \n # Writers.\n metadata.writers.clear()\n for writer in movie.xpath('writer'):\n metadata.writers.add(writer.get('name'))\n \n # Actors.\n metadata.roles.clear()\n for movie_role in movie.xpath('actor'):\n role = metadata.roles.new()\n if movie_role.get('role'):\n role.role = movie_role.get('role')\n #role.photo = headshot_url\n role.actor = movie_role.get('name')\n \n # Studio\n if movie.get('company'):\n metadata.studio = movie.get('company')\n \n # Tagline.\n if len(movie.get('tagline')) > 0:\n metadata.tagline = movie.get('tagline')\n \n # Content rating.\n if movie.get('content_rating'):\n metadata.content_rating = movie.get('content_rating')\n \n # Release date.\n if len(movie.get('originally_available_at')) > 0:\n elements = movie.get('originally_available_at').split('-')\n if len(elements) >= 1 and len(elements[0]) == 4:\n metadata.year = int(elements[0])\n\n if len(elements) == 3:\n metadata.originally_available_at = Datetime.ParseDate(movie.get('originally_available_at')).date()\n \n #************START NEW SECTION****************\n \n #title in language (lang)\n for titolo in movie.xpath('title'):\n titoloLang = titolo.get('lang')\n titoloName = titolo.get('title')\n if titoloLang == lang:\n metadata.title = titoloName\n break\n \n #Original title\n metadata.original_title = movie.get('title')\n metadata.tagline=metadata.original_title\n \n #************END NEW SECTION**************** \n \n except:\n print \"Error obtaining Plex movie data for\", guid\n\n m = re.search('(tt[0-9]+)', metadata.guid)\n if m and not metadata.year:\n id = m.groups(1)[0]\n (title, year) = self.findById(id)\n metadata.year = year\n\n\n def findById(self, id):\n jsonObj = self.getGoogleResults(GOOGLE_JSON_URL % (self.getPublicIP(), id))\n \n try:\n (title, year) = self.parseTitle(jsonObj[0]['titleNoFormatting'])\n return (title, year)\n except:\n pass\n \n return (None, None)\n\n def parseTitle(self, title):\n # Parse out title, year, and extra.\n titleRx = '(.*) \\(([^0-9]+ )?([0-9]+)(/.*)?\\).*'\n m = re.match(titleRx, title)\n if m:\n # A bit more processing for the name.\n imdbName = self.cleanupName(m.groups()[0])\n imdbYear = int(m.groups()[2])\n return (imdbName, imdbYear)\n \n longTitleRx = '(.*\\.\\.\\.)'\n m = re.match(longTitleRx, title)\n if m:\n imdbName = self.cleanupName(m.groups(1)[0])\n return (imdbName, None)\n \n return (None, None)\n \n def cleanupName(self, s):\n imdbName = re.sub('^[iI][mM][dD][bB][ ]*:[ ]*', '', s)\n imdbName = re.sub('^details - ', '', imdbName)\n imdbName = re.sub('(.*:: )+', '', imdbName)\n imdbName = HTML.ElementFromString(imdbName).text\n \n if imdbName:\n if imdbName[0] == '\"' and imdbName[-1] == '\"':\n imdbName = imdbName[1:-1]\n return imdbName\n \n return None\n \n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2010,"string":"2,010"}}},{"rowIdx":40065,"cells":{"__id__":{"kind":"number","value":7224135021644,"string":"7,224,135,021,644"},"blob_id":{"kind":"string","value":"97466b96fc646084c29a603188fac2e46c417853"},"directory_id":{"kind":"string","value":"ddf2677edfda56dfd6d3e59e7f0cd21cdab8f8db"},"path":{"kind":"string","value":"/trunk/src/lino/django/utils/editing.py"},"content_id":{"kind":"string","value":"475d410573ae5bc3e15019b300ec4fd86a9decdd"},"detected_licenses":{"kind":"list like","value":["GPL-2.0-only","MIT"],"string":"[\n \"GPL-2.0-only\",\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"BackupTheBerlios/lino-svn"},"repo_url":{"kind":"string","value":"https://github.com/BackupTheBerlios/lino-svn"},"snapshot_id":{"kind":"string","value":"13398d68b04d36dace1b44f5ec0a567064b8b1dc"},"revision_id":{"kind":"string","value":"93bbb22698a06ba78c84344ec6f639c93deb5ef3"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-23T15:42:41.810323","string":"2021-01-23T15:42:41.810323"},"revision_date":{"kind":"timestamp","value":"2009-07-07T10:26:51","string":"2009-07-07T10:26:51"},"committer_date":{"kind":"timestamp","value":"2009-07-07T10:26:51","string":"2009-07-07T10:26:51"},"github_id":{"kind":"number","value":40806965,"string":"40,806,965"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"## Copyright 2009 Luc Saffre\r\n\r\n## This file is part of the Lino project.\r\n\r\n## Lino is free software; you can redistribute it and/or modify it\r\n## under the terms of the GNU General Public License as published by\r\n## the Free Software Foundation; either version 2 of the License, or\r\n## (at your option) any later version.\r\n\r\n## Lino is distributed in the hope that it will be useful, but WITHOUT\r\n## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\r\n## or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\r\n## License for more details.\r\n\r\n## You should have received a copy of the GNU General Public License\r\n## along with Lino; if not, write to the Free Software Foundation,\r\n## Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r\n\r\nimport os\r\n\r\n\"\"\"\r\nThis middleware manages the \"editing\" status of a Session. \r\n\r\nViews should not pay attention (nor modify) the \"editing\" key in request.GET and in request.session.\r\nViews are supposed to call is_editing() to determine whether they should\r\nrender an editable version or not.\r\n\r\nInternally, editing is activated by a GET editing=1, \r\nstopped explicitly by GET editing=0, or stopped automatically \r\nif the request.path changes. Editing is also \"sticky\", if theres no\r\n\"editing\" key requested, then the previous request's value is \r\nmaintained.\r\n\r\n\r\nThere can be more than one renderers in a single request. \r\nWhen a renderer says stop_editing(), then this should become \r\nactive only for the next request, other renderers of the same \r\nrequest must still get True when they call is_editing().\r\n\r\nIf a renderer calls stop_editing() and some other renderer \r\n(before or after) calls continue_editing(), then editing continues.\r\n\r\nExample: when a renderer saves successfully, then it calls stop_editing(). But if some other renderer detects a validation error, then it calls continue_editing() and this will override the stop call of the first renderer.\r\n\r\n\"\"\"\r\n\r\n\r\nclass EditingMiddleware:\r\n def process_request(self, request):\r\n request.stop_editing = False\r\n request.continue_editing = False\r\n editing = request.GET.get(\"editing\",None)\r\n if editing is not None:\r\n editing = int(editing)\r\n if editing:\r\n request.session[\"editing\"] = path = request.path\r\n else:\r\n request.session[\"editing\"] = path = None\r\n \r\n def process_response(self, request, response):\r\n try:\r\n if request.stop_editing and not request.continue_editing:\r\n request.session[\"editing\"] = None\r\n except AttributeError,e:\r\n pass\r\n return response\r\n \r\n\"\"\" \r\n[23/Apr/2009 09:48:36] \"GET / HTTP/1.1\" 200 4620\r\nTraceback (most recent call last):\r\n File \"l:\\snapshot\\django\\django\\core\\servers\\basehttp.py\", line 278, in run\r\n self.result = application(self.environ, self.start_response)\r\n File \"l:\\snapshot\\django\\django\\core\\servers\\basehttp.py\", line 635, in __call__\r\n return self.application(environ, start_response)\r\n File \"l:\\snapshot\\django\\django\\core\\handlers\\wsgi.py\", line 245, in __call__\r\n response = middleware_method(request, response)\r\n File \"c:\\drives\\t\\svnwork\\lino\\trunk\\src\\lino\\django\\utils\\editing.py\", line 61, in process_response\r\n if request.stop_editing and not request.continue_editing:\r\nAttributeError: 'WSGIRequest' object has no attribute 'stop_editing' \r\n\"\"\" \r\n\r\ndef is_editing(request):\r\n path = request.session.get(\"editing\",None)\r\n return request.path == path\r\n\r\ndef stop_editing(request):\r\n request.stop_editing = True\r\n #request.session[\"editing\"] = None\r\n\r\ndef continue_editing(request):\r\n request.continue_editing = True\r\n \r\n#~ def start_editing(request):\r\n #~ request.session[\"editing\"] = request.path\r\n \r\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2009,"string":"2,009"}}},{"rowIdx":40066,"cells":{"__id__":{"kind":"number","value":17678085408666,"string":"17,678,085,408,666"},"blob_id":{"kind":"string","value":"18533532d86e007179c3e6b45f34335db08da7d7"},"directory_id":{"kind":"string","value":"1a98690ce4db4d4411adcb2eedc43bd8870b5b2d"},"path":{"kind":"string","value":"/utils.py"},"content_id":{"kind":"string","value":"4f0e15f3844698b5ce703a516607e65dfc77673e"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"chirayuk/playswith.angularjs"},"repo_url":{"kind":"string","value":"https://github.com/chirayuk/playswith.angularjs"},"snapshot_id":{"kind":"string","value":"cda6ab8fa69f574a79099fc10af8845e478ca8c8"},"revision_id":{"kind":"string","value":"47c4da1748127fe5f5da528ce80fec4ad17ddd4c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-06-02T04:05:55.755789","string":"2020-06-02T04:05:55.755789"},"revision_date":{"kind":"timestamp","value":"2013-05-06T17:16:42","string":"2013-05-06T17:16:42"},"committer_date":{"kind":"timestamp","value":"2013-05-06T17:16:42","string":"2013-05-06T17:16:42"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- coding: UTF-8 -*-\n\nimport logging\nlogger = logging.getLogger(__name__)\nimport functools\nimport traceback\n\ndef log_exceptions(fn):\n def wrapped_fn(*args, **kwargs):\n try:\n return fn(*args, **kwargs)\n except Exception as e:\n logging.error(traceback.format_exc())\n raise\n return functools.update_wrapper(wrapped_fn, fn)\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":40067,"cells":{"__id__":{"kind":"number","value":1932735290215,"string":"1,932,735,290,215"},"blob_id":{"kind":"string","value":"2d71b9798554dd97f28ab29c502c4890a09cbc55"},"directory_id":{"kind":"string","value":"b4147e9bcc5d74f5b91b5026ecb3e7433f56167c"},"path":{"kind":"string","value":"/esquipulaspy/utility/treefilterproxymodel.py"},"content_id":{"kind":"string","value":"5afab8857759d0793ddfc7912bb40bf590c0b14a"},"detected_licenses":{"kind":"list like","value":["GPL-3.0-only"],"string":"[\n \"GPL-3.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"armonge/EsquipulasPy"},"repo_url":{"kind":"string","value":"https://github.com/armonge/EsquipulasPy"},"snapshot_id":{"kind":"string","value":"7f5590736bbaa1a41e307842bd8c874b37bc5d88"},"revision_id":{"kind":"string","value":"85e1afd160cabe28c1f7f38e9d51595c3af4b562"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-01T17:47:46.447503","string":"2021-01-01T17:47:46.447503"},"revision_date":{"kind":"timestamp","value":"2011-06-15T23:05:38","string":"2011-06-15T23:05:38"},"committer_date":{"kind":"timestamp","value":"2011-06-15T23:05:38","string":"2011-06-15T23:05:38"},"github_id":{"kind":"number","value":4652867,"string":"4,652,867"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# \n# Copyright 2010 Andrés Reyes Monge \n# \n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA.\n\nfrom PyQt4.QtGui import QSortFilterProxyModel\nclass TreeFilterProxyModel( QSortFilterProxyModel ):\n \"\"\"\n Model used to filter a tree model\n \"\"\"\n #FIXME: Funciona pero es endemoniadamente lento\n def __init__( self, parent = None ):\n super( TreeFilterProxyModel, self ).__init__( parent )\n self.__showAllChildren = False\n\n def showAllChildren( self ):\n return self.__showAllChildren\n\n def setShowAllChildren( self, showAllChildren ):\n if showAllChildren == self.__showAllChildren:\n return\n self.__showAllChildren = showAllChildren\n self.invalidateFilter()\n\n def filterAcceptsRow ( self, source_row, source_parent ):\n if self.filterRegExp() == \"\" :\n return True #Shortcut for common case\n\n if super( TreeFilterProxyModel, self ).filterAcceptsRow( source_row, source_parent ) :\n return True\n\n #one of our children might be accepted, so accept this row if one of our children are accepted.\n source_index = self.sourceModel().index( source_row, 0, source_parent )\n for i in range( self.sourceModel().rowCount( source_index ) ):\n if self.filterAcceptsRow( i, source_index ):\n return True\n\n return False\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2011,"string":"2,011"}}},{"rowIdx":40068,"cells":{"__id__":{"kind":"number","value":3925600117266,"string":"3,925,600,117,266"},"blob_id":{"kind":"string","value":"1b6aafbe3e2a2a9a9521819aa54c32bfb4a953dd"},"directory_id":{"kind":"string","value":"2f3c6bcf4f36dadee604b1b2fa0237910ab02d69"},"path":{"kind":"string","value":"/RiotCrew/Profiling/templatetags/Arcee_tags.py"},"content_id":{"kind":"string","value":"0f7563d58429cad94eb5e1ebafb3e2fdf9990f29"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"first-team-58/Arcee"},"repo_url":{"kind":"string","value":"https://github.com/first-team-58/Arcee"},"snapshot_id":{"kind":"string","value":"35f596bfa8d04bd0f4329fe4865156de14117d7f"},"revision_id":{"kind":"string","value":"e3a77e1308a1bb0586680ede3060f6b2a8625ff0"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-10T13:26:11.235983","string":"2020-04-10T13:26:11.235983"},"revision_date":{"kind":"timestamp","value":"2013-03-08T13:44:40","string":"2013-03-08T13:44:40"},"committer_date":{"kind":"timestamp","value":"2013-03-08T13:44:40","string":"2013-03-08T13:44:40"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from django import template\r\n\r\n'''\r\nArcee_tags: Extra tags to implement commonly used template patterns.\r\n\r\nBased on examples ant techniques found at:\r\nhttp://docs.djangoproject.com/en/1.2/howto/custom-template-tags\r\n'''\r\n\r\nregister = template.Library()\r\n\r\n@register.inclusion_tag('snippits/buttons.html')\r\ndef form_save_buttons (root_link = None):\r\n '''\r\n Include the standard 'Save and Continue', 'Save and Quit', and 'Quit' \r\n buttons.\r\n \r\n Uses Template: 'snippits/buttons.html\r\n \r\n Tag Definition: {% form_save_buttons %}\r\n Example: {% form_save_buttons %}\r\n '''\r\n return {'root_link': root_link}\r\n\r\n@register.inclusion_tag('snippits/messages.html')\r\ndef show_messages (messages, errors = False):\r\n '''\r\n Format a list of messages for display in web forms.\r\n \r\n Uses Template: 'snippits/messages.html'\r\n \r\n Tag Parameters:\r\n errors: 'true' if messages are errors else 'false' (default: 'false')\r\n \r\n Tag Definition: {% show_messages messages [errors='false'] %}\r\n Example: {% show_messages form_validation_errors 'true' %}\r\n '''\r\n return {\r\n 'messages': messages,\r\n 'errors': errors,\r\n }\r\n \r\n@register.inclusion_tag('snippits/show_field.html')\r\ndef show_field (field, extra_class = None, width = None):\r\n '''\r\n Format a form field in a standard way\r\n \r\n Uses Template: 'snippits/show_field.html'\r\n \r\n Tag Parameters:\r\n field: a form field to format\r\n css_class: a string with extra css classes\r\n width: a string with a valid CSS length\r\n \r\n Tag Definition: {% show_field field [css_class='' [width=auto]] %}\r\n Example: {% show_field form.notes 'half_height' '35em' %}\r\n '''\r\n return {\r\n 'field': field,\r\n 'extra_class': extra_class,\r\n 'width': width,\r\n }\r\n\r\n@register.simple_tag\t\r\ndef spacer (width=1.2):\r\n '''\r\n Insert a horizontal spacer into the template.\r\n \r\n Uses Template: None\r\n \r\n Tag Parameters:\r\n width: a length measurment in em\r\n \r\n Tag Definition: {% spacer [width=1.2] %}\r\n Example: {% spacer 4 %}{# 4em horizontal spacer #}\r\n '''\r\n return '
' % width\r\n\r\n@register.simple_tag\t\r\ndef vspacer (height=1.2):\r\n '''\r\n Insert a vertical spacer into the template.\r\n \r\n Uses Template: None\r\n \r\n Tag Parameters: \r\n width: a length measurement in em\r\n \r\n Tag Definition: {% vspacer [width=1.2] %}\r\n Example: {% vspacer 0.5 %} {# 0.5em vertical spacer #}\r\n '''\r\n return '
' % height\r\n\r\n@register.tag\r\ndef content (parser, token):\r\n '''\r\n Wrap content to provide consistent styling.\r\n \r\n Uses Template: 'snippits/content.html'\r\n \r\n Tag Patameters:\r\n state: 'default' or 'error' or 'highlight' or 'background' or 'blank'\r\n width: a length measurement in em\r\n height: a length measurement in em\r\n \r\n Tag Definition; {% content [state='' [width=auto [height=auto]]] %}{% endcontent %}\r\n Example: {% content 'highlight' %}{{ messages }}{% endcontent %}\r\n '''\r\n tokens = token.split_contents()\r\n if len(tokens) > 4:\r\n raise template.TemplateSyntaxError, '%r tag takes at most two arguments'% tokens[0]\r\n state = None\r\n height = None\r\n width = None\r\n if len(tokens) > 1:\r\n state = tokens[1]\r\n if len(tokens) > 2:\r\n width = tokens[2]\r\n if len(tokens) > 3:\r\n height = tokens[3]\r\n nodelist = parser.parse(('endcontent',))\r\n parser.delete_first_token()\r\n \r\n if state and state[0] == state[-1] and state[0] in ('\"', \"'\"):\r\n state = state[1:-1]\r\n if width and width[0] == width[-1] and width[0] in ('\"', \"'\"):\r\n width = width[1:-1]\r\n if height and height[0] == height[-1] and height[0] in ('\"', \"'\"):\r\n height = height[1:-1]\r\n return TemplateNode('snippits/content.html', nodelist, {\r\n 'state': state,\r\n 'width': width, \r\n 'height': height,\r\n })\r\n \r\n@register.tag\r\ndef header (parser, token):\r\n '''\r\n Wrap content and style as a header.\r\n \r\n Uses Template: 'snippits/header.html'\r\n \r\n Tag Parameters: \r\n root_link: 'on' to display the home link, 'off' to hide\r\n \r\n Tag Definition: {% header [root_link='on'] %}{% endheader #}\r\n Example: {% header %}{{ header_content }}{% endheader %}\r\n '''\r\n tokens = token.split_contents()\r\n root_link = True\r\n if len(tokens) > 2:\r\n raise template.TemplateSyntaxError, '%r tag takes at most one argument'% tokens[0]\r\n if len(tokens) > 1:\r\n if tokens[1] in ('\"off\"', \"'off'\"):\r\n root_link = False\r\n nodelist = parser.parse(('endheader',))\r\n parser.delete_first_token()\r\n return TemplateNode('snippits/header.html', nodelist, {'root_link': root_link})\r\n\r\n@register.tag\r\ndef section (parser, token):\r\n '''\r\n Wrap content and style as a section with section title.\r\n \r\n Uses Template: 'snippits/section.html'\r\n \r\n Tag Parameters: \r\n title: a string that is the section title\r\n \r\n Tag Definition: {% section title %}{% endsection #}\r\n Example: {% section 'Section Title' %}{{ content }}{% endsection %}\r\n '''\r\n try:\r\n tag, title = token.split_contents()\r\n except ValueError:\r\n raise template.TemplateSyntaxError, '%r tag requires a title' % tag\r\n nodelist = parser.parse(('endsection',))\r\n parser.delete_first_token()\r\n \r\n if title[0] == title[-1] and title[0] in ('\"', \"'\"):\r\n title = title[1:-1]\r\n return TemplateNode('snippits/section.html', nodelist, {'section_title': title})\r\n \r\n@register.tag\r\ndef data (parser, token):\r\n '''\r\n Wrap content and style as read-only data with an optional title.\r\n \r\n Uses Template: 'snippits/show_data.html'\r\n \r\n Tag Parameters: \r\n title: a string that is the data title\r\n \r\n Tag Definition: {% data [title=''] %}{% enddata #}\r\n Example: {% data 'Some Awesome Data' %}{{ data }}{% enddata %}\r\n '''\r\n tokens = token.split_contents()\r\n title = None\r\n width = '33%'\r\n if len(tokens) > 1:\r\n title = tokens[1]\r\n if len(tokens) > 2:\r\n width = tokens[2]\r\n if len(tokens) > 3:\r\n raise template.TemplateSyntaxError, '%r tag takes at most two arguments'% tokens[0]\r\n nodelist = parser.parse(('enddata',))\r\n parser.delete_first_token()\r\n \r\n if title and title[0] == title[-1] and title[0] in ('\"', \"'\"):\r\n title = title[1:-1]\r\n if width and width[0] == width[-1] and width[0] in ('\"', \"'\"):\r\n width = width[1:-1]\r\n \r\n return TemplateNode('snippits/show_data.html', nodelist, {\r\n 'data_title': title,\r\n 'width': width\r\n })\r\n \r\nclass TemplateNode (template.Node):\r\n '''\r\n Renders templates for the following tag types: data, section, header and content\r\n '''\r\n def __init__ (self, template, nodelist= None, context=None):\r\n self.template = template\r\n self.nodelist = nodelist\r\n self.context = context if context else {}\r\n \r\n def render(self, context):\r\n t = template.loader.get_template(self.template)\r\n ctx = self.context\r\n if self.nodelist:\r\n contents = self.nodelist.render(context)\r\n ctx['contents'] = contents\r\n return t.render(template.Context(ctx, autoescape = context.autoescape))"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":40069,"cells":{"__id__":{"kind":"number","value":7670811614480,"string":"7,670,811,614,480"},"blob_id":{"kind":"string","value":"53bbacd84045397f875edef171f0f488ebce2b53"},"directory_id":{"kind":"string","value":"2b2e37432ba07ea3a20aaa22158edcc4ae9924f0"},"path":{"kind":"string","value":"/blotter/tests/core/aggregation/client/test_gplus.py"},"content_id":{"kind":"string","value":"4cde547c049942449600438930ac0a7d630decad"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"tylertreat/TrendBlotter"},"repo_url":{"kind":"string","value":"https://github.com/tylertreat/TrendBlotter"},"snapshot_id":{"kind":"string","value":"ee9473f1ac14147702222fa0388c2eb4fa3b7232"},"revision_id":{"kind":"string","value":"d28101ca0d2828cdfba0c59a931367eb7aeec737"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-06T18:25:19.981068","string":"2020-04-06T18:25:19.981068"},"revision_date":{"kind":"timestamp","value":"2014-02-15T05:58:49","string":"2014-02-15T05:58:49"},"committer_date":{"kind":"timestamp","value":"2014-02-15T05:58:49","string":"2014-02-15T05:58:49"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import unittest\n\nfrom mock import Mock\nfrom mock import patch\nfrom mock import PropertyMock\n\nfrom blotter.core.aggregation.client.gplus import get_trends_by_location\n\n\n@patch('blotter.core.aggregation.client.gplus.urllib2.urlopen')\nclass TestGetTrendsByLocation(unittest.TestCase):\n\n def test_happy_path(self, mock_urlopen):\n \"\"\"Verify get_trends_by_location retrieves the top 10 trends from\n Google+.\n \"\"\"\n\n mock_urlopen.return_value.read.return_value = \\\n \"\"\"#HappyBirthdayViru
  • Red Sox
  • Facebook
  • #Epic
    • New Delhi
    Drone attacks in Pakistan
  • #FallColors
  • #Moon\"\"\"\n\n location = Mock()\n type(location).name = PropertyMock(return_value='Worldwide')\n\n actual = get_trends_by_location(location)\n\n self.assertEqual([('#Moon', 1), ('Taylor Swift', 2),\n ('#FallColors', 3), ('Drone attacks in Pakistan', 4),\n ('New Delhi', 5), ('#Halloween2013', 6),\n ('#Epic', 7), ('Facebook', 8), ('Red Sox', 9),\n ('#HappyBirthdayViru', 10)], actual)\n\n mock_urlopen.assert_called_once_with('https://plus.google.com/s/a')\n\n def test_request_failure(self, mock_urlopen):\n \"\"\"Verify get_trends_by_location returns an empty list when the HTTP\n request fails.\n \"\"\"\n\n def side_effect(url):\n import urllib2\n raise urllib2.URLError('Oh snap')\n\n mock_urlopen.side_effect = side_effect\n\n location = Mock()\n type(location).name = PropertyMock(return_value='Worldwide')\n\n actual = get_trends_by_location(location)\n\n self.assertEqual([], actual)\n mock_urlopen.assert_called_once_with('https://plus.google.com/s/a')\n\n def test_non_worldwide(self, mock_urlopen):\n \"\"\"Verify get_trends_by_location returns an empty list for\n non-worldwide locations.\n \"\"\"\n\n location = Mock()\n type(location).name = PropertyMock(return_value='United States')\n\n self.assertEqual([], get_trends_by_location(location))\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":40070,"cells":{"__id__":{"kind":"number","value":6038724048983,"string":"6,038,724,048,983"},"blob_id":{"kind":"string","value":"2432256be0a0c94541b615301f90baa2fc1e4915"},"directory_id":{"kind":"string","value":"8678bd1d7a1b0879a66bbef03c4edb0d2a8ea3b1"},"path":{"kind":"string","value":"/runserver.py"},"content_id":{"kind":"string","value":"8b68c966c871903f312d1756e3c2f7c23497a999"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"kolobus/jasta"},"repo_url":{"kind":"string","value":"https://github.com/kolobus/jasta"},"snapshot_id":{"kind":"string","value":"e6bea35e253989266e0bdf42ad1d7db5f2b0187b"},"revision_id":{"kind":"string","value":"c40a39e4e3461e3f2359ac878c3484ef105a5888"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-13T09:12:14.725704","string":"2021-01-13T09:12:14.725704"},"revision_date":{"kind":"timestamp","value":"2013-12-03T19:30:21","string":"2013-12-03T19:30:21"},"committer_date":{"kind":"timestamp","value":"2013-12-03T19:30:21","string":"2013-12-03T19:30:21"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n\"\"\"\nRun development server\n\"\"\"\nimport base64\nimport json\n\nfrom bottle import route, view, run, response\nfrom redis import Redis\n\nfrom bot.config import *\n\ndef get_status(jid):\n presence = Redis().hgetall('presence:%s' % jid) or {}\n m = presence.get('status') or ''\n s = presence.get('show') or ''\n return dict(r=presence and 1 or 0, m=m.decode('utf8'), s=s.decode('utf8'))\n\n@route('/.b64.json')\ndef status_b64_json(b64_jid):\n jid = base64.b64decode(b64_jid)\n data = get_status(jid)\n response.content_type = 'application/json'\n return json.dumps(data, ensure_ascii=False)\n\n@route('/.json')\ndef status_json(jid):\n data = get_status(jid)\n response.content_type = 'application/json'\n return json.dumps(data, ensure_ascii=False)\n\n@route('/.txt')\ndef status_text(jid):\n result = get_status(jid)\n return u'%s|%s|%s|\\n' % (result['r'], result['s'], result['m'])\n\n@route('/.html')\n@view('index')\ndef status(jid):\n result = get_status(jid)\n result.update(jid=jid)\n return result\n\nif __name__ == '__main__':\n if DEBUG:\n run(host=\"localhost\", port=5000, debug=True)\n else:\n run(host=\"0.0.0.0\", port=80, debug=False, server='fapws3')\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":40071,"cells":{"__id__":{"kind":"number","value":5033701700897,"string":"5,033,701,700,897"},"blob_id":{"kind":"string","value":"be6b46553dd8572f7bafdd1df212ac4cb9736012"},"directory_id":{"kind":"string","value":"ef4d64ad741d5c282889ae35b634bfe90d480403"},"path":{"kind":"string","value":"/LOTlib/Evaluation/EvaluationException.py"},"content_id":{"kind":"string","value":"9e9575181338f3451e51fb649e56a1167872560f"},"detected_licenses":{"kind":"list like","value":["GPL-1.0-or-later","GPL-3.0-only"],"string":"[\n \"GPL-1.0-or-later\",\n \"GPL-3.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"sa-/LOTlib"},"repo_url":{"kind":"string","value":"https://github.com/sa-/LOTlib"},"snapshot_id":{"kind":"string","value":"d39c992113e97e0b21d3fdaf1eb496c5fbec608a"},"revision_id":{"kind":"string","value":"1a2b9ac7c59b14f2e65b03b01a093aca505f06db"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T23:36:39.154727","string":"2021-01-18T23:36:39.154727"},"revision_date":{"kind":"timestamp","value":"2014-08-29T19:31:27","string":"2014-08-29T19:31:27"},"committer_date":{"kind":"timestamp","value":"2014-08-29T19:31:27","string":"2014-08-29T19:31:27"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"\"\"\"\n The exception we throw for all problems in Evaluation\n\"\"\"\n\nclass EvaluationException(Exception):\n pass\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":40072,"cells":{"__id__":{"kind":"number","value":4002909551127,"string":"4,002,909,551,127"},"blob_id":{"kind":"string","value":"b468a48610937aa34493c96f9f783e0a494f83c9"},"directory_id":{"kind":"string","value":"134dcdfe5a2a0ed80d5d365bff793393a017143e"},"path":{"kind":"string","value":"/src/equ/equ/equ_common/views.py"},"content_id":{"kind":"string","value":"fc7ebc4d5d82cff605c7a6aac73a4e088d0e7170"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"nebalceroc/eq"},"repo_url":{"kind":"string","value":"https://github.com/nebalceroc/eq"},"snapshot_id":{"kind":"string","value":"c895b2f59abec7b356fea13572dc8f66011c1f44"},"revision_id":{"kind":"string","value":"215428f898838d69ec4dc0422c075bc1cf82caa1"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-01T04:08:47.463301","string":"2021-01-01T04:08:47.463301"},"revision_date":{"kind":"timestamp","value":"2014-10-13T23:09:34","string":"2014-10-13T23:09:34"},"committer_date":{"kind":"timestamp","value":"2014-10-13T23:09:34","string":"2014-10-13T23:09:34"},"github_id":{"kind":"number","value":97130399,"string":"97,130,399"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- \nfrom django.contrib.gis.geos import GEOSGeometry\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required \nfrom django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom datetime import date\nfrom equ_common.models import UserProfile, ImageArticle, Article, Category, Trade, TradeOffererArticle\nfrom equ_common.forms import Article_New\nfrom equ_common.services import get_article_dictionary\nfrom userena.decorators import secure_required\nfrom userena.forms import SignupFormOnlyEmail, AuthenticationForm\nfrom helpers import init_categories\nimport datetime\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.gis.geoip import GeoIP\n\n\"\"\"\nThis view return the call to index,html\n\"\"\"\ndef Home(request):\n if len(Category.objects.all()) == 0:\n init_categories()\n diccionary = dict()\n images = dict()\n consult = Article.objects.order_by('id').reverse()[:4]\n for img in consult:\n try:\n im = str(ImageArticle.objects.filter(key_article=img)[0].image)\n except:\n im = str()\n images[str(img.id)] = [im, str(img.name.encode('utf-8'))]\n diccionary['images'] = images\n diccionary['categories'] = Category.objects.exclude(subcategories=None)\n if request.user.is_authenticated():\n seller = UserProfile.objects.filter(user=request.user)[0]\n diccionary['recent_articles'] = Article.objects.filter(date__range=(datetime.datetime.now()+datetime.timedelta(-15),datetime.datetime.now())).exclude(seller=seller)[:4]\n else:\n diccionary['recent_articles'] = Article.objects.filter(date__range=(datetime.datetime.now()+datetime.timedelta(-15),datetime.datetime.now()))[:4]\n if request.user.is_authenticated():\n diccionary['pending_requests'] = list(set(get_pending_requests(request)))\n diccionary['user_items'] = get_items(request)\n return render(request,'index.html',diccionary)\n\n\"\"\"\nThis view return a form of register \n\"\"\"\n@secure_required\ndef RegisterUser(request):\n auth_basic_form = SignupFormOnlyEmail()\n if request.method == 'POST':\n user_form = SignupFormOnlyEmail(request.POST)\n \n if user_form.is_valid():\n try:\n user = User.objects.get(email__iexact=request.POST['email']) \n except Exception as e:\n if 'does not exist' in str(e):\n user=user_form.save()\n user_auth = authenticate(identification=user.email, check_password=False)\n if user_auth is not None:\n login(request,user_auth)\n x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n if x_forwarded_for:\n ip = x_forwarded_for.split(',')[0]\n else:\n ip = request.META.get('REMOTE_ADDR')\n \n g = GeoIP()\n lat,lon = g.lat_lon(ip)\n #lat,lon = g.lat_lon('186.83.0.68')\n UserProfile.objects.filter(user=user).update(coords = 'POINT(' + str(lon) +' ' +str(lat)+ ')')\n request.session['register'] = True\n return redirect(\"/change_user/\")\n else:\n login_form = AuthenticationForm()\n diccionary = {'messageReg':'User already exists', 'login':login_form, 'auth_basic':auth_basic_form, }\n return render(request,\"login.html\", diccionary)\n else:\n login_form = AuthenticationForm()\n diccionary = {'messageReg':'User already exists', 'login':login_form, 'auth_basic':auth_basic_form, }\n return render(request,\"login.html\", diccionary)\n else:\n message = 'Invalid data. Please use different information to register'\n if 'email' in user_form.errors:\n message = user_form.errors['email']\n login_form = AuthenticationForm()\n login_form.fields['identification'].label = 'Email'\n diccionary = {'messageReg':message, 'login':login_form, 'auth_basic':auth_basic_form, }\n return render(request,\"login.html\", diccionary)\n else:\n return redirect(\"/login/\")\n\"\"\"\nThis function return the template for do the login user\n\"\"\"\ndef LoginUser(request):\n url_redirect = request.GET.get(\"next\", \"/\")\n auth_basic_form = SignupFormOnlyEmail()\n if request.method == 'POST':\n login_form = AuthenticationForm(request.POST)\n login_form.fields['identification'].label = 'Email'\n if login_form.is_valid():\n username = request.POST['identification']\n password = request.POST['password']\n user = authenticate(identification=username, password=password)\n if user is not None:\n login(request,user)\n x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n if x_forwarded_for:\n ip = x_forwarded_for.split(',')[0]\n else:\n ip = request.META.get('REMOTE_ADDR')\n \n g = GeoIP()\n lat,lon = g.lat_lon(ip)\n #lat,lon = g.lat_lon('186.83.0.68')\n UserProfile.objects.filter(user=user).update(coords = 'POINT(' + str(lon) +' ' +str(lat)+ ')')\n return redirect(url_redirect)\n else:\n diccionary = {'message':'Invalid information', 'login':login_form, 'auth_basic':auth_basic_form, }\n else:\n diccionary = {'message':'Invalid information', 'login':login_form, 'auth_basic':auth_basic_form, }\n else:\n login_form = AuthenticationForm()\n login_form.fields['identification'].label = 'Email'\n diccionary = {'login':login_form, 'auth_basic':auth_basic_form, }\n if 'message' in request.session:\n diccionary['message'] = request.session['message']\n del request.session['message']\n return render(request,'login.html',diccionary)\n\n\"\"\"\nThis function do logout of an user\n\"\"\"\ndef Logout_User(request):\n print UserProfile.objects.get(user=request.user).coords\n logout(request)\n return redirect('/')\n\n\"\"\"\nThis function do up of an article of an user, the user must be logged\n\"\"\"\n@login_required(login_url='/login/')\ndef ArticleUp(request):\n msg = str()\n if request.method == 'POST':\n article_form = Article_New(request.POST)\n categories_arr = request.POST['item_categories'].split(',')\n if len(categories_arr) > 0 and len(request.FILES) > 0 and article_form.is_valid():\n user = UserProfile.objects.filter(user_id=request.user.id)[0]\n article = Article.objects.create(name=request.POST['name'], description=request.POST['description'], price=request.POST['price'], seller=user, date=datetime.datetime.now())\n #article = Article.objects.create(name=request.POST['name'], description=user.coords, price=request.POST['price'], seller=user, date=datetime.datetime.now())\n for i in range(len(request.FILES)):\n image = ImageArticle.objects.create(key_article=article, image=request.FILES['imgup-{0}'.format(i)])\n article.imagearticle_set.add(image)\n for cat in categories_arr:\n if cat != str():\n category = Category.objects.get(id=cat)\n article.category.add(category)\n request.session['message'] = 'You have added a new article to your account. View article'.format(reverse('product_detail', kwargs={ 'num':article.id }))\n return redirect('your_items')\n else:\n msg = 'Please complete the form.'\n else:\n article_form = Article_New()\n diccionary = {'article_form': article_form, 'message': msg, 'mod':False,}\n diccionary['categories'] = Category.objects.exclude(subcategories=None)\n diccionary['pending_requests'] = list(set(get_pending_requests(request)))\n if diccionary['message'] == str():\n del diccionary['message']\n return render(request, 'listing_item_description.html', diccionary)\n\n\"\"\"\nThis function modify the informaction of an article\n\"\"\"\n@secure_required\n@login_required(login_url='/login/')\ndef Article_Mod(request, id_article):\n article = Article.objects.get(id=id_article)\n message = str()\n if request.method == 'GET': \n data = { 'modify':True, 'article_id':article.id,'article_form':Article_New(article.__dict__), 'categories':Category.objects.exclude(subcategories=None), 'article_categories':article.category.all, 'article_images':article.imagearticle_set.all }\n data['pending_requests'] = list(set(get_pending_requests(request)))\n return render(request, 'listing_item_description.html', data)\n elif request.method == 'POST':\n article.name = request.POST['name']\n article.price = request.POST['price']\n article.description = request.POST['description']\n article.save()\n images = json.loads(request.POST['item_images'])\n for img in images:\n if not img['url'].startswith(settings.MEDIA_URL):\n article.imagearticle_set.add(ImageArticle.objects.create(key_article=article, image=request.FILES[img['name']]))\n article.category.clear()\n for cat in request.POST['item_categories'].split(','):\n category = Category.objects.get(id=cat)\n article.category.add(category)\n message = 'Article {0} modified successfully.'.format(article.name.encode('utf-8'))\n if message != str():\n request.session['message'] = message\n return redirect('your_items')\n\n\"\"\"\nThis function delete an article\n\"\"\"\n@secure_required\n@login_required(login_url='/login/')\ndef Delete_Article(request, id_art):\n article = Article.objects.get(id=id_art)\n article.delete()\n return redirect('your_items')\n\n\"\"\"\nThis view print the list of articles contained in the table of Article\n\"\"\"\ndef Listing_Article(request):\n consult = Article.objects.all()\n #This dictionary of images:\n dic_images = {}\n for field in consult:\n dic_images[field.name] = str(ImageArticle.objects.get(id=field.id).image)\n #This attributte \n article_print = {}\n for field in consult:\n article_print[field.name] = [field.id, field.description, field.price, field.quantity]\n diccionary = {'article_print': article_print, 'image': dic_images}\n return render(request, 'lista_productos.html', diccionary)\n\n\"\"\"\nThis view print the information of an article\n\"\"\"\ndef Product_Detail(request, num):\n diccionary = dict() # It is a dictionary that send all information to template\n if request.method == 'GET':\n diccionary['article'] = Article.objects.get(id=num)\n if request.user.is_authenticated():\n user = UserProfile.objects.filter(user=request.user)[0]\n diccionary['user_items'] = Article.objects.filter(seller=user)\n if request.user.is_authenticated():\n seller = UserProfile.objects.filter(user=request.user)[0]\n diccionary['recent_articles'] = Article.objects.filter(date__range=(datetime.datetime.now()+datetime.timedelta(-15),datetime.datetime.now())).exclude(seller=seller)[:4]\n else:\n diccionary['recent_articles'] = Article.objects.filter(date__range=(datetime.datetime.now()+datetime.timedelta(-15),datetime.datetime.now()))[:4]\n if request.user.is_authenticated():\n diccionary['pending_requests'] = list(set(get_pending_requests(request)))\n if 'error' in request.session:\n diccionary['error'] = request.session['error']\n return render(request,'detalle_productos.html', diccionary)\n\n\"\"\"\nThis function change the information of an user\n\"\"\"\n@secure_required\n@login_required(login_url='/login/')\ndef Profile_Change(request):\n active_user = UserProfile.objects.filter(user_id=request.user.id)[0]\n\n diccionary = { 'msg':str() }\n if request.method == 'POST':\n form_pass = UserProfileForm(request.POST, request.FILES)\n if 'register' in request.POST:\n form_pass.fields['terms'].required = True\n \n if form_pass.is_valid():\n if 'password' in request.POST:\n if 'confirm_password' in request.POST:\n if request.POST['password'] == request.POST['confirm_password']:\n active_user.user.password = request.POST['password']\n else:\n diccionary['msg'] = 'Passwords don\\'t match'\n if diccionary['msg'] == str():\n active_user.user.email = request.POST['email']\n active_user.celular = request.POST['mobile']\n active_user.city = request.POST['city']\n active_user.user.first_name = request.POST['first_name']\n active_user.user.last_name = request.POST['last_name']\n if 'password' in request.POST:\n if 'confirm_password' in request.POST:\n active_user.user.password = request.POST['password']\n\n active_user.user.save()\n \n if 'terms' in request.POST:\n active_user.terms = request.POST['terms']\n categories = request.POST['user_categories'].split(',')\n if len(categories) > 0:\n for user_cat in active_user.categories.all():\n if user_cat.id not in categories:\n active_user.categories.remove(user_cat)\n for cat in categories:\n if cat != str():\n category = Category.objects.get(id=cat)\n active_user.categories.add(category)\n else:\n diccionary['msg'] = 'Select at least one category'\n active_user.save()\n try:\n if 'register' in request.session:\n del request.session['register']\n if 'image' in request.FILES:\n active_user.image = request.FILES['image']\n active_user.save()\n except:\n pass\n return redirect('home')\n else:\n diccionary['msg'] = 'Invalid data. Please fill all the fields of the form'\n form_data = dict()\n form_data['first_name'] = active_user.user.first_name\n form_data['last_name'] = active_user.user.last_name\n form_data['email'] = active_user.user.email\n form_data['mobile'] = active_user.celular\n form_data['city'] = active_user.city\n form_data['image'] = active_user.image\n form_pass = UserProfileForm(form_data, initial={ 'image':active_user.image })\n diccionary['form'] = form_pass\n diccionary['terms'] = active_user.terms\n diccionary['register'] = 'register' in request.session\n diccionary['image'] = active_user.image\n diccionary['user_categories'] = Category.objects.filter(userprofile=active_user)\n diccionary['categories'] = Category.objects.exclude(subcategories=None)\n diccionary['pending_requests'] = list(set(get_pending_requests(request)))\n if diccionary['msg'] == str():\n del diccionary['msg']\n return render(request,'change_profile.html', diccionary)\n\n\"\"\"\nThis function list the items of an user\n\"\"\"\n@secure_required\n@login_required(login_url=\"/login/\")\ndef Your_Items(request):\n user_profile = UserProfile.objects.filter(user=request.user)[0]\n dictionary = { 'articles':Article.objects.filter(seller_id=user_profile.id) }\n dictionary['categories'] = Category.objects.exclude(subcategories=None)\n dictionary['pending_requests'] = list(set(get_pending_requests(request)))\n if 'message' in request.session:\n dictionary['message'] = request.session['message']\n del request.session['message']\n return render(request,'your_items.html',dictionary)\n\n\"\"\"\nThis function search and make the pagination in the web site\n\"\"\"\ndef Busqueda(request):\n search = request.GET['q']\n articles = list()\n article_dictionary = []\n if request.user.is_authenticated():\n seller = UserProfile.objects.filter(user=request.user)\n articles.extend(list(Article.objects.filter(name__icontains=search).exclude(seller=seller)))\n articles.extend(list(Article.objects.filter(description__icontains=search).exclude(seller=seller)))\n else:\n articles.extend(list(Article.objects.filter(name__icontains=search)))\n articles.extend(list(Article.objects.filter(description__icontains=search)))\n categories = Category.objects.filter(name_category__icontains=search)\n \n for cat in categories:\n if request.user.is_authenticated():\n seller = UserProfile.objects.filter(user=request.user)\n articles.extend(list(Article.objects.filter(category=cat).exclude(seller=seller)))\n else:\n articles.extend(list(Article.objects.filter(category=cat)))\n \n\n for article in list(set(articles)):\n if request.user.is_authenticated():\n article_dictionary.append(get_article_dictionary(article,request.user.userprofile.coords.distance(article.seller.coords)))\n else:\n article_dictionary.append(get_article_dictionary(article,0))\n\n \n\n #data = { 'articles':list(set(articles)) }\n data = { 'articles':article_dictionary }\n data['pending_requests'] = Trade.objects.filter(state='Pending')\n if request.user.is_authenticated():\n data['user_items'] = get_items(request)\n data['categories'] = Category.objects.exclude(subcategories=None)\n if 'message' in request.session:\n data['message'] = request.session['message']\n del request.session['message']\n elif 'error' in request.session:\n data['error'] = request.session['error']\n del request.session['error']\n return render(request, 'search/search.html', data)\n\n\n# Novcat's development\nfrom django.core.mail import EmailMultiAlternatives\nimport os, stripe, base64, json, hashlib\nfrom helpers import obfuscate, deobfuscate\nfrom forms import UserProfileForm, ForgotPasswordForm\nfrom models import Buy\n\n@secure_required\n@login_required(login_url='login')\ndef list_trades(request):\n user_profile = UserProfile.objects.filter(user_id=request.user.id)\n articles = Article.objects.filter(seller_id=user_profile[0].id)\n data = dict()\n trades = list()\n for article in articles:\n receipts = Trade.objects.filter(receiver_article_id=article.id)\n trades.extend(list(receipts))\n offerers = TradeOffererArticle.objects.filter(article_id=article.id)\n for offerer in offerers:\n trades.append(Trade.objects.get(id=offerer.offerer_article.id))\n data['trades'] = list(set(trades))\n data['accepted'] = int()\n data['declined'] = int()\n data['pending'] = int()\n for trade in data['trades']:\n if trade.state == 'Pending':\n data['pending'] = int(data['pending']) + 1\n elif trade.state == 'Accepted':\n data['accepted'] = int(data['accepted']) + 1\n else:\n data['declined'] = int(data['declined']) + 1\n data['pending_requests'] = list(set(get_pending_requests(request)))\n return render(request, 'list_trades.jade', data)\n\ndef get_pending_requests(request):\n user_profile = UserProfile.objects.filter(user_id=request.user.id)\n articles = Article.objects.filter(seller_id=user_profile[0].id)\n pending = list()\n for art in articles:\n art_trades = Trade.objects.filter(receiver_article=art)\n for trad in art_trades:\n if trad.state != 'Declined':\n pending.append(trad)\n art_trades = TradeOffererArticle.objects.filter(article=art)\n for trad in art_trades:\n if trad.offerer_article.state != 'Declined':\n pending.append(trad)\n return pending\n\n@secure_required\n@login_required(login_url='login')\ndef delete_trade(request, trade_id):\n Trade.objects.get(id=trade_id).delete()\n return redirect('list_trades')\n\n@secure_required\n@login_required(login_url='login')\ndef respond_trade(request):\n if request.method == 'POST':\n trade = Trade.objects.get(id=request.POST['trade'])\n trade.state = request.POST['response']\n trade.date = date.today()\n trade.save()\n message = str()\n if request.POST['response'] == 'Accepted':\n message = 'Congratulations, your trade for {0} has been accepted.\\n\\nPlease log in Equallo to access the contact\\'s information.\\n\\nRegards,\\n\\nThe Equallo team'.format(trade.receiver_article.name)\n message_file = '

    Congratulations, your trade for {0} has been accepted.

    Please log in Equallo to access the contact\\'s information.

    Regards,

    The Equallo team

    '.format(trade.receiver_article.name)\n else:\n message = 'We\\'re sorry, your trade for {0} has been declined. Maybe try another item?\\n\\nRegards,\\n\\nThe Equallo team'.format(trade.receiver_article.name)\n message_file = '

    We\\'re sorry, your trade for {0} has been declined. Maybe try another item?

    Regards,

    The Equallo team

    '.format(trade.receiver_article.name)\n \n message_html = open(r'/home/equallo/eq/src/equ/equ/equ_common/static/files/trade_email.html').read()\n #message_html = open(r'/home/nicolas/git/equ_project/equ_project/src/equ/equ/equ_common/static/files/trade_email.html').read()\n \n message_html = message_html.replace('{{message}}',message_file)\n email_offerer = EmailMultiAlternatives('Trade result', message, settings.DEFAULT_FROM_EMAIL, [trade.tradeoffererarticle_set.all()[0].article.seller.user.email])\n email_offerer.attach_alternative(message_html, 'text/html')\n email_offerer.send(fail_silently=False)\n email_receiver = EmailMultiAlternatives('Trade result', message, settings.DEFAULT_FROM_EMAIL, [request.user.email])\n email_receiver.attach_alternative(message_html, 'text/html')\n email_receiver.send(fail_silently=False)\n return redirect('list_trades')\n\ndef get_items(request):\n user = UserProfile.objects.filter(user_id=request.user.id)[0]\n return Article.objects.filter(seller=user)\n\n@secure_required\n@login_required(login_url='login')\ndef create_trade(request):\n previous = request.META.get('HTTP_REFERER')\n data = { 'error':str(), 'message':str() }\n if request.method == 'POST':\n if request.POST['user_articles']:\n receiver = Article.objects.get(id=request.POST['article_id'])\n trade = Trade.objects.create(date=datetime.datetime.now(), state='Pending', receiver_article=receiver)\n user_articles_id = request.POST['user_articles'].split(',')\n for art_id in user_articles_id:\n offer = TradeOffererArticle.objects.create(article=Article.objects.get(id=art_id), offerer_article=trade)\n trade.tradeoffererarticle_set.add(offer)\n message = 'Your item is wanted!\\n\\nYou have received a trade for {0}.\\n\\nPlease log in to Equallo to receive further information.\\n\\nRegards,\\n\\nThe Equallo team'.format(receiver.name)\n message_file = '

    Your item is wanted!

    You have received a trade for {0}.

    Please log in to Equallo to receive further information.

    Regards,

    The Equallo team

    '.format(receiver.name)\n \n message_html = open(r'/home/equallo/eq/src/equ/equ/equ_common/static/files/new_trade_email.html').read()\n #message_html = open(r'/home/nicolas/git/equ_project/equ_project/src/equ/equ/equ_common/static/files/new_trade_email.html').read()\n \n \n \n message_html = message_html.replace('{{message}}',message_file)\n email_receiver = EmailMultiAlternatives('New trade received', message, settings.DEFAULT_FROM_EMAIL, [receiver.seller.user.email])\n email_receiver.attach_alternative(message_html, 'text/html')\n email_receiver.send(fail_silently=False)\n request.session['message'] = 'Your trade has been sent.'\n return redirect('list_trades')\n else:\n data['error'] = 'You must offer at least one article.'\n if data['error'] != str():\n request.session['error'] = data['error']\n if data['message'] != str():\n request.session['message'] = data['message']\n return redirect(previous)\n\nif settings.DEBUG:\n stripe.api_key = 'sk_test_j6XEtAa3NiA6uugPHbtDpe6I'\nelse:\n stripe.api_key = 'sk_live_QzSgvbMu1S2jBs96VycxegcA'\n\n@secure_required\n@login_required(login_url='login')\ndef buy_article_information(request):\n previous = request.META.get('HTTP_REFERER')\n\n if request.method == 'POST':\n print request.POST\n\n token = request.POST['stripe_token']\n try:\n stripe.Charge.create(\n amount=199, # amount in cents, again\n currency=\"usd\",\n card=token,\n description=request.user.email\n )\n article = Article.objects.get(id=request.POST['article_id'])\n user = UserProfile.objects.filter(user=request.user)[0]\n buy = Buy.objects.create(buyer=user, article=article, date_buy=datetime.datetime.now())\n if 'trade_id' in request.POST:\n trade = Trade.objects.get(id=request.POST['trade_id'])\n trade.buy = buy\n trade.save()\n request.session['message'] = 'Congratulations! Your payment was approved. You\\'ll receive an email with the article\\'s information'\n \n message_html = open(r'/home/equallo/eq/src/equ/equ/equ_common/static/files/buy_email.html').read().decode('utf8')\n #message_html = open(r'/home/nicolas/git/equ_project/equ_project/src/equ/equ/equ_common/static/files/buy_email.html').read().decode('utf8')\n \n message_html = message_html.replace('{{first_name}}',article.seller.user.first_name.decode('cp437').encode('utf8')).replace('{{last_name}}',article.seller.user.last_name.decode('cp437').encode('utf8')).replace('{{city}}',article.seller.city).replace('{{mobile}}', str(article.seller.celular)).replace('{{email}}', article.seller.user.email.encode('utf8'))\n message_text = 'Congratulations!\\n\\nYou have just bought the following contact information:\\n\\nContact name: {0} {1}\\nContact location:{2}\\nContact mobile:{3}\\nContact email:{4}'.format(article.seller.user.first_name.decode().encode('utf8'), article.seller.user.last_name.decode().encode('utf8'), article.seller.city.decode().encode('utf8'), str(article.seller.celular), article.seller.user.email.encode('utf8'))\n send_email = EmailMultiAlternatives('Buy result', message_text, settings.DEFAULT_FROM_EMAIL, [user.user.email])\n send_email.attach_alternative(message_html, 'text/html')\n send_email.send(fail_silently=False)\n except stripe.CardError:\n request.session['error'] = 'We\\'re sorry, we couldn\\'t process your payment.'\n return redirect(previous)\n\ndef forgot_password(request, forgot_key=None):\n if request.method == 'POST':\n user = User.objects.filter(email=request.POST['email'])\n if len(user) > 0:\n email = user[0].email\n data = '{0}&{1}'.format(email, (datetime.datetime.now()+datetime.timedelta(hours=24)).strftime('%d-%m-%Y %H:%M:%S'))\n sha = hashlib.sha256()\n sha.update(data)\n hash_key = base64.b64encode(sha.digest())\n forgot_key = obfuscate('{0}#{1}'.format(data, hash_key))\n if settings.DEBUG:\n message = 'http://localhost:8000/forgot_password/{0}/'.format(forgot_key)\n else:\n message = 'http://www.equallo.com/forgot_password/{0}/'.format(forgot_key)\n \n message_html = open(r'/home/equallo/eq/src/equ/equ/equ_common/static/files/forgot_password_email.html').read()\n #message_html = open(r'/home/nicolas/git/equ_project/equ_project/src/equ/equ/equ_common/static/files/forgot_password_email.html').read()\n \n message_html = message_html.replace('{{message}}',message)\n message_text = 'Forgot your password?\\n\\nPlease click the following link to set a new one.\\n\\n{0}'.format(message)\n send_email = EmailMultiAlternatives('Password reset', message_text, settings.DEFAULT_FROM_EMAIL, [email])\n send_email.attach_alternative(message_html, 'text/html')\n send_email.send(fail_silently=False)\n else:\n request.session['message'] = 'User not found'\n elif request.method == 'GET':\n try:\n link = deobfuscate(forgot_key)\n parts = link.split('#')\n sha = hashlib.sha256()\n sha.update(parts[0])\n hashing = base64.b64encode(sha.digest())\n if hashing == parts[1]:\n data = parts[0].split('&')\n if datetime.datetime.strptime(data[1],'%d-%m-%Y %H:%M:%S') >= datetime.datetime.now():\n user = User.objects.filter(email=data[0])\n if len(user) > 0:\n form = ForgotPasswordForm(initial={ 'email':data[0] })\n return render(request, 'forgot_password.jade', { 'form':form })\n else:\n request.session['message'] = 'Key to reset password not valid.'\n else:\n request.session['message'] = 'Expired password recovery link.'\n else:\n request.session['message'] = 'Corrupted password recovery link.'\n except Exception as e:\n request.session['message'] = 'Corrupted password recovery link.'\n return redirect('login')\n\ndef reset_password(request):\n if request.method == 'POST':\n form = ForgotPasswordForm(request.POST)\n data = { 'message':str(), 'error':str() }\n if form.is_valid():\n user = User.objects.filter(email=request.POST['email'])\n data['form'] = ForgotPasswordForm()\n if len(user) > 0:\n user = user[0]\n user.set_password(request.POST['password'])\n user.save()\n auth_user = authenticate(identification=request.POST['email'], password=request.POST['password'])\n if auth_user is not None:\n login(request,auth_user)\n return redirect('home')\n else:\n data['error'] = 'Invalid login'\n else:\n data['error'] = 'Invalid user.'\n else:\n data['error'] = 'Passwords must match.'\n if data['error'] == str():\n del data['error']\n if data['message'] == str():\n del data['message']\n return render(request, 'forgot_password.jade', data)\n return render(request, 'forgot_password.jade', dict())\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":40073,"cells":{"__id__":{"kind":"number","value":695784745631,"string":"695,784,745,631"},"blob_id":{"kind":"string","value":"e31da63f82857bc709af85cbc1c09da3e293fa48"},"directory_id":{"kind":"string","value":"f81ec1e3461aaec14366b544cdd20cc6dde6f182"},"path":{"kind":"string","value":"/config-wb.py"},"content_id":{"kind":"string","value":"cc705a17bec613b6dc2b893d473d0d0aed5bdb27"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"FireNeslo/dicegame"},"repo_url":{"kind":"string","value":"https://github.com/FireNeslo/dicegame"},"snapshot_id":{"kind":"string","value":"8bf496c51389fbe6442b8a73d72444518ec0d736"},"revision_id":{"kind":"string","value":"ea51702c1d71b8ae3ef09bdf95630024418d6f6d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T05:49:15.617334","string":"2021-01-18T05:49:15.617334"},"revision_date":{"kind":"timestamp","value":"2012-12-14T19:49:01","string":"2012-12-14T19:49:01"},"committer_date":{"kind":"timestamp","value":"2012-12-14T19:49:01","string":"2012-12-14T19:49:01"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import sys\n\n\nclass config:\n REMOTE_HOST_URI = \"marte.komsys.org:/srv/www/dev.technocake.net/dicegame\"\n REMOTE_WEB_URI = \"http://dev.technocake.net/dicegame/dice.htm\"\n LOCAL_DIR = r'~/code/stats/'\n DELAY = 1\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":40074,"cells":{"__id__":{"kind":"number","value":8710193679659,"string":"8,710,193,679,659"},"blob_id":{"kind":"string","value":"fcdd9b2fa205058cf88c00dd0835ff262dc164fe"},"directory_id":{"kind":"string","value":"a0698c29534a3af25a109e173383dfcd24c84ba0"},"path":{"kind":"string","value":"/common/factory.py"},"content_id":{"kind":"string","value":"7d76540754212d9194b4b92a299a52e258bbd5cd"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"pombredanne/polygraph-2"},"repo_url":{"kind":"string","value":"https://github.com/pombredanne/polygraph-2"},"snapshot_id":{"kind":"string","value":"0f05c01f151d8e7332b87eae372e3d626113b0b5"},"revision_id":{"kind":"string","value":"bc9e6e9709d7608400209782ecd968edef47d5b7"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2017-10-07T12:34:03.475843","string":"2017-10-07T12:34:03.475843"},"revision_date":{"kind":"timestamp","value":"2014-12-26T07:06:10","string":"2014-12-26T07:06:10"},"committer_date":{"kind":"timestamp","value":"2014-12-26T07:06:10","string":"2014-12-26T07:06:10"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n\nfrom django.conf import settings\nfrom django.core.files import File\nfrom domain.models import People, Topic, PeopleCategory, Statement, Meter\nfrom account.models import Staff\nfrom common.constants import STATUS_DRAFT, STATUS_PENDING, STATUS_PUBLISHED\n\nfrom uuid import uuid1\nimport random\n\ndef randstr():\n return str(uuid1())[0: 10].replace('-', '')\n\n\ndef create_staff(username=None, email=None, password='password', first_name='', last_name='', occupation='', description='', homepage_url='', image='', is_staff=False):\n\n username = username or randstr()\n email = email or '%s@kmail.com' % username\n\n first_name = first_name or randstr()\n last_name = last_name or randstr()\n occupation = occupation or randstr()\n description = description or randstr()\n homepage_url = homepage_url or randstr()\n image = image or '%sdefault/default-people.png' % settings.FILES_WIDGET_TEMP_DIR\n\n\n staff = Staff.objects.create_user(\n username = username,\n email = email,\n password = password,\n first_name = first_name,\n last_name = last_name,\n occupation = occupation,\n description = description,\n homepage_url = homepage_url,\n image = image\n )\n\n if is_staff:\n staff.is_staff = True\n staff.save()\n\n staff = Staff.objects.get(id=staff.id)\n\n return staff\n\n\ndef create_people_category(permalink=None, title='', description=''):\n\n permalink = permalink or randstr()\n title = title or randstr()\n description = description or randstr()\n\n people_category = PeopleCategory.objects.create(\n permalink = permalink,\n title = title,\n description = description\n )\n\n people_category = PeopleCategory.objects.get(id=people_category.id)\n\n return people_category\n\n\ndef create_people(permalink=None, first_name='', last_name='', occupation='', description='', homepage_url='', image='', category='', status=STATUS_PUBLISHED, created_by='', summary='', use_long_description=False):\n\n created_by = created_by or create_staff()\n permalink = permalink or randstr()\n first_name = first_name or randstr()\n last_name = last_name or randstr()\n occupation = occupation or randstr()\n\n homepage_url = homepage_url or randstr()\n image = image or '%sdefault/default-people.png' % settings.FILES_WIDGET_TEMP_DIR\n\n category_list = list(PeopleCategory.objects.all()) or [None]\n category = category or random.choice(category_list) or create_people_category()\n\n if use_long_description:\n long_summary = '''\nอดีตอธิบดีกรมสอบสวนคดีพิเศษ, อดีตเลขาธิการคณะกรรมการป้องกันและปราบปรามการทุจริตในภาครัฐ, อดีตอัยการจังหวัดประจำกรม สำนักงานคณะกรรมการอัยการ\n'''\n\n long_description = '''\n

    ก่อนรับราชการอัยการ ธาริตเป็นผู้ช่วยอาจารย์สอนกฎหมาย จนกระทั่งได้พบกับคณิต ณ นคร ในฐานะอาจารย์พิเศษจึงแนะนำให้ธาริตไปสอบอัยการหลังเรียนจบนิติศาสตร์ มหาบัณฑิต และธาริตก็สอบได้เป็นอัยการ[6] จนกระทั่งพ.ต.ท.ทักษิณ ชินวัตรได้ก่อตั้ง พรรคไทยรักไทย ได้ระดมนักกฎหมายหลายคน เช่น คณิต ณ นคร เรวัติ ฉ่ำเฉลิม ร่วมก่อตั้งพรรค ซึ่งในจำนวนนั้นมีธาริตอยู่ด้วยทำให้หลังจากที่พรรคไทยรักไทยชนะการ เลือกตั้ง ธาริตจึงได้รับแต่งตั้งให้ช่วยราชการสำนักนายกรัฐมนตรี โดยทำงานกับนพ. พรหมินทร์ เลิศสุริย์เดช รองนายกรัฐมนตรีขณะเดียวกันธาริตยังเป็นเป็นคณะที่ปรึกษา ของพันศักดิ์ วิญญรัตน์อีกด้วย

    \n

    เมื่อมีการจัดตั้งกรมสอบสวนคดีพิเศษ (DSI) ในรัฐบาลพ.ต.ท.ทักษิณ ชินวัตร ธาริต ได้โอนมาดำรงตำแหน่งรองอธิบดีและต่อมาก็ได้รับแต่งตั้งเป็นเลขาธิการคณะ กรรมการป้องกันและปราบปรามการทุจริตในภาครัฐ กรมสอบสวนคดีพิเศษแทน พ.ต.อ.ทวี สอดส่อง ในรัฐบาลอภิสิทธิ์ เวชชาชีวะ

    \n

    ธาริต เป็นหนึ่งในคณะกรรมการศูนย์อำนวยการแก้ไขสถานการณ์ฉุกเฉิน (ศอฉ.) เมื่อครั้งมีการชุมนุมของแนวร่วมประชาธิปไตยต่อต้านเผด็จการแห่งชาติ ขับไล่รัฐบาล นายอภิสิทธิ์ เวชชาชีวะ ในปี พ.ศ. 2553 แต่ไม่ได้เป็นคณะกรรมการด้านยุทธการ นอกจากนี้ธาริตยังมีส่วนสำคัญในการดำเนินคดีทางการเมืองหลายคดี ปัจจุบัน ธาริต เป็นหนึ่งในคณะกรรมศูนย์อำนวยการรักษาความสงบในสมัยรัฐบาล ยิ่งลักษณ์ ชินวัตร

    \n'''\n summary = summary or '%s %s' % (long_summary, randstr())\n description = description or '%s %s' % (long_description, randstr())\n else:\n summary = summary or randstr()\n description = description or randstr()\n\n\n\n people = People.objects.create(\n permalink = permalink,\n first_name = first_name,\n last_name = last_name,\n occupation = occupation,\n summary=summary,\n description = description,\n homepage_url = homepage_url,\n image=image,\n status=status,\n created_by=created_by\n )\n people.categories.add(category)\n people.save()\n\n people = People.objects.get(id=people.id)\n\n\n return people\n\n\ndef create_topic(created_by=None, title='', description='', created=None, use_long_description=False):\n\n created_by = created_by or create_staff()\n title = title or randstr()\n\n long_description = '''\n

    รถไฟความเร็วสูงของ ชัชชาติ

    \n

    จากการสัมภาษณ์ออกรายการเจาะข่าวตื้น ทาง ที่ออกอากาศเมื่อวันที่ 4 เมษายน 2557 ที่ผ่านมา นายชัชชาติ สิธิพันธุ์ รักษาการรัฐมนตรีว่าการกระทรวงคมนาคม ได้กล่าวเปรียบเทียบงบประมาณระว่างการสร้างรถไฟฟ้าในเขตกรุงเทพฯ และพื้นที่รอบนอกอีกส่วนหนึ่ง กับการสร้างรถไฟฟ้าความเร็วสูงที่ผ่านพื้นที่ 29 จังหวัด ไว้ว่า “…รถไฟ ในกรุงเทพฯ 4 แสนล้าน (งบประมาณการสร้างรถไฟฟ้า) แต่ 4 แสนล้านจังหวัดเดียว 7 แสนล้าน (งบประมาณในการสร้างรถไฟความเร็วสูง) นี่มัน 29 จังหวัด คนกรุงเทพฯก็จะชินกับรถไฟในกรุงเทพฯ แต่รถไฟความเร็วสูงคนค้านกันเยอะ”

    \n

    จากงบประมาณ 2 ล้านล้าน

    \n

    โครงการลงทุนโครงสร้างพื้นฐานวงเงิน 2 ล้านล้านบาท ที่มีกรอบระยะเวลาลงทุน 7 ปี (2557-2563) เป็นโครงการของรัฐบาลเพื่อพัฒนาโครงสร้างพื้นฐานด้านการคมนาคมของประเทศ เชื่อมต่อเส้นทางการเดินทางและขนส่ง ระหว่างภูมิภาคและประเทศใกล้เคียง ด้วยการขยายและพัฒนาระบบรถไฟความเร็วสูง และรถไฟรางคู่เป็นหลัก รวมถึงการลงทุนทางถนน และท่าเรือน้ำลึก

    \n

    จากตัวโครงการทั้งหลายยังคงเป็นที่วิพากษ์วิจารณ์ถึงความคุ้มค่าของการลงทุน และมีกระแสคัดค้านจากหลายภาคส่วน เพราะไม่แน่ใจว่าจะเป็นตอบโจทย์การเสริมสร้างขีดความสามารถในการแข่งขัน ลดต้นทุนโลจิสติกส์ ต้นทุนการขนส่งสินค้าที่แท้จริงหรือไม่ และจากงบประมาณ 2 ล้านล้านตรงนี้ได้มีการแยกออกมาว่างบประมาณที่ใช้ในเรื่องระบบรางเป็นงบประมาณกว่า 80% ของงบประมาณทั้งหมด

    \n

    รถไฟฟ้า VS รถไฟความเร็วสูง

    \n

    เมื่อดูประกอบกับ เอกสารประกอบการพิจารณา ร่างพระราชบัญญัติให้อานาจกระทรวงการคลังกู้เงินเพื่อ การพัฒนาโครงสร้างพื้นฐานด้านคมนาคมขนส่งของประเทศ พ.ศ. … จะทำให้เห็นตัวเลขชัดเจนขึ้นว่าในส่วนของรถไฟความเร็วสูง อยู่ในแผนพัฒนาโครงข่ายเชื่อมต่อภูมิภาค มีตัวเลขงบประมาณอยู่ที่ 994,430.90 ล้านบาท โดย เป็นโครงการรถไฟความเร็วสูง 4 โครงการ เป็นโครงการรถไฟรางคู่ 2 โครงการ และโครงการสร้างทางหลวงพิเศษ 3 โครงการ วงเงินสำหรับรถไฟความเร็วสูงทั้งหมดคิดเป็น 783,229.9 ล้านบาท ส่วนงบประมาณในส่วนของการสร้างรถไฟฟ้า อยู่ในส่วนของแผนพัฒนาระบบขนส่งในเขตเมือง มีตัวเลขงบอยู่ที่ 472,448.12 ล้านบาท

    \n

    และได้มีการสรุปสัดส่วนการใช้งบ 2 ล้านล้านออกมาในโลกออนไลน์ ว่ากามีการใช้งบในส่วน รถไฟความเร็วสูง 783,553 ล้านบาท คิดเป็น 39.2% รถไฟฟ้า 456,662 ล้านบาท คิดเป็น 22.8%

    \n

    ถนนทางหลวง 241,080 ล้านบาท คิดเป็น 12.1% ถนนทางหลวงชนบท 34,309 ล้านบาท คิดเป็น 1.7% สถานีขนส่งสินค้า 14,093 ล้านบาท คิดเป็น 0.7% ท่าเรือ 29,581 ล้านบาท คิดเป็น 1.5% ด่านศุลกากร 12,545 ล้านบาท คิดเป็น 0.6%

    ปรับปรุงระบบรถไฟ (เพิ่มเครื่องกั้น ซ่อมบำรุงรางที่เสียหาย) 23,236 ล้านบาท คิดเป็น 1.2% รถไฟทางคู่ และทางคู่เส้นทางใหม่ 383,891 ล้านบาท คิดเป็น 19.2% ค่าสำรองเผื่อฉุกเฉิน (ความผันผวนราคาวัสดุ การติดตามและประเมินผล) 21,050 ล้านบาท คิดเป็น 1.0% ซึ่งแม้ตัวเลขจะคลาดเคลื่อนจากในเอกสารประกอบร่างพระราชบัญญัติไปบ้าง แต่ก็มีความใกล้เคียง

    \n

    ทั้งนี้ทั้งนั้นก่อนหน้านี้ในปี 2554 ได้มีตัวเลขประมาณการงบประมาณการสร้างรถไฟฟ้า 10 สายในเขตกรุงเทพว่ารวมๆ แล้วจะต้องใช้งบลงทุนประมาณ 668,593 ล้านบาท (รวมค่าเวนคืน-ก่อสร้าง-งานระบบ)

    \n'''\n if use_long_description:\n description = description or '%s %s' % (long_description, randstr())\n else:\n description = description or randstr()\n\n topic = Topic.objects.create(\n title = title,\n description = description,\n created_by = created_by\n )\n\n topic = Topic.objects.get(id=topic.id)\n\n return topic\n\n\ndef create_meter(permalink=None, title='', description='', point=0, order=0, image_large_text='', image_medium_text='', image_small_text='', image_small=''):\n\n permalink = permalink or randstr()\n title = title or randstr()\n description = description or randstr()\n\n\n image_large_text = image_large_text or '%sdefault_meters/status-unverifiable---large-text.png' % settings.FILES_WIDGET_TEMP_DIR\n image_medium_text = image_medium_text or '%sdefault_meters/status-unverifiable---medium-text.png' % settings.FILES_WIDGET_TEMP_DIR\n image_small_text = image_small_text or '%sdefault_meters/status-unverifiable---small-text.png' % settings.FILES_WIDGET_TEMP_DIR\n image_small = image_small or '%sdefault_meters/status-unverifiable---small.png' % settings.FILES_WIDGET_TEMP_DIR\n\n\n\n meter = Meter.objects.create(\n permalink=permalink,\n title=title,\n description=description,\n point=point,\n order=order,\n image_large_text=image_large_text,\n image_small_text=image_small_text,\n image_medium_text=image_medium_text,\n image_small=image_small\n )\n\n meter = Meter.objects.get(id=meter.id)\n\n return meter\n\n\ndef create_statement(created_by=None, quoted_by=None, permalink=None, quote='', references=None, status=STATUS_PENDING, topic=None, tags='hello world', meter=None, relate_statements=[], relate_peoples=[], published=None, published_by=None, source='', created=None, created_raw=None, changed=None, use_long_description=False, hilight=False, promote=False):\n\n created_by_list = list(Staff.objects.all()) or [None]\n created_by = created_by or random.choice(created_by_list) or create_staff()\n\n quoted_by_list = list(People.objects.all()) or [None]\n quoted_by = quoted_by or random.choice(quoted_by_list) or create_people()\n\n\n meter_list = list(Meter.objects.all()) or [None]\n meter = meter or random.choice(meter_list) or create_meter()\n\n topic = topic or create_topic(created_by=created_by, use_long_description=use_long_description)\n\n permalink = permalink or randstr()\n\n dummy_text = u'ฮิแฟ็กซ์ อมาตยาธิปไตยอีโรติก สหรัฐแก๊สโซฮอล์ สหรัฐบอเอ็กซ์เพรสคาแร็คเตอร์ชะโป่าไม้สระโงกอ่อนด้อยเทอร์โบบ็อกซ์ ฟลุกแทงโก้สะกอม ฮิแฟ็กซ์ อมาตยาธิปไตยอีโรติก สหรัฐแก๊สโซฮอล์ สหรัฐบอเอ็กซ์เพรสคาแร็คเตอร์ชะโป่าไม้สระโงกอ่อนด้อยเทอร์โบบ็อกซ์ ฟลุกแทงโก้สะกอม ฮิแฟ็กซ์'\n\n quote = quote or '%s %s' % (dummy_text, randstr())\n source = source or randstr()\n references = references or [{'url': 'http://%s.com/' % randstr(), 'title': randstr()}, {'url': 'http://%s.com/' % randstr(), 'title': randstr()}]\n statement = Statement.objects.create(\n permalink=permalink,\n quote=quote,\n references=references,\n status=status,\n quoted_by=quoted_by,\n created_by=created_by,\n topic=topic,\n tags=tags,\n meter=meter,\n published=published,\n published_by=published_by,\n source=source,\n created=created,\n created_raw=created_raw,\n changed=changed,\n hilight=hilight,\n promote=promote\n )\n\n for relate_statement in relate_statements:\n statement.relate_statements.add(relate_statement)\n\n for relate_people in relate_peoples:\n statement.relate_peoples.add(relate_people)\n\n statement = Statement.objects.get(id=statement.id)\n\n return statement"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":40075,"cells":{"__id__":{"kind":"number","value":11330123766633,"string":"11,330,123,766,633"},"blob_id":{"kind":"string","value":"98daaf6a844dbc2248e401cde16e70f7d981cc61"},"directory_id":{"kind":"string","value":"c5276f3475f8ccff4f60289efeb7d6e3cf1e4774"},"path":{"kind":"string","value":"/date/urls.py"},"content_id":{"kind":"string","value":"2e8053728cf944448042da7d62d48b684dc06ab2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"oneuptim/dating"},"repo_url":{"kind":"string","value":"https://github.com/oneuptim/dating"},"snapshot_id":{"kind":"string","value":"b5a6ef44c8062f909725c7f8462e83204de41002"},"revision_id":{"kind":"string","value":"b28a31a459fd07cccc1a47b25696fcf72d2a8e94"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-12T04:45:39.651735","string":"2021-01-12T04:45:39.651735"},"revision_date":{"kind":"timestamp","value":"2014-10-24T18:29:52","string":"2014-10-24T18:29:52"},"committer_date":{"kind":"timestamp","value":"2014-10-24T18:29:52","string":"2014-10-24T18:29:52"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from django.conf.urls import patterns, include, url\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom date import settings\n# from date_app import urls as profile_urls\n\nurlpatterns = patterns('',\n #ADMIN#\n url(r'^admin/', include(admin.site.urls)),\n #LOGIN AND REGISTER\n url(r'^$', 'django.contrib.auth.views.login', name='login'),\n url(r'^register/$', 'date_app.views.register', name='register'),\n url(r'^login/$', 'django.contrib.auth.views.login', name='login'),\n url(r'^logout/$', 'django.contrib.auth.views.logout_then_login', name='logout'),\n # PASSWORD RESET\n url(r'^password_reset/$', 'django.contrib.auth.views.password_reset', name='password_reset'),\n url(r'^password_reset/done/$', 'django.contrib.auth.views.password_reset_done', name='password_reset_done'),\n url(r'^reset/(?P[0-9A-Za-z_\\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',\n 'django.contrib.auth.views.password_reset_confirm',\n name='password_reset_confirm'),\n #SEARCH#\n url(r'^search/$', 'date_app.views.search', name='search'),\n url(r'^search/(?P.*)/$', 'date_app.views.set_lat_long', name='set_lat_long'),\n url(r'^save-lat-long/$', 'date_app.views.save_lat_long', name='save_lat_long'),\n # url(r'^search/(?P.*)/$', 'date_app.views.search_lat_long', name='search_lat_long'),\n #PROFILE#\n url(r'^profile/$', 'date_app.views.profile', name='profile'),\n #DATER PROFILE#\n url(r'^dater_profile/(?P\\w+)/$', 'date_app.views.dater_profile', name='dater_profile'),\n url(r'^chat_room/(?P\\w+)/$', 'date_app.views.chat_room', name='chat_room'),\n url(r'^chat_messages/(?P\\w+)/$', 'date_app.views.chat_messages', name='chat_messages'),\n url(r'^chat_messages_template/(?P\\w+)/$', 'date_app.views.chat_messages_template', name='chat_messages_template'),\n url(r'^new_message/$', 'date_app.views.new_message', name='new_message'),\n url(r'^get_names/$', 'date_app.views.get_names', name='get_names'),\n #DATER SEARCH#\n url(r'^date_search/(?P\\d+)/$', 'date_app.views.date_search', name='date_search'),\n url(r'^bumped_option/(?P\\d+)/(?P\\d+)/(?P