{ // 获取包含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 !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转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 !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; 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, 'OCR模型免费转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 }); }); } })(); \", None, QtGui.QApplication.UnicodeUTF8))\n self.save.setText(QtGui.QApplication.translate(\"MainWindow\", \"Save\", None, QtGui.QApplication.UnicodeUTF8))\n self.upload.setToolTip(QtGui.QApplication.translate(\"MainWindow\", \"

Sinc. with Google Drive

\", None, QtGui.QApplication.UnicodeUTF8))\n self.upload.setText(QtGui.QApplication.translate(\"MainWindow\", \"Upload\", None, QtGui.QApplication.UnicodeUTF8))\n self.toolButton.setToolTip(QtGui.QApplication.translate(\"MainWindow\", \"

Path to profile photo

\", None, QtGui.QApplication.UnicodeUTF8))\n self.toolButton.setText(QtGui.QApplication.translate(\"MainWindow\", \"Upload Photo\", None, QtGui.QApplication.UnicodeUTF8))\n self.label_10.setText(QtGui.QApplication.translate(\"MainWindow\", \"CV\", None, QtGui.QApplication.UnicodeUTF8))\n self.upload_CV.setToolTip(QtGui.QApplication.translate(\"MainWindow\", \"

Path to CV file

\", None, QtGui.QApplication.UnicodeUTF8))\n self.upload_CV.setText(QtGui.QApplication.translate(\"MainWindow\", \"Upload CV\", None, QtGui.QApplication.UnicodeUTF8))\n self.toolBar.setWindowTitle(QtGui.QApplication.translate(\"MainWindow\", \"toolBar\", None, QtGui.QApplication.UnicodeUTF8))\n\n\n\n\nclass ControlMainWindow(QtGui.QMainWindow):\n def __init__(self, parent=None):\n super(ControlMainWindow, self).__init__(parent)\n self.ui = Ui_MainWindow()\n self.ui.setupUi(self)\n \nif __name__ == \"__main__\":\n app = QtGui.QApplication(sys.argv)\n mySW = ControlMainWindow()\n mySW.show()\n sys.exit(app.exec_())\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":41332,"cells":{"__id__":{"kind":"number","value":6408091206872,"string":"6,408,091,206,872"},"blob_id":{"kind":"string","value":"6f05eea8b4233617c18e31fa21578d8d7f4ce154"},"directory_id":{"kind":"string","value":"897a0ed2a95c8b987bc5b56e41a536f541636a31"},"path":{"kind":"string","value":"/h10n/source.py"},"content_id":{"kind":"string","value":"e8cea8db910223401a3a9d28192ef48d9c64e558"},"detected_licenses":{"kind":"list like","value":["BSD-2-Clause"],"string":"[\n \"BSD-2-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"kr41/h10n"},"repo_url":{"kind":"string","value":"https://github.com/kr41/h10n"},"snapshot_id":{"kind":"string","value":"4051a7529ae64483b1cae89c4bd3e05e3fb55649"},"revision_id":{"kind":"string","value":"3b75e1f927889626218de36309497ee578c15bbb"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2022-04-16T23:51:08.764943","string":"2022-04-16T23:51:08.764943"},"revision_date":{"kind":"timestamp","value":"2012-10-21T09:38:37","string":"2012-10-21T09:38:37"},"committer_date":{"kind":"timestamp","value":"2012-10-21T09:38:37","string":"2012-10-21T09:38:37"},"github_id":{"kind":"number","value":255579074,"string":"255,579,074"},"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":"\"\"\"\nA Source module is used to process different types of message sources.\n\nThere are two global variable in the module: ``file_sources`` and ``scanners``.\n\nThe ``file_sources`` variable is used by :func:`scan_path` to determine\nsupported file types. It is a dictionary, which contain file extensions\n(prefixed by dot char) in its keys and file source factories in its values.\nThis dictionary is filled on import time using entry points from\n``h10n.source.file`` group. The entry point name is used as file extension.\nh10n support only YAML-files out of the box, but you can add another ones using\nentry points.\n\n.. code-block:: pycon\n\n >>> file_sources['.yaml']\n \n >>> file_sources['.yaml'] is file_sources['.yml']\n True\n\n\nThe ``scanners`` variable is used by :func:`scanner` function to determine\nsupported types of scanners. It is a dictionary, which contain protocol name\nof scanner in its keys, and scanners in its values. This dictionary is filled\non import time using entry points from ``h10n.scanner`` group. The entry point\nname is used as protocol name.\n\n.. code-block:: pycon\n\n >>> scanners['path'] # doctest: +ELLIPSIS\n \n >>> scanners['asset'] # doctest: +ELLIPSIS\n \n >>> scanners['py'] # doctest: +ELLIPSIS\n \n\n\"\"\"\n\nimport os\nimport re\nimport pkg_resources\nimport yaml\nimport logging\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass YAMLSource(dict):\n \"\"\" A message source, which extracts message definitions from YAML-files \"\"\"\n def __init__(self, path):\n with open(path) as f:\n self.update(yaml.load(f))\n\n\ndef scanner(uri_list):\n \"\"\"\n A scanner is used to build locale definitions by scanning specified URIs.\n\n The scanner accepts single argument -- URI list, and returns an iterator\n over scanning result of each URI.\n\n URI's protocol is used to determine how to scan particular URI. It must be\n a key from the ``scanners`` dictionary from this module. For example,\n URI ``asset://myapp.resources:translations`` will be scanned\n by :func:`scan_asset`.\n \"\"\"\n for uri in uri_list:\n protocol, spec = uri.split('://')\n try:\n yield scanners[protocol](spec)\n except KeyError:\n raise ValueError('Unknown scanner \"{0}\"'.format(protocol))\n\n\ndef scan_py(spec):\n \"\"\"\n A scanner of Python modules extracts locale definitions from source code\n directly. Accepts ``spec`` argument, which should be a string in format\n ``modlule.name:locale_definitions``. If definition part is empty, i.e.\n ``spec`` is passed as ``module.name``, name ``locales`` is used by default.\n So, ``module.name`` is equal to ``module.name:locales``.\n \"\"\"\n if ':' not in spec:\n spec += ':locales'\n return pkg_resources.EntryPoint.parse('x={0}'.format(spec)).load(False)\n\n\ndef scan_asset(spec):\n \"\"\"\n A scanner of Python package assets works the same way as scanner of file\n system. See :func:`scan_path` doc-string for details. Asset specification\n should be in format ``package.name:asset/path``, where ``asset/path`` is\n a path, relative to ``package.name`` package path.\n \"\"\"\n if ':' in spec:\n package, dir = spec.split(':')\n else:\n package, dir = spec, ''\n path = pkg_resources.resource_filename(package, dir)\n return scan_path(path)\n\n\ndef scan_path(base_path):\n \"\"\"\n A scanner of file system extracts locale definitions from directory path.\n The directory should contain subdirectories, which should be named\n as locale, using format ``xx-YY`` (all other will be skipped).\n Each subdirectory is scanned recursively. Each supported file is used for\n message catalog, where catalog name is equal to file name without extension\n relative to locale directory with slashes replaced by dots, i.e.\n file ``en-US/common/objects.yaml`` will be used as source for catalog\n ``common.objects`` in locale ``en-US``. Supported files are detected\n according its extension, using registry of file sources -- global variable\n from this module ``file_sources``.\n \"\"\"\n if not os.path.isdir(base_path):\n raise ValueError(\"Can't to scan path {0}\".format(base_path))\n result = {}\n locale_pattern = re.compile(r'[a-z]{2}\\-[A-Z]{2}')\n for locale_name in os.listdir(base_path):\n locale_path = os.path.join(base_path, locale_name)\n if not (os.path.isdir(locale_path) and\n locale_pattern.match(locale_name)):\n continue\n locale = result[locale_name] = {}\n for path, dirs, files in os.walk(locale_path):\n for name in files:\n if name[0] in ('.', '_'):\n continue\n file_path = os.path.join(path, name)\n full_name = os.path.relpath(file_path, locale_path)\n name, ext = os.path.splitext(full_name)\n ext = ext.lower()\n if ext not in file_sources:\n logger.info('Unsupported file type \"{0}\"; skipped'.\n format(file_path))\n continue\n name = name.replace(os.path.sep, '.')\n locale[name] = {\n 'factory': file_sources[ext],\n 'path': file_path,\n }\n # Skip directories which names starts with '.' or '_'\n for name in dirs[:]:\n if name[0] in ('.', '_'):\n dirs.remove(name)\n return result\n\n\nfile_sources = {}\nfor entry_point in pkg_resources.iter_entry_points('h10n.source.file'):\n file_sources[entry_point.name] = entry_point.load()\n\nscanners = {}\nfor entry_point in pkg_resources.iter_entry_points('h10n.scanner'):\n scanners[entry_point.name] = entry_point.load()\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":41333,"cells":{"__id__":{"kind":"number","value":11123965329495,"string":"11,123,965,329,495"},"blob_id":{"kind":"string","value":"8215bcd6eb3b3b1f8a783129afa354d9c056d899"},"directory_id":{"kind":"string","value":"4bd0d1bed3a90063459e8bd58977a82a6229121e"},"path":{"kind":"string","value":"/analyser/graph-traceroute/graph-traceroute.py"},"content_id":{"kind":"string","value":"f86ad0f1341d90a9e2e4e8bb6595a4f555a618bb"},"detected_licenses":{"kind":"list like","value":["GPL-3.0-only","LicenseRef-scancode-sun-bcl-sdk-1.4.2"],"string":"[\n \"GPL-3.0-only\",\n \"LicenseRef-scancode-sun-bcl-sdk-1.4.2\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"UCASREN/Crossbear"},"repo_url":{"kind":"string","value":"https://github.com/UCASREN/Crossbear"},"snapshot_id":{"kind":"string","value":"f5edf081b07ff78f11dd89cbd9ba08fc836738d8"},"revision_id":{"kind":"string","value":"864b3b07d6cdbb5f16fab6707963de8af31966d0"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-17T20:35:28.944083","string":"2021-01-17T20:35:28.944083"},"revision_date":{"kind":"timestamp","value":"2014-11-12T14:56:55","string":"2014-11-12T14:56:55"},"committer_date":{"kind":"timestamp","value":"2014-11-12T15:35:11","string":"2014-11-12T15:35: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":"#!/usr/bin/python\nfrom database import DB\nfrom graphfactory import GraphFactory\nimport argparse\n\nparser = argparse.ArgumentParser(description=\"Graphs crossbear traces.\")\nparser.add_argument(\"-i\", \"--intersecting\", action = \"store_true\")\n\nargs = parser.parse_args()\ndb = DB(\"analyser.config\")\ngraphoptions = {}\nif (args.intersecting):\n graphoptions = {\"intersecting\": True}\ngf = GraphFactory(**graphoptions)\ng = gf.tograph(db.traces(1))\ng.draw_to_json(\"out.json\")\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":41334,"cells":{"__id__":{"kind":"number","value":18554258754630,"string":"18,554,258,754,630"},"blob_id":{"kind":"string","value":"ebdeaa584c40ada404cd521725c001415aa4f124"},"directory_id":{"kind":"string","value":"e2a658acd7a85160f17c2293762f151c888fd2ae"},"path":{"kind":"string","value":"/src/dorks/dork.py"},"content_id":{"kind":"string","value":"d11f0b26dd772eee5bad8cd6b2e41b49a62fa706"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"curtislarson/dorky"},"repo_url":{"kind":"string","value":"https://github.com/curtislarson/dorky"},"snapshot_id":{"kind":"string","value":"dba516722e9cfcc227e49d77a4943feecb9c0272"},"revision_id":{"kind":"string","value":"75161d670b3b515f2178632e568c34848d03219c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2022-02-23T22:20:08.571929","string":"2022-02-23T22:20:08.571929"},"revision_date":{"kind":"timestamp","value":"2014-01-12T00:05:57","string":"2014-01-12T00:05:57"},"committer_date":{"kind":"timestamp","value":"2014-01-12T00:05:57","string":"2014-01-12T00:05: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":"class Dork(object):\n\n\tdef __init__(self, type, terms):\n\t\tself.type = type\n\t\tself.terms = terms"},"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":41335,"cells":{"__id__":{"kind":"number","value":4818953326562,"string":"4,818,953,326,562"},"blob_id":{"kind":"string","value":"0f5454342598744ea12e319cd2f1f77e1dd626f4"},"directory_id":{"kind":"string","value":"2d4bfd8bf19a0867444cd73b399325d49f47aafe"},"path":{"kind":"string","value":"/pure.py"},"content_id":{"kind":"string","value":"1d8303d402d715d7628e5739cfc3d84aca8ff172"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"caiohamamura/ClusterAnalysisVariance"},"repo_url":{"kind":"string","value":"https://github.com/caiohamamura/ClusterAnalysisVariance"},"snapshot_id":{"kind":"string","value":"c7a85197944050b1035008719a46ad6952a1add3"},"revision_id":{"kind":"string","value":"ff9a666db2740a9a87a659bedad0e65ebbac3939"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-28T11:45:37.651438","string":"2020-05-28T11:45:37.651438"},"revision_date":{"kind":"timestamp","value":"2014-09-12T13:45:55","string":"2014-09-12T13:45:55"},"committer_date":{"kind":"timestamp","value":"2014-09-12T13:45:55","string":"2014-09-12T13:45:55"},"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 gdal, os, numpy as np, sys, scipy.ndimage as nd, gc\n\ndef CalculateDistribution(arr, mask=None, weight=1):\n #Mascara\n if mask == None:\n maskarr = np.ma.masked_values(arr, 255)\n else:\n maskarr = np.ma.masked_where(mask, arr)\n \n #Calcular variancia\n var = np.var(maskarr)\n std = var**0.5\n \n #Calcular n de elementos\n n = np.sum(maskarr.mask==False)\n \n #Calcular soma\n sum = np.sum(maskarr)\n \n #Calcular media\n mean = np.mean(maskarr)\n \n #Calcular numero de 254 que cabem no somatorio e quanto contribuiria esse numero de 254 para a variancia\n n254 = int(sum/254)\n var_n254 = ((254-mean)**2)*n254\n \n #Calcular quanto resta e quanto isso contribuiria para o calculo da variancia\n mod254 = sum % 254\n var_mod254 = (mean-mod254)**2\n \n #Calcular quantos zeros precisaria para atingir a quantidade n e quanto esses zeros contribuiriam para a variancia maxima\n n0 = n-n254-1\n var_zeros = (mean**2)*n0\n \n varmax = (var_n254 + var_mod254 + var_zeros)/n\n stdmax = varmax**0.5\n return 1-(var/varmax)**(1./weight)\n\ndef doit(rastInput, output, ratio, valores={1:254,2:127,3:25}, percent=0.5):\n tif = gdal.Open(rastInput)\n driver = tif.GetDriver()\n xsize = tif.RasterXSize\n ysize = tif.RasterYSize\n xSizeDesloc = (xsize-xsize/ratio*ratio)/2\n ySizeDesloc = (ysize-ysize/ratio*ratio)/2\n geoTransform = list(tif.GetGeoTransform())\n geoTransform[0] += geoTransform[1]*int(xSizeDesloc)\n geoTransform[1] *= ratio\n geoTransform[-3] += geoTransform[-1]*int(ySizeDesloc)\n geoTransform[-1] *= ratio\n geoTransform = tuple(geoTransform)\n projection = tif.GetProjectionRef()\n b = tif.GetRasterBand(1)\n arr = b.ReadAsArray()\n for (k,v) in valores.iteritems():\n arr[arr==k]=v\n arr[arr==0]=255\n arr[arr<25]=0\n shape0 = arr.shape[0]/ratio*ratio\n shape1 = arr.shape[1]/ratio*ratio\n arr = arr[int(ySizeDesloc):shape0+int(ySizeDesloc),int(xSizeDesloc):shape1+int(xSizeDesloc)]\n indices=np.indices((shape0, shape1))/ratio\n shape0,shape1 =shape0/ratio, shape1/ratio\n groups = indices[1]+indices[0]*shape1\n mask=(nd.sum(arr==255, groups, range(shape0*shape1))>((ratio**2)*percent)).reshape(shape0,shape1)\n groups[arr==255] = -1\n result=nd.mean(arr, groups, range(shape0*shape1)).reshape(shape0,shape1)+0.5\n result[mask] = 255\n out = driver.Create(str(output), xsize/ratio, ysize/ratio, 1, gdal.GDT_Byte)\n out.SetGeoTransform(geoTransform)\n out.SetProjection(projection)\n dstBand = out.GetRasterBand(1)\n b = None\n tif = None\n dstBand.SetNoDataValue(255)\n dstBand.WriteArray(result)\n dstBand= None\n out = None\n del tif, out, dstBand, b\n gc.collect()\n return CalculateDistribution(result)\n \ncurDir = os.getcwd()\nprevDir = '\\\\'.join(curDir.split('\\\\')[:-1])\nrecortes = ['recorte_paineiras','recorte_cambui','recorte_centro1', 'brandina', 'recorte_brandina']\nratio = int(sys.argv[1])\nvalores={1:254,2:127,3:25}\npercent=0.9999\nfor i in range(5):\n nome = recortes[i] \n input = prevDir+'\\\\'+nome+'.tif'\n output = nome+str(ratio)+'.tif'\n dir = os.path.dirname(input)+'/'\n print nome+\": \"+str(doit(input,output,ratio,valores,percent))"},"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":41336,"cells":{"__id__":{"kind":"number","value":13219909363452,"string":"13,219,909,363,452"},"blob_id":{"kind":"string","value":"77cc551842e0c0d2f4fd64a6dbf163a30142defb"},"directory_id":{"kind":"string","value":"536d8eedd3f5190c7aa49903dbb2c0d35389e8d7"},"path":{"kind":"string","value":"/speedseq_setup.py"},"content_id":{"kind":"string","value":"1e138052fb93f1098afe2d61769a826425c05722"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"johnworth/speedseq"},"repo_url":{"kind":"string","value":"https://github.com/johnworth/speedseq"},"snapshot_id":{"kind":"string","value":"714d9c9f21032d9f754e29b79d5d98abfbe67ffd"},"revision_id":{"kind":"string","value":"53a9796259c8b431ce6562fbb98c7ec4dbb390c9"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T00:20:27.738439","string":"2021-01-18T00:20:27.738439"},"revision_date":{"kind":"timestamp","value":"2014-03-22T20:37:13","string":"2014-03-22T20:37:13"},"committer_date":{"kind":"timestamp","value":"2014-03-22T20:37:13","string":"2014-03-22T20:37:13"},"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\"\"\"Installer for speedseq: lightweight, flexible, and open source pipeline that identifies genomic variation \n\nhttps://github.com/cc2qe/speedseq\n\nHandles installation of:\n \n- Required third party software\n\nRequires: \nLinux packages: cmake gcc-c++ gcc git make python27 python-devel python-yaml ncurses-devel zlib-devel \nBioinformatics software: BWA, FREEBAYES, GEMINI (bedtools, samtools, pybedtools), LUMPY (GSL), PARALLEL, SAMBAMBA, SAMBLASTER, SNPEFF, VCFLIB\n\nRun speedseq_install.py -h for usage.\n\"\"\"\nimport argparse\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport shlex\n\nclass PACMAN(object):\n\t\"\"\"\n\tA class to deal with finding/using the linux specific package manager\n\t\"\"\"\n\tdef __init__(self, quiet):\n\t\tself.isYum = False\n\t\tself.isApt_get = False\n\t\tself.quiet = quiet\n\tdef check_installer(self):\n\t\tif not self.quiet:\n\t\t\tprint \"\\nLooking for Linux package installer...\\n\"\n\t\tif (which(\"yum\")):\n\t\t\tif not self.quiet:\n\t\t\t\tprint \"\\nYum found...\\n\"\n\t\t\tself.isYum = True\n\t\tif (which(\"apt-get\")):\n\t\t\tif not self.quiet:\n\t\t\t\tprint \"\\nApt-get found...\\n\"\n\t\t\tself.isApt_get = True\n\t\tif (not self.isYum and not self.isApt_get):\n\t\t\tsys.stderr('Linux package installer (yum/apt-get) cannot be found, make sure it is located in your $PATH')\n\tdef install(self):\n\t\tif (self.isYum):\n\t\t\t#centos/redhat - yum\n\t\t\tsubprocess.call(shlex.split(\"sudo yum update\"))\n\t\t\tpackages = [\"cmake\", \"gcc-c++\", \"gcc\", \"git\", \"make\", \"python27\", \"python-devel\", \\\n\t\t\t\"python-yaml\", \"ncurses-devel\", \"zlib-devel\"]\n\t\t\tfor i in range(len(packages)):\n\t\t\t\tsubprocess.call(shlex.split(\"sudo yum install \" + packages[i]))\n\t\telif (self.isApt_get):\n\t\t\t#ubuntu - apt-get\n\t\t\tsubprocess.call(shlex.split(\"sudo apt-get update\"))\n\t\t\tsubprocess.call(shlex.split(\"sudo apt-get install build-essential cmake gpp gcc git \" + \\\n\t\t\t\"make python2.7 python-dev python-yaml ncurses-dev zlib1g-dev\"))\n\nclass INSTALLER(object):\n\t\"\"\"\n\tA class to deal with installing each of the software pieces in speedseq\n\t\"\"\"\n\tdef __init__(self, software, quiet):\n\t\tself.name = software\n\t\tself.quiet = quiet\n\t\tself.isInstalled = False\n\t\tself.notInstalled = True\n\t\tself.update = False\n\n\tdef download(self, method, url):\n\t\tself.filename = url.split('/')[-1]\n\t\tif (method == \"curl\"):\n\t\t\tself.dlcmd = \"curl -OL \" + url \n\t\telif method == \"wget\":\n\t\t\tself.dlcmd = \"wget \" + url \n\t\telif method == \"git\":\n\t\t\tself.dlcmd = \"git clone --recursive \" + url\n\t\tif not self.quiet:\n\t\t\tprint \"\\nDownloading \" + self.name + \"...\\n\"\n\t\tsubprocess.call(shlex.split(self.dlcmd))\n\n\tdef unpack(self, method):\n\t\tif (method == \"tar\"):\n\t\t\tself.unpackcmd = \"tar -xvf \" + self.filename\n\t\t\t#get the directory things were unpacked into, tar has 2 extentions, use basname\n\t\telif (method == \"unzip\"):\n\t\t\tself.unpackcmd = \"unzip \" + self.filename\n\t\t\t#get the directory things were unpacked into, zip has 1 extension, use basename\n\t\tif not self.quiet:\n\t\t\tprint \"\\nUnpacking \" + self.name + \"...\\n\"\n\t\tsubprocess.call(shlex.split(self.unpackcmd))\n\n\tdef install(self, method, installdir):\n\t\t#This method is messy and very hardcoded\n\t\tself.installdir = installdir\n\t\tif (method == \"make\"):\n\t\t\tself.installcmd = \"make -C \" + self.installdir\n\t\telif (method == \"confmake\"):\n\t\t\tself.installcmd = \"./configure && sudo make && sudo make install\"\n\t\telif (method == \"python2.7\"):\n\t\t\t#This only applies to gemini, uses pip install\n\t\t\tself.installcmd = \"python2.7 gemini_install.py /usr/local \" + self.installdir + \" && gemini update\"\n\t\telse:\n\t\t\tself.installcmd = 'echo \"snpEff is java\"'\n\t\tif not self.quiet:\n\t\t\tprint \"\\nInstalling \" + self.name + \"...\\n\"\n\t\tsubprocess.call(self.installcmd, shell=True)\n\n\tdef cp_bin(self, source, target):\n\t\tif os.path.isfile(source):\n\t\t\tself.copycmd = \"sudo cp \" + os.getcwd() + \"/\" + source + \" \" + target\n\t\telif os.path.isdir(source):\n\t\t\t\tself.copycmd = \"sudo cp -r \" + os.getcwd() + \"/\" + source + \"/* \" + target\n\t\tif not self.quiet:\n\t\t\tprint \"\\nCopying \" + source + \" from \" + self.name + \" to target bin ...\\n\"\n\t\tsubprocess.call(self.copycmd, shell=True)\n\n\tdef check_install(self, exe):\n\t\tif which(exe):\n\t\t\tprint self.name + \" is installed...\\n\"\n\t\t\tself.notInstalled = False\n\t\t\tself.isInstalled = True \n\t\telse:\n\t\t\tprint self.name + \" is not installed...\\n\"\n\t\t\tself.notInstalled = True\n\t\t\tself.isInstalled = False\n\n\tdef get_update(self):\n\t\tneedInput = True\n\t\twhile needInput:\n\t\t\ts = raw_input(self.name + \" was found.\\nIt is recommended to install/update because speedseq may not\" + \\\n\t\t\t\t\" work with the installed version of \" + self.name + \".\\nDo you want to install/update? [y/N]\\n\")\n\t\t\ts = s.lower()\n\t\t\tif ((s == \"n\") or (s == \"no\")):\n\t\t\t\tprint \"\\nNot installing/updating and could lead to potential problems in speedseq\" + self.name + \"...\\nContinuing anyway...\\n\"\n\t\t\t\tself.update = False\n\t\t\t\tneedInput = False\n\t\t\telif ((s == \"y\") or (s == \"yes\")):\n\t\t\t\tprint \"\\nInstalling/updating \" + self.name + \"\\n\"\n\t\t\t\tself.update = True\n\t\t\t\tneedInput = False\n\t\t\telse:\n\t\t\t\tprint \"\\nUnrecognized input, please input yes or no [y/N]\"\n\t\t\t\tneedInput = True\n\ndef which(prgm):\n\tfor path in os.environ[\"PATH\"].split(\":\"):\n\t\tif os.path.exists(path + \"/\" + prgm):\n\t\t\treturn path + \"/\" + prgm\n\treturn None\n\ndef main(args):\n\tprint \"Changing directory to \" + args.targetdir + \" and installing speedseq...\\n\"\n\tif os.path.isdir(args.targetdir):\n\t\tos.chdir(args.targetdir)\n\telse:\n\t\traise OSError(\"cd: \" + args.targetdir + \": No such file or directory\")\n\t#Linux install\n\tpackageManager = PACMAN(args.quiet)\n\tpackageManager.check_installer()\n\tpackageManager.install()\n\tcheck_dependencies()\n\t#bwa install\n\tbwa = INSTALLER(\"bwa\", args.quiet)\n\tbwa.check_install(\"bwa\")\n\tif (bwa.notInstalled or bwa.update):\n\t\turl = \"http://sourceforge.net/projects/bio-bwa/files/bwa-0.7.6a.tar.bz2\"\n\t\tbwa.download(\"curl\", url)\n\t\tbwa.unpack(\"tar\")\n\t\tbwa.install(\"make\", \"bwa-0.7.6a\")\n\t\tbwa.cp_bin(\"bwa-0.7.6a/bwa\", args.targetbin)\n\t\t\n\t#freebayes install\n\tfreebayes = INSTALLER(\"freebayes\", args.quiet)\n\tfreebayes.check_install(\"freebayes\")\n\tif (freebayes.notInstalled or freebayes.update):\n\t\turl=\"git://github.com/ekg/freebayes\"\n\t\tfreebayes.download(\"git\", url)\n\t\tfreebayes.install(\"make\", \"freebayes\")\n\t\tfreebayes.cp_bin(\"freebayes/bin\", args.targetbin)\n \t#gemini install\n\tgemini = INSTALLER(\"gemini\", args.quiet)\n\tgemini.check_install(\"gemini\")\n\tif (gemini.notInstalled or gemini.update):\n\t\turl = \"https://raw.github.com/arq5x/gemini/master/gemini/scripts/gemini_install.py\"\n\t\tgemini.download(\"wget\", url)\n\t\tgemini.install(\"python2.7\", \"/usr/local/share/gemini\")\n\t\tgemini.cp_bin(\"/usr/local/gemini/bin\", args.targetbin)\n\t#gsl install\n\tgsl = INSTALLER(\"gsl\", args.quiet)\n\tgsl.check_install(\"gsl-config\")\n\tif (gsl.notInstalled or gsl.update):\n\t\turl = \"ftp://ftp.gnu.org/gnu/gsl/gsl-1.9.tar.gz\"\n\t\tgsl.download(\"curl\", url)\n\t\tgsl.unpack(\"tar\")\n\t\tos.chdir(\"gsl-1.9\")\n\t\tgsl.install(\"confmake\", \"gsl-1.9\")\n\t#lumpy install\n\tlumpy = INSTALLER(\"lumpy\", args.quiet)\n\tlumpy.check_install(\"lumpy\")\n\tif (lumpy.notInstalled or lumpy.update):\n\t\turl=\"https://github.com/arq5x/lumpy-sv/archive/v0.1.5.tar.gz\"\n\t\tlumpy.download(\"curl\", url)\n\t\tlumpy.unpack(\"tar\")\n\t\tlumpy.install(\"make\", \"lumpy-sv-0.1.5\")\n\t\tlumpy.cp_bin(\"lumpy-sv-0.1.5/bin\", args.targetbin)\n\t\tlumpy.cp_bin(\"lumpy-sv-0.1.5/scripts\", args.targetbin)\n\t#parallel install\n\tparallel = INSTALLER(\"parallel\", args.quiet)\n\tparallel.check_install(\"parallel\")\n\tif (parallel.notInstalled or parallel.update):\n\t\turl = \"http://ftp.gnu.org/gnu/parallel/parallel-20100424.tar.bz2\"\n\t\tparallel.download(\"curl\", url)\n\t\tparallel.unpack(\"tar\")\n\t\tparallel.install(\"confmake\", \"parallel-20100424\")\n\t\tparallel.cp_bin(\"parallel-20100424/src/parallel\", args.targetbin)\n\t#sambamba install\n\tsambamba = INSTALLER(\"sambamba_v0.4.4\", args.quiet)\n\tsambamba.check_install(\"sambamba_v0.4.4\")\n\tif (sambamba.notInstalled or sambamba.update):\n\t\turl = \"https://github.com/lomereiter/sambamba/releases/download/v0.4.4/sambamba_v0.4.4_centos5.tar.bz2\"\n\t\tsambamba.download(\"curl\", url)\n\t\tsambamba.unpack(\"tar\")\n\t\tsambamba.cp_bin(\"sambamba_v0.4.4\", args.targetbin)\n\t#samblaster install\t\n\tsamblaster = INSTALLER(\"samblaster\", args.quiet)\n\tsamblaster.check_install(\"samblaster\")\n\tif (samblaster.notInstalled or samblaster.update):\n\t\turl = \"git://github.com/GregoryFaust/samblaster.git\"\n\t\tsamblaster.download(\"git\", url)\n\t\tsamblaster.install(\"make\", \"samblaster\")\n\t\tsamblaster.cp_bin(\"samblaster/samblaster\", args.targetbin)\n\t#snpeff install\n\tsnpeff = INSTALLER(\"snpeff\", args.quiet)\n\tsnpeff.check_install(\"snpeff\")\n\tif (snpeff.notInstalled or snpeff.update):\n\t\turl = \"http://sourceforge.net/projects/snpeff/files/snpEff_latest_core.zip\"\n\t\tsnpeff.download(\"wget\", url)\n\t\tsnpeff.unpack(\"unzip\")\n\t\tsnpeff.install(None, \"snpEff\")\n\t\tsnpeff.cp_bin(\"snpEff/snpeff\", args.targetbin)\n\t\tsnpeff.cp_bin(\"snpEff/snpEff.config\", args.targetbin)\n\t\tsnpeff.cp_bin(\"snpEff/snpEff.jar\", args.targetbin)\n\t\tsnpeff.cp_bin(\"snpEff/scripts\", args.targetbin)\n\t#vcflib install\n\tvcflib = INSTALLER(\"vcflib\", args.quiet)\n\tif (vcflib.notInstalled or vcflib.update):\n\t\turl = \"https://github.com/ekg/vcflib\"\n\t\tvcflib.download(\"git\", url)\n\t\tvcflib.install(\"make\", \"vcflib\")\n\t\tvcflib.cp_bin(\"vcflib/tabixpp/bgzip\", args.targetbin)\n\t\tvcflib.cp_bin(\"vcflib/tabixpp/tabix\", args.targetbin)\n\t\tvcflib.cp_bin(\"vcflib/bin\", args.targetbin)\n\t\n\tprint \"Checking speedseq installations...\\n\"\n\tbwa.check_install(\"bwa\")\n\tfreebayes.check_install(\"freebayes\")\n\tgemini.check_install(\"gemini\")\n\tgsl.check_install(\"gsl-config\")\n\tlumpy.check_install(\"lumpy\")\n\tparallel.check_install(\"parallel\")\n\tsambamba.check_install(\"sambamba_v0.4.4\")\n\tsamblaster.check_install(\"samblaster\")\n\tsnpeff.check_install(\"snpeff\")\n\tvcflib.check_install(\"bgzip\")\n\tvcflib.check_install(\"tabix\")\n\t\n\ndef check_dependencies():\n\t\t\"\"\"Ensure required tools for installation are present.\n\t\t\"\"\"\n\t\tprint \"Checking required dependencies...\"\n\t\tfor cmd, url in [(\"git\", \"http://git-scm.com/\"),\n\t\t\t(\"wget\", \"http://www.gnu.org/software/wget/\"),\n\t\t\t(\"curl\", \"http://curl.haxx.se/\"),\n\t\t\t(\"python2.7\", \"http://www.python.org/\"),\n\t\t\t(\"make\", \"https://www.gnu.org/software/make/\"),\n\t\t\t(\"cmake\", \"http://www.cmake.org/\")]:\n\t\t\ttry:\n\t\t\t\tretcode = subprocess.call([cmd, \"--version\"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n\t\t\texcept OSError:\n\t\t\t\tretcode = 127\n\t\t\tif retcode == 127:\n\t\t\t\traise OSError(\"speedseq requires %s for installation (%s)\" % (cmd, url))\n\t\t\telse:\n\t\t\t\tprint \" %s found\" % cmd\n\n\nif __name__ == \"__main__\":\n\t\tparser = argparse.ArgumentParser(description=\"Automated installer for speedseq.\")\n\t\tparser.add_argument(\"targetdir\", help=\"Directory to install 3rd party software tools\",\n\t\t\t\t\t\tnargs='?', type=os.path.abspath, default=os.getcwd())\n\t\tparser.add_argument(\"targetbin\", help=\"Directory to install the binaries into\",\n\t\t\t\t\t\tnargs='?', type=os.path.abspath, default=\"/usr/local/bin/\")\n\t\tparser.add_argument(\"--quiet\", '-q', help=\"Determines the verbosity of installation\",\n\t\t\t\t\t\tdefault=False, action='store_true')\n\t\tif len(sys.argv) == 0:\n\t\t\tparser.print_help()\n\t\telse:\n\t\t\tmain(parser.parse_args())\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":41337,"cells":{"__id__":{"kind":"number","value":5609227320342,"string":"5,609,227,320,342"},"blob_id":{"kind":"string","value":"93da02d50ad79bc65c1ab681a42bbca9203412d2"},"directory_id":{"kind":"string","value":"738dd1e061f8763762926a4a946a231dd3409f75"},"path":{"kind":"string","value":"/src/setup/url.py"},"content_id":{"kind":"string","value":"96585cc5813b046fa63c870a793a86ca2c67c692"},"detected_licenses":{"kind":"list like","value":["GPL-3.0-only","GPL-3.0-or-later"],"string":"[\n \"GPL-3.0-only\",\n \"GPL-3.0-or-later\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"vitormadalosso/Paloma"},"repo_url":{"kind":"string","value":"https://github.com/vitormadalosso/Paloma"},"snapshot_id":{"kind":"string","value":"af446c669bc620ed7b208d213fc070f6ee271f6a"},"revision_id":{"kind":"string","value":"6a655967aae22243378108523fe7df42523757c8"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-01-11T19:21:17.216811","string":"2020-01-11T19:21:17.216811"},"revision_date":{"kind":"timestamp","value":"2013-12-30T22:23:27","string":"2013-12-30T22:23:27"},"committer_date":{"kind":"timestamp","value":"2013-12-30T22:24:56","string":"2013-12-30T22:24:56"},"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\nurl = 'https://github.com/hiatobr/Paloma'\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":41338,"cells":{"__id__":{"kind":"number","value":15255723869960,"string":"15,255,723,869,960"},"blob_id":{"kind":"string","value":"3eb485e2590dd162592ac03261b246cb3e5afbe1"},"directory_id":{"kind":"string","value":"7dce6129fc93b4e181e30648f1b4ea54917bc6bb"},"path":{"kind":"string","value":"/urlannotator/settings/imagescale2.py"},"content_id":{"kind":"string","value":"64a0830804766698dc92734544a8a5b6dab779b5"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"kkonrad/urlannotator"},"repo_url":{"kind":"string","value":"https://github.com/kkonrad/urlannotator"},"snapshot_id":{"kind":"string","value":"39ec871ac15fcfcb98fd6efadec65d1078d0c378"},"revision_id":{"kind":"string","value":"f4b2b4df2d145042719b1a448aa11d31e4c5b067"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T06:02:45.309288","string":"2021-01-18T06:02:45.309288"},"revision_date":{"kind":"timestamp","value":"2013-01-29T22:35:26","string":"2013-01-29T22:35:26"},"committer_date":{"kind":"timestamp","value":"2013-01-29T22:35:26","string":"2013-01-29T22:35:26"},"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\n\nfrom tenclouds.imagescale2.settings import *\n\nDEF_HOST = '0.0.0.0'\nDEF_PORT = 12345\n\nDEF_WIDTH = 100\nDEF_HEIGHT = 100\nDEF_USE_FIT = False\n\nHASHING_ALGORITHM = 'md5'\nSALT = ''\n\nlocal_settings = os.path.join(os.path.dirname(__file__), 'local.py')\nif os.path.isfile(local_settings):\n from local import *\n\nAUTHORISATION = ('SaltedUrlHash', [HASHING_ALGORITHM, SALT], {})\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":41339,"cells":{"__id__":{"kind":"number","value":19602230765543,"string":"19,602,230,765,543"},"blob_id":{"kind":"string","value":"7e356b8bd849bddc0f29765b354cc0e540c80831"},"directory_id":{"kind":"string","value":"98c6ea9c884152e8340605a706efefbea6170be5"},"path":{"kind":"string","value":"/examples/data/Assignment_3/bgrtej001/question1.py"},"content_id":{"kind":"string","value":"ebff5259926893df13b0b6fa0100d20dfb5c6e7e"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"MrHamdulay/csc3-capstone"},"repo_url":{"kind":"string","value":"https://github.com/MrHamdulay/csc3-capstone"},"snapshot_id":{"kind":"string","value":"479d659e1dcd28040e83ebd9e3374d0ccc0c6817"},"revision_id":{"kind":"string","value":"6f0fa0fa1555ceb1b0fb33f25e9694e68b6a53d2"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-03-12T21:55:57.781339","string":"2021-03-12T21:55:57.781339"},"revision_date":{"kind":"timestamp","value":"2014-09-22T02:22:22","string":"2014-09-22T02:22:22"},"committer_date":{"kind":"timestamp","value":"2014-09-22T02:22:22","string":"2014-09-22T02:22:22"},"github_id":{"kind":"number","value":22372174,"string":"22,372,174"},"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":"#Question 1, Assignment 3\r\n#Tejasvin Bagirathi\r\n\r\nheight = eval(input(\"Enter the height of the rectangle:\\n\"))\r\nlength = eval(input(\"Enter the width of the rectangle:\\n\"))\r\n\r\nfor i in range (0, height):\r\n print('*'*length)\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":41340,"cells":{"__id__":{"kind":"number","value":7645041826089,"string":"7,645,041,826,089"},"blob_id":{"kind":"string","value":"2a819f952b93bf20112885e24382d9862b3b4fbc"},"directory_id":{"kind":"string","value":"5d026c8ca9d1e3da1efba07938026dcd6148ed7a"},"path":{"kind":"string","value":"/CheckBounce/grammarchecker.py"},"content_id":{"kind":"string","value":"0ee869a0e794c9bf0b976ccee390b7ce23c93cbe"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"joeybaker/my_sublime_packages"},"repo_url":{"kind":"string","value":"https://github.com/joeybaker/my_sublime_packages"},"snapshot_id":{"kind":"string","value":"4b9462ec01473838fba88316dada272d5c3f4a94"},"revision_id":{"kind":"string","value":"ca60fe8b42ffdc51387d0a688bd99a569bf04459"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-17T03:00:27.929237","string":"2021-01-17T03:00:27.929237"},"revision_date":{"kind":"timestamp","value":"2013-05-21T15:54:51","string":"2013-05-21T15:54:51"},"committer_date":{"kind":"timestamp","value":"2013-05-21T15:54:51","string":"2013-05-21T15:54:51"},"github_id":{"kind":"number","value":2143383,"string":"2,143,383"},"star_events_count":{"kind":"number","value":4,"string":"4"},"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 sublime\nST3 = int(sublime.version()) >= 3000\n\nimport os\nimport sys\nPyObjCPath = os.path.join(os.path.dirname(__file__), \"PyObjC\")\nif not PyObjCPath in sys.path and ST3:\n sys.path.insert(0, PyObjCPath)\nfrom Foundation import *\nfrom AppKit import *\n\nif ST3:\n import CheckBounce.const as const\nelse:\n import const\n import functools\n\nimport re\n\nclass GrammarChecker:\n global ST3\n errors = 0\n error_regions = []\n orthography = None\n raw_results = []\n\n start = 0\n checker = None\n tag = None\n scope = 'entity.name.function'\n\n callback = None\n\n def __init__(self, view, callback):\n self.view = view\n self.callback = callback\n self.checker = NSSpellChecker.sharedSpellChecker()\n self.tag = view.settings().get(\"spell_tag\", None) or NSSpellChecker.uniqueSpellDocumentTag()\n view.settings().set(\"spell_tag\", self.tag)\n\n @classmethod\n def is_whitelisted(cls, view):\n whitelist = sublime.load_settings(\"CheckBounce.sublime-settings\").get(\"syntax_whitelist\")\n for syntax in whitelist:\n if syntax.lower() in view.scope_name(0):\n return (True, syntax)\n\n return (False, None)\n\n @classmethod\n def assign(cls, view, callback):\n try:\n vid = view.id()\n except RuntimeError:\n return\n\n checker = None\n whitelisted, _ = cls.is_whitelisted(view)\n if whitelisted and view.settings().get(\"enable_checkbounce_grammar\"):\n checker = GrammarChecker(view, callback)\n const.grammar_checkers[vid] = checker\n return checker\n\n cls.remove(vid)\n\n @classmethod\n def remove(cls, vid):\n if vid in const.grammar_checkers:\n const.grammar_checkers[vid].clear()\n\n del const.grammar_checkers[vid]\n\n @classmethod\n def reload(cls):\n for ID, checker in const.grammar_checkers.items():\n callback = checker.callback\n view = checker.view\n\n checker.clear()\n const.grammar_checkers[ID] = None\n checker = GrammarChecker(checker.view, checker.callback)\n const.grammar_checkers[ID] = checker\n\n checker.view = view\n text, start = cls.text(checker.view)\n checker.start = start\n checker.callback = callback\n checker.pre_check(text)\n\n if ST3:\n callback(checker.view, checker)\n else:\n sublime.set_timeout(functools.partial(callback, checker.view, checker), 0)\n\n return\n\n @classmethod\n def text(cls, view):\n text = view.substr(sublime.Region(0, view.size()))\n _, syn = cls.is_whitelisted(view)\n if syn and syn.lower == \"latex\":\n m = re.search(r\"(?s)(?<=\\\\begin\\{document\\}).+\", text, re.S)\n if m:\n start = m.start(0)\n else:\n start = 0\n else:\n start = 0\n\n return (text, start)\n\n @classmethod\n def check_view(cls, view_id, text, start, callback):\n if view_id in const.grammar_checkers:\n checker = const.grammar_checkers[view_id]\n checker.start = start\n checker.callback = callback\n checker.pre_check(text)\n\n if ST3:\n callback(checker.view, checker)\n else:\n sublime.set_timeout(functools.partial(callback, checker.view, checker), 0)\n\n @classmethod\n def get_view(cls, view_id):\n if view_id in const.grammar_checkers:\n return const.grammar_checkers[view_id].view\n\n @classmethod\n def get_checker(cls, view_id):\n if view_id in const.grammar_checkers:\n return const.grammar_checkers[view_id]\n\n def pre_check(self, text):\n self.errors = 0\n\n if not text: return\n\n self.check(text)\n\n def check(self, text):\n c_range = NSRange()\n c_range.location = self.start\n c_range.length = len(text) - self.start\n\n c_string = NSString.alloc().initWithUTF8String_(text.encode(\"utf-8\"))\n\n (errs, self.orthography, wc) = \\\n self.checker.checkString_range_types_options_inSpellDocumentWithTag_orthography_wordCount_(c_string,\n c_range,\n NSTextCheckingTypeGrammar,\n None,\n self.tag,\n None,\n None)\n\n regions = []\n for i in range(errs.count()):\n theResult = errs.objectAtIndex_(i)\n if theResult.resultType() == NSTextCheckingTypeGrammar:\n theRange = theResult.range()\n rangeRegion = sublime.Region(theRange.location, theRange.location + theRange.length)\n regions.append(rangeRegion)\n\n self.errors = len(regions)\n self.error_regions = regions\n self.raw_results = errs\n\n self.draw()\n\n def draw(self):\n if ST3:\n flags = sublime.DRAW_NO_FILL | sublime.DRAW_NO_OUTLINE | sublime.DRAW_STIPPLED_UNDERLINE | sublime.DRAW_EMPTY_AS_OVERWRITE\n self.view.add_regions('checkbounce-grammar-error', self.error_regions, self.scope, '', flags)\n else:\n flags = sublime.DRAW_OUTLINED\n sublime.set_timeout(functools.partial(self.view.add_regions, 'checkbounce-grammar-error', self.error_regions, self.scope, '', flags), 0)\n\n def clear(self):\n if ST3:\n self.view.erase_regions('checkbounce-grammar-error')\n else:\n sublime.set_timeout(functools.partial(self.view.erase_regions, 'checkbounce-grammar-error'), 0)\n\n def get_explanation_for_region(self, region):\n expl = []\n for result in self.raw_results:\n theRange = result.range()\n rangeRegion = sublime.Region(theRange.location, theRange.location + theRange.length)\n if region == rangeRegion:\n raw_expl = result.grammarDetails()\n expl = []\n for o in raw_expl:\n e = o.objectForKey_(NSGrammarUserDescription)\n e = e.replace('.', '')\n expl.append(e)\n\n return \"; \".join(expl)\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":41341,"cells":{"__id__":{"kind":"number","value":6227702598864,"string":"6,227,702,598,864"},"blob_id":{"kind":"string","value":"98d52ea5ec4af690f6839a64cf0123c90888e0b4"},"directory_id":{"kind":"string","value":"dfab6798ece135946aebb08f93f162c37dd51791"},"path":{"kind":"string","value":"/timber/luban.timber/elements/Image.py"},"content_id":{"kind":"string","value":"59a6dd39d29da87e56793dfca1cf952f414b0eb7"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"yxqd/luban"},"repo_url":{"kind":"string","value":"https://github.com/yxqd/luban"},"snapshot_id":{"kind":"string","value":"405f5f7dcf09015d214079fe7e23d644332be069"},"revision_id":{"kind":"string","value":"00f699d15c572c8bf160516d582fa37f84ac2023"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-03-20T23:08:45.153471","string":"2020-03-20T23:08:45.153471"},"revision_date":{"kind":"timestamp","value":"2012-05-18T14:52:43","string":"2012-05-18T14:52:43"},"committer_date":{"kind":"timestamp","value":"2012-05-18T14:52:43","string":"2012-05-18T14:52:43"},"github_id":{"kind":"number","value":137831650,"string":"137,831,650"},"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#\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# Jiao Lin \n# California Institute of Technology\n# (C) 2006-2011 All Rights Reserved\n#\n# {LicenseText}\n#\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n\nfrom luban import py_major_ver, setup_context\nif py_major_ver == 2: setup_context(locals())\n\n\nfrom luban.ui.elements.SimpleElement import SimpleElement as base\nclass Image(base):\n\n # decorations\n simple_description = 'An image'\n full_description = (\n 'An image widget displays an image'\n )\n\n # properties\n path = descriptors.str()\n path.tip = 'path to the image'\n \n # methods\n def identify(self, inspector):\n return inspector.onImage(self)\n\n\n# End of file \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":41342,"cells":{"__id__":{"kind":"number","value":7507602849527,"string":"7,507,602,849,527"},"blob_id":{"kind":"string","value":"8cf9425d1fcfed591f2c2090f3ce5d0482f95534"},"directory_id":{"kind":"string","value":"89e4b24b9df1a43a280059b995afb423554e6644"},"path":{"kind":"string","value":"/CLI/lib/__init__.py"},"content_id":{"kind":"string","value":"7a4214f0982b993b788bd1221c30d58989edf20c"},"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":"regimantas/4zip"},"repo_url":{"kind":"string","value":"https://github.com/regimantas/4zip"},"snapshot_id":{"kind":"string","value":"99f0363ab04b811972d4c36909d639084a054ca5"},"revision_id":{"kind":"string","value":"ce2f1846f19d1f430a4f90d2184debfd513be7fa"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-05T23:56:58.851051","string":"2016-09-05T23:56:58.851051"},"revision_date":{"kind":"timestamp","value":"2013-05-12T14:55:55","string":"2013-05-12T14:55:55"},"committer_date":{"kind":"timestamp","value":"2013-05-12T14:55:55","string":"2013-05-12T14:55:55"},"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":"\"\"\"\nlz4 librarys\n\"\"\"\n\n__version__ = '0.0.0.1'\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":41343,"cells":{"__id__":{"kind":"number","value":12601434049980,"string":"12,601,434,049,980"},"blob_id":{"kind":"string","value":"fe3203c63ab271f738caf276dca6feb214bfc708"},"directory_id":{"kind":"string","value":"e0b96bd3e5a60ea7532d8c0798dd3ddcec1c1998"},"path":{"kind":"string","value":"/ParseJobAgentLog"},"content_id":{"kind":"string","value":"9915a774ce50ed9ff9b00b63894b41a5decceb56"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Villaz/lhcbVcycle"},"repo_url":{"kind":"string","value":"https://github.com/Villaz/lhcbVcycle"},"snapshot_id":{"kind":"string","value":"e65d5d45ea53d43ca171ca52b9515239ab3afb58"},"revision_id":{"kind":"string","value":"d02e78fdfcaa6e59a4c9b84e1c6affb1f63760ad"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-01T20:06:30.387633","string":"2021-01-01T20:06:30.387633"},"revision_date":{"kind":"timestamp","value":"2014-12-15T11:12:35","string":"2014-12-15T11:12:35"},"committer_date":{"kind":"timestamp","value":"2014-12-15T11:12:35","string":"2014-12-15T11:12: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":"#!/usr/bin/python\n#\n# Parse DIRAC JobAgent log file and output codes and messages\n# to use with HEPiX VM shutdown_command.\n#\n# See https://www.gridpp.ac.uk/wiki/HEPiX_shutdown_command\n#\n# This script takes the full path of the JobAgent.py log file\n# as its single argument, and outputs the code+message on \n# stdout. \n#\n# The last matching pattern determines the code+message.\n# \n# Andrew.McNab@cern.ch - May 2013\n#\n# (Yes, it would be better if JobAgent.py returned these \n# codes explicitly, rather than relying on parsing logs!)\n#\n\nimport sys\n\n# catch-all in case nothing matches\nshutdownMessage = '700 Failed, probably JobAgent or Application problem'\n\n# log file patterns to look for and corresponding messages\nmessageMappings = [\n\n# Variants of: \"100 Shutdown as requested by the VM's host/hypervisor\"\n######################################################################\n# There are other errors from the TimeLeft handling, but we let those go \n# to the 600 Failed default\n['INFO: JobAgent will stop with message \"No time left for slot', '100 No time left for slot'],\n\n# Variants of: \"200 Intended work completed ok\"\n###############################################\n# Our work is done. More work available in the TQ? Who knows!\n['INFO: JobAgent will stop with message \"Filling Mode is Disabled', '200 Fillling Mode is Disabled'],\n['NOTICE: Cycle was successful', '200 Success'],\n\n#\n# !!! Codes 300-699 trigger Vac's backoff procedure !!!\n#\n\n# Variants of: \"300 No more work available from task queue\"\n###########################################################\n# We asked, but nothing more from the matcher. \n['INFO: JobAgent will stop with message \"Nothing to do for more than', '300 Nothing to do'],\n# Treat version mismatch as no work available, since pilot version updated by LHCb via CVMFS\n['ERROR: Pilot version does not match the production version', '300 Cannot match jobs with this pilot version'],\n\n# Currently, there are no outcomes relating to \n# \"400 Site/host/VM is currently banned/disabled from receiving more work\"\n# or \"500 Problem detected with environment/VM/contextualization provided by the site\"\n# or \"600 Grid-wide problem with job agent or application within VM\"\n#######################################################################################\n\n# Variants of: \"700 Error related to job agent or application within VM\"\n########################################################################\n# Some of the ways the JobAgent/Application can stop with errors. \n# Otherwise we just get the default 700 Failed message.\n['INFO: JobAgent will stop with message \"Job Rescheduled', '600 Problem so job rescheduled'],\n['INFO: JobAgent will stop with message \"Matcher Failed', '600 Matcher Failed'],\n['INFO: JobAgent will stop with message \"JDL Problem', '600 JDL Problem'],\n['INFO: JobAgent will stop with message \"Payload Proxy Not Found', '600 Payload Proxy Not Found'],\n['INFO: JobAgent will stop with message \"Problem Rescheduling Job', '600 Problem Rescheduling Job'],\n['INFO: JobAgent will stop with message \"Payload execution failed with error code', '600 Payload execution failed with error'],\n\n]\n\nif len(sys.argv) <= 1 or not sys.argv[1]:\n sys.exit(1)\n\ntry:\n f = open(sys.argv[1], 'r')\nexcept:\n sys.exit(2)\n\noneline = f.readline()\n\nwhile oneline:\n\n for pair in messageMappings:\n if pair[0] in oneline:\n shutdownMessage = pair[1]\n break\n\n oneline = f.readline() \n\nf.close()\n\nprint shutdownMessage\nsys.exit(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":2014,"string":"2,014"}}},{"rowIdx":41344,"cells":{"__id__":{"kind":"number","value":8847632634065,"string":"8,847,632,634,065"},"blob_id":{"kind":"string","value":"880a2c2919dff28f27e4f4ea3c1ea987efa36ff8"},"directory_id":{"kind":"string","value":"5e8f510689dfdc20f50c83d722961cdc1cddb148"},"path":{"kind":"string","value":"/pynutrients/providers/provider.py"},"content_id":{"kind":"string","value":"48aea3269e912d9b10081de9809d4e3cba99040b"},"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":"dck/pynutrients"},"repo_url":{"kind":"string","value":"https://github.com/dck/pynutrients"},"snapshot_id":{"kind":"string","value":"093834ef68ba839e4d1d4bb739d70b6fa4b71fa2"},"revision_id":{"kind":"string","value":"4216be1ab72b8cd4996b3a61f0e96e8da466d6d2"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2018-12-29T09:31:31.481670","string":"2018-12-29T09:31:31.481670"},"revision_date":{"kind":"timestamp","value":"2014-05-06T22:20:40","string":"2014-05-06T22:20:40"},"committer_date":{"kind":"timestamp","value":"2014-05-06T22:20:40","string":"2014-05-06T22:20:40"},"github_id":{"kind":"number","value":18769888,"string":"18,769,888"},"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":"# -*- coding: utf-8 -*-\n\n\nclass Provider(object):\n\n def __init__(self):\n pass\n\n def request_product(self, name):\n raise NotImplementedError"},"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":41345,"cells":{"__id__":{"kind":"number","value":13365938251369,"string":"13,365,938,251,369"},"blob_id":{"kind":"string","value":"8d9ea7402ca19230a85dc3cbe682c699e455b1ee"},"directory_id":{"kind":"string","value":"dc0e7c90b841044982e64c7789f3f0156568a170"},"path":{"kind":"string","value":"/results-archive/tdma-agent/rlagent_patterns.py"},"content_id":{"kind":"string","value":"2898d3a17677fcc209b838fd1da42e5bc32429fd"},"detected_licenses":{"kind":"list like","value":["GPL-2.0-only","GPL-2.0-or-later"],"string":"[\n \"GPL-2.0-only\",\n \"GPL-2.0-or-later\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"extrasyllmit/extrasy"},"repo_url":{"kind":"string","value":"https://github.com/extrasyllmit/extrasy"},"snapshot_id":{"kind":"string","value":"fc198e1e65f89bc31fed80a25128d823f2418aa1"},"revision_id":{"kind":"string","value":"3bafc765218c98db3d0dba08a6b29550c8e8ca2e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-23T18:56:53.515994","string":"2021-01-23T18:56:53.515994"},"revision_date":{"kind":"timestamp","value":"2014-10-14T21:30:42","string":"2014-10-14T21:30:42"},"committer_date":{"kind":"timestamp","value":"2014-10-14T21:30:42","string":"2014-10-14T21:30:42"},"github_id":{"kind":"number","value":22963091,"string":"22,963,091"},"star_events_count":{"kind":"number","value":2,"string":"2"},"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":"'''\r\nPattern File for ExtRaSy example agnets\r\n'''\r\nfrom collections import namedtuple\r\n\r\nPatternTuple = namedtuple(\"PatternTuple\", 'owner len offset type bb_freq')\r\n\r\nslot_init = PatternTuple\r\n\r\nFRAME_LEN_N1 = 0.22000000\r\nSET_N1 = [\r\n # pattern 0\r\n {\"frame_len\":FRAME_LEN_N1,\r\n \"rf_freq_ind\":0,\r\n \"slots\":[slot_init(owner=0, len=0.04000000, offset=0.00000000, type= \"beacon\", bb_freq=2),\r\n slot_init(owner=1, len=0.04000000, offset=0.04000000, type=\"downlink\", bb_freq=1),\r\n slot_init(owner=2, len=0.04000000, offset=0.08000000, type=\"downlink\", bb_freq=0),\r\n slot_init(owner=1, len=0.05000000, offset=0.12000000, type= \"uplink\", bb_freq=7),\r\n slot_init(owner=2, len=0.05000000, offset=0.17000000, type= \"uplink\", bb_freq=6),\r\n ]\r\n },\r\n # pattern 1\r\n {\"frame_len\":FRAME_LEN_N1,\r\n \"rf_freq_ind\":0,\r\n \"slots\":[slot_init(owner=0, len=0.04000000, offset=0.00000000, type= \"beacon\", bb_freq=1),\r\n slot_init(owner=1, len=0.04000000, offset=0.04000000, type=\"downlink\", bb_freq=6),\r\n slot_init(owner=2, len=0.04000000, offset=0.08000000, type=\"downlink\", bb_freq=2),\r\n slot_init(owner=1, len=0.05000000, offset=0.12000000, type= \"uplink\", bb_freq=7),\r\n slot_init(owner=2, len=0.05000000, offset=0.17000000, type= \"uplink\", bb_freq=1),\r\n ]\r\n },\r\n # pattern 2\r\n {\"frame_len\":FRAME_LEN_N1,\r\n \"rf_freq_ind\":0,\r\n \"slots\":[slot_init(owner=0, len=0.04000000, offset=0.00000000, type= \"beacon\", bb_freq=0),\r\n slot_init(owner=1, len=0.04000000, offset=0.04000000, type=\"downlink\", bb_freq=0),\r\n slot_init(owner=2, len=0.04000000, offset=0.08000000, type=\"downlink\", bb_freq=0),\r\n slot_init(owner=1, len=0.05000000, offset=0.12000000, type= \"uplink\", bb_freq=0),\r\n slot_init(owner=2, len=0.05000000, offset=0.17000000, type= \"uplink\", bb_freq=0),\r\n ]\r\n },\r\n\t ]"},"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":41346,"cells":{"__id__":{"kind":"number","value":14766097585998,"string":"14,766,097,585,998"},"blob_id":{"kind":"string","value":"92af7fe8cd382506ca10156c1e8d2dabf93cebe6"},"directory_id":{"kind":"string","value":"6d2b40e7033df2f4134a088d040c6e51f178870f"},"path":{"kind":"string","value":"/5300/hw05/code/qlearn.py"},"content_id":{"kind":"string","value":"c377bd3a46f524cab2f216b2bdeea6cac6dca58a"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"hausdorf/hw"},"repo_url":{"kind":"string","value":"https://github.com/hausdorf/hw"},"snapshot_id":{"kind":"string","value":"53014ee05f23a231cc5c5d8a0d8dc3c27480d73c"},"revision_id":{"kind":"string","value":"de806d7da9493b30bb126620b76602a3403469c0"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-29T03:14:35.282518","string":"2020-04-29T03:14:35.282518"},"revision_date":{"kind":"timestamp","value":"2012-04-13T05:13:59","string":"2012-04-13T05:13:59"},"committer_date":{"kind":"timestamp","value":"2012-04-13T05:13:59","string":"2012-04-13T05:13:59"},"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":"alpha = 0.6\ngamma = 0.9\nactions = ['slow', 'fast']\nstates = ['cool', 'warm', 'off']\n\nQ = {('cool', 'slow'):0, ('cool', 'fast'):0, ('warm', 'slow'):0,\n ('warm', 'fast'):0} # table of action values\nNsa = {k:v for k,v in Q.iteritems()} # Counts\ns = None # prev state\na = None # prev action\nr = None # prev reward\n\n\ndef f(u, n):\n if n < Ne:\n return Rplus\n else:\n return u\n\n\ndef qlearn(sp, rp):\n global s\n global a\n global r\n\n if terminal(s):\n Q[(s, None)] = rp\n\n\n if s != None:\n Nsa[(s, None)] += 1\n mx = max([Q[(sp, ap)] - Q[(s, a)] for ap in actions])\n setVal = Q[(s, a)] + alpha * (Nsa[(s,a)]) * (r + gamma * mx)\n print setVal\n Q[(s, a)] = setVal\n\n amx = max([(f(Q[(sp, sp)], Nsa[(sp, ap)]), ap) for ap in actions])[1]\n s, a, r = sp, , rp\n\n return\n\n\nif __name__ == '__main__':\n qlearn()\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":41347,"cells":{"__id__":{"kind":"number","value":6107443519270,"string":"6,107,443,519,270"},"blob_id":{"kind":"string","value":"52f0062ad162f010d8c65d863475e454a226c895"},"directory_id":{"kind":"string","value":"830f50885bbf7cdeffc08097b55f662a498cf518"},"path":{"kind":"string","value":"/python/wxhello.py"},"content_id":{"kind":"string","value":"7a994da28482b541c9c58f8939723cc97b4f4c3a"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"precimilo/mcandre"},"repo_url":{"kind":"string","value":"https://github.com/precimilo/mcandre"},"snapshot_id":{"kind":"string","value":"86b2e77e28e3bd14d02e40eb9978ae4b7ccf9fcd"},"revision_id":{"kind":"string","value":"e9ab9e3fce7aba93b6528c40e06bde4ae0d461a7"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-30T17:32:37.406612","string":"2020-12-30T17:32:37.406612"},"revision_date":{"kind":"timestamp","value":"2013-05-09T18:46:46","string":"2013-05-09T18:46:46"},"committer_date":{"kind":"timestamp","value":"2013-05-09T18:47:17","string":"2013-05-09T18:47:17"},"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 wx\n\nID_ANY=wx.ID_ANY\nID_HELLO=110\n\nclass HelloFrame(wx.Frame):\n\tdef __init__(self, parent, id, title, pos=wx.DefaultPosition, size=(150, 75)):\n\t\twx.Frame.__init__(self, parent, id, title, pos, size)\n\n\t\tself.button=wx.Button(self, ID_HELLO, \"Hello World\", wx.DefaultPosition, wx.Size(20, 10))\n\n\t\twx.EVT_BUTTON(self, ID_HELLO, self.OnHello)\n\n\t\tself.Show(True)\n\n\tdef OnHello(self, event):\n\t\tprint \"Hello World\"\n\nif __name__==\"__main__\":\n\tapp=wx.PySimpleApp()\n\tframe=HelloFrame(None, ID_ANY, \"wxHello\")\n\tapp.MainLoop()"},"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":41348,"cells":{"__id__":{"kind":"number","value":3367254364946,"string":"3,367,254,364,946"},"blob_id":{"kind":"string","value":"d536c9a73d3441d55c305f47530ec76a181f36cd"},"directory_id":{"kind":"string","value":"b09696f5ce9efe365f0ed0bb63c038985caa2198"},"path":{"kind":"string","value":"/djangoplus/__init__.py"},"content_id":{"kind":"string","value":"db91a4391fe97b8e29186c554f3c803c85095112"},"detected_licenses":{"kind":"list like","value":["LGPL-3.0-or-later"],"string":"[\n \"LGPL-3.0-or-later\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"marinho/django-plus"},"repo_url":{"kind":"string","value":"https://github.com/marinho/django-plus"},"snapshot_id":{"kind":"string","value":"019b108159c79b1898bfb298ec6ff2617dbbe519"},"revision_id":{"kind":"string","value":"a52f8712f64d4e8df461d5dae507cd2f9d8d25c3"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-07T11:48:21.472068","string":"2020-04-07T11:48:21.472068"},"revision_date":{"kind":"timestamp","value":"2012-12-27T08:18:20","string":"2012-12-27T08:18:20"},"committer_date":{"kind":"timestamp","value":"2012-12-27T08:18:20","string":"2012-12-27T08:18:20"},"github_id":{"kind":"number","value":633103,"string":"633,103"},"star_events_count":{"kind":"number","value":13,"string":"13"},"fork_events_count":{"kind":"number","value":3,"string":"3"},"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":"VERSION = (1, 2, 21)\n\ndef get_version():\n return '%d.%d.%d'%VERSION\n\n__author__ = 'Marinho Brandao'\n#__date__ = '$Date: 2008-07-26 14:04:51 -0300 (Ter, 26 Fev 2008) $'[7:-2]\n__license__ = 'GNU Lesser General Public License (LGPL)'\n__url__ = 'http://django-plus.googlecode.com'\n__version__ = get_version()\n\ndef get_dynamic_template(slug, context=None):\n from models import DynamicTemplate\n\n return DynamicTemplate.objects.get(slug=slug).render(context or {})\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":41349,"cells":{"__id__":{"kind":"number","value":6794638292267,"string":"6,794,638,292,267"},"blob_id":{"kind":"string","value":"39d4ab4e4c2d0ae473ee454a6b34a10240b7bcc4"},"directory_id":{"kind":"string","value":"322f94c9ba10204f86398ada3ab2241aa401c05c"},"path":{"kind":"string","value":"/sendjack/model/data/task_instance.py"},"content_id":{"kind":"string","value":"c628eaf071269db70efab9a54e7011a17c2bc4db"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"sendjack/sendjack"},"repo_url":{"kind":"string","value":"https://github.com/sendjack/sendjack"},"snapshot_id":{"kind":"string","value":"ed7a1e7df9b8d3a018d0dcca9b31fd013c42d835"},"revision_id":{"kind":"string","value":"a9e7b7695886b2cbee53abaea131300b3242dc72"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-02T09:26:18.477166","string":"2021-01-02T09:26:18.477166"},"revision_date":{"kind":"timestamp","value":"2013-04-24T20:04:19","string":"2013-04-24T20:04:19"},"committer_date":{"kind":"timestamp","value":"2013-04-24T20:04:19","string":"2013-04-24T20:04:19"},"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\n task_instance\n -------------\n\n Define the task instance model's table schema.\n\n\"\"\"\nfrom sqlalchemy import Column\nfrom sqlalchemy.types import Integer, String, Boolean, Enum\n\nfrom jutil.decorators import constant\n\nfrom types import SerializableDateTime\nfrom task import TaskModel\nfrom crud import CRUD\n\n\nclass _TaskInstance(object):\n\n @constant\n def TABLE_NAME(self):\n return \"task_instance\"\n\n @constant\n def TASK_STATUS(self):\n return \"task_status\"\n\n @constant\n def NEW(self):\n \"\"\"Task is new, but a row exists, probably from a search query.\"\"\"\n return \"new\"\n\n @constant\n def CREATED(self):\n \"\"\"Task has been submitted to us but not processed yet.\"\"\"\n return \"created\"\n\n @constant\n def PROCESSED(self):\n \"\"\"Task has been processed by us but not yet created for posting.\"\"\"\n return \"processed\"\n\n @constant\n def CONFIRMED(self):\n \"\"\"Task has been confirmed but not yet posted to a vendor.\"\"\"\n return \"confirmed\"\n\n @constant\n def POSTED(self):\n \"\"\"Task has been posted to a vendor.\"\"\"\n return \"posted\"\n\n @constant\n def ASSIGNED(self):\n \"\"\"Task has been given to a specific worker.\"\"\"\n return \"assigned\"\n\n @constant\n def COMPLETED(self):\n \"\"\"Work on the task is complete.\"\"\"\n return \"completed\"\n\n @constant\n def APPROVED(self):\n \"\"\"Task has been approved by the customer.\"\"\"\n return \"approved\"\n\n @constant\n def REJECTED(self):\n \"\"\"Task has been rejected by the customer.\"\"\"\n return \"rejected\"\n\n @constant\n def EXPIRED(self):\n \"\"\"Task's deadline has passed without being in a completed state.\"\"\"\n return \"expired\"\n\n @constant\n def CANCELED(self):\n \"\"\"Customer has canceled the task before being completed.\"\"\"\n return \"canceled\"\n\n\nTASK_INSTANCE = _TaskInstance()\n\n\nclass TaskInstanceModel(TaskModel, CRUD):\n\n \"\"\"\n\n customer_title -> title\n customer_description -> summary\n title -> TRTitle\n summary -> TRDescription\n instructions -> description\n properties -> description\n output_type -> description\n output_method -> description\n description -> TRPrivateDescription\n more_details -> TRPrivateDescription\n\n \"\"\"\n __tablename__ = TASK_INSTANCE.TABLE_NAME\n\n # TODO: figure out foreign keys.\n template_id = Column(Integer)\n customer_id = Column(Integer)\n worker_id = Column(Integer)\n\n customer_title = Column(String)\n customer_description = Column(String)\n\n description = Column(String)\n more_details = Column(String)\n\n status = Column(\n Enum(\n TASK_INSTANCE.NEW,\n TASK_INSTANCE.CREATED,\n TASK_INSTANCE.PROCESSED,\n TASK_INSTANCE.CONFIRMED,\n TASK_INSTANCE.POSTED,\n TASK_INSTANCE.ASSIGNED,\n TASK_INSTANCE.COMPLETED,\n TASK_INSTANCE.APPROVED,\n TASK_INSTANCE.REJECTED,\n TASK_INSTANCE.EXPIRED,\n TASK_INSTANCE.CANCELED,\n name=TASK_INSTANCE.TASK_STATUS),\n default=TASK_INSTANCE.NEW)\n\n deadline_ts = Column(SerializableDateTime)\n is_urgent = Column(Boolean)\n\n # in US cents per hour\n price = Column(Integer)\n\n # TODO: it's not clear where this will come from.\n # in seconds\n overhead = Column(Integer)\n\n # TODO: eventually this should be nullable=False but it will be a while\n # before we are equipped to populate that data from the workflow.\n # in emails back and forth\n interactions = Column(Integer)\n\n # TODO: figure out what this means. eventually this should be\n # nullable=False but it will be a while before it is available.\n # in some as yet undefined unit of measure\n score = Column(Integer)\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":41350,"cells":{"__id__":{"kind":"number","value":17033840333109,"string":"17,033,840,333,109"},"blob_id":{"kind":"string","value":"707c25819e2ab660b00065542c10baf45ac8cdca"},"directory_id":{"kind":"string","value":"b17f4a842677e1fb34c17005dbec0514f3a0d118"},"path":{"kind":"string","value":"/py/sts.py"},"content_id":{"kind":"string","value":"1294a390347e10d32f550299a04ea9fb21a6b0cf"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"TripleXChung/STS"},"repo_url":{"kind":"string","value":"https://github.com/TripleXChung/STS"},"snapshot_id":{"kind":"string","value":"dcd14581c29866086c1674588ad6ed51dfa09286"},"revision_id":{"kind":"string","value":"c0a2332f0dc36a449bb2175eb6543010840d996b"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-03-31T10:00:59.488185","string":"2020-03-31T10:00:59.488185"},"revision_date":{"kind":"timestamp","value":"2013-01-29T17:57:28","string":"2013-01-29T17:57:28"},"committer_date":{"kind":"timestamp","value":"2013-01-29T17:57:28","string":"2013-01-29T17:57:28"},"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 redis\nimport time\nimport datetime\nimport collections\nfrom multiprocessing import Process, Pipe\nimport cPickle as pickle\nimport simplejson as json\n\nprofile_count = 0 \nprofile_timestamp = 0\n\ndef profile():\n\tglobal profile_count, profile_timestamp\n\tprofile_count = profile_count + 1\n\ttimestamp = time.mktime(datetime.datetime.now().timetuple())\n\ttimediff = timestamp - profile_timestamp\n\tif(timediff < 1):\n\t\treturn\n\tprofile_timestamp = timestamp\n\tprint (profile_count / timediff)\n\tprofile_count = 0\n\ndatas = {}\ntotals = {}\npersistent = False\n\nclass STS():\n\tdef __init__(self):\n\t\tself.client = redis.Redis(host='localhost', port=6379, db=0)\n\n\tdef publish_avg(self, server, timestamp, avg):\n\t\tmsg = json.dumps([server, timestamp, avg])\n\t\tself.client.publish('avg', msg)\n\t\tprofile()\n\t\t#print msg\n\n\tdef load_data(self, server):\n\t\tglobal datas\n\t\tif(not datas.has_key(server)):\n\t\t\tdatas[server] = collections.deque([])\n\t\t\ttotals[server] = 0\n\t\treturn datas[server]\n\n\tdef load_persistent_data(self, server):\n\t\tif(datas.has_key(server)):\n\t\t\treturn datas[server]\n\t\tl = self.client.llen(server)\n\t\tres = collections.deque([])\n\t\ttotal = 0\n\t\tif(l > 0):\n\t\t\ttmps = self.client.lrange(server, 0, l)\n\t\t\tfor tmp in tmps:\n\t\t\t\tobj = pickle.loads(tmp)\n\t\t\t\tres.append(obj)\n\t\t\t\ttotal = total + obj[1]\n\t\tdatas[server] = res\n\t\ttotals[server] = total\n\n\t\treturn res\n\n\tdef apply_value(self, server, timestamp, value):\n\t\tglobal persistent\n\t\tif(type(server) != int):\n\t\t\treturn\n\t\t#server_string = \"%2.2x\"%(server)\n\n\t\tif(type(timestamp) != int):\n\t\t\treturn\n\t\tif(type(value) != int):\n\t\t\treturn\n\t\tobj = [timestamp, value]\n\t\t\n\t\tif(persistent):\n\t\t\tdata = self.load_persistent_data(server)\n\t\telse:\n\t\t\tdata = self.load_data(server)\n\n\t\tdata.append(obj)\n\t\ttotals[server] = totals[server] + obj[1]\n\t\ttotal = totals[server]\n\n\t\tif(persistent):\n\t\t\tself.client.rpush(server, pickle.dumps(obj))\n\t\t\n\t\tlast_timestamp = timestamp\n\t\twhile True:\n\t\t\tobj = data[0]\n\t\t\ttimestamp = obj[0]\n\t\t\tif(last_timestamp - timestamp > (30 * 24 * 3600)):\n\t\t\t\tdata.popleft()\n\t\t\t\tif(persistent):\n\t\t\t\t\tself.client.lpop(server)\n\t\t\t\ttotals[server] = totals[server] - obj[1]\n\t\t\t\ttotal = totals[server]\n\t\t\telse:\n\t\t\t\tbreak\n\t\tcount = len(datas)\n\t\tavg = total / count\n\t\t#print server_string + '--' + str(count)\n\t\tself.publish_avg(server, last_timestamp, avg)\n\n\tdef handle_request(self, req):\n\t\tserver = req[0]\n\t\ttimestamp = req[1]\n\t\tvalue = req[2]\n\t\tself.apply_value(server, timestamp, value)\n\ndef child_process(q, sts):\n\twhile True:\n\t\treq = q.recv()\n\t\tsts.handle_request(req)\n\nprocess_num = 4\n\nif __name__ == '__main__':\n\tprocess_list = []\n\tqueue_list = []\n\tfor i in xrange(process_num):\n\t\tparent_conn, child_conn = Pipe()\n\t\tp = Process(target=child_process, args=(child_conn, STS()))\n\t\tp.start()\n\t\tqueue_list.append(parent_conn)\n\t\tprocess_list.append(p)\n\t#cnt = 0\n\tsubclient = redis.Redis(host='localhost', port=6379, db=0)\n\tpubsub = subclient.pubsub()\n\tpubsub.psubscribe('event')\n\twhile True:\n\t\tmsg = pubsub.listen().next()\n\t\tchannel = msg['channel']\n\t\tif(channel != 'event'):\n\t\t\tcontinue\n\t\ttry:\n\t\t\treq = json.loads(msg['data'])\n\t\t\tif(type(req) != type([])):\n\t\t\t\tcontinue\n\t\t\tif(len(req) != 3):\n\t\t\t\tcontinue\n\t\t\tserver = req[0]\n\t\t\tif(type(server) != int):\n\t\t\t\tcontinue\n\t\t\tidx = server % process_num\n\t\t\tqueue_list[idx].send(req)\n\t\t\t#threads[cnt % thread_num].enqueue(req)\n\t\t\t#cnt = cnt + 1\n\t\t\t#handle_request(req)\n\t\texcept Exception,e:\n\t\t\tprint e\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":41351,"cells":{"__id__":{"kind":"number","value":14499809609195,"string":"14,499,809,609,195"},"blob_id":{"kind":"string","value":"b9a1bc69652d45d7f865894315a3830559e075b6"},"directory_id":{"kind":"string","value":"42f41581f5bcae78645b8fc89f91cbca9712f354"},"path":{"kind":"string","value":"/junqer/showimporter.py"},"content_id":{"kind":"string","value":"85cee383b0a8b79a691633bedfeb96821afc1c20"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"mru00/junqer"},"repo_url":{"kind":"string","value":"https://github.com/mru00/junqer"},"snapshot_id":{"kind":"string","value":"b2d2bf8507a9f045acb734d3db512a3daa2be34f"},"revision_id":{"kind":"string","value":"cd631e3e6cc29bef1f4b17337ce2d787a23b3378"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-08T06:32:31.191148","string":"2020-04-08T06:32:31.191148"},"revision_date":{"kind":"timestamp","value":"2011-02-20T13:53:03","string":"2011-02-20T13:53:03"},"committer_date":{"kind":"timestamp","value":"2011-02-20T13:53:03","string":"2011-02-20T13:53:03"},"github_id":{"kind":"number","value":1290016,"string":"1,290,016"},"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":"# importer for junqer\n# mru 2011-01\n\nimport gio\nimport os\nfrom model import *\nimport logging\n\nlog = logging.getLogger(\"importer\")\n\n\nclass ShowImporter(object):\n def get_show_from_urls(self, urls):\n pass\n\nclass GnomeShowImporter(ShowImporter):\n def get_show_from_urls(self, urls):\n \"\"\"\n gnome delivers a newline-seperated list of uri's for drag-and-drop data.\n this function reads the directory contents of the dragged folders and adds\n them to the model.\n \"\"\"\n\n shows = []\n for show_dir in filter(lambda s: len(s)>0, map(lambda s: s.rstrip() ,urls.split('\\n'))):\n\n try:\n\n def get_last_path_item(path):\n return os.path.split(path.get_path())[-1]\n show_dir = gio.File(show_dir)\n \n show = Show()\n show.name = get_last_path_item(show_dir)\n show.name.replace('-', ' ')\n show.path = show_dir.get_uri()\n show.seasons = []\n show.meta['name'] = show.name\n \n is_dir = lambda e: e.get_file_type() == gio.FILE_TYPE_DIRECTORY\n is_file = lambda e: e.get_file_type() == gio.FILE_TYPE_REGULAR\n ENUM_DESC = 'standard::name,standard::type'\n \n \n show_infos = show_dir.enumerate_children(ENUM_DESC)\n for season_info in filter(is_dir, show_infos):\n \n season_dir = show_dir.get_child(season_info.get_name())\n \n season = Season()\n season.name = get_last_path_item(season_dir)\n season.path = season_dir.get_uri()\n season.episodes = []\n \n episode_infos = season_dir.enumerate_children(ENUM_DESC)\n for episode_info in filter(is_file, episode_infos):\n \n episode_file = season_dir.get_child(episode_info.get_name())\n episode = Episode()\n episode.name = get_last_path_item(episode_file)\n episode.uri = episode_file.get_uri()\n season.episodes.append(episode)\n \n season.episodes.sort(key=lambda e: e.name)\n show.seasons.append(season)\n \n show.seasons.sort(key=lambda s: s.name)\n shows.append(show)\n except Exception, e:\n log.error(\"Error scanning series: %s\", str(e))\n\n return shows\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":41352,"cells":{"__id__":{"kind":"number","value":12979391196247,"string":"12,979,391,196,247"},"blob_id":{"kind":"string","value":"8c2cbb14344b4e6c18f317e4f6c2017edbf76a9e"},"directory_id":{"kind":"string","value":"74f49f8b86eb85b56a2e28a1bff37038c3dff295"},"path":{"kind":"string","value":"/ftpFiles.py"},"content_id":{"kind":"string","value":"832121543eccac3229e309d2a727b520791ef3f6"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"ubergarm/actor-mq"},"repo_url":{"kind":"string","value":"https://github.com/ubergarm/actor-mq"},"snapshot_id":{"kind":"string","value":"3fa10dc7a96e107d2d0573bb3ee42e92b2b24ad0"},"revision_id":{"kind":"string","value":"51db2894f30e5b518c5f00a91fda3084fe3ac8be"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T00:53:34.040778","string":"2021-01-10T00:53:34.040778"},"revision_date":{"kind":"timestamp","value":"2013-10-11T14:39:54","string":"2013-10-11T14:39:54"},"committer_date":{"kind":"timestamp","value":"2013-10-11T14:39:54","string":"2013-10-11T14:39: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":"#!/usr/bin/env python\n\nimport sys\nfrom ftplib import FTP\nimport json\n\ndef get(host=None,files=[],user=None,passwd=None,timeout=5.0):\n \"\"\"grab files from FTP server using given specifications\n args:\n host = hostname of ftp server\n files = list of absoluate path file names\n user = (None will give anonymous login)\n passwd = (None will give anonymous@ password)\n timeout = floating point number of seconds\n returns:\n a json string of each server, file names and sizes\n \"\"\"\n # can't do much without a hostname or list of files\n if(not host or not files):\n sys.exit(1)\n\n # initalize dictionary with filenames as keys and file size as vals\n results = dict()\n\n # connect to server, timeout in seconds\n try:\n ftp = FTP(host=host,user=user,passwd=passwd,timeout=timeout)\n except Exception as e:\n sys.stderr.write(str(e)+'\\n')\n raise\n\n # login with credentials or anonymous/anonymous@ if 'None'\n try:\n ftp.login()\n except Exception as e:\n sys.stderr.write(str(e)+'\\n')\n raise\n\n # now get each file\n for fname in files:\n data = []\n try:\n ftp.retrbinary('RETR {0}'.format(fname), data.extend)\n except Exception as e:\n sys.stderr.write(str(e)+'\\n')\n raise\n finally:\n results[fname] = len(data)\n # do something with actual data now e.g.:\n # write to disk or pass along for processing\n\n #all done, clean up\n try:\n ftp.quit()\n except Exception as e:\n sys.stderr.write(str(e)+'\\n')\n raise\n\n #we made it, return json results\n print json.dumps(results)\n return json.dumps(results)\n\n\nif __name__ == '__main__':\n servers = ['ftp.debian.org'\n 'debian.cs.binghamton.edu',\n 'debian.ec.as6453.net',\n 'debian.gtisc.gatech.edu',\n 'debian.uchicago.edu']\n\n files = ['/debian/README']\n\n results = dict()\n for server in servers:\n results[server] = get('ftp.debian.org',files)\n print results\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":41353,"cells":{"__id__":{"kind":"number","value":8521215164274,"string":"8,521,215,164,274"},"blob_id":{"kind":"string","value":"e7c2a555cbf1417cebdbe67bfec3591b4fe1760b"},"directory_id":{"kind":"string","value":"4f40d11b9189a8a02c386e140b088ec2c4cd2b76"},"path":{"kind":"string","value":"/tictac.py"},"content_id":{"kind":"string","value":"24ac95681140f8b6c06581372e51251193f42a3f"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"paul-schwendenman/tictac"},"repo_url":{"kind":"string","value":"https://github.com/paul-schwendenman/tictac"},"snapshot_id":{"kind":"string","value":"a44e2a6723e2b1ee358939f53e35556b1e583f62"},"revision_id":{"kind":"string","value":"0d64216096f68004990a691bf74edc223275d1db"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T16:34:12.154543","string":"2016-09-06T16:34:12.154543"},"revision_date":{"kind":"timestamp","value":"2013-03-01T07:51:18","string":"2013-03-01T07:51:18"},"committer_date":{"kind":"timestamp","value":"2013-03-01T07:51:18","string":"2013-03-01T07:51:18"},"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 * * * * * * * * * * * *\n * Paul Schwendenman *\n * 09/20/11 *\n * If you have to ask: *\n * You aren't allowed *\n * * * * * * * * * * * *\n'''\n\n# * * * * * * *\n# * Imported *\n# * * * * * * *\nfrom UserList import UserList\nfrom handleError import handleError\nfrom ProgressBar import ProgressProcess\nfrom Timer import Timer\n\n# * * * * * * * * * * *\n# * Global Variables *\n# * * * * * * * * * * *\nDEBUG = 0 # Choose: 0 or 1\nNUMBERLASTGAMES = 15 # Choose: 1, 2, 3...\nAIADJUST = [{'win': 1, 'lose': -1, 'draw': 0, 'last': 2},\n {'win': 1, 'lose': -1, 'draw': 0, 'last': 2}]\nUSEDSPACE = -5 # This is used to adjust values for used spaces in grids\nRECURSIONCOUNT = 50 # Number of times to try and not pick a used move\n\n\n# * * * * * * * *\n# * Grid Class *\n# * * * * * * * *\nclass Grid(UserList):\n '''\n The Basic 3 by 3 grid\n '''\n def __init__(self, initlist=None):\n # From the userlist\n self.data = []\n if initlist is not None:\n if type(initlist) == type(self.data):\n self.data[:] = initlist\n elif isinstance(initlist, UserList):\n self.data[:] = initlist.data[:]\n elif isinstance(initlist, int):\n self.data = [int(item) for item in ('0' * 9 + str(initlist)) \\\n [-9:]]\n elif isinstance(initlist, str):\n if ':' in initlist:\n self.fromString(initlist)\n else:\n self.data = [int(item) for item in list(initlist)]\n else:\n self.data = list(initlist)\n else:\n self.data = [0] * 9\n if ':' in self:\n raise TypeError\n\n def __str__(self):\n '''\n Prints the list as a continuous word.\n '''\n a = ''.join([str(a) for a in self.data])\n return a\n\n def toString(self):\n '''\n Prints the list joined with \":\"\n '''\n def pick(a, b):\n if a > b:\n return b\n else:\n return a\n return ':'.join([(\" \" + str(a))[pick(-4, -len(str(a))):] \\\n for a in self.data])\n\n def __sub__(self, other):\n '''\n Used to find the differences between two grids item by item\n '''\n assert len(self.data) == len(self.data)\n return Grid([self.data[index] - other[index] for \\\n index in range(0, len(self.data))])\n\n def fromString(self, a):\n '''\n Inverse of toString()\n '''\n self.data = [int(b) for b in a.split(':')]\n\n def returnXO(self):\n '''\n Returns a list with the 0, 1, and 2s replaced.\n '''\n b = {0: \" \", 1: \"X\", 2: \"O\"}\n return [b[a] for a in self.data]\n\n def getEmptySpaces(self):\n '''\n Return the index of all positions with value '0'\n '''\n return [a for a, b in enumerate(self.data) if b == 0]\n\n def getUsedSpaces(self):\n '''\n Returns a list of (spaces) list indices that are not valued empty.\n '''\n return [a for a, b in enumerate(self.data) if b != 0]\n\n def __hash__(self):\n '''\n Okay to hash despite being mutable, hash reveals state not variable\n '''\n #return int(self.__str__())\n return Translate.Hash(self)\n\n\n# * * * * * * * * *\n# * Player Class *\n# * * * * * * * * *\nclass Player():\n '''\n The base player class for a game.\n '''\n def __init__(self, index):\n self.index = index\n\n def getMove(self, *args):\n '''\n This function should take a variable number\n of inputs and return a single number.\n\n Typically takes two inputs:\n - the current grid\n - an error raised flag\n\n Output:\n - should be in [0...8] (3x3 grid)\n '''\n pass\n\n def handleGameOver(self, *args):\n '''\n The method should handle all end game\n activities for the player.\n\n Typical Input:\n - winner\n - startingplayer\n - gamegrids\n - index, aidata <-- local\n '''\n pass\n\n\nclass Human(Player):\n '''\n Player designed for human input.\n '''\n def getMove(self, grid, error):\n '''\n Get the move.\n '''\n try:\n printXO(grid)\n if error != None:\n print \"Invalid Move: \", error + 1\n input = raw_input(\"Move? \")[0]\n if input == \"h\" or input == \"H\":\n self.printHelp()\n input = raw_input(\"Move? \")[0]\n else:\n return int(input) - 1\n except (ValueError, IndexError, KeyError, EOFError, KeyboardInterrupt):\n raise UserError(\"User Quit\")\n\n def handleGameOver(self, winner, gamegrids):\n '''\n Finalize the game.\n '''\n printXO(gamegrids[-1][0])\n assert winner in [-1, 1, 2]\n if winner == -1:\n print \"You tied!\"\n elif (winner == self.index):\n print \"You won! computer lost\"\n else:\n print \"You lost, computer won\"\n \n @staticmethod\n def printHelp():\n '''\n Helpful grid for seeing desired output\n \n Move to player.\n '''\n print\n print \" 1 | 2 | 3 \"\n print \"---+---+---\"\n print \" 4 | 5 | 6 \"\n print \"---+---+---\"\n print \" 7 | 8 | 9 \"\n\n\nclass HumanNumber(Human):\n '''\n Use the numberpad.\n '''\n def getMove(self, *args):\n '''\n Returns the user move from number pad.\n '''\n a = {7: 0, 8: 1, 9: 2, 4: 3, 5: 4, 6: 5, 1: 6, 2: 7, 3: \\\n 8}[Human.getMove(self, *args) + 1] - 1\n print \"Move:\", a\n return a\n\n @staticmethod\n def printHelp():\n '''\n Helpful grid for seeing desired output\n \n Move to player.\n '''\n print\n print \" 7 | 8 | 9 \"\n print \"---+---+---\"\n print \" 4 | 5 | 6 \"\n print \"---+---+---\"\n print \" 1 | 2 | 3 \"\n\n\nclass Comp(Player):\n '''\n Base that all computer players have.\n '''\n def __init__(self, index, **settings):\n self.index = index\n if 'filename' in settings:\n self.filename = settings['filename']\n else:\n self.filename = 'data'\n if 'record' in settings and settings['record'] == 1:\n self.record = 1\n self.load()\n else:\n self.record = 0\n self.aidata = {}\n\n def setAIdata(self, aidata):\n '''\n Set the memory of the ai\n '''\n self.aidata = aidata\n\n def getMove(self, *args):\n '''\n Get the move should be over-ridden\n '''\n pass\n\n def handleGameOver(self, *args):\n '''\n Handle any per game finalization.\n '''\n pass\n\n def loadPickle(self, filename=None):\n '''\n Loads the unpickled data into from file\n into the aidata\n '''\n from cPickle import load\n try:\n a = open(filename)\n self.aidata = load(a)\n a.close()\n except IOError:\n print \"File doesn't exist?\"\n self.aidata = {}\n else:\n print \"aidata has %i items\" % (len(self.aidata))\n\n def load(self):\n '''\n Open previously saved data.\n \n Overload this function to toggle how data is saved\n '''\n self.loadPickle(self.filename)\n\n def dumpPickle(self):\n '''\n Dumps the currently saved aidata into a file with pickle.\n '''\n from cPickle import dump\n b = open(self.filename, \"w\")\n dump(self.aidata, b)\n print \"aidata has %i items\" % (len(self.aidata))\n b.close()\n\n def dump(self):\n '''\n Save the current data\n \n Overload this function to toggle how data is saved.\n '''\n self.record = 0\n self.dumpPickle()\n\n def __del__(self):\n '''\n Save data before deleting\n '''\n if self.record:\n self.dump()\n\n\nclass CompPick(Comp):\n '''\n Pick one... no thought.\n '''\n def getMove(self, grid, c):\n return pickOne(grid.getEmptySpaces())\n\n\nclass CompTwo(Comp):\n '''\n Plays 'perfect' should finish wins and\n should block moves.\n '''\n def getMove(self, grid, c):\n '''\n Return the move.\n '''\n one = ([item[1] for item in filter(lambda a: a[0] == 1, \\\n mapGrid(pickPlay, grid))])\n two = ([item[1] for item in filter(lambda a: a[0] == 2, \\\n mapGrid(pickPlay, grid))])\n grid = grid.getEmptySpaces()\n if self.index == 2:\n if two:\n grid = two\n elif one:\n grid = one\n elif self.index == 1:\n if two:\n grid = two\n elif one:\n grid = one\n return pickOne(grid)\n\n def handleGameOver(self, *args):\n '''\n Doesn't Need to learn anything\n '''\n pass\n\n\nclass CompLearning(Comp):\n def getMove(self, grid, error):\n '''\n Make Move\n '''\n # Make getMove handle errors\n DEBUGFUNC = 0\n if grid.count(0) == len(grid):\n return pickOne([pickOne([0, 2, 6, 8]), pickOne([1, 3, 5, 7]), 4])\n b = Translate.GridMax(grid)\n if DEBUG or DEBUGFUNC:\n printXO(grid)\n printXO(b[0])\n if error != None:\n f = [0, 1, 2, 3, 4, 5, 6, 7, 8, ]\n e = Translate.GridReverse(f, b[1])[error]\n if DEBUG or DEBUGFUNC:\n print \"Invalid Computer Move:\"\n print \"\\t error:\", error, \"\\t e:\", e, \"\\t b[1]:\", b[1]\n print \"\\t self.aidata[b[0]]:\", self.aidata[b[0]].toString(),\n self.aidata[b[0]][e] += USEDSPACE\n if DEBUG or DEBUGFUNC:\n print \"\\nAfter:\"\n print \"\\t self.aidata[b[0]]:\", self.aidata[b[0]].toString()\n d = Translate.GetMove(grid, self.aidata)\n\n if error == d and d != None and error != None:\n raise ValueError(\"error = d\")\n\n if d == None:\n # Should be Intializing 'new' states\n #if DEBUG or DEBUGFUNC:\n # print \"AI\\n\\t self.aidata:\", self.aidata,\n self.aidata[b[0]] = Grid()\n if DEBUG or DEBUGFUNC:\n print \"\\n\\t empty: \", self.aidata[b[0]]\n d = Grid()\n #d = pickOne(grid.getEmptySpaces())\n return pickOne(d)\n #return getEmptySpaces(a)[0]\n\n def handleGameOver(self, a, b):\n '''\n Process move.\n '''\n adjustAI(a, b[: -1][2 - self.index:: 2], self.index, self.aidata)\n\n def load(self):\n '''\n Open saved data.\n '''\n self.aidata = {}\n try:\n file = open(self.filename)\n lines = file.readlines()\n for line in lines:\n line = line[:-1].split(\"\\t\")\n grid = Grid()\n value = Grid()\n grid.fromString(line[0])\n value.fromString(line[1])\n self.aidata[grid] = value\n file.close()\n except IOError:\n print \"File doesn't exist?\"\n self.aidata = {}\n except:\n handleError\n try:\n file.close()\n self.loadPickle()\n except:\n pass\n print \"aidata has %i items\" % (len(self.aidata))\n\n def dump(self):\n '''\n Save opened data.\n '''\n self.record = 0\n file = open(self.filename, \"w\")\n grids = sorted(self.aidata.keys())\n for grid in grids:\n file.write(grid.toString() + \"\\t\" + \\\n self.aidata[grid].toString() + \"\\n\")\n print \"aidata has %i items\" % (len(self.aidata))\n file.close()\n\n\nclass CompTree(Comp):\n def getMove(self, grid, error):\n '''\n Make Move.\n '''\n DEBUGFUNC = 1\n if error != None:\n print \"Error:\", error, grid\n assert error == None\n gridmax, trans = Translate.GridMax(grid)\n #gridmax = grid\n print gridmax, self.hash(gridmax), grid, self.hash(grid)\n print self.hash(gridmax) in self.aidata, len(self.aidata)\n if self.hash(gridmax) in self.aidata:\n if DEBUGFUNC:\n print \"Tree\"\n print \"=\" * 4\n move = self.followTree(gridmax)\n if DEBUGFUNC:\n print \"Moves:\", move\n move = move[0]\n else:\n if DEBUGFUNC:\n print \"Pick\"\n move = gridmax.getEmptySpaces()[0]\n #move = pickOne(gridmax.getEmptySpaces())\n if DEBUGFUNC:\n print \"Move:\", move\n #if move not in grid.getEmptySpaces():\n if DEBUGFUNC:\n print \"Translation Checking:\"\n print \"=\" * 21\n #print \"\\tDisabled\"\n move2 = Translate.GridReverse(range(0, 9), trans)[move]\n print \"trans index:\", trans\n print gridmax, Grid(range(0, 9)), gridmax.getEmptySpaces(), move\n print grid, Translate.GridReverse(range(0, 9), trans), \\\n grid.getEmptySpaces(), move2\n print \"Move checking:\"\n print \"=\" * 14\n print gridmax\n if DEBUGFUNC and 1:\n griiids = sorted(self.aidata.keys())[:10]\n for griiid in griiids:\n print griiid == gridmax\n print \"\\t\", griiid, type(griiid)#, self.aidata[griiid][:4]\n print \"-\" * 45\n return Translate.GridReverse(range(0, 9), trans).index(move)\n #return move\n\n @staticmethod\n def hash(grid):\n '''\n Hash should return a valid key for aidata.\n \n The \"perfect tree\" is using grids but\n the AIdata one uses hash()?\n '''\n #return grid\n return hash(grid)\n\n @staticmethod\n def followResult(item, len=0):\n if isinstance(item, tuple):\n return CompTree.followResult(item[1], len+1)\n else:\n return (len, item)\n\n @staticmethod\n def followResultLength(item):\n if isinstance(item, tuple):\n return 1 + CompTree.followResultLength(item[1])\n else:\n return 0\n\n def followTree(self, grid, **settings):\n '''\n Process Move.\n '''\n DEBUGFUNC = 1\n # print Translate.GridMax(grid)[0], grid, self.aidata, \"\\n\"\n if self.hash(grid) in self.aidata and isinstance(self.aidata[self.hash(grid)], int):\n if len(grid.getEmptySpaces()) == 1:\n return (grid.getEmptySpaces()[0], self.aidata[self.hash(grid)])\n else:\n return (None, self.aidata[self.hash(grid)])\n elif len(self.aidata[self.hash(grid)]) > 0:\n recordedmoves = set([item[0] for item in self.aidata[self.hash(grid)]])\n results = []\n for each in self.aidata[self.hash(grid)]:\n maxgrid, trans = Translate.GridMax(grid)\n if self.index not in (each - maxgrid):\n print each, grid, maxgrid, each - maxgrid\n results.append((Translate.GridReverse(each - maxgrid, trans).index(self.index), \\\n self.followTree(each),))\n if DEBUGFUNC:\n print \"Empty:\", set(grid.getEmptySpaces()), \"Recorded:\", recordedmoves, \"Results:\", results,\n for each in set(grid.getEmptySpaces()) - recordedmoves:\n results.append((each, 0))\n moves = [s for s in filter(lambda a: self.followResult(a[1]) == self.index, results)]\n if not moves: # No Wins \n if DEBUGFUNC:\n print \"No wins,\",\n moves = [s for s in filter(lambda a: self.followResult(a[1]) == -1, results)]\n if not moves: # No ties\n if DEBUGFUNC:\n print \"No ties,\",\n moves = [s for s in filter(lambda a: self.followResult(a[1]) == 0, results)]\n if not moves: # No non-losses / unknown\n if DEBUGFUNC:\n print \"No non-losses,\",\n moves = [s for s in filter(lambda a: self.followResult(a[1]) not in \\\n [-1, 0, self.index], results)]\n assert moves == results\n if DEBUGFUNC:\n print\n return pickOne(moves)\n else:\n raise Exception\n if DEBUGFUNC and 0:\n if 'tabs' not in settings:\n settings['tabs'] = 0\n print '\\t' * settings['tabs'], \"Catch Error\"\n print '\\t' * settings['tabs'], self.aidata[self.hash(grid)][0], grid, \\\n (self.aidata[self.hash(grid)][0] - grid), (self.index)\n print '\\t' * settings['tabs'], [str(key) + \": \" + \\\n str(self.aidata[key]) for key in self.aidata.keys()]\n print self.followTree(self.aidata[self.hash(grid)][0], \\\n tabs=(settings['tabs'] + 1))\n return ((self.aidata[self.hash(grid)][0] - grid).index(self.index), \\\n self.followTree(self.aidata[self.hash(grid)][0]),)\n\n def handleGameOver(self, winner, grids):\n '''\n Process data.\n '''\n DEBUGFUNC = 0\n grids = grids[self.index - 1:: 2]\n if DEBUGFUNC:\n print \"\\nHandle Game Over\"\n print \"-\" * 16\n printGameGrids(grids)\n print [(grids[i][0] - grids[i - 1][0]).index(self.index) \\\n if self.index in (grids[i][0] - grids[i - 1][0]) \\\n else (grids[i][0] - grids[i - 1][0]) \\\n for i in range(1, len(grids))]\n printGameGrids([(grids[i][0] - grids[i - 1][0],) \\\n for i in range(1, len(grids))])\n maxgrids = [Translate.GridMax(grid[0]) for grid in grids]\n if DEBUGFUNC:\n printGameGrids(maxgrids)\n print [(maxgrids[i][0] - maxgrids[i - 1][0]).index(self.index) \\\n if self.index in (maxgrids[i][0] - maxgrids[i - 1][0]) \\\n else (maxgrids[i][0] - maxgrids[i - 1][0]) \\\n for i in range(1, len(maxgrids))]\n print [(maxgrids[i][0] - maxgrids[i - 1][0]) \\\n for i in range(1, len(maxgrids))]\n try:\n for i in range(1, len(maxgrids)):\n printGameGrids(Translate.GuessDifference(maxgrids[i - 1][0], maxgrids[i][0]),) \n except:\n handleError()\n printGrids([maxgrids[i][0] - maxgrids[i - 1][0] \\\n for i in range(1, len(maxgrids))])\n\n grids.reverse()\n maxgrids.reverse()\n while len(grids) > 1:\n #grid = Translate.GridMax(grids.pop()[0])[0]\n grid = (grids.pop()[0])\n maxgrid = maxgrids.pop()\n if self.hash(grid) in self.aidata:\n #self.aidata[grid].append(Translate.GridMax(grids[-1][0])[0])\n self.aidata[self.hash(grid)].append(Translate.Grid(grids[-1][0], maxgrid[1]))\n #self.aidata[grid].append((grids[-1][0]))\n else:\n #self.aidata[grid] = [Translate.GridMax(grids[-1][0])[0]]\n self.aidata[self.hash(grid)] = [Translate.Grid(grids[-1][0], maxgrid[1])]\n #self.aidata[grid] = [(grids[-1][0])]\n assert len(grids) == 1\n #grid = Translate.GridMax(grids.pop()[0])[0]\n if DEBUGFUNC:\n print 'Last', grids\n grid = grids.pop()[0]\n if DEBUGFUNC:\n print grids, grid \n if self.hash(grid) not in self.aidata:\n self.aidata[self.hash(grid)] = winner\n else:\n print self.aidata[self.hash(grid)], winner, self.aidata[self.hash(grid)] == winner\n if self.aidata[self.hash(grid)] != winner:\n print grid, locals()\n assert self.aidata[self.hash(grid)] == winner\n\n\n# * * * * * * * *\n# * UserError *\n# * * * * * * * *\nclass UserError(Exception):\n '''\n When the User quits pass a unique exception to\n eliminate confusion between other valid exceptions.\n '''\n pass\n\n\n# * * * * * * * * * * * * * *\n# * Grid Display Functions *\n# * * * * * * * * * * * * * *\ndef printXO(b):\n '''\n Prints the tictactoe grid with XOs\n '''\n printGrid(b.returnXO())\n\n\ndef printNine(a):\n '''\n Print the list of 9 in 3x3 form.\n '''\n print \"%2i %2i %2i\\n%2i %2i %2i\\n%2i %2i %2i\\n\" % (a[0], a[1], a[2], \\\n a[3], a[4], a[5], a[6], a[7], a[8])\n\n\ndef printGrid(a):\n '''\n Basic formatting for lists\n '''\n if type(a[0]) == type(1):\n print\n print \" %i | %i | %i \" % (a[0], a[1], a[2])\n print \"---+---+---\"\n print \" %i | %i | %i \" % (a[3], a[4], a[5])\n print \"---+---+---\"\n print \" %i | %i | %i \" % (a[6], a[7], a[8])\n else:\n print\n print \" %c | %c | %c \" % (a[0], a[1], a[2])\n print \"---+---+---\"\n print \" %c | %c | %c \" % (a[3], a[4], a[5])\n print \"---+---+---\"\n print \" %c | %c | %c \" % (a[6], a[7], a[8])\n\n\ndef printAIData(a):\n '''\n Prints a useful representation of the AIdata variable.\n '''\n print len(a)\n for b, c in a.iteritems():\n d = b.returnXO()\n printEighteen(d, c)\n\n\ndef printEighteen(a, b):\n '''\n Prints a pair of 3x3 grids next to each other.\n '''\n print \"%c %c %c %2i %2i %2i\" % (a[0], a[1], a[2], b[0], b[1], b[2])\n print \"%c %c %c %2i %2i %2i\" % (a[3], a[4], a[5], b[3], b[4], b[5])\n print \"%c %c %c %2i %2i %2i\" % (a[6], a[7], a[8], b[6], b[7], b[8])\n print\n\n\ndef printGameGrids(a, one='', two='', three=''):\n '''\n Prints a resonable representation of the value of\n GameGrids and thus the history of the game so far.\n \n When passed a list of tuples with a list as the first item\n each with lengths greater than nine prints the first nine\n of each list in 3x3 form horizontally.\n \n '''\n b = [d[0].returnXO() for d in a]\n for c in b:\n print c[0], c[1], c[2], \"|\",\n print one\n for c in b:\n print c[3], c[4], c[5], \"|\",\n print two\n for c in b:\n print c[6], c[7], c[8], \"|\",\n print three\n print\n\n\ndef printGameGridsValues(gamegrids, aidata):\n '''\n Print the value for each grid in gamegrids based on aidata.\n '''\n h = []\n for i in gamegrids:\n f = Translate.FindMax(i[0])\n g = Translate.Grid(i[0], f)\n #print i , g, f\n h.append(Translate.GridReverse(aidata[g], f)\n if (g in aidata) else Grid([''] * 9))\n printGrids(h)\n\n\ndef printGrids(a):\n '''\n When passed a list of lists with lengths greater than\n nine print the first nine of each list in 3x3 form\n horizontally.\n '''\n for c in a:\n print \"%2s%2s%2s%c\" % (c[0], c[1], c[2], \"|\"),\n print\n for c in a:\n print \"%2s%2s%2s%c\" % (c[3], c[4], c[5], \"|\"),\n print\n for c in a:\n print \"%2s%2s%2s%c\" % (c[6], c[7], c[8], \"|\"),\n print\n print\n\n\n# * * * * * * * * * * * * * * * *\n# * Mostly Depricated Functions * <-- Remove them?\n# * * * * * * * * * * * * * * * *\ndef convertGridToNumber(a):\n '''\n Hashs a list based on its contents\n '''\n # int(str(a)) # <-- better?\n c = 0\n for b in a:\n c = c * 10\n c = c + b\n return c\n\n\ndef convertNumberToGrid(a):\n '''\n Turns a hash into a list.\n '''\n b = [] # Make this use Grid()?\n for c in str(a):\n b.append(int(c))\n return b\n\n\ndef convertGridToXO(a):\n '''\n Returns a list based on values of the input Grid\n '''\n b = []\n c = {0: \" \", 1: \"X\", 2: \"O\"}\n for e in a:\n b.append(c[e])\n return b\n\n\ndef getEmptySpaces(a):\n '''\n Returns a list of the spaces that are valued empty.\n '''\n empty = 0\n b = []\n for c, d in enumerate(a):\n if d == empty:\n b.append(c)\n return b\n\n\ndef getUsedSpaces(a):\n '''\n Returns a list of (spaces) list indices that are not valued empty.\n '''\n empty = 0\n b = []\n for c, d in enumerate(a):\n if d != empty:\n b.append(c)\n return b\n\n\n# * * * * * * * * * * * *\n# * Translation Helpers *\n# * * * * * * * * * * * *\ndef join(a):\n '''\n When passed a list joins the list with \":\"\n '''\n return \":\".join(a)\n\n\ndef split(a):\n '''\n The reverse of split. Don't know if these\n are called anymore. \n \n Use to initialize a string into a grid?\n '''\n DEBUGFUNC = 0\n assert isinstance(a, str)\n return [int(b) for b in a.split(\":\")]\n\n\n# * * * * * * * * * * * * *\n# * Translation Functions *\n# * * * * * * * * * * * * *\n\nclass Translate():\n @staticmethod\n def GetMove(a, b):\n '''\n Given a (current grid) and b (aidata)\n Requires c in b to get move\n '''\n c, d = Translate.GridMax(a)\n if c in b:\n f = Translate.GridReverse(b[c], d)\n g = [i for i, j in enumerate(f) if j == max(f)]\n #g = f.index(max(f))\n else:\n g = None\n return g\n\n @staticmethod\n def Grid(a, e):\n '''\n Returns only the selected transition, designated by e.\n '''\n assert Translate.Array(a)[e] == Grid([a[f] \\\n for f in Translate.Data()[e]])\n return Grid([a[f] for f in Translate.Data()[e]])\n\n @staticmethod\n def GridReverse(a, e):\n '''\n Returns the Reverse Grid\n '''\n return Translate.Grid(a, Translate.ReverseIndex(e))\n\n @staticmethod\n def ReverseIndex(a):\n '''\n Returns the complementary translation\n Because clockwise turns need reversed with counter-clockwise turns.\n '''\n b = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 7, 6: 6, 7: 5}\n return b[a]\n\n @staticmethod\n def Array(a):\n '''\n Finds all of the possible transitions.\n '''\n return [Grid([a[f] for f in e]) for e in Translate.Data()]\n\n @staticmethod\n def Hash(a):\n '''\n Return an integer rep. of the grid A.\n '''\n return int(str(Translate.Grid(a, Translate.FindMax(a))))\n\n @staticmethod\n def FindMax(a):\n '''\n Returns the highest valued transition.\n '''\n assert a != type(\"\")\n return max([(Grid([int(a[f]) for f in e]), d) \\\n for d, e in enumerate(Translate.Data())])[1]\n #Remove the above int()\n\n @staticmethod\n def FindIndex(a, b):\n '''\n Find the translation index from grid A to grid B.\n '''\n return Translate.Array(a).index(b)\n\n @staticmethod\n def GridMax(a):\n '''\n Returns the maximum valued grid, and the transition index\n '''\n e = Translate.FindMax(a)\n return (Translate.Grid(a, e), e)\n\n @staticmethod\n def GuessDifference(one, two):\n '''\n Returns possible 'correct' forms of two from the\n perspective of one.\n '''\n array = [a - one for a in Translate.Array(two)]\n valid = filter(lambda a: (array[a].count(0) == 7) and \\\n (array[a].count(1) == 1) and (array[a].count(2) == 1), \\\n range(0, len(array)))\n if len(valid) == 0:\n print \"Not valid?\"\n print printGrids(array)\n printGameGrids([(one,), (two,), (Grid(),)] + [(item,) for item in Translate.Array(two)])\n return [(Translate.Array(two)[a], a) for a in valid]\n\n @staticmethod\n def Data():\n '''\n Returns the transitions used for all\n '''\n return [[0, 1, 2, 3, 4, 5, 6, 7, 8], [2, 1, 0, 5, 4, 3, 8, 7, 6],\n [6, 7, 8, 3, 4, 5, 0, 1, 2], [8, 5, 2, 7, 4, 1, 6, 3, 0],\n [0, 3, 6, 1, 4, 7, 2, 5, 8], [6, 3, 0, 7, 4, 1, 8, 5, 2],\n [8, 7, 6, 5, 4, 3, 2, 1, 0], [2, 5, 8, 1, 4, 7, 0, 3, 6]]\n\n\n# * * * * * * * * * * * * * * * * *\n# * Sorting and Filter Functions *\n# * * * * * * * * * * * * * * * * *\ndef mapGrid(f, grid):\n '''\n Map grid looks at the important lines on a grid and\n compares them using a passed function 'f'\n '''\n lines = [(0, 1, 2), (3, 4, 5), (6, 7, 8), \\\n (0, 3, 6), (1, 4, 7), (2, 5, 8), \\\n (0, 4, 8), (2, 4, 6)]\n return [f(line, grid) for line in lines]\n\n\ndef pickGameOver(sample, grid):\n '''\n Picks the in a given sample. Ex: row.\n '''\n values = [grid[sample[0]], grid[sample[1]], grid[sample[2]]]\n if values[0] == values[1] == values[2] and values[0] != 0:\n return (values[0])\n return (None)\n\n\ndef pickPlay(sample, grid):\n '''\n Picks the open space in a given sample. Ex: row.\n '''\n values = [grid[sample[0]], grid[sample[1]], grid[sample[2]]]\n if values.count(0) == 1:\n index = values.index(0)\n del values[index]\n if values[0] == values[1]:\n return (values[0], sample[index])\n return (None, None)\n\n\ndef gameOver(grid):\n '''\n Checks to see if the Game is Over.\n either by tie or win.\n \n if None => 0\n if 1 Win => 1\n if 2 Win => 2\n if Tie => -1\n '''\n values = filter(lambda a: a != None, mapGrid(pickGameOver, grid))\n if len(values) == 0:\n values = [0]\n if sum(grid) >= 13: # Get empty spaces\n values = [-1]\n assert values.count(values[0]) == len(values)\n return values[0]\n\n\n# * * * * * * * * * * * * * * *\n# * Player Movement Functions *\n# * * * * * * * * * * * * * * *\ndef swapPlayer(n):\n '''\n Return 1 or 2 based on input of 2 or 1.\n \n Use a dictionary or subtract from three.\n '''\n if n == 1:\n return 2\n else: # n == 2:\n return 1\n\n\ndef getMove(n, grid, players, error=None):\n '''\n Get a move from the specified player,\n check and make sure it is a valid move.\n '''\n assert (n == 1) or (n == 2)\n move = players[n].getMove(grid, error)\n count = 0\n if move not in grid.getEmptySpaces():\n move = getMove(n, grid, players, move)\n return move\n\n\ndef pickOne(list):\n '''\n Picks one.\n First: a[0], last: a[-1], random: r(0, len(a) - 1)\n '''\n from random import randint as r\n return list[r(0, len(list) - 1)]\n\n\n# * * * * * * * * * * * * * * * * *\n# * Player Finalization Handlers *\n# * * * * * * * * * * * * * * * * *\ndef handleGameOver(a, b, index, players):\n '''\n Call end game handler for players.\n '''\n assert (index == 1) or (index == 2)\n players[index].handleGameOver(a, b)\n\n\ndef quantifyResult(winner, index):\n '''\n Should return the matching value for win, lose and draw for\n both players based on the winner matching index.\n '''\n if winner == -1: # draw\n return AIADJUST[index - 1]['draw']\n elif (winner == index): # win\n return AIADJUST[index - 1]['win']\n else: # loss\n return AIADJUST[index - 1]['lose']\n\n\ndef adjustAI(winner, gamegrids, index, aidata):\n '''\n Function used by Learning Comp to learn.\n '''\n DEBUGFUNC = 0\n #assert gameOver(gamegrids.pop()[0])[0] != 0\n k = quantifyResult(winner, index)\n if DEBUG or DEBUGFUNC:\n printGameGrids(gamegrids)\n while len(gamegrids) > 0:\n grid, move, g = gamegrids.pop() # AI move\n if DEBUG or DEBUGFUNC:\n print \"grid, move, g, index\", grid, move, g, index\n printXO(grid)\n maxgrid, translation = Translate.GridMax(grid)\n if maxgrid in aidata:\n scores = aidata[maxgrid]\n translatedscores = Translate.GridReverse(scores, translation)\n else:\n translatedscores = scores = aidata[maxgrid] = \\\n Grid([0, 0, 0, 0, 0, 0, 0, 0, 0])\n #raise Exception(\"newgrid not in data\")\n if len(gamegrids) > 2:\n l = AIADJUST[index - 1]['last']\n else:\n l = 1\n\n translatedscores[move] += k * l\n adjustedscores = Translate.Grid(translatedscores, translation)\n aidata[maxgrid] = adjustedscores\n if DEBUG or DEBUGFUNC:\n print \"*\" * 30\n printEighteen(maxgrid.returnXO(), translatedscores)\n printEighteen(grid.returnXO(), scores)\n printEighteen(grid.returnXO(), adjustedscores)\n if DEBUG or DEBUGFUNC:\n print \"AI win\\n\\t winner: \", winner,\n print \"\\n\\t gamegrids: \", gamegrids, \"\\n\\t grid: \", grid,\n print \"\\n\\t move: \", move, \"\\n\\t scores: \", scores,\n print \"\\n\\t adjustedscores: \", adjustedscores,\n print \"\\n\\t index: \", index, \"\\n\\t scores[move]: \", scores[move],\n print \"\\n\\t l*k (change): \", l * k,\n print \"\\n\\t aidata[grid]: \", aidata[maxgrid]\n\n\n# * * * * * * * * * * * * *\n# * Print Game Functions *\n# * * * * * * * * * * * * *\ndef pushGame(b, a):\n '''\n Add a completed game to the stack.\n '''\n b.reverse()\n b.append(a)\n b.reverse()\n if len(b) > NUMBERLASTGAMES:\n b.pop()\n return b\n\n\ndef printGames(games):\n '''\n Print the final representation for each game.\n '''\n for game in games:\n printGameGrids(game)\n\n\n# * * * * * * * * * * * * *\n# * Statistical Functions *\n# * * * * * * * * * * * * *\ndef pushStats(b, a):\n '''\n Add a item to the stack. \n '''\n b.reverse()\n b.append(a)\n b.reverse()\n if len(b) > NUMBERLASTGAMES:\n b.pop()\n return b\n\n\ndef printStats(a):\n '''\n Print the recorded statistical result.\n '''\n b = a[0]\n c = a[1]\n d = a[2]\n e = a[3]\n f = b + c + d\n if f > 0:\n print \"Success for O\"\n print \"\\twins:\\t%i\\t%f%%\" % (c, (c * 100.) / f)\n print \"\\tloses:\\t%i\\t%f%%\" % (b, (b * 100.) / f)\n print \"\\tties:\\t%i\\t%f%%\" % (d, (d * 100.) / f)\n b = e.count(1)\n c = e.count(2)\n d = e.count(-1)\n f = b + c + d\n print \"Last %i games:\" % (NUMBERLASTGAMES)\n print \"\\twins:\\t%i\\t%f%%\" % (c, (c * 100.) / f)\n print \"\\tloses:\\t%i\\t%f%%\" % (b, (b * 100.) / f)\n print \"\\tties:\\t%i\\t%f%%\" % (d, (d * 100.) / f)\n\n\ndef analyzeStats(a, b):\n '''\n Add a piece of information.\n ''' \n if a == 1:\n b[0] += 1\n elif a == 2:\n b[1] += 1\n elif a == -1:\n b[2] += 1\n else:\n \"Winner not -1, 1, or 2\\n\\tWinner: \", winner\n raise IndexError\n b[3] = pushStats(b[3], a)\n\n\n# * * * * * * * * * * * * * *\n# * File Control Functions *\n# * * * * * * * * * * * * * *\n\n# * * * * *\n# * Main *\n# * * * * *\ndef play(players, statdata, games, On, **settings):\n grid = Grid()\n winner = 0\n gamegrids = []\n player = 1\n while winner == 0:\n move = getMove(player, grid, players)\n gamegrids.append((grid[:], move, player))\n grid[move] = player\n player = swapPlayer(player)\n winner = gameOver(grid)\n gamegrids.append((grid[:], move, player))\n analyzeStats(winner, statdata)\n pushGame(games, gamegrids)\n if On('gamegrids'):\n printGameGrids(gamegrids)\n if On('checkdata'):\n # Doesn't work\n copy = dict([(key, aidata[key]) for key in aidata.keys()])\n for index in [1, 2]:\n handleGameOver(winner, gamegrids[:], index, players)\n if On('checkdata'):\n printGameGridsValues(gamegrids, copy)\n printGameGridsValues(gamegrids, aidata)\n\n\ndef main(players, **settings):\n def On(key):\n return key in settings and settings[key] != 0\n if On('timers'):\n timer2 = Timer()\n #printAIData(aidata)\n statdata = [0, 0, 0, []]\n games = []\n if On('times'):\n print \"Running\", (settings['times']), \"games\"\n if On('progressbar'):\n bar = ProgressProcess(settings['times'], settings['progressbar'])\n #bar.setNewline()\n if On('timers'):\n timer = Timer(settings['times'])\n try:\n if On('times'):\n for a in range(0, settings['times']):\n play(players, statdata, games, On)\n if On('progressbar'):\n bar.update(a)\n if On('progressbar'):\n bar.success()\n #del bar\n else:\n while (1):\n play(players, statdata, games, On, **settings)\n except UserError:\n print \"\\nUser quit.\"\n except KeyboardInterrupt:\n print\n if On('timers'):\n timer.setItter(a)\n except:\n if On('timers'):\n timer.setItter(a)\n handleError()\n finally:\n if On('times'):\n print \"Ran\", a + 1, \" times.\"\n if On('timers'):\n del timer\n if On('lastfifteen'):\n printGames(games)\n if On('stats'):\n printStats(statdata)\n #printAIData(aidata)\n\n\nif __name__ == \"__main__\":\n players = [None, CompLearning(1, filename='data', record=1), CompTwo(2)]\n #players = [None, CompTree(1, filename='datatree', record=0), CompTwo(2)]\n #players = [None, CompTree(1, filename='datatree', record=1), Human(2)]\n #players = [None, CompTwo(1), Human(2)]\n #players = [None, CompLearning(1, filename='data', record=1), Human(2)]\n # {'record': 1, 'stats': 1, 'lastfifteen': 1, 'timers': 1, \\\n # 'times': 100, 'progressbar': 50, 'gamegrids': 1, 'checkdata': 1}\n #main(players, stats=1, lastfifteen=1)\n #main(players, times=4, progressbar=60, lastfifteen=1)\n main(players, times=50, progressbar=64, timers=1, lastfifteen=1, stats=1)\n #main([None, CompTwo(1), HumanNumber(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":2013,"string":"2,013"}}},{"rowIdx":41354,"cells":{"__id__":{"kind":"number","value":14748917715700,"string":"14,748,917,715,700"},"blob_id":{"kind":"string","value":"f385aeed5c07316600c3700061a76f8fde7c70d6"},"directory_id":{"kind":"string","value":"85dacb6b7d3c13fe3d8c84cbdf983faa0113b9a8"},"path":{"kind":"string","value":"/metrics/workers/logger.py"},"content_id":{"kind":"string","value":"cec338564297f614c539037ee1156d9d35bc5a34"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"jjcorrea/kanban-metrics"},"repo_url":{"kind":"string","value":"https://github.com/jjcorrea/kanban-metrics"},"snapshot_id":{"kind":"string","value":"b6a95b2e21e71bdd4b9b60d75bdfbaef7adf4d09"},"revision_id":{"kind":"string","value":"1f3de7ce947522f2681f2166bbfb0da605a69531"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-06-06T10:28:16.216758","string":"2020-06-06T10:28:16.216758"},"revision_date":{"kind":"timestamp","value":"2014-01-17T19:57:16","string":"2014-01-17T19:57:16"},"committer_date":{"kind":"timestamp","value":"2014-01-17T19:57:16","string":"2014-01-17T19:57:16"},"github_id":{"kind":"number","value":10921918,"string":"10,921,918"},"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'''\nA duummy Snapshot worker (for now)\n'''\n\nfrom time import mktime\nfrom datetime import datetime\nimport time\nimport config\nimport re\nimport sys\nfrom logging import *\n\nBLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)\n\n#The background is set with 40 plus the number of the color, and the foreground with 30\n\n#These are the sequences need to get colored ouput\nRESET_SEQ = \"\\033[0m\"\nCOLOR_SEQ = \"\\033[1;%dm\"\nBOLD_SEQ = \"\\033[1m\"\n\ndef formatter_message(message, use_color = True):\n if use_color:\n message = message.replace(\"$RESET\", RESET_SEQ).replace(\"$BOLD\", BOLD_SEQ)\n else:\n message = message.replace(\"$RESET\", \"\").replace(\"$BOLD\", \"\")\n return message\n\nCOLORS = {\n 'WARNING': YELLOW,\n 'INFO': WHITE,\n 'DEBUG': BLUE,\n 'CRITICAL': YELLOW,\n 'ERROR': RED\n}\n\nclass Logger(object):\n def __enter__(self):\n basicConfig(level=INFO)\n self.logger = getLogger(__name__)\n return self.logger\n \n def __exit__(self, type, value, traceback):\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":41355,"cells":{"__id__":{"kind":"number","value":4853313085327,"string":"4,853,313,085,327"},"blob_id":{"kind":"string","value":"7f3720a812532e9cc1fc71f7087f2e383f860008"},"directory_id":{"kind":"string","value":"dcb400547b4cf8328c1f29c89f24ae52e68a7953"},"path":{"kind":"string","value":"/urls.py"},"content_id":{"kind":"string","value":"fa0acb5811b22e3e082e2f1fed46726b859d62e1"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"PlumpMath/blogstrap"},"repo_url":{"kind":"string","value":"https://github.com/PlumpMath/blogstrap"},"snapshot_id":{"kind":"string","value":"49a0397077ea822547f0ac5a2366dded612ed694"},"revision_id":{"kind":"string","value":"90e78f651b11e706dc022e86035db4b2f2a7f0b5"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T20:24:16.100875","string":"2021-01-18T20:24:16.100875"},"revision_date":{"kind":"timestamp","value":"2011-10-19T04:39:54","string":"2011-10-19T04:39:54"},"committer_date":{"kind":"timestamp","value":"2011-10-19T04:39:54","string":"2011-10-19T04:39: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":"from django.conf.urls.defaults import *\nfrom django.conf import settings\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^$', 'blog.views.index', name=\"index\"),\n url(r'^(?P\\w+)/$', 'blog.views.post', name=\"view_post\"),\n (r'^site-admin/', include(admin.site.urls)),\n (r'^static/(?P.*)$', 'django.views.static.serve',\n {'document_root': settings.STATIC_ROOT}),\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":41356,"cells":{"__id__":{"kind":"number","value":10823317623323,"string":"10,823,317,623,323"},"blob_id":{"kind":"string","value":"27c14a5ba34ec709ad081b19eea821e33d3c50ca"},"directory_id":{"kind":"string","value":"f194f42b6120b8a91e596371b493170565564467"},"path":{"kind":"string","value":"/intranet/apps/post/models.py"},"content_id":{"kind":"string","value":"c4bf2dfe119d780d84891a3e3a0f7c683f686adf"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"milovtim/django-intranet"},"repo_url":{"kind":"string","value":"https://github.com/milovtim/django-intranet"},"snapshot_id":{"kind":"string","value":"b67e79219571f4ed1214365131a1c5d0024069be"},"revision_id":{"kind":"string","value":"354b5633d9fc0c0cd584f465c664445c35a29e2a"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2015-08-18T00:09:04.734105","string":"2015-08-18T00:09:04.734105"},"revision_date":{"kind":"timestamp","value":"2014-12-11T18:35:53","string":"2014-12-11T18:35:53"},"committer_date":{"kind":"timestamp","value":"2014-12-11T18:35:53","string":"2014-12-11T18:35:53"},"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.db import models\n\n# рубрика\nclass Rubric(models.Model):\n title = models.CharField(\n max_length=255,\n default='',\n verbose_name=u'Название'\n )\n description = models.TextField(\n max_length=500,\n default='',\n blank=True,\n verbose_name=u'Описание'\n )\n display = models.SmallIntegerField(\n max_length=1,\n default=1\n )\n date_update = models.DateTimeField(\n auto_now=True,\n default='0000-00-00 00:00:00'\n )\n date_create = models.DateTimeField(\n auto_now_add=True,\n default='0000-00-00 00:00:00'\n )\n\n class Meta:\n ordering = ['title']\n\n def get_absolute_url(self):\n pass\n\n def __unicode__(self):\n return self.title\n\n# пост\nclass Post(models.Model):\n title = models.CharField(\n max_length=255,\n default='',\n verbose_name=u'Название'\n )\n description = models.TextField(\n max_length=500,\n default='',\n blank=True,\n verbose_name=u'Описание'\n )\n text = models.TextField(\n verbose_name=u'Текст'\n )\n display = models.SmallIntegerField(\n max_length=1,\n default=1\n )\n date_update = models.DateTimeField(\n auto_now=True,\n default='0000-00-00 00:00:00'\n )\n date_create = models.DateTimeField(\n auto_now_add=True,\n default='0000-00-00 00:00:00'\n )\n\n rubric = models.ForeignKey(Rubric, related_name='post_rubric', default=0)\n\n# комментарий\nclass Comment(models.Model):\n text = models.TextField(\n verbose_name=u'Текст'\n )\n display = models.SmallIntegerField(\n max_length=1,\n default=1\n )\n date_update = models.DateTimeField(\n auto_now=True,\n default='0000-00-00 00:00:00'\n )\n date_create = models.DateTimeField(\n auto_now_add=True,\n default='0000-00-00 00:00:00'\n )\n\n post = models.ForeignKey(Post, related_name='comment_post', default=0)"},"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":41357,"cells":{"__id__":{"kind":"number","value":1400159386075,"string":"1,400,159,386,075"},"blob_id":{"kind":"string","value":"17fe928659d51055fc7de56a47301fb19a01697e"},"directory_id":{"kind":"string","value":"9ace3e0388218e59560189e70cc90b9202ea1eed"},"path":{"kind":"string","value":"/matsci/gco.py"},"content_id":{"kind":"string","value":"fd40eb0bc07390aec246c47d9e9c6e3d4f283e6a"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"malloc47/matsciseg"},"repo_url":{"kind":"string","value":"https://github.com/malloc47/matsciseg"},"snapshot_id":{"kind":"string","value":"d5a1034830841d823069fcadea5ea8300ebbd7cc"},"revision_id":{"kind":"string","value":"b602b6ee267bc71bf6af9578880feb9b178639c4"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-19T11:02:43.636602","string":"2021-01-19T11:02:43.636602"},"revision_date":{"kind":"timestamp","value":"2014-02-26T05:37:07","string":"2014-02-26T05:37:07"},"committer_date":{"kind":"timestamp","value":"2014-02-26T05:37:07","string":"2014-02-26T05:37:07"},"github_id":{"kind":"number","value":9760990,"string":"9,760,990"},"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":"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":"# gco module\nimport sys,os,cv,cv2\nimport numpy as np\nimport gcoc\nimport scipy\nfrom scipy import ndimage\nfrom copy import deepcopy\nimport data, adj, label\nimport operator\nimport math\n\ndef smoothFn(s1,s2,l1,l2,adj):\n \"\"\"smoothness function that could be passed to the minimzation\"\"\"\n if l1==l2 :\n return 0\n if not adj :\n return 10000000\n return int(1.0/(max(float(s1),float(s2))+1.0) * 255.0)\n # return int(1.0/float((abs(float(s1)-float(s2)) if \\\n # abs(float(s1)-float(s2)) > 9 else 9)+1)*255.0)\n\ndef smoothFnSigma(s1,s2,l1,l2,adj,sigma):\n \"\"\"smoothness function that could be passed to the minimzation\"\"\"\n if l1==l2 :\n return 0\n if not adj :\n return 10000000\n return int(math.exp( -1 * (((float(s1)-float(s2))**2 )/(2*(float(sigma)**2)))) * 255.0)\n\ndef smoothFnSigmaMax(s1,s2,l1,l2,adj,sigma):\n \"\"\"smoothness function that could be passed to the minimzation\"\"\"\n if l1==l2 :\n return 0\n if not adj :\n return 10000000\n return int(math.exp( -1 * ((max(float(s1),float(s2))**2 )/(2*(float(sigma)**2)))) * 255.0)\n\ndef crop_box(a,box):\n (x0,y0,x1,y1) = box\n return a[y0:y1, x0:x1]\n\ndef candidate_point(p,q,r):\n new_q = tuple([ j-i for i,j in zip(p,q)])\n theta = math.atan2(*new_q[::-1])\n if theta < 0:\n theta += 2*math.pi\n return (int(r*math.cos(theta))+p[0],\n int(r*math.sin(theta))+p[1])\n\ndef estimate_size(c,labels):\n max_size = 50\n lower_size = 2\n fg = labels ==labels[c[0],c[1]]\n d = 1\n while True :\n circle = adj.circle((c[0],c[1],d),labels.shape)\n if np.sum(circle) > np.sum(np.logical_and(circle,fg)) or d >= max_size :\n break\n d = d+1\n if d > lower_size+1:\n return d-lower_size\n else:\n return d if d > lower_size-1 else lower_size\n \n\nclass Slice(object):\n def __init__(self, img, labels, shifted={}, \n win=(0,0), mask=None, lightweight=False,\n nodata=False, center=None, bg=False, adjin=None):\n \"\"\"initialize fields and compute defaults\"\"\"\n # These values are created when the class is instantiated.\n self.img = img.copy()\n if lightweight:\n self.labels = label.Label()\n self.labels.v = labels\n else:\n self.labels = label.Label(\n labels, \n boundary=(None if center is None else labels==0))\n # self.orig_labels = self.labels.copy()\n # self.num_labels = self.labels.max()+1\n if nodata:\n self.data = data.Data()\n else:\n self.data = data.Data(self.labels.v)\n # self.orig = self.data.copy() # potential slowdown\n if adjin is None:\n self.adj = adj.Adj(self.labels) # adjacent(self.labels)\n else:\n self.adj = adj.Adj()\n self.adj.v = adjin\n self.shifted=shifted\n self.win=win\n self.mask=mask\n self.center=center\n self.bg=bg\n\n @classmethod\n def load(cls,in_file):\n npz = np.load(in_file)\n c = cls(npz['img'], npz['label'], nodata=True, lightweight=True, adjin=npz['adj'])\n c.data.regions = data.unstack_matrix(npz['data'])\n return c\n\n def save(self,out):\n img,label,data,adj = self.dump()\n np.savez(out,img=img,label=label,data=data,adj=adj)\n\n def dump(self):\n return (self.img,self.labels.v,data.stack_matrix(self.data.regions),self.adj.v)\n\n def edit_labels_gui(self,d):\n import gui\n while True:\n print(\"Starting GUI\")\n w=gui.Window(self.img,self.labels.v)\n create = [(a,b,c,d) for a,b,c in w.create_list]\n remove=w.remove_list\n self.process_annotations(create,remove)\n if not create and not remove:\n break\n\n def edit_labels(self,addition=[],auto=[],removal=[],line=[]):\n removal = set([self.labels.v[(a,b)] for a,b in removal])\n self.process_annotations(create=addition,auto=auto,remove=removal,line=line)\n\n def process_annotations(self,create=[],auto=[],remove=[],line=[]):\n new_volumes = []\n # print(str(auto))\n for r in remove:\n (x0,y0,x1,y1) = label.fit_region(self.labels.create_mask([r]))\n new_volumes.append(self.remove_label(r,max(x1-x0,y1-y0)+5))\n for c in create:\n new_volumes.append(self.add_label_circle(c))\n for t in auto:\n new_volumes.append(self.add_label_circle_auto(t))\n for l in line:\n new_volumes.append(self.add_label_line(l))\n for v in new_volumes:\n self.merge(v)\n self.__init__(self.img\n , self.labels.v\n , self.shifted\n , self.win\n , self.mask\n , lightweight=True\n , nodata=True\n , center=getattr(self,'center',None))\n\n# lut = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,1,1,0,0]\n def clique_swap(self,d,f=None):\n # print(\"start: \" + str(self.energy()))\n for l in range(0,self.labels.max()):\n v = self.crop([l])\n if v is None:\n continue\n if not f is None and f(v):\n print('skipping ' + str(v.center))\n continue\n # v.data.dilate(d)\n if(d>0):\n v.data.dilate_fixed_center(d, rel_size=0.1, min_size=15)\n v.data.label_exclusive(0, v.labels.v == 0)\n v.data.pixels_exclusive(\n v.labels.region_outline()\n # + [(i,j,l) for (i,j,l) in v.labels.centers_of_mass() if l > 0]\n )\n v.graph_cut(1,lite=False)\n self.merge(v)\n # print(str(self.energy()))\n return self.labels.v\n\n def local_adj(self):\n return [ self.crop([l]).adj for l in range(0,self.labels.max()) ]\n\n def local(self):\n return [ (self.crop([l]),l) for l in range(0,self.labels.max()) ]\n\n def remove_label_dilation(self,l,d):\n \"\"\"removal that uses a large dilation to (hopefully) remove\n the candidate region\"\"\"\n v = self.crop([l])\n v.data.dilate_all(d)\n shifted = v.rev_shift(l)\n v.data.regions[shifted] = v.labels.v==shifted\n v.data.label_inexclusive(v.labels.v==shifted,shifted)\n v.adj.set_adj_all()\n v.graph_cut(1,lite=True)\n return v\n\n def remove_label_old(self,l,d):\n \"\"\"removal that truly removes region\"\"\"\n v = self.crop([l])\n v.data.or_all(crop_box(data.select_region(self.labels.v,l),\n (v.win[1]\n , v.win[0]\n , v.win[1] + v.labels.v.shape[1]\n , v.win[0] + v.labels.v.shape[0])),\n skip=[0])\n new_l = (key for key,value in v.shifted.items() if value==l).next()\n v.data.label_erase(new_l)\n v.adj.set_adj_all()\n v.graph_cut(1)\n return v\n\n def remove_label(self,l,d):\n \"\"\"removal that truly removes region\"\"\"\n v = self.crop([l],[l])\n new_mask = crop_box(data.select_region(self.labels.v,l),\n (v.win[1]\n , v.win[0]\n , v.win[1] + v.labels.v.shape[1]\n , v.win[0] + v.labels.v.shape[0]))\n v.data.or_term(new_mask)\n v.adj.set_adj_all()\n v.graph_cut(1)\n return v\n\n def add_label_circle(self,p,crop=True):\n if crop:\n v = self.crop(list(self.adj.get_adj_radius(p,self.labels.v)))\n p = (p[0]-v.win[0],p[1]-v.win[1],p[2],p[3])\n else:\n v = self\n l = v.new_label_circle(p)\n v.data.label_exclusive(l,v.labels.v==l)\n # v.data.dilate_label(l,p[3])\n # directly set data term instead of dilating--matches gui\n v.data.regions[l] = adj.circle((p[0],p[1],p[2]+p[3]),v.labels.v.shape)\n v.data.label_exclusive(0,v.labels.v==0)\n v.adj.set_adj_label_all(l)\n v.graph_cut(1)\n return v\n\n def add_label_circle_auto(self,p,crop=True):\n if crop:\n v = self.crop(list(self.adj.get_adj_radius(p,self.labels.v)))\n p = (p[0]-v.win[0],p[1]-v.win[1],p[2],p[3])\n else:\n v = self\n d = estimate_size(p,v.labels.v)\n print('auto d : '+str(d))\n p = (p[0],p[1],d,2*d)\n l = v.new_label_circle(p)\n v.data.label_exclusive(l,v.labels.v==l)\n # v.data.dilate_label(l,p[3])\n # directly set data term instead of dilating--matches gui\n v.data.regions[l] = adj.circle((p[0],p[1],p[2]+p[3]),v.labels.v.shape)\n v.data.label_exclusive(0,v.labels.v==0)\n v.adj.set_adj_label_all(l)\n v.graph_cut(1)\n return v\n\n def add_label_line(self,p):\n line_img = data.line(p,self.labels.v.shape,p[4])\n v = self.crop(list(np.unique(self.labels.v[line_img])))\n p = (p[0]-v.win[0],p[1]-v.win[1],p[2]-v.win[0],p[3]-v.win[1],p[4],p[5])\n l = v.new_label_line(p)\n v.data.label_exclusive(l,v.labels.v==l)\n v.data.regions[l] = data.line(p,v.labels.v.shape,p[4]+p[5])\n v.data.label_exclusive(0,v.labels.v==0)\n v.adj.set_adj_label_all(l)\n v.graph_cut(1)\n return v\n\n def new_label_circle(self,p):\n new_label = self.labels.max()+1\n self.labels.v[adj.circle(p,self.labels.v.shape)] = new_label\n # reconstruct data term after adding label\n # todo: constructing these before this is useless work\n self.data = data.Data(self.labels.v)\n self.adj = adj.Adj(self.labels)\n return new_label\n\n def new_label_line(self,p):\n new_label = self.labels.max()+1\n self.labels.v[data.line(p,self.labels.v.shape,p[4])] = new_label\n self.data = data.Data(self.labels.v)\n self.adj = adj.Adj(self.labels)\n return new_label\n\n def new_dummy_label(self):\n new_label = self.labels.max()+1\n self.data.add_dummy_label()\n self.adj.set_adj_new()\n self.adj.set_adj_all()\n # self.adj.set_adj_label_all(new_label)\n return new_label\n\n def non_homeomorphic_remove(self,d,size):\n s = self.labels.sizes()\n # print(str([l for l in s if l < size]))\n for l in [ l for (l,s) in zip(range(len(s)),s) if s < size ]:\n v = self.remove_label_dilation(l,d)\n self.merge(v)\n\n def non_homeomorphic_yjunction(self, d=20, r1=1, r2=1, r3=7, corr=0.66,\n min_size=100, new_min_size=25):\n \"\"\"\n r1 = new point radius\n r2 = new point dilation\n r3 = distance from y-junction to place seed\n \"\"\"\n import pylab\n import matplotlib.cm as cm\n import matsci.gui\n\n def imshow(img):\n pylab.clf()\n pylab.imshow(img,cmap=cm.Greys_r)\n pylab.show()\n\n t = np.mean(self.img)*1.5\n print('Image mean: '+str(np.mean(self.img)))\n j = self.labels.junctions(r1)\n sizes = self.labels.sizes()\n final = []\n for (p,ls) in j:\n if min([sizes[s] for s in ls]) < min_size:\n continue\n v = self.crop(list(ls),extended=False)\n\n # pylab.clf()\n # pylab.imshow(\n # matsci.gui.color_jet(\n # matsci.gui.grey_to_rgb(v.img)\n # , v.labels.v))\n # pylab.hold(True)\n # p_shifted = tuple([ j-i for i,j in zip(v.win,p)])\n # pylab.plot([p_shifted[1]],[p_shifted[0]],'r.',markersize=d)\n\n candidates = [(x,y,l) for ((x,y),l) in v.yjunction_candidates(p,r3)]\n\n # print(str(candidates))\n # for c in candidates:\n # pylab.plot([c[1]],[c[0]],'g.',markersize=d)\n # for c in [(i,j,l) for (i,j,l) in \n # v.labels.centers_of_mass() if l > 0]:\n # pylab.plot([c[1]],[c[0]],'b.',markersize=d)\n\n # pylab.show()\n\n cuts = []\n for c in candidates:\n v2 = v.copy()\n new_l = v2.new_label_circle(c)\n v2.data.dilate(d)\n v2.data.pixels_exclusive([(i,j,l) for (i,j,l) in \n v2.labels.centers_of_mass() \n if l > 0 and v2.labels.v[i,j]==l])\n # v2.data.label_exclusive(new_l,adj.circle((c[0],c[1],r2),v2.labels.v.shape))\n # v2.data.regions[new_l] = adj.circle((c[0],c[1],d),v2.labels.v.shape)\n v2.data.label_exclusive(0,v2.labels.v==0)\n v2.adj.set_adj_label_all(new_l)\n\n # imshow(v2.data.output_data_term())\n\n v2.graph_cut(1)\n\n # new_l = v2.new_label_circle(c)\n # # v2.data.dilate_fixed_center(d, rel_size=0.1, min_size=15,first=False)\n # v2.data.dilate(d)\n # # v2.data.pixels_exclusive([(i,j,l) for (i,j,l) in \n # # v2.labels.centers_of_mass() if l > 0])\n # # v2.data.dilate_fixed_center(d, rel_size=0.1, min_size=15,first=False)\n # imshow(v2.data.output_data_term())\n # v2.data.regions[new_l] = adj.circle((c[0],c[1],r1+r2),v2.labels.v.shape)\n # imshow(v2.data.output_data_term())\n # v2.data.label_exclusive(new_l,adj.circle((c[0],c[1],r1),v2.labels.v.shape))\n # imshow(v2.data.output_data_term())\n # v2.data.label_exclusive(0,v2.labels.v==0)\n # imshow(v2.data.output_data_term())\n # v2.adj.set_adj_label_all(new_l)\n # v2.data.label_exclusive(0,v2.labels.v==0)\n # v2.graph_cut(1,lite=True)\n # v2.add_label_circle(c+(r2,),crop=False)\n if(np.count_nonzero(v2.labels.v == new_l) > new_min_size):\n # img2 = v2.img.copy()\n # img2[np.logical_not(label.binary_remove(v2.labels.v == new_l))] = 0\n # imshow(img2)\n score = v2.labels.region_boundary_intensity(v2.img,new_l,t)\n cuts += [(v2,score)]\n if cuts:\n best = max(cuts,key=operator.itemgetter(1))\n if best[1] > corr:\n print('Creating new region: '+str(best[1]))\n final += [best[0]]\n print('Number of new segments: '+str(len(final)))\n for f in final:\n self.merge(f)\n \n def yjunction_candidates(self,p,r):\n p_shifted = tuple([ j-i for i,j in zip(self.win,p)])\n return [ (candidate_point(p_shifted,(x,y),r),r)\n for x,y,l in self.labels.centers_of_mass() if l > 0 ]\n\n def rev_shift(self,l):\n return dict((v,k) for k,v in self.shifted.items())[l]\n\n def crop(self, label_list, blank=[], extended=True, padding=0, no_bg=False):\n \"\"\"fork off subwindow volume\"\"\"\n if extended:\n new_label_list = self.adj.get_adj(label_list)\n else:\n new_label_list = label_list\n # if len(new_label_list) < 2: # Regression warning: untested\n if len(new_label_list) < 1:\n return None\n mask = self.labels.create_mask(new_label_list)\n try:\n box = label.fit_region(mask, padding)\n except:\n return None\n # crop out everything with the given window\n mask_cropped = crop_box(mask,box)\n cropped_seed = crop_box(self.labels.v,box)\n new_img = crop_box(self.img,box)\n # transform seed img\n new_seed = np.zeros_like(cropped_seed)\n label_transform = {}\n new_label = 1\n for l in new_label_list:\n label_transform[new_label]=l\n # print(\"Shifting \"+str(l)+\" to \"+str(new_label))\n if not l in blank:\n new_seed[cropped_seed==l] = new_label\n new_label += 1\n else:\n new_seed[cropped_seed==l] = 0\n if no_bg:\n new_seed = label.small_filter(new_seed,0)\n # new_seed[np.logical_not(mask_cropped)] = 0\n return Slice(new_img\n , new_seed\n , label_transform\n , (box[1],box[0])\n , mask_cropped\n , lightweight=True\n , center = label_list[0] if len(label_list) < 2 else None)\n\n def merge(self,v):\n \"\"\"merge another subwindow volume into this volume\"\"\"\n u = self.labels.v[v.win[0]:v.win[0]+v.labels.v.shape[0],\n v.win[1]:v.win[1]+v.labels.v.shape[1]] # view into array\n new_label = self.labels.max()+1\n # herein lies the bug: a label might be eliminated\n old_labels = set(np.unique(v.labels.v))\n # bug propagates here\n shifted_labels = [v.shifted[x] \n for x in old_labels \n if x and x in v.shifted]\n\n # bug propagates here\n for l in [x for x in old_labels if x>0]:\n if l in v.shifted:\n # print(\"Shifting \"+str(l)+\" to \"+str(v.shifted[l]))\n u[np.logical_and(v.labels.v==l,v.mask)]=v.shifted[l]\n else:\n # print(\"Shifting \"+str(l)+\" to \"+str(new_label))\n u[v.labels.v==l]=new_label\n # self.adj.set_adj_new(shifted_labels)\n new_label+=1\n\n def alpha_expansion(self, dilation=10, mode=1, bias=1, iterations=5):\n for i in self.labels.list():\n print(str(i))\n v = self.crop([i], extended=False, padding=dilation+5)\n if v is None:\n print('Label '+str(i)+' is empty')\n continue\n if not ( (v.labels.v==0).any() or (v.labels.v==1).any() ):\n print('Label '+str(i)+' is empty')\n continue\n v.data.dilate_fixed_center(dilation, rel_size=0.1, min_size=2, \n first=True,single=True)\n v.graph_cut(mode=mode, bias=bias, tc_iter=iterations)\n v.mask = np.ones_like(v.data.regions[0])\n self.merge(v)\n\n def alpha_beta_swap(self, dilation=10, mode=1, bias=1):\n \"\"\"alpha-beta swap method, written in python and using existing\n crop/merge algorithm to carry it out in an efficient manner\"\"\"\n\n # def remove_bg(v):\n # labels = label.small_filter(v.labels.v,0)\n # return data.Data(v.labels.v)\n\n for i,j in [ (i,j) for i,j, in self.adj.pairs() if i>=0 and j>=0]:\n print(str((i,j)))\n v = self.crop([i,j], extended=False)\n v.adj.set_unadj_bg()\n v.data.dilate(dilation)\n v.data.convert_to_int16()\n v.graph_cut(mode=mode, bias=bias)\n # if max(label.num_components(output)) > 1:\n # print('Rerunning')\n # v = self.crop([i,j], extended=False, no_bg=True)\n # v.adj.set_unadj_bg()\n # v.data.dilate(dilation)\n # v.data.convert_to_int16()\n # v.graph_cut(mode=mode, bias=bias)\n self.merge(v)\n\n def energy(self,mode=0,bias=1,sigma=None,replace=None):\n v = type(self)(self.img,self.labels.v)\n # import code; code.interact(local=locals())\n if sigma is None:\n sigma = np.std(v.img) if mode > 2 else 10\n if replace is None:\n replace = 0 if (v.data.regions[0].dtype.kind == 'b') else -1\n output, energy = gcoc.graph_cut( v.data.matrix()\n # np.ones(self.data.regions[0].shape+(len(self.data.regions),),dtype=bool)\n , v.img\n , np.array(v.labels.v)\n , v.adj.v\n , v.data.length()\n , mode\n , sigma\n , bias\n , replace\n , 0 # no actual minimization\n )\n return energy\n\n def graph_cut(self,mode=0,lite=False,bias=1,sigma=None,replace=None, \\\n tc_iter=0, max_iter=1):\n \"\"\"run graph cut on this volume (mode specifies V(p,q) term\"\"\"\n # if self.win != (0,0):\n # self.output_data_term()\n # w=gui.Window(self.img,self.labels)\n\n # if not data.check_data_term(self.nndata.regions):\n # print(\"Not all pixels have a label\")\n # else:\n # print(\"All pixels have a label\")\n\n # print(\"region size: \" + str(self.img.shape))\n # print(\"min: \" + str(self.labels.v.min()))\n # print(\"max: \" + str(self.labels.v.max()))\n\n # print(str(self.data.matrix().shape))\n # print(str(self.img.shape))\n # print(str(np.array(self.labels.v).shape))\n # print(str(self.adj.v.shape))\n\n if sigma is None:\n sigma = np.std(self.img) if mode > 2 else 10\n\n # assume int if not bool\n if replace is None:\n replace = 0 if (self.data.regions[0].dtype.kind == 'b') else -1\n\n output, energy = gcoc.graph_cut(self.data.matrix()\n , self.img\n , np.array(self.labels.v)#.astype('int16')\n # , self.labels.v,\n , self.adj.v\n # , self.labels.max()+1 # todo: extract from data\n , self.data.length()\n , mode\n , sigma\n , bias\n , replace\n , max_iter\n )\n\n if tc_iter >= 1 and \\\n len(self.data.regions) == 2 and \\\n max(label.num_components(output,full=False)) > 1:\n\n sys.path.insert(0,'./pytopocut/')\n import topocut\n\n num_hole = label.num_components(output,full=False)[0] - 1\n num_comp = label.num_components(output,full=False)[1]\n num_iter = 0\n\n self.data.convert_to_x(data.bool_to_float) # topocut requires float\n\n while ((num_comp > 1 or num_hole > 0) and num_iter < tc_iter):\n num_iter += 1\n # print('running topocut iteration '+str(num_iter))\n\n # first round takes care of components reliably\n # without encountering a degenerate case\n # (non-stocastic)\n ubg, ufg, phi, num_comp, num_hole = \\\n topocut.topofix.fix(self.data.regions[0].astype('float64')\n , self.data.regions[1].astype('float64')\n , output,1,-1, stocastic=False)\n\n # # not 100% sure about this escape clause...\n # if (num_comp <= 1) and ( num_hole <= 0):\n # output = (phi < 0)\n # break\n\n # convert back to ints\n self.data.regions[0] = ubg.astype('int16')\n self.data.regions[1] = ufg.astype('int16')\n\n new_data = self.data.matrix()\n # make \"infinity\" value unused by setting it to max + 1\n output, energy = gcoc.graph_cut(new_data , self.img\n , np.array(self.labels.v) \n , self.adj.v , self.data.length() \n , mode , sigma , bias , new_data.max()+1)\n\n # second round takes care of holes with with\n # stochastic algorithm, since hole filling fails with\n # a non-stochastic process\n ubg, ufg, phi, num_comp, num_hole = \\\n topocut.topofix.fix(self.data.regions[0].astype('float64')\n , self.data.regions[1].astype('float64')\n , output,-1,0, stocastic=True)\n\n self.data.regions[0] = ubg.astype('int16')\n self.data.regions[1] = ufg.astype('int16')\n\n new_data = self.data.matrix()\n\n output, energy = gcoc.graph_cut(new_data , self.img\n , np.array(self.labels.v) \n , self.adj.v , self.data.length()\n , mode , sigma , bias , new_data.max()+1)\n\n num_hole = label.num_components(output,full=False)[0] - 1\n num_comp = label.num_components(output,full=False)[1]\n\n # ignore bg if mask is defined\n # if( (max(label.num_components(output,full=False)) > 1)\n # if self.mask is None else \n # (max(label.num_components(output,full=False)[1:]) > 1) ): # throwing a fit\n # print('ERROR: Inconsistent inter-segment topology')\n # fully reinitialize self (recompute adj, data, etc.)\n self.__init__(self.img\n , output\n , self.shifted\n , self.win\n , self.mask\n , lightweight=lite\n , nodata=lite\n , center=self.center)\n return self.labels.v\n # return output\n\n def copy(self):\n cp = Slice(self.img.copy()\n , self.labels.v.copy()\n , self.shifted\n , self.win\n , self.mask\n , lightweight=True\n , nodata=True\n , center=self.center\n , bg=self.bg)\n cp.data = self.data.copy()\n return cp\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":41358,"cells":{"__id__":{"kind":"number","value":5952824718592,"string":"5,952,824,718,592"},"blob_id":{"kind":"string","value":"2a086506a0f0e8eeaf648e9c67e7425339c7c03b"},"directory_id":{"kind":"string","value":"8a74cfada9444105b414c4d202440bab6a3752a7"},"path":{"kind":"string","value":"/Scraper/makebook.py"},"content_id":{"kind":"string","value":"e3aa341e5fbbc135a092398ca4d407e55d8cddc7"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"shawwwn/KRss"},"repo_url":{"kind":"string","value":"https://github.com/shawwwn/KRss"},"snapshot_id":{"kind":"string","value":"295e1179dcb2b82bd66c42451d81c3c5635108a5"},"revision_id":{"kind":"string","value":"0f7cc2326b70b19e2883a6667e7855d28fa4e6af"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T19:33:00.439807","string":"2016-09-06T19:33:00.439807"},"revision_date":{"kind":"timestamp","value":"2013-10-08T06:37:25","string":"2013-10-08T06:37:25"},"committer_date":{"kind":"timestamp","value":"2013-10-08T06:37:25","string":"2013-10-08T06:37:25"},"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__author__ = 'Administrator'\n\nimport codecs\nfrom django.template.loader import get_template\nfrom django.template import Template, Context\nfrom django.conf import settings\nsettings.configure(\n DEBUG = True,\n TEMPLATE_DEBUG = True,\n TEMPLATE_DIRS = ['../Template/']\n)\n\n\n#####################\n# CODE START #\n#####################\n\n# TODO: replace the hardcoded data\nnews1 = {'title': 'NEWS1', 'url': 'https://www.google.com/', 'content': '

TESTING ON GOOGLE

'}\nnews2 = {'title': 'NEWS2', 'url': 'http://www.baidu.com/', 'content': '

TESTING ON BAIDU

'}\nnews_list1 = [news1, news2]\nnews3 = {'title': 'NEWS3', 'url': 'http://www.weibo.com/', 'content': '

TESTING ON WEIBO

'\n '
a
b
c
d
e
'\n '
f
g
h
i
j
'\n 'k
l
m
n
o
p
'\n 'q
r
s
t
u
v
'\n 'w
x
y
z


'\n 'gagagagaga'}\nnews4 = {'title': 'NEWS4', 'url': 'http://www.msn.com/', 'content': '

TESTING ON MSN

'}\nnews_list2 = [news3, news4]\nfeeds_list = { 'feed1': news_list1, 'feed2': news_list2 }\n###############################\n\ndef makebook(feeds_list):\n t=get_template('Django_Template.html')\n c=Context({\n 'feed_list': feeds_list\n })\n html=t.render(c)\n #TODO: remove the print\n #print html\n\n fs=codecs.open('book.html', 'w', \"utf-8\")\n fs.write(html)\n fs.close()\n\n###############################\n#makebook(feeds_list)"},"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":41359,"cells":{"__id__":{"kind":"number","value":17772574700615,"string":"17,772,574,700,615"},"blob_id":{"kind":"string","value":"ba5ce303f4ac31a9e27e2aaeaff44a44c5acd9e9"},"directory_id":{"kind":"string","value":"f154db73fefbf7d6a0da7ad73348e97ff82763fe"},"path":{"kind":"string","value":"/asn3.py"},"content_id":{"kind":"string","value":"9b19a35392969a35fc352708a6633e7662c056d8"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Eisforinnovate/uwopythonprojects"},"repo_url":{"kind":"string","value":"https://github.com/Eisforinnovate/uwopythonprojects"},"snapshot_id":{"kind":"string","value":"fc7b166f54640f9ed0bda7bb23c4a610b1ce6af7"},"revision_id":{"kind":"string","value":"87a22dc208ec811250f055140b4b8e5cd2ac4734"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-30T14:28:34.325582","string":"2020-05-30T14:28:34.325582"},"revision_date":{"kind":"timestamp","value":"2014-06-24T00:07:38","string":"2014-06-24T00:07:38"},"committer_date":{"kind":"timestamp","value":"2014-06-24T00:07:38","string":"2014-06-24T00:07:38"},"github_id":{"kind":"number","value":21146449,"string":"21,146,449"},"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":"# -*- coding: utf-8 -*-\n#myself: Eric Dolan 250580207\n#worked with Brad Pawson and Michael Kaptanknc\n#Part 1: File I/O\n\ndef loaddata(filename) :\n \n #open CSV file with name filename & read contents\n #of file into a list of lists\n \n import csv\n \n reader = csv.reader(open(filename, 'r'))\n test_lists = []\n \n for r in reader:\n test_lists.append( [r[0],r[1],r[2],r[3],r[4],r[5]])\n return test_lists\n \ndef dat2arr(datalist) :\n\n #takes a list of lists and turns part of it into NumPy array\n #file in format [name, height(cm), weight(kg), \n #stake aversion, garlic aversion, reflectance, shiny, IS_VAMPIRE?]\n \n import numpy \n import scipy.io\n \n a = numpy.array(datalist)\n test_lists1 = a[:,1:5]\n b = test_lists1.astype(float)\n return b\n\n #When we convert to an array, we’ll drop the subject name,\n #and just convert the remaining entries. You should return a \n #2D NumPy array where each row corresponds to one subject, \n #and each column one measure.\n \n \ndef save_array(arr,fname) :\n\n #saves a 2D NumPy array arr to MATLABfile fname\n #with Python array arr stored as MATLAV array named vampire_array\n #First create a dictionary. Then add arr to the dictionary with \n #the key vampire_array. Then use scipy.io.savemat to save the dictionary \n #to a file.\n #First create a dictionary. Then add arr to the dictionary with the key \n #vampire_array. Then use scipy.io.savemat to save the dictionary to a file.\n \n import numpy, scipy.io\n dict_arr = {}\n dict_arr[\"vampire_array\"] = arr\n scipy.io.savemat('', mdict={'arr':arr})\n \n \n\n#Part 2: Analysis and Visualization \n###analyze it to see if we can find measures that are repeatably \n###(across the whole population) different for vampires and non-vampires.\n###Are vampires taller than non-vampires? More averse to garlic? etc\n\ndef column_stats(arr,col):\n import numpy \n import pylab\n \n #will return a list of summary statistics \n #(mean, min and max) for a particular column (col) in the array arr\n \n col_vampire = []\n col_normal= []\n \n #Creates two empty lists Vamp and Normal#\n \n for index, subject in enumerate(arr):\n if arr([index][7]) == 0.0:\n col_normal += [arr[index,col]]\n #Takes the numbers from the colum you choose and stores it in the normal list#\n else:\n col_vampire += [arr[index,col]]\n \n #Takes everything else and puts it in the Vamp list#\n \n vampires = numpy.array(col_vampire)\n normals = numpy.array(col_normal) \n \n #Turns the columns into arrays#\n \n vamps_mean = vampires.mean()\n vamps_min = vampires.min()\n vamps_max = vampires.max()\n norms_mean = normals.mean()\n norms_min = normals.min()\n norms_max = normals.max()\n \n #Calculates the mean, min and maxes of both lists#\n \n compare_cols = [[vamps_mean, vamps_min, vamps_max], [norms_mean, norms_min, norms_max]]\n \n return compare_cols\n #Creates a new list with the seperated mean min and maxes for both vamps and normal#\n\ndef hist_compare(arr,col):\n import pylab\n \n #plot the histogram of values for a particular column\"\n first = column_stats(arr, col)[0]\n second = column_stats(arr, col)[1]\n pylab.hist(first)\n pylab.hist(second)\n #Creates a histogram from the array and column#\n\ndef corr_columns(arr, column1, column2):\n \"computes the Pearson Correlation between columns column1 and column2 in arr\"\n import scipy.stats\n \n column_1 = arr[:,column1]\n column_2 = arr[:,column2]\n #Turns the columns into arrays#\n \n r_value = scipy.stats.pearsonr(column_1, column_2)\n #calcukates the pearson relation between the two columns#\n \n return r_value\n \n \ndef scatter_columns(arr, column1, column2):\n import pylab\n \n \"that will produce a scatterplot of column1 of arr against column2\"\n \n first_c = arr[:,][column1]\n second_c = arr[:,][column2]\n \n pylab.scatter(first_c, second_c)\n \n #truns the columns into arrays and thenturns them into a scater plot#\n\ndef is_vampire(row):\n \n #takes a 1-D array (row) of 6 measurements and returns a probability that the person with these measurements is a vampire\"\n probability = 0\n \n if row[4] >= 0.9 or row[2] <= 0.08999 or row [3] <= 0.39:\n probability = 0.001\n return probability\n \n #if row 4 is so or row 2 is so or row 3 is so the probablity is 0.001#\n \n if row[4] <= 0.7199 or row[2] >= 1.09 or row[3] >= 0.76:\n probability = 0.999\n return probability\n \n #if row 4 is so or row 2 is so or row 3 is so the probablity is 0.999#\n \n if 0.71999 < row[4] <0.9 and 0.39 < row[3] <= 0.57:\n probability = 0.001\n return probability\n \n #if row 4 is so or row 2 is so or row 3 is so the probablity is 0.001#\n \n if 0.71999 < row[4] < 0.9 and 0.08999 < row[2] <= 0.40:\n probability = 0.001\n return probability\n # if row 4 is so or row 2 is so or row 3 is so the probablity is 0.001#\n \n if 0.7199 < row[4] < 0.9:\n probability = 0.07\n return probability\n # if row 4 is so or row 2 is so or row 3 is so the probablity is 0.07#\n \ndef is_vampire2(row):\n \n probability = 0\n \n if row[4] >= 0.9 or row[2] <= 0.08999 or row[3] <= 0.39 or 1.48 <= row[5] <= 1.63:\n probability = 0.001\n return probability\n \n #if row 4 is so or row 2 is so or row 3 is so the probablity is 0.001#\n \n if row[4] <= 0.71999 or row [2] >= 1.09 or row[3] >= 0.76 or -0.66 <= row[5] <= -0.54:\n probability = 0.999\n return probability\n \n #if row 4 is so or row 2 is so or row 3 is so the probablity is 0.999\n \n if 0.71999 < row[4] < 0.9 and 0.39 < row[3] <= 0.57:\n probability = 0.001\n return probability\n \n if 0.71999 < row[4] < 0.9 and 0.08999 < row[2] <= 0.40:\n probability = 0.001\n return probability\n # if row 4 is so or row 2 is so or row 3 is so the probablity is 0.001\n \n if 0.71999 < row[4] <0.9:\n probability = 0.07\n return probability\n #if row 4 is so or row 2 is so or row 3 is so the probablity is 0.07\n \ndef log_likelihood(arr, vamp_function):\n import numpy \n \"compare the is_vampire() functions\"\n log_1 = 0\n #Initiates a counter#\n \n for row in arr:\n result = vamp_function(row)\n if row[6] == 1.0:\n log_1 += numpy.log(result)\n #logs the results if the person was a vampire and your results from your is_Vamp function to compare#\n \n else:\n log_1 += numpy.log(1-result)\n #If they are not a vampire it logs they were not does the opposite of the above line#\n \n return log_1"},"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":41360,"cells":{"__id__":{"kind":"number","value":14688788201783,"string":"14,688,788,201,783"},"blob_id":{"kind":"string","value":"e9db969661edd34140296bb5118be1377014e110"},"directory_id":{"kind":"string","value":"f757d4a62d6ff96a6e3d9da6f0388f93a94991fa"},"path":{"kind":"string","value":"/seaspider/spider3.py"},"content_id":{"kind":"string","value":"33831f7a913859ef29d7fb2d7fd7b93b37868dea"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"antoniobarros/atcg"},"repo_url":{"kind":"string","value":"https://github.com/antoniobarros/atcg"},"snapshot_id":{"kind":"string","value":"a170f4c6586df65f7415875d6371830269cc4062"},"revision_id":{"kind":"string","value":"1f371dee257037343bbedac0295fd80f1b3158b6"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-08-12T04:31:22.096235","string":"2016-08-12T04:31:22.096235"},"revision_date":{"kind":"timestamp","value":"2010-09-26T16:14:34","string":"2010-09-26T16:14:34"},"committer_date":{"kind":"timestamp","value":"2010-09-26T16:14:34","string":"2010-09-26T16:14:34"},"github_id":{"kind":"number","value":46048653,"string":"46,048,653"},"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# Copyright (c) 2008-2010 Shuzhao Li.\n#\n# Licensed under the MIT License.\n# Permission is hereby granted, free of charge, to any person\n# obtaining a copy of this software and associated documentation\n# files (the \"Software\"), to deal in the Software without\n# restriction, including without limitation the rights to use,\n# copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following\n# conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n# OTHER DEALINGS IN THE SOFTWARE.\n\n\n\n\"\"\"\nspider3.py\nThe annotator with MetaFishNet/SeaSpider, three options:\n [0] search homology in MetaFishNet sequences only\n (metabolic genes, from 5 fish genomces)\n [1] fish ontology,\n GO annotation by finding homologs in zebrafish then GO generic, locally\n [2] search NCBI remotely, no GO, descriptive only. \n\nUse:\npython spider3.py inputfile outputdir [annotation_option]\n\nNote:\nIf one only needs option [0] to map sequences to MetaFishNet, \nthe single file version, seaspider-lite.py should be used.\n\nSeaSpider needs support of sequence databases and a few MySQL databases \nto accomplish its tasks. The links to download databases are given at \nhttp://metafishnet.appspot.com .\nA shelved database is used to store data while spider3 is working.\n\n05/28/2010\nFully functional with BLAST ver 2.2.18. However, blastcl3 \nmay be deprecated in the latest BLAST.\nThe remote search option may need rewrite.\n\"\"\"\n\nimport sys, os, shelve\nfrom spider_functions import *\n\nBLAST_BATCH_SIZE = 200\n\nclass spider3:\n \"\"\"\n the annotation tool in SeaSpider\n \"\"\"\n def dispatcher(self, args):\n \"\"\"\n dispatcher subprogram according to args\n \"\"\"\n workplace_db = shelve.open(os.path.join(args[1], 'workplacedb.dat'),\n writeback=True)\n workplace_db['records'] = []\n records = workplace_db['records']\n alist = read_fasta(args[0])\n for item in alist:\n entry = work_entry(input_id=item[0], sequence=item[1])\n records.append(entry)\n \n if len(args) == 2 or args[2] == '0':\n self.mfnmap(records, args[1])\n elif args[2] == '1':\n self.fish_ontology(records, args[1])\n elif args[2] == '2':\n self.remote_desc(records, args[1])\n else:\n print \"annotation options should be one of [0, 1, 2].\"\n\n workplace_db.close()\n\n def mfnmap(self, shelve_list, outputdir):\n \"\"\"\n This option searches against the metabolic genes in MetaFishNet.\n Without GO analysis, mapping to Ensembl_id and descriptions.\n \"\"\"\n tmpt_input = os.path.join(outputdir, TMPT_IN)\n pcmd = path_blastall + ' -p blastn -d ' + metafishnet_seqdb \\\n + ' -i ' + tmpt_input + ' -e 1E-5 -m 7'\n \n worklist = [entry for entry in shelve_list if not entry.homolog]\n workdict = {}\n batchnum = int(len(worklist)/BLAST_BATCH_SIZE) + 1\n for ii in range(batchnum):\n ## process in batch of BLAST_BATCH_SIZE entries\n self.make_input(worklist[ii*BLAST_BATCH_SIZE:\n ii*BLAST_BATCH_SIZE+BLAST_BATCH_SIZE], tmpt_input)\n print \"processing metafishnet blast batch %d of %d\" %(ii+1, batchnum)\n dii = self.blast(pcmd)\n workdict.update(dii)\n \n dbc = MySQLdb.connect(user='guest', db=LOCAL_MFN_DB)\n cursor = dbc.cursor()\n print \"updating annotations from MetaFishNet database.......\"\n for entry in worklist:\n try:\n hit = workdict[entry.input_id][0]['Hit_accession']\n entry.homolog = hit\n entry.description = self.get_mfn_desc(cursor, hit)\n except (KeyError, IndexError):\n pass\n \n dbc.close()\n print \"Finished metafishnet search.\"\n \n out = open(os.path.join(outputdir, ANNOTATION_RESULT), 'w')\n unfound = []\n for entry in shelve_list:\n if entry.homolog:\n out.write(\"\\t\".join( [entry.input_id, entry.homolog, entry.description,\n ] ) + \"\\n\")\n else:\n unfound.append(entry.input_id)\n out.close()\n out = open(os.path.join(outputdir, 'unfound.txt'), 'w')\n out.write(\"\\n\".join(unfound) + \"\\n\")\n out.close()\n \n def fish_ontology(self, shelve_list, outputdir, m=True):\n \"\"\"\n hardwired process of doing fish gene ontology annotation\n follow zebrafish first, then generic GO\n note the seq_db and relational db are hard coded in this section!\n m for metabolic genelist output option.\n \"\"\"\n\n #out_log = open(os.path.joint(outputdir, SPIDER_LOG), 'a')\n tmpt_input = os.path.join(outputdir, TMPT_IN)\n \n #\n # zebrafish\n #\n pcmd = path_blastall + ' -p blastn -d ' + zebrafish_seqdb \\\n + ' -i ' + tmpt_input + ' -e 1E-5 -m 7'\n\n worklist = [entry for entry in shelve_list if not entry.raw_go_terms]\n workdict = {}\n batchnum = int(len(worklist)/BLAST_BATCH_SIZE) + 1\n for ii in range(batchnum):\n ## process in batch of BLAST_BATCH_SIZE entries\n self.make_input(worklist[ii*BLAST_BATCH_SIZE:\n ii*BLAST_BATCH_SIZE+BLAST_BATCH_SIZE], tmpt_input)\n print \"processing zebrafish blast batch %d of %d\" %(ii+1, batchnum)\n dii = self.blast(pcmd)\n workdict.update(dii)\n \n dbc = MySQLdb.connect(user='guest', db=LOCAL_ENSEMBL_DB)\n cursor = dbc.cursor()\n print \"updating annotations from database.......\"\n for entry in worklist:\n try:\n hit = workdict[entry.input_id][0]['Hit_accession']\n entry.homolog = hit\n returned_go = self.get_zebrafish_go(cursor, hit)\n entry.raw_go_terms = [x[0] for x in returned_go if x[0]]\n entry.description = self.get_zebrafish_desc(cursor, hit)\n except (KeyError, IndexError):\n pass\n \n dbc.close()\n print \"Finished zebrafish search.\"\n \n #\n # generic\n #\n pcmd = path_blastall + ' -p blastx -d ' + generic_seqdb \\\n + ' -i ' + tmpt_input + ' -e 1E-5 -m 7'\n\n worklist = [entry for entry in shelve_list if not entry.raw_go_terms]\n workdict = {}\n batchnum = int(len(worklist)/BLAST_BATCH_SIZE) + 1\n for ii in range(batchnum):\n ## process in batch of BLAST_BATCH_SIZE entries\n self.make_input(worklist[ii*BLAST_BATCH_SIZE: \n ii*BLAST_BATCH_SIZE+BLAST_BATCH_SIZE], tmpt_input)\n print \"processing generic_go blast batch %d of %d\" %(ii+1, batchnum)\n dii = self.blast(pcmd)\n workdict.update(dii)\n \n # local GO db connect for both raw_go and next step of collective results\n dbc = MySQLdb.connect(user='guest', db=LOCAL_GO_DB)\n cursor = dbc.cursor()\n print \"updating annotations from GO database.......\"\n for entry in worklist:\n try:\n hit = workdict[entry.input_id][0]['Hit_accession']\n entry.homolog = hit\n returned_go = self.get_generic_go(cursor, hit)\n entry.raw_go_terms = [x[0] for x in returned_go if x[0]]\n entry.description = self.get_go_desc(cursor, hit)\n except (KeyError, IndexError):\n pass\n \n print \"Finished generic GO seq db search.\"\n \n self.write_result(shelve_list, outputdir, cursor, m)\n dbc.close()\n\n\n def write_result(self, shelve_list, outputdir, cursor, m=True):\n \"\"\"\n export collective results; if m:\n also write a separate file for metabolic genes\n \"\"\"\n out = open(os.path.join(outputdir, ANNOTATION_RESULT), 'w')\n for entry in shelve_list:\n if entry.raw_go_terms:\n entry.go_analyze(cursor)# cursor already openned for LOCAL_GO_DB\n out.write(\"\\t\".join( [entry.input_id, entry.homolog, entry.description,\n \",\".join(entry.go_sleek_terms),\n \"$\".join(entry.go_sleek_desc)] ) + \"\\n\")\n out.close()\n print \"Wrote \", ANNOTATION_RESULT\n if m:\n out = open(os.path.join(outputdir, \"metabolic_genes\"), 'w')\n for entry in shelve_list:\n if entry.is_metabolic:\n out.write(\"\\t\".join( [entry.input_id, entry.homolog, entry.description,\n \",\".join(entry.go_sleek_terms),\n \"$\".join(entry.go_sleek_desc)] ) + \"\\n\")\n out.close()\n print \"Wrote \", \"metabolic_genes\"\n\n \n def remote_desc(self, shelve_list, outputdir):\n \"\"\"\n annotation by querying NCBI remotely;\n relaxed to E-value -5, no check_homology.\n !!Since blastcl3 is deprecated now, this function needs update!!\n \"\"\"\n tmpt_input = os.path.join(outputdir, TMPT_IN)\n pcmd = path_blastcl3 + ' -p blastn -d \"nr\" -i ' + tmpt_input \\\n + ' -e 1E-5 -v 5 -b 5 -m 7'\n \n workdict = {}\n batchnum = int(len(shelve_list)/BLAST_BATCH_SIZE) + 1\n for ii in range(batchnum):\n ## process in batch of BLAST_BATCH_SIZE entries\n self.make_input(shelve_list[ii*BLAST_BATCH_SIZE: \n ii*BLAST_BATCH_SIZE+BLAST_BATCH_SIZE], tmpt_input)\n print \"blasting batch %d of %d\" %(ii+1, batchnum)\n dii = self.blast(pcmd, False, True)\n workdict.update(dii)\n \n print \"Finished queries. Processing...\"\n for entry in shelve_list:\n try:\n hits = workdict[entry.input_id]\n for h in hits:\n if check_meaningful(h['Hit_def']):\n entry.homolog = h['Hit_accession']\n entry.description = h['Hit_def']\n entry.evalue = h['E_value']\n break\n except KeyError, IndexError:\n pass\n\n out = open(os.path.join(outputdir, ANNOTATION_RESULT), 'w')\n for entry in shelve_list:\n if entry.description:\n out.write(\"\\t\".join( [entry.input_id, entry.homolog,\n entry.description, entry.evalue] ) + \"\\n\")\n out.close()\n print \"Done.\"\n\n\n def make_input(self, entry_list, tmpt_input):\n \"\"\"\n write a temporary input file for blast\n \"\"\"\n t = open(tmpt_input, 'w')\n for entry in entry_list:\n t.write('>' + entry.input_id + '\\n' + entry.sequence + '\\n')\n t.close()\n\n def blast(self, pcmd, check_homology=True, cl3=False):\n \"\"\"\n this is a BLAST wrapper, run pcmd and return hits dict.\n cl3 uses old style xml, parsed differently\n \"\"\"\n p=Popen(pcmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n # use Popen.communicate() to avoid OS pipe buffer problems \n (blastxml, blasterr) = p.communicate()\n # if blastxml, check error in blast run\n if cl3:\n return mp.parse(blastxml, check_homology, True)\n else:\n return sp.parse(blastxml, check_homology, False)\n\n #\n # database functions for zebrafish and generic_go\n #\n\n def get_zebrafish_go(self, cursor, hit):\n \"\"\"\n get GO terms for hits from local ensembl (simplified) db\n \"\"\"\n query_templ = \"select gene_ontology_id from dre_go where ensembl_id='%s'\"\n cursor.execute(query_templ % hit)\n return cursor.fetchall()\n \n def get_zebrafish_desc(self, cursor, hit):\n \"\"\"find the description from local ensembl (simplified) db\"\"\"\n query_templ = \"select description from dre_desc where ensembl_id = '%s'\"\n cursor.execute(query_templ % hit)\n return cursor.fetchall()[0][0] or \"\"\n\n def get_mfn_desc(self, cursor, hit):\n \"\"\"find the description from MetaFishNet db\"\"\"\n query_templ = \"select description from gene where ensembl_id = '%s'\"\n cursor.execute(query_templ % hit)\n return cursor.fetchall()[0][0] or \"\"\n\n def get_generic_go(self, cursor, seq_id):\n \"\"\"find the GO terms by seq_id in local GO db\"\"\"\n # will make a temporary table to speed this up\n #\n query_templ = \"select term.acc from gene_product \\\n inner join gene_product_seq on (gene_product.id=gene_product_seq.gene_product_id) \\\n inner join seq on (seq.id=gene_product_seq.seq_id) \\\n inner join association on (gene_product.id=association.gene_product_id) \\\n inner join term on (association.term_id=term.id) \\\n where seq.id = %s\"\n cursor.execute(query_templ % seq_id)\n return cursor.fetchall()\n\n def get_go_desc(self, cursor, seq_id):\n \"\"\"find the seq.description by seq_id in local GO db\"\"\"\n query_templ = \"select description from seq where id = %s\"\n cursor.execute(query_templ % seq_id)\n return cursor.fetchall()[0][0] or \"\"\n\n\n\n\n\n\nif __name__ == \"__main__\":\n\n args = sys.argv\n if len(args) > 1:\n # got arguments, proceed\n args = sys.argv[1:]\n # [inputfile, outputdir, annotation_option]\n if os.path.exists(args[1]):\n print \"Output directory already exists! Please name a new one.\"\n \n else:\n os.mkdir(args[1])\n print \"Output directory created...\", args[1]\n \n spd = spider3()\n spd.dispatcher(args)\n\n else:\n print \"\"\"usage:\n python spider3.py inputfile outputdir [annotation_option]\n annotation_option should be one of [0, 1, 2]\n default is 0, for searching MetaFishNet sequences;\n 1 for new annotation based on zebrafish and GO; \n 2 for annotation via remote NCBI blast only\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":41361,"cells":{"__id__":{"kind":"number","value":1924145356026,"string":"1,924,145,356,026"},"blob_id":{"kind":"string","value":"f5fb2fcec2c7ad00c7526e52d19e4952e5aca9ab"},"directory_id":{"kind":"string","value":"907a867a7baeec60eaa4dc3efa28540c66606702"},"path":{"kind":"string","value":"/py/database.py"},"content_id":{"kind":"string","value":"4f6c5b1cfb79b021f310606b78d00d9d07a0341c"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"nijil/chaiproject"},"repo_url":{"kind":"string","value":"https://github.com/nijil/chaiproject"},"snapshot_id":{"kind":"string","value":"d6fb2b62bf395a0e35794d025c1575eb3764cce8"},"revision_id":{"kind":"string","value":"f41330bc9f053897f6bd94f9f4e4043f170101dd"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-11-30T13:36:52.068357","string":"2020-11-30T13:36:52.068357"},"revision_date":{"kind":"timestamp","value":"2011-11-14T07:58:01","string":"2011-11-14T07:58:01"},"committer_date":{"kind":"timestamp","value":"2011-11-14T07:58:01","string":"2011-11-14T07:58: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":"class Database:\n\tdef __init__(self):\n\t\t\"\"\"connect to db\"\"\"\n\t\timport sqlite3\n\t\timport conf\n\t\timport os\n\n\t\tdb_path = os.path.join(os.path.dirname(__file__), '../..', conf.db_path)\n\t\t\n\t\tself.conn = sqlite3.connect(db_path)\n\t\tself.cur = self.conn.cursor()\t\t\n\t\t\n\tdef sql(self, query, values=(), as_dict=None, debug=None):\n\t\t\"\"\"like webnotes.db.sql\"\"\"\n\t\tif debug:\n\t\t\tprint query.replace('?', '%s') % values\n\t\t\n\t\tself.cur.execute(query, values)\n\t\tres = self.cur.fetchall()\n\n\t\tif as_dict:\n\t\t\tout = []\n\t\t\tfor row in res:\n\t\t\t\td = {}\n\t\t\t\tfor idx, col in enumerate(self.cur.description):\n\t\t\t\t\td[col[0]] = row[idx]\n\t\t\t\tout.append(d)\n\t\t\treturn out\n\n\t\treturn res\n\tdef close(self):\n\t\t\"\"\"close connection\"\"\"\n\t\tself.conn.close()"},"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":41362,"cells":{"__id__":{"kind":"number","value":2997887192965,"string":"2,997,887,192,965"},"blob_id":{"kind":"string","value":"199d4ae5537d90b226d6810d06ef59d685c79368"},"directory_id":{"kind":"string","value":"24fd05add3cf4aa916ef7b79e3851029b1f822ad"},"path":{"kind":"string","value":"/bili/apps/eparser/eparser.py"},"content_id":{"kind":"string","value":"465f7b3fa11da23aad304bc3e8cef7d1cb906e1a"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"zbyufei/bili"},"repo_url":{"kind":"string","value":"https://github.com/zbyufei/bili"},"snapshot_id":{"kind":"string","value":"41ac72b216ff5670fa476bb95e8f00a9c700b7bd"},"revision_id":{"kind":"string","value":"7557eb42a06b11baaa9fe3147eab33945a2b82b5"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2018-01-07T08:23:47.776856","string":"2018-01-07T08:23:47.776856"},"revision_date":{"kind":"timestamp","value":"2013-05-21T17:21:50","string":"2013-05-21T17:21:50"},"committer_date":{"kind":"timestamp","value":"2013-05-21T17:21:50","string":"2013-05-21T17:21:50"},"github_id":{"kind":"number","value":10257917,"string":"10,257,917"},"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":"# -*- coding:utf-8 -*-\n'''\neshop parser\n'''\nfrom pyquery import PyQuery\n\n#from crawer import Crawer\n\nimport urllib \n__all__ = ['TmallParser', 'AmazonParser', 'get_parser', 'QueryException', \n 'PARSERS_DICT']\n\n\nclass QueryError(Exception):\n '''\n Raised when query failed\n '''\n pass\n\nclass BaseParser(object):\n '''\n Base parser\n '''\n\n\n\n def parse(self, name):\n '''\n Should be implemented\n '''\n pass\n\n @staticmethod\n def to_gbk(origin_str):\n '''\n encode the string in gbk charset\n '''\n# try:\n# # avoid the string is not in unicode\n# origin_str = origin_str.decode('utf8')\n# except Exception:\n# pass\n return origin_str.encode('gbk')\n\n\n @staticmethod\n def clean_price(price):\n '''\n return the clean price\n '''\n return price.strip(u' $¥¥')\n\n\n\nclass TmallParser(BaseParser):\n '''\n Parser for tmall\n '''\n HOST = 'http://list.tmall.com'\n SUFFIX = '/search_product.htm?q={q}&s={s}&sort=p'\n\n # The pyquery parse pattern\n PRICE_PATTERN = '.product-iWrap .productPrice em'\n HREF_PATTERN = '.product-iWrap .productImg-wrap a'\n IMG_PATTERN = '.product-iWrap .productImg-wrap a img'\n def __init__(self):\n self.host = TmallParser.HOST\n\n def parse(self, name):\n name = urllib.quote(BaseParser.to_gbk(name))\n url = self.host + TmallParser.SUFFIX.format(q=name, s=0)\n\n try:\n dom = PyQuery(url=url)\n except Exception as e:\n raise QueryError(e.message)\n return {'price':\n BaseParser.clean_price(dom(TmallParser.PRICE_PATTERN)[0].text),\n 'img':\n dom(TmallParser.IMG_PATTERN)[0].attrib['data-ks-lazyload'],\n 'href':\n dom(TmallParser.HREF_PATTERN)[0].attrib['href'],\n }\n\n\nclass AmazonParser(BaseParser):\n '''\n Parser for amazon.cn\n '''\n HOST = 'http://www.amazon.cn'\n SUFFIX = '/s?ie=UTF8&page=1&rh=i%3Aaps%2Ck%3A{q}'\n #SUFFIX = '/mn/search/ajax/ref=nb_sb_noss?field-keywords={q}'\n\n DEFAULT_HEADERS = [\n ('Host', 'www.amazon.cn'),\n ('User-Agent', 'Mozilla/5.0 (X11; Linux x86_64) \\\n AppleWebKit/537.17 (KHTML, like Gecko) \\\n Chrome/24.0.1312.56 Safari/537.17'),\n ]\n\n PRICE_PATTERN = '#result_0 .newPrice span'\n IMG_PATTERN = '#result_0 .productImage img'\n HREF_PATTERN = '#result_0 .productImage a'\n\n def __init__(self):\n self.host = AmazonParser.HOST\n\n def parse(self, name):\n url = self.host + AmazonParser.SUFFIX.format(q=name.encode('utf8'))\n opener = urllib.URLopener()\n for key, value in AmazonParser.DEFAULT_HEADERS:\n opener.addheader(key, value)\n\n try:\n dom = PyQuery(url=url, opener=opener.open)\n except Exception as e:\n raise QueryError(e.message)\n return {'price' : \n BaseParser.clean_price(dom(AmazonParser.PRICE_PATTERN)[0].text),\n 'img':\n dom(AmazonParser.IMG_PATTERN)[0].attrib['src'],\n 'href':\n dom(AmazonParser.HREF_PATTERN)[0].attrib['href'],\n }\n\nPARSERS_DICT = {\n 'tmall' : TmallParser, \n 'amazon' : AmazonParser,\n}\n\ndef get_parser(name):\n try:\n return PARSERS_DICT[name.lower()]\n except KeyError:\n raise QueryError('parser %s not found' % name)\n\ndef parse(ename, keyword):\n '''\n search the specific keyword in specific eshop\n '''\n parser = get_parser(ename)()\n return parser.parse(keyword)\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":41363,"cells":{"__id__":{"kind":"number","value":15668040732595,"string":"15,668,040,732,595"},"blob_id":{"kind":"string","value":"06dec0403bd29ca3f283879948b2e1cfe3b19d07"},"directory_id":{"kind":"string","value":"9ca509dba31fe0b71e5fdb57485f3f1670fdcced"},"path":{"kind":"string","value":"/src/slim-wallpaper.py"},"content_id":{"kind":"string","value":"508924efa92bb0e5060b0d46c6a3a941027e95f3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"atheyus/slim-wallpaper"},"repo_url":{"kind":"string","value":"https://github.com/atheyus/slim-wallpaper"},"snapshot_id":{"kind":"string","value":"da8450a15ea98f61a00da4291d0c2bf8c8700b15"},"revision_id":{"kind":"string","value":"95d09fd704d7607c35baa5fa0d8ebef0afc0548c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-28T04:36:55.922473","string":"2020-05-28T04:36:55.922473"},"revision_date":{"kind":"timestamp","value":"2014-01-20T17:49:24","string":"2014-01-20T17:49:24"},"committer_date":{"kind":"timestamp","value":"2014-01-20T17:49:24","string":"2014-01-20T17:49:24"},"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 python2\n\n\nimport pygtk\npygtk.require('2.0')\nimport gtk\nimport re\nimport os.path\n\nconfiguracion = \"/etc/slim.conf\"\n\ndef tema(t):\n theme = open(t)\n for linea in theme:\n if re.search(\"current_theme.*\",linea):\n tema = linea.split()\n return tema[1]\n else:\n pass\n\ntema = tema(configuracion)\n\nimagen = \"/usr/share/slim/themes/%s/background\" %(tema)\n\nif os.path.exists(imagen + '.png'):\n imagen = imagen + '.png'; e = 'png'\nelif os.path.exists(imagen + '.jpeg'):\n imagen = imagen + '.jpeg'; e = 'jpeg'\nelse:\n os.path.exists(imagen + '.jpg')\n imagen = imagen + '.jpg'; e = 'jpg'\n\npath = \"/usr/share/slim/themes/%s/background.%s\" %(tema,e)\nnueva_imagen = ''\n\nclass Fondo():\n def __init__(self):\n self.ventana = gtk.Window(gtk.WINDOW_TOPLEVEL)\n self.ventana.set_position(gtk.WIN_POS_CENTER)\n self.ventana.set_default_size(300, 200)\n self.ventana.set_title('Slim Wallpaper')\n self.ventana.connect(\"destroy\", self.salir)\n self.ventana.set_resizable(False)\n self.im = gtk.Image()\n self.vbox = gtk.VBox(gtk.FALSE,0)\n self.hbox = gtk.HBox(gtk.FALSE,0)\n self.label = gtk.Label(\"Imagen: \")\n self.separador0 = gtk.HSeparator()\n self.separador1 = gtk.HSeparator()\n self.bsalir = gtk.Button(stock=gtk.STOCK_CLOSE)\n self.bimagen = gtk.Button(label=\"Selccionar Imagen Nueva\")\n self.aceptar = gtk.Button(stock=gtk.STOCK_APPLY)\n self.Imagen =gtk.Button(stock=gtk.STOCK_DELETE)\n self.colocar_imagen(imagen)\n self.bsalir.connect('clicked', self.salir)\n self.aceptar.connect('clicked', self.aplicar)\n self.bimagen.connect('clicked', self.abrir)\n self.hbox.pack_start(self.aceptar,gtk.FALSE,gtk.FALSE,10)\n self.hbox.pack_start(self.bimagen,gtk.FALSE,gtk.FALSE,10)\n self.hbox.pack_start(self.bsalir,gtk.FALSE,gtk.FALSE,10)\n self.vbox.pack_start(self.label,gtk.FALSE,gtk.FALSE,2)\n self.vbox.pack_start(self.separador0,gtk.FALSE,gtk.FALSE,2)\n self.vbox.pack_start(self.im,gtk.FALSE,gtk.FALSE,4)\n self.vbox.pack_start(self.separador1,gtk.FALSE,gtk.FALSE,0)\n self.vbox.pack_start(self.hbox,gtk.FALSE,gtk.FALSE,0)\n self.ventana.add(self.vbox)\n self.ventana.show_all()\n def abrir(self,action):\n dialogo = gtk.FileChooserDialog(\"Selecciona una imagen:\",\n self.ventana,\n gtk.FILE_CHOOSER_ACTION_OPEN,\n (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,\n gtk.STOCK_OPEN, gtk.RESPONSE_OK))\n dialogo.set_default_response(gtk.RESPONSE_OK)\n respuesta = dialogo.run()\n if respuesta == gtk.RESPONSE_OK:\n global imagen\n imagen = dialogo.get_filename()\n self.colocar_imagen(imagen)\n dialogo.destroy()\n\n def colocar_imagen(self,imagen):\n error = None\n try:\n self.pixbuf = gtk.gdk.pixbuf_new_from_file(imagen)\n self.scaled_buf = self.pixbuf.scale_simple(230,180,gtk.gdk.INTERP_BILINEAR)\n self.im.set_from_pixbuf(self.scaled_buf)\n except:\n error = gtk.MessageDialog(self.ventana,\n gtk.DIALOG_DESTROY_WITH_PARENT,\n gtk.MESSAGE_ERROR,\n gtk.BUTTONS_CLOSE,\n \"Error no se puede colocar %s:\" %\n (imagen))\n if error is not None:\n error.connect(\"response\", lambda w,resp: w.destroy())\n error.show()\n def aplicar(self,widget,data = None):\n orden = 'pkexec cp %s %s' %(imagen,path)\n os.system(orden)\n def salir(self,widget,data = None):\n gtk.main_quit()\n def main(self):\n gtk.main()\n\nif __name__ == \"__main__\":\n background = Fondo()\n background.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":41364,"cells":{"__id__":{"kind":"number","value":9534827408355,"string":"9,534,827,408,355"},"blob_id":{"kind":"string","value":"b17ae730d4376026a370ada563ecfaf0a87ca536"},"directory_id":{"kind":"string","value":"18b0a759feacbe909544f5716c9459e5e047caa1"},"path":{"kind":"string","value":"/assignments/week06/athome/djangoenv/bin/newsite/djangor/urls.py"},"content_id":{"kind":"string","value":"b15cf7e9a8d7a96e90cd641162c308edb81b1c0b"},"detected_licenses":{"kind":"list like","value":["CC-BY-NC-SA-3.0"],"string":"[\n \"CC-BY-NC-SA-3.0\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"conordean/training.python_web"},"repo_url":{"kind":"string","value":"https://github.com/conordean/training.python_web"},"snapshot_id":{"kind":"string","value":"bd487756e20d6bd007893799d4aeb7684445a5d2"},"revision_id":{"kind":"string","value":"5f631bcc42908766343389a3d336ff316faeab05"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T10:42:21.635497","string":"2021-01-18T10:42:21.635497"},"revision_date":{"kind":"timestamp","value":"2013-02-21T23:17:12","string":"2013-02-21T23:17:12"},"committer_date":{"kind":"timestamp","value":"2013-02-21T23:17:12","string":"2013-02-21T23:17:12"},"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, url\nfrom django.http import HttpResponse\n\nfrom classlab.models import Poll\n\ndef stub(request, *args, **kwargs):\n return HttpResponse('stub view', mimetype=\"text/plain\")\n\nurlpatterns = patterns('djangor.views',\n (r\"\", \"main\"),\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":41365,"cells":{"__id__":{"kind":"number","value":352187331968,"string":"352,187,331,968"},"blob_id":{"kind":"string","value":"482718c64ed307100894d0a83e68d246f4f180b3"},"directory_id":{"kind":"string","value":"1e03806dd2428e23453424d26a749b4c32cc8fff"},"path":{"kind":"string","value":"/src/demo6.py"},"content_id":{"kind":"string","value":"0631899836e324e2d4c44e01afb8606542d16fc5"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"hleeldc/at"},"repo_url":{"kind":"string","value":"https://github.com/hleeldc/at"},"snapshot_id":{"kind":"string","value":"038c71b3cdb8a6e141133572a70ff7023fa95dac"},"revision_id":{"kind":"string","value":"2bba3ecb76ec370b2fe886822de344ce673f7eb9"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-07T12:46:28.322528","string":"2020-04-07T12:46:28.322528"},"revision_date":{"kind":"timestamp","value":"2014-05-05T01:03:58","string":"2014-05-05T01:03:58"},"committer_date":{"kind":"timestamp","value":"2014-05-05T01:03:58","string":"2014-05-05T01:03:58"},"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 at4 import TreeEdit, TreeModel\nfrom PyQt4 import QtGui\nimport sys\n\nif __name__ == \"__main__\":\n app = QtGui.QApplication(sys.argv)\n s = \"(S (NP (N I)) (VP1 (VP2 (V saw) (NP (ART the) (N man))) \" \\\n \"(PP (P with) (NP (ART a) (N telescope)))))\"\n root = TreeModel.importTreebank([s]).next()\n w = TreeEdit()\n w.setData(root)\n w.show()\n app.exec_()\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":41366,"cells":{"__id__":{"kind":"number","value":13606456424190,"string":"13,606,456,424,190"},"blob_id":{"kind":"string","value":"05b20bdd6daa9b444c105f475a70c691f5c29b50"},"directory_id":{"kind":"string","value":"29a580516018057e13841ffc22dcac9dae29eb58"},"path":{"kind":"string","value":"/blog/views.py"},"content_id":{"kind":"string","value":"a9ab24010d7fefd1acc84450e45071b466bc2446"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"lynx-r/django-threadedcomments-example"},"repo_url":{"kind":"string","value":"https://github.com/lynx-r/django-threadedcomments-example"},"snapshot_id":{"kind":"string","value":"5a8bbfa08e4a53c1be25c1f73cd79683ca647044"},"revision_id":{"kind":"string","value":"61a25006a5d7506e19928f9acb4a7544c87ad63c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-11T01:07:59.149366","string":"2016-09-11T01:07:59.149366"},"revision_date":{"kind":"timestamp","value":"2012-07-05T06:52:49","string":"2012-07-05T06:52:49"},"committer_date":{"kind":"timestamp","value":"2012-07-05T06:52:49","string":"2012-07-05T06:52:49"},"github_id":{"kind":"number","value":4859267,"string":"4,859,267"},"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":"bool","value":false,"string":"false"},"gha_event_created_at":{"kind":"timestamp","value":"2021-05-11T07:49:52","string":"2021-05-11T07:49:52"},"gha_created_at":{"kind":"timestamp","value":"2012-07-02T12:02:32","string":"2012-07-02T12:02:32"},"gha_updated_at":{"kind":"timestamp","value":"2014-12-31T22:28:21","string":"2014-12-31T22:28:21"},"gha_pushed_at":{"kind":"timestamp","value":"2021-05-11T07:49:52","string":"2021-05-11T07:49:52"},"gha_size":{"kind":"number","value":116,"string":"116"},"gha_stargazers_count":{"kind":"number","value":0,"string":"0"},"gha_forks_count":{"kind":"number","value":0,"string":"0"},"gha_open_issues_count":{"kind":"number","value":1,"string":"1"},"gha_language":{"kind":"string","value":"Python"},"gha_archived":{"kind":"bool","value":false,"string":"false"},"gha_disabled":{"kind":"bool","value":false,"string":"false"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n\nfrom django.views.generic import ListView, DetailView\n\nfrom models import *\n\n\nclass PostListView(ListView):\n model = Post\n context_object_name = 'posts'\n\n\nclass PostDetailView(DetailView):\n model = Post\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":41367,"cells":{"__id__":{"kind":"number","value":1554778167736,"string":"1,554,778,167,736"},"blob_id":{"kind":"string","value":"0fcb34334ac9f84cef5ace9783406ffbbb6307b6"},"directory_id":{"kind":"string","value":"12dba0886c81ee55934be626ad7e1147d01d7d51"},"path":{"kind":"string","value":"/projects/graph/mapOfScience/smaller-data/node.py"},"content_id":{"kind":"string","value":"3bbd659f362e7df69b2b5a6a2decdb9850264e49"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"xuezhizeng/visualizations"},"repo_url":{"kind":"string","value":"https://github.com/xuezhizeng/visualizations"},"snapshot_id":{"kind":"string","value":"428a4b6e5ca7291cba92748de40a600b377dee66"},"revision_id":{"kind":"string","value":"b14bb0dc0211dd0448b5b6c2cf69826756ded481"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-03-07T14:34:42.868318","string":"2020-03-07T14:34:42.868318"},"revision_date":{"kind":"timestamp","value":"2014-02-12T03:24:55","string":"2014-02-12T03:24:55"},"committer_date":{"kind":"timestamp","value":"2014-02-12T03:24:55","string":"2014-02-12T03:24:55"},"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 random\n\ncolors = [\n \"Blue\",\n \"OliveGreen\",\n \"Canary\",\n \"Peach\",\n \"Dandelion\",\n \"Mahogany\",\n \"Lavender\",\n #\"SkyBlue\",\n #\"MulBerry\",\n #\"BrickRed\",\n #\"Yellow\",\n #\"Emerald\",\n #\"Red\"\n ]\n \n\nclass Node(dict):\n\n def __init__(self, ID, name, x, y, xfact, yfact, color=None, isLabel=False):\n self[\"id\"] = ID\n self[\"name\"] = name\n self[\"x\"] = x\n self[\"y\"] = y\n self[\"xfact\"] = xfact\n self[\"yfact\"] = yfact\n self[\"color\"] = color if color is not None else RandomColor()\n self[\"group\"] = 1 if isLabel else 0\n\n\ndef RandomColor():\n return random.choice(colors)\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":41368,"cells":{"__id__":{"kind":"number","value":2765958973787,"string":"2,765,958,973,787"},"blob_id":{"kind":"string","value":"77e3f4b5ac9f5074d5fcbe31645ccced3ffa0cde"},"directory_id":{"kind":"string","value":"2756451f24c04a536877f94d3e422e21e8dc0182"},"path":{"kind":"string","value":"/ner.py"},"content_id":{"kind":"string","value":"72e19a1b3f39cd4ddf97fa08731dbb9cd3ea7da3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"jjyao/recbysns"},"repo_url":{"kind":"string","value":"https://github.com/jjyao/recbysns"},"snapshot_id":{"kind":"string","value":"412a96b0cf601bd9918e03195053ec2366f544fc"},"revision_id":{"kind":"string","value":"8eb6cf43669747097934d7c72249bffa101be6f3"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T06:09:17.969925","string":"2016-09-06T06:09:17.969925"},"revision_date":{"kind":"timestamp","value":"2014-07-21T09:58:53","string":"2014-07-21T09:58:53"},"committer_date":{"kind":"timestamp","value":"2014-07-21T09:58:53","string":"2014-07-21T09:58:53"},"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# coding=utf8\nimport re\nimport os\nimport operator\nimport numpy as np\nfrom sklearn import svm\nfrom sklearn import tree\nfrom sklearn import preprocessing\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.grid_search import GridSearchCV\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.cross_validation import StratifiedKFold\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom random import choice\nfrom random import shuffle\nfrom evaluator import Evaluator\nfrom consts import NER_BOOK, NER_MOVIE, NER_VIDEO, NER_OTHERS\n\n\nclass NEREntityAnalyzer(object):\n def __init__(self, recbysns):\n self.nlpir = recbysns.nlpir\n\n def __call__(self, entity):\n words = []\n session = entity.session()\n for segment in session:\n pos = self.nlpir.get_POS(segment)\n word = self.nlpir.get_word(segment)\n if pos[0] in [u'n', u'v'] and pos not in [u'vshi', u'vyou']:\n words.append(word)\n return words\n\n\nclass NEREntity(object):\n PERSON_ENTITY_PATTERNS = [(1, '', '', ''),\n (1, '', u'的', ''),\n (1, '', u' ', ''),\n (0, '', '', ''),\n (0, '', u',', '', 76),\n (0, '', u'作者', ''),\n (1, '', u' 的', ''),\n (0, '', u'(', ''),\n (1, '', u'在', ''),\n (1, '', u'老师的', ''),\n (1, '', u'签名', ''),\n (1, '', u'先生的', ''),\n (0, '', u'。', ''),\n (1, '', u'老师签名版', ''),\n (1, '', u'的新书', ''),\n (1, '', u'著', ''),\n (1, '', u'写的', ''),\n (0, '', u' ', ''),\n (1, '', u',', ''),\n (0, '', u'的', ''),\n (1, '', u'新作', ''),\n (1, '', u' 亲笔签名', ''),\n (1, '', u'主演的', ''),\n (1, '', u' 先生的', '')]\n\n def __init__(self, recbysns, entity):\n self.entity = entity\n self.recbysns = recbysns\n self.db = self.recbysns.db\n self.nlpir = self.recbysns.nlpir\n self._pos = None\n self._session = None\n self._ner_class = None\n self._persons = None\n self._title = None\n self._movie = None\n self._book = None\n self._features = None\n\n def pos(self):\n if self._pos is None:\n self._pos = self.nlpir.get_POS(self.entity['entity'])\n return self._pos\n\n def ner_class(self):\n if self._ner_class is None:\n if self.entity['type'] not in [NER_BOOK, NER_MOVIE, NER_VIDEO]:\n self.entity['type'] = NER_OTHERS\n self._ner_class = self.entity['type']\n return self._ner_class\n\n def session(self):\n \"\"\" session segments that the entity belongs to \"\"\"\n if self._session is None:\n status = self.db.select_weibo_status_by_id(\n self.entity['status_id'])\n sessions = self.nlpir.segment_weibo_status(status['text'])\n self._session = sessions[self.entity['session']]\n return list(self._session)\n\n def title(self):\n assert self.ner_class() != NER_VIDEO\n if self._title is None:\n self._title = re.match(u'《(.*?)》', self.nlpir.get_word(\n self.entity['entity'])).group(1)\n return self._title\n\n def movie(self):\n \"\"\" movie that has the same title as the entity \"\"\"\n if self._movie is None:\n self._movie = self.db.select_douban_movie_by_title(self.title())\n return self._movie\n\n def book(self):\n \"\"\" book that has the same title as the entity \"\"\"\n if self._book is None:\n self._book = self.db.select_douban_book_by_title(self.title())\n return self._book\n\n def persons(self):\n \"\"\" persons mentioned in the session that the entity belongs to \"\"\"\n if self._persons is None:\n session = self.session()\n movie = self.movie()\n book = self.book()\n entity_index = [index for index, segment in enumerate(session)\n if segment == self.entity['entity']][self.entity['position']]\n # person['book']: person is the author of the book\n # that has the same title as the entity\n # person['movie']: person is the actor or director of the movie\n # that has the same title as the entity\n # person['pattern']: person and the entity\n # match one of the PERSON_ENTITY_PATTERNS\n self._persons = [{'index': index,\n 'name': self.nlpir.get_word(segment),\n 'book': False, 'movie': False, 'pattern': False}\n for index, segment in enumerate(session)\n if self.nlpir.get_POS(segment) == 'nr']\n for person in self._persons:\n if book and book['pub'] and \\\n re.search(person['name'].strip('@'), book['pub']):\n person['book'] = True\n if movie and movie['pub'] and \\\n re.search(person['name'].strip('@'), movie['pub']):\n person['movie'] = True\n min_index = min(person['index'], entity_index)\n max_index = max(person['index'], entity_index)\n order = 1 if person['index'] < entity_index else 0\n start = min_index + 1\n end = max_index\n middle = self.nlpir.restore_text(session[start:end])\n start = min_index - 5 if min_index >= 5 else 0\n end = min_index\n prefix = self.nlpir.restore_text(session[start:end])\n start = max_index + 1\n end = start + 5\n suffix = self.nlpir.restore_text(session[start:end])\n for pattern in self.PERSON_ENTITY_PATTERNS:\n if pattern[0] == order and pattern[2] == middle and \\\n prefix.endswith(pattern[1]) and \\\n suffix.startswith(pattern[3]):\n person['pattern'] = True\n return self._persons\n\n def features(self):\n \"\"\" features used by classifiers \"\"\"\n assert self.ner_class() != NER_VIDEO\n if self._features is None:\n has_same_title_book = 0\n has_enough_book_raters = 0\n has_same_title_movie = 0\n has_enough_movie_raters = 0\n has_pattern_person = 0\n has_person_book = 0\n has_person_movie = 0\n persons = self.persons()\n book = self.book()\n movie = self.movie()\n for person in persons:\n if person['pattern'] is True:\n has_pattern_person = 1\n # TODO start with @ ?\n if person['movie']:\n has_person_movie = 1\n if person['book']:\n has_person_book = 1\n if movie:\n has_same_title_movie = 1\n if movie['raters_num'] >= 10:\n has_enough_movie_raters = 1\n if book:\n has_same_title_book = 1\n if book['raters_num'] >= 10:\n has_enough_book_raters = 1\n self._features = {\n 'has_same_title_book': float(has_same_title_book),\n 'has_same_title_movie': float(has_same_title_movie),\n 'has_person_book': float(has_person_book),\n 'has_person_movie': float(has_person_movie),\n 'has_pattern_person': float(has_pattern_person),\n 'has_enough_book_raters': float(has_enough_book_raters),\n 'has_enough_movie_raters': float(has_enough_movie_raters),\n }\n return self._features.copy()\n\n\nclass NERValidator(object):\n def __init__(self, recbysns, classifiers):\n self.recbysns = recbysns\n self.db = self.recbysns.db\n self.classifiers = classifiers\n self.evaluator = Evaluator()\n self.confusion_matrixes = {str(classifier):\n [] for classifier in self.classifiers}\n\n def validate(self):\n entities = [NEREntity(self.recbysns, entity)\n for entity in self.db.select_table('recbysns_entity', '1')]\n for classifier in self.classifiers:\n self.test(classifier, entities)\n self.evaluator.evaluate(self.confusion_matrixes)\n\n def test(self, classifier, entities):\n confusion_matrix = {\n NER_BOOK: {NER_BOOK: float(0), NER_MOVIE: float(0),\n NER_VIDEO: float(0), NER_OTHERS: float(0)},\n NER_MOVIE: {NER_BOOK: float(0), NER_MOVIE: float(0),\n NER_VIDEO: float(0), NER_OTHERS: float(0)},\n NER_VIDEO: {NER_BOOK: float(0), NER_MOVIE: float(0),\n NER_VIDEO: float(0), NER_OTHERS: float(0)},\n NER_OTHERS: {NER_BOOK: float(0), NER_MOVIE: float(0),\n NER_VIDEO: float(0), NER_OTHERS: float(0)},\n }\n for entity in entities:\n # predicted ner class\n p_ner_class = classifier.predict(entity)\n ner_class = entity.ner_class()\n confusion_matrix[ner_class][p_ner_class] += 1\n print confusion_matrix\n self.confusion_matrixes[str(classifier)].append(confusion_matrix)\n\n\nclass NERCrossValidator(NERValidator):\n def __init__(self, recbysns, classifiers):\n NERValidator.__init__(self, recbysns, classifiers)\n\n def validate(self):\n X = [NEREntity(self.recbysns, entity)\n for entity in self.db.select_table('recbysns_entity', '1')]\n shuffle(X)\n Y = [entity.ner_class() for entity in X]\n cv = StratifiedKFold(Y, 5)\n i = 0\n for train, test in cv:\n print\n print '############CV %d##############' % i\n X_train = [X[idx] for idx in train]\n X_test = [X[idx] for idx in test]\n for classifier in self.classifiers:\n print '############%s validate start###########' % classifier\n classifier.train(X_train)\n self.test(classifier, X_test)\n i += 1\n self.evaluator.evaluate(self.confusion_matrixes)\n\n\nclass NERClassifier(object):\n def __init__(self, recbysns):\n self.recbysns = recbysns\n self.db = self.recbysns.db\n self.nlpir = self.recbysns.nlpir\n\n def predict(self, entity):\n raise Exception('Not implemented')\n\n def train(self, entities):\n pass\n\n def __repr__(self):\n return str(self.__class__.__name__)\n\n\nclass NERNaiveClassifier(NERClassifier):\n def __init__(self, recbysns):\n NERClassifier.__init__(self, recbysns)\n\n def predict(self, entity):\n if entity.pos() == u'url':\n return NER_VIDEO\n else:\n book = entity.book()\n movie = entity.movie()\n if book and not movie:\n return NER_BOOK\n elif movie and not book:\n return NER_MOVIE\n elif book and movie:\n return choice([NER_BOOK, NER_MOVIE])\n else:\n print '###################Abnormal#######################'\n return -1\n\n\nclass NERBookPreferNaiveClassifier(NERClassifier):\n def __init__(self, recbysns):\n NERClassifier.__init__(self, recbysns)\n\n def predict(self, entity):\n if entity.pos() == u'url':\n return NER_VIDEO\n else:\n book = entity.book()\n movie = entity.movie()\n if book:\n return NER_BOOK\n elif movie:\n return NER_MOVIE\n else:\n print '###################Abnormal#######################'\n return NER_OTHERS\n\n\nclass NERMoviePreferNaiveClassifier(NERClassifier):\n def __init__(self, recbysns):\n NERClassifier.__init__(self, recbysns)\n\n def predict(self, entity):\n if entity.pos() == u'url':\n return NER_VIDEO\n else:\n book = entity.book()\n movie = entity.movie()\n if movie:\n return NER_MOVIE\n elif book:\n return NER_BOOK\n else:\n print '###################Abnormal#######################'\n return NER_OTHERS\n\n\nclass NERPersonFilterNaiveClassifier(NERClassifier):\n def __init__(self, recbysns):\n NERClassifier.__init__(self, recbysns)\n\n def predict(self, entity):\n if entity.pos() == u'url':\n return NER_VIDEO\n persons = entity.persons()\n book = entity.book()\n movie = entity.movie()\n for person in persons:\n if person['movie']:\n return NER_MOVIE\n elif person['book']:\n return NER_BOOK\n for person in persons:\n # person is not the author of the book\n # with same title as the entity\n # or the actor of the movie with same title as the entity\n # because these conditions have been checked before\n if person['pattern'] and person['name'][0] != '@':\n return NER_OTHERS\n if movie:\n return NER_MOVIE\n elif book:\n return NER_BOOK\n else:\n print '###################Abnormal#######################'\n return NER_OTHERS\n\n\nclass NERPersonTitlePatternGenerator(object):\n def __init__(self, recbysns):\n self.recbysns = recbysns\n self.db = recbysns.db\n self.nlpir = recbysns.nlpir\n\n def generate(self):\n occurrences = {0: {}, 1: {}}\n for status in \\\n self.db.select_table('weibo_status',\n \"text like '%%《%%》%%' and \\\n author_id <> 1195031270\"):\n sessions = self.nlpir.segment_weibo_status(status['text'])\n for session in sessions:\n persons = []\n entities = []\n i = 0\n while i < len(session):\n segment = session[i]\n pos = self.nlpir.get_POS(segment)\n if pos == 'nr':\n persons.append(\n (i, self.nlpir.get_word(segment).strip('@')))\n elif pos == 'title':\n title = re.match(u'《(.*?)》',\n self.nlpir.get_word(segment)).group(1)\n book = self.db.select_douban_book_by_title(title)\n movie = self.db.select_douban_movie_by_title(title)\n if book:\n entities.append((i, book))\n if movie:\n entities.append((i, movie))\n i = i + 1\n for person in persons:\n for entity in entities:\n if entity[1]['pub'] and \\\n re.search(person[1], entity[1]['pub']):\n min_index = min(person[0], entity[0])\n max_index = max(person[0], entity[0])\n order = 1 if person[0] < entity[0] else 0\n start = min_index + 1\n end = max_index\n middle = self.nlpir.restore_text(\n session[start:end])\n start = min_index - 5 if min_index >= 5 else 0\n end = min_index\n prefix = self.nlpir.restore_text(\n session[start:end])\n start = max_index + 1\n end = start + 5\n suffix = self.nlpir.restore_text(\n session[start:end])\n if middle not in occurrences[order]:\n occurrences[order][middle] = []\n occurrences[order][middle].append(\n (person[1], entity[1]['title'], order, prefix,\n middle, suffix))\n patterns = []\n for order in [0, 1]:\n for middle, value in occurrences[order].items():\n if len(value) > 10:\n prefix = os.path.commonprefix(\n [occurrence[3][::-1]\n for occurrence in value])[::-1]\n suffix = os.path.commonprefix([occurrence[5]\n for occurrence in value])\n patterns.append((order, prefix,\n middle, suffix, len(value)))\n patterns.sort(key=lambda pattern: pattern[4], reverse=True)\n return patterns\n\n\nclass NERDTClassifier(NERClassifier):\n def __init__(self, recbysns):\n NERClassifier.__init__(self, recbysns)\n self.decision_tree = None\n\n def train(self, entities):\n X = [self.generate_features(entity)\n for entity in entities if entity.pos() == u'title']\n Y = [entity.ner_class()\n for entity in entities if entity.pos() == u'title']\n self.decision_tree = tree.DecisionTreeClassifier()\n self.decision_tree = self.decision_tree.fit(X, Y)\n import StringIO\n import pydot\n dot_data = StringIO.StringIO()\n tree.export_graphviz(self.decision_tree, out_file=dot_data)\n graph = pydot.graph_from_dot_data(dot_data.getvalue())\n graph.write_pdf(\"data/recbysns.dt.pdf\")\n\n def predict(self, entity):\n if entity.pos() == u'url':\n return NER_VIDEO\n else:\n X = [self.generate_features(entity)]\n return self.decision_tree.predict(X)[0]\n\n def generate_features(self, entity):\n return entity.features().values()\n\n\nclass NERDTClassifierWithNBClassifier(NERDTClassifier):\n def __init__(self, recbysns):\n NERDTClassifier.__init__(self, recbysns)\n self.ner_nb_classifier = \\\n NERNBClassifierWithoutFeatures(recbysns, ['domain'])\n\n def train(self, entities):\n X = entities\n Y = [entity.ner_class() for entity in X]\n cv = StratifiedKFold(Y, 2)\n for train, test in cv:\n X_nb_train = [X[idx] for idx in train]\n X_dt_train = [X[idx] for idx in test]\n print len(X_nb_train)\n print len(X_dt_train)\n self.ner_nb_classifier.train(X_nb_train)\n NERDTClassifier.train(self, X_dt_train)\n break\n\n def generate_features(self, entity):\n # ner_class predicted by navie bayes\n nb_p_ner_class = self.ner_nb_classifier.predict(entity)\n features = entity.features().values()\n features.append(nb_p_ner_class)\n return features\n\n\nclass NERRFClassifier(NERClassifier):\n def __init__(self, recbysns):\n NERClassifier.__init__(self, recbysns)\n self.rf = None\n\n def train(self, entities):\n X = [self.generate_features(entity)\n for entity in entities if entity.pos() == u'title']\n Y = [entity.ner_class()\n for entity in entities if entity.pos() == u'title']\n self.rf = RandomForestClassifier(n_estimators=10)\n self.rf = self.rf.fit(X, Y)\n\n def predict(self, entity):\n if entity.pos() == u'url':\n return NER_VIDEO\n else:\n X = [self.generate_features(entity)]\n return self.rf.predict(X)[0]\n\n def generate_features(self, entity):\n return entity.features().values()\n\n\nclass NERSVMClassifier(NERClassifier):\n def __init__(self, recbysns, kernel='rbf'):\n NERClassifier.__init__(self, recbysns)\n self.svm = None\n self.scaler = None\n self.kernel = kernel\n\n def train(self, entities):\n X = [self.generate_features(entity)\n for entity in entities if entity.pos() == u'title']\n Y = [entity.ner_class()\n for entity in entities if entity.pos() == u'title']\n self.scaler = preprocessing.MinMaxScaler((-1, 1))\n X = self.scaler.fit_transform(X)\n Y = np.asarray(Y)\n C_range = 2.0 ** np.arange(-5, 17, 2)\n gamma_range = 2.0 ** np.arange(-15, 5, 2)\n param_grid = dict(gamma=gamma_range, C=C_range)\n cv = StratifiedKFold(y=Y, n_folds=5)\n self.svm = GridSearchCV(svm.SVC(cache_size=1000, kernel=self.kernel),\n param_grid=param_grid, cv=cv)\n self.svm.fit(X, Y)\n\n def predict(self, entity):\n if entity.pos() == u'url':\n return NER_VIDEO\n else:\n X = self.scaler.transform([self.generate_features(entity)])\n return self.svm.predict(X)[0]\n\n def generate_features(self, entity):\n return entity.features().values()\n\n def __repr__(self):\n return '%s: %s' % (self.__class__.__name__, self.kernel)\n\n\nclass NERKNNClassifier(NERClassifier):\n def __init__(self, recbysns):\n NERClassifier.__init__(self, recbysns)\n self.knn = None\n self.vectorizer = None\n\n def train(self, entities):\n self.knn = KNeighborsClassifier(n_neighbors=10)\n self.vectorizer = CountVectorizer(\n analyzer=NEREntityAnalyzer(self.recbysns), max_df=1.0, min_df=2)\n self.vectorizer.fit_transform(entities)\n X = [self.generate_features(entity)\n for entity in entities if entity.pos() == u'title']\n Y = [entity.ner_class()\n for entity in entities if entity.pos() == u'title']\n self.knn = self.knn.fit(X, Y)\n\n def predict(self, entity):\n if entity.pos() == u'url':\n return NER_VIDEO\n else:\n X = [self.generate_features(entity)]\n return self.knn.predict(X)[0]\n\n def generate_features(self, entity):\n text_features = self.vectorizer.transform([entity]).\\\n toarray()[0].tolist()\n features = entity.features().values()\n return text_features + features\n\n\nclass NERNBClassifier(NERClassifier):\n def __init__(self, recbysns, max_df=1.0, min_df=2):\n NERClassifier.__init__(self, recbysns)\n self.mnb = None\n self.vectorizer = None\n self.max_df = max_df\n self.min_df = min_df\n\n def train(self, entities):\n self.mnb = MultinomialNB()\n self.vectorizer = CountVectorizer(\n analyzer=NEREntityAnalyzer(self.recbysns),\n max_df=self.max_df, min_df=self.min_df)\n self.vectorizer.fit_transform(entities)\n X = [self.generate_features(entity)\n for entity in entities if entity.pos() == u'title']\n Y = [entity.ner_class()\n for entity in entities if entity.pos() == u'title']\n self.mnb = self.mnb.fit(X, Y)\n\n def predict(self, entity):\n if entity.pos() == u'url':\n return NER_VIDEO\n else:\n X = [self.generate_features(entity)]\n return self.mnb.predict(X)[0]\n\n def generate_features(self, entity):\n text_features = self.vectorizer.transform([entity]).\\\n toarray()[0].tolist()\n features = entity.features().values()\n return features + text_features\n\n def __repr__(self):\n return '%s: %f&%f' % (self.__class__.__name__,\n self.max_df, self.min_df)\n\n\nclass NERNBClassifierWithoutFeatures(NERNBClassifier):\n def __init__(self, recbysns, features):\n NERNBClassifier.__init__(self, recbysns)\n self.features = features\n\n def generate_features(self, entity):\n features = entity.features()\n text_features = self.vectorizer.transform([entity]).\\\n toarray()[0].tolist()\n if len(self.features) > 0 and self.features[0] == 'domain':\n features = {}\n else:\n for feature in self.features:\n if feature == 'text':\n text_features = []\n else:\n del features[feature]\n return text_features + features.values()\n\n def __repr__(self):\n return '%s: %s' % (self.__class__.__name__, '&'.join(self.features))\n\n\nclass NERSVMClassifierWithNBClassifier(NERSVMClassifier):\n def __init__(self, recbysns):\n NERSVMClassifier.__init__(self, recbysns)\n self.ner_nb_classifier = \\\n NERNBClassifierWithoutFeatures(recbysns, ['domain'])\n\n def train(self, entities):\n X = entities\n Y = [entity.ner_class() for entity in X]\n cv = StratifiedKFold(Y, 2)\n for train, test in cv:\n X_nb_train = [X[idx] for idx in train]\n X_svm_train = [X[idx] for idx in test]\n self.ner_nb_classifier.train(X_nb_train)\n NERSVMClassifier.train(self, X_svm_train)\n break\n #self.ner_nb_classifier.train(entities)\n #NERSVMClassifier.train(self, entities)\n\n def generate_features(self, entity):\n # ner_class predicted by navie bayes\n nb_p_ner_class = self.ner_nb_classifier.predict(entity)\n features = entity.features().values()\n # TODO convert class to the form of (0,0,0)\n features.append(nb_p_ner_class)\n return features\n\n\nclass NERSVMClassifierWithoutFeatures(NERSVMClassifier):\n def __init__(self, recbysns, features):\n NERSVMClassifier.__init__(self, recbysns)\n self.features = features\n\n def generate_features(self, entity):\n features = entity.features()\n for feature in self.features:\n del features[feature]\n return features.values()\n\n def __repr__(self):\n return 'NERSVMClassifierWithoutFeatures: %s' % \\\n '&'.join(map(str, self.features))\n\n\nclass NERMajorVotingClassifier(NERClassifier):\n def __init__(self, recbysns, classifiers):\n NERClassifier.__init__(self, recbysns)\n self.classifiers = classifiers\n\n def train(self, entities):\n for classifier in self.classifiers:\n classifier.train(entities)\n\n def predict(self, entity):\n p_ner_classes = {NER_BOOK: 0, NER_MOVIE: 0,\n NER_VIDEO: 0, NER_OTHERS: 0}\n for classifier in self.classifiers:\n p_ner_class = classifier.predict(entity)\n p_ner_classes[p_ner_class] += 1\n return max(p_ner_classes.iteritems(), key=operator.itemgetter(1))[0]\n\nif __name__ == '__main__':\n from recbysns import recbysns\n ner_naive_classifier = NERNaiveClassifier(recbysns)\n ner_book_prefer_naive_classifier = \\\n NERBookPreferNaiveClassifier(recbysns)\n ner_movie_prefer_naive_classifier = \\\n NERMoviePreferNaiveClassifier(recbysns)\n ner_person_filter_naive_classifier = \\\n NERPersonFilterNaiveClassifier(recbysns)\n ner_svm_classifier = NERSVMClassifier(recbysns)\n ner_nb_classifier = NERNBClassifier(recbysns)\n ner_nb_classifier_without_domain_features = \\\n NERNBClassifierWithoutFeatures(recbysns, ['domain'])\n ner_nb_classifier_without_text_features = \\\n NERNBClassifierWithoutFeatures(recbysns, ['text'])\n ner_dt_classifier = NERDTClassifier(recbysns)\n ner_dt_classifier_with_nb_classifier = \\\n NERDTClassifierWithNBClassifier(recbysns)\n ner_rf_classifier = NERRFClassifier(recbysns)\n ner_knn_classifier = NERKNNClassifier(recbysns)\n ner_svm_classifier_with_nb_classifier = \\\n NERSVMClassifierWithNBClassifier(recbysns)\n ner_svm_classifier_without_feature_has_same_title_book = \\\n NERSVMClassifierWithoutFeatures(recbysns, ['has_same_title_book'])\n ner_svm_classifier_without_feature_has_same_title_movie = \\\n NERSVMClassifierWithoutFeatures(recbysns, ['has_same_title_movie'])\n ner_svm_classifier_without_feature_has_person_book = \\\n NERSVMClassifierWithoutFeatures(recbysns, ['has_person_book'])\n ner_svm_classifier_without_feature_has_person_movie = \\\n NERSVMClassifierWithoutFeatures(recbysns, ['has_person_movie'])\n ner_svm_classifier_without_feature_has_pattern_person = \\\n NERSVMClassifierWithoutFeatures(recbysns, ['has_pattern_person'])\n ner_svm_classifier_without_feature_has_enough_book_raters = \\\n NERSVMClassifierWithoutFeatures(recbysns,\n ['has_enough_book_raters'])\n ner_svm_classifier_without_feature_has_enough_movie_raters = \\\n NERSVMClassifierWithoutFeatures(recbysns,\n ['has_enough_movie_raters'])\n ner_svm_classifier_without_feature_person = \\\n NERSVMClassifierWithoutFeatures(recbysns,\n ['has_person_book',\n 'has_person_movie',\n 'has_pattern_person'])\n ner_svm_classifier_without_feature_person_2 = \\\n NERSVMClassifierWithoutFeatures(recbysns,\n ['has_person_movie',\n 'has_pattern_person'])\n ner_svm_classifier_without_feature_raters = \\\n NERSVMClassifierWithoutFeatures(recbysns,\n ['has_enough_book_raters',\n 'has_enough_movie_raters'])\n ner_major_voting_classifier = \\\n NERMajorVotingClassifier(recbysns,\n [ner_nb_classifier,\n ner_dt_classifier_with_nb_classifier,\n ner_svm_classifier_with_nb_classifier])\n validator = \\\n NERCrossValidator(recbysns,\n [ner_naive_classifier,\n ner_book_prefer_naive_classifier,\n ner_movie_prefer_naive_classifier,\n ner_person_filter_naive_classifier,\n ner_dt_classifier,\n ner_svm_classifier,\n ner_nb_classifier,\n ner_nb_classifier_without_domain_features,\n ner_nb_classifier_without_text_features,\n ner_svm_classifier_with_nb_classifier,\n ner_dt_classifier_with_nb_classifier,\n ner_svm_classifier_without_feature_has_same_title_book,\n ner_svm_classifier_without_feature_has_same_title_movie,\n ner_svm_classifier_without_feature_has_person_book,\n ner_svm_classifier_without_feature_has_person_movie,\n ner_svm_classifier_without_feature_has_pattern_person,\n ner_svm_classifier_without_feature_has_enough_book_raters,\n ner_svm_classifier_without_feature_has_enough_movie_raters,\n ner_svm_classifier_without_feature_person,\n ner_svm_classifier_without_feature_person_2,\n ner_svm_classifier_without_feature_raters])\n svms = [NERSVMClassifier(recbysns, 'rbf'),\n NERSVMClassifier(recbysns, 'linear'),\n NERSVMClassifier(recbysns, 'poly'),\n NERSVMClassifier(recbysns, 'sigmoid')]\n validator = NERCrossValidator(recbysns, svms)\n validator.validate()\n #person_title_pattern_generator = PersonTitlePatternGenerator(recbysns)\n #print person_title_pattern_generator.generate()\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":41369,"cells":{"__id__":{"kind":"number","value":12859132128137,"string":"12,859,132,128,137"},"blob_id":{"kind":"string","value":"fe33fda583af14c423f911a1d9b43e9eaed928d8"},"directory_id":{"kind":"string","value":"b7039376aa8601024a3eb531a3435da4b65c2ce8"},"path":{"kind":"string","value":"/stagecraft/apps/datasets/tests/models/test_backdrop_user.py"},"content_id":{"kind":"string","value":"150c5a504c6e91596ff4e1ca400e67d7b2d214d2"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"sofiangrh/stagecraft"},"repo_url":{"kind":"string","value":"https://github.com/sofiangrh/stagecraft"},"snapshot_id":{"kind":"string","value":"6a28060e4b31f335b60778cd8c1de7850e107772"},"revision_id":{"kind":"string","value":"179bde9b2c56cf8f96b05c9ec39e75e17c8513bf"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-16T19:33:59.043337","string":"2021-01-16T19:33:59.043337"},"revision_date":{"kind":"timestamp","value":"2014-07-11T14:57:43","string":"2014-07-11T14:57:43"},"committer_date":{"kind":"timestamp","value":"2014-07-11T14:57:43","string":"2014-07-11T14:57:43"},"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":"# encoding: utf-8\n# See https://docs.djangoproject.com/en/1.6/topics/testing/tools/\n\nfrom __future__ import unicode_literals\n\nfrom django.test import TestCase, TransactionTestCase\n\nfrom django.core.exceptions import ValidationError\n\nfrom nose.tools import assert_raises, assert_equal\n\nfrom stagecraft.apps.datasets.models import(\n BackdropUser, DataSet)\n\nimport mock\n\n\nclass BackdropUserTestCase(TestCase):\n fixtures = ['test_import_users_datasets.json']\n\n @mock.patch('stagecraft.apps.datasets.models.backdrop_user.purge')\n def test_user_email_must_be_unique(self, mock_purge):\n a = BackdropUser.objects.create(email='email@email.com')\n a.validate_unique()\n\n b = BackdropUser(email='email@email.com')\n assert_raises(ValidationError, lambda: b.validate_unique())\n\n @mock.patch('stagecraft.apps.datasets.models.backdrop_user.purge')\n def test_serialize_returns_serialized_user(self, mock_purge):\n a = BackdropUser.objects.create(email='email@blah.net')\n a.data_sets.add(DataSet.objects.get(name=\"evl_customer_satisfaction\"))\n a.data_sets.add(DataSet.objects.get(name=\"lpa_volumes\"))\n expected_response = {\n 'email': 'email@blah.net',\n 'data_sets': ['evl_customer_satisfaction', 'lpa_volumes']\n }\n\n assert_equal(a.serialize(), expected_response)\n\n\nclass VarnishCacheIntegrationTestCase(TransactionTestCase):\n\n \"\"\"\n Test that Varnish's caches are being purged at the appropriate times.\n \"\"\"\n\n @mock.patch('stagecraft.apps.datasets.models.backdrop_user.purge')\n @mock.patch('stagecraft.apps.datasets.models.backdrop_user.'\n 'get_backdrop_user_path_queries')\n def test_user_purges_cache_on_create(\n self,\n mock_get_path_queries,\n mock_purge):\n\n mock_get_path_queries.return_value = ['/some_url']\n\n BackdropUser.objects.create(email='email@blah.net')\n\n mock_purge.assert_called_once_with(['/some_url'])\n\n @mock.patch('stagecraft.apps.datasets.models.backdrop_user.purge')\n @mock.patch('stagecraft.apps.datasets.models.backdrop_user.'\n 'get_backdrop_user_path_queries')\n def test_user_purges_cache_on_save(\n self,\n mock_get_path_queries,\n mock_purge):\n\n user = BackdropUser.objects.create(email='email@blah.net')\n\n mock_get_path_queries.reset_mock()\n mock_purge.reset_mock()\n\n mock_get_path_queries.return_value = ['/some_url']\n\n user.save()\n\n mock_purge.assert_called_once_with(['/some_url'])\n\n @mock.patch('stagecraft.apps.datasets.models.backdrop_user.purge')\n @mock.patch('stagecraft.apps.datasets.models.backdrop_user.'\n 'get_backdrop_user_path_queries')\n def test_user_purges_cache_on_delete(\n self,\n mock_get_path_queries,\n mock_purge):\n\n user = BackdropUser.objects.create(email='email@blah.net')\n\n mock_get_path_queries.reset_mock()\n mock_purge.reset_mock()\n\n mock_get_path_queries.return_value = ['/some_url']\n\n user.delete()\n\n mock_purge.assert_called_once_with(['/some_url'])\n\n @mock.patch('django.db.models.Model.save')\n @mock.patch('stagecraft.apps.datasets.models.backdrop_user.purge')\n def test_purge_not_called_on_model_save_failure(\n self,\n mock_purge,\n mock_save):\n\n mock_save.side_effect = Exception(\"My first fake db error\")\n\n assert_raises(\n Exception,\n lambda: BackdropUser.objects.create(email='email@blah.net')\n )\n\n assert_equal(mock_purge.called, 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":2014,"string":"2,014"}}},{"rowIdx":41370,"cells":{"__id__":{"kind":"number","value":7687991470176,"string":"7,687,991,470,176"},"blob_id":{"kind":"string","value":"734509806d4ab4fc2a5bab6eea6fb0e8f19baad2"},"directory_id":{"kind":"string","value":"adb819c610508ed72fc3269bb0862211dea81613"},"path":{"kind":"string","value":"/classes/__init__.py"},"content_id":{"kind":"string","value":"8db3e8cf6e172392af97b1f4216adf072c3d3351"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"fleeting-chen/Rabbit_battle"},"repo_url":{"kind":"string","value":"https://github.com/fleeting-chen/Rabbit_battle"},"snapshot_id":{"kind":"string","value":"9640618c47b5fe95088459d4ea46f61b2f5124d3"},"revision_id":{"kind":"string","value":"9f5168eebd8987486ba0e6118851d3545e1bf9f2"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T07:02:24.823071","string":"2016-09-06T07:02:24.823071"},"revision_date":{"kind":"timestamp","value":"2014-10-20T14:12:52","string":"2014-10-20T14:12:52"},"committer_date":{"kind":"timestamp","value":"2014-10-20T14:12:52","string":"2014-10-20T14:12:52"},"github_id":{"kind":"number","value":21566113,"string":"21,566,113"},"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":"__author__ = 'chenhao'\n__date__ = '14-7-7'\n#encoding:utf-8\n\n# main()\ndef main():\n\tprint ''\n\n\nif __name__ == \"__main__\":\n\tmain()"},"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":41371,"cells":{"__id__":{"kind":"number","value":12317966206381,"string":"12,317,966,206,381"},"blob_id":{"kind":"string","value":"d63f3f4159ad292152d39494eff3eec7de8f2aab"},"directory_id":{"kind":"string","value":"3ea133d69c62ec497d13a237e3f59227a3ed4334"},"path":{"kind":"string","value":"/python/pad2drone_controler/b-hori2droneAPI.py"},"content_id":{"kind":"string","value":"3d9803f5b4344b526ac9571b4a91f6a21dcf9623"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"jhotta/project-x"},"repo_url":{"kind":"string","value":"https://github.com/jhotta/project-x"},"snapshot_id":{"kind":"string","value":"8876decd7af7730002d6b4f747c5215c7a5cff3e"},"revision_id":{"kind":"string","value":"66d48de36584de1d6b081b4986e716bb40ea8b76"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-11T11:00:51.940313","string":"2021-01-11T11:00:51.940313"},"revision_date":{"kind":"timestamp","value":"2014-06-20T04:40:20","string":"2014-06-20T04:40:20"},"committer_date":{"kind":"timestamp","value":"2014-06-20T04:40:20","string":"2014-06-20T04:40:20"},"github_id":{"kind":"number","value":17615785,"string":"17,615,785"},"star_events_count":{"kind":"number","value":3,"string":"3"},"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# import pdb; pdb.set_trace()\n\nimport sys\nimport time\nimport pygame\nfrom pygame.locals import *\n#import pygame.surfarray\n#import pygame.transform\nimport libardrone.libardrone as ard\n\n\ndef init_gamepad():\n pygame.joystick.init()\n try:\n pad = pygame.joystick.Joystick(0) # create a joystick instance\n pad.init() # init instance\n return pad\n except pygame.error:\n print \"Unexpected error:\", sys.exc_info()[0]\n\n\ndef init_ardrone():\n try:\n drone = ard.ARDrone()\n drone.reset()\n time.sleep(1)\n print \"drone reset done\"\n return drone()\n except:\n print \"Unexpected error:\", sys.exc_info()[0]\n\n\ndef get_gamepad_action(pad, drone):\n\n # pygame window setting\n Width, Hight = 320, 240\n\n # gamepad value object\n axis_value = {\"0\": 0.0, \"1\": 0.0, \"2\": 0.0, \"3\": 0.0}\n bt_status = [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0]\n\n # movement speed seetting\n default_speed = 0.2\n turning_speed = 0.5\n\n # pyagame initalization\n pygame.init()\n pygame.display.set_mode((Width, Hight))\n clock = pygame.time.Clock()\n running = True\n\n # gamepad action to drone API command\n while running:\n for e in pygame.event.get():\n if e.type == QUIT: # 終了が押された?\n return\n if e.type == KEYDOWN and e.key == K_ESCAPE: # ESCが押された?\n return\n if e.type == pygame.JOYAXISMOTION: # 7\n axis_value[str(e.axis)] = e.value\n print axis_value\n elif e.type == pygame.JOYHATMOTION: # 9\n print e.value\n print \"hat motion\"\n if e.value == (0, 1):\n print \"move forward\"\n drone.move_forward()\n elif e.value == (0, -1):\n print \"move backward\"\n drone.move_backward()\n elif e.value == (-1, 0):\n print \"move left\"\n drone.move_left()\n elif e.value == (1, 0):\n print \"move right\"\n drone.move_right()\n elif e.type == pygame.JOYBUTTONDOWN: # 10\n print \"%s button pushed\" % str(e.button)\n bt_status[e.button] = 1\n if bt_status[4] == 1 and bt_status[5] == 1:\n print \"takeoff\"\n drone.takeoff()\n elif bt_status[6] == 1 and bt_status[7] == 1:\n print \"landing\"\n drone.lannd()\n drone.halt()\n elif bt_status[0] == 1:\n print \"away(turn left)\"\n drone.speed = turning_speed\n drone.turn_left()\n elif bt_status[1] == 1:\n print \"going down\"\n drone.move_down()\n elif bt_status[2] == 1:\n print \"comeby(turn right)\"\n drone.speed = turning_speed\n drone.turn_right()\n elif bt_status[3] == 1:\n print \"going up\"\n drone.move_up()\n print bt_status\n elif e.type == pygame.JOYBUTTONUP: # 11\n print \"%s button released\" % str(e.button)\n bt_status[e.button] = 0\n print bt_status\n\n\ndef main():\n pad = init_gamepad()\n drone = init_ardrone()\n get_gamepad_action(pad, drone)\n\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":41372,"cells":{"__id__":{"kind":"number","value":12249246772779,"string":"12,249,246,772,779"},"blob_id":{"kind":"string","value":"6e446d0c23f9aa84ce3bde0bf9ffbc1000f71f8e"},"directory_id":{"kind":"string","value":"7ec929254d9f30d55932ae0109bd113573118439"},"path":{"kind":"string","value":"/class34_homework/11A_Asen_Stoilov/1.py"},"content_id":{"kind":"string","value":"6d65f9b3a6d22f25990f88b61feee2544691e96c"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"thebravoman/software_engineering_2013"},"repo_url":{"kind":"string","value":"https://github.com/thebravoman/software_engineering_2013"},"snapshot_id":{"kind":"string","value":"2a41da905adc1c2e149c03d96e45b6ef87465273"},"revision_id":{"kind":"string","value":"9121b4b3d7d393aa840c2d94288965a08bbb66db"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-06-06T14:51:09.118535","string":"2020-06-06T14:51:09.118535"},"revision_date":{"kind":"timestamp","value":"2014-05-27T20:33:59","string":"2014-05-27T20:33:59"},"committer_date":{"kind":"timestamp","value":"2014-05-27T20:33:59","string":"2014-05-27T20:33:59"},"github_id":{"kind":"number","value":12457183,"string":"12,457,183"},"star_events_count":{"kind":"number","value":2,"string":"2"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"bool","value":false,"string":"false"},"gha_event_created_at":{"kind":"timestamp","value":"2013-11-28T07:46:28","string":"2013-11-28T07:46:28"},"gha_created_at":{"kind":"timestamp","value":"2013-08-29T10:07:01","string":"2013-08-29T10:07:01"},"gha_updated_at":{"kind":"timestamp","value":"2013-11-28T07:45:35","string":"2013-11-28T07:45:35"},"gha_pushed_at":{"kind":"timestamp","value":"2013-11-28T07:45:34","string":"2013-11-28T07:45:34"},"gha_size":{"kind":"number","value":5790,"string":"5,790"},"gha_stargazers_count":{"kind":"number","value":3,"string":"3"},"gha_forks_count":{"kind":"number","value":15,"string":"15"},"gha_open_issues_count":{"kind":"number","value":11,"string":"11"},"gha_language":{"kind":"string","value":"Ruby"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import random\n\ndef rand_num():\n\tnum = random.randrange(128,512)\n\tcount = 0\n\tfor i in range(1, num):\n\t\tif num%i==0: count+=1\n\n\tif count < 2: return num\n\treturn rand_num()\n\ndef gcd(a,b):\n\ti=1\n\tgcd =0\n\twhile i<=a and i<=b:\n\t\tif a%i==0 and b%i==0: gcd =i\n\t\ti+=1\n\treturn gcd\t\n\ndef gen_d(e,fn):\n\ti=0\n\twhile True:\n\t\td=(fn*i+1)/e;\n\t\tif((fn*i+1)%e==0): return d\n\t\ti+=1\n\n\ndef generate_keys():\n\n\tp = rand_num()\n\tq = rand_num()\n\twhile q == p:\n\t\tq = rand_num()\n\n\tn = p*q\t\n\tfn = (p-1)*(q-1)\n\te =0\n\twhile True:\n\t\te = random.randrange(1,fn)\n\t\tif gcd(e,fn)==1: break\n\n\td= gen_d(e,fn)\n\n\n\treturn(n,e,d)\n\nkeys = generate_keys()\nprint \"public:\", keys[0], keys[1]\nprint \"private:\", keys[0], keys[2]\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":41373,"cells":{"__id__":{"kind":"number","value":17489106839656,"string":"17,489,106,839,656"},"blob_id":{"kind":"string","value":"bf53c9f1144c23c7f1ba14dd7bd6189c9affd914"},"directory_id":{"kind":"string","value":"843813f64df59d5b0893f161345a9569ec87695d"},"path":{"kind":"string","value":"/source/snapdeal_limeroad_paytm/GenerateXML.py"},"content_id":{"kind":"string","value":"41bcff339295b6a2ea467e80ce5bae1e78ae17c3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"naka13/voylla_api"},"repo_url":{"kind":"string","value":"https://github.com/naka13/voylla_api"},"snapshot_id":{"kind":"string","value":"c18e43d1b77e9fbce3c7bac4c0709fb063710a13"},"revision_id":{"kind":"string","value":"35036e6fe9de4e23929c70fd6fd9580c07b3a4b1"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-23T00:01:51.345084","string":"2021-01-23T00:01:51.345084"},"revision_date":{"kind":"timestamp","value":"2014-11-03T21:12:26","string":"2014-11-03T21:12:26"},"committer_date":{"kind":"timestamp","value":"2014-11-03T21:12:26","string":"2014-11-03T21:12:26"},"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 shlex\nimport subprocess\nimport string\nimport sys\nimport json\nfrom datetime import datetime\n\ndef generateXML(skus, qtys):\n\tstamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')\n\tfilename = \"update\"+stamp+\".xml\"\n\ttemp = open(filename,\"w\")\n\ttemp.write('\\n')\n\ttemp.write(\"\\n\")\n\n\tfor index in range(len(skus)):\n\t\tsku = skus[index]\n\t\tqty = qtys[index]\n\t\ttemp.write(\"\\n\")\n\t\ttemp.write(\"\"+sku+\"\\n\")\n\t\ttemp.write(\"\"+str(qty)+\"\\n\")\n\t\ttemp.write(\"\\n\\n\\n\")\n\n\ttemp.write(\"\")\n\ttemp.close()\n\n\n\tprint os.getcwd()\n\tcmd = 'scp ' + filename + ' root@staging.voylla.com:/srv/ftp/'\n\t#cmd = 'scp ' + filename + ' root@staging.voylla.com:/srv/ftp/'\n\tprint cmd\n\targs = shlex.split(cmd)\n\tp=subprocess.Popen(args)\n\tp.wait()\n\n\n\tcmd = 'scp ' + filename + ' root@staging.voylla.com:/home/limeroad/inventory/'\n\t#cmd = 'scp ' + filename + ' root@staging.voylla.com:/home/limeroad/'\n\tprint cmd\n\targs = shlex.split(cmd)\n\tp=subprocess.Popen(args)\n\tp.wait()\n\n\n\tcmd = 'scp ' + filename + ' root@staging.voylla.com:/home/voylla_paytm/Inventory_Update/'\n\t#cmd = 'scp ' + filename + ' root@staging.voylla.com:/home/voylla_paytm/'\n\tprint cmd\n\targs = shlex.split(cmd)\n\tp=subprocess.Popen(args)\n\tp.wait()\n\n\n\tos.remove(filename)"},"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":41374,"cells":{"__id__":{"kind":"number","value":10814727684623,"string":"10,814,727,684,623"},"blob_id":{"kind":"string","value":"b55755ae9d1e7a0dd837e791ea6d3d566072fcba"},"directory_id":{"kind":"string","value":"21c3b128f30f64a25aef299c294f50a237b42889"},"path":{"kind":"string","value":"/willie/modules/ip.py"},"content_id":{"kind":"string","value":"a6afc18a4b5f5f215e42fac912f0205beec09d97"},"detected_licenses":{"kind":"list like","value":["EFL-2.0"],"string":"[\n \"EFL-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"atti92/AtiBot"},"repo_url":{"kind":"string","value":"https://github.com/atti92/AtiBot"},"snapshot_id":{"kind":"string","value":"e2bacc0f625a014605f362adba2d8fee7aae4fa3"},"revision_id":{"kind":"string","value":"b4a5f2924d77459e7094416eafb644f2ad04c666"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-03-12T20:14:25.924155","string":"2021-03-12T20:14:25.924155"},"revision_date":{"kind":"timestamp","value":"2013-06-27T18:11:21","string":"2013-06-27T18:11:21"},"committer_date":{"kind":"timestamp","value":"2013-06-27T18:11:21","string":"2013-06-27T18:11: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":"# coding=utf-8\n\"\"\"\nip.py - Willie IP Lookup Module\nCopyright 2011, Dimitri Molenaars, TyRope.nl,\nCopyright © 2013, Elad Alfassa \nLicensed under the Eiffel Forum License 2.\n\nhttp://willie.dftba.net\n\"\"\"\n\nimport re\nimport pygeoip\nimport socket\nfrom willie.module import commands, example\n\n@commands('iplookup', 'ip')\n@example('.ip 8.8.8.8')\ndef ip(willie, trigger):\n \"\"\"IP Lookup tool\"\"\"\n if not trigger.group(2):\n return willie.reply(\"No search term.\")\n query = trigger.group(2)\n # FIXME: This shouldn't be hardcoded\n gi_city = pygeoip.GeoIP('/usr/share/GeoIP/GeoLiteCity.dat')\n gi_org = pygeoip.GeoIP('/usr/share/GeoIP/GeoIPASNum.dat')\n host = socket.getfqdn(query)\n response = \"[IP/Host Lookup] Hostname: %s\" % host\n response += \" | Location: %s\" % gi_city.country_name_by_name(query)\n region = gi_city.region_by_name(query)['region_name']\n if region is not '':\n response += \" | Region: %s\" % region\n isp = gi_org.org_by_name(query)\n if isp is not None:\n isp = re.sub('^AS\\d+ ', '', isp)\n response += \" | ISP: %s\" % isp\n willie.say(response)\n\nif __name__ == '__main__':\n print __doc__.strip()\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":41375,"cells":{"__id__":{"kind":"number","value":11622181526598,"string":"11,622,181,526,598"},"blob_id":{"kind":"string","value":"02b891dd8ffafd7d8885b244c25df3ad75b3d038"},"directory_id":{"kind":"string","value":"0dfaf4e5a17a3623df799e74d1ee59cba879c74a"},"path":{"kind":"string","value":"/photoplanet/photoplanet/management/commands/load_photos.py"},"content_id":{"kind":"string","value":"04c16420fd80bedc3f47c7180ffadd0a2989911c"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"pyMDB/photoplanet"},"repo_url":{"kind":"string","value":"https://github.com/pyMDB/photoplanet"},"snapshot_id":{"kind":"string","value":"79a7a35af438db3d153b9721a4394704b0005079"},"revision_id":{"kind":"string","value":"c2bfa54aa144b1017d836cf0a774be6dff0f4db0"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-16T20:56:03.285556","string":"2021-01-16T20:56:03.285556"},"revision_date":{"kind":"timestamp","value":"2013-12-19T11:31:59","string":"2013-12-19T11:31:59"},"committer_date":{"kind":"timestamp","value":"2013-12-19T11:31:59","string":"2013-12-19T11:31:59"},"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://docs.djangoproject.com/en/1.5/howto/custom-management-commands/\nfrom django.core.management.base import BaseCommand\nfrom django.conf import settings\nfrom django.utils.timezone import utc\n\nfrom instagram.client import InstagramAPI\n\nfrom photoplanet.models import Photo\n\n\nclass Command(BaseCommand):\n # args = ''\n help = 'Loads recent photos'\n\n def handle(self, *args, **options):\n # raise CommandError('Some error.')\n api = InstagramAPI(\n client_id=settings.INSTAGRAM_CLIENT_ID,\n client_secret=settings.INSTAGRAM_CLIENT_SECRET)\n search_result = api.tag_recent_media(\n settings.MEDIA_COUNT,\n settings.LARGE_MEDIA_MAX_ID,\n settings.MEDIA_TAG\n )\n info = ''\n # list of media is in the first element of the tuple\n for m in search_result[0]:\n p, is_created = Photo.objects.get_or_create(\n id=m.id, username=m.user.username)\n is_like_count_updated = False\n if not p.like_count == m.like_count:\n p.username = m.user.username\n p.user_avatar_url = m.user.profile_picture\n p.photo_url = m.images['standard_resolution'].url\n p.created_time = m.created_time.replace(tzinfo=utc)\n p.like_count = m.like_count\n p.save()\n is_like_count_updated = True\n info = ''\n info += '{id}\\n{username}\\n{avatar_url}\\n{photo_url}\\n'.format(\n id=m.id,\n username=m.user.username,\n avatar_url=m.user.profile_picture,\n photo_url=m.images['standard_resolution'].url\n )\n info += '{created_time}\\n{like_count}\\n{is_created}\\n{is_like_count_updated}\\n'.format(\n created_time=m.created_time,\n like_count=m.like_count,\n is_created=is_created,\n is_like_count_updated=is_like_count_updated\n )\n info += 40 * '-'\n p.update_vote_prediction()\n self.stdout.write(info)\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":41376,"cells":{"__id__":{"kind":"number","value":10282151744191,"string":"10,282,151,744,191"},"blob_id":{"kind":"string","value":"88ea79d96bb0c1ba303d103c6c3116735d8d5295"},"directory_id":{"kind":"string","value":"0a1ec42ddace93933d677475a4938f1c2d58a552"},"path":{"kind":"string","value":"/example/mmolite/master/server.py"},"content_id":{"kind":"string","value":"fa824120773d92c512e2f8d0e1afd35373e3cd98"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"ClayHanson/tge-152-fork"},"repo_url":{"kind":"string","value":"https://github.com/ClayHanson/tge-152-fork"},"snapshot_id":{"kind":"string","value":"f8a242e401e3ea85eebfc75ff2b3dfc84b4fa056"},"revision_id":{"kind":"string","value":"f19fae0c05ee0dbd9822a73ba1fca0fe95d43f53"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2023-03-16T14:30:30.793979","string":"2023-03-16T14:30:30.793979"},"revision_date":{"kind":"timestamp","value":"2013-05-01T05:51:43","string":"2013-05-01T05:51:43"},"committer_date":{"kind":"timestamp","value":"2013-05-01T05:51:43","string":"2013-05-01T05:51:43"},"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":"# MMO Lite 2007\r\n# Master Server - handle user registration, authentication\r\n\r\n#register \"current working folder as system path\"\r\n#there is probably a better way of doing this (change from Python 2.4->2.5)\r\nimport sys, os\r\nsys.path.append(os.getcwd())\r\n\r\nfrom twisted.spread import pb\r\nfrom twisted.cred import checkers, credentials, portal, error as credError\r\nfrom twisted.internet import reactor, defer\r\nfrom twisted.python import failure, log, logfile\r\nfrom zope.interface import Interface, implements\r\n\r\nfrom mmolite.common.define import *\r\nfrom mmolite.common.exceptions import *\r\nfrom mmolite.master.avatars import *\r\nfrom mmolite.master.db_serv import Accounts, Peers, PeersInfo, MasterDBObject\r\nfrom mmolite.common.util import getOptions\r\nfrom mmolite.common.db_serv import Clients\r\n\r\nclass MasterPasswordChecker(object):\r\n implements(checkers.ICredentialsChecker)\r\n credentialInterfaces = (credentials.IUsernamePassword, \r\n credentials.IUsernameHashedPassword)\r\n \r\n def __init__(self):\r\n return\r\n \r\n def requestAvatarId(self, credentials):\r\n type = ObjectType.Peer\r\n name = credentials.username\r\n \r\n row = PeersInfo.selectBy(peername = name)\r\n if row.count() == 0: \r\n type = ObjectType.User\r\n row = Accounts.selectBy(username = name) \r\n if row.count() == 0:\r\n print \"Login Failed: username[%s]\"%(name)\r\n return failure.Failure(credError.UnauthorizedLogin(\"Bad username\"))\r\n peer = row[0]\r\n return defer.maybeDeferred(credentials.checkPassword, peer.password).addCallback(\r\n self._checkedPassword, name, peer.role, type)\r\n \r\n def _checkedPassword(self, matched, name, role, type):\r\n if matched:\r\n return (name, role, type)\r\n else:\r\n print \"Login Failed: username[%s] role[%s] peer[%s]\"%(name, role, type==ObjectType.Peer)\r\n return failure.Failure(credError.UnauthorizedLogin(\"Bad password\"))\r\n \r\nclass MasterRealm(object):\r\n implements(portal.IRealm)\r\n \r\n def __init__(self):\r\n self.userList = {}\r\n self.peerList = {}\r\n return\r\n \r\n def requestAvatar(self, avatarId, mind, *interfaces):\r\n if not pb.IPerspective in interfaces:\r\n raise KeyError(\"No supported avatar Interface\")\r\n return\r\n \r\n name, role, type = avatarId[0], avatarId[1], avatarId[2]\r\n\r\n if type == ObjectType.Peer:\r\n if role & PeerType.Master == PeerType.Master: # e.g. secondary master\r\n avatar = MasterPerspective(mind, self)\r\n elif role & PeerType.Character == PeerType.Character:\r\n avatar = CharacterPerspective(mind, self)\r\n elif role & PeerType.World == PeerType.World:\r\n avatar = WorldPerspective(mind, self)\r\n elif role & PeerType.Cluster == PeerType.Cluster:\r\n avatar = ClusterPerspective(mind, self)\r\n elif role & PeerType.Zone == PeerType.Zone:\r\n avatar = ZonePerspective(mind, self)\r\n else: # PeerType.Client, dun need store into peerList ?\r\n avatar = ClientPerspective(mind, self)\r\n self.peerList[avatar.uniqId] = avatar\r\n else: # user\r\n if role & UserType.Admin == UserType.Admin:\r\n avatar = AdminPerspective(name, mind, self)\r\n elif role & UserType.GameMaster == UserType.GameMaster:\r\n avatar = GameMasterPerspective(name, mind, self)\r\n elif role & UserType.PremiumMember == UserType.PremiumMember:\r\n avatar = PremiumMemberPerspective(name, mind, self)\r\n else: # role & UserType.Member == UserType.Member:\r\n avatar = MemberPerspective(name, mind, self)\r\n self.userList[avatar.uniqId] = avatar\r\n print \"User Login: username[%s] role[%s] uniq[%d] peer[%s]\"%(name, role, avatar.uniqId, type==ObjectType.Peer)\r\n \r\n return pb.IPerspective, avatar, avatar.logout\r\n \r\n # keep alive + load balancing\r\n def updateLoads(self):\r\n for key in self.peerList:\r\n self.peerList[key].updateLoad()\r\n \r\n # TODO: proper peer matching, currently always switch to peer 0\r\n def changeServer(self, worldId, id, name, authenticID, mode):\r\n if worldId not in self.peerList : raise ServerNotFoundError(\"Server not found\")\r\n peer = self.peerList[worldId]\r\n peer.newClient(id, name, authenticID, mode)\r\n return peer.getInfo()\r\n \r\n def logout(self, avatar):\r\n key = avatar.uniqId\r\n if key in self.userList:\r\n del self.userList[key]\r\n elif key in self.peerList:\r\n del self.peerList[key]\r\n\r\ndef keepAlive(realm):\r\n reactor.callLater(300, keepAlive, realm) # call every 5 mins\r\n realm.updateLoads()\r\n\r\ndef main():\r\n OPTIONS, argv = getOptions('mmolite/config/servers.cfg', 'master server', sys.argv)\r\n \r\n dbconn = MasterDBObject('master.db', 'mmolite/data')\r\n \r\n if OPTIONS.setup: \r\n print \"Setting up Master Server...\"\r\n \r\n dbconn.resetDB()\r\n user = PeersInfo(peername = \"Master\", password = \"retsam\", role = PeerType.Master)\r\n user = PeersInfo(peername = \"Character\", password = \"retcarahc\", role = PeerType.Character)\r\n user = PeersInfo(peername = \"World\", password = \"dlrow\", role = PeerType.World)\r\n user = PeersInfo(peername = \"Cluster\", password = \"retsulc\", role = PeerType.Cluster)\r\n user = PeersInfo(peername = \"Zone\", password = \"enoz\", role = PeerType.Zone)\r\n user = PeersInfo(peername = \"Client\", password = \"tneilc\", role = PeerType.Client)\r\n user = Accounts(username = \"darren\", password = \"nerrad\", role = UserType.Admin)\r\n print \"Successfully\"\r\n return\r\n else: \r\n print \"Initialize Master Server database...\"\r\n dbconn.startDB()\r\n Peers.dropTable(ifExists=True); Peers.createTable()\r\n print \"Master Server Listening to port: %d\"%OPTIONS.master_port\r\n \r\n realm = MasterRealm()\r\n p = portal.Portal(realm)\r\n p.registerChecker(MasterPasswordChecker())\r\n reactor.listenTCP(OPTIONS.master_port, pb.PBServerFactory(p))\r\n\r\n keepAlive(realm)\r\n reactor.run()\r\n\r\nif __name__ == '__main__':\r\n main()"},"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":41377,"cells":{"__id__":{"kind":"number","value":549755829779,"string":"549,755,829,779"},"blob_id":{"kind":"string","value":"b3310d89893d81840c8aaf2c216129b202e78373"},"directory_id":{"kind":"string","value":"1449b4c427474c907ff5de7d17be00cd81e904ba"},"path":{"kind":"string","value":"/czaheri-TestNetflix.py"},"content_id":{"kind":"string","value":"5c72a5cf56802e6ee93b33257c350dbaa9be644a"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"cs373-spring-2014/netflix-tests"},"repo_url":{"kind":"string","value":"https://github.com/cs373-spring-2014/netflix-tests"},"snapshot_id":{"kind":"string","value":"87206196e1cecf9875dbc546fa2db220b6c2b74d"},"revision_id":{"kind":"string","value":"27b3573751ffd9610ddce4dc078c040c0ecf539d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-05T17:43:06.912763","string":"2016-09-05T17:43:06.912763"},"revision_date":{"kind":"timestamp","value":"2014-02-17T09:06:53","string":"2014-02-17T09:06:53"},"committer_date":{"kind":"timestamp","value":"2014-02-17T09:06:53","string":"2014-02-17T09:06:53"},"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 python3\n\n# -------------------------------\n# TestNetflix.py\n# Comyar Zaheri\n# -------------------------------\n\n\"\"\"\nTo test the program:\n % python3 TestNetflix.py >& TestNetflix.out\n % chmod ugo+x TestNetflix.py\n % TestNetflix.py >& TestNetflix.out\n\"\"\"\n\n# -------\n# imports\n# -------\n\nimport io\nimport unittest\n\nfrom Netflix import *\n\n# -----------\n# TestCollatz\n# -----------\n\nclass TestNetflix (unittest.TestCase) :\n\n # ----\n # read\n # ----\n\n # Load files\n Globals.actual_ratings_cache = json.load(open(Globals.actual_ratings_path))\n Globals.avg_user_rating_cache = json.load(open(Globals.avg_user_rating_cache_path))\n Globals.avg_movie_ratings_cache = json.load(open(Globals.avg_movie_ratings_cache_path))\n\n def test_read_1 (self) :\n r = io.StringIO(\"2043:\\n1417435\\n\")\n m = netflix_read(r)\n movie, user = list(next(m))\n self.assertTrue(movie == \"2043\")\n self.assertTrue(user == \"1417435\")\n\n def test_read_2 (self) :\n r = io.StringIO(\"10851:\\n1417435\\n\")\n m = netflix_read(r)\n movie, user = list(next(m))\n self.assertTrue(movie == \"10851\")\n self.assertTrue(user == \"1417435\")\n\n def test_read_3 (self) :\n r = io.StringIO(\"2043:\\n1417435\\n2312054\\n\")\n m = netflix_read(r)\n movie, user = list(next(m))\n self.assertTrue(movie == \"2043\")\n self.assertTrue(user == \"1417435\")\n movie, user = list(next(m))\n self.assertTrue(movie == \"2043\")\n self.assertTrue(user == \"2312054\")\n\n # ----\n # predict\n # ----\n\n def test_predict_1 (self) :\n prediction = netflix_predict(\"2043\", \"1417435\")\n\n def test_predict_2 (self) :\n prediction = netflix_predict(\"2043\", \"2312054\")\n\n def test_predict_3 (self) :\n prediction = netflix_predict(\"10851\", \"1417435\")\n\n # -----\n # run\n # -----\n\n def test_run_1 (self) :\n r = io.StringIO(\"2043:\\n1417435\\n2312054\\n\")\n w = io.StringIO()\n netflix_run(r, w)\n\n def test_run_2 (self) :\n r = io.StringIO(\"2043:\\n1417435\\n2312054\\n\")\n w = io.StringIO()\n netflix_run(r, w)\n\n def test_run_3 (self) :\n r = io.StringIO(\"2043:\\n1417435\\n2312054\\n\")\n w = io.StringIO()\n netflix_run(r, w)\n\n# ----\n# main\n# ----\n\nprint(\"TestNetflix.py\")\nunittest.main()\nprint(\"Done.\")\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":41378,"cells":{"__id__":{"kind":"number","value":8787503126095,"string":"8,787,503,126,095"},"blob_id":{"kind":"string","value":"e441dca586d0758c78771676ea78ebc68cc08028"},"directory_id":{"kind":"string","value":"b98cb04fc51cb2e7c02b8c714443227875b70e94"},"path":{"kind":"string","value":"/game.py"},"content_id":{"kind":"string","value":"0b21e48b13682460c82db6e77ee357f5a523d023"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"namlede/srcerr"},"repo_url":{"kind":"string","value":"https://github.com/namlede/srcerr"},"snapshot_id":{"kind":"string","value":"d697571f8693681d6ddf69ca3de0f3179837db69"},"revision_id":{"kind":"string","value":"328b8128aedb282a150291a104c238a2fc6321d3"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-15T16:03:46.927082","string":"2016-09-15T16:03:46.927082"},"revision_date":{"kind":"timestamp","value":"2013-11-10T21:34:59","string":"2013-11-10T21:34:59"},"committer_date":{"kind":"timestamp","value":"2013-11-10T21:34:59","string":"2013-11-10T21:34:59"},"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 pygame import *\nimport math\nimport spells\nclass Sprite:\n def __init__(self, xpos, ypos, filename):\n\tself.x = xpos\n\tself.y = ypos\n\tself.bitmap = image.load(filename)\n\tself.bitmap.set_colorkey((0,0,0))\n def set_position(self, xpos, ypos):\n\tself.x = xpos\n\tself.y = ypos\n def render(self):\n global screen\n\tscreen.blit(self.bitmap, (self.x, self.y))\nclass Mob:\n def __init__(self,newGame):\n self.game = newGame\n self.radius = 100\n self.damage = 100\n self.x=20\n self.y=400\n self.health=10000\n self.states=[]\n def addState(self,a):\n states.append(a)\n def run(self):\n a=0\n for i in self.states:\n if(not i.run()):\n del self.states[a]\n a+=1\n\tif not (self.health>0):\n\t\traise \"You killed the mob!!!\"\n\t\tprint \"WIN\"\n\t\tprint 4/0 \n if (self.game.player.x-self.x)**2+(self.game.player.y-self.y)**2<=self.radius**2:\n self.game.player.health -= self.damage\n \n return self.health>0\nclass Player:\n def __init__(self):\n self.x=20\n self.y=400\n self.energy=50000\n self.health=10000\n self.states=[]\n\n def run(self):\n self.energy+=100\n self.health+=0\n\tif self.health < 0 or self.energy < 0:\n\t\traise \"You died.\"\n\t\tprint \"DIE\"\n\t\tprint 4/0\n\t\treturn False\nclass Spell:\n def __init__(self,newGame):\n self.game=newGame\n self.x=self.game.player.x\n self.y=self.game.player.y\n self.xvelocity=0\n self.yvelocity=0\n def setSpell(self,newUserSpell):\n self.userSpell=newUserSpell\n def run(self):\n self.x+=self.xvelocity\n self.y+=self.yvelocity\n self.alive = self.userSpell.run()\n return self.alive\n def getNouns(self):\n return self.game.nouns\n def getPlayerX(self):\n \treturn self.game.player.x\n def getPlayerY(self):\n \treturn self.game.player.y\n def doDamageWithinRadius(self,damage,radius):\n if (self.game.mob.x-self.x)**2+(self.game.mob.y-self.y)**2<=radius**2:\n self.game.mob.health-=damage\n self.game.player.energy-=radius+damage\n def healWithinRadius(self,heal,radius):\n if (self.game.player.x-self.x)**2+(self.game.player.y-self.y)**2<=radius**2:\n self.game.player.health+=heal\n self.game.player.energy-=radius+heal\n def changeVelocity(self,xChangeChange,yChangeChange):\n self.xvelocity+=xChangeChange\n self.yvelocity+=yChangeChange\n self.game.player.energy-=xChangeChange+yChangeChange\nclass Game:\n def __init__(self):\n init()\n global screen\n key.set_repeat(1, 1)\n display.set_caption('SrcError')\n self.playerSprite = Sprite(20, 400, 'player.png')\n self.mobSprite = Sprite(20, 400, 'mob.png')\n self.player=Player()\n self.mob=Mob(self)\n self.nouns=[self.player,self.mob]\n self.spellList=self.getSpells()\n self.activeSpells=[]\n def cast(self,index):\n a=Spell(self)\n b=self.spellList[index](a)\n a.setSpell(b)\n self.nouns.append(a)\n self.activeSpells.append([Sprite(self.playerSprite.x,self.playerSprite.y,'spell.png'),a])\n def getSpells(self):\n ret=[]\n for i in spells.names:\n ret.append(eval(\"spells.\"+i))\n return ret\n def run(self):\n global screen\n backdrop = image.load('backdrop.bmp')\n screen.blit(backdrop, (0, 0))\n\tfor ourevent in event.get():\n\t if ourevent.type == QUIT:\n\t\tquit = 1\n\t if ourevent.type == KEYDOWN:\n\t\tif ourevent.key == K_RIGHT:\n self.playerSprite.x += 20\n self.player.x += 20\n\t\tif ourevent.key == K_LEFT:\n\t\t self.playerSprite.x -=20\n self.player.x -= 20\n if ourevent.key == K_DOWN:\n\t\t self.playerSprite.y +=20\n self.player.y += 20\n if ourevent.key == K_UP:\n\t\t self.playerSprite.y -=20\n self.player.y -= 20\n\t\tif ourevent.key == K_1:\n\t\t self.cast(0)\n\t\tif ourevent.key == K_2:\n\t\t self.cast(1)\n\t\tif ourevent.key == K_3:\n\t\t self.cast(2)\n a=0\n for i in self.nouns:\n if(not i.run()):\n del self.nouns[a]\n self.player.run()\n if True:\n self.mobSprite.x-=int(0.02*(self.mob.x-self.player.x))\n self.mobSprite.y-=int(0.02*(self.mob.y-self.player.y))\n self.mob.x=self.mobSprite.x\n self.mob.y=self.mobSprite.y\n iterer=0\n for i in self.activeSpells:\n k=i[1].run()\n if(not k):\n del self.activeSpells[iterer]\n break\n i[0].x=i[1].x\n i[0].y=i[1].y\n i[0].render()\n iterer+=1\n \n a+=1\n self.mobSprite.render()\n self.playerSprite.render()\n print [\"Energy: \" + str(self.player.energy), \"Health: \" + str(self.player.health), \"Mob Health: \" + str(self.mob.health)]\n display.update()\n\ttime.delay(5)\nscreen = display.set_mode((768,768))\na=Game()\nfor i in range(100000):\n a.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":2013,"string":"2,013"}}},{"rowIdx":41379,"cells":{"__id__":{"kind":"number","value":6674379183466,"string":"6,674,379,183,466"},"blob_id":{"kind":"string","value":"1fc9f7d2457a208f1a8da3d12eb9e38818e50749"},"directory_id":{"kind":"string","value":"65791f3b4a09082412f3799add8b86e43b47b436"},"path":{"kind":"string","value":"/POTENTIAL_FIELDS/agent9.py"},"content_id":{"kind":"string","value":"b98980af6c0e842d75a989ee9518edf5166b187d"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"lwthatcher/CS-470"},"repo_url":{"kind":"string","value":"https://github.com/lwthatcher/CS-470"},"snapshot_id":{"kind":"string","value":"b666805409e2c11b1688df98725f3a32f7e54d90"},"revision_id":{"kind":"string","value":"d1dfbcd8d886b8dc1a9139ed63e6cc42badf5025"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-23T20:46:53.998996","string":"2021-01-23T20:46:53.998996"},"revision_date":{"kind":"timestamp","value":"2014-12-11T17:28:38","string":"2014-12-11T17:28:38"},"committer_date":{"kind":"timestamp","value":"2014-12-11T17:28:38","string":"2014-12-11T17:28: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":"#!/usr/bin/python -tt\n\n# An incredibly simple agent. All we do is find the closest enemy tank, drive\n# towards it, and shoot. Note that if friendly fire is allowed, you will very\n# often kill your own tanks with this code.\n\n#################################################################\n# NOTE TO STUDENTS\n# This is a starting point for you. You will need to greatly\n# modify this code if you want to do anything useful. But this\n# should help you to know how to interact with BZRC in order to\n# get the information you need.\n#\n# After starting the bzrflag server, this is one way to start\n# this code:\n# python agent0.py [hostname] [port]\n#\n# Often this translates to something like the following (with the\n# port name being printed out by the bzrflag server):\n# python agent0.py localhost 49857\n#################################################################\n\nimport sys\nimport math\nimport time\nimport random\n\nfrom bzrc import BZRC, Command\nfrom numpy import linspace\n\nclass Agent(object):\n\t\"\"\"Class handles all command and control logic for a teams tanks.\"\"\"\n\n\tdef __init__(self, bzrc):\n\t\tself.bzrc = bzrc\n\t\tself.constants = self.bzrc.get_constants()\n\t\tself.commands = []\n\t\tself.ALPHA = 0.01\n\t\tself.BETA = 0.3\n\t\tself.OBS_TOLERANCE = 30.0\n\t\tself.S = 50\n\t\tself.wroteonce = False\n\t\tself.goalradius = 30\n\t\t\n\t\tself.tankradius = 5\n\t\tself.avoidradius = 50\n\t\tself.avoidBETA = .1\n\t\t\n\t\tself.aimtolerance = math.pi/20\n\n\tdef tick(self, time_diff):\n\t\t\"\"\"Some time has passed; decide what to do next.\"\"\"\n\t\tmytanks, othertanks, flags, shots = self.bzrc.get_lots_o_stuff()\n\t\tself.mytanks = mytanks\n\t\tself.othertanks = othertanks\n\t\tself.flags = [flag for flag in flags if flag.color != self.constants['team']]\n\t\tself.shots = shots\n\t\tself.enemies = [tank for tank in othertanks if tank.color !=\n\t\t\t\t\t\tself.constants['team']]\n\t\tself.obstacles = self.bzrc.get_obstacles()\n\t\tself.commands = []\n\t\t\n\t\tmake_map = GnuPlot(self, self.flags, self.obstacles) \n\t\t\n\t\tif not self.wroteonce:\n\t\t\tmake_map.generateGnuMap()\n\t\t\tself.wroteonce = True\n\t\t\n\t\tfor tank in mytanks:\n\t\t\tif tank.flag == '-':\n\t\t\t\tself.goto_flags(tank)\n\t\t\telse:\n\t\t\t\tbase_x, base_y = self.get_base_center(self.get_my_base())\n\t\t\t\tself.move_to_position(tank, base_x, base_y)\n\n\t\tresults = self.bzrc.do_commands(self.commands)\n\n\n\tdef get_my_base(self):\n\t\tmybases = [base for base in self.bzrc.get_bases() if base.color == self.constants['team']]\n\t\tmybase = mybases[0]\n\t\treturn mybase\n\t\n\tdef get_base_center(self, base):\n\t\tcenter_x = ((base.corner1_x + base.corner2_x + base.corner3_x + base.corner4_x) / 4)\n\t\tcenter_y = ((base.corner1_y + base.corner2_y + base.corner3_y + base.corner4_y) / 4)\n\t\treturn center_x, center_y\n\n\tdef goto_flags(self, tank):\n\t\tbest_flag = self.get_best_flag(tank.x, tank.y)\n\t\tif best_flag is None:\n\t\t\tcommand = Command(tank.index, 0, 0, False)\n\t\t\tself.commands.append(command)\n\t\telse:\n\t\t\tself.move_to_position(tank, best_flag.x, best_flag.y)\n\n\tdef get_best_flag(self, x, y):\n\t\tbest_flag = None\n\t\tbest_dist = 2 * float(self.constants['worldsize'])\n\t\tfor flag in self.flags:\n\t\t\tdist = math.sqrt((flag.x - x)**2 + (flag.y - y)**2)\n\t\t\tif dist < best_dist:\n\t\t\t\tbest_dist = dist\n\t\t\t\tbest_flag = flag\n\t\treturn best_flag\n\t\t\n\tdef should_fire(self, tank):\n\t\tfor enemy in self.enemies:\n\t\t\ttarget_angle = math.atan2(enemy.y - tank.y, enemy.x - tank.x)\n\t\t\tif abs(tank.angle - target_angle) < self.aimtolerance:\n\t\t\t\tprint \"firing \", tank.index\n\t\t\t\treturn True\n\t\t\t\t\n\t\treturn False\n\t\t\n\tdef avoid_target(self, my_x, my_y, target_x, target_y):\n\t\tgoal_dist = math.sqrt((target_x - my_x)**2 + (target_y - my_y)**2)\n\t\ttarget_angle = math.atan2(target_y - my_y, target_x - my_x)\n\t\t\n\t\tdx = 0\n\t\tdy = 0\n\t\t\n\t\ts = self.avoidradius\n\t\tr = self.tankradius\n\t\t\n\t\tif goal_dist < self.tankradius:\n\t\t\tdx = -1 * math.cos(target_angle) * 1000 #infinity\n\t\t\tdy = -1 * math.sin(target_angle) * 1000 #infinity\n\t\telif goal_dist >= self.tankradius and goal_dist <= (s + r):\n\t\t\tdx = -1 * self.avoidBETA * (s + r - goal_dist) * math.cos(target_angle)\n\t\t\tdy = -1 * self.avoidBETA * (s + r - goal_dist) * math.sin(target_angle)\n\t\telse:\n\t\t\tdx = 0\n\t\t\tdy = 0\n\t\treturn dx, dy\n\t\t\n\tdef calculate_enemies_delta(self, my_x, my_y, enemies):\n\t\tdelta_x = 0\n\t\tdelta_y = 0\n\t\t\n\t\tfor tank in enemies:\n\t\t\tdx, dy = self.avoid_target(my_x, my_y, tank.x, tank.y)\n\t\t\tdelta_x += dx\n\t\t\tdelta_y += dy\n\t\t\n\t\tsqnorm = math.sqrt(delta_x**2 + delta_y**2)\n\t\t\n\t\tif sqnorm == 0:\n\t\t\tdelta_x = 0\n\t\t\tdelta_y = 0\n\t\telse:\n\t\t\tdelta_x = delta_x / sqnorm\n\t\t\tdelta_y = delta_y / sqnorm\n\t\t\n\t\treturn delta_x, delta_y\n\n\tdef calculate_objective_delta(self, my_x, my_y, target_x, target_y):\n\t\tgoal_dist = math.sqrt((target_x - my_x)**2 + (target_y - my_y)**2)\n\t\ttarget_angle = math.atan2(target_y - my_y, target_x - my_x)\n\t\t\n\t\tdelta_xG = self.ALPHA * goal_dist * math.cos(target_angle) # r = 0\n\t\tdelta_yG = self.ALPHA * goal_dist * math.sin(target_angle) # r = 0\n\t\t\n\t\tsqnorm = math.sqrt(delta_xG**2 + delta_yG**2)\n\t\t\n\t\t#set magnitude\n\t\tmagnitude = 0\n\t\tif goal_dist > self.goalradius:\n\t\t\tmagnitude = 1\n\t\telse:\n\t\t\tmagnitude = sqnorm\n\t\t\n\t\tif sqnorm == 0:\n\t\t\tdelta_xG = 0\n\t\t\tdelta_yG = 0\n\t\telse:\n\t\t\tdelta_xG = delta_xG / sqnorm\n\t\t\tdelta_yG = delta_yG / sqnorm\n\t\t\t\n\t\treturn delta_xG, delta_yG, magnitude\n\n\tdef calculate_obstacles_delta(self, x, y):\n\t\tdelta_xO = 0\n\t\tdelta_yO = 0\n\t\t\n\t\tfor obs in self.obstacles:\n\t\t\trepel_xO, repel_yO = self.get_obstacle_force(obs, x, y)\n\t\t\tdelta_xO += repel_xO\n\t\t\tdelta_yO += repel_yO\n\t\t\n\t\tsqnorm = math.sqrt(delta_xO**2 + delta_yO**2)\n\t\t\t\n\t\tif sqnorm == 0:\n\t\t\tdelta_xO = 0\n\t\t\tdelta_yO = 0\n\t\telse:\n\t\t\tdelta_xO = delta_xO / sqnorm\n\t\t\tdelta_yO = delta_yO / sqnorm\n\t\t\n\t\t'''if delta_xG != 0 or delta_yG != 0:\n\t\t\tprint \"delta_xO: \", delta_xO\n\t\t\tprint \"delta_yO: \", delta_yO'''\n\t\t\t\n\t\treturn delta_xO, delta_yO\n\n\tdef calculate_random_delta(self):\n\t\tdx = random.uniform(-.01, .01)\n\t\tdy = random.uniform(-.01, .01)\n\t\treturn dx, dy\n\n\tdef move_to_position(self, tank, target_x, target_y):\n\t\t\"\"\"Set command to move to given coordinates.\"\"\"\n\t\t\n\t\t#get deltas\n\t\tdelta_xG, delta_yG, magnitude = self.calculate_objective_delta(tank.x, tank.y, target_x, target_y)\n\t\tdelta_xO, delta_yO = self.calculate_obstacles_delta(tank.x, tank.y)\n\t\tdelta_xR, delta_yR = self.calculate_random_delta()\n\t\tdelta_xA, delta_yA = self.calculate_enemies_delta(tank.x, tank.y, self.enemies)\n\t\t\n\t\t#combine\n\t\tdelta_x = delta_xG + delta_xO + delta_xR + delta_xA\n\t\tdelta_y = delta_yG + delta_yO + delta_yR + delta_xA\n\t\t\n\t\t#calculate angle\n\t\tturn_angle = math.atan2(delta_y, delta_x)\n\t\trelative_angle = self.normalize_angle(turn_angle - tank.angle)\n\t\t\n\t\t#put lower bound on speed: no slower than 40%\n\t\tif magnitude < 0.2:\n\t\t\tmagnitude = 0.2\n\t\t\n\t\tfire = self.should_fire(tank)\n\t\t\n\t\tcommand = Command(tank.index, magnitude, 2 * relative_angle, fire)\n\t\tself.commands.append(command)\n\t\n\tdef get_obstacle_force(self, obstacle, x, y):\n\t\t# I need to go around the obstacle and calculate the min_x and min_y distance for the tank\n\t\t\n\t\tdelta_x = 0 \n\t\tdelta_y = 0\n\t\t\n\t\tp1 = obstacle[0]\n\t\tfor p2 in obstacle[1:]:\n\t\t\trepel_x, repel_y = self.get_repel_field(x, y, p1, p2)\n\t\t\tdelta_x += repel_x\n\t\t\tdelta_y += repel_y\t\t\t\t\n\t\t\tp1 = p2\n\t\t\n\t\trepel_x, repel_y = self.get_repel_field(x, y, p2, obstacle[0])\n\t\t\t\t\n\t\treturn delta_x, delta_y\n\t\n\tdef get_repel_field(self, x, y, p1, p2):\n\t\tmy_x = x\n\t\tmy_y = y\n\t\t\n\t\tif self.between_endpoints(my_x, my_y, p1, p2): # need to consider if it's between the start and end of the line\n\t\t\tx1, y1 = p1\n\t\t\tx2, y2 = p2\n\t\t\t\n\t\t\t# find the distance from the tank to the line formed by p1 and p2\n\t\t\t# ax + by + c = 0\n\t\t\ta = y1 - y2\n\t\t\tb = x2 - x1\n\t\t\tc = x1 * y2 - x2 * y1\n\t\t\t\n\t\t\tsqnorm = math.sqrt(a**2 + b**2)\n\t\t\t\n\t\t\t# shortest distance from tank to obstacle\n\t\t\tdist = abs(a * my_x + b * my_y + c) / sqnorm\n\t\t\t\n\t\t\tif dist < self.OBS_TOLERANCE:\n\t\t\t\t# normal vector purpendicular to the obstacle\n\t\t\t\tn_hat = [a / sqnorm, b / sqnorm] \n\t\t\t\t\n\t\t\t\t# get the point on the obstacle that is closest to the tank\n\t\t\t\tscalar = dist - self.dot(my_x, my_y, n_hat)\n\t\t\t\t#scalar = self.dot(my_x, my_y, n_hat) - dist\n\t\t\t\t\n\t\t\t\tobs_point = [my_x + scalar * n_hat[0], my_y + scalar * n_hat[1]]\n\t\t\t\t\n\t\t\t\t'''print \"obs_point: \", obs_point\n\t\t\t\tprint \"tank.x: \", my_x\n\t\t\t\tprint \"tank.y: \", my_y\n\t\t\t\tprint \"dist: \", dist\n\t\t\t\tprint \"scalar: \", scalar\n\t\t\t\tprint'''\n\t\t\t\t\n\t\t\t\t# angle between the tank and the obstacle\n\t\t\t\ttheta = self.get_theta(my_x, my_y, p1, p2, obs_point[0], obs_point[1])\n\n\t\t\t\tdelta_x = -self.BETA * (self.OBS_TOLERANCE - dist) * math.cos(theta) # math.cos returns in radians\n\t\t\t\tdelta_y = -self.BETA * (self.OBS_TOLERANCE - dist) * math.sin(theta)\n\t\t\t\t\n\t\t\t\treturn delta_x, delta_y\n\t\t\telse:\n\t\t\t\treturn 0, 0\n\t\telse:\n\t\t\treturn 0, 0 # this obstacle doesn't have a repelling affect on the tank\n\t\n\tdef get_theta(self, x, y, p1, p2, obs_x, obs_y):\n\t\tx1, y1 = p1\n\t\tx2, y2 = p2\n\t\t\n\t\t'''print \"x: \", x\n\t\tprint \"y: \", y\n\t\tprint \"obs_x: \", obs_x\n\t\tprint \"obs_y: \", obs_y'''\n\t\t\n\t\ttheta = 0\n\t\t\n\t\tif self.is_vertical(x1, x2):\n\t\t\tif x < obs_x: #the tank is on the left side of the obstacle\n\t\t\t\ttheta = math.atan2(obs_y - y, obs_x - x)\n\t\t\t\t#print \"vertical left theta: \", theta\n\t\t\telse: # the tank is on the right side of the obstacle\n\t\t\t\ttheta = math.atan2(obs_y - y, obs_x - x)\n\t\t\t\t#print \"vertical right theta: \", theta\n\t\t\n\t\telif self.is_horizontal(y1, y2):\n\t\t\t#print \"obs_y: \", obs_y\n\t\t\tif y <= obs_y: # the tank is north of the line\n\t\t\t\tif y < 0:\n\t\t\t\t\ttheta = math.atan2(y - obs_y, obs_x - x)\n\t\t\t\telse:\n\t\t\t\t\ttheta = math.atan2(y - obs_y, obs_x - x)\n\t\t\t\t#print \"horizontal north theta: \", theta\n\t\t\telse: # the tank is south of the line\n\t\t\t\tif y < 0:\n\t\t\t\t\ttheta = math.atan2(y - obs_y, x - obs_x)\n\t\t\t\telse:\n\t\t\t\t\ttheta = math.atan2(obs_y - y, x - obs_x)\n\t\t\t\t#print \"horizontal south theta: \", theta\n\t\t\n\t\treturn theta\n\t\n\tdef is_horizontal(self, y1, y2):\n\t\tif y1 == y2:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\t\t\t\n\tdef is_vertical(self, x1, x2):\n\t\tif x1 == x2:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\t\n\tdef between_endpoints(self, x, y, p1, p2):\n\t\tx1, y1 = p1\n\t\tx2, y2 = p2\n\t\t\n\t\tif self.is_vertical(x1, x2): # vertical line\n\t\t\tif y > min([y1, y2]) and y < max([y1, y2]):\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\t\telif self.is_horizontal(y1, y2): # horizontal line\n\t\t\tif x > min([x1, x2]) and x < max([x1,x2]):\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\t\telse: # diagonal line (this checks a box)\n\t\t\tif x > min([x1, x2]) and x < max([x1, x2]) and y > min([y1, y2]) and y < max([y1, y2]):\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\t\n\tdef dot(self, x, y, n_hat):\n\t\treturn (x * n_hat[0] + y * n_hat[1])\n\t\n\tdef normalize_angle(self, angle):\n\t\t\"\"\"Make any angle be between +/- pi.\"\"\"\n\t\tangle -= 2 * math.pi * int (angle / (2 * math.pi))\n\t\tif angle <= -math.pi:\n\t\t\tangle += 2 * math.pi\n\t\telif angle > math.pi:\n\t\t\tangle -= 2 * math.pi\n\t\treturn angle\n\nclass Tank(object):\n\tpass\n\nclass GnuPlot():\n\t\n\tdef __init__(self, agent, flags, obstacles):\n\t\tself.agent = agent\n\t\tself.bzrc = agent.bzrc\n\t\tself.constants = self.bzrc.get_constants()\n\t\t\n\t\tself.FILENAME = 'plot.gpi'\n\t\tself.WORLDSIZE = 800\n\t\tself.SAMPLES = 50\n\t\tself.VEC_LEN = 0.75 * self.WORLDSIZE / self.SAMPLES\n\t\t\n\t\tself.flags = flags\n\t\tself.obstacles = obstacles\n\t\t\n\t\n\tdef generateGnuMap(self):\n\t\toutfile = open(self.FILENAME, 'w')\n\t\tminimum = -self.WORLDSIZE / 2\n\t\tmaximum = self.WORLDSIZE / 2\n\t\tprint >>outfile, self.gnuplot_header(minimum, maximum)\n\t\tprint >>outfile, self.draw_obstacles(self.bzrc.get_obstacles())\n\t\tfield_function = self.generate_field_function(150)\n\t\tprint >>outfile, self.plot_field(field_function)\n\t\toutfile.close()\n\t\t\n\tdef generate_field_function(self, scale):\n\t\t\n\t\ttank1 = Tank()\n\t\ttank1.x = 0\n\t\ttank1.y = 150\n\t\t\n\t\ttank2 = Tank()\n\t\ttank2.x = 0\n\t\ttank2.y = -200\n\t\t\n\t\tfaketanks = [tank1, tank2]\n\t\t\n\t\tdef function(x, y):\n\t\t\ttarget = self.agent.get_best_flag(x, y)\n\t\t\t\n\t\t\t#get deltas\n\t\t\tdelta_xG, delta_yG = [0, 0]\n\t\t\tmagnitude = 1\n\t\t\t##delta_xG, delta_yG, magnitude = self.agent.calculate_objective_delta(x, y, target.x, target.y)\n\t\t\tdelta_xO, delta_yO = self.agent.calculate_obstacles_delta(x, y)\n\t\t\tdelta_xA, delta_yA = self.agent.calculate_enemies_delta(x, y, faketanks)\n\t\t\t\n\t\t\t#combine\n\t\t\tdelta_x = delta_xG + delta_xO + delta_xA\n\t\t\tdelta_y = delta_yG + delta_yO + delta_yA\n\t\t\t\n\t\t\tmagnitude = math.sqrt(delta_x**2 + delta_y**2)\n\t\t\t\n\t\t\treturn delta_x*scale*magnitude, delta_y*scale*magnitude\n\t\t\t\n\t\treturn function\n\t\n\tdef gpi_point(self, x, y, vec_x, vec_y):\n\t\t'''Create the centered gpi data point (4-tuple) for a position and\n\t\tvector. The vectors are expected to be less than 1 in magnitude,\n\t\tand larger values will be scaled down.'''\n\t\tr = (vec_x ** 2 + vec_y ** 2) ** 0.5\n\t\tif r > 1:\n\t\t\tvec_x /= r\n\t\t\tvec_y /= r\n\t\treturn (x - vec_x * self.VEC_LEN / 2, y - vec_y * self.VEC_LEN / 2,\n\t\t\t\tvec_x * self.VEC_LEN, vec_y * self.VEC_LEN)\n\t\n\tdef gnuplot_header(self, minimum, maximum):\n\t\t'''Return a string that has all of the gnuplot sets and unsets.'''\n\t\ts = ''\n\t\ts += 'set xrange [%s: %s]\\n' % (minimum, maximum)\n\t\ts += 'set yrange [%s: %s]\\n' % (minimum, maximum)\n\t\t# The key is just clutter. Get rid of it:\n\t\ts += 'unset key\\n'\n\t\t# Make sure the figure is square since the world is square:\n\t\ts += 'set size square\\n'\n\t\t# Add a pretty title (optional):\n\t\t#s += \"set title 'Potential Fields'\\n\"\n\t\treturn s\n\n\tdef draw_line(self, p1, p2):\n\t\t'''Return a string to tell Gnuplot to draw a line from point p1 to\n\t\tpoint p2 in the form of a set command.'''\n\t\tx1, y1 = p1\n\t\tx2, y2 = p2\n\t\treturn 'set arrow from %s, %s to %s, %s nohead lt 3\\n' % (x1, y1, x2, y2)\n\n\tdef draw_obstacles(self, obstacles):\n\t\t'''Return a string which tells Gnuplot to draw all of the obstacles.'''\n\t\ts = 'unset arrow\\n'\n\t\n\t\tfor obs in obstacles:\n\t\t\tlast_point = obs[0]\n\t\t\tfor cur_point in obs[1:]:\n\t\t\t\ts += self.draw_line(last_point, cur_point)\n\t\t\t\tlast_point = cur_point\n\t\t\ts += self.draw_line(last_point, obs[0])\n\t\treturn s\n\n\tdef plot_field(self, function):\n\t\t'''Return a Gnuplot command to plot a field.'''\n\t\ts = \"plot '-' with vectors head\\n\"\n\t\n\t\tseparation = self.WORLDSIZE / self.SAMPLES\n\t\tend = self.WORLDSIZE / 2 - separation / 2\n\t\tstart = -end\n\n\t\tpoints = ((x, y) for x in linspace(start, end, self.SAMPLES)\n\t\t\t\t\tfor y in linspace(start, end, self.SAMPLES))\n\t\n\t\tfor x, y in points:\n\t\t\tf_x, f_y = function(x, y)\n\t\t\tplotvalues = self.gpi_point(x, y, f_x, f_y)\n\t\t\tif plotvalues is not None:\n\t\t\t\tx1, y1, x2, y2 = plotvalues\n\t\t\t\ts += '%s %s %s %s\\n' % (x1, y1, x2, y2)\n\t\ts += 'e\\n'\n\t\treturn s\n\ndef main():\n\t# Process CLI arguments.\n\ttry:\n\t\texecname, host, port = sys.argv\n\texcept ValueError:\n\t\texecname = sys.argv[0]\n\t\tprint >>sys.stderr, '%s: incorrect number of arguments' % execname\n\t\tprint >>sys.stderr, 'usage: %s hostname port' % sys.argv[0]\n\t\tsys.exit(-1)\n\n\t# Connect.\n\t#bzrc = BZRC(host, int(port), debug=True)\n\tbzrc = BZRC(host, int(port))\n\n\tagent = Agent(bzrc)\n\n\tprev_time = time.time()\n\n\t# Run the agent\n\ttry:\n\t\twhile True:\n\t\t\ttime_diff = time.time() - prev_time\n\t\t\tagent.tick(time_diff)\n\texcept KeyboardInterrupt:\n\t\tprint \"Exiting due to keyboard interrupt.\"\n\t\tbzrc.close()\n\n\nif __name__ == '__main__':\n\tmain()\n\n# vim: et sw=4 sts=4\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":41380,"cells":{"__id__":{"kind":"number","value":9405978402797,"string":"9,405,978,402,797"},"blob_id":{"kind":"string","value":"71b692a951e6c7092f171deb99dc1d1c6bf52d9f"},"directory_id":{"kind":"string","value":"f48ac175974b459b22e7451a531f4ec7ab089a9a"},"path":{"kind":"string","value":"/app/tests.py"},"content_id":{"kind":"string","value":"ec362bcbbcc57e09c964f254fd1dd3f1f168c48d"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Tr-Heath/FlaskMicroBlog"},"repo_url":{"kind":"string","value":"https://github.com/Tr-Heath/FlaskMicroBlog"},"snapshot_id":{"kind":"string","value":"87dd23bf3d91eb2a10c445153ea3405d5a1ce72b"},"revision_id":{"kind":"string","value":"2919cd5832b53fd5ee869249ec9fdc7b32064687"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-01T16:19:52.575471","string":"2021-01-01T16:19:52.575471"},"revision_date":{"kind":"timestamp","value":"2014-05-26T22:56:35","string":"2014-05-26T22:56:35"},"committer_date":{"kind":"timestamp","value":"2014-05-26T22:56:35","string":"2014-05-26T22:56: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":"#!flask/bin/python\nimport os\nimport unittest"},"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":41381,"cells":{"__id__":{"kind":"number","value":14396730422471,"string":"14,396,730,422,471"},"blob_id":{"kind":"string","value":"5bc18ee1a8c844386ea46bc246b2f767d534162b"},"directory_id":{"kind":"string","value":"3a08d9e3497b33028efd6ad6765b9388fca65438"},"path":{"kind":"string","value":"/csdexec/csip/models.py"},"content_id":{"kind":"string","value":"f949bf80f5a9552c68fcbab6e98a5321317d6ca3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"recluze/fastnu-csd-audit"},"repo_url":{"kind":"string","value":"https://github.com/recluze/fastnu-csd-audit"},"snapshot_id":{"kind":"string","value":"6f04ea03a0be44dbde2cdfc9286000dcecb29493"},"revision_id":{"kind":"string","value":"7c66c07a0730d238c4df09c475cb56a0dc3e72e4"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-24T13:35:21.195585","string":"2020-12-24T13:35:21.195585"},"revision_date":{"kind":"timestamp","value":"2013-04-23T03:58:49","string":"2013-04-23T03:58:49"},"committer_date":{"kind":"timestamp","value":"2013-04-23T03:58:49","string":"2013-04-23T03:58:49"},"github_id":{"kind":"number","value":7124630,"string":"7,124,630"},"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":"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 cscm.models import Instructor \nfrom cscm.helpers.choices import * \nfrom cscm.helpers.functions import get_pub_string\n\nfrom datetime import timedelta\nfrom dateutil import relativedelta as rdelta\n\n\nclass InstructorProfile(models.Model):\n instructor = models.OneToOneField(Instructor)\n date_of_birth = models.DateField(blank=True)\n department = models.CharField(max_length=100)\n \n designation = models.CharField(max_length=50, choices=DESIGNATION_CHOICES)\n current_position_appointment_date = models.DateField()\n joining_date = models.DateField()\n \n email = models.EmailField()\n contact_number = models.CharField(max_length=100, blank=True)\n contact_address = models.TextField(blank=True)\n \n areas_of_interest = models.TextField(blank=True, help_text='Please enter one area per line')\n statement_of_research = models.TextField(blank=True, help_text='Please provide a brief statement about your research interest')\n \n admin_responsibility = models.TextField(blank=True)\n pay_grade = models.CharField(max_length=50, blank=True)\n pay_step = models.CharField(max_length=50, blank=True)\n gross_pay = models.CharField(max_length=50, blank=True)\n percent_time_teaching = models.CharField(max_length=4, blank=True, help_text='Percentage of contact hours to total time (formula: contact_hours/42 * 100). Please do not suffix the \\'%\\' symbol ')\n services_to_dept = models.TextField('Services to the University', blank=True)\n awards = models.TextField('Academic Awards/Distinctions', blank=True)\n memberships = models.TextField('Professional Memberships', blank=True, help_text='e.g. editor of journal, academic bodies')\n \n \n def __unicode__(self): \n fields = [str(self.instructor)]\n desc_name = ' '.join(fields)\n return desc_name \n \n \n \nclass InstructorEducation(models.Model):\n instructor = models.ForeignKey(Instructor)\n degree = models.CharField(max_length=100)\n field = models.CharField(max_length=100, blank=True)\n institution = models.CharField(max_length=100, blank=True)\n university = models.CharField('University/Board', max_length=100, blank=True)\n year = models.CharField(max_length=10, blank=True)\n grade = models.CharField(max_length=30, blank=True)\n \n def __unicode__(self): \n fields = [str(self.instructor), '(' + str(self.degree) + ')']\n desc_name = ' '.join(fields)\n return desc_name \n \n \nclass InstructorPublication(models.Model):\n instructor = models.ForeignKey(Instructor)\n pub_bib = models.TextField('BibTex', blank=True, help_text='DEPRECATED. LEAVE BLANK!')\n author_list = models.CharField('List of Authors', max_length=500, help_text='In \"first name last name\" format. Separate multiple authors with a comma.')\n title = models.CharField(max_length=500, blank=True, help_text='In case of book, leave this field blank.')\n journal = models.CharField('Journal/Book/Conference', max_length=500, blank=True)\n journal_address = models.CharField('Address of Journal', max_length=500, blank=True)\n volume = models.CharField(max_length=25, blank=True)\n number = models.CharField(max_length=25, blank=True)\n pages = models.CharField(max_length=25, blank=True, help_text='Page numbers in format starting--ending')\n publisher = models.CharField(max_length=500, blank=True)\n pub_date = models.DateField('Publication Date', help_text='If unpublished, set to today')\n hec_cat = models.CharField('HEC Category', max_length=10, blank=True, help_text='In case of local journals')\n \n pub_type = models.CharField('Type', max_length=30, choices=PUB_TYPE_CHOICES)\n impact_factor = models.CharField(max_length=10, blank=True, help_text='Please leave blank in case of books/conferences/non-impact factor journals')\n status = models.CharField(max_length=30, choices=PUB_STATUS_CHOICES, blank=True)\n \n def get_conf_citation(self, html=False):\n cit = self.author_list + '. \\\"' + self.title + '\\\". ' + self.journal + '. (' + self.publisher + ' ' + str(self.pub_date.year) + ') ' + self.journal_address \n return cit \n def get_journal_citation(self, html=False):\n cit = self.author_list + '. \\\"' + self.title + '\\\". ' + self.journal + '. (' + self.publisher + ' ' + str(self.pub_date.year) + ') ' + self.journal_address \n return cit \n def get_book_citation(self, html=False):\n cit = self.author_list + '. \\\"' + self.journal + '\\\". (' + self.publisher + ' ' + str(self.pub_date.year) + ') ' + self.journal_address \n return cit \n \n def get_citation(self, html=False):\n fnd = {\n 'Conference' : self.get_conf_citation,\n 'Journal' : self.get_journal_citation,\n 'Book Chapter' : self.get_journal_citation,\n 'Book' : self.get_book_citation,\n }\n return fnd[self.pub_type](html)\n \n \n def pub_string(self):\n return self.title + ' ' + self.journal\n \n def __unicode__(self): \n return self.title + ' ' + self.journal \n\n\n\n\nclass InstructorConsultancy(models.Model):\n instructor = models.ForeignKey(Instructor)\n date = models.DateField()\n description = models.TextField(blank=True, help_text='Include project title, funding agency, date of award and duration and total amount of award; please specify whether you were principal investigator (PI) or co-Investigator')\n organization = models.CharField(max_length=200)\n \n \n def __unicode__(self): \n fields = [str(self.organization), '(' + str(self.date) + ')']\n desc_name = ' '.join(fields)\n return desc_name \n \n class Meta:\n verbose_name = \"Instructor Consultancy\"\n verbose_name_plural = \"Instructor Consultancies\"\n \nclass InstructorEventParticpation(models.Model):\n instructor = models.ForeignKey(Instructor)\n title = models.CharField(max_length=200)\n type = models.CharField(max_length=50, choices=EVENT_TYPE_CHOICES)\n start_date = models.DateField()\n duration = models.CharField(max_length=50)\n role = models.TextField(blank=True)\n venue = models.TextField(blank=True)\n \n def __unicode__(self): \n fields = [str(self.title), '(' + str(self.type) + ')']\n desc_name = ' '.join(fields)\n return desc_name \n \n \nclass InstructorEmployment(models.Model):\n instructor = models.ForeignKey(Instructor)\n position = models.CharField(max_length=100, help_text='Please include only past employments (i.e. exclude positions held at FAST)')\n organization = models.CharField(max_length=200)\n start_date = models.DateField()\n end_date = models.DateField(blank=True)\n job_desc = models.TextField(blank=True) \n \n def duration_days(self):\n return str((self.end_date - self.start_date).days) + \" days\"\n \n def duration(self):\n rd = rdelta.relativedelta(self.end_date + timedelta(days=1), self.start_date)\n if rd.months == 0:\n return (\"{0} years\".format(rd.years)) \n else: \n return (\"{0.years} years and {0.months} months\".format(rd))\n \n def __unicode__(self): \n fields = [str(self.position), 'at' + str(self.organization) + '(' + str(self.start_date) + '-' + str(self.end_date) + ')']\n desc_name = ' '.join(fields)\n return desc_name \n \n class Meta:\n verbose_name = \"Instructor Past Employment\"\n verbose_name_plural = \"Instructor Past Employments\"\n\n \nclass InstructorOtherActivity(models.Model):\n instructor = models.ForeignKey(Instructor)\n title = models.CharField(max_length=100)\n description = models.TextField(blank=True)\n date = models.DateField()\n \n def __unicode__(self): \n fields = [str(self.title)]\n desc_name = ' '.join(fields)\n return desc_name \n\n class Meta:\n verbose_name = \"Instructor Other Activity\"\n verbose_name_plural = \"Instructor Other Activities\"\n\nclass StudentTheses(models.Model):\n instructor = models.ForeignKey(Instructor)\n students = models.CharField(max_length=200)\n year = models.DateField(help_text='Start of semester date when thesis was registered')\n thesis_title = models.CharField(max_length=300)\n dates = models.CharField(max_length=200)\n supervision_period = models.CharField(max_length=300) \n \n def __unicode__(self):\n return self.students + '. ' + self.thesis_title \n\n class Meta:\n verbose_name = \"Student Thesis\"\n verbose_name_plural = \"Student Theses\"\n\n\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":2013,"string":"2,013"}}},{"rowIdx":41382,"cells":{"__id__":{"kind":"number","value":3126736200358,"string":"3,126,736,200,358"},"blob_id":{"kind":"string","value":"2755148569b4aac956a89a4149a10e16fa089acd"},"directory_id":{"kind":"string","value":"23539082b42b325d2b748097bacc8c925edd7697"},"path":{"kind":"string","value":"/dclinica/patients/views.py"},"content_id":{"kind":"string","value":"e9cacbed0eb92de4599df5cc6a74d9fdaef4ba76"},"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":"leprosys/dclinica"},"repo_url":{"kind":"string","value":"https://github.com/leprosys/dclinica"},"snapshot_id":{"kind":"string","value":"12f7f128a2ba1dacf7ef921dff8d0ef3e38ebfd1"},"revision_id":{"kind":"string","value":"e4c01cd8e80da095e8832551f7dbaca32138d4a1"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-08-06T09:41:48.537634","string":"2016-08-06T09:41:48.537634"},"revision_date":{"kind":"timestamp","value":"2012-05-30T19:29:31","string":"2012-05-30T19:29:31"},"committer_date":{"kind":"timestamp","value":"2012-05-30T19:29:31","string":"2012-05-30T19:29:31"},"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 -*-\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom django.contrib.auth.decorators import login_required, permission_required\nfrom django.template import RequestContext\nfrom django.core.urlresolvers import reverse\nfrom .forms import PacienteForm, ExpedienteForm\nfrom .models import Paciente, Expediente\n\nfrom io import BytesIO\nfrom reportlab.pdfgen import canvas\nfrom reportlab.lib.pagesizes import letter\nfrom datetime import *\n\n@login_required\ndef download_pdf(request, object_id):\n instance = get_object_or_404(Paciente, id=object_id)\n usuario = Paciente.objects.get(id = object_id)\n \n # Create the HttpResponse object with the appropriate PDF headers.\n response = HttpResponse(mimetype='application/pdf')\n response['Content-Disposition'] = 'attachment; filename=registro.pdf'\n \n buffer = BytesIO()\n \n # Create the PDF object, using the BytesIO object as its \"file.\"\n p = canvas.Canvas(buffer,pagesize=letter)\n \n now = date.today()\n patient = '%s %s' % (usuario.first_name, usuario.last_name)\n birth = usuario.birthday\n weight = usuario.weight\n height = usuario.height\n gender = usuario.gender\n blood = usuario.blood\n adress = usuario.adress\n\n p.setLineWidth(.3)\n p.setFont('Helvetica', 12)\n p.drawString(30,750,'REGISTRO DE PACIENTE')\n p.drawString(500,750,str(now))\n p.line(480,747,580,747)\n\n p.drawString(30,703,'Nombre:')\n p.line(30,700,580,700)\n p.drawString(160,690,patient)\n\n p.drawString(30,670,'Fecha de Nacimiento:')\n p.line(30,668,580,668)\n p.drawString(160,658,str(birth))\n\n p.drawString(30,640,'Peso:')\n p.line(30,638,580,638)\n p.drawString(160,628,str(weight))\n\n p.drawString(30,610,'Estatura:')\n p.line(30,608,580,608)\n p.drawString(160,598,str(height))\n\n p.drawString(30,580,'Genero:')\n p.line(30,578,580,578)\n p.drawString(160,568,gender)\n\n p.drawString(30,550,'Tipo de Sangre:')\n p.line(30,548,580,548)\n p.drawString(160,538,blood)\n\n p.drawString(30,520,'Dirección:')\n p.line(30,518,580,518)\n p.drawString(160,508,str(adress.encode('utf-8')))\n\n # Close the PDF object cleanly.\n p.showPage()\n p.save()\n\n # Get the value of the BytesIO buffer and write it to the response.\n pdf = buffer.getvalue()\n buffer.close()\n response.write(pdf)\n return response\n\n\n# Paciente view\n\n@permission_required('patients.change_paciente', login_url='/denied/')\n@login_required\ndef update(request, object_id): \n instance = get_object_or_404(Paciente, id=object_id)\n form = PacienteForm(request.POST or None, instance=instance)\n if request.method == 'POST':\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(reverse ('patients'))\n\n return render_to_response('patients/paciente_detail.html' , \n {'form': form,\n 'instance': instance, } ,\n context_instance=RequestContext(request))\n\n\n@permission_required('patients.add_paciente', login_url='/denied/')\n@login_required\ndef new(request):\n form = PacienteForm(request.POST or None)\n if request.method == 'POST':\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(reverse ('patients'))\n\n return render_to_response('patients/paciente_new.html' , \n {'form': form,\n 'title': 'Nuevo Paciente', } ,\n context_instance=RequestContext(request))\n\n@permission_required('patients.delete_paciente', login_url='/denied/')\n@login_required\ndef delete(request, object_id):\n u = Paciente.objects.get(pk=object_id).delete()\n return HttpResponseRedirect(reverse ('patients'))\n\n\n# Expediente view\n@permission_required('patients.add_expediente', login_url='/denied/')\n@login_required\ndef enew(request):\n form = ExpedienteForm(request.POST or None)\n if request.method == 'POST':\n if form.is_valid():\n instance = form.save(commit=False)\n if not hasattr(instance,'created_by'):\n instance.created_by = request.user\n instance.edited_by = request.user\n instance.save()\n return HttpResponseRedirect(reverse ('record'))\n\n return render_to_response('patients/record.html' ,\n {'form': form,} ,\n context_instance=RequestContext(request))\n\n\n@permission_required('patients.change_expediente', login_url='/denied/')\n@login_required\ndef eupdate(request, object_id): \n instance = get_object_or_404(Paciente, id=object_id)\n form = ExpedienteForm(request.POST or None, instance=instance)\n if request.method == 'POST':\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(reverse ('patients'))\n\n return render_to_response('patients/expediente_edit.html' , \n {'form': form,\n 'instance': instance, } ,\n context_instance=RequestContext(request))\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":41383,"cells":{"__id__":{"kind":"number","value":5832565636528,"string":"5,832,565,636,528"},"blob_id":{"kind":"string","value":"b1686fea176898b3207eed5a460aca2597377ce3"},"directory_id":{"kind":"string","value":"e83fd29c0d14ba09739b2a49d3feb311a151933f"},"path":{"kind":"string","value":"/wordengine.py"},"content_id":{"kind":"string","value":"e3c2e5e7a03f1235f0b34fb610157966993bb90a"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"joaompinto/WordSeek"},"repo_url":{"kind":"string","value":"https://github.com/joaompinto/WordSeek"},"snapshot_id":{"kind":"string","value":"f4669c3cbd4da58010eaef225d528299374ed1f9"},"revision_id":{"kind":"string","value":"d4962fc0c4c215b477b16a98d2603c57b19881a6"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-05T23:04:37.117836","string":"2016-09-05T23:04:37.117836"},"revision_date":{"kind":"timestamp","value":"2013-08-12T06:07:36","string":"2013-08-12T06:07:36"},"committer_date":{"kind":"timestamp","value":"2013-08-12T06:07:36","string":"2013-08-12T06:07: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":"import string\nimport random\nimport bz2\n\nclass LetterGenerator:\n\tdef __init__(self, letterCount, vowelsMin, exclude_list=()):\n\t\tself.vowels = ('A','E','I','O','U')\n\t\tself.letter_list = []\n\t\tself.exclude_list = exclude_list\n\t\tvowelsCount = 0\n\n\t\tif letterCount < vowelsMin: # Sanity check\n\t\t\tvowelsMin = letterCount\n\n\t\tfor i in range(0, letterCount):\n\t\t\twhile 1:\n\t\t\t\trandom_letter = string.uppercase[random.randint(0,len(string.uppercase)-1)]\n\t\t\t\tif random_letter not in self.exclude_list:\n\t\t\t\t\tbreak\n\t\t\tif random_letter in self.vowels:\n\t\t\t\tvowelsCount = vowelsCount + 1\n\t\t\tif random_letter == \"Q\":\n\t\t\t\trandom_letter = \"Qu\"\t\n\t\t\tself.letter_list.append(random_letter)\t\n\n\t\t# Randomly assign vowels until reaching vowelsmin\t\n\t\twhile vowelsCount < vowelsMin:\n\t\t\trandom_pos = random.randint(0, len(self.letter_list)-1)\n\t\t\tif self.letter_list[random_pos] not in self.vowels:\n\t\t\t\tself.letter_list[random_pos] =\tself.vowels[random.randint(0, len(self.vowels)-1)]\n\t\t\tvowelsCount = vowelsCount + 1\n\n\tdef get_letter(self, pos):\n\t\treturn self.letter_list[pos]\n\nclass WordList:\n\tdef __init__(self, filename):\n\t\twordlistfile = bz2.BZ2File(filename, \"r\")\n\t\tself.word_list = wordlistfile.readlines()\n\t\twordlistfile.close()\n\t\"\"\" Use binary search \"\"\"\n\tdef FindWord(self, word):\n\t\tR = len(self.word_list)-1\n\t\tL = 0\n\t\twhile 1:\n\t\t\tp = (R-L)/2\n\t\t\tif p == 0:\n\t\t\t\tbreak\n\t\t\tp = L + p\n\t\t\tdiff = cmp(self.word_list[p], word)\n\t\t\tif diff == 0:\n\t\t\t\treturn True\n\t\t\telif diff < 0:\n\t\t\t\tL = p\n\t\t\telse:\n\t\t\t\tR = p\n\t\treturn False\n\n\t\t\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":41384,"cells":{"__id__":{"kind":"number","value":8005819065065,"string":"8,005,819,065,065"},"blob_id":{"kind":"string","value":"263a9bb5fe37c125040a9faf9bcde96f060eff19"},"directory_id":{"kind":"string","value":"8c78dd857e9ccf8e74d7406849f371b2039cb45f"},"path":{"kind":"string","value":"/dp/data/scripts/events/LastHero/__init__.py"},"content_id":{"kind":"string","value":"a428e03fae64fe2c73dac475ea6b75b17e53249d"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"gmenge/lineage"},"repo_url":{"kind":"string","value":"https://github.com/gmenge/lineage"},"snapshot_id":{"kind":"string","value":"1c50b6998a711b04d517b80d0e3f4d9ceee31d82"},"revision_id":{"kind":"string","value":"34e35a8c29b6fabe78877748f92aa6ed234d8198"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-04-02T13:45:08.026795","string":"2016-04-02T13:45:08.026795"},"revision_date":{"kind":"timestamp","value":"2014-10-02T02:37:09","string":"2014-10-02T02:37:09"},"committer_date":{"kind":"timestamp","value":"2014-10-02T02:37:09","string":"2014-10-02T02:37:09"},"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\r\nfrom open.brasil.gameserver.model.quest import State\r\nfrom open.brasil.gameserver.model.quest import QuestState\r\nfrom open.brasil.gameserver.model.quest import Quest\r\nfrom open.brasil.gameserver.datatables import DoorTable\r\nfrom open.brasil.gameserver.datatables import SkillTable\r\nfrom open.brasil.gameserver import Announcements\r\nfrom open.brasil import L2DatabaseFactory\r\nfrom open.brasil.gameserver.ai import CtrlIntention\r\nfrom open.brasil.util import Rnd\r\nfrom java.lang import System\r\nfrom open.brasil.gameserver.model import L2World\r\nfrom open.brasil.gameserver.model.actor.instance import L2DoorInstance\r\nfrom open.brasil.gameserver.datatables import DoorTable;\r\n\r\nqn = \"LastHero\"\r\n# =======================================#\r\n# Last Hero #\r\n# Rework by L2ViciO #\r\n# =======================================#\r\n# Event Configurations\r\nEVENTNAME = \"LastHero\" \r\nStartLocation = \"Giran\" \r\nReg_Npc = 77777\r\nReg_Npc_Loc = [82698, 148638, -3468] \r\nPrice = [57]\r\nPrice_count = [10000000]\r\nMin_level = 76\r\n# ALL THE TIME UNITS DOWN HERE ARE SECONDS!\r\nTIME_TO_START = 60\r\nAnnounce_reg_delay = 300\r\n# ALL THE TIME UNITS DOWN HERE ARE MINUTES!\r\nEVENT_INTERVAL = 60\r\nTime_for_registration = 15\r\nTime_to_wait_battle = 60\r\nMin_participate_count = 2\r\nMax_participate_count = 100\r\n\r\nRewards = [[6673, 50, 100], [57, 10000000, 100]]\r\nCOORDINATES = [149438, 46785, -3413]\r\nDoors = [24190002, 24190003]\r\n\r\n\r\n# ================EMPTY VARS================ #\r\n# DON'T CHANGE THEM #\r\nlastPlayers = []\r\nlastX = []\r\nlastY = []\r\nlastZ = []\r\nclosed = 1\r\nPlayers = []\r\nDeadplayers = []\r\nannom = 1\r\nf = 0\r\n# ========================================== #\r\n\r\nclass Quest (JQuest) :\r\n def __init__(self, id, name, descr): JQuest.__init__(self, id, name, descr)\r\n\r\n def init_LoadGlobalData(self) :\r\n self.startQuestTimer(\"open_reg\", TIME_TO_START * 1000, None, None)\r\n return\r\n\r\n def onTalk (Self, npc, player):\r\n global Players, closed\r\n st = player.getQuestState(qn)\r\n npcId = npc.getNpcId()\r\n if npcId == Reg_Npc:\r\n if closed <> 1:\r\n if not player.isInOlympiadMode() :\r\n if player.getLevel() >= Min_level:\r\n if player.getName() not in Players:\r\n if len(Players) <= Max_participate_count :\r\n if Price_count[0] <> 0: \r\n if st.getQuestItemsCount(Price[0]) > Price_count[0]:\r\n st.takeItems(Price[0], Price_count[0])\r\n Players.append(player.getName())\r\n return \"reg.htm\"\r\n else:\r\n st.exitQuest(1)\r\n return \"noPrice.htm\"\r\n else:\r\n Players.append(player.getName())\r\n return \"reg.htm\"\r\n else:\t\t \r\n return \"max.htm\"\r\n else:\r\n return \"yje.htm\"\r\n else:\r\n return \"lvl.htm\"\r\n else:\r\n return \"You register in olympiad games now\"\r\n else:\r\n return \"noreg.htm\"\r\n return\r\n\r\n def onAdvEvent (self, event, npc, player):\r\n global Deadplayers, Players, annom, closed, Doors, lastPlayers, lastX, lastY, lastZ, f, n\r\n if event == \"open_reg\" :\r\n closed = 0\r\n annom = 1\r\n lastPlayers = []\r\n Players = []\r\n Deadplayers = []\r\n lastX = []\r\n lastY = []\r\n lastZ = []\r\n npc = self.addSpawn(Reg_Npc, Reg_Npc_Loc[0], Reg_Npc_Loc[1], Reg_Npc_Loc[2], 30000, False, 0)\r\n self.startQuestTimer(\"wait_battle\", Time_for_registration * 60000, npc, None)\r\n self.startQuestTimer(\"announce\", Announce_reg_delay * 1000, None, None)\r\n Announcements.getInstance().announceToAll(\"Opened registration for \" + str(EVENTNAME) + \" event! You can register in \" + str(StartLocation) + \".\")\r\n if event == \"start_event\":\r\n if len(Players) < Min_participate_count :\r\n closed = 1\r\n Announcements.getInstance().announceToAll(\"Event \" + str(EVENTNAME) + \" was canceled due lack of participation.\")\r\n self.startQuestTimer(\"set_winner\", 1000, None, None)\r\n self.startQuestTimer(\"open_reg\", EVENT_INTERVAL * 60000, None, None)\r\n else:\r\n closed = 1\r\n Announcements.getInstance().announceToAll(\"Event \" + str(EVENTNAME) + \" has started!\")\r\n self.startQuestTimer(\"konec\", EVENT_INTERVAL * 60000, None, None)\r\n f = 0\r\n for nm in Players :\r\n i = L2World.getInstance().getPlayer(nm)\r\n if i <> None:\r\n if i.isOnline() :\r\n\t\t i.getAppearance().setVisible()\r\n\t\t i.broadcastStatusUpdate()\r\n\t\t i.broadcastUserInfo()\r\n while len(Players) > 1 :\r\n for nm in Players :\r\n i = L2World.getInstance().getPlayer(nm)\r\n if i <> None:\r\n\t if i.isDead():\r\n\t\t i.reviveAnswer(0)\r\n\t\t Deadplayers.append(i.getName())\r\n\t\t Players.remove(i.getName())\r\n self.startQuestTimer(\"set_winner\", 1000, None, None)\r\n if event == \"announce\" and closed == 0 and (Time_for_registration * 60 - Announce_reg_delay * annom) > 0: \r\n Announcements.getInstance().announceToAll(str(Time_for_registration * 60 - Announce_reg_delay * annom) + \" seconds until event \" + str(EVENTNAME) + \" will start! You can register in \" + str(StartLocation) + \".\")\r\n annom = annom + 1\r\n self.startQuestTimer(\"announce\", Announce_reg_delay * 1000, None, None)\r\n if event == \"set_winner\" :\r\n if len(Players) > 0 and len(Players + Deadplayers) >= Min_participate_count:\r\n winner = L2World.getInstance().getPlayer(Players[0])\r\n Deadplayers.append(Players[0])\r\n if winner.isDead():\r\n Announcements.getInstance().announceToAll(\"Event \" + str(EVENTNAME) + \" has ended. All players is dead. Nobody Win\")\r\n else :\r\n f = 1 \r\n Announcements.getInstance().announceToAll(\"Event \" + str(EVENTNAME) + \" has ended. \" + str(Players[0]) + \" win!\")\r\n for nm in Deadplayers :\r\n i = L2World.getInstance().getPlayer(nm)\r\n if i <> None and i.isOnline():\r\n if i.isDead():\r\n i.doRevive()\r\n i.setCurrentCp(i.getMaxCp())\r\n i.setCurrentHp(i.getMaxHp())\r\n i.setCurrentMp(i.getMaxMp())\r\n i.stopAllEffects()\r\n i.broadcastStatusUpdate()\r\n i.broadcastUserInfo()\r\n if len(Deadplayers) > 0:\r\n n = 0\r\n for nm in lastPlayers :\r\n i = L2World.getInstance().getPlayer(nm)\r\n i.teleToLocation(lastX[n], lastY[n], lastZ[n])\r\n n = n + 1\r\n if winner <> None:\r\n if winner.isOnline() :\r\n L2World.getInstance().getPlayer(Players[0]).setHero(True)\r\n Announcements.getInstance().announceToAll(\"Next time registration opend at \" + str(Time_to_next_start) + \" minute(s)\")\r\n for d in Doors:\r\n door = DoorTable.getInstance().getDoor(d)\r\n door.openMe()\r\n lastPlayers = []\r\n Players = []\r\n Deadplayers = []\r\n lastX = []\r\n lastY = []\r\n lastZ = []\r\n self.startQuestTimer(\"open_reg\", Time_to_next_start * 60000, None, None)\r\n if event == \"exit\" :\r\n if player.getName() in Players:\r\n Players.remove(player.getName())\r\n return \"exit.htm\"\r\n else:\r\n return \"default.htm\"\r\n\r\n if event == \"konec\" :\r\n if f == 0:\r\n for nm in Players :\r\n i = L2World.getInstance().getPlayer(nm)\r\n if i <> None:\r\n if i.isOnline() :\r\n i.teleToLocation(82698, 148638, -3468)\r\n i.broadcastStatusUpdate()\r\n i.broadcastUserInfo()\r\n Announcements.getInstance().announceToAll(\"Event \" + str(EVENTNAME) + \" was ended in drawn.\")\r\n self.startQuestTimer(\"open_reg\", Time_to_next_start * 60000, None, None)\r\n\r\n if event == \"wait_battle\":\r\n npc.deleteMe()\r\n if len(Players) >= Min_participate_count:\r\n for nm in Players:\r\n i = L2World.getInstance().getPlayer(nm)\r\n if i <> None:\r\n if not i.isOnline() or i.isInOlympiadMode() or i.isInJail():\r\n Players.remove(nm)\r\n else:\r\n Players.remove(nm)\r\n for nm in Players:\r\n i = L2World.getInstance().getPlayer(nm)\r\n if i <> None:\r\n if i.isOnline() :\r\n if i.isDead():\r\n i.doRevive()\r\n i.setCurrentCp(i.getMaxCp())\r\n i.setCurrentHp(i.getMaxHp())\r\n i.setCurrentMp(i.getMaxMp())\r\n i.stopAllEffects()\r\n i.getAppearance().setInvisible();\r\n i.broadcastStatusUpdate()\r\n i.broadcastUserInfo()\r\n lastPlayers.append(nm)\r\n lastX.append(i.getX())\r\n lastY.append(i.getY())\r\n lastZ.append(i.getZ())\r\n i.teleToLocation(COORDINATES[0], COORDINATES[1], COORDINATES[2])\r\n for d in Doors:\r\n door = DoorTable.getInstance().getDoor(d)\r\n door.closeMe()\r\n Announcements.getInstance().announceToAll(\"Event \" + str(EVENTNAME) + \": Registration close. You have \" + str(Time_to_wait_battle) + \" seconds for buffs before battle start\")\r\n self.startQuestTimer(\"start_event\", Time_to_wait_battle * 1000, None, None)\r\n else :\r\n self.startQuestTimer(\"start_event\", 1000, None, None)\r\n\r\nQUEST = LastHero(777, qn, \"LastHero\")\r\n\r\nQUEST.addStartNpc(int(Reg_Npc))\r\nQUEST.addTalkId(int(Reg_Npc))\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":41385,"cells":{"__id__":{"kind":"number","value":5523327962806,"string":"5,523,327,962,806"},"blob_id":{"kind":"string","value":"094a2ad975ca00698d1946ae4667611bfa809c7e"},"directory_id":{"kind":"string","value":"82b5a0383dbdf0f505b7e27423f5718315cc40bd"},"path":{"kind":"string","value":"/hw2/compare.py"},"content_id":{"kind":"string","value":"98b4876299873287608f9a0981baffec267294cc"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"segerphilip/SoftwareDesign"},"repo_url":{"kind":"string","value":"https://github.com/segerphilip/SoftwareDesign"},"snapshot_id":{"kind":"string","value":"7e5b14a80bf48448d82e7e576df6860eba443ef1"},"revision_id":{"kind":"string","value":"101cf6971ccdb56026996a1d16c94544c5e27b32"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-20T16:28:05.575255","string":"2021-01-20T16:28:05.575255"},"revision_date":{"kind":"timestamp","value":"2014-04-28T20:45:14","string":"2014-04-28T20:45:14"},"committer_date":{"kind":"timestamp","value":"2014-04-28T20:45:14","string":"2014-04-28T20:45:14"},"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":"def compare():\n\tx = int(raw_input('x = '))\n\ty = int(raw_input('y = '))\n\tif x > y:\n\t\treturn 1\n\telif x == y:\n\t\treturn 0\n\telif x < y:\n\t\treturn -1\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":41386,"cells":{"__id__":{"kind":"number","value":3839700783121,"string":"3,839,700,783,121"},"blob_id":{"kind":"string","value":"16e910ed3383c7015753f6582bdde063c491d46d"},"directory_id":{"kind":"string","value":"6e32f49768cbb2dfbba30aac6e45027291ce418a"},"path":{"kind":"string","value":"/pyc6accel/app/facedetect/main.py"},"content_id":{"kind":"string","value":"574e3f77ebca57df47c74829d97a49847be46d4c"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Apaisal/pyc6accel"},"repo_url":{"kind":"string","value":"https://github.com/Apaisal/pyc6accel"},"snapshot_id":{"kind":"string","value":"aedd3e8bb216086784cb9c1955bd1ce7e4103875"},"revision_id":{"kind":"string","value":"8ffb25dcdc215000ff61d68b9999c31d78c727e9"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-22T11:41:18.575315","string":"2021-01-22T11:41:18.575315"},"revision_date":{"kind":"timestamp","value":"2011-04-18T11:04:57","string":"2011-04-18T11:04:57"},"committer_date":{"kind":"timestamp","value":"2011-04-18T11:04:57","string":"2011-04-18T11:04:57"},"github_id":{"kind":"number","value":32217466,"string":"32,217,466"},"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 Jul 23, 2010\n\n@author: anol\n'''\nimport time\nimport cv, sys\nimport IPCamera\nfrom optparse import OptionParser\nfrom detect import detect\n\nscale = 1\n\ndef main():\n\tusage = \"usage: %prog [options] [||